Phase 11: radar equation, antenna scan, ESM amplitude, HFDF, lookout

Radar: SNR ~ sigma/R^4 anchored so the nominal range is the Pd = 0.5 point
for a broadside target; Swerling-1 behind a 16-cell CA-CFAR; GIT-type sea
clutter (+3 dB per sea state, CNR ~ R^-3); two-way rain attenuation; aspect
as RCS. The antenna turns in simulation time (phase and pending sweep are
saved) and a contact gets one deterministic look only when the beam swept
it. Missile noise jammers are solved from their burn-through range (JNR ~
R^-2). The CIWS search/track radar holds missiles inside 3 NM. Hostile
platform radars use the same Pd = 0.5 range.

ESM: one-way level vs power class, main beam once per revolution and side
lobes at -25 dB, peak level, measured scan period (drives the LIVE window)
and a range estimate from the best candidate's power class (ELOKA page and
Remote Crew projection).

HFDF: boats pick OWF = 0.85 MUF for their shore path; ground-wave range
falls with frequency, sky wave beyond the skip distance with doubled
bearing error; frequency and mode are published on the observation.

Lookout: Koschmieder contrast, Blackwell threshold vs angular size, optical
horizon, whitecap clutter for sea-level targets and a moon-phase night.

Calibration gains an air-defence section (impact time, CIWS and chaff leak)
recorded on the 1.0.0 tree; all 77 metrics are within tolerance.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
db9979andClaude Opus 5.5 committed 2026-09-23 20:57:07 +02:00
1 parent 9d8e15c8c7
commit 2f3b0f21b2
40 files changed
+1095 -177

No files matched your search

