File size: 3,250 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
#!/usr/bin/env python3
"""Does agreement between n0 and the fitted midpoint depend on fixed service times?

Additive reference condition with type-specific service times that share the
published MEANS but differ in variance: fixed (as published), exponential
(coefficient of variation 1), and lognormal with coefficient of variation 2.
The mean-based balance index n0 is identical across rows; a median-based index
is shown only to illustrate why the median is the wrong estimand for offered
load. Synthetic constructions only.
"""
from __future__ import annotations
import json, math
from pathlib import Path
import numpy as np
import capacity_simulation as S

SESSIONS = 500
DISTS = {"fixed": 0.0, "exponential": 1.0, "lognormal_cv2": 2.0}


def draw_cost(rng, mean, dist):
    if dist == "fixed":
        return mean
    if dist == "exponential":
        return float(rng.exponential(mean))
    cv = DISTS[dist]; s2 = math.log(1 + cv * cv)
    return float(rng.lognormal(math.log(mean) - s2 / 2, math.sqrt(s2)))


def session(rng, n, dist):
    events = []
    for minute in range(S.DURATION_MIN):
        for agent in range(n):
            for _ in range(rng.poisson(S.LAMBDA)):
                k = int(rng.choice(3, p=S.TYPE_PROBS))
                events.append((minute + rng.random(), agent, k, draw_cost(rng, S.TYPE_COSTS[k], dist)))
    if not events:
        return np.nan
    events.sort(key=lambda e: e[0])
    available, correct = 0.0, 0
    for arrival, _, k, cost in events:
        completion = max(arrival, available) + cost / S.BUDGET
        ok = completion - arrival <= S.TYPE_DEADLINES[k]
        correct += int(rng.random() < (0.95 if ok else 0.15))
        available = completion
    return correct / len(events)


def median_factor(dist):
    if dist == "fixed": return 1.0
    if dist == "exponential": return math.log(2)
    return 1 / math.sqrt(1 + DISTS[dist] ** 2)      # lognormal median / mean


def main():
    n0 = S.BUDGET / (S.LAMBDA * float(S.TYPE_PROBS @ S.TYPE_COSTS))
    out = {"n0_mean_based": n0}
    for i, dist in enumerate(DISTS):
        rng = np.random.default_rng(S.SEED + 100 + i)
        values, means = {}, []
        for n in S.TEAM_SIZES.astype(int):
            sc = np.array([session(rng, n, dist) for _ in range(SESSIONS)]); sc = sc[np.isfinite(sc)]
            values[n] = sc; means.append(float(sc.mean()))
        theta = S.fit_curve(S.TEAM_SIZES, np.array(means))
        lo, hi = S.bootstrap_midpoint(rng, values)
        out[dist] = {"cv": DISTS[dist], "midpoint": float(theta[2]), "midpoint_ci": [float(lo), float(hi)],
                     "tau": float(theta[3]), "gap_to_n0": float(theta[2] - n0),
                     "n0_if_median_used": n0 / median_factor(dist)}
    Path("service_variance.json").write_text(json.dumps(out, indent=2) + "\n")
    print(f"mean-based n0 = {n0:.2f} in every row")
    print(f"{'service times':15}{'CV':>5}{'fitted n_mid':>22}{'tau':>7}{'gap':>8}{'n0 from median':>16}")
    for d in DISTS:
        r = out[d]
        print(f"{d:15}{r['cv']:>5.0f}{r['midpoint']:>9.2f} [{r['midpoint_ci'][0]:.2f},{r['midpoint_ci'][1]:.2f}]"
              f"{r['tau']:>7.2f}{r['gap_to_n0']:>+8.2f}{r['n0_if_median_used']:>16.2f}")


if __name__ == "__main__":
    main()