def main(argv): clock = TStopwatch() argc = len(argv) if (argc != 5): return usage() fileName = argv[1] the_type = argv[2] requireTree = argv[3] verbosity = argv[4] if the_type != "event" and the_type != "basket": return usage() if requireTree != "true" and requireTree != "false": return usage() if verbosity == "on": msg.setLevel(logging.DEBUG) elif verbosity == "off": msg.setLevel(logging.INFO) else: return usage() rc = checkFile(fileName, the_type, requireTree) msg.debug('Returning %s' % rc) clock.Stop() clock.Print() return rc
def main(argv): import logging msg = logging.getLogger(__name__) ch = logging.StreamHandler(sys.stdout) # ch.setLevel(logging.DEBUG) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) msg.addHandler(ch) clock = TStopwatch() argc = len(argv) if (argc != 5): return usage() fileName = argv[1] type = argv[2] tree = argv[3] verbosity = argv[4] if type != "event" and type != "basket": return usage() if tree == "true": requireTree = True elif tree == "false": requireTree = False else: return usage() if verbosity == "on": msg.setLevel(logging.DEBUG) elif verbosity == "off": msg.setLevel(logging.INFO) else: return usage() rc = checkFile(fileName, type, requireTree, msg) msg.debug('Returning %s' % rc) clock.Stop() clock.Print() return rc
def main(): try: # Retrive command line options shortopts = "m:i:t:o:vh?" longopts = [ "methods=", "inputfile=", "inputtrees=", "outputfile=", "verbose", "help", "usage" ] opts, args = getopt.getopt(sys.argv[1:], shortopts, longopts) except getopt.GetoptError: # Print help information and exit: print "ERROR: unknown options in argument %s" % sys.argv[1:] usage() sys.exit(1) infname = DEFAULT_INFNAME treeNameSig = DEFAULT_TREESIG treeNameBkg = DEFAULT_TREEBKG outfname = DEFAULT_OUTFNAME methods = DEFAULT_METHODS verbose = False for o, a in opts: if o in ("-?", "-h", "--help", "--usage"): usage() sys.exit(0) elif o in ("-m", "--methods"): methods = a elif o in ("-i", "--inputfile"): infname = a elif o in ("-o", "--outputfile"): outfname = a elif o in ("-t", "--inputtrees"): a.strip() trees = a.rsplit(' ') trees.sort() trees.reverse() if len(trees) - trees.count('') != 2: print "ERROR: need to give two trees (each one for signal and background)" print trees sys.exit(1) treeNameSig = trees[0] treeNameBkg = trees[1] elif o in ("-v", "--verbose"): verbose = True # Print methods mlist = methods.replace(' ', ',').split(',') print "=== TMVApplication: use method(s)..." for m in mlist: if m.strip() != '': print "=== - <%s>" % m.strip() # Import ROOT classes from ROOT import gSystem, gROOT, gApplication, TFile, TTree, TCut, TH1F, TStopwatch # check ROOT version, give alarm if 5.18 if gROOT.GetVersionCode() >= 332288 and gROOT.GetVersionCode() < 332544: print "*** You are running ROOT version 5.18, which has problems in PyROOT such that TMVA" print "*** does not run properly (function calls with enums in the argument are ignored)." print "*** Solution: either use CINT or a C++ compiled version (see TMVA/macros or TMVA/examples)," print "*** or use another ROOT version (e.g., ROOT 5.19)." sys.exit(1) # Logon not automatically loaded through PyROOT (logon loads TMVA library) load also GUI gROOT.SetMacroPath("../macros/") gROOT.Macro("../macros/TMVAlogon.C") # Import TMVA classes from ROOT from ROOT import TMVA # Create the Reader object reader = TMVA.Reader("!Color") # Create a set of variables and declare them to the reader # - the variable names must corresponds in name and type to # those given in the weight file(s) that you use # what to do ??? var1 = array('f', [0]) var2 = array('f', [0]) var3 = array('f', [0]) var4 = array('f', [0]) reader.AddVariable("var1+var2", var1) reader.AddVariable("var1-var2", var2) reader.AddVariable("var3", var3) reader.AddVariable("var4", var4) # book the MVA methods dir = "weights/" prefix = "TMVAnalysis_" for m in mlist: reader.BookMVA(m + " method", dir + prefix + m + ".weights.txt") ####################################################################### # For an example how to apply your own plugin method, please see # TMVA/macros/TMVApplication.C ####################################################################### # Book output histograms nbin = 80 histList = [] for m in mlist: histList.append(TH1F(m, m, nbin, -3, 3)) # Book example histogram for probability (the other methods would be done similarly) if "Fisher" in mlist: probHistFi = TH1F("PROBA_MVA_Fisher", "PROBA_MVA_Fisher", nbin, 0, 1) rarityHistFi = TH1F("RARITY_MVA_Fisher", "RARITY_MVA_Fisher", nbin, 0, 1) # Prepare input tree (this must be replaced by your data source) # in this example, there is a toy tree with signal and one with background events # we'll later on use only the "signal" events for the test in this example. # fname = "./tmva_example.root" print "--- Accessing data file: %s" % fname input = TFile.Open(fname) if not input: print "ERROR: could not open data file: %s" % fname sys.exit(1) # # Prepare the analysis tree # - here the variable names have to corresponds to your tree # - you can use the same variables as above which is slightly faster, # but of course you can use different ones and copy the values inside the event loop # print "--- Select signal sample" theTree = input.Get("TreeS") userVar1 = array('f', [0]) userVar2 = array('f', [0]) theTree.SetBranchAddress("var1", userVar1) theTree.SetBranchAddress("var2", userVar2) theTree.SetBranchAddress("var3", var3) theTree.SetBranchAddress("var4", var4) # Efficiency calculator for cut method nSelCuts = 0 effS = 0.7 # Process the events print "--- Processing: %i events" % theTree.GetEntries() sw = TStopwatch() sw.Start() for ievt in range(theTree.GetEntries()): if ievt % 1000 == 0: print "--- ... Processing event: %i" % ievt # Fill event in memory theTree.GetEntry(ievt) # Compute MVA input variables var1[0] = userVar1[0] + userVar2[0] var2[0] = userVar1[0] - userVar2[0] # Return the MVAs and fill to histograms if "CutsGA" in mlist: passed = reader.EvaluateMVA("CutsGA method", effS) if passed: nSelCuts = nSelCuts + 1 # Fill histograms with MVA outputs for h in histList: h.Fill(reader.EvaluateMVA(h.GetName() + " method")) # Retrieve probability instead of MVA output if "Fisher" in mlist: probHistFi.Fill(reader.GetProba("Fisher method")) rarityHistFi.Fill(reader.GetRarity("Fisher method")) # Get elapsed time sw.Stop() print "--- End of event loop: %s" % sw.Print() # Return computed efficeincies if "CutsGA" in mlist: eff = float(nSelCuts) / theTree.GetEntries() deff = math.sqrt(eff * (1.0 - eff) / theTree.GetEntries()) print "--- Signal efficiency for Cuts method : %.5g +- %.5g (required was: %.5g)" % ( eff, deff, effS) # Test: retrieve cuts for particular signal efficiency mcuts = reader.FindMVA("CutsGA method") cutsMin = array('d', [0, 0, 0, 0]) cutsMax = array('d', [0, 0, 0, 0]) mcuts.GetCuts(0.7, cutsMin, cutsMax) print "--- -------------------------------------------------------------" print "--- Retrieve cut values for signal efficiency of 0.7 from Reader" for ivar in range(4): print "... Cut: %.5g < %s <= %.5g" % ( cutsMin[ivar], reader.GetVarName(ivar), cutsMax[ivar]) print "--- -------------------------------------------------------------" # # write histograms # target = TFile("TMVApp.root", "RECREATE") for h in histList: h.Write() # Write also probability hists if "Fisher" in mlist: probHistFi.Write() rarityHistFi.Write() target.Close() print "--- Created root file: \"TMVApp.root\" containing the MVA output histograms" print "==> TMVApplication is done!"
def inv1(x, b1): return tan(3*x*b1 + atan(a)) def inv2(x, b2): return rt*(-a*exp(x*b2/d) - a - rt*exp(x*b2/d) + rt)/(-a*exp(x*b2/d) + a - rt*exp(x*b2/d) -rt) print('Inv1: ', inv1(0, b1)) print('Inv2: ', inv2(0, b2)) def fncomposition(a, b, a1, a2, b1, b2): while (True): nr = gRandom.Uniform(0,1) nk = gRandom.Uniform(0,1) if nk < a1: return inv1(nr, b1) else: return inv2(nr, b2) c2 = ROOT.TCanvas("myCanvasName2","The Canvas Title", 1200, 500) h2 = TH1F("h2", "composition method", 50, -1, 1) sw = TStopwatch() sw.Start() for i in range(0, 10000): r = fncomposition(a, b, a1, a2, b1, b2) h2.Fill(r) sw.Stop() sw.Print() h2.Draw() h2.Fit(ff) c2.Draw() print('First moment: ', h2.GetMean()) print('Mean square: ', h2.GetStdDev())
event.getByLabel(muon_L, muon_H) muons = muon_H.product() print('muons size = ', muPt.size(), ', good muon size = ', muId.size(), 'good muon collection size = ', len(muons)) for imu in range(0, muPt.size()): print('muon pt in b2g muon collection =', muPt.at(imu)) for imu in muons: print('muon pt', imu.getP4().Pt()) #print ('muon charge', imu.getCharge()) #Lets just get the good muons: #goodMuIso # Done processing the events! # Stop our timer timer.Stop() # Print out our timing information rtime = timer.RealTime() # Real time (or "wall time") ctime = timer.CpuTime() # CPU time print("Analyzed events: {0:6d}".format(nEventsAnalyzed)) print("RealTime={0:6.2f} seconds, CpuTime={1:6.2f} seconds".format( rtime, ctime)) print("{0:4.2f} events / RealTime second .".format(nEventsAnalyzed / rtime)) print("{0:4.2f} events / CpuTime second .".format(nEventsAnalyzed / ctime)) subprocess.call(["ps aux | grep skhalil | cat > memory.txt", ""], shell=True)
old_integration_value = 0.0 first_time_flag = 0 for x in range(minnumberofsteps, maxnumberofsteps + 1): timer_1.Start() Integ_Midpoint.SetBinContent(x, MidPointIntegral( a, b, x, func)) # Set the value of the integral as a function of the steps x y = old_integration_value - 1.0 * MidPointIntegral( a, b, x, func) # Calculate Delta I y = 1.0 * abs(y) / MidPointIntegral(a, b, x, func) # Calculate Delta I/I Integ_Err_Midpoint.SetBinContent( x, y) # Set the Error histogram equal to Delta I / I old_integration_value = MidPointIntegral( a, b, x, func) # Store the "old" integration value timer_1.Stop() timer_Cpu_Midpoint = timer_Cpu_Midpoint + timer_1.CpuTime() #timer_Real_Midpoint = timer_Real_Midpoint + timer_1.RealTime() timer_Midpoint.SetBinContent(x, timer_Cpu_Midpoint) if y < trsh and first_time_flag == 0: first_time_flag = 1 Midpoint_stops_at_n = x print "Midpoint Done at: ", x print " Integral value MidPoint: ", MidPointIntegral(a, b, x, func) print " Error value MidPoint: ", y timer_2 = TStopwatch() timer_Cpu_Trapezoid = 0.0 Trapezoid_stops_at_n = 0.0
for dataset in split_datasets: if BNTreeUseScript: chainName = "OSUAnalysis/" + BNTreeChannel + "/BNTree_" + BNTreeChannel command = "root -l -b -q '" + BNTreeScript + "+(\"" + condor_dir + "\",\"" + dataset + "\",\"" + chainName + "\"," + str( arguments.condorProcessNum) + ")'" print "About to execute command: " + command os.system(command) else: for hist in input_histograms: #chain trees together ch = TChain("OSUAnalysis/" + hist['channel'] + "/BNTree_" + hist['channel']) ch.Add(condor_dir + "/" + dataset + "/hist_*.root") print("Looping over chain with # entries = %f; split time = " % ch.GetEntries()), watch1.Stop() watch1.Print() watch1.Start() outputFile = TFile(condor_dir + "/" + dataset + ".root", "UPDATE") if not outputFile or outputFile.IsZombie(): print "Could not open file: %s/%s.root" % (condor_dir, dataset) outputFile.cd("OSUAnalysis/" + hist['channel']) deleteString = hist[ 'histName'] + ";*" # delete all existing instances of the object currentDir = outputFile.GetDirectory("OSUAnalysis/" + hist['channel']) if not currentDir: