File size: 24,269 Bytes
2469e25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
"""Rhythm-following metrics, revision 2 (reports/節奏跟隨指標設計(草案).md, sections 6.6, 7 and 8).

    uv run python -m chartgen.rhythm_eval2 --out reports/figs/rhythm_eval2.json

Every number is on its natural scale and shown next to the human value on the same footing.

Comparison of one candidate chart (an AI draw or a second human team) with the reference chart of the same song and
tier, on the reference timing and on the stretch where both have notes (rhythm_eval.common). Hit notes snapped to the
1/48-beat grid; a note less than 1 ms before a red line counts in the new section (AI times are not whole ms).
  family distance  sum over the family's classes of |cand share - ref share|; families: straight (beat, 1/2, 1/4),
                   triplet (1/3, 1/6, 1/12), fine (1/8, 1/16, finer)
  B foreign / B missing  as in rhythm_eval (patterns inside one beat)
  density          hits per beat; log ratio cand / ref

1. Pass rate: a song passes a test when its value is within the human floor's 95th percentile (per tier; for the
   triplet and fine families per band of the reference's family share: < 2%, 2-5%, >= 5%). The floor is the
   independent-team pairs outside the songs being scored, reweighted so that its density-ratio distribution matches
   the AI's. Human reference: leave-one-song-out pass rate of the floor, and the pass rate of second teams on the
   same-pool songs. AI: mean over draws, then over songs. CIs: floor songs and scored songs resampled together.
2. Song-following per family (and the gap mix): 1 - mean error / mean error of the tempo-only baseline (training
   charts of the tier within 10% of the song's main BPM), on the same songs for AI and human (same pool) and for the
   AI on all evaluation songs. 100% = identical to the reference; 0% = no better than the baseline.
3. Amount ratio per subdivision class: total share in the candidates / total share in the references, overall and
   per tempo band (< 110, 110-170, >= 170 BPM).
4. Sensitivity (R2 rewritten): floor pairs, tiers 3 and 4 pooled, leave-one-song-out thresholds; only candidate notes
   that sit on reference notes are corrupted, with one fixed random order per chart (nested doses); flag rate at
   doses 0, 0.25, 0.5, 1 and the excess over dose 0.
Same pool: validation songs with an independent second team; the 395 evaluation sets plus the extra list
data/eval/floor_val_sets.txt (AI samples in runs/evalgen_floor_*).
"""

from __future__ import annotations

import argparse
import json
import pickle
from collections import defaultdict
from pathlib import Path

import numpy as np

from . import disteval as de
from .dataset import DIVISORS, GRID, subdiv_class
from .rhythm_eval import (GAP_NAMES, MIN_HITS, N_SUB, SUB_NAMES, TNAMES, common, finer_share, floor_pairs, gap_mix,
                          main_bpm, outside, patterns, sub_mix, tempo_bank)

REPO = Path(__file__).resolve().parents[2]
FAM = {"straight": [0, 1, 3], "triplet": [2, 4, 6], "fine": [5, 7, 8]}
BANDED = ("triplet", "fine")
TESTS = ("straight", "triplet", "fine", "B_foreign", "B_missing")
SYSTEMS = {"v9.1": ("evalgen_v91/mapsets_AI_v9.1.pkl", "evalgen_floor_v91/mapsets_AI_v9.1.pkl"),
           "v10c": ("evalgen_v10c/mapsets_AI_v10c.pkl", "evalgen_floor_v10c/mapsets_AI_v10c.pkl")}
TEMPO = ((0, 110), (110, 170), (170, 10000))
DENS_EDGES = np.array([0.1, 0.2, 0.3, 0.45, 0.7])


# ---------------------------------------------------------------- features

def beats_tol(sections, t, tol=1.0):
    sec = np.asarray(sections, np.float64)
    idx = np.clip(np.searchsorted(sec[:, 0], t + tol, side="right") - 1, 0, len(sec) - 1)
    s = sec[idx]
    return s[:, 3] + (t - s[:, 0]) / s[:, 1]


def grid_of(chart, sections, offset=0.0):
    t = np.asarray(chart["time"], np.float64) + offset
    ty = np.asarray(chart["type"])
    t = np.sort(t[ty <= 3])
    if len(t) == 0:
        return np.zeros(0, np.int64)
    return np.unique(np.round(beats_tol(sections, t) * GRID).astype(np.int64))


