File size: 24,155 Bytes
3726258
 
3f3fbe2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3726258
3f3fbe2
 
 
 
 
 
 
 
 
 
 
3726258
3f3fbe2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3726258
3f3fbe2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3726258
3f3fbe2
 
 
 
 
 
 
 
 
3726258
 
3f3fbe2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3726258
3f3fbe2
 
 
 
 
 
 
 
 
3726258
3f3fbe2
 
 
3726258
3f3fbe2
 
 
 
 
 
 
 
 
 
 
 
 
 
3726258
 
3f3fbe2
3726258
 
3f3fbe2
3726258
3f3fbe2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3726258
3f3fbe2
 
 
 
 
 
 
 
 
3726258
 
3f3fbe2
3726258
3f3fbe2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3726258
3f3fbe2
 
 
 
 
 
3726258
 
3f3fbe2
3726258
3f3fbe2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3726258
3f3fbe2
 
 
 
3726258
3f3fbe2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3726258
3f3fbe2
 
 
 
 
 
 
 
 
 
 
3726258
 
3f3fbe2
3726258
3f3fbe2
 
 
 
 
 
 
 
 
 
 
3726258
3f3fbe2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3726258
3f3fbe2
 
 
 
 
 
 
 
 
3726258
3f3fbe2
 
 
 
 
 
 
 
 
 
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
"""CPU tests of the variant sub-tiers: labels, ``--tiers`` parsing, quotas, small-anchor and clique specs
(no models).
"""
import csv, json, pathlib, subprocess, sys

import numpy as np
import pytest

from strangebench.common import variants as v
from strangebench.scene_specs import never_cliques as nc
from strangebench.generation import gen_sd35l_e2e as gen
from strangebench.audit import filter_small_anchor as fsa
from strangebench.audit import make_complete_annotations as mca
from strangebench.scene_specs.layout_solver import rel_area_of_box, shrink_anchor_box

ROOT = pathlib.Path(__file__).resolve().parents[1]
PY = sys.executable


def test_tag_strip_and_variant_of_label():
    assert v.tag_label("tier2_1typical", "small_anchor") == "tier2_1typical__small_anchor"
    assert v.strip_variant("tier2_1typical__small_anchor") == "tier2_1typical"
    assert v.strip_variant("tier_never_k3") == "tier_never_k3" and v.strip_variant("tier_never") == "tier_never"
    assert v.variant_of_label("tier2_1atypical__small_anchor") == "small_anchor"
    assert v.variant_of_label("tier6_5typical") == "k5" and v.variant_of_label("tier6_5atypical") == "k5"
    assert v.variant_of_label("tier_never_k3") == "never_clique" and v.variant_of_label("tier_never_k4") == "never_clique"
    for lbl in v.V1_LABELS:
        assert v.variant_of_label(lbl) is None
    assert v.variant_of_scene({"variant": "k5", "sub_tier": "tier2_1typical"}) == "k5"
    assert v.variant_of_scene({"sub_tier": "tier_never_k4"}) == "never_clique"
    assert v.variant_of_scene({"sub_tier": "tier3_2typical"}) is None
    assert v.prompt_base_label("tier_never_k3") == "tier_never"
    assert v.prompt_base_label("tier2_1atypical__small_anchor") == "tier2_1atypical"
    assert v.prompt_base_label("tier6_5typical") == "tier6_5typical"


def test_tier_tables_are_consistent():
    labels = [t[0] for t in v.VARIANT_TIERS]
    assert labels == ["tier6_5typical", "tier6_5atypical", "tier_never_k3", "tier_never_k4",
                      "tier2_1typical__small_anchor", "tier2_1atypical__small_anchor"]
    assert not any("natural" in l or "tier7" in l for l in labels)
    assert set(v.SOLVER_ONLY_LABELS) == {"tier6_5typical", "tier6_5atypical", "tier_never_k3", "tier_never_k4"}
    assert set(v.NEVER_CLIQUE_LABELS) == {"tier_never_k3", "tier_never_k4"}
    expanded = {l for grp in v.TIER_GROUPS.values() for l in grp}
    assert expanded == set(v.V1_LABELS) | set(labels)
    for label, mode, n, bg, variant, base in v.VARIANT_TIERS:
        assert variant in v.VARIANTS and base in v.V1_LABELS or base == label
        assert (mode == "never_clique") == (variant == "never_clique")
        assert n == {"k5": 5, "small_anchor": 1}.get(variant, n)


def test_parse_tiers_expands_pairs_and_singles_in_order():
    counts = v.parse_tiers_arg("tier6=4, never_k3=3,never_k4=2,tier2__small_anchor=5,tier1=7,never=1")
    assert list(counts.items()) == [
        ("tier6_5typical", 4), ("tier6_5atypical", 4), ("tier_never_k3", 3), ("tier_never_k4", 2),
        ("tier2_1typical__small_anchor", 5), ("tier2_1atypical__small_anchor", 5),
        ("tier1_natural_bg", 7), ("tier1_atypical_bg", 7), ("tier_never", 1)]
    assert v.parse_tiers_arg("tier3=0") == {"tier3_2typical": 0, "tier3_2atypical": 0}


@pytest.mark.parametrize("bad", ["tier9=4", "tier6=4,tier6=5", "tier6=x", "tier6", "", "never_k3=-1"])
def test_parse_tiers_rejects(bad):
    with pytest.raises(ValueError):
        v.parse_tiers_arg(bad)


def test_pair_tiers_and_order():
    labels = ["tier_never_k3", "tier2_1atypical__small_anchor", "tier6_5atypical", "tier_never",
              "tier2_1typical", "tier6_5typical", "tier2_1atypical", "tier2_1typical__small_anchor",
              "tier1_atypical_bg", "tier1_natural_bg"]
    assert v.order_tiers(labels)[:5] == ["tier1_natural_bg", "tier1_atypical_bg", "tier2_1typical",
                                         "tier2_1atypical", "tier_never"]
    pairs, singles = v.pair_tiers(labels)
    assert ("tier1_natural_bg", "tier1_atypical_bg") in pairs
    assert ("tier2_1typical", "tier2_1atypical") in pairs
    assert ("tier6_5typical", "tier6_5atypical") in pairs
    assert ("tier2_1typical__small_anchor", "tier2_1atypical__small_anchor") in pairs
    assert singles == ["tier_never", "tier_never_k3"]
    assert v.pair_label_of("tier_never_k4") is None
    pairs2, singles2 = v.pair_tiers(["tier6_5typical", "tier_never_k4"])
    assert pairs2 == [] and singles2 == ["tier6_5typical", "tier_never_k4"]
    pv1, sv1 = v.pair_tiers(list(v.V1_LABELS))
    assert pv1 == [("tier1_natural_bg", "tier1_atypical_bg"), ("tier2_1typical", "tier2_1atypical"),
                   ("tier3_2typical", "tier3_2atypical"), ("tier4_3typical", "tier4_3atypical"),
                   ("tier5_4typical", "tier5_4atypical")] and sv1 == ["tier_never"]


def test_allocate_per_anchor_exact_capped_and_deterministic():
    anchors = list(range(80))
    a = v.allocate_per_anchor(50, anchors, seed=5000, tier_label="tier6_5typical")
    assert sum(a.values()) == 50 and max(a.values()) == 1 and len(a) == 50
    assert a == v.allocate_per_anchor(50, anchors, 5000, "tier6_5typical")
    assert a != v.allocate_per_anchor(50, anchors, 5001, "tier6_5typical")
    big = v.allocate_per_anchor(200, anchors, 1, "x")
    assert sum(big.values()) == 200 and set(big.values()) == {2, 3}
    caps = {i: (3 if i < 10 else 0) for i in anchors}
    c = v.allocate_per_anchor(100, [i for i in anchors if caps[i] > 0], 1, "k3", caps=caps)
    assert sum(c.values()) == 30 and all(c[i] == 3 for i in range(10))
    q = v.allocate_per_anchor(100, anchors, 1, "k3", quota_cap=1)
    assert sum(q.values()) == 80 and set(q.values()) == {1}
    assert v.allocate_per_anchor(0, anchors, 1, "k3") == {} and v.allocate_per_anchor(5, [], 1, "k3") == {}
    assert v.stable_hash("a") == v.stable_hash("a") and v.stable_hash("a") != v.stable_hash("b")


def _toy():
    """6 classes. Anchor 0 never co-occurs with 1..5. Among partners: {1,2,3} pairwise zero, {1,2,4}
    pairwise zero, 5 co-occurs with everyone but 0. Class 4 is rare, so E(3,4) < 10 and E(1,4) < 10
    make those zero pairs uninformative."""
    n = 6
    counts = np.full((n, n), 50, dtype=np.int64)
    np.fill_diagonal(counts, 0)
    for a, b in [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (1, 2), (1, 3), (2, 3), (1, 4), (2, 4), (3, 4)]:
        counts[a, b] = counts[b, a] = 0
    n_images = 1000
    n_i = np.array([400, 300, 300, 200, 20, 300], dtype=np.float64)
    return counts, n_i / n_images, n_images


def test_expected_counts_and_informative_mask():
    counts, marginal, n = _toy()
    e = nc.expected_pair_counts(marginal, n)
    assert abs(e[0, 1] - 400 * 300 / 1000) < 1e-9
    mask = nc.informative_zero_mask(counts, marginal, n, min_expected=10)
    assert mask[0, 1] and mask[1, 2] and mask[2, 3]
    assert not mask[3, 4] and not mask[1, 4]
    assert not mask[0, 0] and not mask[1, 5]


def test_cliques_respect_min_expected():
    counts, marginal, n = _toy()
    mask = nc.informative_zero_mask(counts, marginal, n, min_expected=10)
    assert nc.candidate_partners(0, mask) == [1, 2, 3, 5]
    assert set(nc.enumerate_cliques(0, mask, 2)) == {(1, 2), (1, 3), (2, 3)}
    assert nc.enumerate_cliques(0, mask, 3) == [(1, 2, 3)]
    assert nc.enumerate_cliques(0, mask, 4) == []
    assert nc.enumerate_cliques(5, mask, 2) == []
    relaxed = nc.informative_zero_mask(counts, marginal, n, min_expected=1)
    assert relaxed[3, 4] and relaxed[1, 4]
    assert nc.enumerate_cliques(0, relaxed, 4) == [(1, 2, 3, 4)]
    assert nc.min_expected_over_members([0, 1, 2, 3], nc.expected_pair_counts(marginal, n)) == pytest.approx(60.0)


def test_clique_sampling_seeded_and_report():
    counts, marginal, n = _toy()
    mask = nc.informative_zero_mask(counts, marginal, n, min_expected=10)
    a = nc.sample_clique(0, mask, 2, np.random.default_rng(1))
    assert a == nc.sample_clique(0, mask, 2, np.random.default_rng(1)) and a in {(1, 2), (1, 3), (2, 3)}
    assert nc.sample_clique(0, mask, 4, np.random.default_rng(1)) is None
    assert sorted(nc.cliques_for_anchor(0, mask, 2, seed=5)) == [(1, 2), (1, 3), (2, 3)]
    assert nc.cliques_for_anchor(0, mask, 2, seed=5) == nc.cliques_for_anchor(0, mask, 2, seed=5)
    rep = nc.clique_report(mask, (2, 3), {i: f"c{i}" for i in range(6)})
    assert rep["per_anchor"][0]["n_cliques_k3"] == 1
    assert rep["summary"]["anchors_with_k3"] == 4 and rep["summary"]["total_cliques_k3"] == 4
    assert rep["per_anchor"][5]["n_cliques_k2"] == 0
    assert rep["summary"]["n_informative_zero_pairs"] == int(mask.sum()) // 2


