Phase 3: passive and active sonar equations

Add src/sonar/equation.py and route own-ship, dipping and NPC sonars
through it, calibrated so the 1.0.0 detection ranges hold:
- Passive SE = SL - TL - NL + DI - DT per band: source level from target
  quietness, spherical spreading plus path excess and Francois-Garrison
  absorption, Wenz/Knudsen wind, shipping (nearby merchants) and rain
  noise power-summed with a hull self-noise floor and the speed/cavitation
  self noise; own wake astern masks the hull array.
- Active SE with aspect/length target strength, bottom (sediment Lambert),
  surface and volume reverberation, CW Doppler rejection growing with
  radial speed, LFM processing gain, Cramer-Rao range accuracy.
- Selectable CW/LFM pulse (W, saved); charted wrecks return unassociated
  echoes (saved pending clutter).
- NPC passive sonars hear louder targets farther and use their catalog
  receiver sensitivity.
Sea-state deviations at cavitating own speed are recorded with reasons.
Manual EN/DE and help updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
db9979andClaude Opus 5.5 committed 2026-09-23 14:56:57 +02:00
1 parent 236d23be0f
commit 4cd903a58a
20 files changed
+1000 -77

No files matched your search

+6 -1
View File
@@ -3234,5 +3234,10 @@
"help.manual.action": "Funktion",
"help.manual.hint": "Kapitel {chapter}/{chapters} | Zeilen {first}-{last}/{total} | , / . oder [ / ]: Kapitel | 0-9: Schnellstart/Stationen | Auf/Ab, BildAuf/BildAb: scrollen | Links/Rechts/Tab: Kategorie | F1/Esc: zurück",
"commander.web.guide_manual_link": "Vollständiges Handbuch öffnen (neuer Tab)",
"commander.web.workstation_manual": "Handbuchkapitel zu dieser Station"
"commander.web.workstation_manual": "Handbuchkapitel zu dieser Station",
"runtime.echo.unassociated": "Sonar: nicht zugeordnetes Echo {bearing} Grad / {range} NM (Objekt am Grund?)",
"runtime.sonar.pulse": "Aktivpuls: {pulse}",
"sonar.pulse.cw": "CW (Doppler, 1 s)",
"sonar.pulse.lfm": "LFM (100-Hz-Sweep, feine Entfernung)",
"help.control.pulse": "Aktivpuls CW / LFM"
}
+6 -1
View File
@@ -3234,5 +3234,10 @@
"help.manual.action": "Action",
"help.manual.hint": "Chapter {chapter}/{chapters} | Lines {first}-{last}/{total} | , / . or [ / ]: chapter | 0-9: quickstart/stations | Up/Down, PageUp/PageDown: scroll | Left/Right/Tab: category | F1/Esc: back",
"commander.web.guide_manual_link": "Open the full manual (new tab)",
"commander.web.workstation_manual": "Manual chapter for this station"
"commander.web.workstation_manual": "Manual chapter for this station",
"runtime.echo.unassociated": "Sonar: unassociated echo {bearing} deg / {range} NM (seabed object?)",
"runtime.sonar.pulse": "Active pulse: {pulse}",
"sonar.pulse.cw": "CW (Doppler, 1 s)",
"sonar.pulse.lfm": "LFM (100 Hz sweep, fine range)",
"help.control.pulse": "Active pulse CW / LFM"
}
+1 -1
View File
@@ -42,7 +42,7 @@ Im Remote-Crew-Browser (Commander, `F9`) werden Stationen mit Schaltflächen bed
## Unterwasserakustik in fünf Minuten {#qs-acoustics}
- **Passives Sonar liefert nur Peilung.** Jeder Kontakt beginnt als Peillinie. Entfernung liefern aktiver Ping, TMA, Sonarbojen oder Kreuzpeilung.
- **Ortung heißt Signal gegen Rauschen.** SNR = 20 log10(wirksame Reichweite / Abstand). Ab SNR >= 0 dB gilt ein Kontakt als geortet. Leise Ziele und hoher Seegang verkürzen die wirksame Reichweite.
- **Ortung heißt Signal gegen Rauschen.** Es entscheidet die passive Sonargleichung SE = SL - TL - NL + DI - DT: Quellpegel des Ziels (lauter = weiter), Übertragungsverlust (Ausbreitung, Absorption, Schicht- und Pfadverluste), Rauschen (eigenes Rauschen plus Wind, Regen und Schiffsverkehr in der Nähe) und Gewinn der Antenne. Ab SE >= 0 dB gilt ein Kontakt als geortet. Wind und Regen wirken am stärksten, wenn Sie langsam und leise fahren; bei hoher Eigenfahrt dominiert das eigene Rauschen.
- **Eigene Fahrt ist eigener Lärm.** Der Eigenlärm steigt von 4 kn bis 25 kn. Ab 15 kn kavitieren die Schrauben, die Passivreichweite fällt auf etwa ein Drittel.
- **Die Sprungschicht (Thermokline) teilt das Wasser.** Liegen Sensor und Ziel auf verschiedenen Seiten, gehen etwa 6,5 dB verloren. Ein Ping in die Schattenzone unter der Schicht erreicht nur 35 % seiner Reichweite.
- **Konvergenzzonen** bei etwa 40-70 sm und 90-130 sm bringen Schall aus großer Entfernung zurück (+8 dB).
+1 -1
View File
@@ -42,7 +42,7 @@ In the Remote Crew browser (Commander, `F9`) stations are operated with buttons;
## Underwater acoustics in five minutes {#qs-acoustics}
- **Passive sonar gives bearing only.** Every contact starts as a line of bearing. Range comes from active ping, TMA, sonobuoys or a cross-fix.
- **Detection is signal against noise.** SNR = 20 log10(effective range / distance). A contact is detected at SNR >= 0 dB. Quiet targets and high sea state shrink the effective range.
- **Detection is signal against noise.** The passive sonar equation SE = SL - TL - NL + DI - DT decides: the target's source level (louder = farther), transmission loss (spreading, absorption, layer and path losses), noise (own self noise plus wind, rain and nearby shipping), and the array gain. A contact is detected at SE >= 0 dB. Wind and rain matter most when you run slow and quiet; at high own speed your own noise dominates.
- **Own speed is own noise.** Self-noise rises from 4 kn to 25 kn. Above 15 kn the propellers cavitate and passive range drops to about a third.
- **The layer (thermocline) splits the water.** Sensor and target on different sides of the layer lose about 6.5 dB. A ping into the shadow zone below the layer reaches only 35 % of its range.
- **Convergence zones** at roughly 40-70 NM and 90-130 NM return sound from far away (+8 dB).
+1 -1
View File
@@ -63,7 +63,7 @@ Die Anzeige zeigt gemessene Modulation, keine sichere Identität. Die Analysefen
- **TMA** löst Entfernung, Kurs und Fahrt aus einer Peilungsreihe des fokussierten Kontakts. Nötig sind mindestens 4 Peilungen über 180 s und eine eigene Kursänderung von mindestens 6 Grad; die Entfernung gilt ab Qualität 0,35. Tiefe schätzt TMA nicht.
- **UMWELT / FUSION** zeigt den Bathythermographen (`E`, 60 s Abklingzeit): gemessene Schichttiefe, Schallgeschwindigkeitsprofil und Konvergenzzonen, dazu den Vergleich HMS/TAS. Peilungen innerhalb 5 Grad bestätigen sich; ab 9 Grad Abweichung wird ein möglicher Geisterkontakt markiert. Die Schicht ist nicht fest: Nachmittagssonne macht sie flacher (etwa 8 m), starker Wind mischt sie über Stunden tiefer, und interne Wellen verschieben sie um einige Meter. Den BT nach einigen Stunden oder einem Wetterwechsel wiederholen. Das gemessene Profil ist die echte temperaturabhängige Schallgeschwindigkeit (Mackenzie-Gleichung) und fällt deshalb unterhalb der Schicht ab.
- **ACTIVE** listet die Echos der letzten 120 s: Peilung, Entfernung (+/-0,18 sm) und Tiefe (+/-12 m). Ein Ping-Fix veraltet nach 120 s.
- **ACTIVE** listet die Echos der letzten 120 s: Peilung, Entfernung und Tiefe (+/-12 m). Ein Ping-Fix veraltet nach 120 s. `W` wählt den Puls: **CW** (1-s-Ton) misst die Entfernung grob (etwa 0,1-0,3 sm), trennt aber über den Doppler ein bewegtes Ziel vom Nachhall des Meeresbodens; **LFM** (100-Hz-Sweep) misst die Entfernung auf wenige Meter und gewinnt 20 dB gegen Rauschen, ein langsames oder stehendes Ziel bleibt aber im Nachhall. Die Echostärke hängt vom Aspekt (breitseits etwa 15 dB stärker als von vorn) und der Größe des Ziels ab. Felsgrund hallt viel stärker nach als Schlick; kartierte Wracks liefern echte Echos ohne zugehörigen Kontakt ("nicht zugeordnetes Echo").
## Bugsonar und Schleppsonar {#sonar-arrays}
+1 -1
View File
@@ -62,7 +62,7 @@ The display shows measured modulation, not certain identity. The analysis window
- **TMA** solves range, course and speed from a bearing series of the focused contact. It needs at least 4 bearings over 180 s and an own course change of at least 6 degrees; range is trusted from quality 0.35. It does not estimate depth.
- **UMWELT / FUSION** shows the bathythermograph (`E`, 60 s cooldown): measured layer depth, sound-speed profile and convergence-zone bands, plus the HMS/TAS comparison. Bearings within 5 degrees confirm each other; 9 degrees or more apart are flagged as a possible ghost contact. The layer is not fixed: afternoon sun makes it shallower (about 8 m), strong wind mixes it deeper over hours, and internal waves move it a few metres. Repeat the BT after a few hours or a weather change. The measured profile is the real temperature-driven sound speed (Mackenzie equation), so it drops below the layer.
- **ACTIVE** lists echoes of the last 120 s: bearing, range (+/-0.18 NM) and depth (+/-12 m). A ping fix ages out after 120 s.
- **ACTIVE** lists echoes of the last 120 s: bearing, range and depth (+/-12 m). A ping fix ages out after 120 s. `W` selects the pulse: **CW** (1 s tone) gives coarse range (about 0.1-0.3 NM) but its Doppler separates a moving target from seabed reverberation; **LFM** (100 Hz sweep) measures range to a few metres and gains 20 dB against noise, but a slow or stationary target stays inside the reverberation. The echo strength depends on the target's aspect (broadside about 15 dB stronger than bow-on) and size. Rocky ground reverberates far more than mud; charted wrecks return real echoes that no contact owns ("unassociated echo").
## Hull sonar versus towed array {#sonar-arrays}
+1 -1
View File
@@ -18,7 +18,7 @@ Alle Werte sind die Standardwerte der aktuellen Spielversion. Eigene Schwierigke
| Sensor | Reichweite | Genauigkeit / Hinweis |
|---|---|---|
| Passivsonar (Basis) | 20 sm | nur Peilung; HMS +/-6 Grad, TAS +/-2 Grad |
| Aktiver Ping | 18 sm | Entfernung +/-0,18 sm, Tiefe +/-12 m; 30 s Abklingzeit; hörbar bis 60 sm |
| Aktiver Ping | 18 sm (Referenzziel, schräger Aspekt) | CW oder LFM (`W`); Entfernungsgenauigkeit aus Puls und SNR, Tiefe +/-12 m; 30 s Abklingzeit; hörbar bis 60 sm |
| Tauchsonar | 18 sm passiv / 14 sm aktiv | +/-2 Grad |
| Sonarboje | 8 sm | 60 min Batterie |
| Überwasserradar | 30 sm | Radarhorizont; keine getauchten Kontakte |
+1 -1
View File
@@ -18,7 +18,7 @@ All values are the defaults of the current game version. Custom difficulty and m
| Sensor | Range | Accuracy / note |
|---|---|---|
| Passive sonar (base) | 20 NM | bearing only; HMS +/-6 deg, TAS +/-2 deg |
| Active ping | 18 NM | range +/-0.18 NM, depth +/-12 m; 30 s cooldown; heard to 60 NM |
| Active ping | 18 NM (reference target, broadside-quarter aspect) | CW or LFM (`W`); range accuracy from pulse and SNR, depth +/-12 m; 30 s cooldown; heard to 60 NM |
| Dipping sonar | 18 NM passive / 14 NM active | +/-2 deg |
| Sonobuoy | 8 NM | 60 min battery |
| Surface radar | 30 NM | radar horizon; no submerged contacts |
+6 -6
View File
@@ -263,15 +263,15 @@ Scope: Ship dynamics, weapons, enemy AI, air, sonar/sensors, world/environment.
| Gap | Current behaviour | Would need |
|-----|-------------------|------------|
| **No full sonar equation** | Detection threshold is SNR ≥ 0 dB against a pre-computed R_eff; no separate source level, transmission loss, noise, detection threshold terms | `SL - TL + DI - NL - DT` with per-frequency terms; target strength (TS) from aspect and frequency |
| **No source-level model** | Target "quiet" factor is a 0-1 scalar from catalog; no frequency-dependent source level | Per-band source level (line noise, broadband, cavitation) as dB re 1 µPa @ 1 m |
| **No receiver noise model** | Own-ship noise is a single level; sea state adds a flat penalty | Ambient noise spectrum (wind, rain, shipping, biological); receiver self-noise; array noise floor |
| **No target strength (TS)** | No frequency-dependent reflection; active ping range is fixed × thermocline factor | TS as function of frequency, aspect, target size; bubble-cloud effects |
| ~~**No full sonar equation**~~ | **Closed (Phase 3).** `src/sonar/equation.py`: passive SE = SL - TL - NL + DI - DT per band; active SE = SL - 2TL + TS - max(NL - PG, RL - Doppler rejection). Calibrated so 1.0.0 detection ranges hold (`tools/calibrate.py`). Own sonar, dipping sonar and NPC platform sonars use it. | — |
| ~~**No source-level model**~~ | **Closed (Phase 3; speed/cavitation terms Phase 6).** Source level in dB from the catalog quietness; NPC passive sonars hear loud targets farther (up to +5 dB). | — |
| ~~**No receiver noise model**~~ | **Closed (Phase 3).** Wenz/Knudsen wind noise (flat below 500 Hz), distant shipping from nearby merchant count, heavy-rain noise, thermal floor, hull-array self-noise floor plus speed/cavitation self noise, own wake astern; NPC receiver sensitivity from the catalog. | — |
| ~~**No target strength (TS)**~~ | **Closed (Phase 3).** Aspect- and length-dependent target strength (beam highlight ~20 log(L/10)+8 dB, bow/stern 15 dB lower). | — |
| **Propagation: fixed 4 paths** | Direct, refracted (thermocline midpoint), surface, bottom — no full ray tracing | Multi-path with reflection/refraction at boundaries; mode propagation; no normal-mode solution needed but more rays |
| **Propagation: no frequency dependence in path loss** | Absorption is per-band constant; path geometry is frequency-independent | Frequency-dependent ray paths (higher freq → less refracted); dispersion |
| **No Doppler** | Bearing measurements have no Doppler shift information | Doppler = f₀ · (v·r̂)/c; useful for speed estimation and classification |
| **No interference / clutter** | Only terrain blocking; no seafloor reverberation, surface clutter, multipath interference | Reverberation level from bottom type; surface clutter in active sonar; scintillation |
| **Ping: no pulse parameters** | Ping is instantaneous with fixed error; no pulse width, bandwidth, or processing gain | Ping duration → range resolution; bandwidth → frequency content; matched-filter gain |
| ~~**No interference / clutter**~~ | **Closed (Phase 3).** Boundary (Lambert bottom by sediment, wind-dependent surface) and volume reverberation with absorption; CW Doppler rejection grows with radial speed; charted wrecks return unassociated echoes (saved pending clutter). | — |
| ~~**Ping: no pulse parameters**~~ | **Closed (Phase 3).** Selectable CW (1 s) / LFM (1 s, 100 Hz) pulse (`W`, saved): resolution c*tau/2 or c/2B, Cramer-Rao range accuracy, LFM processing gain against noise, CW Doppler against reverberation. | — |
| **TMA: fixed grid** | 24 × 10 = 240 candidates + 9 local; no adaptive grid | Coarse-to-fine search; Gauss-Newton refinement; covariance tracking |
| **No multi-static sonar** | Each platform has independent sensors; no multi-static TDOA/BIARRING fusion | Datalink fusion of passive bearings from multiple platforms (already partially in `PlatformSensorSuite` but not exploited for TMA) |
| **No sonar array beampforming** | Bearing is a scalar with Gaussian-like error; no beam pattern, no side lobes, no spatial sampling | Array geometry → beam pattern; grating lobes; adaptive beamforming |
+41
View File
@@ -36,6 +36,7 @@ from src.core.mission_definition import static_preview, validate_mission
from src.core.station import Station
from src.core.version import SAVE_SCHEMA, SAVE_VERSION
from src.sensors.ais import AISReceiver
from src.sonar import equation as sonar_equation
from src.physics import ship_dynamics
from src.world.ocean import OceanEnvironment
from src.core.save_schema import (
@@ -2381,6 +2382,11 @@ class Game:
Station.SONAR,
self.sonar_page, 1 if e.key == pygame.K_PAGEDOWN else -1)
return
if e.key == pygame.K_w:
pulse = self.sonar.cycle_pulse()
self.flash(message("runtime.sonar.pulse",
pulse=message(f"sonar.pulse.{pulse.lower()}")))
return
if e.key == pygame.K_e:
if self.measure_sonar_bt() is True:
depth = self.sonar.bt_profile["thermocline_m"]
@@ -5801,6 +5807,11 @@ class Game:
self.feed.add(self.world.format_time(), "navigation",
message("runtime.grounding.feed", kind=notice))
def _shipping_noise_contacts(self) -> int:
"""Merchant traffic within 50 NM that feeds distant-shipping noise."""
return sum(1 for ship in self.civilians
if not ship.sunk and ship.distance_nm(self.ship) <= 50.0)
def _update_platform_sensors(self, dt: float) -> None:
"""Run independent NPC sensors before any actor makes a decision."""
ship_target = SimpleNamespace(
@@ -6286,6 +6297,7 @@ class Game:
return
focus = (self._find_target(self.selected_contact.target_id)
if self.selected_contact else None)
self.sonar.shipping_contacts = self._shipping_noise_contacts()
self.sonar.update(dt, self.sim_t, self.ship, targets, self.world,
range_factor=self._sonar_range_factor(),
mode=self.sonar_mode, buoys=self.buoys,
@@ -6327,6 +6339,12 @@ class Game:
bearing_uncertainty_deg=contact.bearing_uncertainty_deg)
while self.sonar.echo_events:
echo = self.sonar.echo_events.pop(0)
if echo["contact_id"] == 0:
self.feed.add(self.world.format_time(), "sonar",
message("runtime.echo.unassociated",
bearing=f"{echo['bearing']:05.1f}",
range=f"{echo['range_nm']:.1f}"))
continue
self.feed.add(self.world.format_time(), "sonar",
message("runtime.echo.feed", contact=echo["contact_id"],
bearing=f"{echo['bearing']:05.1f}",
@@ -6940,6 +6958,10 @@ class Game:
"echo_history": list(self.sonar.echo_history),
"bt_profile": self.sonar.bt_profile,
"bt_cooldown": self.sonar.bt_cooldown,
"ping_pulse": self.sonar.ping_pulse,
"pending_clutter": [dict(ready_at=item["ready_at"], mode=item["mode"],
snapshot=dict(item["snapshot"]))
for item in self.sonar._pending_clutter],
},
"sim_t": self.sim_t,
"time_scale_idx": config.TIME_SCALE_DEFAULT,
@@ -7673,6 +7695,11 @@ class Game:
for target_id, next_t in sn.get("tma_next", {}).items()
if int(target_id) in self.sonar._tracks
}
self.sonar.ping_pulse = sn["ping_pulse"]
self.sonar._pending_clutter = [
dict(ready_at=item["ready_at"], mode=item["mode"],
snapshot=dict(item["snapshot"]))
for item in sn["pending_clutter"]]
for pd in sn.get("pending_pings", []):
target = by_id.get(pd.get("target_id"))
if target is not None:
@@ -9184,6 +9211,20 @@ class Game:
and contact["bearing_filter_t"] > sim_t
for contact in contacts.values())):
return False
if sonar.get("ping_pulse") not in sonar_equation.PULSES:
return False
clutter = sonar.get("pending_clutter")
if (not isinstance(clutter, list)
or len(clutter) > SonarSystem.MAX_PENDING_CLUTTER
or any(not isinstance(item, dict)
or set(item) != {"ready_at", "mode", "snapshot"}
or item["mode"] not in ("BOW", "TOWED", "DIPPING")
or not SonarSystem.valid_ping_snapshot(item["snapshot"])
or not bounded(item["ready_at"], 0, 1e12)
or not item["snapshot"]["t"] <= sim_t
or not 0 <= item["ready_at"] - item["snapshot"]["t"] <= 25000
for item in clutter)):
return False
pending_pings = sonar.get("pending_pings", [])
# 25000 s covers two-way propagation across the 10000 NM snapshot bound.
if len(pending_pings) > SonarSystem.MAX_PENDING_PINGS or any(not isinstance(item, dict)
+1
View File
@@ -50,6 +50,7 @@ STATION_HELP = {
[("Shift+A", "help.control.active_ping"), ("Shift+B", "help.control.array"),
("Y", "help.control.tas"), ("help.key.page_spaced", "help.control.pages"),
("2", "help.control.repeat_sonar_page"), ("E", "help.control.bt"),
("W", "help.control.pulse"),
("U / V", "help.control.tas_depth"), ("R", "help.control.listen_input"),
("<- / ->", "help.control.bearing_step"), ("help.key.up_down", "help.control.contact_select"),
("Enter", "help.control.track_bearing"), ("J | , / .", "help.control.audio"),
+56 -11
View File
@@ -8,7 +8,7 @@ import random
from dataclasses import asdict, dataclass
from src.core import config
from src.sonar import propagation
from src.sonar import equation, propagation
SIDES = ("friendly", "neutral", "hostile")
@@ -240,7 +240,11 @@ class PlatformSensorSuite:
if rcs is not None:
availability *= config.clamp((rcs / 500.0) ** 0.25, 0.5, 1.5)
maximum = (profile.synthetic_range_nm or 0.0) * availability
if maximum <= 0.0 or distance > maximum:
# A passive sonar hears a loud target beyond its reference range
# (source level up to +5 dB); the sonar equation decides below.
reach = maximum * (1.8 if profile.domain == "sonar"
and "active" not in profile.modes else 1.0)
if maximum <= 0.0 or distance > reach:
return
if getattr(world, "land_blocks_line", lambda *args: False)(
owner.x, owner.y, candidate.x, candidate.y):
@@ -267,22 +271,58 @@ class PlatformSensorSuite:
thermo = (float(thermo_at(mx, my)) if thermo_at is not None
else min(100.0, water_depth))
water_depth = max(water_depth, thermo)
frequency = propagation.representative_frequency_hz(
_candidate_acoustic_signature(candidate))
sea_state = float(getattr(world, "effective_sea_state",
getattr(world, "sea_state", 0)))
result = propagation.propagate(
owner.x, owner.y, source_depth,
candidate.x, candidate.y, target_depth,
propagation.representative_frequency_hz(
_candidate_acoustic_signature(candidate)),
thermo, water_depth, sea_state=getattr(
world, "effective_sea_state", getattr(world, "sea_state", 0)),
candidate.x, candidate.y, target_depth, frequency,
thermo, water_depth, sea_state=sea_state,
terrain_blocked=getattr(world, "sonar_path_blocked", None))
maximum *= propagation.passive_range_factor(result, distance)
if maximum <= 0.0 or distance > maximum:
if result.best_path is None:
return
source_noise = (candidate.noise_level()
if hasattr(candidate, "noise_level") else
1.0 - getattr(candidate, "quiet_factor", lambda: 0.0)())
received_signal = max(0.0, source_noise) * max(
0.0, 1.0 - distance / maximum)
if "passive" in profile.modes and not active_sonar:
# Passive sonar equation: the catalog synthetic range is the
# figure of merit against a silent reference target; a
# louder target raises source level, the platform's own
# radiated noise raises its self noise.
owner_noise = (owner.noise_level() if hasattr(owner, "noise_level")
else 1.0 - getattr(owner, "quiet_factor",
lambda: 1.0)())
terms = equation.passive_terms(
frequency_hz=frequency, distance_nm=distance,
target_bonus=1.0 + 0.8 * config.clamp(source_noise, 0.0, 1.0),
excess_path_loss_db=(result.best_path.loss_db
- 20.0 * math.log10(1.0 + distance)),
absorption_db_per_km=equation.francois_garrison_db_per_km(
frequency, 10.0, min(water_depth, 200.0)),
legacy_absorption_db=result.best_path.distance_nm
* propagation.ABSORPTION_DB_PER_NM[frequency],
# The catalog range already includes self noise at a
# typical operating level; only louder operation deafens.
own_range_factor=min(1.0, (1.0 - 0.8 * config.clamp(
owner_noise, 0.0, 1.0)) / (1.0 - 0.8 * NPC_REFERENCE_NOISE)),
array_range_factor=maximum / config.SONAR_PASSIVE_BASE_NM,
sea_state=sea_state,
rain=float(getattr(world, "rain_intensity", 0.0)),
shipping_contacts=equation.REFERENCE_SHIPPING_CONTACTS,
# Receiver sensitivity relative to the catalog reference
# (-100 dB): a more sensitive receiver gains directivity.
sensitivity_db=config.clamp(
NPC_REFERENCE_SENSITIVITY_DB - profile.sensitivity_db,
-12.0, 12.0) if profile.sensitivity_db is not None else 0.0)
excess = terms.signal_excess_db
if excess <= 0.0:
return
received_signal = config.clamp(
excess / config.SONAR_SNR_QUALITY_SPAN_DB, 0.0, 2.0)
else:
received_signal = max(0.0, source_noise) * max(
0.0, 1.0 - distance / maximum)
if received_signal <= 0.01:
return
token = _candidate_token(candidate)
@@ -426,6 +466,11 @@ def side_datalink_group(side: str) -> str | None:
return {"friendly": "blue", "hostile": "red"}.get(side)
# Own radiated-noise level at which catalog passive ranges were tuned.
NPC_REFERENCE_NOISE = 0.8
NPC_REFERENCE_SENSITIVITY_DB = -100.0
def motion_limits(catalog, profile_key: str, *, cruise_speed: float,
maximum_speed: float, turn_rate: float,
acceleration: float, depth_rate: float = 0.5) -> MotionLimits:
+390
View File
@@ -0,0 +1,390 @@
"""Passive and active sonar equations in dB (per canonical band).
Passive: SE = SL - TL - NL + DI - DT
Active: SE = SL_a - 2 TL + TS - max(NL - DI, RL) - DT + PG
The terms are physical in shape (spherical spreading, Francois-Garrison
absorption, Wenz/Knudsen ambient noise, power-summed self noise, aspect
dependent target strength, bottom/surface/volume reverberation, pulse
processing gain). The reference constants are calibrated so that at the
1.0.0 reference conditions the signal excess reproduces the historical
detection ranges (see ``tools/calibrate.py``).
Everything here is a pure function; nothing owns state.
"""
from __future__ import annotations
import math
from dataclasses import dataclass
from src.core import config
BANDS_HZ = (100.0, 400.0, 1600.0, 6400.0)
NM_M = 1852.0
# --- calibration anchors -------------------------------------------------------
# Passive figure of merit: SE = 0 at the 1.0.0 base range (20 NM) for the
# reference target (quiet 1.0 -> target bonus 1) with no own-noise excess, sea
# state 1, reference ambient, bow array, direct path.
PASSIVE_REFERENCE_RANGE_NM = config.SONAR_PASSIVE_BASE_NM
# Active figure of merit: SE = 0 at SONAR_ACTIVE_BASE_NM for the reference
# target strength, sea state 0, bow array, noise limited.
ACTIVE_REFERENCE_RANGE_NM = config.SONAR_ACTIVE_BASE_NM
REFERENCE_SEA_STATE = 1.0
REFERENCE_SHIPPING_CONTACTS = 4
# Reference echo: a 70 m hull at 45 degrees aspect.
REFERENCE_TARGET_LENGTH_M = 70.0
REFERENCE_ASPECT_DEG = 45.0
# CW Doppler processing separates an echo from stationary reverberation once
# the target's radial speed exceeds this.
CW_DOPPLER_MIN_KN = 2.0
CW_DOPPLER_REJECTION_DB = 10.0
# --- ambient noise (spectrum level dB re 1 uPa^2/Hz) -------------------------------
# Knudsen wind noise at 1 kHz by sea state, falling 17 dB/decade.
KNUDSEN_1KHZ_DB = (44.5, 50.0, 55.0, 58.5, 61.5, 63.5, 65.5)
KNUDSEN_SLOPE_DB_PER_DECADE = -17.0
# Distant shipping peaks near 100 Hz and falls 20 dB/decade above.
SHIPPING_100HZ_DB = 60.0
SHIPPING_SLOPE_DB_PER_DECADE = -20.0
# Heavy rain adds a nearly flat 1-10 kHz spectrum.
RAIN_HEAVY_DB = 62.0
WIND_FLAT_BELOW_HZ = 500.0
# Hull-array self-noise floor (flow and machinery noise reaching the dome
# even at low speed); falls with frequency.
SELF_NOISE_FLOOR_100HZ_DB = 68.0
SELF_NOISE_FLOOR_SLOPE_DB_PER_DECADE = -12.0
THERMAL_NOISE_DB_AT_6K4 = 20.0
# --- pulses -------------------------------------------------------------------
PULSES = {
# key: (duration s, bandwidth Hz)
"CW": (1.0, 1.0),
"LFM": (1.0, 100.0),
}
DEFAULT_PULSE = "CW"
# Scattering strengths (dB): Lambert bottom mu per sediment is in ocean.py;
# surface scattering from wind (Chapman-Harris-like), volume column.
VOLUME_SCATTERING_DB = -80.0
def _db_sum(*levels: float) -> float:
"""Incoherent power sum of dB levels."""
return 10.0 * math.log10(sum(10.0 ** (level / 10.0) for level in levels))
def francois_garrison_db_per_km(frequency_hz: float, temperature_c: float = 10.0,
depth_m: float = 100.0, salinity: float = 35.0,
ph: float = 8.0) -> float:
"""Francois-Garrison (1982) sea-water absorption (dB/km)."""
f = frequency_hz / 1000.0
t = temperature_c
c = 1412.0 + 3.21 * t + 1.19 * salinity + 0.0167 * depth_m
# Boric acid
a1 = 8.86 / c * 10.0 ** (0.78 * ph - 5.0)
p1 = 1.0
f1 = 2.8 * math.sqrt(salinity / 35.0) * 10.0 ** (4.0 - 1245.0 / (273.0 + t))
# Magnesium sulphate
a2 = 21.44 * salinity / c * (1.0 + 0.025 * t)
p2 = 1.0 - 1.37e-4 * depth_m + 6.2e-9 * depth_m ** 2
f2 = 8.17 * 10.0 ** (8.0 - 1990.0 / (273.0 + t)) / (1.0 + 0.0018 * (salinity - 35.0))
# Pure water
if t <= 20.0:
a3 = (4.937e-4 - 2.59e-5 * t + 9.11e-7 * t * t - 1.5e-8 * t ** 3)
else:
a3 = (3.964e-4 - 1.146e-5 * t + 1.45e-7 * t * t - 6.5e-10 * t ** 3)
p3 = 1.0 - 3.83e-5 * depth_m + 4.9e-10 * depth_m ** 2
return (a1 * p1 * f1 * f * f / (f1 * f1 + f * f)
+ a2 * p2 * f2 * f * f / (f2 * f2 + f * f)
+ a3 * p3 * f * f)
def spreading_loss_db(distance_nm: float) -> float:
"""Spherical spreading 20 log10(r) with r in metres (>= 1 m)."""
return 20.0 * math.log10(max(1.0, distance_nm * NM_M))
def ambient_noise_db(frequency_hz: float, sea_state: float, rain: float = 0.0,
shipping_contacts: int = REFERENCE_SHIPPING_CONTACTS) -> float:
"""Wenz-style ambient spectrum level: wind + shipping + rain + thermal."""
index = max(0.0, min(6.0, sea_state))
low = int(index)
high = min(6, low + 1)
wind_1k = (KNUDSEN_1KHZ_DB[low]
+ (KNUDSEN_1KHZ_DB[high] - KNUDSEN_1KHZ_DB[low]) * (index - low))
# Wenz: wind noise is roughly flat below ~500 Hz.
decades = math.log10(max(frequency_hz, WIND_FLAT_BELOW_HZ) / 1000.0)
wind = wind_1k + KNUDSEN_SLOPE_DB_PER_DECADE * decades
traffic = max(0, shipping_contacts)
shipping = (SHIPPING_100HZ_DB
+ 10.0 * math.log10((1.0 + traffic) / (1.0 + REFERENCE_SHIPPING_CONTACTS))
+ SHIPPING_SLOPE_DB_PER_DECADE * max(0.0, math.log10(frequency_hz / 100.0)))
levels = [wind, shipping,
THERMAL_NOISE_DB_AT_6K4 + 20.0 * math.log10(frequency_hz / 6400.0)]
if rain > 0.0 and frequency_hz >= 500.0:
levels.append(RAIN_HEAVY_DB + 10.0 * math.log10(max(rain, 1e-3)))
return _db_sum(*levels)
def self_noise_floor_db(frequency_hz: float) -> float:
return (SELF_NOISE_FLOOR_100HZ_DB + SELF_NOISE_FLOOR_SLOPE_DB_PER_DECADE
* math.log10(frequency_hz / 100.0))
def reference_noise_db(frequency_hz: float) -> float:
"""Reference ambient at sea state 1 power-summed with the self floor."""
return _db_sum(ambient_noise_db(frequency_hz, REFERENCE_SEA_STATE),
self_noise_floor_db(frequency_hz))
def self_noise_db(frequency_hz: float, legacy_range_factor: float) -> float:
"""Speed-dependent own-ship self noise above the floor.
The 1.0.0 model multiplied range by ``legacy_range_factor`` (own noise,
cavitation, directional lobe). With power summation over the reference
noise, a penalty of L dB needs an extra level
``N_ref + 10 log10(10^(L/10) - 1)``; it is then a real spectrum level
that adds to whatever the ambient actually is.
"""
floor = self_noise_floor_db(frequency_hz)
loss = -20.0 * math.log10(max(1e-4, min(1.0, legacy_range_factor)))
if loss <= 1e-6:
return floor
extra = reference_noise_db(frequency_hz) + 10.0 * math.log10(
10.0 ** (loss / 10.0) - 1.0)
return _db_sum(floor, extra)
@dataclass(frozen=True, slots=True)
class PassiveTerms:
frequency_hz: float
source_level_db: float
transmission_loss_db: float
noise_level_db: float
directivity_db: float
threshold_db: float
@property
def signal_excess_db(self) -> float:
return (self.source_level_db - self.transmission_loss_db
- self.noise_level_db + self.directivity_db - self.threshold_db)
def passive_figure_of_merit_offset(frequency_hz: float) -> float:
"""SL_ref + DI_ref - DT_ref so that SE = 0 at the reference range."""
return spreading_loss_db(PASSIVE_REFERENCE_RANGE_NM) + reference_noise_db(
frequency_hz)
def passive_terms(*, frequency_hz: float, distance_nm: float,
target_bonus: float, excess_path_loss_db: float,
absorption_db_per_km: float, legacy_absorption_db: float,
own_range_factor: float, array_range_factor: float,
sea_state: float, rain: float, shipping_contacts: int,
sensitivity_db: float = 0.0,
hull_self_noise: bool = True) -> PassiveTerms:
"""Assemble the passive sonar equation for one band.
``target_bonus`` is the 1.0.0 source-level multiplier (louder target),
expressed here as +20 log10 dB of source level; the array factor becomes
directivity; path excess (layer, surface/bottom/refraction) and the
Francois-Garrison absorption replace the legacy fixed absorption.
"""
anchor = passive_figure_of_merit_offset(frequency_hz)
source = anchor + 20.0 * math.log10(max(target_bonus, 1e-6))
absorption = absorption_db_per_km * distance_nm * NM_M / 1000.0
transmission = (spreading_loss_db(distance_nm) + max(
0.0, excess_path_loss_db - legacy_absorption_db) + absorption)
ambient = ambient_noise_db(frequency_hz, sea_state, rain, shipping_contacts)
directivity = 20.0 * math.log10(max(array_range_factor, 1e-6)) + sensitivity_db
if hull_self_noise:
noise = _db_sum(ambient, self_noise_db(frequency_hz, own_range_factor))
else:
# Off-board sensors (dipping sonar, sonobuoys) are ambient limited;
# their smaller aperture is the directivity difference to the hull
# array at the reference noise.
noise = ambient
directivity -= reference_noise_db(frequency_hz) - ambient_noise_db(
frequency_hz, REFERENCE_SEA_STATE)
return PassiveTerms(frequency_hz, source, transmission, noise, directivity,
0.0)
# --- active ---------------------------------------------------------------------
def target_strength_db(length_m: float, aspect_deg: float) -> float:
"""Aspect-dependent echo strength of an elongated hull.
Beam aspect returns a specular highlight ~20 log10(L/10) + 8 dB; bow and
stern aspects are about 15 dB weaker.
"""
beam = 20.0 * math.log10(max(length_m, 5.0) / 10.0) + 8.0
weight = abs(math.sin(math.radians(aspect_deg))) ** 2
return beam - 15.0 * (1.0 - weight)
def surface_scattering_db(wind_kn: float, grazing_deg: float) -> float:
"""Chapman-Harris-like surface backscatter (dB), rising with wind."""
grazing = max(0.5, min(89.0, grazing_deg))
return -60.0 + 0.9 * min(40.0, wind_kn) + 10.0 * math.log10(
math.sin(math.radians(grazing)))
def bottom_scattering_db(lambert_mu_db: float, grazing_deg: float) -> float:
"""Lambert's law: mu + 10 log10(sin^2 theta)."""
grazing = max(0.5, min(89.0, grazing_deg))
return lambert_mu_db + 20.0 * math.log10(math.sin(math.radians(grazing)))
def reverberation_level_db(*, source_level_db: float, distance_nm: float,
pulse: str, beamwidth_deg: float,
water_depth_m: float, lambert_mu_db: float,
wind_kn: float) -> float:
"""Boundary + volume reverberation at the target range."""
tau, _bandwidth = PULSES[pulse]
r = max(1.0, distance_nm * NM_M)
# Ensonified boundary patch: range extent c*tau/2 times cross-range r*theta.
area = (config.SOUND_SPEED_M_S * tau * 0.5) * r * math.radians(beamwidth_deg)
grazing = math.degrees(math.atan2(max(1.0, water_depth_m), r))
two_way = 2.0 * spreading_loss_db(distance_nm)
bottom = (source_level_db - two_way + bottom_scattering_db(lambert_mu_db, grazing)
+ 10.0 * math.log10(area))
surface = (source_level_db - two_way + surface_scattering_db(wind_kn, grazing)
+ 10.0 * math.log10(area))
volume = (source_level_db - two_way + VOLUME_SCATTERING_DB
+ 10.0 * math.log10(area * max(1.0, min(water_depth_m, 500.0))))
return _db_sum(bottom, surface, volume)
@dataclass(frozen=True, slots=True)
class ActiveTerms:
source_level_db: float
two_way_loss_db: float
target_strength_db: float
noise_db: float
reverberation_db: float
processing_gain_db: float
reverberation_rejection_db: float = 0.0
@property
def signal_excess_db(self) -> float:
interference = max(self.noise_db - self.processing_gain_db,
self.reverberation_db - self.reverberation_rejection_db)
return (self.source_level_db - self.two_way_loss_db
+ self.target_strength_db - interference)
@property
def reverberation_limited(self) -> bool:
return (self.reverberation_db - self.reverberation_rejection_db
> self.noise_db - self.processing_gain_db)
ACTIVE_FREQUENCY_HZ = 3500.0 # medium-frequency hull sonar
ACTIVE_BEAMWIDTH_DEG = 12.0
def active_noise_db(sea_state: float, rain: float = 0.0) -> float:
return _db_sum(ambient_noise_db(ACTIVE_FREQUENCY_HZ, sea_state, rain),
self_noise_floor_db(ACTIVE_FREQUENCY_HZ))
def reference_target_strength_db() -> float:
return target_strength_db(REFERENCE_TARGET_LENGTH_M, REFERENCE_ASPECT_DEG)
REFERENCE_WATER_TEMPERATURE_C = 10.0
def _two_way_absorption_db(distance_nm: float, absorption_db_per_km: float) -> float:
return 2.0 * absorption_db_per_km * distance_nm * NM_M / 1000.0
def _active_budget_db(distance_nm: float) -> float:
absorption = francois_garrison_db_per_km(ACTIVE_FREQUENCY_HZ,
REFERENCE_WATER_TEMPERATURE_C)
return (2.0 * spreading_loss_db(distance_nm)
+ _two_way_absorption_db(distance_nm, absorption))
def active_range_factor_db(factor: float) -> float:
"""Two-way loss (dB) that scales the reference active range by ``factor``
on the real spreading+absorption curve (negative for factor > 1)."""
factor = max(factor, 1e-6)
return (_active_budget_db(ACTIVE_REFERENCE_RANGE_NM)
- _active_budget_db(ACTIVE_REFERENCE_RANGE_NM * factor))
def active_source_level_db() -> float:
"""Transmit level such that SE = 0 at the reference range, sea state 0,
reference target strength, reference water temperature, noise limited."""
absorption = francois_garrison_db_per_km(ACTIVE_FREQUENCY_HZ,
REFERENCE_WATER_TEMPERATURE_C)
return (2.0 * spreading_loss_db(ACTIVE_REFERENCE_RANGE_NM)
+ _two_way_absorption_db(ACTIVE_REFERENCE_RANGE_NM, absorption)
- reference_target_strength_db() + active_noise_db(0.0))
def cw_doppler_rejection_db(radial_speed_kn: float) -> float:
"""Reverberation suppression of a CW pulse for a moving echo.
Stationary scatterers stay near zero Doppler; an echo shifted by a few
knots of radial speed leaves the reverberation band and the rejection
grows with the shift (bounded)."""
speed = abs(radial_speed_kn)
if speed < CW_DOPPLER_MIN_KN:
return 0.0
return min(30.0, CW_DOPPLER_REJECTION_DB
+ 10.0 * math.log10(speed / CW_DOPPLER_MIN_KN))
def active_terms(*, distance_nm: float, target_ts_db: float, legacy_range_factor: float,
sea_state: float, rain: float, pulse: str, water_depth_m: float,
lambert_mu_db: float, wind_kn: float,
absorption_db_per_km: float,
radial_speed_kn: float = 0.0,
gain_factor: float = 1.0) -> ActiveTerms:
"""Active sonar equation for one echo.
``legacy_range_factor`` is the below-layer transmission loss of the
1.0.0 model; it attenuates echo and boundary reverberation alike.
``gain_factor`` (array ping multiplier, gameplay range factor) is a
receive/transmit gain against noise only - it cannot beat
reverberation, which scales with the transmitted level.
"""
source = active_source_level_db()
absorption = _two_way_absorption_db(distance_nm, absorption_db_per_km)
# Layer crossing / array transmission penalty of the 1.0.0 model; it
# attenuates the reverberating boundary returns as much as the echo.
path_penalty = active_range_factor_db(legacy_range_factor)
two_way = 2.0 * spreading_loss_db(distance_nm) + absorption + path_penalty
noise = active_noise_db(sea_state, rain)
reverb = reverberation_level_db(
source_level_db=source, distance_nm=distance_nm, pulse=pulse,
beamwidth_deg=ACTIVE_BEAMWIDTH_DEG, water_depth_m=water_depth_m,
lambert_mu_db=lambert_mu_db, wind_kn=wind_kn) - absorption - path_penalty
tau, bandwidth = PULSES[pulse]
gain = 10.0 * math.log10(max(1.0, tau * bandwidth))
gain += active_range_factor_db(1.0 / max(gain_factor, 1e-6))
rejection = cw_doppler_rejection_db(radial_speed_kn) if pulse == "CW" else 0.0
return ActiveTerms(source, two_way, target_ts_db, noise, reverb, gain,
rejection)
def range_resolution_m(pulse: str) -> float:
tau, bandwidth = PULSES[pulse]
if bandwidth > 1.0 / tau:
return config.SOUND_SPEED_M_S / (2.0 * bandwidth)
return config.SOUND_SPEED_M_S * tau / 2.0
def range_sigma_m(pulse: str, snr_db: float) -> float:
"""Cramer-Rao-style range accuracy: resolution / sqrt(2 SNR)."""
snr = 10.0 ** (max(snr_db, 0.0) / 10.0)
return range_resolution_m(pulse) / math.sqrt(2.0 * max(snr, 1.0))
def equivalent_range_nm(distance_nm: float, signal_excess_db: float) -> float:
"""Range multiplier form used by the 1.0.0 consumers: snr_db(R, d) = SE."""
return max(distance_nm, 1e-6) * 10.0 ** (signal_excess_db / 20.0)
+4 -2
View File
@@ -21,6 +21,9 @@ MAX_SEGMENTS_PER_PATH = 3
PROFILE_SAMPLES = 21
PROFILE_MAX_DEPTH_M = 400.0
REPRESENTATIVE_PASSIVE_BAND_HZ = 100.0
# Historical per-band absorption folded into path loss; the sonar equation
# replaces it with Francois-Garrison (src/sonar/equation.py).
ABSORPTION_DB_PER_NM = {100.0: .012, 400.0: .025, 1600.0: .055, 6400.0: .12}
CANONICAL_FREQUENCY_BANDS_HZ = (100.0, 400.0, 1600.0, 6400.0)
@@ -201,8 +204,7 @@ def propagate(source_x_nm: float, source_y_nm: float, source_depth_m: float,
PathKind.SURFACE: 5.0 + .6 * sea_state,
PathKind.BOTTOM: 7.0,
}
absorption_db_nm = {100.0: .012, 400.0: .025,
1600.0: .055, 6400.0: .12}[frequency]
absorption_db_nm = ABSORPTION_DB_PER_NM[frequency]
paths = []
for order, (kind, points) in enumerate(candidates):
segments = tuple(_segment(first, second, profile, terrain_blocked)
+268 -44
View File
@@ -12,7 +12,7 @@ from enum import Enum
import numpy as np
from src.core import config
from src.sonar import propagation
from src.sonar import equation, propagation
from src.sonar.tma import BearingTrack, solve_tma
from src.audio.database import rank_signatures
from src.audio.receiver import AcousticReceiver, directional_gain
@@ -33,6 +33,68 @@ def snr_db(passive_range_nm: float, dist_nm: float) -> float:
/ max(dist_nm, 1e-6))
_HULL_LENGTH_FALLBACK_M = (("torpedo_class", 6.0), ("atype", 15.0),
("kind", 3.0), ("stype", 70.0))
def hull_length_m(tgt) -> float:
"""Catalogued hull length of an echo target (bounded fallbacks)."""
catalog = getattr(tgt, "runtime_catalog", None)
key = getattr(getattr(tgt, "stype", None), "key", None) or getattr(
tgt, "signature_key", None)
if catalog is not None and key is not None:
systems = catalog.profile_systems.get(key)
reference = (catalog.references.get(systems.reference_key)
if systems is not None and systems.reference_key else None)
if reference is not None and reference.length_m:
return float(reference.length_m)
if hasattr(tgt, "length_m"):
return float(tgt.length_m)
if hasattr(tgt, "signature_key"):
return 120.0
for attribute, length in _HULL_LENGTH_FALLBACK_M:
if hasattr(tgt, attribute):
return length
return equation.REFERENCE_TARGET_LENGTH_M
class _WreckEcho:
"""Stationary echo source for a charted wreck (hard, flat-lying hull)."""
speed = 0.0
extra_ts_db = 3.0
def __init__(self, index: int, hazard, seed: int):
from src.core import detrand
self.id = 0
self.x, self.y = hazard.x_nm, hazard.y_nm
self.depth = hazard.top_depth_m + 6.0
self.length_m = hazard.length_m
self.course = detrand.uniform(0.0, 360.0, seed, "wreck-heading", index)
self.sensor_seed = int(detrand.bits(seed, "wreck-echo", index) & 0x7FFFFFFF)
def bearing_from_frigate(self, frigate) -> float:
return math.degrees(math.atan2(self.x - frigate.x,
-(self.y - frigate.y))) % 360.0
def _lambert_mu_db(world, x_nm: float, y_nm: float) -> float:
from src.world.ocean import SEDIMENTS
seabed = getattr(world, "seabed_at", None)
if seabed is None:
return SEDIMENTS["sand"][3]
return SEDIMENTS[seabed(x_nm, y_nm)][3]
def _surface_temperature(world) -> float:
ocean = getattr(world, "ocean", None)
if ocean is None:
return 10.0
return ocean.sea_surface_temperature_c(getattr(world, "hour", 12.0))
def _echo_delay(world, distance_nm: float, frigate, target) -> float:
"""Two-way echo latency with the modelled sound speed on the path."""
if hasattr(world, "mean_sound_speed_m_s"):
@@ -456,6 +518,8 @@ class Contact:
class SonarSystem:
MAX_PENDING_CLUTTER = 8
CLUTTER_SEARCH_NM = 30.0
MAX_PENDING_PINGS = 10000
STOWED = TowState.STOWED
DEPLOYING = TowState.DEPLOYING
@@ -511,6 +575,13 @@ class SonarSystem:
self._own_line_hz = 10.0
self.towed_depth_m = config.SONAR_TOWED_DEPTH_M
self.towed_depth_target_m = config.SONAR_TOWED_DEPTH_M
# Distant-shipping noise input (civilian contacts nearby, set by the
# game each tick) and the selected active pulse.
self.shipping_contacts = equation.REFERENCE_SHIPPING_CONTACTS
self.ping_pulse = equation.DEFAULT_PULSE
self.last_passive_terms = None
# Frozen false echoes from charted wrecks awaiting their return time.
self._pending_clutter: list[dict] = []
self.tow_state = TowState.STOWED
self.tow_payout = 0.0
self.tow_heading_deg = 0.0
@@ -765,7 +836,7 @@ class SonarSystem:
continue
distance = target.distance_nm(frigate)
active_range = self._active_range_nm(
target, world, range_factor, mode)
target, world, range_factor, mode, frigate)
if (distance >= active_range
and distance > config.SONAR_PING_HEAR_RANGE_NM):
continue
@@ -777,8 +848,11 @@ class SonarSystem:
target.x, target.y,
getattr(target, "depth", 0.0))):
continue
snapshot = (self._measure_ping(frigate, target, t_real, distance, active_range)
if distance < active_range else None)
snapshot = (self._measure_ping(
frigate, target, t_real, distance,
self.active_terms(target, frigate, world, range_factor,
mode).signal_excess_db, self.ping_pulse)
if distance < active_range else None)
if distance <= config.SONAR_PING_HEAR_RANGE_NM \
and hasattr(target, "hear_ping"):
target.hear_ping()
@@ -795,6 +869,7 @@ class SonarSystem:
"mode": mode,
"snapshot": snapshot,
})
self._queue_clutter(frigate, world, t_real, range_factor, mode)
def passive_range_nm(self, tgt, dist_nm: float, frigate, world,
range_factor: float, mode: str) -> float:
@@ -810,22 +885,42 @@ class SonarSystem:
tow_available: bool,
apply_propagation: bool = True,
spectral_out: list | None = None) -> float:
passive_range = frigate.passive_sonar_range_nm(
tgt.quiet_factor(), getattr(world, "effective_sea_state",
world.sea_state))
"""Equivalent detection range from the passive sonar equation.
Returns ``R`` with ``snr_db(R, d) == SE`` so existing consumers keep
their range-based interface; SE itself is SL - TL - NL + DI - DT per
``src/sonar/equation.py``.
"""
terms = self.passive_terms(tgt, dist_nm, frigate, world, range_factor,
mode, true_bearing, tow_available,
apply_propagation, spectral_out)
if terms is None:
return 0.0
self.last_passive_terms = terms
return equation.equivalent_range_nm(dist_nm, terms.signal_excess_db)
def passive_terms(self, tgt, dist_nm: float, frigate, world,
range_factor: float, mode: str, true_bearing: float,
tow_available: bool, apply_propagation: bool = True,
spectral_out: list | None = None):
# Own-ship self noise: the calibrated own-noise/cavitation penalty
# (target bonus 1, reference sea state) becomes a self-noise level.
own_factor = frigate.passive_sonar_range_nm(
1.0, int(equation.REFERENCE_SEA_STATE)) / config.SONAR_PASSIVE_BASE_NM
target_bonus = 1.0 + 0.8 * (1.0 - tgt.quiet_factor())
thermo = world.thermocline_depth_m(tgt.x, tgt.y)
sensor_depth = self.towed_depth_m if mode == "TOWED" else 5.0
same_layer = (sensor_depth < thermo) == (tgt.depth < thermo)
array_factor = 1.0
if mode == "TOWED":
if not tow_available:
return 0.0
return None
full_arr = max(0.5, config.SONAR_ARRAY_TOWED_PASSIVE
- config.SONAR_TOWED_SPEED_PENALTY * frigate.speed)
arr = 1.0 + (full_arr - 1.0) * self.tow_performance
passive_range *= arr
array_factor = 1.0 + (full_arr - 1.0) * self.tow_performance
# A deep array gains most when it occupies the target's layer.
if same_layer and self.towed_depth_m >= 30.0:
passive_range *= 1.0 + (config.SONAR_TOWED_DEEP_BONUS - 1.0) \
array_factor *= 1.0 + (config.SONAR_TOWED_DEEP_BONUS - 1.0) \
* self.tow_performance
own_noise = frigate.noise_level()
isotropic_penalty = max(0.2, 1.0 - 0.8 * own_noise)
@@ -833,8 +928,20 @@ class SonarSystem:
* self._receiver_noise_factor(mode) \
* directional_gain(true_bearing,
self._own_noise_bearing(mode, frigate.course))
passive_range *= directional_penalty / isotropic_penalty
passive_range *= range_factor
own_factor *= directional_penalty / isotropic_penalty
# The own wake astern adds bubble noise to the hull array.
wake = getattr(frigate, "wake_strength_at", None)
if mode == "BOW" and wake is not None and frigate.speed > 0.0:
astern = (frigate.course + 180.0) % 360.0
if abs(config.angle_diff_deg(true_bearing, astern)) < 30.0:
own_factor *= 1.0 - 0.3 * wake(
frigate.x - 0.2 * math.sin(math.radians(frigate.course)),
frigate.y + 0.2 * math.cos(math.radians(frigate.course)))
array_factor *= range_factor
frequency = representative_frequency_hz(tgt)
excess = legacy_absorption = 0.0
absorption = 0.0
sea_state = float(getattr(world, "effective_sea_state", world.sea_state))
if apply_propagation:
midpoint_x = (frigate.x + tgt.x) * .5
midpoint_y = (frigate.y + tgt.y) * .5
@@ -846,15 +953,28 @@ class SonarSystem:
float(getattr(tgt, "depth", 0.0)), midpoint_thermo)
result = propagation.propagate(
frigate.x, frigate.y, sensor_depth, tgt.x, tgt.y,
getattr(tgt, "depth", 0.0),
representative_frequency_hz(tgt),
midpoint_thermo, water_depth, sea_state=getattr(
world, "effective_sea_state", world.sea_state),
getattr(tgt, "depth", 0.0), frequency,
midpoint_thermo, water_depth, sea_state=sea_state,
terrain_blocked=getattr(world, "sonar_path_blocked", None))
passive_range *= propagation.passive_range_factor(result, dist_nm)
if result.best_path is None:
return None
excess = result.best_path.loss_db - 20.0 * math.log10(1.0 + dist_nm)
legacy_absorption = result.best_path.distance_nm \
* propagation.ABSORPTION_DB_PER_NM[frequency]
absorption = equation.francois_garrison_db_per_km(
frequency, _surface_temperature(world),
min(water_depth, 200.0))
if spectral_out is not None:
spectral_out.append(result.spectral_gains)
return passive_range
return equation.passive_terms(
frequency_hz=frequency, distance_nm=dist_nm,
target_bonus=target_bonus, excess_path_loss_db=excess,
absorption_db_per_km=absorption,
legacy_absorption_db=legacy_absorption,
own_range_factor=own_factor, array_range_factor=array_factor,
sea_state=sea_state,
rain=float(getattr(world, "rain_intensity", 0.0)),
shipping_contacts=self.shipping_contacts)
def update_dipping_passive(self, dt: float, t: float, helicopter,
targets, world, range_factor: float = 1.0) -> None:
@@ -868,24 +988,40 @@ class SonarSystem:
dx, dy = tgt.x - helicopter.x, tgt.y - helicopter.y
distance = math.hypot(dx, dy)
target_bonus = 1.0 + 0.8 * (1.0 - tgt.quiet_factor())
sea_state = getattr(world, "effective_sea_state", world.sea_state)
sea = 1.0 - config.SEA_STATE_SONAR_FACTOR * max(0, sea_state - 1)
effective_range = (config.HELO_DIP_PASSIVE_RANGE_NM * target_bonus
* sea * range_factor)
sea_state = float(getattr(world, "effective_sea_state", world.sea_state))
midpoint_x = (helicopter.x + tgt.x) * .5
midpoint_y = (helicopter.y + tgt.y) * .5
thermocline = world.thermocline_depth_m(midpoint_x, midpoint_y)
water_depth = max(float(world.depth_m(midpoint_x, midpoint_y)),
sensor_depth, float(getattr(tgt, "depth", 0.0)),
thermocline)
frequency = representative_frequency_hz(tgt)
result = propagation.propagate(
helicopter.x, helicopter.y, sensor_depth, tgt.x, tgt.y,
getattr(tgt, "depth", 0.0),
representative_frequency_hz(tgt),
thermocline, water_depth, sea_state=getattr(
world, "effective_sea_state", world.sea_state),
getattr(tgt, "depth", 0.0), frequency,
thermocline, water_depth, sea_state=sea_state,
terrain_blocked=getattr(world, "sonar_path_blocked", None))
effective_range *= propagation.passive_range_factor(result, distance)
if result.best_path is None:
continue
terms = equation.passive_terms(
frequency_hz=frequency, distance_nm=distance,
target_bonus=target_bonus,
excess_path_loss_db=(result.best_path.loss_db
- 20.0 * math.log10(1.0 + distance)),
absorption_db_per_km=equation.francois_garrison_db_per_km(
frequency, _surface_temperature(world),
min(water_depth, 200.0)),
legacy_absorption_db=result.best_path.distance_nm
* propagation.ABSORPTION_DB_PER_NM[frequency],
own_range_factor=1.0,
array_range_factor=(config.HELO_DIP_PASSIVE_RANGE_NM
/ config.SONAR_PASSIVE_BASE_NM) * range_factor,
sea_state=sea_state,
rain=float(getattr(world, "rain_intensity", 0.0)),
shipping_contacts=self.shipping_contacts,
hull_self_noise=False)
effective_range = equation.equivalent_range_nm(
distance, terms.signal_excess_db)
if distance >= effective_range:
continue
signal = snr_db(effective_range, distance)
@@ -1289,16 +1425,81 @@ class SonarSystem:
data["blade_rate_hz"], None, data["tonal_hz"], data["cavitation"],
self.acoustic_profiles)
@staticmethod
def _active_range_nm(tgt, world, range_factor: float, mode: str) -> float:
def cycle_pulse(self) -> str:
order = tuple(equation.PULSES)
self.ping_pulse = order[(order.index(self.ping_pulse) + 1) % len(order)]
return self.ping_pulse
def _queue_clutter(self, frigate, world, t_real: float,
range_factor: float, mode: str) -> None:
"""Wrecks on the seabed return real echoes that no contact owns."""
ocean = getattr(world, "ocean", None)
if ocean is None:
return
source_depth = self.towed_depth_m if mode == "TOWED" else 5.0
for index, hazard in enumerate(ocean.hazards):
if (hazard.kind != "wreck"
or len(self._pending_clutter) >= self.MAX_PENDING_CLUTTER):
continue
distance = math.hypot(hazard.x_nm - frigate.x, hazard.y_nm - frigate.y)
if distance > self.CLUTTER_SEARCH_NM or distance < 0.05:
continue
echo = _WreckEcho(index, hazard, ocean.seed)
terms = self.active_terms(echo, frigate, world, range_factor, mode)
if terms.signal_excess_db <= 0.0:
continue
if (hasattr(world, "sonar_path_blocked")
and world.sonar_path_blocked(frigate.x, frigate.y, source_depth,
echo.x, echo.y, echo.depth)):
continue
snapshot = self._measure_ping(frigate, echo, t_real, distance,
terms.signal_excess_db, self.ping_pulse)
self._pending_clutter.append({
"ready_at": t_real + _echo_delay(world, distance, frigate, echo),
"mode": mode, "snapshot": snapshot})
def active_terms(self, tgt, frigate, world, range_factor: float,
mode: str, pulse: str | None = None):
"""Active sonar equation for one echo from ``tgt``."""
ping_mult = (config.SONAR_ARRAY_TOWED_PING if mode == "TOWED"
else config.SONAR_ARRAY_BOW_PING)
active_range = (config.HELO_DIP_ACTIVE_RANGE_NM if mode == "DIPPING"
else config.SONAR_ACTIVE_BASE_NM * ping_mult)
gain = (config.HELO_DIP_ACTIVE_RANGE_NM / config.SONAR_ACTIVE_BASE_NM
if mode == "DIPPING" else ping_mult) * range_factor
layer = 1.0
if getattr(tgt, "depth", 0.0) >= world.thermocline_depth_m(tgt.x, tgt.y):
active_range *= config.SONAR_THERMO_ACTIVE_BELOW
sea_state = getattr(world, "effective_sea_state", world.sea_state)
return active_range * (1.0 - 0.03 * sea_state) * range_factor
layer = config.SONAR_THERMO_ACTIVE_BELOW
distance = max(1e-6, math.hypot(tgt.x - frigate.x, tgt.y - frigate.y))
to_observer = math.degrees(math.atan2(frigate.x - tgt.x,
-(frigate.y - tgt.y))) % 360.0
aspect = config.angle_diff_deg(to_observer, getattr(tgt, "course", 0.0))
speed = getattr(tgt, "speed", None)
if speed is None:
speed = getattr(tgt, "speed_kn", 0.0)
radial = speed * math.cos(math.radians(aspect))
mx, my = (frigate.x + tgt.x) * .5, (frigate.y + tgt.y) * .5
return equation.active_terms(
distance_nm=distance,
target_ts_db=(equation.target_strength_db(hull_length_m(tgt), aspect)
+ getattr(tgt, "extra_ts_db", 0.0)),
legacy_range_factor=layer, gain_factor=gain,
sea_state=float(getattr(world, "effective_sea_state", world.sea_state)),
rain=float(getattr(world, "rain_intensity", 0.0)),
pulse=pulse or self.ping_pulse,
water_depth_m=float(getattr(world, "depth_m", lambda x, y: 1000.0)(mx, my)),
lambert_mu_db=_lambert_mu_db(world, mx, my),
wind_kn=float(getattr(world, "wind_speed_kn", 10.0)),
absorption_db_per_km=equation.francois_garrison_db_per_km(
equation.ACTIVE_FREQUENCY_HZ, _surface_temperature(world)),
radial_speed_kn=radial)
def _active_range_nm(self, tgt, world, range_factor: float, mode: str,
frigate=None) -> float:
"""Equivalent range: the echo is detectable while distance < R."""
if frigate is None:
return 0.0
terms = self.active_terms(tgt, frigate, world, range_factor, mode)
distance = math.hypot(tgt.x - frigate.x, tgt.y - frigate.y)
return max(distance, 1e-6) * 10.0 ** (terms.signal_excess_db / 40.0)
def process_lofar_column(self, column, frigate) -> list:
"""Apply operator gain and frequency controls to one LOFAR column."""
@@ -1323,6 +1524,19 @@ class SonarSystem:
is internal association only; neither geometry nor propagation is read
again. Measurement timestamps never become reception timestamps.
"""
clutter = []
for echo in self._pending_clutter:
if t >= echo["ready_at"]:
entry = {key: value for key, value in echo["snapshot"].items()
if key not in ("observer_x", "observer_y")}
entry.update(contact_id=0, mode=echo["mode"])
self.echo_history.append(entry)
del self.echo_history[:-config.SONAR_ECHO_HISTORY_MAX]
self.echo_events.append(dict(entry))
del self.echo_events[:-config.SONAR_ECHO_HISTORY_MAX]
else:
clutter.append(echo)
self._pending_clutter = clutter
pending = []
for ping in self._pending_pings:
target = ping["target"]
@@ -1344,7 +1558,8 @@ class SonarSystem:
limits = {"t": (0, 1e12), "observer_x": (-1e6, 1e6),
"observer_y": (-1e6, 1e6), "bearing": (0, 360),
"range_nm": (0, 10000), "depth_m": (0, 10000),
"range_sigma_nm": (1e-9, config.SONAR_PING_RANGE_ERROR_NM),
"range_sigma_nm": (1e-9, equation.range_resolution_m(
"CW") / 1852.0 / math.sqrt(2.0)),
"depth_sigma_m": (1e-9, config.SONAR_PING_DEPTH_ERROR_M),
"snr_db": (-200, 200)}
if not isinstance(snapshot, dict) or set(snapshot) != set(limits):
@@ -1359,20 +1574,25 @@ class SonarSystem:
return False
@staticmethod
def _measure_ping(frigate, target, t: float, distance: float, active_range: float):
"""Deterministic noisy snapshot; no shared RNG or contact allocation."""
signal = snr_db(active_range, distance)
def _measure_ping(frigate, target, t: float, distance: float,
signal: float, pulse: str = equation.DEFAULT_PULSE):
"""Deterministic noisy snapshot; no shared RNG or contact allocation.
Range accuracy follows the pulse (CW resolution c*tau/2, LFM c/2B)
and the echo SNR (Cramer-Rao); bearing and depth errors shrink with
SNR as before."""
error_scale = 1.0 / max(1.0, 1.0 + signal / 8.0)
seed = getattr(target, "sensor_seed", target.id)
range_sigma = equation.range_sigma_m(pulse, signal) / 1852.0
snapshot = dict(
t=t, observer_x=frigate.x, observer_y=frigate.y,
bearing=(target.bearing_from_frigate(frigate) + 1.5 * error_scale
* _correlated_uniform(seed, t, 1.0, 101)) % 360.0,
range_nm=max(0.0, distance + config.SONAR_PING_RANGE_ERROR_NM
* error_scale * _correlated_uniform(seed, t, 1.0, 211)),
range_nm=max(0.0, distance + math.sqrt(3.0) * range_sigma
* _correlated_uniform(seed, t, 1.0, 211)),
depth_m=max(0.0, target.depth + config.SONAR_PING_DEPTH_ERROR_M
* error_scale * _correlated_uniform(seed, t, 1.0, 307)),
range_sigma_nm=config.SONAR_PING_RANGE_ERROR_NM * error_scale / math.sqrt(3),
range_sigma_nm=range_sigma,
depth_sigma_m=config.SONAR_PING_DEPTH_ERROR_M * error_scale / math.sqrt(3),
snr_db=signal)
if not SonarSystem.valid_ping_snapshot(snapshot):
@@ -1444,7 +1664,8 @@ class SonarSystem:
if tgt_gone(tgt):
continue
dist = tgt.distance_nm(frigate)
active_range = self._active_range_nm(tgt, world, range_factor, mode)
active_range = self._active_range_nm(tgt, world, range_factor, mode,
frigate)
can_hear = (notify_ping and dist <= config.SONAR_PING_HEAR_RANGE_NM
and hasattr(tgt, "hear_ping"))
if dist >= active_range and not can_hear:
@@ -1462,7 +1683,10 @@ class SonarSystem:
# Echo erhalten?
if dist < active_range:
snapshot = self._measure_ping(frigate, tgt, t_real, dist, active_range)
snapshot = self._measure_ping(
frigate, tgt, t_real, dist,
self.active_terms(tgt, frigate, world, range_factor,
mode).signal_excess_db, self.ping_pulse)
contacts.append(self._apply_ping_snapshot(tgt, snapshot, mode))
return contacts
+20
View File
@@ -18,5 +18,25 @@
"phase": 2,
"reason": "Phase 2: first-order Nomoto steering, r = K (V/L) delta, makes the steady turn rate linear in speed, so the turning circle is nearly constant; calibrated at FULL (1.2 deg/s), HALF becomes 0.75 deg/s.",
"value": 0.75
},
"sonar.passive_nm.BOW.sea4.own18.d150": {
"phase": 3,
"reason": "Phase 3: the passive sonar equation power-sums wind/shipping ambient noise with own-ship self noise. At cavitating own speeds self noise dominates, so a higher sea state costs less range than the flat 1.0.0 sea-state factor.",
"value": 3.576355
},
"sonar.passive_nm.BOW.sea4.own18.d30": {
"phase": 3,
"reason": "Phase 3: the passive sonar equation power-sums wind/shipping ambient noise with own-ship self noise. At cavitating own speeds self noise dominates, so a higher sea state costs less range than the flat 1.0.0 sea-state factor.",
"value": 7.554507
},
"sonar.passive_nm.BOW.sea4.own25.d150": {
"phase": 3,
"reason": "Phase 3: the passive sonar equation power-sums wind/shipping ambient noise with own-ship self noise. At cavitating own speeds self noise dominates, so a higher sea state costs less range than the flat 1.0.0 sea-state factor.",
"value": 2.831818
},
"sonar.passive_nm.BOW.sea4.own25.d30": {
"phase": 3,
"reason": "Phase 3: the passive sonar equation power-sums wind/shipping ambient noise with own-ship self noise. At cavitating own speeds self noise dominates, so a higher sea state costs less range than the flat 1.0.0 sea-state factor.",
"value": 5.983241
}
}
+3 -1
View File
@@ -366,7 +366,9 @@ def test_stale_measurement_does_not_refresh_surface_contact_age():
def test_component_damage_can_degrade_or_disable_only_due_sensors():
owner = target(id=1, x=0.0)
detected = target(x=30.0)
# Degraded sonar halves the 40 NM figure of merit; even a loud target
# (source level at most +5 dB, reach x1.8) is not heard beyond 36 NM.
detected = target(x=36.5)
suite = PlatformSensorSuite(
CATALOG, "warship_01", 14, side="friendly",
doctrine="surface_combatant")
+5
View File
@@ -102,8 +102,13 @@ def game():
contact.buoy_fixes = [(16, game.ship.x + 5, game.ship.y, .6),
(18, game.ship.x + 6, game.ship.y, .7)]
game.sonar.contacts[sub.id] = contact
# A bow-on torpedo is a weak echo (target strength about -11 dB, lost in
# reverberation at 8 NM). This fixture only needs a pending echo to save,
# so it gives the weapon a strong reflector.
game.enemy_torpedoes[0].extra_ts_db = 40.0
game.sonar.queue_ping(
game.ship, [game.enemy_torpedoes[0]], game.world, game.sim_t)
del game.enemy_torpedoes[0].extra_ts_db
assert game.sonar._pending_pings
game.sonar._pending_pings[0]["ready_at"] = 25
return game
+172
View File
@@ -0,0 +1,172 @@
"""Phase 3: passive/active sonar equations, noise, reverberation, pulses,
wreck clutter and NPC receiver sensitivity."""
import copy
import json
import math
from types import SimpleNamespace
import pygame
import pytest
from src.core.game import Game
from src.sonar import equation
from src.world.ocean import SEDIMENTS
def test_francois_garrison_matches_reference_magnitudes():
assert 0.04 < equation.francois_garrison_db_per_km(1000.0, 10.0) < 0.09
assert equation.francois_garrison_db_per_km(100.0) < \
equation.francois_garrison_db_per_km(6400.0)
def test_ambient_noise_follows_wind_rain_and_shipping():
calm = equation.ambient_noise_db(1600.0, 1)
rough = equation.ambient_noise_db(1600.0, 5)
assert rough - calm > 8.0
assert equation.ambient_noise_db(1600.0, 1, rain=1.0) > calm + 3.0
assert equation.ambient_noise_db(100.0, 1, shipping_contacts=40) > \
equation.ambient_noise_db(100.0, 1, shipping_contacts=0) + 5.0
def test_passive_reference_and_self_noise_reproduce_calibration():
terms = equation.passive_terms(
frequency_hz=100.0, distance_nm=equation.PASSIVE_REFERENCE_RANGE_NM,
target_bonus=1.0, excess_path_loss_db=0.0, absorption_db_per_km=0.0,
legacy_absorption_db=0.0, own_range_factor=1.0, array_range_factor=1.0,
sea_state=1.0, rain=0.0,
shipping_contacts=equation.REFERENCE_SHIPPING_CONTACTS)
assert terms.signal_excess_db == pytest.approx(0.0, abs=1e-9)
noisy = equation.passive_terms(
frequency_hz=100.0, distance_nm=10.0, target_bonus=1.0,
excess_path_loss_db=0.0, absorption_db_per_km=0.0,
legacy_absorption_db=0.0, own_range_factor=0.5, array_range_factor=1.0,
sea_state=1.0, rain=0.0,
shipping_contacts=equation.REFERENCE_SHIPPING_CONTACTS)
# Half the 1.0.0 range means 6 dB less excess at the same distance.
quiet = equation.passive_terms(
frequency_hz=100.0, distance_nm=10.0, target_bonus=1.0,
excess_path_loss_db=0.0, absorption_db_per_km=0.0,
legacy_absorption_db=0.0, own_range_factor=1.0, array_range_factor=1.0,
sea_state=1.0, rain=0.0,
shipping_contacts=equation.REFERENCE_SHIPPING_CONTACTS)
assert quiet.signal_excess_db - noisy.signal_excess_db == pytest.approx(
20 * math.log10(2), abs=1e-6)
def _active(distance, **overrides):
values = dict(distance_nm=distance,
target_ts_db=equation.reference_target_strength_db(),
legacy_range_factor=1.0, sea_state=0.0, rain=0.0,
pulse="CW", water_depth_m=4000.0,
lambert_mu_db=SEDIMENTS["mud"][3], wind_kn=0.0,
absorption_db_per_km=equation.francois_garrison_db_per_km(
equation.ACTIVE_FREQUENCY_HZ,
equation.REFERENCE_WATER_TEMPERATURE_C))
values.update(overrides)
return equation.active_terms(**values)
def test_active_reference_range_and_target_aspect():
assert _active(equation.ACTIVE_REFERENCE_RANGE_NM).signal_excess_db == \
pytest.approx(0.0, abs=0.5)
assert equation.target_strength_db(70, 90) - equation.target_strength_db(70, 0) \
== pytest.approx(15.0)
def test_reverberation_depends_on_seabed_and_cw_doppler_rejects_it():
rock = _active(3.0, water_depth_m=60.0, lambert_mu_db=SEDIMENTS["rock"][3])
mud = _active(3.0, water_depth_m=60.0, lambert_mu_db=SEDIMENTS["mud"][3])
assert rock.reverberation_db > mud.reverberation_db + 5.0
still = _active(3.0, water_depth_m=60.0, lambert_mu_db=SEDIMENTS["rock"][3])
moving = _active(3.0, water_depth_m=60.0, lambert_mu_db=SEDIMENTS["rock"][3],
radial_speed_kn=12.0)
assert moving.signal_excess_db > still.signal_excess_db
assert equation.cw_doppler_rejection_db(1.0) == 0.0
assert equation.cw_doppler_rejection_db(20.0) > equation.cw_doppler_rejection_db(4.0)
def test_lfm_improves_range_accuracy_and_noise_limited_gain():
assert equation.range_resolution_m("LFM") < equation.range_resolution_m("CW") / 50
assert equation.range_sigma_m("CW", 20.0) < equation.range_sigma_m("CW", 5.0)
far_cw = _active(20.0)
far_lfm = _active(20.0, pulse="LFM")
assert far_lfm.signal_excess_db > far_cw.signal_excess_db
def _game(seed=3301):
return Game(seed=seed, start_menu=False, audio_enabled=False)
def test_pulse_key_cycles_and_persists():
game = _game()
game.station = type(game.station).SONAR
assert game.sonar.ping_pulse == "CW"
game.handle_event(pygame.event.Event(pygame.KEYDOWN, key=pygame.K_w, mod=0,
unicode="w"))
assert game.sonar.ping_pulse == "LFM"
state = json.loads(json.dumps(game.save_state()))
restored = _game(1)
assert restored._load_save_data(copy.deepcopy(state))
assert restored.sonar.ping_pulse == "LFM"
state["sonar"]["ping_pulse"] = "FM"
assert not restored._load_save_data(state)
def test_wreck_returns_unassociated_echo_that_survives_save():
game = _game(3302)
wreck = next(h for h in game.world.ocean.hazards if h.kind == "wreck")
game.ship.x, game.ship.y = wreck.x_nm - 1.0, wreck.y_nm
game.world.sonar_path_blocked = lambda *args: False
game.sonar.queue_ping(game.ship, [], game.world, game.sim_t)
assert game.sonar._pending_clutter
state = json.loads(json.dumps(game.save_state()))
restored = _game(1)
assert restored._load_save_data(copy.deepcopy(state))
assert restored.sonar._pending_clutter == game.sonar._pending_clutter
restored.sonar._process_pending_pings(restored.sim_t + 60.0)
echo = restored.sonar.echo_history[-1]
assert echo["contact_id"] == 0
assert echo["range_nm"] == pytest.approx(1.0, abs=0.3)
broken = copy.deepcopy(state)
broken["sonar"]["pending_clutter"][0]["snapshot"]["bearing"] = 400.0
assert not restored._load_save_data(broken)
def test_npc_receiver_sensitivity_extends_passive_range():
from src.data.catalog import CATALOG
from src.sensors.platform import PlatformSensorSuite
class World:
size_nm = 500.0
depth_m = staticmethod(lambda *a: 1000.0)
thermocline_depth_m = staticmethod(lambda *a: 80.0)
on_land = staticmethod(lambda *a: False)
land_blocks_line = staticmethod(lambda *a: False)
sonar_path_blocked = staticmethod(lambda *a: False)
sea_state = 1
effective_sea_state = 1.0
import dataclasses
base = next(CATALOG.sensors[key] for key in
CATALOG.profile_systems["warship_01"].sensor_keys
if CATALOG.sensors[key].domain == "sonar")
def heard(distance, sensitivity_shift):
suite = PlatformSensorSuite(CATALOG, "warship_01", 5, side="hostile",
doctrine="surface_combatant")
profile = dataclasses.replace(
base, sensitivity_db=base.sensitivity_db + sensitivity_shift)
owner = SimpleNamespace(id=1, x=0.0, y=0.0, depth=5.0, course=0.0,
speed=10.0, noise_level=lambda: 0.3)
target = SimpleNamespace(id=77, x=distance, y=0.0, depth=50.0,
course=0.0, speed=5.0, active=True, sunk=False,
noise_level=lambda: 0.3)
suite._observe_candidate(1.0, owner, target, World(), profile, 0, 1.0)
return bool(suite.local_picture.tracks(1.0)) if hasattr(
suite.local_picture, "tracks") else bool(suite.tactical_tracks(1.0))
far = 68.0 # beyond the 40 NM x source-level reach, inside the 1.8x cap
assert not heard(far, 0.0)
assert heard(far, -6.0)
+16 -5
View File
@@ -217,14 +217,25 @@ def measure_sonar() -> dict:
f"own{int(own_speed)}.d{int(depth)}")
out[key] = _metric(_detection_range(game, target, mode),
"range")
# Active range for a target above and below the layer.
# Active detection range (signal excess zero) for a target above and
# below the layer, broadside-ish geometry fixed by the target course.
_set_sea(game.world, 1)
for depth in (30.0, 250.0):
target.depth = depth
target.x, target.y = ship.x + 5.0, ship.y
out[f"sonar.active_nm.BOW.d{int(depth)}"] = _metric(
game.sonar._active_range_nm(target, game.world, 1.0, "BOW"),
"range")
def excess(dist):
target.x, target.y = ship.x + dist, ship.y
return (game.sonar._active_range_nm(target, game.world, 1.0, "BOW",
ship) - dist)
low, high = 0.05, 60.0
for _ in range(40):
mid = 0.5 * (low + high)
if excess(mid) > 0.0:
low = mid
else:
high = mid
out[f"sonar.active_nm.BOW.d{int(depth)}"] = _metric(0.5 * (low + high),
"range")
from src.sonar.sonar import bearing_error_deg
for mode in ("BOW", "TOWED"):
for speed in (6.0, 12.0):