Repository navigation
Expand file tree
/
Copy pathcompare_cpp_java.py
More file actions
executable file
·503 lines (442 loc) · 21.2 KB
/
Copy pathcompare_cpp_java.py
File metadata and controls
executable file
·503 lines (442 loc) · 21.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
#!/usr/bin/env python3
"""Compare the C++ and Java BeamSpot implementations on a single run.
Runs both the C++ binary (build/beamspot) and the original Java code
(java_imp/run.sh) over the SAME list of DST files, parses each one's
`*_results.txt`, and prints/plots the difference in the five fitted quantities
(Z, R, Phi0, X, Y).
Matching the z binning (IMPORTANT)
----------------------------------
The Java code derives its 2D z-vs-phi map range from the target z with an
integer truncation, and hard-codes the 1D z histogram range:
zmap_min = (int)(targetZ - 4.4) zmap_max = (int)(targetZ + 15.6)
z1d = [-20, 50] (fixed)
The C++ now takes BOTH ranges as explicit options, so to compare apples to
apples this script computes the Java-derived values (replicating Java's
float->double->int arithmetic) and passes them to the C++ binary via
--z-min/--z-max and --z1d-min/--z1d-max. Both sides also get the same
-Z/-N/-R. Otherwise the histograms (and therefore the fits) would not line up.
Java caveats
------------
The Java only writes its results from inside plot(), which is reached only in
graphics mode (-B 0) and pops up Swing windows -- so it needs an X display
(this script auto-wraps it in `xvfb-run` when there's no $DISPLAY) and it keeps
the JVM alive after writing, so we poll for the results file and then terminate
the process. Requires $CLAS12DIR (COATJAVA) to be set, like java_imp/run.sh.
Example
-------
python scripts/compare_cpp_java.py \
/volatile/clas12/rg-l/production/rich_060526/calib/recon/022083 \
--max-files 10 -z 19.6
"""
import argparse
import glob
import os
import shutil
import signal
import subprocess
import sys
import time
import numpy as np
import uproot
import matplotlib as mpl
mpl.use("Agg")
import matplotlib.pyplot as plt
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.dirname(HERE)
PARAMS = ["Z", "R", "Phi0", "X", "Y"]
UNITS = {"Z": "cm", "R": "cm", "Phi0": "deg", "X": "cm", "Y": "cm"}
# --------------------------------------------------------------------------
def java_z_ranges(target_z):
"""Replicate Java's (int)(targetZ-4.4)/(int)(targetZ+15.6) with float math.
Java: targetZ is a 32-bit float; `targetZ - 4.4` promotes it to double and
`(int)` truncates toward zero. The 1D z histogram is fixed at [-20, 50].
"""
tz = float(np.float64(np.float32(target_z)))
zmap_min = float(int(tz - 4.4))
zmap_max = float(int(tz + 15.6))
return zmap_min, zmap_max, -20.0, 50.0
def collect_files(run_dir, pattern, max_files):
files = sorted(glob.glob(os.path.join(run_dir, pattern)))
if not files:
files = sorted(p for p in glob.glob(os.path.join(run_dir, "*"))
if os.path.isfile(p))
if max_files and max_files > 0:
files = files[:max_files]
return files
def parse_results(path):
"""{param: (value, error)} from a `<key> = <val> +- <err>` results file."""
out = {}
with open(path) as fh:
for line in fh:
if "=" in line and "+-" in line:
key, rest = line.split("=", 1)
val, err = rest.split("+-")
try:
out[key.strip()] = (float(val), float(err))
except ValueError:
pass
return out
# --------------------------------------------------------------------------
def run_cpp(opt, files, out_dir, z):
os.makedirs(out_dir, exist_ok=True)
cmd = [opt.beamspot, "-o", out_dir, "-p", "BeamSpot",
"-z", str(opt.target_z),
"--z-min", str(z[0]), "--z-max", str(z[1]),
"--z1d-min", str(z[2]), "--z1d-max", str(z[3]),
"-n", str(opt.bins_per_sector), "-r", str(opt.fit_range),
"-j", str(opt.jobs)] + files
print("\n[C++] " + " ".join(cmd[:14]) + f" ... ({len(files)} files)")
rc = subprocess.run(cmd).returncode
res = os.path.join(out_dir, "BeamSpot_results.txt")
if rc != 0 or not os.path.exists(res):
print(f"[C++] FAILED (rc={rc}, results present={os.path.exists(res)})")
return None
return res
def run_java(opt, files, out_dir):
# The Java aborts if BeamSpot_histos.hipo already exists, so start from a
# clean output dir every time (it holds only this comparison's Java output).
if os.path.isdir(out_dir):
shutil.rmtree(out_dir)
os.makedirs(out_dir, exist_ok=True)
if not os.environ.get("CLAS12DIR"):
print("[Java] SKIP: $CLAS12DIR is not set (needed to compile/run the Java).")
return None
base = ["bash", opt.java_run_sh, "-B", "0", "-X", "0", "-O", "BeamSpot",
"-Z", str(opt.target_z), "-N", str(opt.bins_per_sector),
"-R", str(opt.fit_range)] + files
# The Java only writes results from its graphics path (Swing JFrames), so it
# needs a display. Prefer xvfb-run whenever it's available -- it starts its
# own virtual X server and overrides any inherited (possibly broken, e.g.
# forwarded localhost:NN.0) $DISPLAY. Pass --no-xvfb to use the real display.
if opt.xvfb and shutil.which("xvfb-run"):
cmd = ["xvfb-run", "-a", "--server-args=-screen 0 1400x1000x24"] + base
print("[Java] using xvfb-run (virtual display)")
else:
cmd = base
if opt.xvfb and not shutil.which("xvfb-run"):
print("[Java] WARNING: xvfb-run not found; falling back to $DISPLAY"
f"={os.environ.get('DISPLAY')!r}. Install xvfb for a headless run.")
elif not os.environ.get("DISPLAY"):
print("[Java] WARNING: --no-xvfb and no $DISPLAY; Java graphics mode will fail.")
# Silence groot's verbose Minuit logger (java.util.logging INFO spam from the
# per-theta modulation fits) by handing the JVM a logging config that keeps
# only WARNING+. System.out.println output (event rate, fit params) is kept.
log_props = os.path.join(out_dir, "logging.properties")
with open(log_props, "w") as w:
w.write("handlers=java.util.logging.ConsoleHandler\n"
".level=WARNING\n"
"java.util.logging.ConsoleHandler.level=WARNING\n"
"org.freehep.level=WARNING\n"
"org.freehep.math.minuit.level=WARNING\n")
env = os.environ.copy()
env["_JAVA_OPTIONS"] = (env.get("_JAVA_OPTIONS", "")
+ f" -Djava.util.logging.config.file={log_props}").strip()
res = os.path.join(out_dir, "BeamSpot_results.txt")
print("\n[Java] " + " ".join(cmd) + f" (cwd={out_dir})")
# Java keeps the JVM alive (visible JFrames) after writing results, so run it
# in its own process group, wait for the results file, then terminate it.
proc = subprocess.Popen(cmd, cwd=out_dir, start_new_session=True, env=env)
deadline = time.time() + opt.java_timeout
ok = exited = timed_out = False
while True:
if proc.poll() is not None: # exited on its own
ok, exited = os.path.exists(res), True
break
if os.path.exists(res) and os.path.getsize(res) > 0:
time.sleep(2) # let the ccdb table finish too
ok = True
break
if time.time() >= deadline: # still alive but out of time
timed_out = True
break
time.sleep(2)
if proc.poll() is None: # we broke out while it was alive
try:
os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
proc.wait(timeout=10)
except Exception: # noqa: BLE001
try:
os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
except Exception: # noqa: BLE001
pass
if not ok:
if timed_out:
print(f"[Java] TIMED OUT after {opt.java_timeout:.0f}s while still running "
"(the Java fill is single-threaded and slow). Re-run with a larger "
"--java-timeout, or use --max-files for a quicker check.")
elif exited:
print("[Java] exited without writing results -- check the Java output above.")
return None
return res
# --------------------------------------------------------------------------
def report(cpp, java, out_dir):
print("\n" + "=" * 78)
print(f"{'param':<6} {'C++':>16} {'Java':>16} {'diff (C++-Java)':>18} {'diff/sigma':>10}")
print("-" * 78)
rows = []
for p in PARAMS:
if p not in cpp or p not in java:
continue
cv, ce = cpp[p]
jv, je = java[p]
diff = cv - jv
sig = (ce**2 + je**2) ** 0.5
nsig = diff / sig if sig > 0 else float("nan")
print(f"{p:<6} {cv:>16.6g} {jv:>16.6g} {diff:>18.3g} {nsig:>10.2f}")
rows.append((p, cv, ce, jv, je, diff, nsig))
print("=" * 78)
table = os.path.join(out_dir, "compare_cpp_java.txt")
with open(table, "w") as w:
w.write(f"# {'param':<6} {'cpp':>16} {'cpp_err':>14} {'java':>16} "
f"{'java_err':>14} {'diff':>16} {'diff_over_sigma':>16}\n")
for p, cv, ce, jv, je, diff, nsig in rows:
w.write(f"{p:<8} {cv:>16.8g} {ce:>14.6g} {jv:>16.8g} "
f"{je:>14.6g} {diff:>16.8g} {nsig:>16.3f}\n")
print(f"wrote {table}")
return rows
def _is_float(s):
try:
float(s)
return True
except ValueError:
return False
# --- filled-histogram comparison ------------------------------------------
def read_cpp_h2(results_root):
"""{i: values[z, phi]} for each h2_z_phi_<i> in the C++ results.root."""
out = {}
with uproot.open(results_root) as f:
i = 0
while f"h2_z_phi_{i}" in f:
out[i] = np.asarray(f[f"h2_z_phi_{i}"].to_numpy(flow=False)[0], dtype=float)
i += 1
return out
def read_java_histos_txt(path):
"""{i: values[z, phi]} from Java's BeamSpot_histos.txt.
Layout: a few '#' header lines (theta edges, x edges, y edges), then per
theta bin a '# lo,hi' marker (exactly two numbers) followed by nx rows of
ny comma-separated bin contents -- row = z bin, column = phi bin.
"""
bins, rows, idx, in_bin = {}, [], -1, False
with open(path) as fh:
for line in fh:
line = line.strip()
if not line:
continue
if line.startswith("#"):
parts = [p for p in line[1:].split(",") if p != ""]
if len(parts) == 2 and all(_is_float(p) for p in parts): # bin marker
if in_bin and rows:
bins[idx] = np.array(rows, dtype=float)
idx += 1
rows, in_bin = [], True
continue
if in_bin:
rows.append([float(v) for v in line.split(",") if v != ""])
if in_bin and rows:
bins[idx] = np.array(rows, dtype=float)
return bins
def compare_histograms(cpp_root, java_txt, out_dir):
if not os.path.exists(cpp_root) or not os.path.exists(java_txt):
print(f"\n[hist] skip (cpp_root={os.path.exists(cpp_root)}, "
f"java_txt={os.path.exists(java_txt)})")
return
cpp, jav = read_cpp_h2(cpp_root), read_java_histos_txt(java_txt)
keys = sorted(set(cpp) & set(jav))
print("\n" + "=" * 78)
print("Filled-histogram comparison (h2_z_phi per theta bin, z x phi bins)")
print("-" * 78)
print(f"{'bin':>3} {'cpp_entries':>13} {'java_entries':>13} "
f"{'max|d_bin|':>11} {'sum|d|':>10} {'n_diff_bins':>12}")
all_identical = True
with open(os.path.join(out_dir, "compare_histograms.txt"), "w") as w:
w.write("# bin cpp_entries java_entries max_abs_bin_diff sum_abs_diff n_diff_bins\n")
for i in keys:
a, b = cpp[i], jav[i]
if a.shape != b.shape:
print(f"{i:>3} SHAPE MISMATCH cpp{a.shape} java{b.shape}")
all_identical = False
continue
d = a - b
mx, sd, nd = float(np.abs(d).max()), float(np.abs(d).sum()), int(np.count_nonzero(d))
all_identical = all_identical and nd == 0
print(f"{i:>3} {a.sum():>13.0f} {b.sum():>13.0f} {mx:>11.0f} {sd:>10.0f} {nd:>12}")
w.write(f"{i} {a.sum():.0f} {b.sum():.0f} {mx:.0f} {sd:.0f} {nd}\n")
print("=" * 78)
print("=> fills are BIT-IDENTICAL: every remaining difference is fitter-only."
if all_identical else
"=> fills differ (see per-bin counts above and the residual maps).")
# residual heatmaps (cpp - java), one panel per theta bin
ncol = min(4, len(keys)) or 1
nrow = (len(keys) + ncol - 1) // ncol
fig, axes = plt.subplots(nrow, ncol, figsize=(3.2 * ncol, 3.0 * nrow), squeeze=False)
for ax in axes.flatten():
ax.axis("off")
for j, i in enumerate(keys):
ax = axes.flatten()[j]
ax.axis("on")
d = cpp[i] - jav[i]
vmax = max(1.0, float(np.abs(d).max()))
im = ax.imshow(d.T, origin="lower", aspect="auto", cmap="coolwarm",
vmin=-vmax, vmax=vmax)
ax.set_title(f"bin {i} max|d|={vmax:.0f}", fontsize=9)
ax.set_xlabel("z bin"); ax.set_ylabel("phi bin")
fig.colorbar(im, ax=ax, fraction=0.046)
fig.suptitle("Filled histogram residual (C++ - Java)")
fig.tight_layout()
out = os.path.join(out_dir, "compare_histograms.png")
fig.savefig(out, dpi=150)
plt.close(fig)
print(f"wrote {out}")
# --- per-theta point comparison -------------------------------------------
POINT_COLS = ["theta", "z0", "ez0", "r0", "er0", "phi0", "ephi0",
"x0", "ex0", "y0", "ey0"]
def read_cpp_points(results_root):
with uproot.open(results_root) as f:
if "points" not in f:
return None
t = f["points"].arrays(library="np")
return {c: np.asarray(t[c], dtype=float) for c in POINT_COLS if c in t}
def read_java_points(path):
rows = []
with open(path) as fh:
for line in fh:
line = line.strip()
if line and not line.startswith("#"):
rows.append([float(x) for x in line.split()])
if not rows:
return None
arr = np.array(rows)
return {c: arr[:, j] for j, c in enumerate(POINT_COLS)}
def compare_points(cpp_root, java_txt, out_dir):
if not os.path.exists(cpp_root) or not os.path.exists(java_txt):
print(f"\n[points] skip (cpp_root={os.path.exists(cpp_root)}, "
f"java_pts={os.path.exists(java_txt)})")
return
cpp, jav = read_cpp_points(cpp_root), read_java_points(java_txt)
if not cpp or not jav:
print("\n[points] skip (missing points data)")
return
n = min(len(cpp["theta"]), len(jav["theta"]))
print("\n" + "=" * 78)
print("Per-theta point comparison (C++ vs Java, matched by theta bin)")
print("-" * 78)
print(f"{'theta':>6} " + " ".join(f"{p+'(C-J)':>14}" for p in ("z0", "x0", "y0", "r0")))
with open(os.path.join(out_dir, "compare_points.txt"), "w") as w:
w.write("# theta " + " ".join(f"{p}_cpp {p}_java" for p in
("z0", "r0", "phi0", "x0", "y0")) + "\n")
for k in range(n):
th = cpp["theta"][k]
d = {p: cpp[p][k] - jav[p][k] for p in ("z0", "x0", "y0", "r0")}
print(f"{th:>6.1f} " + " ".join(f"{d[p]:>14.5f}" for p in ("z0", "x0", "y0", "r0")))
w.write(f"{th:.3f} " + " ".join(f"{cpp[p][k]:.6f} {jav[p][k]:.6f}" for p in
("z0", "r0", "phi0", "x0", "y0")) + "\n")
print("=" * 78)
# overlay C++ vs Java per-theta for each parameter
panels = [("z0", "ez0", "cm"), ("x0", "ex0", "cm"), ("y0", "ey0", "cm"),
("r0", "er0", "cm"), ("phi0", "ephi0", "deg")]
fig, axes = plt.subplots(1, len(panels), figsize=(3.0 * len(panels), 3.4), squeeze=False)
for ax, (p, ep, unit) in zip(axes[0], panels):
ax.errorbar(cpp["theta"][:n], cpp[p][:n], yerr=cpp[ep][:n], fmt="o",
color="tab:blue", capsize=3, label="C++")
ax.errorbar(jav["theta"][:n] + 0.1, jav[p][:n], yerr=jav[ep][:n], fmt="s",
color="tab:red", capsize=3, label="Java")
ax.set_title(f"{p} ({unit})", fontsize=11)
ax.set_xlabel(r"$\theta$ (deg)")
ax.grid(True, alpha=0.3)
axes[0][0].legend(fontsize=9)
fig.suptitle("Per-theta points: C++ vs Java")
fig.tight_layout()
out = os.path.join(out_dir, "compare_points.png")
fig.savefig(out, dpi=150)
plt.close(fig)
print(f"wrote {out}")
def plot_compare(rows, out_dir):
if not rows:
return
fig, axes = plt.subplots(1, len(rows), figsize=(2.6 * len(rows), 3.4), squeeze=False)
for ax, (p, cv, ce, jv, je, _d, _n) in zip(axes[0], rows):
ax.errorbar([0], [cv], yerr=[ce], fmt="o", color="tab:blue", capsize=4, label="C++")
ax.errorbar([1], [jv], yerr=[je], fmt="s", color="tab:red", capsize=4, label="Java")
ax.set_xlim(-0.6, 1.6)
ax.set_xticks([0, 1])
ax.set_xticklabels(["C++", "Java"])
ax.set_title(f"{p} ({UNITS.get(p, '')})", fontsize=11)
ax.grid(True, axis="y", alpha=0.3)
fig.suptitle("BeamSpot: C++ vs Java")
fig.tight_layout()
out = os.path.join(out_dir, "compare_cpp_java.png")
fig.savefig(out, dpi=150)
plt.close(fig)
print(f"wrote {out}")
# --------------------------------------------------------------------------
def main():
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("run_dir", help="directory holding one run's DST files")
ap.add_argument("--pattern", default="*.hipo",
help="glob for DST files in run_dir (default *.hipo; "
"falls back to every file if none match)")
ap.add_argument("--max-files", type=int, default=0,
help="use only the first N files (0 = all; both sides get the same set)")
ap.add_argument("--output-dir", default="compare_out",
help="folder for the cpp/ and java/ outputs and the comparison")
ap.add_argument("--beamspot", default=os.path.join(REPO, "build", "beamspot"),
help="path to the compiled C++ beamspot binary")
ap.add_argument("--java-run-sh", default=os.path.join(REPO, "java_imp", "run.sh"),
help="path to the Java run.sh wrapper")
ap.add_argument("-z", "--target-z", type=float, default=19.6,
help="nominal target/foil Z (cm), passed to BOTH (default 19.6)")
ap.add_argument("-n", "--bins-per-sector", type=int, default=10)
ap.add_argument("-r", "--fit-range", type=float, default=1.0)
ap.add_argument("-j", "--jobs", type=int, default=0, help="C++ worker processes")
ap.add_argument("--java-timeout", type=float, default=10800,
help="seconds to wait for the Java results file before giving up "
"(default 3h; the Java fill is single-threaded ~30 kHz, so a "
"full ~100M-event run takes >1h -- raise this or use --max-files)")
ap.add_argument("--no-xvfb", dest="xvfb", action="store_false",
help="don't wrap the Java in xvfb-run even without a $DISPLAY")
ap.add_argument("--skip-cpp", action="store_true")
ap.add_argument("--skip-java", action="store_true")
opt = ap.parse_args()
if not os.path.isdir(opt.run_dir):
sys.exit(f"compare: run dir not found: {opt.run_dir}")
files = collect_files(opt.run_dir, opt.pattern, opt.max_files)
if not files:
sys.exit(f"compare: no input files in {opt.run_dir}")
z = java_z_ranges(opt.target_z)
os.makedirs(opt.output_dir, exist_ok=True)
print(f"run dir : {opt.run_dir}")
print(f"files : {len(files)} (same set for both implementations)")
print(f"target_z: {opt.target_z} N={opt.bins_per_sector} R={opt.fit_range}")
print(f"z-map range (matched to Java) : [{z[0]:g}, {z[1]:g}] cm")
print(f"z-1D range (matched to Java) : [{z[2]:g}, {z[3]:g}] cm")
cpp_out = os.path.join(opt.output_dir, "cpp")
java_out = os.path.join(opt.output_dir, "java")
if opt.skip_cpp:
cpp_res = os.path.join(cpp_out, "BeamSpot_results.txt")
cpp_res = cpp_res if os.path.exists(cpp_res) else None
print(f"[C++] (skip) reusing {cpp_res}" if cpp_res else "[C++] skip: no existing results")
else:
cpp_res = run_cpp(opt, files, cpp_out, z)
if opt.skip_java:
java_res = os.path.join(java_out, "BeamSpot_results.txt")
java_res = java_res if os.path.exists(java_res) else None
print(f"[Java] (skip) reusing {java_res}" if java_res else "[Java] skip: no existing results")
else:
java_res = run_java(opt, files, java_out)
if not cpp_res or not java_res:
print("\ncompare: missing one side; cannot diff "
f"(cpp={bool(cpp_res)}, java={bool(java_res)}).")
sys.exit(1)
# 1) final fitted constants
cpp = parse_results(cpp_res)
java = parse_results(java_res)
rows = report(cpp, java, opt.output_dir)
plot_compare(rows, opt.output_dir)
# 2) the filled histograms (proves whether the fills are identical) and
# 3) the per-theta extracted points (before the pol0 average)
cpp_root = cpp_res.replace("_results.txt", "_results.root")
compare_histograms(cpp_root, os.path.join(java_out, "BeamSpot_histos.txt"), opt.output_dir)
compare_points(cpp_root, os.path.join(java_out, "BeamSpot_points.txt"), opt.output_dir)
if __name__ == "__main__":
main()