Download code/capacity_simulation.py from ai4he/supervisory-capacity-model: direct link, hf CLI and curl.
- Browser
- Download file 10.1 kB
-
https://huggingface.co/datasets/ai4he/supervisory-capacity-model/resolve/main/code/capacity_simulation.py
- Command line
-
hf download hf://datasets/ai4he/supervisory-capacity-model/code/capacity_simulation.py
-
curl -L -o capacity_simulation.py https://huggingface.co/datasets/ai4he/supervisory-capacity-model/resolve/main/code/capacity_simulation.py
10.1 kB
| #!/usr/bin/env python3 | |
| """Synthetic reference study for the Supervisory Capacity Model. | |
| This is not evidence about people or deployed LLMs. It separates an exact | |
| logistic-model recovery control from a queue-model mismatch test and detects | |
| violations caused by correlated arrivals, batching, and switching costs. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| from scipy.optimize import least_squares | |
| SEED = 20260828 | |
| TEAM_SIZES = np.array([1, 2, 3, 4, 5, 6, 8, 10], dtype=float) | |
| SESSIONS_PER_SIZE = 500 | |
| DURATION_MIN = 30 | |
| LAMBDA = 0.25 | |
| BUDGET = 1.0 | |
| TYPE_NAMES = ("perception", "comprehension", "projection") | |
| TYPE_PROBS = np.array([0.50, 0.30, 0.20]) | |
| TYPE_COSTS = np.array([0.60, 1.00, 1.60]) | |
| TYPE_DEADLINES = np.array([2.0, 3.0, 4.0]) | |
| CONDITIONS = ("additive", "correlated", "batched", "switching") | |
| def logistic(n: np.ndarray, floor: float, span: float, midpoint: float, tau: float) -> np.ndarray: | |
| z = np.clip((n - midpoint) / tau, -40.0, 40.0) | |
| return floor + span / (1.0 + np.exp(z)) | |
| def fit_curve(x: np.ndarray, y: np.ndarray) -> np.ndarray: | |
| def residual(theta: np.ndarray) -> np.ndarray: | |
| return logistic(x, *theta) - y | |
| initial = np.array([0.12, 0.82, 4.0, 1.0]) | |
| lower = np.array([0.0, 0.05, 0.25, 0.10]) | |
| upper = np.array([0.60, 1.00, 15.0, 8.0]) | |
| return least_squares(residual, initial, bounds=(lower, upper)).x | |
| def minute_arrivals(rng: np.random.Generator, n_agents: int, condition: str, | |
| minute: int, event_rate: float = LAMBDA, | |
| cost_scale: float = 1.0): | |
| events: list[list[float | int]] = [] | |
| independent_rate = 0.68 * event_rate if condition == "correlated" else event_rate | |
| for agent in range(n_agents): | |
| for _ in range(rng.poisson(independent_rate)): | |
| kind = int(rng.choice(len(TYPE_NAMES), p=TYPE_PROBS)) | |
| events.append([ | |
| minute + rng.random(), agent, kind, | |
| float(TYPE_COSTS[kind] * cost_scale), | |
| ]) | |
| if condition == "correlated": | |
| for _ in range(rng.poisson(event_rate - independent_rate)): | |
| kind = int(rng.choice(len(TYPE_NAMES), p=TYPE_PROBS)) | |
| when = minute + rng.random() | |
| for agent in range(n_agents): | |
| events.append([ | |
| when, agent, kind, float(TYPE_COSTS[kind] * cost_scale), | |
| ]) | |
| if condition == "batched" and events: | |
| by_kind: dict[int, list[int]] = {} | |
| for index, event in enumerate(events): | |
| by_kind.setdefault(int(event[2]), []).append(index) | |
| for kind, indices in by_kind.items(): | |
| if len(indices) > 1: | |
| total = (TYPE_COSTS[kind] * cost_scale | |
| * (1.0 + 0.25 * (len(indices) - 1))) | |
| per_event = float(total / len(indices)) | |
| for index in indices: | |
| events[index][3] = per_event | |
| return events | |
| def simulate_session(rng: np.random.Generator, n_agents: int, condition: str, | |
| event_rate: float = LAMBDA, budget: float = BUDGET, | |
| cost_scale: float = 1.0, | |
| deadline_scale: float = 1.0) -> float: | |
| events: list[list[float | int]] = [] | |
| for minute in range(DURATION_MIN): | |
| events.extend(minute_arrivals( | |
| rng, n_agents, condition, minute, event_rate, cost_scale | |
| )) | |
| events.sort(key=lambda event: (float(event[0]), rng.random())) | |
| if not events: | |
| return np.nan | |
| available = 0.0 | |
| previous_agent = None | |
| correct = 0 | |
| for arrival, agent, kind, cost in events: | |
| switch = 0.35 if condition == "switching" and previous_agent not in (None, agent) else 0.0 | |
| start = max(float(arrival), available) | |
| completion = start + (float(cost) + switch) / budget | |
| recovered = (completion - float(arrival) | |
| <= TYPE_DEADLINES[int(kind)] * deadline_scale) | |
| p_correct = 0.95 if recovered else 0.15 | |
| correct += int(rng.random() < p_correct) | |
| available = completion | |
| previous_agent = agent | |
| return correct / len(events) | |
| def bootstrap_midpoint( | |
| rng: np.random.Generator, values: dict[int, np.ndarray], repetitions: int = 400 | |
| ) -> tuple[float, float]: | |
| estimates = [] | |
| for _ in range(repetitions): | |
| means = np.array( | |
| [rng.choice(values[int(n)], size=len(values[int(n)]), replace=True).mean() for n in TEAM_SIZES] | |
| ) | |
| estimates.append(float(fit_curve(TEAM_SIZES, means)[2])) | |
| return tuple(np.quantile(estimates, [0.025, 0.975])) | |
| def direct_logistic_control(rng: np.random.Generator) -> dict[str, object]: | |
| """Generate scores from the fitted model itself as a code recovery check.""" | |
| truth = np.array([0.15, 0.80, 4.35, 0.90]) | |
| values: dict[int, np.ndarray] = {} | |
| means = [] | |
| for n in TEAM_SIZES.astype(int): | |
| probability = float(logistic(np.array([n]), *truth)[0]) | |
| scores = rng.binomial(1, probability, size=SESSIONS_PER_SIZE).astype(float) | |
| values[n] = scores | |
| means.append(float(scores.mean())) | |
| theta = fit_curve(TEAM_SIZES, np.array(means)) | |
| interval = bootstrap_midpoint(rng, values) | |
| return { | |
| "true_floor": float(truth[0]), | |
| "true_span": float(truth[1]), | |
| "true_midpoint": float(truth[2]), | |
| "true_tau": float(truth[3]), | |
| "fitted_floor": float(theta[0]), | |
| "fitted_span": float(theta[1]), | |
| "fitted_midpoint": float(theta[2]), | |
| "fitted_tau": float(theta[3]), | |
| "midpoint_ci": list(map(float, interval)), | |
| "means": means, | |
| } | |
| def sensitivity_battery(rng: np.random.Generator) -> list[dict[str, float | str]]: | |
| """One-factor-at-a-time queue sensitivity; descriptive, not inferential.""" | |
| settings = [("baseline", 1.0)] | |
| for factor in ("event_rate", "budget", "cost_scale", "deadline_scale"): | |
| settings.extend([(factor, 0.8), (factor, 1.2)]) | |
| records = [] | |
| for factor, multiplier in settings: | |
| values = { | |
| "event_rate": LAMBDA, | |
| "budget": BUDGET, | |
| "cost_scale": 1.0, | |
| "deadline_scale": 1.0, | |
| } | |
| if factor != "baseline": | |
| values[factor] *= multiplier | |
| means = [] | |
| for n in TEAM_SIZES.astype(int): | |
| scores = np.array([ | |
| simulate_session(rng, n, "additive", **values) | |
| for _ in range(200) | |
| ]) | |
| means.append(float(scores[np.isfinite(scores)].mean())) | |
| fitted = float(fit_curve(TEAM_SIZES, np.array(means))[2]) | |
| predicted = float( | |
| values["budget"] | |
| / (values["event_rate"] * values["cost_scale"] | |
| * np.dot(TYPE_PROBS, TYPE_COSTS)) | |
| ) | |
| records.append({ | |
| "factor": factor, | |
| "multiplier": multiplier, | |
| "event_rate": values["event_rate"], | |
| "budget": values["budget"], | |
| "cost_scale": values["cost_scale"], | |
| "deadline_scale": values["deadline_scale"], | |
| "predicted_midpoint": predicted, | |
| "fitted_midpoint": fitted, | |
| "bias": fitted - predicted, | |
| }) | |
| return records | |
| def main() -> None: | |
| rng = np.random.default_rng(SEED) | |
| all_values: dict[str, dict[int, np.ndarray]] = {} | |
| results = {"direct_logistic_control": direct_logistic_control(rng)} | |
| for condition in CONDITIONS: | |
| condition_values = {} | |
| means = [] | |
| for n in TEAM_SIZES.astype(int): | |
| scores = np.array( | |
| [simulate_session(rng, n, condition) for _ in range(SESSIONS_PER_SIZE)] | |
| ) | |
| scores = scores[np.isfinite(scores)] | |
| condition_values[n] = scores | |
| means.append(float(scores.mean())) | |
| all_values[condition] = condition_values | |
| theta = fit_curve(TEAM_SIZES, np.array(means)) | |
| interval = bootstrap_midpoint(rng, condition_values) | |
| results[condition] = { | |
| "means": means, | |
| "floor": float(theta[0]), | |
| "span": float(theta[1]), | |
| "midpoint": float(theta[2]), | |
| "tau": float(theta[3]), | |
| "midpoint_ci": list(map(float, interval)), | |
| } | |
| predicted_midpoint = BUDGET / (LAMBDA * float(np.dot(TYPE_PROBS, TYPE_COSTS))) | |
| results["design"] = { | |
| "seed": SEED, | |
| "sessions_per_size": SESSIONS_PER_SIZE, | |
| "duration_minutes": DURATION_MIN, | |
| "lambda": LAMBDA, | |
| "mean_service_cost": float(np.dot(TYPE_PROBS, TYPE_COSTS)), | |
| "budget": BUDGET, | |
| "predicted_midpoint": predicted_midpoint, | |
| } | |
| results["sensitivity_battery"] = sensitivity_battery(rng) | |
| root = Path(__file__).resolve().parent | |
| (root / "simulation_summary.json").write_text(json.dumps(results, indent=2) + "\n") | |
| rows = ["n additive correlated batched switching"] | |
| for index, n in enumerate(TEAM_SIZES.astype(int)): | |
| rows.append( | |
| f"{n} " | |
| + " ".join(f"{results[c]['means'][index]:.4f}" for c in CONDITIONS) | |
| ) | |
| (root / "simulation_curves.dat").write_text("\n".join(rows) + "\n") | |
| table = [ | |
| r"\begin{tabular}{lccc}", | |
| r"\toprule", | |
| r"Condition & nominal $n_0$ & fitted $n_{\mathrm{mid}}$ (95\% bootstrap) & diagnostic \\", | |
| r"\midrule", | |
| ] | |
| diagnostics = { | |
| "additive": "reference", | |
| "correlated": "shared bursts", | |
| "batched": "joint service", | |
| "switching": "agent-switch cost", | |
| } | |
| for condition in CONDITIONS: | |
| record = results[condition] | |
| lo, hi = record["midpoint_ci"] | |
| pred = f"{predicted_midpoint:.2f}" if condition == "additive" else "4.35 (naive)" | |
| label = condition.capitalize() | |
| table.append( | |
| f"{label} & {pred} & {record['midpoint']:.2f} " | |
| f"[{lo:.2f}, {hi:.2f}] & {diagnostics[condition]} \\\\" | |
| ) | |
| table.extend([r"\bottomrule", r"\end{tabular}"]) | |
| (root / "simulation_table.tex").write_text("\n".join(table) + "\n") | |
| print(json.dumps(results, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |