ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/RateMonShiftTool_dev/DatabaseRatePredictor.py
Revision: 1.28
Committed: Tue Apr 3 12:38:39 2012 UTC (13 years, 1 month ago) by grchrist
Content type: text/x-python
Branch: MAIN
Changes since 1.27: +3 -2 lines
Log Message:
mkTMD_predictions takes tmd predictions and makes pickle files

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