File size: 5,929 Bytes
248a358
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Create the Hugging Face Dataset Viewer records from exact verifier output."""
import argparse
import json
from fractions import Fraction
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
DEFAULT_SOURCE = ROOT / "code" / "verification.json"
DEFAULT_OUTPUT = ROOT / "data" / "results.jsonl"


def record(case_id, experiment, quantity, *, units, exact=None, interval=None,
           fractions=None, alpha=None, degree=None, trial_rank=None, test_rank=None,
           time_steps=None, observations, norm=None):
    """Use a fixed schema. Store exact rationals as strings."""
    if (exact is None) == (interval is None):
        raise ValueError("A record must have either an exact value or an interval")
    if exact is not None:
        Fraction(exact)
    if interval is not None and Fraction(interval[0]) > Fraction(interval[1]):
        raise ValueError(f"Invalid interval: {case_id}")
    if fractions is not None:
        lower, upper = map(Fraction, fractions)
        if not Fraction(interval[0]) <= 100*lower <= 100*upper <= Fraction(interval[1]):
            raise ValueError(f"Percent bounds fail to enclose exact fractions: {case_id}")
    return {
        "case_id": case_id, "experiment": experiment, "quantity": quantity,
        "units": units, "shear_alpha": alpha, "basis_index": degree,
        "trial_rank": trial_rank, "test_rank": test_rank, "time_steps": time_steps,
        "observations": observations, "norm": norm, "value_exact": exact,
        "lower": float(interval[0]) if interval is not None else None,
        "upper": float(interval[1]) if interval is not None else None,
        "lower_bound_exact": fractions[0] if fractions is not None else None,
        "upper_bound_exact": fractions[1] if fractions is not None else None,
    }


def rows(result):
    for enclosure in [*result["rotation_bounds"], result["shear_0.01_continuum"]]:
        with_shear = enclosure is result["shear_0.01_continuum"]
        alpha, norm = ("1/100", "kinetic_plus_shear") if with_shear else ("0", "L2")
        degree = enclosure["degree_parameter"]
        yield record(f"proposal-{norm}-degree-{degree}", "rotational_proposal",
                     "reduction_in_squared_mismatch_vs_affine", units="percent",
                     interval=enclosure["percentage_interval"],
                     fractions=[enclosure["lower_fraction"], enclosure["upper_fraction"]],
                     alpha=alpha, degree=degree, trial_rank=enclosure["lower_space_rank"],
                     test_rank=enclosure["upper_space_rank"], observations="zero_face_flux",
                     norm=norm)

    recovery = result["measured_circulation_recovery"]
    for key, enclosure in recovery["reduction"].items():
        alpha, norm = ("0", "L2") if key == "kinetic" else ("1/100", "kinetic_plus_shear")
        yield record(f"recovery-{norm}", "measured_circulation",
                     "reduction_in_squared_error_vs_zero_trace_affine", units="percent",
                     interval=enclosure["percentage_interval"],
                     fractions=[enclosure["lower_fraction"], enclosure["upper_fraction"]],
                     alpha=alpha, degree=4,
                     observations="zero_face_flux_and_three_independent_angular_components",
                     norm=norm)

    joint = result["closed_cell_full_objective"]
    for field, quantity, units in [
        ("optimal_density_interval", "optimal_density", "reference_density"),
        ("optimal_objective_interval", "optimal_objective", "reference_energy"),
        ("objective_improvement_percent", "objective_reduction_vs_affine", "percent"),
    ]:
        yield record("joint-" + quantity, "joint_density_and_momentum", quantity,
                     units=units, interval=joint[field], alpha="0", degree=4, time_steps=1,
                     observations="zero_face_flux_and_unit_density_anchors", norm="L2")

    time = result["time"]
    for steps, energy in time["root_mobility_energies"].items():
        yield record("birth-root-" + steps, "pure_birth_from_vacuum", "root_mobility_energy",
                     units="reference_energy", exact=energy, time_steps=int(steps),
                     observations="prescribed_proportional_endpoints")
    yield record("birth-arithmetic-1", "pure_birth_from_vacuum", "arithmetic_midpoint_energy",
                 units="reference_energy", exact=time["arithmetic_one_step"], time_steps=1,
                 observations="prescribed_proportional_endpoints")

    certificate = result["conic_certificate"]
    for field in ("primal", "dual_at_tau_1", "dual_at_tau_2", "total_gap"):
        yield record("source-" + field, "scalar_source_certificate", field,
                     units="reference_energy", exact=certificate[field], time_steps=1,
                     observations="scalar_gap_decomposition_parameters" if field == "total_gap"
                     else "scalar_exact_primal_and_dual_parameters")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--source", type=Path, default=DEFAULT_SOURCE)
    parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
    parser.add_argument("--check", action="store_true")
    args = parser.parse_args()
    values = list(rows(json.loads(args.source.read_text(encoding="utf-8"))))
    if len({r["case_id"] for r in values}) != len(values):
        raise ValueError("Duplicate dataset case ID")
    output = "".join(json.dumps(row, ensure_ascii=False) + "\n" for row in values)
    if args.check:
        if args.output.read_text(encoding="utf-8") != output:
            raise SystemExit("Dataset viewer records differ from exact verifier output")
        print(f"Verified {len(values)} Dataset Viewer records.")
    else:
        args.output.write_text(output, encoding="utf-8")
        print(f"Wrote {len(values)} Dataset Viewer records.")


if __name__ == "__main__":
    main()