MachineSex/figures/_figlib.py
Giorgio Gilestro a6eb9b7512 Layer 1 core: Wright-Fisher knowledge-transmission model with E1-E2
Scaffold plus the Layer 1 analytical core and the first two experiments.

- knowledge/: truth, metrics, teachers (2.7.1 shared-switch construction),
  step, lineage, experiment, config, seeding (imported as `knowledge`).
- Validation spine green: neutral decay (Pred 1), fixation (Pred 2), exact
  mutation-drift equilibrium (Pred 3), union coverage (Pred 5). 68 tests pass.
- E1 reproduces tail-first collapse. E2 delivers the headline: a grounding
  phase boundary g* << 1, with stationary H tracking the exact H_eq closed
  form (g=0.005 -> 68% of truth diversity; g=0.05 -> 96%).
- Reproducibility: uv venv from a hash-pinned uv.lock is the source of truth;
  every run writes results.parquet + resolved_config.yaml + manifest.json
  (lib versions, git commit, sha256). Figures and manifests tracked; the
  large regenerable parquet is gitignored.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 18:10:18 +02:00

40 lines
1.4 KiB
Python

"""Shared helpers for Layer-1 figure scripts.
Figures are a pure function of a committed results bundle (``results/EX/``:
``results.parquet`` + ``resolved_config.yaml``). No simulation is rerun here.
"""
from __future__ import annotations
from pathlib import Path
import numpy as np
import pandas as pd
import yaml
def load_bundle(results_dir: str | Path) -> tuple[pd.DataFrame, dict]:
"""Load a results bundle: (long-form DataFrame, source experiment config)."""
results_dir = Path(results_dir)
df = pd.read_parquet(results_dir / "results.parquet")
resolved = yaml.safe_load((results_dir / "resolved_config.yaml").read_text())
return df, resolved["source_config"]
def mean_ci(df: pd.DataFrame, by: str, value: str, ci: float = 0.95):
"""Return (index, mean, half-width) for a normal-approx CI of ``value`` grouped by ``by``."""
from scipy import stats
g = df.groupby(by)[value]
mean = g.mean()
sem = g.sem()
z = stats.norm.ppf(0.5 + ci / 2.0)
return mean.index.to_numpy(), mean.to_numpy(), (z * sem).to_numpy()
def savefig(fig, results_dir: str | Path, name: str) -> None:
"""Write a figure as both PNG (150 dpi) and PDF next to its results bundle."""
results_dir = Path(results_dir)
fig.savefig(results_dir / f"{name}.png", dpi=150, bbox_inches="tight")
fig.savefig(results_dir / f"{name}.pdf", bbox_inches="tight")
print(f"wrote {results_dir}/{name}.png and .pdf")