EVE-AEQIRION / research /code /make_figures.py
PureOne's picture
Release AËQIRION v3.0: manuscript, proofs, code and verification data
8e19377 verified
Raw History Blame Contribute Delete
12.2 kB
#!/usr/bin/env python3
"""Reproduce the finite-model scientific figures for AEQIRION.
Requires NumPy, SciPy, and Matplotlib. These are mathematical model plots,
not image experiments or physical measurements. Source data and numerical
validation are saved in results/figure_data.json.
"""
from __future__ import annotations
from itertools import product
from datetime import datetime, timezone
import json
from math import comb, sqrt
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.colors import BoundaryNorm, ListedColormap
from matplotlib.patches import Patch, Rectangle
from matplotlib.ticker import MaxNLocator
import numpy as np
from scipy.optimize import brentq
ROOT = Path(__file__).resolve().parents[1]
FIGURES = ROOT / "figures"
RESULTS = ROOT / "results"
def configure_style():
plt.rcParams.update({
"font.family": "DejaVu Sans",
"font.size": 10,
"axes.titlesize": 13,
"axes.titleweight": "semibold",
"axes.labelsize": 10,
"axes.edgecolor": "#73808b",
"axes.labelcolor": "#203344",
"xtick.color": "#415565",
"ytick.color": "#415565",
"text.color": "#203344",
"grid.color": "#dbe2e8",
"grid.linewidth": 0.7,
"axes.spines.top": False,
"axes.spines.right": False,
"legend.frameon": False,
"savefig.facecolor": "white",
"figure.facecolor": "white",
"pdf.fonttype": 42,
"ps.fonttype": 42,
})
def save_figure(fig, name):
for suffix in ("pdf", "png"):
fig.savefig(FIGURES / f"{name}.{suffix}", dpi=200,
bbox_inches="tight", pad_inches=0.08,
metadata={"Creator": "AEQIRION reproducible model figures",
"CreationDate": datetime(2026, 10, 20, tzinfo=timezone.utc),
"ModDate": datetime(2026, 10, 20, tzinfo=timezone.utc)}
if suffix == "pdf" else None)
plt.close(fig)
def optimal_one_nonnegative(n):
# Rationalized form avoids cancellation in the displayed closed formula.
return 2.0 * n / (2.0 * n + 1.0 + sqrt(4.0 * n * n + 1.0))
def local_point_eigenvalue(n):
"""Smallest eigenvalue of H0 + e_v e_v^T by its secular equation.
H0 is the unscaled binary edge-sum Gram matrix. Its eigenvalue 2k
has multiplicity binom(n,k), and e_v has squared projection
binom(n,k)/2^n on that eigenspace.
"""
weights = np.array([comb(n, k) / (2 ** n) for k in range(n + 1)])
eigenvalues = np.arange(n + 1, dtype=float) * 2.0
def secular(x):
return 1.0 + float(np.sum(weights / (eigenvalues - x)))
answer = brentq(secular, 1e-18, 2.0 - 1e-12,
xtol=1e-20, rtol=1e-14)
assert 0.0 < answer < 2.0
assert answer <= 1.0 / (2 ** n) + 1e-13
assert abs(secular(answer)) < 2e-12
return answer
def direct_cube_gram(n):
size = 2 ** n
out = n * np.eye(size)
for x in range(size):
for bit in range(n):
out[x, x ^ (1 << bit)] = 1.0
return out
def make_spectral_figure():
points = []
for n in range(1, 25):
points.append({
"n": n,
"vertices": 2 ** n,
"one_local_point_row": local_point_eigenvalue(n),
"one_optimal_nonnegative_row": optimal_one_nonnegative(n),
"two_parity_rows_total_energy_one": 0.5,
"one_signed_parity_row": 1.0,
})
validation = []
for n in range(1, 9):
size = 2 ** n
gram = direct_cube_gram(n)
point = np.zeros(size)
point[0] = 1.0
even = np.array([float(x.bit_count() % 2 == 0) for x in range(size)])
even /= np.linalg.norm(even)
local_numeric = float(np.linalg.eigvalsh(gram + np.outer(point, point))[0])
nonnegative_numeric = float(np.linalg.eigvalsh(gram + np.outer(even, even))[0])
local_error = abs(local_numeric - points[n - 1]["one_local_point_row"])
optimum_error = abs(nonnegative_numeric - optimal_one_nonnegative(n))
assert local_error < 2e-12
assert optimum_error < 2e-12
validation.append({"n": n, "direct_matrix_size": size,
"local_formula_absolute_error": local_error,
"optimal_formula_absolute_error": optimum_error})
fig, ax = plt.subplots(figsize=(7.1, 4.7))
fig.subplots_adjust(bottom=0.24, top=0.87)
n_values = [p["n"] for p in points]
ax.plot(n_values, [p["one_signed_parity_row"] for p in points],
color="#84919b", linestyle=":", linewidth=1.7,
label="One signed parity row")
ax.plot(n_values, [p["two_parity_rows_total_energy_one"] for p in points],
color="#5278b6", linestyle="--", linewidth=1.7,
label="Two nonnegative parity rows")
ax.plot(n_values, [p["one_optimal_nonnegative_row"] for p in points],
color="#008b86", linewidth=2.1, marker="o", markevery=3,
markersize=4.2, label="Best single nonnegative row")
ax.plot(n_values, [p["one_local_point_row"] for p in points],
color="#b84c69", linewidth=2.0, marker="s", markevery=3,
markersize=4.0, label="One local point row")
ax.set_yscale("log")
ax.set_xlabel("Number of binary coordinates, n")
ax.set_ylabel("Minimum eigenvalue of completed Gram matrix")
ax.set_title("Sensor design controls spectral stability", loc="left", pad=14)
ax.set_xlim(1, 24)
ax.set_xticks([1, 4, 8, 12, 16, 20, 24])
ax.set_ylim(2e-8, 1.8)
ax.grid(axis="y", which="major")
ax.legend(loc="lower left", fontsize=9.2)
fig.text(0.125, 0.015,
"Baseline: all unscaled cube edge sums. Added rows have total squared norm 1.\n"
"Synthetic finite-dimensional model; dense masks have an acquisition cost.",
fontsize=8.5, color="#596d7d", va="bottom")
save_figure(fig, "spectral_stability")
return {"model": "H0=A^T A for all unscaled binary edge sums",
"added_measurement_energy": 1,
"points": points,
"direct_matrix_validation": validation}
def make_channel_figure():
rows = []
for q in range(2, 13):
row = {"q": q, "separable_channels": q}
for n in (2, 3, 6):
size = q ** n
rank = size - (q - 1) ** n
row[f"arbitrary_channels_n{n}"] = (size + rank - 1) // rank
rows.append(row)
fig, ax = plt.subplots(figsize=(7.1, 4.6))
fig.subplots_adjust(bottom=0.24, top=0.87)
q_values = [row["q"] for row in rows]
ax.plot(q_values, q_values, color="#73818c", linestyle="--", linewidth=1.7,
label="Separable masks: all n")
for n, color, marker in ((2, "#b84c69", "s"), (3, "#008b86", "o"),
(6, "#5278b6", "^")):
ax.step(q_values, [row[f"arbitrary_channels_n{n}"] for row in rows],
where="mid", color=color, linewidth=1.8,
label=f"Arbitrary masks: n = {n}")
ax.scatter(q_values, [row[f"arbitrary_channels_n{n}"] for row in rows],
color=color, marker=marker, s=24, zorder=3)
ax.set_xlabel("Common alphabet size, q")
ax.set_ylabel("Minimum number of complete channels")
ax.set_title("Coding lowers the exact channel threshold", loc="left", pad=14)
ax.set_xlim(1.7, 12.3)
ax.set_xticks(q_values)
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
ax.set_ylim(0.6, 12.7)
ax.grid(axis="y")
ax.legend(loc="upper left", fontsize=9.0)
fig.text(0.125, 0.015,
"Known positive diagonal masks; all coordinate-line sums in each channel.\n"
"Counts include the unmodulated baseline. No conditioning guarantee is implied.",
fontsize=8.5, color="#596d7d", va="bottom")
save_figure(fig, "channel_thresholds")
return {"formula_arbitrary": "ceil(q^n/[q^n-(q-1)^n])",
"formula_generic_separable": "q",
"counts_include_baseline": True, "points": rows}
def line_multisets(array):
signatures = []
shape = array.shape
for axis in range(array.ndim):
remaining = [i for i in range(array.ndim) if i != axis]
for values in product(*(range(shape[i]) for i in remaining)):
selector = [slice(None)] * array.ndim
for i, value in zip(remaining, values):
selector[i] = value
signatures.append(tuple(sorted(array[tuple(selector)].tolist())))
return signatures
def make_trade_figure():
f = np.zeros((3, 3, 3), dtype=int)
g = np.zeros_like(f)
for index in product(range(2), repeat=3):
f[index] = 2 if sum(index) % 2 == 0 else 5
g[index] = 5 if sum(index) % 2 == 0 else 2
assert int(np.sum(f != g)) == 8
assert line_multisets(f) == line_multisets(g)
assert len(line_multisets(f)) == 27
for tensor in (f, g):
assert int(np.sum(tensor == 2)) == int(np.sum(tensor == 5)) == 4
cmap = ListedColormap(["#e7edf2", "#8dcfca", "#b84c69"])
norm = BoundaryNorm([-0.5, 1, 3.5, 5.5], cmap.N)
fig, axes = plt.subplots(2, 3, figsize=(7.7, 5.15))
for row, (tensor, name) in enumerate(((f, "F"), (g, "G"))):
for k in range(3):
ax = axes[row, k]
slice_values = tensor[:, :, k]
ax.imshow(slice_values, cmap=cmap, norm=norm, interpolation="nearest")
for i, j in product(range(3), repeat=2):
value = int(slice_values[i, j])
ax.text(j, i, str(value), va="center", ha="center", fontsize=12,
fontweight="semibold", color="white" if value == 5 else "#203344")
ax.set_xticks([0, 1, 2])
ax.set_yticks([0, 1, 2])
ax.set_xticks(np.arange(-0.5, 3, 1), minor=True)
ax.set_yticks(np.arange(-0.5, 3, 1), minor=True)
ax.grid(which="minor", color="white", linewidth=1.6)
ax.tick_params(which="both", length=0)
ax.set_title(f"{name}, x₃ = {k}", fontsize=11, pad=6)
if k == 0:
ax.set_ylabel("x₁")
if row == 1:
ax.set_xlabel("x₂")
if k < 2:
ax.add_patch(Rectangle((-0.5, -0.5), 2, 2, fill=False,
edgecolor="#203344", linewidth=1.5))
for spine in ax.spines.values():
spine.set_visible(False)
fig.suptitle("A minimal eight-site ambiguity at every temperature", x=0.10,
ha="left", y=1.015, fontsize=13, fontweight="semibold")
legend = [Patch(facecolor="#e7edf2", label="Unchanged score 0"),
Patch(facecolor="#8dcfca", label="Score 2"),
Patch(facecolor="#b84c69", label="Score 5")]
fig.legend(handles=legend, loc="lower center", bbox_to_anchor=(0.5, -0.055),
ncol=3, fontsize=9)
fig.subplots_adjust(wspace=0.22, hspace=0.38)
save_figure(fig, "minimal_trade")
return {"shape": [3, 3, 3], "F": f.tolist(), "G": g.tolist(),
"changed_entries": 8, "equal_coordinate_line_multisets": True,
"coordinate_line_multisets_checked": 27,
"multiplicity_each_moved_score": 4,
"interpretation": "Score tensors with exact equal line multisets; hence equal soft projections at every positive temperature."}
def main():
FIGURES.mkdir(parents=True, exist_ok=True)
RESULTS.mkdir(parents=True, exist_ok=True)
configure_style()
report = {"status": "PASS", "scope": "Mathematical model figures, not empirical performance",
"spectral_stability": make_spectral_figure(),
"channel_thresholds": make_channel_figure(),
"minimal_trade": make_trade_figure()}
(RESULTS / "figure_data.json").write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps({"status": "PASS", "vector_figures": [
"figures/spectral_stability.pdf", "figures/channel_thresholds.pdf",
"figures/minimal_trade.pdf"],
"direct_spectral_validations": len(report["spectral_stability"]["direct_matrix_validation"]),
"trade_lines_checked": 27}, indent=2))
if __name__ == "__main__":
main()