File size: 6,239 Bytes
ef987bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import csv
import math
import pathlib
import re
import subprocess
import sys
from PIL import Image, ImageChops

root = pathlib.Path.cwd()


def _py_sources():
    _skip = {"tests", "logs", "output", "__pycache__", "node_modules", ".git"}
    return [
        p
        for p in root.rglob("*.py")
        if p.is_file()
        and not (set(p.relative_to(root).parts) & _skip)
        and p.name != "validate_outputs.py"
    ]


def run_candidate() -> None:
    scripts = [root / 'solve.py']
    assert scripts, "missing candidate python source"

    # Prefer scripts that look task-specific.
    scripts = sorted(
        scripts,
        key=lambda p: 0 if ("cifar" in p.name.lower() or "anomaly" in p.name.lower()) else 1,
    )
    failures = []
    for script in scripts[:2]:
        proc = subprocess.run(
            [sys.executable, str(script)],
            cwd=root,
            capture_output=True,
            text=True,
            timeout=60,
        )
        if proc.returncode == 0:
            return
        failures.append((script.name, proc.returncode, proc.stdout, proc.stderr))
    raise AssertionError(
        "candidate script(s) failed to execute:\n"
        + "\n".join(
            f"{name}: rc={rc}\nstdout={out}\nstderr={err}"
            for name, rc, out, err in failures
        )
    )


def validate_once() -> None:
    for name in [
        "cifar_tiny.csv",
        "report.html",
        "anomalies.csv",
        "cluster_centers.csv",
        "anomaly_grid.png",
    ]:
        p = root / name
        assert p.exists() and p.stat().st_size > 0, f"missing or empty {name}"

    rows = list(csv.DictReader((root / "cifar_tiny.csv").open(encoding="utf-8-sig")))
    assert len(rows) >= 1, "cifar_tiny.csv is empty"

    got = list(csv.DictReader((root / "anomalies.csv").open(encoding="utf-8-sig")))
    assert got, "anomalies.csv is empty"
    got_ids = [r.get("image_id") for r in got]
    got_ids = [g for g in got_ids if g is not None]
    centers = list(csv.DictReader((root / "cluster_centers.csv").open(encoding="utf-8-sig")))
    assert centers, "cluster_centers.csv is empty"
    points = [(float(c["r"]), float(c["g"]), float(c["b"])) for c in centers]
    scored = []
    for row in rows:
        pixel = (float(row["r"]), float(row["g"]), float(row["b"]))
        scored.append((min(math.dist(pixel, center) for center in points), row["image_id"]))
    scored.sort(key=lambda item: (-item[0], item[1]))
    required = max(1, math.ceil(len(rows) * 0.05))
    exp = [(image_id, distance) for distance, image_id in scored[:required]]
    exp_ids = [img for img, _ in exp]
    assert got_ids == exp_ids, (
        f"anomaly id mismatch; expected top 5% {exp_ids}, got {got_ids}"
    )

    exp_dist = {img: d for img, d in exp}
    for r in got:
        img = r.get("image_id")
        got_d = r.get("distance")
        assert img in exp_dist, f"unexpected anomaly row {img}"
        if img in exp_dist and got_d is not None:
            assert abs(float(got_d) - exp_dist[img]) <= 0.01, (
                f"distance mismatch for {img}: expected {exp_dist[img]}, got {got_d}"
            )

    by_id = {row["image_id"]: row for row in rows}
    with Image.open(root / "anomaly_grid.png") as raw_grid:
        assert raw_grid.format == "PNG", "anomaly_grid.png is not PNG"
        grid = raw_grid.convert("RGB")
        alpha = raw_grid.convert("RGBA").getchannel("A")
    assert grid.width >= 128 and grid.height >= 64 * len(got), (
        "anomaly_grid.png must contain a 64-pixel sample and center swatch per anomaly"
    )
    for index, item in enumerate(got):
        source_row = by_id[item["image_id"]]
        with Image.open(root / source_row["path"]) as raw_source:
            source = raw_source.convert("RGB").resize((64, 64), Image.Resampling.NEAREST)
        top = index * 64
        assert alpha.crop((0, top, 128, top + 64)).getextrema() == (255, 255), (
            f"comparison row is transparent for {item['image_id']}"
        )
        sample = grid.crop((0, top, 64, top + 64))
        assert ImageChops.difference(source, sample).getbbox() is None, (
            f"visualization does not show source pixels for {item['image_id']}"
        )
        rgb = tuple(float(source_row[channel]) for channel in ("r", "g", "b"))
        nearest = min(points, key=lambda center: math.dist(rgb, center))
        swatch = grid.crop((64, top, 128, top + 64))
        assert all(abs(extreme - expected) <= 3
                   for channel, expected in zip(swatch.getextrema(), nearest)
                   for extreme in channel), (
            f"visualization does not show the nearest center for {item['image_id']}"
        )

    report = (root / "report.html").read_text(encoding="utf-8", errors="ignore").lower()
    assert 'cifar' in report, 'report missing fixture identity'
    assert any(token in report for token in ('cluster', '聚类')), 'report missing clustering discussion'
    assert any(token in report for token in ('anomal', '异常')), 'report missing anomaly discussion'
    assert "k-means" in report or "kmeans" in report or 'k 均值' in report, "report missing K-Means"
    assert "5%" in report or "5 percent" in report or "farthest" in report or '最远' in report, (
        "report missing farthest 5 percent anomaly discussion"
    )



run_candidate()
validate_once()

# Anti-hardcode: inject a bright synthetic outlier and force re-run should change anomaly set.
fixture_path = root / "cifar_tiny.csv"
original = fixture_path.read_text(encoding="utf-8-sig")
injected_image = root / "images" / "injected.ppm"
assert not injected_image.exists(), "test injection path already exists"
mutated = (
    original.rstrip()
    + "\nimg_injected_mut,images/injected.ppm,255,255,255,super_anomaly\n"
)
try:
    injected_image.write_text("P3\n4 4\n255\n" + "255 255 255 " * 16 + "\n", encoding="ascii")
    fixture_path.write_text(mutated + "\n", encoding="utf-8")
    run_candidate()
    validate_once()
finally:
    fixture_path.write_text(original, encoding="utf-8")
    injected_image.unlink(missing_ok=True)
    run_candidate()
    validate_once()

print("validate_outputs OK: task_046 recomputes top-5% anomalies from fixture and adapts to mutated data")