10Validation plots for CDC dedx calibration.
16import matplotlib.pyplot
as plt
19from matplotlib.backends.backend_pdf
import PdfPages
22import process_wiregain
as pw
23import process_cosgain
as pc
24import process_onedcell
as oned
25import process_rungain
as rg
27from prompt
import ValidationSettings
29settings = ValidationSettings(name=
"CDC dedx",
33 "GT":
"data_prompt_rel09",
37def save_to_pdf(pdf, fig):
43def read_txt(filepath, columns, sep=r"\s+"):
44 if not os.path.exists(filepath):
45 basf2.B2ERROR(f
"File not found: {filepath}")
47 return pd.read_csv(filepath, sep=sep, header=
None, names=columns)
50def make_pdf_path(prefix, suffix):
51 pdf_path = os.path.join(
"plots",
"validation", f
"{prefix}_{suffix}.pdf")
52 os.makedirs(os.path.dirname(pdf_path), exist_ok=
True)
56def get_positive_minmax(series):
57 positive = series[series > 0]
58 ymin = positive.min()
if not positive.empty
else series.min()
63def rungain_validation(path, suffix):
64 val_path = os.path.join(path,
"plots",
"run", f
"dedx_vs_run_{suffix}.txt")
65 df = read_txt(val_path, [
"run",
"mean",
"mean_err",
"reso",
"reso_err"])
69 df[
'run'] = df[
'run'].astype(str)
71 pdf_path = make_pdf_path(
"dedx_vs_run", suffix)
73 with PdfPages(pdf_path)
as pdf:
74 fig, ax = plt.subplots(1, 2, figsize=(20, 6))
77 ymin, ymax = get_positive_minmax(df[
'mean'])
78 pc.hist(y_min=ymin-0.02, y_max=ymax+0.02, xlabel=
"Run range", ylabel=
"dE/dx mean", space=30, ax=ax[0])
79 ax[0].errorbar(df[
'run'], df[
'mean'], yerr=df[
'mean_err'], fmt=
'*', markersize=8, rasterized=
True, label=
'Bhabha mean')
80 ax[0].legend(fontsize=12)
81 ax[0].set_title(
'dE/dx Mean vs Run', fontsize=14)
84 ymin, ymax = get_positive_minmax(df[
'reso'])
85 pc.hist(y_min=ymin-0.01, y_max=ymax+0.01, xlabel=
"Run range", ylabel=
"dE/dx reso", space=30, ax=ax[1])
86 ax[1].errorbar(df[
'run'], df[
'reso'], yerr=df[
'reso_err'], fmt=
'*', markersize=8, rasterized=
True, label=
'Bhabha reso')
87 ax[1].legend(fontsize=12)
88 ax[1].set_title(
'dE/dx Resolution vs Run', fontsize=14)
90 fig.suptitle(
"dE/dx vs Run", fontsize=20)
94def wiregain_validation(path, suffix):
96 val_path_gwire = os.path.join(path,
"plots",
"wire", f
"dedx_mean_gwire_{suffix}.txt")
97 val_path_bwire = os.path.join(path,
"plots",
"wire", f
"dedx_mean_badwire_{suffix}.txt")
98 val_path_layer = os.path.join(path,
"plots",
"wire", f
"dedx_mean_layer_{suffix}.txt")
100 df_gwire = read_txt(val_path_gwire, [
"wire",
"mean"])
101 df_bwire = read_txt(val_path_bwire, [
"wire",
"mean"])
102 df_layer = read_txt(val_path_layer, [
"layer",
"mean",
"gmean"])
104 if df_gwire
is None or df_bwire
is None or df_layer
is None:
107 pdf_path = make_pdf_path(
"dedx_vs_wire_layer", suffix)
109 with PdfPages(pdf_path)
as pdf:
110 fig, ax = plt.subplots(2, 2, figsize=(20, 12))
112 ymin, ymax = get_positive_minmax(df_gwire[
'mean'])
114 pc.hist(y_min=ymin-0.05, y_max=ymax+0.05, xlabel=
"Wire", ylabel=
"dE/dx mean", space=1000, ax=ax[0, 0])
115 ax[0, 0].
plot(df_gwire[
'wire'], df_gwire[
'mean'],
'*', markersize=5, rasterized=
True)
116 ax[0, 0].set_title(
'dE/dx Mean vs good Wire', fontsize=14)
118 ymin, ymax = get_positive_minmax(df_bwire[
'mean'])
120 pc.hist(y_min=ymin-0.05, y_max=ymax+0.05, xlabel=
"Wire", ylabel=
"dE/dx mean", space=1000, ax=ax[1, 0])
121 ax[1, 0].
plot(df_bwire[
'wire'], df_bwire[
'mean'],
'*', markersize=5, rasterized=
True)
122 ax[1, 0].set_title(
'dE/dx Mean vs bad Wire', fontsize=14)
124 ymin, ymax = get_positive_minmax(df_layer[
'mean'])
126 pc.hist(x_min=0, x_max=56, y_min=ymin-0.05, y_max=ymax+0.05, xlabel=
"Layer", ylabel=
"dE/dx mean", space=3, ax=ax[0, 1])
127 ax[0, 1].
plot(df_layer[
'layer'], df_layer[
'mean'],
'*', markersize=10, rasterized=
True)
128 ax[0, 1].set_title(
'dE/dx Mean vs Layer', fontsize=14)
130 ymin, ymax = get_positive_minmax(df_layer[
'gmean'])
131 pc.hist(x_min=0, x_max=56, y_min=ymin-0.02, y_max=ymax+0.02, xlabel=
"Layer", ylabel=
"dE/dx mean", space=3, ax=ax[1, 1])
132 ax[1, 1].
plot(df_layer[
'layer'], df_layer[
'gmean'],
'*', markersize=10, rasterized=
True)
133 ax[1, 1].set_title(
'dE/dx Mean vs Layer (good wires)', fontsize=14)
135 fig.suptitle(
"dE/dx vs #wire", fontsize=20)
136 save_to_pdf(pdf, fig)
139def cosgain_validation(path, suffix):
140 val_path_el = os.path.join(path,
"plots",
"costh", f
"dedx_vs_cos_electrons_{suffix}.txt")
141 val_path_po = os.path.join(path,
"plots",
"costh", f
"dedx_vs_cos_positrons_{suffix}.txt")
143 df_el = read_txt(val_path_el, [
"cos",
"mean",
"mean_err",
"reso",
"reso_err"])
144 df_po = read_txt(val_path_po, [
"cos",
"mean",
"mean_err",
"reso",
"reso_err"])
146 if df_el
is None or df_po
is None:
150 df_el = df_el.sort_values(by=
'cos').reset_index(drop=
True)
151 df_po = df_po.sort_values(by=
'cos').reset_index(drop=
True)
154 mean_avg = (df_el[
'mean'] + df_po[
'mean']) / 2
155 err_avg = 0.5 * np.sqrt(df_el[
'mean_err']**2 + df_po[
'mean_err']**2)
156 df_sum = pd.DataFrame({
'cos': df_el[
'cos'],
'mean_sum': mean_avg,
'err_avg': err_avg})
158 pdf_path = make_pdf_path(
"dedx_vs_cosine", suffix)
160 with PdfPages(pdf_path)
as pdf:
161 fig, ax = plt.subplots(1, 2, figsize=(20, 6))
163 pc.hist(x_min=-1.0, x_max=1.0, y_min=0.96, y_max=1.03, xlabel=
r"cos#theta", ylabel=
"dE/dx mean", space=0.1, ax=ax[0])
167 yerr=df_el[
'mean_err'],
175 yerr=df_po[
'mean_err'],
180 ax[0].errorbar(df_sum[
'cos'], df_sum[
'mean_sum'], yerr=df_sum[
'err_avg'], fmt=
'*',
181 markersize=10, rasterized=
True, label=
r'average of e^{+} and e^{-}')
182 ax[0].legend(fontsize=17)
183 ax[0].set_title(
'dE/dx Mean vs cosine', fontsize=14)
186 pc.hist(x_min=-1.0, x_max=1.0, y_min=0.04, y_max=0.13, xlabel=
r"cos#theta", ylabel=
"dE/dx reso", space=0.1, ax=ax[1])
190 yerr=df_el[
'reso_err'],
198 yerr=df_po[
'reso_err'],
203 ax[1].legend(fontsize=17)
204 ax[1].set_title(
'dE/dx Resolution vs cosine', fontsize=14)
206 fig.suptitle(
r"dE/dx vs cos$\theta$", fontsize=20)
207 save_to_pdf(pdf, fig)
210def injection_validation(path, suffix):
212 cols = [
"var",
"bin",
"mean",
"mean_err",
"reso",
"reso_err"]
214 val_path_ler = os.path.join(path,
"plots",
"injection", f
"dedx_vs_inj_ler_{suffix}.txt")
215 val_path_her = os.path.join(path,
"plots",
"injection", f
"dedx_vs_inj_her_{suffix}.txt")
217 df_ler = read_txt(val_path_ler, cols)
218 df_her = read_txt(val_path_her, cols)
221 val_path_ler_nocor = os.path.join(path,
"plots",
"injection", f
"dedx_vs_inj_nocor_ler_{suffix}.txt")
222 val_path_her_nocor = os.path.join(path,
"plots",
"injection", f
"dedx_vs_inj_nocor_her_{suffix}.txt")
224 df_ler_nocor = read_txt(val_path_ler_nocor, cols)
225 df_her_nocor = read_txt(val_path_her_nocor, cols)
227 if df_ler
is None or df_her
is None or df_ler_nocor
is None or df_her_nocor
is None:
230 for df
in [df_ler, df_her, df_ler_nocor, df_her_nocor]:
231 df[
"bin"] = df[
"bin"].astype(str)
233 pdf_path = make_pdf_path(
"dedx_mean_inj", suffix)
235 with PdfPages(pdf_path)
as pdf:
237 fig, ax = plt.subplots(1, 1, figsize=(20, 6))
239 ymin, ymax = get_positive_minmax(df_ler[
'mean'])
241 pc.hist(y_min=ymin - 0.01, y_max=ymax + 0.01,
242 xlabel=
"injection time", ylabel=
"dE/dx mean",
245 ax.errorbar(df_ler[
'bin'], df_ler[
'mean'], yerr=df_ler[
'mean_err'],
246 fmt=
'*', markersize=10, rasterized=
True, label=
'LER')
247 ax.errorbar(df_her[
'bin'], df_her[
'mean'], yerr=df_her[
'mean_err'],
248 fmt=
'*', markersize=10, rasterized=
True, label=
'HER')
249 ax.legend(fontsize=19)
251 fig.suptitle(
"dE/dx vs Injection time", fontsize=20)
252 save_to_pdf(pdf, fig)
255 fig, ax = plt.subplots(1, 1, figsize=(20, 6))
257 all_means = pd.concat([
258 df_ler[
"mean"], df_her[
"mean"],
259 df_ler_nocor[
"mean"], df_her_nocor[
"mean"]
261 positive_means = all_means[all_means > 0]
263 ymin2 = positive_means.min()
if not positive_means.empty
else all_means.min()
264 ymax2 = all_means.max()
266 pc.hist(y_min=ymin2 - 0.01, y_max=ymax2 + 0.01,
267 xlabel=
"injection time", ylabel=
"dE/dx mean",
271 (
"LER corr", df_ler,
"o"),
272 (
"HER corr", df_her,
"s"),
273 (
"LER no corr", df_ler_nocor,
"o"),
274 (
"HER no corr", df_her_nocor,
"s"),
277 for label, df, marker
in datasets:
278 ax.errorbar(df[
'bin'], df[
'mean'], yerr=df[
'mean_err'],
279 fmt=marker, markersize=6, rasterized=
True, label=label)
280 ax.legend(fontsize=19)
281 fig.suptitle(
"dE/dx vs Injection time: corrected vs no correction", fontsize=20)
282 save_to_pdf(pdf, fig)
285def mom_validation(path, suffix):
289 "cos$\\theta > 0.0$",
290 "cos$\\theta < 0.0$",
291 "cos$\\theta \\leq -0.8$",
292 "cos$\\theta > -0.8$ and $\\cos\\theta \\leq -0.6$",
293 "cos$\\theta > -0.6$ and $\\cos\\theta \\leq -0.4$",
294 "cos$\\theta > -0.4$ and $\\cos\\theta \\leq -0.2$",
295 "cos$\\theta > -0.2$ and $\\cos\\theta \\leq 0$",
296 "cos$\\theta > 0$ and $\\cos\\theta \\leq 0.2$",
297 "cos$\\theta > 0.2$ and $\\cos\\theta \\leq 0.4$",
298 "cos$\\theta > 0.4$ and $\\cos\\theta \\leq 0.6$",
299 "cos$\\theta > 0.6$ and $\\cos\\theta \\leq 0.8$",
305 "low": make_pdf_path(
"dedx_vs_mom", suffix),
306 "high": make_pdf_path(
"dedx_vs_mom", f
"{suffix}_cosbins"),
309 with PdfPages(pdf_paths[
"low"])
as pdf_low, PdfPages(pdf_paths[
"high"])
as pdf_high:
311 cols = [
"mom",
"mean",
"mean_err",
"reso",
"reso_err"]
312 val_path_el = os.path.join(path,
"plots",
"mom", f
"dedx_vs_mom_{i}_elec_{suffix}.txt")
313 val_path_po = os.path.join(path,
"plots",
"mom", f
"dedx_vs_mom_{i}_posi_{suffix}.txt")
315 df_el = read_txt(val_path_el, cols)
316 df_po = read_txt(val_path_po, cols)
318 if df_el
is None or df_po
is None:
323 fig, ax = plt.subplots(2, 2, figsize=(20, 12))
325 ymin, ymax = get_positive_minmax(df_el[
'mean'])
328 {
"xlim": (-7, 7),
"ylim": (ymin-0.01, ymax+0.01),
329 "ylabel":
"dE/dx mean",
"df_col":
"mean",
"err_col":
"mean_err",
330 "title":
"dE/dx Mean vs momentum"},
331 {
"xlim": (-7, 7),
"ylim": (0.04, 0.1),
332 "ylabel":
"dE/dx reso",
"df_col":
"reso",
"err_col":
"reso_err",
333 "title":
"dE/dx resolution vs momentum"},
334 {
"xlim": (-3, 3),
"ylim": (ymin-0.01, ymax+0.01),
335 "ylabel":
"dE/dx mean",
"df_col":
"mean",
"err_col":
"mean_err",
336 "title":
"dE/dx Mean vs momentum (zoomed)"},
337 {
"xlim": (-3, 3),
"ylim": (0.04, 0.1),
338 "ylabel":
"dE/dx reso",
"df_col":
"reso",
"err_col":
"reso_err",
339 "title":
"dE/dx resolution vs momentum (zoomed)"},
342 for ax_i, panel
in zip(ax.flat, panels):
343 pc.hist(x_min=panel[
"xlim"][0], x_max=panel[
"xlim"][1],
344 y_min=panel[
"ylim"][0], y_max=panel[
"ylim"][1],
345 xlabel=
"Momentum", ylabel=panel[
"ylabel"],
348 ax_i.errorbar(df_el[
'mom'], df_el[panel[
"df_col"]],
349 yerr=df_el[panel[
"err_col"]],
350 fmt=
'*', markersize=10, rasterized=
True, label=
'electron')
351 ax_i.errorbar(df_po[
'mom'], df_po[panel[
"df_col"]],
352 yerr=df_po[panel[
"err_col"]],
353 fmt=
'*', markersize=10, rasterized=
True, label=
'positron')
354 ax_i.legend(fontsize=17)
355 ax_i.set_title(panel[
"title"], fontsize=14)
356 if i == 3
and panel[
"df_col"] ==
"reso":
357 ymin, ymax = ax_i.get_ylim()
358 ax_i.set_ylim(ymin, ymax * 1.5)
360 fig.suptitle(f
"dE/dx vs Momentum ({cos_labels[i]})", fontsize=20)
365 save_to_pdf(pdf_low, fig)
367 save_to_pdf(pdf_high, fig)
370def oneDcell_validation(path, suffix):
372 val_path_il = os.path.join(path,
"plots",
"oneD", f
"dedx_vs_1D_IL_{suffix}.txt")
373 val_path_ol = os.path.join(path,
"plots",
"oneD", f
"dedx_vs_1D_OL_{suffix}.txt")
375 df_il = read_txt(val_path_il, [
"enta",
"mean"])
376 df_ol = read_txt(val_path_ol, [
"enta",
"mean"])
378 if df_il
is None or df_ol
is None:
381 pdf_path = make_pdf_path(
"dedx_vs_enta", suffix)
383 with PdfPages(pdf_path)
as pdf:
384 fig, ax = plt.subplots(2, 2, figsize=(20, 12))
386 pc.hist(x_min=-1.5, x_max=1.5, y_min=0.9, y_max=1.07, xlabel=
r"entaRS", ylabel=
"dE/dx mean", space=0.3, ax=ax[0, 0])
387 ax[0, 0].
plot(df_il[
'enta'], df_il[
'mean'],
'-', markersize=10, rasterized=
True, label=
'IL')
388 ax[0, 0].legend(fontsize=17)
389 ax[0, 0].set_title(
'dE/dx Mean vs entaRS (IL)', fontsize=14)
391 pc.hist(x_min=-1.5, x_max=1.5, y_min=0.9, y_max=1.05, xlabel=
r"entaRS", ylabel=
"dE/dx mean", space=0.3, ax=ax[0, 1])
392 ax[0, 1].
plot(df_ol[
'enta'], df_ol[
'mean'],
'-', markersize=10, rasterized=
True, label=
'OL')
393 ax[0, 1].legend(fontsize=17)
394 ax[0, 1].set_title(
'dE/dx Mean vs entaRS (OL)', fontsize=14)
396 pc.hist(x_min=-0.2, x_max=0.2, y_min=0.9, y_max=1.07, xlabel=
r"entaRS", ylabel=
"dE/dx mean", space=0.02, ax=ax[1, 0])
397 ax[1, 0].
plot(df_il[
'enta'], df_il[
'mean'],
'-', markersize=10, rasterized=
True, label=
'IL')
398 ax[1, 0].legend(fontsize=17)
399 ax[1, 0].set_title(
'dE/dx Mean vs entaRS (IL) zoom', fontsize=14)
401 pc.hist(x_min=-0.2, x_max=0.2, y_min=0.9, y_max=1.05, xlabel=
r"entaRS", ylabel=
"dE/dx mean", space=0.02, ax=ax[1, 1])
402 ax[1, 1].
plot(df_ol[
'enta'], df_ol[
'mean'],
'-', markersize=10, rasterized=
True, label=
'OL')
403 ax[1, 1].legend(fontsize=17)
404 ax[1, 1].set_title(
'dE/dx Mean vs entaRS (OL) zoom', fontsize=14)
406 fig.suptitle(
"dE/dx vs entaRS", fontsize=20)
407 save_to_pdf(pdf, fig)
410def run_validation(job_path, input_data_path, requested_iov, expert_config, **kwargs):
412 Makes validation plots
413 :job_path: path to cdcdedx calibration output
414 :input_data_path: path to the input files
415 :requested_iov: required argument but not used
416 :expert_config: required argument
418 os.makedirs(
'plots/validation', exist_ok=
True)
419 os.makedirs(
'plots/constant', exist_ok=
True)
421 expert_config = json.loads(expert_config)
422 GT = expert_config[
"GT"]
424 basf2.B2INFO(
"Starting validation...")
426 basf2.B2INFO(
"Processing run gain payloads...")
427 gtpath = os.path.join(job_path,
'rungain2',
'outputdb')
428 rg.getRunGain(gtpath, GT)
430 basf2.B2INFO(
"Processing coscorr payloads...")
431 ccpath = os.path.join(job_path,
'coscorr1',
'outputdb')
432 pc.process_cosgain(ccpath, GT)
434 basf2.B2INFO(
"Processing wire gain payloads...")
435 wgpath = os.path.join(job_path,
'wiregain0',
'outputdb')
436 exp_run_dict = pw.process_wiregain(wgpath, GT)
438 basf2.B2INFO(
"Processing 1D gain payloads...")
439 onedpath = os.path.join(job_path,
'onedcell0',
'outputdb')
440 oned.process_onedgain(onedpath, GT)
442 basf2.B2INFO(
"Generating validation plots...")
443 val_path = os.path.join(job_path,
'validation0',
'0',
'algorithm_output')
446 (
"rungain validation plots", rungain_validation),
447 (
"wire gain validation plots", wiregain_validation),
448 (
"cosine correction validation plots", cosgain_validation),
449 (
"injection time validation plots", injection_validation),
450 (
"momentum validation plots", mom_validation),
451 (
"1D validation plots", oneDcell_validation),
454 for exp, run_list
in exp_run_dict.items():
456 suffix = f
"e{exp}_r{run}"
457 for msg, func
in validators:
458 basf2.B2INFO(f
"Processing {msg} for {suffix}...")
459 func(val_path, suffix)
461 source_path = os.path.join(job_path,
'validation0',
'0',
'algorithm_output',
'plots')
462 shutil.copy(source_path+f
"/costh/dedxpeaks_vs_cos_{suffix}.pdf",
'plots/validation/')
464 shutil.copy(source_path+f
"/mom/dedxpeaks_vs_mom_{suffix}.pdf",
'plots/validation/')
467if __name__ ==
"__main__":