-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathConfigBuilder.py
2391 lines (2053 loc) · 118 KB
/
ConfigBuilder.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python3
from __future__ import print_function
__version__ = "$Revision: 1.19 $"
__source__ = "$Source: /local/reps/CMSSW/CMSSW/Configuration/Applications/python/ConfigBuilder.py,v $"
import FWCore.ParameterSet.Config as cms
from FWCore.ParameterSet.Modules import _Module
# The following import is provided for backward compatibility reasons.
# The function used to be defined in this file.
from FWCore.ParameterSet.MassReplace import massReplaceInputTag as MassReplaceInputTag
import hashlib
import sys
import re
import collections
from subprocess import Popen,PIPE
import FWCore.ParameterSet.DictTypes as DictTypes
class Options:
pass
# the canonical defaults
defaultOptions = Options()
defaultOptions.datamix = 'DataOnSim'
defaultOptions.isMC=False
defaultOptions.isData=True
defaultOptions.step=''
defaultOptions.pileup='NoPileUp'
defaultOptions.pileup_input = None
defaultOptions.pileup_dasoption = ''
defaultOptions.geometry = 'SimDB'
defaultOptions.geometryExtendedOptions = ['ExtendedGFlash','Extended','NoCastor']
defaultOptions.magField = ''
defaultOptions.conditions = None
defaultOptions.scenarioOptions=['pp','cosmics','nocoll','HeavyIons']
defaultOptions.harvesting= 'AtRunEnd'
defaultOptions.gflash = False
defaultOptions.number = -1
defaultOptions.number_out = None
defaultOptions.arguments = ""
defaultOptions.name = "NO NAME GIVEN"
defaultOptions.evt_type = ""
defaultOptions.filein = ""
defaultOptions.dasquery=""
defaultOptions.dasoption=""
defaultOptions.secondfilein = ""
defaultOptions.customisation_file = []
defaultOptions.customisation_file_unsch = []
defaultOptions.customise_commands = ""
defaultOptions.inline_custom=False
defaultOptions.particleTable = 'pythiapdt'
defaultOptions.particleTableList = ['pythiapdt','pdt']
defaultOptions.dirin = ''
defaultOptions.dirout = ''
defaultOptions.filetype = 'EDM'
defaultOptions.fileout = 'output.root'
defaultOptions.filtername = ''
defaultOptions.lazy_download = False
defaultOptions.custom_conditions = ''
defaultOptions.hltProcess = ''
defaultOptions.eventcontent = None
defaultOptions.datatier = None
defaultOptions.inlineEventContent = True
defaultOptions.inlineObjets =''
defaultOptions.hideGen=False
from Configuration.StandardSequences.VtxSmeared import VtxSmearedDefaultKey,VtxSmearedHIDefaultKey
defaultOptions.beamspot=None
defaultOptions.outputDefinition =''
defaultOptions.inputCommands = None
defaultOptions.outputCommands = None
defaultOptions.inputEventContent = ''
defaultOptions.dropDescendant = False
defaultOptions.relval = None
defaultOptions.profile = None
defaultOptions.isRepacked = False
defaultOptions.restoreRNDSeeds = False
defaultOptions.donotDropOnInput = ''
defaultOptions.python_filename =''
defaultOptions.io=None
defaultOptions.lumiToProcess=None
defaultOptions.fast=False
defaultOptions.runsAndWeightsForMC = None
defaultOptions.runsScenarioForMC = None
defaultOptions.runsAndWeightsForMCIntegerWeights = None
defaultOptions.runsScenarioForMCIntegerWeights = None
defaultOptions.runUnscheduled = False
defaultOptions.timeoutOutput = False
defaultOptions.nThreads = '1'
defaultOptions.nStreams = '0'
defaultOptions.nConcurrentLumis = '0'
defaultOptions.nConcurrentIOVs = '0'
defaultOptions.accelerators = None
# some helper routines
def dumpPython(process,name):
theObject = getattr(process,name)
if isinstance(theObject,cms.Path) or isinstance(theObject,cms.EndPath) or isinstance(theObject,cms.Sequence):
return "process."+name+" = " + theObject.dumpPython()
elif isinstance(theObject,_Module) or isinstance(theObject,cms.ESProducer):
return "process."+name+" = " + theObject.dumpPython()+"\n"
else:
return "process."+name+" = " + theObject.dumpPython()+"\n"
def filesFromList(fileName,s=None):
import os
import FWCore.ParameterSet.Config as cms
prim=[]
sec=[]
for line in open(fileName,'r'):
if line.count(".root")>=2:
#two files solution...
entries=line.replace("\n","").split()
prim.append(entries[0])
sec.append(entries[1])
elif (line.find(".root")!=-1):
entry=line.replace("\n","")
prim.append(entry)
# remove any duplicates but keep the order
file_seen = set()
prim = [f for f in prim if not (f in file_seen or file_seen.add(f))]
file_seen = set()
sec = [f for f in sec if not (f in file_seen or file_seen.add(f))]
if s:
if not hasattr(s,"fileNames"):
s.fileNames=cms.untracked.vstring(prim)
else:
s.fileNames.extend(prim)
if len(sec)!=0:
if not hasattr(s,"secondaryFileNames"):
s.secondaryFileNames=cms.untracked.vstring(sec)
else:
s.secondaryFileNames.extend(sec)
print("found files: ",prim)
if len(prim)==0:
raise Exception("There are not files in input from the file list")
if len(sec)!=0:
print("found parent files:",sec)
return (prim,sec)
def filesFromDASQuery(query,option="",s=None):
import os,time
import FWCore.ParameterSet.Config as cms
prim=[]
sec=[]
print("the query is",query)
eC=5
count=0
while eC!=0 and count<3:
if count!=0:
print('Sleeping, then retrying DAS')
time.sleep(100)
p = Popen('dasgoclient %s --query "%s"'%(option,query), stdout=PIPE,shell=True, universal_newlines=True)
pipe=p.stdout.read()
tupleP = os.waitpid(p.pid, 0)
eC=tupleP[1]
count=count+1
if eC==0:
print("DAS succeeded after",count,"attempts",eC)
else:
print("DAS failed 3 times- I give up")
for line in pipe.split('\n'):
if line.count(".root")>=2:
#two files solution...
entries=line.replace("\n","").split()
prim.append(entries[0])
sec.append(entries[1])
elif (line.find(".root")!=-1):
entry=line.replace("\n","")
prim.append(entry)
# remove any duplicates
prim = sorted(list(set(prim)))
sec = sorted(list(set(sec)))
if s:
if not hasattr(s,"fileNames"):
s.fileNames=cms.untracked.vstring(prim)
else:
s.fileNames.extend(prim)
if len(sec)!=0:
if not hasattr(s,"secondaryFileNames"):
s.secondaryFileNames=cms.untracked.vstring(sec)
else:
s.secondaryFileNames.extend(sec)
print("found files: ",prim)
if len(sec)!=0:
print("found parent files:",sec)
return (prim,sec)
def anyOf(listOfKeys,dict,opt=None):
for k in listOfKeys:
if k in dict:
toReturn=dict[k]
dict.pop(k)
return toReturn
if opt!=None:
return opt
else:
raise Exception("any of "+','.join(listOfKeys)+" are mandatory entries of --output options")
class ConfigBuilder(object):
"""The main building routines """
def __init__(self, options, process = None, with_output = False, with_input = False ):
"""options taken from old cmsDriver and optparse """
options.outfile_name = options.dirout+options.fileout
self._options = options
if self._options.isData and options.isMC:
raise Exception("ERROR: You may specify only --data or --mc, not both")
#if not self._options.conditions:
# raise Exception("ERROR: No conditions given!\nPlease specify conditions. E.g. via --conditions=IDEAL_30X::All")
# check that MEtoEDMConverter (running in ENDJOB) and DQMIO don't run in the same job
if 'ENDJOB' in self._options.step:
if (hasattr(self._options,"outputDefinition") and \
self._options.outputDefinition != '' and \
any(anyOf(['t','tier','dataTier'],outdic) == 'DQMIO' for outdic in eval(self._options.outputDefinition))) or \
(hasattr(self._options,"datatier") and \
self._options.datatier and \
'DQMIO' in self._options.datatier):
print("removing ENDJOB from steps since not compatible with DQMIO dataTier")
self._options.step=self._options.step.replace(',ENDJOB','')
# what steps are provided by this class?
stepList = [re.sub(r'^prepare_', '', methodName) for methodName in ConfigBuilder.__dict__ if methodName.startswith('prepare_')]
self.stepMap={}
self.stepKeys=[]
for step in self._options.step.split(","):
if step=='': continue
stepParts = step.split(":")
stepName = stepParts[0]
if stepName not in stepList and not stepName.startswith('re'):
raise ValueError("Step "+stepName+" unknown")
if len(stepParts)==1:
self.stepMap[stepName]=""
elif len(stepParts)==2:
self.stepMap[stepName]=stepParts[1].split('+')
elif len(stepParts)==3:
self.stepMap[stepName]=(stepParts[2].split('+'),stepParts[1])
else:
raise ValueError("Step definition "+step+" invalid")
self.stepKeys.append(stepName)
#print "map of steps is:",self.stepMap
self.with_output = with_output
self.process=process
if hasattr(self._options,"no_output_flag") and self._options.no_output_flag:
self.with_output = False
self.with_input = with_input
self.imports = []
self.create_process()
self.define_Configs()
self.schedule = list()
self.scheduleIndexOfFirstHLTPath = None
# we are doing three things here:
# creating a process to catch errors
# building the code to re-create the process
self.additionalCommands = []
# TODO: maybe a list of to be dumped objects would help as well
self.blacklist_paths = []
self.addedObjects = []
self.additionalOutputs = {}
self.productionFilterSequence = None
self.labelsToAssociate=[]
self.nextScheduleIsConditional=False
self.conditionalPaths=[]
self.excludedPaths=[]
def profileOptions(self):
"""
addIgProfService
Function to add the igprof profile service so that you can dump in the middle
of the run.
"""
profileOpts = self._options.profile.split(':')
profilerStart = 1
profilerInterval = 100
profilerFormat = None
profilerJobFormat = None
if len(profileOpts):
#type, given as first argument is unused here
profileOpts.pop(0)
if len(profileOpts):
startEvent = profileOpts.pop(0)
if not startEvent.isdigit():
raise Exception("%s is not a number" % startEvent)
profilerStart = int(startEvent)
if len(profileOpts):
eventInterval = profileOpts.pop(0)
if not eventInterval.isdigit():
raise Exception("%s is not a number" % eventInterval)
profilerInterval = int(eventInterval)
if len(profileOpts):
profilerFormat = profileOpts.pop(0)
if not profilerFormat:
profilerFormat = "%s___%s___%%I.gz" % (
self._options.evt_type.replace("_cfi", ""),
hashlib.md5(
(str(self._options.step) + str(self._options.pileup) + str(self._options.conditions) +
str(self._options.datatier) + str(self._options.profileTypeLabel)).encode('utf-8')
).hexdigest()
)
if not profilerJobFormat and profilerFormat.endswith(".gz"):
profilerJobFormat = profilerFormat.replace(".gz", "_EndOfJob.gz")
elif not profilerJobFormat:
profilerJobFormat = profilerFormat + "_EndOfJob.gz"
return (profilerStart,profilerInterval,profilerFormat,profilerJobFormat)
def load(self,includeFile):
includeFile = includeFile.replace('/','.')
self.process.load(includeFile)
return sys.modules[includeFile]
def loadAndRemember(self, includeFile):
"""helper routine to load am memorize imports"""
# we could make the imports a on-the-fly data method of the process instance itself
# not sure if the latter is a good idea
includeFile = includeFile.replace('/','.')
self.imports.append(includeFile)
self.process.load(includeFile)
return sys.modules[includeFile]
def executeAndRemember(self, command):
"""helper routine to remember replace statements"""
self.additionalCommands.append(command)
if not command.strip().startswith("#"):
# substitute: process.foo = process.bar -> self.process.foo = self.process.bar
import re
exec(re.sub(r"([^a-zA-Z_0-9]|^)(process)([^a-zA-Z_0-9])",r"\1self.process\3",command))
#exec(command.replace("process.","self.process."))
def addCommon(self):
if 'HARVESTING' in self.stepMap.keys() or 'ALCAHARVEST' in self.stepMap.keys():
self.process.options.Rethrow = ['ProductNotFound']
self.process.options.fileMode = 'FULLMERGE'
self.addedObjects.append(("","options"))
if self._options.lazy_download:
self.process.AdaptorConfig = cms.Service("AdaptorConfig",
stats = cms.untracked.bool(True),
enable = cms.untracked.bool(True),
cacheHint = cms.untracked.string("lazy-download"),
readHint = cms.untracked.string("read-ahead-buffered")
)
self.addedObjects.append(("Setup lazy download","AdaptorConfig"))
#self.process.cmsDriverCommand = cms.untracked.PSet( command=cms.untracked.string('cmsDriver.py '+self._options.arguments) )
#self.addedObjects.append(("what cmsDriver command was used","cmsDriverCommand"))
if self._options.profile:
(start, interval, eventFormat, jobFormat)=self.profileOptions()
self.process.IgProfService = cms.Service("IgProfService",
reportFirstEvent = cms.untracked.int32(start),
reportEventInterval = cms.untracked.int32(interval),
reportToFileAtPostEvent = cms.untracked.string("| gzip -c > %s"%(eventFormat)),
reportToFileAtPostEndJob = cms.untracked.string("| gzip -c > %s"%(jobFormat)))
self.addedObjects.append(("Setup IGProf Service for profiling","IgProfService"))
def addMaxEvents(self):
"""Here we decide how many evts will be processed"""
self.process.maxEvents.input = int(self._options.number)
if self._options.number_out:
self.process.maxEvents.output = int(self._options.number_out)
self.addedObjects.append(("","maxEvents"))
def addSource(self):
"""Here the source is built. Priority: file, generator"""
self.addedObjects.append(("Input source","source"))
def filesFromOption(self):
for entry in self._options.filein.split(','):
print("entry",entry)
if entry.startswith("filelist:"):
filesFromList(entry[9:],self.process.source)
elif entry.startswith("dbs:") or entry.startswith("das:"):
filesFromDASQuery('file dataset = %s'%(entry[4:]),self._options.dasoption,self.process.source)
else:
self.process.source.fileNames.append(self._options.dirin+entry)
if self._options.secondfilein:
if not hasattr(self.process.source,"secondaryFileNames"):
raise Exception("--secondfilein not compatible with "+self._options.filetype+"input type")
for entry in self._options.secondfilein.split(','):
print("entry",entry)
if entry.startswith("filelist:"):
self.process.source.secondaryFileNames.extend((filesFromList(entry[9:]))[0])
elif entry.startswith("dbs:") or entry.startswith("das:"):
self.process.source.secondaryFileNames.extend((filesFromDASQuery('file dataset = %s'%(entry[4:]),self._options.dasoption))[0])
else:
self.process.source.secondaryFileNames.append(self._options.dirin+entry)
if self._options.filein or self._options.dasquery:
if self._options.filetype == "EDM":
self.process.source=cms.Source("PoolSource",
fileNames = cms.untracked.vstring(),
secondaryFileNames= cms.untracked.vstring())
filesFromOption(self)
elif self._options.filetype == "DAT":
self.process.source=cms.Source("NewEventStreamFileReader",fileNames = cms.untracked.vstring())
filesFromOption(self)
elif self._options.filetype == "LHE":
self.process.source=cms.Source("LHESource", fileNames = cms.untracked.vstring())
if self._options.filein.startswith("lhe:"):
#list the article directory automatically
args=self._options.filein.split(':')
article=args[1]
print('LHE input from article ',article)
location='/store/lhe/'
import os
textOfFiles=os.popen('cmsLHEtoEOSManager.py -l '+article)
for line in textOfFiles:
for fileName in [x for x in line.split() if '.lhe' in x]:
self.process.source.fileNames.append(location+article+'/'+fileName)
#check first if list of LHE files is loaded (not empty)
if len(line)<2:
print('Issue to load LHE files, please check and try again.')
sys.exit(-1)
#Additional check to protect empty fileNames in process.source
if len(self.process.source.fileNames)==0:
print('Issue with empty filename, but can pass line check')
sys.exit(-1)
if len(args)>2:
self.process.source.skipEvents = cms.untracked.uint32(int(args[2]))
else:
filesFromOption(self)
elif self._options.filetype == "DQM":
self.process.source=cms.Source("DQMRootSource",
fileNames = cms.untracked.vstring())
filesFromOption(self)
elif self._options.filetype == "DQMDAQ":
# FIXME: how to configure it if there are no input files specified?
self.process.source=cms.Source("DQMStreamerReader")
if ('HARVESTING' in self.stepMap.keys() or 'ALCAHARVEST' in self.stepMap.keys()) and (not self._options.filetype == "DQM"):
self.process.source.processingMode = cms.untracked.string("RunsAndLumis")
if self._options.dasquery!='':
self.process.source=cms.Source("PoolSource", fileNames = cms.untracked.vstring(),secondaryFileNames = cms.untracked.vstring())
filesFromDASQuery(self._options.dasquery,self._options.dasoption,self.process.source)
if ('HARVESTING' in self.stepMap.keys() or 'ALCAHARVEST' in self.stepMap.keys()) and (not self._options.filetype == "DQM"):
self.process.source.processingMode = cms.untracked.string("RunsAndLumis")
##drop LHEXMLStringProduct on input to save memory if appropriate
if 'GEN' in self.stepMap.keys() and not self._options.filetype == "LHE":
if self._options.inputCommands:
self._options.inputCommands+=',drop LHEXMLStringProduct_*_*_*,'
else:
self._options.inputCommands='keep *, drop LHEXMLStringProduct_*_*_*,'
if self.process.source and self._options.inputCommands and not self._options.filetype == "LHE":
if not hasattr(self.process.source,'inputCommands'): self.process.source.inputCommands=cms.untracked.vstring()
for command in self._options.inputCommands.split(','):
# remove whitespace around the keep/drop statements
command = command.strip()
if command=='': continue
self.process.source.inputCommands.append(command)
if not self._options.dropDescendant:
self.process.source.dropDescendantsOfDroppedBranches = cms.untracked.bool(False)
if self._options.lumiToProcess:
import FWCore.PythonUtilities.LumiList as LumiList
self.process.source.lumisToProcess = cms.untracked.VLuminosityBlockRange( LumiList.LumiList(self._options.lumiToProcess).getCMSSWString().split(',') )
if 'GEN' in self.stepMap.keys() or 'LHE' in self.stepMap or (not self._options.filein and hasattr(self._options, "evt_type")):
if self.process.source is None:
self.process.source=cms.Source("EmptySource")
# modify source in case of run-dependent MC
self.runsAndWeights=None
if self._options.runsAndWeightsForMC or self._options.runsScenarioForMC :
if not self._options.isMC :
raise Exception("options --runsAndWeightsForMC and --runsScenarioForMC are only valid for MC")
if self._options.runsAndWeightsForMC:
self.runsAndWeights = eval(self._options.runsAndWeightsForMC)
else:
from Configuration.StandardSequences.RunsAndWeights import RunsAndWeights
if isinstance(RunsAndWeights[self._options.runsScenarioForMC], str):
__import__(RunsAndWeights[self._options.runsScenarioForMC])
self.runsAndWeights = sys.modules[RunsAndWeights[self._options.runsScenarioForMC]].runProbabilityDistribution
else:
self.runsAndWeights = RunsAndWeights[self._options.runsScenarioForMC]
if self.runsAndWeights:
import SimGeneral.Configuration.ThrowAndSetRandomRun as ThrowAndSetRandomRun
ThrowAndSetRandomRun.throwAndSetRandomRun(self.process.source,self.runsAndWeights)
self.additionalCommands.append('import SimGeneral.Configuration.ThrowAndSetRandomRun as ThrowAndSetRandomRun')
self.additionalCommands.append('ThrowAndSetRandomRun.throwAndSetRandomRun(process.source,%s)'%(self.runsAndWeights))
# modify source in case of run-dependent MC (Run-3 method)
self.runsAndWeightsInt=None
if self._options.runsAndWeightsForMCIntegerWeights or self._options.runsScenarioForMCIntegerWeights:
if not self._options.isMC :
raise Exception("options --runsAndWeightsForMCIntegerWeights and --runsScenarioForMCIntegerWeights are only valid for MC")
if self._options.runsAndWeightsForMCIntegerWeights:
self.runsAndWeightsInt = eval(self._options.runsAndWeightsForMCIntegerWeights)
else:
from Configuration.StandardSequences.RunsAndWeights import RunsAndWeights
if isinstance(RunsAndWeights[self._options.runsScenarioForMCIntegerWeights], str):
__import__(RunsAndWeights[self._options.runsScenarioForMCIntegerWeights])
self.runsAndWeightsInt = sys.modules[RunsAndWeights[self._options.runsScenarioForMCIntegerWeights]].runProbabilityDistribution
else:
self.runsAndWeightsInt = RunsAndWeights[self._options.runsScenarioForMCIntegerWeights]
if self.runsAndWeightsInt:
if not self._options.relval:
raise Exception("--relval option required when using --runsAndWeightsInt")
if 'DATAMIX' in self._options.step:
from SimGeneral.Configuration.LumiToRun import lumi_to_run
total_events, events_per_job = self._options.relval.split(',')
lumi_to_run_mapping = lumi_to_run(self.runsAndWeightsInt, int(total_events), int(events_per_job))
self.additionalCommands.append("process.source.firstLuminosityBlockForEachRun = cms.untracked.VLuminosityBlockID(*[cms.LuminosityBlockID(x,y) for x,y in " + str(lumi_to_run_mapping) + "])")
return
def addOutput(self):
""" Add output module to the process """
result=""
if self._options.outputDefinition:
if self._options.datatier:
print("--datatier & --eventcontent options ignored")
#new output convention with a list of dict
outList = eval(self._options.outputDefinition)
for (id,outDefDict) in enumerate(outList):
outDefDictStr=outDefDict.__str__()
if not isinstance(outDefDict,dict):
raise Exception("--output needs to be passed a list of dict"+self._options.outputDefinition+" is invalid")
#requires option: tier
theTier=anyOf(['t','tier','dataTier'],outDefDict)
#optional option: eventcontent, filtername, selectEvents, moduleLabel, filename
## event content
theStreamType=anyOf(['e','ec','eventContent','streamType'],outDefDict,theTier)
theFilterName=anyOf(['f','ftN','filterName'],outDefDict,'')
theSelectEvent=anyOf(['s','sE','selectEvents'],outDefDict,'')
theModuleLabel=anyOf(['l','mL','moduleLabel'],outDefDict,'')
theExtraOutputCommands=anyOf(['o','oC','outputCommands'],outDefDict,'')
# module label has a particular role
if not theModuleLabel:
tryNames=[theStreamType.replace(theTier.replace('-',''),'')+theTier.replace('-','')+'output',
theStreamType.replace(theTier.replace('-',''),'')+theTier.replace('-','')+theFilterName+'output',
theStreamType.replace(theTier.replace('-',''),'')+theTier.replace('-','')+theFilterName+theSelectEvent.split(',')[0].replace(':','for').replace(' ','')+'output'
]
for name in tryNames:
if not hasattr(self.process,name):
theModuleLabel=name
break
if not theModuleLabel:
raise Exception("cannot find a module label for specification: "+outDefDictStr)
if id==0:
defaultFileName=self._options.outfile_name
else:
defaultFileName=self._options.outfile_name.replace('.root','_in'+theTier+'.root')
theFileName=self._options.dirout+anyOf(['fn','fileName'],outDefDict,defaultFileName)
if not theFileName.endswith('.root'):
theFileName+='.root'
if len(outDefDict):
raise Exception("unused keys from --output options: "+','.join(outDefDict.keys()))
if theStreamType=='DQMIO': theStreamType='DQM'
if theStreamType=='ALL':
theEventContent = cms.PSet(outputCommands = cms.untracked.vstring('keep *'))
else:
theEventContent = getattr(self.process, theStreamType+"EventContent")
addAlCaSelects=False
if theStreamType=='ALCARECO' and not theFilterName:
theFilterName='StreamALCACombined'
addAlCaSelects=True
CppType='PoolOutputModule'
if self._options.timeoutOutput:
CppType='TimeoutPoolOutputModule'
if theStreamType=='DQM' and theTier=='DQMIO': CppType='DQMRootOutputModule'
output = cms.OutputModule(CppType,
theEventContent.clone(),
fileName = cms.untracked.string(theFileName),
dataset = cms.untracked.PSet(
dataTier = cms.untracked.string(theTier),
filterName = cms.untracked.string(theFilterName))
)
if not theSelectEvent and hasattr(self.process,'generation_step') and theStreamType!='LHE':
output.SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('generation_step'))
if not theSelectEvent and hasattr(self.process,'filtering_step'):
output.SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('filtering_step'))
if theSelectEvent:
output.SelectEvents =cms.untracked.PSet(SelectEvents = cms.vstring(theSelectEvent))
if addAlCaSelects:
if not hasattr(output,'SelectEvents'):
output.SelectEvents=cms.untracked.PSet(SelectEvents=cms.vstring())
for alca in self.AlCaPaths:
output.SelectEvents.SelectEvents.extend(getattr(self.process,'OutALCARECO'+alca).SelectEvents.SelectEvents)
if hasattr(self.process,theModuleLabel):
raise Exception("the current process already has a module "+theModuleLabel+" defined")
#print "creating output module ",theModuleLabel
setattr(self.process,theModuleLabel,output)
outputModule=getattr(self.process,theModuleLabel)
setattr(self.process,theModuleLabel+'_step',cms.EndPath(outputModule))
path=getattr(self.process,theModuleLabel+'_step')
self.schedule.append(path)
if not self._options.inlineEventContent and hasattr(self.process,theStreamType+"EventContent"):
def doNotInlineEventContent(instance,label = "cms.untracked.vstring(process."+theStreamType+"EventContent.outputCommands)"):
return label
outputModule.outputCommands.__dict__["dumpPython"] = doNotInlineEventContent
if theExtraOutputCommands:
if not isinstance(theExtraOutputCommands,list):
raise Exception("extra ouput command in --option must be a list of strings")
if hasattr(self.process,theStreamType+"EventContent"):
self.executeAndRemember('process.%s.outputCommands.extend(%s)'%(theModuleLabel,theExtraOutputCommands))
else:
outputModule.outputCommands.extend(theExtraOutputCommands)
result+="\nprocess."+theModuleLabel+" = "+outputModule.dumpPython()
##ends the --output options model
return result
streamTypes=self._options.eventcontent.split(',')
tiers=self._options.datatier.split(',')
if not self._options.outputDefinition and len(streamTypes)!=len(tiers):
raise Exception("number of event content arguments does not match number of datatier arguments")
# if the only step is alca we don't need to put in an output
if self._options.step.split(',')[0].split(':')[0] == 'ALCA':
return "\n"
for i,(streamType,tier) in enumerate(zip(streamTypes,tiers)):
if streamType=='': continue
if streamType == 'ALCARECO' and not 'ALCAPRODUCER' in self._options.step: continue
if streamType=='DQMIO': streamType='DQM'
eventContent=streamType
## override streamType to eventContent in case NANOEDM
if streamType == "NANOEDMAOD" :
eventContent = "NANOAOD"
elif streamType == "NANOEDMAODSIM" :
eventContent = "NANOAODSIM"
theEventContent = getattr(self.process, eventContent+"EventContent")
if i==0:
theFileName=self._options.outfile_name
theFilterName=self._options.filtername
else:
theFileName=self._options.outfile_name.replace('.root','_in'+streamType+'.root')
theFilterName=self._options.filtername
CppType='PoolOutputModule'
if self._options.timeoutOutput:
CppType='TimeoutPoolOutputModule'
if streamType=='DQM' and tier=='DQMIO': CppType='DQMRootOutputModule'
if "NANOAOD" in streamType : CppType='NanoAODOutputModule'
output = cms.OutputModule(CppType,
theEventContent,
fileName = cms.untracked.string(theFileName),
dataset = cms.untracked.PSet(dataTier = cms.untracked.string(tier),
filterName = cms.untracked.string(theFilterName)
)
)
if hasattr(self.process,"generation_step") and streamType!='LHE':
output.SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('generation_step'))
if hasattr(self.process,"filtering_step"):
output.SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('filtering_step'))
if streamType=='ALCARECO':
output.dataset.filterName = cms.untracked.string('StreamALCACombined')
if "MINIAOD" in streamType:
from PhysicsTools.PatAlgos.slimming.miniAOD_tools import miniAOD_customizeOutput
miniAOD_customizeOutput(output)
outputModuleName=streamType+'output'
setattr(self.process,outputModuleName,output)
outputModule=getattr(self.process,outputModuleName)
setattr(self.process,outputModuleName+'_step',cms.EndPath(outputModule))
path=getattr(self.process,outputModuleName+'_step')
self.schedule.append(path)
if self._options.outputCommands and streamType!='DQM':
for evct in self._options.outputCommands.split(','):
if not evct: continue
self.executeAndRemember("process.%s.outputCommands.append('%s')"%(outputModuleName,evct.strip()))
if not self._options.inlineEventContent:
tmpstreamType=streamType
if "NANOEDM" in tmpstreamType :
tmpstreamType=tmpstreamType.replace("NANOEDM","NANO")
def doNotInlineEventContent(instance,label = "process."+tmpstreamType+"EventContent.outputCommands"):
return label
outputModule.outputCommands.__dict__["dumpPython"] = doNotInlineEventContent
result+="\nprocess."+outputModuleName+" = "+outputModule.dumpPython()
return result
def addStandardSequences(self):
"""
Add selected standard sequences to the process
"""
# load the pile up file
if self._options.pileup:
pileupSpec=self._options.pileup.split(',')[0]
# Does the requested pile-up scenario exist?
from Configuration.StandardSequences.Mixing import Mixing,defineMixing
if not pileupSpec in Mixing and '.' not in pileupSpec and 'file:' not in pileupSpec:
message = pileupSpec+' is not a know mixing scenario:\n available are: '+'\n'.join(Mixing.keys())
raise Exception(message)
# Put mixing parameters in a dictionary
if '.' in pileupSpec:
mixingDict={'file':pileupSpec}
elif pileupSpec.startswith('file:'):
mixingDict={'file':pileupSpec[5:]}
else:
import copy
mixingDict=copy.copy(Mixing[pileupSpec])
if len(self._options.pileup.split(','))>1:
mixingDict.update(eval(self._options.pileup[self._options.pileup.find(',')+1:]))
# Load the pu cfg file corresponding to the requested pu scenario
if 'file:' in pileupSpec:
#the file is local
self.process.load(mixingDict['file'])
print("inlining mixing module configuration")
self._options.inlineObjets+=',mix'
else:
self.loadAndRemember(mixingDict['file'])
mixingDict.pop('file')
if not "DATAMIX" in self.stepMap.keys(): # when DATAMIX is present, pileup_input refers to pre-mixed GEN-RAW
if self._options.pileup_input:
if self._options.pileup_input.startswith('dbs:') or self._options.pileup_input.startswith('das:'):
mixingDict['F']=filesFromDASQuery('file dataset = %s'%(self._options.pileup_input[4:],),self._options.pileup_dasoption)[0]
elif self._options.pileup_input.startswith("filelist:"):
mixingDict['F']=(filesFromList(self._options.pileup_input[9:]))[0]
else:
mixingDict['F']=self._options.pileup_input.split(',')
specialization=defineMixing(mixingDict)
for command in specialization:
self.executeAndRemember(command)
if len(mixingDict)!=0:
raise Exception('unused mixing specification: '+mixingDict.keys().__str__())
# load the geometry file
try:
if len(self.stepMap):
self.loadAndRemember(self.GeometryCFF)
if ('SIM' in self.stepMap or 'reSIM' in self.stepMap) and not self._options.fast:
self.loadAndRemember(self.SimGeometryCFF)
if self.geometryDBLabel:
self.executeAndRemember('if hasattr(process, "XMLFromDBSource"): process.XMLFromDBSource.label="%s"'%(self.geometryDBLabel))
self.executeAndRemember('if hasattr(process, "DDDetectorESProducerFromDB"): process.DDDetectorESProducerFromDB.label="%s"'%(self.geometryDBLabel))
except ImportError:
print("Geometry option",self._options.geometry,"unknown.")
raise
if len(self.stepMap):
self.loadAndRemember(self.magFieldCFF)
for stepName in self.stepKeys:
stepSpec = self.stepMap[stepName]
print("Step:", stepName,"Spec:",stepSpec)
if stepName.startswith('re'):
##add the corresponding input content
if stepName[2:] not in self._options.donotDropOnInput:
self._options.inputEventContent='%s,%s'%(stepName.upper(),self._options.inputEventContent)
stepName=stepName[2:]
if stepSpec=="":
getattr(self,"prepare_"+stepName)(sequence = getattr(self,stepName+"DefaultSeq"))
elif isinstance(stepSpec, list):
getattr(self,"prepare_"+stepName)(sequence = '+'.join(stepSpec))
elif isinstance(stepSpec, tuple):
getattr(self,"prepare_"+stepName)(sequence = ','.join([stepSpec[1],'+'.join(stepSpec[0])]))
else:
raise ValueError("Invalid step definition")
if self._options.restoreRNDSeeds!=False:
#it is either True, or a process name
if self._options.restoreRNDSeeds==True:
self.executeAndRemember('process.RandomNumberGeneratorService.restoreStateLabel=cms.untracked.string("randomEngineStateProducer")')
else:
self.executeAndRemember('process.RandomNumberGeneratorService.restoreStateTag=cms.untracked.InputTag("randomEngineStateProducer","","%s")'%(self._options.restoreRNDSeeds))
if self._options.inputEventContent or self._options.inputCommands:
if self._options.inputCommands:
self._options.inputCommands+='keep *_randomEngineStateProducer_*_*,'
else:
self._options.inputCommands='keep *_randomEngineStateProducer_*_*,'
def completeInputCommand(self):
if self._options.inputEventContent:
import copy
def dropSecondDropStar(iec):
#drop occurence of 'drop *' in the list
count=0
for item in iec:
if item=='drop *':
if count!=0:
iec.remove(item)
count+=1
## allow comma separated input eventcontent
if not hasattr(self.process.source,'inputCommands'): self.process.source.inputCommands=cms.untracked.vstring()
for evct in self._options.inputEventContent.split(','):
if evct=='': continue
theEventContent = getattr(self.process, evct+"EventContent")
if hasattr(theEventContent,'outputCommands'):
self.process.source.inputCommands.extend(copy.copy(theEventContent.outputCommands))
if hasattr(theEventContent,'inputCommands'):
self.process.source.inputCommands.extend(copy.copy(theEventContent.inputCommands))
dropSecondDropStar(self.process.source.inputCommands)
if not self._options.dropDescendant:
self.process.source.dropDescendantsOfDroppedBranches = cms.untracked.bool(False)
return
def addConditions(self):
"""Add conditions to the process"""
if not self._options.conditions: return
if 'FrontierConditions_GlobalTag' in self._options.conditions:
print('using FrontierConditions_GlobalTag in --conditions is not necessary anymore and will be deprecated soon. please update your command line')
self._options.conditions = self._options.conditions.replace("FrontierConditions_GlobalTag,",'')
self.loadAndRemember(self.ConditionsDefaultCFF)
from Configuration.AlCa.GlobalTag import GlobalTag
self.process.GlobalTag = GlobalTag(self.process.GlobalTag, self._options.conditions, self._options.custom_conditions)
self.additionalCommands.append('from Configuration.AlCa.GlobalTag import GlobalTag')
self.additionalCommands.append('process.GlobalTag = GlobalTag(process.GlobalTag, %s, %s)' % (repr(self._options.conditions), repr(self._options.custom_conditions)))
def addCustomise(self,unsch=0):
"""Include the customise code """
custOpt=[]
if unsch==0:
for c in self._options.customisation_file:
custOpt.extend(c.split(","))
else:
for c in self._options.customisation_file_unsch:
custOpt.extend(c.split(","))
custMap=DictTypes.SortedKeysDict()
for opt in custOpt:
if opt=='': continue
if opt.count('.')>1:
raise Exception("more than . in the specification:"+opt)
fileName=opt.split('.')[0]
if opt.count('.')==0: rest='customise'
else:
rest=opt.split('.')[1]
if rest=='py': rest='customise' #catch the case of --customise file.py
if fileName in custMap:
custMap[fileName].extend(rest.split('+'))
else:
custMap[fileName]=rest.split('+')
if len(custMap)==0:
final_snippet='\n'
else:
final_snippet='\n# customisation of the process.\n'
allFcn=[]
for opt in custMap:
allFcn.extend(custMap[opt])
for fcn in allFcn:
if allFcn.count(fcn)!=1:
raise Exception("cannot specify twice "+fcn+" as a customisation method")
for f in custMap:
# let python search for that package and do syntax checking at the same time
packageName = f.replace(".py","").replace("/",".")
__import__(packageName)
package = sys.modules[packageName]
# now ask the package for its definition and pick .py instead of .pyc
customiseFile = re.sub(r'\.pyc$', '.py', package.__file__)
final_snippet+='\n# Automatic addition of the customisation function from '+packageName+'\n'
if self._options.inline_custom:
for line in file(customiseFile,'r'):
if "import FWCore.ParameterSet.Config" in line:
continue
final_snippet += line
else:
final_snippet += 'from %s import %s \n'%(packageName,','.join(custMap[f]))
for fcn in custMap[f]:
print("customising the process with",fcn,"from",f)
if not hasattr(package,fcn):
#bound to fail at run time
raise Exception("config "+f+" has no function "+fcn)
#execute the command
self.process=getattr(package,fcn)(self.process)
#and print it in the configuration
final_snippet += "\n#call to customisation function "+fcn+" imported from "+packageName
final_snippet += "\nprocess = %s(process)\n"%(fcn,)
if len(custMap)!=0:
final_snippet += '\n# End of customisation functions\n'
### now for a useful command
return final_snippet
def addCustomiseCmdLine(self):
final_snippet='\n# Customisation from command line\n'
if self._options.customise_commands:
import string
for com in self._options.customise_commands.split('\\n'):
com=com.lstrip()
self.executeAndRemember(com)
final_snippet +='\n'+com
return final_snippet
#----------------------------------------------------------------------------
# here the methods to define the python includes for each step or
# conditions
#----------------------------------------------------------------------------
def define_Configs(self):
if len(self.stepMap):
self.loadAndRemember('Configuration/StandardSequences/Services_cff')
if self._options.particleTable not in defaultOptions.particleTableList:
print('Invalid particle table provided. Options are:')
print(defaultOptions.particleTable)
sys.exit(-1)
else:
if len(self.stepMap):
self.loadAndRemember('SimGeneral.HepPDTESSource.'+self._options.particleTable+'_cfi')
self.loadAndRemember('FWCore/MessageService/MessageLogger_cfi')
self.ALCADefaultCFF="Configuration/StandardSequences/AlCaRecoStreams_cff"
self.GENDefaultCFF="Configuration/StandardSequences/Generator_cff"
self.SIMDefaultCFF="Configuration/StandardSequences/Sim_cff"
self.DIGIDefaultCFF="Configuration/StandardSequences/Digi_cff"
self.DIGI2RAWDefaultCFF="Configuration/StandardSequences/DigiToRaw_cff"
self.L1EMDefaultCFF='Configuration/StandardSequences/SimL1Emulator_cff'
self.L1MENUDefaultCFF="Configuration/StandardSequences/L1TriggerDefaultMenu_cff"
self.HLTDefaultCFF="Configuration/StandardSequences/HLTtable_cff"
self.RAW2DIGIDefaultCFF="Configuration/StandardSequences/RawToDigi_Data_cff"
if self._options.isRepacked: self.RAW2DIGIDefaultCFF="Configuration/StandardSequences/RawToDigi_DataMapper_cff"
self.L1RecoDefaultCFF="Configuration/StandardSequences/L1Reco_cff"
self.L1TrackTriggerDefaultCFF="Configuration/StandardSequences/L1TrackTrigger_cff"
self.RECODefaultCFF="Configuration/StandardSequences/Reconstruction_Data_cff"
self.RECOSIMDefaultCFF="Configuration/StandardSequences/RecoSim_cff"
self.PATDefaultCFF="Configuration/StandardSequences/PAT_cff"
self.NANODefaultCFF="PhysicsTools/NanoAOD/nano_cff"
self.NANOGENDefaultCFF="PhysicsTools/NanoAOD/nanogen_cff"
self.SKIMDefaultCFF="Configuration/StandardSequences/Skims_cff"
self.POSTRECODefaultCFF="Configuration/StandardSequences/PostRecoGenerator_cff"
self.VALIDATIONDefaultCFF="Configuration/StandardSequences/Validation_cff"
self.L1HwValDefaultCFF = "Configuration/StandardSequences/L1HwVal_cff"
self.DQMOFFLINEDefaultCFF="DQMOffline/Configuration/DQMOffline_cff"
self.HARVESTINGDefaultCFF="Configuration/StandardSequences/Harvesting_cff"
self.ALCAHARVESTDefaultCFF="Configuration/StandardSequences/AlCaHarvesting_cff"
self.ENDJOBDefaultCFF="Configuration/StandardSequences/EndOfProcess_cff"
self.ConditionsDefaultCFF = "Configuration/StandardSequences/FrontierConditions_GlobalTag_cff"
self.CFWRITERDefaultCFF = "Configuration/StandardSequences/CrossingFrameWriter_cff"
self.REPACKDefaultCFF="Configuration/StandardSequences/DigiToRaw_Repack_cff"
if "DATAMIX" in self.stepMap.keys():
self.DATAMIXDefaultCFF="Configuration/StandardSequences/DataMixer"+self._options.datamix+"_cff"
self.DIGIDefaultCFF="Configuration/StandardSequences/DigiDM_cff"
self.DIGI2RAWDefaultCFF="Configuration/StandardSequences/DigiToRawDM_cff"
self.L1EMDefaultCFF='Configuration/StandardSequences/SimL1EmulatorDM_cff'
self.ALCADefaultSeq=None
self.LHEDefaultSeq='externalLHEProducer'
self.GENDefaultSeq='pgen'
self.SIMDefaultSeq='psim'
self.DIGIDefaultSeq='pdigi'
self.DATAMIXDefaultSeq=None
self.DIGI2RAWDefaultSeq='DigiToRaw'
self.HLTDefaultSeq='GRun'
self.L1DefaultSeq=None
self.L1REPACKDefaultSeq='GT'
self.HARVESTINGDefaultSeq=None