diff --git a/sample_input_file.toml b/sample_input_file.toml index dad99a39..b5c2e6bf 100644 --- a/sample_input_file.toml +++ b/sample_input_file.toml @@ -48,6 +48,14 @@ n_slant_sub = 8 n_energy_low = 3 n_energy_high = 8 +[simulation.streaming] +batch_size = 5000 +reservoir_size = 10000 +rel_unc_target = 0.05 +min_thrown = 50000 +max_walltime_s = 0.0 # wall-clock backstop in seconds; 0 disables +reservoir_weighting = "contribution" + [simulation.tau_shower] id = "nupyprop" etau_frac = 0.5 diff --git a/src/nuspacesim/apps/cli.py b/src/nuspacesim/apps/cli.py index 28575445..ab6deed1 100644 --- a/src/nuspacesim/apps/cli.py +++ b/src/nuspacesim/apps/cli.py @@ -50,7 +50,7 @@ from nuspacesim import version -from . import create_config, run, show_plot +from . import create_config, run, show_plot, stream @click.group() @@ -60,5 +60,6 @@ def cli(): cli.add_command(run.run) +cli.add_command(stream.stream) cli.add_command(create_config.create_config) cli.add_command(show_plot.show_plot) diff --git a/src/nuspacesim/apps/stream.py b/src/nuspacesim/apps/stream.py new file mode 100644 index 00000000..c632eb27 --- /dev/null +++ b/src/nuspacesim/apps/stream.py @@ -0,0 +1,193 @@ +# 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. +"""``nuspacesim stream`` -- streaming, distributed optical Monte-Carlo. + +.. currentmodule:: nuspacesim.apps.stream +""" + +import click + +from ..config import config_from_toml +from ..results_table import output_filename +from .utils import parse_cloud_options, parse_spectra_options + + +@click.command() +@click.option( + "-o", "--output", type=click.Path(exists=False), default=None, help="Output file." +) +@click.option( + "-n", + "--no-result-file", + is_flag=True, + help="Do not save the results to an output file.", +) +@click.option( + "--rel-unc", + type=float, + default=None, + help="Target relative uncertainty (e.g. 0.01 for 1%). Overrides " + "[simulation.streaming].rel_unc_target. 0 runs to the max-thrown backstop.", +) +@click.option( + "--reservoir-size", + type=int, + default=None, + help="Number of representative events (k) to keep and write to disk. " + "Overrides [simulation.streaming].reservoir_size.", +) +@click.option( + "--batch-size", + type=int, + default=None, + help="Trajectories thrown per batch (fixed, reproducible schedule). If " + "omitted, the batch size adapts over the run to maximize throughput.", +) +@click.option( + "--monospectrum", + type=float, + default=None, + help="Mono Energetic Spectrum Log Energy.", +) +@click.option( + "--powerspectrum", + nargs=3, + type=click.Tuple([float, float, float]), + default=None, + help="Power Spectrum index, lower_bound, upper_bound.", +) +@click.option("--nocloud", is_flag=True, default=None, help="No Cloud Model. [Default]") +@click.option( + "--monocloud", + type=float, + default=None, + help="Uniform (mono) Height Cloud Model (km).", +) +@click.option( + "--pressuremapcloud", + type=click.DateTime(["%m", "%B", "%b"]), + default=None, + help="Pressure Map Cloud Model month (name, abbreviation, or number).", +) +@click.argument( + "config_file", + default=None, + type=click.Path(exists=True, dir_okay=False, readable=True), +) +@click.argument("count", type=float, default=0.0) +def stream( + config_file: str, + count: float, + output: str, + no_result_file: bool, + rel_unc: float, + reservoir_size: int, + batch_size: int, + monospectrum: float, + powerspectrum: click.Tuple, + nocloud: bool, + monocloud: float, + pressuremapcloud: click.DateTime, +) -> None: + """Streaming, distributed optical Monte-Carlo simulation. + + Throws neutrino events in batches across a process-based dask cluster, + accumulates the optical Monte-Carlo integral as an exact converging sketch + with live statistics, and stops when the integral's relative uncertainty + reaches the configured target. Only the weighted reservoir of representative + events is materialized to disk. + + \f + + Parameters + ---------- + config_file : str + TOML configuration file. + count : float, optional + Upper bound on thrown trajectories (the backstop). **Defaults to + infinity** -- the run is driven by the relative-uncertainty target (or a + spacebar interrupt), not a fixed count. Provide a value to cap it. + output : str, optional + Output FITS file for the reservoir + integral metadata. + no_result_file : bool, optional + Do not write the results file. + rel_unc : float, optional + Target relative uncertainty; overrides the config value. + reservoir_size : int, optional + Reservoir size k; overrides the config value. + + Examples + -------- + Run until the integral reaches 1% relative uncertainty (no thrown cap):: + + nuspacesim stream --rel-unc 0.01 sample_input_file.toml + + On an interactive terminal, press the **spacebar** to end early and finalize + the partial result. + """ + config = config_from_toml(config_file) + + if rel_unc is not None: + config.simulation.streaming.rel_unc_target = rel_unc + if reservoir_size is not None: + config.simulation.streaming.reservoir_size = reservoir_size + + overwrite_spectrum = parse_spectra_options(monospectrum, powerspectrum) + if overwrite_spectrum: + config.simulation.spectrum = overwrite_spectrum + + overwrite_cloud = parse_cloud_options(nocloud, monocloud, pressuremapcloud) + if overwrite_cloud: + config.simulation.cloud_model = overwrite_cloud + + # Default backstop is infinity: the precision target (or a spacebar + # interrupt) drives the run, not a fixed thrown count. + max_thrown = float("inf") if count == 0.0 else count + + # No --batch-size -> adaptive throughput-tuned sizing. + batch = batch_size if batch_size is not None else "adaptive" + + # Imported here so `nuspacesim --help` stays light (defers dask/rich). + from ..simulation.streaming import compute_streaming + + output = output_filename(output) + simulation = compute_streaming( + config, + verbose=True, + output_file=output, + max_thrown=max_thrown, + batch_size=batch, + ) + + if not no_result_file: + simulation.write(output, format="fits", overwrite=True) diff --git a/src/nuspacesim/config.py b/src/nuspacesim/config.py index f485e2fd..c1c73f2f 100644 --- a/src/nuspacesim/config.py +++ b/src/nuspacesim/config.py @@ -213,6 +213,33 @@ class CherenkovQuadrature(BaseModel): n_energy_high: int = 8 """GL nodes on the high-energy panel [1 GeV, Eshow]. Default 8.""" + ################ Streaming Monte-Carlo classes ################ + + class Streaming(BaseModel): + """Knobs for the streaming, distributed optical Monte-Carlo path. + + Active only under ``nuspacesim run --stream`` (the default one-shot path + ignores these). Events are thrown in batches across the dask cluster; + the integral accumulates as an exact additive sketch and the run stops + when its relative uncertainty reaches ``rel_unc_target`` (or the thrown + count hits the ``count`` backstop, or ``max_walltime_s`` elapses). Only + ``reservoir_size`` representative events are written to disk. Every field + is optional with a default, so the table may be omitted entirely. + """ + + batch_size: int = 5000 + """Trajectories thrown per streamed batch (the unit of parallel work).""" + reservoir_size: int = 10000 + """k: representative events kept (weighted) and materialized to disk.""" + rel_unc_target: float = 0.05 + """Stop once the optical MC integral's relative uncertainty reaches this.""" + min_thrown: int = 50000 + """Warmup: do not honor ``rel_unc_target`` before this many thrown events.""" + max_walltime_s: float = 0.0 + """Wall-clock backstop in seconds; ``0`` (or negative) disables it.""" + reservoir_weighting: Literal["contribution", "uniform"] = "contribution" + """Reservoir weight: ``|contribution|`` (importance) or ``uniform``.""" + ################ tau_shower classes ################ class NuPyPropShower(BaseModel): @@ -351,6 +378,8 @@ def validate_cherenkov_light_engine(cls, value: str) -> str: ionosphere: Optional[Ionosphere] = Ionosphere() cherenkov_quadrature: CherenkovQuadrature = CherenkovQuadrature() """Optical Cherenkov quadrature node-count knobs (optional; defaults match CphotAng).""" + streaming: Streaming = Streaming() + """Streaming distributed optical MC knobs (optional; used by ``run --stream``).""" tau_shower: NuPyPropShower = NuPyPropShower() """ Tau Shower Generator. """ spectrum: Union[MonoSpectrum, PowerSpectrum] = Field( diff --git a/src/nuspacesim/simulation/eas_optical/eas.py b/src/nuspacesim/simulation/eas_optical/eas.py index d8944963..636b71aa 100644 --- a/src/nuspacesim/simulation/eas_optical/eas.py +++ b/src/nuspacesim/simulation/eas_optical/eas.py @@ -92,6 +92,7 @@ def __call__( *args, cloudf=None, client=None, + serial=False, **kwargs, ): """ @@ -100,6 +101,13 @@ def __call__( ``client`` is an optional pre-built distributed client forwarded to :meth:`CphotAng.__call__`; see :class:`BackgroundCluster`. When ``None`` CphotAng spins up its own LocalCluster. + + ``serial`` selects the per-batch kernel :meth:`CphotAng.run` directly + instead of the dask-chunked :meth:`CphotAng.__call__`. The streaming + driver runs each event batch *as* a dask task, so the optical kernel + must execute serially inside the worker -- spinning up a nested + cluster there would be pathological. ``client`` is ignored when + ``serial`` is set. """ # Mask out-of-bounds events. Do not pass to CphotAng. Instead use @@ -113,19 +121,38 @@ def __call__( # Run CphotAng on in-bounds events quad = self.config.simulation.cherenkov_quadrature - dphots[mask], thetaCh100PeV[mask] = self.CphotAng( - beta[mask], - altDec[mask], - showerEnergy[mask], - init_lat[mask], - init_long[mask], - cloudf, - client=client, - 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, - ) + if serial: + # Already inside a dask worker (streaming): drive the per-batch + # kernel directly, no nested cluster. run() does not guard an empty + # batch, so skip it when nothing is in bounds. + if np.any(mask): + dphots[mask], thetaCh100PeV[mask] = self.CphotAng.run( + beta[mask], + altDec[mask], + showerEnergy[mask], + init_lat[mask], + init_long[mask], + cloudf=cloudf, + n_nodes=quad.n_nodes, + n_slant_sub=quad.n_slant_sub, + per_wavelength=False, + n_energy_low=quad.n_energy_low, + n_energy_high=quad.n_energy_high, + ) + else: + dphots[mask], thetaCh100PeV[mask] = self.CphotAng( + beta[mask], + altDec[mask], + showerEnergy[mask], + init_lat[mask], + init_long[mask], + cloudf, + client=client, + 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, + ) numPEs = ( dphots diff --git a/src/nuspacesim/simulation/geometry/region_geometry.py b/src/nuspacesim/simulation/geometry/region_geometry.py index 643a6bb8..25e2b54c 100644 --- a/src/nuspacesim/simulation/geometry/region_geometry.py +++ b/src/nuspacesim/simulation/geometry/region_geometry.py @@ -40,7 +40,64 @@ from .local_plots import geom_beta_tr_hist from .too import ToOEvent -__all__ = ["RegionGeom", "RegionGeomToO"] +__all__ = ["RegionGeom", "RegionGeomToO", "mc_contribution"] + + +def mc_contribution( + cos_tr_sub_n, + cos_n_sub_v, + cos_tr_sub_v, + triggers, + costheta, + tauexitprob, + threshold, + spec_norm, + spec_weights_sum, + bshr=0.826, +): + """Per-event Monte-Carlo integrand for the region geometry. + + Pure function mapping per-(valid-)event geometry cosines and detector + response to the two per-event arrays the MC integral sums: + + * ``geo`` : geometry-only factor *after* the separation-angle cut, + summed for the GEO-only integral. + * ``mcintfactor``: the full contribution (geometry x branching x + tau-exit-prob / spectrum weights), zeroed below the trigger threshold; + summed for the full integral, its variance, and the passing-event count. + + This is the per-event half of :meth:`RegionGeom.mcintegral`, extracted so + the streaming sketch (:mod:`nuspacesim.simulation.streaming`) and the + one-shot batch integral share a single definition. It reproduces the + original in-place math byte-for-byte: ``geo`` is the separation-cut base + used for the GEO-only sum, and ``mcintfactor`` is built from it without + mutating it. + + Parameters + ---------- + cos_tr_sub_n, cos_n_sub_v, cos_tr_sub_v + Per-valid-event direction cosines (trajectory-vs-nadir, nadir-vs-view, + trajectory-vs-view). ``cos_tr_sub_v`` doubles as the separation cosine. + triggers + Per-event detector observable compared against ``threshold`` + (numPEs for Optical, SNR for Radio). + costheta + Cherenkov-angle cosine cut; per-event (Optical) or scalar (Radio). + tauexitprob + Per-event tau exit probability. + threshold, spec_norm, spec_weights_sum, bshr + Scalar constants (detector threshold, spectrum normalization, spectrum + weight integral, shower branching ratio). + """ + geo = cos_tr_sub_n / cos_n_sub_v / cos_tr_sub_v + geo[cos_tr_sub_v < costheta] = 0.0 + + mcintfactor = geo * (bshr * tauexitprob) + mcintfactor /= spec_norm + mcintfactor /= spec_weights_sum + mcintfactor[triggers < threshold] = 0.0 + + return mcintfactor, geo class RegionGeom: @@ -373,34 +430,27 @@ def mcintegral( ): """Monte Carlo integral.""" - cossepangle = self.costhetaTrSubV[self.event_mask] - - mcintfactor = ( - self.valid_costhetaTrSubN() - / self.valid_costhetaNSubV() - / self.valid_costhetaTrSubV() + # Per-event integrand (shared with the streaming sketch). ``geo`` is the + # separation-cut geometry factor; ``mcintfactor`` adds branching, tau + # exit probability, spectrum weighting, and the trigger threshold cut. + mcintfactor, geo = mc_contribution( + self.valid_costhetaTrSubN(), + self.valid_costhetaNSubV(), + self.valid_costhetaTrSubV(), + triggers, + costheta, + tauexitprob, + threshold, + spec_norm, + spec_weights_sum, ) mcnorm = self.mcnorm - # Number of Trajectories + # Number of Trajectories (all thrown, including geometry-invalid). numTrajs = len(self.betaTrSubN) - # Geometry Factors - mcintfactor[cossepangle < costheta] = 0 - mcintegralgeoonly = np.sum(mcintfactor) * mcnorm / numTrajs - - Bshr = 0.826 - - # Multiply by tau exit probability and branching ratio (currently ignores muon channel for tau decays; it's also hard coded in, so will need to be changed) - mcintfactor *= Bshr * tauexitprob - - # Weighting by energy spectrum if other than monoenergetic spectrum - mcintfactor /= spec_norm - mcintfactor /= spec_weights_sum - - # PE threshold - mcintfactor[triggers < threshold] = 0 + mcintegralgeoonly = np.sum(geo) * mcnorm / numTrajs mcintegral = np.sum(mcintfactor) * mcnorm / numTrajs mcintegraluncert = np.sqrt(np.var(mcintfactor, ddof=1) / numTrajs) * mcnorm diff --git a/src/nuspacesim/simulation/streaming/__init__.py b/src/nuspacesim/simulation/streaming/__init__.py new file mode 100644 index 00000000..93a0268c --- /dev/null +++ b/src/nuspacesim/simulation/streaming/__init__.py @@ -0,0 +1,59 @@ +# 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. + +"""Streaming, distributed Monte-Carlo for nuspacesim (optical first cut). + +Throws events in batches across the dask cluster, accumulates the optical MC +integral as an exact additive :class:`~.sketch.MomentSketch`, keeps a bounded +weighted :class:`~.reservoir.WeightedReservoir` of representative events, and +stops on a relative-uncertainty target with a max-thrown backstop. + +The integral sketch is *exact* (the MC integral is a mean of per-event +contributions); the reservoir is a separate materialization artifact and never +feeds the integral. +""" + +from .reservoir import WeightedReservoir +from .sketch import MomentSketch + +__all__ = ["MomentSketch", "WeightedReservoir", "compute_streaming"] + + +def __getattr__(name): + # Lazy import of the driver so importing the sketch/reservoir primitives + # does not pull in dask/rich until a streaming run is actually launched. + if name == "compute_streaming": + from .driver import compute_streaming + + return compute_streaming + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/src/nuspacesim/simulation/streaming/batch.py b/src/nuspacesim/simulation/streaming/batch.py new file mode 100644 index 00000000..de16cd3b --- /dev/null +++ b/src/nuspacesim/simulation/streaming/batch.py @@ -0,0 +1,224 @@ +# 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. + +"""One streaming batch: throw -> physics -> per-event contribution -> sketch. + +:func:`run_batch` is the unit of work the driver ships to a dask worker. It runs +the same stage sequence as :func:`nuspacesim.compute.compute` on a small batch +of thrown trajectories and returns only the two small, mergeable summaries -- +a :class:`~.sketch.MomentSketch` (a few scalars) and a +:class:`~.reservoir.WeightedReservoir` (<= k rows). The full per-event arrays +never leave the worker. + +Heavy engine objects (geometry, spectra, taus, the optical kernel) are built +once per worker process and cached; a streaming run uses a single config, so the +cache holds one entry for the worker's lifetime. +""" + +from __future__ import annotations + +import numpy as np + +from .reservoir import WeightedReservoir +from .sketch import MomentSketch + +__all__ = ["run_batch"] + +# Per-process engine cache. A worker handles many batches of one config; build +# the engines (which load atmosphere/kernel tables) once and reuse them. +_ENGINE_CACHE: dict = {} + + +def _get_engines(config): + """Build (and cache) the per-worker simulation engines for ``config``.""" + key = config.model_dump_json() + engines = _ENGINE_CACHE.get(key) + if engines is None: + from ..atmosphere.clouds import CloudTopHeight + from ..eas_optical.eas import EAS + from ..geometry.region_geometry import RegionGeom + from ..spectra.spectra import Spectra + from ..taus.taus import Taus + + engines = { + "geom": RegionGeom(config), + "cloud": CloudTopHeight(config), + "spec": Spectra(config), + "tau": Taus(config), + "eas": EAS(config), + } + _ENGINE_CACHE.clear() # only ever one config per run; bound the cache + _ENGINE_CACHE[key] = engines + return engines + + +def _seed_batch_rng(root_entropy: int, batch_idx: int) -> np.random.Generator: + """Seed this batch's RNG state deterministically from ``(root, batch_idx)``. + + Two independent child streams are derived: one seeds the legacy global + ``np.random`` state used by the physics stages (geometry throw, power + spectrum, tau sampling, decay altitude), the other is returned as an + explicit :class:`~numpy.random.Generator` for the reservoir sampling keys. + Because the seed depends only on ``batch_idx`` (not on worker or schedule), + batch *i* always produces the same events and keys -- the materialized + reservoir is reproducible even though the float-sum sketch may reorder. + """ + seq = np.random.SeedSequence(entropy=root_entropy, spawn_key=(batch_idx,)) + phys_seq, key_seq = seq.spawn(2) + np.random.seed(int(phys_seq.generate_state(1)[0])) + return np.random.default_rng(key_seq) + + +# Per-event fields materialized into the reservoir (optical diagnostics + +# provenance). Mirrors the columns the one-shot path stores, minus radio-only. +_RESERVOIR_FIELDS = ( + "beta_rad", + "theta", + "path_len", + "altDec", + "lenDec", + "showerEnergy", + "numPEs", + "costhetaChEff", + "mcintfactor", + "init_lat", + "init_lon", +) + + +def run_batch( + config, + batch_idx: int, + batch_size: int, + reservoir_size: int, + weighting: str, + root_entropy: int, +): + """Throw and process one batch; return ``(MomentSketch, WeightedReservoir)``. + + Parameters + ---------- + config : NssConfig + Full simulation configuration (shipped from the driver). + batch_idx : int + Index of this batch; seeds the deterministic per-batch RNG. + batch_size : int + Number of trajectories to throw (the integral denominator contribution). + reservoir_size : int + ``k`` for the weighted reservoir. + weighting : {"contribution", "uniform"} + Reservoir sampling weight: ``|mcintfactor|`` (importance) or uniform. + root_entropy : int + Run-level RNG entropy; combined with ``batch_idx`` for reproducibility. + """ + from ..geometry.region_geometry import mc_contribution + + key_rng = _seed_batch_rng(root_entropy, batch_idx) + eng = _get_engines(config) + geom, cloud, spec, tau, eas = ( + eng["geom"], + eng["cloud"], + eng["spec"], + eng["tau"], + eng["eas"], + ) + + geom.throw(batch_size) + n_thrown = len(geom.betaTrSubN) + beta_tr = geom.beta_rad() + n_valid = beta_tr.size + + mcnorm = geom.mcnorm + + # No valid geometry this batch: still counts toward the denominator. + if n_valid == 0: + return ( + MomentSketch(mcnorm=mcnorm, n_thrown=n_thrown), + WeightedReservoir.empty(reservoir_size), + ) + + init_lat, init_long = geom.find_lat_long_along_traj(np.zeros_like(beta_tr)) + theta = geom.thetas() + path_len = geom.pathLens() + + log_e_nu, spec_norm, spec_weights_sum = spec(n_valid) + tauBeta, tauLorentz, _tauEnergy, showerEnergy, tauExitProb = tau(beta_tr, log_e_nu) + altDec, lenDec = eas.altDec(beta_tr, tauBeta, tauLorentz) + + numPEs, costhetaChEff = eas( + beta_tr, + altDec, + showerEnergy, + init_lat, + init_long, + cloudf=cloud, + serial=True, + ) + + mcintfactor, geo = mc_contribution( + geom.valid_costhetaTrSubN(), + geom.valid_costhetaNSubV(), + geom.valid_costhetaTrSubV(), + numPEs, + costhetaChEff, + tauExitProb, + config.detector.optical.photo_electron_threshold, + spec_norm, + spec_weights_sum, + ) + + sketch = MomentSketch.from_batch(mcintfactor, geo, n_thrown, mcnorm) + + weights = ( + np.ones_like(mcintfactor) if weighting == "uniform" else np.abs(mcintfactor) + ) + records = dict( + zip( + _RESERVOIR_FIELDS, + ( + beta_tr, + theta, + path_len, + altDec, + lenDec, + showerEnergy, + numPEs, + costhetaChEff, + mcintfactor, + init_lat, + init_long, + ), + ) + ) + reservoir = WeightedReservoir.from_batch(reservoir_size, records, weights, key_rng) + return sketch, reservoir diff --git a/src/nuspacesim/simulation/streaming/driver.py b/src/nuspacesim/simulation/streaming/driver.py new file mode 100644 index 00000000..a3788f9a --- /dev/null +++ b/src/nuspacesim/simulation/streaming/driver.py @@ -0,0 +1,562 @@ +# 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. + +"""Streaming Monte-Carlo driver: batch -> merge -> live stats -> stop. + +:func:`compute_streaming` is the streaming counterpart to +:func:`nuspacesim.compute.compute` for the optical channel. It throws events in +batches across a process-based dask cluster, merges each batch's +:class:`~.sketch.MomentSketch` and :class:`~.reservoir.WeightedReservoir` into +running totals, shows an always-updating ``rich`` panel, and stops when the MC +integral's relative uncertainty reaches the configured target (with thrown-count +and wall-clock backstops). Only the weighted reservoir of representative events +is materialized into the returned table. +""" + +from __future__ import annotations + +import contextlib +import logging +import sys +import threading +import time +import warnings + +import numpy as np +from dask.distributed import as_completed +from rich.console import Console +from rich.live import Live +from rich.panel import Panel +from rich.table import Table + +from ... import results_table +from ...utils.distributed import BackgroundCluster +from ..geometry.region_geometry import RegionGeom +from .batch import run_batch +from .reservoir import WeightedReservoir +from .sketch import MomentSketch + +__all__ = ["compute_streaming"] + +_META_COMMENTS = { + "OMCINT": "Optical MonteCarlo Integral", + "OMCINTGO": "Optical MonteCarlo Integral, GEO Only", + "ONEVPASS": "Optical Number of Passing Events", + "OMCINTUN": "Stat unc of MonteCarlo Integral", +} + + +def _silence_worker_logs(): + """Raise dask worker-process log levels to CRITICAL (runs on each worker). + + Shipped via ``client.run`` just before teardown to quiet the benign + heartbeat / comm-closed ERRORs a worker emits while the cluster shuts down. + Called only after the computation is complete -- real task failures have + already surfaced in the driver via ``future.result()``. + """ + import logging as _logging + + for _name in ( + "distributed.worker", + "distributed.nanny", + "distributed.core", + "distributed.comm", + ): + _logging.getLogger(_name).setLevel(_logging.CRITICAL) + + +class _SpacebarListener: + """Watch stdin for a spacebar press in a background thread (TTY only). + + Lets the user end a streaming run early *gracefully* -- the partial result + is finalized normally (unlike Ctrl-C, which aborts). A daemon thread puts + the terminal in cbreak mode and polls stdin; pressing space sets + :attr:`pressed`, which the driver loop checks each batch. Automatically + disabled when stdin is not an interactive TTY (pipes, tests, CI), so + non-interactive runs are unaffected. + """ + + def __init__(self): + self.pressed = threading.Event() + self._stop = threading.Event() + self._thread = None + try: + self.enabled = sys.stdin is not None and sys.stdin.isatty() + except (ValueError, OSError): + self.enabled = False + + def __enter__(self): + if self.enabled: + self._thread = threading.Thread(target=self._watch, daemon=True) + self._thread.start() + return self + + def _watch(self): + try: + import select + import termios + import tty + except ImportError: # non-POSIX terminal: silently disable + return + fd = sys.stdin.fileno() + old = termios.tcgetattr(fd) + try: + tty.setcbreak(fd) + while not self._stop.is_set(): + ready, _, _ = select.select([sys.stdin], [], [], 0.2) + if ready and sys.stdin.read(1) == " ": + self.pressed.set() + return + except Exception: + return + finally: + termios.tcsetattr(fd, termios.TCSADRAIN, old) + + def __exit__(self, *_exc): + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=1) + + +def _fmt_max(max_thrown): + """Format the max-thrown backstop, rendering an infinite cap as ``∞``.""" + return "∞" if not np.isfinite(max_thrown) else f"{int(max_thrown):,}" + + +class _AdaptiveBatch: + """Tune the streaming batch size toward the throughput "knee". + + When ``--batch-size`` is not given, the driver lets this controller choose + each batch's size. From the batch size ``B`` and the inter-completion gap + ``dt`` (wall seconds between consecutive batch completions), ``B / dt`` + estimates the aggregate event throughput -- in steady state with ``W`` busy + workers, completions arrive roughly every ``service_time / W`` seconds, so + ``B / dt ~ B * W / service_time``. The controller grows ``B`` while a smoothed + throughput keeps improving and *settles at the knee* once gains fall below + ``min_gain`` -- i.e. the smallest batch that still saturates throughput. That + keeps the run efficient (overhead amortized) while staying responsive + (fine-grained stopping / live updates / quick reaction to the precision + target). ``B`` is clamped to ``[lo, hi]``. + + The integral is exact for *any* ``B`` (the sketch is additive), so adaptation + never affects correctness, only speed. It does make the *contents* of batch + ``i`` timing-dependent, so an adaptive run is not bit-reproducible -- pass + ``--batch-size`` for a fixed, reproducible schedule. + """ + + def __init__( + self, + start, + lo=1000, + hi=50000, + step=1.4, + min_gain=0.03, + alpha=0.4, + eval_every=3, + ): + self.lo = lo + self.hi = hi + self.step = step + self.min_gain = min_gain + self.alpha = alpha + self.eval_every = eval_every + self.size = self._clamp(int(start)) + self.mode = "grow" # grow -> hold once throughput gains diminish + self._ewma = None + self._ref = None # smoothed throughput at the last decision point + self._since = 0 + + def _clamp(self, b): + return int(min(self.hi, max(self.lo, b))) + + def current(self): + return self.size + + def update(self, batch_size, dt): + """Fold one completion ``(size, gap)`` and return the next batch size.""" + if dt <= 0.0: + return self.size + rate = batch_size / dt + self._ewma = ( + rate + if self._ewma is None + else self.alpha * rate + (1.0 - self.alpha) * self._ewma + ) + self._since += 1 + if self._since < self.eval_every: # average out parallel-overlap noise + return self.size + self._since = 0 + + if self.mode == "grow": + if self._ref is not None: + gain = (self._ewma - self._ref) / self._ref + if gain < self.min_gain: + # Diminishing returns: step back to the knee and hold. + self.size = self._clamp(int(self.size / self.step)) + self.mode = "hold" + self._ref = self._ewma + return self.size + self._ref = self._ewma + grown = self._clamp(int(self.size * self.step)) + if grown == self.size: # hit the cap; nothing more to gain + self.mode = "hold" + self.size = grown + return self.size + + +def _stop_reason(sketch, started, st, max_thrown): + """Return the name of a tripped stop condition, or ``None`` to continue.""" + if sketch.n_thrown >= max_thrown: + return "max_thrown" + if st.max_walltime_s > 0 and (time.monotonic() - started) >= st.max_walltime_s: + return "walltime" + if ( + sketch.n_thrown >= st.min_thrown + and sketch.mcint > 0.0 + and sketch.rel_unc <= st.rel_unc_target + ): + return "rel_unc_target" + return None + + +def _render(sketch, n_res, k, elapsed, st, max_thrown, interruptible=False, batch=None): + """A rich panel of the current running statistics.""" + grid = Table.grid(padding=(0, 2)) + grid.add_column(justify="right", style="blue") + grid.add_column(style="bold") + + rate = sketch.n_thrown / elapsed if elapsed > 0 else 0.0 + rel = sketch.rel_unc + rel_str = f"{rel * 100:.3f}%" if np.isfinite(rel) else "—" + + grid.add_row("Thrown", f"{sketch.n_thrown:,} / {_fmt_max(max_thrown)}") + grid.add_row("Valid", f"{sketch.n_valid:,}") + grid.add_row("Passing", f"{sketch.n_pass:,}") + grid.add_row("MC integral", f"{sketch.mcint:.6g} ± {sketch.mcunc:.3g}") + grid.add_row("Rel. uncert", f"{rel_str} (target {st.rel_unc_target * 100:.3f}%)") + grid.add_row("GEO-only", f"{sketch.mcint_geo:.6g}") + grid.add_row("Reservoir", f"{n_res:,} / {k:,}") + if batch is not None: + grid.add_row("Batch", batch) + grid.add_row("Elapsed", f"{elapsed:.1f}s ({rate:,.0f} ev/s)") + + subtitle = "[dim]Press [Space] to end[/]" if interruptible else None + return Panel( + grid, + title="[cyan]NuSpaceSim streaming (optical)[/]", + subtitle=subtitle, + width=64, + ) + + +def _stream_loop( + client, + config, + st, + sketch, + reservoir, + *, + adaptive, + sizer, + fixed_size, + max_thrown, + started, + root_entropy, + verbose, + console, +): + """Submit/merge batches until a stop condition trips. + + Drives a sliding window of dask futures: each completion merges into the + running sketch + reservoir, feeds the adaptive sizer, refreshes the live + panel, and checks the stop criteria. Returns ``(sketch, reservoir, + stop_reason)``. Outstanding futures are cancelled on stop. + """ + cfg = client.scatter(config, broadcast=True) + n_workers = max(len(client.scheduler_info().get("workers", {})), 1) + window = max(2 * n_workers, 4) + + def cur_size(): + return sizer.current() if adaptive else fixed_size + + ac = as_completed() + pending = set() + fut_size = {} + next_idx = 0 + + def submit_one(idx): + size = cur_size() + fut = client.submit( + run_batch, + cfg, + idx, + size, + st.reservoir_size, + st.reservoir_weighting, + root_entropy, + pure=False, + ) + ac.add(fut) + pending.add(fut) + fut_size[fut] = size + + for _ in range(window): + submit_one(next_idx) + next_idx += 1 + + listener = _SpacebarListener() + live_cm = ( + Live(console=console, refresh_per_second=8, transient=False) + if verbose + else None + ) + stop_reason = "max_thrown" + if live_cm is not None: + live_cm.__enter__() + listener.__enter__() + last_t = time.monotonic() + try: + for fut in ac: + part_sketch, part_res = fut.result() + pending.discard(fut) + + # Feed the adaptive controller the completed batch's size and the + # gap since the previous completion (the throughput signal). + bs = fut_size.pop(fut, None) + now = time.monotonic() + if adaptive and bs is not None: + sizer.update(bs, now - last_t) + last_t = now + + sketch = sketch.merge(part_sketch) + reservoir = reservoir.merge(part_res) + + if live_cm is not None: + batch_now = ( + f"{cur_size():,} (adaptive)" if adaptive else f"{fixed_size:,}" + ) + live_cm.update( + _render( + sketch, + len(reservoir), + st.reservoir_size, + now - started, + st, + max_thrown, + interruptible=listener.enabled, + batch=batch_now, + ) + ) + + if listener.pressed.is_set(): + stop_reason = "user_interrupt" + break + + reason = _stop_reason(sketch, started, st, max_thrown) + if reason is not None: + stop_reason = reason + break + + submit_one(next_idx) + next_idx += 1 + finally: + listener.__exit__() + if live_cm is not None: + live_cm.__exit__(None, None, None) + + # Computation done: quiet the workers before cancelling/closing so their + # shutdown heartbeat/comm errors don't spill onto the console. Best-effort: + # a worker that already died mid-teardown is exactly the noise case, so a + # failure here must never mask the finished result. + with contextlib.suppress(Exception): + client.run(_silence_worker_logs) + if pending: + client.cancel(list(pending)) + return sketch, reservoir, stop_reason + + +def compute_streaming( + config, + verbose: bool = False, + output_file: str | None = None, + to_plot: list | None = None, + write_stages: bool = False, + seed: int | None = None, + max_thrown: float | None = None, + batch_size: int | str | None = None, +): + """Run the streaming optical Monte-Carlo and return a results table. + + Parameters + ---------- + config : NssConfig + Simulation configuration. ``config.simulation.streaming`` supplies the + batch size, reservoir size, stop target, and weighting. + verbose : bool + Render the live statistics panel. + output_file, to_plot, write_stages + Accepted for signature parity with :func:`compute`. The streaming path + materializes only the reservoir; per-batch staged writes and reservoir + plots are not produced in this first cut. The caller writes the returned + table. + seed : int, optional + Root RNG entropy. ``None`` draws fresh entropy (logged for reproducibility). + max_thrown : float, optional + Upper bound on thrown trajectories (the backstop). ``None`` falls back to + ``config.simulation.thrown_events``; pass ``float("inf")`` to run until + the precision target or a user interrupt. The ``stream`` CLI command + defaults this to infinity. + batch_size : int or "adaptive", optional + Trajectories per batch. ``None`` uses ``config.simulation.streaming``'s + fixed value; an int overrides it (fixed, reproducible schedule); + ``"adaptive"`` lets :class:`_AdaptiveBatch` tune the size for throughput + over the run. The ``stream`` CLI command passes ``"adaptive"`` when + ``--batch-size`` is not given. + + Returns + ------- + astropy.table.Table + Reservoir rows as columns; sketch results and streaming provenance in + ``.meta`` (legacy ``OMCINT``/``OMCINTGO``/``ONEVPASS``/``OMCINTUN`` keys). + + Notes + ----- + On an interactive terminal, pressing the **spacebar** ends the run early but + gracefully -- the partial result is finalized normally (``STRMSTOP`` = + ``user_interrupt``). + """ + console = Console(width=80, log_path=False) + + def logv(*args): + if verbose: + console.log(*args) + + if not config.detector.optical.enable: + raise ValueError("Streaming compute is optical-only; enable detector.optical.") + if config.simulation.mode == "Target": + raise NotImplementedError( + "Streaming compute does not support Target-of-Opportunity mode yet." + ) + + st = config.simulation.streaming + if max_thrown is None: + max_thrown = float(config.simulation.thrown_events) + max_thrown = float(max_thrown) + root_entropy = int(seed) if seed is not None else np.random.SeedSequence().entropy + + # Batch sizing: "adaptive" -> throughput controller; else a fixed size. + if batch_size is None: + batch_size = st.batch_size + adaptive = isinstance(batch_size, str) and batch_size == "adaptive" + sizer = _AdaptiveBatch(start=st.batch_size) if adaptive else None + fixed_size = None if adaptive else int(batch_size) + batch_label = "adaptive" if adaptive else f"{fixed_size:,}" + + # mcnorm is config-only; build one RegionGeom to seed the empty sketch. + mcnorm = RegionGeom(config).mcnorm + sketch = MomentSketch.empty(mcnorm) + reservoir = WeightedReservoir.empty(st.reservoir_size) + + logv(f"Streaming optical MC: seed={root_entropy}") + logv( + f"\tbatch={batch_label} reservoir={st.reservoir_size:,} " + f"target={st.rel_unc_target:.3g} max_thrown={_fmt_max(max_thrown)}" + ) + + # Stopping mid-stream cancels the in-flight sliding-window futures, which + # makes each *worker* process log a benign CancelledError at WARNING level. + # ``silence_logs`` raises the worker/scheduler/nanny log threshold to ERROR + # so that teardown noise (and dask's INFO chatter) stays out of the console; + # genuine worker errors still surface via ``future.result()``. + cluster = BackgroundCluster(threads_per_worker=1, silence_logs=logging.ERROR) + started = time.monotonic() + + try: + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", "Sending large graph") + client = cluster.client() + sketch, reservoir, stop_reason = _stream_loop( + client, + config, + st, + sketch, + reservoir, + adaptive=adaptive, + sizer=sizer, + fixed_size=fixed_size, + max_thrown=max_thrown, + started=started, + root_entropy=root_entropy, + verbose=verbose, + console=console, + ) + finally: + cluster.close() + + elapsed = time.monotonic() - started + logv( + f"\t[green]Stopped[/] ({stop_reason}): " + f"thrown={sketch.n_thrown:,} valid={sketch.n_valid:,} " + f"passing={sketch.n_pass:,} in {elapsed:.1f}s" + ) + logv(f"\t[blue]Optical MC Integral[/]: {sketch.mcint:.6g} ± {sketch.mcunc:.3g}") + logv(f"\t[blue]GEO-only[/]: {sketch.mcint_geo:.6g}") + + # ``sizer is not None`` iff adaptive; test the object so mypy sees it too. + batch_meta = f"adaptive({sizer.current()})" if sizer is not None else batch_label + return _finalize( + config, sketch, reservoir, root_entropy, stop_reason, elapsed, batch_meta + ) + + +def _finalize( + config, sketch, reservoir, root_entropy, stop_reason, elapsed, batch_meta +): + """Assemble the results table: reservoir rows + sketch/provenance metadata.""" + sim = results_table.init(config) + + if len(reservoir) > 0: + names = list(reservoir.records.keys()) + sim.add_columns([reservoir.records[n] for n in names], names=names) + + for key, value in sketch.as_meta().items(): + sim.meta[key] = (value, _META_COMMENTS[key]) + + sim.meta["STRMSEED"] = (str(root_entropy), "Streaming RNG root entropy") + sim.meta["STRMSTOP"] = (stop_reason, "Streaming stop reason") + sim.meta["STRMNTHR"] = (sketch.n_thrown, "Streaming total thrown trajectories") + sim.meta["STRMNVAL"] = (sketch.n_valid, "Streaming total valid events") + sim.meta["STRMNRES"] = (len(reservoir), "Streaming reservoir rows materialized") + sim.meta["STRMWALL"] = (float(elapsed), "Streaming wall-clock seconds") + sim.meta["STRMBATC"] = (batch_meta, "Streaming batch size (or adaptive(final))") + return sim diff --git a/src/nuspacesim/simulation/streaming/reservoir.py b/src/nuspacesim/simulation/streaming/reservoir.py new file mode 100644 index 00000000..b54402ac --- /dev/null +++ b/src/nuspacesim/simulation/streaming/reservoir.py @@ -0,0 +1,161 @@ +# 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. + +"""Mergeable weighted reservoir sample (Efraimidis-Spirakis bottom-k). + +Each item ``i`` drawn from the stream is assigned a random key + + key_i = u_i ** (1 / w_i), u_i ~ Uniform(0, 1), + +and the reservoir keeps the ``k`` items with the **largest** keys. This is the +A-Res / A-ExpJ scheme of Efraimidis & Spirakis (2006). We store and compare the +keys in **log space** (``log(u_i) / w_i``): the ordering is identical, but the +log form is immune to underflow. Optical contributions are tiny in absolute +value (~1e-5), so ``1/w`` is ~1e5 and the direct ``u ** (1/w)`` rounds almost +every key to ``0.0`` -- making real events indistinguishable from zero-weight +ones. The log key also makes the sample invariant to a global rescaling of the +weights (it only shifts every log key by a constant factor, preserving order). + +Two properties make it the right fit for a distributed, batched pipeline: + +* **Associative & commutative** — merging two reservoirs is just "keep the top-k + keys of the union", so partial reservoirs from independent dask batches + tree-reduce in any order to the same result. +* **Weight-tunable** — with equal weights it reduces to a uniform sample (the + distribution of Vitter's Algorithm L); with ``w_i = |contribution_i|`` it + biases the retained sample toward the events that dominate the MC integral. + +Larger weight ⇒ ``1/w`` smaller ⇒ key closer to its maximum ⇒ more likely kept. +Zero-weight items get key ``-inf`` and are retained only to backfill an +under-full reservoir. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field + +import numpy as np + +__all__ = ["WeightedReservoir"] + + +def _topk(keys: np.ndarray, records: dict[str, np.ndarray], k: int): + """Return the ``k`` rows with the largest keys (no order guarantee).""" + n = keys.size + if n <= k: + return keys, records + # Indices of the k largest keys; argpartition is O(n). + idx = np.argpartition(keys, n - k)[n - k :] + return keys[idx], {name: col[idx] for name, col in records.items()} + + +@dataclass +class WeightedReservoir: + """A bounded weighted-without-replacement sample of stream records. + + Holds at most ``k`` rows as parallel arrays: ``keys`` (the E-S sampling + keys) and ``records`` (a dict of column name -> aligned array). Pickles + cheaply (``k`` rows), so a worker returns its batch reservoir to the driver + for merging. + """ + + k: int + keys: np.ndarray = field(default_factory=lambda: np.empty(0, dtype=np.float64)) + records: dict[str, np.ndarray] = field(default_factory=dict) + + def __post_init__(self): + if self.k < 1: + raise ValueError(f"reservoir size k must be >= 1, got {self.k}") + for name, col in self.records.items(): + if len(col) != self.keys.size: + raise ValueError( + f"record column {name!r} length {len(col)} != " + f"keys length {self.keys.size}" + ) + + @classmethod + def empty(cls, k: int) -> WeightedReservoir: + return cls(k=k) + + @classmethod + def from_batch( + cls, + k: int, + records: dict[str, np.ndarray], + weights: np.ndarray, + rng: np.random.Generator, + ) -> WeightedReservoir: + """Build a reservoir from one batch of records and their weights. + + ``records`` maps column name -> array (all the same length ``n``); + ``weights`` is the per-row sampling weight (``n``-vector). ``rng`` is a + per-batch :class:`numpy.random.Generator` so keys are reproducible and + independent of how batches are scheduled. + """ + w = np.asarray(weights, dtype=np.float64) + n = w.size + if n == 0: + return cls.empty(k) + u = rng.random(n) + with np.errstate(divide="ignore", invalid="ignore"): + # Log-domain E-S key: order by log(u)/w == order by u**(1/w), but + # without underflow for tiny weights. Zero/negative weight -> -inf, + # so such rows are retained only to backfill an under-full reservoir. + keys = np.where(w > 0.0, np.log(u) / w, -np.inf) + records = {name: np.asarray(col) for name, col in records.items()} + keys, records = _topk(keys, records, k) + return cls(k=k, keys=keys, records=records) + + def merge(self, other: WeightedReservoir) -> WeightedReservoir: + """Combine two reservoirs: keep the top-k keys of the union.""" + if self.k != other.k: + raise ValueError(f"reservoir size mismatch: {self.k} vs {other.k}") + if self.keys.size == 0: + return other + if other.keys.size == 0: + return self + if self.records.keys() != other.records.keys(): + raise ValueError( + "cannot merge reservoirs with different columns: " + f"{sorted(self.records)} vs {sorted(other.records)}" + ) + keys = np.concatenate([self.keys, other.keys]) + records = { + name: np.concatenate([self.records[name], other.records[name]]) + for name in self.records + } + keys, records = _topk(keys, records, self.k) + return WeightedReservoir(k=self.k, keys=keys, records=records) + + def __len__(self) -> int: + return self.keys.size diff --git a/src/nuspacesim/simulation/streaming/sketch.py b/src/nuspacesim/simulation/streaming/sketch.py new file mode 100644 index 00000000..e15293c9 --- /dev/null +++ b/src/nuspacesim/simulation/streaming/sketch.py @@ -0,0 +1,197 @@ +# 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. + +"""Exact additive sketch for the streaming Monte-Carlo integral. + +The MC integral, GEO-only integral, statistical uncertainty, and passing-event +count reported by :meth:`RegionGeom.mcintegral` are all linear functionals of a +per-event contribution scaled by config-only constants (``mcnorm``, +``spec_norm``, ``sum_spec_weights``). They therefore reduce to a handful of +**additive moment accumulators** that can be folded batch-by-batch and merged +across dask workers with *no loss of precision* relative to a single one-shot +run. + +This module owns only the reduction. The per-event integrand is produced by +:func:`nuspacesim.simulation.geometry.region_geometry.mc_contribution`, shared +with the one-shot path. +""" + +from __future__ import annotations + +from dataclasses import dataclass, replace + +import numpy as np + +__all__ = ["MomentSketch"] + + +@dataclass(frozen=True) +class MomentSketch: + """Additive, mergeable accumulator for the optical MC integral. + + All fields are plain scalars so the sketch pickles to a few dozen bytes and + ships cheaply back from a dask worker. Instances are immutable; folding a + batch (:meth:`from_batch`) or combining partials (:meth:`merge`) returns a + new ``MomentSketch``. + + Fields + ------ + mcnorm + Config-derived geometry normalization (``RegionGeom.mcnorm``); identical + across all batches of a run. + n_thrown + Total trajectories thrown, **including** geometry-invalid ones. This is + the integral's denominator (the legacy ``numTrajs``). + n_valid + Trajectories surviving the geometry mask (length of the contribution + arrays). The variance is taken over this set, matching the legacy + ``np.var(mcintfactor, ddof=1)``. + s1, s2 + Sum and sum-of-squares of the full per-event contribution + ``mcintfactor`` over valid events. + s1_geo + Sum of the geometry-only factor (post separation-angle cut) over valid + events. + n_pass + Count of valid events with non-zero contribution (passing all cuts). + """ + + mcnorm: float + n_thrown: int = 0 + n_valid: int = 0 + s1: float = 0.0 + s2: float = 0.0 + s1_geo: float = 0.0 + n_pass: int = 0 + + @classmethod + def empty(cls, mcnorm: float) -> MomentSketch: + """A zero sketch; the identity element for :meth:`merge`.""" + return cls(mcnorm=float(mcnorm)) + + @classmethod + def from_batch( + cls, + mcintfactor: np.ndarray, + geo: np.ndarray, + n_thrown: int, + mcnorm: float, + ) -> MomentSketch: + """Fold one batch's per-event arrays into a fresh sketch. + + ``mcintfactor`` and ``geo`` are the per-valid-event outputs of + :func:`mc_contribution`. ``n_thrown`` is the number of trajectories + thrown to produce them (valid + geometry-invalid). + """ + mc = np.asarray(mcintfactor, dtype=np.float64) + return cls( + mcnorm=float(mcnorm), + n_thrown=int(n_thrown), + n_valid=int(mc.size), + s1=float(np.sum(mc)), + s2=float(np.sum(mc * mc)), + s1_geo=float(np.sum(geo)), + n_pass=int(np.count_nonzero(mc)), + ) + + def merge(self, other: MomentSketch) -> MomentSketch: + """Combine two partial sketches (associative & commutative).""" + if not np.isclose(self.mcnorm, other.mcnorm): + raise ValueError( + f"Cannot merge sketches with different mcnorm: " + f"{self.mcnorm} vs {other.mcnorm}" + ) + return replace( + self, + n_thrown=self.n_thrown + other.n_thrown, + n_valid=self.n_valid + other.n_valid, + s1=self.s1 + other.s1, + s2=self.s2 + other.s2, + s1_geo=self.s1_geo + other.s1_geo, + n_pass=self.n_pass + other.n_pass, + ) + + # -- Derived quantities (the reported integral) ------------------------ + + @property + def mcint(self) -> float: + """Optical Monte-Carlo integral.""" + if self.n_thrown == 0: + return 0.0 + return self.s1 * self.mcnorm / self.n_thrown + + @property + def mcint_geo(self) -> float: + """GEO-only Monte-Carlo integral.""" + if self.n_thrown == 0: + return 0.0 + return self.s1_geo * self.mcnorm / self.n_thrown + + @property + def variance(self) -> float: + """Sample variance of ``mcintfactor`` over valid events (ddof=1). + + Computed from moments: ``(s2 - s1**2 / n_valid) / (n_valid - 1)``, + algebraically equal to ``np.var(..., ddof=1)`` (differs only by + floating-point rounding). ``nan`` for fewer than two valid events, + matching numpy. + """ + if self.n_valid < 2: + return np.nan + v = (self.s2 - self.s1 * self.s1 / self.n_valid) / (self.n_valid - 1) + # Guard tiny negative values from catastrophic cancellation. + return max(v, 0.0) + + @property + def mcunc(self) -> float: + """Statistical uncertainty of :attr:`mcint`.""" + if self.n_thrown == 0 or self.n_valid < 2: + return 0.0 if self.n_thrown == 0 else np.nan + return float(np.sqrt(self.variance / self.n_thrown) * self.mcnorm) + + @property + def rel_unc(self) -> float: + """Relative uncertainty ``mcunc / mcint`` (``inf`` when no signal).""" + mc = self.mcint + if mc <= 0.0 or not np.isfinite(self.mcunc): + return np.inf + return self.mcunc / mc + + def as_meta(self) -> dict: + """Sketch results keyed by the legacy FITS header names.""" + return { + "OMCINT": self.mcint, + "OMCINTGO": self.mcint_geo, + "ONEVPASS": self.n_pass, + "OMCINTUN": self.mcunc, + } diff --git a/src/nuspacesim/utils/distributed.py b/src/nuspacesim/utils/distributed.py index 360494e5..94e1a5ec 100644 --- a/src/nuspacesim/utils/distributed.py +++ b/src/nuspacesim/utils/distributed.py @@ -61,7 +61,11 @@ class BackgroundCluster: and re-raised from :meth:`client` so the caller's stack frame sees them. """ - def __init__(self): + def __init__(self, **cluster_kwargs): + # Extra LocalCluster kwargs (e.g. ``threads_per_worker=1`` for the + # streaming driver, which seeds the global RNG per batch and so needs + # one task per worker process at a time). ``processes=True`` is forced. + self._cluster_kwargs = {"processes": True, **cluster_kwargs} self._holder = {} self._error = None self._thread = threading.Thread(target=self._spawn, daemon=True) @@ -69,7 +73,7 @@ def __init__(self): def _spawn(self): try: - cluster = LocalCluster(processes=True) + cluster = LocalCluster(**self._cluster_kwargs) self._holder["cluster"] = cluster self._holder["client"] = Client(cluster) except BaseException as exc: diff --git a/test/apps/test_cli.py b/test/apps/test_cli.py index 5709f4fe..33ddf972 100644 --- a/test/apps/test_cli.py +++ b/test/apps/test_cli.py @@ -11,3 +11,23 @@ def test_cli_version_option_reports_package_version(): assert result.exit_code == 0 assert result.output == f"nuspacesim, version {version}\n" + + +def test_cli_registers_all_commands(): + runner = CliRunner() + + result = runner.invoke(cli, ["--help"]) + + assert result.exit_code == 0 + for cmd in ("run", "stream", "create-config", "show-plot"): + assert cmd in result.output + + +def test_stream_help_lists_override_options(): + runner = CliRunner() + + result = runner.invoke(cli, ["stream", "--help"]) + + assert result.exit_code == 0 + for opt in ("--rel-unc", "--reservoir-size", "--batch-size"): + assert opt in result.output diff --git a/test/core/test_config.py b/test/core/test_config.py index 465b9d84..f79e3b67 100644 --- a/test/core/test_config.py +++ b/test/core/test_config.py @@ -327,6 +327,14 @@ def test_default_simulation(): "n_energy_low": 3, "n_energy_high": 8, }, + "streaming": { + "batch_size": 5000, + "reservoir_size": 10000, + "rel_unc_target": 0.05, + "min_thrown": 50000, + "max_walltime_s": 0.0, + "reservoir_weighting": "contribution", + }, "tau_shower": {"id": "nupyprop", "etau_frac": 0.5, "table_version": "3"}, "spectrum": {"id": "monospectrum", "log_nu_energy": 8.0}, "cloud_model": {"id": "no_cloud"}, @@ -429,6 +437,50 @@ def test_cherenkov_quadrature_backward_compatible(): assert cfg.simulation.cherenkov_quadrature.n_energy_high == 8 +def test_streaming_defaults(): + s = Simulation().streaming + assert s.batch_size == 5000 + assert s.reservoir_size == 10000 + assert s.rel_unc_target == 0.05 + assert s.min_thrown == 50000 + assert s.max_walltime_s == 0.0 + assert s.reservoir_weighting == "contribution" + + +def test_streaming_custom_values(): + sim = Simulation( + streaming=Simulation.Streaming( + batch_size=2000, + reservoir_size=500, + rel_unc_target=0.01, + min_thrown=10000, + max_walltime_s=120.0, + reservoir_weighting="uniform", + ) + ) + assert sim.streaming.batch_size == 2000 + assert sim.streaming.reservoir_size == 500 + assert sim.streaming.rel_unc_target == 0.01 + assert sim.streaming.min_thrown == 10000 + assert sim.streaming.max_walltime_s == 120.0 + assert sim.streaming.reservoir_weighting == "uniform" + + +def test_streaming_backward_compatible(): + """A config file lacking the [simulation.streaming] table loads with defaults.""" + with tempfile.NamedTemporaryFile(mode="w", suffix=".toml", delete=False) as tmp: + tmp.write("[simulation]\nthrown_events = 42\n") + name = tmp.name + cfg = config_from_toml(name) + assert cfg.simulation.streaming.batch_size == 5000 + assert cfg.simulation.streaming.reservoir_weighting == "contribution" + + +def test_streaming_invalid_weighting(): + with pytest.raises(ValidationError): + Simulation.Streaming(reservoir_weighting="bogus") + + def test_invalid_spectrum_type(): with pytest.raises(ValidationError): Simulation(spectrum="invalid_spectrum_type") diff --git a/test/simulation/streaming/test_batch.py b/test/simulation/streaming/test_batch.py new file mode 100644 index 00000000..247e5670 --- /dev/null +++ b/test/simulation/streaming/test_batch.py @@ -0,0 +1,58 @@ +"""In-process tests for the streaming batch worker. + +``run_batch`` normally executes inside dask worker processes, where the parent +process's coverage and assertions can't see it. These tests drive it directly +in-process to lock its contracts: determinism from ``(root_entropy, +batch_idx)``, batch independence, and the shape of the returned summaries. +""" + +import numpy as np + +from nuspacesim.config import NssConfig +from nuspacesim.simulation.streaming.batch import run_batch + + +def _config(): + config = NssConfig() + config.detector.optical.enable = True + config.detector.radio.enable = False + config.simulation.mode = "Diffuse" + return config + + +def test_run_batch_returns_consistent_summaries(): + sk, res = run_batch( + _config(), + batch_idx=0, + batch_size=5000, + reservoir_size=100, + weighting="contribution", + root_entropy=20260625, + ) + assert sk.n_thrown == 5000 + assert 0 < sk.n_valid <= 5000 + assert sk.n_pass >= 0 + assert sk.mcint >= 0.0 and np.isfinite(sk.mcint) + assert sk.mcint_geo > 0.0 + assert len(res) <= 100 + # contribution weighting: retained rows all passed the trigger + if len(res): + assert np.all(res.records["mcintfactor"] > 0.0) + assert set(res.records) >= {"beta_rad", "numPEs", "costhetaChEff"} + + +def test_run_batch_deterministic_in_batch_idx_and_entropy(): + kw = { + "batch_size": 5000, + "reservoir_size": 100, + "weighting": "contribution", + "root_entropy": 12345, + } + sk1, res1 = run_batch(_config(), batch_idx=3, **kw) + sk2, res2 = run_batch(_config(), batch_idx=3, **kw) + assert sk1 == sk2 # frozen dataclass: bit-identical accumulators + np.testing.assert_array_equal(np.sort(res1.keys), np.sort(res2.keys)) + + # a different batch_idx must give a different event stream + sk3, _ = run_batch(_config(), batch_idx=4, **kw) + assert sk3.s1 != sk1.s1 diff --git a/test/simulation/streaming/test_contribution.py b/test/simulation/streaming/test_contribution.py new file mode 100644 index 00000000..0bf2fc68 --- /dev/null +++ b/test/simulation/streaming/test_contribution.py @@ -0,0 +1,142 @@ +"""Regression lock: ``mc_contribution`` must reproduce the original inlined +``RegionGeom.mcintegral`` per-event math byte-for-byte. + +The oracle below is a verbatim copy of the pre-refactor ``mcintegral`` body +(operating on plain per-event arrays). If the extracted pure function ever +drifts from it, these bit-exact assertions fail. +""" + +import numpy as np + +from nuspacesim.simulation.geometry.region_geometry import mc_contribution + + +def _original_mcintegral( + cos_tr_sub_n, + cos_n_sub_v, + cos_tr_sub_v, + triggers, + costheta, + tauexitprob, + threshold, + spec_norm, + spec_weights_sum, + mcnorm, + numTrajs, +): + """Verbatim pre-refactor math (the regression oracle).""" + cossepangle = cos_tr_sub_v + + mcintfactor = cos_tr_sub_n / cos_n_sub_v / cos_tr_sub_v + + mcintfactor[cossepangle < costheta] = 0 + mcintegralgeoonly = np.sum(mcintfactor) * mcnorm / numTrajs + + Bshr = 0.826 + + mcintfactor *= Bshr * tauexitprob + mcintfactor /= spec_norm + mcintfactor /= spec_weights_sum + + mcintfactor[triggers < threshold] = 0 + mcintegral = np.sum(mcintfactor) * mcnorm / numTrajs + mcintegraluncert = np.sqrt(np.var(mcintfactor, ddof=1) / numTrajs) * mcnorm + + numEvPass = np.count_nonzero(mcintfactor) + + return mcintegral, mcintegralgeoonly, numEvPass, mcintegraluncert + + +def _sample(rng, n, per_event_costheta=True): + cos_tr_sub_n = rng.uniform(0.2, 1.0, n) + cos_n_sub_v = rng.uniform(0.3, 1.0, n) + cos_tr_sub_v = rng.uniform(0.985, 1.0, n) + # numPEs-like: many below threshold, some far above + triggers = rng.lognormal(mean=2.0, sigma=2.0, size=n) + tauexitprob = rng.uniform(0.0, 1.0, n) + if per_event_costheta: + # costhetaChEff near 1; some events fail the separation cut + costheta = rng.uniform(0.99, 1.0, n) + else: + costheta = 0.9986 # scalar (radio-like) + return cos_tr_sub_n, cos_n_sub_v, cos_tr_sub_v, triggers, tauexitprob, costheta + + +def test_mc_contribution_matches_original_reduction_bitexact(): + rng = np.random.default_rng(20260625) + for trial in range(25): + n = int(rng.integers(50, 5000)) + cos_tr_sub_n, cos_n_sub_v, cos_tr_sub_v, triggers, tauexitprob, costheta = ( + _sample(rng, n, per_event_costheta=bool(trial % 2)) + ) + threshold = 10.0 + spec_norm = rng.uniform(0.5, 2.0) + spec_weights_sum = rng.uniform(0.5, 2.0) + mcnorm = rng.uniform(1e3, 1e6) + numTrajs = n + int(rng.integers(0, n)) # invalid events inflate the denom + + want = _original_mcintegral( + cos_tr_sub_n.copy(), + cos_n_sub_v.copy(), + cos_tr_sub_v.copy(), + triggers.copy(), + np.array(costheta).copy(), + tauexitprob.copy(), + threshold, + spec_norm, + spec_weights_sum, + mcnorm, + numTrajs, + ) + + mcintfactor, geo = mc_contribution( + cos_tr_sub_n.copy(), + cos_n_sub_v.copy(), + cos_tr_sub_v.copy(), + triggers.copy(), + costheta, + tauexitprob.copy(), + threshold, + spec_norm, + spec_weights_sum, + ) + got = ( + np.sum(mcintfactor) * mcnorm / numTrajs, + np.sum(geo) * mcnorm / numTrajs, + np.count_nonzero(mcintfactor), + np.sqrt(np.var(mcintfactor, ddof=1) / numTrajs) * mcnorm, + ) + + # Bit-exact: same float operations in the same order. + np.testing.assert_array_equal(got[0], want[0]) + np.testing.assert_array_equal(got[1], want[1]) + assert got[2] == want[2] + np.testing.assert_array_equal(got[3], want[3]) + + +def test_mc_contribution_does_not_mutate_geo_into_full(): + """``geo`` (GEO-only sum) must stay the separation-cut base, not the full + contribution.""" + rng = np.random.default_rng(7) + n = 1000 + cos_tr_sub_n, cos_n_sub_v, cos_tr_sub_v, triggers, tauexitprob, costheta = _sample( + rng, n + ) + mcintfactor, geo = mc_contribution( + cos_tr_sub_n, + cos_n_sub_v, + cos_tr_sub_v, + triggers, + costheta, + tauexitprob, + 10.0, + 1.0, + 1.0, + ) + # geo is the pre-weight base: where it survived the sep cut it must equal + # cos_tr_sub_n / cos_n_sub_v / cos_tr_sub_v exactly. + survived = cos_tr_sub_v >= costheta + base = cos_tr_sub_n / cos_n_sub_v / cos_tr_sub_v + np.testing.assert_array_equal(geo[survived], base[survived]) + # full contribution is <= geo*const, and zero below threshold + assert np.all(mcintfactor[triggers < 10.0] == 0.0) diff --git a/test/simulation/streaming/test_reservoir.py b/test/simulation/streaming/test_reservoir.py new file mode 100644 index 00000000..598ca710 --- /dev/null +++ b/test/simulation/streaming/test_reservoir.py @@ -0,0 +1,135 @@ +"""WeightedReservoir: mergeability, bounded size, and sampling correctness.""" + +import numpy as np +import pytest +from scipy import stats + +from nuspacesim.simulation.streaming.reservoir import WeightedReservoir + + +def _batch_records(start, n): + ids = np.arange(start, start + n) + return {"id": ids, "value": ids.astype(np.float64)} + + +def test_size_never_exceeds_k(): + rng = np.random.default_rng(0) + k = 100 + res = WeightedReservoir.empty(k) + for b in range(20): + recs = _batch_records(b * 500, 500) + w = rng.uniform(0.1, 5.0, 500) + res = res.merge(WeightedReservoir.from_batch(k, recs, w, rng)) + assert len(res) <= k + assert len(res) == k # well over k seen total + + +def test_merge_is_order_independent(): + # Fixed per-batch reservoirs (keys frozen), then merge in different orders. + parts = [] + for b in range(12): + rng = np.random.default_rng(1000 + b) # deterministic keys per batch + recs = _batch_records(b * 300, 300) + w = rng.uniform(0.1, 9.0, 300) + parts.append(WeightedReservoir.from_batch(64, recs, w, rng)) + + def fold(seq): + r = WeightedReservoir.empty(64) + for p in seq: + r = r.merge(p) + return set(r.records["id"].tolist()) + + forward = fold(parts) + backward = fold(list(reversed(parts))) + shuffled = fold( + [parts[i] for i in np.random.default_rng(7).permutation(len(parts))] + ) + + assert forward == backward == shuffled + assert len(forward) == 64 + + +def test_uniform_weights_give_uniform_sample(): + # Equal weights -> keys are i.i.d. uniform -> retained values are a uniform + # random subset, independent of the value field. + n, k = 40_000, 4_000 + rng = np.random.default_rng(20260625) + recs = {"value": np.arange(n, dtype=np.float64)} + w = np.ones(n) + res = WeightedReservoir.from_batch(k, recs, w, rng) + assert len(res) == k + retained = res.records["value"] / n # -> [0, 1) + ks = stats.kstest(retained, "uniform") + assert ks.pvalue > 0.01, f"retained sample not uniform (p={ks.pvalue})" + + +def test_contribution_weighting_biases_toward_large_values(): + # weight == value: large-value items should be over-represented vs uniform. + n, k = 40_000, 2_000 + rng = np.random.default_rng(42) + values = np.arange(1, n + 1, dtype=np.float64) + recs = {"value": values} + weighted = WeightedReservoir.from_batch(k, recs, values, rng) + uniform = WeightedReservoir.from_batch(k, recs, np.ones(n), rng) + + pop_mean = values.mean() + # Weighted reservoir's retained mean should sit well above the population + # mean; the uniform one should hug it. + assert weighted.records["value"].mean() > 1.2 * pop_mean + assert uniform.records["value"].mean() == pytest.approx(pop_mean, rel=0.1) + + +def test_determinism_same_seed_same_keys(): + recs = _batch_records(0, 1000) + w = np.linspace(0.1, 3.0, 1000) + a = WeightedReservoir.from_batch(50, recs, w, np.random.default_rng(5)) + b = WeightedReservoir.from_batch(50, recs, w, np.random.default_rng(5)) + np.testing.assert_array_equal(np.sort(a.keys), np.sort(b.keys)) + assert set(a.records["id"].tolist()) == set(b.records["id"].tolist()) + + +def test_empty_merge_identity_and_underfull(): + rng = np.random.default_rng(3) + recs = _batch_records(0, 30) + r = WeightedReservoir.from_batch(100, recs, np.ones(30), rng) + assert len(r) == 30 # under-full: keep everything + e = WeightedReservoir.empty(100) + assert set(e.merge(r).records["id"].tolist()) == set(r.records["id"].tolist()) + assert set(r.merge(e).records["id"].tolist()) == set(r.records["id"].tolist()) + + +def test_invalid_k_raises(): + with pytest.raises(ValueError, match="k must be >= 1"): + WeightedReservoir.empty(0) + + +def test_mismatched_column_length_raises(): + with pytest.raises(ValueError, match="length"): + WeightedReservoir(k=10, keys=np.zeros(3), records={"a": np.zeros(2)}) + + +def test_merge_mismatched_k_raises(): + a = WeightedReservoir.empty(10) + b = WeightedReservoir.empty(20) + with pytest.raises(ValueError, match="size mismatch"): + a.merge(b) + + +def test_merge_mismatched_columns_raises(): + rng = np.random.default_rng(0) + a = WeightedReservoir.from_batch(10, {"x": np.arange(5)}, np.ones(5), rng) + b = WeightedReservoir.from_batch(10, {"y": np.arange(5)}, np.ones(5), rng) + with pytest.raises(ValueError, match="different columns"): + a.merge(b) + + +def test_zero_weight_items_only_backfill(): + # Half the items have zero weight; with k smaller than the positive-weight + # count, no zero-weight item should be retained. + rng = np.random.default_rng(11) + n = 1000 + w = np.ones(n) + w[: n // 2] = 0.0 # first half zero-weight + recs = {"idx": np.arange(n)} + res = WeightedReservoir.from_batch(200, recs, w, rng) + assert np.all(res.records["idx"] >= n // 2) diff --git a/test/simulation/streaming/test_sketch.py b/test/simulation/streaming/test_sketch.py new file mode 100644 index 00000000..af7c9089 --- /dev/null +++ b/test/simulation/streaming/test_sketch.py @@ -0,0 +1,166 @@ +"""MomentSketch: the streaming integral must equal the one-shot integral. + +Two proofs: + +1. **Authoritative single-batch** — a real :class:`RegionGeom` run: a sketch + built from the same per-event arrays reproduces ``RegionGeom.mcintegral`` + exactly for the linear terms and to floating tolerance for the variance. +2. **Merge exactness** — splitting one sample into many random batches and + merging the partial sketches reproduces the single-batch sketch (additivity + is order-independent). +""" + +import numpy as np +import pytest + +from nuspacesim.config import NssConfig +from nuspacesim.simulation.geometry.region_geometry import RegionGeom, mc_contribution +from nuspacesim.simulation.streaming.sketch import MomentSketch + + +def _real_region_geom(n_thrown=200_000, seed=20260625): + np.random.seed(seed) + geom = RegionGeom(NssConfig()) + geom.throw(n_thrown) + n_valid = int(np.count_nonzero(geom.event_mask)) + rng = np.random.default_rng(seed + 1) + # Fabricate detector response on the valid set. + triggers = rng.lognormal(mean=2.5, sigma=1.5, size=n_valid) # numPEs-like + tauexitprob = rng.uniform(0.0, 1.0, n_valid) + costheta = rng.uniform(0.99, 1.0, n_valid) # costhetaChEff-like + return geom, triggers, costheta, tauexitprob + + +def test_sketch_matches_real_region_geom_single_batch(): + geom, triggers, costheta, tauexitprob = _real_region_geom() + threshold, spec_norm, spec_weights_sum = 10.0, 1.0, 1.0 + + want = geom.mcintegral( + triggers, costheta, tauexitprob, threshold, spec_norm, spec_weights_sum + ) + mcint_ref, geo_ref, npass_ref, unc_ref = want + + mcintfactor, geo = mc_contribution( + geom.valid_costhetaTrSubN(), + geom.valid_costhetaNSubV(), + geom.valid_costhetaTrSubV(), + triggers, + costheta, + tauexitprob, + threshold, + spec_norm, + spec_weights_sum, + ) + sketch = MomentSketch.from_batch( + mcintfactor, geo, n_thrown=len(geom.betaTrSubN), mcnorm=geom.mcnorm + ) + + # Linear terms: identical float operations -> bit-exact. + assert sketch.mcint == mcint_ref + assert sketch.mcint_geo == geo_ref + assert sketch.n_pass == npass_ref + # Variance via moments vs np.var(ddof=1): equal to floating tolerance. + assert sketch.mcunc == pytest.approx(unc_ref, rel=1e-9) + assert sketch.rel_unc == pytest.approx(unc_ref / mcint_ref, rel=1e-9) + + +def test_sketch_merge_reproduces_single_batch(): + geom, triggers, costheta, tauexitprob = _real_region_geom() + threshold = 10.0 + mcintfactor, geo = mc_contribution( + geom.valid_costhetaTrSubN(), + geom.valid_costhetaNSubV(), + geom.valid_costhetaTrSubV(), + triggers, + costheta, + tauexitprob, + threshold, + 1.0, + 1.0, + ) + n_thrown_total = len(geom.betaTrSubN) + n_valid = mcintfactor.size + + single = MomentSketch.from_batch(mcintfactor, geo, n_thrown_total, geom.mcnorm) + + # Partition valid events AND the thrown denominator across random batches. + rng = np.random.default_rng(99) + order = rng.permutation(n_valid) + n_batches = 17 + valid_chunks = np.array_split(order, n_batches) + # distribute the geometry-invalid throws (n_thrown_total - n_valid) + invalid_total = n_thrown_total - n_valid + inv_per = np.full(n_batches, invalid_total // n_batches, dtype=int) + inv_per[: invalid_total % n_batches] += 1 + + merged = MomentSketch.empty(geom.mcnorm) + for chunk, inv in zip(valid_chunks, inv_per): + part = MomentSketch.from_batch( + mcintfactor[chunk], + geo[chunk], + n_thrown=len(chunk) + int(inv), + mcnorm=geom.mcnorm, + ) + merged = merged.merge(part) + + assert merged.n_thrown == single.n_thrown + assert merged.n_valid == single.n_valid + assert merged.n_pass == single.n_pass + assert merged.mcint == pytest.approx(single.mcint, rel=1e-12) + assert merged.mcint_geo == pytest.approx(single.mcint_geo, rel=1e-12) + assert merged.mcunc == pytest.approx(single.mcunc, rel=1e-10) + + +def test_sketch_merge_is_order_independent(): + rng = np.random.default_rng(3) + mcnorm = 12345.0 + parts = [] + for _ in range(8): + n = int(rng.integers(10, 500)) + mc = rng.lognormal(size=n) + mc[rng.uniform(size=n) < 0.4] = 0.0 # some non-passing + geo = rng.lognormal(size=n) + parts.append(MomentSketch.from_batch(mc, geo, n + 5, mcnorm)) + + a = MomentSketch.empty(mcnorm) + for p in parts: + a = a.merge(p) + b = MomentSketch.empty(mcnorm) + for p in reversed(parts): + b = b.merge(p) + + assert a.n_thrown == b.n_thrown and a.n_pass == b.n_pass + assert a.mcint == pytest.approx(b.mcint, rel=1e-12) + assert a.mcunc == pytest.approx(b.mcunc, rel=1e-10) + + +def test_empty_sketch_is_merge_identity(): + rng = np.random.default_rng(1) + mc = rng.lognormal(size=100) + geo = rng.lognormal(size=100) + s = MomentSketch.from_batch(mc, geo, 150, 99.0) + e = MomentSketch.empty(99.0) + assert e.merge(s).mcint == s.mcint + assert s.merge(e).mcint == s.mcint + assert e.merge(s).mcunc == s.mcunc + + +def test_merge_mismatched_mcnorm_raises(): + a = MomentSketch.empty(100.0) + b = MomentSketch.empty(200.0) + with pytest.raises(ValueError, match="different mcnorm"): + a.merge(b) + + +def test_no_signal_gives_zero_integral_and_inf_rel_unc(): + s = MomentSketch.empty(1000.0) + assert s.mcint == 0.0 + assert s.mcint_geo == 0.0 + assert s.rel_unc == np.inf + # valid events but all below threshold -> zero contribution, finite sketch + zeros = np.zeros(50) + geo = np.ones(50) + s2 = MomentSketch.from_batch(zeros, geo, 80, 1000.0) + assert s2.mcint == 0.0 + assert s2.mcint_geo > 0.0 + assert s2.rel_unc == np.inf diff --git a/test/simulation/streaming/test_streaming_smoke.py b/test/simulation/streaming/test_streaming_smoke.py new file mode 100644 index 00000000..f215fb3a --- /dev/null +++ b/test/simulation/streaming/test_streaming_smoke.py @@ -0,0 +1,161 @@ +"""End-to-end smoke test for the streaming optical Monte-Carlo driver. + +Spins up a real (small) dask cluster and runs ``compute_streaming`` to the +max-thrown backstop, checking the returned table's structure, metadata, and +that the integral is physically sane. The scientific streaming-vs-one-shot +equivalence (within MC noise) is verified separately; here we keep it fast. +""" + +import numpy as np +import pytest +from astropy.table import Table as AstropyTable + +from nuspacesim.config import NssConfig +from nuspacesim.simulation.streaming import compute_streaming + + +@pytest.fixture +def small_streaming_config(): + config = NssConfig() + config.detector.optical.enable = True + config.detector.radio.enable = False + config.simulation.mode = "Diffuse" + config.simulation.thrown_events = 40_000 # max-thrown backstop + s = config.simulation.streaming + s.batch_size = 10_000 + s.reservoir_size = 200 + s.rel_unc_target = 0.0 # never met -> deterministic max_thrown stop + s.min_thrown = 0 + return config + + +def test_compute_streaming_end_to_end(small_streaming_config): + sim = compute_streaming(small_streaming_config, verbose=False, seed=20260625) + + assert isinstance(sim, AstropyTable) + + # Sketch metadata, legacy keys. + assert sim.meta["OMCINT"][0] > 0.0 + assert sim.meta["OMCINTGO"][0] > 0.0 + assert sim.meta["ONEVPASS"][0] > 0 + assert sim.meta["OMCINTUN"][0] > 0.0 + # GEO-only integral exceeds the trigger-cut full integral. + assert sim.meta["OMCINTGO"][0] > sim.meta["OMCINT"][0] + + # Streaming provenance. + assert sim.meta["STRMSTOP"][0] == "max_thrown" + assert sim.meta["STRMNTHR"][0] >= 40_000 + assert sim.meta["STRMNVAL"][0] > 0 + assert sim.meta["STRMSEED"][0] == "20260625" + + # Reservoir materialized, bounded by k. + n_res = sim.meta["STRMNRES"][0] + assert 0 < n_res <= 200 + assert len(sim) == n_res + for col in ("beta_rad", "numPEs", "costhetaChEff", "mcintfactor", "init_lat"): + assert col in sim.colnames + assert np.all(np.isfinite(sim["numPEs"])) + + # Contribution-weighted reservoir: retained events should be passing + # (non-zero contribution) while passing events outnumber k. + assert sim.meta["ONEVPASS"][0] > 200 + assert np.all(sim["mcintfactor"] > 0.0) + + +def test_compute_streaming_infinite_cap_stops_on_precision(small_streaming_config): + # max_thrown=inf must NOT loop forever: the precision target drives the stop. + cfg = small_streaming_config + cfg.simulation.streaming.rel_unc_target = 0.05 + cfg.simulation.streaming.min_thrown = 0 + sim = compute_streaming(cfg, verbose=False, seed=1, max_thrown=float("inf")) + assert sim.meta["STRMSTOP"][0] == "rel_unc_target" + assert 0 < sim.meta["STRMNTHR"][0] < 10_000_000 + assert sim.meta["OMCINTUN"][0] / sim.meta["OMCINT"][0] <= 0.05 + 1e-9 + + +def test_compute_streaming_adaptive_batch(small_streaming_config): + cfg = small_streaming_config + cfg.simulation.streaming.rel_unc_target = 0.05 + cfg.simulation.streaming.min_thrown = 0 + sim = compute_streaming( + cfg, verbose=False, seed=2, max_thrown=float("inf"), batch_size="adaptive" + ) + assert sim.meta["STRMBATC"][0].startswith("adaptive(") + assert sim.meta["OMCINT"][0] > 0.0 + assert sim.meta["STRMSTOP"][0] == "rel_unc_target" + + +def test_adaptive_batch_climbs_and_settles(): + from nuspacesim.simulation.streaming.driver import _AdaptiveBatch + + asymptote = 1_000_000.0 + half = 8000.0 # throughput half-saturation batch size + + def rate(B): # increasing, saturating: B/dt == rate(B) below drives the loop + return asymptote * B / (half + B) + + ctrl = _AdaptiveBatch(start=1000) + B = ctrl.current() + for _ in range(80): + dt = B / rate(B) + B = ctrl.update(B, dt) + + assert ctrl.mode == "hold" # settled + assert ctrl.current() > 1000 # grew from the small start + assert ctrl.lo <= ctrl.current() <= ctrl.hi + assert rate(ctrl.current()) > 0.8 * asymptote # near saturation + + +def test_adaptive_batch_holds_when_starting_past_knee(): + from nuspacesim.simulation.streaming.driver import _AdaptiveBatch + + def rate(B): + return 1_000_000.0 * B / (2000.0 + B) # knee at a few thousand + + ctrl = _AdaptiveBatch(start=40000) # already saturated + B = ctrl.current() + for _ in range(20): + dt = B / rate(B) + B = ctrl.update(B, dt) + + assert ctrl.mode == "hold" + assert ctrl.current() <= 40000 # did not keep growing + + +def test_adaptive_batch_ignores_nonpositive_dt(): + from nuspacesim.simulation.streaming.driver import _AdaptiveBatch + + ctrl = _AdaptiveBatch(start=5000) + assert ctrl.update(5000, 0.0) == 5000 + assert ctrl.update(5000, -1.0) == 5000 + + +def test_fmt_max_renders_infinity(): + from nuspacesim.simulation.streaming.driver import _fmt_max + + assert _fmt_max(float("inf")) == "∞" + assert _fmt_max(1_000_000) == "1,000,000" + + +def test_spacebar_listener_safe_construction(): + # Construction and enter/exit must never raise or pre-trip, regardless of + # whether stdin is a TTY in this environment. + from nuspacesim.simulation.streaming.driver import _SpacebarListener + + lis = _SpacebarListener() + assert lis.pressed.is_set() is False + with lis: + pass + assert lis.pressed.is_set() is False + + +def test_compute_streaming_rejects_target_mode(small_streaming_config): + small_streaming_config.simulation.mode = "Target" + with pytest.raises(NotImplementedError): + compute_streaming(small_streaming_config, verbose=False) + + +def test_compute_streaming_requires_optical(small_streaming_config): + small_streaming_config.detector.optical.enable = False + with pytest.raises(ValueError, match="optical"): + compute_streaming(small_streaming_config, verbose=False)