diff --git a/.gitignore b/.gitignore index 1062b846..c500ecbc 100644 --- a/.gitignore +++ b/.gitignore @@ -188,3 +188,6 @@ cython_debug/ AGENTS.md .claude/ docs/*.md + +# CONEX output files +*.root diff --git a/sample_input_file.toml b/sample_input_file.toml index dad99a39..8dc33835 100644 --- a/sample_input_file.toml +++ b/sample_input_file.toml @@ -35,6 +35,7 @@ max_cherenkov_angle = "3.0000000000000004 deg" max_azimuth_angle = "360.0 deg" angle_from_limb = "7.0 deg" eas_long_profile = "Greisen" +conex_output = false cherenkov_light_engine = "nuspacesim" [simulation.ionosphere] diff --git a/src/nuspacesim/apps/run.py b/src/nuspacesim/apps/run.py index d5625461..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 @@ -59,6 +60,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 +144,7 @@ def run( count: float, no_result_file: bool, output: str, + conex_output: bool, plot: list, plotconfig: str, plotall: bool, @@ -183,6 +192,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 ) @@ -198,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 99e092e0..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 @@ -58,6 +58,7 @@ from . import results_table 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 @@ -77,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. @@ -119,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 ------- @@ -248,6 +256,7 @@ def add_meta(self, name: str, value: Any, comment: str): 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, ) 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/config.py b/src/nuspacesim/config.py index 0e279933..ef023722 100644 --- a/src/nuspacesim/config.py +++ b/src/nuspacesim/config.py @@ -356,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 7b934a3d..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,6 +435,7 @@ def run( n_energy_low=3, n_energy_high=8, photon_model=None, + on_profile=None, ): """Main simulation: compute photon density and Cherenkov angle. @@ -447,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 ------- @@ -506,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) @@ -864,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 @@ -906,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 ( @@ -926,8 +997,13 @@ def __call__( # caller actually wants it. n_wl = len(self.wmean) n_den = n_wl if per_wavelength else 1 + # 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): + captured = [] d_batch, c_batch = self.run( b, a, @@ -941,10 +1017,13 @@ def chunk_worker(b, a, e, lat, lon): 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, ) # 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, :]] + rows += [getattr(p, f).T for p in captured for f in profile_fields] + return np.concatenate(rows, axis=0) if serial: results = chunk_worker( @@ -954,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, + n_rows=n_rows, chunks=chunks, client=client, ) @@ -962,4 +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 + 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 3a3f8b98..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 @@ -93,6 +95,7 @@ def __call__( cloudf=None, client=None, serial=False, + on_profile=None, **kwargs, ): """ @@ -102,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 @@ -124,6 +131,7 @@ def __call__( cloudf, 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, @@ -152,6 +160,17 @@ def __call__( 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/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)