def test_shrink_big_box_to_two_percent_keeps_center_and_aspect():
    box = [100, 200, 700, 500]
    nb, rel = shrink_anchor_box(box, 1024, max_rel_area=0.02, min_short_side=72)
    assert rel <= 0.02 + 1e-6 and abs(rel - rel_area_of_box(nb, 1024)) < 1e-9
    cx, cy = (box[0] + box[2]) / 2, (box[1] + box[3]) / 2
    assert abs(cx - (nb[0] + nb[2]) / 2) <= 1 and abs(cy - (nb[1] + nb[3]) / 2) <= 1
    w, h = nb[2] - nb[0], nb[3] - nb[1]
    assert abs(w / h - 2.0) < 0.05 and min(w, h) >= 72


def test_shrink_small_box_unchanged_and_floors():
    box = [34, 34, 134, 134]
    nb, rel = shrink_anchor_box(box, 1024)
    assert nb == box and abs(rel - 100 * 100 / 1024 ** 2) < 1e-9
    nb, rel = shrink_anchor_box([0, 400, 1000, 600], 1024, max_rel_area=0.02, min_short_side=72)
    assert nb[3] - nb[1] == 72 and rel <= 0.02 + 1e-6
    assert nb[2] - nb[0] <= int(round(0.02 * 1024 * 1024 / 72)) + 1
    nb, _ = shrink_anchor_box([900, 900, 1024, 1024], 1024, margin=24)
    assert nb[0] >= 24 and nb[1] >= 24 and nb[2] <= 1000 and nb[3] <= 1000 and nb[2] > nb[0]


def test_anchor_rel_area():
    assert gen.anchor_rel_area([10, 20, 128, 64], 1024, 1024) == pytest.approx(128 * 64 / 1024 ** 2, abs=1e-5)
    assert gen.anchor_rel_area([0, 0, 512, 256], 1024, 512) == pytest.approx(0.25)
    assert gen.anchor_rel_area(None, 1024, 1024) is None


def test_attempt_ok_and_small_anchor_choice():
    assert gen.attempt_ok(2, 2) and not gen.attempt_ok(1, 2)
    assert gen.attempt_ok(2, 2, 0.03, 0.04) and not gen.attempt_ok(2, 2, 0.10, 0.04)
    assert not gen.attempt_ok(2, 2, None, 0.04)
    assert gen.attempt_ok(2, 2, 0.10, None)
    assert gen.choose_attempt([2, 2], 2, [0.10, 0.02], 0.04) == 1
    assert gen.choose_attempt([2, 2], 2, [0.10, 0.02], None) == 0
    assert gen.choose_attempt([2, 2], 2) == 0
    assert gen.choose_attempt([2, 1, 2, 2], 2, [0.09, 0.01, 0.06, 0.06], 0.04) == 2
    assert gen.choose_attempt([1, 2, 2], 2, [None, None, None], 0.04) == 1
    with pytest.raises(ValueError):
        gen.choose_attempt([2, 2], 2, [0.1], 0.04)


SCENE = dict(scene_id="tier2_1typical__small_anchor__a064_s0000", sub_tier="tier2_1typical__small_anchor",
             variant="small_anchor", n_partners=1, anchor={"idx": 64, "name": "mouse"},
             labels=["mouse", "keyboard"], layout_boxes=[[450, 450, 550, 550], [100, 700, 900, 1000]],
             img_size=1024, prompt="A photorealistic photo of a mouse and a keyboard, in a natural everyday scene")


