From 2a1bf3cebb69a6e5ad069829cf49f9b754cfdbcc Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 5 Oct 2026 18:31:39 +0000 Subject: [PATCH] Prepare ray tables ahead and trim the sensor burst (Paket 2 L1, L2) Ray tables are pure functions of their key: predicted keys (start pairs, path drift, rounding edges) are traced ahead by a niced helper process or in time-budgeted slices, and a key needed now is waited for, finished or built at once, so results stay bit-identical. Sound speed profiles are cached, receiver curves, masks and windows precomputed, and civilian coast probes skipped where open water is guaranteed. Co-Authored-By: Claude Opus 5.5 (1M context) --- main.py | 4 + src/audio/receiver.py | 66 ++++++++-- src/core/config.py | 10 ++ src/core/game_reset.py | 1 + src/core/game_sim.py | 39 +++++- src/core/mission_bridge.py | 10 ++ src/enemies/surface.py | 9 +- src/sensors/platform.py | 3 +- src/sonar/propagation.py | 129 ++++++++++++++++++-- src/sonar/raytrace.py | 216 +++++++++++++++++++++++++++++++-- src/sonar/raytrace_worker.py | 228 +++++++++++++++++++++++++++++++++++ src/sonar/sonar.py | 9 +- src/world/coastline.py | 50 ++++++++ 13 files changed, 740 insertions(+), 34 deletions(-) create mode 100644 src/sonar/raytrace_worker.py diff --git a/main.py b/main.py index c76907db..93fd4de3 100644 --- a/main.py +++ b/main.py @@ -9,6 +9,7 @@ import sys from pathlib import Path from urllib.parse import urlsplit +from src.core import config from src.core.crashlog import run_logged from src.core.game import Game from src.core.preferences import load_preferences @@ -97,6 +98,9 @@ def _start(args, argv=None) -> int: preferences = load_preferences() seed = args.seed if args.seed is not None else random.SystemRandom().randrange( 1, 1_000_000_000) + # The interactive game finishes a mission's first ray tables with its + # start instead of in its first sensor pass (src/sonar/raytrace.py). + config.RAY_PREWARM_ON_START = True game = Game(seed=seed, start_menu=True, preferences=preferences, fullscreen=preferences.fullscreen and not args.windowed and not args.web_host, diff --git a/src/audio/receiver.py b/src/audio/receiver.py index 2307e012..05f30d13 100644 --- a/src/audio/receiver.py +++ b/src/audio/receiver.py @@ -58,6 +58,25 @@ def smooth_limit(samples, knee: float = 0.75, return np.copysign(limited, signal).astype(np.float32) +_CURVE_ARRAYS: "OrderedDict[tuple, tuple]" = OrderedDict() + + +def _curve_arrays(curve): + """(x, y) arrays of a gain curve, memoised in a bounded LRU (pure).""" + arrays = _CURVE_ARRAYS.get(curve) + if arrays is not None: + _CURVE_ARRAYS.move_to_end(curve) + return arrays + x = np.asarray([point[0] for point in curve]) + y = np.asarray([point[1] for point in curve]) + x.setflags(write=False) + y.setflags(write=False) + arrays = _CURVE_ARRAYS[curve] = (x, y) + while len(_CURVE_ARRAYS) > 256: + _CURVE_ARRAYS.popitem(last=False) + return arrays + + def _finite(value, default=0.0): try: value = float(value) @@ -140,6 +159,12 @@ class AcousticReceiver: widths = np.where(centers < 40, 1, np.where(centers < 100, 2, 5)) self._bin_starts = np.searchsorted(self._frequencies, centers - widths / 2) self._band_cache = OrderedDict() + self._curve_masks = OrderedDict() + # Analysis constants of the fixed two-second history (pure). + self._low_bins = self._frequencies <= 300 + self._demon_bins = np.flatnonzero((self._frequencies >= 1) + & (self._frequencies <= 80)) + self._windows = {} self.evicted_blocks = 0 self.reset() @@ -256,10 +281,23 @@ class AcousticReceiver: @staticmethod def _curve_gain(curve: tuple[tuple[float, float], ...], frequencies): - x = np.asarray([point[0] for point in curve]) - y = np.asarray([point[1] for point in curve]) + x, y = _curve_arrays(curve) return np.interp(frequencies, x, y, left=y[0], right=y[-1]) + def _curve_mask(self, curve: tuple[tuple[float, float], ...]) -> np.ndarray: + """``_curve_gain`` over the block FFT grid, memoised per curve (a + bounded LRU of read-only arrays; identical values, fewer interps).""" + mask = self._curve_masks.get(curve) + if mask is not None: + self._curve_masks.move_to_end(curve) + return mask + mask = self._curve_gain(curve, self._block_freqs) + mask.setflags(write=False) + self._curve_masks[curve] = mask + while len(self._curve_masks) > self.BAND_CACHE_SIZE: + self._curve_masks.popitem(last=False) + return mask + def _frame_audio(self, frame: np.ndarray, mask: np.ndarray, window: np.ndarray) -> np.ndarray: return np.fft.irfft(np.fft.rfft(window * frame) * mask, n=frame.size) @@ -444,9 +482,8 @@ class AcousticReceiver: self._time.size) # OLA preserves the boundary while this bounded per-frame blend # prevents abrupt spectral coloration as path geometry changes. - frequencies = self._block_freqs - target_mask = self._curve_gain(curve, frequencies) - previous_mask = self._curve_gain(old_curve, frequencies) + target_mask = self._curve_mask(curve) + previous_mask = self._curve_mask(old_curve) base_mask = self._band_mask(bb_low, bb_high) mask = base_mask * ( .5 * previous_mask + .5 * target_mask) @@ -519,6 +556,18 @@ class AcousticReceiver: self._blocks.append((self.sequence, self.samples)) self._analyze(data) + def _window(self, size: int): + """Hann window of ``size`` samples and its amplitude scale (bounded: + the history fills in whole blocks, so few sizes ever occur).""" + cached = self._windows.get(size) + if cached is None: + if len(self._windows) >= 16: + self._windows.clear() + window = np.hanning(size) + window.setflags(write=False) + cached = self._windows[size] = (window, 2 / window.sum()) + return cached + def _analyze(self, data): """Analyze raw beam samples, with no access to source descriptors.""" self.demon_analysis = None @@ -529,10 +578,9 @@ class AcousticReceiver: self.spectrum = [0.0] * config.LOFAR_BINS return data = data - data.mean() - window = np.hanning(data.size) - scale = 2 / window.sum() + window, scale = self._window(data.size) amplitudes = np.abs(np.fft.rfft(data * window, n=self._history.size)) * scale - low = amplitudes[self._frequencies <= 300] + low = amplitudes[self._low_bins] self.spectrum = np.clip(np.maximum.reduceat(low, self._bin_starts) / .25, 0, 1).tolist() self.native_spectrum = np.clip(low[:601] / .25, 0, 1) if data.size < self.sample_rate: @@ -556,7 +604,7 @@ class AcousticReceiver: envelope_mean = float(envelope.mean()) modulation = np.abs(np.fft.rfft((envelope - envelope_mean) * window, n=self._history.size)) * scale - band_indices = np.flatnonzero((self._frequencies >= 1) & (self._frequencies <= 80)) + band_indices = self._demon_bins band = modulation[band_indices] self.demon_spectrum = np.clip(np.interp(np.arange(1, 81), self._frequencies, modulation) / .10, 0, 1).tolist() diff --git a/src/core/config.py b/src/core/config.py index 727d5a55..234eab25 100644 --- a/src/core/config.py +++ b/src/core/config.py @@ -44,6 +44,16 @@ FPS_DEFAULT = 30 # stall that long is concealed and then fully caught up instead of cut. SIM_FRAME_DT_MAX = 0.1 SIM_CATCHUP_MAX_S = 2.5 +# Ray tables asked for ahead (src/sonar/raytrace.py) are traced in slices of +# at most this much wall time per frame; the menus, which simulate nothing, +# give them more. Wall time decides only how soon a table is ready. +RAY_PREFETCH_FRAME_BUDGET_S = 0.003 +RAY_PREFETCH_MENU_BUDGET_S = 0.012 +# A mission started from the menus finishes its first tables with the start +# (up to this long) instead of in its first sensor pass; main.py switches this +# on for the interactive game, tests and tools keep it off. +RAY_PREWARM_ON_START = False +RAY_PREWARM_MAX_S = 6.0 AUDIO_ENABLED = True AUDIO_SAMPLE_RATE = 22050 # Solo Remote Crew: while the paired browser is live the uConsole only redraws a diff --git a/src/core/game_reset.py b/src/core/game_reset.py index 048b871d..bc75de8a 100644 --- a/src/core/game_reset.py +++ b/src/core/game_reset.py @@ -546,6 +546,7 @@ class ResetMixin: self.hq_msg(self._initial_threat_notice()) if self.hq_intel_mode() == "exact": self.hq_msg(self._threat_identification_notice()) + self._prefetch_start_ray_tables() # Menu input cannot operate the simulation. Only this unstarted world # may be consumed by menu start; loads replace its world/sonar identity. self._prepared_menu_mission = ( diff --git a/src/core/game_sim.py b/src/core/game_sim.py index 1778cd29..c6e24ee2 100644 --- a/src/core/game_sim.py +++ b/src/core/game_sim.py @@ -36,6 +36,7 @@ from src.sensors import threat_cue from src.ui import unit_variants from src.sonar import equation as sonar_equation from src.sonar import propagation as sonar_propagation +from src.sonar import raytrace from src.physics import torpedo_dyn from src.physics import ship_dynamics from src.weapons import ciws as ciws_physics @@ -111,6 +112,36 @@ class SimMixin: 0.5 + 0.5 * self.damage.capability("sonar")) return 1.0 + # Mission start: ray tables of the paths the first sensor passes will + # trace, queued to be traced ahead (src/sonar/raytrace.py). + RAY_PREFETCH_START_NM = 40.0 + + def _prefetch_start_ray_tables(self) -> int: + """Queue the first ray tables of a new mission (a cache hint only).""" + from src.sonar.sonar import hull_array_depth_m + + try: + sonar = self.sonar + depths = {hull_array_depth_m(self.ship), float(sonar.towed_depth_m), + float(sonar.vds_depth_m)} + reach = self.RAY_PREFETCH_START_NM + pairs = [] + for target in self._sonar_targets(): + if math.hypot(target.x - self.ship.x, target.y - self.ship.y) <= reach: + pairs.extend((self.ship.x, self.ship.y, depth, target.x, target.y) + for depth in sorted(depths)) + listeners = [target for target in [self.ship, *self.civilians, *self.warships] + if not getattr(target, "sunk", False)] + for sub in self.subs: + if sub.sunk: + continue + pairs.extend((sub.x, sub.y, getattr(sub, "depth", 5.0), other.x, other.y) + for other in listeners + if math.hypot(other.x - sub.x, other.y - sub.y) <= reach) + return sonar_propagation.prefetch_ray_tables(self.world, pairs) + except Exception: # noqa: BLE001 - a cache hint must never stop a start + return 0 + def _sonar_targets(self) -> list: """Akustisch auffassbare Ziele: Boote, Tiere, Dekoys, Zivilverkehr, feindliche Schiffe und laufende Feindtorpedos.""" @@ -167,6 +198,8 @@ class SimMixin: self._frame_clock_reset = True self.audio.stop() self._sonar_audio_sequence = -1 + # The prepared mission's first ray tables while the menu idles. + raytrace.service(config.RAY_PREFETCH_MENU_BUDGET_S) return playing_boat = self.local_side == "uboot" # The umpire screen of a crew-versus-crew round plays nothing of either unit. @@ -226,6 +259,9 @@ class SimMixin: else: self.audio.stop() self._sonar_audio_sequence = -1 + # Ray tables the sensors will need soon, a slice per frame (never a + # result: the tables are pure functions of their keys). + raytrace.service(config.RAY_PREFETCH_FRAME_BUDGET_S) def _update_audio(self, dt: float) -> None: """Stream opt-in sonar; there is no continuous own-ship ambience.""" @@ -969,7 +1005,8 @@ class SimMixin: frequency = torpedo_dyn.RUNNING_NOISE_BAND_HZ excess = sonar_propagation.ray_excess_db( self.world, sub.x, sub.y, max(sub.depth, 1.0), torpedo.x, torpedo.y, - max(torpedo.depth, 1.0), frequency) + max(torpedo.depth, 1.0), frequency, + drift_nm=sonar_propagation.path_drift_nm(sub, torpedo)) absorption = sonar_equation.francois_garrison_db_per_km(frequency) terms = sonar_equation.passive_terms( frequency_hz=frequency, distance_nm=max(distance_nm, 0.01), diff --git a/src/core/mission_bridge.py b/src/core/mission_bridge.py index e8d37f17..bd13ebd0 100644 --- a/src/core/mission_bridge.py +++ b/src/core/mission_bridge.py @@ -11,6 +11,7 @@ import math from src.core import config, crashlog from src.core.i18n import message, raw_text +from src.sonar import raytrace from src.core.mission_definition import (_stable_seed, mission_side, reference_sector_index, static_preview, validate_mission) @@ -409,12 +410,21 @@ class MissionBridgeMixin: f"seed {self.seed}, side {self.local_side}") if not reuse: self.reset(self.seed, self.scenario_key) + self._prewarm_ray_tables() return self._clear_controls() self.audio.stop() self.msg = "" self.msg_until = 0.0 self._t = 0.0 + self._prewarm_ray_tables() + + def _prewarm_ray_tables(self) -> None: + """Finish the new mission's first ray tables with its start (the + menu began them while it idled), not in its first sensor pass. + Only the interactive game waits (``config.RAY_PREWARM_ON_START``).""" + if config.RAY_PREWARM_ON_START: + raytrace.prefetch_idle(config.RAY_PREWARM_MAX_S) def _reroll_menu_seed(self) -> None: """Choose a menu seed uniformly without repeating the current value.""" diff --git a/src/enemies/surface.py b/src/enemies/surface.py index f32150e5..aee3dc3d 100644 --- a/src/enemies/surface.py +++ b/src/enemies/surface.py @@ -333,10 +333,15 @@ class SurfaceShip(FrigateRelativeMixin): def _steer(self, dt: float, max_rate: float, world=None) -> None: # Safety owns the final steering order, after tactical/route orders. - if world is not None: + lookahead = max(1.0, self.speed / 6.0) + open_water = getattr(getattr(world, "coast", None), "open_water_near", None) + if world is not None and not ( + # Far from every coast the straight-ahead probe is certainly + # clear: the probes below would change nothing. + open_water is not None and getattr(world, "land_blocks_line", None) + is not None and open_water(self.x, self.y, lookahead)): land = getattr(world, "on_land", lambda x, y: False) blocked = getattr(world, "land_blocks_line", lambda x0, y0, x1, y1: land(x1, y1)) - lookahead = max(1.0, self.speed / 6.0) for offset in (0.0, 60.0, 120.0, 180.0): course = (self.course + self.orbit_direction * offset) % 360.0 x = self.x + lookahead * math.sin(math.radians(course)) diff --git a/src/sensors/platform.py b/src/sensors/platform.py index 2eae0ae4..0d84a09e 100644 --- a/src/sensors/platform.py +++ b/src/sensors/platform.py @@ -310,7 +310,8 @@ class PlatformSensorSuite: lambda: 1.0)()) ray = propagation.ray_excess_db( world, owner.x, owner.y, source_depth, candidate.x, - candidate.y, target_depth, frequency) + candidate.y, target_depth, frequency, + drift_nm=propagation.path_drift_nm(owner, candidate)) terms = equation.passive_terms( frequency_hz=frequency, distance_nm=distance, target_bonus=(1.0 + 0.8 * config.clamp(source_noise, 0.0, 1.0)) diff --git a/src/sonar/propagation.py b/src/sonar/propagation.py index 12f6ef86..542cdd85 100644 --- a/src/sonar/propagation.py +++ b/src/sonar/propagation.py @@ -10,6 +10,7 @@ from __future__ import annotations import math from dataclasses import dataclass from enum import Enum +from functools import lru_cache from typing import Callable from src.core import config @@ -115,15 +116,27 @@ def synthetic_sound_speed_m_s(depth_m: float, thermocline_m: float) -> float: + .012 * max(0.0, depth - thermo)) +def _speed(depth: float, thermo: float) -> float: + """``synthetic_sound_speed_m_s`` without validation, for depths and a + thermocline already validated as finite floats (identical arithmetic).""" + return 1504.0 - .018 * min(depth, thermo) + .012 * max(0.0, depth - thermo) + + def synthetic_sound_speed_profile(thermocline_m: float, water_depth_m: float) -> SoundSpeedProfile: """Sample the canonical 21-point, at-most-400 m synthetic profile.""" water_depth = _number("water_depth_m", water_depth_m, 1.0, 10_000.0) thermo = _number("thermocline_m", thermocline_m, 0.0, water_depth) + return _cached_profile(thermo, water_depth) + + +@lru_cache(maxsize=512) +def _cached_profile(thermo: float, water_depth: float) -> SoundSpeedProfile: + """Pure, bounded: the immutable profile of validated float arguments.""" maximum = min(water_depth, PROFILE_MAX_DEPTH_M) step = maximum / (PROFILE_SAMPLES - 1) depths = tuple(step * index for index in range(PROFILE_SAMPLES)) - speeds = tuple(synthetic_sound_speed_m_s(depth, thermo) for depth in depths) + speeds = tuple(_speed(depth, thermo) for depth in depths) return SoundSpeedProfile(thermo, water_depth, depths, speeds) @@ -135,10 +148,11 @@ def _segment(start: AcousticPoint, end: AcousticPoint, distance_nm = math.hypot(horizontal_nm, vertical_nm) middle_depth = (start.depth_m + end.depth_m) * .5 # Simpson integration retains profile dependence without an iterative ray solver. + thermo = profile.thermocline_m reciprocal_speed = ( - 1.0 / synthetic_sound_speed_m_s(start.depth_m, profile.thermocline_m) - + 4.0 / synthetic_sound_speed_m_s(middle_depth, profile.thermocline_m) - + 1.0 / synthetic_sound_speed_m_s(end.depth_m, profile.thermocline_m) + 1.0 / _speed(start.depth_m, thermo) + + 4.0 / _speed(middle_depth, thermo) + + 1.0 / _speed(end.depth_m, thermo) ) / 6.0 blocked = False if terrain_blocked is None else bool(terrain_blocked( start.x_nm, start.y_nm, start.depth_m, @@ -301,6 +315,18 @@ def ray_anchor_db() -> float: return _ray_anchor_db +def _sensor_depth_key(sensor_depth_m: float) -> float: + from src.sonar.raytrace import quantize + + return quantize(sensor_depth_m, 10.0 if sensor_depth_m > 30.0 else 5.0) or 5.0 + + +def _water_depth_key(depth: float) -> float: + from src.sonar.raytrace import quantize + + return quantize(depth, 25.0 if depth < 1000.0 else 100.0) or 25.0 + + def ray_environment_key(world, sensor_depth_m: float, mid_x: float, mid_y: float) -> tuple | None: """Quantized environment at the path midpoint (None without an ocean).""" @@ -310,27 +336,114 @@ def ray_environment_key(world, sensor_depth_m: float, mid_x: float, if ocean is None: return None depth = max(10.0, float(world.depth_m(mid_x, mid_y))) - return (quantize(sensor_depth_m, 10.0 if sensor_depth_m > 30.0 else 5.0) or 5.0, + return (_sensor_depth_key(sensor_depth_m), max(10.0, quantize(world.thermocline_depth_m(mid_x, mid_y), 10.0)), quantize(ocean.sea_surface_temperature_c(getattr(world, "hour", 12.0)), 1.0), - quantize(depth, 25.0 if depth < 1000.0 else 100.0) or 25.0, + _water_depth_key(depth), world.seabed_at(mid_x, mid_y), quantize(float(getattr(world, "wind_speed_kn", 10.0)), 5.0)) +# Prefetch (src/sonar/raytrace.py): a path asks ahead for the table of its +# midpoint RAY_PREFETCH_LEAD_S from now, and for the sensor depth, mixed +# layer or wind on the far side of a rounding step it has come close to. +RAY_PREFETCH_LEAD_S = 90.0 +RAY_PREFETCH_EDGE = 0.15 # fraction of a step from the rounding boundary + + +def path_drift_nm(sensor, target, lead_s: float = RAY_PREFETCH_LEAD_S) -> tuple: + """How far the midpoint of a sensor-target path moves in ``lead_s`` at + the present courses and speeds (objects without them stand still).""" + dx = dy = 0.0 + for body in (sensor, target): + speed = getattr(body, "speed", 0.0) + course = getattr(body, "course", 0.0) + if not isinstance(speed, (int, float)) or not isinstance(course, (int, float)): + continue + run = config.kn_to_nm_per_s(float(speed)) * lead_s * .5 + dx += run * math.sin(math.radians(course)) + dy -= run * math.cos(math.radians(course)) + return dx, dy + + +def _edge_neighbour(value: float, step: float) -> float | None: + """The neighbouring step's value when ``value`` lies within + ``RAY_PREFETCH_EDGE`` of a step of the boundary rounding switches at.""" + position = value / step + fraction = position - math.floor(position) + if abs(fraction - .5) > RAY_PREFETCH_EDGE: + return None + return (math.floor(position) + (1.0 if fraction < .5 else 0.0)) * step + + +def predicted_ray_keys(world, sensor_depth_m: float, mid_x: float, mid_y: float, + key: tuple, drift_nm=None) -> list: + """Keys a path will likely need next (a cache hint, never a result).""" + keys = [] + if drift_nm is not None and (drift_nm[0] or drift_nm[1]): + moved = ray_environment_key(world, sensor_depth_m, mid_x + drift_nm[0], + mid_y + drift_nm[1]) + if moved is not None and moved != key: + keys.append(moved) + sensor = _edge_neighbour(float(sensor_depth_m), + 10.0 if sensor_depth_m > 30.0 else 5.0) + if sensor is not None and (sensor or 5.0) != key[0]: + keys.append((sensor or 5.0,) + key[1:]) + thermo = _edge_neighbour(float(world.thermocline_depth_m(mid_x, mid_y)), 10.0) + if thermo is not None and max(10.0, thermo) != key[1]: + keys.append((key[0], max(10.0, thermo)) + key[2:]) + wind = _edge_neighbour(float(getattr(world, "wind_speed_kn", 10.0)), 5.0) + if wind is not None and wind != key[5]: + keys.append(key[:5] + (wind,)) + return keys + + +def _prefetch_ray_tables(world, sensor_depth_m: float, mid_x: float, mid_y: float, + key: tuple, drift_nm) -> None: + from src.sonar import raytrace + + if not raytrace.PREFETCH_ENABLED: + return + try: + keys = predicted_ray_keys(world, sensor_depth_m, mid_x, mid_y, key, drift_nm) + except Exception: # noqa: BLE001 - a cache hint must never stop the game + return + if keys: + raytrace.prefetch(keys, _profile_from_key) + + +def prefetch_ray_tables(world, pairs) -> int: + """Queue the tables of ``pairs`` = (sensor x, y, depth, target x, y) + for the background builder (mission start). Returns the keys queued.""" + from src.sonar import raytrace + + if not raytrace.PREFETCH_ENABLED: + return 0 + keys = {RAY_REFERENCE_KEY: None} + for sensor_x, sensor_y, depth, target_x, target_y in pairs: + key = ray_environment_key(world, depth, (sensor_x + target_x) * .5, + (sensor_y + target_y) * .5) + if key is not None: + keys[key] = None + return raytrace.prefetch(keys, _profile_from_key) + + def ray_excess_db(world, sensor_x: float, sensor_y: float, sensor_depth_m: float, target_x: float, target_y: float, target_depth_m: float, - frequency_hz: float) -> float | None: + frequency_hz: float, drift_nm=None) -> float | None: """Ray-traced loss beyond spherical spreading, relative to the anchor. Reciprocity: the own sensor is the ray source, the target the receiver, - so one cached table serves every target seen by that sensor.""" + so one cached table serves every target seen by that sensor. + ``drift_nm`` (see ``path_drift_nm``) only lets the table the path will + need next be prepared ahead; it never changes the result.""" from src.sonar import raytrace mid_x, mid_y = (sensor_x + target_x) * .5, (sensor_y + target_y) * .5 key = ray_environment_key(world, sensor_depth_m, mid_x, mid_y) if key is None: return None + _prefetch_ray_tables(world, sensor_depth_m, mid_x, mid_y, key, drift_nm) table = raytrace.cached_table(key, _profile_from_key) distance = math.hypot(target_x - sensor_x, target_y - sensor_y) tl = raytrace.lookup_tl_db(table, frequency_hz, distance, diff --git a/src/sonar/raytrace.py b/src/sonar/raytrace.py index a2744907..1f0e81a1 100644 --- a/src/sonar/raytrace.py +++ b/src/sonar/raytrace.py @@ -13,11 +13,24 @@ profile instead of being prescribed. Tables are pure functions of a quantized environment key and are cached in a bounded LRU; a table costs one vectorized trace (48 rays x 370 range steps) and is rebuilt only when the quantized environment changes. + +A table the simulation is about to need can be requested ahead with +``prefetch``; ``service`` (called once per frame on the game thread) hands +it to a helper process (``raytrace_worker``) on another core, or, where no +helper can run, traces it a few range steps at a time within a small +wall-time budget, and puts it into the same cache. ``cached_table`` stays +exact: a key needed right now is taken from the cache, waited for while the +helper traces it, finished at once if it is half built, or built at once. +As a table is a pure function of its key, where, when and in how many +slices it was built never changes a result; prefetching only moves the work +off the frame that needs it. """ from __future__ import annotations import math +import os +import time from collections import OrderedDict import numpy as np @@ -42,6 +55,19 @@ SHADOW_TL_DB = 200.0 _cache: "OrderedDict[tuple, np.ndarray]" = OrderedDict() build_count = 0 +# Prefetch (see the module docstring): requested keys, newest last, and the +# one table being traced in slices. +PREFETCH_QUEUE_MAX = 24 +PREFETCH_ENABLED = os.environ.get("U_JAGD_RAY_PREFETCH", "1") != "0" +WORKER_ENABLED = os.environ.get("U_JAGD_RAY_WORKER", "1") != "0" +_queued: "OrderedDict[tuple, object]" = OrderedDict() +_active: list = [] # [key, generator] while a table is in slices +_worker = None # raytrace_worker.TraceWorker once started +_worker_failed = False +# Statistics (diagnostics and tests): builds the caller had to make at once +# because nothing had prepared the key, and builds finished by ``service``. +inline_builds = 0 +prefetch_builds = 0 def _surface_loss_db(grazing_rad: np.ndarray, wind_kn: float, @@ -89,6 +115,19 @@ def _refract_step(z, direction, xi, sin_t, cos_t, step_m, speed_at): def trace_table(source_depth_m: float, profile_depths_m, profile_m_s, water_depth_m: float, sediment: str, wind_kn: float) -> np.ndarray: """Return TL[band, range_bin, depth_bin] in dB (without absorption).""" + steps = _trace_steps(source_depth_m, profile_depths_m, profile_m_s, + water_depth_m, sediment, wind_kn) + while True: + try: + next(steps) + except StopIteration as done: + return done.value + + +def _trace_steps(source_depth_m: float, profile_depths_m, profile_m_s, + water_depth_m: float, sediment: str, wind_kn: float): + """``trace_table`` as a generator: yields after every range step and + returns the table (identical arithmetic, so it can run in slices).""" global build_count build_count += 1 depths = np.asarray(profile_depths_m, dtype=float) @@ -164,30 +203,185 @@ def trace_table(source_depth_m: float, profile_depths_m, profile_m_s, ray_power = np.where(alive, flux * 10.0 ** (-losses[band_index] / 10.0), 0.0) intensity[band_index, step] = ray_power @ weights + yield step with np.errstate(divide="ignore"): table = -10.0 * np.log10(np.maximum(intensity, 10.0 ** (-SHADOW_TL_DB / 10.0))) return table +def _store(key: tuple, table: np.ndarray) -> None: + table.setflags(write=False) + _cache[key] = table + _cache.move_to_end(key) + while len(_cache) > CACHE_SIZE: + _cache.popitem(last=False) + + +def _steps_for(key: tuple, profile_builder): + depths, speeds = profile_builder(key) + return _trace_steps(key[0], depths, speeds, key[3], key[4], key[5]) + + +def _finish(steps) -> np.ndarray: + while True: + try: + next(steps) + except StopIteration as done: + return done.value + + +def _helper(): + """The running helper process, started on first use (None: slices).""" + global _worker, _worker_failed + if _worker is not None and not _worker.alive: + _collect() + _worker, _worker_failed = None, True + if _worker is None and not _worker_failed and WORKER_ENABLED: + from src.sonar.raytrace_worker import TraceWorker + + _worker = TraceWorker.start() + _worker_failed = _worker is None + if _worker is not None: + import atexit + + atexit.register(_worker.close) + return _worker + + +def _collect() -> int: + """Store the tables the helper has finished.""" + global prefetch_builds + if _worker is None: + return 0 + finished = 0 + for key, table in _worker.poll(): + if table is not None and key not in _cache: + prefetch_builds += 1 + _store(key, table) + finished += 1 + return finished + + def cached_table(key: tuple, profile_builder) -> np.ndarray: """TL table for a quantized environment ``key``. The result is a pure function of the key, so the cache only saves time: - save/load, evaluation order or an empty cache never change results. - ``key`` = (sensor depth, mixed-layer depth, SST, water depth, sediment, - wind); ``profile_builder(key)`` returns (depths, speeds).""" + save/load, evaluation order, prefetching or an empty cache never change + results. ``key`` = (sensor depth, mixed-layer depth, SST, water depth, + sediment, wind); ``profile_builder(key)`` returns (depths, speeds).""" + global inline_builds, prefetch_builds table = _cache.get(key) if table is not None: _cache.move_to_end(key) return table - depths, speeds = profile_builder(key) - table = trace_table(key[0], depths, speeds, key[3], key[4], key[5]) - _cache[key] = table - while len(_cache) > CACHE_SIZE: - _cache.popitem(last=False) + if _worker is not None and key in _worker.in_flight: + # The helper is tracing exactly this key: wait for it. + table = _worker.wait(key) + _collect() + if table is not None: + prefetch_builds += 1 + _store(key, table) + return table + if _active and _active[0] == key: + # Half built by ``service``: finish it now. + steps = _active[1] + _active.clear() + prefetch_builds += 1 + else: + _queued.pop(key, None) + steps = _steps_for(key, profile_builder) + inline_builds += 1 + table = _finish(steps) + _store(key, table) return table +def prefetch(keys, profile_builder) -> int: + """Request ``keys`` (not cached yet) for ``service`` to build ahead. + + Returns how many were newly queued. Bounded: the oldest requests give + way to newer ones. Never builds and never changes a result.""" + if not PREFETCH_ENABLED: + return 0 + queued = 0 + for key in keys: + if (key in _cache or (_active and _active[0] == key) + or (_worker is not None and key in _worker.in_flight)): + continue + if key in _queued: + _queued.move_to_end(key) + continue + _queued[key] = profile_builder + queued += 1 + while len(_queued) > PREFETCH_QUEUE_MAX: + _queued.popitem(last=False) + return queued + + +def pending_prefetch() -> int: + """Requested tables not built yet (in flight or in slices included).""" + return (len(_queued) + bool(_active) + + (len(_worker.in_flight) if _worker is not None else 0)) + + +def service(budget_s: float) -> int: + """Advance the requested tables (game thread, once per frame); returns + the tables finished. With the helper process this only collects and + submits; without it, tables are traced in range-step slices for up to + ``budget_s`` of wall time. Wall time decides only how soon a table is + ready, never what it contains.""" + global prefetch_builds + if not PREFETCH_ENABLED or not (_queued or _active or _worker is not None): + return 0 + finished = _collect() + helper = _helper() if (_queued or _active) else _worker + if helper is not None and not _active: + while _queued and len(helper.in_flight) < helper.MAX_IN_FLIGHT: + key, builder = _queued.popitem(last=True) # newest first + if key in _cache: + continue + depths, speeds = builder(key) + if not helper.submit(key, key[0], depths, speeds, key[3], key[4], key[5]): + _queued[key] = builder + break + return finished + deadline = time.perf_counter() + max(0.0, budget_s) + while True: + if not _active: + while _queued: + key, builder = _queued.popitem(last=True) # newest first + if key not in _cache: + _active[:] = [key, _steps_for(key, builder)] + break + if not _active: + return finished + key, steps = _active + try: + while time.perf_counter() < deadline: + next(steps) + return finished + except StopIteration as done: + _active.clear() + prefetch_builds += 1 + _store(key, done.value) + finished += 1 + except Exception: # noqa: BLE001 - a hint only; a caller builds it itself + _active.clear() + + +def prefetch_idle(timeout_s: float = 60.0) -> bool: + """Run ``service`` until every requested table is built (tools, tests + and a mission started without a menu).""" + deadline = time.monotonic() + timeout_s + while pending_prefetch(): + if time.monotonic() >= deadline: + return False + service(0.05) + if _worker is not None and _worker.in_flight: + time.sleep(0.002) + return True + + def lookup_tl_db(table: np.ndarray, band_hz: float, range_nm: float, receiver_depth_m: float, water_depth_m: float) -> float: """Interpolated TL (dB) for one receiver; beyond the table, cylindrical.""" @@ -209,10 +403,12 @@ def lookup_tl_db(table: np.ndarray, band_hz: float, range_nm: float, def clear_cache() -> None: - global build_count + global build_count, inline_builds, prefetch_builds + _queued.clear() + _active.clear() _cache.clear() _cz_cache.clear() - build_count = 0 + build_count = inline_builds = prefetch_builds = 0 # Convergence zones (plan 1.3, phase 7): ranges beyond CZ_SCAN_MIN_NM where diff --git a/src/sonar/raytrace_worker.py b/src/sonar/raytrace_worker.py new file mode 100644 index 00000000..48c52c80 --- /dev/null +++ b/src/sonar/raytrace_worker.py @@ -0,0 +1,228 @@ +"""Separate helper process that traces ray tables ahead of need. + +``raytrace.prefetch`` asks for tables the sensors will need soon. Python +runs one thread of the game at a time, so a thread could only take turns +with the game; this helper is its own process (``python -m +src.sonar.raytrace_worker``) on another core, at a lower scheduling +priority. It runs exactly ``raytrace.trace_table`` on the same arguments, +so its tables are the ones the game would build itself. + +Protocol over the helper's stdin/stdout: each request is a 4-byte +big-endian length and a JSON object (``id``, ``source``, ``depths``, +``speeds``, ``water``, ``sediment``, ``wind``); each answer a 4-byte length, +a JSON header (``id``, ``shape`` or ``error``) and, on success, the table's +float64 bytes. JSON writes floats exactly (shortest round-trip repr). + +Where no helper can be started (a frozen build, no ``sys.executable``, a +platform without processes) ``TraceWorker.start`` returns None and +``raytrace.service`` traces in slices on the game thread instead. +""" + +from __future__ import annotations + +import json +import os +import queue +import struct +import subprocess +import sys +import threading + +import numpy as np + +_LENGTH = struct.Struct(">I") +MAX_MESSAGE = 16 * 1024 * 1024 +WAIT_TIMEOUT_S = 60.0 + + +def _read_exact(stream, size: int) -> bytes | None: + data = bytearray() + while len(data) < size: + chunk = stream.read(size - len(data)) + if not chunk: + return None + data += chunk + return bytes(data) + + +def _read_message(stream) -> bytes | None: + head = _read_exact(stream, _LENGTH.size) + if head is None: + return None + (size,) = _LENGTH.unpack(head) + if size > MAX_MESSAGE: + return None + return _read_exact(stream, size) + + +def _write_message(stream, payload: bytes) -> None: + stream.write(_LENGTH.pack(len(payload)) + payload) + + +def serve(stdin=None, stdout=None) -> int: + """The helper's main loop: trace every request until stdin closes.""" + from src.sonar.raytrace import trace_table + + stdin = stdin or sys.stdin.buffer + stdout = stdout or sys.stdout.buffer + while True: + raw = _read_message(stdin) + if raw is None: + return 0 + try: + request = json.loads(raw) + table = np.ascontiguousarray(trace_table( + request["source"], request["depths"], request["speeds"], + request["water"], request["sediment"], request["wind"]), + dtype=np.float64) + header = {"id": request["id"], "shape": list(table.shape)} + _write_message(stdout, json.dumps(header).encode("ascii")) + _write_message(stdout, table.tobytes()) + except Exception as exc: # noqa: BLE001 - answer, never die silently + ident = request.get("id") if isinstance(request, dict) else None + _write_message(stdout, json.dumps({"id": ident, "error": type(exc).__name__}) + .encode("ascii")) + stdout.flush() + + +class TraceWorker: + """The game's side of the helper: submit, collect, wait.""" + + MAX_IN_FLIGHT = 2 + + def __init__(self, process: subprocess.Popen): + self._process = process + self._results: "queue.Queue" = queue.Queue() + self._done: dict = {} + self._next_id = 0 + self.in_flight: dict = {} # key -> request id + self.alive = True + self._reader = threading.Thread(target=self._read, name="u-jagd-raytrace-reader", + daemon=True) + self._reader.start() + + @classmethod + def start(cls) -> "TraceWorker | None": + if getattr(sys, "frozen", False) or not sys.executable: + return None + root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + env = dict(os.environ) + env["PYTHONPATH"] = root + (os.pathsep + env["PYTHONPATH"] + if env.get("PYTHONPATH") else "") + flags = {} + if os.name == "nt": + flags["creationflags"] = (getattr(subprocess, "CREATE_NO_WINDOW", 0) + | getattr(subprocess, "BELOW_NORMAL_PRIORITY_CLASS", 0)) + try: + process = subprocess.Popen( + [sys.executable, "-m", "src.sonar.raytrace_worker"], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, cwd=root, env=env, **flags) + except (OSError, ValueError): + return None + return cls(process) + + def _read(self) -> None: + stream = self._process.stdout + while True: + raw = _read_message(stream) + if raw is None: + break + try: + header = json.loads(raw) + except ValueError: + break + if "error" in header: + self._results.put((header.get("id"), None)) + continue + body = _read_message(stream) + if body is None: + break + try: + table = np.frombuffer(body, dtype=np.float64).reshape(header["shape"]) + except (ValueError, TypeError, KeyError): + break + self._results.put((header["id"], table)) + self.alive = False + self._results.put((None, None)) + + def submit(self, key: tuple, source: float, depths, speeds, water: float, + sediment: str, wind: float) -> bool: + if not self.alive or key in self.in_flight: + return False + self._next_id += 1 + request = {"id": self._next_id, "source": source, + "depths": [float(value) for value in depths], + "speeds": [float(value) for value in speeds], + "water": water, "sediment": sediment, "wind": wind} + try: + _write_message(self._process.stdin, json.dumps(request).encode("ascii")) + self._process.stdin.flush() + except (OSError, ValueError): + self.alive = False + return False + self.in_flight[key] = self._next_id + return True + + def _settle(self, ident, table) -> None: + for key, request in list(self.in_flight.items()): + if request == ident: + del self.in_flight[key] + self._done[key] = table + return + + def poll(self) -> list: + """Finished ``(key, table or None)`` pairs, without waiting.""" + while True: + try: + ident, table = self._results.get_nowait() + except queue.Empty: + break + if ident is not None: + self._settle(ident, table) + if not self.alive: + for key in list(self.in_flight): + self._done[key] = None + self.in_flight.clear() + done, self._done = list(self._done.items()), {} + return done + + def wait(self, key: tuple): + """Block until the table of ``key`` (in flight) arrives; None if the + helper failed. Other finished tables wait in ``poll``.""" + while key in self.in_flight and self.alive: + try: + ident, table = self._results.get(timeout=WAIT_TIMEOUT_S) + except queue.Empty: + self.close() + break + if ident is not None: + self._settle(ident, table) + if key in self._done: + return self._done.pop(key) + self.in_flight.pop(key, None) + return None + + def close(self) -> None: + self.alive = False + try: + self._process.stdin.close() + except OSError: + pass + try: + self._process.wait(timeout=1.0) + except subprocess.TimeoutExpired: + self._process.kill() + + +def main() -> int: + if hasattr(os, "nice"): + try: + os.nice(5) # the game keeps its core first + except OSError: + pass + return serve() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/sonar/sonar.py b/src/sonar/sonar.py index 7478c7a8..e8675646 100644 --- a/src/sonar/sonar.py +++ b/src/sonar/sonar.py @@ -685,7 +685,8 @@ class SonarSystem(ArrayHandlingMixin): * propagation.ABSORPTION_DB_PER_NM[frequency] ray = propagation.ray_excess_db( world, frigate.x, frigate.y, sensor_depth, tgt.x, tgt.y, - float(getattr(tgt, "depth", 0.0)), frequency) + float(getattr(tgt, "depth", 0.0)), frequency, + drift_nm=propagation.path_drift_nm(frigate, tgt)) if ray is not None: excess, legacy_absorption = ray, 0.0 absorption = equation.francois_garrison_db_per_km( @@ -734,7 +735,8 @@ class SonarSystem(ArrayHandlingMixin): continue ray = propagation.ray_excess_db( world, helicopter.x, helicopter.y, sensor_depth, tgt.x, tgt.y, - float(getattr(tgt, "depth", 0.0)), frequency) + float(getattr(tgt, "depth", 0.0)), frequency, + drift_nm=propagation.path_drift_nm(None, tgt)) terms = equation.passive_terms( frequency_hz=frequency, distance_nm=distance, target_bonus=target_bonus, @@ -1040,7 +1042,8 @@ class SonarSystem(ArrayHandlingMixin): frequency = representative_frequency_hz(tgt) ray = propagation.ray_excess_db( world, b.x, b.y, buoy_depth, tgt.x, tgt.y, - float(getattr(tgt, "depth", 0.0)), frequency) + float(getattr(tgt, "depth", 0.0)), frequency, + drift_nm=propagation.path_drift_nm(None, tgt)) if ray is None: ray = (6.5 if (tgt.depth > world.thermocline_depth_m(b.x, b.y)) != (buoy_depth > world.thermocline_depth_m(b.x, b.y)) diff --git a/src/world/coastline.py b/src/world/coastline.py index e40d2246..c4771beb 100644 --- a/src/world/coastline.py +++ b/src/world/coastline.py @@ -17,6 +17,12 @@ _DEFAULT_PATH = os.path.join(os.path.dirname(os.path.dirname( os.path.dirname(os.path.abspath(__file__)))), "data", "coastlines", "region.json") _OCCLUSION_CACHE_LIMIT = 1024 +# Open-water shortcut for steering probes (``Coastline.open_water_near``): +# cells of this size whose square grown by the reach (plus slack) touches no +# landmass bounding box and no sector edge. +_CLEAR_CELL_NM = 5.0 +_CLEAR_REACH_NM = 8.0 +_CLEAR_SLACK_NM = 0.01 _GEOMETRY_EPSILON = 1e-9 _MAX_SNAPSHOT_LANDMASSES = 4096 _MAX_SNAPSHOT_POINTS = 200_000 @@ -581,6 +587,50 @@ class Coastline: return True return False + def _clear_grid(self): + """Cells (``_CLEAR_CELL_NM``) whose square grown by ``_CLEAR_REACH_NM`` + touches no landmass bounding box and stays inside the sector; built + once per landmass list (pure, bounded by the sector size).""" + token = (id(self.landmasses), len(self.landmasses), self.world_size_nm) + cached = getattr(self, "_clear_cache", None) + if cached is not None and cached[0] == token: + return cached[1] + size = float(self.world_size_nm) + count = max(1, int(math.ceil(size / _CLEAR_CELL_NM))) + reach = _CLEAR_REACH_NM + _CLEAR_SLACK_NM + clear = [[True] * count for _ in range(count)] + for row in range(count): + for column in range(count): + left = column * _CLEAR_CELL_NM - reach + top = row * _CLEAR_CELL_NM - reach + right = (column + 1) * _CLEAR_CELL_NM + reach + bottom = (row + 1) * _CLEAR_CELL_NM + reach + if left < 0.0 or top < 0.0 or right > size or bottom > size: + clear[row][column] = False + for landmass in self.landmasses: + b_left, b_top, b_right, b_bottom = landmass.bounds + first_column = max(0, int((b_left - reach) // _CLEAR_CELL_NM)) + last_column = min(count - 1, int((b_right + reach) // _CLEAR_CELL_NM)) + first_row = max(0, int((b_top - reach) // _CLEAR_CELL_NM)) + last_row = min(count - 1, int((b_bottom + reach) // _CLEAR_CELL_NM)) + for row in range(first_row, last_row + 1): + for column in range(first_column, last_column + 1): + clear[row][column] = False + self._clear_cache = (token, clear) + return clear + + def open_water_near(self, x: float, y: float, reach_nm: float) -> bool: + """True only when every line from (x, y) no longer than ``reach_nm`` + is certainly clear of mapped land and inside the sector, so + ``land_blocks_line`` would answer False for it. False means "ask + ``land_blocks_line``", never "blocked". A conservative shortcut for + steering probes far from any coast.""" + if not (reach_nm <= _CLEAR_REACH_NM and 0.0 <= x < self.world_size_nm + and 0.0 <= y < self.world_size_nm): + return False + clear = self._clear_grid() + return clear[int(y // _CLEAR_CELL_NM)][int(x // _CLEAR_CELL_NM)] + def land_blocks_line(self, x1: float, y1: float, x2: float, y2: float) -> bool: """Whether mapped land blocks a radar/HFDF-style line.