File size: 6,414 Bytes
f3a3f9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Reproduce the six viewer tables and the Bloch-pair baseline."""

import argparse
from fractions import Fraction
import itertools
import json
from math import lcm
from pathlib import Path

import numpy as np

from frame_demo import estimate_frame, sample_vectors


ROOT = Path(__file__).resolve().parents[1]
SEED = 20261130
SAMPLES_PER_CLOUD = 8192
AXES = ((1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1))


def write_rows(path, rows):
    with path.open("w", encoding="utf-8", newline="\n") as result:
        for row in rows:
            result.write(json.dumps(row, ensure_ascii=False, allow_nan=False, separators=(",", ":")) + "\n")


def load_json(path):
    return json.loads(path.read_text(encoding="utf-8"))


def proper_frame(rng):
    q, upper = np.linalg.qr(rng.standard_normal((3, 3)))
    q *= np.where(np.diag(upper) < 0, -1, 1)
    if np.linalg.det(q) < 0:
        q[:, -1] *= -1
    return q


def bloch_points(cases, case_seeds, pairs, measurements):
    for row_id, ((h, amplitude, parity), case_seed) in enumerate(zip(cases, case_seeds, strict=True), start=1):
        case_id = f"pair-{row_id:03d}"
        frame_seed, source_seed, target_seed = case_seed.spawn(3)
        rng = np.random.default_rng(frame_seed)
        source_frame = proper_frame(rng)
        target_frame = proper_frame(rng) @ np.diag([1, parity, 1])
        truth = target_frame @ source_frame.T
        pairs.append(
            {"case_id": case_id, "frequency": h, "amplitude": amplitude,
             "points_per_cloud": SAMPLES_PER_CLOUD, "relative_determinant_sign": parity,
             "relative_frame_row_major": truth.ravel().tolist()}
        )
        estimates = []
        for cloud, frame, seed in (("source", source_frame, source_seed), ("target", target_frame, target_seed)):
            vectors = sample_vectors(SAMPLES_PER_CLOUD, h, amplitude, frame, np.random.default_rng(seed))
            estimate, _ = estimate_frame(vectors, h)
            estimates.append(estimate)
            for idx, (x, y, z) in enumerate(vectors.tolist()):
                yield {"case_id": case_id, "cloud": cloud, "sample_index": idx, "x": x, "y": y, "z": z}
        estimated = estimates[1] @ estimates[0].T
        measurements.append(
            {"case_id": case_id, "estimated_determinant_sign": int(np.linalg.slogdet(estimated)[0]),
             "relative_frame_frobenius_error": float(np.linalg.norm(estimated - truth))}
        )


def rotate_about_z(point, parameter):
    x, y, z = point
    cosine = (1-parameter**2)/(1+parameter**2)
    sine = 2*parameter/(1+parameter**2)
    return cosine*x-sine*y, sine*x+cosine*y, Fraction(z)


def rational_core():
    points = []
    for j, offset in enumerate(AXES, start=1):
        for child in AXES:
            rotated = rotate_about_z(child, Fraction(j, 64))
            points.append(tuple(a+b/10 for a, b in zip(offset, rotated, strict=True)))
    return points


def fractal_points(rng):
    source = rational_core()
    twin = [(x, -y, z) for x, y, z in source]
    for cloud, points in (("source", source), ("mirror", twin)):
        for idx, selected in enumerate(rng.permutation(len(points))):
            point = points[selected]
            denominator = lcm(*(coordinate.denominator for coordinate in point))
            numerators = [int(coordinate*denominator) for coordinate in point]
            yield {"cloud": cloud, "point_index": idx, "x": float(point[0]), "y": float(point[1]),
                   "z": float(point[2]), "x_num": numerators[0], "y_num": numerators[1],
                   "z_num": numerators[2], "denominator": denominator}


def build(output):
    directory = output / "data"
    directory.mkdir(parents=True, exist_ok=True)
    (output / "results").mkdir(parents=True, exist_ok=True)
    verification = load_json(ROOT / "results" / "verification.json")
    trials = load_json(ROOT / "results" / "frame_demo_results.json")
    combinations = list(itertools.product((1, 3, 7), (1/8, 1/16), (1, -1)))
    order_seed, fractal_seed, *seeds = np.random.SeedSequence(SEED).spawn(len(combinations) + 2)
    order = np.random.default_rng(order_seed).permutation(len(combinations))
    cases = [combinations[index] for index in order]
    pairs, measurements = [], []
    write_rows(directory / "bloch_pairs.jsonl", bloch_points(cases, seeds, pairs, measurements))
    write_rows(directory / "pair_cases.jsonl", pairs)
    write_rows(directory / "fractal_cores.jsonl", fractal_points(np.random.default_rng(fractal_seed)))
    write_rows(directory / "quantum_thresholds.jsonl", verification["radial_moment_flags"])
    write_rows(directory / "pauli_trials.jsonl", (
        {"seed": trials["seed"], "frequency": trials["h"], "amplitude": trials["amplitude"],
         "independent_blocks": trials["independent_blocks_per_trial"],
         "pauli_copies_per_axis": trials["Pauli_copies_per_axis_per_block"], **trial}
        for trial in trials["observed"]
    ))
    write_rows(directory / "transport_regressions.jsonl", (
        {"case_id": "two-point", "single_frame_squared_cost": verification["two_point"]["fixed_costs"][0],
         "one_sided_squared_cost": verification["two_point"]["source_independence"],
         "single_frame_exact_formula": "2", "one_sided_value_kind": "optimum"},
        {"case_id": "square-to-octagon", "single_frame_squared_cost": verification["square_octagon"]["squared_minimum"],
         "one_sided_squared_cost": verification["square_octagon"]["relaxed_cost"],
         "single_frame_exact_formula": "2 - 2*cos(pi/8)", "one_sided_value_kind": "optimum"},
        {"case_id": "continuous-entropy", "single_frame_squared_cost": 1/12,
         "one_sided_squared_cost": verification["continuous_entropic_gap"]["relaxed_zero_temperature_limit"],
         "single_frame_exact_formula": verification["continuous_entropic_gap"]["deterministic"],
         "one_sided_value_kind": "zero-regularization limit"},
    ))
    (output / "results" / "bloch_pair_baseline.json").write_text(
        json.dumps({"seed": SEED, "estimator": "untapered radial feature plus polar fit",
                    "observations": measurements}, indent=2, allow_nan=False) + "\n", encoding="utf-8", newline="\n"
    )


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=Path, default=ROOT)
    build(parser.parse_args().output.resolve())