FairShip
Loading...
Searching...
No Matches
convertEvtCalc.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2# SPDX-FileCopyrightText: Copyright CERN for the benefit of the SHiP Collaboration
3
4"""Convert files from EventCalc to ROOT format."""
5
6import os
7import sys
8from argparse import ArgumentParser
9
10import numpy as np
11import ROOT as r
12
13
14def parse_file(infile: str):
15 """
16 Parse the given text file and extracts process type, sample points, and variables.
17
18 Parameters:
19 infile (str): Path to the input text file.
20
21 Returns:
22 tuple: A tuple containing process type (str), sample points (int), and a list of numpy arrays for each variable.
23 """
24 try:
25 with open(infile) as file:
26 lines = file.readlines()
27 lines = lines[2:]
28
29 parsed_data = []
30 current_block = []
31 process_type = None
32 sampled_points = None
33
34 for line in lines:
35 if line.startswith("#<"):
36 if current_block:
37 data = np.loadtxt(current_block)
38 variables = [data[:, i] for i in range(data.shape[1])]
39 current_block = []
40 header = line.strip()
41 process_type = header.split(";")[0].split("=")[1]
42 # print(f'Process type: {process_type}')
43 sampled_points = int(header.split(";")[1].split("=")[1][:-1])
44 # print(f'Sampled points: {sampled_points}')
45 parsed_data.append((process_type, sampled_points, variables))
46 else:
47 current_block.append(line.strip())
48
49 if current_block:
50 if process_type is None or sampled_points is None:
51 raise ValueError("bin data encountered before any header")
52 data = np.loadtxt(current_block)
53 variables = [data[:, i] for i in range(data.shape[1])]
54 parsed_data.append((process_type, sampled_points, variables))
55
56 return parsed_data
57
58 except FileNotFoundError:
59 print(f"- convertEvtCalc - Error: The file {infile} was not found.")
60 return None
61 except (ValueError, IndexError) as e:
62 print(f"- convertEvtCalc - An error occurred: {e}")
63 return None
64
65
66def check_consistency_infile(nvars, ncols) -> None:
67 """
68 Check the consistency between number of columns in the input file (ncols) and variables (nvars).
69
70 Parameters:
71 nvars, ncols (int or float): The value to be checked. Must be equal.
72
73 """
74 if nvars != ncols:
75 raise ValueError("Nr of variables does not match input file.")
76 return
77
78
79def convert_file(infile, outdir) -> str | None:
80 """
81 Create a ROOT file with a TTree containing the variables from the parsed input text file.
82
83 Parameters:
84 infile (str): Path to the input text file.
85 outdir (str): Name of the output directory, the filename will be the same
86 as inputfile with the .dat replaced with .root.
87 """
88 vars_names = [
89 "px_llp",
90 "py_llp",
91 "pz_llp",
92 "e_llp",
93 "mass_llp",
94 "pdg_llp",
95 "decay_prob",
96 "vx",
97 "vy",
98 "vz",
99 ]
100 daughter_vars = [
101 "px_prod",
102 "py_prod",
103 "pz_prod",
104 "e_prod",
105 "mass_prod",
106 "pdg_prod",
107 ]
108 fname = infile.split("/")[-1]
109 command = f"cp {infile} {outdir}/{fname}"
110
111 if os.path.isfile(f"{outdir}/{fname}"):
112 print(f"Warning: The file {outdir}/{fname} already exists.")
113 else:
114 os.system(command)
115
116 infile = f"{outdir}/{fname}"
117 parsed_data = parse_file(infile)
118 if parsed_data is None:
119 # parse_file already reported the failure
120 sys.exit(1)
121 if not parsed_data:
122 print(f"- convertEvtCalc - Error: no completed blocks found in {infile}.")
123 sys.exit(1)
124 outfile = infile.split(".dat")[0] + ".root"
125 ncols = len(parsed_data[0][2])
126 nvardau = 6 # qualifiers for each daughter
127 remaining_vars = ncols - len(vars_names)
128
129 if (remaining_vars % nvardau) != 0:
130 raise ValueError("- convertEvtCalc - Error: number of daughters is not exact.")
131
132 ndau = remaining_vars // nvardau
133 print(f"- convertEvtCalc - Max multiplicity of daughters: {ndau}")
134
135 vars_names.extend(f"{var}{i}" for i in range(1, ndau + 1) for var in daughter_vars)
136
137 try:
138 check_consistency_infile(nvars=len(vars_names), ncols=ncols)
139 except ValueError as e:
140 print(f"- convertEvtCalc - Error: {e}")
141 sys.exit(1)
142
143 vars_names += ["ndau"]
144
145 if parsed_data:
146 root_file = r.TFile.Open(outfile, "RECREATE")
147 tree = r.TTree("LLP_tree", "LLP_tree")
148
149 branch_f = {}
150 for var in vars_names:
151 branch_f[var] = np.zeros(1, dtype=float)
152 tree.Branch(var, branch_f[var], f"{var}/D")
153
154 for pt, sp, vars in parsed_data:
155 for row in zip(*vars):
156 for i, value in enumerate(row):
157 if i < len(vars_names) - 1:
158 branch_f[vars_names[i]][0] = value
159 branch_f["ndau"][0] = ndau / 1.0
160 tree.Fill()
161
162 tree.Write()
163 root_file.Close()
164 print(f"- convertEvtCalc - ROOT file '{outfile}' created successfully.")
165 return outfile
166
167
168def main() -> None:
169 """Convert files from EventCalc to ROOT format."""
170 parser = ArgumentParser(description=__doc__)
171 parser.add_argument(
172 "-f",
173 "--inputfile",
174 help="""Simulation results to use as input."""
175 """Supports retrieving file from EOS via the XRootD protocol.""",
176 required=True,
177 )
178 parser.add_argument("-o", "--outputdir", help="""Output directory, must exist.""", default=".")
179 args = parser.parse_args()
180 print(f"Opening input file for conversion: {args.inputfile}")
181 if not os.path.isfile(args.inputfile):
182 raise FileNotFoundError("EvtCalc: input .dat file does not exist")
183 if not os.path.isdir(args.outputdir):
184 print(f"Warning: The specified directory {args.outputdir} does not exist. Creating it now.")
185 command = f"mkdir {args.outputdir}"
186 os.system(command)
187 outputfile = convert_file(infile=args.inputfile, outdir=args.outputdir)
188 print(f"{args.inputfile} successfully converted to {outputfile}.")
189
190
191if __name__ == "__main__":
192 main()
parse_file(str infile)
str|None convert_file(infile, outdir)
None check_consistency_infile(nvars, ncols)