def mapset_grid(ms, sections=None):
    out = {}
    for t, c in ms.items():
        g = grid_of(c, c["sections"] if sections is None else sections, float(c.get("offset_ms", 0.0)))
        if len(g) >= MIN_HITS:
            out[int(t)] = g
    return out


def density(g):
    return len(g) / max((g[-1] - g[0]) / GRID, 1.0)


def vocab_of(grids):
    return set().union(*[set(patterns(g)) for g in grids.values()]) if grids else set()


def compare(cg, rg, vocab):
    c, r = common(cg, rg)
    if len(c) < MIN_HITS or len(r) < MIN_HITS:
        return None
    sc, sr, gc, gr = sub_mix(c), sub_mix(r), gap_mix(c), gap_mix(r)
    pc = patterns(c)
    out = {f: float(np.abs(sc[ix] - sr[ix]).sum()) for f, ix in FAM.items()}
    out.update(B_foreign=outside(pc, vocab), B_missing=outside(patterns(r), set(pc)),
               gap=float(np.abs(gc - gr).sum()), logdens=float(np.log(density(c) / density(r))),
               share={f: float(sr[ix].sum()) for f, ix in FAM.items()}, sub_c=sc, sub_r=sr, gap_c=gc, gap_r=gr)
    return out


def band(share):
    return 0 if share < 0.02 else (1 if share < 0.05 else 2)


def base_err(b, cmp):
    """errors of the tempo-only profile b (sub 9 + gap 12) against the reference of one comparison."""
    out = {f: float(np.abs(b[ix] - cmp["sub_r"][ix]).sum()) for f, ix in FAM.items()}
    out["gap"] = float(np.abs(b[N_SUB:] - cmp["gap_r"]).sum())
    return out


# ---------------------------------------------------------------- thresholds

def wquantile(v, w, q):
    v, w = np.asarray(v, float), np.asarray(w, float)
    m = w > 0
    if m.sum() == 0:
        return np.inf
    o = np.argsort(v[m])
    cw = np.cumsum(w[m][o])
    return float(v[m][o][min(np.searchsorted(cw, q * cw[-1]), m.sum() - 1)])


def dens_bin(ld):
    return int(np.searchsorted(DENS_EDGES, abs(ld)))


def thresholds(rows, w):
    """rows: list of comparison dicts; w: weights -> {test: value or [band values]}."""
    out = {}
    for tname in TESTS:
        v = np.array([r[tname] for r in rows])
        if tname in BANDED:
            b = np.array([band(r["share"][tname]) for r in rows])
            out[tname] = [wquantile(v[b == k], w[b == k], 0.95) if (b == k).sum() >= 10 else wquantile(v, w, 0.95)
                          for k in range(3)]
        else:
            out[tname] = wquantile(v, w, 0.95)
    return out


def thr_matrix(thr):
    return np.array([thr[t] if t in BANDED else [thr[t]] * 3 for t in TESTS], float)   # [tests, 3 bands]


def pack(cmps_by_song):
    """values [n, tests], band [n, tests], song index [n] of all comparisons of a list of songs."""
    V, B, S = [], [], []
    for i, cs in enumerate(cmps_by_song):
        for c in cs:
            V.append([c[t] for t in TESTS])
            B.append([band(c["share"][t]) if t in BANDED else 0 for t in TESTS])
            S.append(i)
    return np.array(V, float).reshape(-1, len(TESTS)), np.array(B, int).reshape(-1, len(TESTS)), np.array(S, int), \
        len(cmps_by_song)


def song_pass(pk, M):
    """per-song pass share (mean over the song's comparisons): {test: [songs]} incl. 'any'."""
    V, B, S, n = pk
    f = V > M[np.arange(len(TESTS))[None, :], B]
    cnt = np.maximum(np.bincount(S, minlength=n), 1)
    out = {t: 1 - np.bincount(S, weights=f[:, i].astype(float), minlength=n) / cnt for i, t in enumerate(TESTS)}
    out["any"] = 1 - np.bincount(S, weights=f.any(1).astype(float), minlength=n) / cnt
    return out


def fails(cmp, thr):
    f = {}
    for tname in TESTS:
        t = thr[tname][band(cmp["share"][tname])] if tname in BANDED else thr[tname]
        f[tname] = cmp[tname] > t
    f["any"] = any(f[t] for t in TESTS)
    return f


# ---------------------------------------------------------------- data

