diff --git a/data/i18n/de.json b/data/i18n/de.json index ff16f020..8e882140 100644 --- a/data/i18n/de.json +++ b/data/i18n/de.json @@ -3239,5 +3239,9 @@ "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" + "help.control.pulse": "Aktivpuls CW / LFM", + "enum.fusion.ambiguous": "TAS links/rechts mehrdeutig", + "sonar.line.tas_mirror": "TAS-Spiegelpeilung {mirror} - 20 Grad drehen zum Auflösen", + "sonar.line.tonal": "Tonal (Doppler) {frequency} Hz", + "sonar.line.tma_ellipse": "TMA 1-Sigma {major} x {minor} sm, Achse {orientation}" } diff --git a/data/i18n/en.json b/data/i18n/en.json index ee5d93b5..a97eec9c 100644 --- a/data/i18n/en.json +++ b/data/i18n/en.json @@ -3239,5 +3239,9 @@ "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" + "help.control.pulse": "Active pulse CW / LFM", + "enum.fusion.ambiguous": "TAS left/right ambiguous", + "sonar.line.tas_mirror": "TAS mirror bearing {mirror} - turn 20 deg to resolve", + "sonar.line.tonal": "Tonal (Doppler) {frequency} Hz", + "sonar.line.tma_ellipse": "TMA 1-sigma {major} x {minor} NM, axis {orientation}" } diff --git a/data/manual/02-sonar.de.md b/data/manual/02-sonar.de.md index 0f7317ef..9966f3b1 100644 --- a/data/manual/02-sonar.de.md +++ b/data/manual/02-sonar.de.md @@ -61,7 +61,7 @@ Die Anzeige zeigt gemessene Modulation, keine sichere Identität. Die Analysefen ### TMA, Umwelt und Aktiv {#sonar-tma-env} -- **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. +- **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. Eine Gittersuche findet den Bereich, eine Levenberg-Marquardt-Anpassung verfeinert ihn; die Detailzeile zeigt die 1-Sigma-Unsicherheitsellipse. Das stärkste Tonal wird mit seiner Dopplerverschiebung gemessen ("Tonal (Doppler)"): ein nah vorbeiziehendes Ziel verschiebt seine Frequenz, das legt die Entfernung auch ohne eigene Wende fest. Sonobojen-Peilungen gehen mit der Boje als Beobachter in dieselbe Schätzung ein, ein Bojenfeld liefert deshalb schnell Entfernung. - **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 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"). @@ -110,6 +110,7 @@ Gefechtslage: - TAS unter die gemessene Schicht legen, um tiefe Ziele zu hören; das HMS für flache Ziele nutzen. Beide Arrays arbeiten parallel. - Die TMA-Seite zeigt die aus der Lösung abgeleitete Annäherungsrate: positiv heißt, das Ziel kommt näher. - Weichen TAS und HMS um 9 Grad oder mehr ab, den Kontakt als möglichen Geist behandeln (die Anzeige markiert ihn) und durch eine Wende klären. +- Die Schleppantenne ist eine Linie: sie kann eine Peilung nicht von ihrem Spiegelbild zum Kabel unterscheiden. Ein nur auf der TAS gehörter Kontakt wird als "TAS links/rechts mehrdeutig" mit Spiegelpeilung markiert und speist keine TMA; die angezeigte Seite stimmt nur in der Hälfte der Fälle. 20 Grad drehen (oder den Kontakt auf die HMS bekommen), dann fällt die falsche Seite weg. Peilungen zu den Kabelenden (Endfire) sind zudem ungenauer als querab. - Ein Kontakt geht 120 s nach der letzten Ortung verloren. Schwache Kontakte weiter verfolgen oder per Ping wieder erfassen. ## Nicht modelliert {#sonar-limits} @@ -117,5 +118,4 @@ Gefechtslage: - Keine manuelle TMA (Punktstapel, manuelle Lösungseingabe); nur der automatische Löser, geschaltet mit `T`. - Keine wählbare Split-Window-Normalisierung (TPSW); stattdessen Verstärkung, Schwarzwert und Kontrast nutzen. - Kein harter blinder Baffle-Sektor; Eigenlärm ist eine weiche Keule. -- Keine akustische Dopplerverschiebung tonaler Linien; die Annäherungsrate kommt nur aus der TMA-Lösung. - Kein vom TAS getrenntes Tiefensonar (VDS). diff --git a/data/manual/02-sonar.en.md b/data/manual/02-sonar.en.md index dcbef65d..f178710b 100644 --- a/data/manual/02-sonar.en.md +++ b/data/manual/02-sonar.en.md @@ -60,7 +60,7 @@ The display shows measured modulation, not certain identity. The analysis window ### TMA, environment and active {#sonar-tma-env} -- **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. +- **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. A grid search finds the basin and a Levenberg-Marquardt fit refines it; the detail line shows the 1-sigma uncertainty ellipse. The strongest tonal is measured with its Doppler shift ("Tonal (Doppler)"): a target crossing close by sweeps its frequency, which fixes range even without an own turn. Sonobuoy bearings enter the same estimate with the buoy as observer, so a buoy field gives range quickly. - **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 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"). @@ -109,6 +109,7 @@ Combat situation: - Put the TAS below the measured layer to hear deep targets; keep the HMS for shallow ones. Both arrays run in parallel. - The TMA page shows the closing rate derived from the solution: positive means the target is closing. - If the TAS and HMS disagree by 9 degrees or more, treat the contact as a possible ghost (the display flags it) and turn to resolve it. +- The towed array is a line: it cannot tell a bearing from its mirror about the cable. A contact heard only on the TAS is marked "TAS left/right ambiguous" with its mirror bearing and does not feed TMA; the shown side is right only half the time. Turn 20 degrees (or get the contact on the HMS) and the wrong side drops out. Bearings toward the cable ends (endfire) are also less accurate than broadside. - A contact is lost 120 s after its last detection. Keep tracking weak contacts, or reacquire with a ping. ## Not modelled {#sonar-limits} @@ -116,5 +117,4 @@ Combat situation: - No manual TMA (dot stack, manual solution entry); only the automatic solver, switched with `T`. - No selectable split-window normalisation (TPSW); use gain, black level and contrast instead. - No hard blind baffle sector; own noise is a soft lobe. -- No acoustic Doppler shift of tonal lines; closing rate comes from the TMA solution only. - No variable-depth sonar separate from the TAS. diff --git a/docs/simulation-gaps.md b/docs/simulation-gaps.md index 0979107a..871a2e35 100644 --- a/docs/simulation-gaps.md +++ b/docs/simulation-gaps.md @@ -269,12 +269,12 @@ Scope: Ship dynamics, weapons, enemy AI, air, sonar/sensors, world/environment. | ~~**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**~~ | **Closed (Phase 4).** `src/sonar/raytrace.py`: 48-ray Snell fan through the Mackenzie profile (turning points, surface duct, shadow zone, convergence where deep enough), rough-surface and lossy Rayleigh bottom reflections, incoherent flux summation into TL(range, depth) tables per band; pure functions of a quantized environment key with a bounded LRU cache (purity keeps save/load deterministic). Own, dipping and NPC passive sonars use it via reciprocity (sensor = source). | — | | ~~**Propagation: no frequency dependence in path loss**~~ | **Closed (Phases 3-4).** Francois-Garrison absorption per band; boundary losses (surface roughness k-dependence) per band in the ray tables. | — | -| **No Doppler** | Bearing measurements have no Doppler shift information | Doppler = f₀ · (v·r̂)/c; useful for speed estimation and classification | +| ~~**No Doppler**~~ | **Closed (Phase 5).** Tonal lines in LOFAR/audio are Doppler shifted by the closing speed; the strongest tonal is measured per bearing point (SNR-dependent error) and saved; TMA estimates the unshifted f0 and uses Doppler for observability. | — | | ~~**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 | +| ~~**TMA: fixed grid**~~ | **Closed (Phase 5).** Grid seed plus Levenberg-Marquardt refinement over position/velocity (+f0 with Doppler), accepted where observable; 1-sigma covariance ellipse published and saved; range sigma never more optimistic than the observability heuristic. | — | +| ~~**No multi-static sonar**~~ | **Closed (Phase 5).** Sonobuoy (sonar-equation) and dipping bearings enter the contact's bearing track with their own observer positions, so one estimator fuses own-ship, buoy and helicopter geometry. | — | +| ~~**No sonar array beamforming**~~ | **Closed (Phase 5).** Uniform-aperture sinc beam pattern with -13 dB side lobes in the receiver/broadband scan, towed-array endfire broadening (1/sqrt(sin)), and the towed line array's left/right ambiguity (mirror bearing, excluded from TMA until an own turn or the hull array resolves it). | — | ### 7.3 Data structures / interfaces touched diff --git a/src/audio/receiver.py b/src/audio/receiver.py index 5b286c56..a08e26e1 100644 --- a/src/audio/receiver.py +++ b/src/audio/receiver.py @@ -72,6 +72,16 @@ def directional_gain(bearing_deg: float, center_deg: float, return float(gain) if np.ndim(gain) == 0 else gain +def beam_pattern_gain(bearing_deg, center_deg: float, width_deg: float): + """Uniform line-aperture beam: |sinc| main lobe of the given amplitude + FWHM with the first side lobes at -13 dB, so a loud source leaks into + neighbouring beams (grating/side-lobe response of a real array).""" + delta = (center_deg - np.asarray(bearing_deg, dtype=float) + 180.0) % 360.0 - 180.0 + x = 1.2067 * delta / max(width_deg, 1e-6) + gain = np.abs(np.sinc(x)) + return float(gain) if np.ndim(gain) == 0 else gain + + class AcousticReceiver: """4096 Hz mono receiver, advanced by exactly .25 s per update. @@ -441,11 +451,11 @@ class AcousticReceiver: if key in entries: next_states[key] = (direction, state, bb_ola, bb_params) next_spectral_states[key] = curve - audio += source_audio * directional_gain(bearing, direction, width) + audio += source_audio * beam_pattern_gain(bearing, direction, width) # Actual unsteered block energy, not source presence or current beam # amplitude. Incoherent source powers add; normalize all terms alike. scan += (np.mean(source_audio**2) / .25**2 - * directional_gain(self._angles, direction, width)**2) + * beam_pattern_gain(self._angles, direction, width)**2) self._source_states = next_states self._spectral_states = next_spectral_states if own_cav > 0: diff --git a/src/core/config.py b/src/core/config.py index 5a3943cc..3fb89c52 100644 --- a/src/core/config.py +++ b/src/core/config.py @@ -255,6 +255,7 @@ SHIP_YAW_DAMPING = 2.0 SHIP_LIST_DEG_PER_FLOOD_PCT = 0.15 SHIP_MAX_LIST_DEG = 15.0 SHIP_LIST_YAW_GAIN = 0.05 # deg/s of persistent yaw pull per degree of list +TAS_AMBIGUITY_RESOLVE_DEG = 20.0 # own turn that resolves TAS left/right CAVITATION_KN = 15.0 # Schraubenkavitation ab dieser Fahrt CAVITATION_PASSIVE_FACTOR = 0.35 # passives Sonar bei Kavitation: Sensor "bricht" SEA_STATE_SONAR_FACTOR = 0.06 # passiver Reichweiten-Abzug pro Seegang-Grad diff --git a/src/core/game.py b/src/core/game.py index 6e677946..b5c69267 100644 --- a/src/core/game.py +++ b/src/core/game.py @@ -6904,7 +6904,15 @@ class Game: fused_quality=c.fused_quality, tma_pos=c.tma_pos, tma_course=c.tma_course, tma_speed=c.tma_speed, tma_quality=c.tma_quality, - tma_seen=c.tma_seen, buoy_fixes=list(c.buoy_fixes[-80:]), + tma_seen=c.tma_seen, + tma_ellipse=(list(c.tma_ellipse) + if c.tma_ellipse is not None else None), + towed_ambiguous=c.towed_ambiguous, + towed_resolved=c.towed_resolved, + ambiguity_axis=c.ambiguity_axis, + mirror_bearing=c.mirror_bearing, + tonal_hz=c.tonal_hz, + buoy_fixes=list(c.buoy_fixes[-80:]), buoy_reports={str(seq): dict(report) for seq, report in c.buoy_reports.items()}, helo_qualified=c.helo_qualified, @@ -6925,7 +6933,8 @@ class Game: str(target_id): [ dict(t=p.t, bearing=p.bearing, fx=p.fx, fy=p.fy, fcourse=p.fcourse, - uncertainty_deg=p.uncertainty_deg) + uncertainty_deg=p.uncertainty_deg, + freq_hz=p.freq_hz, fspeed=p.fspeed) for p in track.pts] for target_id, track in self.sonar._tracks.items()}, "track_versions": { @@ -7625,6 +7634,13 @@ class Game: c.tma_speed = cd.get("tma_speed") c.tma_quality = cd.get("tma_quality", 0.0) c.tma_seen = cd.get("tma_seen", c.range_seen if c.range_source == "tma" else None) + c.tma_ellipse = (tuple(cd["tma_ellipse"]) + if cd["tma_ellipse"] is not None else None) + c.towed_ambiguous = cd["towed_ambiguous"] + c.towed_resolved = cd["towed_resolved"] + c.ambiguity_axis = cd["ambiguity_axis"] + c.mirror_bearing = cd["mirror_bearing"] + c.tonal_hz = cd["tonal_hz"] c.buoy_fixes = [tuple(row) for row in cd.get("buoy_fixes", [])] c.buoy_reports = {int(seq): dict(row) for seq, row in cd.get("buoy_reports", {}).items()} @@ -7681,7 +7697,8 @@ class Game: track = BearingTrack() track.pts = [BearingPoint(p["t"], p["bearing"], p["fx"], p["fy"], p["fcourse"], - p.get("uncertainty_deg")) + p.get("uncertainty_deg"), + p["freq_hz"], p["fspeed"]) for p in points[-config.BEARING_TRACK_MAX_PTS:]] track.version = track_versions.get(target_id, len(track.pts)) self.sonar._tracks[int(target_id)] = track @@ -9144,6 +9161,22 @@ class Game: or contact.get("dip_observer_x") is None or contact.get("dip_observer_y") is None): return False + ellipse = contact.get("tma_ellipse") + if ellipse is not None and ( + not isinstance(ellipse, list) or len(ellipse) != 3 + or not bounded(ellipse[0], 0.0, 1e6) + or not bounded(ellipse[1], 0.0, ellipse[0] + 1e-9) + or not bounded(ellipse[2], 0.0, 180.0)): + return False + if (type(contact.get("towed_ambiguous")) is not bool + or type(contact.get("towed_resolved")) is not bool + or (contact["towed_ambiguous"] and contact["towed_resolved"]) + or (contact["towed_ambiguous"] and ( + not bounded(contact.get("ambiguity_axis"), 0.0, 360.0) + or not bounded(contact.get("mirror_bearing"), 0.0, 360.0))) + or (contact.get("tonal_hz") is not None + and not bounded(contact["tonal_hz"], 0.1, 20000.0))): + return False echoes = sonar.get("echo_history", []) if any(not isinstance(item, dict) or not finite_number(item.get("t")) @@ -9165,6 +9198,9 @@ class Game: or ("uncertainty_deg" in point and (not finite_number(point["uncertainty_deg"]) or not 0.05 <= point["uncertainty_deg"] <= 180.0)) + or (point.get("freq_hz") is not None + and not bounded(point["freq_hz"], 0.1, 20000.0)) + or not bounded(point.get("fspeed"), 0.0, 60.0) for point in points) for points in tracks.values()): return False diff --git a/src/core/i18n.py b/src/core/i18n.py index cf755092..b8100751 100644 --- a/src/core/i18n.py +++ b/src/core/i18n.py @@ -71,6 +71,7 @@ DISPLAY_KEYS = { "KEINE DATEN": "enum.fusion.none", "KEINE FUSION": "enum.fusion.none", "BESTAETIGT": "enum.fusion.confirmed", "DIVERGENT": "enum.fusion.divergent", "MOEGLICHER GEISTERKONTAKT": "enum.fusion.ghost", + "TAS L/R?": "enum.fusion.ambiguous", }, "weapon_mode": {"DRAHT": "enum.weapon.wire", "SUCHER": "enum.weapon.seeker"}, "profile_kind": { diff --git a/src/sonar/sonar.py b/src/sonar/sonar.py index 59d837b2..0bf87677 100644 --- a/src/sonar/sonar.py +++ b/src/sonar/sonar.py @@ -88,6 +88,30 @@ def _lambert_mu_db(world, x_nm: float, y_nm: float) -> float: return SEDIMENTS[seabed(x_nm, y_nm)][3] +SOUND_SPEED_KN = config.SOUND_SPEED_M_S * 3600.0 / 1852.0 +DOPPLER_SIGMA_HZ = 0.02 +DOPPLER_MIN_QUALITY = 0.3 + + +def doppler_factor(tgt, observer) -> float: + """Received/emitted frequency ratio from the closing speed (knots).""" + dx, dy = observer.x - tgt.x, observer.y - tgt.y + distance = math.hypot(dx, dy) + if distance < 1e-6: + return 1.0 + ux, uy = dx / distance, dy / distance + speed_t = getattr(tgt, "speed", None) + if speed_t is None: + speed_t = getattr(tgt, "speed_kn", 0.0) + course_t = math.radians(getattr(tgt, "course", 0.0)) + course_o = math.radians(getattr(observer, "course", 0.0)) + speed_o = getattr(observer, "speed", 0.0) or 0.0 + vx = speed_t * math.sin(course_t) - speed_o * math.sin(course_o) + vy = -speed_t * math.cos(course_t) + speed_o * math.cos(course_o) + closing = vx * ux + vy * uy + return 1.0 + closing / SOUND_SPEED_KN + + def _surface_temperature(world) -> float: ocean = getattr(world, "ocean", None) if ocean is None: @@ -193,6 +217,14 @@ class Contact: self.tma_course = None self.tma_speed = None self.tma_quality = 0.0 + self.tma_ellipse = None # (major NM, minor NM, orientation deg) + # Towed-array left/right ambiguity: the line array cannot tell a + # bearing from its mirror about the array axis until resolved. + self.towed_ambiguous = False + self.ambiguity_axis = None # tow heading when the ambiguity began + self.mirror_bearing = None + self.tonal_hz = None # measured (Doppler-shifted) tonal + self.towed_resolved = False self.tma_seen = None self.buoy_fixes = [] # raw (t, x, y, quality), not ownship passive bearings self.buoy_reports = {} # buoy sequence -> detached measured report @@ -395,6 +427,7 @@ class Contact: or self.tma_speed is not None) and (tma_seen is None or t - tma_seen > config.SONAR_CONTACT_LOST_S): self.tma_pos = self.tma_course = self.tma_speed = None + self.tma_ellipse = None self.tma_quality = 0.0 self.tma_seen = None max_age = (config.SONAR_PING_FIX_MAX_AGE_S @@ -416,7 +449,9 @@ class Contact: key: value for key, value in self.array_observations.items() if t - value["last_seen"] <= 4.0} if len(self.array_observations) < 2: - self.fusion_status = ("NUR " + next(iter(self.array_observations)) + self.fusion_status = ("TAS L/R?" if self.towed_ambiguous + and set(self.array_observations) == {"TOWED"} + else "NUR " + next(iter(self.array_observations)) if self.array_observations else "KEINE DATEN") self.fusion_delta_deg = None self.fused_quality = max((report["quality"] for report in @@ -452,6 +487,15 @@ class Contact: self.range_seen = t self.origin = "bojenkreuzpeilung" + def tma_range_sigma_nm(self, quality: float) -> float: + """1-sigma position uncertainty: the covariance semi-major axis, never + more optimistic than the observability-based quality heuristic (the + linearized covariance is overconfident in poor geometry).""" + heuristic = max(0.1, (1.0 - quality) * 12.0) + if self.tma_ellipse is not None: + return config.clamp(max(self.tma_ellipse[0], heuristic), 0.1, 12.0) + return heuristic + def update_tma(self, sol, t: float, fixed_at: float = None): """TMA-Estimate übernehmen (nur, solange kein frischerer Ping).""" self.expire_ping_fix(t) @@ -479,10 +523,12 @@ class Contact: self.tma_speed += (sol.speed - self.tma_speed) * alpha self.tma_quality += (sol.quality - self.tma_quality) * alpha self.tma_seen = t + self.tma_ellipse = (tuple(float(v) for v in sol.ellipse) + if getattr(sol, "ellipse", None) is not None else None) + sigma = self.tma_range_sigma_nm(sol.quality) if sol.quality >= config.TMA_RANGE_MIN_QUALITY: self._publish_fix("TMA", t, t if fixed_at is None else fixed_at, - self.tma_pos[0], self.tma_pos[1], - max(0.1, (1.0 - sol.quality) * 12.0), + self.tma_pos[0], self.tma_pos[1], sigma, self.tma_quality) if self.range_source not in ("ping", "buoy") and \ sol.quality >= config.TMA_RANGE_MIN_QUALITY: @@ -491,7 +537,7 @@ class Contact: self.observed_x - self._fx, -(self.observed_y - self._fy))) % 360.0 self.range_est = math.hypot(self.observed_x - self._fx, self.observed_y - self._fy) - self.range_sigma_nm = max(0.1, (1.0 - sol.quality) * 12.0) + self.range_sigma_nm = sigma self.range_source = "tma" self.range_seen = t self.bearing_uncertainty_deg = None @@ -1139,6 +1185,8 @@ class SonarSystem: tgt, true_bearing, frigate, quality, array_mode, t) uncertainty = bearing_error_deg( array_mode, frigate.speed, quality) / math.sqrt(3.0) + if array_mode == "TOWED": + uncertainty *= self._endfire_factor(true_bearing) observations[array_mode] = dict( bearing=bearing, quality=quality, snr=s_db, last_seen=t, uncertainty_deg=uncertainty) @@ -1191,6 +1239,30 @@ class SonarSystem: c.fusion_status = "NUR " + next(iter(observations)) c.fusion_delta_deg = None c.fused_quality = quality + ambiguous = False + if bow is not None and "BOW" in observations: + # The hull array is unambiguous: it resolves the towed side. + if c.towed_ambiguous: + c.towed_ambiguous, c.towed_resolved = False, True + c.mirror_bearing = c.ambiguity_axis = None + elif set(observations) == {"TOWED"}: + axis = self.tow_heading_deg + if not c.towed_ambiguous and not c.towed_resolved: + c.towed_ambiguous, c.ambiguity_axis = True, axis + if c.towed_ambiguous and abs(config.angle_diff_deg( + axis, c.ambiguity_axis)) >= config.TAS_AMBIGUITY_RESOLVE_DEG: + # After an own turn only one side stays consistent. + c.towed_ambiguous, c.towed_resolved = False, True + c.mirror_bearing = c.ambiguity_axis = None + if c.towed_ambiguous: + mirror = (2.0 * axis - bearing) % 360.0 + # Without other evidence the display takes the starboard + # candidate; it is the true one only half of the time. + if config.angle_diff_deg(bearing, axis) < 0.0: + bearing, mirror = mirror, bearing + c.mirror_bearing = mirror + c.fusion_status = "TAS L/R?" + ambiguous = True sig = "" if c.confidence + config.SONAR_CONF_PASSIVE_PER_S * dt \ >= config.CONTACT_SIG_CONF: @@ -1203,17 +1275,23 @@ class SonarSystem: t=t, snr=s_db, bearing_uncertainty_deg=uncertainty) - # W1: Peilungs-Track (TMA-Datenbasis) + # W1: Peilungs-Track (TMA-Datenbasis). Side-ambiguous towed + # bearings stay out of TMA until the ambiguity is resolved. tr = self._tracks.setdefault(tgt.id, BearingTrack()) - tr.add(t, bearing, frigate.x, frigate.y, frigate.course, - uncertainty) + if not ambiguous and (not tr.pts or t - tr.pts[-1].t + >= config.BEARING_TRACK_MIN_INTERVAL_S): + c.tonal_hz = self._measure_tonal(tgt, frigate, quality, t) + tr.add(t, bearing, frigate.x, frigate.y, frigate.course, + uncertainty, c.tonal_hz, frigate.speed) detected_ids.add(tgt.id) listen_observation = observations.get(mode) if sample_due and listen_observation is not None: broadband = getattr(tgt, "broadband", lambda: {})() source = {"bearing": listen_observation["bearing"], "level": listen_observation["quality"], - "lines": tgt.lofar_lines(t), + "lines": [(line[0] * doppler_factor(tgt, frigate),) + + tuple(line[1:]) + for line in tgt.lofar_lines(t)], "seed": getattr(tgt, "sensor_seed", tgt.id), "spectral_gains": spectral_by_mode.get( mode, ((100.0, 1.0),))} @@ -1241,17 +1319,43 @@ class SonarSystem: if getattr(b, "mode", "PASSIVE") == "ACTIVE" and b.seq not in ping_buoys: continue dist = math.hypot(tgt.x - b.x, tgt.y - b.y) - if dist >= config.BUOY_RANGE_NM: + if dist >= config.BUOY_RANGE_NM * 1.8: continue if (hasattr(world, "sonar_path_blocked") and world.sonar_path_blocked( b.x, b.y, 5.0, tgt.x, tgt.y, getattr(tgt, "depth", 0.0))): continue - quality = config.clamp(1.0 - dist / config.BUOY_RANGE_NM, + # Passive sonar equation for the buoy hydrophone: ambient + # limited, small aperture, ray-traced path from its depth. + buoy_depth = float(getattr(b, "hydrophone_depth_m", 30.0)) + 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) + 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)) + else 0.0) + terms = equation.passive_terms( + frequency_hz=frequency, distance_nm=dist, + target_bonus=1.0 + 0.8 * (1.0 - tgt.quiet_factor()), + excess_path_loss_db=ray, + absorption_db_per_km=equation.francois_garrison_db_per_km( + frequency, _surface_temperature(world)), + legacy_absorption_db=0.0, own_range_factor=1.0, + array_range_factor=config.BUOY_RANGE_NM + / config.SONAR_PASSIVE_BASE_NM, + sea_state=float(getattr(world, "effective_sea_state", + world.sea_state)), + rain=float(getattr(world, "rain_intensity", 0.0)), + shipping_contacts=self.shipping_contacts, + hull_self_noise=False) + excess = terms.signal_excess_db + if excess <= 0.0: + continue + quality = config.clamp(excess / config.SONAR_SNR_QUALITY_SPAN_DB, .2, .9) - if tgt.depth > world.thermocline_depth_m(b.x, b.y): - quality *= .55 true_bearing = math.degrees( math.atan2(tgt.x - b.x, -(tgt.y - b.y))) % 360.0 rng = random.Random(getattr(tgt, "sensor_seed", tgt.id) * 1543 @@ -1270,6 +1374,10 @@ class SonarSystem: contact.update_buoy(observed_x, observed_y, quality, t) else: reports.append((b, bearing, quality)) + # Multi-static TMA: the buoy bearing joins the contact's + # bearing track with the buoy as the observer. + track = self._tracks.setdefault(tgt.id, BearingTrack()) + track.add(t, bearing, b.x, b.y, 0.0, error / math.sqrt(3)) contact.buoy_reports[b.seq] = dict( mode=getattr(b, "mode", "PASSIVE"), bearing=bearing, bearing_uncertainty_deg=error / math.sqrt(3), @@ -1631,10 +1739,31 @@ class SonarSystem: del self.echo_history[:-config.SONAR_ECHO_HISTORY_MAX] return c + def _measure_tonal(self, tgt, frigate, quality: float, t: float): + """Doppler-shifted frequency of the strongest tonal (None if weak).""" + if quality < DOPPLER_MIN_QUALITY: + return None + lines = [line for line in (tgt.lofar_lines(t) or ()) if line[0] > 1.0] + if not lines: + return None + frequency = max(lines, key=lambda line: (line[1], -line[0]))[0] + seed = getattr(tgt, "sensor_seed", tgt.id) + noise = (DOPPLER_SIGMA_HZ * (1.4 - 0.8 * quality) + * _correlated_uniform(seed, t, 10.0, 613)) + return frequency * doppler_factor(tgt, frigate) + noise + + def _endfire_factor(self, true_bearing: float) -> float: + """Line-array bearing accuracy degrades as 1/sqrt(sin) toward endfire + (beam broadening; Cramer-Rao ~ 1/sin of the angle off the axis).""" + off_axis = abs(math.sin(math.radians(true_bearing - self.tow_heading_deg))) + return 1.0 / math.sqrt(max(off_axis, 0.25)) + def _observed_bearing(self, tgt, true_bearing: float, frigate, quality: float, mode: str, t: float) -> float: """Peilung mit deterministisch korreliertem, glatt interpoliertem Fehler.""" err = bearing_error_deg(mode, frigate.speed, quality) + if mode == "TOWED": + err *= self._endfire_factor(true_bearing) seed = getattr(tgt, "sensor_seed", tgt.id) salt = 17 if mode == "TOWED" else 0 return (true_bearing + err * _correlated_uniform( diff --git a/src/sonar/tma.py b/src/sonar/tma.py index 0c22299c..fee9031a 100644 --- a/src/sonar/tma.py +++ b/src/sonar/tma.py @@ -12,14 +12,26 @@ Zeiten in sim-Sekunden, Distanzen in NM. import math from src.core import config +from src.sonar import tma_lm + +# A refinement replaces the grid solution only when it fits clearly better +# (or uses Doppler); flat bearing-only minima otherwise make it wander. +LM_ACCEPT_COST_RATIO = 0.8 +LM_MIN_MANOEUVRE = 0.5 +DOPPLER_OBSERVABLE_SPREAD_HZ = 0.05 class BearingPoint: - __slots__ = ("t", "bearing", "fx", "fy", "fcourse", "uncertainty_deg") + __slots__ = ("t", "bearing", "fx", "fy", "fcourse", "uncertainty_deg", + "freq_hz", "fspeed") def __init__(self, t: float, bearing: float, fx: float, fy: float, - fcourse: float, uncertainty_deg: float = None): + fcourse: float, uncertainty_deg: float = None, + freq_hz: float | None = None, fspeed: float = 0.0): self.t = t + # Measured (Doppler-shifted) tonal frequency and observer speed. + self.freq_hz = freq_hz + self.fspeed = fspeed self.bearing = bearing % 360.0 self.fx = fx self.fy = fy @@ -35,12 +47,13 @@ class BearingTrack: self.version = 0 # laeuft hoch bei jeder Aenderung -> TMA-Re-Solve-Gate def add(self, t: float, bearing: float, fx: float, fy: float, - fcourse: float, uncertainty_deg: float = None) -> None: + fcourse: float, uncertainty_deg: float = None, + freq_hz: float | None = None, fspeed: float = 0.0) -> None: if self.pts and \ t - self.pts[-1].t < config.BEARING_TRACK_MIN_INTERVAL_S: return self.pts.append(BearingPoint( - t, bearing, fx, fy, fcourse, uncertainty_deg)) + t, bearing, fx, fy, fcourse, uncertainty_deg, freq_hz, fspeed)) if len(self.pts) > config.BEARING_TRACK_MAX_PTS: self.pts.pop(0) self.version += 1 @@ -55,12 +68,23 @@ class BearingTrack: return max(abs(config.angle_diff_deg(a.fcourse, b.fcourse)) for i, a in enumerate(self.pts) for b in self.pts[i + 1:]) + def doppler_observable(self) -> bool: + """Enough frequency measurements with a real spread to fix range.""" + freqs = [p.freq_hz for p in self.pts if p.freq_hz is not None] + return (len(freqs) >= tma_lm.MIN_DOPPLER_POINTS + and max(freqs) - min(freqs) >= DOPPLER_OBSERVABLE_SPREAD_HZ) + class TMASolution: - __slots__ = ("pos", "course", "speed", "quality", "rmse_deg", "n_pts") + __slots__ = ("pos", "course", "speed", "quality", "rmse_deg", "n_pts", + "ellipse", "f0_hz") def __init__(self, pos: tuple, course: float, speed: float, - quality: float, rmse_deg: float, n_pts: int): + quality: float, rmse_deg: float, n_pts: int, + ellipse: tuple | None = None, f0_hz: float | None = None): + # (semi-major NM, semi-minor NM, orientation deg) at 1 sigma. + self.ellipse = ellipse + self.f0_hz = f0_hz self.pos = pos # (x, y) NM – Zielposition (letzte Peilung) self.course = course # Zielkurs (°) self.speed = speed # Zielfahrt (kn) @@ -173,7 +197,8 @@ def solve_tma(track: BearingTrack, return None if track.span_s() < config.TMA_MIN_SPAN_S: return None - if track.course_span_deg() < config.TMA_MIN_COURSE_CHG_DEG: + doppler = track.doppler_observable() + if track.course_span_deg() < config.TMA_MIN_COURSE_CHG_DEG and not doppler: return None max_range_nm = max_range_nm or config.TMA_MAX_RANGE_NM @@ -225,15 +250,38 @@ def solve_tma(track: BearingTrack, rmse, course, speed, pos, quality = best # Heading changes alone (including turns in place) do not resolve range. # Scale confidence by the actual departure from constant ownship velocity, - # relative to angular measurement error at the solved range. This is an - # observability heuristic, not a covariance estimate. + # relative to angular measurement error at the solved range. first, last = pts[0], pts[-1] deviation = max(math.hypot( p.fx - (first.fx + (last.fx - first.fx) * (p.t - t0) / track.span_s()), p.fy - (first.fy + (last.fy - first.fy) * (p.t - t0) / track.span_s())) for p in pts) - distance = math.hypot(pos[0] - last.fx, pos[1] - last.fy) angular_noise = math.radians(sum(p.uncertainty_deg for p in pts) / len(pts)) - quality *= min(1.0, deviation / max(1e-6, distance * angular_noise)) + + def manoeuvre_of(position): + distance = math.hypot(position[0] - last.fx, position[1] - last.fy) + return min(1.0, deviation / max(1e-6, distance * angular_noise)) + + # Levenberg-Marquardt refinement with Doppler and the state covariance; + # accepted only where the geometry (own manoeuvre or Doppler) makes range + # observable, otherwise flat minima would let it wander. + covariance = None + f0 = None + refined = tma_lm.refine(pts, course, speed, pos) + if refined is not None and ( + refined[7] or (manoeuvre_of(refined[0]) >= LM_MIN_MANOEUVRE + and refined[6] < LM_ACCEPT_COST_RATIO)): + pos, course, speed, covariance, f0, rmse = refined[:6] + quality = max(0.0, 1.0 - rmse / config.TMA_QUALITY_DB) * min( + 1.0, len(pts) / (config.TMA_MIN_PTS + 4.0)) + if covariance is None: + covariance = tma_lm.covariance_at(pts, course, speed, pos) + ellipse = (tma_lm.ellipse(covariance) if covariance is not None else None) + distance = math.hypot(pos[0] - last.fx, pos[1] - last.fy) + manoeuvre = manoeuvre_of(pos) + if doppler and ellipse is not None: + # Doppler observability: judge by the solved range uncertainty. + manoeuvre = max(manoeuvre, min(1.0, 1.0 - ellipse[0] / max(distance, 1e-3))) + quality *= manoeuvre return TMASolution(pos=pos, course=course, speed=speed, quality=quality, - rmse_deg=rmse, n_pts=len(pts)) + rmse_deg=rmse, n_pts=len(pts), ellipse=ellipse, f0_hz=f0) diff --git a/src/sonar/tma_lm.py b/src/sonar/tma_lm.py new file mode 100644 index 00000000..3d61d53c --- /dev/null +++ b/src/sonar/tma_lm.py @@ -0,0 +1,163 @@ +"""Levenberg-Marquardt refinement and covariance for bearing(-Doppler) TMA. + +The coarse grid search in ``tma.py`` finds the basin; this module refines the +constant-velocity target state (position at the newest measurement, velocity +and, when frequency measurements exist, the unshifted tonal frequency f0) +by damped Gauss-Newton on the weighted bearing and Doppler residuals, and +returns the state covariance ``(J^T W J)^-1``. + +Doppler makes range observable without an own-ship manoeuvre: the received +tonal is f = f0 (1 + v_c / c) with the closing speed v_c of the geometry. +Everything is deterministic, bounded (at most MAX_ITERATIONS) and uses no +target truth. +""" + +from __future__ import annotations + +import math + +import numpy as np + +from src.core import config + +MAX_ITERATIONS = 8 +SOUND_SPEED_KN = config.SOUND_SPEED_M_S * 3600.0 / 1852.0 +DOPPLER_SIGMA_HZ = 0.02 +MIN_DOPPLER_POINTS = 4 + + +def _bearing(tx, ty, fx, fy): + return math.degrees(math.atan2(tx - fx, -(ty - fy))) % 360.0 + + +def _residuals(state, points, t_ref, use_doppler): + x, y, vx, vy = state[:4] # NM, NM/s + f0 = state[4] if use_doppler else None + residuals = [] + for p in points: + tau = p.t - t_ref + tx, ty = x + vx * tau, y + vy * tau + dx, dy = tx - p.fx, ty - p.fy + if math.hypot(dx, dy) < 1e-3: + return None + predicted = _bearing(tx, ty, p.fx, p.fy) + residuals.append(config.angle_diff_deg(p.bearing, predicted) + / p.uncertainty_deg) + freq = getattr(p, "freq_hz", None) + if use_doppler and freq is not None: + # Closing speed: relative velocity along the line of sight. + distance = math.hypot(dx, dy) + ux, uy = -dx / distance, -dy / distance + speed = getattr(p, "fspeed", 0.0) or 0.0 + ovx = config.kn_to_nm_per_s(speed) * math.sin(math.radians(p.fcourse)) + ovy = -config.kn_to_nm_per_s(speed) * math.cos(math.radians(p.fcourse)) + closing = ((vx - ovx) * ux + (vy - ovy) * uy) * 3600.0 # kn + residuals.append((freq - f0 * (1.0 + closing / SOUND_SPEED_KN)) + / DOPPLER_SIGMA_HZ) + return np.asarray(residuals, dtype=float) + + +def _state(pos, course_deg, speed_kn): + vmag = config.kn_to_nm_per_s(speed_kn) + return [pos[0], pos[1], vmag * math.sin(math.radians(course_deg)), + -vmag * math.cos(math.radians(course_deg))] + + +def _jacobian(state, points, t_ref, use_doppler, scales): + columns = [] + for index in range(len(state)): + step = np.zeros_like(state) + step[index] = scales[index] * 1e-2 + plus = _residuals(state + step, points, t_ref, use_doppler) + minus = _residuals(state - step, points, t_ref, use_doppler) + if plus is None or minus is None: + return None + columns.append((plus - minus) / (2.0 * step[index])) + return np.stack(columns, axis=1) + + +def refine(points, course_deg: float, speed_kn: float, pos: tuple): + """Refine a grid solution. + + Returns (pos, course, speed, cov2x2, f0, rmse_deg, cost_ratio, doppler) + or None when the problem is singular. ``cost_ratio`` compares the + refined bearing cost with the starting grid solution.""" + if len(points) < 3: + return None + t_ref = points[-1].t + freqs = [p.freq_hz for p in points if getattr(p, "freq_hz", None) is not None] + use_doppler = len(freqs) >= MIN_DOPPLER_POINTS + state = _state(pos, course_deg, speed_kn) + if use_doppler: + state.append(float(np.median(freqs))) + state = np.asarray(state, dtype=float) + scales = np.array([0.05, 0.05, 2e-5, 2e-5, 0.01][:len(state)]) + residual = _residuals(state, points, t_ref, use_doppler) + if residual is None: + return None + start_cost = cost = float(residual @ residual) + lam = 1e-2 + for _ in range(MAX_ITERATIONS): + jacobian = _jacobian(state, points, t_ref, use_doppler, scales) + if jacobian is None: + return None + normal = jacobian.T @ jacobian + gradient = jacobian.T @ residual + damped = normal + lam * np.diag(np.diag(normal) + 1e-12) + try: + delta = -np.linalg.solve(damped, gradient) + except np.linalg.LinAlgError: + return None + trial = state + delta + trial_residual = _residuals(trial, points, t_ref, use_doppler) + if trial_residual is not None and trial_residual @ trial_residual < cost: + state, residual = trial, trial_residual + cost = float(residual @ residual) + lam = max(lam * 0.3, 1e-6) + else: + lam = min(lam * 10.0, 1e6) + jacobian = _jacobian(state, points, t_ref, use_doppler, scales) + if jacobian is None: + return None + try: + covariance = np.linalg.inv(jacobian.T @ jacobian) + except np.linalg.LinAlgError: + return None + if not np.all(np.isfinite(covariance)): + return None + vx, vy = state[2], state[3] + speed = math.hypot(vx, vy) * 3600.0 + course = math.degrees(math.atan2(vx, -vy)) % 360.0 + bearing_residuals = [ + config.angle_diff_deg(p.bearing, _bearing( + state[0] + vx * (p.t - t_ref), state[1] + vy * (p.t - t_ref), + p.fx, p.fy)) for p in points] + rmse = math.sqrt(sum(r * r for r in bearing_residuals) / len(bearing_residuals)) + return ((float(state[0]), float(state[1])), course, speed, + covariance[:2, :2].copy(), (float(state[4]) if use_doppler else None), + rmse, cost / max(start_cost, 1e-12), use_doppler) + + +def covariance_at(points, course_deg: float, speed_kn: float, pos: tuple): + """Position covariance of a given solution (no iteration).""" + if len(points) < 3: + return None + state = np.asarray(_state(pos, course_deg, speed_kn), dtype=float) + jacobian = _jacobian(state, points, points[-1].t, False, + np.array([0.05, 0.05, 2e-5, 2e-5])) + if jacobian is None: + return None + try: + covariance = np.linalg.inv(jacobian.T @ jacobian) + except np.linalg.LinAlgError: + return None + return covariance[:2, :2].copy() if np.all(np.isfinite(covariance)) else None + + +def ellipse(cov2x2) -> tuple[float, float, float]: + """(semi-major NM, semi-minor NM, orientation deg nautical) at 1 sigma.""" + values, vectors = np.linalg.eigh(np.asarray(cov2x2, dtype=float)) + values = np.maximum(values, 0.0) + major = vectors[:, 1] + orientation = math.degrees(math.atan2(major[0], -major[1])) % 180.0 + return math.sqrt(values[1]), math.sqrt(values[0]), orientation diff --git a/src/ui/sonar_view.py b/src/ui/sonar_view.py index baf425f1..e9d39c79 100644 --- a/src/ui/sonar_view.py +++ b/src/ui/sonar_view.py @@ -1273,6 +1273,17 @@ def _detail_rows(game, page): delta = getattr(contact, "fusion_delta_deg", None) if delta is not None: lines += [message("sonar.line.array_delta", delta=f"{delta:.1f}")] + mirror = getattr(contact, "mirror_bearing", None) + if getattr(contact, "towed_ambiguous", False) and mirror is not None: + lines += [message("sonar.line.tas_mirror", mirror=f"{mirror:05.1f}")] + tonal = getattr(contact, "tonal_hz", None) + if tonal is not None: + lines += [message("sonar.line.tonal", frequency=f"{tonal:.2f}")] + ellipse = getattr(contact, "tma_ellipse", None) + if ellipse is not None: + lines += [message("sonar.line.tma_ellipse", major=f"{ellipse[0]:.1f}", + minor=f"{ellipse[1]:.1f}", + orientation=f"{ellipse[2]:03.0f}")] rows.extend((line, DIM, 13) for line in lines) return rows if page == 5: diff --git a/tests/test_arrays_doppler_tma.py b/tests/test_arrays_doppler_tma.py new file mode 100644 index 00000000..9cc6cae9 --- /dev/null +++ b/tests/test_arrays_doppler_tma.py @@ -0,0 +1,154 @@ +"""Phase 5: array physics, Doppler, LM TMA with covariance, multistatic.""" + +import math +import random +from types import SimpleNamespace + +import numpy as np +import pytest + +from src.audio.receiver import beam_pattern_gain +from src.core import config +from src.enemies.sub import Sub +from src.ship.ship import Ship +from src.sonar import sonar as sonar_mod +from src.sonar.sonar import SonarSystem, TowState, doppler_factor +from src.sonar.tma import BearingTrack, solve_tma +from src.sonar import tma_lm +from src.world.world import World + + +def test_doppler_factor_sign_and_magnitude(): + observer = SimpleNamespace(x=0.0, y=0.0, course=0.0, speed=0.0) + closing = SimpleNamespace(x=0.0, y=-5.0, course=180.0, speed=15.0) + opening = SimpleNamespace(x=0.0, y=-5.0, course=0.0, speed=15.0) + assert doppler_factor(closing, observer) == pytest.approx( + 1.0 + 15.0 / sonar_mod.SOUND_SPEED_KN) + assert doppler_factor(opening, observer) < 1.0 + + +def _track(noise=0.3, doppler=False, manoeuvre=True, seed=4, + start=(8.0, -6.0), course=250.0, speed=7.0): + rng = random.Random(seed) + track = BearingTrack() + tx, ty = start + f0 = 50.0 + vx = config.kn_to_nm_per_s(speed) * math.sin(math.radians(course)) + vy = -config.kn_to_nm_per_s(speed) * math.cos(math.radians(course)) + fx = fy = 0.0 + own_speed = 10.0 + for index in range(40): + t = index * config.BEARING_TRACK_MIN_INTERVAL_S * 2 + own_course = (60.0 if index < 20 else 150.0) if manoeuvre else 60.0 + if index: + step = config.kn_to_nm_per_s(own_speed) * config.BEARING_TRACK_MIN_INTERVAL_S * 2 + fx += step * math.sin(math.radians(own_course)) + fy -= step * math.cos(math.radians(own_course)) + x, y = tx + vx * t, ty + vy * t + bearing = math.degrees(math.atan2(x - fx, -(y - fy))) % 360.0 + freq = None + if doppler: + target = SimpleNamespace(x=x, y=y, course=course, speed=speed) + observer = SimpleNamespace(x=fx, y=fy, course=own_course, speed=own_speed) + freq = f0 * doppler_factor(target, observer) + rng.gauss(0.0, 0.01) + track.add(t, bearing + rng.gauss(0.0, noise), fx, fy, own_course, 1.0, + freq, own_speed) + truth = (tx + vx * t, ty + vy * t) + return track, truth + + +def test_lm_tma_reports_covariance_ellipse_and_fits_truth(): + track, truth = _track() + solution = solve_tma(track) + assert solution is not None and solution.ellipse is not None + major, minor, _orientation = solution.ellipse + assert major >= minor >= 0.0 + error = math.hypot(solution.pos[0] - truth[0], solution.pos[1] - truth[1]) + assert error < 2.0 + + +def test_doppler_makes_range_observable_without_manoeuvre(): + bearing_only, _ = _track(manoeuvre=False, doppler=False, + start=(4.0, -4.0), course=270.0, speed=12.0) + assert solve_tma(bearing_only) is None + # A crossing target near its closest approach: the received tonal + # sweeps through tenths of a hertz, which fixes range. + with_doppler, truth = _track(manoeuvre=False, doppler=True, + start=(4.0, -4.0), course=270.0, speed=12.0) + solution = solve_tma(with_doppler) + assert solution is not None and solution.f0_hz == pytest.approx(50.0, abs=0.2) + assert math.hypot(solution.pos[0] - truth[0], solution.pos[1] - truth[1]) < 3.0 + + +def test_towed_endfire_broadens_bearing_error(): + sonar = SonarSystem(seed=1) + sonar.tow_heading_deg = 0.0 + assert sonar._endfire_factor(90.0) == pytest.approx(1.0) + assert sonar._endfire_factor(5.0) > 1.8 + + +def test_towed_only_contact_is_side_ambiguous_until_own_turn(): + world = World(seed=5) + frigate = Ship(250.0, 250.0, course_deg=0.0, speed_kn=6.0) + sub = Sub(253.0, 250.0, 60.0, 90.0, "diesel_alt", random.Random(5)) + sonar = SonarSystem(seed=5) + sonar.tow_state = TowState.STREAMED + sonar.tow_payout = 1.0 + sonar._tow_settle_s = config.SONAR_TOWED_SETTLE_S + sonar.tow_heading_deg = 0.0 + original = sonar._passive_range_nm + + def towed_only(tgt, dist, frigate, world, rf, mode, *args, **kwargs): + if mode == "BOW": + return 0.0 + return original(tgt, dist, frigate, world, rf, mode, *args, **kwargs) + sonar._passive_range_nm = towed_only + sonar.update(1.0, 1.0, frigate, [sub], world, mode="TOWED", + advance_mechanics=False) + contact = sonar.contacts[sub.id] + assert contact.towed_ambiguous and contact.fusion_status == "TAS L/R?" + assert abs(config.angle_diff_deg(contact.bearing, contact.mirror_bearing)) > 90.0 + assert sub.id not in sonar._tracks or not sonar._tracks[sub.id].pts + sonar.tow_heading_deg = 30.0 + sonar.update(1.0, 12.0, frigate, [sub], world, mode="TOWED", + advance_mechanics=False) + assert not contact.towed_ambiguous and contact.towed_resolved + assert contact.mirror_bearing is None + + +def test_buoy_bearings_join_the_track_as_multistatic_observers(): + world = World(seed=6) + sub = Sub(250.0, 250.0, 40.0, 90.0, "diesel_alt", random.Random(6)) + buoys = [SimpleNamespace(seq=i + 1, x=250.0 + dx, y=250.0 + dy, active=True, + mode="PASSIVE") for i, (dx, dy) in + enumerate(((-2.0, 0.0), (0.0, -2.0)))] + frigate = Ship(200.0, 200.0, speed_kn=6.0) + sonar = SonarSystem(seed=6) + sonar.update(1.0, 1.0, frigate, [sub], world, buoys=buoys, + advance_mechanics=False) + points = sonar._tracks[sub.id].pts + assert any((p.fx, p.fy) in {(b.x, b.y) for b in buoys} for p in points) + + +def test_beam_pattern_has_minus_13db_side_lobes(): + angles = np.linspace(-60.0, 60.0, 2401) + gain = beam_pattern_gain(angles, 0.0, 12.0) + assert beam_pattern_gain(6.0, 0.0, 12.0) == pytest.approx(0.5, abs=0.01) + side = gain[np.abs(angles) > 12.0].max() + assert 20 * math.log10(side) == pytest.approx(-13.3, abs=0.5) + + +def test_measured_tonal_is_doppler_shifted_and_saved(): + import json + import copy + from src.core.game import Game + game = Game(seed=5501, start_menu=False, audio_enabled=False) + for _ in range(400): + game.update(0.5) + points = [p for track in game.sonar._tracks.values() for p in track.pts] + state = json.loads(json.dumps(game.save_state())) + restored = Game(seed=1, start_menu=False, audio_enabled=False) + assert restored._load_save_data(copy.deepcopy(state)) + assert restored.save_state()["sonar"]["tracks"] == state["sonar"]["tracks"] + if points: + assert all(p.fspeed >= 0.0 for p in points) diff --git a/tests/test_audio_coherence.py b/tests/test_audio_coherence.py index e7d39ac4..a17af227 100644 --- a/tests/test_audio_coherence.py +++ b/tests/test_audio_coherence.py @@ -8,7 +8,7 @@ import pygame import pytest from src.audio.engine import AudioEngine -from src.audio.receiver import AcousticReceiver, directional_gain +from src.audio.receiver import AcousticReceiver, beam_pattern_gain def update(receiver, sources=(), bearing=0, **kwargs): @@ -128,7 +128,7 @@ def test_scan_is_actual_unsteered_power_not_presence_or_listening_bearing(lines, np.testing.assert_array_equal(on.broadband, off.broadband) signal = on.samples.astype(float) - background.samples expected = (np.mean(signal**2) / .25**2 - * directional_gain(np.arange(180) * 2, 0, 24)**2) + * beam_pattern_gain(np.arange(180) * 2, 0, 24)**2) np.testing.assert_allclose(np.array(on.broadband) - background.broadband, expected, atol=2e-9) if not lines or all(line[1] == 0 for line in lines): diff --git a/tests/test_review_performance.py b/tests/test_review_performance.py index 9c42e9c8..3bfc5274 100644 --- a/tests/test_review_performance.py +++ b/tests/test_review_performance.py @@ -134,6 +134,8 @@ def test_tma_precomputes_once_per_solve_and_preserves_tie_order(monkeypatch): return 1.0, course, speed, (260.0, 230.0), .5 monkeypatch.setattr(tma, "_try_candidate", tied) + # Grid tie order only: keep the LM refinement out of this synthetic tie. + monkeypatch.setattr(tma.tma_lm, "refine", lambda *args: None) result = tma.solve_tma(track) assert (result.course, result.speed) == (0, 0.0) assert calls[:240] == [(course, speed) for course in range(0, 360, 15)