beforedone-paper / analysis /precision.py
RedinGhost's picture
Publish curated reproducibility artifact
598316f verified
Raw
History Blame Contribute Delete
24.6 kB
from __future__ import annotations
import argparse
import hashlib
import json
import math
import random
from collections import Counter
from functools import lru_cache
from pathlib import Path
from statistics import NormalDist, mean, stdev
from typing import Any, Mapping, Sequence
from artifact.contracts import ContractError, canonical_sha256, load_json
from artifact.schedule import load_tasks, validate_schedule
PRECISION_VERSION = "0.2.1-prepilot"
PRECISION_SEED = 2026072302
DEFAULT_BASELINES = (0.2, 0.4, 0.6)
DEFAULT_TASK_CORRELATIONS = (0.0, 0.3, 0.6)
DEFAULT_WITHIN_RUN_PHASE_INCREMENTS = (0.0, 0.2)
DEFAULT_EFFECTS = tuple(round(index * 0.05, 2) for index in range(13))
DEFAULT_PHASE_COUNTS = (1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2)
NORMAL = NormalDist()
def _stable_seed(seed: int, label: str) -> int:
digest = hashlib.sha256(f"{seed}:{label}".encode("utf-8")).digest()
return int.from_bytes(digest[:8], "big")
@lru_cache(maxsize=64)
def _normal_cutoff(probability: float) -> float:
return NORMAL.inv_cdf(probability)
def _quantile(values: Sequence[float], probability: float) -> float:
ordered = sorted(float(value) for value in values)
if not ordered:
raise ValueError("quantile requires values")
if len(ordered) == 1:
return ordered[0]
position = (len(ordered) - 1) * probability
lower = math.floor(position)
upper = math.ceil(position)
if lower == upper:
return ordered[lower]
fraction = position - lower
return ordered[lower] * (1.0 - fraction) + ordered[upper] * fraction
def _studentized_task_difference(differences: Sequence[float]) -> float:
if not differences:
return 0.0
center = mean(differences)
if len(differences) < 2:
return math.inf if center else 0.0
spread = stdev(differences)
if spread == 0:
return math.inf if center else 0.0
return center / (spread / math.sqrt(len(differences)))
def load_precision_design(root: Path) -> dict[str, Any]:
"""Derive task phase opportunities from validated frozen study inputs."""
artifact_root = root.resolve()
schedule_path = artifact_root / "data" / "schedule.json"
if not schedule_path.is_file():
raise ValueError(f"precision schedule is missing: {schedule_path}")
try:
tasks = load_tasks(artifact_root)
schedule = load_json(schedule_path)
validate_schedule(schedule, tasks)
except (ContractError, ValueError) as exc:
raise ValueError(f"precision design inputs are invalid: {exc}") from exc
mapping = [
{
"task_id": task["task_id"],
"scenario": task["scenario"],
"phase_count": 1 if task["scenario"] == "premature" else 2,
"task_manifest_sha256": task["_manifest_sha256"],
}
for task in sorted(
(
item
for item in tasks
if item["study_phase"] == "confirmatory"
),
key=lambda item: item["task_id"],
)
]
phase_shape = Counter(item["phase_count"] for item in mapping)
if len(mapping) != 12 or phase_shape != Counter({1: 4, 2: 8}):
raise ValueError(
"validated confirmatory tasks do not have the frozen 4x1 plus 8x2 phase shape"
)
return {
"source": "validated_confirmatory_task_manifests_and_schedule",
"schedule_sha256": schedule["schedule_sha256"],
"task_phase_design_sha256": canonical_sha256(mapping),
"tasks": mapping,
}
def validate_precision_report(
report: Mapping[str, Any],
design: Mapping[str, Any],
) -> None:
"""Reject a saved design report that no longer matches frozen study inputs."""
if set(report) != {"precision", "scenarios", "interpretation"}:
raise ValueError("precision report has missing or unknown top-level fields")
precision = report["precision"]
scenarios = report["scenarios"]
interpretation = report["interpretation"]
if (
not isinstance(precision, Mapping)
or not isinstance(scenarios, list)
or not isinstance(interpretation, Mapping)
):
raise ValueError("precision report has invalid container types")
if precision.get("version") != PRECISION_VERSION:
raise ValueError("precision report version is stale")
if precision.get("phase_design") != design:
raise ValueError(
"precision report phase design does not match current task manifests and schedule"
)
phase_counts = tuple(int(item["phase_count"]) for item in design["tasks"])
expected_counts = {
str(key): value
for key, value in sorted(Counter(phase_counts).items())
}
expected_denominators = [3 * phase_count for phase_count in phase_counts]
expected = {
"seed": PRECISION_SEED,
"clusters": len(phase_counts),
"repetitions_per_condition_per_cluster": 3,
"task_phase_counts": list(phase_counts),
"task_counts_by_phase_count": expected_counts,
"phase_opportunities_per_condition": 3 * sum(phase_counts),
"task_condition_denominators": expected_denominators,
"simulations_per_grid_point": 4_000,
"alpha_two_sided": 0.05,
"target_power": 0.80,
}
for key, value in expected.items():
if precision.get(key) != value:
raise ValueError(f"precision report {key} differs from the preregistered design")
expected_combinations = {
(baseline, task_correlation, phase_increment)
for baseline in DEFAULT_BASELINES
for task_correlation in DEFAULT_TASK_CORRELATIONS
for phase_increment in DEFAULT_WITHIN_RUN_PHASE_INCREMENTS
}
observed_combinations: set[tuple[float, float, float]] = set()
for scenario in scenarios:
if not isinstance(scenario, Mapping):
raise ValueError("precision report contains a non-object scenario")
combination = (
float(scenario.get("baseline_risk")),
float(scenario.get("task_latent_correlation")),
float(scenario.get("within_run_phase_increment")),
)
if combination in observed_combinations:
raise ValueError("precision report contains a duplicate scenario")
observed_combinations.add(combination)
curve = scenario.get("power_curve")
if not isinstance(curve, list):
raise ValueError("precision report scenario has no power curve")
observed_effects = [
float(point.get("absolute_risk_reduction"))
for point in curve
if isinstance(point, Mapping)
]
expected_effects = [
float(effect)
for effect in DEFAULT_EFFECTS
if effect <= combination[0]
]
if len(observed_effects) != len(curve) or observed_effects != expected_effects:
raise ValueError("precision report power grid differs from the preregistered design")
if observed_combinations != expected_combinations:
raise ValueError("precision report scenario grid differs from the preregistered design")
def validate_saved_precision_inputs(
root: Path,
output: Path | None = None,
) -> dict[str, Any]:
"""Cheap lock-time validation of saved precision provenance and design."""
artifact_root = root.resolve()
path = output or (artifact_root / "analysis" / "precision.json")
resolved = path.resolve() if path.is_absolute() else (artifact_root / path).resolve()
try:
report = load_json(resolved)
except ContractError as exc:
raise ValueError(f"saved precision report is invalid: {exc}") from exc
design = load_precision_design(artifact_root)
validate_precision_report(report, design)
return report
def _validate_phase_design(
phase_counts: Sequence[int],
phase_design: Mapping[str, Any] | None,
) -> tuple[tuple[int, ...], dict[str, Any]]:
task_phase_counts = tuple(int(value) for value in phase_counts)
if phase_design is None:
mapping = [
{
"task_id": f"task-{index:02d}",
"phase_count": phase_count,
}
for index, phase_count in enumerate(task_phase_counts, 1)
]
return task_phase_counts, {
"source": "explicit_phase_counts_for_diagnostics",
"schedule_sha256": None,
"task_phase_design_sha256": canonical_sha256(mapping),
"tasks": mapping,
}
if set(phase_design) != {
"source",
"schedule_sha256",
"task_phase_design_sha256",
"tasks",
}:
raise ValueError("precision phase design has missing or unknown fields")
tasks = phase_design["tasks"]
if not isinstance(tasks, list) or not tasks:
raise ValueError("precision phase design tasks must be a non-empty list")
derived = tuple(int(item["phase_count"]) for item in tasks)
if task_phase_counts != derived:
raise ValueError(
"explicit phase counts contradict the validated task phase design"
)
if canonical_sha256(tasks) != phase_design["task_phase_design_sha256"]:
raise ValueError("precision task phase design digest does not match")
return derived, dict(phase_design)
def _one_dataset(
rng: random.Random,
*,
phase_counts: Sequence[int],
repetitions: int,
baseline_risk: float,
absolute_reduction: float,
task_latent_correlation: float,
within_run_phase_increment: float,
) -> tuple[list[float], float]:
treatment_risk = max(0.0, baseline_risk - absolute_reduction)
control_cutoff = _normal_cutoff(baseline_risk)
treatment_cutoff = (
-math.inf if treatment_risk == 0 else _normal_cutoff(treatment_risk)
)
task_weight = math.sqrt(task_latent_correlation)
run_weight = math.sqrt(within_run_phase_increment)
residual_weights = {
phase_count: math.sqrt(
1.0
- task_latent_correlation
- (within_run_phase_increment if phase_count > 1 else 0.0)
)
for phase_count in set(phase_counts)
}
gaussian = rng.gauss
differences: list[float] = []
for phase_count in phase_counts:
task_factor = gaussian(0.0, 1.0) if task_weight else 0.0
control_events = 0
treatment_events = 0
for _ in range(repetitions):
active_run_weight = run_weight if phase_count > 1 else 0.0
residual_weight = residual_weights[phase_count]
control_run_factor = (
gaussian(0.0, 1.0) if active_run_weight else 0.0
)
treatment_run_factor = (
gaussian(0.0, 1.0) if active_run_weight else 0.0
)
for _ in range(phase_count):
control_latent = (
task_weight * task_factor
+ active_run_weight * control_run_factor
+ residual_weight * gaussian(0.0, 1.0)
)
treatment_latent = (
task_weight * task_factor
+ active_run_weight * treatment_run_factor
+ residual_weight * gaussian(0.0, 1.0)
)
control_events += control_latent <= control_cutoff
treatment_events += treatment_latent <= treatment_cutoff
opportunities = repetitions * phase_count
differences.append(
treatment_events / opportunities - control_events / opportunities
)
return differences, treatment_risk
def simulate_precision(
*,
phase_counts: Sequence[int] = DEFAULT_PHASE_COUNTS,
phase_design: Mapping[str, Any] | None = None,
repetitions: int = 3,
baselines: Sequence[float] = DEFAULT_BASELINES,
task_correlations: Sequence[float] = DEFAULT_TASK_CORRELATIONS,
within_run_phase_increments: Sequence[float] = DEFAULT_WITHIN_RUN_PHASE_INCREMENTS,
effects: Sequence[float] = DEFAULT_EFFECTS,
simulations: int = 4_000,
alpha: float = 0.05,
target_power: float = 0.80,
seed: int = PRECISION_SEED,
) -> dict[str, Any]:
"""Estimate design precision under an explicit clustered latent-normal model.
The empirical null critical value avoids pretending that twelve discrete
task differences follow a large-sample normal distribution. The simulation
remains an assumption-dependent design diagnostic, not a promise of power.
"""
task_phase_counts, design_provenance = _validate_phase_design(
phase_counts,
phase_design,
)
if len(task_phase_counts) < 2 or any(
value not in {1, 2} for value in task_phase_counts
):
raise ValueError(
"precision simulation requires at least two tasks with phase count one or two"
)
if repetitions < 1 or simulations < 100:
raise ValueError(
"precision simulation requires >=1 repetition and >=100 simulations"
)
if not 0 < alpha < 1 or not 0 < target_power < 1:
raise ValueError("alpha and target_power must be between zero and one")
if any(not 0 < value < 1 for value in baselines):
raise ValueError("baseline risks must be strictly between zero and one")
if any(not 0 <= value < 1 for value in task_correlations):
raise ValueError("task latent correlations must be in [0, 1)")
if any(not 0 <= value < 1 for value in within_run_phase_increments):
raise ValueError("within-run phase increments must be in [0, 1)")
if any(
task_correlation + phase_increment >= 1
for task_correlation in task_correlations
for phase_increment in within_run_phase_increments
):
raise ValueError(
"task correlation plus within-run phase increment must be below one"
)
if any(value < 0 for value in effects):
raise ValueError("effect sizes must be non-negative")
scenarios: list[dict[str, Any]] = []
for baseline in baselines:
for task_correlation in task_correlations:
for phase_increment in within_run_phase_increments:
label = (
f"p={baseline:.6f}:task={task_correlation:.6f}:"
f"phase_increment={phase_increment:.6f}:"
f"shape={','.join(str(value) for value in task_phase_counts)}"
)
null_rng = random.Random(_stable_seed(seed, label + ":null"))
null_statistics: list[float] = []
for _ in range(simulations):
differences, _ = _one_dataset(
null_rng,
phase_counts=task_phase_counts,
repetitions=repetitions,
baseline_risk=baseline,
absolute_reduction=0.0,
task_latent_correlation=task_correlation,
within_run_phase_increment=phase_increment,
)
null_statistics.append(
abs(_studentized_task_difference(differences))
)
critical = _quantile(null_statistics, 1.0 - alpha)
powers: list[dict[str, Any]] = []
for effect in sorted(
set(float(value) for value in effects if value <= baseline)
):
effect_rng = random.Random(
_stable_seed(seed, label + f":effect={effect:.6f}")
)
rejected = 0
observed_differences: list[float] = []
for _ in range(simulations):
differences, treatment_risk = _one_dataset(
effect_rng,
phase_counts=task_phase_counts,
repetitions=repetitions,
baseline_risk=baseline,
absolute_reduction=effect,
task_latent_correlation=task_correlation,
within_run_phase_increment=phase_increment,
)
observed_differences.append(mean(differences))
rejected += (
abs(_studentized_task_difference(differences))
> critical
)
powers.append(
{
"absolute_risk_reduction": effect,
"treatment_risk": treatment_risk,
"estimated_power": rejected / simulations,
"mean_observed_risk_difference": mean(
observed_differences
),
}
)
detectable = next(
(
item["absolute_risk_reduction"]
for item in powers
if item["absolute_risk_reduction"] > 0
and item["estimated_power"] >= target_power
),
None,
)
scenarios.append(
{
"baseline_risk": baseline,
"task_latent_correlation": task_correlation,
"within_run_phase_increment": phase_increment,
"same_run_phase_latent_correlation": (
task_correlation + phase_increment
),
"empirical_two_sided_critical_value": critical,
"minimum_grid_effect_at_target_power": detectable,
"power_curve": powers,
}
)
return {
"precision": {
"version": PRECISION_VERSION,
"seed": seed,
"clusters": len(task_phase_counts),
"repetitions_per_condition_per_cluster": repetitions,
"task_phase_counts": list(task_phase_counts),
"phase_design": design_provenance,
"task_counts_by_phase_count": {
str(key): value
for key, value in sorted(Counter(task_phase_counts).items())
},
"phase_opportunities_per_condition": repetitions
* sum(task_phase_counts),
"task_condition_denominators": [
repetitions * phase_count for phase_count in task_phase_counts
],
"simulations_per_grid_point": simulations,
"alpha_two_sided": alpha,
"target_power": target_power,
"estimand": "risk(beforedone) - risk(prompt_only)",
"model": (
"latent-normal phase-opportunity Bernoulli outcomes with a shared "
"task factor, condition-and-repetition-specific run factors for "
"two-stage tasks, and phase residuals"
),
"test": (
"pool phase opportunities within each task-condition, form twelve "
"paired task risk differences, and compare their absolute "
"studentized mean with a scenario-specific empirical null critical value"
),
},
"scenarios": scenarios,
"interpretation": {
"grid_definition": (
"The reported MDE is the first tested absolute risk-reduction grid "
"point reaching target power; it is not an exact continuous threshold."
),
"small_sample_warning": (
"Twelve task clusters provide limited precision. Wide intervals or "
"non-significant findings are not evidence of equivalence."
),
"scope_warning": (
"Power depends on the simulated baseline phase-opportunity risk, "
"latent task correlation, additional within-run phase correlation, "
"and paired-outcome model; it does not generalize beyond the frozen "
"benchmark suite."
),
"correlation_warning": (
"The correlation parameters are Gaussian latent-factor variance "
"components, not Bernoulli Pearson correlations. Same-run phase "
"latent correlation equals task correlation plus the reported "
"within-run increment."
),
"repository_dependence_warning": (
"The twelve task clusters come from only three repositories, with "
"four tasks per repository. This simulation has no additional "
"repository-level factor, so unmodeled within-repository dependence "
"can overstate precision; it does not support repository-population "
"inference."
),
},
}
def write_precision(report: dict[str, Any], output: Path) -> None:
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(
json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
encoding="utf-8",
newline="\n",
)
def _csv_floats(value: str) -> tuple[float, ...]:
return tuple(float(item.strip()) for item in value.split(",") if item.strip())
def _parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Simulate BeforeDone study precision")
parser.add_argument("--root", type=Path, default=Path.cwd())
parser.add_argument(
"--output",
type=Path,
default=Path("analysis/precision.json"),
)
parser.add_argument("--repetitions", type=int, default=3)
parser.add_argument("--baselines", type=_csv_floats, default=DEFAULT_BASELINES)
parser.add_argument(
"--task-correlations",
type=_csv_floats,
default=DEFAULT_TASK_CORRELATIONS,
)
parser.add_argument(
"--within-run-phase-increments",
type=_csv_floats,
default=DEFAULT_WITHIN_RUN_PHASE_INCREMENTS,
)
parser.add_argument("--effects", type=_csv_floats, default=DEFAULT_EFFECTS)
parser.add_argument("--simulations", type=int, default=4_000)
parser.add_argument("--alpha", type=float, default=0.05)
parser.add_argument("--target-power", type=float, default=0.80)
parser.add_argument("--seed", type=int, default=PRECISION_SEED)
parser.add_argument(
"--verify",
action="store_true",
help="recompute and require byte-identical output instead of writing it",
)
return parser
def main(argv: Sequence[str] | None = None) -> int:
args = _parser().parse_args(argv)
root = args.root.resolve()
try:
design = load_precision_design(root)
phase_counts = tuple(item["phase_count"] for item in design["tasks"])
report = simulate_precision(
phase_counts=phase_counts,
phase_design=design,
repetitions=args.repetitions,
baselines=args.baselines,
task_correlations=args.task_correlations,
within_run_phase_increments=args.within_run_phase_increments,
effects=args.effects,
simulations=args.simulations,
alpha=args.alpha,
target_power=args.target_power,
seed=args.seed,
)
except ValueError as exc:
print(f"precision simulation failed: {exc}")
return 1
output = (
args.output.resolve()
if args.output.is_absolute()
else (root / args.output).resolve()
)
if args.verify:
if not output.is_file():
print(f"precision verification failed: output is missing: {output}")
return 1
expected = json.dumps(
report,
ensure_ascii=False,
indent=2,
sort_keys=True,
) + "\n"
try:
observed = output.read_text(encoding="utf-8")
except (OSError, UnicodeError) as exc:
print(f"precision verification failed: cannot read output: {exc}")
return 1
if observed != expected:
print(
"precision verification failed: saved report is not the "
"deterministic result for current inputs"
)
return 1
print(f"verified {output}")
return 0
write_precision(report, output)
print(f"wrote {output}")
return 0
if __name__ == "__main__":
raise SystemExit(main())