forked from cms-tsg-fog/RateMon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDatabaseRatePredictor.py
executable file
·1908 lines (1674 loc) · 89.4 KB
/
DatabaseRatePredictor.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
from DatabaseParser import *
from GetListOfRuns import *
import sys
import os
from numpy import *
import pickle
import getopt
from StreamMonitor import StreamMonitor
from itertools import groupby
from operator import itemgetter
from collections import deque
from ROOT import gROOT, TCanvas, TF1, TGraph, TGraphErrors, TPaveStats, gPad, gStyle
from ROOT import TFile, TPaveText, TBrowser
from ROOT import gBenchmark
import array
import math
from ReadConfig import RateMonConfig
from TablePrint import *
from selectionParser import selectionParser
def usage():
print sys.argv[0]+" [options] <list of runs>"
print "This script is used to generate fits and do secondary shifter validation"
print "For more information, see https://twiki.cern.ch/twiki/bin/view/CMS/RateMonitoringScriptWithReferenceComparison"
print "<list of runs> this is a list of the form: a b c-d e f-g, specifying individual runs and/or run ranges"
print " be careful with using ranges (c-d), it is highly recommended to use a JSON in this case"
print "options: "
print "--makeFits run in fit making mode"
print "--secondary run in secondary shifter mode"
print "--fitFile=<path> path to the fit file"
print "--json=<path> path to the JSON file"
print "--TriggerList=<path> path to the trigger list (without versions!)"
print "--AllTriggers Run for all triggers instead of specifying a trigger list"
print "--maxdt=<max deadtime> Mask LS above max deadtime threshold"
print "--All Mask LS with any red LS on WBM LS page (not inc castor zdc etc)"
print "--Mu Mask LS with Mu (RPC, DT+, DT-, DT0, CSC+ and CSC-) off"
print "--HCal Mask LS with HCal barrel off"
print "--Tracker Mask LS with Tracker barrel off"
print "--ECal Mask LS with ECal barrel off"
print "--EndCap Mask LS with EndCap sys off, used in combination with other subsys"
print "--Beam Mask LS with Beam off"
print "--UseVersionNumbers Don't ignore path version numbers"
print "--LumiPerBunch Divide the instantaneous luminosity by the number of colliding bunches"
print "--linear Force linear fits"
print "--inst Make fits using instantaneous luminosity instead of delivered"
print "--write Writes fit info into csv, for ranking nonlinear triggers"
class Modes:
none,fits,secondary = range(3)
def pickYear():
global thisyear
thisyear="2015"
print "Year set to ",thisyear
def main():
gROOT.SetBatch(True)
try:
##set year to 2012
pickYear()
try:
opt, args = getopt.getopt(sys.argv[1:],"",["makeFits","secondary","fitFile=","json=","TriggerList=","maxdt=","All","Mu","HCal","Tracker","ECal","EndCap","Beam","UseVersionNumbers","LumiPerBunch","linear","inst","write","AllTriggers","UsePSCol="])
except getopt.GetoptError, err:
print str(err)
usage()
sys.exit(2)
##### RUN LIST ########
run_list=[]
if len(args)<1:
inputrunlist=[]
print "No runs specified"
runinput=raw_input("Enter run range in form <run1> <run2> <run3> or <run1>-<run2>:")
inputrunlist.append(runinput)
if runinput.find(' ')!=-1:
args=runinput.split(' ')
else:
args.append(runinput)
for r in args:
if r.find('-')!=-1: # r is a run range
rrange = r.split('-')
if len(rrange)!=2:
print "Invalid run range %s" % (r,)
sys.exit(0)
try:
for rr in range(int(rrange[0]),int(rrange[1])+1):
run_list.append(rr)
except:
print "Invalid run range %s" % (r,)
sys.exit(0)
else: # r is not a run range
try:
run_list.append(int(r))
except:
print "Invalid run %s" % (r,)
##### READ CMD LINE ARGS #########
mode = Modes.none
fitFile = ""
jsonfile = ""
trig_list = []
max_dt=-1.0
subsys=-1.0
NoVersion=True
useLumiPerBunch=False
linear=False
do_inst=False
wp_bool=False
all_triggers=False
DoL1=True
UsePSCol=-1
SubSystemOff={'All':False,'Mu':False,'HCal':False,'ECal':False,'Tracker':False,'EndCap':False,'Beam':False}
for o,a in opt:
if o == "--makeFits":
mode = Modes.fits
elif o == "--secondary":
mode = Modes.secondary
elif o == "--fitFile":
fitFile = str(a)
elif o == "--json":
jsonfile = a
elif o=="--maxdt":
max_dt = float(a)
elif o=="--All":
subsys=1
SubSystemOff["All"]=True
elif o=="--Mu":
subsys=1
SubSystemOff["Mu"]=True
elif o=="--HCal":
SubSystemOff["HCal"]=True
subsys=1
elif o=="--Tracker":
SubSystemOff["Tracker"]=True
subsys=1
elif o=="--ECal":
SubSystemOff["ECal"]=True
subsys=1
elif o=="--EndCap":
SubSystemOff["EndCap"]=True
subsys=1
elif o=="--Beam":
SubSystemOff["Beam"]=True
subsys=1
elif o=="--UseVersionNumbers":
NoVersion=False
elif o=="--LumiPerBunch":
useLumiPerBunch=True
elif o=="--linear":
linear=True
elif o=="--inst":
do_inst=True
elif o=="--write":
wp_bool=True
elif o=="--AllTriggers":
all_triggers=True
elif o=="--UsePSCol":
UsePSCol=int(a)
elif o == "--TriggerList":
try:
f = open(a)
for entry in f:
if entry.startswith('#'):
continue
if entry.find(':')!=-1:
entry = entry[:entry.find(':')] ## We can point this to the existing monitor list, just remove everything after ':'!
if entry.find('#')!=-1:
entry = entry[:entry.find('#')] ## We can point this to the existing monitor list, just remove everything after ':'!
trig_list.append( entry.rstrip('\n'))
except:
print "\nInvalid Trigger List\n"
sys.exit(0)
else:
print "\nInvalid Option %s\n" % (str(o),)
usage()
sys.exit(2)
print "\n\n"
###### MODES #########
if mode == Modes.none: ## no mode specified
print "\nNo operation mode specified!\n"
modeinput=raw_input("Enter mode, --makeFits or --secondary:")
print "modeinput=",modeinput
if not (modeinput=="--makeFits" or modeinput=="--secondary"):
print "not either"
usage()
sys.exit(0)
elif modeinput == "--makeFits":
mode=Modes.fits
elif modeinput == "--secondary":
mode=Modes.secondary
else:
print "FATAL ERROR: No Mode specified"
sys.exit(0)
if mode == Modes.fits:
print "Running in Fit Making mode\n\n"
elif mode == Modes.secondary:
print "Running in Secondary Shifter mode\n\n"
else: ## should never get here, but exit if we do
print "FATAL ERROR: No Mode specified"
sys.exit(0)
if fitFile=="" and not mode==Modes.fits:
print "\nPlease specify fit file. These are available:\n"
path="Fits/%s/" % (thisyear) # insert the path to the directory of interest
dirList=os.listdir(path)
for fname in dirList:
print fname
fitFile = path+raw_input("Enter fit file in format Fit_HLT_10LS_Run176023to180252.pkl: ")
elif fitFile=="":
NoVstr=""
if NoVersion:
NoVstr="NoV_"
if not do_inst:
fitFile="Fits/%s/Fit_HLT_%s10LS_Run%sto%s.pkl" % (thisyear,NoVstr,min(run_list),max(run_list))
else:
fitFile="Fits/%s/Fit_inst_HLT_%s10LS_Run%sto%s.pkl" % (thisyear,NoVstr,min(run_list),max(run_list))
if "NoV" in fitFile:
NoVersion=True
###### TRIGGER LIST #######
if trig_list == [] and not all_triggers:
print "\nPlease specify list of triggers\n"
print "Available lists are:"
dirList=os.listdir(".")
for fname in dirList:
entry=fname
if entry.find('.')!=-1:
extension = entry[entry.find('.'):] ## We can point this to the existing monitor list, just remove everything after ':'!
if extension==".list":
print fname
trig_input=raw_input("\nEnter triggers in format HLT_IsoMu30_eta2p1 or a .list file, or enter AllTriggers to run over all triggers in the menu: ")
if trig_input.find('AllTriggers') != -1:
all_triggers = True
elif trig_input.find('.') != -1:
extension = trig_input[trig_input.find('.'):]
if extension==".list":
try:
fl=open(trig_input)
except:
print "Cannot open file"
usage()
sys.exit(0)
for line in fl:
if line.startswith('#'):
continue
if len(line)<1:
continue
if len(line)>=2:
arg=line.rstrip('\n').rstrip(' ').lstrip(' ')
trig_list.append(arg)
else:
arg=''
else:
trig_list.append(trig_input)
if jsonfile=="":
JSON=[]
else:
print "Using JSON: %s" % (jsonfile,)
JSON = GetJSON(jsonfile) ##Returns array JSON[runs][ls_list]
###### TO CREATE FITS #########
if mode == Modes.fits:
trig_name = "HLT"
num_ls = 10
physics_active_psi = True ##Requires that physics and active be on, and that the prescale column is not 0
debug_print = False
no_versions=False
min_rate = 0.0
print_table = False
data_clean = True ##Gets rid of anomalous rate points, reqires physics_active_psi (PAP) and deadtime < 20%
##plot_properties = [varX, varY, do_fit, save_root, save_png, fit_file]
if not do_inst:
plot_properties = [["delivered", "rate", True, True, False, fitFile]]
# plot_properties = [["delivered", "rawrate", True, True, False, fitFile]]
else:
plot_properties = [["inst", "rate", True, True, False, fitFile]]
masked_triggers = ["AlCa_", "DST_", "HLT_L1", "HLT_Zero", "HLT_BeamGas", "HLT_Activity", "L1_BeamGas", "L1_ZeroBias"]
save_fits = True
if max_dt==-1.0:
max_dt=0.08 ## no deadtime cutuse 2.0
force_new=True
print_info=True
if subsys==-1.0:
SubSystemOff={'All':False,'Mu':False,'HCal':False,'ECal':False,'Tracker':False,'EndCap':False,'Beam':True}
###### TO SEE RATE VS PREDICTION ########
if mode == Modes.secondary:
trig_name = "HLT"
num_ls = 1
physics_active_psi = True
debug_print = False
no_versions=False
min_rate = 0.0
print_table = False
data_clean = True
##plot_properties = [varX, varY, do_fit, save_root, save_png, fit_file]
plot_properties = [["ls", "rawrate", False, True, False,fitFile]]
## rate is calculated as: (measured rate, deadtime corrected) * prescale [prediction not dt corrected]
## rawrate is calculated as: measured rate [prediction is dt corrected]
masked_triggers = ["AlCa_", "DST_", "HLT_L1", "HLT_Zero", "HLT_BeamGas", "HLT_Activity", "L1_BeamGas", "L1_ZeroBias"]
save_fits = False
if max_dt==-1.0:
max_dt=2.0 ## no deadtime cut=2.0
force_new=True
print_info=True
if subsys==-1.0:
SubSystemOff={'All':True,'Mu':False,'HCal':False,'ECal':False,'Tracker':False,'EndCap':False,'Beam':True}
for k in SubSystemOff.iterkeys():
print k,"=",SubSystemOff[k]," ",
print " "
L1SeedChangeFit=True
######## END PARAMETERS - CALL FUNCTIONS ##########
#[Rates,LumiPageInfo, L1_trig_list,nps]= GetDBRates(run_list, trig_name, trig_list, num_ls, max_dt, physics_active_psi, JSON, debug_print, force_new, SubSystemOff,NoVersion,useLumiPerBunch,all_triggers, DoL1,UsePSCol,L1SeedChangeFit)
[Rates, LumiPageInfo, L1_trig_list, nps, nCollidingBunches]= GetDBRates(run_list, trig_name, trig_list, num_ls, max_dt, physics_active_psi, JSON, debug_print, force_new, SubSystemOff, NoVersion, useLumiPerBunch, all_triggers, DoL1,UsePSCol,L1SeedChangeFit, save_fits)
if DoL1:
trig_list=L1_trig_list
MakePlots(Rates, LumiPageInfo, run_list, trig_name, trig_list, num_ls, min_rate, max_dt, print_table, data_clean, plot_properties, masked_triggers, save_fits, debug_print,SubSystemOff, print_info,NoVersion, nCollidingBunches, linear, do_inst,wp_bool,all_triggers,L1SeedChangeFit,nps)
except KeyboardInterrupt:
print "Wait... come back..."
#def GetDBRates(run_list,trig_name,trig_list, num_ls, max_dt, physics_active_psi,JSON,debug_print, force_new, SubSystemOff,NoVersion,all_triggers, DoL1,UsePSCol,L1SeedChangeFit):
def GetDBRates(run_list, trig_name, trig_list, num_ls, max_dt, physics_active_psi, JSON, debug_print, force_new, SubSystemOff, NoVersion, useLumiPerBunch, all_triggers, DoL1,UsePSCol, L1SeedChangeFit, save_fits):
nps = 0
Rates = {}
LumiPageInfo={}
## Save in RefRuns with name dependent on trig_name, num_ls, JSON, and physics_active_psi
if JSON:
#print "Using JSON file"
if physics_active_psi:
RefRunNameTemplate = "RefRuns/%s/Rates_%s_%sLS_JPAP.pkl"
else:
RefRunNameTemplate = "RefRuns/%s/Rates_%s_%sLS_JSON.pkl"
else:
print "Using Physics and Active ==1"
if physics_active_psi:
RefRunNameTemplate = "RefRuns/%s/Rates_%s_%sLS_PAP.pkl"
else:
RefRunNameTemplate = "RefRuns/%s/Rates_%s_%sLS.pkl"
RefRunFile = RefRunNameTemplate % (thisyear,trig_name,num_ls)
RefRunFileHLT = RefRunNameTemplate % (thisyear,"HLT",num_ls)
print "RefRun: ",RefRunFile
print "RefRunFileHLT: ",RefRunFileHLT
if not force_new:
try: ##Open an existing RefRun file with the same parameters and trigger name
pkl_file = open(RefRunFile, 'rb')
Rates = pickle.load(pkl_file)
pkl_file.close()
os.remove(RefRunFile)
print "using",RefRunFile
except:
try: ##Open an existing RefRun file with the same parameters and HLT for trigger name
pkl_file = open(RefRunFileHLT)
HLTRates = pickle.load(pkl_file)
for key in HLTRates:
if trig_name in str(key):
Rates[key] = HLTRates[key]
#print str(RefRunFile)+" does not exist. Creating ..."
except:
print str(RefRunFile)+" does not exist. Creating ..."
## try the lumis file
RefLumiNameTemplate = "RefRuns/%s/Lumis_%s_%sLS.pkl"
RefLumiFile= RefLumiNameTemplate % (thisyear,"HLT",num_ls)
if not force_new:
try:
pkl_lumi_file = open(RefLumiFile, 'rb')
LumiPageInfo = pickle.load(pkl_lumi_file)
pkl_lumi_file.close()
os.remove(RefLumiFile)
print "using",RefLumiFile
except:
print str(RefLumiFile)+" doesn't exist. Make it..."
trig_list_noV=[]
for trigs in trig_list:
trig_list_noV.append(StripVersion(trigs))
if NoVersion:
trig_list=trig_list_noV
for RefRunNum in run_list:
if JSON:
if not RefRunNum in JSON:
continue
try:
ExistsAlready = False
for key in Rates:
if RefRunNum in Rates[key]["run"]:
ExistsAlready = True
break
LumiExistsLAready=False
for v in LumiPageInfo.itervalues():
if RefRunNum == v["Run"]:
LumiExistsAlready=True
break
if ExistsAlready and LumiExistsAlready:
continue
except:
print "Getting info for run "+str(RefRunNum)
if RefRunNum < 1:
continue
ColRunNum,isCol,isGood = GetLatestRunNumber(RefRunNum)
# if not isGood:
# print "Run ",RefRunNum, " is not Collisions"
# continue
# if not isCol:
# print "Run ",RefRunNum, " is not Collisions"
# continue
print "calculating rates and green lumis for run ",RefRunNum
if True: ##Placeholder
if True: #May replace with "try" - for now it's good to know when problems happen
RefParser = DatabaseParser()
RefParser.RunNumber = RefRunNum
RefParser.ParseRunSetup()
global cosmic
if 'cosmic' in RefParser.L1_HLT_Key:
print "COSMICS MODE"
cosmic = True
else:
cosmic = False
RefLumiRangePhysicsActive = RefParser.GetLSRange(1,9999) ##Gets array of all LS with physics and active on
RefLumiArray = RefParser.GetLumiInfo() ##Gets array of all existing LS and their lumi info
RefLumiRange = []
RefMoreLumiArray = RefParser.GetMoreLumiInfo()#dict with keys as bits from lumisections WBM page and values are dicts with key=LS:value=bit
L1HLTseeds=RefParser.GetL1HLTseeds()
HLTL1PS=RefParser.GetL1PSbyseed()
# Get Number of Colliding Bunches
nCollidingBunches = 1
if useLumiPerBunch:
nCollidingBunches = RefParser.GetNuberCollidingBunches()
print "Number of colliding bunches in run", RefParser.RunNumber, ":", nCollidingBunches
if nCollidingBunches <= 0 or nCollidingBunches!=nCollidingBunches:
nCollidingBunches = 1
###Add all triggers to list if all trigger
try:
TriggerRatesCheck = RefParser.GetHLTRates([1])##just grab from 1st LS
except:
print "ERROR: unable to get HLT triggers for this run"
exit(2)
for HLTkey in TriggerRatesCheck:
if NoVersion:
name = StripVersion(HLTkey)
else:
name=HLTkey
if not name in trig_list:
if all_triggers:
trig_list.append(name)
###add L1 triggers to list if Do L1
if DoL1:
for HLTkey in trig_list:
#print name
# if "L1" in HLTkey:
# continue
if not HLTkey.startswith('HLT'):
continue
else:
try:
for L1seed in L1HLTseeds[HLTkey]:
if L1seed not in trig_list:
trig_list.append(L1seed)
except:
print "Failed on trigger "+str(HLTkey)
pass
for iterator in RefLumiArray[0]: ##Makes array of LS with proper PAP and JSON properties
##cheap way of getting PSCol None-->0
if RefLumiArray[0][iterator] not in range(1,9):
RefLumiArray[0][iterator]=0
if not UsePSCol==-1:
if not RefLumiArray[0][iterator]==UsePSCol:
print "skipping LS",iterator
continue
if cosmic or not physics_active_psi or (RefLumiArray[5][iterator] == 1 and RefLumiArray[6][iterator] == 1 and RefMoreLumiArray["b1pres"][iterator]==1 and RefMoreLumiArray["b2pres"][iterator]==1 and RefMoreLumiArray["b1stab"][iterator] and RefMoreLumiArray["b2stab"][iterator]==1):
if not JSON or RefRunNum in JSON:
if not JSON or iterator in JSON[RefRunNum]:
RefLumiRange.append(iterator)
try:
nls = RefLumiRange[0]
LSRange = {}
except:
print "Run "+str(RefRunNum)+" has no good LS"
continue
if num_ls > len(RefLumiRange):
print "Run "+str(RefRunNum)+" is too short: from "+str(nls)+" to "+str(RefLumiRange[-1])+", while num_ls = "+str(num_ls)
continue
while nls < RefLumiRange[-1]-num_ls:
LSRange[nls] = []
counter = 0
for iterator in RefLumiRange:
if iterator >= nls and counter < num_ls:
LSRange[nls].append(iterator)
counter += 1
nls = LSRange[nls][-1]+1
[HLTL1_seedchanges,nps]=checkL1seedChangeALLPScols(trig_list,HLTL1PS) #for L1prescale changes
#print HLTL1_seedchanges
#print "nps=",nps
#print "Run "+str(RefRunNum)+" contains LS from "+str(min(LSRange))+" to "+str(max(LSRange))
for nls in sorted(LSRange.iterkeys()):
TriggerRates = RefParser.GetHLTRates(LSRange[nls])
#L1Rate=RefParser.GetDeadTimeBeamActive(LSRange[nls])
## Clumsy way to append Stream A. Should choose correct method for calculating stream a based on ps column used in data taking.
if ('HLT_Stream_A' in trig_list) or all_triggers:
config = RateMonConfig(os.path.abspath(os.path.dirname(sys.argv[0])))
config.ReadCFG()
stream_mon = StreamMonitor()
core_a_rates = stream_mon.getStreamACoreRatesByLS(RefParser,LSRange[nls],config).values()
avg_core_a_rate = sum(core_a_rates)/len(LSRange[nls])
TriggerRates['HLT_Stream_A'] = [1,1,avg_core_a_rate,avg_core_a_rate]
HLTL1_seedchanges["HLT_Stream_A"] = [[ps_col] for ps_col in range(0,nps)]
# dummylist=[]
# for pscol in range(0,nps):
# doubledummylist=[]
# doubledummylist.append(pscol)
# dummylist.append(doubledummylist)
# HLTL1_seedchanges["HLT_Stream_A"]=dummylist
if DoL1:
L1RatesALL=RefParser.GetL1RatesALL(LSRange[nls])
for L1seed in L1RatesALL.iterkeys():
TriggerRates[L1seed]=L1RatesALL[L1seed]
[inst, live, delivered, dead, pscols] = RefParser.GetAvLumiInfo(LSRange[nls])
deadtimebeamactive=RefParser.GetDeadTimeBeamActive(LSRange[nls])
physics = 1
active = 1
psi = 99
if save_fits and (max(pscols) != min(pscols)):#kick out points which average over two ps columns if doing running in fit making mode
continue
for iterator in LSRange[nls]: ##Gets lowest value of physics, active, and psi in the set of lumisections
if RefLumiArray[5][iterator] == 0:
physics = 0
if RefLumiArray[6][iterator] == 0:
active = 0
if RefLumiArray[0][iterator] < psi:
psi = RefLumiArray[0][iterator]
if inst < 0 or live < 0 or delivered < 0 or nCollidingBunches<0:
print "Run "+str(RefRunNum)+" LS "+str(nls)+" inst lumi = "+str(inst)+" live lumi = "+str(live)+", ncollbunches = "+str(nCollidingBunches)+" delivered = "+str(delivered)+", physics = "+str(physics)+", active = "+str(active)
LumiPageInfo[nls] = LumiRangeGreens(RefMoreLumiArray,LSRange,nls,RefRunNum,deadtimebeamactive)
for key in TriggerRates:
if NoVersion:
name = StripVersion(key)
else:
name=key
if not name in trig_list:
if all_triggers and name.startswith('HLT_Stream_A'):
trig_list.append(name) ##Only triggers in trig_list have HLTL1_seedchanges filled
else:
continue
if not Rates.has_key(name):
Rates[name] = {}
Rates[name]["run"] = []
Rates[name]["ls"] = []
Rates[name]["ps"] = []
Rates[name]["inst_lumi"] = []
Rates[name]["live_lumi"] = []
Rates[name]["delivered_lumi"] = []
Rates[name]["deadtime"] = []
Rates[name]["rawrate"] = []
Rates[name]["rate"] = []
Rates[name]["rawxsec"] = []
Rates[name]["xsec"] = []
Rates[name]["physics"] = []
Rates[name]["active"] = []
Rates[name]["psi"] = []
Rates[name]["L1seedchange"]=[]
[avps, ps, rate, psrate] = TriggerRates[key]
Rates[name]["run"].append(RefRunNum)
Rates[name]["ls"].append(nls)
Rates[name]["ps"].append(ps)
Rates[name]["inst_lumi"].append(inst)
Rates[name]["live_lumi"].append(live)
Rates[name]["delivered_lumi"].append(delivered)
Rates[name]["deadtime"].append(deadtimebeamactive)
Rates[name]["rawrate"].append(rate)
if name in HLTL1_seedchanges:
Rates[name]["L1seedchange"].append(HLTL1_seedchanges[name])
else:
Rates[name]["L1seedchange"].append([])
if live == 0:
Rates[name]["rate"].append(0.0)
Rates[name]["rawxsec"].append(0.0)
Rates[name]["xsec"].append(0.0)
else:
try:
Rates[name]["rate"].append(psrate/(1.0-deadtimebeamactive))
except:
Rates[name]["rate"].append(0.0)
Rates[name]["rawxsec"].append(rate/live)
Rates[name]["xsec"].append(psrate/live)
Rates[name]["physics"].append(physics)
Rates[name]["active"].append(active)
Rates[name]["psi"].append(psi)
RateOutput = open(RefRunFile, 'wb') ##Save new Rates[] to RefRuns
pickle.dump(Rates, RateOutput, 2)
RateOutput.close()
LumiOutput = open(RefLumiFile,'wb')
pickle.dump(LumiPageInfo,LumiOutput, 2)
LumiOutput.close()
return [Rates,LumiPageInfo,trig_list,nps,nCollidingBunches]
def MakePlots(Rates, LumiPageInfo, run_list, trig_name, trig_list, num_ls, min_rate, max_dt, print_table, data_clean, plot_properties, masked_triggers, save_fits, debug_print, SubSystemOff, print_info,NoVersion, nCollidingBunches,linear, do_inst,wp_bool,all_triggers,L1SeedChangeFit,nps):
[min_run, max_run, priot, InputFit, OutputFit, OutputFitPS, failed_paths, first_trigger, varX, varY, do_fit, save_root, save_png, fit_file, RootNameTemplate, RootFile, InputFitPS]=InitMakePlots(run_list, trig_name, num_ls, plot_properties, nps, L1SeedChangeFit)
##modify for No Version and check the trigger list
trig_list=InitTrigList(trig_list, save_fits, NoVersion, InputFit)
for print_trigger in sorted(Rates):
[trig_list, passchecktriglist, meanrawrate] = CheckTrigList(trig_list, print_trigger, all_triggers, masked_triggers, min_rate, Rates, run_list, trig_name, failed_paths)
# print "\n\n\n\n"
# print "print_trigger ",print_trigger," mean raw rate = ",meanrawrate
if not passchecktriglist: #failed_paths is modified by CheckTrigList to include output messages explaining why a trigger failed
print print_trigger," Failed passcheckTrigList"
# continue
[meanrate, meanxsec, meanlumi, sloperate, slopexsec, nlow, nhigh, lowrate, lowxsec, lowlumi, highrate, highxsec, highlumi]=GetMeanRates(Rates, print_trigger, max_dt)
chioffset=1.0 ##chioffset now a fraction; must be 10% better to use expo rather than quad, quad rather than line
width = max([len(trigger_name) for trigger_name in trig_list])
for psi in range(0,nps):
OutputFitPS[psi][print_trigger]=[]##define empty list for each trigger
####START OF L1 SEED LOOP####
#print "LIST L1 seed changes",Rates[print_trigger]["L1seedchange"][0]
if L1SeedChangeFit and do_fit:
dummyPSColslist=Rates[print_trigger]["L1seedchange"][0]
if len(dummyPSColslist)!=1:
dummyPSColslist.append(range(0,nps))
else:
dummyPSColslist=[]
dummyPSColslist.append(range(0,nps))
if not do_fit:
[fitparams, passedGetFit, failed_paths, fitparamsPS]=GetFit(do_fit, InputFit, failed_paths, print_trigger, num_ls,L1SeedChangeFit, InputFitPS,nps)
if not passedGetFit:
print str(print_trigger)+" did not passedGetFit"
continue
else:
fitparams=["unset",0,0,0,0,0,0]
fitparamsPS=["unset",{},{},{},{},{},{}]
for PSColslist in dummyPSColslist:
#print print_trigger, PSColslist
passPSinCol=0
for iterator in range (len(Rates[print_trigger]["run"])):
if Rates[print_trigger]["psi"][iterator] in PSColslist:
passPSinCol=1
#print PSColslist, Rates[print_trigger]["run"][iterator], Rates[print_trigger]["psi"][iterator]
if not passPSinCol:
##for when there are no LS in some PS col (pretty common!)
#print print_trigger, "No data for",PSColslist
continue
AllPlotArrays=DoAllPlotArrays(Rates, print_trigger, run_list, data_clean, meanxsec, num_ls, LumiPageInfo, SubSystemOff, max_dt, print_info, trig_list, do_fit, do_inst, debug_print, fitparams, fitparamsPS, L1SeedChangeFit, PSColslist, first_trigger, nCollidingBunches)
[VX, VXE, x_label, VY, VYE, y_label, VF, VFE] = GetVXVY(plot_properties, fit_file, AllPlotArrays, L1SeedChangeFit)
print "PSColslist = ",PSColslist
if cosmic:
OutputFit[print_trigger] = ['line', meanrawrate, 0., 0., 0.0, 0., meanrawrate, 0., 0., 0., 0.0]
if do_fit:
for PSI in PSColslist:
if not OutputFitPS[PSI][print_trigger]:
OutputFitPS[PSI][print_trigger]=OutputFit[print_trigger]
#print meanrawrate,OutputFit[print_trigger]
####defines gr1 and failure if no graph in OutputFit ####
defgrapass = False
if len(VX) > 0:
[OutputFit,gr1, gr3, failed_paths, defgrapass]=DefineGraphs(print_trigger,OutputFit,do_fit,varX,varY,x_label,y_label,VX,VY,VXE,VYE,VF,VFE,fit_file, failed_paths,PSColslist)
if not defgrapass:
continue
if do_fit:
[f1a,f1b,f1c,f1d,f1f,first_trigger]= Fitter(gr1,VX,VY,sloperate,nlow,Rates,print_trigger, first_trigger, varX, varY,lowrate)
if print_table or save_fits:
###aditional info from f1 params
[f1a_Chi2, f1b_Chi2, f1c_Chi2,f1d_Chi2,f1f_Chi2, f1a_BadMinimum, f1b_BadMinimum, f1c_BadMinimum, meanps, av_rte, passmorefitinfo]=more_fit_info(f1a,f1b,f1c,f1d,f1f,VX,VY,print_trigger,Rates)
if not passmorefitinfo:
OutputFit[print_trigger] = ["fit failed","Zero NDF"]
###output fit params
else:
[OutputFit,first_trigger, failed_paths]=output_fit_info(do_fit,f1a,f1b,f1c,f1d,f1f,varX,varY,VX,VY,linear,print_trigger,first_trigger,Rates,width,chioffset,wp_bool,num_ls,meanrawrate,OutputFit, failed_paths, PSColslist, dummyPSColslist)
#print "OutputFit == ",OutputFit
if do_fit:
for PSI in PSColslist:
if not OutputFitPS[PSI][print_trigger]:
OutputFitPS[PSI][print_trigger]=OutputFit[print_trigger]
PSlist=deque(PSColslist)
PSmin=PSlist.popleft()
if not PSlist:
PSmax=PSmin
else:
PSmax=PSlist.pop()
first_trigger=False
if save_root or save_png:
c1 = TCanvas(str(varX),str(varY))
c1.SetName(str(print_trigger)+"_ps"+str(PSmin)+"_"+str(PSmax)+"_"+str(varY)+"_vs_"+str(varX))
gr1.Draw("APZ")
if not do_fit:
gr3.Draw("P3")
c1.Update()
else:
c1=DrawFittedCurve(f1a, f1b,f1c, f1d, f1f, chioffset,do_fit,c1,VX ,VY,print_trigger,Rates)
if save_root:
myfile = TFile( RootFile, 'UPDATE' )
c1.Write()
myfile.Close()
if save_png:
c1.SaveAs(str(print_trigger)+"_"+str(varY)+"_vs_"+str(varX)+".png")
EndMkrootfile(failed_paths, save_fits, save_root, fit_file, RootFile, OutputFit, OutputFitPS, L1SeedChangeFit)
############# SUPPORTING FUNCTIONS ################
def InitMakePlots(run_list, trig_name, num_ls, plot_properties, nps, L1SeedChangeFit):
min_run = min(run_list)
max_run = max(run_list)
priot.has_been_called=False
InputFit = {}
InputFitPS = {}
OutputFit = {}
failed_paths = []
first_trigger=True
OutputFitPS={}
for ii in range(0,nps):
OutputFitPS[ii]={}
[[varX, varY, do_fit, save_root, save_png, fit_file]] = plot_properties
RootNameTemplate = "%s_%sLS_%s_vs_%s_Run%s-%s.root"
RootFile = RootNameTemplate % (trig_name, num_ls, varX, varY, min_run, max_run)
if not do_fit:
try:
pkl_file = open(fit_file, 'rb')
InputFit = pickle.load(pkl_file)
print "opening fit_file"
pkl_file.close()
except:
print "ERROR: could not open fit file: %s" % (fit_file,)
exit(2)
if L1SeedChangeFit:
try:
PSfitfile=fit_file.replace("HLT_NoV","HLT_NoV_ByPS")
print "opening",PSfitfile
pklfilePS = open(PSfitfile, 'rb')
InputFitPS = pickle.load(pklfilePS)
except:
print "ERROR: could not open fit file: %s" % (PSfitfile,)
exit(2)
if save_root:
try:
os.remove(RootFile)
except:
pass
return [min_run, max_run, priot, InputFit, OutputFit, OutputFitPS, failed_paths, first_trigger, varX, varY, do_fit, save_root, save_png, fit_file, RootNameTemplate, RootFile, InputFitPS]
def InitTrigList(trig_list, save_fits, NoVersion, InputFit):
trig_list_noV=[]
for trigs in trig_list:
trig_list_noV.append(StripVersion(trigs))
if NoVersion:
trig_list=trig_list_noV
## check that all the triggers we ask to plot are in the input fit
if not save_fits:
goodtrig_list = []
FitInputNoV={}
for trig in trig_list:
if NoVersion:
for trigger in InputFit.iterkeys():
FitInputNoV[StripVersion(trigger)]=InputFit[trigger]
InputFit=FitInputNoV
else:
if not InputFit.has_key(trig):
print "WARNING: No Fit Prediction for Trigger %s, SKIPPING" % (trig,)
else:
goodtrig_list.append(trig)
trig_list = goodtrig_list
return trig_list
##Limits Rates[] to runs in run_list
def CheckTrigList(trig_list, print_trigger, all_triggers, masked_triggers, min_rate, Rates, run_list, trig_name, failed_paths):
NewTrigger = {}
passed = 1 ##to replace continue
mean_raw_rate = 0
if not print_trigger in trig_list:
if all_triggers:
trig_list.append(print_trigger)
else:
failed_paths.append([print_trigger,"The monitorlist did not include these paths"])
passed = 0
return [trig_list, passed, mean_raw_rate]
for key in Rates[print_trigger]:
NewTrigger[key] = []
for iterator in range(len(Rates[print_trigger]["run"])):
if Rates[print_trigger]["run"][iterator] in run_list:
for key in Rates[print_trigger]:
NewTrigger[key].append(Rates[print_trigger][key][iterator])
Rates[print_trigger] = NewTrigger
# print "Raw Rates = ",Rates[print_trigger]["rawrate"]
# print "Rates ====== ",Rates
mean_raw_rate = sum(Rates[print_trigger]["rawrate"])/len(Rates[print_trigger]["rawrate"])
if mean_raw_rate < min_rate:
failed_paths.append([print_trigger,"The rate of these paths did not exceed the minimum"])
passed = 0
masked_trig = False
for mask in masked_triggers:
if str(mask) in print_trigger:
masked_trig = True
if masked_trig:
failed_paths.append([print_trigger,"These paths were masked"])
passed = 0
return [trig_list, passed, mean_raw_rate]
def GetMeanRates(Rates, print_trigger, max_dt):
lowlumi = 0
meanlumi_init = median(Rates[print_trigger]["live_lumi"])
meanlumi = 0
highlumi = 0
lowrate = 0
meanrate = 0
highrate = 0
lowxsec = 0
meanxsec = 0
highxsec = 0
nlow = 0
nhigh = 0
for iterator in range(len(Rates[print_trigger]["rate"])):
if Rates[print_trigger]["live_lumi"][iterator] <= meanlumi_init:
if ( Rates[print_trigger]["rawrate"][iterator] > 0.04 and Rates[print_trigger]["physics"][iterator] == 1 and Rates[print_trigger]["active"][iterator] == 1 and Rates[print_trigger]["deadtime"][iterator] < max_dt and Rates[print_trigger]["psi"][iterator] > 0 and Rates[print_trigger]["live_lumi"] > 500):
meanrate+=Rates[print_trigger]["rate"][iterator]
lowrate+=Rates[print_trigger]["rate"][iterator]
meanxsec+=Rates[print_trigger]["xsec"][iterator]
lowxsec+=Rates[print_trigger]["xsec"][iterator]
meanlumi+=Rates[print_trigger]["live_lumi"][iterator]
lowlumi+=Rates[print_trigger]["live_lumi"][iterator]
nlow+=1
if Rates[print_trigger]["live_lumi"][iterator] > meanlumi_init:
if ( Rates[print_trigger]["rawrate"][iterator] > 0.04 and Rates[print_trigger]["physics"][iterator] == 1 and Rates[print_trigger]["active"][iterator] == 1 and Rates[print_trigger]["deadtime"][iterator] < max_dt and Rates[print_trigger]["psi"][iterator] > 0 and Rates[print_trigger]["live_lumi"] > 500):
meanrate+=Rates[print_trigger]["rate"][iterator]
highrate+=Rates[print_trigger]["rate"][iterator]
meanxsec+=Rates[print_trigger]["xsec"][iterator]
highxsec+=Rates[print_trigger]["xsec"][iterator]
meanlumi+=Rates[print_trigger]["live_lumi"][iterator]
highlumi+=Rates[print_trigger]["live_lumi"][iterator]
nhigh+=1
try:
meanrate = meanrate/(nlow+nhigh)
meanxsec = meanxsec/(nlow+nhigh)
meanlumi = meanlumi/(nlow+nhigh)
if (nlow==0):
sloperate = (highrate/nhigh) / (highlumi/nhigh)
slopexsec = (highxsec/nhigh) / (highlumi/nhigh)
elif (nhigh==0):
sloperate = (lowrate/nlow) / (lowlumi/nlow)
slopexsec = (lowxsec/nlow) / (lowlumi/nlow)
else:
sloperate = ( (highrate/nhigh) - (lowrate/nlow) ) / ( (highlumi/nhigh) - (lowlumi/nlow) )
slopexsec = ( (highxsec/nhigh) - (lowxsec/nlow) ) / ( (highlumi/nhigh) - (lowlumi/nlow) )
except:
# print str(print_trigger)+" has no good datapoints - setting initial xsec slope estimate to 0"
meanrate = median(Rates[print_trigger]["rate"])
meanxsec = median(Rates[print_trigger]["xsec"])
meanlumi = median(Rates[print_trigger]["live_lumi"])
sloperate = meanxsec
slopexsec = 0
return [meanrate, meanxsec, meanlumi, sloperate, slopexsec, nlow, nhigh, lowrate, lowxsec, lowlumi, highrate, highxsec, highlumi]
################
def GetFit(do_fit, InputFit, failed_paths, print_trigger, num_ls, L1SeedChangeFit, InputFitPS,nps):
passed=1
FitTypePS={}
X0PS={}
X1PS={}
X2PS={}
X3PS={}
sigmaPS={}
X0errPS={}
try:
FitType = InputFit[print_trigger][0]
except:
failed_paths.append([print_trigger,"These paths did not exist in the monitorlist used to create the fit"])
FitType = "parse failed"
passed=0
fitparams=[FitType, 0, 0, 0, 0, 0, 0]
if FitType == "fit failed":
failure_comment = InputFit[print_trigger][1]
failed_paths.append([print_trigger, failure_comment])
passed=0
fitparams=[FitType, 0, 0, 0, 0, 0, 0]
elif FitType == "parse failed":
failure_comment = "These paths did not exist in the monitorlist used to create the fit"
else:
X0 = InputFit[print_trigger][1]
X1 = InputFit[print_trigger][2]
X2 = InputFit[print_trigger][3]
X3 = InputFit[print_trigger][4]
sigma = InputFit[print_trigger][5]/math.sqrt(num_ls)*3#Display 3 sigma band to show outliers more clearly
X0err= InputFit[print_trigger][7]
fitparams=[FitType, X0, X1, X2, X3, sigma, X0err]
if L1SeedChangeFit:
for psi in range(0,nps):
#print psi, print_trigger, InputFitPS[psi][print_trigger]
try:
FitTypePS[psi] = InputFitPS[psi][print_trigger][0]
except:
failed_paths.append([print_trigger+'_PS_'+str(psi),"These paths did not exist in the monitorlist used to create the fit"])
FitTypePS[psi] = "parse failed"
passed=0
fitparamsPS=[FitTypePS, X0PS, X1PS, X2PS, X3PS, sigmaPS, X0errPS]
if FitTypePS[psi] == "fit failed":
failure_comment = InputFitPS[psi][print_trigger][1]
failed_paths.append([print_trigger+str(psi), failure_comment])
passed=0
fitparamsPS=[FitTypePS, X0PS, X1PS, X2PS, X3PS, sigmaPS, X0errPS]
else:
try: