ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/RateMonShiftTool_dev/DatabaseRatePredictor.py
Revision: 1.71
Committed: Sat Nov 10 22:30:45 2012 UTC (12 years, 5 months ago) by grchrist
Content type: text/x-python
Branch: MAIN
CVS Tags: V00-02-05
Changes since 1.70: +60 -1 lines
Log Message:
added L1 prescale change funcion

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