ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/RateMonShiftTool_dev/DatabaseRatePredictor.py
Revision: 1.23
Committed: Mon Mar 26 16:09:02 2012 UTC (13 years, 1 month ago) by grchrist
Content type: text/x-python
Branch: MAIN
Changes since 1.22: +4 -8 lines
Log Message:
got rid of a few extra printing that wasn't needed

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