File size: 9,267 Bytes
88152cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# Copyright 2026 Emile de Bruyn
# SPDX-License-Identifier: Apache-2.0

"""Validate the immutable published artifacts without third-party dependencies."""
import csv
import hashlib
import json
import re
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
SEGMENT = re.compile(r"^([A-Za-z0-9])(\d+)(?:-(\d+))?$")
GAP = re.compile(r"^(\d+)(?:-(\d+))?$")
CORRECTED_FILES = {"cluster_membership.csv", "contigs.csv", "contig_specifications.csv"}


def table(name):
    with (ROOT / name).open(newline="") as handle:
        return list(csv.DictReader(handle))


def residues(spec):
    result = set()
    for token in filter(None, spec.split(";")):
        match = SEGMENT.fullmatch(token)
        if not match:
            raise ValueError(f"invalid residue segment {token!r}")
        chain, first, last = match.groups()
        start, end = int(first), int(last or first)
        if start > end:
            raise ValueError(f"reversed residue segment {token!r}")
        segment = {(chain, i) for i in range(start, end + 1)}
        if result & segment:
            raise ValueError(f"overlapping residue segment {token!r}")
        result.update(segment)
    return result


def pdb_residues(path):
    found = set()
    ca = set()
    with path.open() as handle:
        for line in handle:
            if line.startswith("ATOM  "):
                if len(line) < 54 or line[26] != " ":
                    raise ValueError(f"{path.name}: malformed ATOM or insertion code")
                key = (line[21], int(line[22:26]))
                for start in (30, 38, 46):
                    float(line[start:start + 8])
                found.add(key)
                if line[12:16].strip() == "CA":
                    ca.add(key)
    if not found or found != ca:
        raise ValueError(f"{path.name}: missing ATOM records or CA atoms")
    return found


def ca_coordinates(path):
    coordinates = {}
    with path.open() as handle:
        for line in handle:
            if line.startswith("ATOM  ") and line[12:16].strip() == "CA":
                key = (line[21], int(line[22:26]))
                xyz = tuple(float(line[i:i + 8]) for i in (30, 38, 46))
                coordinates.setdefault(key, set()).add(xyz)
    return coordinates


def historical_bytes(path, data):
    """Reverse only the documented changes to compare to the submission."""
    if path == "cluster_membership.csv":
        lines = data.splitlines(keepends=True)
        converted = [lines[0]]
        for line in lines[1:]:
            fields = line.split(b",")
            fields[1] = re.sub(rb"_c(\d+)$", rb"_v\1", fields[1])
            converted.append(b",".join(fields))
        return b"".join(converted)
    if path in {"contigs.csv", "contig_specifications.csv"}:
        lines = data.splitlines(keepends=True)
        changed = 0
        for index, line in enumerate(lines):
            if line.startswith(b"1A22_PS01352_c1,"):
                expected = 2 if path == "contig_specifications.csv" else 1
                if line.count(b"21-25") != expected:
                    raise ValueError(f"{path}: unexpected corrected contig")
                lines[index] = line.replace(b"21-25", b"25-25")
                changed += 1
        if changed != 1:
            raise ValueError(f"{path}: expected exactly one corrected case")
        return b"".join(lines)
    return data


