OCEAN-Lab commited on
Commit
7627dcd
·
verified ·
1 Parent(s): 758d397

Upload visualize_SS_Sine_data_shards.py

Browse files
Files changed (1) hide show
  1. visualize_SS_Sine_data_shards.py +331 -0
visualize_SS_Sine_data_shards.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ─────────────────────────────────────────────────────────────────────────────
2
+ # VISUALIZE A SINGLE DATA POINT FROM THE SHARDED HDF5 DATASET
3
+ #
4
+ # Loads one (frequency, power, repetition) data point from the SS_Sine_data_shards dataset
5
+ # and plots it: the noisy (Data-channel) modulated windows vs. the clean (Reference-derived)
6
+ # target windows, and the per-rep calibration (unmodulated) block.
7
+ #
8
+ # Dataset layout:
9
+ # shards_dir/
10
+ # {stem}_point{NNNN}_f{frequency:.4g}GHz_p{power:+.1f}dBm.h5
11
+ # attrs: power_dbm, frequency_ghz, source_point_path,
12
+ # pulses_per_window, pulse_samples
13
+ # /rep_000/calib_unmod 1D float32 (calib_len,)
14
+ # /rep_000/clean_mod 2D float32 (n_windows, win_len)
15
+ # /rep_000/noisy_mod 2D float32 (n_windows, win_len)
16
+ # /rep_000/rf_phase 1D float32 (n_windows,)
17
+ # /rep_001/...
18
+ #
19
+ # USAGE (command line):
20
+ # python visualize_SS_Sine_data.py --shards_dir /path/to/shards \
21
+ # --frequency 3.5 --power -10.0 --repetition 0 --window 0
22
+ #
23
+ # # list what's actually available in a shards_dir, if you don't know
24
+ # # the exact (frequency, power) values on file:
25
+ # python visualize_SS_Sine_data.py --shards_dir /path/to/shards --list
26
+ #
27
+ # USAGE (as a library, e.g. from a notebook):
28
+ # from visualize_SS_Sine_data import load_point, plot_point
29
+ # point = load_point("/path/to/shards", frequency=3.5, power=-10.0, repetition=0)
30
+ # plot_point(point, window=0)
31
+ # ─────────────────────────────────────────────────────────────────────────────
32
+
33
+ import argparse
34
+ import glob
35
+ import os
36
+ from dataclasses import dataclass
37
+
38
+ import h5py
39
+ import numpy as np
40
+ import matplotlib.pyplot as plt
41
+
42
+ SAMPLE_RATE_HZ = 16e9
43
+
44
+ # Net RF-chain gain (amplifier + cable losses + fixed attenuator) between the
45
+ # AWG-programmed power stored in the shard's power_dbm attr and the actual
46
+ # power delivered to the MZM, for the two attenuator configurations used
47
+ # across the sweep (see the dataset paper's hardware section). Provided as a
48
+ # convenience for --attenuator_db below; pass --gain_db directly for any
49
+ # other value.
50
+ ATTENUATOR_NET_GAIN_DB = {
51
+ 30: 15.2263, # 30 dB attenuator configuration
52
+ 20: 25.2263, # 20 dB attenuator configuration ("high power" filenames)
53
+ }
54
+
55
+
56
+ @dataclass
57
+ class ShardPoint:
58
+ shard_path: str
59
+ frequency_ghz: float
60
+ power_dbm: float # AWG-programmed power, as stored in the shard's attrs
61
+ repetition: str # rep group name, e.g. "rep_000"
62
+ clean_mod: np.ndarray # (n_windows, win_len)
63
+ noisy_mod: np.ndarray # (n_windows, win_len)
64
+ calib_unmod: np.ndarray # (calib_len,)
65
+ pulse_samples: int
66
+ pulses_per_window: int
67
+ gain_db: float = 0.0 # net RF-chain gain to add before display (see load_point)
68
+
69
+ @property
70
+ def display_power_dbm(self):
71
+ """power_dbm + gain_db -- the actual power delivered to the MZM, if gain_db was set."""
72
+ return self.power_dbm + self.gain_db
73
+
74
+
75
+ # ─────────────────────────────────────────────────────────────────────────────
76
+ # FINDING THE RIGHT SHARD
77
+ # ─────────────────────────────────────────────────────────────────────────────
78
+
79
+ def find_shard_file(shards_dir, frequency, power, freq_tol=1e-3, power_tol=1e-3,
80
+ pattern="*.h5"):
81
+ """
82
+ Finds the shard file in shards_dir whose stored attrs match the
83
+ requested (frequency, power) within tolerance. Scans attrs directly
84
+ (robust to filename rounding, e.g. frequency written as %.4g in the
85
+ filename) rather than reconstructing the filename from frequency/power.
86
+
87
+ Returns the matching file path, or raises ValueError listing the
88
+ closest candidates if nothing matches within tolerance.
89
+ """
90
+ h5_paths = sorted(glob.glob(os.path.join(shards_dir, pattern)))
91
+ if not h5_paths:
92
+ raise ValueError(f"No files matching '{pattern}' found in {shards_dir}.")
93
+
94
+ best = None
95
+ best_dist = None
96
+ for path in h5_paths:
97
+ try:
98
+ with h5py.File(path, "r") as f:
99
+ f_ghz = float(f.attrs["frequency_ghz"])
100
+ p_dbm = float(f.attrs["power_dbm"])
101
+ except (OSError, KeyError):
102
+ continue # skip unreadable / non-shard files
103
+
104
+ if abs(f_ghz - frequency) <= freq_tol and abs(p_dbm - power) <= power_tol:
105
+ return path
106
+
107
+ dist = abs(f_ghz - frequency) + abs(p_dbm - power)
108
+ if best_dist is None or dist < best_dist:
109
+ best, best_dist = (path, f_ghz, p_dbm), dist
110
+
111
+ msg = f"No shard in {shards_dir} matches frequency={frequency} GHz, power={power} dBm " \
112
+ f"within tolerance (freq_tol={freq_tol}, power_tol={power_tol})."
113
+ if best is not None:
114
+ msg += f" Closest available: {os.path.basename(best[0])} " \
115
+ f"(frequency_ghz={best[1]}, power_dbm={best[2]})."
116
+ raise ValueError(msg)
117
+
118
+
119
+ def list_available_points(shards_dir, pattern="*.h5"):
120
+ """
121
+ Prints every shard's (frequency, power, n_reps) so you can see what's
122
+ actually on disk without guessing exact values.
123
+ """
124
+ h5_paths = sorted(glob.glob(os.path.join(shards_dir, pattern)))
125
+ if not h5_paths:
126
+ print(f"No files matching '{pattern}' found in {shards_dir}.")
127
+ return
128
+
129
+ print(f"{'shard file':55s} {'freq (GHz)':>10s} {'power (dBm)':>12s} {'n_reps':>7s}")
130
+ print("-" * 90)
131
+ for path in h5_paths:
132
+ try:
133
+ with h5py.File(path, "r") as f:
134
+ freq = float(f.attrs.get("frequency_ghz", float("nan")))
135
+ power = float(f.attrs.get("power_dbm", float("nan")))
136
+ reps = [k for k in f.keys() if k.startswith("rep_")]
137
+ except OSError:
138
+ print(f"{os.path.basename(path):55s} (could not open)")
139
+ continue
140
+ print(f"{os.path.basename(path):55s} {freq:10.4g} {power:12.2f} {len(reps):7d}")
141
+
142
+
143
+ # ─────────────────────────────────────────────────────────────────────────────
144
+ # LOADING A SINGLE DATA POINT
145
+ # ─────────────────────────────────────────────────────────────────────────────
146
+
147
+ def load_point(shards_dir, frequency, power, repetition=0,
148
+ freq_tol=1e-3, power_tol=1e-3, pattern="*.h5", gain_db=0.0):
149
+ """
150
+ Loads one (frequency, power, repetition) data point from the shard
151
+ dataset.
152
+
153
+ frequency, power: the sweep-point values to match (GHz, dBm). These
154
+ are matched against the AWG-programmed power stored in the
155
+ shard's attrs, regardless of gain_db -- gain_db only affects what
156
+ gets displayed (point.display_power_dbm / plot titles), not which
157
+ shard is selected.
158
+ repetition: either an int index into the sorted rep group names
159
+ (0 -> "rep_000", 1 -> "rep_001", ...) or a rep group name string
160
+ directly (e.g. "rep_003").
161
+ gain_db: net RF-chain gain (amplifier + cable losses + fixed
162
+ attenuator) to add to the stored AWG-programmed power when
163
+ displaying/plotting, so plots can show the actual power
164
+ delivered to the MZM instead of the AWG-set value. Defaults to
165
+ 0.0 (no adjustment). See ATTENUATOR_NET_GAIN_DB for the two
166
+ known chain-gain values used across the sweep.
167
+
168
+ Returns a ShardPoint with everything needed to plot/inspect it.
169
+ """
170
+ shard_path = find_shard_file(shards_dir, frequency, power, freq_tol, power_tol, pattern)
171
+
172
+ with h5py.File(shard_path, "r") as f:
173
+ frequency_ghz = float(f.attrs["frequency_ghz"])
174
+ power_dbm = float(f.attrs["power_dbm"])
175
+ pulses_per_window = int(f.attrs["pulses_per_window"])
176
+ pulse_samples = int(f.attrs["pulse_samples"])
177
+
178
+ rep_names = sorted(k for k in f.keys() if k.startswith("rep_"))
179
+ if not rep_names:
180
+ raise ValueError(f"{shard_path} has no rep_* groups.")
181
+
182
+ if isinstance(repetition, str):
183
+ if repetition not in rep_names:
184
+ raise ValueError(f"Repetition '{repetition}' not found in {shard_path}. "
185
+ f"Available: {rep_names}")
186
+ rep_name = repetition
187
+ else:
188
+ if repetition < 0 or repetition >= len(rep_names):
189
+ raise ValueError(f"Repetition index {repetition} out of range for "
190
+ f"{shard_path} (has {len(rep_names)} rep(s): {rep_names}).")
191
+ rep_name = rep_names[repetition]
192
+
193
+ g = f[rep_name]
194
+ clean_mod = g["clean_mod"][:]
195
+ noisy_mod = g["noisy_mod"][:]
196
+ calib_unmod = g["calib_unmod"][:]
197
+
198
+ return ShardPoint(
199
+ shard_path=shard_path,
200
+ frequency_ghz=frequency_ghz,
201
+ power_dbm=power_dbm,
202
+ repetition=rep_name,
203
+ clean_mod=clean_mod,
204
+ noisy_mod=noisy_mod,
205
+ calib_unmod=calib_unmod,
206
+ pulse_samples=pulse_samples,
207
+ pulses_per_window=pulses_per_window,
208
+ gain_db=gain_db,
209
+ )
210
+
211
+
212
+ # ─────────────────────────────────────────────────────────────────────────────
213
+ # PLOTTING
214
+ # ────────────────────────���────────────────────────────────────────────────────
215
+
216
+ def plot_point(point, window=0, save_path=None, show=True):
217
+ """
218
+ Plots one window of a loaded ShardPoint: noisy vs. clean modulated
219
+ waveform (time domain), plus the rep's calibration (unmodulated)
220
+ block.
221
+ """
222
+ n_windows = point.clean_mod.shape[0]
223
+ if window < 0 or window >= n_windows:
224
+ raise ValueError(f"window={window} out of range (this rep has {n_windows} window(s)).")
225
+
226
+ clean_w = point.clean_mod[window]
227
+ noisy_w = point.noisy_mod[window]
228
+
229
+ t_mod_ns = np.arange(len(clean_w)) / SAMPLE_RATE_HZ * 1e9
230
+ t_calib_ns = np.arange(len(point.calib_unmod)) / SAMPLE_RATE_HZ * 1e9
231
+
232
+ fig, axes = plt.subplots(2, 1, figsize=(11, 7), constrained_layout=True)
233
+
234
+ ax = axes[0]
235
+ ax.plot(t_mod_ns, noisy_w, label="noisy_mod (Data channel)", color="tab:orange", lw=0.8)
236
+ ax.plot(t_mod_ns, clean_w, label="clean_mod (Reference target)", color="tab:blue", lw=1.0)
237
+ ax.set_xlabel("Time (ns)")
238
+ ax.set_ylabel("Amplitude")
239
+ power_label = f"power={point.display_power_dbm:+.1f} dBm"
240
+ if point.gain_db:
241
+ power_label += f" (AWG {point.power_dbm:+.1f} dBm + gain {point.gain_db:+.2f} dB)"
242
+ ax.set_title(
243
+ f"freq={point.frequency_ghz:.4g} GHz, {power_label}, "
244
+ f"{point.repetition}, window {window}/{n_windows - 1}"
245
+ )
246
+ ax.legend(loc="upper right")
247
+ ax.grid(alpha=0.3)
248
+
249
+ ax = axes[1]
250
+ ax.plot(t_calib_ns, point.calib_unmod, color="tab:green", lw=0.8)
251
+ ax.set_xlabel("Time (ns)")
252
+ ax.set_ylabel("Amplitude")
253
+ ax.set_title(f"calib_unmod (shared calibration block for {point.repetition})")
254
+ ax.grid(alpha=0.3)
255
+
256
+ if save_path:
257
+ fig.savefig(save_path, dpi=150)
258
+ print(f"Saved figure to {save_path}")
259
+ if show:
260
+ plt.show()
261
+ else:
262
+ plt.close(fig)
263
+ return fig
264
+
265
+
266
+ # ─────────────────────────────────────────────────────────────────────────────
267
+ # CLI
268
+ # ─────────────────────────────────────────────────────────────────────────────
269
+
270
+ def main():
271
+ parser = argparse.ArgumentParser(
272
+ description="Load and visualize one (frequency, power, repetition) "
273
+ "data point from the SS_Sine_data_shards dataset."
274
+ )
275
+ parser.add_argument("--shards_dir", required=True, help="Directory containing the .h5 shard files.")
276
+ parser.add_argument("--frequency", type=float, help="Target RF frequency in GHz.")
277
+ parser.add_argument("--power", type=float, help="Target RF power in dBm.")
278
+ parser.add_argument("--repetition", default=0,
279
+ help="Repetition index (0,1,2,...) or rep group name (e.g. rep_003). Default: 0.")
280
+ parser.add_argument("--window", type=int, default=0,
281
+ help="Which window within the repetition to plot. Default: 0.")
282
+ parser.add_argument("--freq_tol", type=float, default=1e-3, help="Matching tolerance for frequency (GHz).")
283
+ parser.add_argument("--power_tol", type=float, default=1e-3, help="Matching tolerance for power (dBm).")
284
+ parser.add_argument("--gain_db", type=float, default=0.0,
285
+ help="Net RF-chain gain (dB) to add to the shard's stored (AWG-programmed) "
286
+ "power when displaying/plotting, so plots show the actual power "
287
+ "delivered to the MZM. Does not affect --power matching. "
288
+ "Ignored if --attenuator_db is given.")
289
+ parser.add_argument("--attenuator_db", type=int, default=None, choices=sorted(ATTENUATOR_NET_GAIN_DB),
290
+ help="Convenience alternative to --gain_db: pick the attenuator configuration "
291
+ f"used for this capture ({', '.join(f'{k} -> {v} dB' for k, v in ATTENUATOR_NET_GAIN_DB.items())}) "
292
+ "and the matching net chain gain is applied automatically.")
293
+ parser.add_argument("--save", default=None,
294
+ help="If given, save the figure(s) to this path (prefix) instead of only showing them.")
295
+ parser.add_argument("--no_show", action="store_true", help="Don't open an interactive window (just save/print).")
296
+ parser.add_argument("--list", action="store_true",
297
+ help="List every shard's (frequency, power, n_reps) in shards_dir and exit.")
298
+ args = parser.parse_args()
299
+
300
+ if args.list:
301
+ list_available_points(args.shards_dir)
302
+ return
303
+
304
+ if args.frequency is None or args.power is None:
305
+ parser.error("--frequency and --power are required unless --list is given.")
306
+
307
+ repetition = args.repetition
308
+ try:
309
+ repetition = int(repetition)
310
+ except (TypeError, ValueError):
311
+ pass # keep as string rep group name
312
+
313
+ gain_db = ATTENUATOR_NET_GAIN_DB[args.attenuator_db] if args.attenuator_db is not None else args.gain_db
314
+
315
+ point = load_point(
316
+ args.shards_dir, args.frequency, args.power, repetition,
317
+ freq_tol=args.freq_tol, power_tol=args.power_tol, gain_db=gain_db,
318
+ )
319
+ print(f"Loaded {point.shard_path}")
320
+ print(f" frequency_ghz={point.frequency_ghz}, power_dbm (AWG)={point.power_dbm}, "
321
+ f"gain_db={point.gain_db}, display_power_dbm={point.display_power_dbm}, "
322
+ f"repetition={point.repetition}")
323
+ print(f" clean_mod/noisy_mod shape: {point.clean_mod.shape}, "
324
+ f"calib_unmod shape: {point.calib_unmod.shape}")
325
+
326
+ save_path = f"{args.save}_window.png" if args.save else None
327
+ plot_point(point, window=args.window, save_path=save_path, show=not args.no_show)
328
+
329
+
330
+ if __name__ == "__main__":
331
+ main()