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