From dd39545a8a8798c37ba0fb02311d84dc833a7d7b Mon Sep 17 00:00:00 2001 From: Alex Reustle Date: Fri, 11 Sep 2026 11:33:51 -0400 Subject: [PATCH 1/4] ToO: fetch sun/moon ephemerides once in sun_moon_cut sun_moon_cut called get_body four times per evaluation (sun and moon for the altitude cuts, then both again inside moon_phase_angle) and built three identical AltAz frames. Fetch each body once, share one frame, and compute the phase angle from the coordinates already in hand. Output is bit-identical (A/B on 1k/10k/40k random observation times); the cut stage runs 1.67x faster, ~12% off ToO-mode wall time at 1M thrown. get_sun/get_moon/moon_phase_angle(time) keep their signatures. Co-Authored-By: Claude Fable 5 --- src/nuspacesim/simulation/geometry/too.py | 43 ++++++++++++++++------- 1 file changed, 30 insertions(+), 13 deletions(-) diff --git a/src/nuspacesim/simulation/geometry/too.py b/src/nuspacesim/simulation/geometry/too.py index dbb1bb02..77ee1709 100755 --- a/src/nuspacesim/simulation/geometry/too.py +++ b/src/nuspacesim/simulation/geometry/too.py @@ -74,44 +74,61 @@ def __init__(self, config): height=self.detalt * 1000 * u.m, ) + def detframe(self, time): + return astropy.coordinates.AltAz(obstime=time, location=self.detcords) + def localcoords(self, time): - detframe = astropy.coordinates.AltAz(obstime=time, location=self.detcords) - return self.eventcoords.transform_to(detframe) + return self.eventcoords.transform_to(self.detframe(time)) def get_sun(self, time): sun_coord = astropy.coordinates.get_body("sun", time) - detframe = astropy.coordinates.AltAz(obstime=time, location=self.detcords) - return sun_coord.transform_to(detframe) + return sun_coord.transform_to(self.detframe(time)) def get_moon(self, time): moon_coord = astropy.coordinates.get_body("moon", time) - detframe = astropy.coordinates.AltAz(obstime=time, location=self.detcords) - return moon_coord.transform_to(detframe) + return moon_coord.transform_to(self.detframe(time)) @staticmethod - def moon_phase_angle(time: astropy.time.Time) -> float: + def phase_angle_from_bodies(sun, moon): """ - Returns the moon phase angle in rad + Moon phase angle in rad from geocentric sun and moon coordinates 0 -> full moon pi -> new moon """ - sun = astropy.coordinates.get_body("sun", time) - moon = astropy.coordinates.get_body("moon", time) elongation = sun.separation(moon) return np.arctan2( sun.distance * np.sin(elongation), moon.distance - sun.distance * np.cos(elongation), ) + @classmethod + def moon_phase_angle(cls, time: astropy.time.Time) -> float: + """ + Returns the moon phase angle in rad + 0 -> full moon + pi -> new moon + """ + sun = astropy.coordinates.get_body("sun", time) + moon = astropy.coordinates.get_body("moon", time) + return cls.phase_angle_from_bodies(sun, moon) + def sun_moon_cut(self, time: astropy.time.Time) -> bool: """ Function to calculate the time during which sun and moon allow observation True -> observation possible False -> no observation posible """ - sun_alt = self.get_sun(time).alt.rad < self.sun_alt_cut - moon_alt = self.get_moon(time).alt.rad < self.moon_alt_cut - moon_phase = self.moon_phase_angle(time).value > self.MoonMinPhaseAngleCut + # One ephemeris lookup per body and one AltAz frame serve the altitude + # cuts and the phase angle; the lookups dominate ToO-mode runtime. + sun = astropy.coordinates.get_body("sun", time) + moon = astropy.coordinates.get_body("moon", time) + detframe = self.detframe(time) + + sun_alt = sun.transform_to(detframe).alt.rad < self.sun_alt_cut + moon_alt = moon.transform_to(detframe).alt.rad < self.moon_alt_cut + moon_phase = ( + self.phase_angle_from_bodies(sun, moon).value > self.MoonMinPhaseAngleCut + ) moon_cut = np.logical_or(moon_phase, moon_alt) return np.logical_and(sun_alt, moon_cut) From 10558625968165f76fc00a2f47a82259323aa43e Mon Sep 17 00:00:00 2001 From: Alex Reustle Date: Fri, 11 Sep 2026 13:41:59 -0400 Subject: [PATCH 2/4] ToO: evaluate sky positions on a coarse time grid and interpolate Target mode asked astropy for the exact source AltAz at every thrown time and exact sun/moon ephemerides at every valid time. Those are smooth functions over the observation window, so evaluate them exactly on a grid (simulation.target.ephemeris_step, default 60 s; 0 = exact) and cubic-interpolate to the requested times. The source is interpolated as a unit vector so azimuth wrap is harmless; sun/moon altitude and phase angle are interpolated directly. Scalar or few-point queries (fewer than the grid) still evaluate exactly. A/B vs exact at 200k thrown (24 h window): source position error 2e-8 rad, sun/moon altitude 2e-10 rad, phase 3e-11 rad; horizon, volume and sun/moon masks identical for steps up to 900 s. End-to-end compute at 1M thrown: identical row count and passing events, OMCINT relative difference 2.6e-11, wall 25.1 s -> 1.7 s. Co-Authored-By: Claude Fable 5 --- src/nuspacesim/config.py | 4 ++ src/nuspacesim/simulation/geometry/too.py | 87 +++++++++++++++++++---- test/core/test_config.py | 1 + test/simulation/geometry/test_too.py | 35 +++++++++ 4 files changed, 113 insertions(+), 14 deletions(-) diff --git a/src/nuspacesim/config.py b/src/nuspacesim/config.py index f485e2fd..480bd92b 100644 --- a/src/nuspacesim/config.py +++ b/src/nuspacesim/config.py @@ -293,6 +293,10 @@ class TargetOfOpportunity(BaseModel): """Date of the event and format""" source_obst: float = 86400 # 24.0 * 60.0 * 60.0 """Observation time (s). Default = 1 day""" + ephemeris_step: float = 60.0 + """Grid spacing (s) for source/sun/moon sky positions, which are + evaluated exactly on the grid and cubic-interpolated to thrown times. + 0 evaluates every thrown time exactly. Default = 60 s""" ################################################################################ diff --git a/src/nuspacesim/simulation/geometry/too.py b/src/nuspacesim/simulation/geometry/too.py index 77ee1709..52433a10 100755 --- a/src/nuspacesim/simulation/geometry/too.py +++ b/src/nuspacesim/simulation/geometry/too.py @@ -35,6 +35,7 @@ import astropy.time import astropy.units as u import numpy as np +from scipy.interpolate import CubicSpline class ToOEvent: @@ -56,6 +57,7 @@ def __init__(self, config): self.sourceDATE = self.config.simulation.target.source_date self.sourceDateFormat = self.config.simulation.target.source_date_format self.sourceOBSTime = self.config.simulation.target.source_obst + self.ephemeris_step = self.config.simulation.target.ephemeris_step self.eventtime = astropy.time.Time( self.sourceDATE, format=self.sourceDateFormat, scale="utc" @@ -77,8 +79,47 @@ def __init__(self, config): def detframe(self, time): return astropy.coordinates.AltAz(obstime=time, location=self.detcords) + def _ephemeris_grid(self, time): + """Coarse time grid spanning ``time`` for interpolated sky positions. + + Returns ``(grid_time, grid_x, x)`` with ``x`` the query abscissae in + seconds, or ``None`` when exact evaluation is requested or is no more + work than the grid itself. + """ + step = self.ephemeris_step + if step <= 0 or time.isscalar: + return None + x = time.utc.unix + x0, x1 = x.min(), x.max() + # Pad one step each side so every query is interior to the spline. + n_grid = int(np.ceil((x1 - x0) / step)) + 3 + if n_grid >= x.size: + return None + grid_x = (x0 - step) + step * np.arange(n_grid) + grid_time = astropy.time.Time(grid_x, format="unix", scale="utc") + return grid_time, grid_x, x + def localcoords(self, time): - return self.eventcoords.transform_to(self.detframe(time)) + grid = self._ephemeris_grid(time) + if grid is None: + return self.eventcoords.transform_to(self.detframe(time)) + grid_time, grid_x, x = grid + exact = self.eventcoords.transform_to(self.detframe(grid_time)) + # Interpolate the unit vector, not (alt, az): azimuth wraps at 2pi. + cos_alt = np.cos(exact.alt.rad) + vec = np.stack( + [ + cos_alt * np.cos(exact.az.rad), + cos_alt * np.sin(exact.az.rad), + np.sin(exact.alt.rad), + ] + ) + vx, vy, vz = CubicSpline(grid_x, vec, axis=1)(x) + alt = np.arctan2(vz, np.hypot(vx, vy)) + az = np.arctan2(vy, vx) % (2.0 * np.pi) + return astropy.coordinates.AltAz( + alt=alt * u.rad, az=az * u.rad, obstime=time, location=self.detcords + ) def get_sun(self, time): sun_coord = astropy.coordinates.get_body("sun", time) @@ -112,23 +153,41 @@ def moon_phase_angle(cls, time: astropy.time.Time) -> float: moon = astropy.coordinates.get_body("moon", time) return cls.phase_angle_from_bodies(sun, moon) - def sun_moon_cut(self, time: astropy.time.Time) -> bool: - """ - Function to calculate the time during which sun and moon allow observation - True -> observation possible - False -> no observation posible - """ + def _sun_moon_state(self, time): + """Exact (sun altitude, moon altitude, moon phase angle) in rad.""" # One ephemeris lookup per body and one AltAz frame serve the altitude # cuts and the phase angle; the lookups dominate ToO-mode runtime. sun = astropy.coordinates.get_body("sun", time) moon = astropy.coordinates.get_body("moon", time) detframe = self.detframe(time) - - sun_alt = sun.transform_to(detframe).alt.rad < self.sun_alt_cut - moon_alt = moon.transform_to(detframe).alt.rad < self.moon_alt_cut - moon_phase = ( - self.phase_angle_from_bodies(sun, moon).value > self.MoonMinPhaseAngleCut + return np.stack( + [ + sun.transform_to(detframe).alt.rad, + moon.transform_to(detframe).alt.rad, + self.phase_angle_from_bodies(sun, moon).value, + ] ) - moon_cut = np.logical_or(moon_phase, moon_alt) - return np.logical_and(sun_alt, moon_cut) + def sun_moon_state(self, time): + """(sun altitude, moon altitude, moon phase angle) in rad at ``time``. + + Evaluated on the ephemeris grid and cubic-interpolated when that is + cheaper than evaluating every requested time. + """ + grid = self._ephemeris_grid(time) + if grid is None: + return self._sun_moon_state(time) + grid_time, grid_x, x = grid + return CubicSpline(grid_x, self._sun_moon_state(grid_time), axis=1)(x) + + def sun_moon_cut(self, time: astropy.time.Time) -> bool: + """ + Function to calculate the time during which sun and moon allow observation + True -> observation possible + False -> no observation posible + """ + sun_alt, moon_alt, moon_phase = self.sun_moon_state(time) + moon_cut = np.logical_or( + moon_phase > self.MoonMinPhaseAngleCut, moon_alt < self.moon_alt_cut + ) + return np.logical_and(sun_alt < self.sun_alt_cut, moon_cut) diff --git a/test/core/test_config.py b/test/core/test_config.py index 465b9d84..0ed6cc0f 100644 --- a/test/core/test_config.py +++ b/test/core/test_config.py @@ -336,6 +336,7 @@ def test_default_simulation(): "source_date": "2022-06-02T01:00:00", "source_date_format": "isot", "source_obst": 86400, + "ephemeris_step": 60.0, }, } diff --git a/test/simulation/geometry/test_too.py b/test/simulation/geometry/test_too.py index 85e6c167..90abff96 100644 --- a/test/simulation/geometry/test_too.py +++ b/test/simulation/geometry/test_too.py @@ -1,5 +1,6 @@ import numpy as np import pytest +import astropy.units as u from astropy.time import Time from nuspacesim.config import NssConfig @@ -100,3 +101,37 @@ def test_sun_moon_cuts(too_event): darkmoon_date = "2022-11-29" dark = Time(darkmoon_date + "T22:00:00", format="isot", scale="utc") assert too_event.sun_moon_cut(dark) + + +def test_ephemeris_grid_matches_exact(nss_config_event): + """Grid-interpolated sky positions must reproduce exact evaluation.""" + import copy + + exact_conf = copy.deepcopy(nss_config_event) + exact_conf.simulation.target.ephemeris_step = 0.0 + exact = too.ToOEvent(exact_conf) + interp = too.ToOEvent(nss_config_event) + assert interp.ephemeris_step == 60.0 + + # Random times over one observation window: far more queries than grid points. + rng = np.random.default_rng(7) + times = exact.eventtime + rng.random(5000) * exact.sourceOBSTime * u.s + + a, b = exact.localcoords(times), interp.localcoords(times) + sep = np.arccos( + np.clip( + np.sin(a.alt.rad) * np.sin(b.alt.rad) + + np.cos(a.alt.rad) * np.cos(b.alt.rad) * np.cos(a.az.rad - b.az.rad), + -1, + 1, + ) + ) + assert sep.max() < 1e-6 # rad; ~0.2 arcsec + + sa, sb = exact.sun_moon_state(times), interp.sun_moon_state(times) + assert np.abs(sa - sb).max() < 1e-6 + assert np.array_equal(exact.sun_moon_cut(times), interp.sun_moon_cut(times)) + + # Scalar and few-point queries fall back to exact evaluation. + assert interp._ephemeris_grid(times[0]) is None + assert interp._ephemeris_grid(times[:3]) is None From dc591c2939d3a3c224810a210df8b16f6a26cd55 Mon Sep 17 00:00:00 2001 From: Alex Reustle Date: Fri, 11 Sep 2026 15:08:50 -0400 Subject: [PATCH 3/4] compute: run EAS optical in-process below a valid-shower threshold The dask LocalCluster costs ~0.7 s to spawn and ~0.25 s to close, which was half the wall time of a 1M-throw Target run once the ToO geometry was fixed. CphotAng.__call__ and EAS.__call__ gain serial=True, which runs the same packed chunk kernel on the whole batch in this process. compute() now decides after geometry, when the valid count is known: below simulation.eas_parallel_threshold (default 150_000; 0 = always cluster) it runs serially and never starts a cluster; at or above it, the background cluster starts there and overlaps the spectra/tau/decay stages as before. A/B, seed-matched, every column and MC meta bit-identical both ways: Diffuse 99k valid: cluster 1.88 s, serial 1.10 s Diffuse 992k valid: cluster 3.99 s, serial 11.36 s Diffuse 3.97M valid: cluster 10.9 s, serial 45.5 s Target 39k valid: cluster 2.27 s, serial 0.74 s Target 194k valid: cluster 2.88 s, serial 3.07 s Fit: ~11 us/shower serial vs ~1.3 s + ~2.7 us/shower on the cluster, break-even ~150k valid showers. Co-Authored-By: Claude Fable 5 --- src/nuspacesim/compute.py | 27 +++++++++++-------- src/nuspacesim/config.py | 4 +++ .../simulation/eas_optical/cphotang.py | 25 ++++++++++++----- src/nuspacesim/simulation/eas_optical/eas.py | 5 +++- test/core/test_config.py | 1 + 5 files changed, 43 insertions(+), 19 deletions(-) diff --git a/src/nuspacesim/compute.py b/src/nuspacesim/compute.py index 6cc5c24f..99e092e0 100644 --- a/src/nuspacesim/compute.py +++ b/src/nuspacesim/compute.py @@ -187,12 +187,6 @@ def add_meta(self, name: str, value: Any, comment: str): logv(f"Running NuSpaceSim with Energy Spectrum ({config.simulation.spectrum})") - # The single EAS optical __call__ needs a process-based dask cluster whose - # ~2s spawn would otherwise be paid serially at that stage. Start it now, in - # the background, so the spawn overlaps the geometry/spectra/tau/decay - # stages; it's handed to eas() warm and torn down right after. - optical_cluster = BackgroundCluster() if config.detector.optical.enable else None - logv("Computing [green] Geometries.[/]") beta_tr, thetaArr, pathLenArr, *_ = geom( config.simulation.thrown_events, store=sw, plot=to_plot @@ -208,10 +202,19 @@ def add_meta(self, name: str, value: Any, comment: str): console.log( "\t[red] WARNING: No valid events thrown! Exiting early! Check geometry![/]" ) - if optical_cluster is not None: - optical_cluster.close() return sim + # The single EAS optical __call__ can fan out over a process-based dask + # cluster, but its ~1s spawn/teardown only pays for itself on large valid + # batches. Decide now that the valid count is known; when a cluster is + # warranted, start it in the background so the spawn overlaps the + # spectra/tau/decay stages, then hand it to eas() warm and tear it down + # right after. + use_cluster = config.detector.optical.enable and ( + beta_tr.size >= config.simulation.eas_parallel_threshold + ) + optical_cluster = BackgroundCluster() if use_cluster else None + init_lat, init_long = geom.find_lat_long_along_traj(np.zeros_like(beta_tr)) sw( ("init_lat", "init_lon"), @@ -243,14 +246,16 @@ def add_meta(self, name: str, value: Any, comment: str): init_lat, init_long, cloudf=cloud, - client=optical_cluster.client(), + client=optical_cluster.client() if use_cluster else None, + serial=not use_cluster, store=sw, plot=to_plot, ) # Single consumer is done; release the warm cluster immediately. - optical_cluster.close() - optical_cluster = None + if use_cluster: + optical_cluster.close() + optical_cluster = None logv("Computing [green] Optical Monte Carlo Integral.[/]") mcint, mcintgeo, passEV, mcunc = geom.mcintegral( diff --git a/src/nuspacesim/config.py b/src/nuspacesim/config.py index 480bd92b..0e279933 100644 --- a/src/nuspacesim/config.py +++ b/src/nuspacesim/config.py @@ -304,6 +304,10 @@ class TargetOfOpportunity(BaseModel): """ The Simulation Mode """ thrown_events: int = 1000 """ Number of thrown event trajectories. """ + eas_parallel_threshold: int = 150_000 + """Valid showers at or above which the EAS optical stage runs on a + process-based dask cluster; below it the stage runs in-process, avoiding + the cluster's ~1 s spawn/teardown. 0 always uses the cluster.""" max_cherenkov_angle: Radians = np.radians(3) """ Maximum Cherenkov Angle (Radians). """ max_azimuth_angle: Radians = np.radians(360) diff --git a/src/nuspacesim/simulation/eas_optical/cphotang.py b/src/nuspacesim/simulation/eas_optical/cphotang.py index ad95859a..7b934a3d 100644 --- a/src/nuspacesim/simulation/eas_optical/cphotang.py +++ b/src/nuspacesim/simulation/eas_optical/cphotang.py @@ -863,6 +863,7 @@ def __call__( n_slant_sub=8, n_energy_low=3, n_energy_high=8, + serial=False, ): """ Iterate over the list of events and return the result as pair of @@ -900,6 +901,11 @@ def __call__( Gauss-Legendre quadrature node counts forwarded to :meth:`run` (defaults match ``run()``). The pipeline wires these from ``config.simulation.cherenkov_quadrature``. + + ``serial=True`` runs the whole batch in this process through the same + 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. """ if ( @@ -940,13 +946,18 @@ def chunk_worker(b, a, e, lat, lon): d_rows = d_batch.T if per_wavelength else d_batch[None, :] return np.concatenate([d_rows, c_batch[None, :]], axis=0) - results = map_showers_distributed( - chunk_worker, - (betaE, alt, Eshow100PeV, init_lat, init_long), - n_rows=n_den + 1, - chunks=chunks, - client=client, - ) + if serial: + results = chunk_worker( + *(np.asarray(x) for x in (betaE, alt, Eshow100PeV, init_lat, init_long)) + ) + else: + results = map_showers_distributed( + chunk_worker, + (betaE, alt, Eshow100PeV, init_lat, init_long), + n_rows=n_den + 1, + chunks=chunks, + client=client, + ) # Unpack (n_rows, N): density rows then the Cang row. Collapsed -> # (N,); per-wavelength -> (N, n_wl) (transpose back the n_den rows). diff --git a/src/nuspacesim/simulation/eas_optical/eas.py b/src/nuspacesim/simulation/eas_optical/eas.py index d8944963..3a3f8b98 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, ): """ @@ -99,7 +100,8 @@ 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. + CphotAng spins up its own LocalCluster. ``serial=True`` skips the + cluster entirely and runs CphotAng in this process. """ # Mask out-of-bounds events. Do not pass to CphotAng. Instead use @@ -121,6 +123,7 @@ def __call__( init_long[mask], cloudf, client=client, + serial=serial, n_nodes=quad.n_nodes, n_slant_sub=quad.n_slant_sub, n_energy_low=quad.n_energy_low, diff --git a/test/core/test_config.py b/test/core/test_config.py index 0ed6cc0f..0f83cd7d 100644 --- a/test/core/test_config.py +++ b/test/core/test_config.py @@ -309,6 +309,7 @@ def test_default_simulation(): assert a.model_dump() == { "mode": "Diffuse", "thrown_events": 1000, + "eas_parallel_threshold": 150000, "max_cherenkov_angle": "3.0000000000000004 deg", "max_azimuth_angle": "360.0 deg", "angle_from_limb": "7.0 deg", From 41143afab866a8f8ba4426905b39cd7a1c28a479 Mon Sep 17 00:00:00 2001 From: Alex Reustle Date: Fri, 11 Sep 2026 15:27:52 -0400 Subject: [PATCH 4/4] test: isort import order in test_too.py Co-Authored-By: Claude Fable 5 --- test/simulation/geometry/test_too.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/simulation/geometry/test_too.py b/test/simulation/geometry/test_too.py index 90abff96..44897b5c 100644 --- a/test/simulation/geometry/test_too.py +++ b/test/simulation/geometry/test_too.py @@ -1,6 +1,6 @@ +import astropy.units as u import numpy as np import pytest -import astropy.units as u from astropy.time import Time from nuspacesim.config import NssConfig