File size: 19,373 Bytes
4ef198a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
"""analyze.py --raw RAW_RUN_DIR [--raw2 REPLICATION_DIR] --out OUT_DIR
Reads ONLY the raw records of a T1 bench run (t1bench.sh output) and writes every table and figure of the report:
summary.json, tables.md, fig-*.svg. Definitions are the frozen pre-registration's (PREREGISTRATION.md section 3):

  valid rollout       labbench `useful`: every gate passed (clean-hash after reset, alive, isolation canary, setup, pre-check 0.0,
                      no guest fault, checker returned a score). Success or failure both count.
  operating N         the arm's pass-1 sustained rung with the most valid rollouts per hour (labbench sustained_active_n)
  max sustained N     the highest pass-1 rung that passed the sustain rule (>= 95 % valid, 0 contamination, MemAvailable >= 3 GiB,
                      step env p95 <= 2x rung 1)
  valid per USD       valid rollouts / (rung wall h x host USD/h) at the operating N (on-demand price primary, spot secondary)
  memory per desktop  (MemAvailable before the arm's first slot - median MemAvailable during the rung) / N   (host-level, every arm alike)
  reset p50 / p99     per-rollout reset_s (the arm's reset call, as the harness times it) at the operating N
  invalid rate        1 - valid / rollouts started, at the operating N (Wilson 95 % CI)
  USD per desktop-day 24 x host USD/h / max sustained N  (the unit OSGym reports)
CIs: paired bootstrap over tasks (10,000 resamples, seed 20261108, 95 % percentile) for ratios of valid per USD; bootstrap over
rollouts for reset percentiles; over 60-s blocks of host samples for memory; Wilson for rates."""
from __future__ import annotations
import argparse, glob, json, math, os, random, statistics

ARMS = ["drums-api", "qemu-tuned-shared", "firecracker", "firecracker-settled", "firecracker-pci", "firecracker-hp2m", "osgym-reimpl", "osworld-docker"]
NAMES = {"drums-api": "Drums (drumsd release)", "qemu-tuned-shared": "tuned KVM", "firecracker": "tuned Firecracker (R2-3, 20 s snapshot)",
         "firecracker-settled": "tuned Firecracker (R2-3, quiescent snapshot)", "firecracker-pci": "Firecracker --enable-pci (exploratory)", "firecracker-hp2m": "Firecracker 2M hugetlbfs + UFFD (exploratory)",
         "osgym-reimpl": "OSGym (labelled reimplementation)", "osworld-docker": "OSWorld stock Docker"}
B = 10000


def jl(p):
    return [json.loads(l) for l in open(p) if l.strip()] if os.path.exists(p) else []


def pct(xs, q):
    xs = sorted(xs)
    if not xs:
        return None
    k = (len(xs) - 1) * q
    f, c = math.floor(k), math.ceil(k)
    return xs[f] if f == c else xs[f] + (xs[c] - xs[f]) * (k - f)


def wilson(k, n, z=1.96):
    if n == 0:
        return (None, None)
    p = k / n; d = 1 + z * z / n; c = p + z * z / (2 * n); h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n))
    return ((c - h) / d, (c + h) / d)


def boot(vals, stat, rng, b=2000):
    out = []
    for _ in range(b):
        s = [vals[rng.randrange(len(vals))] for _ in vals]
        out.append(stat(s))
    return (pct(out, 0.025), pct(out, 0.975))


def load_rung(d):
    run = json.load(open(os.path.join(d, "run.json")))
    rows = jl(os.path.join(d, "rollouts.jsonl"))
    host = jl(os.path.join(d, "host.jsonl"))
    return run, rows, host


def arm_baseline(raw, arm, pass_):
    """MemAvailable recorded by the driver 20 s after the arm's services were up and before its first slot (mem-baseline.json)."""
    p = os.path.join(raw, f"{pass_}-{arm}", "mem-baseline.json")
    return json.load(open(p))["mem_available"] if os.path.exists(p) else None


