#!/usr/bin/env python3 """Export the Ilyaxune finite example and its recorded results as JSONL. Run from an extracted repository with ``python tools/build_dataset.py``. The source files are resolved beside this script's parent directory, never from the current working directory. Requires NumPy and the Python standard library; the verification program is not imported or executed. """ from __future__ import annotations import argparse import json import math from pathlib import Path import numpy as np def write_jsonl(path: Path, records: list[dict]) -> None: path.parent.mkdir(parents=True, exist_ok=True) encoded = "".join( json.dumps(record, ensure_ascii=False, allow_nan=False, sort_keys=True) + "\n" for record in records ) path.write_bytes(encoded.encode("utf-8")) def assert_close(name: str, observed: float, recorded: float, tolerance: float) -> None: if not math.isclose(observed, recorded, rel_tol=0.0, abs_tol=tolerance): raise ValueError( f"Reconstructed {name} does not match verification.json: " f"{observed!r} versus {recorded!r} (absolute tolerance {tolerance!r})" ) def build(root: Path, destination: Path) -> dict[str, int]: if not (root / "verify.py").is_file(): raise FileNotFoundError(f"Expected the original verification program: {root / 'verify.py'}") source = root / "verification.json" recorded = json.loads(source.read_text(encoding="utf-8")) params = recorded["parameters"] n_samples = int(params["N"]) bandwidth = int(params["L"]) rho = float(params["rho"]) tolerance = float(params["absolute_tolerance"]) if not (n_samples > 0 and n_samples % 2 == 0 and 0 < bandwidth < n_samples / 8 and 0 < rho < 1): raise ValueError("Parameters do not describe the released separated-band construction.") if tolerance <= 0 or not math.isfinite(tolerance): raise ValueError("The recorded absolute tolerance must be positive and finite.") # Same operations and normalization as verify.py. The sample values are # constructed inputs, while the other exports preserve recorded outputs. 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") window = np.abs(q) ** 2 window /= np.linalg.norm(window) alternating = (-1.0) ** n f_plus = window * (1.0 + 0.5 * alternating) / np.sqrt(1.25) f_minus = window * (1.0 - 0.5 * alternating) / np.sqrt(1.25) measurements = { "window_minimum": float(np.min(window)), "window_l2_norm": float(np.linalg.norm(window)), "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), } inner = np.vdot(f_minus, f_plus) alpha = inner / abs(inner) if abs(inner) else 1.0 + 0.0j measurements["signal_quotient_distance"] = float(np.linalg.norm(f_plus - alpha * f_minus)) for name, value in measurements.items(): assert_close(name, value, float(recorded["values"][name]), tolerance) if not (np.all(window > 0) and np.all(f_plus > 0) and np.all(f_minus > 0)): raise ValueError("The finite example must remain strictly positive at every sample.") checks = [] for name, passed in recorded["checks"].items(): if not isinstance(passed, bool): raise TypeError(f"Check {name!r} must be a Boolean.") checks.append({ "name": name, "passed": passed, "check_scope": recorded["scope"], "tolerance": tolerance, "source": f"verification.json#/checks/{name}", }) samples = [ { "cyclic_index": int(index), "window": float(window[index]), "f_plus": float(f_plus[index]), "f_minus": float(f_minus[index]), } for index in range(n_samples) ] perturbations = [dict(row) for row in recorded["perturbations"]] bridge_measurements = [] for row in recorded["bridge_measurements"]: edge_i, edge_j = row["edge"] bridge_measurements.append({ "edge_i": int(edge_i), "edge_j": int(edge_j), **{key: value for key, value in row.items() if key != "edge"}, }) exports = { "verification_checks": checks, "signal_samples": samples, "perturbations": perturbations, "bridge_measurements": bridge_measurements, } for name, records in exports.items(): if not records: raise ValueError(f"Empty export: {name}") keys = set(records[0]) field_types = {key: type(value) for key, value in records[0].items()} for row in records: if set(row) != keys: raise ValueError(f"Inconsistent fields in {name}") for key, value in row.items(): if type(value) not in (bool, int, float, str): raise TypeError(f"{name}.{key} is not a primitive JSON field.") if type(value) is not field_types[key]: raise TypeError(f"Inconsistent field types in {name}.{key}") write_jsonl(destination / f"{name}.jsonl", records) return {name: len(records) for name, records in exports.items()} def main() -> None: root = Path(__file__).resolve().parent.parent parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--output-dir", type=Path, help="Write JSONL exports here instead of the repository's data directory.", ) args = parser.parse_args() destination = args.output_dir.resolve() if args.output_dir else root / "data" counts = build(root, destination) print(json.dumps({"output_directory": str(destination), "row_counts": counts}, indent=2)) if __name__ == "__main__": main()