ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/RateMonShiftTool_dev/DatabaseRatePredictor.py
Revision: 1.47
Committed: Thu Aug 9 12:01:40 2012 UTC (12 years, 8 months ago) by awoodard
Content type: text/x-python
Branch: MAIN
CVS Tags: V00-01-07
Changes since 1.46: +42 -103 lines
Log Message:
Now makes a fit for prompt stream A if 'HLT_Stream_A' is included in the trigger list

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