77def convert_file(infile, outdir) -> str | None:
78 """
79 Create a ROOT file with a TTree containing the variables from the parsed input text file.
80
81 Parameters:
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.
85 """
86 vars_names = [
87 "px_llp",
88 "py_llp",
89 "pz_llp",
90 "e_llp",
91 "mass_llp",
92 "pdg_llp",
93 "decay_prob",
94 "vx",
95 "vy",
96 "vz",
97 ]
98 daughter_vars = [
99 "px_prod",
100 "py_prod",
101 "pz_prod",
102 "e_prod",
103 "mass_prod",
104 "pdg_prod",
105 ]
106 fname = infile.split("/")[-1]
107 command = f"cp {infile} {outdir}/{fname}"
108
109 if os.path.isfile(f"{outdir}/{fname}"):
110 print(f"Warning: The file {outdir}/{fname} already exists.")
111 else:
112 os.system(command)
113
114 infile = f"{outdir}/{fname}"
115 parsed_data = parse_file(infile)
116 outfile = infile.split(".dat")[0] + ".root"
117 ncols = len(parsed_data[0][2])
118 nvardau = 6
119 remaining_vars = ncols - len(vars_names)
120
121 if (remaining_vars % nvardau) != 0:
122 raise ValueError("- convertEvtCalc - Error: number of daughters is not exact.")
123
124 ndau = remaining_vars // nvardau
125 print(f"- convertEvtCalc - Max multiplicity of daughters: {ndau}")
126
127 vars_names.extend(f"{var}{i}" for i in range(1, ndau + 1) for var in daughter_vars)
128
129 try:
130 check_consistency_infile(nvars=len(vars_names), ncols=ncols)
131 except ValueError as e:
132 print(f"- convertEvtCalc - Error: {e}")
133 sys.exit(1)
134
135 vars_names += ["ndau"]
136
137 if parsed_data:
138 root_file = r.TFile.Open(outfile, "RECREATE")
139 tree = r.TTree("LLP_tree", "LLP_tree")
140
141 branch_f = {}
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")
145
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
152 tree.Fill()
153
154 tree.Write()
155 root_file.Close()
156 print(f"- convertEvtCalc - ROOT file '{outfile}' created successfully.")
157 return outfile
158
159