def test_small_anchor_prompt_bits_and_v1_wording_unchanged():
    block = gen.make_objects_block(SCENE, small_anchor=True).split("\n")
    assert block[0].startswith("  - computer mouse → ") and block[0].endswith(", " + gen.SMALL_ANCHOR_OBJECT_SUFFIX)
    assert "small and far from the camera" in block[0] and "small and far" not in block[1]
    assert gen.make_objects_block(SCENE) == gen.make_objects_block(SCENE, small_anchor=False)
    assert gen.positive_prompt_suffix(SCENE) == "the computer mouse is small in the distance"
    assert gen.positive_prompt_suffix(SCENE, display_names=False) == "the mouse is small in the distance"
    assert gen.apply_positive_suffix("A wide shot of a mouse.", "the mouse is small in the distance") \
        == "A wide shot of a mouse, the mouse is small in the distance."
    assert gen.apply_positive_suffix("abc", "") == "abc"
    up = gen.build_user_prompt(SCENE, small_anchor=True)
    assert "MINIMALIST" in up and "small and far from the camera" in up
    assert gen.build_user_prompt(SCENE) == gen.build_user_prompt(SCENE, small_anchor=False)
    assert gen.tier_descriptor(SCENE) == gen.tier_descriptor(dict(SCENE, sub_tier="tier2_1typical"))
    assert gen.tier_descriptor(dict(SCENE, sub_tier="tier_never_k3", n_partners=3)) \
        == gen.tier_descriptor(dict(SCENE, sub_tier="tier_never", n_partners=3)) \
        == ("in a highly unusual scene", "would normally never appear together")
    per = {"keyboard": 0.05}
    assert gen.sam3_min_score_for("zebra", True, True, per, 0.15, 0.10) == 0.10
    assert gen.sam3_min_score_for("zebra", False, True, per, 0.15, 0.10) == 0.15
    assert gen.sam3_min_score_for("zebra", True, False, per, 0.15, 0.10) == 0.15
    assert gen.sam3_min_score_for("keyboard", True, True, per, 0.15, 0.10) == 0.05


def _toy_coco():
    cats = [{"id": 74, "name": "mouse"}, {"id": 76, "name": "keyboard"}]
    imgs = [dict(id=i, file_name=f"s{i}.png", width=1024, height=1024, scene_id=f"s{i}",
                 labels_intended=["mouse", "keyboard"]) for i in range(1, 6)]
    anns = [dict(id=1, image_id=1, category_id=74, bbox=[0, 0, 100, 100], iscrowd=0),
            dict(id=2, image_id=1, category_id=76, bbox=[0, 0, 500, 500], iscrowd=0),
            dict(id=3, image_id=2, category_id=74, bbox=[0, 0, 400, 400], iscrowd=0),
            dict(id=4, image_id=3, category_id=74, bbox=[0, 0, 100, 100], iscrowd=0),
            dict(id=5, image_id=4, category_id=76, bbox=[0, 0, 100, 100], iscrowd=0),
            dict(id=6, image_id=5, category_id=74, bbox=[0, 0, 400, 400], iscrowd=0)]
    imgs[4]["anchor_rel_area"] = 0.03
    return dict(info={}, categories=cats, images=imgs, annotations=anns)


def test_filter_small_anchor_toy():
    out, st = fsa.filter_coco(_toy_coco(), {"s1": 0.01, "s2": 0.10}, max_rel=0.04)
    kept = {im["scene_id"]: im["anchor_rel_area"] for im in out["images"]}
    assert kept == {"s1": 0.01, "s3": pytest.approx(100 * 100 / 1024 ** 2, abs=1e-5), "s5": 0.03}
    assert st["imgs_in"] == 5 and st["imgs_out"] == 3
    assert st["dropped_anchor_too_big"] == 1 and st["dropped_anchor_missing"] == 1
    assert {a["image_id"] for a in out["annotations"]} == {1, 3, 5}
    assert out["info"]["small_anchor_filter"]["max_anchor_rel_area"] == 0.04
    assert fsa.anchor_rel_area_from_coco(_toy_coco(), _toy_coco()["images"][3], "mouse") is None


def test_filter_small_anchor_tier_dir_discovery_and_idempotent(tmp_path):
    for name in ("tier2_1typical__small_anchor", "tier2_1typical", "tier6_5typical"):
        d = tmp_path / name
        d.mkdir()
        json.dump(_toy_coco(), open(d / "annotations_clean.json", "w"))
    sa = tmp_path / "tier2_1typical__small_anchor"
    (sa / "s1_anns.json").write_text(json.dumps(dict(scene_id="s1", anchor_rel_area=0.01)))
    (sa / "s2_anns.json").write_text(json.dumps(dict(scene_id="s2", anchor_rel_area=0.10)))
    (sa / "_audit_anns.json").write_text("{}")
    assert [d.name for d in fsa.small_anchor_tier_dirs(tmp_path, "annotations_clean.json")] == [sa.name]
    assert [d.name for d in fsa.small_anchor_tier_dirs(tmp_path, "annotations_clean.json", ["tier6_5typical"])] \
        == ["tier6_5typical"]
    st = fsa.filter_tier_dir(sa, "annotations_clean.json", 0.04)
    assert st["imgs_out"] == 3 and st["fragments_with_area"] == 2
    assert (sa / "annotations_clean_pre_small_anchor.json").exists()
    st2 = fsa.filter_tier_dir(sa, "annotations_clean.json", 0.02)
    assert st2["imgs_in"] == 5 and st2["imgs_out"] == 2
    assert len(json.load(open(sa / "annotations_clean_pre_small_anchor.json"))["images"]) == 5
    assert len(json.load(open(tmp_path / "tier2_1typical" / "annotations_clean.json"))["images"]) == 5


def _run(args, cwd):
    r = subprocess.run([PY] + args, capture_output=True, text=True, cwd=str(cwd))
    assert r.returncode == 0, r.stdout[-2000:] + r.stderr[-2000:]
    return r


CATS = [{"id": 1, "name": "person"}, {"id": 2, "name": "dog"}, {"id": 3, "name": "zebra"}]


def _tier(root, name, n_complete, n_incomplete, labels=("person", "dog"), with_images=False):
    d = root / name
    (d / "images").mkdir(parents=True, exist_ok=True)
    images, anns, aid = [], [], 1
    for i in range(n_complete + n_incomplete):
        sid = f"{name}_s{i}"
        images.append(dict(id=i + 1, file_name=f"{sid}.png", width=8, height=8, scene_id=sid,
                           labels_intended=list(labels)))
        present = labels if i < n_complete else labels[:1]
        for lbl in present:
            anns.append(dict(id=aid, image_id=i + 1, category_id={c["name"]: c["id"] for c in CATS}[lbl],
                             bbox=[0, 0, 2, 2], area=4, iscrowd=0))
            aid += 1
        if with_images:
            from PIL import Image
            Image.new("RGB", (8, 8)).save(d / "images" / f"{sid}.png")
    json.dump(dict(info={}, categories=CATS, images=images, annotations=anns), open(d / "annotations.json", "w"))
    return [im["scene_id"] for im in images]


def test_make_complete_annotations_discovers_suffixed_dirs(tmp_path):
    root = tmp_path / "clean"
    _tier(root, "tier2_1typical__small_anchor", 2, 1)
    _tier(root, "tier_never_k3", 1, 1, labels=("person", "dog", "zebra"))
    _tier(root, "tier2_1typical", 3, 0)
    _tier(root, "tier6_5atypical", 0, 2)
    assert mca.discover_tiers(root) == ["tier2_1typical", "tier2_1typical__small_anchor", "tier6_5atypical",
                                        "tier_never_k3"]
    d_k3 = json.load(open(root / "tier_never_k3" / "annotations.json"))
    res = mca.complete_subset(d_k3, {"tier_never_k3_s0": "person", "tier_never_k3_s1": "person"})
    assert (res["n_images"], res["n_complete"], res["n_anchor_unannotated"]) == (2, 1, 0)
    res = mca.complete_subset(d_k3, {"tier_never_k3_s0": "zebra", "tier_never_k3_s1": "zebra"})
    assert res["n_anchor_unannotated"] == 1
    out_csv = tmp_path / "completeness.csv"
    _run(["strangebench/audit/make_complete_annotations.py", "--root", str(root), "--out-csv", str(out_csv),
          "--scene-specs", str(tmp_path / "missing_specs.json")], ROOT)
    rows = {r["tier"]: r for r in csv.DictReader(l for l in open(out_csv) if not l.startswith("#"))}
    assert list(rows) == ["tier2_1typical", "tier2_1typical__small_anchor", "tier6_5atypical", "tier_never_k3"]
    assert rows["tier2_1typical__small_anchor"]["n_complete"] == "2" and rows["tier6_5atypical"]["n_complete"] == "0"
    for t in rows:
        comp = json.load(open(root / t / "annotations_complete.json"))
        assert len(comp["images"]) == int(rows[t]["n_complete"])
        assert comp["info"]["completeness_filter"] == "every intended class annotated"


def test_build_v11_dataset_pairs_variant_tiers(tmp_path):
    clean = tmp_path / "clean"
    sids = []
    sids += _tier(clean, "tier6_5typical", 3, 1, with_images=True)
    sids += _tier(clean, "tier6_5atypical", 2, 0, with_images=True)
    sids += _tier(clean, "tier_never_k3", 2, 1, labels=("person", "dog", "zebra"), with_images=True)
    sids += _tier(clean, "tier2_1typical__small_anchor", 2, 0, with_images=True)
    sids += _tier(clean, "tier2_1atypical__small_anchor", 1, 1, with_images=True)
    sids += _tier(clean, "tier2_1typical", 2, 0, with_images=True)
    specs = tmp_path / "scene_specs.json"
    json.dump([dict(scene_id=s, anchor={"idx": 0, "name": "person"}, partners=[{"idx": 1, "name": "dog"}],
                    sub_tier=s.rsplit("_s", 1)[0], variant=v.variant_of_label(s.rsplit("_s", 1)[0]),
                    layout_source="solver") for s in sids], open(specs, "w"))
    dst = tmp_path / "out"
    r = _run(["strangebench/strict/build_dataset.py", "--source", "v2var", str(clean), str(specs),
              "--dst", str(dst)], ROOT)
    assert "variant tiers discovered" in r.stdout
    n_bal = {t: len(json.load(open(dst / "balanced" / t / "annotations.json"))["images"])
             for t in ("tier6_5typical", "tier6_5atypical", "tier_never_k3", "tier2_1typical__small_anchor",
                       "tier2_1atypical__small_anchor", "tier2_1typical")}
    assert n_bal == {"tier6_5typical": 2, "tier6_5atypical": 2,
                     "tier_never_k3": 2,
                     "tier2_1typical__small_anchor": 1, "tier2_1atypical__small_anchor": 1,
                     "tier2_1typical": 0}
    assert len(json.load(open(dst / "clean" / "tier6_5typical" / "annotations.json"))["images"]) == 4
    rows = {r["scene_id"]: r for r in csv.DictReader(open(dst / "tier_manifest.csv"))}
    assert rows["tier6_5typical_s0"]["variant"] == "k5" and rows["tier_never_k3_s0"]["variant"] == "never_clique"
    assert rows["tier2_1typical_s0"]["variant"] == ""
    stats = open(dst / "stats.csv").read()
    assert "# variant tiers: tier2_1atypical__small_anchor, tier2_1typical__small_anchor" in stats
    assert "tier_never_k3" in stats.split("singles keep all complete scenes")[1]
    tiers_in_stats = [r["tier"] for r in csv.DictReader(l for l in open(dst / "stats.csv") if not l.startswith("#"))]
    assert tiers_in_stats[:11] == list(v.V1_LABELS)
    assert tiers_in_stats[11:] == ["tier2_1atypical__small_anchor", "tier2_1typical__small_anchor",
                                   "tier6_5atypical", "tier6_5typical", "tier_never_k3"]
    assert (dst / "clean" / "tier1_natural_bg" / "annotations.json").exists()


