4"""Convert files from EventCalc to ROOT format."""
8from argparse
import ArgumentParser
16 Parse the given text file and extracts process type, sample points,
and variables.
19 infile (str): Path to the input text file.
22 tuple: A tuple containing process type (str), sample points (int),
and a list of numpy arrays
for each variable.
25 with open(infile)
as file:
26 lines = file.readlines()
35 if line.startswith(
"#<"):
37 data = np.loadtxt(current_block)
38 variables = [data[:, i]
for i
in range(data.shape[1])]
41 process_type = header.split(
";")[0].split(
"=")[1]
43 sampled_points = int(header.split(
";")[1].split(
"=")[1][:-1])
45 parsed_data.append((process_type, sampled_points, variables))
47 current_block.append(line.strip())
50 data = np.loadtxt(current_block)
51 variables = [data[:, i]
for i
in range(data.shape[1])]
52 parsed_data.append((process_type, sampled_points, variables))
56 except FileNotFoundError:
57 print(f
"- convertEvtCalc - Error: The file {infile} was not found.")
58 return None,
None,
None
59 except Exception
as e:
60 print(f
"- convertEvtCalc - An error occurred: {e}")
61 return None,
None,
None
66 Check the consistency between number of columns in the input file (ncols)
and variables (nvars).
69 nvars, ncols (int
or float): The value to be checked. Must be equal.
73 raise ValueError(
"Nr of variables does not match input file.")
79 Create a ROOT file with a TTree containing the variables
from the parsed input text file.
82 infile (str): Path to the input text file.
83 outdir (str): Name of the output directory, the filename will be the same
84 as inputfile
with the .dat replaced
with .root.
106 fname = infile.split(
"/")[-1]
107 command = f
"cp {infile} {outdir}/{fname}"
109 if os.path.isfile(f
"{outdir}/{fname}"):
110 print(f
"Warning: The file {outdir}/{fname} already exists.")
114 infile = f
"{outdir}/{fname}"
116 outfile = infile.split(
".dat")[0] +
".root"
117 ncols = len(parsed_data[0][2])
119 remaining_vars = ncols - len(vars_names)
121 if (remaining_vars % nvardau) != 0:
122 raise ValueError(
"- convertEvtCalc - Error: number of daughters is not exact.")
124 ndau = remaining_vars // nvardau
125 print(f
"- convertEvtCalc - Max multiplicity of daughters: {ndau}")
127 vars_names.extend(f
"{var}{i}" for i
in range(1, ndau + 1)
for var
in daughter_vars)
131 except ValueError
as e:
132 print(f
"- convertEvtCalc - Error: {e}")
135 vars_names += [
"ndau"]
138 root_file = r.TFile.Open(outfile,
"RECREATE")
139 tree = r.TTree(
"LLP_tree",
"LLP_tree")
142 for var
in vars_names:
143 branch_f[var] = np.zeros(1, dtype=float)
144 tree.Branch(var, branch_f[var], f
"{var}/D")
146 for pt, sp, vars
in parsed_data:
147 for row
in zip(*vars):
148 for i, value
in enumerate(row):
149 if i < len(vars_names) - 1:
150 branch_f[vars_names[i]][0] = value
151 branch_f[
"ndau"][0] = ndau / 1.0
156 print(f
"- convertEvtCalc - ROOT file '{outfile}' created successfully.")
161 """Convert files from EventCalc to ROOT format."""
162 parser = ArgumentParser(description=__doc__)
166 help=
"""Simulation results to use as input."""
167 """Supports retrieving file from EOS via the XRootD protocol.""",
170 parser.add_argument(
"-o",
"--outputdir", help=
"""Output directory, must exist.""", default=
".")
171 args = parser.parse_args()
172 print(f
"Opening input file for conversion: {args.inputfile}")
173 if not os.path.isfile(args.inputfile):
174 raise FileNotFoundError(
"EvtCalc: input .dat file does not exist")
175 if not os.path.isdir(args.outputdir):
176 print(f
"Warning: The specified directory {args.outputdir} does not exist. Creating it now.")
177 command = f
"mkdir {args.outputdir}"
179 outputfile =
convert_file(infile=args.inputfile, outdir=args.outputdir)
180 print(f
"{args.inputfile} successfully converted to {outputfile}.")
183if __name__ ==
"__main__":
str|None convert_file(infile, outdir)
None check_consistency_infile(nvars, ncols)
def parse_file(str infile)
int open(const char *, int)
Opens a file descriptor.