def rung_stats(raw, arm, pass_, n, price, rng):
    d = os.path.join(raw, f"{pass_}-{arm}", f"rung-n{n}")
    if not os.path.exists(os.path.join(d, "run.json")):
        return None
    run, rows, host = load_rung(d)
    wall_h = run["wall_s"] / 3600
    useful = [r for r in rows if r.get("useful")]
    resets = [r["reset_s"] for r in rows if r.get("reset_s") and r.get("failure_reason") != "reset_failed"]
    base = baseline_cache.get((arm, pass_))
    mem = None
    if base and host:
        avail = [h["mem_available"] for h in host]
        per = (base - statistics.median(avail)) / n
        blocks = {}
        for h in host:
            blocks.setdefault(int(h["t"] // 60), []).append(h["mem_available"])
        bl = [statistics.median(v) for v in blocks.values()]
        ci = boot(bl, lambda s: (base - statistics.median(s)) / n, rng) if len(bl) > 1 else (None, None)
        mem = {"per_desktop_gib": per / 1024**3, "ci": [c / 1024**3 if c is not None else None for c in ci], "baseline_gib": base / 1024**3,
               "min_avail_gib": min(avail) / 1024**3}
    fr = {}
    for r in rows:
        if not r.get("useful"):
            fr[r.get("failure_reason") or "?"] = fr.get(r.get("failure_reason") or "?", 0) + 1
    by_pol = {}
    for r in useful:
        p = by_pol.setdefault(r["policy"], [0, 0]); p[0] += 1; p[1] += 1 if r.get("correct") else 0
    lo, hi = wilson(len(rows) - len(useful), len(rows))
    return {"n": n, "rollouts": len(rows), "valid": len(useful), "wall_s": run["wall_s"],
            "valid_per_h": len(useful) / wall_h, "valid_per_usd": len(useful) / (wall_h * price),
            "invalid_rate": (len(rows) - len(useful)) / len(rows) if rows else None, "invalid_rate_ci": [lo, hi],
            "invalid_by_reason": fr, "success_by_policy": {k: {"valid": v[0], "success": v[1]} for k, v in sorted(by_pol.items())},
            "reset_p50_s": pct(resets, 0.5), "reset_p99_s": pct(resets, 0.99), "reset_n": len(resets),
            "reset_p50_ci": boot(resets, lambda s: pct(s, 0.5), rng, 1000) if len(resets) > 1 else None,
            "reset_p99_ci": boot(resets, lambda s: pct(s, 0.99), rng, 1000) if len(resets) > 1 else None,
            "memory": mem, "cpu_busy_mean": statistics.mean(h["cpu_busy"] for h in host) if host else None,
            "_rows": rows, "_wall_h": wall_h}


def per_task(rows, wall_h, price):
    """valid count and attributed USD per task (a rollout's USD = run USD x its env_held_s share)"""
    tot = sum(r.get("env_held_s") or 0 for r in rows) or 1.0
    usd = wall_h * price
    out = {}
    for r in rows:
        t = out.setdefault(r["task"], [0, 0.0])
        t[0] += 1 if r.get("useful") else 0
        t[1] += usd * (r.get("env_held_s") or 0) / tot
    return out


def paired_ratio(a, b, rng):
    tasks = sorted(set(a) & set(b))
    if len(tasks) < 2:
        return None
    def r(ts):
        ua = sum(a[t][0] for t in ts); ca = sum(a[t][1] for t in ts)
        ub = sum(b[t][0] for t in ts); cb = sum(b[t][1] for t in ts)
        return (ua / ca) / (ub / cb) if ca and cb and ub else float("inf")
    point = r(tasks)
    rs = sorted(r([tasks[rng.randrange(len(tasks))] for _ in tasks]) for _ in range(B))
    return {"ratio": point, "ci": [pct(rs, 0.025), pct(rs, 0.975)], "paired_tasks": len(tasks)}


def verdict(ci, higher_is_better=True):
    if not ci or ci[0] is None:
        return "no claim"
    lo, hi = ci
    if lo > 1.0:
        return "Drums better" if higher_is_better else "Drums worse"
    if hi < 1.0:
        return "Drums worse" if higher_is_better else "Drums better"
    return "no difference detected"


baseline_cache = {}


def analyze(raw, price, spot):
    rng = random.Random(20261108)
    res = {"raw": raw, "price_usd_per_h": price, "spot_usd_per_h": spot, "arms": {}}
    for arm in ARMS:
        lad_p = os.path.join(raw, f"p1-{arm}", "ladder.json")
        if not os.path.exists(lad_p):
            res["arms"][arm] = {"missing": True}; continue
        lad = json.load(open(lad_p))
        for pass_ in ("p1", "p2"):
            baseline_cache[(arm, pass_)] = arm_baseline(raw, arm, pass_)
        a = {"name": NAMES[arm], "op_n": lad.get("sustained_active_n"), "max_sustained_n": lad.get("max_sustained_n") or
             max((r["n"] for r in lad["rungs"] if r.get("sustained")), default=None),
             "ladder": [{k: r.get(k) for k in ("n", "rollouts", "useful", "useful_share", "useful_per_h", "step_env_s_p95",
                                                "min_mem_available_gib", "sustained", "why")} for r in lad["rungs"]]}
        a["rungs"] = {}
        for r in lad["rungs"]:
            s = rung_stats(raw, arm, "p1", r["n"], price, rng)
            if s:
                a["rungs"][r["n"]] = s
        # marginal memory per desktop: least-squares slope of host memory in use (baseline - median MemAvailable) over N across the
        # sustained pass-1 rungs; the intercept is the arm's fixed cost (daemons, shared captures, page cache). Secondary metric.
        pts = [(n, s_["memory"]["per_desktop_gib"] * n) for n, s_ in a["rungs"].items() if s_.get("memory") and
               any(r["n"] == n and r.get("sustained") for r in lad["rungs"])]
        if len(pts) >= 2:
            mx, my = statistics.mean(p[0] for p in pts), statistics.mean(p[1] for p in pts)
            sxx = sum((p[0] - mx) ** 2 for p in pts)
            slope = sum((p[0] - mx) * (p[1] - my) for p in pts) / sxx if sxx else None
            a["memory_marginal"] = {"gib_per_desktop": slope, "fixed_gib": (my - slope * mx) if slope is not None else None,
                                    "points": [[n, round(g, 3)] for n, g in sorted(pts)]}
        if a["op_n"]:
            a["op"] = a["rungs"].get(a["op_n"])
            p2 = rung_stats(raw, arm, "p2", a["op_n"], price, rng)
            a["p2"] = p2
        if a["max_sustained_n"]:
            a["usd_per_desktop_day"] = 24 * price / a["max_sustained_n"]
            a["usd_per_desktop_day_spot"] = 24 * spot / a["max_sustained_n"] if spot else None
        res["arms"][arm] = a
    d = res["arms"].get("drums-api", {})
    res["vs"] = {}
    if d.get("op"):
        dt = per_task(d["op"]["_rows"], d["op"]["_wall_h"], price)
        for arm in ARMS[1:]:
            o = res["arms"].get(arm, {})
            if not o.get("op"):
                res["vs"][arm] = {"valid_per_usd": None, "note": "arm has no sustained rung"}; continue
            ot = per_task(o["op"]["_rows"], o["op"]["_wall_h"], price)
            pr = paired_ratio(dt, ot, rng)
            v = {"valid_per_usd": pr, "valid_per_usd_verdict": verdict(pr and pr["ci"])}
            # pre-registration section 6: >= 24 paired tasks and >= 200 rollouts per arm, else "underpowered, no claim"
            nd, no = d["op"]["rollouts"], o["op"]["rollouts"]
            if not pr or pr["paired_tasks"] < 24 or nd < 200 or no < 200:
                v["valid_per_usd_verdict"] = f"underpowered (rollouts Drums {nd}, arm {no}; paired tasks {pr and pr['paired_tasks']}): no claim; CI direction: {verdict(pr and pr['ci'])}"
            if d.get("p2") and o.get("p2"):
                pr2 = paired_ratio(per_task(d["p2"]["_rows"], d["p2"]["_wall_h"], price), per_task(o["p2"]["_rows"], o["p2"]["_wall_h"], price), rng)
                v["valid_per_usd_pass2"] = pr2
            dm, om = (d["op"].get("memory") or {}), (o["op"].get("memory") or {})
            if dm.get("per_desktop_gib") and om.get("per_desktop_gib"):
                v["memory_ratio_arm_over_drums"] = om["per_desktop_gib"] / dm["per_desktop_gib"]
            if d["op"]["reset_p50_s"] and o["op"]["reset_p50_s"]:
                v["reset_p50_ratio_arm_over_drums"] = o["op"]["reset_p50_s"] / d["op"]["reset_p50_s"]
                v["reset_p99_ratio_arm_over_drums"] = o["op"]["reset_p99_s"] / d["op"]["reset_p99_s"]
            if d.get("max_sustained_n") and o.get("max_sustained_n"):
                v["max_sustained_ratio"] = d["max_sustained_n"] / o["max_sustained_n"]
            res["vs"][arm] = v
    return res


def strip(o):
    if isinstance(o, dict):
        return {str(k): strip(v) for k, v in o.items() if not str(k).startswith("_")}
    if isinstance(o, list):
        return [strip(x) for x in o]
    if isinstance(o, float):
        return round(o, 6)
    return o


def f(x, nd=2):
    return "–" if x is None else (f"{x:,.{nd}f}" if isinstance(x, (int, float)) else str(x))


def tables(res):
    L = ["| arm | op N | max sustained N | valid/USD (OD) | valid/h | memory/desktop GiB [95% CI] | reset p50 s | reset p99 s | invalid rate [95% CI] | USD/desktop-day (OD) |",
         "|---|---|---|---|---|---|---|---|---|---|"]
    for arm in ARMS:
        a = res["arms"].get(arm, {})
        op = a.get("op") or {}
        m = op.get("memory") or {}
        L.append(f"| {NAMES[arm]} | {a.get('op_n') or '–'} | {a.get('max_sustained_n') or '–'} | {f(op.get('valid_per_usd'), 1)} | {f(op.get('valid_per_h'), 0)} | "
                 f"{f(m.get('per_desktop_gib'), 3)} [{f((m.get('ci') or [None])[0], 3)}, {f((m.get('ci') or [None, None])[1], 3)}] | "
                 f"{f(op.get('reset_p50_s'), 3)} | {f(op.get('reset_p99_s'), 3)} | "
                 f"{f(op.get('invalid_rate'), 4)} [{f((op.get('invalid_rate_ci') or [None])[0], 4)}, {f((op.get('invalid_rate_ci') or [None, None])[1], 4)}] | "
                 f"{f(a.get('usd_per_desktop_day'), 3)} |")
    L += ["", "| Drums vs | valid/USD ratio [95% CI], paired tasks | verdict | pass-2 ratio [95% CI] | memory ratio (arm/Drums) | reset p50 ratio | reset p99 ratio | max-N ratio |",
          "|---|---|---|---|---|---|---|---|"]
    for arm, v in res.get("vs", {}).items():
        pr = v.get("valid_per_usd") or {}; p2 = v.get("valid_per_usd_pass2") or {}
        L.append(f"| {NAMES[arm]} | {f(pr.get('ratio'))} [{f((pr.get('ci') or [None])[0])}, {f((pr.get('ci') or [None, None])[1])}], {pr.get('paired_tasks', '–')} | "
                 f"{v.get('valid_per_usd_verdict', '–')} | {f(p2.get('ratio'))} [{f((p2.get('ci') or [None])[0])}, {f((p2.get('ci') or [None, None])[1])}] | "
                 f"{f(v.get('memory_ratio_arm_over_drums'))} | {f(v.get('reset_p50_ratio_arm_over_drums'))} | {f(v.get('reset_p99_ratio_arm_over_drums'))} | {f(v.get('max_sustained_ratio'))} |")
    L += ["", "| arm | marginal GiB per desktop (slope over sustained rungs) | fixed GiB (intercept) | points (N, GiB in use) |", "|---|---|---|---|"]
    for arm in ARMS:
        mm = res["arms"].get(arm, {}).get("memory_marginal") or {}
        L.append(f"| {NAMES[arm]} | {f(mm.get('gib_per_desktop'), 3)} | {f(mm.get('fixed_gib'), 1)} | {mm.get('points', '–')} |")
    L += ["", "Equal-N comparison (pass-1 rung at the same N for every arm; secondary, not a claim):", "",
          "| arm | N | valid/USD | memory/desktop GiB [95% CI] | reset p50 s [95% CI] | reset p99 s [95% CI] | invalid rate |", "|---|---|---|---|---|---|---|"]
    for n in (16, 32):
        for arm in ARMS:
            st = (res["arms"].get(arm, {}).get("rungs") or {}).get(n)
            if not st:
                continue
            m = st.get("memory") or {}; c50 = st.get("reset_p50_ci") or [None, None]; c99 = st.get("reset_p99_ci") or [None, None]; mc = m.get("ci") or [None, None]
            L.append(f"| {NAMES[arm]} | {n} | {f(st['valid_per_usd'], 1)} | {f(m.get('per_desktop_gib'), 3)} [{f(mc[0], 3)}, {f(mc[1], 3)}] | "
                     f"{f(st['reset_p50_s'], 3)} [{f(c50[0], 3)}, {f(c50[1], 3)}] | {f(st['reset_p99_s'], 3)} [{f(c99[0], 3)}, {f(c99[1], 3)}] | {f(st['invalid_rate'], 4)} |")
    L += ["", "Ladders (pass 1):", "", "| arm | N | rollouts | valid share | valid/h | step env p95 s | min MemAvailable GiB | sustained | why |", "|---|---|---|---|---|---|---|---|---|"]
    for arm in ARMS:
        for r in (res["arms"].get(arm, {}).get("ladder") or []):
            L.append(f"| {NAMES[arm]} | {r['n']} | {r.get('rollouts') or '–'} | {f(r.get('useful_share'), 4)} | {f(r.get('useful_per_h'), 0)} | {f(r.get('step_env_s_p95'), 3)} | "
                     f"{f(r.get('min_mem_available_gib'), 1)} | {r.get('sustained')} | {r['why'] if isinstance(r.get('why'), str) else (', '.join(r.get('why') or []))} |")
    return "\n".join(L) + "\n"


def svg_bars(path, title, unit, items):
    """items: [(label, value, lo, hi)]"""
    W, H, left, top, bh, gap = 760, 60 + 46 * len(items), 250, 40, 26, 20
    mx = max([(hi if hi is not None else v) for _, v, lo, hi in items if v is not None] + [1e-9]) * 1.1
    s = [f'<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" font-family="sans-serif" font-size="13">',
         f'<rect width="{W}" height="{H}" fill="white"/><text x="10" y="22" font-size="15">{title}</text>']
    for i, (lab, v, lo, hi) in enumerate(items):
        y = top + i * (bh + gap)
        s.append(f'<text x="{left - 8}" y="{y + 18}" text-anchor="end">{lab}</text>')
        if v is None:
            s.append(f'<text x="{left + 4}" y="{y + 18}" fill="#666">not sustained</text>'); continue
        w = (W - left - 120) * v / mx
        s.append(f'<rect x="{left}" y="{y}" width="{w:.1f}" height="{bh}" fill="#3b6fb6"/>')
        if lo is not None and hi is not None:
            x1, x2 = left + (W - left - 120) * lo / mx, left + (W - left - 120) * hi / mx
            s.append(f'<line x1="{x1:.1f}" x2="{x2:.1f}" y1="{y + bh / 2}" y2="{y + bh / 2}" stroke="black" stroke-width="2"/>')
        s.append(f'<text x="{left + w + 6:.1f}" y="{y + 18}">{v:,.3g} {unit}</text>')
    s.append("</svg>")
    open(path, "w").write("\n".join(s))


def figures(res, out):
    A = res["arms"]
    def it(fn):
        return [(NAMES[a], *fn(A.get(a, {}))) for a in ARMS]
    svg_bars(os.path.join(out, "fig-valid-per-usd.svg"), f"Valid rollouts per USD at each arm's operating N (on-demand {res['price_usd_per_h']} USD/h, one r8i.16xlarge)", "/USD",
             it(lambda a: ((a.get("op") or {}).get("valid_per_usd"), None, None)))
    svg_bars(os.path.join(out, "fig-memory-per-desktop.svg"), "Host memory per active desktop at the operating N (GiB, 95% CI)", "GiB",
             it(lambda a: (((a.get("op") or {}).get("memory") or {}).get("per_desktop_gib"), *((((a.get("op") or {}).get("memory") or {}).get("ci")) or [None, None]))))
    svg_bars(os.path.join(out, "fig-reset-p50.svg"), "Reset time p50 under load at the operating N (s, 95% CI)", "s",
             it(lambda a: ((a.get("op") or {}).get("reset_p50_s"), *(((a.get("op") or {}).get("reset_p50_ci")) or [None, None]))))
    svg_bars(os.path.join(out, "fig-max-sustained.svg"), "Max sustained concurrent desktops per host (pass-1 ladder)", "desktops",
             it(lambda a: (a.get("max_sustained_n"), None, None)))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--raw", required=True); ap.add_argument("--raw2"); ap.add_argument("--out", required=True)
    ap.add_argument("--price", type=float); ap.add_argument("--spot", type=float)
    a = ap.parse_args()
    os.makedirs(a.out, exist_ok=True)
    pins = json.load(open(os.path.join(a.raw, "pins.json")))
    price = a.price or pins["cost"]["on_demand_usd_per_h"]
    spot = a.spot
    if spot is None and os.path.exists(os.path.join(a.raw, "spot-price.json")):
        spot = json.load(open(os.path.join(a.raw, "spot-price.json"))).get("usd_per_h")
    res = analyze(a.raw, price, spot)
    md = "## Run " + os.path.basename(a.raw.rstrip("/")) + "\n\n" + tables(res)
    if a.raw2:
        res2 = analyze(a.raw2, price, spot)
        res["replication"] = strip(res2)
        md += "\n## Replication " + os.path.basename(a.raw2.rstrip("/")) + "\n\n" + tables(res2)
    json.dump(strip(res), open(os.path.join(a.out, "summary.json"), "w"), indent=1)
    open(os.path.join(a.out, "tables.md"), "w").write(md)
    figures(res, a.out)
    print(md)


if __name__ == "__main__":
    main()