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 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))
58 except FileNotFoundError:
59 print(f
"- convertEvtCalc - Error: The file {infile} was not found.")
61 except (ValueError, IndexError)
as e:
62 print(f
"- convertEvtCalc - An error occurred: {e}")
81 Create a ROOT file with a TTree containing the variables from the parsed input text file.
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.
108 fname = infile.split(
"/")[-1]
109 command = f
"cp {infile} {outdir}/{fname}"
111 if os.path.isfile(f
"{outdir}/{fname}"):
112 print(f
"Warning: The file {outdir}/{fname} already exists.")
116 infile = f
"{outdir}/{fname}"
118 if parsed_data
is None:
122 print(f
"- convertEvtCalc - Error: no completed blocks found in {infile}.")
124 outfile = infile.split(
".dat")[0] +
".root"
125 ncols = len(parsed_data[0][2])
127 remaining_vars = ncols - len(vars_names)
129 if (remaining_vars % nvardau) != 0:
130 raise ValueError(
"- convertEvtCalc - Error: number of daughters is not exact.")
132 ndau = remaining_vars // nvardau
133 print(f
"- convertEvtCalc - Max multiplicity of daughters: {ndau}")
135 vars_names.extend(f
"{var}{i}" for i
in range(1, ndau + 1)
for var
in daughter_vars)
139 except ValueError
as e:
140 print(f
"- convertEvtCalc - Error: {e}")
143 vars_names += [
"ndau"]
146 root_file = r.TFile.Open(outfile,
"RECREATE")
147 tree = r.TTree(
"LLP_tree",
"LLP_tree")
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")
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
164 print(f
"- convertEvtCalc - ROOT file '{outfile}' created successfully.")
169 """Convert files from EventCalc to ROOT format."""
170 parser = ArgumentParser(description=__doc__)
174 help=
"""Simulation results to use as input."""
175 """Supports retrieving file from EOS via the XRootD protocol.""",
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}"
187 outputfile =
convert_file(infile=args.inputfile, outdir=args.outputdir)
188 print(f
"{args.inputfile} successfully converted to {outputfile}.")