A new section, alongside the aircraft, the weather sensors and APRS. FT8 is the odd one out among the things this program listens to, and the reason is worth stating because it shapes everything below. Every station on the band transmits in the same quarter-minute slots, on the same dial frequency, fifty hertz wide each, stacked across three kilohertz of audio. One receiver parked on one frequency therefore hears the whole band's worth of stations at once -- and hears most of them well below the noise, because half of what is sent is error-correcting code. That is the entire trick: a rate of about one half buys a mode that decodes twenty-odd decibels under what an operator can hear. A receiver that took the loudest tone of each symbol and hoped would decode almost nothing, which is why the tone detector reports how confident it is bit by bit rather than what it thinks it heard. Written from first principles except for two tables. The checksum, the belief propagation over the sparse graph, the Costas sync search, the waterfall, the soft-bit metric, and the seventy-seven bits that hold two callsigns and a grid square are all here. The generator and the parity-check matrix are not: they cannot be derived, being the code itself rather than consequences of anything, so they are taken from ft8_lib under its MIT licence with the attribution it asks for, and said so in the readme, the manual and the file. No decoding logic came with them. That the two agree -- and they are not derivable from one another, the generator's parity half running to fifty-odd bits a row against the sparse matrix's six or seven -- is a test rather than an assumption. Tested against the air, not against itself. Eleven off-air recordings with published decodes: ninety-seven of a hundred and fifty messages, no false decodes, timing within a hundredth of a second, frequency within a hertz, signal reports within half a decibel on average. The third not decoded are the weakest in each slot; a mature decoder subtracts what it has decoded and looks again in the remainder, and does ordered-statistics decoding where belief propagation fails, and neither is built here. What is here decodes nothing that other receivers did not also hear, which is the property that matters in a log. Ten whole codewords lifted off the air are in the tests as a permanent fixture, so the recordings can go missing and the regression cannot. Three things that looked like bugs and were not, and three that were. The half-second timing discrepancy was the convention: a transmission is 12.64 seconds in a slot of fifteen and everybody starts half a second in, so lateness is reported against that. Synthetic signals at known offsets proved the clock self-consistent before anything was changed. The signal reports were twenty-one decibels optimistic because those recordings have a receiver passband above three kilohertz, putting a whole-band median twelve to sixteen decibels below the real noise floor -- so noise is now measured beside the signal, and in the tone that was actually sent rather than the loudest of eight, the largest of eight noisy numbers being well above their mean even with no signal at all. And the test transmitter was thirteen decibels pessimistic, scaling its noise into a fifty-hertz reference instead of the sampled bandwidth, which made the decoder look deaf when it was the test signal that had been quietly attenuated. The real bug the simulator caught was a one-block timestamp error: samples were dated a block earlier than they were taken, which slid every slot slice a second late and cut the first half-second -- three symbols, part of the opening Costas array -- off every transmission on the band. One decode a slot became six. Reachable both ways, as everything here is. Twenty-one options, every one of them a command-line flag and a line in the menu, both built from one table so they cannot disagree -- and a test that says so, since an option in no group would be settable from the command line and invisible in the menu. The band list says which channels a plain dongle can reach and which need an upconverter, because almost all the activity is on shortwave and finding that out by listening to silence for ten minutes is the wrong way to learn it. The default is two metres, which a plain dongle can hear. --grid turns decodes into geography: every CQ says where it is, so each gets a distance and a bearing and the furthest is named. --adif writes the log in the form every amateur logging program imports, marked as heard rather than worked, because nothing here transmits and an ADIF that let a logging program treat these as contacts would put claims into somebody's log that they cannot make. One bug shipped and found by being used rather than by being tested: the line that opens the receiver called a function this program has never had. Every test reached it through the simulator, which takes the other branch, so the one line that matters to somebody with an aerial was the one line never run. There is now a check that every name these modules import actually exists -- it names the missing one rather than failing somewhere downstream -- and two that say a receiver which cannot be opened is reported rather than raised, and that nothing claims to be listening before there is one. It had been announcing the frequency first, so a dongle that would not open read as listening that had gone wrong. Ninety-six new tests. Full suite 2781 passed. Built as 2026-09-21_04. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016PsWPTweCT6pwxKngvVxcg
172 lines
7 KiB
Python
172 lines
7 KiB
Python
"""A made-up FT8 band, on a real clock.
|
|
|
|
For trying the display, the report and the exports without an aerial, and
|
|
for testing the whole path from samples to tables. It stands in for a
|
|
receiver: same `tune`, `read_samples` and `close`, same sample rate, same
|
|
complex samples.
|
|
|
|
What it cannot tell you is whether your receiver hears anything, which is
|
|
the one question a simulator is never allowed to answer. It is also the
|
|
lesson this project learned expensively on another band: an encoder tested
|
|
against its own decoder agrees with it about anything they are both wrong
|
|
about. So the decoding is tested against real off-air recordings; this is
|
|
here for the parts above the decoding.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import math
|
|
import time
|
|
|
|
import numpy as np
|
|
|
|
from . import ft8code as code
|
|
from . import ft8wave as wave
|
|
|
|
__all__ = ["SimulatedBand", "CALLS", "GRIDS"]
|
|
|
|
# A plausible spread: a few continents, a few strengths, a few habits.
|
|
CALLS = ("G4UJS", "SP4FCA", "IK4LZH", "EA1ABT", "DL1UDO", "OH8GDU",
|
|
"JA2GQT", "VK4BLE", "RA6ABO", "F4FSY", "K1ABC", "W2XYZ",
|
|
"PA3EPP", "SM0ABC", "LZ1LZ", "9A9TT", "ZS6ABC", "LU1AAA")
|
|
GRIDS = ("IO83", "KO03", "JN54", "IN73", "JO31", "KP24",
|
|
"PM85", "QG62", "KN96", "JN25", "FN42", "FN20",
|
|
"JO21", "JO99", "KN12", "JN75", "KG33", "GF05")
|
|
|
|
|
|
class SimulatedBand:
|
|
"""A receiver that invents a band of FT8 stations.
|
|
|
|
Paced against the real clock, because everything about FT8 is: the
|
|
slots are quarter-minutes of UTC, and a simulator that produced fifteen
|
|
seconds of audio instantly would make the section look as though it
|
|
worked while testing none of the timing that makes it work.
|
|
"""
|
|
|
|
def __init__(self, rate: float = 240_000.0, seed: int = 0,
|
|
stations: int = 12, realtime: bool = True,
|
|
clock=time.time, sleep=time.sleep):
|
|
self.rate = float(rate)
|
|
self.frequency = 0.0
|
|
self.rng = np.random.default_rng(seed)
|
|
self.stations = max(1, int(stations))
|
|
self.realtime = realtime
|
|
self.clock = clock
|
|
self.sleep = sleep
|
|
self.closed = False
|
|
self._audio_rate = 12_000
|
|
self._made: dict[float, np.ndarray] = {}
|
|
self._one_sided: dict[float, np.ndarray] = {}
|
|
self._at = None
|
|
|
|
# -- the receiver's shape -------------------------------------------
|
|
def tune(self, hz: float) -> None:
|
|
self.frequency = float(hz)
|
|
|
|
def close(self) -> None:
|
|
self.closed = True
|
|
|
|
def read_samples(self, count: int):
|
|
"""A block of samples, paced to take as long as it would on the air."""
|
|
if self.closed:
|
|
return None
|
|
now = self.clock()
|
|
if self._at is None:
|
|
self._at = now
|
|
wanted = count / self.rate
|
|
if self.realtime:
|
|
behind = self._at + wanted - self.clock()
|
|
if behind > 0:
|
|
self.sleep(behind)
|
|
block = self._samples_for(self._at, count)
|
|
self._at += wanted
|
|
return block
|
|
|
|
# -- making the band ------------------------------------------------
|
|
def _slot_audio(self, slot_at: float) -> np.ndarray:
|
|
"""One slot of the band, at twelve kilohertz, made once and kept."""
|
|
have = self._made.get(slot_at)
|
|
if have is not None:
|
|
return have
|
|
rng = np.random.default_rng(int(slot_at) & 0xFFFFFFFF)
|
|
total = int(self._audio_rate * code.SLOT_S)
|
|
audio = rng.standard_normal(total).astype(np.float32) * 0.02
|
|
# Stations pick a frequency and keep it, mostly, and take turns.
|
|
even = int(slot_at / code.SLOT_S) % 2 == 0
|
|
for i in range(self.stations):
|
|
if (i % 2 == 0) != even:
|
|
continue
|
|
call = CALLS[(i + int(slot_at / code.SLOT_S) // 2) % len(CALLS)]
|
|
grid = GRIDS[CALLS.index(call)]
|
|
other = CALLS[(i * 7 + 3) % len(CALLS)]
|
|
pick = rng.integers(0, 3)
|
|
if pick == 0:
|
|
text = f"CQ {call} {grid}"
|
|
elif pick == 1:
|
|
text = f"{other} {call} {grid}"
|
|
else:
|
|
text = f"{other} {call} {rng.integers(-24, 5):+03d}"
|
|
hertz = 300.0 + i * 190.0 + float(rng.integers(-30, 30))
|
|
strength = float(rng.uniform(-18.0, 10.0))
|
|
one = wave.transmit(text, rate=float(self._audio_rate),
|
|
hertz=hertz,
|
|
offset=0.5 + float(rng.uniform(-0.3, 0.6)),
|
|
seconds=code.SLOT_S)
|
|
scale = 10.0 ** (strength / 20.0) * 0.05
|
|
audio[:one.size] += (one * scale).astype(np.float32)
|
|
if len(self._made) > 2:
|
|
self._made.clear()
|
|
self._made[slot_at] = audio
|
|
return audio
|
|
|
|
def _samples_for(self, at: float, count: int):
|
|
"""Complex samples covering ``count`` samples from ``at``.
|
|
|
|
The band is made as audio and then put back on a carrier, which is
|
|
the reverse of what the section does to it. One-sided, so that
|
|
what comes out of the demodulator is what went in: a real audio
|
|
tone at 1000 Hz has to arrive as a complex tone at +1000 Hz, or
|
|
upper sideband and lower sideband would be the same thing.
|
|
|
|
Held at the audio rate and stepped through, rather than properly
|
|
resampled. The images that leaves sit at multiples of twelve
|
|
kilohertz and the demodulator's own decimation filter removes them
|
|
-- which is worth saying out loud, because it means this simulator
|
|
leans on the thing it is being used to test. That is tolerable for
|
|
the display and the report, and is exactly why the decoding itself
|
|
is tested against real recordings instead.
|
|
"""
|
|
out = np.zeros(count, dtype=np.complex64)
|
|
step = 1.0 / self.rate
|
|
ratio = self._audio_rate / self.rate
|
|
for k in range(0, count, 4096):
|
|
piece = min(4096, count - k)
|
|
when = at + k * step
|
|
slot_at = math.floor(when / code.SLOT_S) * code.SLOT_S
|
|
audio = self._analytic_slot(slot_at)
|
|
into = (when - slot_at) * self._audio_rate
|
|
idx = np.clip((into + np.arange(piece) * ratio).astype(np.int64),
|
|
0, audio.size - 1)
|
|
out[k:k + piece] = audio[idx].astype(np.complex64)
|
|
return out
|
|
|
|
def _analytic_slot(self, slot_at: float) -> np.ndarray:
|
|
have = self._one_sided.get(slot_at)
|
|
if have is None:
|
|
have = _analytic(self._slot_audio(slot_at))
|
|
# Two slots kept: a block of samples commonly straddles a
|
|
# boundary, and rebuilding a slot for every such block is most
|
|
# of the simulator's time.
|
|
if len(self._one_sided) > 2:
|
|
self._one_sided.clear()
|
|
self._one_sided[slot_at] = have
|
|
return have
|
|
|
|
|
|
def _analytic(real_audio: np.ndarray) -> np.ndarray:
|
|
"""The one-sided version of a real signal: no energy below zero."""
|
|
spectrum = np.fft.fft(real_audio)
|
|
n = spectrum.size
|
|
spectrum[n // 2 + 1:] = 0.0
|
|
spectrum[1:(n + 1) // 2] *= 2.0
|
|
return np.fft.ifft(spectrum)
|