def __init__(self, input_file="", **kwargs): super(ReaderHepMC, self).__init__(**kwargs) # Create reader self.reader = pyhepmc_ng.ReaderAscii(input_file) if self.reader.failed(): raise ValueError( "[error] unable to read from {}".format(input_file))
def test_pythonic_read_write(evt): oss = hep.stringstream() with hep.WriterAscii(oss) as f: f.write(evt) with hep.ReaderAscii(oss) as f: for i, evt2 in enumerate(f): assert i == 0 assert evt.particles == evt2.particles assert evt.vertices == evt2.vertices assert evt == evt2
def test_read_write(evt): oss = hep.stringstream() with hep.WriterAscii(oss) as f: f.write_event(evt) evt2 = hep.GenEvent() assert evt != evt2 with hep.ReaderAscii(oss) as f: f.read_event(evt2) assert evt.event_number == evt2.event_number assert evt.momentum_unit == evt2.momentum_unit assert evt.length_unit == evt2.length_unit assert evt.particles == evt2.particles assert evt.vertices == evt2.vertices assert evt == evt2
def main(): input_file = "$HOME/data/jetscape/test_out.hepmc" if len(sys.argv) > 1: input_file = sys.argv[1] input_file = os.path.expandvars(input_file) print('[i] reading from:', input_file) # input = pyhepmc_ng.ReaderAsciiHepMC2(input_file) input = pyhepmc_ng.ReaderAscii(input_file) if input.failed(): print("[error] unable to read from {}".format(input_file)) return nevents = 1000 # print the banner first fj.ClusterSequence.print_banner() print() jet_R0 = 0.4 jet_def = fj.JetDefinition(fj.antikt_algorithm, jet_R0) jet_selector = fj.SelectorPtMin(0.0) & fj.SelectorPtMax( 200.0) & fj.SelectorAbsEtaMax(3) all_jets = [] event = pyhepmc_ng.GenEvent() pbar = tqdm.tqdm(range(nevents)) while not input.failed(): e = input.read_event(event) if input.failed(): break fjparts = [] for i, p in enumerate(event.particles): if p.status == 1 and not p.end_vertex: psj = fj.PseudoJet(p.momentum.px, p.momentum.py, p.momentum.pz, p.momentum.e) psj.set_user_index(i) fjparts.append(psj) jets = jet_selector(jet_def(fjparts)) all_jets.append([[j.pt(), j.eta()] for j in jets]) pbar.update() for j in jets: hjetpt.Fill(j.perp()) if pbar.n >= nevents: break pbar.close()
def test_read_write_file(): evt1 = prepare_event() with hep.WriterAscii("test_read_write_file.dat") as f: f.write_event(evt1) evt2 = hep.GenEvent() assert evt1 != evt2 with hep.ReaderAscii("test_read_write_file.dat") as f: ok = f.read_event(evt2) assert ok assert evt1.particles == evt2.particles assert evt1.vertices == evt2.vertices assert evt1 == evt2 import os os.unlink("test_read_write_file.dat")
def main(): input_file = "$HOME/data/jetscape/test_out.hepmc" if len(sys.argv) > 1: input_file = sys.argv[1] input_file = os.path.expandvars(input_file) print('[i] reading from:', input_file) input = pyhepmc_ng.ReaderAscii(input_file) if input.failed(): print("[error] unable to read from {}".format(input_file)) return event = pyhepmc_ng.GenEvent() while not input.failed(): e = input.read_event(event) if input.failed(): break
def test_read_write_stream(): evt1 = prepare_event() oss = hep.stringstream() with hep.WriterAscii(oss) as f: f.write_event(evt1) assert str(oss) == """HepMC::Version 3.01.00 HepMC::Asciiv3-START_EVENT_LISTING E 1 4 8 U GEV MM W 1.0000000000000000000000e+00 P 1 0 2212 0.0000000000000000e+00 0.0000000000000000e+00 7.0000000000000000e+03 7.0000000000000000e+03 9.3799999999999994e-01 1 P 2 0 2212 0.0000000000000000e+00 0.0000000000000000e+00 -7.0000000000000000e+03 7.0000000000000000e+03 9.3799999999999994e-01 2 V -1 0 [1] @ 1.0000000000000000e+00 1.0000000000000000e+00 1.0000000000000000e+00 1.0000000000000000e+00 P 3 -1 1 7.5000000000000000e-01 -1.5690000000000000e+00 3.2191000000000003e+01 3.2238000000000000e+01 0.0000000000000000e+00 3 V -2 0 [2] @ 2.0000000000000000e+00 2.0000000000000000e+00 2.0000000000000000e+00 2.0000000000000000e+00 P 4 -2 -2 -3.0470000000000002e+00 -1.9000000000000000e+01 -5.4628999999999998e+01 5.7920000000000002e+01 0.0000000000000000e+00 4 V -3 0 [3,4] @ 3.0000000000000000e+00 3.0000000000000000e+00 3.0000000000000000e+00 3.0000000000000000e+00 P 5 -3 -24 1.5169999999999999e+00 -2.0680000000000000e+01 -2.0605000000000000e+01 8.5924999999999997e+01 8.0799000000000007e+01 5 P 6 -3 22 -3.8130000000000002e+00 1.1300000000000000e-01 -1.8330000000000000e+00 4.2329999999999997e+00 0.0000000000000000e+00 6 V -4 0 [5] @ 4.0000000000000000e+00 4.0000000000000000e+00 4.0000000000000000e+00 4.0000000000000000e+00 P 7 -4 1 -2.4449999999999998e+00 2.8815999999999999e+01 6.0819999999999999e+00 2.9552000000000000e+01 1.0000000000000000e-02 7 P 8 -4 -2 3.9620000000000002e+00 -4.9497999999999998e+01 -2.6687000000000001e+01 5.6372999999999998e+01 6.0000000000000001e-03 8 HepMC::Asciiv3-END_EVENT_LISTING """ evt2 = hep.GenEvent() assert evt1 != evt2 with hep.ReaderAscii(oss) as f: f.read_event(evt2) assert evt1.event_number == evt2.event_number assert evt1.momentum_unit == evt2.momentum_unit assert evt1.length_unit == evt2.length_unit assert evt1.particles == evt2.particles assert evt1.vertices == evt2.vertices assert evt1 == evt2
def main(self): if self.hepmc == 3: input_hepmc = pyhepmc_ng.ReaderAscii(self.input) if self.hepmc == 2: input_hepmc = pyhepmc_ng.ReaderAsciiHepMC2(self.input) if input_hepmc.failed(): print("[error] unable to read from {}".format(self.input)) sys.exit(1) event_hepmc = pyhepmc_ng.GenEvent() while not input_hepmc.failed(): ev = input_hepmc.read_event(event_hepmc) if input_hepmc.failed(): break self.fill_event(event_hepmc) self.increment_event() if self.nev > 0 and self.ev_id > self.nev: break self.finish()
def main(): parser = argparse.ArgumentParser(description='jetscape in python', \ prog=os.path.basename(__file__)) parser.add_argument('-i', '--input', help='input file', \ default='low', type=str, required=True) parser.add_argument('--nev', help='number of events', \ default=1000, type=int) args = parser.parse_args() plot_hadrons = False plot_final_state_partons = True plot_nth_partons = False include_thermal_background = False # Initialize histogram dictionary hDict = initializeHistograms() # Use pyhepmc_ng to parse the HepMC file input_hepmc = pyhepmc_ng.ReaderAscii(args.input) if input_hepmc.failed(): print("[error] unable to read from {}".format(args.input)) sys.exit(1) # jet finder fj.ClusterSequence.print_banner() print() jetR = 0.4 jet_def = fj.JetDefinition(fj.antikt_algorithm, jetR) jet_selector = fj.SelectorPtMin(50.0) & fj.SelectorAbsEtaMax(2) # Jet re-clustering definition, for primary Lund plane jet_def_lund = fj.JetDefinition(fj.cambridge_algorithm, jetR) lund_gen = fjcontrib.LundGenerator(jet_def_lund) # Load thermal background: array of dataframes, one per event if include_thermal_background: thermal_background_array = get_thermal_background() # Loop through events all_jets_hadron = [] all_jets_parton = [] kt_shower_list = [] event_hepmc = pyhepmc_ng.GenEvent() pbar = tqdm.tqdm(range(args.nev)) while not input_hepmc.failed(): ev = input_hepmc.read_event(event_hepmc) if input_hepmc.failed(): nstop = pbar.n pbar.close() print('End of HepMC file at event {} '.format(nstop)) break if plot_hadrons: hadrons = get_hadrons(event_hepmc) jets_hadron = find_jets(jet_def, jet_selector, hadrons) all_jets_hadron.extend(jets_hadron) if plot_final_state_partons: parton_list = get_final_partons(event_hepmc, hDict) elif plot_nth_partons: # Get the first parton in the shower (it is apparently the child of the initiating parton) first_parton = [] first_parton.append( get_first_parton(event_hepmc, hDict).children[0]) #print('-----------------------------') #print('First parton E: {}'.format(first_parton[0].momentum.e)) n = 3 parton_list = get_nth_partons(first_parton, n) #print('Total number of partons: {}'.format(len(parton_list))) fj_particles = [] for parton in parton_list: fj_particles.append( fj.PseudoJet(parton.momentum.px, parton.momentum.py, parton.momentum.pz, parton.momentum.e)) # Append thermal background if include_thermal_background: thermal_background_df = thermal_background_array[0] thermal_background_fjparticles = get_fjparticles( thermal_background_df) fj_particles.extend(thermal_background_fjparticles) jets_parton = find_jets(jet_def, jet_selector, fj_particles) all_jets_parton.extend(jets_parton) # Analyze shower history max_kt = get_max_kt_shower(event_hepmc, hDict) kt_shower_list.append(max_kt) pbar.update() if pbar.n >= args.nev: pbar.close() print('{} event limit reached'.format(args.nev)) break print('Constructing histograms...') if plot_hadrons: n_jets_hadron = len(all_jets_hadron) print('n_jets_hadron: {}'.format(n_jets_hadron)) n_jets_parton = len(all_jets_parton) print('n_jets_parton: {}'.format(n_jets_parton)) # Fill histogram if plot_hadrons: [fill_jet_histogram(hDict, jet) for jet in all_jets_hadron] # Fill Lund diagram # Note: l in lunds, l is the list of splittings in a given jet (following hardest splitting) lunds_hadron = [lund_gen.result(jet) for jet in all_jets_hadron] [ fill_lund_histogram(hDict, "hLundHadron", splitting_list) for splitting_list in lunds_hadron ] hDict['hLundHadron'].Scale(1. / n_jets_hadron, "width") lunds_parton = [lund_gen.result(jet) for jet in all_jets_parton] [ fill_lund_histogram(hDict, "hLundParton", splitting_list) for splitting_list in lunds_parton ] hDict['hLundParton'].Scale(1. / n_jets_parton, "width") for splitting_list in lunds_parton: max_kt_recluster = 0 for split in splitting_list: kt = split.kt() if kt > max_kt_recluster: max_kt_recluster = kt hDict['hMaxKT_2D'].Fill(np.log(max_kt_recluster), np.log(kt)) plot_histograms(hDict)
def main(): parser = argparse.ArgumentParser(description='pythia8 in python', prog=os.path.basename(__file__)) parser.add_argument('-i', '--input', help='input file', default='low', type=str, required=True) parser.add_argument('--hepmc', help='what format 2 or 3', default=2, type=int) parser.add_argument('--nev', help='number of events', default=10, type=int) args = parser.parse_args() ### # now lets read the HEPMC file and do some jet finding if args.hepmc == 3: input_hepmc = pyhepmc_ng.ReaderAscii(args.input) if args.hepmc == 2: input_hepmc = pyhepmc_ng.ReaderAsciiHepMC2(args.input) if input_hepmc.failed(): print("[error] unable to read from {}".format(args.input)) sys.exit(1) # jet finder # print the banner first fj.ClusterSequence.print_banner() print() jet_R0 = 0.4 jet_def = fj.JetDefinition(fj.antikt_algorithm, jet_R0) jet_selector = fj.SelectorPtMin(10.0) & fj.SelectorPtMax( 500.0) & fj.SelectorAbsEtaMax(3) all_jets = [] event_hepmc = pyhepmc_ng.GenEvent() pbar = tqdm.tqdm(range(args.nev)) while not input_hepmc.failed(): ev = input_hepmc.read_event(event_hepmc) if input_hepmc.failed(): break jets_hepmc = find_jets_hepmc(jet_def, jet_selector, event_hepmc) all_jets.extend(jets_hepmc) pbar.update() if pbar.n >= args.nev: break jet_def_lund = fj.JetDefinition(fj.cambridge_algorithm, 1.0) lund_gen = fjcontrib.LundGenerator(jet_def_lund) print('[i] making lund diagram for all jets...') lunds = [lund_gen.result(j) for j in all_jets] print('[i] listing lund plane points... Delta, kt - for {} selected jets'. format(len(all_jets))) for l in lunds: if len(l) < 1: continue print('- jet pT={0:5.2f} eta={1:5.2f}'.format(l[0].pair().perp(), l[0].pair().eta())) print(' Deltas={}'.format([s.Delta() for s in l])) print(' kts={}'.format([s.kt() for s in l])) print() print('[i] reclustering and using soft drop...') jet_def_rc = fj.JetDefinition(fj.cambridge_algorithm, 0.1) print('[i] Reclustering:', jet_def_rc) all_jets_sd = [] rc = fjcontrib.Recluster(jet_def_rc, True) sd = fjcontrib.SoftDrop(0, 0.1, 1.0) for i, j in enumerate(all_jets): j_rc = rc.result(j) print() print('- [{0:3d}] orig pT={1:10.3f} reclustered pT={2:10.3f}'.format( i, j.perp(), j_rc.perp())) j_sd = sd.result(j) print(' |-> after soft drop pT={0:10.3f} delta={1:10.3f}'.format( j_sd.perp(), j_sd.perp() - j.perp())) all_jets_sd.append(j_sd) sd_info = fjcontrib.get_SD_jet_info(j_sd) print( " |-> SD jet params z={0:10.3f} dR={1:10.3f} mu={2:10.3f}".format( sd_info.z, sd_info.dR, sd_info.mu)) fout = ROOT.TFile('hepmc_jetreco.root', 'recreate') lbins = logbins(1., 500, 50) hJetPt04 = ROOT.TH1D("hJetPt04", "hJetPt04", 50, lbins) hJetPt04sd = ROOT.TH1D("hJetPt04sd", "hJetPt04sd", 50, lbins) [hJetPt04.Fill(j.perp()) for j in all_jets] [hJetPt04sd.Fill(j.perp()) for j in all_jets_sd] hLund = ROOT.TH2D("hLund", "hLund", 60, 0, 6, 100, -4, 5) lunds = [lund_gen.result(j) for j in all_jets if j.perp() > 100] j100 = [j for j in all_jets if j.perp() > 100] print('{} jets above 100 GeV/c'.format(len(j100))) for l in lunds: for s in l: hLund.Fill(math.log(1. / s.Delta()), math.log(s.kt())) fout.Write()
def test_read_empty_stream(): oss = hep.stringstream() with hep.ReaderAscii(oss) as f: evt = hep.GenEvent() ok = f.read_event(evt) assert ok == True # reading empty stream is ok in HepMC
def test_failed_read_file(): with pytest.raises(IOError): with hep.ReaderAscii("test_failed_read_file.dat") as f: f.read()
def main(): parser = argparse.ArgumentParser( description='hepmc to ALICE Ntuple format', prog=os.path.basename(__file__)) parser.add_argument('-i', '--input', help='input file', default='', type=str, required=True) parser.add_argument('-o', '--output', help='output root file', default='', type=str, required=True) parser.add_argument('--as-data', help='write as data - tree naming convention', action='store_true', default=False) parser.add_argument('--hepmc', help='what format 2 or 3', default=2, type=int) parser.add_argument('--nev', help='number of events', default=-1, type=int) args = parser.parse_args() if args.hepmc == 3: input_hepmc = pyhepmc_ng.ReaderAscii(args.input) if args.hepmc == 2: input_hepmc = pyhepmc_ng.ReaderAsciiHepMC2(args.input) if input_hepmc.failed(): print("[error] unable to read from {}".format(args.input)) sys.exit(1) outf = ROOT.TFile(args.output, 'recreate') outf.cd() tdf = ROOT.TDirectoryFile('PWGHF_TreeCreator', 'PWGHF_TreeCreator') tdf.cd() if args.as_data: t_p = ROOT.TNtuple( 'tree_Particle', 'tree_Particle', 'run_number:ev_id:ParticlePt:ParticleEta:ParticlePhi:ParticlePID') else: t_p = ROOT.TNtuple( 'tree_Particle_gen', 'tree_Particle_gen', 'run_number:ev_id:ParticlePt:ParticleEta:ParticlePhi:ParticlePID') t_e = ROOT.TNtuple('tree_event_char', 'tree_event_char', 'run_number:ev_id:z_vtx_reco:is_ev_rej') # run number will be a double - file size in MB run_number = os.path.getsize(args.input) / 1.e6 ev_id = 0 # unfortunately pyhepmc_ng does not provide the table # pdt = pyhepmc_ng.ParticleDataTable() # use ROOT instead pdg = ROOT.TDatabasePDG() event_hepmc = pyhepmc_ng.GenEvent() if args.nev > 0: pbar = tqdm.tqdm(range(args.nev)) else: pbar = tqdm.tqdm() while not input_hepmc.failed(): ev = input_hepmc.read_event(event_hepmc) if input_hepmc.failed(): break fill_event(run_number, ev_id, event_hepmc, t_e, t_p, pdg) ev_id = ev_id + 1 pbar.update() if args.nev > 0 and ev_id > args.nev: break outf.Write() outf.Close()
def main(): parser = argparse.ArgumentParser(description='jetscape in python', \ prog=os.path.basename(__file__)) parser.add_argument('-i', '--input', help='input file', \ default='low', type=str, required=True) parser.add_argument('--nev', help='number of events', \ default=1000, type=int) args = parser.parse_args() # Use pyhepmc_ng to parse the HepMC file input_hepmc = pyhepmc_ng.ReaderAscii(args.input) if input_hepmc.failed(): print("[error] unable to read from {}".format(args.input)) sys.exit(1) # Create a histogram with ROOT lbins = logbins(1., 500, 50) hJetPt04 = ROOT.TH1D("hJetPt04", "hJetPt04", 50, lbins) # jet finder fj.ClusterSequence.print_banner() print() jet_R0 = 0.4 jet_def = fj.JetDefinition(fj.antikt_algorithm, jet_R0) jet_selector = fj.SelectorPtMin(50.0) & fj.SelectorPtMax( 200.0) & fj.SelectorAbsEtaMax(3) # Loop through events all_jets = [] event_hepmc = pyhepmc_ng.GenEvent() pbar = tqdm.tqdm(range(args.nev)) while not input_hepmc.failed(): ev = input_hepmc.read_event(event_hepmc) if input_hepmc.failed(): nstop = pbar.n pbar.close() print('End of HepMC file at event {} '.format(nstop)) break jets_hepmc = find_jets_hepmc(jet_def, jet_selector, event_hepmc) all_jets.extend(jets_hepmc) pbar.update() # Fill histogram [fill_jet_histogram(hJetPt04, jet) for jet in all_jets] if pbar.n >= args.nev: pbar.close() print('{} event limit reached'.format(args.nev)) break # Plot and save histogram print('Creating ROOT file...') c = ROOT.TCanvas('c', 'c', 600, 450) c.cd() c.SetLogy() hJetPt04.SetMarkerStyle(21) hJetPt04.Sumw2() hJetPt04.Draw('E P') output_filename = './AnalysisResult.root' c.SaveAs(output_filename) fout = ROOT.TFile(output_filename, "update") fout.cd() hJetPt04.Write() fout.Close()
def test_failed_read_file(): with hep.ReaderAscii("test_failed_read_file.dat") as f: assert f.read() is None