File size: 5,249 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
import csv
import math
import os
import pathlib
import struct
import subprocess
import sys


root = pathlib.Path.cwd()
ARTIFACTS = ("anomalies.csv", "cluster_centers.csv", "anomaly_grid.png", "report.html")


def clean_environment():
    env = os.environ.copy()
    for name in (
        "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY",
        "http_proxy", "https_proxy", "all_proxy", "no_proxy",
    ):
        env.pop(name, None)
    env["PYTHONHASHSEED"] = "0"
    return env


def run_candidate() -> None:
    scripts = [root / 'solve.py']
    assert scripts, "missing candidate Python source"
    scripts.sort(key=lambda p: ("cifar" not in p.name.lower(), "anomal" not in p.name.lower(), str(p)))
    failures = []
    for script in scripts[:3]:
        proc = subprocess.run(
            [sys.executable, str(script)], cwd=root, capture_output=True,
            text=True, timeout=60, env=clean_environment(),
        )
        if proc.returncode == 0 and all(
            (root / name).is_file()
            for name in ARTIFACTS
        ):
            return
        failures.append(f"{script}: rc={proc.returncode}: {proc.stderr[-300:]}")
    raise AssertionError("candidate did not produce required artifacts: " + " | ".join(failures))


def read_csv(name: str):
    with (root / name).open(encoding="utf-8-sig", newline="") as handle:
        return list(csv.DictReader(handle))


def case_1_top_five_percent_contract() -> None:
    # ENHANCED_CASE_1: the anomaly file represents exactly the farthest 5% population.
    source_rows = read_csv("cifar_tiny.csv")
    anomaly_rows = read_csv("anomalies.csv")
    required = max(1, math.ceil(len(source_rows) * 0.05))
    assert len(anomaly_rows) == required, (
        f"expected {required} anomaly rows for {len(source_rows)} inputs, got {len(anomaly_rows)}"
    )
    source_ids = {row["image_id"] for row in source_rows}
    result_ids = [row.get("image_id") for row in anomaly_rows]
    assert len(set(result_ids)) == len(result_ids), "anomaly image ids must be unique"
    assert set(result_ids) <= source_ids, "anomalies.csv contains an id absent from the fixture"
    for row in anomaly_rows:
        distance = float(row["distance"])
        assert math.isfinite(distance) and distance >= 0, "anomaly distances must be finite and non-negative"


def case_2_center_table_is_well_formed() -> None:
    # ENHANCED_CASE_2: the chosen K and reported RGB centers form a usable center table.
    source_rows = read_csv("cifar_tiny.csv")
    centers = read_csv("cluster_centers.csv")
    assert 2 <= len(centers) < len(source_rows), "chosen K must be non-trivial and smaller than sample count"
    required_columns = {"cluster", "r", "g", "b"}
    assert required_columns <= set(centers[0]), "center table must contain cluster,r,g,b columns"
    cluster_ids = [row["cluster"] for row in centers]
    assert len(set(cluster_ids)) == len(cluster_ids), "cluster identifiers must be unique"
    center_values = []
    for index, center in enumerate(centers):
        point = []
        for channel in ("r", "g", "b"):
            value = float(center[channel])
            assert math.isfinite(value), f"center {index} {channel} is not finite"
            assert 0 <= value <= 255, f"center {index} {channel}={value} is outside the RGB domain"
            point.append(value)
        center_values.append(tuple(point))
    assert len(set(center_values)) == len(center_values), "reported centers must not be duplicates"
    # A well-shaped arbitrary palette is not a fitted K-Means model. At a
    # converged Lloyd solution, each non-empty center is its assigned mean.
    groups = [[] for _ in center_values]
    for row in source_rows:
        point = tuple(float(row[channel]) for channel in ('r', 'g', 'b'))
        nearest = min(range(len(center_values)), key=lambda i: (math.dist(point, center_values[i]), i))
        groups[nearest].append(point)
    for center, group in zip(center_values, groups):
        assert group, 'reported cluster must contain at least one source image'
        mean = tuple(sum(point[j] for point in group) / len(group) for j in range(3))
        assert math.dist(center, mean) <= 0.01, 'center is not the mean of its nearest-assigned images'


def png_size(path: pathlib.Path) -> tuple[int, int]:
    data = path.read_bytes()
    assert data[:8] == b"\x89PNG\r\n\x1a\n", "anomaly_grid.png is not a PNG"
    assert data[12:16] == b"IHDR" and len(data) >= 24, "PNG has no valid IHDR"
    return struct.unpack(">II", data[16:24])


def case_3_visualization_is_concrete() -> None:
    # ENHANCED_CASE_3: the saved PNG has a concrete canvas.
    width, height = png_size(root / "anomaly_grid.png")
    assert width > 0 and height > 0, "anomaly visualization must have a non-empty canvas"


run_candidate()
cases = [
    ("ENHANCED_CASE_1", case_1_top_five_percent_contract),
    ("ENHANCED_CASE_2", case_2_center_table_is_well_formed),
    ("ENHANCED_CASE_3", case_3_visualization_is_concrete),
]
failed = []
for case_id, validator in cases:
    try:
        validator()
        print(f"{case_id}: PASS")
    except Exception as exc:
        failed.append(case_id)
        print(f"{case_id}: FAIL: {exc}", file=sys.stderr)
if failed:
    raise SystemExit(1)