ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/RateMonShiftTool_dev/DatabaseRatePredictor.py
Revision: 1.29
Committed: Tue Apr 3 13:25:47 2012 UTC (13 years, 1 month ago) by grchrist
Content type: text/x-python
Branch: MAIN
Changes since 1.28: +24 -12 lines
Log Message:
changed year=2011 to global var called thisyear

File Contents

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