[Rivet-svn] r2101 - in trunk: bin pyext

blackhole at projects.hepforge.org blackhole at projects.hepforge.org
Thu Nov 26 12:52:10 GMT 2009


Author: eike
Date: Thu Nov 26 12:52:09 2009
New Revision: 2101

Log:
move .plot parsing from compare-histos to lighthisto.py

Modified:
   trunk/bin/compare-histos
   trunk/pyext/lighthisto.py

Modified: trunk/bin/compare-histos
==============================================================================
--- trunk/bin/compare-histos	Thu Nov 26 12:23:32 2009	(r2100)
+++ trunk/bin/compare-histos	Thu Nov 26 12:52:09 2009	(r2101)
@@ -21,7 +21,7 @@
     s = s.replace('%','\\%')
     return s
 
-from lighthisto import Histo
+from lighthisto import Histo, PlotParser
 
 
 ## Try to load faster but non-standard cElementTree module
@@ -36,24 +36,6 @@
         except:
             sys.stderr.write("Can't load the ElementTree XML parser: please install it!\n")
             sys.exit(1)
-## regex patterns ##
-import re
-pat_begin_block = re.compile('^# BEGIN ([A-Z0-9_]+) ?(\S+)?')
-# temporarily allow several hashes before END for YODA
-pat_end_block =   re.compile('^#+ END ([A-Z0-9_]+)')
-pat_comment = re.compile('^#|^\s*$')
-pat_property = re.compile('^(\w+?)=(.*)$')
-pat_path_property  = re.compile('^(\S+?)::(\w+?)=(.*)$')
-
-def is_end_marker(line, blockname):
-    m = pat_end_block.match(line)
-    return m and m.group(1) == blockname
-
-def is_comment(line):
-    return pat_comment.match(line) is not None
-
-## END HISTO HACKS
-##############################################################
 
 
 if __name__ == "__main__":
@@ -61,7 +43,7 @@
 
     usage = """%prog - generate comparison plots
 
-    USAGE: 
+    USAGE:
       %prog [options] [REF:'Expt data'] aidafile1:'label 1' [path/to/aidafile2:label2 ...]
 
     TODO:
@@ -259,6 +241,7 @@
     ## For < 2.4 compatibility, since Set has no 'sort' method
     NAMES = [i for i in NAMES]
     num_written = 0
+    plotparser = PlotParser(opts.PLOTINFODIR)
     for name in sorted(NAMES):
         logging.debug("Writing histos for plot '%s'" % name)
 
@@ -285,7 +268,7 @@
 
         if len(activefiles) == 1 and opts.NO_SHOW_IF_ONLY_ONE:
             logging.warning("Skipping histo '%s' since only one plot is present" % name)
-            continue 
+            continue
 
         ## Identify reference file for this histo
         ref = opts.REF_ID
@@ -295,33 +278,7 @@
 
 
         ## Header
-        plotfilebase = name.split("/")[1]+".plot"
-        plotfile = plotfilebase
-        for pidir in opts.PLOTINFODIR:
-            if os.access(os.path.join(pidir, plotfilebase), os.R_OK):
-                plotfile = os.path.join(pidir, plotfilebase)
-                break
-        headers = {}
-        if os.access(plotfile, os.R_OK):
-            f = open(plotfile)
-            startreading=False
-            for line in f:
-                m = pat_begin_block.match(line)
-                if m:
-                    tag, pathpat = m.group(1,2)
-                    if tag == 'PLOT' and re.match(pathpat, name) is not None:
-                        startreading=True
-                        continue
-                if not startreading:
-                    continue
-                if is_end_marker(line, 'PLOT'):
-                    break
-                elif is_comment(line):
-                    continue
-                vm = pat_property.match(line)
-                if vm:
-                    prop, value = vm.group(1,2)
-                    headers[prop] = value
+        headers = plotparser.getHeaders(name)
 
         drawonlystr = ""
         for hfile in activefiles:

Modified: trunk/pyext/lighthisto.py
==============================================================================
--- trunk/pyext/lighthisto.py	Thu Nov 26 12:23:32 2009	(r2100)
+++ trunk/pyext/lighthisto.py	Thu Nov 26 12:52:09 2009	(r2101)
@@ -1,6 +1,7 @@
 #!/usr/bin/env python
 
 import os
+import re
 import logging
 
 ## Work around lacking functionality in old Python versions:
@@ -381,3 +382,78 @@
         return self
 
     yerr = property(getYErr, setYErr)
+
+
+class PlotParser(object):
+    pat_begin_block = re.compile('^# BEGIN ([A-Z0-9_]+) ?(\S+)?')
+    # temporarily allow several hashes before END for YODA
+    pat_end_block =   re.compile('^#+ END ([A-Z0-9_]+)')
+    pat_comment = re.compile('^#|^\s*$')
+    pat_property = re.compile('^(\w+?)=(.*)$')
+    pat_path_property  = re.compile('^(\S+?)::(\w+?)=(.*)$')
+
+    def __init__(self, plotpaths=None):
+        if plotpaths is None:
+            plotpaths = []
+
+        self.plotpaths = plotpaths
+
+        if len(self.plotpaths) == 0:
+            try:
+                # Use old os.popen to be Python 2.3 compatible.
+                path = os.popen("rivet-config --datadir", "r").readline()
+                path = path.strip()
+                if not path:
+                    raise ValueError("path is empty!")
+                self.plotpaths.append(path)
+            except Exception:
+                raise ValueError("No plotpaths given and rivet-config call"
+                                 " failed!")
+
+    def getHeaders(self, hpath):
+        """Get a header dict for histogram hpath.
+
+        hpath must have the form /AnalysisID/HistogramID
+        """
+        # parts = os.path.split(hpath)
+        parts = hpath.split("/")
+        if len(parts) != 3:
+            raise ValueError("hpath has wrong number of parts (%i)" %
+                             (len(parts)))
+        base = parts[1] + ".plot"
+        plotfile = None
+        for pidir in self.plotpaths:
+            if os.access(os.path.join(pidir, base), os.R_OK):
+                plotfile = os.path.join(pidir, base)
+                break
+        if plotfile is None:
+            raise ValueError("no plot file %s found in plotpaths %s" %
+                             (base, self.plotpaths))
+        headers = {}
+        startreading = False
+        f = open(plotfile)
+        for line in f:
+            m = self.pat_begin_block.match(line)
+            if m:
+                tag, pathpat = m.group(1,2)
+                if tag == 'PLOT' and re.match(pathpat, hpath) is not None:
+                    startreading=True
+                    continue
+            if not startreading:
+                continue
+            if self.isEndMarker(line, 'PLOT'):
+                break
+            elif self.isComment(line):
+                continue
+            vm = self.pat_property.match(line)
+            if vm:
+                prop, value = vm.group(1,2)
+                headers[prop] = value
+        return headers
+
+    def isEndMarker(self, line, blockname):
+        m = self.pat_end_block.match(line)
+        return m and m.group(1) == blockname
+
+    def isComment(self, line):
+        return self.pat_comment.match(line) is not None


More information about the Rivet-svn mailing list