ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/RateMonShiftTool_dev/DatabaseRatePredictor.py
Revision: 1.33
Committed: Thu Apr 5 22:51:47 2012 UTC (13 years ago) by grchrist
Content type: text/x-python
Branch: MAIN
Changes since 1.32: +3 -1 lines
Log Message:
more changes

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