COOCCUR = ROOT / "data" / "cooccurrence" / "coco_train"


@pytest.mark.skipif(not (COOCCUR / "marginal.npy").exists(), reason="co-occurrence dir not built (code/README.md, step 0)")
def test_stage1_tiers_end_to_end(tmp_path):
    out = tmp_path / "stage1"
    _run(["strangebench/scene_specs/select_scenes_and_layouts.py", "--cooccur-dir", str(COOCCUR), "--metric", "npmi",
          "--tiers", "tier6=2,never_k3=2,never_k4=2,tier2__small_anchor=2", "--layout-source", "qwen", "--no-llm",
          "--out-root", str(out), "--seed", "7", "--write-mode", "json"], ROOT)
    scenes = json.load(open(out / "scene_specs.json"))
    by_tier = {}
    for s in scenes:
        by_tier.setdefault(s["sub_tier"], []).append(s)
    assert {t: len(v_) for t, v_ in by_tier.items()} == {
        "tier6_5typical": 2, "tier6_5atypical": 2, "tier_never_k3": 2, "tier_never_k4": 2,
        "tier2_1typical__small_anchor": 2, "tier2_1atypical__small_anchor": 2}
    for s in by_tier["tier6_5typical"] + by_tier["tier6_5atypical"]:
        assert s["variant"] == "k5" and s["n_partners"] == 5 and len(s["labels"]) == 6
        assert s["layout_source"] == "solver"
    for k, t in ((3, "tier_never_k3"), (4, "tier_never_k4")):
        for s in by_tier[t]:
            assert s["variant"] == "never_clique" and s["mode"] == "never_clique" and s["n_partners"] == k
            assert s["is_strict_clique"] is True and s["clique_size"] == k and s["min_expected"] == 10.0
            assert s["clique_min_expected"] >= 10.0 and s["layout_source"] == "solver"
            assert s["base_sub_tier"] == "tier_never"
    for s in by_tier["tier2_1typical__small_anchor"] + by_tier["tier2_1atypical__small_anchor"]:
        assert s["variant"] == "small_anchor" and s["base_sub_tier"] == s["sub_tier"].split("__")[0]
        assert s["anchor_target_rel_area"] <= 0.02 + 1e-6 and len(s["layout_boxes_pre_shrink"]) == 2
        assert s["layout_source"] == "grid_fallback"
        b = s["layout_boxes"][0]
        assert (b[2] - b[0]) * (b[3] - b[1]) / 1024 ** 2 == pytest.approx(s["anchor_target_rel_area"], abs=1e-5)
    assert (out / "_stage1_partial" / "never_clique_report.json").exists()
    rep = json.load(open(out / "_stage1_partial" / "never_clique_report.json"))
    assert rep["summary"]["anchors_with_k3"] == 48 and rep["summary"]["anchors_with_k4"] == 28
    out2 = tmp_path / "stage1b"
    _run(["strangebench/scene_specs/select_scenes_and_layouts.py", "--cooccur-dir", str(COOCCUR), "--metric", "npmi",
          "--tiers", "tier6=2,never_k3=2,never_k4=2,tier2__small_anchor=2", "--layout-source", "qwen", "--no-llm",
          "--out-root", str(out2), "--seed", "7", "--write-mode", "json"], ROOT)
    assert (out2 / "scene_specs.json").read_bytes() == (out / "scene_specs.json").read_bytes()