[Rivet-svn] r2197 - trunk/bin

blackhole at projects.hepforge.org blackhole at projects.hepforge.org
Thu Dec 17 14:37:27 GMT 2009


Author: holsch
Date: Thu Dec 17 14:37:26 2009
New Revision: 2197

Log:
New name for chopping script

Added:
   trunk/bin/rivet-chop-bins   (contents, props changed)
Deleted:
   trunk/bin/chop_bins
Modified:
   trunk/bin/Makefile.am

Modified: trunk/bin/Makefile.am
==============================================================================
--- trunk/bin/Makefile.am	Thu Dec 17 14:36:00 2009	(r2196)
+++ trunk/bin/Makefile.am	Thu Dec 17 14:37:26 2009	(r2197)
@@ -1,5 +1,5 @@
 bin_SCRIPTS = rivet-config rivet-buildplugin
-dist_bin_SCRIPTS = aida2flat aida2root compare-histos make-html make-plots rivet-mkanalysis chop_bins rivet-normalise-histos
+dist_bin_SCRIPTS = aida2flat aida2root compare-histos make-html make-plots rivet-mkanalysis rivet-chop-bins rivet-normalise-histos
 EXTRA_DIST = flat2aida
 
 if ENABLE_PYEXT

Added: trunk/bin/rivet-chop-bins
==============================================================================
--- /dev/null	00:00:00 1970	(empty, because file is newly added)
+++ trunk/bin/rivet-chop-bins	Thu Dec 17 14:37:26 2009	(r2197)
@@ -0,0 +1,144 @@
+#!/usr/bin/env python
+"""%prog -b <HISTO/PATH:min:max> [ -b ... ] <AIDAFILE> [...]
+
+Strip specified bins from data sets. Histograms not specified will be passed
+through without any chopping. Bins to be kept can be specified on command
+line via `-b' options. The format is
+    -b AIDAPATH:start:stop
+where start and stop are x values contained in the first and last bins,
+respectively, that should be kept. They need not to be the bin-center but
+must only lie somewhere in the bin's x-range.
+
+To chop bins from different observables can be achieved by using the `-b'
+option multiple times.
+
+Example:
+    %prog -b /ALEPH_1996_S3486095/d03-x01-y01:0.095:0.27 out.aida
+This will give you the all bins of the ALEPH 1-T distribution that are
+between the bins that contain the x-values 0.095 and 0.27 .
+
+TODO:
+    * what if the same observable is mentioned multiple times?
+"""
+
+import os
+import sys
+import logging
+
+import lighthisto
+## Make "sorted" a builtin function on Python < 2.4
+if 'sorted' not in dir(__builtins__):
+    def sorted(iterable, cmp=None, key=None, reverse=None):
+        rtn = iterable
+        rtn.sort(cmp)
+        return rtn
+
+## Add logging.log if needed
+if 'log' not in dir(logging):
+    def _logit(level, msg):
+        l = logging.getLogger()
+        l.log(level, msg)
+    logging.log = _logit
+
+
+## Try to load faster but non-standard cElementTree module
+try:
+    import xml.etree.cElementTree as ET
+except ImportError:
+    try:
+        import cElementTree as ET
+    except ImportError:
+        try:
+            import xml.etree.ElementTree as ET
+        except:
+            sys.stderr.write("Can't load the ElementTree XML parser: please install it!\n")
+            sys.exit(1)
+
+
+if __name__ == "__main__":
+    from optparse import OptionParser, OptionGroup
+    parser = OptionParser(usage=__doc__)
+
+    parser.add_option("-b", "--bins",
+                      action="append",
+                      help="Specify a histogram and bin range that is to be"
+                           " kept. The format is `AIDAPATH:start:stop'.")
+    parser.add_option("-o", "--out",
+                      dest="outdir",
+                      help="output directory (default: %default)")
+
+    verbgroup = OptionGroup(parser, "Verbosity control")
+    verbgroup.add_option("-V", "--verbose", action="store_const",
+                         const=logging.DEBUG, dest="LOGLEVEL",
+                         help="print debug (very verbose) messages")
+    verbgroup.add_option("-Q", "--quiet", action="store_const",
+                         const=logging.WARNING, dest="LOGLEVEL",
+                         help="be very quiet")
+    parser.set_defaults(bins=[],
+            outdir=".",
+            LOGLEVEL=logging.INFO)
+    opts, args = parser.parse_args()
+
+
+    ## Configure logging
+    try:
+        logging.basicConfig(level=opts.LOGLEVEL, format="%(message)s")
+    except:
+        pass
+    h = logging.StreamHandler()
+    h.setFormatter(logging.Formatter("%(message)s"))
+    logging.getLogger().setLevel(opts.LOGLEVEL)
+    if logging.getLogger().handlers:
+        logging.getLogger().handlers[0] = h
+    else:
+        logging.getLogger().addHandler(h)
+
+
+    if len(args) == 0:
+        sys.stderr.write("Must specify at least one AIDA histogram file!\n")
+        sys.exit(1)
+    if len(opts.bins) == 0:
+        sys.stderr.write("No bins specified, so I'm doing nothing!\n")
+        sys.exit(1)
+
+    bindefs = {}
+    for bd in opts.bins:
+        try:
+            path, low, high = bd.split(":")
+        except:
+            sys.stderr.write("Problem parsing bin definition `%s'" % (bd))
+            sys.exit(1)
+        if low == "":
+            low = None
+        else:
+            low = float(low)
+        if high == "":
+            high = None
+        else:
+            high = float(high)
+        bindefs[path] = (low, high)
+
+    for aidafile in args:
+        if not os.access(aidafile, os.R_OK):
+            logging.error("%s can not be read" % aidafile)
+            break
+
+        base, ext = os.path.splitext(os.path.basename(aidafile))
+        chopfile = os.path.join(opts.outdir, base + "-chop" + ext)
+        outhistos = []
+
+        tree = ET.parse(aidafile)
+        for dps in tree.findall("dataPointSet"):
+            thishist = lighthisto.Histo.fromDPS(dps)
+            if thishist.histopath in bindefs.keys():
+                outhistos.append(thishist.chop(bindefs[thishist.histopath]))
+            else:
+                outhistos.append(thishist)
+        out = open(chopfile, "w")
+        out.write('<?xml version="1.0" encoding="ISO-8859-1" ?>\n')
+        out.write('<!DOCTYPE aida SYSTEM "http://aida.freehep.org/schemas/3.3/aida.dtd">\n')
+        out.write('<aida version="3.3">\n')
+        out.write('  <implementation version="1.1" package="FreeHEP"/>\n')
+        out.write("\n\n".join([h.asAIDA() for h in sorted(outhistos)]) + "\n")
+        out.write("</aida>\n")
+        out.close()


More information about the Rivet-svn mailing list