def same_pool(E, cat, sets):
    """set -> (reference grids, sections, main BPM, [second-team grids]) anchored on that set's mapset."""
    by_id = {e["beatmapset_id"]: e for e in E}
    by_song = de.group_songs(E)
    out = {}
    for s in sets:
        e = by_id.get(s)
        if e is None:
            continue
        ref_ms = de._entry_mapset(e, cat)
        if not ref_ms:
            continue
        sec = ref_ms[max(ref_ms)]["sections"]
        rg = mapset_grid(ref_ms)
        used = de._mappers(ref_ms)
        teams = []
        for o in by_song.get(e.get("song_key") or str(s), []):
            if o["beatmapset_id"] == s:
                continue
            ms = de._entry_mapset(o, cat)
            if not ms or not de._mappers(ms) or de._mappers(ms) & used:
                continue
            d, ok = de.align_mapsets(ref_ms, ms)
            if not ok:
                continue
            ms = {t: {**c, "offset_ms": float(c.get("offset_ms", 0.0)) + d} for t, c in ms.items()}
            cg = mapset_grid(ms, sec)
            both = sorted(set(rg) & set(cg))
            if both and finer_share(cg[t] for t in both) <= finer_share(rg[t] for t in both) + 0.03:
                teams.append(cg)
                used |= de._mappers(ms)
        out[s] = {"ref": rg, "sec": sec, "bpm": main_bpm(sec), "teams": teams, "key": e.get("song_key") or str(s)}
    return out


def load_system(paths):
    d = {}
    for p in paths:
        f = REPO / "data/hfruns/runs" / p
        if f.exists():
            d.update(pickle.load(open(f, "rb")))
    return d


def ai_grids(d, s, t):
    out = []
    for dr in d.get(s, {}).get("draws", [])[:4]:
        c = dr["charts"].get(t)
        if c is not None:
            g = grid_of(c, c["sections"])
            if len(g) >= MIN_HITS:
                out.append(g)
    return out


# ---------------------------------------------------------------- corruption (sensitivity)

def corrupt(c, r, kind, dose, order):
    """Corrupt the first ceil(dose * n) of the candidate notes that sit on reference notes of the kind's class, in the
    chart's fixed random `order` (indices into those matched notes)."""
    c = c.copy()
    on_ref = np.isin(c, r)
    cls = subdiv_class(c)
    if kind == "binarize":
        sel = on_ref & np.isin(cls, [DIVISORS.index(3), DIVISORS.index(6), DIVISORS.index(12)])
    elif kind == "drop_fine":
        sel = on_ref & (cls >= DIVISORS.index(8))
    else:   # shift: off-beat notes
        sel = on_ref & (c % GRID != 0)
    idx = np.where(sel)[0][order]
    k = int(np.ceil(dose * len(idx)))
    pick = idx[:k]
    if kind == "binarize":
        pos = c[pick] % GRID
        c[pick] = c[pick] - pos + np.round(pos / 12).astype(np.int64) * 12
    elif kind == "drop_fine":
        c = np.delete(c, pick)
    else:
        c[pick] = c[pick] + 12
    return np.unique(c), int(len(idx))


def matched(c, r, kind):
    on_ref = np.isin(c, r)
    cls = subdiv_class(c)
    if kind == "binarize":
        return int((on_ref & np.isin(cls, [DIVISORS.index(3), DIVISORS.index(6), DIVISORS.index(12)])).sum())
    if kind == "drop_fine":
        return int((on_ref & (cls >= DIVISORS.index(8))).sum())
    return int((on_ref & (c % GRID != 0)).sum())


# ---------------------------------------------------------------- main

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--out", type=Path, default=REPO / "reports/figs/rhythm_eval2.json")
    ap.add_argument("--cache", type=Path, default=REPO / "data/eval/rhythm_floor_pairs.pkl")
    ap.add_argument("--tiers", type=int, nargs="+", default=[3, 4])
    ap.add_argument("--boot", type=int, default=500)
    ap.add_argument("--seed", type=int, default=0)
    a = ap.parse_args()
    rng = np.random.default_rng(a.seed)
    E = de.load_charts_all()
    cat = de.load_catalog()
    bank = tempo_bank(E)

    eval_sets = [int(x) for x in open(REPO / "data/eval_modern_val_sets.txt").read().split()]
    extra_sets = [int(x) for x in open(REPO / "data/eval/floor_val_sets.txt").read().split()]
    pool = same_pool(E, cat, eval_sets + extra_sets)
    sp_sets = [s for s in pool if pool[s]["teams"]]
    sp_keys = {pool[s]["key"] for s in sp_sets}
    systems = {k: load_system(p) for k, p in SYSTEMS.items()}
    print(f"songs: eval {len(eval_sets)}, extra {len(extra_sets)}; same pool (second team) {len(sp_sets)};"
          f" AI coverage " + ", ".join(f"{k} {sum(s in d for s in pool)}" for k, d in systems.items()))

    def baseline(t, bpm):
        bb, bp = bank[t]
        m = np.abs(np.log(bb / bpm)) < np.log(1.1)
        return bp[m].mean(0) if m.sum() >= 20 else bp[np.argsort(np.abs(np.log(bb / bpm)))[:20]].mean(0)

    pairs = floor_pairs(E, cat, a.cache)
    res = {"same_pool_songs": len(sp_sets), "tiers": {}}
    for t in a.tiers:
        T = TNAMES[t]
        # ---- floor comparisons (outside the same-pool songs)
        F, Fkey = [], []
        for key, year, rg, cg in pairs:
            if key in sp_keys or t not in rg or t not in cg:
                continue
            both = sorted(set(rg) & set(cg))
            if finer_share(cg[u] for u in both) > finer_share(rg[u] for u in both) + 0.03:
                continue
            cmp = compare(cg[t], rg[t], vocab_of(rg))
            if cmp:
                F.append(cmp)
                Fkey.append(key)
        Fkey = np.array(Fkey)
        # ---- AI comparisons on every pool song; second teams on same-pool songs
        AI = {sysn: {} for sysn in systems}
        HU = {}
        for s, v in pool.items():
            if t not in v["ref"]:
                continue
            vocab = vocab_of(v["ref"])
            for sysn, d in systems.items():
                cs = [compare(g, v["ref"][t], vocab) for g in ai_grids(d, s, t)]
                cs = [c for c in cs if c]
                if cs:
                    AI[sysn][s] = cs
            for tm in v["teams"]:
                if t in tm:
                    c = compare(tm[t], v["ref"][t], vocab)
                    if c:
                        HU[s] = c
                        break
        # ---- density matching weights for the floor (to the AI's density-ratio distribution, both systems pooled)
        ai_ld = [c["logdens"] for sysn in AI for cs in AI[sysn].values() for c in cs]
        p_ai = np.bincount([dens_bin(x) for x in ai_ld], minlength=len(DENS_EDGES) + 1) / len(ai_ld)
        fb = np.array([dens_bin(c["logdens"]) for c in F])
        p_fl = np.bincount(fb, minlength=len(DENS_EDGES) + 1) / len(F)
        w = np.where(p_fl[fb] > 0, p_ai[fb] / np.maximum(p_fl[fb], 1e-12), 0.0)
        thr = thresholds(F, w)
        # leave-one-song-out human pass rate on the floor
        uk = np.unique(Fkey)
        loo_fail = defaultdict(list)
        loo_thr = {}
        for k in uk:
            m = Fkey != k
            loo_thr[k] = thresholds([F[i] for i in np.where(m)[0]], w[m])
            for i in np.where(~m)[0]:
                f = fails(F[i], loo_thr[k])
                for tn in (*TESTS, "any"):
                    loo_fail[tn].append((f[tn], w[i]))
        human_loo = {tn: 1 - float(np.average([x for x, _ in v], weights=[y for _, y in v])) for tn, v in loo_fail.items()}

        r = {"floor_pairs": len(F), "floor_songs": int(len(uk)), "thresholds": thr, "human_loo_pass": human_loo,
             "same_pool_n": {"human": len(HU), **{k: sum(s in AI[k] for s in HU) for k in AI}}}
        eval_songs = [s for s in eval_sets if s in pool and t in pool[s]["ref"]]
        r["eval_n"] = {k: sum(s in AI[k] for s in eval_songs) for k in AI}
        hu_list = list(HU)
        pk_h = pack([[HU[s]] for s in hu_list])
        pk_ev = {k: pack([AI[k][s] for s in eval_songs if s in AI[k]]) for k in AI}
        sp_ai = {k: [s for s in hu_list if s in AI[k]] for k in AI}
        pk_sp = {k: pack([AI[k][s] for s in sp_ai[k]]) for k in AI}
        hmask = {k: np.array([s in AI[k] for s in hu_list]) for k in AI}
        M = thr_matrix(thr)
        pr = {"human_same_pool": {k: float(v.mean()) for k, v in song_pass(pk_h, M).items()}}
        for k in AI:
            pr[k] = {"eval": {x: float(v.mean()) for x, v in song_pass(pk_ev[k], M).items()},
                     "same_pool": {x: float(v.mean()) for x, v in song_pass(pk_sp[k], M).items()}}
        # joint bootstrap: floor songs (threshold) + scored songs, as song multiplicities
        boot = defaultdict(list)
        key_rows = {k: np.where(Fkey == k)[0] for k in uk}
        for _ in range(a.boot):
            ks = rng.choice(uk, len(uk))
            idx = np.concatenate([key_rows[k] for k in ks])
            Mb = thr_matrix(thresholds([F[i] for i in idx], w[idx]))
            for k in AI:
                n = pk_ev[k][3]
                cnt = np.bincount(rng.integers(0, n, n), minlength=n)
                for x, v in song_pass(pk_ev[k], Mb).items():
                    boot[f"{k}|eval|{x}"].append(float((cnt * v).sum() / n))
            nh = len(hu_list)
            ch = np.bincount(rng.integers(0, nh, nh), minlength=nh)
            ph = song_pass(pk_h, Mb)
            for x, v in ph.items():
                boot[f"human|same_pool|{x}"].append(float((ch * v).sum() / nh))
            for k in AI:
                ca = ch[hmask[k]]
                pa = song_pass(pk_sp[k], Mb)
                for x in ph:
                    a_ = float((ca * pa[x]).sum() / max(ca.sum(), 1))
                    h_ = float((ca * ph[x][hmask[k]]).sum() / max(ca.sum(), 1))
                    boot[f"{k}|same_pool|{x}"].append(a_)
                    boot[f"{k}-human|same_pool|{x}"].append(a_ - h_)
        ci = {k: [float(np.percentile(v, 2.5)), float(np.percentile(v, 97.5))] for k, v in boot.items()}
        r["pass"] = pr
        r["pass_ci"] = ci

        # ---- song-following (same pool: AI and human on the same songs; eval pool: AI)
        def follow(cmp_lists, bpms):
            fam = list(FAM) + ["gap"]
            e = {f: [] for f in fam}
            eb = {f: [] for f in fam}
            for cs, bpm in zip(cmp_lists, bpms):
                b = baseline(t, bpm)
                for f in fam:
                    e[f].append(np.mean([c[f] if f != "gap" else c["gap"] for c in cs]))
                    eb[f].append(np.mean([base_err(b, c)[f] for c in cs]))
            return {f: (np.array(e[f]), np.array(eb[f])) for f in fam}

        fol = {}
        sp_common = [s for s in HU if all(s in AI[k] for k in AI)]
        hf = follow([[HU[s]] for s in sp_common], [pool[s]["bpm"] for s in sp_common])
        af = {k: follow([AI[k][s] for s in sp_common], [pool[s]["bpm"] for s in sp_common]) for k in AI}
        ae = {k: follow([AI[k][s] for s in eval_songs if s in AI[k]], [pool[s]["bpm"] for s in eval_songs if s in AI[k]])
              for k in AI}
        for f in hf:
            def score(x, idx=None):
                e, eb = x[f]
                if idx is not None:
                    e, eb = e[idx], eb[idx]
                return 1 - e.mean() / eb.mean()
            bs = defaultdict(list)
            for _ in range(a.boot):
                j = rng.integers(0, len(sp_common), len(sp_common))
                h = score(hf, j)
                bs["human"].append(h)
                for k in AI:
                    bs[k].append(score(af[k], j))
                    bs[k + "-human"].append(score(af[k], j) - h)
                    je = rng.integers(0, len(ae[k][f][0]), len(ae[k][f][0]))
                    bs[k + "|eval"].append(score(ae[k], je))
            fol[f] = {"human_same_pool": float(score(hf)), "n_same_pool": len(sp_common),
                      **{k: float(score(af[k])) for k in AI}, **{k + "|eval": float(score(ae[k])) for k in AI},
                      "ci": {k: [float(np.percentile(v, 2.5)), float(np.percentile(v, 97.5))] for k, v in bs.items()}}
        r["follow"] = fol

        # ---- amount ratio per class, overall and per tempo band
        amt = {}
        for name, lists, songs in [("human_same_pool", {s: [HU[s]] for s in HU}, list(HU))] + \
                [(k + "|same_pool", AI[k], [s for s in HU if s in AI[k]]) for k in AI] + \
                [(k + "|eval", AI[k], [s for s in eval_songs if s in AI[k]]) for k in AI]:
            C = np.array([np.mean([c["sub_c"] for c in lists[s]], 0) for s in songs])
            R = np.array([np.mean([c["sub_r"] for c in lists[s]], 0) for s in songs])
            bpm = np.array([pool[s]["bpm"] for s in songs])
            def ratio(Cx, Rx):
                # undefined (None) when the references hardly use the class: mean share below 0.2%
                return [float(c / r) if r >= 0.002 * len(Rx) else None for c, r in zip(Cx.sum(0), Rx.sum(0))]

            row = {"all": ratio(C, R), "n": len(songs)}
            bs = []
            for _ in range(a.boot):
                j = rng.integers(0, len(songs), len(songs))
                bs.append([np.nan if x is None else x for x in ratio(C[j], R[j])])
            bs = np.array(bs)
            row["ci"] = [None if row["all"][k] is None else np.nanpercentile(bs[:, k], [2.5, 97.5]).tolist()
                         for k in range(bs.shape[1])]
            for lo, hi in TEMPO:
                m = (bpm >= lo) & (bpm < hi)
                row[f"bpm{lo}-{hi}"] = ratio(C[m], R[m]) if m.sum() >= 5 else None
                row[f"bpm{lo}-{hi}_n"] = int(m.sum())
            amt[name] = row
        r["amount"] = amt
        r["density_within_25pct"] = {
            "human_same_pool": float(np.mean([abs(HU[s]["logdens"]) < np.log(1.25) for s in HU])),
            **{k: float(np.mean([np.mean([abs(c["logdens"]) < np.log(1.25) for c in AI[k][s]]) for s in eval_songs
                                 if s in AI[k]])) for k in AI}}
        res["tiers"][T] = r
        print(f"done {T}")

    # ---- sensitivity: floor pairs of the requested tiers pooled, leave-one-song-out thresholds (unweighted)
    res["sensitivity"] = sensitivity(E, cat, pairs, sp_keys, a.tiers, rng)
    a.out.parent.mkdir(parents=True, exist_ok=True)
    json.dump(res, open(a.out, "w"), ensure_ascii=False, indent=1, default=float)
    print(f"wrote {a.out}")


def sensitivity(E, cat, pairs, sp_keys, tiers, rng):
    out = {}
    per_tier = {}
    for t in tiers:
        F, keys = [], []
        for key, year, rg, cg in pairs:
            if key in sp_keys or t not in rg or t not in cg:
                continue
            both = sorted(set(rg) & set(cg))
            if finer_share(cg[u] for u in both) > finer_share(rg[u] for u in both) + 0.03:
                continue
            c, r = common(cg[t], rg[t])
            if len(c) < MIN_HITS or len(r) < MIN_HITS:
                continue
            vocab = vocab_of(rg)
            cmp = compare(cg[t], rg[t], vocab)
            F.append((key, c, r, vocab, cmp))
            keys.append(key)
        keys = np.array(keys)
        w = np.ones(len(F))
        loo = {k: thresholds([F[i][4] for i in np.where(keys != k)[0]], w[keys != k]) for k in np.unique(keys)}
        per_tier[t] = (F, loo)
    for kind, test in (("binarize", "triplet"), ("drop_fine", "fine"), ("shift", "B_foreign")):
        flags = defaultdict(list)   # dose -> [(test fail, any fail)]
        moved = []
        n = 0
        for t, (F, loo) in per_tier.items():
            for key, c, r, vocab, _ in F:
                m = matched(c, r, kind)
                if m < 5:
                    continue
                n += 1
                order = rng.permutation(m)
                for dose in (0.0, 0.25, 0.5, 1.0):
                    g, _ = corrupt(c, r, kind, dose, order)
                    cmp = compare(g, r, vocab) if len(g) >= MIN_HITS else None
                    if cmp is None:
                        continue
                    f = fails(cmp, loo[key])
                    flags[dose].append((f[test], f["any"]))
                moved.append(m / len(c))
        res = {"n": n, "median_share_moved_at_1": float(np.median(moved)) if moved else None}
        for dose, v in flags.items():
            v = np.array(v, float)
            res[f"dose{dose}"] = {"test": float(v[:, 0].mean()), "any": float(v[:, 1].mean())}
        if 0.0 in flags and 1.0 in flags and len(flags[0.0]) == len(flags[1.0]):
            d = np.array(flags[1.0], float)[:, 0] - np.array(flags[0.0], float)[:, 0]
            bs = [d[rng.integers(0, len(d), len(d))].mean() for _ in range(1000)]
            res["excess_test_at_1"] = [float(d.mean()), float(np.percentile(bs, 2.5)), float(np.percentile(bs, 97.5))]
        out[kind] = res
    return out


if __name__ == "__main__":
    main()