ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/RateMonShiftTool_dev/DatabaseRatePredictor.py
Revision: 1.44
Committed: Wed Jul 18 09:18:20 2012 UTC (12 years, 9 months ago) by grchrist
Content type: text/x-python
Branch: MAIN
CVS Tags: V00-00-34
Changes since 1.43: +2 -2 lines
Log Message:
fixed fitting bug

File Contents

# Content
1 #!/usr/bin/env python
2
3 from DatabaseParser import *
4 from GetListOfRuns import *
5 import sys
6 import os
7 from numpy import *
8 import pickle
9 import getopt
10
11
12 from ROOT import gROOT, TCanvas, TF1, TGraph, TGraphErrors, TPaveStats, gPad, gStyle
13 from ROOT import TFile, TPaveText, TBrowser
14 from ROOT import gBenchmark
15 import array
16 import math
17 from ReadConfig import RateMonConfig
18
19 from selectionParser import selectionParser
20
21 def usage():
22 print sys.argv[0]+" [options] <list of runs>"
23 print "This script is used to generate fits and do secondary shifter validation"
24 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"
25 print " be careful with using ranges (c-d), it is highly recommended to use a JSON in this case"
26 print "options: "
27 print "--makeFits run in fit making mode"
28 print "--secondary run in secondary shifter mode"
29 print "--TMD put in TMD predictions"
30 print "--fitFile=<path> path to the fit file"
31 print "--json=<path> path to the JSON file"
32 print "--TriggerList=<path> path to the trigger list (without versions!)"
33 print "--maxdt=<max deadtime> Mask LS above max deadtime threshold"
34 print "--All Mask LS with any red LS on WBM LS page (not inc castor zdc etc)"
35 print "--Mu Mask LS with Mu off"
36 print "--HCal Mask LS with HCal barrel off"
37 print "--Tracker Mask LS with Tracker barrel off"
38 print "--ECal Mask LS with ECal barrel off"
39 print "--EndCap Mask LS with EndCap sys off, used in combination with other subsys"
40 print "--Beam Mask LS with Beam off"
41 print "--NoVersion Ignore version numbers"
42 print "--linear Force Linear fits"
43 print "--inst Fits using inst not delivered"
44 print "--TMDerr Use errors from TMD predictions"
45 class Modes:
46 none,fits,secondary = range(3)
47
48 def pickYear():
49 global thisyear
50 thisyear="2012"
51 print "Year set to ",thisyear
52
53
54 def main():
55 try:
56
57 ##set year to 2012
58 pickYear()
59 try:
60 opt, args = getopt.getopt(sys.argv[1:],"",["makeFits","secondary","fitFile=","json=","TriggerList=","maxdt=","All","Mu","HCal","Tracker","ECal","EndCap","Beam","NoVersion","linear","inst","TMDerr"])
61
62 except getopt.GetoptError, err:
63 print str(err)
64 usage()
65 sys.exit(2)
66
67 ## if len(args)<1:
68 ## print "\nPlease specify at least 1 run to look at\n"
69 ## usage()
70 ## sys.exit(0)
71
72
73 ##### RUN LIST ########
74 run_list=[]
75
76 if len(args)<1:
77 inputrunlist=[]
78 print "No runs specified"
79 runinput=raw_input("Enter run range in form <run1> <run2> <run3> or <run1>-<run2>:")
80 inputrunlist.append(runinput)
81
82
83 if runinput.find(' ')!=-1:
84 args=runinput.split(' ')
85 else:
86 args.append(runinput)
87
88
89
90 for r in args:
91 if r.find('-')!=-1: # r is a run range
92 rrange = r.split('-')
93 if len(rrange)!=2:
94 print "Invalid run range %s" % (r,)
95 sys.exit(0)
96 try:
97 for rr in range(int(rrange[0]),int(rrange[1])+1):
98 run_list.append(rr)
99 except:
100 print "Invalid run range %s" % (r,)
101 sys.exit(0)
102 else: # r is not a run range
103 try:
104 run_list.append(int(r))
105 except:
106 print "Invalid run %s" % (r,)
107
108
109 ##### READ CMD LINE ARGS #########
110 mode = Modes.none
111 fitFile = ""
112 jsonfile = ""
113 trig_list = []
114 max_dt=-1.0
115 subsys=-1.0
116 NoVersion=False
117 linear=False
118 do_inst=False
119 TMDerr=False
120 SubSystemOff={'All':False,'Mu':False,'HCal':False,'ECal':False,'Tracker':False,'EndCap':False,'Beam':False}
121 for o,a in opt:
122 if o == "--makeFits":
123 mode = Modes.fits
124 elif o == "--secondary":
125 mode = Modes.secondary
126 elif o == "--fitFile":
127 fitFile = str(a)
128 elif o == "--json":
129 jsonfile = a
130 elif o=="--maxdt":
131 max_dt = float(a)
132 elif o=="--All":
133 subsys=1
134 SubSystemOff["All"]=True
135 elif o=="--Mu":
136 subsys=1
137 SubSystemOff["Mu"]=True
138 elif o=="--HCal":
139 SubSystemOff["HCal"]=True
140 subsys=1
141 elif o=="--Tracker":
142 SubSystemOff["Tracker"]=True
143 subsys=1
144 elif o=="--ECal":
145 SubSystemOff["ECal"]=True
146 subsys=1
147 elif o=="--EndCap":
148 SubSystemOff["EndCap"]=True
149 subsys=1
150 elif o=="--Beam":
151 SubSystemOff["Beam"]=True
152 subsys=1
153 elif o=="--NoVersion":
154 NoVersion=True
155 elif o=="--linear":
156 linear=True
157 elif o=="--inst":
158 do_inst=True
159 elif o=="--TMDerr":
160 TMDerr=True
161 elif o == "--TriggerList":
162 try:
163 f = open(a)
164 for entry in f:
165 if entry.startswith('#'):
166 continue
167 if entry.find(':')!=-1:
168 entry = entry[:entry.find(':')] ## We can point this to the existing monitor list, just remove everything after ':'!
169 if entry.find('#')!=-1:
170 entry = entry[:entry.find('#')] ## We can point this to the existing monitor list, just remove everything after ':'!
171 trig_list.append( entry.rstrip('\n'))
172 except:
173 print "\nInvalid Trigger List\n"
174 sys.exit(0)
175 else:
176 print "\nInvalid Option %s\n" % (str(o),)
177 usage()
178 sys.exit(2)
179
180 print "\n\n"
181 ###### MODES #########
182
183 if mode == Modes.none: ## no mode specified
184 print "\nNo operation mode specified!\n"
185 modeinput=raw_input("Enter mode, --makeFits or --secondary:")
186 print "modeinput=",modeinput
187 if not (modeinput=="--makeFits" or modeinput=="--secondary"):
188 print "not either"
189 usage()
190 sys.exit(0)
191 elif modeinput == "--makeFits":
192 mode=Modes.fits
193 elif modeinput =="--secondary":
194 mode=Modes.secondary
195 else:
196 print "FATAL ERROR: No Mode specified"
197 sys.exit(0)
198
199 if mode == Modes.fits:
200 print "Running in Fit Making mode\n\n"
201 elif mode == Modes.secondary:
202 print "Running in Secondary Shifter mode\n\n"
203 else: ## should never get here, but exit if we do
204 print "FATAL ERROR: No Mode specified"
205 sys.exit(0)
206
207 if fitFile=="" and not mode==Modes.fits:
208 print "\nPlease specify fit file. These are available:\n"
209 path="Fits/%s/" % (thisyear) # insert the path to the directory of interest
210 dirList=os.listdir(path)
211 for fname in dirList:
212 print fname
213 fitFile = path+raw_input("Enter fit file in format Fit_HLT_10LS_Run176023to180252.pkl: ")
214
215 ##usage()
216 ##sys.exit(0)
217 elif fitFile=="":
218 NoVstr=""
219 if NoVersion:
220 NoVstr="NoV_"
221 if not do_inst:
222 fitFile="Fits/%s/Fit_HLT_%s10LS_Run%sto%s.pkl" % (thisyear,NoVstr,min(run_list),max(run_list))
223 else:
224 fitFile="Fits/%s/Fit_inst_HLT_%s10LS_Run%sto%s.pkl" % (thisyear,NoVstr,min(run_list),max(run_list))
225
226 if "NoV" in fitFile:
227 NoVersion=True
228
229
230 ###### TRIGGER LIST #######
231
232 if trig_list == []:
233
234 print "\nPlease specify list of triggers\n"
235 print "Available lists are:"
236 dirList=os.listdir(".")
237 for fname in dirList:
238 entry=fname
239 if entry.find('.')!=-1:
240 extension = entry[entry.find('.'):] ## We can point this to the existing monitor list, just remove everything after ':'!
241 if extension==".list":
242 print fname
243 trig_input=raw_input("\nEnter triggers in format HLT_IsoMu30_eta2p1 or a .list file: ")
244
245 if trig_input.find('.')!=-1:
246 extension = trig_input[trig_input.find('.'):]
247 if extension==".list":
248 try:
249 fl=open(trig_input)
250 except:
251 print "Cannot open file"
252 usage()
253 sys.exit(0)
254
255 for line in fl:
256 if line.startswith('#'):
257 continue
258 if len(line)<1:
259 continue
260
261 if len(line)>=2:
262 arg=line.rstrip('\n').rstrip(' ').lstrip(' ')
263 trig_list.append(arg)
264 else:
265 arg=''
266 else:
267 trig_list.append(trig_input)
268
269
270
271
272 ##usage()
273 ##sys.exit(0)
274
275
276
277 ## Can use any combination of LowestRunNumber, HighestRunNumber, and NumberOfRuns -
278 ## just modify "ExistingRuns.sort" and for "run in ExistingRuns" accordingly
279
280 if jsonfile=="":
281 JSON=[]
282 else:
283 print "Using JSON: %s" % (jsonfile,)
284 JSON = GetJSON(jsonfile) ##Returns array JSON[runs][ls_list]
285
286
287
288 ###### TO CREATE FITS #########
289 if mode == Modes.fits:
290 trig_name = "HLT"
291 num_ls = 10
292 physics_active_psi = True ##Requires that physics and active be on, and that the prescale column is not 0
293 #JSON = [] ##To not use a JSON file, just leave the array empty
294 debug_print = False
295 no_versions=False
296 min_rate = 0.0
297 print_table = False
298 data_clean = True ##Gets rid of anomalous rate points, reqires physics_active_psi (PAP) and deadtime < 20%
299 ##plot_properties = [varX, varY, do_fit, save_root, save_png, fit_file]
300 ##plot_properties = [["delivered", "rate", True, True, False, fitFile]]
301 if not do_inst:
302 plot_properties = [["delivered", "rate", True, True, False, fitFile]]
303 else:
304 plot_properties = [["inst", "rate", True, True, False, fitFile]]
305
306 masked_triggers = ["AlCa_", "DST_", "HLT_L1", "HLT_Zero"]
307 save_fits = True
308 if max_dt==-1.0:
309 max_dt=0.08 ## no deadtime cutuse 2.0
310 force_new=True
311 print_info=True
312 if subsys==-1.0:
313 SubSystemOff={'All':False,'Mu':False,'HCal':False,'ECal':False,'Tracker':False,'EndCap':False,'Beam':True}
314
315
316 ###### TO SEE RATE VS PREDICTION ########
317 if mode == Modes.secondary:
318 trig_name = "HLT"
319 num_ls = 1
320 physics_active_psi = True
321 debug_print = False
322 no_versions=False
323 min_rate = 0.0
324 print_table = False
325 data_clean = True
326 ##plot_properties = [varX, varY, do_fit, save_root, save_png, fit_file]
327 ##plot_properties = [["ls", "rawrate", False, True, False, "Fits/2011/Fit_HLT_10LS_Run176023to180252.pkl"]]
328 ##plot_properties = [["ls", "rawrate", False, True, False, "Fits/2011/Fit_HLT_10LS_Run179497to180252.pkl"]]
329 plot_properties = [["ls", "rawrate", False, True, False,fitFile]]
330
331 masked_triggers = ["AlCa_", "DST_", "HLT_L1", "HLT_Zero"]
332 save_fits = False
333 if max_dt==-1.0:
334 max_dt=2.0 ## no deadtime cut=2.0
335 force_new=True
336 print_info=True
337 if subsys==-1.0:
338 SubSystemOff={'All':True,'Mu':False,'HCal':False,'ECal':False,'Tracker':False,'EndCap':False,'Beam':True}
339
340
341
342
343 for k in SubSystemOff.iterkeys():
344 print k,"=",SubSystemOff[k]," ",
345 print " "
346
347 ##print "Trigger list=",trig_list
348 ######## END PARAMETERS - CALL FUNCTIONS ##########
349 [Rates,LumiPageInfo]= GetDBRates(run_list, trig_name, trig_list, num_ls, max_dt, physics_active_psi, JSON, debug_print, force_new, SubSystemOff,NoVersion)
350 ##if not checkLS(Rates,LumiPageInfo,trig_list):
351 ## print "Missing LS!"
352
353
354 #for iterator in range(len(Rates["HLT_Mu17_TkMu8"]["run"])):
355 # print iterator, "run=",Rates["HLT_Mu17_TkMu8"]["run"][iterator],"ls=",Rates["HLT_Mu17_TkMu8"]["ls"][iterator],"rate=",round(Rates["HLT_Mu17_TkMu8"]["run"][iterator],2)
356
357 rootFileName = 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, linear, do_inst, TMDerr)
358 except KeyboardInterrupt:
359 print "Wait... come back..."
360
361 def GetDBRates(run_list,trig_name,trig_list, num_ls, max_dt, physics_active_psi,JSON,debug_print, force_new, SubSystemOff,NoVersion):
362
363 Rates = {}
364 LumiPageInfo={}
365 ## Save in RefRuns with name dependent on trig_name, num_ls, JSON, and physics_active_psi
366 if JSON:
367 #print "Using JSON file"
368 if physics_active_psi:
369 RefRunNameTemplate = "RefRuns/%s/Rates_%s_%sLS_JPAP.pkl"
370 else:
371 RefRunNameTemplate = "RefRuns/%s/Rates_%s_%sLS_JSON.pkl"
372 else:
373 print "Using Physics and Active ==1"
374 if physics_active_psi:
375 RefRunNameTemplate = "RefRuns/%s/Rates_%s_%sLS_PAP.pkl"
376 else:
377 RefRunNameTemplate = "RefRuns/%s/Rates_%s_%sLS.pkl"
378
379
380 RefRunFile = RefRunNameTemplate % (thisyear,trig_name,num_ls)
381 RefRunFileHLT = RefRunNameTemplate % (thisyear,"HLT",num_ls)
382
383 print "RefRun=",RefRunFile
384 print "RefRunFileHLT",RefRunFileHLT
385 if not force_new:
386 try: ##Open an existing RefRun file with the same parameters and trigger name
387 pkl_file = open(RefRunFile, 'rb')
388 Rates = pickle.load(pkl_file)
389 pkl_file.close()
390 os.remove(RefRunFile)
391 print "using",RefRunFile
392
393
394 except:
395 try: ##Open an existing RefRun file with the same parameters and HLT for trigger name
396 pkl_file = open(RefRunFileHLT)
397 HLTRates = pickle.load(pkl_file)
398 for key in HLTRates:
399 if trig_name in str(key):
400 Rates[key] = HLTRates[key]
401 #print str(RefRunFile)+" does not exist. Creating ..."
402 except:
403 print str(RefRunFile)+" does not exist. Creating ..."
404
405 ## try the lumis file
406 RefLumiNameTemplate = "RefRuns/%s/Lumis_%s_%sLS.pkl"
407 RefLumiFile= RefLumiNameTemplate % (thisyear,"HLT",num_ls)
408 if not force_new:
409 try:
410 pkl_lumi_file = open(RefLumiFile, 'rb')
411 LumiPageInfo = pickle.load(pkl_lumi_file)
412 pkl_lumi_file.close()
413 os.remove(RefLumiFile)
414 print "using",RefLumiFile
415 except:
416 print str(RefLumiFile)+" doesn't exist. Make it..."
417
418
419 trig_list_noV=[]
420 for trigs in trig_list:
421 trig_list_noV.append(StripVersion(trigs))
422
423 if NoVersion:
424 trig_list=trig_list_noV
425
426 for RefRunNum in run_list:
427 if JSON:
428 if not RefRunNum in JSON:
429 continue
430 try:
431
432 ExistsAlready = False
433 for key in Rates:
434 if RefRunNum in Rates[key]["run"]:
435 ExistsAlready = True
436 break
437
438
439 LumiExistsLAready=False
440 for v in LumiPageInfo.itervalues():
441 #print RefRunNum, v["Run"]
442
443 if RefRunNum == v["Run"]:
444 LumiExistsAlready=True
445 break
446 if ExistsAlready and LumiExistsAlready:
447 continue
448
449
450 except:
451 print "Getting info for run "+str(RefRunNum)
452
453 if RefRunNum < 1:
454 continue
455 ColRunNum,isCol,isGood = GetLatestRunNumber(RefRunNum)
456 if not isGood:
457 print "Run ",RefRunNum, " is not Collisions"
458
459 continue
460 if not isCol:
461 print "Run ",RefRunNum, " is not Collisions"
462
463 continue
464
465 print "calculating rates and green lumis for run ",RefRunNum
466
467 if True: ##Placeholder
468 if True: #May replace with "try" - for now it's good to know when problems happen
469 RefParser = DatabaseParser()
470 RefParser.RunNumber = RefRunNum
471 RefParser.ParseRunSetup()
472 RefLumiRangePhysicsActive = RefParser.GetLSRange(1,9999) ##Gets array of all LS with physics and active on
473 RefLumiArray = RefParser.GetLumiInfo() ##Gets array of all existing LS and their lumi info
474 RefLumiRange = []
475 RefMoreLumiArray = RefParser.GetMoreLumiInfo()#dict with keys as bits from lumisections WBM page and values are dicts with key=LS:value=bit
476
477
478 ## We have specified the trig list without version numbers, we add them specific to this run
479 ##print "Processing Triggers: "
480 ## trig_list=[]
481 ## for entry in trig_list_noV:
482 ## trig_list.append(RefParser.GetTriggerVersion(entry))
483 ## if trig_list[-1]=="":
484 ## print ">> WARNING: could not find version for trigger %s, SKIPPING" % (entry,)
485 ## else:
486 ## ##print ">> %s " % (trig_list[-1],)
487 ## pass
488 #DeadTimeBeamActive=RefParser.GetDeadTimeBeamActive()
489 #print "deadtime ls run 180250=",DeadTimeBeamActive
490 for iterator in RefLumiArray[0]: ##Makes array of LS with proper PAP and JSON properties
491 ##cheap way of getting PSCol None-->0
492 if RefLumiArray[0][iterator] not in range(1,9):
493 RefLumiArray[0][iterator]=0
494
495
496 if 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):
497 if not JSON or RefRunNum in JSON:
498 if not JSON or iterator in JSON[RefRunNum]:
499 RefLumiRange.append(iterator)
500 #print iterator, RefLumiArray[0][iterator], "active=",RefLumiArray[5][iterator],"physics=",RefLumiArray[6][iterator]
501 #print "hbhea=",RefMoreLumiArray['hbhea'][iterator]
502
503 try:
504 nls = RefLumiRange[0]
505 LSRange = {}
506 except:
507 print "Run "+str(RefRunNum)+" has no good LS"
508 continue
509 if num_ls > len(RefLumiRange):
510 print "Run "+str(RefRunNum)+" is too short: from "+str(nls)+" to "+str(RefLumiRange[-1])+", while num_ls = "+str(num_ls)
511 continue
512 while nls < RefLumiRange[-1]-num_ls:
513 LSRange[nls] = []
514 counter = 0
515 for iterator in RefLumiRange:
516 if iterator >= nls and counter < num_ls:
517 LSRange[nls].append(iterator)
518 counter += 1
519 nls = LSRange[nls][-1]+1
520
521 #print "Run "+str(RefRunNum)+" contains LS from "+str(min(LSRange))+" to "+str(max(LSRange))
522 for nls in sorted(LSRange.iterkeys()):
523
524 TriggerRates = RefParser.GetHLTRates(LSRange[nls])
525 #print nls, RefLumiArray[1][nls], RefLumiArray[2][nls]
526
527 [inst, live, delivered, dead, pscols] = RefParser.GetAvLumiInfo(LSRange[nls])
528 deadtimebeamactive=RefParser.GetDeadTimeBeamActive(LSRange[nls])
529 #print LSRange,deadtimebeamactive
530 physics = 1
531 active = 1
532 psi = 99
533 for iterator in LSRange[nls]: ##Gets lowest value of physics, active, and psi in the set of lumisections
534 if RefLumiArray[5][iterator] == 0:
535 physics = 0
536 if RefLumiArray[6][iterator] == 0:
537 active = 0
538 if RefLumiArray[0][iterator] < psi:
539 psi = RefLumiArray[0][iterator]
540
541 MoreLumiMulti=LumiRangeGreens(RefMoreLumiArray,LSRange,nls,RefRunNum,deadtimebeamactive)
542
543 #print MoreLumiMulti.keys()
544 # print "\n\n\n"
545
546
547
548 if inst < 0 or live < 0 or delivered < 0:
549 print "Run "+str(RefRunNum)+" LS "+str(nls)+" inst lumi = "+str(inst)+" live lumi = "+str(live)+", delivered = "+str(delivered)+", physics = "+str(physics)+", active = "+str(active)
550
551
552
553 LumiPageInfo[nls]=MoreLumiMulti
554 ##print LumiPageInfo[nls]
555 ## try:
556 ## LumiPageInfo[keys].append(values)
557 ## except:
558 ## print "Failed",RefRunNum, nls, keys
559
560 for key in TriggerRates:
561 ##if not key in trig_list:
562 ## continue
563
564 ##if not trig_name in key:
565 ## continue
566 if NoVersion:
567 name = StripVersion(key)
568 else:
569 name=key
570 ##if re.match('.*_v[0-9]+',name): ##Removes _v#
571 ## name = name[:name.rfind('_')]
572 if not name in trig_list:
573 continue
574
575
576 if not Rates.has_key(name):
577 Rates[name] = {}
578 Rates[name]["run"] = []
579 Rates[name]["ls"] = []
580 Rates[name]["ps"] = []
581 Rates[name]["inst_lumi"] = []
582 Rates[name]["live_lumi"] = []
583 Rates[name]["delivered_lumi"] = []
584 Rates[name]["deadtime"] = []
585 Rates[name]["rawrate"] = []
586 Rates[name]["rate"] = []
587 Rates[name]["rawxsec"] = []
588 Rates[name]["xsec"] = []
589 Rates[name]["physics"] = []
590 Rates[name]["active"] = []
591 Rates[name]["psi"] = []
592
593 #for keys, values in MoreLumiMulti.iteritems():
594 # Rates[name][keys] = []
595
596
597 [avps, ps, rate, psrate] = TriggerRates[key]
598 #print "TriggerRates=",TriggerRates[key], "key=",key
599 Rates[name]["run"].append(RefRunNum)
600 Rates[name]["ls"].append(nls)
601 Rates[name]["ps"].append(ps)
602 Rates[name]["inst_lumi"].append(inst)
603 Rates[name]["live_lumi"].append(live)
604 Rates[name]["delivered_lumi"].append(delivered)
605 Rates[name]["deadtime"].append(deadtimebeamactive)
606 Rates[name]["rawrate"].append(rate)
607 if live == 0:
608 Rates[name]["rate"].append(0)
609 Rates[name]["rawxsec"].append(0.0)
610 Rates[name]["xsec"].append(0.0)
611 else:
612 Rates[name]["rate"].append(psrate/(1.0-deadtimebeamactive))
613 Rates[name]["rawxsec"].append(rate/live)
614 Rates[name]["xsec"].append(psrate/live)
615 Rates[name]["physics"].append(physics)
616 Rates[name]["active"].append(active)
617 Rates[name]["psi"].append(psi)
618 #print iterator, "LS=", nls, "dt=",round(deadtimebeamactive,2), "deliv=",delivered, "live=",live
619
620 #for keys, values in MoreLumiMulti.iteritems():
621 # Rates[name][keys].append(values)
622 #print nls, name, keys, values
623 #print " "
624 #except: ##If we replace "if True:" with "try:"
625 #print "Failed to parse run "+str(RefRunNum)
626
627 RateOutput = open(RefRunFile, 'wb') ##Save new Rates[] to RefRuns
628 pickle.dump(Rates, RateOutput, 2)
629 RateOutput.close()
630 LumiOutput = open(RefLumiFile,'wb')
631 pickle.dump(LumiPageInfo,LumiOutput, 2)
632 LumiOutput.close()
633
634
635 return [Rates,LumiPageInfo]
636
637 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, linear,do_inst, TMDerr):
638 min_run = min(run_list)
639 max_run = max(run_list)
640
641 InputFit = {}
642 OutputFit = {}
643 first_trigger=True
644
645
646 [[varX, varY, do_fit, save_root, save_png, fit_file]] = plot_properties
647
648 RootNameTemplate = "%s_%sLS_%s_vs_%s_Run%s-%s.root"
649 RootFile = RootNameTemplate % (trig_name, num_ls, varX, varY, min_run, max_run)
650
651 if not do_fit:
652 try:
653 pkl_file = open(fit_file, 'rb')
654 InputFit = pickle.load(pkl_file)
655
656 except:
657 print "ERROR: could not open fit file: %s" % (fit_file,)
658 if save_root:
659 try:
660 os.remove(RootFile)
661 except:
662 pass
663
664 trig_list_noV=[]
665 for trigs in trig_list:
666 trig_list_noV.append(StripVersion(trigs))
667 ##print "trig list nov=",trig_list_noV
668 if NoVersion:
669 trig_list=trig_list_noV
670
671 ## check that all the triggers we ask to plot are in the input fit
672 if not save_fits:
673 goodtrig_list = []
674 FitInputNoV={}
675 for trig in trig_list:
676
677 if NoVersion:
678 for trigger in InputFit.iterkeys():
679 FitInputNoV[StripVersion(trigger)]=InputFit[trigger]
680 InputFit=FitInputNoV
681
682
683
684 else:
685 if not InputFit.has_key(trig):
686 print "WARNING: No Fit Prediction for Trigger %s, SKIPPING" % (trig,)
687 else:
688 goodtrig_list.append(trig)
689 trig_list = goodtrig_list
690
691
692
693 for print_trigger in sorted(Rates):
694 ##Limits Rates[] to runs in run_list
695 NewTrigger = {}
696
697 if not print_trigger in trig_list:
698 print "not in trig_list:",print_trigger, trig_list
699 continue
700
701 for key in Rates[print_trigger]:
702 NewTrigger[key] = []
703 for iterator in range (len(Rates[print_trigger]["run"])):
704 if Rates[print_trigger]["run"][iterator] in run_list:
705 for key in Rates[print_trigger]:
706 NewTrigger[key].append(Rates[print_trigger][key][iterator])
707 Rates[print_trigger] = NewTrigger
708
709
710 meanrawrate = sum(Rates[print_trigger]["rawrate"])/len(Rates[print_trigger]["rawrate"])
711
712 if not trig_name in print_trigger:
713 print "failed",trig_name, print_trigger
714 continue
715
716 if meanrawrate < min_rate:
717 continue
718 masked_trig = False
719 for mask in masked_triggers:
720 if str(mask) in print_trigger:
721 masked_trig = True
722 if masked_trig:
723 continue
724
725 OutputFit[print_trigger] = {}
726
727 lowlumi = 0
728 meanlumi_init = median(Rates[print_trigger]["live_lumi"])
729 meanlumi = 0
730 highlumi = 0
731 lowxsec = 0
732 meanxsec = 0
733 highxsec = 0
734 nlow = 0
735 nhigh = 0
736
737 for iterator in range(len(Rates[print_trigger]["rate"])):
738 if Rates[print_trigger]["live_lumi"][iterator] <= meanlumi_init:
739 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):
740 meanxsec+=Rates[print_trigger]["xsec"][iterator]
741 lowxsec+=Rates[print_trigger]["xsec"][iterator]
742 meanlumi+=Rates[print_trigger]["live_lumi"][iterator]
743 lowlumi+=Rates[print_trigger]["live_lumi"][iterator]
744 nlow+=1
745 if Rates[print_trigger]["live_lumi"][iterator] > meanlumi_init:
746 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):
747 meanxsec+=Rates[print_trigger]["xsec"][iterator]
748 highxsec+=Rates[print_trigger]["xsec"][iterator]
749 meanlumi+=Rates[print_trigger]["live_lumi"][iterator]
750 highlumi+=Rates[print_trigger]["live_lumi"][iterator]
751 nhigh+=1
752 try:
753 meanxsec = meanxsec/(nlow+nhigh)
754 meanlumi = meanlumi/(nlow+nhigh)
755 slopexsec = ( (highxsec/nhigh) - (lowxsec/nlow) ) / ( (highlumi/nhigh) - (lowlumi/nlow) )
756 except:
757 #print str(print_trigger)+" has no good datapoints - setting initial xsec slope estimate to 0"
758 meanxsec = median(Rates[print_trigger]["xsec"])
759 meanlumi = median(Rates[print_trigger]["live_lumi"])
760 slopexsec = 0
761
762 [run_t,ls_t,ps_t,inst_t,live_t,delivered_t,deadtime_t,rawrate_t,rate_t,rawxsec_t,xsec_t,psi_t,e_run_t,e_ls_t,e_ps_t,e_inst_t,e_live_t,e_delivered_t,e_deadtime_t,e_rawrate_t,e_rate_t,e_rawxsec_t,e_xsec_t,e_psi_t,rawrate_fit_t,rate_fit_t,rawxsec_fit_t,xsec_fit_t,e_rawrate_fit_t,e_rate_fit_t,e_rawxsec_fit_t,e_xsec_fit_t] = MakePlotArrays()
763
764 if not do_fit:
765
766 FitType = InputFit[print_trigger][0]
767 X0 = InputFit[print_trigger][1]
768 X1 = InputFit[print_trigger][2]
769 X2 = InputFit[print_trigger][3]
770 X3 = InputFit[print_trigger][4]
771 Chi2 = InputFit[print_trigger][5]
772 X0err= InputFit[print_trigger][7]
773 ##print print_trigger," X0err=",X0err
774 #print str(print_trigger)+" "+str(FitType)+" "+str(X0)+" "+str(X1)+" "+str(X2)+" "+str(X3)
775 #if (first_trigger):
776 # print '%20s % 10s % 6s % 5s % 5s % 3s % 4s' % ('trigger', 'fit type ', 'cubic', 'quad', ' linear', ' c ', 'Chi2')
777 # first_trigger=False
778 #print '%20s % 10s % 2.2g % 2.2g % 2.2g % 2.2g % 2.2g' % (print_trigger, FitType, X3, X2, X1, X0, Chi2)
779 #print '{}, {}, {:02.2g}, {:02.2g}, {:02.2g}, {:02.2g} '.format(print_trigger, FitType, X0, X1, X2, X3)
780 ## we are 2 lumis off when we start! -gets worse when we skip lumis
781 it_offset=0
782 for iterator in range(len(Rates[print_trigger]["rate"])):
783 if not Rates[print_trigger]["run"][iterator] in run_list:
784 continue
785 prediction = meanxsec + slopexsec * (Rates[print_trigger]["live_lumi"][iterator] - meanlumi)
786 realvalue = Rates[print_trigger]["xsec"][iterator]
787
788
789 if pass_cuts(data_clean, realvalue, prediction, meanxsec, Rates, print_trigger, iterator, num_ls,LumiPageInfo,SubSystemOff,max_dt,print_info, trig_list):
790
791 run_t.append(Rates[print_trigger]["run"][iterator])
792 ls_t.append(Rates[print_trigger]["ls"][iterator])
793 ps_t.append(Rates[print_trigger]["ps"][iterator])
794 inst_t.append(Rates[print_trigger]["inst_lumi"][iterator])
795 live_t.append(Rates[print_trigger]["live_lumi"][iterator])
796 delivered_t.append(Rates[print_trigger]["delivered_lumi"][iterator])
797 deadtime_t.append(Rates[print_trigger]["deadtime"][iterator])
798 rawrate_t.append(Rates[print_trigger]["rawrate"][iterator])
799 rate_t.append(Rates[print_trigger]["rate"][iterator])
800 rawxsec_t.append(Rates[print_trigger]["rawxsec"][iterator])
801 xsec_t.append(Rates[print_trigger]["xsec"][iterator])
802 psi_t.append(Rates[print_trigger]["psi"][iterator])
803
804 e_run_t.append(0.0)
805 e_ls_t.append(0.0)
806 e_ps_t.append(0.0)
807 e_inst_t.append(14.14)
808 e_live_t.append(14.14)
809 e_delivered_t.append(14.14)
810 e_deadtime_t.append(0.01)
811 e_rawrate_t.append(math.sqrt(Rates[print_trigger]["rawrate"][iterator]/(num_ls*23.3)))
812 e_rate_t.append(Rates[print_trigger]["ps"][iterator]*math.sqrt(Rates[print_trigger]["rawrate"][iterator]/(num_ls*23.3)))
813 e_psi_t.append(0.0)
814 if live_t[-1] == 0:
815 e_rawxsec_t.append(0)
816 e_xsec_t.append(0)
817 else:
818 try:
819 e_rawxsec_t.append(math.sqrt(Rates[print_trigger]["rawrate"][iterator]/(num_ls*23.3))/Rates[print_trigger]["live_lumi"][iterator])
820 e_xsec_t.append(Rates[print_trigger]["ps"][iterator]*math.sqrt(Rates[print_trigger]["rawrate"][iterator]/(num_ls*23.3))/Rates[print_trigger]["live_lumi"][iterator])
821 except:
822 e_rawxsec_t.append(0.)
823 e_xsec_t.append(0.)
824 if not do_fit:
825 if not do_inst:
826 if FitType == "expo":
827 rate_prediction = X0 + X1*math.exp(X2+X3*delivered_t[-1])
828 else:
829 rate_prediction = X0 + X1*delivered_t[-1] + X2*delivered_t[-1]*delivered_t[-1] + X3*delivered_t[-1]*delivered_t[-1]*delivered_t[-1]
830 ## if rate_t[-1] < 0.7 * rate_prediction or rate_t[-1] > 1.4 * rate_prediction:
831 ## print str(run_t[-1])+" "+str(ls_t[-1])+" "+str(print_trigger)+" "+str(ps_t[-1])+" "+str(deadtime_t[-1])+" "+str(rate_prediction)+" "+str(rate_t[-1])+" "+str(rawrate_t[-1])
832 else:
833 if FitType == "expo":
834 rate_prediction = X0 + X1*math.exp(X2+X3*inst_t[-1])
835 else:
836 rate_prediction = X0 + X1*inst_t[-1] + X2*inst_t[-1]*inst_t[-1] + X3*inst_t[-1]*inst_t[-1]*inst_t[-1]
837
838 if live_t[-1] == 0:
839 rawrate_fit_t.append(0)
840 rate_fit_t.append(0)
841 rawxsec_fit_t.append(0)
842 xsec_fit_t.append(0)
843 e_rawrate_fit_t.append(0)
844 e_rate_fit_t.append(math.sqrt(Chi2))
845 e_rawxsec_fit_t.append(0)
846 e_xsec_fit_t.append(0)
847 #print "live_t=0", ls_t[-1], rawrate_fit_t[-1]
848 else:
849 if ps_t[-1]>0.0:
850 rawrate_fit_t.append(rate_prediction*(1.0-deadtime_t[-1])/(ps_t[-1]))
851 else:
852 rawrate_fit_t.append(0.0)
853
854 rate_fit_t.append(rate_prediction)
855 e_rate_fit_t.append(math.sqrt(Chi2))
856 rawxsec_fit_t.append(rawrate_fit_t[-1]/live_t[-1])
857 xsec_fit_t.append(rate_prediction*(1.0-deadtime_t[-1])/live_t[-1])
858 try:
859
860 if not TMDerr:
861 e_rawrate_fit_t.append(math.sqrt(Chi2)*rawrate_fit_t[-1]/rate_fit_t[-1])
862 e_rawxsec_fit_t.append(math.sqrt(Chi2)*rawxsec_fit_t[-1]/rate_fit_t[-1])
863 e_xsec_fit_t.append(math.sqrt(Chi2)*xsec_fit_t[-1]/rate_fit_t[-1])
864 ###error from TMD predictions, calculated at 5e33
865 else:
866 e_rawrate_fit_t.append(X0err*inst_t[-1]/5000.)
867 e_rawxsec_fit_t.append(X0err/live_t[-1]*inst_t[-1]/5000.)
868 e_xsec_fit_t.append(X0err/live_t[-1]*inst_t[-1]/5000.)
869
870 except:
871 print print_trigger, "has no fitted rate for LS", Rates[print_trigger]["ls"][iterator]
872 e_rawrate_fit_t.append(math.sqrt(Chi2))
873 e_rawxsec_fit_t.append(math.sqrt(Chi2))
874 e_xsec_fit_t.append(math.sqrt(Chi2))
875 #print "live_t>0", ls_t[-1], rawrate_fit_t[-1]
876
877 ##print iterator, iterator, "ls=",ls_t[-1],"rate=",round(rawrate_t[-1],2), "deadtime=",round(deadtime_t[-1],2),"rawrate_fit=",round(rawrate_fit_t[-1],2),"max it=",len(Rates[print_trigger]["rate"])
878
879 if (print_info and num_ls==1 and (fabs(rawrate_fit_t[-1]-rawrate_t[-1])>2.5*sqrt(sum(Rates[print_trigger]["rawrate"])/len(Rates[print_trigger]["rawrate"])))):
880 pass
881 ###print '%-60s has a bad prediction, run=%-10s LS=%-4s' % (print_trigger, Rates[print_trigger]["run"][iterator], Rates[print_trigger]["ls"][iterator])
882
883 else: ##If the data point does not pass the data_clean filter
884 #print "not passed", iterator, ls_t[-1], rawrate_fit_t[-1]
885 if debug_print:
886 print str(print_trigger)+" has xsec "+str(round(Rates[print_trigger]["xsec"][iterator],6))+" at lumi "+str(round(Rates[print_trigger]["live_lumi"][iterator],2))+" where the expected value is "+str(prediction)
887
888 ## End "for iterator in range(len(Rates[print_trigger]["rate"])):" loop
889
890 AllPlotArrays = [run_t,ls_t,ps_t,inst_t,live_t,delivered_t,deadtime_t,rawrate_t,rate_t,rawxsec_t,xsec_t,psi_t,e_run_t,e_ls_t,e_ps_t,e_inst_t,e_live_t,e_delivered_t,e_deadtime_t,e_rawrate_t,e_rate_t,e_rawxsec_t,e_xsec_t,e_psi_t,rawrate_fit_t,rate_fit_t,rawxsec_fit_t,xsec_fit_t,e_rawrate_fit_t,e_rate_fit_t,e_rawxsec_fit_t,e_xsec_fit_t]
891
892 [VX, VXE, VY, VYE, VF, VFE] = GetVXVY(plot_properties, fit_file, AllPlotArrays)
893
894 if save_root or save_png:
895 c1 = TCanvas(str(varX),str(varY))
896 c1.SetName(str(print_trigger)+"_"+str(varY)+"_vs_"+str(varX))
897
898 try:
899 gr1 = TGraphErrors(len(VX), VX, VY, VXE, VYE)
900 except:
901 print "No lumisections with events for", print_trigger, "probably due to v high deadtime"
902 continue
903 gr1.SetName("Graph_"+str(print_trigger)+"_"+str(varY)+"_vs_"+str(varX))
904 gr1.GetXaxis().SetTitle(varX)
905 gr1.GetYaxis().SetTitle(varY)
906 gr1.SetTitle(str(print_trigger))
907 gr1.SetMinimum(0)
908 gr1.SetMaximum(1.2*max(VY))
909 #gr1.GetXaxis().SetLimits(min(VX)-0.2*max(VX),1.2*max(VX))
910 gr1.GetXaxis().SetLimits(0,1.2*max(VX))
911 gr1.SetMarkerStyle(8)
912
913
914 if fit_file:
915 gr1.SetMarkerSize(0.8)
916 else:
917 gr1.SetMarkerSize(0.5)
918 gr1.SetMarkerColor(2)
919
920 if not do_fit:
921 gr3 = TGraphErrors(len(VX), VX, VF, VXE, VFE)
922 gr3.SetMarkerStyle(8)
923 gr3.SetMarkerSize(0.4)
924 gr3.SetMarkerColor(4)
925 gr3.SetFillColor(4)
926 gr3.SetFillStyle(3003)
927
928 if do_fit:
929 if "rate" in varY and not linear:
930
931 f1a=0
932 f1a = TF1("f1a","pol2",0,8000)
933 f1a.SetLineColor(4)
934 f1a.SetLineWidth(2)
935 #f1a.SetParLimits(0,0,0.2*(sum(VY)/len(VY))+0.8*min(VY))
936 #f1a.SetParLimits(1,0,2.0*max(VY)/(max(VX)*max(VX)))
937 gr1.Fit("f1a","Q","rob=0.90")
938
939
940
941 f1b = 0
942 f1c = 0
943 if True:
944 f1b = TF1("f1b","pol3",0,8000)
945 f1b.SetLineColor(2)
946 f1b.SetLineWidth(2)
947 ## f1b.SetParLimits(0,0,0.2*(sum(VY)/len(VY))+0.8*min(VY))
948 ## f1b.SetParLimits(1,0,f1a.GetParameter(1)+0.0000001)
949 ## f1b.SetParLimits(2,0,f1a.GetParameter(2)+0.0000000001)
950 ## f1b.SetParLimits(3,0,2.0*max(VY)/(max(VX)*max(VX)*max(VX)))
951 gr1.Fit("f1b","Q","rob=0.90")
952 ## #if f1b.GetChisquare()/f1b.GetNDF() < f1a.GetChisquare()/f1a.GetNDF():
953 ## #print "X0 = "+str(f1a.GetParameter(0))+" X1 = "+str(f1a.GetParameter(1))+" X2 = "+str(f1a.GetParameter(2))
954 ## #print str(print_trigger)+" f1a Chi2 = "+str(10*f1a.GetChisquare()*math.sqrt(len(VY))/(math.sqrt(sum(VY))*num_ls*f1a.GetNDF()))+", f1b Chi2 = "+str(10*f1b.GetChisquare()*math.sqrt(len(VY))/(math.sqrt(sum(VY))*num_ls*f1b.GetNDF()))
955 ## #print "X0 = "+str(f1b.GetParameter(0))+" X1 = "+str(f1b.GetParameter(1))+" X2 = "+str(f1b.GetParameter(2))+" X3 = "+str(f1b.GetParameter(3))
956 ## if (first_trigger):
957 ## print '%-60s %4s x0 x1 x2 x3 chi2 ndf chi2/ndf' % ('trigger', 'type')
958
959 ## first_trigger=False
960
961
962
963 f1c = TF1("f1c","[0]+[1]*expo(2)",0,8000)
964 f1c.SetLineColor(3)
965 f1c.SetLineWidth(2)
966 f1c.SetParLimits(0,0,0.2*(sum(VY)/len(VY))+0.8*min(VY))
967 f1c.SetParLimits(1,max(VY)/math.exp(10.0),max(VY)/math.exp(2.0))
968 f1c.SetParLimits(2,0.0,0.0000000001)
969 f1c.SetParLimits(3,2.0/max(VX),10.0/max(VX))
970 ## #print str(max(VY)/math.exp(2.0))+" "+str(10.0/max(VX))
971 gr1.Fit("f1c","Q","rob=0.90")
972 ## #if f1c.GetChisquare()/f1c.GetNDF() < f1a.GetChisquare()/f1a.GetNDF():
973 ## #print str(print_trigger)+" f1a Chi2 = "+str(10*f1a.GetChisquare()*math.sqrt(len(VY))/(math.sqrt(sum(VY))*num_ls*f1a.GetNDF()))+", f1c Chi2 = "+str(10*f1c.GetChisquare()*math.sqrt(len(VY))/(math.sqrt(sum(VY))*num_ls*f1c.GetNDF()))
974 ## #print "X0 = "+str(f1c.GetParameter(0))+" X1 = "+str(f1c.GetParameter(1))+" X2 = "+str(f1c.GetParameter(2))+" X3 = "+str(f1c.GetParameter(3))
975
976
977
978
979
980 ## if (f1c.GetChisquare()/f1c.GetNDF() < f1b.GetChisquare()/f1b.GetNDF() and f1c.GetChisquare()/f1c.GetNDF() < f1a.GetChisquare()/f1a.GetNDF()):
981 ## print '%-60s expo % .2f+/-%.2f % .2e+/-%.1e % .2e+/-%.1e % .2e+/-%.1e %7.2f %4.0f %5.3f ' % (print_trigger, f1c.GetParameter(0), f1c.GetParError(0), f1c.GetParameter(1), f1c.GetParError(1), 0 , 0 , 0 , 0 , f1c.GetChisquare(), f1c.GetNDF(), f1c.GetChisquare()/f1c.GetNDF())
982 ## elif (f1b.GetChisquare()/f1b.GetNDF() < f1a.GetChisquare()/f1a.GetNDF()):
983 ## print '%-60s cube % .2f+/-%.2f % .2e+/-%.1e % .2e+/-%.1e % .2e+/-%.1e %7.2f %4.0f %5.3f ' % (print_trigger, f1b.GetParameter(0), f1b.GetParError(0), f1b.GetParameter(1), f1b.GetParError(1), f1b.GetParameter(2), f1b.GetParError(2), f1b.GetParameter(3), f1b.GetParError(3), f1b.GetChisquare(), f1b.GetNDF(), f1b.GetChisquare()/f1b.GetNDF())
984 ## else:
985
986 print f1a.GetChisquare()/f1a.GetNDF(), f1b.GetChisquare()/f1b.GetNDF(), f1c.GetChisquare()/f1c.GetNDF()
987 if (f1c.GetChisquare()/f1c.GetNDF() < (f1a.GetChisquare()/f1a.GetNDF()-1) and (f1b.GetChisquare()/f1b.GetNDF() < f1a.GetChisquare()/f1a.GetNDF()-1)):
988 print '%-60s | expo | % .2f | +/-%.2f | % .2e | +/-%.1e | % .2e | +/-%.1e | % .2e | +/-%.1e | %7.2f | %4.0f | %5.3f | ' % (print_trigger, f1c.GetParameter(0) , f1c.GetParError(0) , f1c.GetParameter(1) , f1c.GetParError(1) , f1c.GetParameter(2), f1c.GetParError(2) ,f1c.GetParameter(3), f1c.GetParError(3) ,f1c.GetChisquare() , f1c.GetNDF() , f1c.GetChisquare()/f1c.GetNDF())
989 f1c.SetLineColor(1)
990 elif (f1b.GetChisquare()/f1b.GetNDF() < (f1a.GetChisquare()/f1a.GetNDF()-1)):
991 print '%-60s | cube | % .2f | +/-%.2f | % .2e | +/-%.1e | % .2e | +/-%.1e | % .2e | +/-%.1e | %7.2f | %4.0f | %5.3f | ' % (print_trigger, f1b.GetParameter(0) , f1b.GetParError(0) , f1b.GetParameter(1) , f1b.GetParError(1) , f1b.GetParameter(2), f1b.GetParError(2) ,f1b.GetParameter(3), f1b.GetParError(3), f1b.GetChisquare() , f1b.GetNDF() , f1b.GetChisquare()/f1b.GetNDF())
992 f1b.SetLineColor(1)
993 else:
994 print '%-60s | quad | % .2f | +/-%.2f | % .2e | +/-%.1e | % .2e | +/-%.1e | % .2e | +/-%.1e | %7.2f | %4.0f | %5.3f | ' % (print_trigger, f1a.GetParameter(0) , f1a.GetParError(0) , f1a.GetParameter(1) , f1a.GetParError(1) , f1a.GetParameter(2), f1a.GetParError(2), 0 , 0 , f1a.GetChisquare() , f1a.GetNDF() , f1a.GetChisquare()/f1a.GetNDF())
995
996 f1a.SetLineColor(1)
997
998
999
1000
1001 else: ##If this is not a rate plot
1002 f1a = TF1("f1a","pol1",0,8000)
1003 f1a.SetLineColor(4)
1004 f1a.SetLineWidth(2)
1005 if "xsec" in varY:
1006 f1a.SetParLimits(0,0,meanxsec*1.5)
1007 if slopexsec > 0:
1008 f1a.SetParLimits(1,0,max(VY)/max(VX))
1009 else:
1010 f1a.SetParLimits(1,2*slopexsec,-2*slopexsec)
1011 else:
1012 f1a.SetParLimits(0,-1000,1000)
1013 gr1.Fit("f1a","Q","rob=0.80")
1014
1015 if (first_trigger):
1016 print '%-60s %4s x0 x1 x2 x3 chi2 ndf chi2/ndf' % ('trigger', 'type')
1017 first_trigger=False
1018 try:
1019 print '%-60s | line | % .2f | +/-%.2f | % .2e | +/-%.1e | % .2e | +/-%.1e | % .2e | +/-%.1e | %7.2f | %4.0f | %5.3f | ' % (print_trigger, f1a.GetParameter(0), f1a.GetParError(0), f1a.GetParameter(1), f1a.GetParError(1), 0 , 0 , 0 , 0 , f1a.GetChisquare(), f1a.GetNDF(), f1a.GetChisquare()/f1a.GetNDF())
1020 except:
1021 pass
1022 if save_root or save_png:
1023 gr1.Draw("APZ")
1024 ## ##Option to draw stats box
1025 ## p1 = TPaveStats()
1026 ## p1 = gr1.GetListOfFunctions().FindObject("stats")
1027 ## print p1
1028 ## gr1.PaintStats(f1b).Draw("same")
1029 if not do_fit:
1030 gr3.Draw("P3")
1031 if do_fit:
1032 f1a.Draw("same")
1033 try:
1034 f1b.Draw("same")
1035 f1c.Draw("same")
1036 except:
1037 True
1038 c1.Update()
1039 if save_root:
1040 myfile = TFile( RootFile, 'UPDATE' )
1041 c1.Write()
1042 myfile.Close()
1043 if save_png:
1044 c1.SaveAs(str(print_trigger)+"_"+str(varY)+"_vs_"+str(varX)+".png")
1045
1046
1047 if print_table or save_fits:
1048 if not do_fit:
1049 print "Can't have save_fits = True and do_fit = False"
1050 continue
1051 ## if f1c.GetChisquare()/f1c.GetNDF() < 0.95*f1a.GetChisquare()/f1a.GetNDF() and f1c.GetChisquare()/f1c.GetNDF() < 0.95*f1b.GetChisquare()/f1b.GetNDF():
1052 ## OutputFit[print_trigger] = ["expo", f1c.GetParameter(0), f1c.GetParameter(1), f1c.GetParameter(3), 0.0, f1c.GetChisquare()/f1c.GetNDF(), meanrawrate, f1c.GetParError(0), f1c.GetParError(1), f1c.GetParError(2), f1c.GetParError(3)]
1053 ## elif f1b.GetChisquare()/f1b.GetNDF() < 0.95*f1a.GetChisquare()/f1a.GetNDF():
1054 ## OutputFit[print_trigger] = ["poly", f1b.GetParameter(0), f1b.GetParameter(1), f1b.GetParameter(2), f1b.GetParameter(3), f1b.GetChisquare()/f1b.GetNDF(), meanrawrate,f1b.GetParError(0), f1b.GetParError(1), f1b.GetParError(2), f1b.GetParError(3)]
1055 ##else:
1056 try:
1057 if (f1c.GetChisquare()/f1c.GetNDF() < (f1a.GetChisquare()/f1a.GetNDF()+1) and (f1b.GetChisquare()/f1b.GetNDF() < f1a.GetChisquare()/f1a.GetNDF()+1)):
1058 OutputFit[print_trigger] = ["expo", f1c.GetParameter(0) , f1c.GetParameter(1) , f1c.GetParameter(2) , f1c.GetParameter(3) , f1c.GetChisquare()/f1a.GetNDF() , meanrawrate, f1c.GetParError(0) , f1c.GetParError(1) , f1c.GetParError(2) , f1c.GetParError(3)]
1059 elif (f1b.GetChisquare()/f1b.GetNDF() < (f1a.GetChisquare()/f1a.GetNDF()+1)):
1060 OutputFit[print_trigger] = ["poly", f1b.GetParameter(0) , f1b.GetParameter(1) , f1b.GetParameter(2) , f1b.GetParameter(3) , f1b.GetChisquare()/f1b.GetNDF() , meanrawrate, f1b.GetParError(0) , f1b.GetParError(1) , f1b.GetParError(2) , f1b.GetParError(3)]
1061 else:
1062 OutputFit[print_trigger] = ["poly", f1a.GetParameter(0) , f1a.GetParameter(1) , f1a.GetParameter(2) , 0.0 , f1a.GetChisquare()/f1a.GetNDF() , meanrawrate, f1a.GetParError(0) , f1a.GetParError(1) , f1a.GetParError(2) , 0.0]
1063
1064 except ZeroDivisionError:
1065 print "No NDF for",print_trigger,"skipping"
1066
1067 ##print print_trigger, OutputFit[print_trigger]
1068 if save_root:
1069 print "Output root file is "+str(RootFile)
1070
1071 if save_fits:
1072 #FitNameTemplate = "Fits/%/Fit_%s_%sLS_Run%sto%s.pkl" % (thisyear)
1073 #FitFile = FitNameTemplate % (trig_name, num_ls, min_run, max_run)
1074 if os.path.exists(fit_file):
1075 os.remove(fit_file)
1076 FitOutputFile = open(fit_file, 'wb')
1077 pickle.dump(OutputFit, FitOutputFile, 2)
1078 FitOutputFile.close()
1079 print "Output fit file is "+str(fit_file)
1080
1081 if print_table:
1082 print "The expo fit is of the form p0+p1*e^(p2*x), poly is p0+(p1/10^3)*x+(p2/10^6)*x^2+(p3/10^9)*x^3, where x is Deliv. Lumi."
1083 print '%60s%10s%10s%10s%10s%10s%10s%10s' % ("Trig", "fit", "p0", "p1", "p2", "p3", "Chi2", "Av raw")
1084 for print_trigger in OutputFit:
1085 _trigger = (print_trigger[:56] + '...') if len(print_trigger) > 59 else print_trigger
1086 try:
1087 if OutputFit[print_trigger][0] == "poly":
1088 print '%60s%10s%10s%10s%10s%10s%10s' % (_trigger, OutputFit[print_trigger][0], round(OutputFit[print_trigger][1],3), round(OutputFit[print_trigger][2],6)*1000, round(OutputFit[print_trigger][3],9)*1000000, round(OutputFit[print_trigger][4],12)*1000000000, round(OutputFit[print_trigger][5],2), round(OutputFit[print_trigger][6],3))
1089 else:
1090 print '%60s%10s%10s%10s%10s%10s%10s' % (_trigger, OutputFit[print_trigger][0], OutputFit[print_trigger][1], OutputFit[print_trigger][2], OutputFit[print_trigger][3], OutputFit[print_trigger][4], round(OutputFit[print_trigger][5],2), round(OutputFit[print_trigger][6],3))
1091 except:
1092 print str(print_trigger)+" is somehow broken"
1093 return RootFile
1094
1095 ############# SUPPORTING FUNCTIONS ################
1096
1097
1098 def GetJSON(json_file):
1099
1100 input_file = open(json_file)
1101 file_content = input_file.read()
1102 inputRange = selectionParser(file_content)
1103 JSON = inputRange.runsandls()
1104 return JSON
1105 ##JSON is an array: JSON[run_number] = [1st ls, 2nd ls, 3rd ls ... nth ls]
1106
1107 def MakePlotArrays():
1108 run_t = array.array('f')
1109 ls_t = array.array('f')
1110 ps_t = array.array('f')
1111 inst_t = array.array('f')
1112 live_t = array.array('f')
1113 delivered_t = array.array('f')
1114 deadtime_t = array.array('f')
1115 rawrate_t = array.array('f')
1116 rate_t = array.array('f')
1117 rawxsec_t = array.array('f')
1118 xsec_t = array.array('f')
1119 psi_t = array.array('f')
1120
1121 e_run_t = array.array('f')
1122 e_ls_t = array.array('f')
1123 e_ps_t = array.array('f')
1124 e_inst_t = array.array('f')
1125 e_live_t = array.array('f')
1126 e_delivered_t = array.array('f')
1127 e_deadtime_t = array.array('f')
1128 e_rawrate_t = array.array('f')
1129 e_rate_t = array.array('f')
1130 e_rawxsec_t = array.array('f')
1131 e_xsec_t = array.array('f')
1132 e_psi_t = array.array('f')
1133
1134 rawrate_fit_t = array.array('f')
1135 rate_fit_t = array.array('f')
1136 rawxsec_fit_t = array.array('f')
1137 xsec_fit_t = array.array('f')
1138 e_rawrate_fit_t = array.array('f')
1139 e_rate_fit_t = array.array('f')
1140 e_rawxsec_fit_t = array.array('f')
1141 e_xsec_fit_t = array.array('f')
1142
1143 return [run_t,ls_t,ps_t,inst_t,live_t,delivered_t,deadtime_t,rawrate_t,rate_t,rawxsec_t,xsec_t,psi_t,e_run_t,e_ls_t,e_ps_t,e_inst_t,e_live_t,e_delivered_t,e_deadtime_t,e_rawrate_t,e_rate_t,e_rawxsec_t,e_xsec_t,e_psi_t,rawrate_fit_t,rate_fit_t,rawxsec_fit_t,xsec_fit_t,e_rawrate_fit_t,e_rate_fit_t,e_rawxsec_fit_t,e_xsec_fit_t]
1144
1145
1146 def GetVXVY(plot_properties, fit_file, AllPlotArrays):
1147
1148 VF = "0"
1149 VFE = "0"
1150
1151 [run_t,ls_t,ps_t,inst_t,live_t,delivered_t,deadtime_t,rawrate_t,rate_t,rawxsec_t,xsec_t,psi_t,e_run_t,e_ls_t,e_ps_t,e_inst_t,e_live_t,e_delivered_t,e_deadtime_t,e_rawrate_t,e_rate_t,e_rawxsec_t,e_xsec_t,e_psi_t,rawrate_fit_t,rate_fit_t,rawxsec_fit_t,xsec_fit_t,e_rawrate_fit_t,e_rate_fit_t,e_rawxsec_fit_t,e_xsec_fit_t] = AllPlotArrays
1152 for varX, varY, do_fit, save_root, save_png, fit_file in plot_properties:
1153 if varX == "run":
1154 VX = run_t
1155 VXE = run_t_e
1156 elif varX == "ls":
1157 VX = ls_t
1158 VXE = e_ls_t
1159 elif varX == "ps":
1160 VX = ps_t
1161 VXE = e_ps_t
1162 elif varX == "inst":
1163 VX = inst_t
1164 VXE = e_inst_t
1165 elif varX == "live":
1166 VX = live_t
1167 VXE = e_live_t
1168 elif varX == "delivered":
1169 VX = delivered_t
1170 VXE = e_delivered_t
1171 elif varX == "deadtime":
1172 VX = deadtime_t
1173 VXE = e_deadtime_t
1174 elif varX == "rawrate":
1175 VX = rawrate_t
1176 VXE = e_rawrate_t
1177 elif varX == "rate":
1178 VX = rate_t
1179 VXE = e_rate_t
1180 elif varX == "rawxsec":
1181 VX = rawxsec_t
1182 VXE = e_rawxsec_t
1183 elif varX == "xsec":
1184 VX = xsec_t
1185 VXE = e_xsec_t
1186 elif varX == "psi":
1187 VX = psi_t
1188 VXE = e_psi_t
1189 else:
1190 print "No valid variable entered for X"
1191 continue
1192 if varY == "run":
1193 VY = run_t
1194 VYE = run_t_e
1195 elif varY == "ls":
1196 VY = ls_t
1197 VYE = e_ls_t
1198 elif varY == "ps":
1199 VY = ps_t
1200 VYE = e_ps_t
1201 elif varY == "inst":
1202 VY = inst_t
1203 VYE = e_inst_t
1204 elif varY == "live":
1205 VY = live_t
1206 VYE = e_live_t
1207 elif varY == "delivered":
1208 VY = delivered_t
1209 VYE = e_delivered_t
1210 elif varY == "deadtime":
1211 VY = deadtime_t
1212 VYE = e_deadtime_t
1213 elif varY == "rawrate":
1214 VY = rawrate_t
1215 VYE = e_rawrate_t
1216 if fit_file:
1217 VF = rawrate_fit_t
1218 VFE = e_rawrate_fit_t
1219 elif varY == "rate":
1220 VY = rate_t
1221 VYE = e_rate_t
1222 if fit_file:
1223 VF = rate_fit_t
1224 VFE = e_rate_fit_t
1225 elif varY == "rawxsec":
1226 VY = rawxsec_t
1227 VYE = e_rawxsec_t
1228 if fit_file:
1229 VF = rawxsec_fit_t
1230 VFE = e_rawxsec_fit_t
1231 elif varY == "xsec":
1232 VY = xsec_t
1233 VYE = e_xsec_t
1234 if fit_file:
1235 VF = xsec_fit_t
1236 VFE = e_xsec_fit_t
1237 elif varY == "psi":
1238 VY = psi_t
1239 VYE = e_psi_t
1240 else:
1241 print "No valid variable entered for Y"
1242 continue
1243
1244 return [VX, VXE, VY, VYE, VF, VFE]
1245
1246 def pass_cuts(data_clean, realvalue, prediction, meanxsec, Rates, print_trigger, iterator, num_ls,LumiPageInfo,SubSystemOff, max_dt, print_info, trig_list):
1247 it_offset=0
1248 Passed=True
1249 subsystemfailed=[]
1250
1251 if num_ls==1:
1252 ##fit is 2 ls ahead of real rate
1253
1254
1255 LS=Rates[print_trigger]["ls"][iterator]
1256 #print "ls=",LS,
1257 LSRange=LumiPageInfo[LS]["LSRange"]
1258 #print LSRange,
1259 LS2=LSRange[-1]
1260 #LS2=LSRange.pop()
1261 #print "LS2=",LS2
1262
1263 #print LumiPageInfo[LS]
1264 lumidict={}
1265 lumidict=LumiPageInfo[LS]
1266
1267
1268
1269
1270
1271 if print_info:
1272 if (iterator==0 and print_trigger==trig_list[0]):
1273 print '%10s%10s%10s%10s%10s%10s%10s%15s%20s' % ("Status", "Run", "LS", "Physics", "Active", "Deadtime", " MaxDeadTime", " Passed all subsystems?", " List of Subsystems failed")
1274
1275 ## if SubSystemOff["All"]:
1276 ## for keys in LumiPageInfo[LS]:
1277 ## #print LS, keys, LumiPageInfo[LS][keys]
1278 ## if not LumiPageInfo[LS][keys]:
1279 ## Passed=False
1280 ## subsystemfailed.append(keys)
1281 ## break
1282 ## else:
1283 if SubSystemOff["Mu"] or SubSystemOff["All"]:
1284 if not (LumiPageInfo[LS]["rpc"] and LumiPageInfo[LS]["dt0"] and LumiPageInfo[LS]["dtp"] and LumiPageInfo[LS]["dtm"] and LumiPageInfo[LS]["cscp"] and LumiPageInfo[LS]["cscm"]):
1285 Passed=False
1286 subsystemfailed.append("Mu")
1287 if SubSystemOff["HCal"] or SubSystemOff["All"]:
1288 if not (LumiPageInfo[LS]["hbhea"] and LumiPageInfo[LS]["hbheb"] and LumiPageInfo[LS]["hbhec"]):
1289 Passed=False
1290 subsystemfailed.append("HCal")
1291 if (SubSystemOff["EndCap"] or SubSystemOff["All"]) and not (LumiPageInfo[LS]["hf"]):
1292 Passed=False
1293 subsystemfailed.append("HCal-EndCap")
1294 if SubSystemOff["ECal"] or SubSystemOff["All"]:
1295 if not (LumiPageInfo[LS]["ebp"] and LumiPageInfo[LS]["ebm"]):
1296 Passed=False
1297 subsystemfailed.append("ECal")
1298 if (SubSystemOff["EndCap"] or SubSystemOff["All"]) and not (LumiPageInfo[LS]["eep"] and LumiPageInfo[LS]["eem"] and LumiPageInfo[LS]["esp"] or LumiPageInfo[LS]["esm"]):
1299 Passed=False
1300 subsystemfailed.append("ECal-EndCap")
1301 if SubSystemOff["Tracker"] or SubSystemOff["All"]:
1302 if not (LumiPageInfo[LS]["tob"] and LumiPageInfo[LS]["tibtid"] and LumiPageInfo[LS]["bpix"] and LumiPageInfo[LS]["fpix"]):
1303 Passed=False
1304 subsystemfailed.append("Tracker")
1305 if (SubSystemOff["EndCap"] or SubSystemOff["All"]) and not (LumiPageInfo[LS]["tecp"] and LumiPageInfo[LS]["tecm"]):
1306 Passed=False
1307 subsystemfailed.append("Tracker-EndCap")
1308 if SubSystemOff["Beam"] or SubSystemOff["All"]:
1309 if not(LumiPageInfo[LS]["b1pres"] and LumiPageInfo[LS]["b2pres"] and LumiPageInfo[LS]["b1stab"] and LumiPageInfo[LS]["b2stab"]):
1310 Passed=False
1311 subsystemfailed.append("Beam")
1312 else:
1313
1314 Passed=True
1315
1316
1317
1318 if not data_clean or (
1319 ## (
1320
1321 ## (
1322 ## realvalue > 0.4*prediction
1323 ## and realvalue < 2.5*prediction
1324 ## )
1325
1326 ## or
1327
1328 ## (
1329 ## realvalue > 0.4*meanxsec
1330 ## and realvalue < 2.5*meanxsec
1331 ## )
1332
1333 ## or prediction < 0
1334 ## )
1335
1336 Rates[print_trigger]["physics"][iterator] == 1
1337 and Rates[print_trigger]["active"][iterator] == 1
1338 and Rates[print_trigger]["deadtime"][iterator] < max_dt
1339 #and Rates[print_trigger]["psi"][iterator] > 0
1340 and Passed
1341 ):
1342 #print LS, "True"
1343 if (print_info and num_ls==1 and (realvalue <0.4*prediction or realvalue>2.5*prediction)):
1344 pass
1345 ##print '%-60s%10s%10s%10s%10s%10s%10s%10s%15s%20s' % (print_trigger,"Passed", Rates[print_trigger]["run"][iterator], LS, Rates[print_trigger]["physics"][iterator], Rates[print_trigger]["active"][iterator], round(Rates[print_trigger]["deadtime"][iterator],2), max_dt, Passed, subsystemfailed)
1346
1347 return True
1348 else:
1349
1350 if (print_info and print_trigger==trig_list[0] and num_ls==1):
1351 print '%10s%10s%10s%10s%10s%10s%10s%15s%20s' % ("Failed", Rates[print_trigger]["run"][iterator], LS, Rates[print_trigger]["physics"][iterator], Rates[print_trigger]["active"][iterator], round(Rates[print_trigger]["deadtime"][iterator],2), max_dt, Passed, subsystemfailed)
1352
1353 return False
1354
1355
1356 #### LumiRangeGreens ####
1357 ####inputs: RefMoreLumiArray --dict with lumi page info in LS by LS blocks,
1358 #### LRange --list range over lumis,
1359 #### nls --number of lumisections
1360 #### RefRunNum --run number
1361 ####
1362 ####outputs RangeMoreLumi --lumi page info in dict LSRange blocks with lumi, added items Run and LSRange
1363 def LumiRangeGreens(RefMoreLumiArray,LSRange,nls,RefRunNum,deadtimebeamactive):
1364
1365 RangeMoreLumi={}
1366 for keys,values in RefMoreLumiArray.iteritems():
1367 RangeMoreLumi[keys]=1
1368
1369 for iterator in LSRange[nls]:
1370 for keys, values in RefMoreLumiArray.iteritems():
1371 if RefMoreLumiArray[keys][iterator]==0:
1372 RangeMoreLumi[keys]=0
1373 RangeMoreLumi['LSRange']=LSRange[nls]
1374 RangeMoreLumi['Run']=RefRunNum
1375 RangeMoreLumi['DeadTimeBeamActive']=deadtimebeamactive
1376 return RangeMoreLumi
1377
1378 #### CheckLumis ####
1379 ####inputs:
1380 #### PageLumiInfo --dict of LS with dict of some lumipage info
1381 #### Rates --dict of triggernames with dict of info
1382 def checkLS(Rates, PageLumiInfo,trig_list):
1383 rateslumis=Rates[trig_list[-1]]["ls"]
1384 keys=PageLumiInfo.keys()
1385 print "lumi run=",PageLumiInfo[keys[-1]]["Run"]
1386 ll=0
1387 for ls in keys:
1388 print ls,rateslumis[ll]
1389 ll=ll+1
1390 return False
1391
1392
1393
1394
1395 if __name__=='__main__':
1396 global thisyear
1397 main()