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.2 by slacapra, Thu Jun 22 16:05:18 2006 UTC vs.
Revision 1.38 by fanzago, Fri May 28 09:46:00 2010 UTC

# Line 1 | Line 1
1   #!/usr/bin/env python
2 <                                                                                                                                                            
3 < import os, sys, commands
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 < # Crabpydir=commands.getoutput('which crab')
12 < # Topdir=string.replace(Crabpydir,'/python/crab','')
13 < # sys.path.append(Topdir+'/PsetCode')
14 <
15 < from cmsconfig import cmsconfig
16 < from CfgInterface import CfgInterface
11 > from ProdCommon.CMSConfigTools.ConfigAPI.CfgInterface import CfgInterface
12 > # FIXME: Cleanup includes from FWCore. Most of this is not needed.
13 > #from FWCore.ParameterSet.Config    import include
14 > from FWCore.ParameterSet.DictTypes import SortedKeysDict
15 > from FWCore.ParameterSet.Modules   import OutputModule
16 > from FWCore.ParameterSet.Modules   import Service
17 > from FWCore.ParameterSet.Types     import *
18 >
19 > import FWCore.ParameterSet.Types   as CfgTypes
20 > import FWCore.ParameterSet.Modules as CfgModules
21 > import FWCore.ParameterSet.Config  as cms
22  
23   class PsetManipulator:
24      def __init__(self, pset):
25 <        """
26 <        Convert Pset in Python format  
19 <        and initialize  
25 >        """
26 >        Read in Pset object and initialize
27          """
28  
29          self.pset = pset
30 <        #convert Pset
31 <        self.pyPset = os.path.basename(pset)  
32 <        cmd = 'EdmConfigToPython > '+common.work_space.shareDir()+self.pyPset+'py < '+ self.pset
33 <        #cmd = 'EdmConfigToPython > '+common.work_space.shareDir()+self.pset+'py < '+ self.pset
34 <        cmd_out = runCommand(cmd)  
35 <        if cmd_out != '':
36 <            msg = 'Could not convert Pset.cfg into python Dictionary \n'
37 <            msg1= '      Did you do eval `scramv1 runtime ...` from your CMSSW working area ?'
38 <            raise CrabException(msg+msg1)
30 >
31 >        common.logger.debug("PsetManipulator::__init__: PSet file = "+self.pset)
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 >
43 >        self.cfg = CfgInterface(self.cmsProcess)
44 >        try: # Quiet the output
45 >            if self.cfg.data.MessageLogger.cerr.FwkReport.reportEvery.value() < 100:
46 >                self.cfg.data.MessageLogger.cerr.FwkReport.reportEvery = cms.untracked.int32(100)
47 >        except AttributeError:
48              pass
33        
34        self.par = file(common.work_space.shareDir()+self.pyPset+'py').read()
35       # par = file(common.work_space.shareDir()+self.pset+'py').read()
36
37        # get PSet
38        self.cfg = CfgInterface(self.par,True)
39
40    def inputModule(self, source):
41        """ Clean  String FileName if there
42            and add  vString Filenames key
43        """
44        # set input module
45        inModule = self.cfg.inputSource
46        inModule.cleanStringFileNames() ## Add Daniele
47        inModule.setFileNames(source)
48        return
49  
50    def pythiaSeed(self,seed):
51        """
52            Set pythia seed key
53        """
54        # set seed
55        inModule = self.cfg.inputSource
56        inModule.setPythiaSeed(self.cfg,seed)
57        return
49  
50      def maxEvent(self, maxEv):
51 <        """ """
52 <        # set input module
53 <        inModule = self.cfg.inputSource
54 <        inModule.cleanMaxEvent()  
64 <        inModule.setMaxEvents(maxEv)   ## Add Daniele
51 >        """
52 >        Set max event in the standalone untracked module
53 >        """
54 >        self.cfg.maxEvents.setMaxEventsInput(maxEv)
55          return
56  
57 <    def outputModule(self, output):
58 <
59 <        #set output module
60 <        outModule = self.cfg.outputModules['out']
61 <        outModule.setFileName('file:'+str(output))
72 <
57 >    def skipEvent(self, skipEv):
58 >        """
59 >        Set max event in the standalone untracked module
60 >        """
61 >        self.cfg.inputSource.setSkipEvents(skipEv)
62          return
63  
64      def psetWriter(self, name):
65 +        """
66 +        Write out modified CMSSW.py
67 +        """
68  
69 <        configObject = cmsconfig(str(self.cfg))
69 >        pklFileName = common.work_space.jobDir() + name + ".pkl"
70 >        pklFile = open(pklFileName, "wb")
71 >        myPickle = pickle.Pickler(pklFile)
72 >        myPickle.dump(self.cmsProcess)
73 >        pklFile.close()
74 >
75 >        outFile = open(common.work_space.jobDir()+name, "w")
76 >        outFile.write("import FWCore.ParameterSet.Config as cms\n")
77 >        outFile.write("import pickle\n")
78 >        outFile.write("process = pickle.load(open('%s', 'rb'))\n" % (name + ".pkl"))
79 >        outFile.close()
80  
79        file1 = open(common.work_space.jobDir()+name,"w")
80        file1.write(str(configObject.asConfigurationString()))
81        file1.close()
81  
82          return
83 +
84 +    def getTFileService(self):
85 +        """ Get Output filename from TFileService and return it. If not existing, return None """
86 +        if not self.cfg.data.services.has_key('TFileService'):
87 +            return None
88 +        tFileService = self.cfg.data.services['TFileService']
89 +        if "fileName" in tFileService.parameterNames_():
90 +            fileName = getattr(tFileService,'fileName',None).value()
91 +            return fileName
92 +        return None
93 +
94 +    def getPoolOutputModule(self):
95 +        """ Get Output filename from PoolOutputModule and return it. If not existing, return None """
96 +        outputFinder = PoolOutputFinder()
97 +        for p  in self.cfg.data.endpaths.itervalues():
98 +            p.visit(outputFinder)
99 +        return outputFinder.getDict()
100 +        #return outputFinder.getList()
101 +
102 +    def getBadFilesSetting(self):
103 +        setting = False
104 +        try:
105 +            if self.cfg.data.source.skipBadFiles.value():
106 +                setting = True
107 +        except AttributeError:
108 +            pass # Either no source or no setting of skipBadFiles
109 +        return setting
110 +
111 + class PoolOutputFinder(object):
112 +
113 +    def __init__(self):
114 +        self._poolList = []
115 +        self._poolDict = {}
116 +
117 +    def enter(self,visitee):
118 +        if isinstance(visitee,OutputModule) and visitee.type_() == "PoolOutputModule":
119 +            filename=visitee.fileName.value().split(":")[-1]
120 +            self._poolList.append(filename)
121 +
122 +            try:
123 +                selectEvents = visitee.SelectEvents.SelectEvents.value()
124 +            except AttributeError:
125 +                selectEvents = None
126 +            try:
127 +                dataset = visitee.dataset.filterName.value()
128 +            except AttributeError:
129 +                dataset = None
130 +            self._poolDict.update({filename:{'dataset':dataset, 'selectEvents':selectEvents}})
131 +
132 +    def leave(self,visitee):
133 +        pass
134 +
135 +    def getList(self):
136 +        return self._poolList
137 +
138 +    def getDict(self):
139 +        #### FEDE FOR MULTI ####
140 +        return self._poolDict

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines