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
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
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