ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/RateMonShiftTool_dev/DatabaseRatePredictor.py
Revision: 1.82
Committed: Tue Nov 20 13:44:16 2012 UTC (12 years, 5 months ago) by grchrist
Content type: text/x-python
Branch: MAIN
Changes since 1.81: +11 -7 lines
Log Message:
all trigger works in secondary mode

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