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.11 by slacapra, Thu May 10 13:47:06 2007 UTC vs.
Revision 1.32 by slacapra, Tue Nov 3 17:53:04 2009 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.DictTypes import SortedKeysDict
13 > from FWCore.ParameterSet.Modules   import Service
14 > from FWCore.ParameterSet.Types     import *
15 > from FWCore.ParameterSet.Modules   import OutputModule
16 >
17 > import FWCore.ParameterSet.Types   as CfgTypes
18 > import FWCore.ParameterSet.Modules as CfgModules
19  
20   class PsetManipulator:
21      def __init__(self, pset):
22 <        """
23 <        Convert Pset in Python format  
15 <        and initialize  
22 >        """
23 >        Read in Pset object and initialize
24          """
25  
26          self.pset = pset
27          #convert Pset
28 <        self.pyPset = os.path.basename(pset)  
29 <        cmd = 'EdmConfigToPython > '+common.work_space.shareDir()+self.pyPset+'py < '+ self.pset
30 <        exit_code = os.system(cmd)
31 <        if exit_code != 0 :
32 <            msg = 'Could not convert '+self.pset+' into a python Dictionary \n'
33 <            msg += 'Failed to execute \n'+cmd+'\n'
34 <            msg += 'Exit code : '+str(exit_code)
35 <
36 <            raise CrabException(msg)
37 <            pass
38 <        
39 <        self.par = file(common.work_space.shareDir()+self.pyPset+'py').read()
40 <
41 <        # get PSet
42 <        self.cfg = CfgInterface(self.par,True)
43 <
44 <    def inputModule(self, source):
45 <        """ Clean  String FileName if there
46 <            and add  vString Filenames key
47 <        """
48 <        # set input module
49 <        inModule = self.cfg.inputSource
50 <        inModule.cleanStringFileNames() ## Add Daniele
51 <        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
28 >        from FWCore.ParameterSet.Config import include
29 >        common.logger.debug("PsetManipulator::__init__: PSet file = "+self.pset)
30 >        # FUTURE: Can drop cfg mode for CMSSW < 2_1_x
31 >        if self.pset.endswith('py'):
32 >            handle = open(self.pset, 'r')
33 >            try:   # Nested form for Python < 2.5
34 >                try:
35 >                    self.cfo = imp.load_source("pycfg", self.pset, handle)
36 >                    self.cmsProcess = self.cfo.process
37 >                except Exception, ex:
38 >                    msg = "Your config file is not valid python: %s" % str(ex)
39 >                    raise CrabException(msg)
40 >            finally:
41 >                handle.close()
42 >        else:
43 >            try:
44 >                self.cfo = include(self.pset)
45 >                self.cmsProcess = self.cfo
46 >            except Exception, ex:
47 >                msg =  "Your cfg file is not valid, %s\n" % str(ex)
48 >                msg += "  https://twiki.cern.ch/twiki/bin/view/CMS/SWGuideCrabFaq#Problem_with_ParameterSet_parsin\n"
49 >                msg += "  may help you understand the problem."
50 >                raise CrabException(msg)
51 >        self.cfg = CfgInterface(self.cmsProcess)
52  
53      def maxEvent(self, maxEv):
54 <        """ """
55 <        # set input module
56 <        inModule = self.cfg.inputSource
57 <        inModule.cleanMaxEvent()  
94 <        inModule.setMaxEvents(maxEv)   ## Add Daniele
54 >        """
55 >        Set max event in the standalone untracked module
56 >        """
57 >        self.cfg.maxEvents.setMaxEventsInput(maxEv)
58          return
59  
60      def skipEvent(self, skipEv):
61 <        """ """
62 <        # set input module
63 <        inModule = self.cfg.inputSource
64 <        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 <
61 >        """
62 >        Set max event in the standalone untracked module
63 >        """
64 >        self.cfg.inputSource.setSkipEvents(skipEv)
65          return
66  
67      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):
68          """
69 <
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 <
69 >        Write out modified CMSSW.py
70          """
71  
72 <        # check if MessageLogger service already exist in configuration, if not, add it
73 <        if not "MessageLogger" in self.cfg.cmsConfig.serviceNames() :
74 <            self.cfg.cmsConfig.psdata['services']['MessageLogger'] = {
75 <                '@classname': ('string', 'tracked', 'MessageLogger'),
76 <                }
77 <            
78 <        # get MessageLogger service
79 <        loggerSvc = self.cfg.cmsConfig.service("MessageLogger")
72 >        pklFileName=common.work_space.jobDir()+name+".pkl"
73 >        pklFile = open(pklFileName,"w")
74 >        myPickle = pickle.Pickler(pklFile)
75 >        myPickle.dump(self.cmsProcess)
76 >        pklFile.close()
77 >        pklFile = open(pklFileName,"rb")
78 >        outFile = open(common.work_space.jobDir()+name,"w")
79 >        outFile.write("import FWCore.ParameterSet.Config as cms\n")
80 >        outFile.write("import pickle\n")
81 >        outFile.write("pickledCfg=\"\"\"")
82 >        outFile.write(pklFile.read())
83 >        outFile.write("\"\"\"\n")
84 >        outFile.write("process = pickle.loads(pickledCfg)\n")
85 >        pklFile.close()
86 >        outFile.close()
87  
88 <        # check if FJR is in MessageLogger service configuration, if not, add it
144 <        if not loggerSvc.has_key("fwkJobReports"):
145 <            loggerSvc['fwkJobReports'] = ("vstring", "untracked", [])
88 >        return
89  
90 <        # check if crab FJR configuration is in MessageLogger configuration, if not, add it
91 <        if not '\"'+name+'\"' in loggerSvc['fwkJobReports'][2] :
92 <            loggerSvc['fwkJobReports'][2].append('\"'+name+'\"')
90 >    def getTFileService(self):
91 >        """ Get Output filename from TFileService and return it. If not existing, return None """
92 >        if not self.cfg.data.services.has_key('TFileService'):
93 >            return None
94 >        tFileService = self.cfg.data.services['TFileService']
95 >        if "fileName" in tFileService.parameterNames_():
96 >            fileName = getattr(tFileService,'fileName',None).value()
97 >            return fileName
98 >        return None
99 >
100 >    def getPoolOutputModule(self):
101 >        """ Get Output filename from PoolOutputModule and return it. If not existing, return None """
102 >        outputFinder = PoolOutputFinder()
103 >        for p  in self.cfg.data.endpaths.itervalues():
104 >            p.visit(outputFinder)
105 >        return outputFinder.getList()
106 >
107 >    def getBadFilesSetting(self):
108 >        setting = False
109 >        try:
110 >            if self.cfg.data.source.skipBadFiles.value():
111 >                setting = True
112 >        except AttributeError:
113 >            pass # Either no source or no setting of skipBadFiles
114 >        return setting
115 >
116 > class PoolOutputFinder(object):
117 >
118 >    def __init__(self):
119 >        self._poolList = []
120 >    def enter(self,visitee):
121 >        if isinstance(visitee,OutputModule) and visitee.type_() == "PoolOutputModule":
122 >            self._poolList.append(visitee.fileName.value())
123 >    def leave(self,visitee):
124 >        pass
125  
126 <        # check that default is taken for CRAB FJR configuration and any user specific is removed
127 <        if loggerSvc.has_key(name):
153 <            del loggerSvc[name]
126 >    def getList(self):
127 >        return self._poolList

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines