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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
ir_source_localizer.py
|
| 4 |
+
======================
|
| 5 |
+
|
| 6 |
+
Localize an acoustic source from its impulse response at known
|
| 7 |
+
microphones. RANSAC over receiver subsets rejects outlying
|
| 8 |
+
arrival-time detections.
|
| 9 |
+
|
| 10 |
+
Fix history (5 iterations to get here):
|
| 11 |
+
v1 wide-window argmax -- locks on strong reflection
|
| 12 |
+
v2 first local max after rise -- picks leading-edge noise
|
| 13 |
+
v3 half-peak leading edge -- smoothing merges direct+reflection
|
| 14 |
+
v4 squared signal + tight smoothing -- r2 still +0.7 ms biased
|
| 15 |
+
v5 quality-weighted loss -- weighting helped nothing
|
| 16 |
+
v6 RANSAC over receiver subsets -- rejects the bad receiver
|
| 17 |
+
|
| 18 |
+
The insight: three of four receivers detect the direct within
|
| 19 |
+
0.02 ms. One is off by 0.70 ms. Any scheme that averages all four
|
| 20 |
+
inherits the outlier. RANSAC finds the consensus of three and
|
| 21 |
+
drops the fourth.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
from __future__ import annotations
|
| 25 |
+
|
| 26 |
+
import argparse
|
| 27 |
+
import itertools
|
| 28 |
+
import json
|
| 29 |
+
import math
|
| 30 |
+
import wave
|
| 31 |
+
from dataclasses import dataclass, asdict
|
| 32 |
+
from typing import List, Optional, Sequence, Tuple
|
| 33 |
+
|
| 34 |
+
import numpy as np
|
| 35 |
+
|
| 36 |
+
SPEED_OF_SOUND = 343.0
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# =====================================================================
|
| 40 |
+
# §1 Result type
|
| 41 |
+
# =====================================================================
|
| 42 |
+
|
| 43 |
+
@dataclass
|
| 44 |
+
class LocalizationResult:
|
| 45 |
+
x: float
|
| 46 |
+
y: float
|
| 47 |
+
sigma_x: float
|
| 48 |
+
sigma_y: float
|
| 49 |
+
detected_times: List[float]
|
| 50 |
+
detection_quality: List[float]
|
| 51 |
+
predicted_times: List[float]
|
| 52 |
+
arrival_residual_ms: List[float]
|
| 53 |
+
rms_residual_ms: float
|
| 54 |
+
n_receivers: int
|
| 55 |
+
n_inliers: int
|
| 56 |
+
inlier_mask: List[bool]
|
| 57 |
+
method: str = "energy envelope + RANSAC + Adam"
|
| 58 |
+
|
| 59 |
+
def to_dict(self) -> dict:
|
| 60 |
+
return asdict(self)
|
| 61 |
+
|
| 62 |
+
def __str__(self) -> str:
|
| 63 |
+
return (f"source at ({self.x:+.3f}, {self.y:+.3f}) m "
|
| 64 |
+
f"± ({self.sigma_x*100:.1f}, "
|
| 65 |
+
f"{self.sigma_y*100:.1f}) cm "
|
| 66 |
+
f"inliers {self.n_inliers}/{self.n_receivers} "
|
| 67 |
+
f"rms resid {self.rms_residual_ms:.3f} ms")
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# =====================================================================
|
| 71 |
+
# §2 Direct arrival detection (unchanged from v4)
|
| 72 |
+
# =====================================================================
|
| 73 |
+
|
| 74 |
+
def detect_direct_arrival(ir, sample_rate, sigma_guess,
|
| 75 |
+
threshold=0.30):
|
| 76 |
+
dt = 1.0 / sample_rate
|
| 77 |
+
w = max(3, int(round(1.0 * sigma_guess / dt)))
|
| 78 |
+
kernel = np.ones(w) / w
|
| 79 |
+
env = np.convolve(ir ** 2, kernel, mode="same")
|
| 80 |
+
peak = float(env.max())
|
| 81 |
+
if peak < 1e-12:
|
| 82 |
+
return None, 0.0
|
| 83 |
+
above = env >= threshold * peak
|
| 84 |
+
if not above.any():
|
| 85 |
+
return None, 0.0
|
| 86 |
+
first_idx = int(np.argmax(above))
|
| 87 |
+
lo = first_idx
|
| 88 |
+
hi = min(len(env), first_idx + 3 * w)
|
| 89 |
+
if hi - lo < 3:
|
| 90 |
+
return None, 0.0
|
| 91 |
+
peak_idx = lo + int(np.argmax(env[lo:hi]))
|
| 92 |
+
return float(peak_idx * dt), float(env[peak_idx] / peak)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def detect_all(irs, sample_rate, sigma_guess):
|
| 96 |
+
times, qualities = [], []
|
| 97 |
+
for ir in irs:
|
| 98 |
+
t, q = detect_direct_arrival(ir, sample_rate, sigma_guess)
|
| 99 |
+
times.append(t)
|
| 100 |
+
qualities.append(q)
|
| 101 |
+
return times, qualities
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
# =====================================================================
|
| 105 |
+
# §3 Position estimation
|
| 106 |
+
# =====================================================================
|
| 107 |
+
|
| 108 |
+
def predict_arrivals(sx, sy, sz, receivers, c=SPEED_OF_SOUND):
|
| 109 |
+
d = np.sqrt((receivers[:, 0] - sx) ** 2
|
| 110 |
+
+ (receivers[:, 1] - sy) ** 2
|
| 111 |
+
+ (receivers[:, 2] - sz) ** 2)
|
| 112 |
+
return d / c
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def arrival_loss(sx, sy, sz, receivers, times):
|
| 116 |
+
pred = predict_arrivals(sx, sy, sz, receivers)
|
| 117 |
+
return float(np.mean((pred - times) ** 2))
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def localize_grid(times, receivers, sz, x_range, y_range, n_grid=60):
|
| 121 |
+
xs = np.linspace(x_range[0], x_range[1], n_grid)
|
| 122 |
+
ys = np.linspace(y_range[0], y_range[1], n_grid)
|
| 123 |
+
best = (float(xs[0]), float(ys[0]), float("inf"))
|
| 124 |
+
for i in range(n_grid):
|
| 125 |
+
for j in range(n_grid):
|
| 126 |
+
sx = float(xs[i]); sy = float(ys[j])
|
| 127 |
+
d = np.sqrt((receivers[:, 0] - sx) ** 2
|
| 128 |
+
+ (receivers[:, 1] - sy) ** 2
|
| 129 |
+
+ (receivers[:, 2] - sz) ** 2)
|
| 130 |
+
t_pred = d / SPEED_OF_SOUND
|
| 131 |
+
err = float(np.mean((t_pred - times) ** 2))
|
| 132 |
+
if err < best[2]:
|
| 133 |
+
best = (sx, sy, err)
|
| 134 |
+
return best
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def refine_position(sx0, sy0, sz, receivers, times,
|
| 138 |
+
n_iter=300, lr=0.02):
|
| 139 |
+
p = np.array([sx0, sy0])
|
| 140 |
+
|
| 141 |
+
def L(p):
|
| 142 |
+
return arrival_loss(p[0], p[1], sz, receivers, times)
|
| 143 |
+
|
| 144 |
+
m = np.zeros(2); v = np.zeros(2)
|
| 145 |
+
best_p = p.copy(); best_L = L(p)
|
| 146 |
+
eps = 1e-3
|
| 147 |
+
for t in range(1, n_iter + 1):
|
| 148 |
+
g = np.zeros(2)
|
| 149 |
+
for i in range(2):
|
| 150 |
+
rp = p.copy(); rp[i] += eps
|
| 151 |
+
rm = p.copy(); rm[i] -= eps
|
| 152 |
+
g[i] = (L(rp) - L(rm)) / (2.0 * eps)
|
| 153 |
+
m = 0.9 * m + 0.1 * g
|
| 154 |
+
v = 0.999 * v + 0.001 * g * g
|
| 155 |
+
mh = m / (1 - 0.9 ** t)
|
| 156 |
+
vh = v / (1 - 0.999 ** t)
|
| 157 |
+
p = p - lr * mh / (np.sqrt(vh) + 1e-8)
|
| 158 |
+
Li = L(p)
|
| 159 |
+
if Li < best_L:
|
| 160 |
+
best_L = Li
|
| 161 |
+
best_p = p.copy()
|
| 162 |
+
return float(best_p[0]), float(best_p[1]), best_L
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
# =====================================================================
|
| 166 |
+
# §4 RANSAC over receiver subsets -- the v6 fix
|
| 167 |
+
# =====================================================================
|
| 168 |
+
|
| 169 |
+
def ransac_localize(times, receivers, sz,
|
| 170 |
+
x_range, y_range,
|
| 171 |
+
inlier_threshold_ms=0.30,
|
| 172 |
+
n_grid=50,
|
| 173 |
+
n_refine_ransac=100,
|
| 174 |
+
n_refine_final=300,
|
| 175 |
+
seed=0):
|
| 176 |
+
"""Try every subset of 3 receivers. Count how many of the K
|
| 177 |
+
receivers agree with each solution within `inlier_threshold_ms`.
|
| 178 |
+
Return the position with the largest consensus, then refine on
|
| 179 |
+
the inlier set only.
|
| 180 |
+
|
| 181 |
+
If K == 3, there is one subset and the result is the ordinary
|
| 182 |
+
solution. For K >= 4, this rejects outlier receivers.
|
| 183 |
+
"""
|
| 184 |
+
K = len(times)
|
| 185 |
+
if K < 3:
|
| 186 |
+
raise ValueError("need at least 3 receivers")
|
| 187 |
+
|
| 188 |
+
threshold_s = inlier_threshold_ms / 1000.0
|
| 189 |
+
subsets = list(itertools.combinations(range(K), 3))
|
| 190 |
+
|
| 191 |
+
best = None # (n_inliers, inlier_indices, sx, sy)
|
| 192 |
+
for sub in subsets:
|
| 193 |
+
sub_idx = np.array(sub)
|
| 194 |
+
recv_sub = receivers[sub_idx]
|
| 195 |
+
times_sub = np.asarray(times)[sub_idx]
|
| 196 |
+
# Coarse grid on the subset
|
| 197 |
+
sx0, sy0, _ = localize_grid(times_sub, recv_sub, sz,
|
| 198 |
+
x_range, y_range, n_grid)
|
| 199 |
+
# Fine on the subset
|
| 200 |
+
sx, sy, _ = refine_position(sx0, sy0, sz, recv_sub,
|
| 201 |
+
times_sub,
|
| 202 |
+
n_iter=n_refine_ransac, lr=0.03)
|
| 203 |
+
# Count inliers among all receivers
|
| 204 |
+
pred = predict_arrivals(sx, sy, sz, receivers)
|
| 205 |
+
resid = np.abs(pred - np.asarray(times))
|
| 206 |
+
inliers = np.where(resid <= threshold_s)[0]
|
| 207 |
+
score = len(inliers)
|
| 208 |
+
if best is None or score > best[0]:
|
| 209 |
+
best = (score, inliers, sx, sy)
|
| 210 |
+
|
| 211 |
+
_, inlier_indices, sx, sy = best
|
| 212 |
+
|
| 213 |
+
# Final refinement on inliers only
|
| 214 |
+
inliers_arr = np.asarray(inlier_indices)
|
| 215 |
+
if len(inliers_arr) >= 3:
|
| 216 |
+
sx, sy, _ = refine_position(
|
| 217 |
+
sx, sy, sz,
|
| 218 |
+
receivers[inliers_arr],
|
| 219 |
+
np.asarray(times)[inliers_arr],
|
| 220 |
+
n_iter=n_refine_final, lr=0.02)
|
| 221 |
+
|
| 222 |
+
return sx, sy, inlier_indices
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
# =====================================================================
|
| 226 |
+
# §5 Uncertainty (Monte Carlo over inliers)
|
| 227 |
+
# =====================================================================
|
| 228 |
+
|
| 229 |
+
def estimate_uncertainty(sx, sy, sz, receivers, times, inliers,
|
| 230 |
+
x_range, y_range,
|
| 231 |
+
sigma_t, n_samples=50, n_grid=40, seed=0):
|
| 232 |
+
rng = np.random.default_rng(seed)
|
| 233 |
+
R = receivers[inliers]
|
| 234 |
+
T = np.asarray(times)[inliers]
|
| 235 |
+
xs = np.empty(n_samples); ys = np.empty(n_samples)
|
| 236 |
+
for k in range(n_samples):
|
| 237 |
+
tp = T + rng.normal(0, sigma_t, size=len(T))
|
| 238 |
+
sx0, sy0, _ = localize_grid(tp, R, sz, x_range, y_range, n_grid)
|
| 239 |
+
xr, yr, _ = refine_position(sx0, sy0, sz, R, tp,
|
| 240 |
+
n_iter=120, lr=0.03)
|
| 241 |
+
xs[k] = xr; ys[k] = yr
|
| 242 |
+
return float(np.std(xs)), float(np.std(ys))
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
# =====================================================================
|
| 246 |
+
# §6 Main API
|
| 247 |
+
# =====================================================================
|
| 248 |
+
|
| 249 |
+
def localize(irs, sample_rate, receivers, sz,
|
| 250 |
+
x_range, y_range,
|
| 251 |
+
sigma_guess=4e-4,
|
| 252 |
+
n_grid=60, n_refine=300,
|
| 253 |
+
estimate_unc=True, n_unc_samples=50,
|
| 254 |
+
unc_sigma_t=None,
|
| 255 |
+
inlier_threshold_ms=0.30,
|
| 256 |
+
seed=0):
|
| 257 |
+
if len(irs) != len(receivers):
|
| 258 |
+
raise ValueError(
|
| 259 |
+
f"got {len(irs)} IRs and {len(receivers)} receivers")
|
| 260 |
+
if len(irs) < 3:
|
| 261 |
+
raise ValueError(f"need at least 3 receivers, got {len(irs)}")
|
| 262 |
+
|
| 263 |
+
receivers_arr = np.asarray(receivers, dtype=np.float64)
|
| 264 |
+
times, qualities = detect_all(irs, sample_rate, sigma_guess)
|
| 265 |
+
bad = [k for k, t in enumerate(times) if t is None]
|
| 266 |
+
if bad:
|
| 267 |
+
raise RuntimeError(
|
| 268 |
+
f"detection failed at receivers {bad}")
|
| 269 |
+
times_arr = np.asarray(times, dtype=np.float64)
|
| 270 |
+
qualities = np.asarray(qualities, dtype=np.float64)
|
| 271 |
+
|
| 272 |
+
sx, sy, inliers = ransac_localize(
|
| 273 |
+
times_arr, receivers_arr, sz,
|
| 274 |
+
x_range, y_range,
|
| 275 |
+
inlier_threshold_ms=inlier_threshold_ms,
|
| 276 |
+
n_grid=50,
|
| 277 |
+
n_refine_ransac=100,
|
| 278 |
+
n_refine_final=n_refine,
|
| 279 |
+
seed=seed)
|
| 280 |
+
|
| 281 |
+
t_pred = predict_arrivals(sx, sy, sz, receivers_arr)
|
| 282 |
+
resid_ms = (t_pred - times_arr) * 1000.0
|
| 283 |
+
rms_ms = float(np.sqrt(np.mean(resid_ms ** 2)))
|
| 284 |
+
|
| 285 |
+
sigma_x = float("nan"); sigma_y = float("nan")
|
| 286 |
+
if estimate_unc:
|
| 287 |
+
sigma_t = (unc_sigma_t if unc_sigma_t is not None
|
| 288 |
+
else 0.3 * sigma_guess)
|
| 289 |
+
sigma_x, sigma_y = estimate_uncertainty(
|
| 290 |
+
sx, sy, sz, receivers_arr, times_arr, inliers,
|
| 291 |
+
x_range, y_range, sigma_t,
|
| 292 |
+
n_samples=n_unc_samples, seed=seed)
|
| 293 |
+
|
| 294 |
+
inlier_mask = [bool(k in set(int(i) for i in inliers))
|
| 295 |
+
for k in range(len(irs))]
|
| 296 |
+
|
| 297 |
+
return LocalizationResult(
|
| 298 |
+
x=sx, y=sy,
|
| 299 |
+
sigma_x=sigma_x, sigma_y=sigma_y,
|
| 300 |
+
detected_times=[float(t) for t in times],
|
| 301 |
+
detection_quality=[float(q) for q in qualities],
|
| 302 |
+
predicted_times=[float(t) for t in t_pred],
|
| 303 |
+
arrival_residual_ms=[float(r) for r in resid_ms],
|
| 304 |
+
rms_residual_ms=rms_ms,
|
| 305 |
+
n_receivers=len(irs),
|
| 306 |
+
n_inliers=len(inliers),
|
| 307 |
+
inlier_mask=inlier_mask,
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
# =====================================================================
|
| 312 |
+
# §7 WAV I/O
|
| 313 |
+
# =====================================================================
|
| 314 |
+
|
| 315 |
+
def load_wav(path):
|
| 316 |
+
with wave.open(path, "rb") as w:
|
| 317 |
+
n_ch = w.getnchannels()
|
| 318 |
+
samp_w = w.getsampwidth()
|
| 319 |
+
sr = w.getframerate()
|
| 320 |
+
raw = w.readframes(w.getnframes())
|
| 321 |
+
if samp_w == 2:
|
| 322 |
+
data = (np.frombuffer(raw, dtype=np.int16)
|
| 323 |
+
.astype(np.float64) / 32768.0)
|
| 324 |
+
elif samp_w == 4:
|
| 325 |
+
data = (np.frombuffer(raw, dtype=np.int32)
|
| 326 |
+
.astype(np.float64) / 2147483648.0)
|
| 327 |
+
elif samp_w == 1:
|
| 328 |
+
data = ((np.frombuffer(raw, dtype=np.uint8)
|
| 329 |
+
.astype(np.float64) - 128.0) / 128.0)
|
| 330 |
+
else:
|
| 331 |
+
raise ValueError(f"unsupported sample width: {samp_w}")
|
| 332 |
+
if n_ch > 1:
|
| 333 |
+
data = data.reshape(-1, n_ch).mean(axis=1)
|
| 334 |
+
return data, sr
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
# =====================================================================
|
| 338 |
+
# §8 Simulator
|
| 339 |
+
# =====================================================================
|
| 340 |
+
|
| 341 |
+
def _image_sources(sx, sy, sz, Lx, Ly, Lz, n_reflect):
|
| 342 |
+
pos, n_r = [], []
|
| 343 |
+
for i in range(-n_reflect, n_reflect + 1):
|
| 344 |
+
for j in range(-n_reflect, n_reflect + 1):
|
| 345 |
+
for k in range(-n_reflect, n_reflect + 1):
|
| 346 |
+
nr = abs(i) + abs(j) + abs(k)
|
| 347 |
+
if nr > n_reflect:
|
| 348 |
+
continue
|
| 349 |
+
for xs_ in (sx + 2 * i * Lx, -sx + 2 * i * Lx):
|
| 350 |
+
for ys_ in (sy + 2 * j * Ly, -sy + 2 * j * Ly):
|
| 351 |
+
for zs_ in (sz + 2 * k * Lz,
|
| 352 |
+
-sz + 2 * k * Lz):
|
| 353 |
+
pos.append((xs_, ys_, zs_))
|
| 354 |
+
n_r.append(nr)
|
| 355 |
+
return (np.array(pos, dtype=np.float64),
|
| 356 |
+
np.array(n_r, dtype=np.float64))
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def _pulse_mex(delta, sigma):
|
| 360 |
+
x = delta / sigma
|
| 361 |
+
return (1.0 - x * x) * np.exp(-x * x / 2.0)
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def simulate_ir(receiver, source, room, times,
|
| 365 |
+
alpha=0.72, sigma=4e-4, n_reflect=2):
|
| 366 |
+
Lx, Ly, Lz = room
|
| 367 |
+
sx, sy, sz = source
|
| 368 |
+
pos, nr = _image_sources(sx, sy, sz, Lx, Ly, Lz, n_reflect)
|
| 369 |
+
d = np.linalg.norm(pos - receiver[None, :], axis=1)
|
| 370 |
+
t_arr = d / SPEED_OF_SOUND
|
| 371 |
+
amp = (alpha ** nr) / np.maximum(d, 0.15)
|
| 372 |
+
delta = times[:, None] - t_arr[None, :]
|
| 373 |
+
return (amp[None, :] * _pulse_mex(delta, sigma)).sum(axis=1)
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def simulate_all(receivers, source, room, times,
|
| 377 |
+
alpha=0.72, sigma=4e-4, n_reflect=2,
|
| 378 |
+
noise_frac=0.0, seed=0):
|
| 379 |
+
irs = np.stack([
|
| 380 |
+
simulate_ir(r, source, room, times, alpha, sigma, n_reflect)
|
| 381 |
+
for r in receivers
|
| 382 |
+
])
|
| 383 |
+
if noise_frac > 0:
|
| 384 |
+
rng = np.random.default_rng(seed)
|
| 385 |
+
rms = float(np.sqrt(np.mean(irs ** 2)))
|
| 386 |
+
irs = irs + noise_frac * rms * rng.standard_normal(irs.shape)
|
| 387 |
+
return irs
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
# =====================================================================
|
| 391 |
+
# §9 Self-test
|
| 392 |
+
# =====================================================================
|
| 393 |
+
|
| 394 |
+
def self_test(verbose=True):
|
| 395 |
+
checks = []
|
| 396 |
+
sr = 48000
|
| 397 |
+
T = 4000
|
| 398 |
+
times = np.arange(T) / sr
|
| 399 |
+
sigma = 4e-4
|
| 400 |
+
pulse_time = 0.010
|
| 401 |
+
|
| 402 |
+
pulse = _pulse_mex(times - pulse_time, sigma)
|
| 403 |
+
t_det, q = detect_direct_arrival(pulse, sr, sigma)
|
| 404 |
+
checks.append(("clean pulse within 0.5 ms",
|
| 405 |
+
t_det is not None
|
| 406 |
+
and abs(t_det - pulse_time) < 5e-4))
|
| 407 |
+
checks.append(("quality near 1.0", q > 0.9))
|
| 408 |
+
|
| 409 |
+
rng = np.random.default_rng(0)
|
| 410 |
+
noisy = pulse + 0.05 * rng.standard_normal(T)
|
| 411 |
+
t_det2, _ = detect_direct_arrival(noisy, sr, sigma)
|
| 412 |
+
checks.append(("5% noise within 1 ms",
|
| 413 |
+
t_det2 is not None
|
| 414 |
+
and abs(t_det2 - pulse_time) < 1e-3))
|
| 415 |
+
|
| 416 |
+
room = (5.0, 4.0, 2.8)
|
| 417 |
+
source = (1.5, 1.5, 1.0)
|
| 418 |
+
recv = np.array([
|
| 419 |
+
[4.5, 3.5, 1.0], [0.5, 3.5, 1.0],
|
| 420 |
+
[4.5, 0.5, 1.0], [0.5, 0.5, 1.0],
|
| 421 |
+
])
|
| 422 |
+
|
| 423 |
+
# RANSAC self-test: inject an outlier time.
|
| 424 |
+
t_arr = predict_arrivals(source[0], source[1], source[2], recv)
|
| 425 |
+
t_with_outlier = t_arr.copy()
|
| 426 |
+
t_with_outlier[2] += 0.7e-3 # add 0.7 ms to receiver 2
|
| 427 |
+
sx, sy, inliers = ransac_localize(
|
| 428 |
+
t_with_outlier, recv, source[2],
|
| 429 |
+
(0.2, 4.8), (0.2, 3.8),
|
| 430 |
+
inlier_threshold_ms=0.3,
|
| 431 |
+
n_grid=50, n_refine_ransac=100, n_refine_final=200,
|
| 432 |
+
seed=0)
|
| 433 |
+
err = math.hypot(sx - source[0], sy - source[1])
|
| 434 |
+
checks.append((f"RANSAC rejects outlier (err {err*100:.2f} cm)",
|
| 435 |
+
err < 0.05))
|
| 436 |
+
checks.append(("outlier receiver is not an inlier",
|
| 437 |
+
2 not in inliers))
|
| 438 |
+
|
| 439 |
+
# End-to-end at 2% noise
|
| 440 |
+
T_ir = 2000
|
| 441 |
+
times_ir = np.arange(T_ir) / sr
|
| 442 |
+
irs = simulate_all(recv, source, room, times_ir,
|
| 443 |
+
alpha=0.72, sigma=sigma, n_reflect=2,
|
| 444 |
+
noise_frac=0.02, seed=1)
|
| 445 |
+
res = localize(irs, sr, recv, sz=source[2],
|
| 446 |
+
x_range=(0.2, 4.8), y_range=(0.2, 3.8),
|
| 447 |
+
sigma_guess=sigma, n_grid=50, n_refine=250,
|
| 448 |
+
estimate_unc=False)
|
| 449 |
+
err_e2e = math.hypot(res.x - source[0], res.y - source[1])
|
| 450 |
+
checks.append((f"end-to-end within 5 cm (err {err_e2e*100:.2f})",
|
| 451 |
+
err_e2e < 0.05))
|
| 452 |
+
|
| 453 |
+
# Uncertainty
|
| 454 |
+
res_u = localize(irs, sr, recv, sz=source[2],
|
| 455 |
+
x_range=(0.2, 4.8), y_range=(0.2, 3.8),
|
| 456 |
+
sigma_guess=sigma, n_grid=40, n_refine=200,
|
| 457 |
+
estimate_unc=True, n_unc_samples=20, seed=3)
|
| 458 |
+
checks.append(("uncertainty positive",
|
| 459 |
+
res_u.sigma_x > 0 and res_u.sigma_y > 0))
|
| 460 |
+
|
| 461 |
+
try:
|
| 462 |
+
localize(irs[:2], sr, recv[:2], sz=source[2],
|
| 463 |
+
x_range=(0, 5), y_range=(0, 4))
|
| 464 |
+
checks.append(("rejects <3 receivers", False))
|
| 465 |
+
except ValueError:
|
| 466 |
+
checks.append(("rejects <3 receivers", True))
|
| 467 |
+
|
| 468 |
+
try:
|
| 469 |
+
import tempfile, os
|
| 470 |
+
with tempfile.NamedTemporaryFile(suffix=".wav",
|
| 471 |
+
delete=False) as f:
|
| 472 |
+
path = f.name
|
| 473 |
+
sig = np.clip(irs[0], -1.0, 1.0)
|
| 474 |
+
with wave.open(path, "wb") as wf:
|
| 475 |
+
wf.setnchannels(1); wf.setsampwidth(2)
|
| 476 |
+
wf.setframerate(sr)
|
| 477 |
+
wf.writeframes((sig * 32767).astype(np.int16).tobytes())
|
| 478 |
+
loaded, sr_loaded = load_wav(path)
|
| 479 |
+
os.unlink(path)
|
| 480 |
+
checks.append(("WAV sr preserved", sr_loaded == sr))
|
| 481 |
+
checks.append(("WAV len preserved", len(loaded) == len(irs[0])))
|
| 482 |
+
checks.append(("WAV values close",
|
| 483 |
+
float(np.max(np.abs(loaded - sig))) < 1e-3))
|
| 484 |
+
except Exception as e:
|
| 485 |
+
checks.append((f"WAV failed: {e}", False))
|
| 486 |
+
|
| 487 |
+
passed = sum(1 for _, ok in checks if ok)
|
| 488 |
+
if verbose:
|
| 489 |
+
print()
|
| 490 |
+
print("=" * 74)
|
| 491 |
+
print("SELF-TEST")
|
| 492 |
+
print("=" * 74)
|
| 493 |
+
for name, ok in checks:
|
| 494 |
+
mark = "PASS" if ok else "FAIL"
|
| 495 |
+
print(f" [{mark}] {name}")
|
| 496 |
+
print()
|
| 497 |
+
print(f" {passed}/{len(checks)} correct")
|
| 498 |
+
return passed, len(checks)
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
# =====================================================================
|
| 502 |
+
# §10 Demo
|
| 503 |
+
# =====================================================================
|
| 504 |
+
|
| 505 |
+
def banner(t, w=76):
|
| 506 |
+
print()
|
| 507 |
+
print("=" * w)
|
| 508 |
+
print(t)
|
| 509 |
+
print("=" * w)
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
def demo():
|
| 513 |
+
sr = 48000
|
| 514 |
+
sigma = 4e-4
|
| 515 |
+
room = (5.0, 4.0, 2.8)
|
| 516 |
+
source_true = (1.5, 1.5, 1.0)
|
| 517 |
+
recv = np.array([
|
| 518 |
+
[4.5, 3.5, 1.0], [0.5, 3.5, 1.0],
|
| 519 |
+
[4.5, 0.5, 1.0], [0.5, 0.5, 1.0],
|
| 520 |
+
])
|
| 521 |
+
banner("IR SOURCE LOCALIZER v6 -- RANSAC outlier rejection")
|
| 522 |
+
print(f" true source : "
|
| 523 |
+
f"({source_true[0]:.2f}, {source_true[1]:.2f}, "
|
| 524 |
+
f"{source_true[2]:.2f}) m")
|
| 525 |
+
print(f" room : {room[0]} x {room[1]} x {room[2]} m")
|
| 526 |
+
|
| 527 |
+
print()
|
| 528 |
+
print(f" {'noise':>6} {'x':>8} {'y':>8} {'err cm':>8} "
|
| 529 |
+
f"{'inliers':>8} {'rms ms':>8}")
|
| 530 |
+
print(" " + "-" * 60)
|
| 531 |
+
|
| 532 |
+
times_ir = np.arange(2000) / sr
|
| 533 |
+
for noise in (0.005, 0.01, 0.02, 0.05, 0.10):
|
| 534 |
+
irs = simulate_all(recv, source_true, room, times_ir,
|
| 535 |
+
noise_frac=noise, seed=1)
|
| 536 |
+
try:
|
| 537 |
+
res = localize(irs, sr, recv, sz=source_true[2],
|
| 538 |
+
x_range=(0.2, 4.8), y_range=(0.2, 3.8),
|
| 539 |
+
sigma_guess=sigma, n_grid=50,
|
| 540 |
+
n_refine=250, estimate_unc=False)
|
| 541 |
+
err_cm = math.hypot(res.x - source_true[0],
|
| 542 |
+
res.y - source_true[1]) * 100
|
| 543 |
+
print(f" {noise*100:>5.1f}% "
|
| 544 |
+
f"{res.x:>8.3f} {res.y:>8.3f} {err_cm:>8.2f} "
|
| 545 |
+
f"{res.n_inliers:>3}/{res.n_receivers:<4} "
|
| 546 |
+
f"{res.rms_residual_ms:>8.3f}")
|
| 547 |
+
except RuntimeError as e:
|
| 548 |
+
print(f" {noise*100:>5.1f}% fail: {e}")
|
| 549 |
+
|
| 550 |
+
banner("DETAIL -- 2% noise, single run")
|
| 551 |
+
irs = simulate_all(recv, source_true, room, times_ir,
|
| 552 |
+
noise_frac=0.02, seed=1)
|
| 553 |
+
res = localize(irs, sr, recv, sz=source_true[2],
|
| 554 |
+
x_range=(0.2, 4.8), y_range=(0.2, 3.8),
|
| 555 |
+
sigma_guess=sigma, n_grid=50, n_refine=250,
|
| 556 |
+
estimate_unc=True, n_unc_samples=40, seed=7)
|
| 557 |
+
print(f" {res}")
|
| 558 |
+
print()
|
| 559 |
+
print(f" {'recv':>5} {'detected (ms)':>14} "
|
| 560 |
+
f"{'predicted (ms)':>15} {'resid (ms)':>11} "
|
| 561 |
+
f"{'quality':>8} {'inlier':>7}")
|
| 562 |
+
print(" " + "-" * 72)
|
| 563 |
+
for k in range(res.n_receivers):
|
| 564 |
+
print(f" {k:>5} {res.detected_times[k]*1000:>14.4f} "
|
| 565 |
+
f"{res.predicted_times[k]*1000:>15.4f} "
|
| 566 |
+
f"{res.arrival_residual_ms[k]:>+11.4f} "
|
| 567 |
+
f"{res.detection_quality[k]:>8.3f} "
|
| 568 |
+
f"{str(res.inlier_mask[k]):>7}")
|
| 569 |
+
print()
|
| 570 |
+
print(f" RMS arrival residual : {res.rms_residual_ms:.4f} ms")
|
| 571 |
+
print(f" position uncertainty : "
|
| 572 |
+
f"sx = {res.sigma_x*100:.2f} cm, "
|
| 573 |
+
f"sy = {res.sigma_y*100:.2f} cm")
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
# =====================================================================
|
| 577 |
+
# §11 CLI
|
| 578 |
+
# =====================================================================
|
| 579 |
+
|
| 580 |
+
def _parse_xyz(s):
|
| 581 |
+
parts = s.replace(",", " ").split()
|
| 582 |
+
if len(parts) != 3:
|
| 583 |
+
raise argparse.ArgumentTypeError("expected 3 numbers")
|
| 584 |
+
return tuple(float(p) for p in parts)
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
def main():
|
| 588 |
+
p = argparse.ArgumentParser()
|
| 589 |
+
sub = p.add_subparsers(dest="cmd")
|
| 590 |
+
sub.add_parser("self-test")
|
| 591 |
+
sub.add_parser("demo")
|
| 592 |
+
p_loc = sub.add_parser("localize")
|
| 593 |
+
p_loc.add_argument("wavs", nargs="+")
|
| 594 |
+
p_loc.add_argument("--sample-rate", type=int, required=True)
|
| 595 |
+
p_loc.add_argument("--receivers", nargs="+", required=True,
|
| 596 |
+
type=_parse_xyz)
|
| 597 |
+
p_loc.add_argument("--sz", type=float, required=True)
|
| 598 |
+
p_loc.add_argument("--x-range", nargs=2, type=float, required=True)
|
| 599 |
+
p_loc.add_argument("--y-range", nargs=2, type=float, required=True)
|
| 600 |
+
p_loc.add_argument("--sigma", type=float, default=4e-4)
|
| 601 |
+
p_loc.add_argument("--grid", type=int, default=50)
|
| 602 |
+
p_loc.add_argument("--refine", type=int, default=300)
|
| 603 |
+
p_loc.add_argument("--inlier-threshold-ms", type=float, default=0.30)
|
| 604 |
+
p_loc.add_argument("--no-unc", action="store_true")
|
| 605 |
+
p_loc.add_argument("--json", action="store_true")
|
| 606 |
+
|
| 607 |
+
args = p.parse_args()
|
| 608 |
+
if args.cmd in (None, "self-test"):
|
| 609 |
+
self_test()
|
| 610 |
+
if args.cmd is None:
|
| 611 |
+
print()
|
| 612 |
+
print(" usage: python ir_source_localizer.py [self-test|demo|localize ...]")
|
| 613 |
+
return
|
| 614 |
+
if args.cmd == "demo":
|
| 615 |
+
demo()
|
| 616 |
+
return
|
| 617 |
+
if args.cmd == "localize":
|
| 618 |
+
irs = []
|
| 619 |
+
for path in args.wavs:
|
| 620 |
+
data, sr = load_wav(path)
|
| 621 |
+
if sr != args.sample_rate:
|
| 622 |
+
raise SystemExit(f"sample rate mismatch: {path}")
|
| 623 |
+
irs.append(data)
|
| 624 |
+
res = localize(irs, args.sample_rate, args.receivers,
|
| 625 |
+
sz=args.sz,
|
| 626 |
+
x_range=tuple(args.x_range),
|
| 627 |
+
y_range=tuple(args.y_range),
|
| 628 |
+
sigma_guess=args.sigma,
|
| 629 |
+
n_grid=args.grid, n_refine=args.refine,
|
| 630 |
+
estimate_unc=not args.no_unc,
|
| 631 |
+
inlier_threshold_ms=args.inlier_threshold_ms)
|
| 632 |
+
if args.json:
|
| 633 |
+
print(json.dumps(res.to_dict(), indent=2))
|
| 634 |
+
else:
|
| 635 |
+
print(res)
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
if __name__ == "__main__":
|
| 639 |
+
main()
|