fix: align all range/carrier/velocity values to PLFM hardware + FPGA bug fixes

- Correct carrier from 10.525/10 GHz to 10.5 GHz (verified ADF4382 config)
- Correct range-per-bin from 4.8/5.6/781.25 m to 24.0 m (matched-filter)
- Correct velocity resolution from 1.484 to 2.67 m/s/bin (PRI-based)
- Correct processing rate from 4 MSPS to 100 MSPS (post-DDC)
- Correct max range from 307/5000/50000 m to 1536 m (64 bins x 24 m)
- Add WaveformConfig.pri_s field (167 us PRI for velocity calculation)
- Fix short chirp chirp_complete deadlock (Bug A)
- Remove dead short_chirp ports, rename long_chirp to ref_chirp (Bug B)
- Fix stale latency comment 2159 -> 3187 cycles (Bug C)
- Create radar_params.vh as single source of truth for FPGA parameters
- Lower RadarSettings.cpp map_size validation bound from 1000 to 100
- Add PLFM hardware constants to golden_reference.py
- Update all GUI versions, tests, and cross-layer contracts

All 244 tests passing (167 Python + 21 MCU + 29 cross-layer + 27 FPGA)
This commit is contained in:
Jason
2026-04-15 10:38:59 +05:45
parent d8d30a6315
commit d259e5c106
26 changed files with 415 additions and 4826 deletions
+5 -5
View File
@@ -108,7 +108,7 @@ class GPSData:
@dataclass
class RadarSettings:
"""Radar system configuration"""
system_frequency: float = 10e9 # Hz
system_frequency: float = 10.5e9 # Hz (PLFM TX LO)
chirp_duration_1: float = 30e-6 # Long chirp duration (s)
chirp_duration_2: float = 0.5e-6 # Short chirp duration (s)
chirps_per_position: int = 32
@@ -116,8 +116,8 @@ class RadarSettings:
freq_max: float = 30e6 # Hz
prf1: float = 1000 # PRF 1 (Hz)
prf2: float = 2000 # PRF 2 (Hz)
max_distance: float = 50000 # Max detection range (m)
coverage_radius: float = 50000 # Map coverage radius (m)
max_distance: float = 1536 # Max detection range (m) -- 64 bins x 24 m
coverage_radius: float = 1536 # Map coverage radius (m)
class TileServer(Enum):
@@ -198,7 +198,7 @@ class RadarMapWidget(QWidget):
pitch=0.0
)
self._targets: list[RadarTarget] = []
self._coverage_radius = 50000 # meters
self._coverage_radius = 1536 # meters (64 bins x 24 m, 3 km mode)
self._tile_server = TileServer.OPENSTREETMAP
self._show_coverage = True
self._show_trails = False
@@ -1088,7 +1088,7 @@ class TargetSimulator(QObject):
new_range = target.range - target.velocity * 0.5 # 0.5 second update
# Check if target is still in range
if new_range < 500 or new_range > 50000:
if new_range < 50 or new_range > 1536:
# Remove this target and add a new one
continue
+5 -5
View File
@@ -81,7 +81,7 @@ class RadarTarget:
@dataclass
class RadarSettings:
system_frequency: float = 10e9
system_frequency: float = 10.5e9
chirp_duration_1: float = 30e-6 # Long chirp duration
chirp_duration_2: float = 0.5e-6 # Short chirp duration
chirps_per_position: int = 32
@@ -89,8 +89,8 @@ class RadarSettings:
freq_max: float = 30e6
prf1: float = 1000
prf2: float = 2000
max_distance: float = 50000
map_size: float = 50000 # Map size in meters
max_distance: float = 1536
map_size: float = 1536 # Map size in meters (64 bins x 24 m)
@dataclass
@@ -1196,8 +1196,8 @@ class RadarGUI:
("Frequency Max (Hz):", "freq_max", 30e6),
("PRF1 (Hz):", "prf1", 1000),
("PRF2 (Hz):", "prf2", 2000),
("Max Distance (m):", "max_distance", 50000),
("Map Size (m):", "map_size", 50000),
("Max Distance (m):", "max_distance", 1536),
("Map Size (m):", "map_size", 1536),
("Google Maps API Key:", "google_maps_api_key", "YOUR_GOOGLE_MAPS_API_KEY"),
]
+5 -5
View File
@@ -77,7 +77,7 @@ class RadarTarget:
@dataclass
class RadarSettings:
system_frequency: float = 10e9
system_frequency: float = 10.5e9
chirp_duration_1: float = 30e-6 # Long chirp duration
chirp_duration_2: float = 0.5e-6 # Short chirp duration
chirps_per_position: int = 32
@@ -85,8 +85,8 @@ class RadarSettings:
freq_max: float = 30e6
prf1: float = 1000
prf2: float = 2000
max_distance: float = 50000
map_size: float = 50000 # Map size in meters
max_distance: float = 1536
map_size: float = 1536 # Map size in meters (64 bins x 24 m)
@dataclass
@@ -1254,8 +1254,8 @@ class RadarGUI:
("Frequency Max (Hz):", "freq_max", 30e6),
("PRF1 (Hz):", "prf1", 1000),
("PRF2 (Hz):", "prf2", 2000),
("Max Distance (m):", "max_distance", 50000),
("Map Size (m):", "map_size", 50000),
("Max Distance (m):", "max_distance", 1536),
("Map Size (m):", "map_size", 1536),
]
self.settings_vars = {}
+5 -5
View File
@@ -64,7 +64,7 @@ class RadarTarget:
@dataclass
class RadarSettings:
system_frequency: float = 10e9
system_frequency: float = 10.5e9
chirp_duration_1: float = 30e-6 # Long chirp duration
chirp_duration_2: float = 0.5e-6 # Short chirp duration
chirps_per_position: int = 32
@@ -72,8 +72,8 @@ class RadarSettings:
freq_max: float = 30e6
prf1: float = 1000
prf2: float = 2000
max_distance: float = 50000
map_size: float = 50000 # Map size in meters
max_distance: float = 1536
map_size: float = 1536 # Map size in meters (64 bins x 24 m)
@dataclass
class GPSData:
@@ -1653,8 +1653,8 @@ class RadarGUI:
('Frequency Max (Hz):', 'freq_max', 30e6),
('PRF1 (Hz):', 'prf1', 1000),
('PRF2 (Hz):', 'prf2', 2000),
('Max Distance (m):', 'max_distance', 50000),
('Map Size (m):', 'map_size', 50000),
('Max Distance (m):', 'max_distance', 1536),
('Map Size (m):', 'map_size', 1536),
('Google Maps API Key:', 'google_maps_api_key', 'YOUR_GOOGLE_MAPS_API_KEY')
]
+13 -11
View File
@@ -98,9 +98,10 @@ class DemoTarget:
__slots__ = ("azimuth", "classification", "id", "range_m", "snr", "velocity")
# Physical range grid: 64 bins x ~4.8 m/bin = ~307 m max
_RANGE_PER_BIN: float = (3e8 / (2 * 500e6)) * 16 # ~4.8 m
_MAX_RANGE: float = _RANGE_PER_BIN * NUM_RANGE_BINS # ~307 m
# Physical range grid: matched-filter receiver, 100 MSPS post-DDC, 16:1 decimation
# range_per_bin = c / (2 * 100e6) * 16 = 24.0 m
_RANGE_PER_BIN: float = (3e8 / (2 * 100e6)) * 16 # 24.0 m
_MAX_RANGE: float = _RANGE_PER_BIN * NUM_RANGE_BINS # 1536 m
def __init__(self, tid: int):
self.id = tid
@@ -187,10 +188,10 @@ class DemoSimulator:
mag = np.zeros((NUM_RANGE_BINS, NUM_DOPPLER_BINS), dtype=np.float64)
det = np.zeros((NUM_RANGE_BINS, NUM_DOPPLER_BINS), dtype=np.uint8)
# Range/Doppler scaling (approximate)
range_per_bin = (3e8 / (2 * 500e6)) * 16 # ~4.8 m/bin
# Range/Doppler scaling -- matched-filter receiver, 100 MSPS, 16:1 decimation
range_per_bin = (3e8 / (2 * 100e6)) * 16 # 24.0 m/bin
max_range = range_per_bin * NUM_RANGE_BINS
vel_per_bin = 1.484 # m/s per Doppler bin (from WaveformConfig)
vel_per_bin = 2.67 # m/s per Doppler bin (lam/(2*32*167us))
for t in targets:
if t.range_m > max_range or t.range_m < 0:
@@ -385,7 +386,9 @@ class RadarDashboard:
UPDATE_INTERVAL_MS = 100 # 10 Hz display refresh
# Radar parameters used for range-axis scaling.
BANDWIDTH = 500e6 # Hz — chirp bandwidth
# Matched-filter receiver: range_per_bin = c / (2 * fs_processing) * decimation
# = 3e8 / (2 * 100e6) * 16 = 24.0 m/bin
BANDWIDTH = 20e6 # Hz — chirp bandwidth (for display/info only)
C = 3e8 # m/s — speed of light
def __init__(self, root: tk.Tk, connection: FT2232HConnection,
@@ -514,10 +517,9 @@ class RadarDashboard:
self._build_log_tab(tab_log)
def _build_display_tab(self, parent):
# Compute physical axis limits
range_res = self.C / (2.0 * self.BANDWIDTH) # ~0.3 m per FFT bin
# After decimation 1024→64, each range bin = 16 FFT bins
range_per_bin = range_res * 16
# Compute physical axis limits -- matched-filter receiver
# Range per bin: c / (2 * fs_processing) * decimation_factor = 24.0 m
range_per_bin = self.C / (2.0 * 100e6) * 16 # 24.0 m
max_range = range_per_bin * NUM_RANGE_BINS
doppler_bin_lo = 0
+2 -2
View File
@@ -45,7 +45,7 @@ class RadarSettings:
range_bins: int = 1024
doppler_bins: int = 32
prf: float = 1000
max_range: float = 5000
max_range: float = 1536
max_velocity: float = 100
cfar_threshold: float = 13.0
@@ -577,7 +577,7 @@ class RadarDemoGUI:
('Range Bins:', 'range_bins', 1024, 256, 2048),
('Doppler Bins:', 'doppler_bins', 32, 8, 128),
('PRF (Hz):', 'prf', 1000, 100, 10000),
('Max Range (m):', 'max_range', 5000, 100, 50000),
('Max Range (m):', 'max_range', 1536, 100, 25000),
('Max Velocity (m/s):', 'max_vel', 100, 10, 500),
('CFAR Threshold (dB):', 'cfar', 13.0, 5.0, 30.0)
]
-338
View File
@@ -1,338 +0,0 @@
# ruff: noqa: T201
#!/usr/bin/env python3
"""
One-off AGC saturation analysis for ADI CN0566 raw IQ captures.
Bit-accurate simulation of rx_gain_control.v AGC inner loop applied
to real captured IQ data. Three scenarios per dataset:
Row 1 — AGC OFF: Fixed gain_shift=0 (pass-through). Shows raw clipping.
Row 2 — AGC ON: Auto-adjusts from gain_shift=0. Clipping clears.
Row 3 — AGC delayed: OFF for first half, ON at midpoint.
Shows the transition: clipping → AGC activates → clears.
Key RTL details modelled exactly:
- gain_shift[3]=direction (0=amplify/left, 1=attenuate/right), [2:0]=amount
- Internal agc_gain is signed -7..+7
- Peak is measured PRE-gain (raw input |sample|, upper 8 of 15 bits)
- Saturation is measured POST-gain (overflow from shift)
- Attack: gain -= agc_attack when any sample clips (immediate)
- Decay: gain += agc_decay when peak < target AND holdoff expired
- Hold: when peak >= target AND no saturation, hold gain, reset holdoff
Usage:
python adi_agc_analysis.py
python adi_agc_analysis.py --data /path/to/file.npy --label "my capture"
"""
import argparse
import sys
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
from v7.agc_sim import (
encoding_to_signed,
apply_gain_shift,
quantize_iq,
AGCConfig,
AGCState,
process_agc_frame,
)
# ---------------------------------------------------------------------------
# FPGA AGC parameters (rx_gain_control.v reset defaults)
# ---------------------------------------------------------------------------
AGC_TARGET = 200 # host_agc_target (8-bit, default 200)
ADC_RAIL = 4095 # 12-bit ADC max absolute value
# ---------------------------------------------------------------------------
# Per-frame AGC simulation using v7.agc_sim (bit-accurate to RTL)
# ---------------------------------------------------------------------------
def simulate_agc(frames: np.ndarray, agc_enabled: bool = True,
enable_at_frame: int = 0,
initial_gain_enc: int = 0x00) -> dict:
"""Simulate FPGA inner-loop AGC across all frames.
Parameters
----------
frames : (N, chirps, samples) complex — raw ADC captures (12-bit range)
agc_enabled : if False, gain stays fixed
enable_at_frame : frame index where AGC activates
initial_gain_enc : gain_shift[3:0] encoding when AGC enables (default 0x00 = pass-through)
"""
n_frames = frames.shape[0]
# Output arrays
out_gain_enc = np.zeros(n_frames, dtype=int)
out_gain_signed = np.zeros(n_frames, dtype=int)
out_peak_mag = np.zeros(n_frames, dtype=int)
out_sat_count = np.zeros(n_frames, dtype=int)
out_sat_rate = np.zeros(n_frames, dtype=float)
out_rms_post = np.zeros(n_frames, dtype=float)
# AGC state — managed by process_agc_frame()
state = AGCState(
gain=encoding_to_signed(initial_gain_enc),
holdoff_counter=0,
was_enabled=False,
)
for i in range(n_frames):
frame_i, frame_q = quantize_iq(frames[i])
agc_active = agc_enabled and (i >= enable_at_frame)
# Build per-frame config (enable toggles at enable_at_frame)
config = AGCConfig(enabled=agc_active)
result = process_agc_frame(frame_i, frame_q, config, state)
# RMS of shifted signal
rms = float(np.sqrt(np.mean(
result.shifted_i.astype(np.float64)**2
+ result.shifted_q.astype(np.float64)**2)))
total_samples = frame_i.size + frame_q.size
sat_rate = result.overflow_raw / total_samples if total_samples > 0 else 0.0
# Record outputs
out_gain_enc[i] = result.gain_enc
out_gain_signed[i] = result.gain_signed
out_peak_mag[i] = result.peak_mag_8bit
out_sat_count[i] = result.saturation_count
out_sat_rate[i] = sat_rate
out_rms_post[i] = rms
return {
"gain_enc": out_gain_enc,
"gain_signed": out_gain_signed,
"peak_mag": out_peak_mag,
"sat_count": out_sat_count,
"sat_rate": out_sat_rate,
"rms_post": out_rms_post,
}
# ---------------------------------------------------------------------------
# Range-Doppler processing for heatmap display
# ---------------------------------------------------------------------------
def process_frame_rd(frame: np.ndarray, gain_enc: int,
n_range: int = 64,
n_doppler: int = 32) -> np.ndarray:
"""Range-Doppler magnitude for one frame with gain applied."""
frame_i, frame_q = quantize_iq(frame)
si, sq, _ = apply_gain_shift(frame_i, frame_q, gain_enc)
iq = si.astype(np.float64) + 1j * sq.astype(np.float64)
n_chirps, _ = iq.shape
range_fft = np.fft.fft(iq, axis=1)[:, :n_range]
doppler_fft = np.fft.fftshift(np.fft.fft(range_fft, axis=0), axes=0)
center = n_chirps // 2
half_d = n_doppler // 2
doppler_fft = doppler_fft[center - half_d:center + half_d, :]
rd_mag = np.abs(doppler_fft.real) + np.abs(doppler_fft.imag)
return rd_mag.T # (n_range, n_doppler)
# ---------------------------------------------------------------------------
# Plotting
# ---------------------------------------------------------------------------
def plot_scenario(axes, data: np.ndarray, agc: dict, title: str,
enable_frame: int = 0):
"""Plot one AGC scenario across 5 axes."""
n = data.shape[0]
xs = np.arange(n)
# Range-Doppler heatmap
if enable_frame > 0 and enable_frame < n:
f_before = max(0, enable_frame - 1)
f_after = min(n - 1, n - 2)
rd_before = process_frame_rd(data[f_before], int(agc["gain_enc"][f_before]))
rd_after = process_frame_rd(data[f_after], int(agc["gain_enc"][f_after]))
combined = np.hstack([rd_before, rd_after])
im = axes[0].imshow(
20 * np.log10(combined + 1), aspect="auto", origin="lower",
cmap="inferno", interpolation="nearest")
axes[0].axvline(x=rd_before.shape[1] - 0.5, color="cyan",
linewidth=2, linestyle="--")
axes[0].set_title(f"{title}\nL: f{f_before} (pre) | R: f{f_after} (post)")
else:
worst = int(np.argmax(agc["sat_count"]))
best = int(np.argmin(agc["sat_count"]))
f_show = worst if agc["sat_count"][worst] > 0 else best
rd = process_frame_rd(data[f_show], int(agc["gain_enc"][f_show]))
im = axes[0].imshow(
20 * np.log10(rd + 1), aspect="auto", origin="lower",
cmap="inferno", interpolation="nearest")
axes[0].set_title(f"{title}\nFrame {f_show}")
axes[0].set_xlabel("Doppler bin")
axes[0].set_ylabel("Range bin")
plt.colorbar(im, ax=axes[0], label="dB", shrink=0.8)
# Signed gain history (the real AGC state)
axes[1].plot(xs, agc["gain_signed"], color="#00ff88", linewidth=1.5)
axes[1].axhline(y=0, color="gray", linestyle=":", alpha=0.5,
label="Pass-through")
if enable_frame > 0:
axes[1].axvline(x=enable_frame, color="yellow", linewidth=2,
linestyle="--", label="AGC ON")
axes[1].set_ylim(-8, 8)
axes[1].set_ylabel("Gain (signed)")
axes[1].set_title("AGC Internal Gain (-7=max atten, +7=max amp)")
axes[1].legend(fontsize=7, loc="upper right")
axes[1].grid(True, alpha=0.3)
# Peak magnitude (PRE-gain, 8-bit)
axes[2].plot(xs, agc["peak_mag"], color="#ffaa00", linewidth=1.0)
axes[2].axhline(y=AGC_TARGET, color="cyan", linestyle="--",
alpha=0.7, label=f"Target ({AGC_TARGET})")
axes[2].axhspan(240, 255, color="red", alpha=0.15, label="Clip zone")
if enable_frame > 0:
axes[2].axvline(x=enable_frame, color="yellow", linewidth=2,
linestyle="--", alpha=0.8)
axes[2].set_ylim(0, 260)
axes[2].set_ylabel("Peak (8-bit)")
axes[2].set_title("Peak Magnitude (pre-gain, raw input)")
axes[2].legend(fontsize=7, loc="upper right")
axes[2].grid(True, alpha=0.3)
# Saturation count (POST-gain overflow)
axes[3].fill_between(xs, agc["sat_count"], color="red", alpha=0.4)
axes[3].plot(xs, agc["sat_count"], color="red", linewidth=0.8)
if enable_frame > 0:
axes[3].axvline(x=enable_frame, color="yellow", linewidth=2,
linestyle="--", alpha=0.8)
axes[3].set_ylabel("Overflow Count")
total = int(agc["sat_count"].sum())
axes[3].set_title(f"Post-Gain Overflow (total={total})")
axes[3].grid(True, alpha=0.3)
# RMS signal level (post-gain)
axes[4].plot(xs, agc["rms_post"], color="#44aaff", linewidth=1.0)
if enable_frame > 0:
axes[4].axvline(x=enable_frame, color="yellow", linewidth=2,
linestyle="--", alpha=0.8)
axes[4].set_ylabel("RMS")
axes[4].set_xlabel("Frame")
axes[4].set_title("Post-Gain RMS Level")
axes[4].grid(True, alpha=0.3)
def analyze_dataset(data: np.ndarray, label: str):
"""Run 3-scenario analysis for one dataset."""
n_frames = data.shape[0]
mid = n_frames // 2
print(f"\n{'='*60}")
print(f" {label} — shape {data.shape}")
print(f"{'='*60}")
# Raw ADC stats
raw_sat = np.sum((np.abs(data.real) >= ADC_RAIL) |
(np.abs(data.imag) >= ADC_RAIL))
print(f" Raw ADC saturation: {raw_sat} samples "
f"({100*raw_sat/(2*data.size):.2f}%)")
# Scenario 1: AGC OFF — pass-through (gain_shift=0x00)
print(" [1/3] AGC OFF (gain=0, pass-through) ...")
agc_off = simulate_agc(data, agc_enabled=False, initial_gain_enc=0x00)
print(f" Post-gain overflow: {agc_off['sat_count'].sum()} "
f"(should be 0 — no amplification)")
# Scenario 2: AGC ON from frame 0
print(" [2/3] AGC ON (from start) ...")
agc_on = simulate_agc(data, agc_enabled=True, enable_at_frame=0,
initial_gain_enc=0x00)
print(f" Final gain: {agc_on['gain_signed'][-1]} "
f"(enc=0x{agc_on['gain_enc'][-1]:X})")
print(f" Post-gain overflow: {agc_on['sat_count'].sum()}")
# Scenario 3: AGC delayed
print(f" [3/3] AGC delayed (ON at frame {mid}) ...")
agc_delayed = simulate_agc(data, agc_enabled=True,
enable_at_frame=mid,
initial_gain_enc=0x00)
pre_sat = int(agc_delayed["sat_count"][:mid].sum())
post_sat = int(agc_delayed["sat_count"][mid:].sum())
print(f" Pre-AGC overflow: {pre_sat} "
f"Post-AGC overflow: {post_sat}")
# Plot
fig, axes = plt.subplots(3, 5, figsize=(28, 14))
fig.suptitle(f"AERIS-10 AGC Analysis — {label}\n"
f"({n_frames} frames, {data.shape[1]} chirps, "
f"{data.shape[2]} samples/chirp, "
f"raw ADC sat={100*raw_sat/(2*data.size):.2f}%)",
fontsize=13, fontweight="bold", y=0.99)
plot_scenario(axes[0], data, agc_off, "AGC OFF (pass-through)")
plot_scenario(axes[1], data, agc_on, "AGC ON (from start)")
plot_scenario(axes[2], data, agc_delayed,
f"AGC delayed (ON at frame {mid})", enable_frame=mid)
for ax, lbl in zip(axes[:, 0],
["AGC OFF", "AGC ON", "AGC DELAYED"],
strict=True):
ax.annotate(lbl, xy=(-0.35, 0.5), xycoords="axes fraction",
fontsize=13, fontweight="bold", color="white",
ha="center", va="center", rotation=90)
plt.tight_layout(rect=[0.03, 0, 1, 0.95])
return fig
def main():
parser = argparse.ArgumentParser(
description="AGC analysis for ADI raw IQ captures "
"(bit-accurate rx_gain_control.v simulation)")
parser.add_argument("--amp", type=str,
default=str(Path.home() / "Downloads/adi_radar_data"
"/amp_radar"
"/phaser_amp_4MSPS_500M_300u_256_m3dB.npy"),
help="Path to amplified radar .npy")
parser.add_argument("--noamp", type=str,
default=str(Path.home() / "Downloads/adi_radar_data"
"/no_amp_radar"
"/phaser_NOamp_4MSPS_500M_300u_256.npy"),
help="Path to non-amplified radar .npy")
parser.add_argument("--data", type=str, default=None,
help="Single dataset mode")
parser.add_argument("--label", type=str, default="Custom Data")
args = parser.parse_args()
plt.style.use("dark_background")
if args.data:
data = np.load(args.data)
analyze_dataset(data, args.label)
plt.show()
return
figs = []
for path, label in [(args.amp, "With Amplifier (-3 dB)"),
(args.noamp, "No Amplifier")]:
if not Path(path).exists():
print(f"WARNING: {path} not found, skipping")
continue
data = np.load(path)
fig = analyze_dataset(data, label)
figs.append(fig)
if not figs:
print("No data found. Use --amp/--noamp or --data.")
sys.exit(1)
plt.show()
if __name__ == "__main__":
main()
+19 -17
View File
@@ -65,9 +65,9 @@ class TestRadarSettings(unittest.TestCase):
def test_defaults(self):
s = _models().RadarSettings()
self.assertEqual(s.system_frequency, 10e9)
self.assertEqual(s.coverage_radius, 50000)
self.assertEqual(s.max_distance, 50000)
self.assertEqual(s.system_frequency, 10.5e9)
self.assertEqual(s.coverage_radius, 1536)
self.assertEqual(s.max_distance, 1536)
class TestGPSData(unittest.TestCase):
@@ -425,26 +425,27 @@ class TestWaveformConfig(unittest.TestCase):
def test_defaults(self):
from v7.models import WaveformConfig
wc = WaveformConfig()
self.assertEqual(wc.sample_rate_hz, 4e6)
self.assertEqual(wc.bandwidth_hz, 500e6)
self.assertEqual(wc.chirp_duration_s, 300e-6)
self.assertEqual(wc.center_freq_hz, 10.525e9)
self.assertEqual(wc.sample_rate_hz, 100e6)
self.assertEqual(wc.bandwidth_hz, 20e6)
self.assertEqual(wc.chirp_duration_s, 30e-6)
self.assertEqual(wc.pri_s, 167e-6)
self.assertEqual(wc.center_freq_hz, 10.5e9)
self.assertEqual(wc.n_range_bins, 64)
self.assertEqual(wc.n_doppler_bins, 32)
self.assertEqual(wc.fft_size, 1024)
self.assertEqual(wc.decimation_factor, 16)
def test_range_resolution(self):
"""range_resolution_m should be ~5.62 m/bin with ADI defaults."""
"""range_resolution_m should be ~24.0 m/bin with PLFM defaults."""
from v7.models import WaveformConfig
wc = WaveformConfig()
self.assertAlmostEqual(wc.range_resolution_m, 5.621, places=1)
self.assertAlmostEqual(wc.range_resolution_m, 23.98, places=1)
def test_velocity_resolution(self):
"""velocity_resolution_mps should be ~1.484 m/s/bin."""
"""velocity_resolution_mps should be ~2.67 m/s/bin."""
from v7.models import WaveformConfig
wc = WaveformConfig()
self.assertAlmostEqual(wc.velocity_resolution_mps, 1.484, places=2)
self.assertAlmostEqual(wc.velocity_resolution_mps, 2.67, places=1)
def test_max_range(self):
"""max_range_m = range_resolution * n_range_bins."""
@@ -466,7 +467,8 @@ class TestWaveformConfig(unittest.TestCase):
"""Non-default parameters correctly change derived values."""
from v7.models import WaveformConfig
wc1 = WaveformConfig()
wc2 = WaveformConfig(bandwidth_hz=1e9) # double BW → halve range res
# Matched-filter: range_per_bin = c/(2*fs)*dec — proportional to 1/fs
wc2 = WaveformConfig(sample_rate_hz=200e6) # double fs → halve range res
self.assertAlmostEqual(wc2.range_resolution_m, wc1.range_resolution_m / 2, places=2)
def test_zero_center_freq_velocity(self):
@@ -925,18 +927,18 @@ class TestExtractTargetsFromFrame(unittest.TestCase):
"""Detection at range bin 10 → range = 10 * range_resolution."""
from v7.processing import extract_targets_from_frame
frame = self._make_frame(det_cells=[(10, 16)]) # dbin=16 = center → vel=0
targets = extract_targets_from_frame(frame, range_resolution=5.621)
targets = extract_targets_from_frame(frame, range_resolution=23.98)
self.assertEqual(len(targets), 1)
self.assertAlmostEqual(targets[0].range, 10 * 5.621, places=2)
self.assertAlmostEqual(targets[0].range, 10 * 23.98, places=1)
self.assertAlmostEqual(targets[0].velocity, 0.0, places=2)
def test_velocity_sign(self):
"""Doppler bin < center → negative velocity, > center → positive."""
from v7.processing import extract_targets_from_frame
frame = self._make_frame(det_cells=[(5, 10), (5, 20)])
targets = extract_targets_from_frame(frame, velocity_resolution=1.484)
# dbin=10: vel = (10-16)*1.484 = -8.904 (approaching)
# dbin=20: vel = (20-16)*1.484 = +5.936 (receding)
targets = extract_targets_from_frame(frame, velocity_resolution=2.67)
# dbin=10: vel = (10-16)*2.67 = -16.02 (approaching)
# dbin=20: vel = (20-16)*2.67 = +10.68 (receding)
self.assertLess(targets[0].velocity, 0)
self.assertGreater(targets[1].velocity, 0)
+1 -1
View File
@@ -98,7 +98,7 @@ class RadarMapWidget(QWidget):
)
self._targets: list[RadarTarget] = []
self._pending_targets: list[RadarTarget] | None = None
self._coverage_radius = 50_000 # metres
self._coverage_radius = 1_536 # metres (64 bins x 24 m, 3 km mode)
self._tile_server = TileServer.OPENSTREETMAP
self._show_coverage = True
self._show_trails = False
+24 -22
View File
@@ -108,12 +108,12 @@ class RadarSettings:
range_resolution and velocity_resolution should be calibrated to
the actual waveform parameters.
"""
system_frequency: float = 10e9 # Hz (carrier, used for velocity calc)
range_resolution: float = 781.25 # Meters per range bin (default: 50km/64)
velocity_resolution: float = 1.0 # m/s per Doppler bin (calibrate to waveform)
max_distance: float = 50000 # Max detection range (m)
map_size: float = 50000 # Map display size (m)
coverage_radius: float = 50000 # Map coverage radius (m)
system_frequency: float = 10.5e9 # Hz (PLFM TX LO, verified from ADF4382 config)
range_resolution: float = 24.0 # Meters per decimated range bin (c/(2*100MSPS)*16)
velocity_resolution: float = 2.67 # m/s per Doppler bin (lam/(2*32*167us))
max_distance: float = 1536 # Max detection range (m) -- 64 bins x 24 m (3 km mode)
map_size: float = 1536 # Map display size (m)
coverage_radius: float = 1536 # Map coverage radius (m)
@dataclass
@@ -196,42 +196,44 @@ class TileServer(Enum):
class WaveformConfig:
"""Physical waveform parameters for converting bins to SI units.
Encapsulates the radar waveform so that range/velocity resolution
Encapsulates the PLFM radar waveform so that range/velocity resolution
can be derived automatically instead of hardcoded in RadarSettings.
Defaults match the ADI CN0566 Phaser capture parameters used in
the golden_reference cosim (4 MSPS, 500 MHz BW, 300 us chirp).
Defaults match the PLFM hardware: 100 MSPS post-DDC processing rate,
20 MHz chirp bandwidth, 30 us long chirp, 167 us PRI, 10.5 GHz carrier.
The receiver uses matched-filter pulse compression (NOT deramped FMCW),
so range-per-bin = c / (2 * fs_processing) * decimation_factor.
"""
sample_rate_hz: float = 4e6 # ADC sample rate
bandwidth_hz: float = 500e6 # Chirp bandwidth
chirp_duration_s: float = 300e-6 # Chirp ramp time
center_freq_hz: float = 10.525e9 # Carrier frequency
n_range_bins: int = 64 # After decimation
sample_rate_hz: float = 100e6 # Post-DDC processing rate (400 MSPS / 4)
bandwidth_hz: float = 20e6 # Chirp bandwidth (Phase 1 target: 30 MHz)
chirp_duration_s: float = 30e-6 # Long chirp ramp (informational only)
pri_s: float = 167e-6 # Pulse repetition interval (chirp + listen)
center_freq_hz: float = 10.5e9 # TX LO carrier (verified: ADF4382 config)
n_range_bins: int = 64 # After decimation (3 km mode)
n_doppler_bins: int = 32 # After Doppler FFT
fft_size: int = 1024 # Pre-decimation FFT length
decimation_factor: int = 16 # 1024 → 64
@property
def range_resolution_m(self) -> float:
"""Meters per decimated range bin (FMCW deramped baseband).
"""Meters per decimated range bin (matched-filter receiver).
For deramped FMCW: bin spacing = c * Fs * T / (2 * N_FFT * BW).
For matched-filter pulse compression: bin spacing = c / (2 * fs).
After decimation the bin spacing grows by *decimation_factor*.
This is independent of chirp bandwidth (BW affects resolution, not
bin spacing).
"""
c = 299_792_458.0
raw_bin = (
c * self.sample_rate_hz * self.chirp_duration_s
/ (2.0 * self.fft_size * self.bandwidth_hz)
)
raw_bin = c / (2.0 * self.sample_rate_hz)
return raw_bin * self.decimation_factor
@property
def velocity_resolution_mps(self) -> float:
"""m/s per Doppler bin. lambda / (2 * n_doppler * chirp_duration)."""
"""m/s per Doppler bin. lambda / (2 * n_doppler * PRI)."""
c = 299_792_458.0
wavelength = c / self.center_freq_hz
return wavelength / (2.0 * self.n_doppler_bins * self.chirp_duration_s)
return wavelength / (2.0 * self.n_doppler_bins * self.pri_s)
@property
def max_range_m(self) -> float:
+1 -1
View File
@@ -368,7 +368,7 @@ class TargetSimulator(QObject):
for t in self._targets:
new_range = t.range - t.velocity * 0.5
if new_range < 500 or new_range > 50000:
if new_range < 50 or new_range > 1536:
continue # target exits coverage — drop it
new_vel = max(-150, min(150, t.velocity + random.uniform(-2, 2)))