From 476701cd56c327af919ed6f9cf799f1cfa9cc35d Mon Sep 17 00:00:00 2001 From: jorge Date: Thu, 24 Sep 2026 19:49:39 +0200 Subject: [PATCH 1/5] Conex output implementation --- .gitignore | 4 + sample_input_file.toml | 5 +- src/nuspacesim/apps/run.py | 11 + src/nuspacesim/compute.py | 44 ++- src/nuspacesim/conex_out.py | 350 ++++++++++++++++++ src/nuspacesim/config.py | 2 + .../simulation/eas_optical/cphotang.py | 42 ++- src/nuspacesim/simulation/eas_optical/eas.py | 7 +- src/nuspacesim/utils/decorators.py | 4 +- 9 files changed, 446 insertions(+), 23 deletions(-) create mode 100644 src/nuspacesim/conex_out.py diff --git a/.gitignore b/.gitignore index 1062b846..a6f0bf35 100644 --- a/.gitignore +++ b/.gitignore @@ -188,3 +188,7 @@ cython_debug/ AGENTS.md .claude/ docs/*.md + +#debug files +*.root +*.png diff --git a/sample_input_file.toml b/sample_input_file.toml index dad99a39..118948a5 100644 --- a/sample_input_file.toml +++ b/sample_input_file.toml @@ -30,11 +30,12 @@ gain = "1.8 dB" [simulation] mode = "Diffuse" -thrown_events = 100 +thrown_events = 100000 max_cherenkov_angle = "3.0000000000000004 deg" max_azimuth_angle = "360.0 deg" angle_from_limb = "7.0 deg" eas_long_profile = "Greisen" +conex_output = true cherenkov_light_engine = "nuspacesim" [simulation.ionosphere] @@ -55,7 +56,7 @@ table_version = "3" [simulation.spectrum] id = "monospectrum" -log_nu_energy = 8.0 +log_nu_energy = 9.0 [simulation.cloud_model] id = "no_cloud" diff --git a/src/nuspacesim/apps/run.py b/src/nuspacesim/apps/run.py index d5625461..7d52e6d9 100644 --- a/src/nuspacesim/apps/run.py +++ b/src/nuspacesim/apps/run.py @@ -59,6 +59,13 @@ @click.option( "-o", "--output", type=click.Path(exists=False), default=None, help="Output file." ) +@click.option( + "-c", + "--conex-output", + is_flag=True, + default=False, + help="Generate CONEX-compatible ROOT output.", +) @click.option( "-p", "--plot", @@ -136,6 +143,7 @@ def run( count: float, no_result_file: bool, output: str, + conex_output: bool, plot: list, plotconfig: str, plotall: bool, @@ -183,6 +191,9 @@ def run( # User Inputs config = config_from_toml(config_file) + if conex_output: + config.simulation.conex_output = True + config.simulation.thrown_events = int( config.simulation.thrown_events if count == 0.0 else count ) diff --git a/src/nuspacesim/compute.py b/src/nuspacesim/compute.py index 99e092e0..a29f4f39 100644 --- a/src/nuspacesim/compute.py +++ b/src/nuspacesim/compute.py @@ -56,6 +56,7 @@ from rich.console import Console from . import results_table +from .conex_out import conex_out from .config import NssConfig from .simulation.atmosphere.clouds import CloudTopHeight from .simulation.eas_optical.eas import EAS @@ -191,6 +192,7 @@ def add_meta(self, name: str, value: Any, comment: str): beta_tr, thetaArr, pathLenArr, *_ = geom( config.simulation.thrown_events, store=sw, plot=to_plot ) + thrown_color = "[blue]" if beta_tr.size else "[red]" logv( f"\t{thrown_color}Threw {config.simulation.thrown_events} neutrinos.\ @@ -239,18 +241,36 @@ def add_meta(self, name: str, value: Any, comment: str): if config.detector.optical.enable: logv("Computing [green] EAS Optical Cherenkov light.[/]") - numPEs, costhetaChEff = eas( - beta_tr, - altDec, - showerEnergy, - init_lat, - init_long, - cloudf=cloud, - client=optical_cluster.client() if use_cluster else None, - serial=not use_cluster, - store=sw, - plot=to_plot, - ) + if config.simulation.conex_output: + numPEs, costhetaChEff, RN, z_nodes, X_to_node = eas( + beta_tr, + altDec, + showerEnergy, + init_lat, + init_long, + cloudf=cloud, + conex=True, + client=optical_cluster.client() if use_cluster else None, + serial=not use_cluster, + store=sw, + plot=to_plot, + ) + conex_out(sim, RN, z_nodes, X_to_node, output_file) + + else: + numPEs, costhetaChEff = eas( + beta_tr, + altDec, + showerEnergy, + init_lat, + init_long, + cloudf=cloud, + conex=False, + client=optical_cluster.client() if use_cluster else None, + serial=not use_cluster, + store=sw, + plot=to_plot, + ) # Single consumer is done; release the warm cluster immediately. if use_cluster: diff --git a/src/nuspacesim/conex_out.py b/src/nuspacesim/conex_out.py new file mode 100644 index 00000000..f327a32a --- /dev/null +++ b/src/nuspacesim/conex_out.py @@ -0,0 +1,350 @@ +import numpy as np +import uproot +from scipy.optimize import curve_fit, least_squares + +from .simulation.eas_optical.propagation import lexpr, slant_depth + + +def conex_out(data, RN, z_nodes, X_to_node, output_file): # noqa: C901 + def GH(X, X0, Xmax, Nmax, p3, p2, p1): + return ( + Nmax + * ((X - X0) / (Xmax - X0)) ** ((Xmax - X0) / (p3 * X**2 + p2 * X + p1)) + * np.exp((Xmax - X) / (p3 * X**2 + p2 * X + p1)) + ) + + def alpha(s): + c1 = 47.9511 + c2 = 0.971315 + c3 = 9.23001 + c4 = 2.29587 + c5 = 0.285196 + return (c1 / (c2 + s) ** c3 + c4 + c5 * s) * 0.001 + + def showerage(x, xmax): + return 3 * x / (x + 2 * xmax) + + Zfirst = np.asarray(data["altDec"], dtype=np.float64) + TauEnergy = np.log10(np.asarray(data["tauEnergy"], dtype=np.float64)) + 9 + RN = np.asarray(RN, dtype=np.float64) + Zmax = 20 + Zmin = 0 + # TauEnergyMax=18 + # Useful masks (Zfirst masks are necessary between 0 and 20km). To introduce masks you must also change them in simulation/eas_optical/eas.py + z_mask = np.asarray((Zfirst >= Zmin) & (Zfirst <= Zmax), dtype=bool) + beta = np.asarray(data["beta_rad"], dtype=np.float64)[z_mask] + Zfirst = Zfirst[z_mask] + TauEnergy = TauEnergy[z_mask] + rn_max_not_reached = RN[:, -1] < np.max(RN[:, :-1], axis=1) + mask = rn_max_not_reached + beta = beta[mask] + Zfirst = Zfirst[mask] + TauEnergy = TauEnergy[mask] + beta = np.asarray(beta, dtype=np.float64) + RN = RN[mask] + z_nodes = np.asarray(z_nodes, dtype=np.float64)[mask] + X_to_node = np.asarray(X_to_node, dtype=np.float64)[mask] + + # The optical pipeline's X_to_node starts at the decay point. CONEX X must + # start at ground, so add the slant depth from ground to each decay point. + ground_length = lexpr(0.0, beta) + decay_length = lexpr(Zfirst, beta) + Xfirst = slant_depth(ground_length, decay_length, beta) + + n = np.size(Zfirst) + X = np.asarray(X_to_node + Xfirst[:, None], dtype=np.float32) + Z = np.asarray(z_nodes, dtype=np.float32) + RN = np.asarray(RN, dtype=np.float32) + print(f"Number of valid events with Xmax inside atmosphere: {n}") + # CONEX D is propagation distance measured from ground, in km here. + D = lexpr(z_nodes, beta[:, None]) - ground_length[:, None] + profile_size = X_to_node.shape[-1] + + azim = 360 * np.random.rand(n) # Random azimuth + zenith = 90 + np.degrees(beta) + # Force file name to end in .root and start with conex + if not output_file.endswith(".root"): + # strip any existing extension and add .root + output_file = ".".join(output_file.split(".")[:-1]) + ".root" + if not output_file.startswith("conex"): + output_file = "conex_" + output_file + # Useful variables to fill the conex File + PID = np.array([100], dtype="i4") # Proton type for Conex + zmin = np.array([90], dtype="i4") + zmax = np.array([132], dtype="i4") + nan4 = np.array([np.nan], dtype="f4") + nan8 = np.array([np.nan], dtype="f8") + int4 = np.array([-1], dtype="i4") + intn = np.full(n, -1, dtype="i4") + nan4n = np.full(n, np.nan, dtype="f4") + nan8n = np.full(n, np.nan, dtype="f8") + Xempty = np.zeros_like(X) + OutputVersion = np.array([2.51], dtype="f4") + a = np.full((1, 31), np.nan, dtype="f8") + Eground = np.full((n, 3), nan4) + Eg = Eground + + # Initialize some variables for GH fit + Xmax = np.empty(n, dtype="f4") + Nmax = np.empty(n, dtype="f4") + X0 = np.empty(n, dtype="f4") + p1 = np.empty(n, dtype="f4") + p2 = np.empty(n, dtype="f4") + p3 = np.empty(n, dtype="f4") + chi2 = np.zeros(n, dtype="f4") + Xmx = np.empty(n, dtype="f4") + Nmx = np.empty(n, dtype="f4") + dEdXmx = np.empty(n, dtype="f4") + dEdX_profiles = [] + + for i in range(n): + x_profile = np.array(X[i]) + # Shift profile in X and reduce magnitude in N to simplify the fits. + x0 = x_profile[0] + x = x_profile - x0 + rn = np.array(RN[i]) + y = rn / 1e5 + + init = np.empty(6) + max_pos = np.argmax(y) + y = y[ + 0 : max_pos * 2 + ] # Only interested in profile around the maximum, disregard the tail + x = x[0 : max_pos * 2] + + # Best initial values for a good, fast and reliable fit. + init[1] = x[max_pos] + init[0] = -0.30943336 * init[1] + init[2] = y[max_pos] + init[3:] = [1e-7, 4e-4, 44] + + fit_succeeded = True + try: + popt, pcov = curve_fit(GH, x, y, p0=init, maxfev=1000000) + if not np.all(np.isfinite(popt)): + raise RuntimeError("curve_fit returned non-finite parameters") + except (RuntimeError, ValueError, FloatingPointError) as error: + print(f"Warning: fit failed for event {i}: {error}") + try: + fallback = least_squares( + lambda parameters: GH(x, *parameters) - y, + init, + max_nfev=1000000, + ) + popt = fallback.x + if not np.all(np.isfinite(popt)): + raise RuntimeError("least_squares returned non-finite parameters") + print(f"Using best-effort least-squares parameters for event {i}.") + except (RuntimeError, ValueError, FloatingPointError) as fallback_error: + print(f"Warning: no fit found for event {i}: {fallback_error}") + fit_succeeded = False + popt = np.full(6, np.nan) + + yfit = GH(x, *popt) if fit_succeeded else np.full_like(y, np.nan) + fit_xmax = popt[1] if fit_succeeded else x[max_pos] + dedx = alpha(showerage(x_profile, fit_xmax + x0)) * rn + dEdX_profiles.append(dedx) + + # Calculate chi**2 + if fit_succeeded: + for j in range(yfit.size): + if y[j] > 0: + chi2[i] += (y[j] - yfit[j]) ** 2 / y[j] + + chi2[i] = chi2[i] / (y.size - 6) / (np.sqrt(popt[2] * 1e5)) + else: + chi2[i] = np.nan + + g3 = popt[3] + g2 = popt[4] + g1 = popt[5] + if np.isnan(chi2[i]): + print(f"Warning: chi2 is NaN for event {i}.") + elif chi2[i] < 0: + print(f"Warning: chi2 is negative for event {i}: {chi2[i]:.3g}.") + elif chi2[i] > 0.1: + print( + f"Warning: chi2 for event {i} is too high ({chi2[i]:.3f}). " + "This may indicate a poor fit." + ) + # Undo the variable change. For p1, p2, p3 this involves shifting the parabola coefficients. + X0[i] = popt[0] + x0 + Xmax[i] = popt[1] + x0 + Nmax[i] = popt[2] * 1e5 + p3[i] = popt[3] + p2[i] = g2 - 2 * g3 * x0 + p1[i] = g1 - g2 * x0 + g3 * x0**2 + Xmx[i] = x[max_pos] + x0 + Nmx[i] = rn[max_pos] + dEdXmx[i] = dedx[max_pos] + chi2[i] = chi2[i] * 1e5 + + nan_chi2 = np.flatnonzero(np.isnan(chi2)) + negative_chi2 = np.flatnonzero(chi2 < 0) + if nan_chi2.size: + print(f"Warning: NaN chi2 values found for events {nan_chi2.tolist()}.") + if negative_chi2.size: + print( + f"Warning: negative chi2 values found for events " + f"{negative_chi2.tolist()}." + ) + + branches_header = { + "Seed1": np.dtype("i4"), + "Particle": np.dtype("i4"), + "Alpha": np.dtype("f8"), + "lgEmin": np.dtype("f8"), + "lgEmax": np.dtype("f8"), + "zMin": np.dtype("f8"), + "zMax": np.dtype("f8"), + "SvnRevision": np.dtype("b"), + "Version": np.dtype("f4"), + "OutputVersion": np.dtype("f4"), + "HEModel": np.dtype("i4"), + "LEModel": np.dtype("i4"), + "HiLowEgy": np.dtype("f4"), + "hadCut": np.dtype("f4"), + "emCut": np.dtype("f4"), + "hadThr": np.dtype("f4"), + "muThr": np.dtype("f4"), + "emThr": np.dtype("f4"), + "haCut": np.dtype("f4"), + "muCut": np.dtype("f4"), + "elCut": np.dtype("f4"), + "gaCut": np.dtype("f4"), + "lambdaLgE": ("f8", (31,)), + "lambdaProton": ("f8", (31,)), + "lambdaPion": ("f8", (31,)), + "lambdaHelium": ("f8", (31,)), + "lambdaNitrogen": ("f8", (31,)), + "lambdaIron": ("f8", (31,)), + } + + branches_shower = { + "lgE": np.dtype("f4"), + "zenith": np.dtype("f4"), + "azimuth": np.dtype("f4"), + "Seed2": np.dtype("i4"), + "Seed3": np.dtype("i4"), + "Xfirst": np.dtype("f4"), + "Hfirst": np.dtype("f4"), + "XfirstIn": np.dtype("f4"), + "altitude": np.dtype("f8"), + "X0": np.dtype("f4"), + "Xmax": np.dtype("f4"), + "Nmax": np.dtype("f4"), + "p1": np.dtype("f4"), + "p2": np.dtype("f4"), + "p3": np.dtype("f4"), + "chi2": np.dtype("f4"), + "Xmx": np.dtype("f4"), + "Nmx": np.dtype("f4"), + "XmxdEdX": np.dtype("f4"), + "dEdXmx": np.dtype("f4"), + "cpuTime": np.dtype("f4"), + "X": ("f4", (profile_size,)), + "N": ("f4", (profile_size,)), + "H": ("f4", (profile_size,)), + "D": ("f4", (profile_size,)), + "dEdX": ("f4", (profile_size,)), + "Mu": ("f4", (profile_size,)), + "Gamma": ("f4", (profile_size,)), + "Electrons": ("f4", (profile_size,)), + "Hadrons": ("f4", (profile_size,)), + "dMu": ("f4", (profile_size,)), + "nX": np.dtype("i4"), + "nN": np.dtype("i4"), + "nH": np.dtype("i4"), + "nD": np.dtype("i4"), + "ndEdX": np.dtype("i4"), + "nMu": np.dtype("i4"), + "nGamma": np.dtype("i4"), + "nElectrons": np.dtype("i4"), + "nHadrons": np.dtype("i4"), + "ndMu": np.dtype("i4"), + "EGround": ("f4", (3,)), + } + + f = uproot.recreate(output_file) + f.mktree("Header", branches_header, title="run header") + f.mktree("Shower", branches_shower, title="shower info") + f["Header"].extend( + { + "Seed1": int4, + "Particle": PID, # Proton type (no specific ID for tau) + "Alpha": nan8, + "lgEmin": nan8, + "lgEmax": nan8, + "zMin": zmin, + "zMax": zmax, + "SvnRevision": [0], + "Version": [64], + "OutputVersion": OutputVersion, + "HEModel": int4, + "LEModel": int4, + "HiLowEgy": nan4, + "hadCut": nan4, + "emCut": nan4, + "hadThr": nan4, + "muThr": nan4, + "emThr": nan4, + "haCut": nan4, + "muCut": nan4, + "elCut": nan4, + "gaCut": nan4, + "lambdaLgE": a, + "lambdaProton": a, + "lambdaPion": a, + "lambdaHelium": a, + "lambdaNitrogen": a, + "lambdaIron": a, + } + ) + f["Shower"].extend( + { + "lgE": TauEnergy, + "zenith": zenith, # 90+np.degree(beta_rad) + "azimuth": azim, + "Seed2": intn, + "Seed3": intn, + "Xfirst": Xfirst, + "Hfirst": Zfirst * 1000, + "XfirstIn": np.full(n, 0.5, dtype="f4"), + "altitude": nan8n, + "X0": X0, + "Xmax": Xmax, + "Nmax": Nmax, + "p1": p1, + "p2": p2, + "p3": p3, + "chi2": chi2, + "Xmx": Xmx, + "Nmx": Nmx, + "XmxdEdX": Xmx, + "dEdXmx": dEdXmx, + "cpuTime": nan4n, + "X": X, + "N": RN, + "H": Z * 1000, # in meters + "D": np.asarray(D, dtype=np.float32) * 1000, + "dEdX": np.asarray(dEdX_profiles, dtype=np.float32), + "Mu": Xempty, # Xempty + "Gamma": Xempty, # Xempty + "Electrons": RN, + "Hadrons": Xempty, # Xempty + "dMu": Xempty, # Xempty + "nX": np.full(n, profile_size, dtype="i4"), + "nN": np.full(n, profile_size, dtype="i4"), + "nH": np.full(n, profile_size, dtype="i4"), + "nD": np.full(n, profile_size, dtype="i4"), + "ndEdX": np.full(n, profile_size, dtype="i4"), + "nMu": np.full(n, profile_size, dtype="i4"), + "nGamma": np.full(n, profile_size, dtype="i4"), + "nElectrons": np.full(n, profile_size, dtype="i4"), + "nHadrons": np.full(n, profile_size, dtype="i4"), + "ndMu": np.full(n, profile_size, dtype="i4"), + "EGround": Eg, + } + ) + f.close() + print(f"Output file saved to {output_file}") diff --git a/src/nuspacesim/config.py b/src/nuspacesim/config.py index 0e279933..db9008ab 100644 --- a/src/nuspacesim/config.py +++ b/src/nuspacesim/config.py @@ -324,6 +324,8 @@ class TargetOfOpportunity(BaseModel): use_refactored_photon_sum: bool = False """Use Phase-B refactored photon-sum kernel in EAS optical simulation.""" + conex_output: bool = False + """Enable CONEX output generation.""" refactored_photon_sum_variant: Literal["v1", "v2", "v3", "v4", "v6"] = "v2" """Refactored photon-sum variant key (used when use_refactored_photon_sum=True).""" diff --git a/src/nuspacesim/simulation/eas_optical/cphotang.py b/src/nuspacesim/simulation/eas_optical/cphotang.py index 7b934a3d..3be03f0b 100644 --- a/src/nuspacesim/simulation/eas_optical/cphotang.py +++ b/src/nuspacesim/simulation/eas_optical/cphotang.py @@ -388,6 +388,7 @@ def run( n_energy_low=3, n_energy_high=8, photon_model=None, + conex=False, ): """Main simulation: compute photon density and Cherenkov angle. @@ -551,7 +552,10 @@ def run( altitude_scaling, per_wavelength, ) - return photonDen.astype(self.dtype), Cang.astype(self.dtype) + result = photonDen.astype(self.dtype), Cang.astype(self.dtype) + if conex: + return result + (RN, z_nodes, X_to_node) + return result # ------------------------------------------------------------------ # run() stages (each operates on (n_showers,) / (n_showers, n_nodes)) @@ -855,6 +859,7 @@ def __call__( init_lat, init_long, cloudf=None, + conex=False, chunks=None, photon_model=None, per_wavelength=False, @@ -915,6 +920,14 @@ def __call__( or len(init_lat) < 1 or len(init_long) < 1 ): + if conex: + return ( + np.empty([]), + np.empty([]), + np.empty([]), + np.empty([]), + np.empty([]), + ) return np.empty([]), np.empty([]) # Per block, run() yields density (N,) [collapsed] or (N, n_wl) @@ -923,18 +936,21 @@ def __call__( # the density (n_den = 1 collapsed, n_wl per-wavelength), the last row # is Cang. The collapsed path stays (2, N) -- bit-identical to before; # per-wavelength avoids the (N, n_nodes, n_wl) tensor only when the - # caller actually wants it. + # caller actually wants it. CONEX diagnostics are packed as n_nodes rows + # for each of RN, z_nodes, and X_to_node after the density and angle. n_wl = len(self.wmean) n_den = n_wl if per_wavelength else 1 + diagnostic_rows = 3 * n_nodes if conex else 0 def chunk_worker(b, a, e, lat, lon): - d_batch, c_batch = self.run( + run_result = self.run( b, a, e, lat, lon, cloudf=cloudf, + conex=conex, n_nodes=n_nodes, n_slant_sub=n_slant_sub, per_wavelength=per_wavelength, @@ -942,9 +958,16 @@ def chunk_worker(b, a, e, lat, lon): n_energy_high=n_energy_high, photon_model=photon_model, ) + if conex: + d_batch, c_batch, rn_batch, z_batch, x_batch = run_result + else: + d_batch, c_batch = run_result # d_batch is (N,) collapsed or (N, n_wl); make it (n_den, N). d_rows = d_batch.T if per_wavelength else d_batch[None, :] - return np.concatenate([d_rows, c_batch[None, :]], axis=0) + rows = [d_rows, c_batch[None, :]] + if conex: + rows.extend([rn_batch.T, z_batch.T, x_batch.T]) + return np.concatenate(rows, axis=0) if serial: results = chunk_worker( @@ -954,7 +977,7 @@ def chunk_worker(b, a, e, lat, lon): results = map_showers_distributed( chunk_worker, (betaE, alt, Eshow100PeV, init_lat, init_long), - n_rows=n_den + 1, + n_rows=n_den + 1 + diagnostic_rows, chunks=chunks, client=client, ) @@ -962,4 +985,11 @@ def chunk_worker(b, a, e, lat, lon): # Unpack (n_rows, N): density rows then the Cang row. Collapsed -> # (N,); per-wavelength -> (N, n_wl) (transpose back the n_den rows). dphots = results[0] if n_den == 1 else results[:n_den].T - return dphots, results[n_den] + cang = results[n_den] + if conex: + diagnostics = results[n_den + 1 :] + rn = diagnostics[:n_nodes].T + z_nodes = diagnostics[n_nodes : 2 * n_nodes].T + x_to_node = diagnostics[2 * n_nodes :].T + return dphots, cang, rn, z_nodes, x_to_node + return dphots, cang diff --git a/src/nuspacesim/simulation/eas_optical/eas.py b/src/nuspacesim/simulation/eas_optical/eas.py index 3a3f8b98..4b9b5017 100644 --- a/src/nuspacesim/simulation/eas_optical/eas.py +++ b/src/nuspacesim/simulation/eas_optical/eas.py @@ -91,6 +91,7 @@ def __call__( init_long, *args, cloudf=None, + conex=False, client=None, serial=False, **kwargs, @@ -115,13 +116,14 @@ def __call__( # Run CphotAng on in-bounds events quad = self.config.simulation.cherenkov_quadrature - dphots[mask], thetaCh100PeV[mask] = self.CphotAng( + cphotang_result = self.CphotAng( beta[mask], altDec[mask], showerEnergy[mask], init_lat[mask], init_long[mask], cloudf, + conex, client=client, serial=serial, n_nodes=quad.n_nodes, @@ -129,6 +131,7 @@ def __call__( n_energy_low=quad.n_energy_low, n_energy_high=quad.n_energy_high, ) + dphots[mask], thetaCh100PeV[mask] = cphotang_result[:2] numPEs = ( dphots @@ -149,6 +152,8 @@ def __call__( costhetaChEff = np.cos(np.radians(thetaChEff)) + if conex: + return numPEs, costhetaChEff, *cphotang_result[2:] return numPEs, costhetaChEff diff --git a/src/nuspacesim/utils/decorators.py b/src/nuspacesim/utils/decorators.py index dcc594b9..95f42a12 100644 --- a/src/nuspacesim/utils/decorators.py +++ b/src/nuspacesim/utils/decorators.py @@ -83,8 +83,8 @@ def store_f(*args, store=None, **kwargs): values = func(*args, **kwargs) if store is not None: if isinstance(values, tuple): - assert len(names) == len(values) - store(names, [*values]) + assert len(values) >= len(names) + store(names, [*values[: len(names)]]) else: assert len(names) == 1 store(names, [values]) From 4308232de76658c1d526ed97880a96de726513a2 Mon Sep 17 00:00:00 2001 From: jorge Date: Thu, 24 Sep 2026 19:59:06 +0200 Subject: [PATCH 2/5] Restored sample config to original --- sample_input_file.toml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/sample_input_file.toml b/sample_input_file.toml index 118948a5..8dc33835 100644 --- a/sample_input_file.toml +++ b/sample_input_file.toml @@ -30,12 +30,12 @@ gain = "1.8 dB" [simulation] mode = "Diffuse" -thrown_events = 100000 +thrown_events = 100 max_cherenkov_angle = "3.0000000000000004 deg" max_azimuth_angle = "360.0 deg" angle_from_limb = "7.0 deg" eas_long_profile = "Greisen" -conex_output = true +conex_output = false cherenkov_light_engine = "nuspacesim" [simulation.ionosphere] @@ -56,7 +56,7 @@ table_version = "3" [simulation.spectrum] id = "monospectrum" -log_nu_energy = 9.0 +log_nu_energy = 8.0 [simulation.cloud_model] id = "no_cloud" From 96ad056a33fa381610d3f6257a3932b97e0d2daf Mon Sep 17 00:00:00 2001 From: jorge Date: Thu, 24 Sep 2026 20:03:48 +0200 Subject: [PATCH 3/5] Updated dependencies with uproot --- setup.cfg | 1 + 1 file changed, 1 insertion(+) diff --git a/setup.cfg b/setup.cfg index fe7b6aa3..918bc0f2 100644 --- a/setup.cfg +++ b/setup.cfg @@ -39,6 +39,7 @@ install_requires = scipy tomli-w tomli;python_version<"3.11" + uproot python_requires = >=3.9 package_dir = = src From 1c34cbb0931113212c624d8f1dd96102472a6556 Mon Sep 17 00:00:00 2001 From: jorge Date: Thu, 24 Sep 2026 20:11:08 +0200 Subject: [PATCH 4/5] Updated dependencies with uproot --- setup.cfg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.cfg b/setup.cfg index 918bc0f2..c9de9087 100644 --- a/setup.cfg +++ b/setup.cfg @@ -38,8 +38,8 @@ install_requires = rich scipy tomli-w - tomli;python_version<"3.11" uproot + tomli;python_version<"3.11" python_requires = >=3.9 package_dir = = src From 61847e1936bdcdb71f7bf2d8da7c81069473ed89 Mon Sep 17 00:00:00 2001 From: Alex Reustle Date: Thu, 8 Oct 2026 14:31:48 -0400 Subject: [PATCH 5/5] CONEX output: write nuSpaceSim shower profiles as CONEX ROOT files Adds CONEX-format output of the optical showers' longitudinal profiles (resolves #129), enabled by `nuspacesim run -c` or simulation.conex_output. * conex/format.py codifies the CONEX Header/Shower trees as fixed-shape NumPy structured dtypes. Every shower shares the fixed EAS node grid, so profile branches are fixed X[n_nodes] leaves -- no variable-length arrays. * conex/root_file.py writes those trees directly; no uproot/awkward dependency. Verified with ROOT 6.40 and uproot. * conex/writer.py maps profiles onto the format (Gaisser-Hillas fit, depths from ground, dE/dX) and provides ConexWriter. * compute() takes an on_shower_profile callable, forwarded through EAS and CphotAng as on_profile; it receives a fixed-shape ShowerProfile without changing any return value (serial and dask alike). No conditional branching in compute.py. lgE uses showerEnergy (the energy the profile was built with); geometry uses the beta the node grid was built with (clamped to >= 1 deg); showers whose maximum lies outside the visible window are skipped. Co-Authored-By: jorge Co-Authored-By: Claude Opus 5.5 --- .gitignore | 3 +- setup.cfg | 1 - src/nuspacesim/apps/run.py | 3 + src/nuspacesim/compute.py | 55 ++- src/nuspacesim/conex/__init__.py | 10 + src/nuspacesim/conex/format.py | 207 +++++++++++ src/nuspacesim/conex/root_file.py | 325 ++++++++++++++++ src/nuspacesim/conex/writer.py | 145 ++++++++ src/nuspacesim/conex_out.py | 350 ------------------ src/nuspacesim/config.py | 6 +- .../simulation/eas_optical/cphotang.py | 132 +++++-- src/nuspacesim/simulation/eas_optical/eas.py | 26 +- src/nuspacesim/utils/decorators.py | 4 +- test/conex/test_conex.py | 100 +++++ test/core/test_config.py | 2 + .../eas_optical/test_shower_profile_hook.py | 87 +++++ 16 files changed, 1026 insertions(+), 430 deletions(-) create mode 100644 src/nuspacesim/conex/__init__.py create mode 100644 src/nuspacesim/conex/format.py create mode 100644 src/nuspacesim/conex/root_file.py create mode 100644 src/nuspacesim/conex/writer.py delete mode 100644 src/nuspacesim/conex_out.py create mode 100644 test/conex/test_conex.py create mode 100644 test/simulation/eas_optical/test_shower_profile_hook.py diff --git a/.gitignore b/.gitignore index a6f0bf35..c500ecbc 100644 --- a/.gitignore +++ b/.gitignore @@ -189,6 +189,5 @@ AGENTS.md .claude/ docs/*.md -#debug files +# CONEX output files *.root -*.png diff --git a/setup.cfg b/setup.cfg index c9de9087..fe7b6aa3 100644 --- a/setup.cfg +++ b/setup.cfg @@ -38,7 +38,6 @@ install_requires = rich scipy tomli-w - uproot tomli;python_version<"3.11" python_requires = >=3.9 package_dir = diff --git a/src/nuspacesim/apps/run.py b/src/nuspacesim/apps/run.py index 7d52e6d9..d1891ca2 100644 --- a/src/nuspacesim/apps/run.py +++ b/src/nuspacesim/apps/run.py @@ -49,6 +49,7 @@ import click from ..compute import compute +from ..conex import ConexWriter, conex_path from ..config import config_from_toml from ..results_table import output_filename from ..utils.plot_function_registry import registry @@ -209,12 +210,14 @@ def run( plot = read_plot_config(registry, plotall, plotconfig, plot) output = output_filename(output) + conex = ConexWriter(conex_path(output)) if config.simulation.conex_output else None simulation = compute( config, verbose=True, to_plot=plot, output_file=output, write_stages=write_stages, + on_shower_profile=conex, ) if not no_result_file: diff --git a/src/nuspacesim/compute.py b/src/nuspacesim/compute.py index a29f4f39..6b64d5b3 100644 --- a/src/nuspacesim/compute.py +++ b/src/nuspacesim/compute.py @@ -48,7 +48,7 @@ from __future__ import annotations -from typing import Any, Iterable +from typing import Any, Callable, Iterable import numpy as np from astropy.table import Table as AstropyTable @@ -56,9 +56,9 @@ from rich.console import Console from . import results_table -from .conex_out import conex_out from .config import NssConfig from .simulation.atmosphere.clouds import CloudTopHeight +from .simulation.eas_optical.cphotang import ShowerProfile from .simulation.eas_optical.eas import EAS from .simulation.eas_radio.radio import EASRadio from .simulation.eas_radio.radio_antenna import calculate_snr @@ -78,6 +78,7 @@ def compute( output_file: str | None = None, to_plot: list = [], write_stages=False, + on_shower_profile: Callable[[ShowerProfile], None] | None = None, ) -> AstropyTable: r"""Simulate an upward going shower. @@ -120,6 +121,12 @@ def compute( Call the listed plotting functions as appropritate. write_stages: bool, optional Enable writing intermediate results to the output_file. + on_shower_profile: callable, optional + Called with the :class:`ShowerProfile` (fixed-shape longitudinal + profiles) of the optically simulated showers; its ``index`` refers to + rows of the thrown-event arrays. Use it to emit per-shower outputs such + as CONEX files (:class:`nuspacesim.conex.ConexWriter`) without changing + the simulation. Default None. Returns ------- @@ -192,7 +199,6 @@ def add_meta(self, name: str, value: Any, comment: str): beta_tr, thetaArr, pathLenArr, *_ = geom( config.simulation.thrown_events, store=sw, plot=to_plot ) - thrown_color = "[blue]" if beta_tr.size else "[red]" logv( f"\t{thrown_color}Threw {config.simulation.thrown_events} neutrinos.\ @@ -241,36 +247,19 @@ def add_meta(self, name: str, value: Any, comment: str): if config.detector.optical.enable: logv("Computing [green] EAS Optical Cherenkov light.[/]") - if config.simulation.conex_output: - numPEs, costhetaChEff, RN, z_nodes, X_to_node = eas( - beta_tr, - altDec, - showerEnergy, - init_lat, - init_long, - cloudf=cloud, - conex=True, - client=optical_cluster.client() if use_cluster else None, - serial=not use_cluster, - store=sw, - plot=to_plot, - ) - conex_out(sim, RN, z_nodes, X_to_node, output_file) - - else: - numPEs, costhetaChEff = eas( - beta_tr, - altDec, - showerEnergy, - init_lat, - init_long, - cloudf=cloud, - conex=False, - client=optical_cluster.client() if use_cluster else None, - serial=not use_cluster, - store=sw, - plot=to_plot, - ) + numPEs, costhetaChEff = eas( + beta_tr, + altDec, + showerEnergy, + init_lat, + init_long, + cloudf=cloud, + client=optical_cluster.client() if use_cluster else None, + serial=not use_cluster, + on_profile=on_shower_profile, + store=sw, + plot=to_plot, + ) # Single consumer is done; release the warm cluster immediately. if use_cluster: diff --git a/src/nuspacesim/conex/__init__.py b/src/nuspacesim/conex/__init__.py new file mode 100644 index 00000000..eeded559 --- /dev/null +++ b/src/nuspacesim/conex/__init__.py @@ -0,0 +1,10 @@ +r"""CONEX-format ROOT output of simulated shower profiles. + +* :mod:`~nuspacesim.conex.format` -- the fixed-shape output schema. +* :mod:`~nuspacesim.conex.writer` -- :class:`ConexWriter`, an + ``on_shower_profile`` callable for :func:`nuspacesim.compute.compute`. +""" + +from .writer import ConexWriter, build_showers, conex_path + +__all__ = ["ConexWriter", "build_showers", "conex_path"] diff --git a/src/nuspacesim/conex/format.py b/src/nuspacesim/conex/format.py new file mode 100644 index 00000000..ab973569 --- /dev/null +++ b/src/nuspacesim/conex/format.py @@ -0,0 +1,207 @@ +# The Clear BSD License +# +# Copyright (c) 2021 Alexander Reustle and the NuSpaceSim Team +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted (subject to the limitations in the disclaimer +# below) provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# * Neither the name of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived from this +# software without specific prior written permission. +# +# NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY +# THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND +# CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR +# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +r"""The nuSpaceSim CONEX output format: an explicit, fixed-shape schema. + +A CONEX file holds two TTrees (CONEX output version 2.51 branch names): + +* ``Header`` -- one entry describing the run. +* ``Shower`` -- one entry per shower, with scalar summary branches and + longitudinal *profile* branches. + +In CONEX proper the profile branches are variable length (``X[nX]/F``). Here +every shower is sampled on the same fixed set of ``n_nodes`` longitudinal nodes +(the EAS optical quadrature grid), so each profile branch is a *fixed* array +leaf ``X[n_nodes]/F`` and the whole format is a NumPy structured dtype: +:func:`shower_dtype` is the template, :func:`empty_showers` instantiates it with +every field at its documented fill value, and the writer only overwrites the +fields nuSpaceSim actually computes. The ``n*`` count branches are kept (always +``n_nodes``) so readers written against CONEX, which loop to ``nX``, still work. + +Every field below states its type, unit, and the value written when nuSpaceSim +has no counterpart (``fill``). Change the format here, nowhere else. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +import numpy as np + +__all__ = [ + "Field", + "HEADER_FIELDS", + "SHOWER_FIELDS", + "PROFILE", + "header_dtype", + "shower_dtype", + "empty_header", + "empty_showers", +] + +PROFILE = "profile" # shape marker: one value per longitudinal node +N_LAMBDA = 31 # CONEX hadronic cross-section table length + + +@dataclass(frozen=True) +class Field: + name: str + dtype: str + unit: str + doc: str + fill: float | int = 0 + shape: tuple | str = () + + +nan = float("nan") + +HEADER_FIELDS = ( + Field("Seed1", "i4", "", "Random seed (none used)", -1), + Field( + "Particle", "i4", "", "Primary particle code (100 = proton; no tau code)", 100 + ), + Field("Alpha", "f8", "", "Energy spectrum slope (unset)", nan), + Field("lgEmin", "f8", "log10(eV)", "Minimum primary energy (unset)", nan), + Field("lgEmax", "f8", "log10(eV)", "Maximum primary energy (unset)", nan), + Field("zMin", "f8", "deg", "Minimum zenith angle", 90), + Field("zMax", "f8", "deg", "Maximum zenith angle", 132), + Field("SvnRevision", "i1", "", "CONEX revision (unset)", 0), + Field("Version", "f4", "", "CONEX version emulated", 64), + Field("OutputVersion", "f4", "", "CONEX output format version", 2.51), + Field("HEModel", "i4", "", "High-energy hadronic model (none)", -1), + Field("LEModel", "i4", "", "Low-energy hadronic model (none)", -1), + Field("HiLowEgy", "f4", "GeV", "HE/LE model transition energy (unset)", nan), + Field("hadCut", "f4", "", "Hadron MC/CE switch threshold (unset)", nan), + Field("emCut", "f4", "", "EM MC/CE switch threshold (unset)", nan), + Field("hadThr", "f4", "GeV", "Hadron threshold (unset)", nan), + Field("muThr", "f4", "GeV", "Muon threshold (unset)", nan), + Field("emThr", "f4", "GeV", "EM threshold (unset)", nan), + Field("haCut", "f4", "GeV", "Hadron energy cut (unset)", nan), + Field("muCut", "f4", "GeV", "Muon energy cut (unset)", nan), + Field("elCut", "f4", "GeV", "Electron energy cut (unset)", nan), + Field("gaCut", "f4", "GeV", "Photon energy cut (unset)", nan), + Field( + "lambdaLgE", "f8", "log10(eV)", "Cross-section table energies", nan, (N_LAMBDA,) + ), + Field("lambdaProton", "f8", "g/cm2", "Proton interaction length", nan, (N_LAMBDA,)), + Field("lambdaPion", "f8", "g/cm2", "Pion interaction length", nan, (N_LAMBDA,)), + Field("lambdaHelium", "f8", "g/cm2", "Helium interaction length", nan, (N_LAMBDA,)), + Field( + "lambdaNitrogen", "f8", "g/cm2", "Nitrogen interaction length", nan, (N_LAMBDA,) + ), + Field("lambdaIron", "f8", "g/cm2", "Iron interaction length", nan, (N_LAMBDA,)), +) + +_PROFILE_COUNTS = ("nX", "nN", "nH", "nD", "ndEdX", "nMu", "nGamma", "nElectrons") +_PROFILE_COUNTS += ("nHadrons", "ndMu") + +SHOWER_FIELDS = ( + Field("lgE", "f4", "log10(eV)", "Shower energy"), + Field("zenith", "f4", "deg", "Zenith angle of the axis (90 + emergence angle)"), + Field("azimuth", "f4", "deg", "Azimuth of the axis (uniform random)"), + Field("Seed2", "i4", "", "Random seed (none used)", -1), + Field("Seed3", "i4", "", "Random seed (none used)", -1), + Field("Xfirst", "f4", "g/cm2", "Slant depth from ground to the tau decay point"), + Field("Hfirst", "f4", "m", "Altitude of the tau decay point"), + Field("XfirstIn", "f4", "", "Inverse first-interaction length (fixed)", 0.5), + Field("altitude", "f8", "m", "Observation altitude (unset)", nan), + Field("X0", "f4", "g/cm2", "Gaisser-Hillas X0", nan), + Field("Xmax", "f4", "g/cm2", "Gaisser-Hillas Xmax", nan), + Field("Nmax", "f4", "", "Gaisser-Hillas Nmax", nan), + Field("p1", "f4", "g/cm2", "GH lambda(X) = p1 + p2 X + p3 X^2: constant", nan), + Field("p2", "f4", "", "GH lambda(X): linear coefficient", nan), + Field("p3", "f4", "cm2/g", "GH lambda(X): quadratic coefficient", nan), + Field("chi2", "f4", "", "Gaisser-Hillas fit quality (x1e5, CONEX scaling)", nan), + Field("Xmx", "f4", "g/cm2", "Depth of the profile node with the most particles"), + Field("Nmx", "f4", "", "Particle count at Xmx"), + Field("XmxdEdX", "f4", "g/cm2", "Depth of the dE/dX maximum (taken = Xmx)"), + Field("dEdXmx", "f4", "GeV cm2/g", "dE/dX at Xmx"), + Field("cpuTime", "f4", "s", "CPU time (unset)", nan), + Field("X", "f4", "g/cm2", "Slant depth from ground at each node", shape=PROFILE), + Field("N", "f4", "", "Charged particles at each node", shape=PROFILE), + Field("H", "f4", "m", "Altitude of each node", shape=PROFILE), + Field("D", "f4", "m", "Distance from ground along the axis", shape=PROFILE), + Field( + "dEdX", "f4", "GeV cm2/g", "Energy deposit (age-parameterized)", shape=PROFILE + ), + Field("Mu", "f4", "", "Muons (not simulated)", shape=PROFILE), + Field("Gamma", "f4", "", "Photons (not simulated)", shape=PROFILE), + Field("Electrons", "f4", "", "Electrons (= N)", shape=PROFILE), + Field("Hadrons", "f4", "", "Hadrons (not simulated)", shape=PROFILE), + Field("dMu", "f4", "", "Muon production (not simulated)", shape=PROFILE), + *( + Field(c, "i4", "", f"Length of {c[1:]} (always n_nodes)") + for c in _PROFILE_COUNTS + ), + Field("EGround", "f4", "GeV", "Energy reaching ground (unset)", nan, (3,)), +) + + +def _dtype(fields, n_nodes=None) -> np.dtype: + spec = [] + for f in fields: + shape = (n_nodes,) if f.shape == PROFILE else f.shape + spec.append((f.name, f.dtype, shape) if shape else (f.name, f.dtype)) + return np.dtype(spec) + + +def header_dtype() -> np.dtype: + """Structured dtype of one ``Header`` entry.""" + return _dtype(HEADER_FIELDS) + + +def shower_dtype(n_nodes: int) -> np.dtype: + """Structured dtype of one ``Shower`` entry with ``n_nodes`` profile nodes.""" + if n_nodes < 1: + raise ValueError(f"n_nodes must be >= 1, got {n_nodes}") + return _dtype(SHOWER_FIELDS, n_nodes) + + +def _filled(fields, dtype, n, n_nodes) -> np.ndarray: + out = np.zeros(n, dtype) + for f in fields: + out[f.name] = f.fill + if n_nodes is not None: + for c in _PROFILE_COUNTS: + out[c] = n_nodes + return out + + +def empty_header() -> np.ndarray: + """A 1-entry ``Header`` array with every field at its fill value.""" + return _filled(HEADER_FIELDS, header_dtype(), 1, None) + + +def empty_showers(n: int, n_nodes: int) -> np.ndarray: + """``n`` ``Shower`` entries with every field at its fill value.""" + return _filled(SHOWER_FIELDS, shower_dtype(n_nodes), n, n_nodes) diff --git a/src/nuspacesim/conex/root_file.py b/src/nuspacesim/conex/root_file.py new file mode 100644 index 00000000..807e06c7 --- /dev/null +++ b/src/nuspacesim/conex/root_file.py @@ -0,0 +1,325 @@ +r"""Minimal ROOT file writer for the CONEX ``Header`` and ``Shower`` trees. + +Writes flat TTrees from NumPy structured arrays -- one branch per field, a +``(k,)`` subarray field as a fixed ``name[k]`` leaf -- with no ROOT/uproot +dependency. Scope is exactly what the CONEX schema needs: int8/int32/float32/ +float64 leaves, uncompressed, one basket per branch, files under 2 GB. + +Layout (written front to back):: + + 0 file header (fBEGIN = 100) + 100 TFile key + top directory, (empty) StreamerInfo record + per tree: one TBasket per branch, then the TTree + KeysList, FreeSegments + fEND + +Object layouts follow ROOT 6.24 (TTree v20, TBranch v13, TLeaf v2) as +written by uproot; see ROOT's ``io/doc/TFile`` format notes. +""" + +from __future__ import annotations + +import datetime +import os +import struct +import uuid + +import numpy as np + +__all__ = ["write_trees"] + +_BEGIN = 100 +_LIMIT = 2_000_000_000 # 4-byte seek limit of the small file format +_BYTECOUNT = 0x40000000 +_NEW_CLASS = 0xFFFFFFFF +_ON_HEAP_NOT_DELETED = 0x03000000 + +# dtype -> (TLeaf letter, fMinimum/fMaximum format) +_LEAF = {"i1": ("B", ">bb"), "i4": ("I", ">ii"), "f4": ("F", ">ff"), "f8": ("D", ">dd")} + +_KEY = struct.Struct(">ihiIhhii") # small TKey: 4-byte seeks +_KEY_BIG = struct.Struct(">ihiIhhqq") # TTree/TBasket keys (as ROOT/uproot write them) +_TIOFEATURES = b"@\x00\x00\x07\x00\x00\x1a\xa1/\x10\x00" +_EMPTY_TOBJARRAY = b"@\x00\x00\x15\x00\x03\x00\x01\x00\x00\x00\x00\x03" + b"\x00" * 12 + + +def _tstring(s: str) -> bytes: + b = s.encode() + assert len(b) < 255 + return bytes([len(b)]) + b + + +class _Buffer: + """Big-endian builder with back-patched ROOT byte counts.""" + + def __init__(self): + self.data = bytearray() + + def put(self, b): + self.data += b + + def pack(self, fmt, *values): + self.data += struct.pack(fmt, *values) + + def open(self, version=None, classname=None): + pos = len(self.data) + if classname is None: + self.pack(">IH", 0, version) + else: + self.pack(">II", 0, _NEW_CLASS) + self.put(classname.encode() + b"\x00") + return pos + + def close(self, pos): + count = (len(self.data) - pos - 4) | _BYTECOUNT + struct.pack_into(">I", self.data, pos, count) + + def tnamed(self, name, title, bits=0): + pos = self.open(1) + self.pack(">HII", 1, 0, bits | _ON_HEAP_NOT_DELETED) + self.put(_tstring(name) + _tstring(title)) + self.close(pos) + + def tobjarray_header(self, size): + self.pack(">HII", 1, 0, _ON_HEAP_NOT_DELETED) + self.put(b"\x00") # fName "" + self.pack(">ii", size, 0) + + +def _branches(records): + out = [] + for name in records.dtype.names: + field = records.dtype[name] + base, shape = field.subdtype or (field, ()) + code = f"{base.kind}{base.itemsize}" + if code not in _LEAF or len(shape) > 1: + raise TypeError(f"branch {name!r}: unsupported field type {field}") + out.append((name, base.newbyteorder(">"), shape)) + return out + + +def _ttree(name, title, n, branches, baskets, keylen): + """Serialize a TTree; ``baskets[name] = (seek, nbytes, totbytes)``.""" + buf = _Buffer() + tree = buf.open(20) + buf.tnamed(name, title, bits=0x8) # kMustCleanup + buf.put(b"@\x00\x00\x08\x00\x02" + struct.pack(">hhh", 602, 1, 1)) # TAttLine + buf.put(b"@\x00\x00\x06\x00\x02" + struct.pack(">hh", 0, 1001)) # TAttFill + buf.put(b"@\x00\x00\x0a\x00\x02" + struct.pack(">hhf", 1, 1, 1.0)) # TAttMarker + tot = sum(b[2] for b in baskets.values()) + zipped = sum(b[1] for b in baskets.values()) + # fEntries .. fEstimate (TTree v20 members), then empty cluster arrays. + buf.pack( + ">qqqqqdiiiiIqqqqqq", + n, + tot, + zipped, + 0, + 0, + 1.0, + 0, + 25, + 0, + 1000, + 0, + 10**12, + 10**12, + 0, + -300_000_000, + -30_000_000, + 1_000_000, + ) + buf.put(b"\x00\x00" + _TIOFEATURES) + + arr = buf.open(3) + buf.tobjarray_header(len(branches)) + leaf_refs = [] + for bname, dtype, shape in branches: + letter, minmax = _LEAF[f"{dtype.kind}{dtype.itemsize}"] + dims = "".join(f"[{d}]" for d in shape) + seek, nbytes, totbytes = baskets[bname] + nb = 1 if n else 0 + + obj = buf.open(classname="TBranch") + ver = buf.open(13) + buf.tnamed(bname, f"{bname}{dims}/{letter}", bits=0x00400000) + buf.put(b"@\x00\x00\x06\x00\x02" + struct.pack(">hh", 0, 1001)) # TAttFill + buf.pack(">iiiiq", 0, 32000, 0, nb, n) # fCompress .. fEntryNumber + buf.put(_TIOFEATURES) + buf.pack(">iIiqqqq", 0, 2, 0, n, 0, totbytes, nbytes) # fOffset .. fZipBytes + buf.put(_EMPTY_TOBJARRAY) # sub-branches + + leaves = buf.open(3) + buf.tobjarray_header(1) + leaf_refs.append(keylen + len(buf.data) + 2) # +kMapOffset + leaf = buf.open(classname=f"TLeaf{letter}") + typed = buf.open(1) + base = buf.open(2) + buf.tnamed(bname, f"{bname}{dims}") + buf.pack(">iii??", int(np.prod(shape)), dtype.itemsize, 0, False, False) + buf.put(b"\x00" * 4) # no fLeafCount: fixed length + buf.close(base) + buf.pack(minmax, 0, 0) + buf.close(typed) + buf.close(leaf) + buf.close(leaves) + + buf.put(_EMPTY_TOBJARRAY) # fBaskets + buf.put(b"\x01" + struct.pack(">ii", nbytes if n else 0, 0)) # fBasketBytes + buf.put(b"\x01" + struct.pack(">qq", 0, n)) # fBasketEntry + buf.put(b"\x01" + struct.pack(">qq", seek if n else 0, 0)) # fBasketSeek + buf.put(b"\x00") # fFileName + buf.close(ver) + buf.close(obj) + buf.close(arr) + + leaves = buf.open(3) + buf.tobjarray_header(len(leaf_refs)) + buf.pack(f">{len(leaf_refs)}I", *leaf_refs) + buf.close(leaves) + buf.put(b"\x00" * 28) # fAliases .. fBranchRef: all empty + buf.close(tree) + return bytes(buf.data) + + +def write_trees(path, trees): + """Write ``{name: (title, structured array)}`` as TTrees to a new ROOT file.""" + filename = os.path.basename(os.fspath(path)) + t = datetime.datetime.now() + datime = ( + (t.year - 1995) << 26 + | t.month << 22 + | t.day << 17 + | t.hour << 12 + | t.minute << 6 + | t.second + ) + file_uuid = uuid.uuid4().bytes + # Empty StreamerInfo TList: ROOT and uproot have built-in layouts for + # TTree/TBranch/TLeaf, so no class descriptions are needed. + payload = struct.pack(">IHHIIBI", 17 | _BYTECOUNT, 5, 1, 0, 0x02000000, 0, 0) + names = _tstring(filename) + _tstring("") + + def key(fmt, cls, name, title, objlen, seek, pdir=_BEGIN): + strings = _tstring(cls) + _tstring(name) + _tstring(title) + keylen = fmt.size + len(strings) + version = 1004 if fmt is _KEY_BIG else 4 + head = fmt.pack(keylen + objlen, version, objlen, datime, keylen, 1, seek, pdir) + return head + strings + + with open(path, "wb") as fh: + fh.write(b"\x00" * _BEGIN) + dir_rec = 60 # TDirectory record (fits the big variant too) + top = key(_KEY, "TFile", filename, "", len(names) + dir_rec, _BEGIN, 0) + fh.write(top + names) + dir_at = fh.tell() + fh.write(b"\x00" * dir_rec) + + seek_info = fh.tell() + fh.write( + key( + _KEY, + "TList", + "StreamerInfo", + "Doubly linked list", + len(payload), + seek_info, + ) + + payload + ) + nbytes_info = fh.tell() - seek_info + + top_keys = [] + for tname, (title, records) in trees.items(): + branches = _branches(records) + baskets = {} + for bname, dtype, _ in branches: + raw = np.ascontiguousarray(records[bname], dtype=dtype).tobytes() + strings = _tstring("TBasket") + _tstring(bname) + _tstring(tname) + keylen = _KEY_BIG.size + len(strings) + 19 # + TBasket header, flag + seek = fh.tell() + entry_bytes = len(raw) // max(len(records), 1) + fh.write( + _KEY_BIG.pack( + keylen + len(raw), + 1004, + len(raw), + datime, + keylen, + 1, + seek, + _BEGIN, + ) + + strings + ) + fh.write( + struct.pack( + ">Hiiii", 3, 32000, entry_bytes, len(records), keylen + len(raw) + ) + + b"\x00" + + raw + ) + baskets[bname] = (seek, keylen + len(raw), keylen + len(raw)) + strings = _tstring("TTree") + _tstring(tname) + _tstring(title) + body = _ttree( + tname, + title, + len(records), + branches, + baskets, + _KEY_BIG.size + len(strings), + ) + k = key(_KEY_BIG, "TTree", tname, title, len(body), fh.tell()) + fh.write(k + body) + top_keys.append(k) + + seek_keys = fh.tell() + body = struct.pack(">i", len(top_keys)) + b"".join(top_keys) + fh.write(key(_KEY, "TFile", filename, "", len(body), seek_keys) + body) + nbytes_keys = fh.tell() - seek_keys + + seek_free = fh.tell() + end = seek_free + _KEY.size + len(_tstring("TFile") + names) + 10 + if end >= _LIMIT: + raise ValueError(f"{path}: CONEX file would exceed 2 GB") + fh.write( + key(_KEY, "TFile", filename, "", 10, seek_free) + + struct.pack(">HII", 1, end, _LIMIT) + ) + + fh.seek(dir_at) + fh.write( + struct.pack( + ">hIIiiiii", + 5, + datime, + datime, + nbytes_keys, + len(top) + len(names), + _BEGIN, + 0, + seek_keys, + ) + + b"\x00\x01" + + file_uuid + ) + fh.seek(0) + fh.write( + struct.pack( + ">4siiiiiiiBiiiH16s", + b"root", + 62400, + _BEGIN, + end, + seek_free, + end - seek_free, + 1, + len(top) + len(names), + 4, + 0, + seek_info, + nbytes_info, + 1, + file_uuid, + ) + ) diff --git a/src/nuspacesim/conex/writer.py b/src/nuspacesim/conex/writer.py new file mode 100644 index 00000000..20d7c3d5 --- /dev/null +++ b/src/nuspacesim/conex/writer.py @@ -0,0 +1,145 @@ +r"""Map nuSpaceSim shower profiles onto the CONEX format and write it. + +:class:`ConexWriter` is an ``on_shower_profile`` callable for +:func:`nuspacesim.compute.compute`:: + + compute(config, on_shower_profile=ConexWriter("conex_run.root")) +""" + +from __future__ import annotations + +import warnings +from pathlib import Path + +import numpy as np +from scipy.optimize import OptimizeWarning, curve_fit, least_squares + +from ..simulation.eas_optical.cphotang import ShowerProfile +from ..simulation.eas_optical.propagation import lexpr, slant_depth +from .format import empty_header, empty_showers +from .root_file import write_trees + +__all__ = ["ConexWriter", "build_showers", "conex_path"] + + +def conex_path(output_file) -> Path: + """CONEX file name for a results file: ``dir/conex_.root``.""" + p = Path(output_file) + name = p.with_suffix(".root").name + return p.with_name(name if name.startswith("conex") else f"conex_{name}") + + +def gaisser_hillas(X, X0, Xmax, Nmax, p3, p2, p1): + lam = p3 * X**2 + p2 * X + p1 + return ( + Nmax + * ((X - X0) / (Xmax - X0)) ** ((Xmax - X0) / lam) + * np.exp((Xmax - X) / lam) + ) + + +def _fit_gh(X, N): + """Six-parameter Gaisser-Hillas fit of one profile, CONEX conventions. + + Fits nodes up to twice the peak index, shifted to the first node and with N + scaled by 1e-5. Returns ``(X0, Xmax, Nmax, p1, p2, p3, chi2)``; all NaN when + there are no more points than parameters or no finite fit is found. + """ + x0 = X[0] + stop = 2 * int(np.argmax(N)) + x, y = X[:stop] - x0, N[:stop] / 1e5 + if x.size <= 6: + return (np.nan,) * 7 + peak = int(np.argmax(y)) + init = [-0.30943336 * x[peak], x[peak], y[peak], 1e-7, 4e-4, 44.0] + popt = None + with warnings.catch_warnings(): + warnings.simplefilter("ignore", (OptimizeWarning, RuntimeWarning)) + try: + popt, _ = curve_fit(gaisser_hillas, x, y, p0=init, maxfev=1_000_000) + except (RuntimeError, ValueError): + pass + if popt is None or not np.all(np.isfinite(popt)): + popt = least_squares( + lambda p: gaisser_hillas(x, *p) - y, init, max_nfev=1_000_000 + ).x + if not np.all(np.isfinite(popt)): + return (np.nan,) * 7 + yfit = gaisser_hillas(x, *popt) + pos = y > 0 + chi2 = np.sum((y[pos] - yfit[pos]) ** 2 / y[pos]) + chi2 = chi2 / (x.size - 6) / np.sqrt(popt[2] * 1e5) * 1e5 + g3, g2, g1 = popt[3], popt[4], popt[5] + # Undo the shift X -> X - x0 (lambda's coefficients re-expand about 0). + return ( + popt[0] + x0, + popt[1] + x0, + popt[2] * 1e5, + g1 - g2 * x0 + g3 * x0**2, + g2 - 2 * g3 * x0, + g3, + chi2, + ) + + +def build_showers(profile: ShowerProfile, rng: np.random.Generator) -> np.ndarray: + """Fill CONEX ``Shower`` records from a profile batch. + + Keeps showers whose particle maximum lies inside the node window (first and + last node below the peak). Depths are measured from ground along the axis: + ``X`` adds the ground-to-decay slant depth ``Xfirst``. + """ + N = profile.N + peak_N = N.max(axis=1) + keep = (N[:, 0] < peak_N) & (N[:, -1] < peak_N) + beta, alt, N, z = profile.beta[keep], profile.altDec[keep], N[keep], profile.z[keep] + n, n_nodes = N.shape + + L_ground = lexpr(0.0, beta) + Xfirst = slant_depth(L_ground, lexpr(alt, beta), beta) + X = profile.X[keep] + Xfirst[:, None] + fit = np.array([_fit_gh(X[i], N[i]) for i in range(n)]).reshape(n, 7) + + rows = np.arange(n) + peak = np.argmax(N, axis=1) + Xmx = X[rows, peak] + # Energy deposit: age about the fitted Xmax (peak node if the fit failed). + xmax_ref = np.where(np.isnan(fit[:, 1]), Xmx, fit[:, 1]) + age = 3.0 * X / (X + 2.0 * xmax_ref[:, None]) + alpha = (47.9511 / (0.971315 + age) ** 9.23001 + 2.29587 + 0.285196 * age) * 1e-3 + dEdX = alpha * N + + out = empty_showers(n, n_nodes) + out["lgE"] = np.log10(profile.showerEnergy[keep]) + 17.0 # 100 PeV = 1e17 eV + out["zenith"] = 90.0 + np.degrees(beta) + out["azimuth"] = 360.0 * rng.random(n) + out["Xfirst"] = Xfirst + out["Hfirst"] = alt * 1e3 + for j, name in enumerate(("X0", "Xmax", "Nmax", "p1", "p2", "p3", "chi2")): + out[name] = fit[:, j] + out["Xmx"] = out["XmxdEdX"] = Xmx + out["Nmx"] = N[rows, peak] + out["dEdXmx"] = dEdX[rows, peak] + out["X"] = X + out["N"] = out["Electrons"] = N + out["H"] = z * 1e3 + out["D"] = (lexpr(z, beta[:, None]) - L_ground[:, None]) * 1e3 + out["dEdX"] = dEdX + return out + + +class ConexWriter: + """``on_shower_profile`` callable writing the profiles to a CONEX ROOT file.""" + + def __init__(self, path, rng=None): + self.path = Path(path) + self.rng = np.random.default_rng() if rng is None else rng + + def __call__(self, profile: ShowerProfile) -> None: + write_trees( + self.path, + { + "Header": ("run header", empty_header()), + "Shower": ("shower info", build_showers(profile, self.rng)), + }, + ) diff --git a/src/nuspacesim/conex_out.py b/src/nuspacesim/conex_out.py deleted file mode 100644 index f327a32a..00000000 --- a/src/nuspacesim/conex_out.py +++ /dev/null @@ -1,350 +0,0 @@ -import numpy as np -import uproot -from scipy.optimize import curve_fit, least_squares - -from .simulation.eas_optical.propagation import lexpr, slant_depth - - -def conex_out(data, RN, z_nodes, X_to_node, output_file): # noqa: C901 - def GH(X, X0, Xmax, Nmax, p3, p2, p1): - return ( - Nmax - * ((X - X0) / (Xmax - X0)) ** ((Xmax - X0) / (p3 * X**2 + p2 * X + p1)) - * np.exp((Xmax - X) / (p3 * X**2 + p2 * X + p1)) - ) - - def alpha(s): - c1 = 47.9511 - c2 = 0.971315 - c3 = 9.23001 - c4 = 2.29587 - c5 = 0.285196 - return (c1 / (c2 + s) ** c3 + c4 + c5 * s) * 0.001 - - def showerage(x, xmax): - return 3 * x / (x + 2 * xmax) - - Zfirst = np.asarray(data["altDec"], dtype=np.float64) - TauEnergy = np.log10(np.asarray(data["tauEnergy"], dtype=np.float64)) + 9 - RN = np.asarray(RN, dtype=np.float64) - Zmax = 20 - Zmin = 0 - # TauEnergyMax=18 - # Useful masks (Zfirst masks are necessary between 0 and 20km). To introduce masks you must also change them in simulation/eas_optical/eas.py - z_mask = np.asarray((Zfirst >= Zmin) & (Zfirst <= Zmax), dtype=bool) - beta = np.asarray(data["beta_rad"], dtype=np.float64)[z_mask] - Zfirst = Zfirst[z_mask] - TauEnergy = TauEnergy[z_mask] - rn_max_not_reached = RN[:, -1] < np.max(RN[:, :-1], axis=1) - mask = rn_max_not_reached - beta = beta[mask] - Zfirst = Zfirst[mask] - TauEnergy = TauEnergy[mask] - beta = np.asarray(beta, dtype=np.float64) - RN = RN[mask] - z_nodes = np.asarray(z_nodes, dtype=np.float64)[mask] - X_to_node = np.asarray(X_to_node, dtype=np.float64)[mask] - - # The optical pipeline's X_to_node starts at the decay point. CONEX X must - # start at ground, so add the slant depth from ground to each decay point. - ground_length = lexpr(0.0, beta) - decay_length = lexpr(Zfirst, beta) - Xfirst = slant_depth(ground_length, decay_length, beta) - - n = np.size(Zfirst) - X = np.asarray(X_to_node + Xfirst[:, None], dtype=np.float32) - Z = np.asarray(z_nodes, dtype=np.float32) - RN = np.asarray(RN, dtype=np.float32) - print(f"Number of valid events with Xmax inside atmosphere: {n}") - # CONEX D is propagation distance measured from ground, in km here. - D = lexpr(z_nodes, beta[:, None]) - ground_length[:, None] - profile_size = X_to_node.shape[-1] - - azim = 360 * np.random.rand(n) # Random azimuth - zenith = 90 + np.degrees(beta) - # Force file name to end in .root and start with conex - if not output_file.endswith(".root"): - # strip any existing extension and add .root - output_file = ".".join(output_file.split(".")[:-1]) + ".root" - if not output_file.startswith("conex"): - output_file = "conex_" + output_file - # Useful variables to fill the conex File - PID = np.array([100], dtype="i4") # Proton type for Conex - zmin = np.array([90], dtype="i4") - zmax = np.array([132], dtype="i4") - nan4 = np.array([np.nan], dtype="f4") - nan8 = np.array([np.nan], dtype="f8") - int4 = np.array([-1], dtype="i4") - intn = np.full(n, -1, dtype="i4") - nan4n = np.full(n, np.nan, dtype="f4") - nan8n = np.full(n, np.nan, dtype="f8") - Xempty = np.zeros_like(X) - OutputVersion = np.array([2.51], dtype="f4") - a = np.full((1, 31), np.nan, dtype="f8") - Eground = np.full((n, 3), nan4) - Eg = Eground - - # Initialize some variables for GH fit - Xmax = np.empty(n, dtype="f4") - Nmax = np.empty(n, dtype="f4") - X0 = np.empty(n, dtype="f4") - p1 = np.empty(n, dtype="f4") - p2 = np.empty(n, dtype="f4") - p3 = np.empty(n, dtype="f4") - chi2 = np.zeros(n, dtype="f4") - Xmx = np.empty(n, dtype="f4") - Nmx = np.empty(n, dtype="f4") - dEdXmx = np.empty(n, dtype="f4") - dEdX_profiles = [] - - for i in range(n): - x_profile = np.array(X[i]) - # Shift profile in X and reduce magnitude in N to simplify the fits. - x0 = x_profile[0] - x = x_profile - x0 - rn = np.array(RN[i]) - y = rn / 1e5 - - init = np.empty(6) - max_pos = np.argmax(y) - y = y[ - 0 : max_pos * 2 - ] # Only interested in profile around the maximum, disregard the tail - x = x[0 : max_pos * 2] - - # Best initial values for a good, fast and reliable fit. - init[1] = x[max_pos] - init[0] = -0.30943336 * init[1] - init[2] = y[max_pos] - init[3:] = [1e-7, 4e-4, 44] - - fit_succeeded = True - try: - popt, pcov = curve_fit(GH, x, y, p0=init, maxfev=1000000) - if not np.all(np.isfinite(popt)): - raise RuntimeError("curve_fit returned non-finite parameters") - except (RuntimeError, ValueError, FloatingPointError) as error: - print(f"Warning: fit failed for event {i}: {error}") - try: - fallback = least_squares( - lambda parameters: GH(x, *parameters) - y, - init, - max_nfev=1000000, - ) - popt = fallback.x - if not np.all(np.isfinite(popt)): - raise RuntimeError("least_squares returned non-finite parameters") - print(f"Using best-effort least-squares parameters for event {i}.") - except (RuntimeError, ValueError, FloatingPointError) as fallback_error: - print(f"Warning: no fit found for event {i}: {fallback_error}") - fit_succeeded = False - popt = np.full(6, np.nan) - - yfit = GH(x, *popt) if fit_succeeded else np.full_like(y, np.nan) - fit_xmax = popt[1] if fit_succeeded else x[max_pos] - dedx = alpha(showerage(x_profile, fit_xmax + x0)) * rn - dEdX_profiles.append(dedx) - - # Calculate chi**2 - if fit_succeeded: - for j in range(yfit.size): - if y[j] > 0: - chi2[i] += (y[j] - yfit[j]) ** 2 / y[j] - - chi2[i] = chi2[i] / (y.size - 6) / (np.sqrt(popt[2] * 1e5)) - else: - chi2[i] = np.nan - - g3 = popt[3] - g2 = popt[4] - g1 = popt[5] - if np.isnan(chi2[i]): - print(f"Warning: chi2 is NaN for event {i}.") - elif chi2[i] < 0: - print(f"Warning: chi2 is negative for event {i}: {chi2[i]:.3g}.") - elif chi2[i] > 0.1: - print( - f"Warning: chi2 for event {i} is too high ({chi2[i]:.3f}). " - "This may indicate a poor fit." - ) - # Undo the variable change. For p1, p2, p3 this involves shifting the parabola coefficients. - X0[i] = popt[0] + x0 - Xmax[i] = popt[1] + x0 - Nmax[i] = popt[2] * 1e5 - p3[i] = popt[3] - p2[i] = g2 - 2 * g3 * x0 - p1[i] = g1 - g2 * x0 + g3 * x0**2 - Xmx[i] = x[max_pos] + x0 - Nmx[i] = rn[max_pos] - dEdXmx[i] = dedx[max_pos] - chi2[i] = chi2[i] * 1e5 - - nan_chi2 = np.flatnonzero(np.isnan(chi2)) - negative_chi2 = np.flatnonzero(chi2 < 0) - if nan_chi2.size: - print(f"Warning: NaN chi2 values found for events {nan_chi2.tolist()}.") - if negative_chi2.size: - print( - f"Warning: negative chi2 values found for events " - f"{negative_chi2.tolist()}." - ) - - branches_header = { - "Seed1": np.dtype("i4"), - "Particle": np.dtype("i4"), - "Alpha": np.dtype("f8"), - "lgEmin": np.dtype("f8"), - "lgEmax": np.dtype("f8"), - "zMin": np.dtype("f8"), - "zMax": np.dtype("f8"), - "SvnRevision": np.dtype("b"), - "Version": np.dtype("f4"), - "OutputVersion": np.dtype("f4"), - "HEModel": np.dtype("i4"), - "LEModel": np.dtype("i4"), - "HiLowEgy": np.dtype("f4"), - "hadCut": np.dtype("f4"), - "emCut": np.dtype("f4"), - "hadThr": np.dtype("f4"), - "muThr": np.dtype("f4"), - "emThr": np.dtype("f4"), - "haCut": np.dtype("f4"), - "muCut": np.dtype("f4"), - "elCut": np.dtype("f4"), - "gaCut": np.dtype("f4"), - "lambdaLgE": ("f8", (31,)), - "lambdaProton": ("f8", (31,)), - "lambdaPion": ("f8", (31,)), - "lambdaHelium": ("f8", (31,)), - "lambdaNitrogen": ("f8", (31,)), - "lambdaIron": ("f8", (31,)), - } - - branches_shower = { - "lgE": np.dtype("f4"), - "zenith": np.dtype("f4"), - "azimuth": np.dtype("f4"), - "Seed2": np.dtype("i4"), - "Seed3": np.dtype("i4"), - "Xfirst": np.dtype("f4"), - "Hfirst": np.dtype("f4"), - "XfirstIn": np.dtype("f4"), - "altitude": np.dtype("f8"), - "X0": np.dtype("f4"), - "Xmax": np.dtype("f4"), - "Nmax": np.dtype("f4"), - "p1": np.dtype("f4"), - "p2": np.dtype("f4"), - "p3": np.dtype("f4"), - "chi2": np.dtype("f4"), - "Xmx": np.dtype("f4"), - "Nmx": np.dtype("f4"), - "XmxdEdX": np.dtype("f4"), - "dEdXmx": np.dtype("f4"), - "cpuTime": np.dtype("f4"), - "X": ("f4", (profile_size,)), - "N": ("f4", (profile_size,)), - "H": ("f4", (profile_size,)), - "D": ("f4", (profile_size,)), - "dEdX": ("f4", (profile_size,)), - "Mu": ("f4", (profile_size,)), - "Gamma": ("f4", (profile_size,)), - "Electrons": ("f4", (profile_size,)), - "Hadrons": ("f4", (profile_size,)), - "dMu": ("f4", (profile_size,)), - "nX": np.dtype("i4"), - "nN": np.dtype("i4"), - "nH": np.dtype("i4"), - "nD": np.dtype("i4"), - "ndEdX": np.dtype("i4"), - "nMu": np.dtype("i4"), - "nGamma": np.dtype("i4"), - "nElectrons": np.dtype("i4"), - "nHadrons": np.dtype("i4"), - "ndMu": np.dtype("i4"), - "EGround": ("f4", (3,)), - } - - f = uproot.recreate(output_file) - f.mktree("Header", branches_header, title="run header") - f.mktree("Shower", branches_shower, title="shower info") - f["Header"].extend( - { - "Seed1": int4, - "Particle": PID, # Proton type (no specific ID for tau) - "Alpha": nan8, - "lgEmin": nan8, - "lgEmax": nan8, - "zMin": zmin, - "zMax": zmax, - "SvnRevision": [0], - "Version": [64], - "OutputVersion": OutputVersion, - "HEModel": int4, - "LEModel": int4, - "HiLowEgy": nan4, - "hadCut": nan4, - "emCut": nan4, - "hadThr": nan4, - "muThr": nan4, - "emThr": nan4, - "haCut": nan4, - "muCut": nan4, - "elCut": nan4, - "gaCut": nan4, - "lambdaLgE": a, - "lambdaProton": a, - "lambdaPion": a, - "lambdaHelium": a, - "lambdaNitrogen": a, - "lambdaIron": a, - } - ) - f["Shower"].extend( - { - "lgE": TauEnergy, - "zenith": zenith, # 90+np.degree(beta_rad) - "azimuth": azim, - "Seed2": intn, - "Seed3": intn, - "Xfirst": Xfirst, - "Hfirst": Zfirst * 1000, - "XfirstIn": np.full(n, 0.5, dtype="f4"), - "altitude": nan8n, - "X0": X0, - "Xmax": Xmax, - "Nmax": Nmax, - "p1": p1, - "p2": p2, - "p3": p3, - "chi2": chi2, - "Xmx": Xmx, - "Nmx": Nmx, - "XmxdEdX": Xmx, - "dEdXmx": dEdXmx, - "cpuTime": nan4n, - "X": X, - "N": RN, - "H": Z * 1000, # in meters - "D": np.asarray(D, dtype=np.float32) * 1000, - "dEdX": np.asarray(dEdX_profiles, dtype=np.float32), - "Mu": Xempty, # Xempty - "Gamma": Xempty, # Xempty - "Electrons": RN, - "Hadrons": Xempty, # Xempty - "dMu": Xempty, # Xempty - "nX": np.full(n, profile_size, dtype="i4"), - "nN": np.full(n, profile_size, dtype="i4"), - "nH": np.full(n, profile_size, dtype="i4"), - "nD": np.full(n, profile_size, dtype="i4"), - "ndEdX": np.full(n, profile_size, dtype="i4"), - "nMu": np.full(n, profile_size, dtype="i4"), - "nGamma": np.full(n, profile_size, dtype="i4"), - "nElectrons": np.full(n, profile_size, dtype="i4"), - "nHadrons": np.full(n, profile_size, dtype="i4"), - "ndMu": np.full(n, profile_size, dtype="i4"), - "EGround": Eg, - } - ) - f.close() - print(f"Output file saved to {output_file}") diff --git a/src/nuspacesim/config.py b/src/nuspacesim/config.py index db9008ab..ef023722 100644 --- a/src/nuspacesim/config.py +++ b/src/nuspacesim/config.py @@ -324,8 +324,6 @@ class TargetOfOpportunity(BaseModel): use_refactored_photon_sum: bool = False """Use Phase-B refactored photon-sum kernel in EAS optical simulation.""" - conex_output: bool = False - """Enable CONEX output generation.""" refactored_photon_sum_variant: Literal["v1", "v2", "v3", "v4", "v6"] = "v2" """Refactored photon-sum variant key (used when use_refactored_photon_sum=True).""" @@ -358,6 +356,10 @@ def validate_cherenkov_light_engine(cls, value: str) -> str: return "nuspacesim" return value + conex_output: bool = False + """Write the optical showers' longitudinal profiles to a CONEX ROOT file + (``conex_.root``; see :mod:`nuspacesim.conex`).""" + ionosphere: Optional[Ionosphere] = Ionosphere() cherenkov_quadrature: CherenkovQuadrature = CherenkovQuadrature() """Optical Cherenkov quadrature node-count knobs (optional; defaults match CphotAng).""" diff --git a/src/nuspacesim/simulation/eas_optical/cphotang.py b/src/nuspacesim/simulation/eas_optical/cphotang.py index 3be03f0b..76289101 100644 --- a/src/nuspacesim/simulation/eas_optical/cphotang.py +++ b/src/nuspacesim/simulation/eas_optical/cphotang.py @@ -94,6 +94,7 @@ "BackgroundCluster", "CphotAng", "PhotonYieldInputs", + "ShowerProfile", "hillas_single_integral_model", ] @@ -156,6 +157,52 @@ class PhotonYieldInputs: n_nodes: int +@dataclass(frozen=True) +class ShowerProfile: + """Longitudinal profiles of a batch of showers on the fixed node grid. + + Handed to an ``on_profile`` callable by :meth:`CphotAng.run` / + :meth:`CphotAng.__call__` / :meth:`EAS.__call__`, which lets a caller observe + the per-node shower state without changing what those functions return. + Every shower has exactly ``n_nodes`` nodes, so all arrays are fixed shape: + per-shower fields are ``(n_showers,)`` and per-node fields are + ``(n_showers, n_nodes)``. Nodes span the visible window of each shower in + two Gauss-Legendre panels split at the Greisen maximum, so ``X`` is + non-decreasing along each row. It is strictly increasing unless the + maximum lies outside the window: that panel then has zero width and its + nodes coincide on the window edge (contributing nothing). + + Attributes + ---------- + index : ndarray of int, shape (n_showers,) + Row of each shower in the *receiving caller's* event arrays. Each layer + re-maps it, so at the pipeline level it indexes ``beta_tr`` & co. + beta : ndarray, shape (n_showers,) + Earth emergence angle (rad) the node grid was built with (run() clamps + it to >= 1 deg). + altDec : ndarray, shape (n_showers,) + Tau decay altitude (km). + showerEnergy : ndarray, shape (n_showers,) + Shower energy (100 PeV). + X : ndarray, shape (n_showers, n_nodes) + Slant depth from the decay point to each node (g/cm^2). + z : ndarray, shape (n_showers, n_nodes) + Altitude of each node (km). + N : ndarray, shape (n_showers, n_nodes) + Charged-particle count at each node (the configured profile model). + """ + + index: np.ndarray + beta: np.ndarray + altDec: np.ndarray + showerEnergy: np.ndarray + X: np.ndarray + z: np.ndarray + N: np.ndarray + + NODE_FIELDS = ("X", "z", "N") # the (n_showers, n_nodes) fields, in order + + # Lower edge of the shower's valid slant-depth window. The Hillas e2 parameter # e2hill = 1150 + 454*ln(s) vanishes at the shower-age floor s_floor; below it # the angular parameterization is undefined. Converting that age floor to slant @@ -388,7 +435,7 @@ def run( n_energy_low=3, n_energy_high=8, photon_model=None, - conex=False, + on_profile=None, ): """Main simulation: compute photon density and Cherenkov angle. @@ -448,6 +495,10 @@ def run( ``n_energy_low``/``n_energy_high``). Supply a custom callable to swap in a different parameterization, function approximation, or physical model without changing the surrounding pipeline. + on_profile : callable, optional + Called once with the batch's :class:`ShowerProfile` (``index`` = + ``arange(n_showers)``) as soon as the per-node shower state exists. + Observation only: it does not change the return value. Default None. Returns ------- @@ -507,6 +558,18 @@ def run( # Phase 3: shower-physics fields and the derived Cherenkov quantities. AirN, s, RN, e2hill = shower_state_at_nodes(z_nodes, X_to_node, gb) + if on_profile is not None: + on_profile( + ShowerProfile( + index=np.arange(betaE.shape[0]), + beta=betaE, + altDec=alt, + showerEnergy=np.atleast_1d(np.asarray(Eshow100PeV, np.float64)), + X=X_to_node, + z=z_nodes, + N=RN, + ) + ) eCthres, thetaC = cherenkov_threshold_angle(AirN) E0 = hillas_scale_energy(z_nodes.shape, s) Tfrac = tracklen(E0, eCthres, s) @@ -552,10 +615,7 @@ def run( altitude_scaling, per_wavelength, ) - result = photonDen.astype(self.dtype), Cang.astype(self.dtype) - if conex: - return result + (RN, z_nodes, X_to_node) - return result + return photonDen.astype(self.dtype), Cang.astype(self.dtype) # ------------------------------------------------------------------ # run() stages (each operates on (n_showers,) / (n_showers, n_nodes)) @@ -859,7 +919,6 @@ def __call__( init_lat, init_long, cloudf=None, - conex=False, chunks=None, photon_model=None, per_wavelength=False, @@ -869,6 +928,7 @@ def __call__( n_energy_low=3, n_energy_high=8, serial=False, + on_profile=None, ): """ Iterate over the list of events and return the result as pair of @@ -911,6 +971,12 @@ def __call__( kernel the workers use and ignores ``client``; the pipeline picks it below ``config.simulation.eas_parallel_threshold`` showers, where a cluster's spawn and teardown would outweigh the work. + + ``on_profile`` (optional) is called once, in this process, with the whole + batch's :class:`ShowerProfile` (``index`` = ``arange(n)``). Each block's + per-node arrays ride back from the workers as extra fixed-width rows of + the packed block, so this works serially and distributed alike, and the + return value is unchanged. None (default) adds no work. """ if ( @@ -920,14 +986,6 @@ def __call__( or len(init_lat) < 1 or len(init_long) < 1 ): - if conex: - return ( - np.empty([]), - np.empty([]), - np.empty([]), - np.empty([]), - np.empty([]), - ) return np.empty([]), np.empty([]) # Per block, run() yields density (N,) [collapsed] or (N, n_wl) @@ -936,37 +994,35 @@ def __call__( # the density (n_den = 1 collapsed, n_wl per-wavelength), the last row # is Cang. The collapsed path stays (2, N) -- bit-identical to before; # per-wavelength avoids the (N, n_nodes, n_wl) tensor only when the - # caller actually wants it. CONEX diagnostics are packed as n_nodes rows - # for each of RN, z_nodes, and X_to_node after the density and angle. + # caller actually wants it. n_wl = len(self.wmean) n_den = n_wl if per_wavelength else 1 - diagnostic_rows = 3 * n_nodes if conex else 0 + # With an on_profile observer, each ShowerProfile.NODE_FIELDS array adds + # n_nodes rows after Cang (fixed width: every shower has n_nodes nodes). + profile_fields = ShowerProfile.NODE_FIELDS if on_profile is not None else () + n_rows = n_den + 1 + len(profile_fields) * n_nodes def chunk_worker(b, a, e, lat, lon): - run_result = self.run( + captured = [] + d_batch, c_batch = self.run( b, a, e, lat, lon, cloudf=cloudf, - conex=conex, n_nodes=n_nodes, n_slant_sub=n_slant_sub, per_wavelength=per_wavelength, n_energy_low=n_energy_low, n_energy_high=n_energy_high, photon_model=photon_model, + on_profile=captured.append if profile_fields else None, ) - if conex: - d_batch, c_batch, rn_batch, z_batch, x_batch = run_result - else: - d_batch, c_batch = run_result # d_batch is (N,) collapsed or (N, n_wl); make it (n_den, N). d_rows = d_batch.T if per_wavelength else d_batch[None, :] rows = [d_rows, c_batch[None, :]] - if conex: - rows.extend([rn_batch.T, z_batch.T, x_batch.T]) + rows += [getattr(p, f).T for p in captured for f in profile_fields] return np.concatenate(rows, axis=0) if serial: @@ -977,7 +1033,7 @@ def chunk_worker(b, a, e, lat, lon): results = map_showers_distributed( chunk_worker, (betaE, alt, Eshow100PeV, init_lat, init_long), - n_rows=n_den + 1 + diagnostic_rows, + n_rows=n_rows, chunks=chunks, client=client, ) @@ -985,11 +1041,19 @@ def chunk_worker(b, a, e, lat, lon): # Unpack (n_rows, N): density rows then the Cang row. Collapsed -> # (N,); per-wavelength -> (N, n_wl) (transpose back the n_den rows). dphots = results[0] if n_den == 1 else results[:n_den].T - cang = results[n_den] - if conex: - diagnostics = results[n_den + 1 :] - rn = diagnostics[:n_nodes].T - z_nodes = diagnostics[n_nodes : 2 * n_nodes].T - x_to_node = diagnostics[2 * n_nodes :].T - return dphots, cang, rn, z_nodes, x_to_node - return dphots, cang + if profile_fields: + node_rows = results[n_den + 1 :].reshape(len(profile_fields), n_nodes, -1) + # The same coerced (beta-clamped) inputs run() built the grid with. + beta_grid, alt_grid, *_ = self._coerce_inputs( + betaE, alt, Eshow100PeV, init_lat, init_long + ) + on_profile( + ShowerProfile( + index=np.arange(node_rows.shape[-1]), + beta=beta_grid, + altDec=alt_grid, + showerEnergy=np.asarray(Eshow100PeV, np.float64), + **{f: rows.T for f, rows in zip(profile_fields, node_rows)}, + ) + ) + return dphots, results[n_den] diff --git a/src/nuspacesim/simulation/eas_optical/eas.py b/src/nuspacesim/simulation/eas_optical/eas.py index 4b9b5017..63db7a8e 100644 --- a/src/nuspacesim/simulation/eas_optical/eas.py +++ b/src/nuspacesim/simulation/eas_optical/eas.py @@ -31,6 +31,8 @@ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. +import dataclasses + import numpy as np from astropy import units from astropy.constants import R_earth, c @@ -91,9 +93,9 @@ def __call__( init_long, *args, cloudf=None, - conex=False, client=None, serial=False, + on_profile=None, **kwargs, ): """ @@ -103,6 +105,10 @@ def __call__( :meth:`CphotAng.__call__`; see :class:`BackgroundCluster`. When ``None`` CphotAng spins up its own LocalCluster. ``serial=True`` skips the cluster entirely and runs CphotAng in this process. + + ``on_profile`` is an optional callable receiving the + :class:`~.cphotang.ShowerProfile` of the simulated (in-bounds) + showers; its ``index`` refers to rows of *these* input arrays. """ # Mask out-of-bounds events. Do not pass to CphotAng. Instead use @@ -116,22 +122,21 @@ def __call__( # Run CphotAng on in-bounds events quad = self.config.simulation.cherenkov_quadrature - cphotang_result = self.CphotAng( + dphots[mask], thetaCh100PeV[mask] = self.CphotAng( beta[mask], altDec[mask], showerEnergy[mask], init_lat[mask], init_long[mask], cloudf, - conex, client=client, serial=serial, + on_profile=_reindexed(on_profile, np.flatnonzero(mask)), n_nodes=quad.n_nodes, n_slant_sub=quad.n_slant_sub, n_energy_low=quad.n_energy_low, n_energy_high=quad.n_energy_high, ) - dphots[mask], thetaCh100PeV[mask] = cphotang_result[:2] numPEs = ( dphots @@ -152,11 +157,20 @@ def __call__( costhetaChEff = np.cos(np.radians(thetaChEff)) - if conex: - return numPEs, costhetaChEff, *cphotang_result[2:] return numPEs, costhetaChEff +def _reindexed(on_profile, rows): + """Wrap ``on_profile`` so a profile's ``index`` maps through ``rows``.""" + if on_profile is None: + return None + + def forward(profile): + on_profile(dataclasses.replace(profile, index=rows[profile.index])) + + return forward + + def show_plot(sim, simclass, plot): plotfs = (eas_optical_density, eas_optical_histogram) inputs = ("beta_rad", "altDec", "showerEnergy") diff --git a/src/nuspacesim/utils/decorators.py b/src/nuspacesim/utils/decorators.py index 95f42a12..dcc594b9 100644 --- a/src/nuspacesim/utils/decorators.py +++ b/src/nuspacesim/utils/decorators.py @@ -83,8 +83,8 @@ def store_f(*args, store=None, **kwargs): values = func(*args, **kwargs) if store is not None: if isinstance(values, tuple): - assert len(values) >= len(names) - store(names, [*values[: len(names)]]) + assert len(names) == len(values) + store(names, [*values]) else: assert len(names) == 1 store(names, [values]) diff --git a/test/conex/test_conex.py b/test/conex/test_conex.py new file mode 100644 index 00000000..6c29f955 --- /dev/null +++ b/test/conex/test_conex.py @@ -0,0 +1,100 @@ +"""CONEX output: fixed-shape schema, mapping from shower profiles, ROOT file.""" + +from pathlib import Path + +import numpy as np +import pytest + +from nuspacesim.conex import ConexWriter, build_showers, conex_path +from nuspacesim.conex.format import PROFILE, SHOWER_FIELDS, empty_header, shower_dtype +from nuspacesim.conex.writer import gaisser_hillas +from nuspacesim.simulation.eas_optical.cphotang import ShowerProfile +from nuspacesim.simulation.eas_optical.propagation import lexpr, slant_depth + +K = 12 +GH = (-60.0, 700.0, 3e8, 1e-6, -0.01, 70.0) # X0, Xmax, Nmax, p3, p2, p1 + + +def _profile(n=4): + """Up-going showers with GH profiles on a GL grid split at Xmax.""" + x, _ = np.polynomial.legendre.leggauss(K // 2) + lo, peak, hi = 20.0, GH[1], 1700.0 + grid = np.concatenate( + [ + 0.5 * (peak + lo) + 0.5 * (peak - lo) * x, + 0.5 * (hi + peak) + 0.5 * (hi - peak) * x, + ] + ) + X = np.tile(grid, (n, 1)) + alt = np.linspace(0.5, 3.0, n) + return ShowerProfile( + index=np.arange(n), + beta=np.radians(np.linspace(5.0, 30.0, n)), + altDec=alt, + showerEnergy=np.full(n, 0.5), + X=X, + z=alt[:, None] + np.linspace(0.1, 8.0, K), + N=gaisser_hillas(X, *GH), + ) + + +def test_schema_is_fixed_shape(): + dt = shower_dtype(K) + assert dt.names == tuple(f.name for f in SHOWER_FIELDS) + for f in SHOWER_FIELDS: + assert dt[f.name].shape == ((K,) if f.shape == PROFILE else f.shape) + assert empty_header()["OutputVersion"][0] == np.float32(2.51) + + +def test_build_showers_maps_the_profile(): + p = _profile() + out = build_showers(p, np.random.default_rng(0)) + assert out.dtype == shower_dtype(K) and len(out) == 4 + L0 = lexpr(0.0, p.beta) + Xfirst = slant_depth(L0, lexpr(p.altDec, p.beta), p.beta) + np.testing.assert_allclose(out["X"], p.X + Xfirst[:, None], rtol=1e-6) + np.testing.assert_allclose(out["N"], p.N, rtol=1e-6) + np.testing.assert_allclose(out["H"], p.z * 1e3, rtol=1e-6) + np.testing.assert_allclose( + out["D"], (lexpr(p.z, p.beta[:, None]) - L0[:, None]) * 1e3, rtol=1e-6 + ) + np.testing.assert_allclose(out["lgE"], np.log10(0.5) + 17.0) + np.testing.assert_allclose(out["zenith"], 90.0 + np.degrees(p.beta), rtol=1e-6) + # The fit recovers the generating Xmax (shifted by Xfirst). + np.testing.assert_allclose(out["Xmax"], GH[1] + Xfirst, rtol=1e-4) + assert np.all(out["nX"] == K) + + +def test_build_showers_drops_unresolved_maxima(): + p = _profile(3) + N = p.N.copy() + N[1] = np.linspace(1.0, 2.0, K) # still growing at the window top + N[2] = np.linspace(2.0, 1.0, K) # maximum before the window start + out = build_showers( + ShowerProfile(p.index, p.beta, p.altDec, p.showerEnergy, p.X, p.z, N), + np.random.default_rng(0), + ) + assert len(out) == 1 + + +def test_written_file_reads_back(tmp_path): + uproot = pytest.importorskip("uproot") + path = tmp_path / "conex_run.root" + p = _profile() + ConexWriter(path, rng=np.random.default_rng(1))(p) + expected = build_showers(p, np.random.default_rng(1)) + with uproot.open(path) as f: + shower = f["Shower"] + assert shower["X"].typename == f"float[{K}]" # fixed, not jagged + got = shower.arrays(library="np") + for name in expected.dtype.names: + np.testing.assert_array_equal(np.asarray(got[name]), expected[name]) + assert f["Header"]["Particle"].array(library="np")[0] == 100 + + +@pytest.mark.parametrize( + "output,expected", + [("nss.fits", "conex_nss.root"), ("out/run.fits", "out/conex_run.root")], +) +def test_conex_path(output, expected): + assert conex_path(output) == Path(expected) diff --git a/test/core/test_config.py b/test/core/test_config.py index 0f83cd7d..50c0bcb9 100644 --- a/test/core/test_config.py +++ b/test/core/test_config.py @@ -297,6 +297,7 @@ def test_default_simulation(): assert a.use_refactored_photon_sum is False assert a.refactored_photon_sum_variant == "v2" assert a.cherenkov_light_engine == "nuspacesim" + assert a.conex_output is False assert a.ionosphere is not None assert a.ionosphere.total_electron_content == 10.0 assert a.ionosphere.total_electron_error == 0.1 @@ -317,6 +318,7 @@ def test_default_simulation(): "use_refactored_photon_sum": False, "refactored_photon_sum_variant": "v2", "cherenkov_light_engine": "nuspacesim", + "conex_output": False, "ionosphere": { "enable": True, "total_electron_content": 10.0, diff --git a/test/simulation/eas_optical/test_shower_profile_hook.py b/test/simulation/eas_optical/test_shower_profile_hook.py new file mode 100644 index 00000000..a14e538a --- /dev/null +++ b/test/simulation/eas_optical/test_shower_profile_hook.py @@ -0,0 +1,87 @@ +"""The ``on_profile`` observation hook of CphotAng.run / CphotAng.__call__ / EAS. + +The hook must (a) leave every return value unchanged, (b) deliver fixed-shape +``(n_showers, n_nodes)`` profiles, and (c) carry an ``index`` that maps each +profile row back to the receiving caller's event arrays. +""" + +import numpy as np + +from nuspacesim.config import NssConfig +from nuspacesim.simulation.eas_optical.cphotang import CphotAng, ShowerProfile +from nuspacesim.simulation.eas_optical.eas import EAS + +N_NODES = 12 + + +def _events(n=40, seed=5): + rng = np.random.default_rng(seed) + beta = np.radians(rng.uniform(0.5, 40.0, n)) + alt = rng.uniform(0.0, 18.0, n) + energy = 10 ** rng.uniform(-1.5, 1.0, n) # 100 PeV units + return beta, alt, energy, np.zeros(n), np.zeros(n) + + +def test_run_hook_observes_without_changing_results(): + cpa = CphotAng(detector_altitude=525.0) + ev = _events() + base = cpa.run(*ev, n_nodes=N_NODES, per_wavelength=False) + seen = [] + got = cpa.run(*ev, n_nodes=N_NODES, per_wavelength=False, on_profile=seen.append) + for a, b in zip(base, got): + assert np.array_equal(a, b) + + (p,) = seen + n = len(ev[0]) + assert isinstance(p, ShowerProfile) + assert np.array_equal(p.index, np.arange(n)) + for f in ShowerProfile.NODE_FIELDS: + assert getattr(p, f).shape == (n, N_NODES) + assert np.all(np.isfinite(getattr(p, f))) + # Ordered along the axis; strictly so iff the maximum is inside the window + # (otherwise one GL panel collapses onto the window edge). + assert np.all(np.diff(p.X, axis=1) >= 0) + assert np.all(np.diff(p.z, axis=1) >= 0) # up-going: altitude increases + half = N_NODES // 2 + collapsed = (p.X[:, 0] == p.X[:, half - 1]) | (p.X[:, half] == p.X[:, -1]) + strict = np.all(np.diff(p.X, axis=1) > 0, axis=1) + assert np.array_equal(strict, ~collapsed) + assert strict.any() and collapsed.any() # both cases occur in this sample + assert np.all(p.N >= 0) + assert np.array_equal(p.altDec, ev[1]) and np.array_equal(p.showerEnergy, ev[2]) + assert np.array_equal(p.beta, np.maximum(ev[0], np.radians(1.0))) + + +def test_call_hook_matches_run_and_keeps_returns(): + cpa = CphotAng(detector_altitude=525.0) + ev = _events() + base = cpa(*ev, n_nodes=N_NODES, serial=True) + seen = [] + got = cpa(*ev, n_nodes=N_NODES, serial=True, on_profile=seen.append) + for a, b in zip(base, got): + assert np.array_equal(a, b) + + ref = [] + cpa.run(*ev, n_nodes=N_NODES, per_wavelength=False, on_profile=ref.append) + (p,), (r,) = seen, ref + for f in ("index", "beta", "altDec", "showerEnergy", *ShowerProfile.NODE_FIELDS): + assert np.array_equal(getattr(p, f), getattr(r, f)), f + + +def test_eas_hook_index_maps_to_in_bounds_events(): + cfg = NssConfig() + eas = EAS(cfg) + beta, alt, energy, lat, lon = _events(30) + alt[[0, 7, 19]] = [-1.0, 25.0, 21.0] # out of bounds: never simulated + seen = [] + base = eas(beta, alt, energy, lat, lon, serial=True) + got = eas(beta, alt, energy, lat, lon, serial=True, on_profile=seen.append) + for a, b in zip(base, got): + assert np.array_equal(a, b) + + (p,) = seen + expected = np.flatnonzero((alt >= 0) & (alt <= 20)) + assert np.array_equal(p.index, expected) + assert np.array_equal(p.altDec, alt[p.index]) + assert np.array_equal(p.showerEnergy, energy[p.index]) + assert p.N.shape == (expected.size, cfg.simulation.cherenkov_quadrature.n_nodes)