-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathpico.py
executable file
·1345 lines (1226 loc) · 54.3 KB
/
pico.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 python
# Author: Izaak Neutelings (April 2020)
import os, sys, re, glob, json
from datetime import datetime
from collections import OrderedDict
import ROOT; ROOT.PyConfig.IgnoreCommandLineOptions = True
from ROOT import TFile
import TauFW.PicoProducer.tools.config as GLOB
from TauFW.common.tools.file import ensuredir, ensurefile, ensureinit, getline
from TauFW.common.tools.utils import execute, chunkify, repkey
from TauFW.common.tools.log import Logger, color, bold
from TauFW.PicoProducer.analysis.utils import getmodule, ensuremodule
from TauFW.PicoProducer.batch.utils import getbatch, getsamples, getcfgsamples
from TauFW.PicoProducer.storage.utils import getstorage
from argparse import ArgumentParser
os.chdir(GLOB.basedir)
CONFIG = GLOB.getconfig(verb=0)
LOG = Logger()
###############
# INSTALL #
###############
def main_install(args):
"""Install producer."""
# TODO:
# - guess location (lxplus/PSI/...)
# - set defaults of config file
# - outside CMSSW: create symlinks for standalone
if args.verbosity>=1:
print ">>> main_install", args
verbosity = args.verbosity
###########
# LIST #
###########
def main_list(args):
"""List contents of configuration for those lazy to do 'cat config/config.json'."""
if args.verbosity>=1:
print ">>> main_list", args
verbosity = args.verbosity
cfgname = CONFIG._path
if verbosity>=1:
print '-'*80
print ">>> %-14s = %s"%('cfgname',cfgname)
print ">>> %-14s = %s"%('config',CONFIG)
print '-'*80
print ">>> Configuration %s:"%(cfgname)
for variable, value in CONFIG.iteritems():
variable = "'"+color(variable)+"'"
if isinstance(value,dict):
print ">>> %s:"%(variable)
for key, item in value.iteritems():
if isinstance(item,basestring): item = str(item)
print ">>> %-12r -> %r"%(str(key),str(item))
else:
if isinstance(value,basestring): value = str(value)
print ">>> %-24s = %r"%(variable,value)
###########
# GET #
###########
def main_get(args):
"""Get information of given variable in configuration or samples."""
if args.verbosity>=1:
print ">>> main_get", args
variable = args.variable
eras = args.eras
dtypes = args.dtypes
filters = args.samples
vetoes = args.vetoes
channels = args.channels or [""]
checkdas = args.checkdas
writedir = args.write # write sample file list to text file
tag = args.tag
verbosity = args.verbosity
cfgname = CONFIG._path
if verbosity>=1:
print '-'*80
print ">>> %-14s = %s"%('variable',variable)
print ">>> %-14s = %s"%('cfgname',cfgname)
print ">>> %-14s = %s"%('config',CONFIG)
print '-'*80
# SAMPLES
if variable=='files':
# LOOP over ERAS & CHANNELS
if not eras:
LOG.warning("Please specify an era to get a sample for.")
for era in eras:
for channel in channels:
# VERBOSE
if verbosity>=1:
print ">>> %-12s = %r"%('channel',channel)
# GET SAMPLES
LOG.insist(era in CONFIG.eras,"Era '%s' not found in the configuration file. Available: %s"%(era,CONFIG.eras))
samples = getsamples(era,channel=channel,dtype=dtypes,filter=filters,veto=vetoes,verb=verbosity)
# LOOP over SAMPLES
for sample in samples:
print ">>> %s"%(bold(sample.name))
for path in sample.paths:
print ">>> %s"%(bold(path))
infiles = sample.getfiles(url=False,verb=verbosity+1)
if checkdas:
ndasevents = sample.getnevents(verb=verbosity+1)
print ">>> %-12s = %s"%('ndasevents',ndasevents)
print ">>> %-12s = %r"%('url',sample.url)
print ">>> %-12s = %r"%('postfix',sample.postfix)
print ">>> %-12s = %s"%('nfiles',len(infiles))
print ">>> %-12s = [ "%('infiles')
for file in infiles:
print ">>> %r"%file
print ">>> ]"
if writedir:
flistname = repkey(writedir,ERA=era,GROUP=sample.group,SAMPLE=sample.name,TAG=tag)
print ">>> Write list to %r..."%(flistname)
ensuredir(os.path.dirname(flistname))
with open(flistname,'w+') as flist:
for infile in infiles:
flist.write(infile+'\n')
# CONFIGURATION
else:
if variable in CONFIG:
print ">>> Configuration of %r: %s"%(variable,color(CONFIG[variable]))
else:
print ">>> Did not find %r in the configuration"%(variable)
###########
# SET #
###########
def main_set(args):
"""Set variables in the config file."""
if args.verbosity>=1:
print ">>> main_set", args
variable = args.variable
key = args.key # 'channel' or 'era'
value = args.value
verbosity = args.verbosity
cfgname = CONFIG._path
if key: # redirect 'channel' and 'era' keys to main_link
args.subcommand = variable
return main_link(args)
elif variable in ['channel','era']:
LOG.throw(IOError,"Variable '%s' is reserved for dictionaries!"%(variable))
if verbosity>=1:
print '-'*80
print ">>> Setting variable '%s' to '%s' config"%(variable,value)
if verbosity>=1:
print ">>> %-14s = %s"%('cfgname',cfgname)
print ">>> %-14s = %s"%('config',CONFIG)
print '-'*80
if variable=='all':
if 'default' in value:
GLOB.setdefaultconfig(verb=verb)
else:
LOG.warning("Did not recognize value '%s'. Did you mean 'default'?"%(value))
else:
CONFIG[variable] = value
CONFIG.write()
############
# LINK #
############
def main_link(args):
"""Link channels or eras in the config file."""
if args.verbosity>=1:
print ">>> main_link", args
variable = args.subcommand
varkey = variable+'s'
key = args.key
value = args.value
verbosity = args.verbosity
cfgname = CONFIG._path
if verbosity>=1:
print '-'*80
print ">>> Linking %s '%s' to '%s' in the configuration..."%(variable,key,value)
if verbosity>=1:
print ">>> %-14s = %s"%('cfgname',cfgname)
print ">>> %-14s = %s"%('key',key)
print ">>> %-14s = %s"%('value',value)
print ">>> %-14s = %s"%('config',CONFIG)
print '-'*80
# SANITY CHECKS
if varkey not in CONFIG:
CONFIG[varkey] = { }
LOG.insist(isinstance(CONFIG[varkey],dict),"%s in %s has to be a dictionary"%(varkey,cfgname))
oldval = value
for char in '/\,:;!?\'"':
if char in key:
LOG.throw(IOError,"Given key '%s', but keys cannot contain any of these characters: %s"%(key,char))
if varkey=='channels':
if 'skim' in key.lower(): #or 'test' in key:
parts = value.split(' ')
script = os.path.basename(parts[0]) # separate script from options
ensurefile("python/processors",script)
value = ' '.join([script]+parts[1:])
else:
if 'python/analysis/' in value: # useful for tab completion
value = value.split('python/analysis/')[-1].replace('/','.')
value = value.rstrip('.py')
path = os.path.join('python/analysis/','/'.join(value.split('.')[:-1]))
print path
ensureinit(path,by="pico.py")
ensuremodule(value)
elif varkey=='eras':
if 'samples/' in value: # useful for tab completion
value = ''.join(value.split('samples/')[1:])
path = os.path.join("samples",repkey(value,ERA='*',CHANNEL='*',TAG='*'))
LOG.insist(glob.glob(path),"Did not find any sample lists '%s'"%(path))
ensureinit(os.path.dirname(path),by="pico.py")
if value!=oldval:
print ">>> Converted '%s' to '%s'"%(oldval,value)
CONFIG[varkey][key] = value
CONFIG.write()
##############
# REMOVE #
##############
def main_rm(args):
"""Remove variable from the config file."""
if args.verbosity>=1:
print ">>> main_rm", args
variable = args.variable
key = args.key # 'channel' or 'era'
verbosity = args.verbosity
cfgname = CONFIG._path
if verbosity>=1:
print '-'*80
if key:
print ">>> Removing %s '%s' from the configuration..."%(variable,key)
else:
print ">>> Removing variable '%s' from the configuration..."%(variable)
if verbosity>=1:
print ">>> %-14s = %s"%('variable',variable)
print ">>> %-14s = %s"%('key',key)
print ">>> %-14s = %s"%('cfgname',cfgname)
print ">>> %-14s = %s"%('config',CONFIG)
print '-'*80
if key: # redirect 'channel' and 'era' keys to main_link
variable = variable+'s'
if variable in CONFIG:
CONFIG[variable].pop(key)
CONFIG.write()
else:
print ">>> Variable '%s' not in the configuration. Nothing to remove..."%(variable)
else:
if variable in CONFIG:
CONFIG.pop(variable)
CONFIG.write()
else:
print ">>> Variable '%s' not in the configuration. Nothing to remove..."%(variable)
###########
# RUN #
###########
def main_run(args):
"""Run given module locally."""
if args.verbosity>=1:
print ">>> main_run", args
eras = args.eras
channels = args.channels
tag = args.tag
outdir = args.outdir
dtypes = args.dtypes
filters = args.samples
vetoes = args.vetoes
force = args.force
extraopts = args.extraopts
maxevts = args.maxevts
userfiles = args.infiles
nfiles = args.nfiles
nsamples = args.nsamples
dryrun = args.dryrun
verbosity = args.verbosity
# LOOP over ERAS
if not eras:
print ">>> Please specify a valid era (-y) and a channel (-c)."
for era in eras:
moddict = { } # save time by loading samples and get their files only once
# LOOP over CHANNELS
for channel in channels:
LOG.header("%s, %s"%(era,channel))
# CHANNEL -> MODULE
skim = 'skim' in channel.lower()
LOG.insist(channel in CONFIG.channels,"Channel '%s' not found in the configuration file. Available: %s"%(channel,CONFIG.channels))
module = CONFIG.channels[channel]
if not skim: # channel!='test' and
ensuremodule(module)
outdir = ensuredir(outdir.lstrip('/'))
# PROCESSOR
procopts_ = "" # extra options for processor
if skim:
parts = module.split(' ')
processor = parts[0]
procopts_ = ' '.join(parts[1:])
###elif channel=='test':
### processor = module
else:
processor = "picojob.py"
processor = os.path.join("python/processors",processor)
if not os.path.isfile(processor):
LOG.throw(IOError,"Processor '%s' does not exist in '%s'..."%(processor,procpath))
#processor = os.path.abspath(procpath)
# VERBOSE
if verbosity>=1:
print '-'*80
print ">>> Running %r"%(channel)
print ">>> %-12s = %r"%('channel',channel)
print ">>> %-12s = %r"%('module',module)
print ">>> %-12s = %r"%('processor',processor)
print ">>> %-12s = %s"%('filters',filters)
print ">>> %-12s = %s"%('vetoes',vetoes)
print ">>> %-12s = %r"%('dtypes',dtypes)
print ">>> %-12s = %r"%('outdir',outdir)
# GET SAMPLES
if not userfiles and (filters or vetoes or dtypes):
LOG.insist(era in CONFIG.eras,"Era '%s' not found in the configuration file. Available: %s"%(era,CONFIG.eras))
samples = getsamples(era,channel=channel,tag=tag,dtype=dtypes,filter=filters,veto=vetoes,moddict=moddict,verb=verbosity)
if nsamples>0:
samples = samples[:nsamples]
if not samples:
print ">>> Did not find any samples."
else:
samples = [None]
if verbosity>=2:
print ">>> %-12s = %r"%('samples',samples)
if verbosity>=1:
print '-'*80
# LOOP over SAMPLES
for sample in samples:
if sample:
print ">>> %s"%(bold(sample.name))
if verbosity>=1:
for path in sample.paths:
print ">>> %s"%(bold(path))
# SETTINGS
filetag = tag
dtype = None
extraopts_ = extraopts[:]
if sample:
filetag += '_%s_%s'%(era,sample.name)
if sample.extraopts:
extraopts_.extend(sample.extraopts)
if verbosity>=1:
print ">>> %-12s = %s"%('sample',sample)
print ">>> %-12s = %r"%('filetag',filetag) # postfix
print ">>> %-12s = %s"%('extraopts',extraopts_)
# GET FILES
infiles = [ ]
if userfiles:
infiles = userfiles[:]
elif sample:
nevents = 0
infiles = sample.getfiles(verb=verbosity)
dtype = sample.dtype
if nfiles>0:
infiles = infiles[:nfiles]
if verbosity==1:
print ">>> %-12s = %r"%('dtype',dtype)
print ">>> %-12s = %s"%('nfiles',len(infiles))
print ">>> %-12s = [ "%('infiles')
for file in infiles:
print ">>> %r"%file
print ">>> ]"
if verbosity==1:
print '-'*80
# RUN
runcmd = processor
if procopts_:
runcmd += " %s"%(procopts_)
if skim:
runcmd += " -y %s -o %s"%(era,outdir)
###elif 'test' in channel:
### runcmd += " -o %s"%(outdir)
else: # analysis
runcmd += " -y %s -c %s -M %s -o %s"%(era,channel,module,outdir)
if dtype:
runcmd += " -d %r"%(dtype)
if filetag:
runcmd += " -t %r"%(filetag) # postfix
if maxevts:
runcmd += " -m %s"%(maxevts)
if infiles:
runcmd += " -i %s"%(' '.join(infiles))
if extraopts_:
runcmd += " --opt '%s'"%("' '".join(extraopts_))
#elif nfiles:
# runcmd += " --nfiles %s"%(nfiles)
print ">>> Executing: "+bold(runcmd)
if not dryrun:
#execute(runcmd,dry=dryrun,verb=verbosity+1) # real-time print out does not work well with python script
os.system(runcmd)
print
####################
# PREPARE JOBS #
####################
def preparejobs(args):
"""Help function for (re)submission to iterate over samples per given channel and era
and prepare job config and list."""
if args.verbosity>=1:
print ">>> preparejobs", args
resubmit = args.subcommand=='resubmit'
eras = args.eras
channels = args.channels
tag = args.tag
dtypes = args.dtypes
filters = args.samples
vetoes = args.vetoes
checkdas = args.checkdas
checkqueue = args.checkqueue
extraopts = args.extraopts
prefetch = args.prefetch
nfilesperjob = args.nfilesperjob
split_nfpj = args.split_nfpj
testrun = args.testrun
verbosity = args.verbosity
jobs = [ ]
# LOOP over ERAS
for era in eras:
moddict = { } # save time by loading samples and get their file list only once
# LOOP over CHANNELS
for channel in channels:
LOG.header("%s, %s"%(era,channel))
# CHANNEL -> MODULE
skim = 'skim' in channel.lower()
LOG.insist(channel in CONFIG.channels,"Channel '%s' not found in the configuration file. Available: %s"%(channel,CONFIG.channels))
module = CONFIG.channels[channel]
if not skim: #channel!='test'
ensuremodule(module)
if verbosity>=1:
print '-'*80
print ">>> %-12s = %r"%('channel',channel)
print ">>> %-12s = %r"%('module',module)
print ">>> %-12s = %s"%('filters',filters)
print ">>> %-12s = %s"%('vetoes',vetoes)
print ">>> %-12s = %r"%('dtypes',dtypes)
# PROCESSOR
procopts_ = ""
if skim:
parts = module.split(' ')
processor = parts[0]
procopts_ = ' '.join(parts[1:])
###elif channel=='test':
### processor = module
else:
processor = "picojob.py"
procpath = os.path.join("python/processors",processor)
if not os.path.isfile(procpath):
LOG.throw(IOError,"Processor '%s' does not exist in '%s'..."%(processor,procpath))
processor = os.path.abspath(procpath)
if verbosity>=1:
print ">>> %-12s = %r"%('processor',processor)
print '-'*80
# GET SAMPLES
jobdirformat = CONFIG.jobdir # for job config & log files
outdirformat = CONFIG.nanodir if skim else CONFIG.outdir # for job output
if resubmit:
# TODO: allow user to resubmit given config file
jobcfgs = repkey(os.path.join(jobdirformat,"config/jobconfig_$SAMPLE$TAG_try[0-9]*.json"),
ERA=era,SAMPLE='*',CHANNEL=channel,TAG=tag)
if verbosity>=2:
print ">>> %-12s = %s"%('cwd',os.getcwd())
print ">>> %-12s = %s"%('jobcfgs',jobcfgs)
samples = getcfgsamples(jobcfgs,filter=filters,veto=vetoes,dtype=dtypes,verb=verbosity)
else:
LOG.insist(era in CONFIG.eras,"Era '%s' not found in the configuration file. Available: %s"%(era,CONFIG.eras))
samples = getsamples(era,channel=channel,tag=tag,dtype=dtypes,filter=filters,veto=vetoes,moddict=moddict,verb=verbosity)
if verbosity>=2:
print ">>> Found samples: "+", ".join(repr(s.name) for s in samples)
if testrun:
samples = samples[:2] # only run two samples
# SAMPLE over SAMPLES
found = False
for sample in samples:
if sample.channels and channel not in sample.channels: continue
found = True
print ">>> %s"%(bold(sample.name))
for path in sample.paths:
print ">>> %s"%(bold(path))
# DIRECTORIES
subtry = sample.subtry+1 if resubmit else 1
jobids = sample.jobcfg.get('jobids',[ ])
dtype = sample.dtype
postfix = "_%s%s"%(channel,tag)
jobtag = '_%s_try%d'%(postfix,subtry)
jobname = sample.name+jobtag.rstrip('try1').rstrip('_')
extraopts_ = extraopts[:]
if sample.extraopts:
extraopts_.extend(sample.extraopts)
nfilesperjob_ = sample.nfilesperjob if sample.nfilesperjob>0 else nfilesperjob
if split_nfpj>1:
nfilesperjob_ = min(1,nfilesperjob_/split_nfpj)
outdir = repkey(outdirformat,ERA=era,CHANNEL=channel,TAG=tag,SAMPLE=sample.name,
DAS=sample.paths[0].strip('/'),GROUP=sample.group)
jobdir = ensuredir(repkey(jobdirformat,ERA=era,CHANNEL=channel,TAG=tag,SAMPLE=sample.name,
DAS=sample.paths[0].strip('/'),GROUP=sample.group))
cfgdir = ensuredir(jobdir,"config")
logdir = ensuredir(jobdir,"log")
cfgname = "%s/jobconfig%s.json"%(cfgdir,jobtag)
joblist = '%s/jobarglist%s.txt'%(cfgdir,jobtag)
if verbosity==1:
print ">>> %-12s = %s"%('cfgname',cfgname)
print ">>> %-12s = %s"%('joblist',joblist)
elif verbosity>=2:
print '-'*80
print ">>> Preparing job %ssubmission for '%s'"%("re" if resubmit else "",sample.name)
print ">>> %-12s = %r"%('processor',processor)
print ">>> %-12s = %r"%('dtype',dtype)
print ">>> %-12s = %r"%('jobname',jobname)
print ">>> %-12s = %r"%('jobtag',jobtag)
print ">>> %-12s = %r"%('postfix',postfix)
print ">>> %-12s = %r"%('outdir',outdir)
print ">>> %-12s = %r"%('extraopts',extraopts_)
print ">>> %-12s = %r"%('cfgdir',cfgdir)
print ">>> %-12s = %r"%('logdir',logdir)
print ">>> %-12s = %r"%('cfgname',cfgname)
print ">>> %-12s = %r"%('joblist',joblist)
print ">>> %-12s = %s"%('try',subtry)
print ">>> %-12s = %r"%('jobids',jobids)
# CHECKS
if os.path.isfile(cfgname):
# TODO: check for running jobs
LOG.warning("Job configuration %r already exists and will be overwritten! "%(cfgname)+
"Beware of conflicting job output!")
if not resubmit:
cfgpattern = re.sub(r"(?<=try)\d+(?=.json$)",r"*",cfgname)
cfgnames = [f for f in glob.glob(cfgpattern) if not f.endswith("_try1.json")]
if cfgnames:
LOG.warning("Job configurations for resubmission already exists! This can cause conflicting job output!"+
"If you are sure you want to submit from scratch, please remove these files:\n>>> "+"\n>>> ".join(cfgnames))
storage = getstorage(outdir,verb=verbosity,ensure=True)
# GET FILES
nevents = 0
if resubmit: # resubmission
if checkqueue==0 and not jobs: # check jobs only once
batch = getbatch(CONFIG,verb=verbosity)
jobs = batch.jobs(verb=verbosity-1)
infiles, chunkdict = checkchuncks(sample,outdir=outdir,channel=channel,tag=tag,jobs=jobs,
checkqueue=checkqueue,das=checkdas,verb=verbosity)
nevents = sample.jobcfg['nevents'] # updated in checkchuncks
else: # first-time submission
infiles = sample.getfiles(verb=verbosity-1)
if checkdas:
nevents = sample.getnevents()
chunkdict = { }
if testrun:
infiles = infiles[:2] # only run two files per sample
if verbosity==1:
print ">>> %-12s = %s"%('nfilesperjob',nfilesperjob_)
print ">>> %-12s = %s"%('nfiles',len(infiles))
elif verbosity>=2:
print ">>> %-12s = %s"%('nfilesperjob',nfilesperjob_)
print ">>> %-12s = %s"%('nfiles',len(infiles))
print ">>> %-12s = [ "%('infiles')
for file in infiles:
print ">>> %r"%file
print ">>> ]"
print ">>> %-12s = %s"%('nevents',nevents)
# CHUNKS
infiles.sort() # to have consistent order with resubmission
chunks = [ ] # chunk indices
fchunks = chunkify(infiles,nfilesperjob_) # file chunks
nfiles = len(infiles)
nchunks = len(fchunks)
if verbosity>=1:
print ">>> %-12s = %s"%('nchunks',nchunks)
if verbosity>=2:
print '-'*80
# WRITE JOB LIST with arguments per job
if args.verbosity>=1:
print ">>> Creating job list %s..."%(joblist)
if fchunks:
with open(joblist,'w') as listfile:
ichunk = 0
for fchunk in fchunks:
while ichunk in chunkdict:
ichunk += 1 # allows for different nfilesperjob on resubmission
continue
jobfiles = ' '.join(fchunk) # list of input files
filetag = postfix
if not skim:
filetag += "_%d"%(ichunk)
jobcmd = processor
if procopts_:
jobcmd += " %s"%(procopts_)
if skim:
jobcmd += " -y %s -d '%s' --copydir %s -t %s"%(era,dtype,outdir,filetag)
###elif channel=='test':
### jobcmd += " -o %s -t %s -i %s"%(outdir,filetag)
else:
jobcmd += " -y %s -d %r -c %s -M %s --copydir %s -t %s"%(era,dtype,channel,module,outdir,filetag)
if prefetch:
jobcmd += " -p"
if testrun:
jobcmd += " -m %d"%(testrun) # process a limited amount of events
if extraopts_:
jobcmd += " --opt '%s'"%("' '".join(extraopts_))
jobcmd += " -i %s"%(jobfiles) # add last
if args.verbosity>=1:
print jobcmd
listfile.write(jobcmd+'\n')
chunkdict[ichunk] = fchunk
chunks.append(ichunk)
# JSON CONFIG
jobcfg = OrderedDict([
('time',str(datetime.now())),
('group',sample.group), ('paths',sample.paths), ('name',sample.name), ('nevents',nevents),
('dtype',dtype), ('channel',channel), ('module',module), ('extraopts',extraopts_),
('jobname',jobname), ('jobtag',jobtag), ('tag',tag), ('postfix',postfix),
('try',subtry), ('jobids',jobids),
('outdir',outdir), ('jobdir',jobdir), ('cfgdir',cfgdir), ('logdir',logdir),
('cfgname',cfgname), ('joblist',joblist),
('nfiles',nfiles), ('files',infiles), ('nfilesperjob',nfilesperjob_), #('nchunks',nchunks),
('nchunks',nchunks), ('chunks',chunks), ('chunkdict',chunkdict),
])
# YIELD
yield jobcfg
print
if not found:
print ">>> Did not find any samples."
if verbosity>=1:
print ">>> %-8s = %s"%('filters',filters)
print ">>> %-8s = %s"%('vetoes',vetoes)
##################
# CHECK JOBS #
##################
def checkchuncks(sample,**kwargs):
"""Help function to check jobs status: success, pending, failed or missing.
Return list of files to be resubmitted, and a dictionary between chunk index and input files."""
outdir = kwargs.get('outdir', None)
channel = kwargs.get('channel', None)
tag = kwargs.get('tag', None)
checkqueue = kwargs.get('checkqueue', False)
pendjobs = kwargs.get('jobs', [ ])
checkdas = kwargs.get('das', True)
verbosity = kwargs.get('verb', 0)
oldjobcfg = sample.jobcfg
oldcfgname = oldjobcfg['config']
chunkdict = oldjobcfg['chunkdict'] # filenames
jobids = oldjobcfg['jobids']
joblist = oldjobcfg['joblist']
postfix = oldjobcfg['postfix']
nfilesperjob = oldjobcfg['nfilesperjob']
if outdir==None:
outdir = oldjobcfg['outdir']
storage = getstorage(outdir,ensure=True)
if channel==None:
channel = oldjobcfg['channel']
if tag==None:
tag = oldjobcfg['tag']
noldchunks = len(chunkdict) # = number of jobs
goodchunks = [ ] # good job output
pendchunks = [ ] # pending or running jobs
badchunks = [ ] # corrupted job output
misschunks = [ ] # missing job output
resubfiles = [ ] # files to resubmit (if bad or missing)
# NUMBER OF EVENTS
nprocevents = 0 # total number of processed events
ndasevents = oldjobcfg['nevents'] # total number of available events
if checkdas and oldjobcfg['nevents']==0:
ndasevents = sample.getnevents()
oldjobcfg['nevents'] = ndasevents
if verbosity>=2:
print ">>> %-12s = %s"%('ndasevents',ndasevents)
if verbosity>=3:
print ">>> %-12s = %s"%('chunkdict',chunkdict)
# CHECK PENDING JOBS
if checkqueue<0 or pendjobs:
batch = getbatch(CONFIG,verb=verbosity)
if checkqueue!=1 or not pendjobs:
pendjobs = batch.jobs(jobids,verb=verbosity-1) # get refreshed job list
else:
pendjobs = [j for j in pendjobs if j.jobid in jobids] # get new job list with right job id
###########################################################################
# CHECK SKIMMED OUTPUT: nanoAOD format, one or more output files per job
if 'skim' in channel.lower(): # and nfilesperjob>1:
flagexp = re.compile(r"-i (.+\.root)") #r"-i ((?:(?<! -).)+\.root[, ])"
fpattern = "*%s.root"%(postfix)
chunkexp = re.compile(r".+%s\.root"%(postfix))
if verbosity>=2:
print ">>> %-12s = %r"%('flagexp',flagexp.pattern)
print ">>> %-12s = %r"%('fpattern',fpattern)
print ">>> %-12s = %r"%('chunkexp',chunkexp.pattern)
print ">>> %-12s = %s"%('checkqueue',checkqueue)
print ">>> %-12s = %s"%('pendjobs',pendjobs)
print ">>> %-12s = %s"%('jobids',jobids)
# CHECK PENDING JOBS
pendfiles = [ ]
for job in pendjobs:
if verbosity>=3:
print ">>> Found job %r, status=%r, args=%r"%(job,job.getstatus(),job.args.rstrip())
if job.getstatus() in ['q','r']:
if CONFIG.batch=='HTCondor':
jobarg = str(job.args)
matches = flagexp.findall(jobarg)
else:
jobarg = getline(joblist,job.taskid-1)
matches = flagexp.findall(jobarg)
if verbosity>=3:
print ">>> matches = ",matches
if not matches:
continue
infiles = [ ]
for file in matches[0].split():
if not file.endswith('.root'):
break
infiles.append(file)
LOG.insist(infiles,"Did not find any root files in %r, matches=%r"%(jobarg,matches))
ichunk = -1
for i in chunkdict:
if all(f in chunkdict[i] for f in infiles):
ichunk = i
break
LOG.insist(ichunk>=0,
"Did not find to which the input files of jobids %s belong! "%(jobids)+
"\nichunk=%s,\ninfiles=%s,\nchunkdict=%s"%(ichunk,infiles,chunkdict))
LOG.insist(len(chunkdict[i])==len(infiles),
"Mismatch between input files of jobids %s and chunkdict! "%(jobids)+
"\nichunk=%s,\ninfiles=%s,\nchunkdict[%s]=%s"%(ichunk,infiles,ichunk,chunkdict[ichunk]))
pendchunks.append(ichunk)
# CHECK OUTPUT FILES
badfiles = [ ]
goodfiles = [ ]
fnames = storage.getfiles(filter=fpattern,verb=verbosity-1)
if verbosity>=2:
print ">>> %-12s = %s"%('pendchunks',pendchunks)
print ">>> %-12s = %s"%('fnames',fnames)
for fname in fnames:
if verbosity>=2:
print ">>> Checking job output '%s'..."%(fname)
infile = os.path.basename(fname.replace(postfix+".root",".root")) # reconstruct input file
nevents = isvalid(fname) # check for corruption
ichunk = -1
fmatch = None
for i in chunkdict:
if fmatch:
break
for chunkfile in chunkdict[i]:
if infile in chunkfile: # find chunk input file belongs to
ichunk = i
fmatch = chunkfile
break
if ichunk<0:
if verbosity>=2:
print ">>> => No match..."
#LOG.warning("Did not recognize output file '%s'!"%(fname))
continue
if ichunk in pendchunks:
if verbosity>=2:
print ">>> => Pending..."
continue
if nevents<0:
if verbosity>=2:
print ">>> => Bad nevents=%s..."%(nevents)
badfiles.append(fmatch)
else:
if verbosity>=2:
print ">>> => Good, nevents=%s"%(nevents)
nprocevents += nevents
goodfiles.append(fmatch)
# GET FILES for RESUBMISSION + sanity checks
for ichunk in chunkdict.keys():
if ichunk in pendchunks:
continue
chunkfiles = chunkdict[ichunk]
if all(f in goodfiles for f in chunkfiles): # all files succesful
goodchunks.append(ichunk)
continue
bad = False # count each chunk only once: bad, else missing
for fname in chunkfiles:
LOG.insist(fname not in resubfiles,"Found file for chunk '%d' more than once: %s "%(ichunk,fname)+
"Possible overcounting or conflicting job output file format!")
if fname in badfiles:
bad = True
resubfiles.append(fname)
elif fname not in goodfiles:
resubfiles.append(fname)
if bad:
badchunks.append(ichunk)
else:
misschunks.append(ichunk)
chunkdict.pop(ichunk)
###########################################################################
# CHECK ANALYSIS OUTPUT: custom tree format, one output file per job, numbered post-fix
else:
flagexp = re.compile(r"-t \w*_(\d+)")
fpattern = "*%s_[0-9]*.root"%(postfix)
chunkexp = re.compile(r".+%s_(\d+)\.root"%(postfix))
if verbosity>=2:
print ">>> %-12s = %r"%('flagexp',flagexp.pattern)
print ">>> %-12s = %r"%('fpattern',fpattern)
print ">>> %-12s = %r"%('chunkexp',chunkexp.pattern)
print ">>> %-12s = %s"%('checkqueue',checkqueue)
print ">>> %-12s = %s"%('pendjobs',pendjobs)
print ">>> %-12s = %s"%('jobids',jobids)
# CHECK PENDING JOBS
for job in pendjobs:
if verbosity>=3:
print ">>> Found job %r, status=%r, args=%r"%(job,job.getstatus(),job.args.rstrip())
if job.getstatus() in ['q','r']:
if CONFIG.batch=='HTCondor':
jobarg = str(job.args)
matches = flagexp.findall(jobarg)
else:
jobarg = getline(joblist,job.taskid-1)
matches = flagexp.findall(jobarg)
if verbosity>=3:
print ">>> jobarg = %r"%(jobarg)
print ">>> matches = %s"%(matches)
if not matches:
continue
ichunk = int(matches[0])
LOG.insist(ichunk in chunkdict,"Found an impossible chunk %d for job %s.%s! "%(ichunk,job.jobid,job.taskid)+
"Possible overcounting!")
pendchunks.append(ichunk)
# CHECK OUTPUT FILES
fnames = storage.getfiles(filter=fpattern,verb=verbosity-1)
if verbosity>=2:
print ">>> %-12s = %s"%('pendchunks',pendchunks)
print ">>> %-12s = %s"%('fnames',fnames)
for fname in fnames:
if verbosity>=2:
print ">>> Checking job output '%s'..."%(fname)
match = chunkexp.search(fname)
if match:
ichunk = int(match.group(1))
LOG.insist(ichunk in chunkdict,"Found an impossible chunk %d for file %s!"%(ichunk,fname)+
"Possible overcounting or conflicting job output file format!")
if ichunk in pendchunks:
continue
else:
#LOG.warning("Did not recognize output file '%s'!"%(fname))
continue
nevents = isvalid(fname) # check for corruption
if nevents<0:
if verbosity>=2:
print ">>> => Bad, nevents=%s"%(nevents)
badchunks.append(ichunk)
# TODO: remove file from outdir?
else:
if verbosity>=2:
print ">>> => Good, nevents=%s"%(nevents)
nprocevents += nevents
goodchunks.append(ichunk)
# GET FILES for RESUBMISSION + sanity checks
if verbosity>=2:
print ">>> %-12s = %s"%('nprocevents',nprocevents)
for ichunk in chunkdict.keys():
count = goodchunks.count(ichunk)+pendchunks.count(ichunk)+badchunks.count(ichunk)
LOG.insist(count in [0,1],"Found %d times chunk '%d' (good=%d, pending=%d, bad=%d). "%(
count,ichunk,goodchunks.count(ichunk),pendchunks.count(ichunk),badchunks.count(ichunk))+
"Possible overcounting or conflicting job output file format!")
if count==0: # missing chunk
misschunks.append(ichunk)
elif ichunk not in badchunks: # good or pending chunk
continue
fchunk = chunkdict[ichunk]
for fname in fchunk:
LOG.insist(fname not in resubfiles,"Found file for chunk '%d' more than once: %s "%(ichunk,fname)+
"Possible overcounting or conflicting job output file format!")
resubfiles.extend(chunkdict[ichunk])
chunkdict.pop(ichunk) # only save good chunks
###########################################################################
goodchunks.sort()
pendchunks.sort()
badchunks.sort()
misschunks.sort()
# PRINT
def printchunks(jobden,label,text,col,show=False):
if jobden:
ratio = color("%4d/%d"%(len(jobden),noldchunks),col,bold=False)
label = color(label,col,bold=True)
jlist = (": "+', '.join(str(j) for j in jobden)) if show else ""
print ">>> %s %s - %s%s"%(ratio,label,text,jlist)
#else:
# print ">>> %2d/%d %s - %s"%(len(jobden),len(jobs),label,text)
rtext = ""
if ndasevents>0:
ratio = 100.0*nprocevents/ndasevents
rcol = 'green' if ratio>90. else 'yellow' if ratio>80. else 'red'
rtext = ": "+color("%d/%d (%d%%)"%(nprocevents,ndasevents,ratio),rcol,bold=True)
printchunks(goodchunks,'SUCCESS', "Chunks with output in outdir"+rtext,'green')
printchunks(pendchunks,'PEND',"Chunks with pending or running jobs",'white',True)
printchunks(badchunks, 'FAIL', "Chunks with corrupted output in outdir",'red',True)
printchunks(misschunks,'MISS',"Chunks with no output in outdir",'red',True)
return resubfiles, chunkdict
def isvalid(fname):
"""Check if a given file is valid, or corrupt."""
nevts = -1
file = TFile.Open(fname,'READ')
if file and not file.IsZombie():
if file.GetListOfKeys().Contains('tree') and file.GetListOfKeys().Contains('cutflow'):
nevts = file.Get('cutflow').GetBinContent(1)
if nevts<=0:
LOG.warning("Cutflow of file %r has nevts=%s<=0..."%(fname,nevts))
if file.GetListOfKeys().Contains('Events'):
nevts = file.Get('Events').GetEntries()
if nevts<=0:
LOG.warning("'Events' tree of file %r has nevts=%s<=0..."%(fname,nevts))
return nevts
##################
# (RE)SUBMIT #
##################
def main_submit(args):
"""Submit or resubmit jobs to the batch system."""
if args.verbosity>=1:
print ">>> main_submit", args
verbosity = args.verbosity
resubmit = args.subcommand=='resubmit'
force = args.force #or True
dryrun = args.dryrun #or True
testrun = args.testrun #or True
queue = args.queue
batchopts = args.batchopts
batch = getbatch(CONFIG,verb=verbosity+1)
for jobcfg in preparejobs(args):
jobid = None
cfgname = jobcfg['cfgname']