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