Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
221 lines (175 loc) · 6.52 KB

File metadata and controls

221 lines (175 loc) · 6.52 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
#!/usr/bin/env python3
"""
02_plot_debug.py - Visualize chirp recovery results
Plots:
1. Aliased STFT spectrogram + ridge trajectory
2. De-aliased frequency trajectory vs expected
3. Recovered chirp: amplitude and phase
Usage:
python 02_plot_debug.py
"""
import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path
INPUT_FILE = "chirp_recovered.npz"
def load_results(path):
"""Load recovery results."""
if not Path(path).exists():
raise FileNotFoundError(f"Run 01_recover_chirp.py first! File not found: {path}")
data = np.load(path, allow_pickle=True)
return {key: data[key] for key in data.keys()}
def plot_aliased_spectrogram(ax, data):
"""Plot 1: Aliased STFT with ridge trajectory."""
t = data['t_stft']
f = data['f_stft']
Z_mag = data['Z_mag']
f_alias = data['f_alias']
Fs = float(data['Fs'])
# Convert to dB
Z_db = 20 * np.log10(Z_mag + 1e-10)
vmin = np.percentile(Z_db, 10)
vmax = np.percentile(Z_db, 95)
im = ax.pcolormesh(t * 1000, f / 1e3, Z_db, shading='gouraud',
cmap='viridis', vmin=vmin, vmax=vmax)
# Overlay ridge
ax.plot(t * 1000, f_alias / 1e3, 'r-', linewidth=1.5, label='Ridge (aliased)')
ax.set_xlabel("Time (ms)")
ax.set_ylabel("Frequency (kHz)")
ax.set_title("(a) Aliased STFT + Ridge")
ax.set_ylim(-Fs / 2 / 1e3, Fs / 2 / 1e3)
ax.axhline(y=0, color='white', linestyle='--', alpha=0.3)
ax.legend(loc='upper right', fontsize=8)
return im
def plot_dealiased_trajectory(ax, data):
"""Plot 2: De-aliased frequency vs expected."""
t = data['t_stft']
f_orig = data['f_orig']
f_exp = data['f_exp']
BW = float(data['BW'])
# Filter valid points
valid = ~np.isnan(f_orig)
ax.plot(t[valid] * 1000, f_orig[valid] / 1e3, 'b-', linewidth=1.5,
label='Recovered f(t)')
ax.plot(t * 1000, f_exp / 1e3, 'r--', linewidth=1, alpha=0.7,
label='Expected f(t)')
ax.set_xlabel("Time (ms)")
ax.set_ylabel("Frequency (kHz)")
ax.set_title("(b) De-aliased Frequency Trajectory")
ax.set_ylim(-BW / 1e3 * 1.1, BW / 1e3 * 1.1)
ax.axhline(y=0, color='gray', linestyle='--', alpha=0.3)
ax.axhline(y=BW / 1e3, color='gray', linestyle=':', alpha=0.3)
ax.axhline(y=-BW / 1e3, color='gray', linestyle=':', alpha=0.3)
ax.legend(loc='upper left', fontsize=8)
ax.grid(True, alpha=0.3)
def plot_recovered_chirp(axes, data):
"""Plot 3: Recovered chirp amplitude and phase."""
chirp = data['chirp']
t = data['t_chirp']
# Amplitude
amp = np.abs(chirp)
axes[0].plot(t * 1000, amp, 'g-', linewidth=0.5)
axes[0].set_xlabel("Time (ms)")
axes[0].set_ylabel("Amplitude")
axes[0].set_title("(c) Recovered Chirp Amplitude |x(t)|")
axes[0].grid(True, alpha=0.3)
# Phase (unwrapped)
phase = np.unwrap(np.angle(chirp))
axes[1].plot(t * 1000, phase, 'purple', linewidth=0.5)
axes[1].set_xlabel("Time (ms)")
axes[1].set_ylabel("Phase (rad)")
axes[1].set_title("(d) Recovered Chirp Phase (unwrapped)")
axes[1].grid(True, alpha=0.3)
def plot_single_chirp_detail(fig, data):
"""Plot detailed view of one chirp period."""
t = data['t_stft']
f_alias = data['f_alias']
f_orig = data['f_orig']
f_exp = data['f_exp']
n_fold = data['n_fold']
BW = float(data['BW'])
SF = int(data['SF'])
Fs = float(data['Fs'])
T_chirp = (2 ** SF) / BW
T_ms = T_chirp * 1000
# Filter to one chirp period
mask = t <= T_chirp
t_one = t[mask]
f_alias_one = f_alias[mask]
f_orig_one = f_orig[mask]
f_exp_one = f_exp[mask]
n_fold_one = n_fold[mask]
# Create 2x2 subplot for single chirp
gs = fig.add_gridspec(2, 2, left=0.55, right=0.98, top=0.48, bottom=0.05,
hspace=0.35, wspace=0.3)
# Aliased frequency
ax1 = fig.add_subplot(gs[0, 0])
ax1.plot(t_one * 1000, f_alias_one / 1e3, 'r.-', markersize=2, linewidth=1)
ax1.set_xlabel("Time (ms)")
ax1.set_ylabel("Freq (kHz)")
ax1.set_title(f"Aliased f(t) [0-{T_ms:.1f}ms]", fontsize=9)
ax1.set_ylim(-Fs / 2 / 1e3, Fs / 2 / 1e3)
ax1.grid(True, alpha=0.3)
# De-aliased frequency
ax2 = fig.add_subplot(gs[0, 1])
valid = ~np.isnan(f_orig_one)
ax2.plot(t_one[valid] * 1000, f_orig_one[valid] / 1e3, 'b.-', markersize=2, linewidth=1,
label='Recovered')
ax2.plot(t_one * 1000, f_exp_one / 1e3, 'r--', linewidth=1, alpha=0.5, label='Expected')
ax2.set_xlabel("Time (ms)")
ax2.set_ylabel("Freq (kHz)")
ax2.set_title(f"De-aliased f(t)", fontsize=9)
ax2.set_ylim(-BW / 1e3 * 1.1, BW / 1e3 * 1.1)
ax2.legend(fontsize=7, loc='upper left')
ax2.grid(True, alpha=0.3)
# Fold count
ax3 = fig.add_subplot(gs[1, 0])
ax3.plot(t_one * 1000, n_fold_one, 'g.-', markersize=2, linewidth=1)
ax3.set_xlabel("Time (ms)")
ax3.set_ylabel("n_fold")
ax3.set_title("Fold Count", fontsize=9)
ax3.grid(True, alpha=0.3)
# Error
ax4 = fig.add_subplot(gs[1, 1])
error = (f_orig_one - f_exp_one) / 1e3 # kHz
ax4.plot(t_one[valid] * 1000, error[valid], 'm.-', markersize=2, linewidth=1)
ax4.set_xlabel("Time (ms)")
ax4.set_ylabel("Error (kHz)")
ax4.set_title("Recovery Error", fontsize=9)
ax4.axhline(y=0, color='gray', linestyle='--', alpha=0.5)
ax4.grid(True, alpha=0.3)
def main():
print("Loading results...")
data = load_results(INPUT_FILE)
# Print summary
Fs = float(data['Fs'])
BW = float(data['BW'])
SF = int(data['SF'])
T_chirp = (2 ** SF) / BW
print(f" Fs = {Fs / 1e3:.1f} kHz")
print(f" BW = {BW / 1e3:.1f} kHz")
print(f" SF = {SF}")
print(f" T_chirp = {T_chirp * 1000:.2f} ms")
# Create figure
fig = plt.figure(figsize=(16, 12))
# Main plots (left side)
ax1 = fig.add_subplot(2, 2, 1)
im = plot_aliased_spectrogram(ax1, data)
fig.colorbar(im, ax=ax1, label='dB')
ax2 = fig.add_subplot(2, 2, 3)
plot_dealiased_trajectory(ax2, data)
# Chirp plots (top right)
ax3 = fig.add_subplot(4, 2, 2)
ax4 = fig.add_subplot(4, 2, 4)
plot_recovered_chirp([ax3, ax4], data)
# Single chirp detail (bottom right)
plot_single_chirp_detail(fig, data)
fig.suptitle(f"LoRa Chirp Recovery | SF={SF}, BW={BW / 1e3:.1f}kHz, Fs={Fs / 1e3:.1f}kHz",
fontsize=12, y=0.98)
# Save
out_path = Path(INPUT_FILE).stem + "_debug.png"
fig.savefig(out_path, dpi=150, bbox_inches='tight')
print(f"Saved: {out_path}")
plt.tight_layout()
plt.show()
if __name__ == "__main__":
main()
Morty Proxy This is a proxified and sanitized view of the page, visit original site.