Add dense harmonic active probe loop

This commit is contained in:
Meta Vens 2026-05-18 22:00:37 +01:00
commit e7a4bff764
8 changed files with 245 additions and 5 deletions

View file

@ -41,6 +41,9 @@ class ActiveConfidenceMaintainer:
end_hz: float = 9000.0,
channels: int = 2,
channel: int = 0,
pattern: str = "single",
harmonic_root_hz: float = 440.0,
harmonic_voices: int = 24,
):
self.optimizer = optimizer
self.sample_rate = int(sample_rate)
@ -50,6 +53,9 @@ class ActiveConfidenceMaintainer:
self.end_hz = float(end_hz)
self.channels = int(channels)
self.channel = int(channel)
self.pattern = str(pattern)
self.harmonic_root_hz = float(harmonic_root_hz)
self.harmonic_voices = int(harmonic_voices)
if self.channels <= 0:
raise ValueError("channels must be positive")
if self.channel < 0 or self.channel >= self.channels:
@ -62,7 +68,7 @@ class ActiveConfidenceMaintainer:
request = self.optimizer.choose_probe(meaning.frame_id, states, masked_window=masked)
if request is None:
return None
waveform = make_probe_chirplet(
waveform = make_probe_waveform(
self.sample_rate,
duration_seconds=self.duration_seconds,
start_hz=self.start_hz,
@ -70,6 +76,9 @@ class ActiveConfidenceMaintainer:
level_dbfs=request.level_dbfs,
channels=self.channels,
channel=self.channel,
pattern=self.pattern,
harmonic_root_hz=self.harmonic_root_hz,
harmonic_voices=self.harmonic_voices,
)
path = self.output_dir / f"probe-{meaning.frame_id:08d}-{request.source_id}.wav"
wavfile.write(path, self.sample_rate, waveform.astype(np.float32))
@ -136,6 +145,96 @@ def make_probe_chirplet(
return out
def make_probe_waveform(
sample_rate: int,
*,
duration_seconds: float,
start_hz: float,
end_hz: float,
level_dbfs: float,
channels: int = 2,
channel: int = 0,
pattern: str = "single",
harmonic_root_hz: float = 440.0,
harmonic_voices: int = 24,
) -> np.ndarray:
if pattern == "single":
return make_probe_chirplet(
sample_rate,
duration_seconds=duration_seconds,
start_hz=start_hz,
end_hz=end_hz,
level_dbfs=level_dbfs,
channels=channels,
channel=channel,
)
if pattern == "harmonic-dense":
return make_harmonic_probe_texture(
sample_rate,
duration_seconds=duration_seconds,
start_hz=start_hz,
end_hz=end_hz,
level_dbfs=level_dbfs,
channels=channels,
channel=channel,
root_hz=harmonic_root_hz,
voices=harmonic_voices,
)
raise ValueError(f"unknown probe pattern: {pattern}")
def make_harmonic_probe_texture(
sample_rate: int,
*,
duration_seconds: float,
start_hz: float,
end_hz: float,
level_dbfs: float,
channels: int = 2,
channel: int = 0,
root_hz: float = 440.0,
voices: int = 24,
) -> np.ndarray:
frames = max(8, int(round(float(duration_seconds) * int(sample_rate))))
texture = np.zeros(frames, dtype=np.float64)
harmonics = harmonic_frequencies(float(root_hz), float(start_hz), float(end_hz))
if not harmonics:
harmonics = list(np.linspace(float(start_hz), float(end_hz), max(1, int(voices))))
span_hz = max(40.0, min(420.0, (float(end_hz) - float(start_hz)) / max(4.0, float(voices))))
voice_count = max(1, int(voices))
for index in range(voice_count):
center = harmonics[index % len(harmonics)]
direction = -1.0 if index % 2 else 1.0
f0 = clamp(center - direction * span_hz * 0.5, float(start_hz), float(end_hz))
f1 = clamp(center + direction * span_hz * 0.5, float(start_hz), float(end_hz))
voice_frames = max(8, min(frames, int(round(frames * 0.38))))
offset = int(((index * 0.61803398875) % 1.0) * max(1, frames - voice_frames))
t = np.arange(voice_frames, dtype=np.float64) / float(sample_rate)
chirp = signal.chirp(t, f0=f0, f1=f1, t1=voice_frames / float(sample_rate), method="linear")
chirp *= signal.windows.tukey(voice_frames, alpha=0.7)
chirp *= 0.55 + 0.45 * ((index % 5) / 4.0)
texture[offset : offset + voice_frames] += chirp
peak = float(np.max(np.abs(texture)))
if peak > 0.0:
texture = texture / peak
texture *= db_to_amp(level_dbfs)
out = np.zeros((frames, int(channels)), dtype=np.float32)
out[:, int(channel)] = texture.astype(np.float32)
return out
def harmonic_frequencies(root_hz: float, start_hz: float, end_hz: float) -> list[float]:
if root_hz <= 0.0:
raise ValueError("root_hz must be positive")
first = max(1, int(math.ceil(start_hz / root_hz)))
last = int(math.floor(end_hz / root_hz))
return [root_hz * harmonic for harmonic in range(first, last + 1)]
def clamp(value: float, low: float, high: float) -> float:
return max(low, min(high, value))
def db_to_amp(db: float) -> float:
return float(math.pow(10.0, float(db) / 20.0))

View file

@ -140,6 +140,18 @@ Close the confidence loop by letting the phase-field stream schedule strategic a
`--maintain-confidence` converts low-confidence phase-field state into `ActiveProbeOptimizer` requests, writes each emitted chirplet to `calibration/runs/active-probes`, and appends `active-probes.jsonl`. `--play-probes` sends the emitted chirplet to the default output device through `sounddevice`; omit it for dry-run scheduling. `--ultrasonic-probes` uses the highest safe band under Nyquist, roughly `18.5-22 kHz` at 48 kHz. This can fail silently in the physical world if the speaker, mic, driver, or resampler refuses to carry that band; the confidence feedback is the judge, not the command line's self-esteem.
For the current live app, start the dense harmonic confidence-maintenance loop:
```powershell
.\scripts\start-live-audio-phase-field.ps1
```
That launcher runs `stream_phase_field.py` in realtime loop mode with playback enabled, dense harmonic probes, a near-ultrasonic band, `-24 dBFS` level cap, 80 ms probe textures, and 48 harmonic voices. Stop it with:
```powershell
.\scripts\stop-live-audio-phase-field.ps1
```
Record local mics while playing one speaker sweep. Use the output rate that the device probe says is real:
```powershell
@ -223,6 +235,7 @@ The `play-record` and `record-field` commands remain for a `shared-input-device`
- Runtime sync updates delay/SRO/phase estimates from known speaker chirplets every block/frame, gated by confidence so a bad observation freezes rather than poisons the field.
- Active chirplet probes are scheduled by an optimization loop, not by panic. It should prefer masked windows, respect minimum spacing and level caps, and maximize expected confidence gain per audible intrusion.
- Ultrasonic probes are allowed only as a bounded optimization strategy. They must stay below Nyquist, remain level-capped, and prove themselves by raising measured confidence; hardware may distort or discard them.
- Dense probe textures should be harmonically organized so any lower-band aliases land closer to musical relationships than arbitrary squeal. This is damage control, not a license to trust aliasing.
- FOA output is AmbiX: ACN channel order, SN3D normalization, channels `W,Y,Z,X`.
- Speaker calibration is a measurement path, not a generic monitor output.
- Source-event geometry is published beside the AmbiX bed; render effects do not have to infer transient positions from mixed audio.

View file

@ -42,6 +42,7 @@
- `localcast.audio.phase_field` is a typed CultCache document at `calibration/runs/audio-phase-field.msgpack`.
- `scripts/stream_phase_field.py` publishes the live meaning document from an aligned mic field plus known program/loopback reference without exposing raw phase bands as the renderer API.
- `audio_field.active_probe` wires low phase-field confidence into `ActiveProbeOptimizer`, emits bounded chirplet WAVs plus `active-probes.jsonl`, and can play probes through the default output device.
- `scripts/start-live-audio-phase-field.ps1` starts the live dense harmonic confidence loop with near-ultrasonic probes; `scripts/stop-live-audio-phase-field.ps1` stops the PID recorded in `logs/audio-phase-field.pid`.
## Temporary

View file

@ -0,0 +1,66 @@
param(
[string]$Root = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path,
[string]$Python = ".\.venv\Scripts\python.exe",
[string]$Field = ".\calibration\runs\audio-program-live-20260518-180226\field-program-cleaned.wav",
[string]$Reference = ".\calibration\runs\audio-program-live-20260518-180226\ground_truth_loopback.wav",
[string]$Cache = ".\calibration\runs\audio-phase-field.msgpack",
[string]$ProbeDir = ".\calibration\runs\active-probes",
[double]$TargetConfidence = 0.72,
[double]$TriggerConfidence = 0.45,
[int]$MinProbeIntervalFrames = 1,
[double]$ProbeLevelDbfs = -24.0,
[double]$ProbeSeconds = 0.08,
[double]$HarmonicRootHz = 440.0,
[int]$HarmonicVoices = 48,
[switch]$NoPlayback
)
$ErrorActionPreference = "Stop"
Set-Location -LiteralPath $Root
$logDir = Join-Path $Root "logs"
New-Item -ItemType Directory -Force -Path $logDir | Out-Null
$resolvedPython = if ([System.IO.Path]::IsPathRooted($Python)) { $Python } else { Join-Path $Root $Python }
$stdout = Join-Path $logDir "audio-phase-field.stdout.log"
$stderr = Join-Path $logDir "audio-phase-field.stderr.log"
$pidPath = Join-Path $logDir "audio-phase-field.pid"
$arguments = @(
".\scripts\stream_phase_field.py",
"--field", $Field,
"--reference", $Reference,
"--cache", $Cache,
"--source-id", "host-focusrite",
"--source-id", "co-streamer-focusrite",
"--source-id", "kiyo-0",
"--source-id", "kiyo-1",
"--source-id", "ps-eye-0",
"--source-id", "ps-eye-1",
"--loop",
"--realtime",
"--maintain-confidence",
"--cram-harmonic-probes",
"--probe-output-dir", $ProbeDir,
"--probe-unmasked",
"--target-confidence", ([string]$TargetConfidence),
"--trigger-confidence", ([string]$TriggerConfidence),
"--min-probe-interval-frames", ([string]$MinProbeIntervalFrames),
"--probe-level-dbfs", ([string]$ProbeLevelDbfs),
"--probe-seconds", ([string]$ProbeSeconds),
"--harmonic-root-hz", ([string]$HarmonicRootHz),
"--harmonic-voices", ([string]$HarmonicVoices)
)
if (-not $NoPlayback) {
$arguments += "--play-probes"
}
$process = Start-Process -FilePath $resolvedPython -ArgumentList $arguments -RedirectStandardOutput $stdout -RedirectStandardError $stderr -PassThru -WindowStyle Hidden
Set-Content -Path $pidPath -Value ([string]$process.Id) -Encoding ASCII
Write-Host "Started live audio phase-field confidence loop PID $($process.Id)"
Write-Host "stdout: $stdout"
Write-Host "stderr: $stderr"
Write-Host "pid: $pidPath"

View file

@ -0,0 +1,30 @@
param(
[string]$Root = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
)
$ErrorActionPreference = "Stop"
Set-Location -LiteralPath $Root
$pidPath = Join-Path $Root "logs\audio-phase-field.pid"
if (-not (Test-Path -LiteralPath $pidPath)) {
Write-Host "No live audio phase-field PID file found."
exit 0
}
$pidText = (Get-Content -LiteralPath $pidPath -Raw).Trim()
if ($pidText.Length -eq 0) {
Remove-Item -LiteralPath $pidPath -Force
Write-Host "Empty PID file removed."
exit 0
}
$process = Get-Process -Id ([int]$pidText) -ErrorAction SilentlyContinue
if ($null -ne $process) {
Stop-Process -Id $process.Id -Force
Write-Host "Stopped live audio phase-field PID $($process.Id)"
} else {
Write-Host "Live audio phase-field PID $pidText is not running."
}
Remove-Item -LiteralPath $pidPath -Force

View file

@ -85,6 +85,10 @@ def main() -> None:
parser.add_argument("--probe-seconds", type=float, default=0.03)
parser.add_argument("--probe-band", default="1800:9000")
parser.add_argument("--ultrasonic-probes", action="store_true", help="Use a near-ultrasonic probe band below Nyquist.")
parser.add_argument("--probe-pattern", choices=["single", "harmonic-dense"], default="single")
parser.add_argument("--cram-harmonic-probes", action="store_true", help="Shortcut for dense near-ultrasonic harmonic probes.")
parser.add_argument("--harmonic-root-hz", type=float, default=440.0)
parser.add_argument("--harmonic-voices", type=int, default=36)
parser.add_argument("--probe-channel", type=int, default=0)
parser.add_argument("--probe-output-channels", type=int, default=2)
parser.add_argument("--probe-unmasked", action="store_true", help="Allow probes even when the reference block is not masking them.")
@ -105,7 +109,9 @@ def main() -> None:
)
maintainer = None
if args.maintain_confidence:
band_start, band_end = ultrasonic_probe_band(sample_rate) if args.ultrasonic_probes else parse_probe_band(args.probe_band)
use_ultrasonic = args.ultrasonic_probes or args.cram_harmonic_probes
probe_pattern = "harmonic-dense" if args.cram_harmonic_probes else args.probe_pattern
band_start, band_end = ultrasonic_probe_band(sample_rate) if use_ultrasonic else parse_probe_band(args.probe_band)
maintainer = ActiveConfidenceMaintainer(
ActiveProbeOptimizer(
ProbePolicy(
@ -123,6 +129,9 @@ def main() -> None:
end_hz=band_end,
channels=args.probe_output_channels,
channel=args.probe_channel,
pattern=probe_pattern,
harmonic_root_hz=args.harmonic_root_hz,
harmonic_voices=args.harmonic_voices,
)
start_monotonic = time.monotonic()

View file

@ -135,8 +135,10 @@ research:
weights, correction energy, and active-probe need. `audio_field.active_probe`
closes the next loop by feeding that confidence state into
ActiveProbeOptimizer and emitting bounded chirplet WAVs/manifests, with
optional default-device playback. This is learned audio-field state, not
a phase display.
optional default-device playback. The live launcher now uses dense
harmonic near-ultrasonic probe textures so aliases have a musical
relationship instead of arbitrary squeal. This is learned audio-field
state, not a phase display.
sensor_fusion_architecture:
summary: docs/sensor-fusion-architecture.md
key_decision: >

View file

@ -4,7 +4,7 @@ from pathlib import Path
import numpy as np
from audio_field.active_probe import ActiveConfidenceMaintainer, is_masked_window, make_probe_chirplet
from audio_field.active_probe import ActiveConfidenceMaintainer, harmonic_frequencies, is_masked_window, make_harmonic_probe_texture, make_probe_chirplet
from audio_field.phase_meaning import PhaseFieldMeaning, SourcePhaseMeaning
from audio_field.probe_optimizer import ActiveProbeOptimizer, ProbePolicy
from scripts.stream_phase_field import ultrasonic_probe_band
@ -59,6 +59,26 @@ class ActiveProbeTests(unittest.TestCase):
self.assertGreaterEqual(start_hz, 18000.0)
self.assertLess(end_hz, 24000.0)
def test_harmonic_texture_packs_many_chirps_under_level_cap(self):
texture = make_harmonic_probe_texture(
48000,
duration_seconds=0.08,
start_hz=18500.0,
end_hz=22000.0,
level_dbfs=-18.0,
voices=36,
)
self.assertEqual((3840, 2), texture.shape)
self.assertLessEqual(float(np.max(np.abs(texture))), 0.127)
self.assertGreater(float(np.sqrt(np.mean(texture[:, 0] ** 2))), 0.005)
def test_harmonic_frequencies_follow_root(self):
freqs = harmonic_frequencies(440.0, 18500.0, 22000.0)
self.assertIn(18920.0, freqs)
self.assertIn(22000.0, freqs)
if __name__ == "__main__":
unittest.main()