""" Continuous-Time Photonic Time-Stretch ADC (CTS-PADC) Dataset Data inspection, loading, and visualization script. Repository: https://huggingface.co/datasets/OCEAN-Lab/CTS-PADC_Dataset """ import json import numpy as np import pandas as pd import matplotlib.pyplot as plt # ===================================================================== # Constants & Acquisition Specifications # ===================================================================== VECTOR_LEN = 400 # Sequence length (temporal samples per vector) STRETCH_FACTOR = 3.0 # Nominal photonic stretch factor (S ≈ 3) SAMPLE_RATE_GSPS = 1.0 # Digitizer sampling rate (1 GSa/s post-stretch) # ===================================================================== # 1. Data Parsing Utilities # ===================================================================== def parse_waveform_series(series: pd.Series, length: int = VECTOR_LEN) -> np.ndarray: """ Decodes string-encoded JSON arrays from CSVs or extracts lists from Parquet/Hugging Face. """ first_item = series.iloc[0] if isinstance(first_item, str): return np.array([json.loads(row)[:length] for row in series], dtype=np.float32) elif isinstance(first_item, (list, np.ndarray)): return np.array([row[:length] for row in series], dtype=np.float32) else: raise TypeError(f"Unexpected data type in series: {type(first_item)}") # ===================================================================== # 2. Loading Methods # ===================================================================== def load_via_huggingface(split: str = "train"): """ Downloads and loads the dataset directly using the Hugging Face `datasets` library. Install dependency: pip install datasets """ try: from datasets import load_dataset except ImportError: raise ImportError("Run `pip install datasets` to fetch data directly from Hugging Face.") print(f"Loading '{split}' partition from Hugging Face (OCEAN-Lab/CTS-PADC_Dataset)...") dataset = load_dataset("OCEAN-Lab/CTS-PADC_Dataset", split=split) df = pd.DataFrame(dataset) return df def load_via_local_csv(csv_path: str): """ Loads dataset directly from a local CSV file. """ print(f"Loading data from local path: {csv_path}...") df = pd.read_csv(csv_path) return df # ===================================================================== # 3. Diagnostic Visualization (Time & Frequency Domain) # ===================================================================== def plot_sample_diagnostics(df: pd.DataFrame, sample_index: int = 0, save_path: str = "sample_inspection.png"): """ Plots the distorted input waveform versus the ground truth continuous-wave target in both the time and frequency domains. """ record = df.iloc[sample_index] # Extract metadata rf_freq = record["Frequencies"] rf_power = record["Power"] expected_freq = record.get("expected_recovered_freq", rf_freq / STRETCH_FACTOR) # Parse temporal vectors raw_distorted = record["arcsin_results"] if isinstance(raw_distorted, str): x_distorted = np.array(json.loads(raw_distorted)[:VECTOR_LEN]) y_ground_truth = np.array(json.loads(record["test_data"])[:VECTOR_LEN]) else: x_distorted = np.array(raw_distorted[:VECTOR_LEN]) y_ground_truth = np.array(record["test_data"][:VECTOR_LEN]) # Time and frequency axes time_ns = np.arange(VECTOR_LEN) / SAMPLE_RATE_GSPS # Time in nanoseconds freqs_mhz = np.fft.rfftfreq(VECTOR_LEN, d=1.0 / (SAMPLE_RATE_GSPS * 1e9)) / 1e6 # Frequency in MHz # FFT Spectra (in dB) fft_distorted = 20 * np.log10(np.abs(np.fft.rfft(x_distorted)) + 1e-6) fft_ground_truth = 20 * np.log10(np.abs(np.fft.rfft(y_ground_truth)) + 1e-6) # Plot fig, axes = plt.subplots(1, 2, figsize=(14, 4.5)) # Time-Domain axes[0].plot(time_ns, y_ground_truth, label="Ground Truth (Ideal CW)", color="black", linestyle="--", linewidth=1.2) axes[0].plot(time_ns, x_distorted, label="Distorted Input (arcsin_results)", color="crimson", alpha=0.75, linewidth=1.0) axes[0].set_title(f"Time-Domain Waveform\n($f_{{RF}} = {rf_freq}$ GHz, $P_{{in}} = {rf_power}$ dBm)", fontsize=11) axes[0].set_xlabel("Time (ns)", fontsize=10) axes[0].set_ylabel("Amplitude (V)", fontsize=10) axes[0].grid(True, linestyle=":", alpha=0.6) axes[0].legend(loc="upper right", frameon=True) # Frequency-Domain axes[1].plot(freqs_mhz, fft_ground_truth, label="Ground Truth Target", color="black", linestyle="--", linewidth=1.2) axes[1].plot(freqs_mhz, fft_distorted, label="Distorted Spectrum", color="crimson", alpha=0.75, linewidth=1.0) axes[1].axvline(expected_freq * 1e3, color="blue", linestyle=":", label=f"Stretched Carrier ({expected_freq * 1e3:.1f} MHz)") axes[1].set_title(f"Power Spectrum (FFT)\nExpected Peak: ~{expected_freq * 1e3:.1f} MHz", fontsize=11) axes[1].set_xlabel("Frequency (MHz)", fontsize=10) axes[1].set_ylabel("Magnitude (dB)", fontsize=10) axes[1].grid(True, linestyle=":", alpha=0.6) axes[1].legend(loc="upper right", frameon=True) plt.tight_layout() plt.savefig(save_path, dpi=300) print(f"Saved diagnostic plot to: {save_path}") plt.show() # ===================================================================== # 4. Main Entry Point # ===================================================================== if __name__ == "__main__": # Set to True if reading from downloaded CSV files locally USE_LOCAL_CSV = False if USE_LOCAL_CSV: df = load_via_local_csv("training_data.csv") else: # Stream / download directly from Hugging Face df = load_via_huggingface(split="train") print("\nDataset Summary:") print(f"Total Rows: {len(df):,}") print(f"Columns: {list(df.columns)}") # Plot sample 0 plot_sample_diagnostics(df, sample_index=0, save_path="padc_sample_plot.png")