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.14 by ewv, Fri Dec 7 21:41:20 2007 UTC vs.
Revision 1.34.2.2 by ewv, Thu Apr 15 21:54:29 2010 UTC

# Line 3 | Line 3
3   import os
4   import common
5   import imp
6 + import pickle
7 +
8   from crab_util import *
9   from crab_exceptions import *
8 from crab_logger import Logger
10  
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):
# Line 22 | Line 26 | class PsetManipulator:
26          """
27  
28          self.pset = pset
29 <        #convert Pset
30 <        from FWCore.ParameterSet.Config import include
31 <        common.logger.debug(3,"PsetManipulator::__init__: PSet file = "+self.pset)
32 <        if (self.pset.endswith('py') or self.pset.endswith('pycfg') ):
29 <          handle = open(self.pset, 'r')
30 <          try:   # Nested form for Python < 2.5
29 >
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)
34 >                self.cfo = imp.load_source("pycfg", self.pset, handle)
35 >                self.cmsProcess = self.cfo.process
36              except Exception, ex:
37 <              msg = "Your pycfg file is not valid python: %s" % str(ex)
38 <              raise CrabException(msg)
39 <          finally:
40 <              handle.close()
41 <          self.cfg = CfgInterface(self.cfo.process)
42 <        else:
43 <          try:
44 <            self.cfo = include(self.pset)
45 <            self.cfg = CfgInterface(self.cfo)
46 <          except Exception, ex:
47 <            msg =  "Your cfg file is not valid, %s\n" % str(ex)
45 <            msg += "  https://twiki.cern.ch/twiki/bin/view/CMS/CrabFaq#Problem_with_ParameterSet_parsin\n"
46 <            msg += "  may help you understand the problem."
47 <            raise CrabException(msg)
48 <    def inputModule(self, source):
49 <        """
50 <        Set  vString Filenames key
51 <        """
52 <        # set input module
53 <        inModule = self.cfg.inputSource
54 <        inModule.setFileNames(source)
55 <        return
56 <
57 <    def pythiaSeed(self,seed):
58 <        """
59 <        Set pythia seed key
60 <        """
61 <        ranGenerator = self.cfg.data.services['RandomNumberGeneratorService']
62 <        ranGenerator.sourceSeed = CfgTypes.untracked(CfgTypes.uint32(seed))
63 <        return
64 <
65 <    def vtxSeed(self,vtxSeed):
66 <        """
67 <        Set vtx seed key
68 <        """
69 <        ranGenerator = self.cfg.data.services['RandomNumberGeneratorService']
70 <        ranModules   = ranGenerator.moduleSeeds
71 <        # set seed
72 <        ranModules.VtxSmeared = CfgTypes.untracked(CfgTypes.uint32(vtxSeed))
73 <        return
74 <
75 <    def g4Seed(self,g4Seed):
76 <        """
77 <        Set g4 seed key
78 <        """
79 <        ranGenerator = self.cfg.data.services['RandomNumberGeneratorService']
80 <        ranModules   = ranGenerator.moduleSeeds
81 <        # set seed
82 <        ranModules.g4SimHits = CfgTypes.untracked(CfgTypes.uint32(g4Seed))
83 <        return
84 <
85 <    def mixSeed(self,mixSeed):
86 <        """
87 <        Set mix seed key
88 <        """
89 <        ranGenerator = self.cfg.data.services['RandomNumberGeneratorService']
90 <        ranModules   = ranGenerator.moduleSeeds
91 <        ranModules.mix = CfgTypes.untracked(CfgTypes.uint32(mixSeed))
92 <        return
93 <
94 <    def pythiaFirstRun(self, firstrun):
95 <        """
96 <        Set firstRun
97 <        """
98 <        inModule = self.cfg.inputSource
99 <        inModule.setFirstRun(firstrun)   ## Add Daniele
100 <        return
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
48  
49      def maxEvent(self, maxEv):
50          """
# Line 108 | Line 55 | class PsetManipulator:
55  
56      def skipEvent(self, skipEv):
57          """
58 <        Set skipEvents
58 >        Set max event in the standalone untracked module
59          """
60 <        inModule = self.cfg.inputSource
114 <        inModule.setSkipEvents(skipEv)   ## Add Daniele
115 <        return
116 <
117 <    def outputModule(self, output):
118 <
119 <        #set output module
120 <        outModule = self.cfg.outputModules['out']
121 <        outModule.setFileName('file:'+str(output))
122 <
60 >        self.cfg.inputSource.setSkipEvents(skipEv)
61          return
62  
63      def psetWriter(self, name):
64          """
65 <        Write out modified CMSSW.cfg
65 >        Write out modified CMSSW.py
66          """
67  
68 <        file1 = open(common.work_space.jobDir()+name,"w")
69 <        file1.write(str(self.cfg))
70 <        file1.close()
68 >        pklFileName=common.work_space.jobDir()+name+".pkl"
69 >        pklFile = open(pklFileName,"w")
70 >        myPickle = pickle.Pickler(pklFile)
71 >        myPickle.dump(self.cmsProcess)
72 >        pklFile.close()
73 >        pklFile = open(pklFileName,"rb")
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("pickledCfg=\"\"\"")
78 >        outFile.write(pklFile.read())
79 >        outFile.write("\"\"\"\n")
80 >        outFile.write("process = pickle.loads(pickledCfg)\n")
81 >        pklFile.close()
82 >        outFile.close()
83  
84          return
85  
86 <    def addCrabFJR(self,name):
87 <        """
88 <        _addCrabFJR_
89 <        add CRAB specific FrameworkJobReport (FJR)
90 <        if a FJR already exists in input CMSSW parameter-set, add a second one.
91 <        This code is not needed for CMSSW >= 1.5.x and is non-functional in CMSSW >= 1.7.x.
92 <        It should be removed at some point in the future.
93 <        """
94 <
95 <        # Check if MessageLogger service already exists in configuration. If not, add it
96 <        svcs = self.cfg.data.services
97 <        if not svcs.has_key('MessageLogger'):
98 <            self.cfg.data.add_(CfgModules.Service("MessageLogger"))
99 <
100 <        messageLogger = self.cfg.data.services['MessageLogger']
101 <
102 <        # Add fwkJobReports to Message logger if it doesn't exist
103 <        if "fwkJobReports" not in messageLogger.parameterNames_():
104 <            messageLogger.fwkJobReports = CfgTypes.untracked(CfgTypes.vstring())
105 <
106 <        # should figure out how to remove "name" if it is there.
107 <
108 <        if name not in messageLogger.fwkJobReports:
109 <            messageLogger.fwkJobReports.append(name)
86 >    def getTFileService(self):
87 >        """ Get Output filename from TFileService and return it. If not existing, return None """
88 >        if not self.cfg.data.services.has_key('TFileService'):
89 >            return None
90 >        tFileService = self.cfg.data.services['TFileService']
91 >        if "fileName" in tFileService.parameterNames_():
92 >            fileName = getattr(tFileService,'fileName',None).value()
93 >            return fileName
94 >        return None
95 >
96 >    def getPoolOutputModule(self):
97 >        """ Get Output filename from PoolOutputModule and return it. If not existing, return None """
98 >        outputFinder = PoolOutputFinder()
99 >        for p  in self.cfg.data.endpaths.itervalues():
100 >            p.visit(outputFinder)
101 >        return outputFinder.getList()
102 >
103 >    def getBadFilesSetting(self):
104 >        setting = False
105 >        try:
106 >            if self.cfg.data.source.skipBadFiles.value():
107 >                setting = True
108 >        except AttributeError:
109 >            pass # Either no source or no setting of skipBadFiles
110 >        return setting
111 >
112 > class PoolOutputFinder(object):
113 >
114 >    def __init__(self):
115 >        self._poolList = []
116 >    def enter(self,visitee):
117 >        if isinstance(visitee,OutputModule) and visitee.type_() == "PoolOutputModule":
118 >            filename=visitee.fileName.value().split(":")[-1]
119 >            self._poolList.append(filename)
120 >    def leave(self,visitee):
121 >        pass
122  
123 <        return
123 >    def getList(self):
124 >        return self._poolList

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines