Belle II Software development
hepmc_roundtrip.py
1#!/usr/bin/env python3
2
3
10
11"""
12Test HepMC reader and writer by reading in a hepmc file and writing out one
13again and checking if they match.
14
15"""
16
17import os
18import sys
19import math
20import basf2 as b2
21import modularAnalysis as ma
22from tempfile import TemporaryDirectory
23
24# analogous to lhereader.py
25
26input_filename = b2.find_file("generators/tests/event.hepmc")
27
28if len(input_filename) == 0:
29 sys.stderr.write("TEST SKIPPED: input file " + input_filename + " not found.")
30 sys.exit(-1)
31
32with TemporaryDirectory() as tmp:
33
34
35 output_filename = "event.hepmc.out"
36
37 os.chdir(tmp)
38 path = ma.create_path()
39 path.add_module("HepMCInput", inputFileList=[input_filename], expNum=0, runNum=0)
40 path.add_module("HepMCOutput", OutputFilename=output_filename)
41 b2.process(path)
42
43
44 def valid_line(li):
45 """
46 Check only lines that contain numbers
47
48 HepMC lines look like this:
49 Letter Number Number Number Number ...
50
51 with letters:
52 E: event, V: vertex, P: particle
53 """
54 return li.split()[0] in ["E", "V", "P"]
55
56
57 def parse_line(li):
58 tokens = li.split()
59 start_index = 1
60 if tokens[0] == "E":
61 # For events, the first number is the event number
62 # We don't check this here, since it will be incremented in basf2
63 start_index = 2
64 return [float(t) for t in tokens[start_index:]]
65
66 def get_nonempty_lines(f):
67 return [li for li in f if not li.isspace()]
68
69 with open(input_filename) as inputfile, open(output_filename) as outputfile:
70 lines_input = get_nonempty_lines(inputfile)
71 lines_output = get_nonempty_lines(outputfile)
72 for line_input, line_output in zip(lines_input, lines_output):
73 if valid_line(line_input):
74 assert valid_line(line_output)
75 numbers_input = parse_line(line_input)
76 numbers_output = parse_line(line_output)
77 for number_input, number_output in zip(numbers_input, numbers_output):
78 assert math.isclose(number_input, number_output, rel_tol=1e-5)
79