File size: 3,150 Bytes
2abd452
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Verify released generated rows against their untouched raw batch tables."""

import hashlib
import json
from pathlib import Path

import pandas as pd


def validate():
    release = Path(__file__).resolve().parents[1]
    root = release / "generated/scddpm_rfr_fixed_range"
    rows = pd.read_csv(root / "Generated_Designs.csv.gz", float_precision="round_trip")
    manifest_path = release / "file_manifest.json"
    manifest = json.loads(manifest_path.read_text())

    # Validate the release's original raw files against the recorded hashes.
    hashed = 0
    for record in manifest:
        if not record["path"].startswith("generated/scddpm_rfr_fixed_range/raw/"):
            continue
        with (release / record["path"]).open("rb") as stream:
            observed = hashlib.file_digest(stream, "sha256").hexdigest()
        if observed != record["sha256"]:
            raise RuntimeError(f"Released raw file hash differs: {record['path']}")
        hashed += 1

    # Compare all decoded inputs and all saved outcome fields, not merely the
    # aggregate totals. Original evaluator indices are intentionally reused.
    compared = 0
    for voyage_range in (1000, 5000, 8000):
        for batch in range(10):
            batch_root = root / f"raw/range_{voyage_range}/batch_{batch:02d}"
            released = rows.loc[rows.Range_nmi.eq(voyage_range) & rows.Batch.eq(batch)].sort_values("Sample_In_Batch")
            for filename in ("Submitted_Designs_189.csv.gz", "Exact_Results.csv.gz"):
                original = pd.read_csv(batch_root / filename, float_precision="round_trip").sort_values("Sample_In_Batch")
                pd.testing.assert_frame_equal(
                    released.loc[:, original.columns].reset_index(drop=True),
                    original.reset_index(drop=True), check_dtype=False, check_exact=True,
                )
            compared += len(released)

    if compared != 3000 or rows.Sample_ID.duplicated().any():
        raise RuntimeError("The release lost or duplicated generated attempt identities")
    report = {"attempts_compared": compared, "raw_file_hashes_verified": hashed,
              "all_decoded_inputs_match_raw": True, "all_saved_outcomes_match_raw": True,
              "duplicate_sample_ids": int(rows.Sample_ID.duplicated().sum()),
              "completed": int(rows.Evaluator_Completed.eq(True).sum()),
              "feasible": int((rows.Evaluator_Completed.eq(True) & rows.Global_V1p1_Feasible.eq(True)).sum()),
              "evaluation_failures_retained": int(rows.Evaluator_Completed.eq(False).sum())}
    output = root / "provenance/Validation.json"
    output.write_text(json.dumps(report, indent=2) + "\n")
    relative = output.relative_to(release).as_posix()
    manifest = [row for row in manifest if row["path"] != relative]
    manifest.append({"path": relative, "bytes": output.stat().st_size,
                     "sha256": hashlib.sha256(output.read_bytes()).hexdigest()})
    manifest_path.write_text(json.dumps(sorted(manifest, key=lambda row: row["path"]), indent=2) + "\n")
    print(json.dumps(report, indent=2))


if __name__ == "__main__":
    validate()