Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2024-04-06 12:24:10

0001 from __future__ import print_function
0002 import ROOT
0003 import string
0004 import random
0005 import sys
0006 
0007 from PhysicsTools.SelectorUtils.centralIDRegistry import central_id_registry
0008 from PhysicsTools.SelectorUtils.VIDCutFlowResult import VIDCutFlowResult
0009 import DataFormats.FWLite
0010 
0011 # load FWLite C++ libraries
0012 ROOT.gSystem.Load("libFWCoreFWLite.so");
0013 ROOT.gSystem.Load("libDataFormatsFWLite.so");
0014 ROOT.FWLiteEnabler.enable()
0015 
0016 # define some C++ helpers that are only used in this VID selector class and deriving classes
0017 ROOT.gInterpreter.Declare("""
0018 #include "FWCore/ParameterSetReader/interface/ParameterSetReader.h"
0019 
0020 template <class PhysObj>
0021 struct MakeVersionedSelector {
0022   MakeVersionedSelector() {}
0023 
0024   VersionedSelector<edm::Ptr<PhysObj> > operator()(const std::string& pset, const std::string& which_config) {
0025     const edm::ParameterSet& temp = edm::readPSetsFrom(pset)->getParameter<edm::ParameterSet>(which_config);
0026     return VersionedSelector<edm::Ptr<PhysObj> >(temp);
0027   }
0028 
0029   VersionedSelector<edm::Ptr<PhysObj> > operator()() { return VersionedSelector<edm::Ptr<PhysObj> >(); }
0030 };
0031 
0032 template <class Collection,
0033           class InPhysObj = typename Collection::value_type,
0034           class OutPhysObj = typename Collection::value_type>
0035 struct MakePtrFromCollection {
0036   edm::Ptr<OutPhysObj> operator()(const Collection& coll, unsigned idx) {
0037     edm::Ptr<InPhysObj> temp(&coll, idx);
0038     return edm::Ptr<OutPhysObj>(temp);
0039   }
0040 };
0041 """)
0042 
0043 
0044 config_template = """
0045 import FWCore.ParameterSet.Config as cms
0046 
0047 from PhysicsTools.SelectorUtils.centralIDRegistry import central_id_registry
0048 
0049 ebCutOff = 1.479
0050 
0051 %s = %s
0052 """
0053 
0054 def process_pset( builder, pythonpset, suffix ):  
0055     """ turn a python cms.PSet into a VID ID """    
0056     idname = pythonpset.idName.value().replace('-','_') + suffix
0057     escaped_pset = config_template%(idname, pythonpset)
0058     
0059     return builder(escaped_pset,idname)
0060 
0061 def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
0062     return ''.join(random.choice(chars) for _ in range(size))
0063 
0064 class VIDSelectorBase:
0065     def __init__(self, vidSelectorBuilder, ptrMaker, pythonpset = None):
0066         self.__initialized = False
0067         self.__suffix = id_generator(12)
0068         self.__ptrMaker = ptrMaker
0069         self.__selectorBuilder = vidSelectorBuilder()
0070         self.__instance = None
0071         if pythonpset is not None:
0072             if hasattr(pythonpset,'isPOGApproved'):
0073                 approved = pythonpset.isPOGApproved.value()
0074                 if not approved:
0075                     sys.stderr.write('This ID is not POG approved and likely under development!!!!\n')
0076                     sys.stderr.write('Please make sure to report your progress with this ID'\
0077                                          ' at the next relevant POG meeting.\n')
0078                 del pythonpset.isPOGApproved
0079             else:
0080                 sys.stderr.write('This ID is not POG approved and likely under development!!!!\n')
0081                 sys.stderr.write('Please make sure to report your progress with this ID'\
0082                                      ' at the next relevant POG meeting.\n')
0083             self.__instance = process_pset( self.__selectorBuilder, pythonpset,  self.__suffix ) 
0084             expectedmd5 = central_id_registry.getMD5FromName(pythonpset.idName)
0085             if expectedmd5 != self.md5String():
0086                 sys.stderr.write("ID: %s\n"%self.name())
0087                 sys.stderr.write("The expected md5: %s does not match the md5\n"%expectedmd5)
0088                 sys.stderr.write("calculated by the ID: %s please\n"%self.md5String())
0089                 sys.stderr.write("update your python configuration or determine the source\n")
0090                 sys.stderr.write("of transcription error!\n")
0091             self.__initialized = True
0092         else:
0093             self.__instance = self.__selectorBuilder()
0094     
0095     def __call__(self,*args):
0096         if( len(args) == 1 ):
0097             return self.__instance(*args)
0098         if( len(args) == 2 and isinstance(args[1],DataFormats.FWLite.Events) ):
0099             return self.__instance(args[0],args[1].object().event())
0100         elif( len(args) == 2 and isinstance(args[1], int) ):
0101             temp = self.__ptrMaker(args[0],args[1])
0102             newargs = [temp] 
0103             return self.__instance(*newargs)
0104         if( len(args) == 3 and isinstance(args[1], int) and isinstance(args[2], DataFormats.FWLite.Events) ):
0105             temp = self.__ptrMaker(args[0],args[1])
0106             newargs = [temp]
0107             newargs += [args[2].object().event()]
0108             return self.__instance(*newargs)
0109         raise ValueError('VIDSelectorBase __call__ with args: "%s" is not a valid call pattern'%(','.join([repr(arg) for arg in args])))
0110             
0111         
0112     def initialize(self,pythonpset):
0113         if( self.__initialized ): 
0114             print('VID Selector is already initialized, doing nothing!')
0115             return
0116         del process.__instance
0117         if hasattr(pythonpset,'isPOGApproved'):
0118             approved = pythonpset.isPOGApproved.value()
0119             if not approved:
0120                 sys.stderr.write('This ID is not POG approved and likely under development!!!!\n')
0121                 sys.stderr.write('Please make sure to report your progress with this ID'\
0122                                      ' at the next relevant POG meeting.\n')
0123             del pythonpset.isPOGApproved
0124         else:
0125             sys.stderr.write('This ID is not POG approved and likely under development!!!!\n')
0126             sys.stderr.write('Please make sure to report your progress with this ID'\
0127                                  ' at the next relevant POG meeting.\n')
0128         self.__instance = process_pset( self.__selectorBuilder, pythonpset, self.__suffix )         
0129         expectedmd5 = central_id_registry.getMD5FromName(pythonpset.idName)
0130         if expectedmd5 != self.md5String():
0131             sys.stderr.write("ID: %s\n"%self.name())
0132             sys.stderr.write("The expected md5: %s does not match the md5\n"%expectedmd5)
0133             sys.stderr.write("calculated by the ID: %s please\n"%self.md5String())
0134             sys.stderr.write("update your python configuration or determine the source\n")
0135             sys.stderr.write("of transcription error!\n")
0136         self.__initialized = True
0137 
0138     def cutFlowSize(self):
0139         return self.__instance.cutFlowSize()
0140 
0141     def cutFlowResult(self):
0142         return VIDCutFlowResult(self.__instance.cutFlowResult())
0143 
0144     def howFarInCutFlow(self):
0145         return self.__instance.howFarInCutFlow()
0146 
0147     def name(self):
0148         return self.__instance.name()
0149 
0150     def bitMap(self):
0151         return self.__instance.bitMap()
0152 
0153     def md5String(self):
0154         return self.__instance.md5String()
0155 
0156     def md55Raw(self):
0157         return self.__instance.md55Raw()
0158 
0159     def __repr__(self):
0160         out = ROOT.std.stringstream()
0161         self.__instance.print(out)
0162         return out.str();