ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/PsetManipulator.py
(Generate patch)

Comparing COMP/CRAB/python/PsetManipulator.py (file contents):
Revision 1.10 by slacapra, Wed Apr 18 17:06:21 2007 UTC vs.
Revision 1.36 by ewv, Thu Apr 8 18:25:57 2010 UTC

# Line 1 | Line 1
1   #!/usr/bin/env python
2 <                                                                                                                                                            
2 >
3   import os
4   import common
5 + import imp
6 + import pickle
7 +
8   from crab_util import *
9   from crab_exceptions import *
10  
11 < from cmsconfig import cmsconfig
12 < from CfgInterface import CfgInterface
11 > from ProdCommon.CMSConfigTools.ConfigAPI.CfgInterface import CfgInterface
12 > from FWCore.ParameterSet.Config    import include
13 > from FWCore.ParameterSet.DictTypes import SortedKeysDict
14 > from FWCore.ParameterSet.Modules   import OutputModule
15 > from FWCore.ParameterSet.Modules   import Service
16 > from FWCore.ParameterSet.Types     import *
17 >
18 > import FWCore.ParameterSet.Types   as CfgTypes
19 > import FWCore.ParameterSet.Modules as CfgModules
20 > import FWCore.ParameterSet.Config  as cms
21  
22   class PsetManipulator:
23      def __init__(self, pset):
24 <        """
25 <        Convert Pset in Python format  
15 <        and initialize  
24 >        """
25 >        Read in Pset object and initialize
26          """
27  
28          self.pset = pset
19        #convert Pset
20        self.pyPset = os.path.basename(pset)  
21        cmd = 'EdmConfigToPython > '+common.work_space.shareDir()+self.pyPset+'py < '+ self.pset
22        exit_code = os.system(cmd)
23        if exit_code != 0 :
24            msg = 'Could not convert '+self.pset+' into a python Dictionary \n'
25            msg += 'Failed to execute '+cmd+'\n'
26            msg += 'Exit code : '+exit_code
29  
30 <            raise CrabException(msg)
30 >        common.logger.debug("PsetManipulator::__init__: PSet file = "+self.pset)
31 >        handle = open(self.pset, 'r')
32 >        try:   # Nested form for Python < 2.5
33 >            try:
34 >                self.cfo = imp.load_source("pycfg", self.pset, handle)
35 >                self.cmsProcess = self.cfo.process
36 >            except Exception, ex:
37 >                msg = "Your config file is not valid python: %s" % str(ex)
38 >                raise CrabException(msg)
39 >        finally:
40 >            handle.close()
41 >
42 >        self.cfg = CfgInterface(self.cmsProcess)
43 >        try: # Quiet the output
44 >            if self.cfg.data.MessageLogger.cerr.FwkReport.reportEvery.value() < 100:
45 >                self.cfg.data.MessageLogger.cerr.FwkReport.reportEvery = cms.untracked.int32(100)
46 >        except AttributeError:
47              pass
30        
31        self.par = file(common.work_space.shareDir()+self.pyPset+'py').read()
32
33        # get PSet
34        self.cfg = CfgInterface(self.par,True)
35
36    def inputModule(self, source):
37        """ Clean  String FileName if there
38            and add  vString Filenames key
39        """
40        # set input module
41        inModule = self.cfg.inputSource
42        inModule.cleanStringFileNames() ## Add Daniele
43        inModule.setFileNames(source)
44        return
45  
46    def pythiaSeed(self,seed):
47        """
48        Set pythia seed key
49        """
50        # set seed
51        inModule = self.cfg.inputSource
52        inModule.setPythiaSeed(self.cfg,seed)
53        return
54
55    def vtxSeed(self,vtxSeed):
56        """
57        Set vtx seed key
58        """
59        # set seed
60        inModule = self.cfg.inputSource
61        inModule.setVtxSeed(self.cfg,vtxSeed)
62        return
63
64    def g4Seed(self,g4Seed):
65        """
66        Set g4 seed key
67        """
68        # set seed
69        inModule = self.cfg.inputSource
70        inModule.setG4Seed(self.cfg, g4Seed)
71        return
72
73    def mixSeed(self,mixSeed):
74        """
75        Set mix seed key
76        """
77        # set seed
78        inModule = self.cfg.inputSource
79        inModule.setMixSeed(self.cfg, mixSeed)
80        return
81
82    def pythiaFirstRun(self, firstrun):
83        """ """
84        # set input module
85        inModule = self.cfg.inputSource
86        inModule.setFirstRun(firstrun)   ## Add Daniele
87        return
48  
49      def maxEvent(self, maxEv):
50 <        """ """
51 <        # set input module
52 <        inModule = self.cfg.inputSource
53 <        inModule.cleanMaxEvent()  
94 <        inModule.setMaxEvents(maxEv)   ## Add Daniele
50 >        """
51 >        Set max event in the standalone untracked module
52 >        """
53 >        self.cfg.maxEvents.setMaxEventsInput(maxEv)
54          return
55  
56      def skipEvent(self, skipEv):
57 <        """ """
58 <        # set input module
59 <        inModule = self.cfg.inputSource
60 <        inModule.cleanSkipEvent()
102 <        inModule.setSkipEvents(skipEv)   ## Add Daniele
103 <        return
104 <
105 <    def outputModule(self, output):
106 <
107 <        #set output module
108 <        outModule = self.cfg.outputModules['out']
109 <        outModule.setFileName('file:'+str(output))
110 <
57 >        """
58 >        Set max event in the standalone untracked module
59 >        """
60 >        self.cfg.inputSource.setSkipEvents(skipEv)
61          return
62  
63      def psetWriter(self, name):
114
115        configObject = cmsconfig(str(self.cfg))
116
117        file1 = open(common.work_space.jobDir()+name,"w")
118        file1.write(str(configObject.asConfigurationString()))
119        file1.close()
120
121        return
122
123    def addCrabFJR(self,name):
64          """
65 <
126 <        _addCrabFJR_
127 <
128 <        add CRAB specific FrameworkJobReport (FJR)
129 <
130 <        if already a FJR exist in input CMSSW parameter-set, add a second one
131 <
65 >        Write out modified CMSSW.py
66          """
67  
68 <        # check if MessageLogger service already exist in configuration, if not, add it
69 <        if not "MessageLogger" in self.cfg.cmsConfig.serviceNames() :
70 <            self.cfg.cmsConfig.psdata['services']['MessageLogger'] = {
71 <                '@classname': ('string', 'tracked', 'MessageLogger'),
72 <                }
73 <            
74 <        # get MessageLogger service
75 <        loggerSvc = self.cfg.cmsConfig.service("MessageLogger")
68 >        pklFileName = common.work_space.jobDir() + name + ".pkl"
69 >        pklFile = open(pklFileName, "wb")
70 >        myPickle = pickle.Pickler(pklFile)
71 >        myPickle.dump(self.cmsProcess)
72 >        pklFile.close()
73 >
74 >        outFile = open(common.work_space.jobDir()+name, "w")
75 >        outFile.write("import FWCore.ParameterSet.Config as cms\n")
76 >        outFile.write("import pickle\n")
77 >        outFile.write("process = pickle.load(open('%s', 'rb'))\n" % (name + ".pkl"))
78 >        outFile.close()
79 >
80  
81 <        # check if FJR is in MessageLogger service configuration, if not, add it
144 <        if not loggerSvc.has_key("fwkJobReports"):
145 <            loggerSvc['fwkJobReports'] = ("vstring", "untracked", [])
81 >        return
82  
83 <        # check if crab FJR configuration is in MessageLogger configuration, if not, add it
84 <        if not '\"'+name+'\"' in loggerSvc['fwkJobReports'][2] :
85 <            loggerSvc['fwkJobReports'][2].append('\"'+name+'\"')
83 >    def getTFileService(self):
84 >        """ Get Output filename from TFileService and return it. If not existing, return None """
85 >        if not self.cfg.data.services.has_key('TFileService'):
86 >            return None
87 >        tFileService = self.cfg.data.services['TFileService']
88 >        if "fileName" in tFileService.parameterNames_():
89 >            fileName = getattr(tFileService,'fileName',None).value()
90 >            return fileName
91 >        return None
92 >
93 >    def getPoolOutputModule(self):
94 >        """ Get Output filename from PoolOutputModule and return it. If not existing, return None """
95 >        outputFinder = PoolOutputFinder()
96 >        for p  in self.cfg.data.endpaths.itervalues():
97 >            p.visit(outputFinder)
98 >        return outputFinder.getList()
99 >
100 >    def getBadFilesSetting(self):
101 >        setting = False
102 >        try:
103 >            if self.cfg.data.source.skipBadFiles.value():
104 >                setting = True
105 >        except AttributeError:
106 >            pass # Either no source or no setting of skipBadFiles
107 >        return setting
108 >
109 > class PoolOutputFinder(object):
110 >
111 >    def __init__(self):
112 >        self._poolList = []
113 >    def enter(self,visitee):
114 >        if isinstance(visitee,OutputModule) and visitee.type_() == "PoolOutputModule":
115 >            filename=visitee.fileName.value().split(":")[-1]
116 >            self._poolList.append(filename)
117 >    def leave(self,visitee):
118 >        pass
119  
120 <        # check that default is taken for CRAB FJR configuration and any user specific is removed
121 <        if loggerSvc.has_key(name):
153 <            del loggerSvc[name]
120 >    def getList(self):
121 >        return self._poolList

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines