Datasets:
Formats:
json
Languages:
English
Size:
< 1K
ArXiv:
Tags:
mathematics
phase-retrieval
short-time-fourier-transform
inverse-problems
identifiability
signal-processing
Download verify.py from PureOne/Ilyaxune-Phase-Retrieval: direct link, hf CLI and curl.
- Browser
- Download file 12.6 kB
-
https://huggingface.co/datasets/PureOne/Ilyaxune-Phase-Retrieval/resolve/main/verify.py
- Command line
-
hf download hf://datasets/PureOne/Ilyaxune-Phase-Retrieval/verify.py
-
curl -L -o verify.py https://huggingface.co/datasets/PureOne/Ilyaxune-Phase-Retrieval/resolve/main/verify.py
12.6 kB
| #!/usr/bin/env python3 | |
| """Reproduce a FINITE CYCLIC analogue of the manuscript's STFT obstruction. | |
| This numerical experiment does not prove the infinite-dimensional theorem. | |
| Its complete finite measurement grid is Z_N x Z_N, using a unitary DFT. | |
| Only NumPy and matplotlib are required. Run: python3 verify.py | |
| Outputs: verification.json, verification_figure.png, verification_figure.pdf. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| from pathlib import Path | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| def stft(f: np.ndarray, window: np.ndarray) -> np.ndarray: | |
| """Rows are all cyclic shifts; columns are all unitary-DFT frequencies.""" | |
| return np.array([ | |
| np.fft.fft(f * np.conjugate(np.roll(window, shift)), norm="ortho") | |
| for shift in range(len(f)) | |
| ]) | |
| def quotient_distance(x: np.ndarray, y: np.ndarray) -> float: | |
| """min_{|alpha|=1} ||x - alpha*y||_2, with stable direct subtraction.""" | |
| inner = np.vdot(y, x) | |
| alpha = inner / abs(inner) if abs(inner) else 1.0 + 0.0j | |
| return float(np.linalg.norm(x - alpha * y)) | |
| def main() -> None: | |
| out = Path(__file__).resolve().parent | |
| n_samples, bandwidth, rho, seed = 256, 12, 0.82, 20261115 | |
| n = np.arange(n_samples) | |
| spectrum_q = np.zeros(n_samples, dtype=complex) | |
| spectrum_q[:bandwidth] = rho ** np.arange(bandwidth) | |
| q = np.fft.ifft(spectrum_q, norm="ortho") | |
| g = np.abs(q) ** 2 | |
| g /= np.linalg.norm(g) | |
| alternating = (-1.0) ** n | |
| f_plus = g * (1.0 + 0.5 * alternating) / np.sqrt(1.25) | |
| f_minus = g * (1.0 - 0.5 * alternating) / np.sqrt(1.25) | |
| v_plus, v_minus = stft(f_plus, g), stft(f_minus, g) | |
| mag_plus, mag_minus = np.abs(v_plus), np.abs(v_minus) | |
| mag_difference = np.abs(mag_plus - mag_minus) | |
| v_first, v_second = stft(g, g), stft(alternating * g, g) | |
| centered_frequencies = np.fft.fftfreq(n_samples) * n_samples | |
| outside_g_support = np.abs(centered_frequencies) > bandwidth - 1 | |
| spectrum_g = np.fft.fft(g, norm="ortho") | |
| tol = 1e-12 | |
| expected_distance = 2.0 / np.sqrt(5.0) | |
| # Three spectral sectors, each a modulation of the same normalized window. | |
| # Their windowed Fourier supports are disjoint on the complete finite grid. | |
| sectors_count = 3 | |
| centers = np.array([0, 85, 170]) | |
| basis = np.array([ | |
| g * np.exp(2j * np.pi * center * n / n_samples) for center in centers | |
| ]) | |
| gram = basis.conjugate() @ basis.T | |
| fourier_mixtures = np.array([ | |
| np.exp(2j * np.pi * r * np.arange(sectors_count) / sectors_count) @ basis | |
| / np.sqrt(sectors_count) | |
| for r in range(sectors_count) | |
| ]) | |
| mixture_gram = fourier_mixtures.conjugate() @ fourier_mixtures.T | |
| mixture_data = np.array([np.abs(stft(f, g)) for f in fourier_mixtures]) | |
| sector_data_discrepancy = max( | |
| float(np.max(np.abs(y - mixture_data[0]))) for y in mixture_data | |
| ) | |
| # Tree bridge measurements repair the relative phases on this known orbit. | |
| phases = np.array([0.37, -1.14, 2.02]) | |
| coefficients = np.exp(1j * phases) / np.sqrt(sectors_count) | |
| bridge_edges = [(0, 1), (1, 2)] | |
| recovered = np.zeros(sectors_count, dtype=complex) | |
| recovered[0] = abs(coefficients[0]) | |
| bridge_records = [] | |
| for i, j in bridge_edges: | |
| y_real = float(abs(coefficients[i] + coefficients[j]) ** 2) | |
| y_imag = float(abs(coefficients[i] + 1j * coefficients[j]) ** 2) | |
| diagonal_sum = float(abs(coefficients[i]) ** 2 + abs(coefficients[j]) ** 2) | |
| correlation = (y_real - diagonal_sum) / 2 + 1j * (y_imag - diagonal_sum) / 2 | |
| recovered[j] = np.conjugate(correlation / recovered[i]) | |
| bridge_records.append({ | |
| "edge": [i, j], "intensity_plus": y_real, "intensity_plus_i": y_imag, | |
| "correlation_real": float(correlation.real), | |
| "correlation_imag": float(correlation.imag), | |
| }) | |
| bridge_error = quotient_distance(recovered, coefficients) | |
| # The raw perturbation has exactly the requested l2 size. For the normalized | |
| # window, use the ACTUAL perturbation size in the theorem, not the nominal one. | |
| rng = np.random.default_rng(seed) | |
| direction = rng.standard_normal(n_samples) + 1j * rng.standard_normal(n_samples) | |
| direction /= np.linalg.norm(direction) | |
| perturbations = [] | |
| for epsilon in [1e-6, 1e-4, 1e-2, 1e-1]: | |
| raw_window = g + epsilon * direction | |
| for mode in ["raw", "normalized"]: | |
| window = raw_window if mode == "raw" else raw_window / np.linalg.norm(raw_window) | |
| delta = float(np.linalg.norm(window - g)) | |
| plus = np.abs(stft(f_plus, window)) | |
| minus = np.abs(stft(f_minus, window)) | |
| distance = float(np.linalg.norm(plus - minus)) | |
| intensity_distance = float(np.linalg.norm(plus ** 2 - minus ** 2)) | |
| orbit_to_common = max( | |
| float(np.linalg.norm(np.abs(stft(f, window)) - mixture_data[0])) | |
| for f in fourier_mixtures | |
| ) | |
| perturbations.append({ | |
| "mode": mode, | |
| "nominal_epsilon": epsilon, | |
| "actual_window_change_l2": delta, | |
| "window_l2_norm": float(np.linalg.norm(window)), | |
| "pair_amplitude_data_l2_distance": distance, | |
| "pair_amplitude_bound": 2.0 * delta, | |
| "pair_intensity_data_l2_distance": intensity_distance, | |
| "pair_intensity_bound": 4.0 * delta + 2.0 * delta ** 2, | |
| "three_sector_max_distance_to_common_baseline": orbit_to_common, | |
| "three_sector_common_baseline_bound": delta, | |
| "bounds_pass": bool( | |
| distance <= 2.0 * delta + tol | |
| and intensity_distance <= 4.0 * delta + 2.0 * delta ** 2 + tol | |
| and orbit_to_common <= delta + tol | |
| ), | |
| }) | |
| values = { | |
| "window_minimum": float(np.min(g)), | |
| "window_l2_norm": float(np.linalg.norm(g)), | |
| "f_plus_minimum": float(np.min(f_plus)), | |
| "f_minus_minimum": float(np.min(f_minus)), | |
| "f_plus_l2_norm": float(np.linalg.norm(f_plus)), | |
| "f_minus_l2_norm": float(np.linalg.norm(f_minus)), | |
| "f_plus_minus_inner_product": float(np.vdot(f_plus, f_minus).real), | |
| "signal_quotient_distance": quotient_distance(f_plus, f_minus), | |
| "predicted_signal_quotient_distance": float(expected_distance), | |
| "max_amplitude_data_difference": float(np.max(mag_difference)), | |
| "amplitude_data_l2_difference": float(np.linalg.norm(mag_difference)), | |
| "max_intensity_data_difference": float(np.max(np.abs(mag_plus ** 2 - mag_minus ** 2))), | |
| "moyal_sum_plus": float(np.sum(mag_plus ** 2)), | |
| "max_component_crossproduct": float(np.max(np.abs(v_first * np.conjugate(v_second)))), | |
| "max_window_spectrum_outside_proved_support": float(np.max(np.abs(spectrum_g[outside_g_support]))), | |
| "three_sector_basis_gram_error": float(np.max(np.abs(gram - np.eye(sectors_count)))), | |
| "three_sector_mixture_gram_error": float(np.max(np.abs(mixture_gram - np.eye(sectors_count)))), | |
| "three_sector_max_amplitude_data_difference": sector_data_discrepancy, | |
| "bridge_reconstruction_error_mod_global_phase": bridge_error, | |
| } | |
| checks = { | |
| "window_strictly_positive_at_every_cyclic_sample": bool(np.all(g > 0)), | |
| "both_signals_strictly_positive_at_every_cyclic_sample": bool(np.all(f_plus > 0) and np.all(f_minus > 0)), | |
| "all_norms_correct": bool(max(abs(np.linalg.norm(f) - 1) for f in [g, f_plus, f_minus]) < tol), | |
| "quotient_distance_correct": abs(values["signal_quotient_distance"] - expected_distance) < tol, | |
| "full_spectrogram_equality_to_numerical_tolerance": values["max_amplitude_data_difference"] < tol, | |
| "component_crossproducts_zero_to_numerical_tolerance": values["max_component_crossproduct"] < tol, | |
| "finite_moyal_identity": abs(values["moyal_sum_plus"] - 1.0) < tol, | |
| "proved_fourier_support_matches": values["max_window_spectrum_outside_proved_support"] < tol, | |
| "three_sector_orbit_verifies": bool(sector_data_discrepancy < tol and values["three_sector_mixture_gram_error"] < tol), | |
| "tree_bridge_reconstruction_verifies": bridge_error < tol, | |
| "all_perturbation_bounds_verify": all(p["bounds_pass"] for p in perturbations), | |
| } | |
| checks = {name: bool(passed) for name, passed in checks.items()} | |
| result = { | |
| "scope": "Finite cyclic analogue on Z_256; numerical reproduction, not the infinite-dimensional proof.", | |
| "parameters": {"N": n_samples, "L": bandwidth, "rho": rho, "random_seed": seed, "absolute_tolerance": tol}, | |
| "normalization": "Unitary DFT; sum over the complete shift-frequency grid of |V_g f|^2 equals ||g||_2^2 ||f||_2^2.", | |
| "construction": "Q[r]=rho^r for 0<=r<L, q=unitary IDFT(Q), g=|q|^2/|||q|^2||_2, f_plus/minus=g*(1 +/- 0.5*(-1)^n)/sqrt(1.25).", | |
| "theoretical_reason": "The geometric sum makes q nonzero at all samples. The DFT of g is supported in [-(L-1),L-1]. The two STFT component frequency regions are disjoint, so their relative sign is invisible.", | |
| "values": values, | |
| "checks": checks, | |
| "all_checks_pass": all(checks.values()), | |
| "three_sector_centers": centers.tolist(), | |
| "bridge_measurements": bridge_records, | |
| "bridge_scope": "Repairs relative phases of this known three-sector orbit, not arbitrary unknown within-sector signals. Two distinct interference phases per edge of a tree.", | |
| "perturbations": perturbations, | |
| "limitations": [ | |
| "Floating-point agreement verifies this finite construction only.", | |
| "The exact infinite-dimensional theorem must be checked from the analytic proof.", | |
| "No AI training, RSI experiment, or wall-clock acceleration is measured.", | |
| "Perturbed-window injectivity is not assumed or established by these checks.", | |
| ], | |
| } | |
| (out / "verification.json").write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") | |
| plt.rcParams.update({"font.size": 10, "axes.titlesize": 11, "axes.labelsize": 10}) | |
| fig, axes = plt.subplots(1, 3, figsize=(14.2, 4.7), constrained_layout=True) | |
| fig.suptitle("A positive window and two positive signals with identical finite STFT magnitudes", fontsize=14) | |
| axes[0].plot(n, f_plus, color="#a34e16", label="$f_+$", linewidth=1.15) | |
| axes[0].plot(n, f_minus, color="#087e8b", label="$f_-$", linewidth=1.15, alpha=0.9) | |
| axes[0].plot(n, g, color="#545b65", label="$g$", linewidth=1.0, linestyle="--", alpha=0.8) | |
| axes[0].set(title="Distinct, strictly positive signals", xlabel="Cyclic sample", ylabel="Signal value") | |
| axes[0].legend(frameon=False) | |
| axes[0].text(0.05, 0.84, f"Distance modulo phase: {values['signal_quotient_distance']:.6f}", transform=axes[0].transAxes, fontsize=9) | |
| axes[0].grid(alpha=0.15) | |
| relative = np.fft.fftshift(mag_plus, axes=1).T / np.max(mag_plus) | |
| db = 20 * np.log10(np.maximum(relative, 1e-6)) | |
| im = axes[1].imshow(db, origin="lower", aspect="auto", extent=(0, n_samples - 1, -0.5, 0.5), cmap="magma", vmin=-120, vmax=0) | |
| axes[1].set(title="Complete magnitude data for $f_+$", xlabel="Window shift", ylabel="Frequency (cycles/sample)") | |
| fig.colorbar(im, ax=axes[1], label="dB relative to peak; floor −120 dB", shrink=0.85) | |
| residual = np.fft.fftshift(mag_difference, axes=1).T | |
| residual_scale = 1e-17 | |
| im2 = axes[2].imshow(residual / residual_scale, origin="lower", aspect="auto", extent=(0, n_samples - 1, -0.5, 0.5), cmap="viridis", vmin=0) | |
| axes[2].set(title="Floating-point residual $||V_g f_+|-|V_g f_-||$", xlabel="Window shift", ylabel="Frequency (cycles/sample)") | |
| fig.colorbar(im2, ax=axes[2], label="Absolute difference × $10^{17}$", shrink=0.85) | |
| axes[2].text(0.04, 0.94, f"Maximum: {values['max_amplitude_data_difference']:.2e}", transform=axes[2].transAxes, fontsize=9, color="white", va="top", bbox={"facecolor": "black", "alpha": 0.55, "edgecolor": "none"}) | |
| fig.supxlabel("Finite cyclic analogue, N = 256. Numerical agreement is not the infinite-dimensional proof.", fontsize=10) | |
| fig.savefig(out / "verification_figure.png", dpi=200) | |
| fig.savefig(out / "verification_figure.pdf") | |
| plt.close(fig) | |
| print(json.dumps({"all_checks_pass": result["all_checks_pass"], "values": values}, indent=2)) | |
| if not result["all_checks_pass"]: | |
| raise SystemExit("At least one verification check failed.") | |
| if __name__ == "__main__": | |
| main() | |