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
28from prompt
import ValidationSettings
30settings = ValidationSettings(name=
"CDC dedx",
34 "GT":
"data_prompt_rel09",
35 "payload_boundaries": []
39def get_latest_calibration_dir(base_dir, cal_name):
44 for idir
in os.listdir(base_dir):
46 match = re.fullmatch(rf
"{re.escape(cal_name)}(\d+)", idir)
51 idx = int(match.group(1))
57 if latest_dir
is None:
58 basf2.B2FATAL(f
"No calibration directory found for {cal_name}")
60 basf2.B2INFO(f
"Using latest calibration directory: {latest_dir}")
62 return os.path.join(base_dir, latest_dir)
65def save_to_pdf(pdf, fig):
71def read_txt(filepath, columns, sep=r"\s+"):
72 if not os.path.exists(filepath):
73 basf2.B2ERROR(f
"File not found: {filepath}")
75 return pd.read_csv(filepath, sep=sep, header=
None, names=columns)
78def make_pdf_path(prefix, suffix):
79 pdf_path = os.path.join(
"plots",
"validation", f
"{prefix}_{suffix}.pdf")
80 os.makedirs(os.path.dirname(pdf_path), exist_ok=
True)
84def get_positive_minmax(series):
85 positive = series[series > 0]
86 ymin = positive.min()
if not positive.empty
else series.min()
91def rungain_validation(path, suffix):
92 val_path = os.path.join(path,
"plots",
"run", f
"dedx_vs_run_{suffix}.txt")
93 df = read_txt(val_path, [
"run",
"mean",
"mean_err",
"reso",
"reso_err"])
97 df[
'run'] = df[
'run'].astype(str)
99 pdf_path = make_pdf_path(
"dedx_vs_run", suffix)
101 with PdfPages(pdf_path)
as pdf:
102 fig, ax = plt.subplots(1, 2, figsize=(20, 6))
104 space = max(10, min(50, int(200 / max(n, 1))))
107 ymin, ymax = get_positive_minmax(df[
'mean'])
108 pc.hist(y_min=ymin-0.02, y_max=ymax+0.02, xlabel=
"Run range", ylabel=
"dE/dx mean", space=space, ax=ax[0])
109 ax[0].errorbar(df[
'run'], df[
'mean'], yerr=df[
'mean_err'], fmt=
'*', markersize=8, rasterized=
True, label=
'Bhabha mean')
110 ax[0].legend(fontsize=12)
111 ax[0].set_title(
'dE/dx Mean vs Run', fontsize=14)
114 ymin, ymax = get_positive_minmax(df[
'reso'])
115 pc.hist(y_min=ymin-0.01, y_max=ymax+0.01, xlabel=
"Run range", ylabel=
"dE/dx reso", space=space, ax=ax[1])
116 ax[1].errorbar(df[
'run'], df[
'reso'], yerr=df[
'reso_err'], fmt=
'*', markersize=8, rasterized=
True, label=
'Bhabha reso')
117 ax[1].legend(fontsize=12)
118 ax[1].set_title(
'dE/dx Resolution vs Run', fontsize=14)
120 fig.suptitle(
"dE/dx vs Run", fontsize=20)
121 save_to_pdf(pdf, fig)
124def wiregain_validation(path, suffix):
126 val_path_gwire = os.path.join(path,
"plots",
"wire", f
"dedx_mean_gwire_{suffix}.txt")
127 val_path_bwire = os.path.join(path,
"plots",
"wire", f
"dedx_mean_badwire_{suffix}.txt")
128 val_path_layer = os.path.join(path,
"plots",
"wire", f
"dedx_mean_layer_{suffix}.txt")
130 df_gwire = read_txt(val_path_gwire, [
"wire",
"mean"])
131 df_bwire = read_txt(val_path_bwire, [
"wire",
"mean"])
132 df_layer = read_txt(val_path_layer, [
"layer",
"mean",
"gmean"])
134 if df_gwire
is None or df_bwire
is None or df_layer
is None:
137 pdf_path = make_pdf_path(
"dedx_vs_wire_layer", suffix)
139 with PdfPages(pdf_path)
as pdf:
140 fig, ax = plt.subplots(2, 2, figsize=(20, 12))
142 ymin, ymax = get_positive_minmax(df_gwire[
'mean'])
144 pc.hist(y_min=ymin-0.05, y_max=ymax+0.05, xlabel=
"Wire", ylabel=
"dE/dx mean", space=1000, ax=ax[0, 0])
145 ax[0, 0].
plot(df_gwire[
'wire'], df_gwire[
'mean'],
'*', markersize=5, rasterized=
True)
146 ax[0, 0].set_title(
'dE/dx Mean vs good Wire', fontsize=14)
148 ymin, ymax = get_positive_minmax(df_bwire[
'mean'])
150 pc.hist(y_min=ymin-0.05, y_max=ymax+0.05, xlabel=
"Wire", ylabel=
"dE/dx mean", space=1000, ax=ax[1, 0])
151 ax[1, 0].
plot(df_bwire[
'wire'], df_bwire[
'mean'],
'*', markersize=5, rasterized=
True)
152 ax[1, 0].set_title(
'dE/dx Mean vs bad Wire', fontsize=14)
154 ymin, ymax = get_positive_minmax(df_layer[
'mean'])
156 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])
157 ax[0, 1].
plot(df_layer[
'layer'], df_layer[
'mean'],
'*', markersize=10, rasterized=
True)
158 ax[0, 1].set_title(
'dE/dx Mean vs Layer', fontsize=14)
160 ymin, ymax = get_positive_minmax(df_layer[
'gmean'])
161 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])
162 ax[1, 1].
plot(df_layer[
'layer'], df_layer[
'gmean'],
'*', markersize=10, rasterized=
True)
163 ax[1, 1].set_title(
'dE/dx Mean vs Layer (good wires)', fontsize=14)
165 fig.suptitle(f
"dE/dx vs #wire {suffix}", fontsize=20)
166 save_to_pdf(pdf, fig)
169def cosgain_validation(path, suffix):
170 val_path_el = os.path.join(path,
"plots",
"costh", f
"dedx_vs_cos_electrons_{suffix}.txt")
171 val_path_po = os.path.join(path,
"plots",
"costh", f
"dedx_vs_cos_positrons_{suffix}.txt")
173 df_el = read_txt(val_path_el, [
"cos",
"mean",
"mean_err",
"reso",
"reso_err"])
174 df_po = read_txt(val_path_po, [
"cos",
"mean",
"mean_err",
"reso",
"reso_err"])
176 if df_el
is None or df_po
is None:
180 df_el = df_el.sort_values(by=
'cos').reset_index(drop=
True)
181 df_po = df_po.sort_values(by=
'cos').reset_index(drop=
True)
184 mean_avg = (df_el[
'mean'] + df_po[
'mean']) / 2
185 err_avg = 0.5 * np.sqrt(df_el[
'mean_err']**2 + df_po[
'mean_err']**2)
186 df_sum = pd.DataFrame({
'cos': df_el[
'cos'],
'mean_sum': mean_avg,
'err_avg': err_avg})
188 pdf_path = make_pdf_path(
"dedx_vs_cosine", suffix)
190 with PdfPages(pdf_path)
as pdf:
191 fig, ax = plt.subplots(1, 2, figsize=(20, 6))
193 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])
197 yerr=df_el[
'mean_err'],
205 yerr=df_po[
'mean_err'],
210 ax[0].errorbar(df_sum[
'cos'], df_sum[
'mean_sum'], yerr=df_sum[
'err_avg'], fmt=
'*',
211 markersize=10, rasterized=
True, label=
r'average of e^{+} and e^{-}')
212 ax[0].legend(fontsize=17)
213 ax[0].set_title(
'dE/dx Mean vs cosine', fontsize=14)
216 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])
220 yerr=df_el[
'reso_err'],
228 yerr=df_po[
'reso_err'],
233 ax[1].legend(fontsize=17)
234 ax[1].set_title(
'dE/dx Resolution vs cosine', fontsize=14)
236 fig.suptitle(fr
"dE/dx vs cos$\theta$ {suffix}", fontsize=20)
237 save_to_pdf(pdf, fig)
240def injection_validation(path, suffix):
242 cols = [
"var",
"bin",
"mean",
"mean_err",
"reso",
"reso_err"]
244 val_path_ler = os.path.join(path,
"plots",
"injection", f
"dedx_vs_inj_ler_{suffix}.txt")
245 val_path_her = os.path.join(path,
"plots",
"injection", f
"dedx_vs_inj_her_{suffix}.txt")
247 df_ler = read_txt(val_path_ler, cols)
248 df_her = read_txt(val_path_her, cols)
251 val_path_ler_nocor = os.path.join(path,
"plots",
"injection", f
"dedx_vs_inj_nocor_ler_{suffix}.txt")
252 val_path_her_nocor = os.path.join(path,
"plots",
"injection", f
"dedx_vs_inj_nocor_her_{suffix}.txt")
254 df_ler_nocor = read_txt(val_path_ler_nocor, cols)
255 df_her_nocor = read_txt(val_path_her_nocor, cols)
257 if df_ler
is None or df_her
is None or df_ler_nocor
is None or df_her_nocor
is None:
260 for df
in [df_ler, df_her, df_ler_nocor, df_her_nocor]:
261 df[
"bin"] = df[
"bin"].astype(str)
263 pdf_path = make_pdf_path(
"dedx_mean_inj", suffix)
265 with PdfPages(pdf_path)
as pdf:
267 fig, ax = plt.subplots(2, 1, figsize=(18, 10), sharex=
True)
269 ymin, ymax = get_positive_minmax(
270 pd.concat([df_ler[
"mean"], df_her[
"mean"]])
273 pc.hist(y_min=ymin - 0.01, y_max=ymax + 0.01,
274 xlabel=
"", ylabel=
"dE/dx mean",
277 ax[0].errorbar(df_ler[
'bin'], df_ler[
'mean'], yerr=df_ler[
'mean_err'],
278 fmt=
'*', markersize=10, rasterized=
True, label=
'LER')
279 ax[0].errorbar(df_her[
'bin'], df_her[
'mean'], yerr=df_her[
'mean_err'],
280 fmt=
'*', markersize=10, rasterized=
True, label=
'HER')
282 ax[0].legend(fontsize=14)
283 ax[0].set_title(
"Corrected", fontsize=16)
285 all_means = pd.concat([
286 df_ler[
"mean"], df_her[
"mean"],
287 df_ler_nocor[
"mean"], df_her_nocor[
"mean"]
290 positive_means = all_means[all_means > 0]
291 ymin2 = positive_means.min()
if not positive_means.empty
else all_means.min()
292 ymax2 = all_means.max()
294 pc.hist(y_min=ymin2 - 0.01, y_max=ymax2 + 0.01,
295 xlabel=
"injection time", ylabel=
"dE/dx mean",
299 (
"LER corr", df_ler,
"o"),
300 (
"HER corr", df_her,
"s"),
301 (
"LER no corr", df_ler_nocor,
"^"),
302 (
"HER no corr", df_her_nocor,
"D"),
305 for label, df, marker
in datasets:
306 ax[1].errorbar(df[
'bin'], df[
'mean'], yerr=df[
'mean_err'],
307 fmt=marker, markersize=6, rasterized=
True, label=label)
309 ax[1].legend(fontsize=12)
310 ax[1].set_title(
"Corrected vs No correction", fontsize=16)
312 fig.suptitle(f
"dE/dx vs Injection time {suffix}", fontsize=20)
314 plt.tight_layout(rect=[0, 0, 1, 0.96])
315 save_to_pdf(pdf, fig)
318def mom_validation(path, suffix):
322 "cos$\\theta > 0.0$",
323 "cos$\\theta < 0.0$",
324 "cos$\\theta \\leq -0.8$",
325 "cos$\\theta > -0.8$ and $\\cos\\theta \\leq -0.6$",
326 "cos$\\theta > -0.6$ and $\\cos\\theta \\leq -0.4$",
327 "cos$\\theta > -0.4$ and $\\cos\\theta \\leq -0.2$",
328 "cos$\\theta > -0.2$ and $\\cos\\theta \\leq 0$",
329 "cos$\\theta > 0$ and $\\cos\\theta \\leq 0.2$",
330 "cos$\\theta > 0.2$ and $\\cos\\theta \\leq 0.4$",
331 "cos$\\theta > 0.4$ and $\\cos\\theta \\leq 0.6$",
332 "cos$\\theta > 0.6$ and $\\cos\\theta \\leq 0.8$",
338 "low": make_pdf_path(
"dedx_vs_mom", suffix),
339 "high": make_pdf_path(
"dedx_vs_mom", f
"{suffix}_cosbins"),
342 with PdfPages(pdf_paths[
"low"])
as pdf_low, PdfPages(pdf_paths[
"high"])
as pdf_high:
344 cols = [
"mom",
"mean",
"mean_err",
"reso",
"reso_err"]
345 val_path_el = os.path.join(path,
"plots",
"mom", f
"dedx_vs_mom_{i}_elec_{suffix}.txt")
346 val_path_po = os.path.join(path,
"plots",
"mom", f
"dedx_vs_mom_{i}_posi_{suffix}.txt")
348 df_el = read_txt(val_path_el, cols)
349 df_po = read_txt(val_path_po, cols)
351 if df_el
is None or df_po
is None:
356 fig, ax = plt.subplots(2, 2, figsize=(20, 12))
358 ymin, ymax = get_positive_minmax(df_el[
'mean'])
361 {
"xlim": (-7, 7),
"ylim": (ymin-0.01, ymax+0.01),
362 "ylabel":
"dE/dx mean",
"df_col":
"mean",
"err_col":
"mean_err",
363 "title":
"dE/dx Mean vs momentum"},
364 {
"xlim": (-7, 7),
"ylim": (0.04, 0.1),
365 "ylabel":
"dE/dx reso",
"df_col":
"reso",
"err_col":
"reso_err",
366 "title":
"dE/dx resolution vs momentum"},
367 {
"xlim": (-3, 3),
"ylim": (ymin-0.01, ymax+0.01),
368 "ylabel":
"dE/dx mean",
"df_col":
"mean",
"err_col":
"mean_err",
369 "title":
"dE/dx Mean vs momentum (zoomed)"},
370 {
"xlim": (-3, 3),
"ylim": (0.04, 0.1),
371 "ylabel":
"dE/dx reso",
"df_col":
"reso",
"err_col":
"reso_err",
372 "title":
"dE/dx resolution vs momentum (zoomed)"},
375 for ax_i, panel
in zip(ax.flat, panels):
376 pc.hist(x_min=panel[
"xlim"][0], x_max=panel[
"xlim"][1],
377 y_min=panel[
"ylim"][0], y_max=panel[
"ylim"][1],
378 xlabel=
"Momentum", ylabel=panel[
"ylabel"],
381 ax_i.errorbar(df_el[
'mom'], df_el[panel[
"df_col"]],
382 yerr=df_el[panel[
"err_col"]],
383 fmt=
'*', markersize=10, rasterized=
True, label=
'electron')
384 ax_i.errorbar(df_po[
'mom'], df_po[panel[
"df_col"]],
385 yerr=df_po[panel[
"err_col"]],
386 fmt=
'*', markersize=10, rasterized=
True, label=
'positron')
387 ax_i.legend(fontsize=17)
388 ax_i.set_title(panel[
"title"], fontsize=14)
389 if i == 3
and panel[
"df_col"] ==
"reso":
390 ymin, ymax = ax_i.get_ylim()
391 ax_i.set_ylim(ymin, ymax * 1.5)
393 fig.suptitle(f
"dE/dx vs Momentum ({cos_labels[i]}) {suffix}", fontsize=20)
398 save_to_pdf(pdf_low, fig)
400 save_to_pdf(pdf_high, fig)
403def oneDcell_validation(path, suffix):
405 val_path_sl0 = os.path.join(path,
"plots",
"oneD", f
"dedx_vs_1D_SL0_{suffix}.txt")
406 val_path_sl1 = os.path.join(path,
"plots",
"oneD", f
"dedx_vs_1D_SL1_{suffix}.txt")
407 val_path_sl2_8 = os.path.join(path,
"plots",
"oneD", f
"dedx_vs_1D_SL2-8_{suffix}.txt")
409 df_sl0 = read_txt(val_path_sl0, [
"enta",
"mean"])
410 df_sl1 = read_txt(val_path_sl1, [
"enta",
"mean"])
411 df_sl2_8 = read_txt(val_path_sl2_8, [
"enta",
"mean"])
413 if df_sl0
is None or df_sl1
is None or df_sl2_8
is None:
416 pdf_path = make_pdf_path(
"dedx_vs_enta", suffix)
418 with PdfPages(pdf_path)
as pdf:
419 fig, ax = plt.subplots(3, 2, figsize=(16, 18))
422 (df_sl0,
"SL0", 0.9, 1.07),
423 (df_sl1,
"SL1", 0.9, 1.07),
424 (df_sl2_8,
"SL2-8", 0.9, 1.07),
427 for i, (df, label, y_min, y_max)
in enumerate(datasets):
428 pc.hist(x_min=-1.5, x_max=1.5, y_min=y_min, y_max=y_max, xlabel=
r"entaRS", ylabel=
"dE/dx mean", space=0.3, ax=ax[i, 0])
429 ax[i, 0].
plot(df[
"enta"], df[
"mean"],
"-", markersize=10, rasterized=
True, label=label)
430 ax[i, 0].legend(fontsize=17)
431 ax[i, 0].set_title(f
"dE/dx Mean vs entaRS ({label})", fontsize=14)
433 pc.hist(x_min=-0.2, x_max=0.2, y_min=y_min, y_max=y_max, xlabel=
r"entaRS", ylabel=
"dE/dx mean", space=0.03, ax=ax[i, 1])
434 ax[i, 1].
plot(df[
"enta"], df[
"mean"],
"-", markersize=10, rasterized=
True, label=label)
435 ax[i, 1].legend(fontsize=17)
436 ax[i, 1].set_title(f
"dE/dx Mean vs entaRS ({label}) zoom", fontsize=14)
438 fig.suptitle(f
"dE/dx vs entaRS {suffix}", fontsize=20)
439 save_to_pdf(pdf, fig)
442def run_validation(job_path, input_data_path, requested_iov, expert_config, **kwargs):
444 Makes validation plots
445 :job_path: path to cdcdedx calibration output
446 :input_data_path: path to the input files
447 :requested_iov: required argument
448 :expert_config: required argument
450 os.makedirs(
'plots/validation', exist_ok=
True)
451 os.makedirs(
'plots/constant', exist_ok=
True)
453 expert_config = json.loads(expert_config)
454 GT = expert_config[
"GT"]
456 basf2.B2INFO(
"Starting validation...")
459 (
"rungain",
"run gain", rg.getRunGain),
460 (
"coscorr",
"coscorr", pc.process_cosgain),
461 (
"wiregain",
"wire gain", pw.process_wiregain),
462 (
"onedcell",
"1D gain", oned.process_onedgain),
465 for dirname, label, function
in payloads:
467 basf2.B2INFO(f
"Processing {label} payloads...")
469 caldir = get_latest_calibration_dir(job_path, dirname)
471 dbpath = os.path.join(caldir,
"outputdb")
475 basf2.B2INFO(
"Generating validation plots...")
476 val_path = os.path.join(job_path,
'validation0',
'0',
'algorithm_output')
479 (
"rungain validation plots", rungain_validation),
480 (
"wire gain validation plots", wiregain_validation),
481 (
"cosine correction validation plots", cosgain_validation),
482 (
"injection time validation plots", injection_validation),
483 (
"momentum validation plots", mom_validation),
484 (
"1D validation plots", oneDcell_validation),
487 if isinstance(requested_iov, str):
488 requested_iov = json.loads(requested_iov)
490 from caf.utils
import ExpRun, IoV
491 requested_iov = IoV(*requested_iov)
493 payload_boundaries = [ExpRun(requested_iov.exp_low, requested_iov.run_low)]
494 payload_boundaries.extend([ExpRun(*boundary)
for boundary
in expert_config[
"payload_boundaries"]])
495 basf2.B2INFO(f
"Expert set payload boundaries are: {expert_config['payload_boundaries']}")
497 for exp_run
in payload_boundaries:
498 suffix = f
"e{exp_run.exp}_r{exp_run.run}"
499 for msg, func
in validators:
500 basf2.B2INFO(f
"Processing {msg} for {suffix}...")
501 func(val_path, suffix)
503 source_path = os.path.join(job_path,
'validation0',
'0',
'algorithm_output',
'plots')
504 shutil.copy(source_path+f
"/costh/dedxpeaks_vs_cos_{suffix}.pdf",
'plots/validation/')
506 shutil.copy(source_path+f
"/mom/dedxpeaks_vs_mom_{suffix}.pdf",
'plots/validation/')
509if __name__ ==
"__main__":