ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/RateMonShiftTool_dev/DatabaseRatePredictor.py
Revision: 1.34
Committed: Fri Apr 6 11:28:31 2012 UTC (13 years, 1 month ago) by grchrist
Content type: text/x-python
Branch: MAIN
Changes since 1.33: +57 -31 lines
Log Message:
added --NoVersion option to rate predictor and added core trigger list

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