def validate():
    cases = table("test_cases.csv")
    metadata = table("motif_cases_metadata_croissant.csv")
    contigs = table("contigs.csv")
    specs = table("contig_specifications.csv")
    clusters = table("cluster_membership.csv")
    assert len(cases) == len(metadata) == len(contigs) == len(specs) == 220
    assert len({r["motif_entry"] for r in metadata}) == 174
    ids = [r["pdb_id"] for r in cases]
    assert len(set(ids)) == 220
    for rows, key in ((metadata, "benchmark_pdb_id"), (contigs, "benchmark_pdb_id"),
                      (specs, "problem")):
        assert len({r[key] for r in rows}) == 220 and {r[key] for r in rows} == set(ids)
    assert {r["benchmark_pdb_id"] for r in clusters} == set(ids)
    meta = {r["benchmark_pdb_id"]: r for r in metadata}
    spec = {r["problem"]: r for r in specs}
    assert len({r["case_id"] for r in metadata}) == 220
    for row in contigs:
        assert row["case_id"] == meta[row["benchmark_pdb_id"]]["case_id"]
    representatives = [r for r in clusters if r["role"] == "representative"]
    assert len(representatives) == 220
    assert {r["benchmark_pdb_id"] for r in representatives} == set(ids)
    for row in clusters:
        case = meta[row["benchmark_pdb_id"]]
        assert row["case_id"] == case["case_id"], row["benchmark_pdb_id"]
        if row["role"] == "representative":
            assert row["motif_entry"] == case["motif_entry"]
        else:
            assert row["role"] == "member"
    assert len({(r["benchmark_pdb_id"], r["motif_entry"]) for r in clusters}) == len(clusters)
    original_contigs = {r["benchmark_pdb_id"]: r["contigs"] for r in contigs}
    assert {p.stem for p in (ROOT / "motif_pdbs").glob("*.pdb")} == set(ids)
    assert {p.stem for p in (ROOT / "original_pdbs").glob("*.pdb")} == set(ids)
    infeasible = []
    for row in cases:
        case = row["pdb_id"]
        motif = residues(row["motif_residues"])
        assert residues(row["redesign_idcs"]) <= motif, case
        assert motif == residues(meta[case]["motif_segments"]), case
        assert residues(row["redesign_idcs"]) == residues(meta[case]["redesignable_segments"]), case
        assert motif == pdb_residues(ROOT / "motif_pdbs" / f"{case}.pdb"), case
        assert spec[case]["contig_original"] == original_contigs[case], case
        assert int(spec[case]["length"]) == int(row["length"]), case
        assert int(meta[case]["motif_length"]) == len(motif), case
        source_ca = ca_coordinates(ROOT / "original_pdbs" / f"{case}.pdb")
        motif_ca = ca_coordinates(ROOT / "motif_pdbs" / f"{case}.pdb")
        original_segments = meta[case]["motif_segments_original"].split(";")
        normalized_segments = row["motif_residues"].split(";")
        assert len(original_segments) == len(normalized_segments), case
        for original, normalized in zip(original_segments, normalized_segments):
            old, new = sorted(residues(original)), sorted(residues(normalized))
            assert len(old) == len(new), case
            for old_key, new_key in zip(old, new):
                assert source_ca.get(old_key, set()) & motif_ca.get(new_key, set()), case
        fixed, minimum, maximum = set(), 0, 0
        for token in spec[case]["contig"].split(";"):
            gap = GAP.fullmatch(token)
            if gap:
                lo, hi = gap.groups()
                minimum += int(lo)
                maximum += int(hi or lo)
                assert int(lo) <= int(hi or lo), case
            else:
                fixed |= residues(token)
        assert fixed == motif, case
        if not minimum + len(motif) <= int(row["length"]) <= maximum + len(motif):
            infeasible.append(case)
    if infeasible:
        raise ValueError(f"infeasible contigs: {infeasible}")
    with (ROOT / "provenance/huggingface-manifest.json").open() as handle:
        manifest = {entry["path"]: entry for entry in json.load(handle) if entry["type"] == "file"}
    with (ROOT / "provenance/release-sha256.txt").open() as handle:
        release_hashes = dict(line.rstrip("\n").split("  ", 1)[::-1] for line in handle)
    checked = set()
    changed = set()
    with (ROOT / "provenance/published-sha256.txt").open() as handle:
        for line in handle:
            expected, path = line.rstrip("\n").split("  ", 1)
            data = (ROOT / path).read_bytes()
            if hashlib.sha256(data).hexdigest() != release_hashes[path]:
                raise ValueError(f"release artifact checksum mismatch: {path}")
            historical = historical_bytes(path, data)
            if historical != data:
                changed.add(path)
            if hashlib.sha256(historical).hexdigest() != expected:
                raise ValueError(f"unexpected difference from published artifact: {path}")
            git_object = hashlib.sha1(b"blob " + str(len(historical)).encode() + b"\0" + historical).hexdigest()
            entry = manifest[path]
            if entry["size"] != len(historical) or entry["oid"] != git_object:
                raise ValueError(f"published Hugging Face object mismatch: {path}")
            checked.add(path)
    if checked != set(manifest) - {".gitattributes", "LICENSE", "README.md"}:
        raise ValueError("published artifact list does not match the Hugging Face manifest")
    if checked != set(release_hashes) or changed != CORRECTED_FILES:
        raise ValueError(f"unexpected release artifact list or changed files: {changed}")
    print("Validated 220 cases, 174 patterns, feasible contigs and 445 release hashes.")
    print("Historical regression: exactly three documented tables differ from the submission.")


if __name__ == "__main__":
    try:
        validate()
    except (AssertionError, ValueError, OSError, KeyError) as exc:
        print(f"Validation failed: {exc}", file=sys.stderr)
        sys.exit(1)