File size: 7,303 Bytes
f4fe362
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Export the published finite-audit results into deterministic flat CSV tables.

Python 3.10+, standard library only. The source JSON remains authoritative.
No simulation, training, or new evidence is created by this conversion.
"""
from __future__ import annotations

import argparse
import csv
import json
import math
from pathlib import Path


def compact(value: object) -> str:
    return json.dumps(value, ensure_ascii=False, separators=(",", ":"), allow_nan=False)


def require(condition: bool, message: str) -> None:
    if not condition:
        raise ValueError(message)


def tables(results: dict) -> dict[str, list[dict]]:
    """Validate source shape and produce five evaluation-fixture tables."""
    enumeration = results["enumeration"]
    rank = results["additive_rank_regime"]
    cue = results["delayed_cue_observability"]
    coherence = results["program_coherence"]
    interventions = results["nonunique_fillings"]["candidate_interventions"]
    require(enumeration["all_complexes_including_empty"] == 167, "Unexpected complex count")
    require(enumeration["nested_pairs"] == 7413, "Unexpected nested-pair count")
    require(enumeration["failures"] == 0 and rank["failures"] == 0, "Source reports audit failures")
    require(rank["seed"] == results["seed"] == 314159, "Unexpected random seed")
    require(rank["instances"] == len(rank["instances_detail"]) == 100, "Expected 100 rank-cover instances")
    require(len(interventions) == 4, "Expected four interventions")
    require(cue["one_bit_machine_count"] == len(cue["all_machines"]) == 16, "Expected 16 one-bit machines")
    require(len(coherence["programs"]) == 3, "Expected three coherent-program examples")

    rank_rows = []
    for item in rank["instances_detail"]:
        d = item["d"]
        require(d in (1, 2, 3, 4), "Unexpected vector-space dimension")
        require(len(item["blocks"]) == len(item["costs"]) == rank["candidates_per_instance"] == 6,
                "Candidate count mismatch")
        require(all(isinstance(c, int) and c > 0 for c in item["costs"]), "Nonpositive cost")
        require(all(isinstance(v, int) and 0 <= v < 2 ** d for block in item["blocks"] for v in block),
                "Vector bitmask outside its dimension")
        require(item["optimal_cost"] > 0 and math.isclose(item["ratio"], item["greedy_cost"] / item["optimal_cost"]),
                "Cost-ratio mismatch")
        require(item["ratio"] <= item["H_d"] + 1e-12, "Greedy harmonic bound fails")
        rank_rows.append({
            "id": f"rank-d{d}-i{item['instance']:02d}", "d": d, "instance": item["instance"],
            "blocks_json": compact(item["blocks"]), "costs_json": compact(item["costs"]),
            "optimal_cost": item["optimal_cost"], "greedy_cost": item["greedy_cost"],
            "ratio": item["ratio"], "H_d": item["H_d"], "H_d_exact": item["H_d_exact"],
            "greedy_order_json": compact(item["greedy_order"]), "seed": rank["seed"],
        })

    intervention_rows = [{
        "id": f"intervention-{item['name']}", "name": item["name"],
        "added_simplices_json": compact(item["added_simplices"]),
        "hits_one_witness_support": item["hits_one_witness_support"],
        "contains_one_complete_witness_support": item["contains_one_complete_witness_support"],
        "actually_kills_fixed_cycle": item["actually_kills_fixed_cycle"],
        "fillable_dimension_after": item["fillable_dimension_after"],
    } for item in interventions]

    cue_rows = []
    for item in cue["all_machines"]:
        encoder, decoder, outputs = item["cue_to_memory"], item["memory_to_action"], item["outputs_by_cue"]
        require(all(len(v) == 2 and all(x in (0, 1) for x in v) for v in (encoder, decoder, outputs)),
                "Malformed binary machine")
        require(outputs == [decoder[encoder[h]] for h in (0, 1)], "Machine-output mismatch")
        require(item["balanced_accuracy"] == sum(outputs[h] == h for h in (0, 1)) / 2,
                "Machine-accuracy mismatch")
        cue_rows.append({
            "id": f"cue-e{encoder[0]}{encoder[1]}-d{decoder[0]}{decoder[1]}",
            "encode_cue_0": encoder[0], "encode_cue_1": encoder[1],
            "decode_state_0": decoder[0], "decode_state_1": decoder[1],
            "output_cue_0": outputs[0], "output_cue_1": outputs[1],
            "balanced_accuracy": item["balanced_accuracy"],
            "perfect": item["balanced_accuracy"] == 1.0,
        })
    require(sum(row["perfect"] for row in cue_rows) == cue["perfect_one_bit_machine_count"] == 2,
            "Expected exactly two perfect machines")

    coherence_rows = [{
        "id": f"coherence-{item['program']}", "program": item["program"],
        "cost": item["cost"], "cost_is_stipulated": True, "betti_H1": item["betti_H1"],
        "fixed_square_cycle_is_boundary": item["fixed_square_cycle_is_boundary"],
        "example_budget": coherence["budget"],
        "affordable_at_example_budget": item["cost"] <= coherence["budget"],
    } for item in coherence["programs"]]

    audit_rows = []
    for suite, values, fields in (
        ("enumeration", enumeration, ("identity_checks", "boundary_squared_checks", "cycle_filling_witness_checks")),
        ("additive_rank_regime", rank, ("submodularity_checks", "monotonicity_checks", "quotient_residual_checks",
                                      "optimal_cover_enumerations", "weighted_greedy_bound_checks")),
    ):
        for field in fields:
            audit_rows.append({
                "id": f"audit-{suite}-{field}", "suite": suite, "metric": field,
                "check_count": values[field], "suite_failure_count": values["failures"],
                "source_json_pointer": f"/{suite}/{field}",
            })

    result = {"rank_cover": rank_rows, "interventions": intervention_rows, "delayed_cue": cue_rows,
              "program_coherence": coherence_rows, "audit_summary": audit_rows}
    for name, rows in result.items():
        require(len({row["id"] for row in rows}) == len(rows), f"Duplicate row IDs in {name}")
    return result


def write_tables(results: dict, output: Path) -> dict[str, int]:
    converted = tables(results)
    output.mkdir(parents=True, exist_ok=True)
    for name, rows in converted.items():
        with (output / f"{name}.csv").open("w", encoding="utf-8", newline="") as stream:
            writer = csv.DictWriter(stream, fieldnames=list(rows[0]), lineterminator="\n")
            writer.writeheader()
            writer.writerows({key: str(value).lower() if isinstance(value, bool) else value
                             for key, value in row.items()} for row in rows)
    return {name: len(rows) for name, rows in converted.items()}


def main() -> None:
    root = Path(__file__).resolve().parents[1]
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--source", type=Path, default=root / "experiments" / "results.json")
    parser.add_argument("--output", type=Path, default=root / "data")
    args = parser.parse_args()
    results = json.loads(args.source.read_text(encoding="utf-8"))
    counts = write_tables(results, args.output)
    print(json.dumps({"row_counts": counts, "total_rows": sum(counts.values())}, sort_keys=True))


if __name__ == "__main__":
    main()