Belle II Software development
cdcdedx_validation.py
1
8
9'''
10Validation plots for CDC dedx calibration.
11'''
12
13import sys
14import os
15import json
16import matplotlib.pyplot as plt
17import pandas as pd
18import numpy as np
19from matplotlib.backends.backend_pdf import PdfPages
20import shutil
21import basf2
22import process_wiregain as pw
23import process_cosgain as pc
24import process_onedcell as oned
25import process_rungain as rg
26import re
27
28from prompt import ValidationSettings
29
30settings = ValidationSettings(name="CDC dedx",
31 description=__doc__,
32 download_files=[],
33 expert_config={
34 "GT": "data_prompt_rel09",
35 "payload_boundaries": []
36 })
37
38
39def get_latest_calibration_dir(base_dir, cal_name):
40
41 latest_idx = -1
42 latest_dir = None
43
44 for idir in os.listdir(base_dir):
45
46 match = re.fullmatch(rf"{re.escape(cal_name)}(\d+)", idir)
47
48 if not match:
49 continue
50
51 idx = int(match.group(1))
52
53 if idx > latest_idx:
54 latest_idx = idx
55 latest_dir = idir
56
57 if latest_dir is None:
58 basf2.B2FATAL(f"No calibration directory found for {cal_name}")
59
60 basf2.B2INFO(f"Using latest calibration directory: {latest_dir}")
61
62 return os.path.join(base_dir, latest_dir)
63
64
65def save_to_pdf(pdf, fig):
66 fig.tight_layout()
67 pdf.savefig(fig)
68 plt.close(fig)
69
70
71def read_txt(filepath, columns, sep=r"\s+"):
72 if not os.path.exists(filepath):
73 basf2.B2ERROR(f"File not found: {filepath}")
74 return None
75 return pd.read_csv(filepath, sep=sep, header=None, names=columns)
76
77
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)
81 return pdf_path
82
83
84def get_positive_minmax(series):
85 positive = series[series > 0]
86 ymin = positive.min() if not positive.empty else series.min()
87 ymax = series.max()
88 return ymin, ymax
89
90
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"])
94 if df is None:
95 return
96
97 df['run'] = df['run'].astype(str)
98
99 pdf_path = make_pdf_path("dedx_vs_run", suffix)
100
101 with PdfPages(pdf_path) as pdf:
102 fig, ax = plt.subplots(1, 2, figsize=(20, 6))
103 n = len(df)
104 space = max(10, min(50, int(200 / max(n, 1))))
105
106 # Mean plot
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)
112
113 # Reso plot
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)
119
120 fig.suptitle("dE/dx vs Run", fontsize=20)
121 save_to_pdf(pdf, fig)
122
123
124def wiregain_validation(path, suffix):
125
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")
129
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"])
133
134 if df_gwire is None or df_bwire is None or df_layer is None:
135 return
136
137 pdf_path = make_pdf_path("dedx_vs_wire_layer", suffix)
138
139 with PdfPages(pdf_path) as pdf:
140 fig, ax = plt.subplots(2, 2, figsize=(20, 12))
141
142 ymin, ymax = get_positive_minmax(df_gwire['mean'])
143
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)
147
148 ymin, ymax = get_positive_minmax(df_bwire['mean'])
149
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)
153
154 ymin, ymax = get_positive_minmax(df_layer['mean'])
155
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)
159
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)
164
165 fig.suptitle(f"dE/dx vs #wire {suffix}", fontsize=20)
166 save_to_pdf(pdf, fig)
167
168
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")
172
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"])
175
176 if df_el is None or df_po is None:
177 return
178
179 # Ensure both dataframes are sorted by 'cos' so addition is element-wise correct
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)
182
183 # New DataFrame with summed means
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})
187
188 pdf_path = make_pdf_path("dedx_vs_cosine", suffix)
189
190 with PdfPages(pdf_path) as pdf:
191 fig, ax = plt.subplots(1, 2, figsize=(20, 6)) # Two plots side-by-side
192 # mean
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])
194 ax[0].errorbar(
195 df_el['cos'],
196 df_el['mean'],
197 yerr=df_el['mean_err'],
198 fmt='*',
199 markersize=10,
200 rasterized=True,
201 label='electron')
202 ax[0].errorbar(
203 df_po['cos'],
204 df_po['mean'],
205 yerr=df_po['mean_err'],
206 fmt='*',
207 markersize=10,
208 rasterized=True,
209 label='positrons')
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)
214
215 # reso
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])
217 ax[1].errorbar(
218 df_el['cos'],
219 df_el['reso'],
220 yerr=df_el['reso_err'],
221 fmt='*',
222 markersize=10,
223 rasterized=True,
224 label='electron')
225 ax[1].errorbar(
226 df_po['cos'],
227 df_po['reso'],
228 yerr=df_po['reso_err'],
229 fmt='*',
230 markersize=10,
231 rasterized=True,
232 label='positrons')
233 ax[1].legend(fontsize=17)
234 ax[1].set_title('dE/dx Resolution vs cosine', fontsize=14)
235
236 fig.suptitle(fr"dE/dx vs cos$\theta$ {suffix}", fontsize=20)
237 save_to_pdf(pdf, fig)
238
239
240def injection_validation(path, suffix):
241
242 cols = ["var", "bin", "mean", "mean_err", "reso", "reso_err"]
243 # corrected files
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")
246
247 df_ler = read_txt(val_path_ler, cols)
248 df_her = read_txt(val_path_her, cols)
249
250 # no-correction files
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")
253
254 df_ler_nocor = read_txt(val_path_ler_nocor, cols)
255 df_her_nocor = read_txt(val_path_her_nocor, cols)
256
257 if df_ler is None or df_her is None or df_ler_nocor is None or df_her_nocor is None:
258 return
259
260 for df in [df_ler, df_her, df_ler_nocor, df_her_nocor]:
261 df["bin"] = df["bin"].astype(str)
262
263 pdf_path = make_pdf_path("dedx_mean_inj", suffix)
264
265 with PdfPages(pdf_path) as pdf:
266
267 fig, ax = plt.subplots(2, 1, figsize=(18, 10), sharex=True)
268
269 ymin, ymax = get_positive_minmax(
270 pd.concat([df_ler["mean"], df_her["mean"]])
271 )
272
273 pc.hist(y_min=ymin - 0.01, y_max=ymax + 0.01,
274 xlabel="", ylabel="dE/dx mean",
275 space=3, ax=ax[0])
276
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')
281
282 ax[0].legend(fontsize=14)
283 ax[0].set_title("Corrected", fontsize=16)
284
285 all_means = pd.concat([
286 df_ler["mean"], df_her["mean"],
287 df_ler_nocor["mean"], df_her_nocor["mean"]
288 ])
289
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()
293
294 pc.hist(y_min=ymin2 - 0.01, y_max=ymax2 + 0.01,
295 xlabel="injection time", ylabel="dE/dx mean",
296 space=3, ax=ax[1])
297
298 datasets = [
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"),
303 ]
304
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)
308
309 ax[1].legend(fontsize=12)
310 ax[1].set_title("Corrected vs No correction", fontsize=16)
311
312 fig.suptitle(f"dE/dx vs Injection time {suffix}", fontsize=20)
313
314 plt.tight_layout(rect=[0, 0, 1, 0.96]) # important to avoid overlap
315 save_to_pdf(pdf, fig)
316
317
318def mom_validation(path, suffix):
319
320 cos_labels = [
321 "acos",
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$",
333 "cos$\\theta > 0.8$"
334 ]
335
336 # Define output PDFs
337 pdf_paths = {
338 "low": make_pdf_path("dedx_vs_mom", suffix),
339 "high": make_pdf_path("dedx_vs_mom", f"{suffix}_cosbins"),
340 }
341
342 with PdfPages(pdf_paths["low"]) as pdf_low, PdfPages(pdf_paths["high"]) as pdf_high:
343 for i in range(13):
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")
347
348 df_el = read_txt(val_path_el, cols)
349 df_po = read_txt(val_path_po, cols)
350
351 if df_el is None or df_po is None:
352 continue
353
354 df_el['mom'] *= -1 # flip electron momentum
355
356 fig, ax = plt.subplots(2, 2, figsize=(20, 12))
357
358 ymin, ymax = get_positive_minmax(df_el['mean'])
359
360 panels = [
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)"},
373 ]
374
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"],
379 space=1, ax=ax_i)
380
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)
392
393 fig.suptitle(f"dE/dx vs Momentum ({cos_labels[i]}) {suffix}", fontsize=20)
394 plt.tight_layout()
395
396 # Save to correct PDF
397 if i <= 2:
398 save_to_pdf(pdf_low, fig)
399 else:
400 save_to_pdf(pdf_high, fig)
401
402
403def oneDcell_validation(path, suffix):
404
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")
408
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"])
412
413 if df_sl0 is None or df_sl1 is None or df_sl2_8 is None:
414 return
415
416 pdf_path = make_pdf_path("dedx_vs_enta", suffix)
417
418 with PdfPages(pdf_path) as pdf:
419 fig, ax = plt.subplots(3, 2, figsize=(16, 18))
420
421 datasets = [
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),
425 ]
426
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)
432
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)
437
438 fig.suptitle(f"dE/dx vs entaRS {suffix}", fontsize=20)
439 save_to_pdf(pdf, fig)
440
441
442def run_validation(job_path, input_data_path, requested_iov, expert_config, **kwargs):
443 '''
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
449 '''
450 os.makedirs('plots/validation', exist_ok=True)
451 os.makedirs('plots/constant', exist_ok=True)
452
453 expert_config = json.loads(expert_config)
454 GT = expert_config["GT"]
455
456 basf2.B2INFO("Starting validation...")
457
458 payloads = [
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),
463 ]
464
465 for dirname, label, function in payloads:
466
467 basf2.B2INFO(f"Processing {label} payloads...")
468
469 caldir = get_latest_calibration_dir(job_path, dirname)
470
471 dbpath = os.path.join(caldir, "outputdb")
472
473 function(dbpath, GT)
474
475 basf2.B2INFO("Generating validation plots...")
476 val_path = os.path.join(job_path, 'validation0', '0', 'algorithm_output')
477
478 validators = [
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),
485 ]
486
487 if isinstance(requested_iov, str):
488 requested_iov = json.loads(requested_iov)
489
490 from caf.utils import ExpRun, IoV
491 requested_iov = IoV(*requested_iov)
492
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']}")
496
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)
502
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/')
505
506 shutil.copy(source_path+f"/mom/dedxpeaks_vs_mom_{suffix}.pdf", 'plots/validation/')
507
508
509if __name__ == "__main__":
510 run_validation(*sys.argv[1:])
Definition plot.py:1