"""Measure phase lag and chronology in Chen et al.'s locked probe records.""" from argparse import ArgumentParser import csv from hashlib import file_digest from io import BytesIO, StringIO import json from pathlib import Path from zipfile import ZipFile import numpy as np from scipy.io import loadmat FIGURE = "Phase_Locking_Data_Zenodo/Fig3/" INPUT_MD5 = "d7884c1e82d2e54fe585b1cdd56106b1" TRACES = [ ("fast", 100_000, 1, (0.00002, 0.0001, 0.001, 0.01, 0.1)), ("slow", 10, 120, (0.1, 1, 10, 60)), ] def checksum(path, algorithm): with path.open("rb") as handle: return file_digest(handle, algorithm).hexdigest() def mat(archive, path, names): return loadmat(BytesIO(archive.read(FIGURE + path)), variable_names=names) def calibration(archive, speed): if speed == "fast": raw = mat(archive, "fast_data/1_5_pi_max_min.mat", ["y"])["y"].ravel() else: received = archive.read(FIGURE + "slow_data/max_min_20241004.csv").decode("utf-8-sig") series = [] for row in list(csv.reader(StringIO(received)))[13:]: if len(row) < 4: continue try: series.append(float(row[3])) except ValueError: continue raw = np.asarray(series) if not (len(raw) > 50 and np.isfinite(raw).all() and raw.min() < raw.max()): raise ValueError(f"Unexpected {speed} calibration stream.") return float(raw.min()), float(raw.max()) def complex_output(value): return [float(value.real), float(value.imag)] def compare(phase, times, rate, seconds_per_stratum, lag_seconds): lag = int(round(rate * lag_seconds)) stride = int(seconds_per_stratum * rate) total = compared_strata = 0 observed = shuffled = 0j sum_d2 = shuffle_d2 = cross = first_square = second_square = 0.0 for start in range(0, len(phase), stride): chunk = phase[start:start + stride] take = (len(chunk) // (2 * lag)) * 2 * lag if take == 0: continue windows = chunk[:take].reshape(-1, lag * 2) first, second = windows[:, :lag].ravel(), windows[:, lag:].ravel() valid = np.isfinite(first) & np.isfinite(second) if times is not None: stamps = times[start:start + take].reshape(-1, 2 * lag) gap = (stamps[:, lag:] - stamps[:, :lag]).ravel() valid &= np.isclose(gap, lag_seconds, rtol=.0002, atol=2e-8) first, second = first[valid], second[valid] if len(first) < 2: continue total += len(first) compared_strata += 1 a, b = np.exp(1j * first), np.exp(1j * second) observed += np.vdot(a, b) shuffled += len(first) * np.conj(a.mean()) * b.mean() sum_d2 += np.square(second - first).sum() shuffle_d2 += len(first) * (first.var() + second.var() + (first.mean() - second.mean())**2) first -= first.mean() second -= second.mean() cross += np.dot(first, second) first_square += np.dot(first, first) second_square += np.dot(second, second) if not total or not (first_square > 0 and second_square > 0): raise ValueError(f"Insufficient qualifying lag pairs at {lag_seconds} s.") chron, control = observed / total, shuffled / total return {"lagSeconds": lag_seconds, "disjointPairs": total, "strata": compared_strata, "chronologicalIncrementMoment": complex_output(chron), "shuffledIncrementMoment": complex_output(control), "phaseResidualCorrelation": float(cross / np.sqrt(first_square * second_square)), "rmsIncrementMrad": float(1000 * np.sqrt(sum_d2 / total)), "shuffledRmsIncrementMrad": float(1000 * np.sqrt(shuffle_d2 / total)), "idealParityGainOverFixedMarginalsWithPhaseMask": float((chron.real - control.real) / 4)} def measure(archive, speed, rate, seconds_per_stratum, lags): limits = calibration(archive, speed) low, high = limits data = mat(archive, speed + "_data/2_0_pi.mat", ["t", "y"]) samples = data["y"].ravel() normalized = 2 * (samples - low) / (high - low) - 1 included = np.abs(normalized) <= 1 phase = np.full(len(samples), np.nan) phase[included] = np.arcsin(normalized[included]) stamps = data["t"].ravel() if "t" in data else None clock = None if stamps is not None: if len(stamps) != len(samples): raise ValueError("Fast trace and recorded time lengths disagree.") differences = np.diff(stamps) if (differences <= 0).any(): raise ValueError("Recorded time is not strictly increasing.") clock = {"startSec": float(stamps[0]), "endSec": float(stamps[-1]), "medianStepSec": float(np.median(differences))} if not np.isclose(clock["medianStepSec"], 1 / rate, rtol=.001): raise ValueError("Recorded time does not support the nominal sampling rate.") halfway = len(samples) // 2 summary = {} for label, start, stop in [("firstHalf", 0, halfway), ("heldOutHalf", halfway, len(samples))]: subset = phase[start:stop] summary[label] = {"samples": len(subset), "phaseMeanMrad": float(1000 * np.nanmean(subset)), "phaseStdMrad": float(1000 * np.nanstd(subset)), "lags": [compare(subset, stamps[start:stop] if stamps is not None else None, rate, seconds_per_stratum, lag) for lag in lags]} return {"samplingHz": rate, "calibrationMinMax": list(limits), "outOfCalibrationRange": int(np.count_nonzero(~included)), "recordedClock": clock, "stratumSeconds": seconds_per_stratum, **summary} def main(): parser = ArgumentParser(description=__doc__) parser.add_argument("archive", type=Path) parser.add_argument("report", type=Path) args = parser.parse_args() if checksum(args.archive, "md5") != INPUT_MD5: raise SystemExit("Input does not match the repository's published checksum.") with ZipFile(args.archive) as source: analysis = {trace[0]: measure(source, *trace) for trace in TRACES} report = {"inputSha256": checksum(args.archive, "sha256"), "source": "https://doi.org/10.5281/zenodo.13896882", "method": "classical locked phase probe; dimensionless circular incremental moment", "traces": analysis} with args.report.open("x", encoding="utf-8") as output: json.dump(report, output, indent=2, allow_nan=False) output.write("\n") for name, stage in analysis.items(): print(name, stage["recordedClock"], "out of calibration", stage["outOfCalibrationRange"]) for part in ("firstHalf", "heldOutHalf"): for row in stage[part]["lags"]: print(part, row["lagSeconds"], row["disjointPairs"], row["phaseResidualCorrelation"], row["rmsIncrementMrad"], row["shuffledRmsIncrementMrad"]) if __name__ == "__main__": main()