File size: 10,108 Bytes
c383c28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
#!/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()