ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/RateMonShiftTool_dev/DatabaseRatePredictor.py
Revision: 1.62
Committed: Mon Oct 8 13:16:08 2012 UTC (12 years, 6 months ago) by awoodard
Content type: text/x-python
Branch: MAIN
CVS Tags: V00-02-04
Changes since 1.61: +12 -8 lines
Log Message:
Adding an except so script won't crash in secondary mode when the fit for a trigger isn't found.

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