+2
View File
@@ -1074,6 +1074,8 @@
["bearing", unit(row.bearing, "\u00b0", 0)], ["bearing_uncertainty", unit(row.bearing_uncertainty_deg, "\u00b0")],
["frequency", unit(row.frequency_hz, "Hz", 0)], ["frequency_band", row.frequency_band.toUpperCase().replace("_", "/")], ["prf", unit(row.prf_hz, "Hz", 0)],
["modulation", row.modulation], ["quality", number(row.quality, 2)], ["age", unit(row.age_s, "s", 0)],
["signal_level", unit(row.signal_db, "dB", 0)], ["range_estimate", row.range_estimate_nm === null ? t("station_none") : unit(row.range_estimate_nm, "NM", 0)],
["scan_period", row.scan_period_s === null ? t("station_none") : unit(row.scan_period_s, "s", 1)],
["radar_type", row.radar_type || t("station_none")], ["threat", row.threat],
["synthetic_assumption", yesNo(row.synthetic_assumption)],
["jamming_effectiveness", row.jamming_effectiveness === null ? t("station_none") : number(row.jamming_effectiveness, 2)],
+11 -3
View File
@@ -1936,10 +1936,10 @@
"help.note.nato": "NATO-Rahmen: Freund blau, Neutral gruen, Feind rot, Unbekannt gelb.",
"help.note.ciws": "CIWS: automatisch abfangend < 1.5 NM (begrenzt).",
"help.note.jammer": "JAMMER-ASMs: jenseits 20 NM nur HOJ-Peilung (Bearing-only).",
"help.note.clutter": "Radarclutter und Messstoerung beginnen erst bei Seegang 5.",
"help.note.clutter": "Die Antenne dreht alle 4 s; Seegangsclutter w\u00e4chst mit dem Seegang und Regen d\u00e4mpft, daher kann ein Kontakt einen Umlauf verfehlen.",
"help.note.chaff": "Chaff: Rakete bricht ab (40 %) oder wird kurz blind.",
"help.note.air_defense": "Erst Chaff + Man\u00f6ver, dann ESSM gezielt. VLS-Zellen sind knapp.",
"help.note.hfdf": "HFDF: Peilung (\u00b18\u00b0) sendender U-Boote (Schnorchel, HF).",
"help.note.hfdf": "HFDF: Peilung und Frequenz sendender U-Boote (\u00b18\u00b0 Bodenwelle, \u00b116\u00b0 Raumwelle).",
"help.note.teletype": "Teletype: HQ-Bulletins, Wetter, ROE-\u00c4nderungen.",
"help.note.hfdf_map": "Protokollierte Peilstriche und Kreuzpeilungen erscheinen auf der Karte.",
"help.note.hfdf_tactic": "HFDF-Peilung + Sonar-Peilung -> Kreuzpeilung zur Positionssch\u00e4tzung.",
@@ -3243,5 +3243,13 @@
"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}"
"sonar.line.tma_ellipse": "TMA 1-Sigma {major} x {minor} sm, Achse {orientation}",
"eloka.field.signal": "Pegel / Entf.-Schaetzung / Umlauf",
"eloka.value.signal": "+{level} dB / ~{range} sm / {scan}s",
"radio.hfdf.frequency": "{frequency} kHz {mode}",
"radio.hfdf.mode.GROUND": "Bodenwelle",
"radio.hfdf.mode.SKY": "Raumwelle",
"commander.web.signal_level": "Signalpegel",
"commander.web.range_estimate": "Entfernungsschaetzung",
"commander.web.scan_period": "Antennenumlauf"
}
+11 -3
View File
@@ -1936,10 +1936,10 @@
"help.note.nato": "NATO frames: friendly blue, neutral green, hostile red, unknown yellow.",
"help.note.ciws": "CIWS intercepts automatically inside 1.5 NM (limited ammunition).",
"help.note.jammer": "Jammer ASMs beyond 20 NM provide only a HOJ bearing.",
"help.note.clutter": "Radar clutter and measurement interference begin at sea state 5.",
"help.note.clutter": "The antenna sweeps every 4 s; sea clutter grows with sea state and rain attenuates, so a contact may miss a sweep.",
"help.note.chaff": "Chaff makes a missile break lock (40%) or blinds it briefly.",
"help.note.air_defense": "Use chaff and maneuver first, then engage with ESSM. VLS cells are scarce.",
"help.note.hfdf": "HFDF gives bearings (+/-8 degrees) to transmitting submarines (snorkel, HF).",
"help.note.hfdf": "HFDF gives bearings and frequency of transmitting submarines (+/-8 degrees ground wave, +/-16 sky wave).",
"help.note.teletype": "Teletype carries HQ bulletins, weather, and ROE changes.",
"help.note.hfdf_map": "Logged bearing lines and cross-fixes appear on the chart.",
"help.note.hfdf_tactic": "Combine an HFDF bearing with a sonar bearing for a position cross-fix.",
@@ -3243,5 +3243,13 @@
"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}"
"sonar.line.tma_ellipse": "TMA 1-sigma {major} x {minor} NM, axis {orientation}",
"eloka.field.signal": "Level / range est. / scan",
"eloka.value.signal": "+{level} dB / ~{range} NM / {scan}s",
"radio.hfdf.frequency": "{frequency} kHz {mode}",
"radio.hfdf.mode.GROUND": "ground wave",
"radio.hfdf.mode.SKY": "sky wave",
"commander.web.signal_level": "Signal level",
"commander.web.range_estimate": "Range estimate",
"commander.web.scan_period": "Antenna scan period"
}
+1 -1
View File
@@ -18,7 +18,7 @@ Seite 1 ist eine freie Karte über die volle Höhe mit allen veröffentlichten T
- **Überwasserradar:** 30 sm, begrenzt durch Radarhorizont (20-m-Mast) und Zielhöhe; getauchte U-Boote sind unsichtbar.
- **Luftradar:** 100 sm für Flugzeuge und Seezielflugkörper (ASM).
- Wetter verringert die Reichweite; ab Seegang 5 nehmen Clutter und Messfehler zu. Regen kostet weitere Reichweite.
- Die Antenne dreht sich alle 4 s einmal: ein Kontakt wird nur aktualisiert, wenn der Strahl über ihn streicht, und jeder Umlauf erfasst ihn mit einer Wahrscheinlichkeit, die mit der Entfernung sinkt (50 % bei Nennreichweite für ein Schiff in Breitseite; Ziele mit spitzem Aspekt werden später gesehen, schwankende Echos können einen Umlauf verfehlen). Seegangsclutter wächst mit dem Seegang (etwa -5 % bei Seegang 4, -25 % bei 6), Regen dämpft das Echo (-10 % Überwasser, -20 % Luft); ab Seegang 5 nehmen Messfehler zu. Innerhalb 3 sm hält das Such-/Folgeradar des CIWS einen anfliegenden Flugkörper ununterbrochen, solange das CIWS freigegeben ist.
- **AIS:** zivile Schiffe senden Kurs und Fahrt alle 2-10 s (vor Anker alle 3 min) und ihren Namen etwa alle 6 min. Der UKW-Empfänger hört sie nur in Sichtlinie (etwa 20 NM). Ein Radartrack eines Zivilschiffs zeigt Name und Kurs erst, wenn die passende AIS-Meldung empfangen wurde; Radar allein liefert nur die Position. Optionaler Live-AIS/ADS-B-Verkehr ist von simuliertem Verkehr nicht unterscheidbar.
- **Fusion:** 2-8 Rohmeldungen markieren (`Leertaste`) und zu einem Bedienertrack fusionieren (`L`); `Shift+L` löst ihn auf.
- **Unterdrückung:** `Entf` blendet eine Meldung lokal aus; `H` zeigt unterdrückte Meldungen wieder.
+1 -1
View File
@@ -18,7 +18,7 @@ Page 1 is a full-height free chart with all published tracks; page 2 is the targ
- **Surface radar:** 30 NM, limited by the radar horizon (20 m mast) and target height; submerged submarines are invisible.
- **Air radar:** 100 NM for aircraft and anti-ship missiles (ASM).
- Weather reduces range; from sea state 5 clutter and measurement errors increase. Rain costs further range.
- The antenna turns once every 4 s: a contact is updated only when the beam sweeps past it, and each sweep detects it with a probability that falls with range (50 % at the nominal range for a broadside ship; bow-on targets are seen later, fluctuating echoes can miss a sweep). Sea clutter grows with sea state (about -5 % at sea state 4, -25 % at 6) and rain attenuates the echo (-10 % surface, -20 % air); from sea state 5 measurement errors increase. Inside 3 NM the CIWS search/track radar holds an inbound missile continuously while CIWS is released.
- **AIS:** civilian ships broadcast course and speed every 2-10 s (3 min at anchor) and their name about every 6 min. The VHF receiver hears them only within line of sight (about 20 NM). A radar track of a civilian shows name and course only after the matching AIS report has been received; radar alone gives position only. Optional live AIS/ADS-B traffic is indistinguishable from simulated traffic.
- **Fusion:** mark 2-8 raw reports (`Space`) and fuse them (`L`) into one operator track; `Shift+L` dissolves it.
- **Suppression:** `Delete` hides a report locally; `H` shows suppressed reports again.
+3 -2
View File
@@ -19,7 +19,8 @@ Seite 1 listet aktuelle HFDF-Signale und das Peilprotokoll; Seite 2 ist der Fern
Pos B *------------------/
```
- Der Peilfehler beträgt +/-8 Grad; Signale älter als 30 s lassen sich nicht mehr protokollieren.
- Der Peilfehler beträgt +/-8 Grad bei Bodenwelle und +/-16 Grad bei Raumwelle; Signale älter als 30 s lassen sich nicht mehr protokollieren.
- Jedes Signal zeigt Frequenz und Ausbreitung. Ein U-Boot, das eine ferne Landstation ruft, wählt tagsüber eine hohe Frequenz (Bodenwelle bis etwa 95 sm hörbar) und nachts eine niedrigere (etwa 150 sm). Jenseits der Sprungdistanz, einige hundert sm entfernt, kommt stattdessen die Raumwelle an.
- Protokollierte Linien und Kreuzpeilungen erscheinen auf den Karten von Brücke, Waffenzentrale und Helikopter.
- Eine zweite Peilung desselben Signals ergibt eine Kreuzpeilung, wenn sie mindestens 1 sm entfernt von der ersten und innerhalb von 300 s genommen wird.
- Der Fernschreiber bringt außerdem alle 30 Minuten den Wetterbericht und HQ-Meldungen (Bedrohungswarnungen, ROE FREI).
@@ -41,4 +42,4 @@ Seite 1 listet aktuelle HFDF-Signale und das Peilprotokoll; Seite 2 ist der Fern
## Nicht modelliert {#radio-limits}
- Keine eigenen Funksprüche oder Meldungen an das HQ; kein Fernmeldeplan und keine Kryptierung.
- Keine Frequenzabstimmung: HFDF listet die erfassten Signale direkt.
- Keine Frequenzabstimmung: HFDF überwacht das ganze KW-Band und listet die erfassten Signale mit ihrer Frequenz.
+3 -2
View File
@@ -19,7 +19,8 @@ Page 1 lists current HFDF signals and the bearing log; page 2 is the teletype wi
pos B *------------------/
```
- Bearing error is +/-8 degrees; signals older than 30 s can no longer be logged.
- Bearing error is +/-8 degrees for a ground wave and +/-16 degrees for a sky wave; signals older than 30 s can no longer be logged.
- Each signal shows its frequency and propagation. A submarine calling a distant shore station picks a high frequency by day (ground wave heard to about 95 NM) and a lower one at night (about 150 NM). Beyond the skip distance, several hundred NM away, the sky wave arrives instead.
- Logged lines and cross-fixes appear on the charts of Bridge, Weapons and Helicopter.
- A second bearing of the same signal gives a cross-fix if it is taken at least 1 NM away from the first and within 300 s.
- The teletype also carries the weather bulletin every 30 minutes and HQ messages (threat warnings, ROE FREE).
@@ -41,4 +42,4 @@ Page 1 lists current HFDF signals and the bearing log; page 2 is the teletype wi
## Not modelled {#radio-limits}
- No own radio transmissions or reports to HQ; no communication plan or crypto.
- No frequency tuning: HFDF lists the detected signals directly.
- No frequency tuning: HFDF monitors the whole HF band and lists the detected signals with their frequency.
+1
View File
@@ -21,6 +21,7 @@ Seite 1 listet die Erfassungen; Seite 2 zeigt die Belege für die gewählte Erfa
```
- Die Peilgenauigkeit beträgt etwa +/-3 Grad. Erfassungen sind Peilungen, keine Positionen.
- Ein drehendes Suchradar trifft die ESM-Antenne einmal je Umlauf mit der Hauptkeule; seine Nebenkeulen sind nur aus der Nähe hörbar. Die Belegseite zeigt den Spitzenpegel, eine Entfernungsschätzung unter Annahme der Leistungsklasse des besten Kandidaten (ein falscher Kandidat ergibt eine falsche Entfernung) und die gemessene Antennenumlaufzeit.
- Kandidaten werden nur aus beobachteter Frequenz, PRF und Modulation gerankt. Ein Gleichstand ist keine Identifizierung.
- Die Korrelation mit Radar- oder Sonartracks nutzt vereinbare Zeit, Peilung und beobachtete Position, nie verborgene Identität.
- ESM läuft aus der OPZ-Abteilung: eine zerstörte OPZ legt es lahm.
+1
View File
@@ -21,6 +21,7 @@ Page 1 lists intercepts; page 2 shows the evidence for the selected intercept (f
```
- Bearing accuracy is about +/-3 degrees. Intercepts are bearings, not positions.
- A rotating search radar reaches the ESM antenna with its main beam once per revolution; its side lobes are heard only close in. The evidence page shows the peak signal level, a range estimate that assumes the power class of the best candidate (a wrong candidate gives a wrong range) and the measured antenna scan period.
- Candidates are ranked only from observed frequency, PRF and modulation. A tie is not an identification.
- Correlation with radar or sonar tracks uses compatible time, bearing and observed position, never hidden identity.
- ESM runs from the operations compartment: a destroyed operations room disables it.
+5 -5
View File
@@ -21,11 +21,11 @@ Alle Werte sind die Standardwerte der aktuellen Spielversion. Eigene Schwierigke
| 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 |
| Luftradar | 100 sm | Flugzeuge und Flugkörper |
| ESM | 150 sm | +/-3 Grad Peilung |
| HFDF | 120 sm | +/-8 Grad Peilung |
| Ausguck | 12 sm Überwasser, 5 sm aufgetauchtes U-Boot, 20 sm Luft | x0,35 bei Nacht |
| Überwasserradar | 30 sm (50 % je Umlauf) | 4 s Antennenumlauf; Radarhorizont; keine getauchten Kontakte |
| Luftradar | 100 sm (50 % je Umlauf) | Flugzeuge und Flugkörper; Störer werden aus der Nähe durchbrannt |
| ESM | 150 sm (Hauptkeule) | +/-3 Grad Peilung; Pegel und Entfernungsschätzung |
| HFDF | etwa 95-150 sm Bodenwelle | +/-8 Grad Peilung (Raumwelle +/-16) |
| Ausguck | 12 sm Überwasser, 5 sm aufgetauchtes U-Boot, 20 sm Luft | x0,25 (Neumond) bis x0,45 (Vollmond) bei Nacht; Nebel und Seegang verkürzen |
## Waffen und Gegenmaßnahmen {#ref-weapons}
+5 -5
View File
@@ -21,11 +21,11 @@ All values are the defaults of the current game version. Custom difficulty and m
| 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 |
| Air radar | 100 NM | aircraft and missiles |
| ESM | 150 NM | +/-3 deg bearing |
| HFDF | 120 NM | +/-8 deg bearing |
| Lookout | 12 NM surface, 5 NM surfaced sub, 20 NM air | x0.35 at night |
| Surface radar | 30 NM (50 % per sweep) | 4 s antenna revolution; radar horizon; no submerged contacts |
| Air radar | 100 NM (50 % per sweep) | aircraft and missiles; jammers burn through close in |
| ESM | 150 NM (main beam) | +/-3 deg bearing; level and range estimate |
| HFDF | about 95-150 NM ground wave | +/-8 deg bearing (sky wave +/-16) |
| Lookout | 12 NM surface, 5 NM surfaced sub, 20 NM air | x0.25 (new moon) to x0.45 (full moon) at night; fog and sea state reduce |
## Weapons and countermeasures {#ref-weapons}
+6 -2
View File
@@ -221,8 +221,12 @@ Die ELOKA-Auffassungszeile von v2 enthält zusätzlich die abgeleiteten Felder
`signal_state` (`LIVE`, `RECENT`, `MEMORY` oder `UNCONFIRMED`) und `operational`.
Die Browserfilter für Status, Mindestbedrohung und Frequenzband bleiben
clientlokal und verwenden für Auffassungsliste, Kontakte, Scope und barrierefreie
Textalternative dieselbe Teilmenge. Aktive ECM-Ziele bleiben sichtbar. Entfernung
und verborgene Senderidentität werden weder projiziert noch filterbar gemacht.
Textalternative dieselbe Teilmenge. Aktive ECM-Ziele bleiben sichtbar. Die Zeilen
tragen außerdem den gemessenen Spitzenpegel `signal_db`, die gemessene
Antennenumlaufzeit `scan_period_s` (oder null) und eine `range_estimate_nm`, die
nur aus diesem Pegel und der Leistungsklasse der besten Katalog-Hypothese
abgeleitet ist (oder null); wahre Entfernung und verborgene Senderidentität werden
weder projiziert noch filterbar gemacht.
Befehle enthalten `protocol`, kryptografische Anfrage-ID, Clientsequenz, Station,
Stations- und Aktivgeneration, Weltsitzung/-epoche, Ressourcenrevision, Aktion und
+5 -2
View File
@@ -188,8 +188,11 @@ The ELOKA v2 intercept row additionally carries derived `signal_state`
(`LIVE`, `RECENT`, `MEMORY`, or `UNCONFIRMED`) and boolean `operational` fields.
Browser status, minimum-threat, and frequency-band filters are client-local and
apply one identical subset to the intercept list, contacts, scope, and accessible
text alternative. Active ECM targets remain visible. No range or hidden emitter
identity is projected or filterable.
text alternative. Active ECM targets remain visible. Rows also carry the
measured peak `signal_db`, the measured antenna `scan_period_s` (or null) and a
`range_estimate_nm` derived only from that level and the power class of the
best catalog hypothesis (or null); no true range or hidden emitter identity is
projected or filterable.
Commands carry protocol, cryptographic request ID, client sequence, station,
station and active generations, world session/epoch, resource revision, action,
+6 -6
View File
@@ -307,13 +307,13 @@ All closed in Phase 9:
| Gap | Current behaviour | Would need |
|-----|-------------------|------------|
| **No radar equation** | Detection = distance < range × aspect; no radar cross-section vs range, no pulse parameters, no clutter | Radar range equation: `R_max = (P_t·G²·λ²·σ)/(P_min·(4π)³·k·T·B)`; clutter rejection; sea-spike, ground-clutter |
| **No scan rate / PPI dynamics** | Tracks appear/disappear per 0.5 s epoch; no sweep angle | Radar sweep: contacts only visible when beam sweeps past; afterglow decay; PPI refresh |
| **No ECCM / jamming effect on radar** | Jamming only produces a HOJ bearing (bearing-only, no range) | Radar jamming: range-gate pull-off, angle deception, burn-through; radar self-protection |
| **ESM: no signal strength** | Detection is binary (in range or not); no amplitude | Signal level vs distance; frequency-agile waveform detection; dwell time |
| **HFDF: no frequency** | Only bearing; no frequency measurement | HF frequency → rough distance via ionospheric model; or at least frequency for emitter ID |
| ~~**No radar equation**~~ | **Closed (Phase 11).** `src/sensors/radar.py`: SNR ~ sigma/R^4 anchored so the nominal range is the Pd = 0.5 point for a broadside target; Swerling-1 target behind a 16-cell CA-CFAR (exact closed form, Pfa 1e-6); GIT-type sea clutter (+3 dB per sea state, CNR ~ R^-3; air search with MTI); two-way rain attenuation; aspect enters as RCS (aspect^4). Hostile platform radars use the same Pd = 0.5 range. Anchors reproduce the 1.0.0 weather/rain losses (calibration harness). | — |
| ~~**No scan rate / PPI dynamics**~~ | **Closed (Phase 11).** The antenna turns in simulation time (90 deg/s, phase and pending sweep saved); a contact gets one look only when the beam passed its bearing since the previous publication; one deterministic (`detrand`) detection draw per look; the PPI sweep line is the saved antenna phase. | — |
| ~~**No ECCM / jamming effect on radar**~~ | **Closed (Phase 11).** Self-screening noise jammer as JNR ~ R^-2 solved from the profiled burn-through range; skin detection uses SINR = S/(N + C + J), so the echo emerges inside burn-through (HOJ bearing outside). Deception jamming (RGPO/angle) is out of scope: missiles carry noise jammers only. | — |
| ~~**ESM: no signal strength**~~ | **Closed (Phase 11).** One-way level 20 log10(R_class/R); rotating search radars reach the mast with the main beam once per revolution (2-5 s by role, 0.5 s dwell), side lobes at -25 dB; peak-hold level, measured scan period (LIVE window follows it) and a range estimate from the best candidate's power class, shown at ELOKA and in Remote Crew. | — |
| ~~**HFDF: no frequency**~~ | **Closed (Phase 11).** `src/sensors/hfdf.py`: the boat picks OWF = 0.85 MUF for its shore path (foF2 day/night, F2 height 300 km); ground-wave range falls with frequency (anchored 120 NM at 15 MHz); sky wave only beyond the skip distance with doubled bearing error; frequency and mode are published on the observation. | — |
| ~~**No AIS decoding**~~ | **Closed (Phase 0).** `src/sensors/ais.py` is a simulated own-ship AIS receiver: ITU-R M.1371 class-A dynamic reports (COG/SOG every 2-10 s, 3 min at anchor) and static reports (name every 6 min), received only inside VHF line of sight and not through land. Radar observations of civilians no longer carry the true name/course (an observation-boundary leak); both come from the latest decoded report. MMSI is deliberately not shown to the player, so live and simulated traffic stay indistinguishable. Decoded reports are saved (save v12). | — |
| **Lookout: no silhouette / size** | Visual detection is a range gate; no target size effect | Target height, silhouette against sea/sky; searchlight; smoke |
| ~~**Lookout: no silhouette / size**~~ | **Closed (Phase 11).** `src/sensors/visual.py`: Koschmieder contrast decay with meteorological visibility, Blackwell-type threshold vs angular size (target height), optical horizon (eye 18 m), whitecap clutter for sea-level targets, night threshold interpolated by lunar illumination (seeded lunar age advancing with sim time). C0 anchored to the 1.0.0 day ranges; searchlight and smoke are out of scope. | — |
### 8.3 Data structures touched
+3
View File
@@ -720,6 +720,9 @@ def _eloka(game, rows, esm_refs, candidate_refs):
jamming=channel is not None),
ambiguous=False if analysis is None else analysis.ambiguous,
synthetic_assumption=bool(track.synthetic_assumption),
signal_db=_number(track.signal_db),
range_estimate_nm=_number(game.eloka_range_estimate(track)),
scan_period_s=_number(track.revisit_s) if track.revisit_s > 0.0 else None,
auto_jamming=bool(game.ecm_jammer.auto_enabled),
jamming=channel is not None,
jamming_effectiveness=(None if channel is None else
+168 -53
View File
@@ -18,6 +18,7 @@ from src.audio.receiver import AcousticReceiver
from src.audio.preview import unit_sonar_preview
from src.commander.local import CommanderConsole
from src.core import config
from src.core import detrand
from src.core.autocrew import AutocrewController, station_key
from src.core.commands import (MAP_STATIONS, STATION_PAGES, event_feed_heading,
station_page_step, toggle_tas)
@@ -36,6 +37,9 @@ 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.sensors import radar as radar_physics
from src.sensors import visual as visual_physics
from src.sensors import hfdf as hf_physics
from src.sonar import equation as sonar_equation
from src.sonar import propagation as sonar_propagation
from src.physics import torpedo_dyn
@@ -70,6 +74,7 @@ from src.sensors.esm import (
scan_for_signals,
analyze_signal,
correlate_observations,
estimated_range_nm,
filter_and_sort_tracks,
rank_emitters,
valid_esm_state,
@@ -248,6 +253,14 @@ _ECO_REFRESH_EVENTS = frozenset(
TORPEDO_WAKE_VISIBLE_NM = 1.5
TORPEDO_WAKE_VISIBLE_DEPTH_M = 15.0
# Close-in weapon system: own Ku-band search/track radar that keeps an
# inbound missile under continuous track inside this range.
CIWS_TRACK_RANGE_NM = 3.0
# Koschmieder lookout model anchored to the 1.0.0 day/calm/clear ranges.
LOOKOUT_MODEL = visual_physics.LookoutModel(
{"SURFACE": config.LOOKOUT_SURFACE_RANGE_NM, "SUB": config.LOOKOUT_SUB_RANGE_NM,
"FLG": config.LOOKOUT_AIR_RANGE_NM, "TORP": TORPEDO_WAKE_VISIBLE_NM},
config.WEATHER_VISIBILITY_MAX_NM)
class Game:
@@ -657,6 +670,10 @@ class Game:
self.hfdf_fixes = {}
self.ciws_ammo = self._air_defense_loadout["ciws"]["ammo"]
self.ciws_cooldown_s = 0.0
# Rotating search antenna in simulation time (saved): targets are
# looked at only when the beam sweeps past them.
self.radar_scan_phase = 0.0
self.radar_scan_pending_deg = 0.0
self.ciws_authorized = True # session-only fire-release gate, OPZ "I"
self.aa_ammo = self._air_defense_loadout["aa_gun"]["ammo"]
self.aa_cooldown_s = 0.0
@@ -3214,22 +3231,52 @@ class Game:
return config.clamp(getattr(self.world, "rain_intensity", 0.0), 0.0, 1.0)
def radar_effective_range(self, domain: str) -> float:
loss = (config.RADAR_AIR_WEATHER_LOSS if domain == "air"
else config.RADAR_SURFACE_WEATHER_LOSS)
"""Range of Pd = 0.5 per look for a reference target (radar equation
with sea clutter, rain attenuation and console damage)."""
nominal = (config.RADAR_AIR_RANGE_NM if domain == "air"
else config.RADAR_SURFACE_RANGE_NM)
rain_loss = (config.RADAR_RAIN_AIR_LOSS if domain == "air"
else config.RADAR_RAIN_SURFACE_LOSS)
conditions = self._radar_conditions()
return nominal * radar_physics.detection_fraction(
domain, conditions["sea_state"], conditions["rain_intensity"],
nominal, conditions["capability"])
def _asm_jammer_to_noise(self, asm, distance: float) -> float:
"""Self-screening noise jammer of a missile, solved from its profiled
burn-through range (J/S ~ R^2): inside it the skin echo wins."""
if not asm.jammer:
return 0.0
burn_through = asm.profile["jam_break_nm"]
skin = radar_physics.snr(burn_through, config.RADAR_AIR_RANGE_NM)
return radar_physics.jammer_to_noise(distance, burn_through, skin)
def _radar_conditions(self) -> dict:
# Damage to the operations room (radar consoles, power) degrades the
# radar continuously rather than only at destruction.
capability = (1.0 if not self.damage.station_degraded("opz")
else 0.5 + 0.5 * self.damage.capability("opz"))
return (nominal * (1.0 - loss * self.radar_weather_severity())
* (1.0 - rain_loss * self.radar_rain_severity()) * capability)
return dict(
sea_state=getattr(self.world, "effective_sea_state", self.world.sea_state),
rain_intensity=self.radar_rain_severity(), capability=capability)
def _radar_look(self, domain: str, key: int, distance: float, bearing: float,
*, swept_deg: float, rcs_factor: float = 1.0,
jnr: float = 0.0) -> bool:
"""One antenna look: the beam must have passed the bearing and the
Swerling-1/CFAR detector must declare the echo (deterministic draw)."""
if not radar_physics.swept(bearing, self.radar_scan_phase, swept_deg):
return False
nominal = (config.RADAR_AIR_RANGE_NM if domain == "air"
else config.RADAR_SURFACE_RANGE_NM)
sinr = radar_physics.sinr(distance, nominal, rcs_factor=rcs_factor,
domain=domain, jnr=jnr,
**self._radar_conditions())
tick = math.floor(self.sim_t * 4.0 + 1e-6)
return (detrand.u01(self.seed, "radar-look-" + domain, key, tick)
< radar_physics.pd_from_sinr(sinr))
def radar_sweep_bearing(self) -> float:
"""Nautische Peilung: zunehmende Werte drehen Nord -> Ost rechtsherum."""
return (self._t * config.RADAR_SWEEP_DEG_PER_S) % 360.0
return self.radar_scan_phase
def toggle_helo(self) -> None:
if self.helo.airborne:
@@ -3664,20 +3711,27 @@ class Game:
value = f"{self.seed}:{namespace}:{identity}".encode("utf-8")
return hashlib.blake2b(value, digest_size=8).hexdigest().upper()
def moon_illumination(self) -> float:
"""Illuminated lunar fraction; the lunar age is seeded per world and
advances with simulation time."""
age = (detrand.u01(self.seed, "lunar-age") * visual_physics.SYNODIC_MONTH_D
+ self.sim_t / 86400.0)
return visual_physics.moon_illumination(age)
def _lookout_observe(self, actor, namespace: str, kind: str,
base_range_nm: float, seed: int) -> None:
seed: int, altitude_m: float | None = None) -> None:
import random
if self.world.is_night():
base_range_nm *= config.LOOKOUT_NIGHT_FACTOR
base_range_nm *= max(0.0, 1.0 - getattr(
self.world, "effective_sea_state", self.world.sea_state)
* config.LOOKOUT_SEA_STATE_LOSS)
base_range_nm = min(base_range_nm, getattr(
self.world, "visibility_nm", config.WEATHER_VISIBILITY_MAX_NM))
dx, dy = actor.x - self.ship.x, actor.y - self.ship.y
distance = math.hypot(dx, dy)
if (distance > base_range_nm or self.world.land_blocks_line(
margin = LOOKOUT_MODEL.margin(
kind, distance,
visibility_nm=getattr(self.world, "visibility_nm",
config.WEATHER_VISIBILITY_MAX_NM),
night=self.world.is_night(), illumination=self.moon_illumination(),
sea_state=getattr(self.world, "effective_sea_state", self.world.sea_state),
altitude_m=altitude_m)
if (margin < 1.0 or self.world.land_blocks_line(
self.ship.x, self.ship.y, actor.x, actor.y)):
return
bearing = math.degrees(math.atan2(dx, -dy)) % 360.0
@@ -3688,8 +3742,8 @@ class Game:
config.LOOKOUT_BEARING_ERR_DEG)) % 360.0
measured_range = max(0.0, distance * (1.0 + rng.uniform(
-config.LOOKOUT_RANGE_ERR_FRAC, config.LOOKOUT_RANGE_ERR_FRAC)))
quality = config.clamp(.95 - .45 * distance / max(base_range_nm, .01),
.5, .95)
# Contrast margin: just above threshold is a doubtful sighting.
quality = config.clamp(.5 + .45 * (1.0 - 1.0 / margin), .5, .95)
identity = getattr(actor, "id", getattr(actor, "seq", 0))
self.air_picture.observe(
track_id="L-" + self._observation_key(namespace, identity),
@@ -3711,44 +3765,46 @@ class Game:
and math.hypot(torpedo.x - self.ship.x, torpedo.y - self.ship.y)
<= TORPEDO_WAKE_VISIBLE_NM):
self._lookout_observe(torpedo, "torpedo-wake", "TORP",
TORPEDO_WAKE_VISIBLE_NM, torpedo.id)
torpedo.id)
for actor in sorted(self.civilians + self.warships,
key=lambda item: item.id):
if not actor.sunk:
self._lookout_observe(
actor, "surface", "SURFACE",
config.LOOKOUT_SURFACE_RANGE_NM, actor.sensor_seed)
actor, "surface", "SURFACE", actor.sensor_seed)
for actor in sorted(self.subs, key=lambda item: item.id):
if (not actor.sunk and actor.state != "SINKING"
and actor.depth <= config.LOOKOUT_SUB_SURFACED_MAX_DEPTH_M):
self._lookout_observe(
actor, "sub", "SUB", config.LOOKOUT_SUB_RANGE_NM,
actor.sensor_seed)
self._lookout_observe(actor, "sub", "SUB", actor.sensor_seed)
for actor in sorted(self.flights.flights, key=lambda item: item.seq):
if actor.active:
self._lookout_observe(
actor, "flight", "FLG", config.LOOKOUT_AIR_RANGE_NM,
actor.sensor_seed + 200_000)
actor, "flight", "FLG", actor.sensor_seed + 200_000,
altitude_m=actor.altitude_m)
for actor in sorted(self.raiders, key=lambda item: item.seq):
if not actor.despawned and actor.hp > 0:
self._lookout_observe(
actor, "raider", "FLG", config.LOOKOUT_AIR_RANGE_NM,
actor.seq + 400_000)
actor, "raider", "FLG", actor.seq + 400_000,
altitude_m=getattr(actor, "altitude_m", 0.0))
for actor in sorted(self.live_traffic.aircraft.values(),
key=lambda item: item.seq):
if not actor.despawned:
self._lookout_observe(
actor, "live_air", "FLG", config.LOOKOUT_AIR_RANGE_NM,
actor.seq + 800_000)
actor, "live_air", "FLG", actor.seq + 800_000,
altitude_m=getattr(actor, "altitude_m", 0.0))
def _update_air_picture(self) -> None:
"""Create noisy observations; consumers never receive world objects."""
def _update_air_picture(self, full_scan: bool = False) -> None:
"""Create noisy observations; consumers never receive world objects.
Radar contacts are looked at only where the rotating antenna swept
since the previous publication (``full_scan`` treats the call as one
complete revolution) and only when the detector declares the echo.
"""
import random
station_live = not self.damage.station_down("opz")
surface_live = self.surface_radar_on and station_live
air_live = self.air_radar_on and station_live
surface_eff = self.radar_effective_range("surface")
air_eff = self.radar_effective_range("air")
swept_deg = 360.0 if full_scan else self.radar_scan_pending_deg
self.radar_scan_pending_deg = 0.0
self.ais.update(self.sim_t, self.civilians, self.ship, self.world)
error_scale = 1.0 + (config.RADAR_WEATHER_ERROR_GAIN
* self.radar_weather_severity()
@@ -3762,7 +3818,10 @@ class Game:
aspect = config.aspect_rcs_factor(c.course, bearing)
horizon = config.radar_horizon_nm(
config.RADAR_ANTENNA_HEIGHT_M, config.RADAR_SURFACE_TARGET_HEIGHT_M)
radar_eligible = surface_live and dist <= min(surface_eff * aspect, horizon)
radar_eligible = (surface_live and dist <= horizon
and self._radar_look("surface", c.sensor_seed, dist,
bearing, swept_deg=swept_deg,
rcs_factor=aspect ** 4))
radar_clear = radar_eligible and not self.world.land_blocks_line(
self.ship.x, self.ship.y, c.x, c.y)
if radar_eligible and radar_clear:
@@ -3788,7 +3847,10 @@ class Game:
aspect = config.aspect_rcs_factor(w.course, bearing)
horizon = config.radar_horizon_nm(
config.RADAR_ANTENNA_HEIGHT_M, config.RADAR_SURFACE_TARGET_HEIGHT_M)
radar_eligible = surface_live and dist <= min(surface_eff * aspect, horizon)
radar_eligible = (surface_live and dist <= horizon
and self._radar_look("surface", w.sensor_seed, dist,
bearing, swept_deg=swept_deg,
rcs_factor=aspect ** 4))
radar_clear = radar_eligible and not self.world.land_blocks_line(
self.ship.x, self.ship.y, w.x, w.y)
if radar_eligible and radar_clear:
@@ -3809,7 +3871,9 @@ class Game:
bearing = f.bearing_to_frigate(self.ship)
horizon = config.radar_horizon_nm(
config.RADAR_ANTENNA_HEIGHT_M, f.altitude_m)
radar_eligible = air_live and dist <= min(air_eff, horizon)
radar_eligible = (air_live and dist <= horizon
and self._radar_look("air", f.seq + 10000, dist,
bearing, swept_deg=swept_deg))
radar_clear = radar_eligible and not self.world.land_blocks_line(
self.ship.x, self.ship.y, f.x, f.y)
if radar_eligible and radar_clear:
@@ -3831,7 +3895,9 @@ class Game:
bearing = r.bearing_from_frigate(self.ship)
horizon = config.radar_horizon_nm(
config.RADAR_ANTENNA_HEIGHT_M, getattr(r, "altitude_m", 0.0))
radar_eligible = air_live and dist <= min(air_eff, horizon)
radar_eligible = (air_live and dist <= horizon
and self._radar_look("air", r.seq + 60000, dist,
bearing, swept_deg=swept_deg))
radar_clear = radar_eligible and not self.world.land_blocks_line(
self.ship.x, self.ship.y, r.x, r.y)
if radar_eligible and radar_clear:
@@ -3857,7 +3923,9 @@ class Game:
bearing = live.bearing_from_frigate(self.ship)
horizon = config.radar_horizon_nm(
config.RADAR_ANTENNA_HEIGHT_M, getattr(live, "altitude_m", 0.0))
radar_eligible = air_live and dist <= min(air_eff, horizon)
radar_eligible = (air_live and dist <= horizon
and self._radar_look("air", live.seq + 90000, dist,
bearing, swept_deg=swept_deg))
radar_clear = radar_eligible and not self.world.land_blocks_line(
self.ship.x, self.ship.y, live.x, live.y)
if radar_eligible and radar_clear:
@@ -3879,6 +3947,7 @@ class Game:
quality=.85, now=self.sim_t, label=f"A-{live.seq}",
bearing_uncertainty_deg=bearing_error / math.sqrt(3.0),
altitude_m=altitude)
ciws_track = station_live and self.ciws_authorized
for a in self.asms:
if a.state not in ("LAUF", "CHAFF"):
continue
@@ -3895,7 +3964,14 @@ class Game:
observer_x=self.ship.x, observer_y=self.ship.y, course=None,
quality=.55, now=self.sim_t, label=f"A-{a.seq}",
jamming=True, bearing_uncertainty_deg=5.0 / math.sqrt(3.0))
elif (air_live and dist <= air_eff
elif ((air_live or ciws_track)
and self._radar_look(
"air", a.seq + 120000, dist, a.bearing_to_frigate(self.ship),
# The CIWS search/track radar holds close-in missiles
# continuously; beyond it only the rotating antenna looks.
swept_deg=(360.0 if ciws_track and dist <= CIWS_TRACK_RANGE_NM
else swept_deg if air_live else 0.0),
jnr=self._asm_jammer_to_noise(a, dist))
and not self.world.land_blocks_line(
self.ship.x, self.ship.y, a.x, a.y)):
rng = random.Random(a.seq * 7919 + int(self.sim_t * 2.0))
@@ -4611,6 +4687,17 @@ class Game:
return (None if track is None else
analyze_signal(track, self.runtime_catalog.emitters))
def eloka_range_estimate(self, track=None) -> float | None:
"""Range implied by the intercept's peak level, assuming the power
class of the best-ranked catalog hypothesis (never emitter truth)."""
track = track or self.selected_eloka_track()
analysis = self.eloka_analysis(track)
if analysis is None or not analysis.candidates or track.signal_db <= 0.0:
return None
emitter = self.runtime_catalog.emitters.get(
analysis.candidates[0].emitter_key)
return estimated_range_nm(track, getattr(emitter, "power_class", "medium"))
def deploy_jamming(self, track, technique=None):
if self.damage.station_down("opz"):
return "opz_down"
@@ -4911,7 +4998,10 @@ class Game:
seed * 1009 + int(signal.signal_id[1:9], 16),
self.sim_t, 5.0),
line_of_sight=lambda signal: not self.world.land_blocks_line(
self.ship.x, self.ship.y, signal.x, signal.y))
self.ship.x, self.ship.y, signal.x, signal.y),
level_noise_for=lambda signal: detrand.normal(
self.seed, "esm-level", int(signal.signal_id[1:9], 16),
math.floor(self.sim_t * 2.0 + 1e-6)))
def _ecm_effect_against_asm(self, asm):
if not asm.seeker_active(self.ship) or not self.ecm_jammer.channels:
@@ -5044,23 +5134,34 @@ class Game:
if self.damage.station_down("radio"):
self.radio_picture.expire(self.sim_t)
return
night = self.world.is_night()
for sub in self.subs:
if not sub.transmitting:
continue
dist = sub.distance_nm(self.ship)
if dist > config.HFDF_RANGE_NM:
seed = getattr(sub, "sensor_seed", sub.id)
# One call keeps its frequency; a new 5-minute schedule window
# may pick another one for the path to the shore station.
frequency = hf_physics.transmit_frequency_mhz(
seed, math.floor(self.sim_t / 300.0), night)
mode = hf_physics.propagation_mode(
dist, frequency, night, config.HFDF_RANGE_NM)
if mode is None:
continue
if self.world.land_blocks_line(self.ship.x, self.ship.y, sub.x, sub.y):
if (mode == "GROUND" and self.world.land_blocks_line(
self.ship.x, self.ship.y, sub.x, sub.y)):
continue
seed = getattr(sub, "sensor_seed", sub.id) * 777
noise = self._smooth_sensor_noise(seed, self.sim_t, 10.0)
brg = (sub.bearing_from_frigate(self.ship)
+ noise * config.HFDF_BEARING_ERR_DEG) % 360.0
error = config.HFDF_BEARING_ERR_DEG * (
hf_physics.SKY_WAVE_BEARING_FACTOR if mode == "SKY" else 1.0)
noise = self._smooth_sensor_noise(seed * 777, self.sim_t, 10.0)
brg = (sub.bearing_from_frigate(self.ship) + noise * error) % 360.0
self.radio_picture.observe(track_id=f"H-{sub.id}", kind="HF",
target_id=sub.id, source="HFDF", bearing=brg, range_nm=None,
observer_x=self.ship.x, observer_y=self.ship.y, course=None,
quality=.55, now=self.sim_t, label=f"SIG-{sub.id:02d}",
bearing_uncertainty_deg=config.HFDF_BEARING_ERR_DEG / math.sqrt(3.0))
quality=.55 if mode == "GROUND" else .4, now=self.sim_t,
label=f"SIG-{sub.id:02d}",
bearing_uncertainty_deg=error / math.sqrt(3.0),
frequency_hz=round(frequency * 1e6, -2), propagation=mode)
self.radio_picture.expire(self.sim_t)
def _cycle_hfdf(self, delta: int) -> None:
@@ -5128,7 +5229,9 @@ class Game:
# Angular errors projected at the two measurement origins. This assumes
# a stationary emitter throughout the bounded observation span.
b1, b2 = math.radians(previous["bearing"]), math.radians(row["bearing"])
sigma_rad = math.radians(config.HFDF_BEARING_ERR_DEG) / math.sqrt(3.0)
# Sky-wave intercepts carry the larger ionospheric-tilt uncertainty.
sigma_rad = math.radians(report.bearing_uncertainty_deg
or config.HFDF_BEARING_ERR_DEG / math.sqrt(3.0))
v1 = sigma_rad ** 2 * ((x - previous["observer_x"]) ** 2
+ (y - previous["observer_y"]) ** 2)
v2 = sigma_rad ** 2 * ((x - row["observer_x"]) ** 2
@@ -6493,6 +6596,9 @@ class Game:
self.flash(notice, 3.0)
self.feed.add(self.world.format_time(), "sonar", notice)
self._last_tow_state = self.sonar.tow_state
sweep = config.RADAR_SWEEP_DEG_PER_S * dt
self.radar_scan_phase = (self.radar_scan_phase + sweep) % 360.0
self.radar_scan_pending_deg = min(360.0, self.radar_scan_pending_deg + sweep)
self._sensor_acc += dt
publish_picture = self._sensor_acc >= .25
if publish_picture:
@@ -6753,7 +6859,9 @@ class Game:
volume=self.sonar_volume),
"radars": dict(surface=self.surface_radar_on,
air=self.air_radar_on,
range_nm=self.opz_range_nm),
range_nm=self.opz_range_nm,
scan_phase=self.radar_scan_phase,
scan_pending_deg=self.radar_scan_pending_deg),
"roe": self.roe,
"asm_spawned": self.asm_spawned,
"air_threat_reported": self.air_threat_reported,
@@ -7341,6 +7449,8 @@ class Game:
self.surface_radar_on = radars["surface"]
self.air_radar_on = radars["air"]
self.opz_range_nm = radars["range_nm"]
self.radar_scan_phase = radars["scan_phase"]
self.radar_scan_pending_deg = radars["scan_pending_deg"]
self.roe = data["roe"]
self.asm_spawned = data["asm_spawned"]
self.air_threat_reported = data["air_threat_reported"]
@@ -8272,10 +8382,15 @@ class Game:
return False
radars = data.get("radars")
if (not isinstance(radars, dict)
or set(radars) != {"surface", "air", "range_nm"}
or set(radars) != {"surface", "air", "range_nm", "scan_phase",
"scan_pending_deg"}
or type(radars["surface"]) is not bool
or type(radars["air"]) is not bool
or radars["range_nm"] not in config.RADAR_RANGE_SCALES_NM):
or radars["range_nm"] not in config.RADAR_RANGE_SCALES_NM
or type(radars["scan_phase"]) is not float
or not 0.0 <= radars["scan_phase"] < 360.0
or type(radars["scan_pending_deg"]) is not float
or not 0.0 <= radars["scan_pending_deg"] <= 360.0):
return False
order = ship.get("order_idx", config.TELEGRAPH_DEFAULT)
hull = ship.get("hull")
+83 -11
View File
@@ -75,6 +75,18 @@ THREAT_LEVELS = {
SignalType.MISSILE_SEEKER: "critical",
}
POWER_CLASS_RANGE_NM = {"low": 60.0, "medium": 100.0, "high": 150.0}
# Rotating search antennas illuminate the ESM mast only when their main beam
# passes (one-way level 20 log10(R_class / R)); between passes only the
# side lobes reach it. Tracking/fire-control and seeker radars point at
# their target. Periods are generic rotation rates per radar role.
ANTENNA_SCAN_PERIOD_S = {"navigation": 2.5, "surface_search": 2.5,
"air_search": 5.0, "multi_function": 2.0}
MAIN_BEAM_WIDTH_DEG = 2.0
SIDELOBE_DB = -25.0
ESM_DWELL_S = 0.5
ESM_LEVEL_NOISE_DB = 2.0
ESM_SIGNAL_DB_RANGE = (-60.0, 200.0)
ESM_LIVE_SCAN_CAP_S = 7.5
THREAT_ORDER = {"unknown": 0, "low": 1, "medium": 2, "high": 3,
"critical": 4}
ESM_STATUS_FILTERS = ("OPERATIONAL", "LIVE", "MEMORY", "ALL")
@@ -188,6 +200,7 @@ class ESMMeasurement:
quality: float
observed_at: float
synthetic_assumption: bool = False
signal_db: float = 0.0
@dataclass(slots=True)
@@ -204,6 +217,10 @@ class ESMTrack:
first_seen: float
last_seen: float
synthetic_assumption: bool = False
# Peak received level over the ESM sensitivity (dB) and the measured
# interval between intercepts (antenna scan period, 0 until measured).
signal_db: float = 0.0
revisit_s: float = 0.0
def age(self, now: float) -> float:
return max(0.0, now - self.last_seen)
@@ -212,6 +229,18 @@ class ESMTrack:
return max(0.0, self.quality * (1.0 - self.age(now) / stale_s))
def live_window_s(track: ESMTrack) -> float:
"""A scanning emitter is still live until one missed revolution."""
return max(ECM_SIGNAL_FRESH_S,
1.5 * min(track.revisit_s, ESM_LIVE_SCAN_CAP_S))
def estimated_range_nm(track: ESMTrack, power_class: str) -> float:
"""Range implied by the peak level for an assumed emitter power class."""
reference = POWER_CLASS_RANGE_NM.get(power_class, POWER_CLASS_RANGE_NM["medium"])
return reference * 10.0 ** (-track.signal_db / 20.0)
def signal_state(track: ESMTrack, now: float, threat_level: str) -> str:
"""Derive the operator state solely from retained observation data."""
confirmed = (track.last_seen - track.first_seen >= ESM_CONFIRMATION_S
@@ -219,7 +248,7 @@ def signal_state(track: ESMTrack, now: float, threat_level: str) -> str:
if not confirmed:
return "UNCONFIRMED"
age = track.age(now)
if age <= ECM_SIGNAL_FRESH_S:
if age <= live_window_s(track):
return "LIVE"
if age <= ESM_ASSOCIATION_MAX_GAP_S:
return "RECENT"
@@ -781,6 +810,7 @@ class ESMPicture:
first_seen=measurement.observed_at,
last_seen=measurement.observed_at,
synthetic_assumption=measurement.synthetic_assumption,
signal_db=measurement.signal_db,
)
while len(self._tracks) > self.maximum:
evicted = min(self._tracks.values(), key=lambda track: (
@@ -805,6 +835,16 @@ class ESMPicture:
track.prf_hz = measurement.prf_hz
track.modulation_code = measurement.modulation_code
track.quality = measurement.quality
gap = measurement.observed_at - track.last_seen
if gap > 0.0:
gap = min(gap, ESM_ASSOCIATION_MAX_GAP_S)
track.revisit_s = (gap if track.revisit_s <= 0.0
else track.revisit_s + (gap - track.revisit_s) * alpha)
# Peak-hold amplitude that relaxes slowly (side lobes read low).
if measurement.signal_db >= track.signal_db:
track.signal_db = measurement.signal_db
else:
track.signal_db += (measurement.signal_db - track.signal_db) * 0.05
track.last_seen = measurement.observed_at
track.synthetic_assumption = measurement.synthetic_assumption
@@ -820,11 +860,8 @@ class ESMPicture:
restored = {}
previous = None
for row in rows:
if not isinstance(row, dict) or set(row) not in (
fields, fields - {"synthetic_assumption"}):
if not isinstance(row, dict) or set(row) != fields:
raise ValueError("invalid ESM track fields")
if "synthetic_assumption" not in row:
row = {**row, "synthetic_assumption": False}
track = ESMTrack(**row)
_validate_track(track, now, track_seq)
if track.track_key in restored or (previous is not None
@@ -876,11 +913,31 @@ def analyze_signal(track: ESMTrack, emitters: Mapping[str, object],
candidates, ambiguous)
def antenna_main_beam_on(signal: RadarSignal, bearing_to_observer: float,
now: float, dwell_s: float) -> bool:
"""Did the emitter's main beam sweep the observer during the dwell?"""
period = ANTENNA_SCAN_PERIOD_S.get(getattr(signal.signal_type, "value",
signal.signal_type))
if period is None:
return True
offset = _stable_u64(signal.signal_id, "azimuth") % 3600 / 10.0
azimuth = (offset + now * 360.0 / period) % 360.0
swept = 360.0 * dwell_s / period + MAIN_BEAM_WIDTH_DEG
if swept >= 360.0:
return True
return (azimuth - bearing_to_observer + MAIN_BEAM_WIDTH_DEG / 2.0) % 360.0 < swept
def scan_for_signals(signals, *, observer_x: float, observer_y: float,
now: float, maximum_range_nm: float,
bearing_error_deg: float, noise_for,
line_of_sight=lambda _signal: True) -> tuple[ESMMeasurement, ...]:
"""Convert internal emissions to detached bearing-only ESM measurements."""
line_of_sight=lambda _signal: True,
dwell_s: float = ESM_DWELL_S,
level_noise_for=None) -> tuple[ESMMeasurement, ...]:
"""Convert internal emissions to detached bearing-only ESM measurements.
The one-way received level decides the intercept: main beam out to the
power-class range, side lobes (-25 dB) only close in."""
received = []
for signal in signals:
if not isinstance(signal, RadarSignal) or signal.emitted_at > now:
@@ -893,15 +950,25 @@ def scan_for_signals(signals, *, observer_x: float, observer_y: float,
noise = max(-1.0, min(1.0, float(noise_for(signal))))
effective_range = min(maximum_range_nm, POWER_CLASS_RANGE_NM.get(
signal.power_class, POWER_CLASS_RANGE_NM["medium"]))
if distance > effective_range:
level = 20.0 * math.log10(effective_range / max(distance, 1e-3))
if not antenna_main_beam_on(signal, (true_bearing + 180.0) % 360.0,
now, dwell_s):
level += SIDELOBE_DB
if level < 0.0:
continue
quality = max(.05, min(1.0, 1.0 - .65 * distance / effective_range))
# Quality follows the received level (legacy 1 - .65 R/R_eff for the
# main beam).
quality = max(.05, min(1.0, 1.0 - .65 * 10.0 ** (-level / 20.0)))
level_noise = (0.0 if level_noise_for is None
else max(-3.0, min(3.0, float(level_noise_for(signal)))))
measured_level = max(ESM_SIGNAL_DB_RANGE[0], min(
ESM_SIGNAL_DB_RANGE[1], level + level_noise * ESM_LEVEL_NOISE_DB))
received.append(ESMMeasurement(
observer_x, observer_y,
(true_bearing + noise * bearing_error_deg) % 360.0,
bearing_error_deg / math.sqrt(3.0), signal.frequency_hz,
signal.prf_hz, signal.modulation_code, quality, signal.emitted_at,
signal.synthetic_assumption))
signal.synthetic_assumption, measured_level))
return tuple(sorted(received, key=_measurement_sort_key)[:ESM_MAX_TRACKS])
@@ -1003,6 +1070,8 @@ def _validate_measurement(measurement: ESMMeasurement, now: float) -> None:
or not 0.0 <= measurement.observed_at <= now
or measurement.modulation_code not in ESM_MODULATIONS
or type(measurement.synthetic_assumption) is not bool
or not _finite_number(measurement.signal_db)
or not ESM_SIGNAL_DB_RANGE[0] <= measurement.signal_db <= ESM_SIGNAL_DB_RANGE[1]
or (measurement.prf_hz is not None and (
not _finite_number(measurement.prf_hz)
or not 1.0 <= measurement.prf_hz <= 1e7))):
@@ -1018,9 +1087,12 @@ def _validate_track(track: ESMTrack, now: float, track_seq: int) -> None:
frequency_hz=track.frequency_hz, prf_hz=track.prf_hz,
modulation_code=track.modulation_code, quality=track.quality,
observed_at=track.last_seen,
synthetic_assumption=track.synthetic_assumption)
synthetic_assumption=track.synthetic_assumption,
signal_db=track.signal_db)
_validate_measurement(measurement, now)
if (sequence is None or sequence > track_seq
or not _finite_number(track.revisit_s)
or not 0.0 <= track.revisit_s <= ESM_ASSOCIATION_MAX_GAP_S
or not _finite_number(track.first_seen)
or not 0.0 <= track.first_seen <= track.last_seen):
raise ValueError("invalid ESM track")
+70
View File
@@ -0,0 +1,70 @@
"""HF propagation for the HFDF receiver (pure functions).
* A submarine calls a distant shore station and picks the optimum working
frequency for that path: OWF = 0.85 x MUF, MUF = foF2 sqrt(1 + (d/2h)^2)
(flat-Earth single hop off the F2 layer, virtual height h). foF2 follows
the day/night ionosphere.
* Ground wave over sea water: the usable range falls with frequency. It is
anchored so that a typical 15 MHz call is heard to the 1.0.0 HFDF range.
* Sky wave returns to the sea surface only beyond the skip distance
d_skip = 2h sqrt((f/foF2)^2 - 1); sky-wave bearings suffer ionospheric
tilt errors and are about twice as uncertain as ground-wave bearings.
The measured carrier frequency and the propagation mode are observable; the
receiver never learns the true range from them.
"""
from __future__ import annotations
import math
from src.core import detrand
F2_HEIGHT_KM = 300.0
FOF2_DAY_MHZ = 8.0
FOF2_NIGHT_MHZ = 4.5
OWF_FRACTION = 0.85
SHORE_PATH_KM = (800.0, 2500.0)
GROUND_WAVE_REF_MHZ = 15.0
GROUND_WAVE_EXPONENT = 0.7
SKY_WAVE_BEARING_FACTOR = 2.0
MIN_FREQUENCY_MHZ = 2.0
MAX_FREQUENCY_MHZ = 30.0
NM_KM = 1.852
def fof2_mhz(night: bool) -> float:
return FOF2_NIGHT_MHZ if night else FOF2_DAY_MHZ
def muf_mhz(path_km: float, night: bool) -> float:
return fof2_mhz(night) * math.sqrt(1.0 + (path_km / (2.0 * F2_HEIGHT_KM)) ** 2)
def transmit_frequency_mhz(sensor_seed: int, window: int, night: bool) -> float:
"""Frequency a boat picks for one call (deterministic per call window)."""
path = detrand.uniform(*SHORE_PATH_KM, sensor_seed, "hf-path", window)
return max(MIN_FREQUENCY_MHZ,
min(MAX_FREQUENCY_MHZ, OWF_FRACTION * muf_mhz(path, night)))
def ground_wave_range_nm(frequency_mhz: float, reference_range_nm: float) -> float:
return reference_range_nm * (GROUND_WAVE_REF_MHZ
/ max(frequency_mhz, 0.1)) ** GROUND_WAVE_EXPONENT
def skip_distance_nm(frequency_mhz: float, night: bool) -> float:
ratio = frequency_mhz / fof2_mhz(night)
if ratio <= 1.0:
return 0.0
return 2.0 * F2_HEIGHT_KM * math.sqrt(ratio * ratio - 1.0) / NM_KM
def propagation_mode(distance_nm: float, frequency_mhz: float, night: bool,
reference_range_nm: float) -> str | None:
"""'GROUND', 'SKY' or None when the call is not heard at this distance."""
if distance_nm <= ground_wave_range_nm(frequency_mhz, reference_range_nm):
return "GROUND"
if distance_nm >= skip_distance_nm(frequency_mhz, night):
return "SKY"
return None
+8 -13
View File
@@ -8,6 +8,7 @@ import random
from dataclasses import asdict, dataclass
from src.core import config
from src.sensors import radar as radar_physics
from src.sonar import equation, propagation
@@ -229,20 +230,14 @@ class PlatformSensorSuite:
if profile.domain == "radar":
sea_state = getattr(world, "effective_sea_state",
getattr(world, "sea_state", 0.0))
sea = config.clamp(
(sea_state - (config.RADAR_WEATHER_THRESHOLD - 1)) / 2.0,
0.0, 1.0)
rain = config.clamp(getattr(world, "rain_intensity", 0.0), 0.0, 1.0)
sea_loss = (config.RADAR_AIR_WEATHER_LOSS
if target_domain == "air"
else config.RADAR_SURFACE_WEATHER_LOSS)
rain_loss = (config.RADAR_RAIN_AIR_LOSS
if target_domain == "air"
else config.RADAR_RAIN_SURFACE_LOSS)
availability *= (1.0 - sea_loss * sea) * (1.0 - rain_loss * rain)
# Radar cross-section is catalog metadata, not a physics model: a
# small, bounded scaling factor around a ~500 m2 reference target,
# not a rewrite of the range-based detection formula.
# Radar equation: sea clutter and rain attenuation shorten the
# Pd = 0.5 range of this radar.
availability *= radar_physics.detection_fraction(
"air" if target_domain == "air" else "surface", sea_state,
rain, max(profile.synthetic_range_nm or 1.0, 1.0))
# Radar equation: detection range scales with RCS^(1/4) around a
# ~500 m2 reference target (bounded for catalog outliers).
rcs = getattr(getattr(candidate, "profile", None), "rcs_m2", None)
if rcs is not None:
availability *= config.clamp((rcs / 500.0) ** 0.25, 0.5, 1.5)
+153
View File
@@ -0,0 +1,153 @@
"""Radar detection physics (pure functions).
* Radar equation: the signal-to-noise ratio of a point target falls with
R^-4 and rises with its cross-section. It is anchored so that the
nominal instrumented range of each radar is the range at which a
reference (broadside) target is detected with Pd = 0.5 in a calm sea.
* Swerling-1 target fluctuation with a cell-averaging CFAR detector:
Pd = (1 + T / (1 + SINR))^-N with T = Pfa^(-1/N) - 1 (exact closed form
for N reference cells). The CFAR adapts its threshold to the local
interference, so clutter and jamming act as extra noise.
* Sea clutter (GIT-type): the clutter-to-noise ratio of a resolution cell
grows about 3 dB per sea state and falls with R^-3 (illuminated area ~ R,
two-way spreading ~ R^-4). Air search uses MTI and suffers less.
* Rain: two-way specific attenuation proportional to the rain intensity.
* Self-screening noise jammer: jammer-to-noise ratio ~ R^-2 (one-way), so
the skin return burns through inside a finite range; the jammer power is
solved from the profiled burn-through range.
The legacy range multipliers (weather 25 %/10 %, rain 10 %/20 %, aspect
0.55..1) are reproduced at their anchor points, which the calibration
harness checks.
"""
from __future__ import annotations
import math
from functools import lru_cache
from src.core import config
PFA = 1.0e-6
CFAR_CELLS = 16
CFAR_T = PFA ** (-1.0 / CFAR_CELLS) - 1.0
# SINR (linear) for Pd = 0.5 with this CFAR.
SNR_50 = CFAR_T / (2.0 ** (1.0 / CFAR_CELLS) - 1.0) - 1.0
NM_KM = 1.852
# Legacy anchor points (range fraction lost at full severity: sea state 6,
# rain intensity 1.0).
SURFACE_CLUTTER_ANCHOR = config.RADAR_SURFACE_WEATHER_LOSS
AIR_CLUTTER_ANCHOR = config.RADAR_AIR_WEATHER_LOSS
SURFACE_RAIN_ANCHOR = config.RADAR_RAIN_SURFACE_LOSS
AIR_RAIN_ANCHOR = config.RADAR_RAIN_AIR_LOSS
CLUTTER_DB_PER_SEA_STATE = 3.0
CLUTTER_REFERENCE_SEA_STATE = 6.0
def pd_from_sinr(sinr: float) -> float:
"""Swerling-1 detection probability behind a CA-CFAR detector."""
if not math.isfinite(sinr) or sinr <= 0.0:
return 0.0
return (1.0 + CFAR_T / (1.0 + sinr)) ** (-CFAR_CELLS)
def snr(range_nm: float, reference_range_nm: float, rcs_factor: float = 1.0) -> float:
"""Signal-to-noise ratio (linear) from the anchored radar equation."""
range_nm = max(range_nm, 1e-3)
return (SNR_50 * max(rcs_factor, 0.0)
* (reference_range_nm / range_nm) ** 4)
def _clutter_coefficient(anchor_loss: float) -> float:
# At the anchor range fraction x the SINR equals SNR_50:
# x^-4 / (1 + c x^-3) = 1 => c = (x^-4 - 1) x^3.
x = 1.0 - anchor_loss
return (x ** -4 - 1.0) * x ** 3
SURFACE_CNR_REF = _clutter_coefficient(SURFACE_CLUTTER_ANCHOR)
AIR_CNR_REF = _clutter_coefficient(AIR_CLUTTER_ANCHOR)
def clutter_to_noise(domain: str, sea_state: float, range_nm: float,
reference_range_nm: float) -> float:
"""Sea-clutter CNR (linear) in the target's resolution cell."""
ref = SURFACE_CNR_REF if domain == "surface" else AIR_CNR_REF
level = ref * 10.0 ** (CLUTTER_DB_PER_SEA_STATE
* (max(0.0, sea_state) - CLUTTER_REFERENCE_SEA_STATE) / 10.0)
return level * (reference_range_nm / max(range_nm, 1e-3)) ** 3
def _rain_coefficient(anchor_loss: float, reference_range_nm: float) -> float:
# Two-way attenuation 2 * gamma * R_km equals the SNR margin at the
# anchor range fraction x: 40 log10(1/x) dB.
x = 1.0 - anchor_loss
return 40.0 * math.log10(1.0 / x) / (2.0 * x * reference_range_nm * NM_KM)
def rain_loss_db(domain: str, rain_intensity: float, range_nm: float,
reference_range_nm: float) -> float:
anchor = SURFACE_RAIN_ANCHOR if domain == "surface" else AIR_RAIN_ANCHOR
gamma = _rain_coefficient(anchor, reference_range_nm) * max(0.0, rain_intensity)
return 2.0 * gamma * max(range_nm, 0.0) * NM_KM
def jammer_to_noise(range_nm: float, burn_through_nm: float,
skin_snr_at_burn_through: float) -> float:
"""Self-screening jammer JNR (linear), R^-2, solved from burn-through."""
jnr_bt = max(0.0, skin_snr_at_burn_through / SNR_50 - 1.0)
return jnr_bt * (burn_through_nm / max(range_nm, 1e-3)) ** 2
def sinr(range_nm: float, reference_range_nm: float, *, rcs_factor: float = 1.0,
domain: str = "surface", sea_state: float = 0.0,
rain_intensity: float = 0.0, capability: float = 1.0,
jnr: float = 0.0) -> float:
"""Signal to interference-plus-noise ratio for one look."""
signal = snr(range_nm, reference_range_nm * max(capability, 1e-3), rcs_factor)
signal *= 10.0 ** (-rain_loss_db(domain, rain_intensity, range_nm,
reference_range_nm) / 10.0)
cnr = clutter_to_noise(domain, sea_state, range_nm, reference_range_nm)
return signal / (1.0 + cnr + max(0.0, jnr))
def detection_range_nm(reference_range_nm: float, **kwargs) -> float:
"""Range at which Pd falls to 0.5 (bisection; for displays and tests)."""
low, high = 1e-3, reference_range_nm * 4.0
for _ in range(60):
mid = 0.5 * (low + high)
if sinr(mid, reference_range_nm, **kwargs) >= SNR_50:
low = mid
else:
high = mid
return low
@lru_cache(maxsize=128)
def _detection_fraction(domain: str, sea_state: float, rain: float,
capability: float, reference_range_nm: float) -> float:
return detection_range_nm(reference_range_nm, domain=domain,
sea_state=sea_state, rain_intensity=rain,
capability=capability) / reference_range_nm
def detection_fraction(domain: str, sea_state: float, rain_intensity: float,
reference_range_nm: float, capability: float = 1.0) -> float:
"""Pd = 0.5 range as a fraction of the calm-sea reference. Conditions
are quantized before the (pure, bounded) cache so the result depends
only on the arguments, never on call order."""
return _detection_fraction(domain, round(float(sea_state), 2),
round(float(rain_intensity), 3),
round(float(capability), 3),
float(reference_range_nm))
def swept(bearing_deg: float, scan_end_deg: float, swept_deg: float) -> bool:
"""True when the beam passed ``bearing_deg`` during the last
``swept_deg`` degrees of rotation that ended at ``scan_end_deg``."""
if swept_deg >= 360.0:
return True
if swept_deg <= 0.0:
return False
return (scan_end_deg - bearing_deg) % 360.0 < swept_deg
+10 -2
View File
@@ -34,6 +34,9 @@ class SensorTrack:
derived_course: float | None = None
derived_speed: float | None = None
altitude_m: float | None = None
# HF intercepts: measured carrier frequency and propagation mode.
frequency_hz: float | None = None
propagation: str | None = None
def age(self, now: float) -> float:
return max(0.0, now - self.last_seen)
@@ -126,7 +129,9 @@ class TrackPicture:
hostile: bool = False, jamming: bool = False,
position_time: float | None = None,
bearing_uncertainty_deg: float | None = None,
altitude_m: float | None = None) -> SensorTrack:
altitude_m: float | None = None,
frequency_hz: float | None = None,
propagation: str | None = None) -> SensorTrack:
raw_bearing = bearing % 360.0
x = y = None
if range_nm is not None:
@@ -155,7 +160,8 @@ class TrackPicture:
position_seen=(position_time if position_time is not None else now)
if x is not None else None,
bearing_uncertainty_deg=bearing_uncertainty_deg,
altitude_m=altitude_m)
altitude_m=altitude_m, frequency_hz=frequency_hz,
propagation=propagation)
measurement["track_bearing"] = track.bearing
self._tracks[track_id] = track
else:
@@ -179,6 +185,8 @@ class TrackPicture:
track.raw_x, track.raw_y = x, y
track.raw_course = course
track.bearing_uncertainty_deg = bearing_uncertainty_deg
track.frequency_hz = frequency_hz
track.propagation = propagation
if altitude_m is not None:
track.altitude_m = (
altitude_m if track.altitude_m is None
+112
View File
@@ -0,0 +1,112 @@
"""Visual detection physics for lookouts (pure functions).
* Koschmieder's law: the apparent contrast of a target against the horizon
sky decays as C(R) = C0 exp(-3.912 R / V), V = meteorological visibility.
* The eye's contrast threshold rises for small targets (Blackwell-type):
eps(alpha) = EPS0 (1 + (ALPHA0 / alpha)^2), alpha = target height / range.
* Whitecaps raise the background clutter of sea-level targets by a factor
per sea state (small, low targets such as a sail suffer most); aircraft
are seen against the sky.
* Night: the threshold rises by the ratio of adaptation luminances, and the
moon's illuminated fraction (from its phase) interpolates between a dark
new-moon night and a full-moon night.
* A target is visible only above the geometric horizon of lookout eye height
plus target height.
The inherent contrast C0 of each target kind is solved so that the 1.0.0
day, calm, clear-air ranges are reproduced exactly; the night multipliers
are solved so that a half moon reproduces the 1.0.0 night factor for a
surface ship.
"""
from __future__ import annotations
import math
KOSCHMIEDER = 3.912
EPS0 = 0.02
ALPHA0_RAD = math.radians(1.0 / 60.0) * 3.0 # ~3 arcmin knee
LOOKOUT_EYE_HEIGHT_M = 18.0
SYNODIC_MONTH_D = 29.530588
NIGHT_RANGE_NEW_MOON = 0.25 # fraction of day range, surface ship
NIGHT_RANGE_FULL_MOON = 0.45
SEA_CLUTTER_PER_STATE = 0.45 # threshold growth per sea state (sea-level targets)
TARGET_HEIGHT_M = {
"SURFACE": 12.0,
"SUB": 3.0, # sail/periscope and wake of a surfaced boat
"FLG": 6.0, # apparent size of an aircraft
"TORP": 1.0, # bubble track
}
def optical_horizon_nm(eye_m: float, target_m: float) -> float:
"""Geometric horizon with standard optical refraction (2.08 NM/sqrt(m))."""
return 2.08 * (math.sqrt(max(eye_m, 0.0)) + math.sqrt(max(target_m, 0.0)))
def threshold(height_m: float, range_nm: float) -> float:
alpha = height_m / max(range_nm * 1852.0, 1.0)
return EPS0 * (1.0 + (ALPHA0_RAD / max(alpha, 1e-12)) ** 2)
def apparent_contrast(c0: float, range_nm: float, visibility_nm: float) -> float:
return c0 * math.exp(-KOSCHMIEDER * range_nm / max(visibility_nm, 1e-3))
def inherent_contrast(kind: str, reference_range_nm: float,
reference_visibility_nm: float) -> float:
"""C0 such that the day/clear/calm threshold crossing is at the reference."""
height = TARGET_HEIGHT_M[kind]
return (threshold(height, reference_range_nm)
* math.exp(KOSCHMIEDER * reference_range_nm / reference_visibility_nm))
def night_multiplier(fraction: float, reference_range_nm: float,
reference_visibility_nm: float) -> float:
"""Threshold multiplier giving a surface night range = fraction x day."""
height = TARGET_HEIGHT_M["SURFACE"]
c0 = inherent_contrast("SURFACE", reference_range_nm, reference_visibility_nm)
night_range = fraction * reference_range_nm
return (apparent_contrast(c0, night_range, reference_visibility_nm)
/ threshold(height, night_range))
def moon_illumination(lunar_age_days: float) -> float:
"""Illuminated fraction of the lunar disc (0 new, 1 full)."""
return 0.5 * (1.0 - math.cos(2.0 * math.pi * lunar_age_days / SYNODIC_MONTH_D))
class LookoutModel:
"""Anchored visual model; construct once per world visibility maximum."""
def __init__(self, reference_ranges: dict, reference_visibility_nm: float):
self.reference_visibility_nm = float(reference_visibility_nm)
self.c0 = {kind: inherent_contrast(kind, rng, reference_visibility_nm)
for kind, rng in reference_ranges.items()}
surface = reference_ranges["SURFACE"]
self.night_new = night_multiplier(
NIGHT_RANGE_NEW_MOON, surface, reference_visibility_nm)
self.night_full = night_multiplier(
NIGHT_RANGE_FULL_MOON, surface, reference_visibility_nm)
def night_factor(self, illumination: float) -> float:
"""Log-interpolated threshold multiplier between new and full moon."""
f = max(0.0, min(1.0, illumination))
return self.night_new ** (1.0 - f) * self.night_full ** f
def margin(self, kind: str, range_nm: float, *, visibility_nm: float,
night: bool, illumination: float, sea_state: float,
altitude_m: float | None = None) -> float:
"""Apparent contrast over threshold (>= 1 means seen)."""
height = TARGET_HEIGHT_M[kind]
top = height if altitude_m is None else max(height, altitude_m)
if range_nm > optical_horizon_nm(LOOKOUT_EYE_HEIGHT_M, top):
return 0.0
eps = threshold(height, range_nm)
if kind != "FLG":
# Aircraft are seen against the sky, not the whitecaps.
eps *= 1.0 + SEA_CLUTTER_PER_STATE * max(0.0, sea_state)
if night:
eps *= self.night_factor(illumination)
return apparent_contrast(self.c0[kind], range_nm, visibility_nm) / eps
+19 -2
View File
@@ -22,6 +22,12 @@ from src.ui import nato_symbols
from src.ui import observations
def _hfdf_error_deg(report) -> float:
"""Half-width of the HFDF bearing error (uniform sigma x sqrt(3))."""
sigma = getattr(report, "bearing_uncertainty_deg", None)
return (sigma * math.sqrt(3.0) if sigma else config.HFDF_BEARING_ERR_DEG)
def message(key, **values):
return localize(structured_message(key, **values))
@@ -689,7 +695,12 @@ def station_hit_target(game, pos):
message("radio.tooltip.hfdf_title",
label=game.hfdf_display_id(report)),
observations.format_bearing_pair(report, game.ship),
message("radio.tooltip.error", error=f"{config.HFDF_BEARING_ERR_DEG:.0f}"),
message("radio.tooltip.error", error=f"{_hfdf_error_deg(report):.0f}"),
message("radio.hfdf.frequency",
frequency=(f"{report.frequency_hz / 1e3:.0f}"
if report.frequency_hz else "--"),
mode=localize("radio.hfdf.mode." + report.propagation)
if report.propagation in ("GROUND", "SKY") else ""),
message("radio.tooltip.age", age=f"{report.age(game.sim_t):.0f}"),
"control.radio_tooltip",
target_id=f"radio:{game.hfdf_display_id(report)}")
@@ -980,6 +991,12 @@ def draw_eloka_view(game, tr=None) -> None:
"eloka.value.quality_age",
quality=f"{selected.display_quality(game.sim_t):.0%}",
age=f"{selected.age(game.sim_t):.1f}")),
("eloka.field.signal", message(
"eloka.value.signal", level=f"{selected.signal_db:.0f}",
range=(f"{estimate:.0f}" if (estimate := game.eloka_range_estimate(
selected)) is not None else "--"),
scan=(f"{selected.revisit_s:.1f}" if selected.revisit_s > 0.0
else "--"))),
("eloka.field.radar_type", localize(
"eloka.radar_type." + (analysis.radar_type.value
if analysis is not None and analysis.radar_type is not None
@@ -1764,7 +1781,7 @@ def draw_radio_view(game, tr=None) -> None:
s, message("radio.line.signal", prefix='>' if selected else ' ',
label=game.hfdf_display_id(report),
bearing=observations.format_bearing(report, game.ship),
error=f"{config.HFDF_BEARING_ERR_DEG:.0f}", age=f"{age:.0f}"),
error=f"{_hfdf_error_deg(report):.0f}", age=f"{age:.0f}"),
(lx, ly, lw, row_h - 8),
config.COLOR_WARN if selected else
config.COLOR_TEXT if age < 30 else config.COLOR_TEXT_DIM,
+13 -1
View File
@@ -1,5 +1,17 @@
{
"metrics": {
"air.asm.time_to_impact_s.30nm": {
"kind": "transient",
"value": 214.9
},
"air.chaff.leak_fraction": {
"kind": "statistic",
"value": 0.65
},
"air.ciws.leak_fraction": {
"kind": "statistic",
"value": 0.175
},
"damage.flood_total_1800s_two_hits.mean": {
"kind": "statistic",
"value": 203.0
@@ -297,6 +309,6 @@
"value": 8.0
}
},
"note": "Kinematic U-Jagd 1.0.0 reference behaviour.",
"note": "Kinematic U-Jagd 1.0.0 reference behaviour. air.* metrics measured on the 1.0.0 tree (3b3753c) with the phase-11 air probe.",
"recorded_from_commit": "3b3753cf4e79927103cb03e44d0fc4b50dd8c6cb"
}
+2 -2
View File
@@ -29,7 +29,7 @@ def _live(game, altitude_m=9000.0, dx=1.0):
def _air_track(game, track_id):
game._update_air_picture()
game._update_air_picture(full_scan=True)
return next(t for t in game.air_picture.tracks(game.sim_t, ("FLG",))
if t.track_id == track_id)
@@ -82,7 +82,7 @@ def test_altitude_is_smoothed_not_replaced_by_each_noisy_fix(game):
def test_non_air_tracks_have_no_altitude(game):
game._update_air_picture()
game._update_air_picture(full_scan=True)
assert all(t.altitude_m is None for t in game.air_picture.tracks(
game.sim_t) if t.kind != "FLG")
+2 -2
View File
@@ -158,7 +158,7 @@ def test_fresh_own_radar_supersedes_retained_stale_datalink(game, monkeypatch):
for controller in sender.sensor_suite.controllers.values():
controller.next_scan_s = 11.0
game._update_platform_sensors(.25)
game._update_air_picture()
game._update_air_picture(full_scan=True)
track = game.air_picture._tracks[f"M-{missile.seq}"]
assert track.source == "RADAR-L"
@@ -180,7 +180,7 @@ def test_equal_time_own_radar_supersedes_datalink(game, monkeypatch):
monkeypatch.setattr(game.world, "land_blocks_line", lambda *args: False)
game._update_platform_sensors(.25)
game._update_air_picture()
game._update_air_picture(full_scan=True)
track = game.air_picture._tracks[f"M-{missile.seq}"]
assert track.source == "RADAR-L"
+5 -5
View File
@@ -332,13 +332,13 @@ def test_raider_publishes_as_anonymous_flg_track(game, monkeypatch):
game.rng_raid, profile["raider"])
game.raiders = [raider]
game.raid_seq = 3
game._update_air_picture()
game._update_air_picture(full_scan=True)
track = game.air_picture._tracks.get("R-3")
assert track is not None and track.kind == "FLG"
assert track.source == "RADAR-L" and track.hostile is False
game.air_radar_on = False
game.air_picture._tracks.clear()
game._update_air_picture()
game._update_air_picture(full_scan=True)
assert "R-3" not in game.air_picture._tracks
@@ -355,14 +355,14 @@ def test_raider_radar_detection_is_capped_by_geometric_horizon(game, monkeypatch
game.rng_raid, profile["raider"])
game.raiders = [beyond_horizon]
game.raid_seq = 4
game._update_air_picture()
game._update_air_picture(full_scan=True)
assert "R-4" not in game.air_picture._tracks
within_horizon = Raider(game.ship.x + horizon - 5.0, game.ship.y, 0.0, 5,
game.rng_raid, profile["raider"])
game.raiders = [within_horizon]
game.raid_seq = 5
game._update_air_picture()
game._update_air_picture(full_scan=True)
track = game.air_picture._tracks.get("R-5")
assert track is not None and track.source == "RADAR-L"
@@ -374,7 +374,7 @@ def test_raider_first_contact_flashes_once(game, monkeypatch):
game.rng_raid, profile["raider"])
game.raiders = [raider]
game.raid_seq = 1
game._update_air_picture()
game._update_air_picture(full_scan=True)
flashes = []
monkeypatch.setattr(game, "flash",
lambda text, seconds=3.0: flashes.append(text))
+13 -5
View File
@@ -23,6 +23,14 @@ from src.sensors.esm import (
)
def esm_revolution(game, steps=12):
"""Rotating search radars reach the ESM mast with their main beam only
once per revolution (up to 5 s); sample the picture over one."""
for _ in range(steps):
game.sim_t += .5
game._update_esm_picture()
def measurement(*, bearing=90.0, frequency=9.2e9, prf=800.0,
modulation="pulse", quality=.8, now=1.0):
return ESMMeasurement(
@@ -208,7 +216,7 @@ def test_future_correlation_evidence_is_rejected():
def test_radar_off_esm_on_and_parallel_evidence(monkeypatch):
game, actor = emitting_game(monkeypatch, radar=False)
game.sim_t = .5
game._update_air_picture()
game._update_air_picture(full_scan=True)
game._update_esm_picture()
assert game.eloka_tracks()
@@ -216,7 +224,7 @@ def test_radar_off_esm_on_and_parallel_evidence(monkeypatch):
game.surface_radar_on = True
game.sim_t = 1.0
game._update_air_picture()
game._update_air_picture(full_scan=True)
game._update_esm_picture()
assert f"W-{actor.id}" in game.air_picture._tracks
assert game.eloka_tracks()
@@ -266,7 +274,7 @@ def test_military_patrol_and_transit_emit_without_own_radar_and_continue_after_s
game.flights._seq = 103
game.radar_on = False
game.sim_t = 1.0
game._update_esm_picture()
esm_revolution(game)
assert len(game.eloka_tracks()) == 2
state = game.save_state()
@@ -276,7 +284,7 @@ def test_military_patrol_and_transit_emit_without_own_radar_and_continue_after_s
assert [flight.radar_emitting for flight in restored.flights.flights] == [
True, True, False]
game.sim_t = restored.sim_t = 1.5
game.sim_t = restored.sim_t = restored.sim_t + .5
game._update_esm_picture()
restored._update_esm_picture()
assert restored.esm_picture.serialize() == game.esm_picture.serialize()
@@ -391,7 +399,7 @@ def test_malformed_esm_source_state_is_rejected_transactionally(
def test_malformed_or_oversized_correlation_sources_are_rejected(monkeypatch):
game, _ = emitting_game(monkeypatch, radar=True)
game._update_air_picture()
game._update_air_picture(full_scan=True)
before = game.save_state()
malformed = copy.deepcopy(before)
+3 -3
View File
@@ -288,7 +288,7 @@ def test_sensor_picture_uses_generic_evidence_not_platform_truth(monkeypatch):
game.civilians = []
game.flights.flights = []
game.asms = []
game._update_air_picture()
game._update_air_picture(full_scan=True)
track = game.air_picture._tracks[f"W-{warship.id}"]
assert track.label == f"W-{warship.id}"
assert track.course is None and track.hostile is False
@@ -330,14 +330,14 @@ def test_surface_radar_detection_is_capped_by_geometric_horizon(monkeypatch):
random.Random(850), hostile=True)
beyond_horizon.emitter = True
game.warships = [beyond_horizon]
game._update_air_picture()
game._update_air_picture(full_scan=True)
assert f"W-{beyond_horizon.id}" not in game.air_picture._tracks
within_horizon = SurfaceShip(game.ship.x + horizon - 5.0, game.ship.y,
random.Random(851), hostile=True)
within_horizon.emitter = True
game.warships = [within_horizon]
game._update_air_picture()
game._update_air_picture(full_scan=True)
assert f"W-{within_horizon.id}" in game.air_picture._tracks
+5 -5
View File
@@ -65,7 +65,7 @@ def test_hostile_classification_alone_still_withholds_fire_pending_confirmation(
itself and must never auto-authorize weapons - the AA gun stays silent
until the player separately confirms the attack."""
aircraft = _place_close_low_aircraft(game, "unconfirmed1")
for _ in range(5):
for _ in range(45): # one antenna revolution (4 s) plus margin
game.update(0.1, audio_dt=0.1)
_classify_as_hostile(game, aircraft)
assert game.live_engage_confirm_pending == "unconfirmed1"
@@ -77,7 +77,7 @@ def test_hostile_classification_alone_still_withholds_fire_pending_confirmation(
def test_manually_classified_hostile_aircraft_can_be_engaged_after_confirmation(game):
aircraft = _place_close_low_aircraft(game, "hostile1")
for _ in range(5):
for _ in range(45): # one antenna revolution (4 s) plus margin
game.update(0.1, audio_dt=0.1)
_classify_as_hostile(game, aircraft)
assert game.confirm_live_engagement() is True
@@ -93,7 +93,7 @@ def test_reclassifying_hostile_again_requires_a_fresh_confirmation(game):
IFF affiliation away and back to HOSTILE (or a stray re-classification)
revokes the earlier confirmation and demands a renewed one."""
aircraft = _place_close_low_aircraft(game, "hostile3")
for _ in range(5):
for _ in range(45): # one antenna revolution (4 s) plus margin
game.update(0.1, audio_dt=0.1)
_classify_as_hostile(game, aircraft)
assert game.confirm_live_engagement() is True
@@ -113,7 +113,7 @@ def test_reclassifying_hostile_again_requires_a_fresh_confirmation(game):
def test_destroyed_icao24_is_removed_from_active_tracking(game):
aircraft = _place_close_low_aircraft(game, "hostile2")
for _ in range(5):
for _ in range(45): # one antenna revolution (4 s) plus margin
game.update(0.1, audio_dt=0.1)
_classify_as_hostile(game, aircraft)
assert game.confirm_live_engagement() is True
@@ -133,7 +133,7 @@ def test_live_aircraft_track_id_is_indistinguishable_from_simulated_flights(game
simulated_seq_before = game.flights.next_seq()
aircraft = _place_close_low_aircraft(game, "abc123")
assert aircraft.seq == simulated_seq_before + 1 # same monotonic counter
for _ in range(5):
for _ in range(45): # one antenna revolution (4 s) plus margin
game.update(0.1, audio_dt=0.1)
track_id = f"A-{aircraft.seq}"
tracks = {t.track_id for t in game.air_picture.tracks(game.sim_t, ("FLG",))}
+11 -3
View File
@@ -38,6 +38,14 @@ def _fake_game(ship_x=250.0, ship_y=250.0):
ship=SimpleNamespace(x=ship_x, y=ship_y))
def esm_revolution(game, steps=12):
"""Rotating search radars reach the ESM mast with their main beam only
once per revolution (up to 5 s); sample the picture over one."""
for _ in range(steps):
game.sim_t += .5
game._update_esm_picture()
def test_category_for_ais_type_mapping():
assert _category_for_ais_type(65) == "PASSAGIER"
assert _category_for_ais_type(70) == "FRACHT"
@@ -596,7 +604,7 @@ def test_live_ship_is_not_published_without_simulated_sensor_detection(game):
game.air_picture = TrackPicture(game.air_picture.stale_s)
game.surface_radar_on = False
game._update_air_picture()
game._update_air_picture(full_scan=True)
assert not [track for track in game.air_picture.tracks(game.sim_t)
if track.target_id == live_ship.id]
@@ -608,7 +616,7 @@ def test_live_ship_is_radar_observed_and_manually_classifiable(game, monkeypatch
game.surface_radar_on = True
monkeypatch.setattr(game.world, "land_blocks_line", lambda *args: False)
game._update_air_picture()
game._update_air_picture(full_scan=True)
track = next(track for track in game.air_picture.tracks(game.sim_t)
if track.target_id == live_ship.id)
@@ -635,7 +643,7 @@ def test_live_ship_participates_in_lookout_and_eloka(game, monkeypatch):
for track in game.air_picture.tracks(game.sim_t))
live_ship.emitter = True
game._update_esm_picture()
esm_revolution(game)
assert game.eloka_tracks()
+6 -6
View File
@@ -46,7 +46,7 @@ def surface(game, distance):
def lookout(game):
game._update_air_picture()
game._update_air_picture(full_scan=True)
return [track for track in game.opz_tracks() if track.source == "LOOKOUT"]
@@ -186,7 +186,7 @@ def test_lookout_is_neutral_noisy_separate_and_does_not_mutate_global_rng(monkey
actor = surface(game, 5.0)
monkeypatch.setattr(game.world, "land_blocks_line", lambda *args: False)
global_state = random.getstate()
game._update_air_picture()
game._update_air_picture(full_scan=True)
visual = next(track for track in game.opz_tracks() if track.source == "LOOKOUT")
radar_key = f"W-{actor.id}"
assert not hasattr(visual, "target_id")
@@ -197,7 +197,7 @@ def test_lookout_is_neutral_noisy_separate_and_does_not_mutate_global_rng(monkey
first = copy.deepcopy(visual)
game.air_picture._tracks.clear()
game._update_air_picture()
game._update_air_picture(full_scan=True)
second = next(track for track in game.opz_tracks() if track.source == "LOOKOUT")
assert second == first
@@ -207,7 +207,7 @@ def test_visual_track_never_overwrites_radar_track(monkeypatch):
actor = surface(game, 5.0)
game.surface_radar_on = True
monkeypatch.setattr(game.world, "land_blocks_line", lambda *args: False)
game._update_air_picture()
game._update_air_picture(full_scan=True)
tracks = game.opz_tracks()
assert {track.source for track in tracks} == {"RADAR-S", "LOOKOUT"}
assert len({track.track_id for track in tracks}) == 2
@@ -234,7 +234,7 @@ def test_v2_roles_receive_only_authorized_new_picture_sources(monkeypatch):
intercept = game.eloka_tracks()[0]
game.eloka_annotations[intercept.track_key] = "emitter.warship_01.radar"
game._publish_released_esm()
game._update_air_picture()
game._update_air_picture(full_scan=True)
bridge, server = CommanderBridge(), Server()
bridge.pump(game, server, now=10.0)
@@ -266,7 +266,7 @@ def test_new_picture_sources_save_round_trip_validate_and_continue(monkeypatch):
intercept = game.eloka_tracks()[0]
game.eloka_annotations[intercept.track_key] = "emitter.warship_01.radar"
game._publish_released_esm()
game._update_air_picture()
game._update_air_picture(full_scan=True)
state = game.save_state()
assert Game._valid_save_document(state, game.runtime_catalog)
restored = Game(seed=1, start_menu=False, audio_enabled=False)
+31 -20
View File
@@ -3,6 +3,7 @@
from types import SimpleNamespace as NS
import pygame
import pytest
from src.core import config
from src.core.game import Game
@@ -131,39 +132,49 @@ def test_range_keys_cycle_display_scale_without_changing_sensor_maximum():
assert game.opz_range_nm == 40.0
press(game, pygame.K_PAGEUP)
assert game.opz_range_nm == 80.0
assert game.radar_effective_range("surface") == config.RADAR_SURFACE_RANGE_NM
before = game.radar_effective_range("surface")
press(game, pygame.K_PAGEUP)
assert game.radar_effective_range("surface") == before
def test_radar_sweep_bearing_turns_clockwise():
def test_radar_sweep_turns_clockwise_in_simulation_time():
game = opz_game()
game._t = 0.0
game.radar_scan_phase = 0.0
assert game.radar_sweep_bearing() == 0.0
game._t = 1.0
assert game.radar_sweep_bearing() == 90.0
game._t = 2.0
assert game.radar_sweep_bearing() == 180.0
game._t += 5.0 # wall time alone does not turn the antenna
assert game.radar_sweep_bearing() == 0.0
game.paused = False
for _ in range(10):
game._update_sim(0.1)
assert game.radar_sweep_bearing() == pytest.approx(90.0)
for _ in range(10):
game._update_sim(0.1)
assert game.radar_sweep_bearing() == pytest.approx(180.0)
def test_blip_glow_follows_sweep_and_then_expires():
game = opz_game()
game._t = 1.0 # Sweep steht auf Ost/90 Grad.
game.radar_scan_phase = 90.0 # Sweep steht auf Ost/90 Grad.
assert stations_view._radar_glow(game, 90.0) == 1.0
assert 0.0 < stations_view._radar_glow(game, 0.0) < 1.0
assert stations_view._radar_glow(game, 100.0) == 0.0
def test_weather_has_no_radar_effect_until_sea_state_five():
def test_sea_clutter_shortens_radar_range_progressively():
"""Radar equation with GIT-type sea clutter: small losses in moderate
seas, the 1.0.0 anchors (-12.5 % / -25 % surface) at sea state 5/6."""
game = opz_game()
for sea_state in range(5):
game.radar_rain_severity = lambda: 0.0 # isolate the clutter term
ranges = []
for sea_state in range(7):
game.world.sea_state = sea_state
assert game.radar_weather_severity() == 0.0
assert game.radar_effective_range("surface") == config.RADAR_SURFACE_RANGE_NM
assert game.radar_effective_range("air") == config.RADAR_AIR_RANGE_NM
game.world.sea_state = 5
assert game.radar_weather_severity() == .5
assert game.radar_effective_range("surface") < config.RADAR_RANGE_NM
game.world.sea_state = 6
assert game.radar_weather_severity() == 1.0
ranges.append(game.radar_effective_range("surface"))
assert game.radar_effective_range("air") <= config.RADAR_AIR_RANGE_NM
assert ranges == sorted(ranges, reverse=True)
assert ranges[0] == pytest.approx(config.RADAR_SURFACE_RANGE_NM, rel=.01)
assert ranges[4] >= .93 * config.RADAR_SURFACE_RANGE_NM
assert ranges[5] == pytest.approx(.875 * config.RADAR_SURFACE_RANGE_NM, rel=.02)
assert ranges[6] == pytest.approx(.75 * config.RADAR_SURFACE_RANGE_NM, rel=.01)
def test_separate_radars_publish_only_their_domains(monkeypatch):
@@ -180,13 +191,13 @@ def test_separate_radars_publish_only_their_domains(monkeypatch):
game.asms = []
game.surface_radar_on, game.air_radar_on = True, False
game._update_air_picture()
game._update_air_picture(full_scan=True)
assert {track.kind for track in game.opz_tracks()
if track.source.startswith("RADAR")} == {"SURFACE"}
game.air_picture._tracks.clear()
game.surface_radar_on, game.air_radar_on = False, True
game._update_air_picture()
game._update_air_picture(full_scan=True)
assert {track.kind for track in game.opz_tracks()
if track.source.startswith("RADAR")} == {"FLG"}
+224
View File
@@ -0,0 +1,224 @@
"""Phase 11: radar equation, antenna scan, ESM amplitude, HFDF, lookout."""
import copy
import json
import math
from types import SimpleNamespace
import pytest
from src.core import config
from src.core.game import LOOKOUT_MODEL, Game
from src.sensors import esm, hfdf, radar, visual
def test_swerling_cfar_detection_probability_is_anchored_at_snr_50():
assert radar.pd_from_sinr(radar.SNR_50) == pytest.approx(0.5)
values = [radar.pd_from_sinr(s) for s in (1.0, 10.0, 30.0, 100.0, 1000.0)]
assert values == sorted(values)
assert radar.pd_from_sinr(0.0) == 0.0
def test_radar_range_anchors_reproduce_the_legacy_ranges():
surface = radar.detection_range_nm(30.0, domain="surface")
assert surface == pytest.approx(30.0, rel=.01)
assert radar.detection_range_nm(30.0, domain="surface", sea_state=6) \
== pytest.approx(30.0 * .75, rel=.01)
assert radar.detection_range_nm(100.0, domain="air", rain_intensity=1.0) \
== pytest.approx(80.0, rel=.01)
# R^4: a -6 dB smaller target is seen at ~0.71 of the range.
assert radar.detection_range_nm(30.0, rcs_factor=.25) \
== pytest.approx(30.0 * .25 ** .25, rel=.02)
def test_self_screening_jammer_burns_through_at_the_profiled_range():
skin = radar.snr(8.0, 100.0)
for distance, expected in ((8.0, .5), (4.0, None), (20.0, None)):
jnr = radar.jammer_to_noise(distance, 8.0, skin)
pd = radar.pd_from_sinr(radar.sinr(distance, 100.0, domain="air", jnr=jnr))
if expected is not None:
assert pd == pytest.approx(expected, abs=.01)
inside = radar.pd_from_sinr(radar.sinr(
4.0, 100.0, domain="air", jnr=radar.jammer_to_noise(4.0, 8.0, skin)))
outside = radar.pd_from_sinr(radar.sinr(
20.0, 100.0, domain="air", jnr=radar.jammer_to_noise(20.0, 8.0, skin)))
assert inside > .5 > outside
def _surface_target_game(monkeypatch):
game = Game(seed=1101, start_menu=False, audio_enabled=False)
monkeypatch.setattr(game.world, "land_blocks_line", lambda *args: False)
civilian = game.civilians[0]
civilian.x, civilian.y = game.ship.x + 6.0, game.ship.y # bearing 090
civilian.emitter = False
game.civilians, game.warships, game.asms = [civilian], [], []
game.flights.flights = []
game.air_picture._tracks.clear()
return game, civilian
def test_contacts_are_looked_at_only_where_the_beam_swept(monkeypatch):
game, civilian = _surface_target_game(monkeypatch)
game.radar_scan_phase, game.radar_scan_pending_deg = 45.0, 40.0
game._update_air_picture()
assert not any(t.source == "RADAR-S" for t in game.air_picture.tracks(game.sim_t))
assert game.radar_scan_pending_deg == 0.0
game.radar_scan_phase, game.radar_scan_pending_deg = 100.0, 30.0
game._update_air_picture()
assert any(t.source == "RADAR-S" for t in game.air_picture.tracks(game.sim_t))
def test_antenna_turns_only_with_simulation_time():
game = Game(seed=1102, start_menu=False, audio_enabled=False)
game.radar_scan_phase = 0.0
game._t += 30.0
assert game.radar_sweep_bearing() == 0.0
for _ in range(20):
game._update_sim(0.1)
assert game.radar_sweep_bearing() == pytest.approx(
2.0 * config.RADAR_SWEEP_DEG_PER_S % 360.0)
def test_radar_scan_state_round_trips_and_is_validated():
game = Game(seed=1103, start_menu=False, audio_enabled=False)
game.radar_scan_phase, game.radar_scan_pending_deg = 123.5, 17.25
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.radar_scan_phase, restored.radar_scan_pending_deg) == (123.5, 17.25)
for key, value in (("scan_phase", 360.0), ("scan_pending_deg", -1.0),
("scan_phase", 5)):
broken = copy.deepcopy(state)
broken["radars"][key] = value
assert not restored._load_save_data(broken)
def _signal(role="surface_search", power="high", x=0.0, y=40.0, now=0.0):
return esm.RadarSignal("R0123456789abcdef", "emitter.test", 9.4e9, 1000.0,
"pulse", "search", esm.SignalType(role), x, y,
power, now)
def test_esm_hears_main_beam_far_and_side_lobes_only_close():
far = _signal(y=100.0) # 100 NM, inside the 150 NM high-power class
near = _signal(y=5.0)
hits = {"far": 0, "near": 0}
for step in range(40):
now = step * 0.5
for name, signal in (("far", far), ("near", near)):
if esm.scan_for_signals((signal,), observer_x=0.0, observer_y=0.0,
now=now, maximum_range_nm=150.0,
bearing_error_deg=3.0, noise_for=lambda s: 0.0):
hits[name] += 1
# 2.5 s rotation, 0.5 s dwell: the far emitter is heard once per turn.
assert 6 <= hits["far"] <= 12
assert hits["near"] == 40
def test_esm_track_measures_scan_period_level_and_range_estimate():
picture = esm.ESMPicture()
for step in range(60):
now = step * 0.5
picture.observe_batch(esm.scan_for_signals(
(_signal(y=60.0, now=now),), observer_x=0.0, observer_y=0.0, now=now,
maximum_range_nm=150.0, bearing_error_deg=3.0,
noise_for=lambda s: 0.0), now)
(track,) = picture.tracks(30.0)
assert track.revisit_s == pytest.approx(2.5, abs=.6)
assert esm.estimated_range_nm(track, "high") == pytest.approx(60.0, rel=.05)
assert esm.live_window_s(track) > esm.ECM_SIGNAL_FRESH_S
def test_hf_frequency_and_propagation_modes():
day = hfdf.transmit_frequency_mhz(7, 0, night=False)
night = hfdf.transmit_frequency_mhz(7, 0, night=True)
assert 2.0 <= night < day <= 30.0
ground = hfdf.ground_wave_range_nm(day, config.HFDF_RANGE_NM)
assert hfdf.propagation_mode(ground * .9, day, False, config.HFDF_RANGE_NM) == "GROUND"
skip = hfdf.skip_distance_nm(day, False)
assert skip > ground
assert hfdf.propagation_mode((ground + skip) / 2, day, False,
config.HFDF_RANGE_NM) is None
assert hfdf.propagation_mode(skip + 1.0, day, False, config.HFDF_RANGE_NM) == "SKY"
def test_hfdf_observation_carries_frequency_and_mode(monkeypatch):
game = Game(seed=1104, start_menu=False, audio_enabled=False)
monkeypatch.setattr(game.world, "land_blocks_line", lambda *args: False)
sub = game.subs[0]
sub.x, sub.y = game.ship.x + 20.0, game.ship.y
monkeypatch.setattr(type(sub), "transmitting", property(lambda self: True))
game.subs = [sub]
game._update_radio_picture()
(report,) = game.hfdf_bearings()
assert report.propagation == "GROUND"
assert 2e6 <= report.frequency_hz <= 30e6
assert report.range_nm is None
def test_lookout_follows_koschmieder_moon_and_sea_state():
kwargs = dict(visibility_nm=config.WEATHER_VISIBILITY_MAX_NM, night=False,
illumination=.5, sea_state=0.0)
def reach(kind, **changes):
low, high = .01, 60.0
for _ in range(50):
mid = (low + high) / 2
if LOOKOUT_MODEL.margin(kind, mid, **{**kwargs, **changes}) >= 1.0:
low = mid
else:
high = mid
return low
assert reach("SURFACE") == pytest.approx(config.LOOKOUT_SURFACE_RANGE_NM, rel=.01)
assert reach("SUB") == pytest.approx(config.LOOKOUT_SUB_RANGE_NM, rel=.01)
new_moon = reach("SURFACE", night=True, illumination=0.0)
full_moon = reach("SURFACE", night=True, illumination=1.0)
assert new_moon < reach("SURFACE", night=True) < full_moon < reach("SURFACE")
assert reach("SURFACE", night=True) == pytest.approx(
config.LOOKOUT_NIGHT_FACTOR * config.LOOKOUT_SURFACE_RANGE_NM, rel=.05)
assert reach("SURFACE", visibility_nm=2.0) < 2.0
assert reach("SUB", sea_state=4.0) < reach("SUB")
# Aircraft are seen against the sky: whitecaps do not hide them.
assert reach("FLG", sea_state=5.0, altitude_m=3000.0) == pytest.approx(
reach("FLG", altitude_m=3000.0))
assert visual.moon_illumination(0.0) == 0.0
assert visual.moon_illumination(visual.SYNODIC_MONTH_D / 2) == pytest.approx(1.0)
def test_radar_and_lookout_picture_is_deterministic():
def run():
game = Game(seed=1105, start_menu=False, audio_enabled=False)
game.world.land_blocks_line = lambda *args: False
game.civilians[0].x, game.civilians[0].y = game.ship.x + 8.0, game.ship.y
game.flights.flights[0].x = game.ship.x - 30.0
game.flights.flights[0].y = game.ship.y
for _ in range(200):
game._update_sim(0.1)
# Entity IDs come from process-wide counters; compare measurements.
return sorted((t["source"], round(t["bearing"], 9), t["range_nm"],
t["last_seen"]) for t in game.air_picture.serialize()
if t["source"] in ("RADAR-S", "RADAR-L", "LOOKOUT"))
first = run()
assert first and first == run()
def test_ciws_track_radar_holds_close_in_missiles_between_sweeps(monkeypatch):
from src.air.asm import ASM
from src.core.game import CIWS_TRACK_RANGE_NM
game = Game(seed=1106, start_menu=False, audio_enabled=False)
monkeypatch.setattr(game.world, "land_blocks_line", lambda *args: False)
asm = ASM(game.ship.x + CIWS_TRACK_RANGE_NM - 0.5, game.ship.y, 270.0, 3,
game.rng_asm, game._air_defense_loadout["asm"])
asm.jammer = False
game.asms = [asm]
game.radar_scan_phase, game.radar_scan_pending_deg = 0.0, 10.0 # beam north
game._update_air_picture()
assert game.asm_tracks()
game.air_picture._tracks.clear()
game.ciws_authorized = False
game.radar_scan_pending_deg = 10.0
game._update_air_picture()
assert not game.asm_tracks()
+14 -4
View File
@@ -12,6 +12,16 @@ from src.sonar.sonar import Contact, SonarSystem
from src.weapons.torpedo import Torpedo
def scan_until_asm_track(game, revolutions=6):
"""Swerling-1 fluctuation: a single look may miss; the track forms
within a few antenna revolutions."""
for _ in range(revolutions):
game.sim_t += 4.0
game._update_air_picture(full_scan=True)
if game.asm_tracks():
return
def press(game, key):
game.handle_event(pygame.event.Event(pygame.KEYDOWN, key=key))
@@ -21,11 +31,11 @@ def test_radar_off_does_not_publish_ground_truth_asm():
game.asms = [ASM(game.ship.x + 10.0, game.ship.y, 0.0, 7, game.rng_asm)]
game.air_picture._tracks.clear()
game.radar_on = False
game._update_air_picture()
game._update_air_picture(full_scan=True)
assert game.asm_tracks() == []
game.radar_on = True
game._update_air_picture()
scan_until_asm_track(game)
tracks = game.radar_tracks()
assert len([track for track in tracks if track["kind"] == "ASM"]) == 1
assert "obj" not in tracks[0]
@@ -39,7 +49,7 @@ def test_essm_requires_sensor_track_not_live_asm_object():
game.launch_essm()
assert game.vls_cells == before and not game.essms
game._update_air_picture()
scan_until_asm_track(game)
game.launch_essm()
assert game.vls_cells == before - 1 and len(game.essms) == 1
@@ -48,7 +58,7 @@ def test_essm_rejects_track_outside_engagement_envelope():
game = Game(seed=457, start_menu=False)
game.asms = [ASM(game.ship.x + game._air_defense_loadout["sam"]["range_nm"] + 5.0,
game.ship.y, 0.0, 9, game.rng_asm)]
game._update_air_picture()
game._update_air_picture(full_scan=True)
before = game.vls_cells
game.launch_essm()
assert game.vls_cells == before
+1 -1
View File
@@ -43,7 +43,7 @@ def test_air_picture_skips_terrain_queries_for_ineligible_sources(monkeypatch):
ship.emitter = False
monkeypatch.setattr(game.world, "land_blocks_line", lambda *a:
pytest.fail("ineligible sensors must reject before terrain work"))
game._update_air_picture()
game._update_air_picture(full_scan=True)
def test_lost_sonar_fix_is_not_retained_by_common_picture():
+10 -2
View File
@@ -53,6 +53,14 @@ def observed_target(game, target_id):
return contact
def esm_revolution(game, steps=12):
"""Rotating search radars reach the ESM mast with their main beam only
once per revolution (up to 5 s); sample the picture over one."""
for _ in range(steps):
game.sim_t += .5
game._update_esm_picture()
@pytest.mark.parametrize("kind", ["sub", "civilian", "animal", "decoy", "missing"])
@pytest.mark.parametrize("launcher", ["launch_torpedo", "launch_helo_torpedo"])
def test_launch_authorization_is_observation_equivalent_across_hidden_categories(game, kind, launcher):
@@ -270,7 +278,7 @@ def test_aircraft_receiver_capability_does_not_make_it_an_emitter(game):
civil.esm = True
game.flights.flights = [civil]
game.radar_on = False
game._update_air_picture()
game._update_air_picture(full_scan=True)
game._update_esm_picture()
assert not game.air_picture.tracks(game.sim_t)
assert not game.eloka_tracks()
@@ -280,7 +288,7 @@ def test_aircraft_receiver_capability_does_not_make_it_an_emitter(game):
military.esm = False
military.esm_range_nm = 1 # Its receiver range is not the player's receiver range.
game.flights.flights = [military]
game._update_esm_picture()
esm_revolution(game)
assert len(game.eloka_tracks()) == 1
assert not game.air_picture.tracks(game.sim_t)
+1 -1
View File
@@ -119,7 +119,7 @@ def test_radar_track_has_no_truth_name_or_course_until_ais_report():
civil = _civilian_near(game, 4.0)
game.ais.reports.clear()
game.ais.update = lambda *args, **kwargs: None # receiver silent
game._update_air_picture()
game._update_air_picture(full_scan=True)
track = game.air_picture._tracks[f"S-{civil.id}"]
assert track.label == f"S-{civil.id}"
assert track.course is None
+3 -3
View File
@@ -190,7 +190,7 @@ def test_correlated_bearing_sources_have_continuous_displayed_steps(monkeypatch)
displayed = {"ESM": [], "HOJ": [], "HFDF": []}
for now in (9.5, 10.0, 10.5):
game.sim_t = now
game._update_air_picture()
game._update_air_picture(full_scan=True)
game._update_esm_picture()
game._update_radio_picture()
displayed["ESM"].append(game.eloka_tracks()[0].bearing)
@@ -287,12 +287,12 @@ def test_hoj_noise_uses_simulation_time_not_cosmetic_time():
game.warships = []
game.flights.flights = []
game.sim_t, game._t = 7.0, 1.0
game._update_air_picture()
game._update_air_picture(full_scan=True)
first = game.air_picture._tracks["M-17"].raw_bearing
game.air_picture._tracks.clear()
game._t = 10000.0
game._update_air_picture()
game._update_air_picture(full_scan=True)
assert game.air_picture._tracks["M-17"].raw_bearing == first
+64 -1
View File
@@ -285,7 +285,11 @@ def measure_radar() -> dict:
altitude_m=100.0)
before = len(game.air_picture._tracks)
game.sim_t += 10.0
game._lookout_observe(actor, namespace, kind, base, 12345 + step)
try:
game._lookout_observe(actor, namespace, kind, 12345 + step,
altitude_m=100.0 if kind == "FLG" else None)
except TypeError: # 1.0.0 signature (golden recording)
game._lookout_observe(actor, namespace, kind, base, 12345 + step)
seen = len(game.air_picture._tracks) > before
if seen:
low = mid
@@ -391,6 +395,64 @@ def measure_damage() -> dict:
return out
# --------------------------------------------------------------------------
# Air defence (added with phase 11; golden values measured on the 1.0.0
# tree with this same probe)
def _air_game(seed):
from src.core import config
from src.core.game import Game
game = Game(seed=seed, start_menu=False, audio_enabled=False)
game.world.land_blocks_line = lambda *args: False
game.subs, game.warships, game.civilians, game.raiders = [], [], [], []
game.flights.flights = []
game.mission.asm_count = 0
game.ship.speed = game.ship.target_speed = 0.0
game.ship.order_idx = next(i for i, item in enumerate(config.TELEGRAPH_ORDERS)
if item[1] == 0.0)
game.paused = False
return game
def _air_run(seed, *, ciws, chaff_at=None, distance=30.0, max_s=400.0, dt=0.1):
from src.air.asm import ASM
game = _air_game(seed)
game.ciws_authorized = ciws
asm = ASM(game.ship.x + distance, game.ship.y, 270.0, 1, game.rng_asm,
game._air_defense_loadout["asm"])
asm.jammer = False
game.asms = [asm]
elapsed, chaffed = 0.0, False
while elapsed < max_s:
if (chaff_at is not None and not chaffed
and math.hypot(asm.x - game.ship.x, asm.y - game.ship.y) <= chaff_at):
tracks = game.asm_tracks()
if tracks:
game.launch_chaff_at(tracks[0])
chaffed = True
game._update_sim(dt)
elapsed += dt
if asm.state in ("TREFFER", "ABGEFANGEN", "VERLOREN"):
break
return asm.state, elapsed
def measure_air() -> dict:
out = {}
_state, elapsed = _air_run(1, ciws=False)
out["air.asm.time_to_impact_s.30nm"] = _metric(elapsed, "transient")
samples = 40
leaks = sum(_air_run(100 + seed, ciws=True)[0] == "TREFFER"
for seed in range(samples))
out["air.ciws.leak_fraction"] = _metric(leaks / samples, "statistic")
leaks = sum(_air_run(300 + seed, ciws=False, chaff_at=7.0)[0] == "TREFFER"
for seed in range(samples))
out["air.chaff.leak_fraction"] = _metric(leaks / samples, "statistic")
return out
SECTIONS = {
"ship": measure_ship,
"sonar": measure_sonar,
@@ -398,6 +460,7 @@ SECTIONS = {
"torpedo": measure_torpedo,
"sub": measure_sub,
"damage": measure_damage,
"air": measure_air,
}