-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathConfig.py
4966 lines (4658 loc) · 237 KB
/
Config.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
### command line options helper
import os
from .Options import Options
options = Options()
## imports
import sys
from typing import Union
from .Mixins import PrintOptions,_ParameterTypeBase,_SimpleParameterTypeBase, _Parameterizable, _ConfigureComponent, _TypedParameterizable, _Labelable, _Unlabelable, _ValidatingListBase, _modifyParametersFromDict
from .Mixins import *
from .Types import *
from .Modules import *
from .Modules import _Module
from .SequenceTypes import *
from .SequenceTypes import _ModuleSequenceType, _Sequenceable #extend needs it
from .SequenceVisitors import PathValidator, EndPathValidator, FinalPathValidator, ScheduleTaskValidator, NodeVisitor, CompositeVisitor, ModuleNamesFromGlobalsVisitor
from .MessageLogger import MessageLogger
from . import DictTypes
from .ExceptionHandling import *
#when building RECO paths we have hit the default recursion limit
if sys.getrecursionlimit()<5000:
sys.setrecursionlimit(5000)
class edm(object):
class errors(object):
#Allowed errors to be used within Python
Configuration = "{Configuration}"
UnavailableAccelerator = "{UnavailableAccelerator}"
class EDMException(Exception):
def __init__(self, error:str, message: str):
super().__init__(error+"\n"+message)
def checkImportPermission(minLevel: int = 2, allowedPatterns = []):
"""
Raise an exception if called by special config files. This checks
the call or import stack for the importing file. An exception is raised if
the importing module is not in allowedPatterns and if it is called too deeply:
minLevel = 2: inclusion by top lvel cfg only
minLevel = 1: No inclusion allowed
allowedPatterns = ['Module1','Module2/SubModule1'] allows import
by any module in Module1 or Submodule1
"""
import inspect
import os
ignorePatterns = ['FWCore/ParameterSet/Config.py', 'FWCore/ParameterSet/python/Config.py','<string>','<frozen ']
CMSSWPath = [os.path.realpath(os.getenv(base)) for base in ['CMSSW_BASE', 'CMSSW_RELEASE_BASE', 'CMSSW_FULL_RELEASE_BASE'] if os.getenv(base, '')]
# Filter the stack to things in CMSSWPath and not in ignorePatterns
trueStack = []
for item in inspect.stack():
inPath = False
ignore = False
for pattern in CMSSWPath:
if item[1].find(pattern) != -1:
inPath = True
break
if item[1].find('/') == -1: # The base file, no path
inPath = True
for pattern in ignorePatterns:
if item[1].find(pattern) != -1:
ignore = True
break
if inPath and not ignore:
trueStack.append(item[1])
importedFile = trueStack[0]
importedBy = ''
if len(trueStack) > 1:
importedBy = trueStack[1]
for pattern in allowedPatterns:
if importedBy.find(pattern) > -1:
return True
if len(trueStack) <= minLevel: # Imported directly
return True
raise ImportError("Inclusion of %s is allowed only by cfg or specified cfi files."
% importedFile)
def findProcess(module):
"""Look inside the module and find the Processes it contains"""
class Temp(object):
pass
process = None
if isinstance(module,dict):
if 'process' in module:
p = module['process']
module = Temp()
module.process = p
if hasattr(module,'process'):
if isinstance(module.process,Process):
process = module.process
else:
raise RuntimeError("The attribute named 'process' does not inherit from the Process class")
else:
raise RuntimeError("no 'process' attribute found in the module, please add one")
return process
class Process(object):
"""Root class for a CMS configuration process"""
_firstProcess = True
def __init__(self,name: str, *Mods):
"""The argument 'name' will be the name applied to this Process
Can optionally pass as additional arguments cms.Modifier instances
that will be used to modify the Process as it is built
"""
self.__dict__['_Process__name'] = name
if not name.isalnum():
raise RuntimeError("Error: The process name is an empty string or contains non-alphanumeric characters")
self.__dict__['_Process__filters'] = {}
self.__dict__['_Process__producers'] = {}
self.__dict__['_Process__switchproducers'] = {}
self.__dict__['_Process__source'] = None
self.__dict__['_Process__looper'] = None
self.__dict__['_Process__subProcesses'] = []
self.__dict__['_Process__schedule'] = None
self.__dict__['_Process__analyzers'] = {}
self.__dict__['_Process__outputmodules'] = {}
self.__dict__['_Process__paths'] = DictTypes.SortedKeysDict() # have to keep the order
self.__dict__['_Process__endpaths'] = DictTypes.SortedKeysDict() # of definition
self.__dict__['_Process__finalpaths'] = DictTypes.SortedKeysDict() # of definition
self.__dict__['_Process__sequences'] = {}
self.__dict__['_Process__tasks'] = {}
self.__dict__['_Process__conditionaltasks'] = {}
self.__dict__['_Process__services'] = {}
self.__dict__['_Process__essources'] = {}
self.__dict__['_Process__esproducers'] = {}
self.__dict__['_Process__esprefers'] = {}
self.__dict__['_Process__aliases'] = {}
self.__dict__['_Process__psets']={}
self.__dict__['_Process__vpsets']={}
self.__dict__['_cloneToObjectDict'] = {}
# policy switch to avoid object overwriting during extend/load
self.__dict__['_Process__InExtendCall'] = False
self.__dict__['_Process__partialschedules'] = {}
self.__isStrict = False
self.__dict__['_Process__modifiers'] = Mods
self.__dict__['_Process__accelerators'] = {}
self.__dict__['_Process__specialOverrideReleaseVersionOnlyForTesting'] = None
self.__injectValidValue('options', Process.defaultOptions_())
self.__injectValidValue('maxEvents', Process.defaultMaxEvents_())
self.maxLuminosityBlocks = Process.defaultMaxLuminosityBlocks_()
# intentionally not cloned to ensure that everyone taking
# MessageLogger still via
# FWCore.Message(Logger|Service).MessageLogger_cfi
# use the very same MessageLogger object.
self.MessageLogger = MessageLogger
if Process._firstProcess:
Process._firstProcess = False
else:
if len(Mods) > 0:
for m in self.__modifiers:
if not m._isChosen():
raise RuntimeError("The Process {} tried to redefine which Modifiers to use after another Process was already started".format(name))
for m in self.__modifiers:
m._setChosen()
def setStrict(self, value: bool):
self.__isStrict = value
_Module.__isStrict__ = True
# some user-friendly methods for command-line browsing
def producerNames(self):
"""Returns a string containing all the EDProducer labels separated by a blank"""
return ' '.join(self.producers_().keys())
def switchProducerNames(self):
"""Returns a string containing all the SwitchProducer labels separated by a blank"""
return ' '.join(self.switchProducers_().keys())
def analyzerNames(self):
"""Returns a string containing all the EDAnalyzer labels separated by a blank"""
return ' '.join(self.analyzers_().keys())
def filterNames(self):
"""Returns a string containing all the EDFilter labels separated by a blank"""
return ' '.join(self.filters_().keys())
def pathNames(self):
"""Returns a string containing all the Path names separated by a blank"""
return ' '.join(self.paths_().keys())
def __setstate__(self, pkldict):
"""
Unpickling hook.
Since cloneToObjectDict stores a hash of objects by their
id() it needs to be updated when unpickling to use the
new object id values instantiated during the unpickle.
"""
self.__dict__.update(pkldict)
tmpDict = {}
for value in self._cloneToObjectDict.values():
tmpDict[id(value)] = value
self.__dict__['_cloneToObjectDict'] = tmpDict
def filters_(self):
"""returns a dict of the filters that have been added to the Process"""
return DictTypes.FixedKeysDict(self.__filters)
filters = property(filters_, doc="dictionary containing the filters for the process")
def name_(self) -> str:
return self.__name
def setName_(self,name: str):
if not name.isalnum():
raise RuntimeError("Error: The process name is an empty string or contains non-alphanumeric characters")
self.__dict__['_Process__name'] = name
process = property(name_,setName_, doc="name of the process")
def producers_(self):
"""returns a dict of the producers that have been added to the Process"""
return DictTypes.FixedKeysDict(self.__producers)
producers = property(producers_,doc="dictionary containing the producers for the process")
def switchProducers_(self):
"""returns a dict of the SwitchProducers that have been added to the Process"""
return DictTypes.FixedKeysDict(self.__switchproducers)
switchProducers = property(switchProducers_,doc="dictionary containing the SwitchProducers for the process")
def source_(self):
"""returns the source that has been added to the Process or None if none have been added"""
return self.__source
def setSource_(self,src):
self._placeSource('source',src)
source = property(source_,setSource_,doc='the main source or None if not set')
def looper_(self):
"""returns the looper that has been added to the Process or None if none have been added"""
return self.__looper
def setLooper_(self,lpr):
self._placeLooper('looper',lpr)
looper = property(looper_,setLooper_,doc='the main looper or None if not set')
@staticmethod
def defaultOptions_():
return untracked.PSet(numberOfThreads = untracked.uint32(1),
numberOfStreams = untracked.uint32(0),
numberOfConcurrentRuns = untracked.uint32(1),
numberOfConcurrentLuminosityBlocks = untracked.uint32(0),
eventSetup = untracked.PSet(
numberOfConcurrentIOVs = untracked.uint32(0),
forceNumberOfConcurrentIOVs = untracked.PSet(
allowAnyLabel_ = required.untracked.uint32
)
),
accelerators = untracked.vstring('*'),
wantSummary = untracked.bool(False),
fileMode = untracked.string('FULLMERGE'),
forceEventSetupCacheClearOnNewRun = untracked.bool(False),
throwIfIllegalParameter = untracked.bool(True),
printDependencies = untracked.bool(False),
deleteNonConsumedUnscheduledModules = untracked.bool(True),
sizeOfStackForThreadsInKB = optional.untracked.uint32,
Rethrow = untracked.vstring(),
TryToContinue = untracked.vstring(),
IgnoreCompletely = untracked.vstring(),
modulesToCallForTryToContinue = untracked.vstring(),
canDeleteEarly = untracked.vstring(),
holdsReferencesToDeleteEarly = untracked.VPSet(),
modulesToIgnoreForDeleteEarly = untracked.vstring(),
dumpOptions = untracked.bool(False),
allowUnscheduled = obsolete.untracked.bool,
emptyRunLumiMode = obsolete.untracked.string,
makeTriggerResults = obsolete.untracked.bool,
)
def __updateOptions(self,opt):
newOpts = self.defaultOptions_()
if isinstance(opt,dict):
for k,v in opt.items():
setattr(newOpts,k,v)
else:
for p in opt.parameters_():
setattr(newOpts, p, getattr(opt,p))
return newOpts
@staticmethod
def defaultMaxEvents_():
return untracked.PSet(input=optional.untracked.int32,
output=optional.untracked.allowed(int32,PSet))
def __updateMaxEvents(self,ps: Union[dict,PSet]):
newMax = self.defaultMaxEvents_()
if isinstance(ps,dict):
for k,v in ps.items():
setattr(newMax,k,v)
else:
for p in ps.parameters_():
setattr(newMax, p, getattr(ps,p))
return newMax
@staticmethod
def defaultMaxLuminosityBlocks_():
return untracked.PSet(input=untracked.int32(-1))
def subProcesses_(self):
"""returns a list of the subProcesses that have been added to the Process"""
return self.__subProcesses
subProcesses = property(subProcesses_,doc='the SubProcesses that have been added to the Process')
def analyzers_(self):
"""returns a dict of the analyzers that have been added to the Process"""
return DictTypes.FixedKeysDict(self.__analyzers)
analyzers = property(analyzers_,doc="dictionary containing the analyzers for the process")
def outputModules_(self):
"""returns a dict of the output modules that have been added to the Process"""
return DictTypes.FixedKeysDict(self.__outputmodules)
outputModules = property(outputModules_,doc="dictionary containing the output_modules for the process")
def paths_(self):
"""returns a dict of the paths that have been added to the Process"""
return DictTypes.SortedAndFixedKeysDict(self.__paths)
paths = property(paths_,doc="dictionary containing the paths for the process")
def endpaths_(self):
"""returns a dict of the endpaths that have been added to the Process"""
return DictTypes.SortedAndFixedKeysDict(self.__endpaths)
endpaths = property(endpaths_,doc="dictionary containing the endpaths for the process")
def finalpaths_(self):
"""returns a dict of the finalpaths that have been added to the Process"""
return DictTypes.SortedAndFixedKeysDict(self.__finalpaths)
finalpaths = property(finalpaths_,doc="dictionary containing the finalpaths for the process")
def sequences_(self):
"""returns a dict of the sequences that have been added to the Process"""
return DictTypes.FixedKeysDict(self.__sequences)
sequences = property(sequences_,doc="dictionary containing the sequences for the process")
def tasks_(self):
"""returns a dict of the tasks that have been added to the Process"""
return DictTypes.FixedKeysDict(self.__tasks)
tasks = property(tasks_,doc="dictionary containing the tasks for the process")
def conditionaltasks_(self):
"""returns a dict of the conditionaltasks that have been added to the Process"""
return DictTypes.FixedKeysDict(self.__conditionaltasks)
conditionaltasks = property(conditionaltasks_,doc="dictionary containing the conditionatasks for the process")
def schedule_(self):
"""returns the schedule that has been added to the Process or None if none have been added"""
return self.__schedule
def setPartialSchedule_(self,sch: Schedule,label: str):
if label == "schedule":
self.setSchedule_(sch)
else:
self._place(label, sch, self.__partialschedules)
def setSchedule_(self,sch: Schedule):
# See if every path and endpath has been inserted into the process
index = 0
try:
for p in sch:
p.label_()
index +=1
except:
raise RuntimeError("The path at index "+str(index)+" in the Schedule was not attached to the process.")
self.__dict__['_Process__schedule'] = sch
schedule = property(schedule_,setSchedule_,doc='the schedule or None if not set')
def services_(self):
"""returns a dict of the services that have been added to the Process"""
return DictTypes.FixedKeysDict(self.__services)
services = property(services_,doc="dictionary containing the services for the process")
def processAccelerators_(self):
"""returns a dict of the ProcessAccelerators that have been added to the Process"""
return DictTypes.FixedKeysDict(self.__accelerators)
processAccelerators = property(processAccelerators_,doc="dictionary containing the ProcessAccelerators for the process")
def es_producers_(self):
"""returns a dict of the esproducers that have been added to the Process"""
return DictTypes.FixedKeysDict(self.__esproducers)
es_producers = property(es_producers_,doc="dictionary containing the es_producers for the process")
def es_sources_(self):
"""returns a the es_sources that have been added to the Process"""
return DictTypes.FixedKeysDict(self.__essources)
es_sources = property(es_sources_,doc="dictionary containing the es_sources for the process")
def es_prefers_(self):
"""returns a dict of the es_prefers that have been added to the Process"""
return DictTypes.FixedKeysDict(self.__esprefers)
es_prefers = property(es_prefers_,doc="dictionary containing the es_prefers for the process")
def aliases_(self):
"""returns a dict of the aliases that have been added to the Process"""
return DictTypes.FixedKeysDict(self.__aliases)
aliases = property(aliases_,doc="dictionary containing the aliases for the process")
def psets_(self):
"""returns a dict of the PSets that have been added to the Process"""
return DictTypes.FixedKeysDict(self.__psets)
psets = property(psets_,doc="dictionary containing the PSets for the process")
def vpsets_(self):
"""returns a dict of the VPSets that have been added to the Process"""
return DictTypes.FixedKeysDict(self.__vpsets)
vpsets = property(vpsets_,doc="dictionary containing the PSets for the process")
def isUsingModifier(self,mod) -> bool:
"""returns True if the Modifier is in used by this Process"""
if mod._isChosen():
for m in self.__modifiers:
if m._isOrContains(mod):
return True
return False
def __setObjectLabel(self, object, newLabel:str) :
if not object.hasLabel_() :
object.setLabel(newLabel)
return
if newLabel == object.label_() :
return
if newLabel is None :
object.setLabel(None)
return
if (hasattr(self, object.label_()) and id(getattr(self, object.label_())) == id(object)) :
msg100 = "Attempting to change the label of an attribute of the Process\n"
msg101 = "Old label = "+object.label_()+" New label = "+newLabel+"\n"
msg102 = "Type = "+str(type(object))+"\n"
msg103 = "Some possible solutions:\n"
msg104 = " 1. Clone modules instead of using simple assignment. Cloning is\n"
msg105 = " also preferred for other types when possible.\n"
msg106 = " 2. Declare new names starting with an underscore if they are\n"
msg107 = " for temporaries you do not want propagated into the Process. The\n"
msg108 = " underscore tells \"from x import *\" and process.load not to import\n"
msg109 = " the name.\n"
msg110 = " 3. Reorganize so the assigment is not necessary. Giving a second\n"
msg111 = " name to the same object usually causes confusion and problems.\n"
msg112 = " 4. Compose Sequences: newName = cms.Sequence(oldName)\n"
raise ValueError(msg100+msg101+msg102+msg103+msg104+msg105+msg106+msg107+msg108+msg109+msg110+msg111+msg112)
object.setLabel(None)
object.setLabel(newLabel)
def __setattr__(self,name:str,value):
# check if the name is well-formed (only _ and alphanumerics are allowed)
if not name.replace('_','').isalnum():
raise ValueError('The label '+name+' contains forbiden characters')
if name == 'options':
value = self.__updateOptions(value)
if name == 'maxEvents':
value = self.__updateMaxEvents(value)
# private variable exempt from all this
if name.startswith('_Process__'):
self.__dict__[name]=value
return
if not isinstance(value,_ConfigureComponent):
raise TypeError("can only assign labels to an object that inherits from '_ConfigureComponent'\n"
+"an instance of "+str(type(value))+" will not work - requested label is "+name)
if not isinstance(value,_Labelable) and not isinstance(value,Source) and not isinstance(value,Looper) and not isinstance(value,Schedule):
if name == value.type_():
if hasattr(self,name) and (getattr(self,name)!=value):
self._replaceInTasks(name, value)
self._replaceInConditionalTasks(name, value)
# Only Services get handled here
self.add_(value)
return
else:
raise TypeError("an instance of "+str(type(value))+" can not be assigned the label '"+name+"'.\n"+
"Please either use the label '"+value.type_()+" or use the 'add_' method instead.")
#clone the item
if self.__isStrict:
newValue =value.copy()
try:
newValue._filename = value._filename
except:
pass
value.setIsFrozen()
else:
newValue =value
if not self._okToPlace(name, value, self.__dict__):
newFile='top level config'
if hasattr(value,'_filename'):
newFile = value._filename
oldFile='top level config'
oldValue = getattr(self,name)
if hasattr(oldValue,'_filename'):
oldFile = oldValue._filename
msg = "Trying to override definition of process."+name
msg += "\n new object defined in: "+newFile
msg += "\n existing object defined in: "+oldFile
raise ValueError(msg)
# remove the old object of the name (if there is one)
if hasattr(self,name) and not (getattr(self,name)==newValue):
# Complain if items in sequences or tasks from load() statements have
# degenerate names, but if the user overwrites a name in the
# main config, replace it everywhere
if newValue._isTaskComponent():
if not self.__InExtendCall:
self._replaceInTasks(name, newValue)
self._replaceInConditionalTasks(name, newValue)
self._replaceInSchedule(name, newValue)
else:
if not isinstance(newValue, Task):
#should check to see if used in task before complaining
newFile='top level config'
if hasattr(value,'_filename'):
newFile = value._filename
oldFile='top level config'
oldValue = getattr(self,name)
if hasattr(oldValue,'_filename'):
oldFile = oldValue._filename
msg1 = "Trying to override definition of "+name+" while it is used by the task "
msg2 = "\n new object defined in: "+newFile
msg2 += "\n existing object defined in: "+oldFile
s = self.__findFirstUsingModule(self.tasks,oldValue)
if s is not None:
raise ValueError(msg1+s.label_()+msg2)
if isinstance(newValue, _Sequenceable) or newValue._isTaskComponent() or isinstance(newValue, ConditionalTask):
if not self.__InExtendCall:
if isinstance(newValue, ConditionalTask):
self._replaceInConditionalTasks(name, newValue)
self._replaceInSequences(name, newValue)
else:
#should check to see if used in sequence before complaining
newFile='top level config'
if hasattr(value,'_filename'):
newFile = value._filename
oldFile='top level config'
oldValue = getattr(self,name)
if hasattr(oldValue,'_filename'):
oldFile = oldValue._filename
msg1 = "Trying to override definition of "+name+" while it is used by the "
msg2 = "\n new object defined in: "+newFile
msg2 += "\n existing object defined in: "+oldFile
s = self.__findFirstUsingModule(self.sequences,oldValue)
if s is not None:
raise ValueError(msg1+"sequence "+s.label_()+msg2)
s = self.__findFirstUsingModule(self.paths,oldValue)
if s is not None:
raise ValueError(msg1+"path "+s.label_()+msg2)
s = self.__findFirstUsingModule(self.endpaths,oldValue)
if s is not None:
raise ValueError(msg1+"endpath "+s.label_()+msg2)
s = self.__findFirstUsingModule(self.finalpaths,oldValue)
if s is not None:
raise ValueError(msg1+"finalpath "+s.label_()+msg2)
# In case of EDAlias, raise Exception always to avoid surprises
if isinstance(newValue, EDAlias):
oldValue = getattr(self, name)
#should check to see if used in task/sequence before complaining
newFile='top level config'
if hasattr(value,'_filename'):
newFile = value._filename
oldFile='top level config'
if hasattr(oldValue,'_filename'):
oldFile = oldValue._filename
msg1 = "Trying to override definition of "+name+" with an EDAlias while it is used by the "
msg2 = "\n new object defined in: "+newFile
msg2 += "\n existing object defined in: "+oldFile
s = self.__findFirstUsingModule(self.tasks,oldValue)
if s is not None:
raise ValueError(msg1+"task "+s.label_()+msg2)
s = self.__findFirstUsingModule(self.sequences,oldValue)
if s is not None:
raise ValueError(msg1+"sequence "+s.label_()+msg2)
s = self.__findFirstUsingModule(self.paths,oldValue)
if s is not None:
raise ValueError(msg1+"path "+s.label_()+msg2)
s = self.__findFirstUsingModule(self.endpaths,oldValue)
if s is not None:
raise ValueError(msg1+"endpath "+s.label_()+msg2)
s = self.__findFirstUsingModule(self.finalpaths,oldValue)
if s is not None:
raise ValueError(msg1+"finalpath "+s.label_()+msg2)
if not self.__InExtendCall and (Schedule._itemIsValid(newValue) or isinstance(newValue, Task)):
self._replaceInScheduleDirectly(name, newValue)
self._delattrFromSetattr(name)
self.__injectValidValue(name, value, newValue)
def __injectValidValue(self, name:str, value, newValue = None):
if newValue is None:
newValue = value
self.__dict__[name]=newValue
if isinstance(newValue,_Labelable):
self.__setObjectLabel(newValue, name)
self._cloneToObjectDict[id(value)] = newValue
self._cloneToObjectDict[id(newValue)] = newValue
#now put in proper bucket
newValue._place(name,self)
def __findFirstUsingModule(self, seqsOrTasks, mod):
"""Given a container of sequences or tasks, find the first sequence or task
containing mod and return it. If none is found, return None"""
from FWCore.ParameterSet.SequenceTypes import ModuleNodeVisitor
l = list()
for seqOrTask in seqsOrTasks.values():
l[:] = []
v = ModuleNodeVisitor(l)
seqOrTask.visit(v)
if mod in l:
return seqOrTask
return None
def _delHelper(self,name:str):
if not hasattr(self,name):
raise KeyError('process does not know about '+name)
elif name.startswith('_Process__'):
raise ValueError('this attribute cannot be deleted')
# we have to remove it from all dictionaries/registries
dicts = [item for item in self.__dict__.values() if (isinstance(item, dict) or isinstance(item, DictTypes.SortedKeysDict))]
for reg in dicts:
if name in reg: del reg[name]
# if it was a labelable object, the label needs to be removed
obj = getattr(self,name)
if isinstance(obj,_Labelable):
obj.setLabel(None)
if isinstance(obj,Service):
obj._inProcess = False
def __delattr__(self,name:str):
self._delHelper(name)
obj = getattr(self,name)
if not obj is None:
if not isinstance(obj, Sequence) and not isinstance(obj, Task) and not isinstance(obj,ConditionalTask):
# For modules, ES modules and services we can also remove
# the deleted object from Sequences, Paths, EndPaths, and
# Tasks. Note that for Sequences and Tasks that cannot be done
# reliably as the places where the Sequence or Task was used
# might have been expanded so we do not even try. We considered
# raising an exception if a Sequences or Task was explicitly
# deleted, but did not because when done carefully deletion
# is sometimes OK (for example in the prune function where it
# has been checked that the deleted Sequence is not used).
if obj._isTaskComponent():
self._replaceInTasks(name, None)
self._replaceInConditionalTasks(name, None)
self._replaceInSchedule(name, None)
if isinstance(obj, _Sequenceable) or obj._isTaskComponent():
self._replaceInSequences(name, None)
if Schedule._itemIsValid(obj) or isinstance(obj, Task):
self._replaceInScheduleDirectly(name, None)
# now remove it from the process itself
try:
del self.__dict__[name]
except:
pass
def _delattrFromSetattr(self,name:str):
"""Similar to __delattr__ but we need different behavior when called from __setattr__"""
self._delHelper(name)
# now remove it from the process itself
try:
del self.__dict__[name]
except:
pass
def add_(self,value):
"""Allows addition of components that do not have to have a label, e.g. Services"""
if not isinstance(value,_ConfigureComponent):
raise TypeError
if not isinstance(value,_Unlabelable):
raise TypeError
#clone the item
if self.__isStrict:
newValue =value.copy()
value.setIsFrozen()
else:
newValue =value
newValue._place('',self)
def _okToPlace(self, name:str, mod, d) -> bool:
if not self.__InExtendCall:
# if going
return True
elif not self.__isStrict:
return True
elif name in d:
# if there's an old copy, and the new one
# hasn't been modified, we're done. Still
# not quite safe if something has been defined twice.
# Need to add checks
if mod._isModified:
if d[name]._isModified:
return False
else:
return True
else:
return True
else:
return True
def _place(self, name:str, mod, d):
if self._okToPlace(name, mod, d):
if self.__isStrict and isinstance(mod, _ModuleSequenceType):
d[name] = mod._postProcessFixup(self._cloneToObjectDict)
else:
d[name] = mod
if isinstance(mod,_Labelable):
self.__setObjectLabel(mod, name)
def _placeOutputModule(self,name:str,mod):
self._place(name, mod, self.__outputmodules)
def _placeProducer(self,name:str,mod):
self._place(name, mod, self.__producers)
def _placeSwitchProducer(self,name:str,mod):
self._place(name, mod, self.__switchproducers)
def _placeFilter(self,name:str,mod):
self._place(name, mod, self.__filters)
def _placeAnalyzer(self,name:str,mod):
self._place(name, mod, self.__analyzers)
def _placePath(self,name:str,mod):
self._validateSequence(mod, name)
try:
self._place(name, mod, self.__paths)
except ModuleCloneError as msg:
context = format_outerframe(4)
raise Exception("%sThe module %s in path %s is unknown to the process %s." %(context, msg, name, self._Process__name))
def _placeEndPath(self,name:str,mod):
self._validateSequence(mod, name)
try:
self._place(name, mod, self.__endpaths)
except ModuleCloneError as msg:
context = format_outerframe(4)
raise Exception("%sThe module %s in endpath %s is unknown to the process %s." %(context, msg, name, self._Process__name))
def _placeFinalPath(self,name:str,mod):
self._validateSequence(mod, name)
try:
self._place(name, mod, self.__finalpaths)
except ModuleCloneError as msg:
context = format_outerframe(4)
raise Exception("%sThe module %s in finalpath %s is unknown to the process %s." %(context, msg, name, self._Process__name))
def _placeSequence(self,name:str,mod):
self._validateSequence(mod, name)
self._place(name, mod, self.__sequences)
def _placeESProducer(self,name:str,mod):
self._place(name, mod, self.__esproducers)
def _placeESPrefer(self,name:str,mod):
self._place(name, mod, self.__esprefers)
def _placeESSource(self,name:str,mod):
self._place(name, mod, self.__essources)
def _placeTask(self,name:str,task):
self._validateTask(task, name)
self._place(name, task, self.__tasks)
def _placeConditionalTask(self,name:str,task):
self._validateConditionalTask(task, name)
self._place(name, task, self.__conditionaltasks)
def _placeAlias(self,name:str,mod):
self._place(name, mod, self.__aliases)
def _placePSet(self,name:str,mod):
self._place(name, mod, self.__psets)
def _placeVPSet(self,name:str,mod):
self._place(name, mod, self.__vpsets)
def _placeSource(self,name:str,mod):
"""Allow the source to be referenced by 'source' or by type name"""
if name != 'source':
raise ValueError("The label '"+name+"' can not be used for a Source. Only 'source' is allowed.")
if self.__dict__['_Process__source'] is not None :
del self.__dict__[self.__dict__['_Process__source'].type_()]
self.__dict__['_Process__source'] = mod
self.__dict__[mod.type_()] = mod
def _placeLooper(self,name:str,mod):
if name != 'looper':
raise ValueError("The label '"+name+"' can not be used for a Looper. Only 'looper' is allowed.")
self.__dict__['_Process__looper'] = mod
self.__dict__[mod.type_()] = mod
def _placeSubProcess(self,name:str,mod):
self.__dict__['_Process__subProcess'] = mod
self.__dict__[mod.type_()] = mod
def addSubProcess(self,mod):
self.__subProcesses.append(mod)
def _placeService(self,typeName:str,mod):
self._place(typeName, mod, self.__services)
if typeName in self.__dict__:
self.__dict__[typeName]._inProcess = False
self.__dict__[typeName]=mod
def _placeAccelerator(self,typeName:str,mod):
self._place(typeName, mod, self.__accelerators)
self.__dict__[typeName]=mod
def load(self, moduleName:str):
moduleName = moduleName.replace("/",".")
module = __import__(moduleName)
self.extend(sys.modules[moduleName])
def extend(self,other,items=()):
"""Look in other and find types that we can use"""
# enable explicit check to avoid overwriting of existing objects
self.__dict__['_Process__InExtendCall'] = True
seqs = dict()
tasksToAttach = dict()
mods = []
for name in dir(other):
#'from XX import *' ignores these, and so should we.
if name.startswith('_'):
continue
item = getattr(other,name)
if name == "source" or name == "looper":
# In these cases 'item' could be None if the specific object was not defined
if item is not None:
self.__setattr__(name,item)
elif isinstance(item,_ModuleSequenceType):
seqs[name]=item
elif isinstance(item,Task) or isinstance(item, ConditionalTask):
tasksToAttach[name] = item
elif isinstance(item,_Labelable):
self.__setattr__(name,item)
if not item.hasLabel_() :
item.setLabel(name)
elif isinstance(item,Schedule):
self.__setattr__(name,item)
elif isinstance(item,_Unlabelable):
self.add_(item)
elif isinstance(item,ProcessModifier):
mods.append(item)
elif isinstance(item,ProcessFragment):
self.extend(item)
#now create a sequence that uses the newly made items
for name,seq in seqs.items():
if id(seq) not in self._cloneToObjectDict:
self.__setattr__(name,seq)
else:
newSeq = self._cloneToObjectDict[id(seq)]
self.__dict__[name]=newSeq
self.__setObjectLabel(newSeq, name)
#now put in proper bucket
newSeq._place(name,self)
for name, task in tasksToAttach.items():
self.__setattr__(name, task)
#apply modifiers now that all names have been added
for item in mods:
item.apply(self)
self.__dict__['_Process__InExtendCall'] = False
def _specialOverrideReleaseVersionOnlyForTesting(self, version):
"This function is intended only for specific framework tests. Do not use for anything else."
self.__specialOverrideReleaseVersionOnlyForTesting = version
def _dumpConfigNamedList(self,items,typeName:str,options:PrintOptions) -> str:
returnValue = ''
for name,item in items:
returnValue +=options.indentation()+typeName+' '+name+' = '+item.dumpConfig(options)
return returnValue
def _dumpConfigUnnamedList(self,items,typeName:str,options:PrintOptions) -> str:
returnValue = ''
for name,item in items:
returnValue +=options.indentation()+typeName+' = '+item.dumpConfig(options)
return returnValue
def _dumpConfigOptionallyNamedList(self,items,typeName:str,options:PrintOptions) -> str:
returnValue = ''
for name,item in items:
if name == item.type_():
name = ''
returnValue +=options.indentation()+typeName+' '+name+' = '+item.dumpConfig(options)
return returnValue
def dumpConfig(self, options:PrintOptions=PrintOptions()) -> str:
"""return a string containing the equivalent process defined using the old configuration language"""
config = "process "+self.__name+" = {\n"
options.indent()
if self.source_():
config += options.indentation()+"source = "+self.source_().dumpConfig(options)
if self.looper_():
config += options.indentation()+"looper = "+self.looper_().dumpConfig(options)
config+=self._dumpConfigNamedList(self.subProcesses_(),
'subProcess',
options)
config+=self._dumpConfigNamedList(self.producers_().items(),
'module',
options)
config+=self._dumpConfigNamedList(self.switchProducers_().items(),
'module',
options)
config+=self._dumpConfigNamedList(self.filters_().items(),
'module',
options)
config+=self._dumpConfigNamedList(self.analyzers_().items(),
'module',
options)
config+=self._dumpConfigNamedList(self.outputModules_().items(),
'module',
options)
config+=self._dumpConfigNamedList(self.sequences_().items(),
'sequence',
options)
config+=self._dumpConfigNamedList(self.paths_().items(),
'path',
options)
config+=self._dumpConfigNamedList(self.endpaths_().items(),
'endpath',
options)
config+=self._dumpConfigNamedList(self.finalpaths_().items(),
'finalpath',
options)
config+=self._dumpConfigUnnamedList(self.services_().items(),
'service',
options)
config+=self._dumpConfigNamedList(self.aliases_().items(),
'alias',
options)
config+=self._dumpConfigOptionallyNamedList(
self.es_producers_().items(),
'es_module',
options)
config+=self._dumpConfigOptionallyNamedList(
self.es_sources_().items(),
'es_source',
options)
config += self._dumpConfigESPrefers(options)
for name,item in self.psets.items():
config +=options.indentation()+item.configTypeName()+' '+name+' = '+item.configValue(options)
for name,item in self.vpsets.items():
config +=options.indentation()+'VPSet '+name+' = '+item.configValue(options)
if self.schedule:
pathNames = [p.label_() for p in self.schedule]
config +=options.indentation()+'schedule = {'+','.join(pathNames)+'}\n'
# config+=self._dumpConfigNamedList(self.vpsets.items(),
# 'VPSet',
# options)
config += "}\n"
options.unindent()
return config
def _dumpConfigESPrefers(self, options:PrintOptions) -> str:
result = ''
for item in self.es_prefers_().values():
result +=options.indentation()+'es_prefer '+item.targetLabel_()+' = '+item.dumpConfig(options)
return result
def _dumpPythonSubProcesses(self, l, options:PrintOptions) -> str:
returnValue = ''
for item in l:
returnValue += item.dumpPython(options)+'\n\n'
return returnValue
def _dumpPythonList(self, d, options:PrintOptions) -> str:
returnValue = ''
if isinstance(d, DictTypes.SortedKeysDict):
for name,item in d.items():
returnValue +='process.'+name+' = '+item.dumpPython(options)+'\n\n'
else:
for name,item in sorted(d.items()):
returnValue +='process.'+name+' = '+item.dumpPython(options)+'\n\n'
return returnValue
def _splitPythonList(self, subfolder, d, options:PrintOptions) -> str:
parts = DictTypes.SortedKeysDict()
for name, item in d.items() if isinstance(d, DictTypes.SortedKeysDict) else sorted(d.items()):
code = ''
dependencies = item.directDependencies()
for module_subfolder, module in dependencies:
module = module + '_cfi'
if options.useSubdirectories and module_subfolder:
module = module_subfolder + '.' + module
if options.targetDirectory is not None:
if options.useSubdirectories and subfolder:
module = '..' + module
else:
module = '.' + module
code += 'from ' + module + ' import *\n'
if dependencies:
code += '\n'
code += name + ' = ' + item.dumpPython(options)
parts[name] = subfolder, code
return parts
def _validateSequence(self, sequence, label):
# See if every module has been inserted into the process
try:
l = set()
visitor = NodeNameVisitor(l)
sequence.visit(visitor)
except Exception as e:
raise RuntimeError("An entry in sequence {} has no label\n Seen entries: {}\n Error: {}".format(label, l, e))
def _validateTask(self, task, label:str):
# See if every module and service has been inserted into the process
try:
l = set()
visitor = NodeNameVisitor(l)
task.visit(visitor)
except:
raise RuntimeError("An entry in task " + label + ' has not been attached to the process')
def _validateConditionalTask(self, task, label:str):
# See if every module and service has been inserted into the process
try:
l = set()
visitor = NodeNameVisitor(l)
task.visit(visitor)
except:
raise RuntimeError("An entry in task " + label + ' has not been attached to the process')
def _itemsInDependencyOrder(self, processDictionaryOfItems):
# The items can be Sequences or Tasks and the input
# argument should either be the dictionary of sequences
# or the dictionary of tasks from the process.
returnValue=DictTypes.SortedKeysDict()
# For each item, see what other items it depends upon
# For our purpose here, an item depends on the items it contains.
dependencies = {}
for label,item in processDictionaryOfItems.items():
containedItems = []
if isinstance(item, Task):
v = TaskVisitor(containedItems)
elif isinstance(item, ConditionalTask):
v = ConditionalTaskVisitor(containedItems)
else:
v = SequenceVisitor(containedItems)
try:
item.visit(v)
except RuntimeError:
if isinstance(item, Task):