#!/usr/bin/env python3 """Run E2 controlled spectral experiments and write auditable reports.""" from __future__ import annotations import argparse import csv import json import math import platform import subprocess import sys import zlib from collections import defaultdict from datetime import datetime, timezone from pathlib import Path from typing import Any import numpy as np import torch PROJECT_ROOT = Path(__file__).resolve().parents[1] if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) from gmnet.synthetic import SyntheticExperiment, load_synthetic_config from gmnet.synthetic.metrics import bootstrap_mean_ci IDENTITY_COLUMNS = ("protocol", "gate", "seed", "condition") METRIC_DEFINITIONS = { "harmonic_generation": "Fraction of output FFT power outside the exact input-tone bins.", "band_transfer": "Fraction of output FFT power outside the input tone support or radial band.", "fundamental_gain": "Output/input power ratio on the exact input-frequency support.", "alias_fraction": "Output power at wrapped harmonic bins attributable to orders above Nyquist.", "dc_fraction": "Fraction of output power at DC.", "frequency_response": "Output/input power gain inside a random field's source band.", "frequency_auc": "AUC of source-band gain normalized by the lowest-band gain.", "fundamental_fraction": "Fraction of output power retained at the input fundamental.", "phase_sensitivity": "Coefficient of variation across translations/phases at fixed amplitude.", "high_frequency_preference": "High-cue power divided by low-plus-high power at original cue bins.", "phase_cross_modulation": "Relative high-cue power change caused only by a pi low-cue phase flip.", "high_readout_phase_shift": "Absolute high-cue coefficient phase change after a pi low-cue flip.", "cue_preference_auc": "AUC of high-frequency preference over log2 low/high amplitude ratio.", } def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument("--config", default="configs/e2_synthetic/full.yaml") parser.add_argument("--output-dir", default=None) return parser.parse_args() def metric_columns(rows: list[dict[str, Any]]) -> list[str]: return sorted(set().union(*(row.keys() for row in rows)) - set(IDENTITY_COLUMNS)) def write_csv(path: Path, rows: list[dict[str, Any]], columns: list[str]) -> None: with path.open("w", newline="", encoding="utf-8") as handle: writer = csv.DictWriter(handle, fieldnames=columns, extrasaction="ignore") writer.writeheader() writer.writerows(rows) def summarize( rows: list[dict[str, Any]], metrics: list[str], config: dict[str, Any], *, by_condition: bool, ) -> list[dict[str, Any]]: keys = ["protocol", "gate"] + (["condition"] if by_condition else []) groups: dict[tuple[Any, ...], list[dict[str, Any]]] = defaultdict(list) for row in rows: groups[tuple(row[key] for key in keys)].append(row) result: list[dict[str, Any]] = [] statistics = config["statistics"] for group_key, group_rows in sorted(groups.items()): for metric in metrics: seed_values: dict[int, list[float]] = defaultdict(list) raw_count = 0 for row in group_rows: if metric not in row or not math.isfinite(float(row[metric])): continue seed_values[int(row["seed"])].append(float(row[metric])) raw_count += 1 # Fixed frequencies, amplitudes, and phases are experimental # conditions, not independent replicates. Macro-average them per # seed before bootstrapping to avoid pseudo-replication. values = [float(np.mean(items)) for items in seed_values.values() if items] if not values: continue stable_seed = int(statistics["bootstrap_seed"]) + zlib.crc32( repr((group_key, metric)).encode() ) mean, low, high, count = bootstrap_mean_ci( values, samples=int(statistics["bootstrap_samples"]), confidence=float(statistics["confidence"]), seed=stable_seed, ) item = dict(zip(keys, group_key, strict=True)) item.update( metric=metric, mean=mean, ci_low=low, ci_high=high, n=count, observations=raw_count, ) result.append(item) return result def lookup( summaries: list[dict[str, Any]], protocol: str, gate: str, metric: str ) -> dict[str, Any] | None: return next( ( row for row in summaries if row["protocol"] == protocol and row["gate"] == gate and row["metric"] == metric ), None, ) def format_estimate(item: dict[str, Any] | None) -> str: if item is None: return "NA" return f'{item["mean"]:.4f} [{item["ci_low"]:.4f}, {item["ci_high"]:.4f}]' def raw_mean( rows: list[dict[str, Any]], protocol: str, gate: str, metric: str, condition_fragment: str, ) -> float: values = [ float(row[metric]) for row in rows if row["protocol"] == protocol and row["gate"] == gate and condition_fragment in row["condition"] and metric in row and math.isfinite(float(row[metric])) ] return float(np.mean(values)) if values else math.nan def make_report( config: dict[str, Any], rows: list[dict[str, Any]], summaries: list[dict[str, Any]], metadata: dict[str, Any], ) -> str: gates = config["gates"] lines = [ "# E2 Controlled Spectral Mechanism Results", "", "This is an operator-level causal experiment. No classifier was trained, and no", "classification accuracy claim is made. Intervals are 95% percentile bootstrap", "confidence intervals over seed-level macro averages of the fixed conditions.", "", "## Run", "", f'- UTC: {metadata["finished_at_utc"]}', f'- Device: {metadata["device"]}', f'- Grid: {config["grid_size"]} x {config["grid_size"]}', f'- Seeds: {config["seeds"]}', f'- Raw observations: {len(rows)}', "", "## Main estimates", "", "All table cells are mean [95% CI].", "", "| Gate | Single-tone generated | Dual-tone generated | Random-field transfer | Frequency AUC | Alias power |", "|---|---:|---:|---:|---:|---:|", ] for gate in gates: values = [ lookup(summaries, "single_tone", gate, "harmonic_generation"), lookup(summaries, "dual_tone", gate, "harmonic_generation"), lookup(summaries, "random_field", gate, "band_transfer"), lookup(summaries, "frequency_auc", gate, "frequency_auc"), lookup(summaries, "single_tone", gate, "alias_fraction"), ] lines.append(f'| {gate} | ' + " | ".join(format_estimate(value) for value in values) + " |") amplitudes = [float(value) for value in config["single_tone"]["amplitudes"]] lines.extend( [ "", "## Controlled sweeps", "", "### Single-tone out-of-support power by amplitude", "", "| Gate | " + " | ".join(f"A={value:g}" for value in amplitudes) + " |", "|---|" + "---:|" * len(amplitudes), ] ) for gate in gates: values = [ raw_mean(rows, "single_tone", gate, "harmonic_generation", f"_a={amplitude:g}_") for amplitude in amplitudes ] lines.append(f'| {gate} | ' + " | ".join(f"{value:.4f}" for value in values) + " |") bands = [tuple(map(float, value)) for value in config["random_field"]["bands"]] lines.extend( [ "", "### Random-field out-of-band transfer by source band", "", "| Gate | " + " | ".join(f"{low:g}-{high:g}" for low, high in bands) + " |", "|---|" + "---:|" * len(bands), ] ) for gate in gates: values = [ raw_mean(rows, "random_field", gate, "band_transfer", f"band={low:g}-{high:g}") for low, high in bands ] lines.append(f'| {gate} | ' + " | ".join(f"{value:.4f}" for value in values) + " |") ratios = [float(value) for value in config["cue_conflict"]["low_to_high_ratios"]] lines.extend( [ "", "### Causal high-cue modulation by low/high amplitude ratio", "", "| Gate | " + " | ".join(f"{ratio:g}" for ratio in ratios) + " |", "|---|" + "---:|" * len(ratios), ] ) for gate in gates: values = [ raw_mean( rows, "cue_conflict", gate, "phase_cross_modulation", f"low_high={ratio:g}", ) for ratio in ratios ] lines.append( f'| {gate} | ' + " | ".join("NA" if math.isnan(value) else f"{value:.4f}" for value in values) + " |" ) lines.extend( [ "", "| Gate | Phase sensitivity | High-frequency cue AUC | Low-phase causal modulation |", "|---|---:|---:|---:|", ] ) for gate in gates: values = [ lookup(summaries, "phase_sensitivity", gate, "phase_sensitivity"), lookup(summaries, "cue_conflict_auc", gate, "cue_preference_auc"), lookup(summaries, "cue_conflict", gate, "phase_cross_modulation"), ] lines.append(f'| {gate} | ' + " | ".join(format_estimate(value) for value in values) + " |") no_gate_harmonic = lookup(summaries, "single_tone", "no_gate", "harmonic_generation") nonlinear = [] for gate in gates: item = lookup(summaries, "single_tone", gate, "harmonic_generation") if item and gate not in {"no_gate", "identity"}: nonlinear.append((float(item["mean"]), gate)) nonlinear.sort(reverse=True) cue_rank = [] for gate in gates: item = lookup(summaries, "cue_conflict", gate, "phase_cross_modulation") if item: cue_rank.append((float(item["mean"]), gate)) cue_rank.sort(reverse=True) relu6_high = raw_mean(rows, "single_tone", "relu6_self", "harmonic_generation", "_a=9_") relu_high = raw_mean(rows, "single_tone", "relu_self", "harmonic_generation", "_a=9_") smooth_high = raw_mean( rows, "single_tone", "smooth_clipped_self", "harmonic_generation", "_a=9_" ) lines.extend( [ "", "## Conclusions", "", f'1. The linear no_gate control generated {no_gate_harmonic["mean"]:.3e} mean out-of-support power, validating the FFT protocol against its zero-generation prediction.' if no_gate_harmonic else "1. The no_gate validation estimate was unavailable.", f"2. Among the composite gates, the largest average single-tone redistribution was produced by {nonlinear[0][1]} ({nonlinear[0][0]:.4f}). The x*x identity self-gate gives the analytic extreme of 1.0000 because it removes the original fundamental and creates DC plus the second harmonic." if nonlinear else "2. No nonlinear-gate estimate was available.", f"3. At amplitude 9, ReLU6 generated {relu6_high:.4f} out-of-support power versus {relu_high:.4f} for unclipped ReLU; smooth-clipped gave {smooth_high:.4f}. Thus the smooth static approximation tracks the clipping regime, while GELU's strongest difference occurs at small amplitude (see sweep).", f"4. In cue conflict, {cue_rank[0][1]} had the largest causal high-cue modulation under a low-cue phase flip ({cue_rank[0][0]:.4f}). A nonzero value demonstrates cross-frequency coupling introduced by the gate." if cue_rank else "4. No identifiable cue-conflict modulation estimate was available.", "5. Identity means the self-gate x*x, whereas no_gate is the pass-through control. For x*x, original cue bins disappear exactly in this cue setup; undefined cue-preference observations are excluded rather than converted to zeros.", "6. Phase sensitivity is numerically zero for every gate, as expected for a pointwise translation-equivariant operator on exact periodic tones. The nonzero cue result therefore comes from interaction between cues, not absolute signal translation.", "7. Frequency AUC near one means stationary band-limited fields receive comparable in-band gain across tested bands. It does not imply that the output remains in-band; band transfer reports that separately.", "", "## Metric definitions", "", ] ) lines.extend(f'- **{name}**: {definition}' for name, definition in METRIC_DEFINITIONS.items()) lines.extend( [ "", "## Scope", "", "These results identify mechanisms of the isolated static gate under exact sampled", "signals. They should be paired with trained-network E1/E3 measurements before making", "claims about ImageNet features, robustness, or accuracy.", "", ] ) return "\n".join(lines) def json_safe(value: Any) -> Any: if isinstance(value, float) and not math.isfinite(value): return None if isinstance(value, dict): return {key: json_safe(item) for key, item in value.items()} if isinstance(value, list): return [json_safe(item) for item in value] return value def main() -> None: args = parse_args() config_path = Path(args.config).resolve() config = load_synthetic_config(config_path) stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") output_dir = Path(args.output_dir or f"/tmp/gmnet_runs/e2_synthetic_{stamp}") output_dir.mkdir(parents=True, exist_ok=False) started = datetime.now(timezone.utc) experiment = SyntheticExperiment(config) rows = experiment.run() metrics = metric_columns(rows) summaries = summarize(rows, metrics, config, by_condition=False) condition_summaries = summarize(rows, metrics, config, by_condition=True) finished = datetime.now(timezone.utc) try: revision = subprocess.check_output( ["git", "rev-parse", "HEAD"], cwd=config_path.parents[2], text=True, stderr=subprocess.DEVNULL, ).strip() except (subprocess.CalledProcessError, FileNotFoundError): revision = "unknown" metadata = { "started_at_utc": started.isoformat(), "finished_at_utc": finished.isoformat(), "duration_seconds": (finished - started).total_seconds(), "device": str(experiment.device), "torch_version": torch.__version__, "python_version": platform.python_version(), "git_revision": revision, "config_path": str(config_path), } write_csv(output_dir / "raw_metrics.csv", rows, list(IDENTITY_COLUMNS) + metrics) write_csv( output_dir / "summary.csv", summaries, ["protocol", "gate", "metric", "mean", "ci_low", "ci_high", "n", "observations"], ) write_csv( output_dir / "summary_by_condition.csv", condition_summaries, ["protocol", "gate", "condition", "metric", "mean", "ci_low", "ci_high", "n", "observations"], ) payload = { "metadata": metadata, "config": config, "metric_definitions": METRIC_DEFINITIONS, "summaries": summaries, } (output_dir / "results.json").write_text( json.dumps(json_safe(payload), indent=2, sort_keys=True) + "\n", encoding="utf-8" ) report = make_report(config, rows, summaries, metadata) (output_dir / "CONCLUSIONS.md").write_text(report, encoding="utf-8") print(output_dir) if __name__ == "__main__": main()