Loading files
#!/usr/bin/env python
"""
gen_headers.py - emit main/generated/ from the sealed Stage-0 artifacts.
NOTHING here is hand-copied. Every constant, table and sample comes from a
read-only source of truth:
data/device_config.json every detector constant + the two presets
src/detector.py instantiated to export its OWN gather tables
data/golden_*.h the three vectors, copied byte for byte
Outputs (all deterministic - byte-identical for identical inputs, no
timestamps, no dict ordering surprises):
detector_config.h constants, NORMAL_THRESHOLD and DEFAULT_THRESHOLD
window.h np.hanning(2048) as float32
tables.h t_i0 / t_fr / g_i0 / g_fr / tw / gw / znorm / n_tooth
golden_*.h the three vectors, unmodified
Float formatting is exact by construction: %.9g round-trips any float32 and
%.17g any float64 (IEEE-754 guarantees), so no value is approximated on its
way into the firmware.
Run: conda run -n acoustic-detector python scripts/gen_headers.py --out DIR
"""
import argparse
import hashlib
import json
import math
import shutil
import sys
from pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parent
PROJ = HERE.parent # firmware/sentry_node
ROOT = PROJ.parent.parent # repo root
SRC = ROOT / "src"
DATA = ROOT / "data"
sys.path.insert(0, str(SRC))
import detector as D # noqa: E402
import operating_point as op # noqa: E402
BANNER = ("// GENERATED by firmware/sentry_node/scripts/gen_headers.py - "
"DO NOT EDIT.\n"
"// Source of truth: data/device_config.json + src/detector.py.\n"
"// Regenerate with the build; a stale copy cannot be linked.\n")
def _decimal(s):
"""Force a floating-point token. "%.9g" of 0.0 is "0", and "0f" is an
invalid integer suffix, not a float."""
if not any(c in s for c in ".eEnif"):
s += ".0"
return s
def f32(x):
"""A C float literal that round-trips to exactly this float32."""
v = np.float32(x)
if not np.isfinite(v):
raise ValueError(f"non-finite constant {x}")
return _decimal(f"{float(v):.9g}") + "f"
def f64(x):
if not np.isfinite(x):
raise ValueError(f"non-finite constant {x}")
return _decimal(f"{float(x):.17g}")
def emit_array(name, values, ctype, fmt, per_line, extra="static const"):
out = [f"{extra} {ctype} {name}[{len(values)}] = {{"]
line = " "
for i, v in enumerate(values):
tok = fmt(v) + ","
if len(line) + len(tok) > 78:
out.append(line)
line = " "
line += " " + tok
if line.strip():
out.append(line)
out.append("};")
return "\n".join(out)
# ---------------------------------------------------------------------------
def gen_detector_config(cfg, dcfg):
d = dcfg["detector"]
fr = dcfg["frame"]
det = D.CombDetector(cfg)
n_f0 = len(det.f0s)
# Cross-check: the Config the tables came from must equal device_config.
live = cfg.to_dict()
drift = {k: (live[k], v) for k, v in d.items()
if k in live and live[k] != v}
if drift:
raise SystemExit(f"device_config.json disagrees with the committed "
f"Config: {drift}")
L = [BANNER, "#pragma once", "#include <stdint.h>", ""]
L.append("// ---- identity -------------------------------------------")
L.append(f'#define SENTRY_SITE "{dcfg["site"]}"')
L.append(f'#define SENTRY_CORPUS_TAG "{dcfg["corpus_tag"]}"')
L.append(f'#define SENTRY_CONFIG_SCHEMA "{dcfg["schema"]}"')
L.append("")
L.append("// ---- the two operating points ---------------------------")
L.append("// NORMAL_THRESHOLD is the PARITY point: the golden vectors were")
L.append("// cut at it and the port is judged against it.")
L.append("// DEFAULT_THRESHOLD is the DEPLOYMENT default (HIGH_ALERT); it")
L.append("// is not exercised by the golden vectors. Two names, on")
L.append("// purpose - conflating them would silently rejudge the port.")
L.append(f'#define SENTRY_DEFAULT_PRESET "{dcfg["default_preset"]}"')
L.append(f'#define NORMAL_THRESHOLD '
f'{f64(dcfg["presets"]["NORMAL"]["threshold"])}')
L.append(f'#define HIGH_ALERT_THRESHOLD '
f'{f64(dcfg["presets"]["HIGH_ALERT"]["threshold"])}')
L.append(f'#define DEFAULT_THRESHOLD HIGH_ALERT_THRESHOLD')
L.append(f'#define GOLDEN_THRESHOLD NORMAL_THRESHOLD')
L.append("")
L.append("// ---- frame geometry -------------------------------------")
for k in ("fs", "n_fft", "hop"):
L.append(f"#define CFG_{k.upper():<16} {int(d[k])}")
L.append(f"#define CFG_N_BINS {int(fr['n_bins'])}")
L.append(f"#define CFG_N_CHANNELS 1 // combiner is identity at N=1")
L.append(f"#define CFG_BIN_WIDTH_HZ {f64(fr['bin_width_hz'])}")
L.append(f"#define CFG_FRAME_PERIOD_S {f64(fr['frame_period_s'])}")
L.append(f"#define CFG_CYCLES_PER_FRAME {f64(fr['cycles_at_240mhz'])}")
L.append("")
L.append("// ---- candidate grid / comb ------------------------------")
L.append(f"#define CFG_N_F0 {n_f0}")
L.append(f"#define CFG_F_SEARCH_LO {f64(d['f_search_lo'])}")
L.append(f"#define CFG_F_SEARCH_HI {f64(d['f_search_hi'])}")
L.append(f"#define CFG_F_STEP {f64(d['f_step'])}")
L.append(f"#define CFG_N_HARM_MAX {int(d['n_harm_max'])}")
L.append(f"#define CFG_N_HARM_MIN {int(d['n_harm_min'])}")
L.append(f"#define CFG_F_MAX_HARM {f64(d['f_max_harm'])}")
L.append(f"#define CFG_TEETH_LEVEL {f32(d['teeth_level'])}")
L.append(f"#define CFG_SAT_LOG {f64(d['sat_log'])}")
L.append(f"#define CFG_SAT_LOG_F {f32(d['sat_log'])}")
L.append("")
L.append("// ---- alert bands ----------------------------------------")
for k in ("f_alert_lo", "f_alert_hi", "f_prio_lo", "f_prio_hi",
"thr_off_prio", "thr_off_gen"):
L.append(f"#define CFG_{k.upper():<16} {f64(d[k])}")
L.append("")
L.append("// ---- tonality floor (COMMITTED) -------------------------")
L.append(f'#define CFG_FLOOR_MODE_TONALITY 1 // "{d["floor_mode"]}"')
for k in ("tau_rise_s", "tau_fall_s", "tau_rise_fast_s", "tau_energy_s",
"gate_ratio", "flat_hi"):
L.append(f"#define CFG_{k.upper():<16} {f64(d[k])}")
L.append("")
L.append("// Smoothing coefficients are exp(-hop/fs/tau) evaluated ON THE")
L.append("// HOST in float64 and frozen here, so the device never depends")
L.append("// on its own libm agreeing with numpy's.")
L.append(f"#define CFG_A_RISE {f64(det.a_rise)}")
L.append(f"#define CFG_A_FALL {f64(det.a_fall)}")
L.append(f"#define CFG_A_RISE_FAST {f64(det.a_rise_fast)}")
L.append(f"#define CFG_A_ENERGY {f64(det.a_energy)}")
L.append("")
L.append("// ---- tracker --------------------------------------------")
L.append(f"#define CFG_T_WARMUP_S {f64(d['t_warmup_s'])}")
L.append(f"#define CFG_TRACK_NEED {int(d['track_need'])}")
L.append(f"#define CFG_TRACK_MISS {int(d['track_miss'])}")
L.append(f"#define CFG_CONT_FRAC {f64(d['cont_frac'])}")
L.append(f"#define CFG_CONT_MIN_HZ {f64(d['cont_min_hz'])}")
L.append(f"#define CFG_MAX_JITTER {f64(d['max_jitter'])}")
L.append(f"#define CFG_MIN_TEETH {int(d['min_teeth'])}")
L.append("")
L.append("// ---- the voice and struck-note veto ---------------------")
L.append("// Calibrated; docs/VETO_CAL.md holds the whole")
L.append("// measurement including two mechanisms rejected before this")
L.append("// one. These constants are INERT unless the runtime flag")
L.append("// veto_voice is set, and the branch that reads them is")
L.append("// unreachable while it is clear, so a cleared flag is")
L.append("// bit-identical to the sealed detector by construction.")
L.append(f"#define CFG_VETO_F0_MIN_HZ {f64(d['veto_f0_min_hz'])}")
L.append(f"#define CFG_VETO_MIN_TEETH {int(d['veto_min_teeth'])}")
L.append("")
L.append("// ---- REJECTED features: tripwires, not switches ---------")
for k, v in sorted(dcfg["disabled_features"].items()):
L.append(f"// {k} = {json.dumps(v['value'])}: {v['why']}")
L.append("#define CFG_REANCHOR_ENABLED 0 // no code path exists")
L.append("#define CFG_HOLD_ENABLED 0 // no code path exists")
L.append("_Static_assert(CFG_REANCHOR_ENABLED == 0,")
L.append(' "re-anchoring was rejected; see docs/");')
L.append("_Static_assert(CFG_HOLD_ENABLED == 0,")
L.append(' "comb-hold was rejected; see docs/");')
L.append("")
L.append("// ---- trace field order (device_config.json trace_fields) -")
L.append("// " + ", ".join(dcfg["trace_fields"]))
L.append(f"#define TRACE_N_FIELDS {len(dcfg['trace_fields'])}")
L.append("")
return "\n".join(L) + "\n"
def gen_t2_config(cfg, t2doc):
"""generated/t2_config.h - Tier-2's constants, from data/t2_config.json.
ADDITIVE. Nothing here touches detector_config.h, and no v1 constant is
read, written or re-derived. The T2 grid is expressed as ROW INDICES into
the existing gather tables, never as a second table: if these two rows ever
stopped agreeing with f_search_lo/f_step, T2 would be scoring a comb at a
frequency it was not told about, so the derivation is asserted here and
again as a _Static_assert on the device.
"""
import detector_t2 as T2
t2 = T2.T2Config.from_dict(t2doc["t2"])
det = D.CombDetector(cfg)
row_lo, row_hi = det._idx(t2.f2_lo), det._idx(t2.f2_hi)
if row_lo < 0 or row_hi < row_lo:
raise SystemExit(f"T2 band {t2.f2_lo}-{t2.f2_hi} Hz is not inside the "
f"v1 search grid")
n_rows = row_hi - row_lo + 1
if abs(det.f0s[row_lo] - t2.f2_lo) > 1e-9 or \
abs(det.f0s[row_hi] - t2.f2_hi) > 1e-9:
raise SystemExit("T2 band does not land on the v1 grid exactly")
dt = cfg.hop / cfg.fs
half = t2doc.get("derived_half_rate", {})
L = [BANNER, "#pragma once", "#include <stdint.h>",
'#include "detector_config.h"', ""]
L.append("// ---- Tier-2. ADDITIVE: no v1 constant is affected.")
L.append("// Source of truth: data/t2_config.json, written by")
L.append("// src/evaluate_t2.py --calibrate.")
L.append(f'#define T2_CORPUS_TAG "{t2doc.get("corpus_tag", "")}"')
L.append(f'#define T2_CALIBRATED {1 if t2doc.get("calibrated", True) else 0}')
L.append("")
L.append("// ---- search band: ROWS OF THE EXISTING TABLES, not new ones")
L.append(f"#define T2_F_LO {f64(t2.f2_lo)}")
L.append(f"#define T2_F_HI {f64(t2.f2_hi)}")
L.append(f"#define T2_ROW_LO {row_lo}")
L.append(f"#define T2_ROW_HI {row_hi}")
L.append(f"#define T2_N_F0 {n_rows}")
L.append("_Static_assert(T2_ROW_LO == (int)((T2_F_LO - CFG_F_SEARCH_LO)")
L.append(" / CFG_F_STEP + 0.5),")
L.append(' "T2 row_lo is not the v1 grid index of T2_F_LO");')
L.append("_Static_assert(T2_ROW_HI < CFG_N_F0,")
L.append(' "T2 band runs off the end of the v1 tables");')
L.append("")
L.append("// ---- floor2: asymmetric exponential, NO tonality gate ------")
L.append("// Coefficients are exp(-hop/fs/tau) evaluated ON THE HOST in")
L.append("// float64 and frozen, so the device never depends on its own")
L.append("// libm agreeing with numpy's. Same discipline as CFG_A_RISE.")
L.append(f"#define T2_TAU_RISE_S {f64(t2.tau2_rise_s)}")
L.append(f"#define T2_TAU_FALL_S {f64(t2.tau2_fall_s)}")
L.append(f"#define T2_A_UP {f64(math.exp(-dt / t2.tau2_rise_s))}")
L.append(f"#define T2_A_DN {f64(math.exp(-dt / t2.tau2_fall_s))}")
L.append("// half rate: the SAME time constants, stepped half as often")
L.append(f"#define T2_A_UP_HALF {f64(math.exp(-2 * dt / t2.tau2_rise_s))}")
L.append(f"#define T2_A_DN_HALF {f64(math.exp(-2 * dt / t2.tau2_fall_s))}")
L.append("")
L.append("// ---- decision ---------------------------------------------")
L.append(f"#define T2_TAU2 {f64(t2.tau2)}")
L.append(f"#define T2_N2 {t2.n2}")
L.append(f"#define T2_M2 {t2.m2}")
L.append(f"#define T2_GAP {t2.n2_gap}")
L.append(f"#define T2_RELEASE {t2.release_frames}")
L.append(f"#define T2_WARMUP_S {f64(t2.t2_warmup_s)}")
L.append(f"#define T2_CONT_FRAC {f64(t2.cont_frac)}")
L.append(f"#define T2_CONT_MIN_HZ {f64(t2.cont_min_hz)}")
L.append(f"#define T2_SAT_LOG_F {f32(t2.sat_log)}")
L.append(f"#define T2_KAPPA_F_MAX {f64(t2.kappa_f_max)}")
L.append("")
L.append("// half-rate derivatives: every frame count halves, so the")
L.append("// integration measured in SECONDS is identical.")
L.append(f"#define T2_N2_HALF {half.get('n2', max(1, round(t2.n2 / 2)))}")
L.append(f"#define T2_M2_HALF {half.get('m2', max(1, round(t2.m2 / 2)))}")
L.append(f"#define T2_GAP_HALF {half.get('n2_gap', max(1, round(t2.n2_gap / 2)))}")
L.append(f"#define T2_RELEASE_HALF {half.get('release_frames', max(1, round(t2.release_frames / 2)))}")
L.append(f"#define T2_HALF_RATE_DEFAULT {1 if t2doc.get('half_rate_default_on_device', True) else 0}")
L.append("")
L.append("// ---- persistent-source exclusion (D11). SHIPS EMPTY. -------")
L.append("// There is no self-learning. A human puts a number here from a")
L.append("// site baseline, or it stays empty forever.")
L.append("#define T2_MAX_EXCL 4")
L.append(f"#define T2_N_EXCL {len(t2.excluded_f0)}")
if t2.excluded_f0:
cs = ", ".join(f64(c) for c, _ in t2.excluded_f0)
ts = ", ".join(f64(w) for _, w in t2.excluded_f0)
L.append(f"#define T2_EXCL_CENTRES {{ {cs} }}")
L.append(f"#define T2_EXCL_TOLS {{ {ts} }}")
else:
L.append("#define T2_EXCL_CENTRES { 0.0 }")
L.append("#define T2_EXCL_TOLS { 0.0 }")
L.append("")
L.append("// Largest ring the state struct must be able to hold, so the")
L.append("// runtime N2 argument can never overrun it.")
L.append("#define T2_MAX_N2 256")
L.append("_Static_assert(T2_N2 <= T2_MAX_N2, \"N2 exceeds the ring\");")
L.append("")
return "\n".join(L) + "\n"
def gen_window(cfg):
w = np.hanning(cfg.n_fft).astype(np.float32)
L = [BANNER, "#pragma once", "",
"// np.hanning(2048).astype(np.float32), verbatim.",
"// numpy's hanning is the SYMMETRIC window: 0.5 - 0.5*cos(2*pi*n/(M-1)),",
"// denominator M-1 = 2047, NOT the periodic M. Getting this wrong",
"// shifts every magnitude by ~1e-3 and voids the whole trace.",
"",
emit_array("SENTRY_WINDOW", w, "float", f32, 6), ""]
return "\n".join(L)
def gen_tables(cfg):
det = D.CombDetector(cfg)
n_f0, n_h = det.tw.shape
n_tooth = det.tooth_ok.sum(axis=1).astype(np.uint8)
n_gap = (det.g_i0 >= 0) # placeholder, recomputed below
# tooth_ok / gap_ok are PREFIX masks in k (tooth_f = f0*k is monotone in
# k), so a single count per f0 reproduces the mask exactly. Assert it.
for row in det.tooth_ok:
k = int(row.sum())
if not (row[:k].all() and not row[k:].any()):
raise SystemExit("tooth_ok is not a prefix mask - the count "
"export is invalid")
if not np.array_equal(det.valid, n_tooth >= cfg.n_harm_min):
raise SystemExit("valid != (n_tooth >= n_harm_min)")
ti0 = det.t_i0.astype(np.int64)
gi0 = det.g_i0.astype(np.int64)
if ti0.max() > det.n_bins - 2 or gi0.max() > det.n_bins - 2:
raise SystemExit("gather index would read past the spectrum")
if ti0.min() < 0 or gi0.min() < 0:
raise SystemExit("negative gather index")
L = [BANNER, "#pragma once", "#include <stdint.h>",
'#include "detector_config.h"', "",
"// The detector's OWN precomputed gather tables, exported from an",
"// instantiated CombDetector. ~0.47 MB: far too big for SRAM, and",
"// deliberately const so they land in flash .rodata.",
"//",
"// t_i0/t_fr linear-interpolation index+fraction for tooth k*f0",
"// g_i0/g_fr ... and for the gap (k+0.5)*f0",
"// tw/gw 1/sqrt(k) weights, zeroed above f_max_harm and then",
"// normalised to sum 1 per row",
"// znorm 1/sqrt(sum tw^2 + sum gw^2)",
"// n_tooth teeth at or below f_max_harm; the mask is a prefix,",
"// and valid[] is exactly (n_tooth >= n_harm_min)",
"",
f"#define TBL_N_F0 {n_f0}",
f"#define TBL_N_HARM {n_h}",
f"_Static_assert(TBL_N_F0 == CFG_N_F0, \"f0 grid mismatch\");",
f"_Static_assert(TBL_N_HARM == CFG_N_HARM_MAX, \"harmonic mismatch\");",
""]
# ---- one-byte indexed tables (COMMITTED) ---------------------------
# tw/gw take only ~76 distinct values because the 1/sqrt(k) weights,
# normalised per row, depend ONLY on how many harmonics fall below
# f_max_harm - and that count takes 10 values across the whole grid, not
# 1931. t_fr/g_fr take exactly 125 because bin_w = fs/n_fft = 16000/2048
# = 125/16, so every position f/bin_w is an exact multiple of 1/125 and its
# fractional part can only be one of 125 values.
#
# So these are not QUANTISED, they are INDEXED: one byte per entry into the
# table's own distinct float32 values. Bit-exact by construction - the
# dequantised array is asserted equal to the original, bit for bit - at
# less than half the flash traffic. Scalar uint8 quantisation of the same
# tables was measured on the host and BREAKS the golden gate (13 decision
# mismatches, a verdict flip); uint16 survives but is both bigger and less
# accurate than this.
u16 = lambda v: str(int(v)) # noqa: E731
idx_blocks = []
for nm, arr in (("T_FR", det.t_fr), ("G_FR", det.g_fr),
("TW", det.tw), ("GW", det.gw)):
a = arr.astype(np.float32).ravel()
vals = np.unique(a)
if len(vals) > 256:
raise SystemExit(f"{nm}: {len(vals)} distinct values, will not "
f"fit a uint8 index - keep the float table")
idx = np.searchsorted(vals, a).astype(np.uint8)
if not np.array_equal(vals[idx].view(np.uint32),
a.view(np.uint32)):
raise SystemExit(f"{nm}: index round-trip is not bit-exact")
idx_blocks.append((nm, idx, vals))
L.append("// ---- indexed tables: one byte per entry, EXACT -----------")
for nm, idx, vals in idx_blocks:
L.append(f"#define SENTRY_{nm}_NLUT {len(vals)}")
L.append("")
for nm, idx, vals in idx_blocks:
L.append(emit_array(f"SENTRY_{nm}_LUT", vals, "float", f32, 6))
L.append("")
L.append(emit_array(f"SENTRY_{nm}_IDX", idx, "uint8_t", u16, 20))
L.append("")
L.append("// ---- float tables: retained for the A/B, not committed ---")
L.append(emit_array("SENTRY_T_I0", ti0.ravel(), "uint16_t", u16, 12))
L.append("")
L.append(emit_array("SENTRY_T_FR", det.t_fr.ravel(), "float", f32, 6))
L.append("")
L.append(emit_array("SENTRY_G_I0", gi0.ravel(), "uint16_t", u16, 12))
L.append("")
L.append(emit_array("SENTRY_G_FR", det.g_fr.ravel(), "float", f32, 6))
L.append("")
L.append(emit_array("SENTRY_TW", det.tw.ravel(), "float", f32, 6))
L.append("")
L.append(emit_array("SENTRY_GW", det.gw.ravel(), "float", f32, 6))
L.append("")
L.append(emit_array("SENTRY_ZNORM", det.znorm, "float", f32, 6))
L.append("")
L.append(emit_array("SENTRY_N_TOOTH", n_tooth, "uint8_t", u16, 20))
L.append("")
return "\n".join(L)
def gen_t4_config(t4doc):
"""generated/t4_config.h - Tier-4's constants and its tooth table.
ADDITIVE, and DISABLED, for a reason that is a NUMBER rather than a
failure: the tier calibrates cleanly on every real recording the project
owns, and eleven minutes of drone-free audio cannot certify a 0.40/h
false-alarm allowance. T4_ENABLED_DEFAULT stays 0 until Field-2 brings
back the hours.
THE TOOTH TABLE IS GENERATED, not computed on the device. 591 fundamentals
x 6 harmonics of bin indices is 7 KB of flash and no runtime arithmetic,
and - the part that matters - it is rounded ON THE HOST in float64, so the
device cannot disagree with the reference about which bin a tooth is in.
That is the same discipline CFG_A_RISE and the T3 Butterworth
coefficients follow, and it exists because a one-bin disagreement is a
silent scoring difference rather than a crash.
"""
c = t4doc["config"]
d = t4doc["derived"]
n_f0 = int(d["n_f0"])
n_harm = int(c["n_harm"])
f0_lo, step = float(c["f0_lo"]), float(c["f0_step"])
df = float(c.get("df", 16000.0 / 2048.0))
L = [BANNER, "#pragma once", "#include <stdint.h>",
'#include "detector_config.h"', ""]
L.append("// ---- Tier-4, the slow comb. ADDITIVE and DISABLED.")
L.append("// Source of truth: data/t4_config.json.")
L.append("//")
for line in _wrap_comment(t4doc.get("why_disabled", "")):
L.append("// " + line)
L.append("")
L.append(f'#define T4_CORPUS_TAG "{t4doc.get("corpus_tag", "")}"')
L.append(f'#define T4_ENABLED_DEFAULT '
f'{1 if t4doc.get("enabled_default") else 0}')
L.append("")
L.append("// ---- the fundamental grid")
L.append(f"#define T4_F0_LO {f64(f0_lo)}")
L.append(f"#define T4_F0_HI {f64(c['f0_hi'])}")
L.append(f"#define T4_F0_STEP {f64(step)}")
L.append(f"#define T4_N_F0 {n_f0}")
L.append(f"#define T4_N_HARM {n_harm}")
L.append(f"#define T4_MAX_HARM 8")
L.append(f"#define T4_CAP_DB {f32(c['cap_db'])}")
L.append("")
L.append("// ---- the accumulator and the local median")
L.append(f"#define T4_WIN_FRAMES {int(c['win_frames'])}")
L.append(f"#define T4_UPDATE_FRAMES {int(c['update_frames'])}")
L.append(f"#define T4_N_SUB {int(c['n_sub'])}")
L.append(f"#define T4_SUB_FRAMES {int(c['win_frames'])//int(c['n_sub'])}")
L.append(f"#define T4_LOCAL_LO {int(c['local_lo'])}")
L.append(f"#define T4_LOCAL_HI {int(c['local_hi'])}")
L.append(f"#define T4_MED_N {int(d['med_n'])}")
L.append(f"#define T4_B_LO {int(d['b_lo'])}")
L.append(f"#define T4_B_HI {int(d['b_hi'])}")
L.append(f"#define T4_N_BINS_USED {int(d['n_bins_used'])}")
L.append("")
L.append("// ---- the decision")
L.append(f"#define T4_TAU4 {f64(c['tau4'])}")
L.append(f"#define T4_N4 {int(c['n4'])}")
L.append(f"#define T4_MAX_N4 16")
L.append(f"#define T4_M4 {int(c['m4'])}")
L.append(f"#define T4_RELEASE_UPDATES {int(c['release_updates'])}")
L.append(f"#define T4_WARMUP_S {f64(c['warmup_s'])}")
L.append(f"#define T4_FREEZE_TAIL_S {f64(c['freeze_tail_s'])}")
L.append(f"#define T4_CONT_FRAC {f64(c['cont_frac'])}")
L.append(f"#define T4_CONT_MIN_HZ {f64(c['cont_min_hz'])}")
L.append(f"#define T4_MAX_EXCL 4")
L.append(f"#define T4_CEILING {f32(d['ceiling'])}")
L.append("")
L.append("// ---- family ratios. v1 forgives a 2x hop and not a 3x one;")
L.append("// the threat is a THREE-blade propeller, measured alternating")
L.append("// between its shaft line and its third harmonic.")
rr = list(c["ratios"])
L.append(f"#define T4_N_RATIO {len(rr)}")
L.append("static const double T4_RATIO[T4_N_RATIO] = {"
+ ", ".join(f64(v) for v in rr) + "};")
L.append("")
L.append("// ---- 1/sqrt(k) harmonic weights, host-evaluated")
L.append("static const float T4_KW[T4_N_HARM] = {"
+ ", ".join(f32((k + 1) ** -0.5) for k in range(n_harm)) + "};")
L.append("")
L.append("// ---- tooth bins: T4_TOOTH[row * T4_N_HARM + k] is the bin of")
L.append("// harmonic k+1 of fundamental T4_F0_LO + row * T4_F0_STEP.")
L.append(f"static const uint16_t T4_TOOTH[{n_f0 * n_harm}] = {{")
row = []
vals = []
for i in range(n_f0):
f0 = f0_lo + i * step
for k in range(1, n_harm + 1):
vals.append(int(round(k * f0 / df)))
for i in range(0, len(vals), 16):
L.append(" " + ", ".join(str(v) for v in vals[i:i + 16]) + ",")
L.append("};")
L.append("")
for cond, why in (
("T4_B_HI < CFG_N_BINS",
"Tier-4 reaches past the spectrum it is given"),
("T4_M4 <= T4_N4",
"Tier-4 can never reach its own hit count"),
("T4_N4 <= T4_MAX_N4", "Tier-4 ring longer than its storage"),
("T4_N_HARM <= T4_MAX_HARM", "more harmonics than storage"),
("T4_WIN_FRAMES % T4_N_SUB == 0",
"sub-blocks do not divide the window")):
L.append(f'_Static_assert({cond},')
L.append(f' "{why}");')
L.append("")
return "\n".join(L) + "\n"
def _wrap_comment(text, width=72):
out, line = [], ""
for w in str(text).split():
if len(line) + len(w) + 1 > width:
out.append(line)
line = w
else:
line = (line + " " + w).strip()
if line:
out.append(line)
return out
def gen_t3_config(t3doc, cfg_hop):
"""generated/t3_config.h - Tier-3's constants, from data/t3_config.json.
ADDITIVE, and DISABLED. T3_ENABLED_DEFAULT is emitted from the JSON's
`calibrated` flag, which is false: the calibration ran, failed,
and is recorded rather than hidden. A _Static_assert here would be the
wrong instrument - the point is not that the tier is broken, it is that it
is not yet separable from a fan - so the flag is a value the `W` command
prints and an operator can override, not a compile error.
The Butterworth coefficients and the one-pole constant are evaluated ON THE
HOST in float64 and frozen, exactly as CFG_A_RISE and T2_A_UP are, so the
device never depends on its own libm agreeing with scipy's.
"""
t3 = t3doc["t3"]
fe = t3doc["front_end"]
sos = fe["hp_sos"]
L = [BANNER, "#pragma once", "#include <stdint.h>",
'#include "detector_config.h"', ""]
L.append("// ---- Tier-3, the wash tier. ADDITIVE and DISABLED.")
L.append("// Source of truth: data/t3_config.json.")
for line in t3doc.get("_comment", []):
L.append("// " + line if line else "//")
L.append("")
L.append(f'#define T3_CORPUS_TAG "{t3doc.get("corpus_tag", "")}"')
L.append(f'#define T3_ENABLED_DEFAULT '
f'{1 if t3doc.get("calibrated") else 0}')
L.append("")
L.append("// ---- front end. The time-domain path is REQUIRED: a per-frame")
L.append("// band energy is sampled at 31.25 Hz and cannot see an 82 Hz")
L.append("// modulation. Do not fold this into the existing transform.")
L.append(f"#define T3_HOP {cfg_hop}")
L.append(f"#define T3_DECIM {int(fe['decim']) if 'decim' in fe else int(t3['decim'])}")
L.append(f"#define T3_FS_ENV {int(fe['fs_env'])}")
L.append(f"#define T3_ENV_NFFT {int(fe['env_nfft'])}")
L.append(f"#define T3_ENV_HOP {int(fe['env_hop'])}")
L.append(f"#define T3_ENV_BINS {int(fe['env_nfft'])//2 + 1}")
L.append(f"#define T3_WELCH_N {int(fe['welch_n'])}")
L.append(f"#define T3_LP_POLES {int(t3['env_lp_poles'])}")
L.append(f"#define T3_MAX_POLES 4")
L.append(f"#define T3_MAX_CH {int(t3doc.get('max_ch', 4))}")
L.append(f"#define T3_LP_A {f32(fe['env_lp_a'])}")
L.append("")
L.append("// 4th-order Butterworth high-pass at "
f"{t3['hp_fc']:.0f} Hz, as two biquads,")
L.append("// transposed direct form II - the form scipy's sosfilt uses.")
L.append("static const float T3_HP_SOS_B[2][3] = {")
for r in sos:
L.append(f" {{{f32(r[0])}, {f32(r[1])}, {f32(r[2])}}},")
L.append("};")
L.append("static const float T3_HP_SOS_A[2][3] = {")
for r in sos:
L.append(f" {{{f32(r[3])}, {f32(r[4])}, {f32(r[5])}}},")
L.append("};")
L.append("")
L.append("// ---- the local-median reference")
L.append(f"#define T3_MED_HALF {int(fe['med_half'])}")
L.append(f"#define T3_MED_SKIP {int(fe['med_skip'])}")
L.append(f"#define T3_MED_N "
f"{2*int(fe['med_half']) - 2*int(fe['med_skip'])}")
L.append("")
L.append("// ---- the rate grid. COMPUTED from grid_lo for telemetry;")
L.append("// only fire_lo..fire_hi may raise anything.")
L.append(f"#define T3_GRID_LO {f64(t3['grid_lo'])}")
L.append(f"#define T3_GRID_HI {f64(t3['grid_hi'])}")
L.append(f"#define T3_RATE_STEP {f64(fe['rate_step'])}")
n_rates = int(round((t3['grid_hi'] - t3['grid_lo']) / fe['rate_step'])) + 1
L.append(f"#define T3_N_RATES {n_rates}")
L.append(f"#define T3_HARM_F_MAX {f64(fe['harm_f_max'])}")
L.append(f"#define T3_MAX_HARM 6")
L.append("")
L.append("// ---- decision. tau3 is quoted against a MEASURED null:")
L.append(f"// pure noise returns W = {t3doc.get('w_null_measured')}, because")
L.append("// the statistic maximises over the whole grid.")
L.append(f"#define T3_W_NULL {f64(t3doc.get('w_null_measured', 11.0))}")
for k, name in (("tau3", "T3_TAU3"), ("fire_lo", "T3_FIRE_LO"),
("fire_hi", "T3_FIRE_HI"), ("weight_exp", "T3_WEIGHT_EXP"),
("harm_cap_db", "T3_HARM_CAP_DB"),
("cont_frac", "T3_CONT_FRAC"), ("warmup_s", "T3_WARMUP_S"),
("freeze_tail_s", "T3_FREEZE_TAIL_S")):
L.append(f"#define {name:20s} {f64(t3[k])}")
for k, name in (("n_harm", "T3_N_HARM"), ("n3", "T3_N3"), ("m3", "T3_M3"),
("n3_gap", "T3_N3_GAP"),
("release_updates", "T3_RELEASE_UPDATES")):
L.append(f"#define {name:20s} {int(t3[k])}")
L.append(f"#define T3_MAX_N3 64")
L.append("")
L.append("_Static_assert(T3_N_HARM <= T3_MAX_HARM, "
'"n_harm exceeds the table width");')
L.append("_Static_assert(T3_N3 <= T3_MAX_N3, "
'"n3 exceeds the ring");')
L.append("_Static_assert(T3_LP_POLES <= T3_MAX_POLES, "
'"env_lp_poles exceeds the state array");')
L.append("_Static_assert(T3_HOP % T3_DECIM == 0, "
'"decimation does not divide the hop");')
L.append("")
return "\n".join(L) + "\n"
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--out", required=True)
a = ap.parse_args()
out = Path(a.out)
out.mkdir(parents=True, exist_ok=True)
dcfg = json.loads((DATA / "device_config.json").read_text())
gv = json.loads((DATA / "golden_vectors.json").read_text())
cfg, thr = op.preset_config("NORMAL")
# The golden vectors were cut at this exact Config. If the two ever drift
# the port is being judged against the wrong reference: refuse to generate.
live = cfg.to_dict()
drift = {k: (live.get(k), v) for k, v in gv["config"].items()
if live.get(k) != v}
if drift:
raise SystemExit(f"golden_vectors.json config != committed NORMAL "
f"Config: {drift}")
if abs(thr - gv["threshold"]) > 0:
raise SystemExit("NORMAL threshold != golden_vectors.json threshold")
written = {}
written["detector_config.h"] = gen_detector_config(cfg, dcfg)
written["window.h"] = gen_window(cfg)
written["tables.h"] = gen_tables(cfg)
written["t2_config.h"] = gen_t2_config(
cfg, json.loads((DATA / "t2_config.json").read_text()))
written["t3_config.h"] = gen_t3_config(
json.loads((DATA / "t3_config.json").read_text()), cfg.hop)
t4p = DATA / "t4_config.json"
if t4p.exists():
written["t4_config.h"] = gen_t4_config(json.loads(t4p.read_text()))
for name, text in written.items():
p = out / name
if not p.exists() or p.read_text() != text:
p.write_text(text)
# The VECTOR LIST comes from golden_vectors.json, not device_config.json:
# golden_vectors.json is the authority on which vectors exist and which
# preset each was cut at. device_config.json predates the HIGH_ALERT
# vector and lists only the three parity ones.
names = [v["name"] for v in gv["vectors"]]
presets = {p: c["threshold"] for p, c in dcfg["presets"].items()}
for v in gv["vectors"]:
pn = v.get("preset", "NORMAL")
if pn not in presets:
raise SystemExit(f"{v['name']}: unknown preset {pn}")
if abs(presets[pn] - v["threshold"]) > 0:
raise SystemExit(
f"{v['name']}: cut at {v['threshold']} but preset {pn} is "
f"{presets[pn]} - a vector must be replayed at a NAMED "
f"preset, never at a loose number")
# vectors: copied in UNMODIFIED
for name in names:
s, d = DATA / f"{name}.h", out / f"{name}.h"
if not d.exists() or d.read_bytes() != s.read_bytes():
shutil.copyfile(s, d)
# a manifest so the firmware can prove which vectors it holds
vec = [v for v in gv["vectors"]]
L = [BANNER, "#pragma once", "#include <stdint.h>",
'#include "detector_config.h"', ""]
for name in names:
L.append(f'#include "{name}.h"')
L.append("")
L.append("// Expected outcomes live in data/golden_vectors.json and are")
L.append("// applied by the HOST comparator. They are NOT compiled in:")
L.append("// firmware that knows the answer cannot be said to have")
L.append("// reproduced it.")
L.append("//")
L.append("// The THRESHOLD is not an outcome, it is the operating point a")
L.append("// vector was cut at, so it does travel with the vector. Each")
L.append("// entry names a PRESET constant, never a loose literal, so a")
L.append("// vector cannot be replayed at a threshold no preset defines.")
L.append("// DEFAULT_THRESHOLD (the deployment default) is untouched by")
L.append("// any of this.")
L.append(f"#define GOLDEN_N_VECTORS {len(vec)}")
L.append("typedef struct { const char *name; const int16_t *q;"
" uint32_t n; double thr; const char *preset; } golden_vec_t;")
L.append("static const golden_vec_t GOLDEN_VECTORS[GOLDEN_N_VECTORS] = {")
for v in vec:
pn = v.get("preset", "NORMAL")
macro = {"NORMAL": "NORMAL_THRESHOLD",
"HIGH_ALERT": "HIGH_ALERT_THRESHOLD"}[pn]
L.append(f' {{ "{v["name"]}", {v["name"]}, {v["n_samples"]}, '
f'{macro}, "{pn}" }},')
L.append("};")
L.append("")
text = "\n".join(L)
p = out / "vectors.h"
if not p.exists() or p.read_text() != text:
p.write_text(text)
tot = sum(f.stat().st_size for f in out.iterdir())
h = hashlib.sha256()
for f in sorted(out.iterdir()):
h.update(f.name.encode())
h.update(f.read_bytes())
print(f"generated {len(list(out.iterdir()))} headers in {out} "
f"({tot / 1e6:.2f} MB source) sha256={h.hexdigest()[:16]}")
if __name__ == "__main__":
main()
214702cffThis file is pinned to the selected release. Download the original to open it in your design tool.