"""Estimate time-slit separations in Tirole et al.'s published Fig. 2f spectra.""" import argparse import hashlib from io import BytesIO from json import dumps from pathlib import Path from zipfile import ZipFile import numpy as np from openpyxl import load_workbook ARCHIVE_SHA256 = "1384eb10d5aafb2a3758d46bfd71f40595d82cb04647100791b422c04865f289" FIGURE = "Double-slit time diffraction at optical frequencies - Source Data/Fig_2_Source_data.xlsx" BANDS = ((220.5, 226.5), (236.0, 242.0)) SCAN_FS = np.arange(450.0, 1551.0, 1.0) def fit_band(frequencies, spectra): """Remove a quadratic baseline in signed counts and fit both phase quadratures.""" centered = frequencies - frequencies.mean() trends = np.column_stack([np.ones(len(centered)), centered, centered ** 2]) envelope, _ = np.linalg.qr(trends) residuals = spectra - (spectra @ envelope) @ envelope.T angles = 2 * np.pi / 1000 * np.outer(SCAN_FS, centered) quadratures = np.stack([np.cos(angles), np.sin(angles)], axis=-1) orthogonal = quadratures - envelope @ (envelope.T @ quadratures) projection, _ = np.linalg.qr(orthogonal) fit_energy = np.sum((projection.transpose(0, 2, 1) @ residuals.T) ** 2, axis=1) energy = np.sum(residuals ** 2, axis=1) if np.any(energy <= 0): raise ValueError("A selected trace has no variation after baseline removal.") r_squared = fit_energy / energy best = np.argmax(r_squared, axis=0) return SCAN_FS[best], r_squared[best, np.arange(len(spectra))], r_squared def nearest_score(scores, delays): grid = np.abs(SCAN_FS[:, None] - delays[None, :]).argmin(axis=0) return scores[grid, np.arange(scores.shape[1])] def extract(archive_path): if hashlib.sha256(archive_path.read_bytes()).hexdigest() != ARCHIVE_SHA256: raise ValueError("Input differs from the frozen authors’ source archive.") with ZipFile(archive_path) as archive: figure = archive.read(FIGURE) workbook = load_workbook(BytesIO(figure), data_only=True, read_only=True) try: rows = list(workbook["Fig 2f"].values) measured = list(workbook["Fig 2e"].values) finally: workbook.close() exact_axes = rows[0][1] == "Frequencies (THz)" and rows[1][:2] == ("Slit separation (fs)", "Counts (MHz):") if not exact_axes: raise ValueError("The source column meanings changed.") frequencies = np.asarray(rows[0][2:], dtype=float) labels = np.asarray([row[0] for row in rows[2:]], dtype=float) spectra = np.asarray([row[2:] for row in rows[2:]], dtype=float) if spectra.shape != (27, 640) or not np.isfinite(spectra).all(): raise ValueError("Unexpected source scan coverage.") pairs = np.array([(x, y) for x, y in zip(measured[0][1:], measured[1][1:]) if x is not None and y is not None]) return frequencies, labels, spectra, pairs def recheck(archive): frequencies, labels, spectra, published = extract(archive) all_rows = len(labels) # Require at least 4 nominal periods in each six-THz band. Keep both sides # of the original delay scan, plus its zero-delay comparison row. check = (np.abs(labels) >= 700 - 1e-6) | (labels == 0) spectra = spectra[check, :] labels = labels[check] result = [] for band in BANDS: mask = (frequencies >= band[0]) & (frequencies <= band[1]) result.append(fit_band(frequencies[mask], spectra[:, mask])) (fit_low, score_low, _), (fit_high, score_high, all_high) = result predictive_score = nearest_score(all_high, fit_low) entries = [{"nominalDelay_fs": round(float(label)), "lowerBandFit_fs": int(lo), "upperBandFit_fs": int(hi), "lowerBandR2": float(r_lo), "upperBandR2": float(r_hi), "upperBandR2AtLowerBandFit": float(holdout)} for label, lo, hi, r_lo, r_hi, holdout in zip(labels, fit_low, fit_high, score_low, score_high, predictive_score)] observed = labels != 0 error = np.abs(fit_low[observed] - fit_high[observed]) / np.abs(labels[observed]) direct = np.abs(fit_low[observed] - np.abs(labels[observed])) / np.abs(labels[observed]) original_criterion = np.abs(published[:, 0]) * published[:, 1] / 1000 return {"archiveSha256": ARCHIVE_SHA256, "sheet": "Fig 2f", "allDelayRows": all_rows, "usableFrequencyBins": len(frequencies), "frequencyBands_THz": BANDS, "fits": entries, "nominalNonzeroRows": int(np.sum(observed)), "medianIndependentBandDisagreementRelativeToNominal": float(np.median(error)), "medianLowerBandRelativeErrorFromNominal": float(np.median(direct)), "publishedOscillationPoints": {"sheet": "Fig 2e", "rows": len(published), "medianReciprocalRatio": float(np.median(original_criterion))}} if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("archive", type=Path, help="Verified Figshare source ZIP, DOI 10.6084/m9.figshare.21968435") print(dumps(recheck(parser.parse_args().archive), indent=2))