File size: 11,478 Bytes
3b80460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
"""Explicit D4 realization on the unit square; no affine-box search.

The fundamental boundary sector is q(t)=(1/2,t), 0<t<1/2.
For every bin of t choose one sign.  A D4 image is selected precisely
when its determinant times the bin sign is positive.  All corner and
edge-midpoint points are added.  Reflection in any normal axis with
angle 0, pi/4, pi/2, or 3pi/4 reverses determinant and preserves the bin,
so every line in those four directional audits is hit exactly.

Each open fundamental bin has eight images, exactly four selected;
the barrier length is therefore exactly 2.  The code evaluates finite
formulas in float64.  Sampling-based line statistics are diagnostics,
not opacity proofs or certified continuum error bounds.
"""
from __future__ import annotations

import math
from typing import Mapping

import numpy as np

AUDIT_NORMALS = np.arange(4, dtype=float) * (math.pi / 4)
FIXED_POINTS = np.array([
    [-.5, -.5], [-.5, 0.], [-.5, .5], [0., -.5],
    [0., .5], [.5, -.5], [.5, 0.], [.5, .5],
])

# h=x*y*(x*x-y*y), r2=x*x+y*y.  The last three positive costs
# distinguish the two determinant classes.  Lower-degree moments alone
# are exactly balanced by D4 symmetry and would be insufficient tests.
POLYNOMIAL_TESTS = {
    "mass": {(0, 0): 1.},
    "x": {(1, 0): 1.},
    "y": {(0, 1): 1.},
    "x_squared": {(2, 0): 1.},
    "xy": {(1, 1): 1.},
    "1+32h": {(0, 0): 1., (3, 1): 32., (1, 3): -32.},
    "1+64h_r2": {(0, 0): 1., (5, 1): 64., (1, 5): -64.},
    "1+128h_r4": {(0, 0): 1., (7, 1): 128., (5, 3): 128.,
                    (3, 5): -128., (1, 7): -128.},
}
NONTRIVIAL_TESTS = ("1+32h", "1+64h_r2", "1+128h_r4")


def _validate_bits(bits):
    b = np.asarray(bits, dtype=np.int8)
    if b.ndim != 1 or not len(b) or not np.all((b == -1) | (b == 1)):
        raise ValueError("bits must be a nonempty one-dimensional +/-1 array")
    return b


def group_sectors(bin_count):
    """Return all eight D4 images, shape (8,M,2,2), and determinants."""
    if int(bin_count) != bin_count or bin_count < 1:
        raise ValueError("bin_count must be a positive integer")
    m = int(bin_count)
    cuts = np.linspace(0., .5, m + 1)
    sectors, determinants = [], []
    for vertical in (True, False):
        for sx in (-1, 1):
            for sy in (-1, 1):
                segments = np.empty((m, 2, 2), dtype=float)
                if vertical:
                    segments[:, :, 0] = sx * .5
                    segments[:, 0, 1] = sy * cuts[:-1]
                    segments[:, 1, 1] = sy * cuts[1:]
                    determinant = sx * sy
                else:
                    segments[:, 0, 0] = sx * cuts[:-1]
                    segments[:, 1, 0] = sx * cuts[1:]
                    segments[:, :, 1] = sy * .5
                    determinant = -sx * sy
                sectors.append(segments)
                determinants.append(determinant)
    return np.asarray(sectors), np.asarray(determinants, dtype=np.int8)


def square_barrier(bits, include_fixed=True):
    """Construct all selected closed segments; fixed points are degenerate pieces."""
    b = _validate_bits(bits)
    sectors, determinant = group_sectors(len(b))
    selected = sectors[determinant[:, None] * b[None, :] > 0]
    if include_fixed:
        selected = np.concatenate((selected, np.repeat(FIXED_POINTS[:, None, :], 2, axis=1)))
    return selected


def segment_lengths(segments):
    s = np.asarray(segments, dtype=float)
    return np.linalg.norm(s[:, 1] - s[:, 0], axis=1)


def integrate_monomial(segments, x_power, y_power):
    """Exact axis-aligned monomial integrals, evaluated in float64, per segment."""
    s = np.asarray(segments, dtype=float)
    if s.shape[-2:] != (2, 2):
        raise ValueError("segments must end in dimensions (2,2)")
    i, j = int(x_power), int(y_power)
    if i < 0 or j < 0:
        raise ValueError("monomial powers must be nonnegative")
    vertical = np.abs(s[..., 1, 0] - s[..., 0, 0]) < 1e-14
    horizontal = np.abs(s[..., 1, 1] - s[..., 0, 1]) < 1e-14
    if not np.all(vertical | horizontal):
        raise ValueError("this exact integrator accepts only axis-aligned pieces")
    xlo = np.minimum(s[..., 0, 0], s[..., 1, 0])
    xhi = np.maximum(s[..., 0, 0], s[..., 1, 0])
    ylo = np.minimum(s[..., 0, 1], s[..., 1, 1])
    yhi = np.maximum(s[..., 0, 1], s[..., 1, 1])
    v = s[..., 0, 0] ** i * (yhi ** (j + 1) - ylo ** (j + 1)) / (j + 1)
    h = s[..., 0, 1] ** j * (xhi ** (i + 1) - xlo ** (i + 1)) / (i + 1)
    return np.where(vertical, v, h)


def integrate_polynomial(segments, polynomial: Mapping):
    s = np.asarray(segments, dtype=float)
    out = np.zeros(s.shape[:-2], dtype=float)
    for (i, j), coefficient in polynomial.items():
        out += coefficient * integrate_monomial(s, i, j)
    return out


def cost_model(bin_count, polynomial):
    """Cost = half_full_cost + dot(bits, coefficients), exactly as finite formulas."""
    sectors, determinant = group_sectors(bin_count)
    integrals = integrate_polynomial(sectors, polynomial)
    full_cost = float(integrals.sum())
    coefficients = .5 * (determinant[:, None] * integrals).sum(axis=0)
    return {
        "full_cost": full_cost,
        "half_full_cost": full_cost / 2,
        "coefficients": coefficients,
        "independent_bit_variance": float(coefficients @ coefficients),
    }


def choose_balanced_bits(bin_count, seed, candidates=32):
    """Reproducible finite search; this is not an optimizer or a monotonicity guarantee."""
    if candidates < 1:
        raise ValueError("candidates must be positive")
    rng = np.random.default_rng(seed)
    possibilities = 2 * rng.integers(0, 2, size=(candidates, bin_count), dtype=np.int8) - 1
    coefficient = np.stack([cost_model(bin_count, POLYNOMIAL_TESTS[n])["coefficients"]
                            for n in NONTRIVIAL_TESTS])
    deviations = possibilities @ coefficient.T
    score = np.max(np.abs(deviations), axis=1)
    best = int(np.argmin(score))
    return possibilities[best], {
        "seed": int(seed), "candidates": int(candidates),
        "selected_candidate_index": best, "selected_max_cost_error": float(score[best]),
        "selection_rule": "minimum maximum absolute error over the three nontrivial polynomial costs",
    }


def projection_union(segments, normal, tolerance=1e-13):
    """Merge actual segment projections; return components and missed square length."""
    s = np.asarray(segments, dtype=float)
    n = np.asarray(normal, dtype=float)
    n = n / np.linalg.norm(n)
    values = s @ n
    intervals = np.sort(values, axis=1)
    intervals = intervals[np.argsort(intervals[:, 0], kind="stable")]
    merged = []
    for lo, hi in intervals:
        if merged and lo <= merged[-1][1] + tolerance:
            merged[-1][1] = max(merged[-1][1], float(hi))
        else:
            merged.append([float(lo), float(hi)])
    half_width = .5 * float(np.abs(n).sum())
    cursor = -half_width
    gaps = []
    for lo, hi in merged:
        lo, hi = max(lo, -half_width), min(hi, half_width)
        if hi < -half_width or lo > half_width:
            continue
        if lo > cursor + tolerance:
            gaps.append([cursor, lo])
        cursor = max(cursor, hi)
    if cursor < half_width - tolerance:
        gaps.append([cursor, half_width])
    return {"components": merged, "target": [-half_width, half_width], "gaps": gaps,
            "uncovered_length": float(sum(b-a for a,b in gaps))}


def square_line_sample(power=19, seed=20261029):
    """Fixed scrambled Sobol sample, rejected to the square line cylinder.

    Sampling diagnostics use the accepted low-discrepancy points.  They
    are not independent Monte Carlo samples, and no IID confidence band
    is assigned to them.
    """
    from scipy.stats import qmc
    points = qmc.Sobol(d=2, scramble=True, seed=seed).random_base2(power)
    theta = math.pi * points[:, 0]
    offset = math.sqrt(2.) * (points[:, 1] - .5)
    normals = np.column_stack((np.cos(theta), np.sin(theta)))
    half_width = .5 * np.abs(normals).sum(axis=1)
    accepted = np.abs(offset) < half_width
    theta, offset, normals = theta[accepted], offset[accepted], normals[accepted]
    direction = np.column_stack((-normals[:, 1], normals[:, 0]))
    origin = offset[:, None] * normals
    lower = (-.5 - origin) / direction
    upper = (.5 - origin) / direction
    lo = np.minimum(lower, upper).max(axis=1)
    hi = np.maximum(lower, upper).min(axis=1)
    endpoints = np.stack((origin + lo[:, None]*direction,
                          origin + hi[:, None]*direction), axis=1)
    rectangle_area = math.pi * math.sqrt(2.)
    return {
        "theta": theta, "offset": offset, "endpoints": endpoints,
        "input_count": int(2**power), "accepted_count": int(accepted.sum()),
        "seed": int(seed), "sobol_power": int(power),
        "estimated_cylinder_area": float(rectangle_area * accepted.mean()),
        "exact_cylinder_area": 4.,
    }


def endpoint_labels(endpoints, bin_count, fixed_tolerance=2e-13):
    """D4 bin and orientation character, independent of the segment construction."""
    e = np.asarray(endpoints, dtype=float)
    absolute = np.abs(e)
    t = absolute.min(axis=-1)
    cell = np.clip(np.floor(2 * bin_count * t).astype(np.int64), 0, bin_count - 1)
    vertical = absolute[..., 0] >= absolute[..., 1]
    sx = np.where(e[..., 0] >= 0, 1, -1)
    sy = np.where(e[..., 1] >= 0, 1, -1)
    determinant = sx * sy * np.where(vertical, 1, -1)
    fixed = (t < fixed_tolerance) | (np.abs(absolute[..., 0]-absolute[..., 1]) < fixed_tolerance)
    return cell, determinant.astype(np.int8), fixed


def selected_endpoints(endpoints, bits):
    b = _validate_bits(bits)
    cell, determinant, fixed = endpoint_labels(endpoints, len(b))
    return (determinant * b[cell] > 0) | fixed


def line_hit_counts(endpoints, bits):
    return selected_endpoints(endpoints, bits).sum(axis=-1)


def line_weights(sample):
    theta, offset = sample["theta"], sample["offset"]
    return {
        "constant": np.ones(len(theta)),
        "1+0.5cos2theta": 1 + .5 * np.cos(2*theta),
        "1+0.5sin2theta": 1 + .5 * np.sin(2*theta),
        "1+2offset_squared": 1 + 2 * offset**2,
    }


def line_diagnostics(sample, bits):
    counts = line_hit_counts(sample["endpoints"], bits)
    weights = line_weights(sample)
    weighted = {name: [float(np.sum(w * (counts == k)) / np.sum(w)) for k in range(3)]
                for name, w in weights.items()}
    cell, _, _ = endpoint_labels(sample["endpoints"], len(bits))
    target = np.array([.25, .5, .25])
    return {
        "hit_fractions": weighted["constant"], "weighted_hit_fractions": weighted,
        "largest_weighted_hit_error": float(max(np.max(np.abs(np.array(v)-target))
                                                  for v in weighted.values())),
        "same_bin_endpoint_fraction": float(np.mean(cell[:, 0] == cell[:, 1])),
        "sampled_counts": [int(np.count_nonzero(counts == k)) for k in range(3)],
    }


def point_membership_from_segments(points, segments, tolerance=2e-12):
    """Independent geometric membership for a modest batch of boundary points."""
    points = np.asarray(points, dtype=float).reshape(-1, 2)
    s = np.asarray(segments, dtype=float)
    out = np.zeros(len(points), dtype=bool)
    for a, b in s:
        lower, upper = np.minimum(a, b), np.maximum(a, b)
        out |= np.all((points >= lower-tolerance) & (points <= upper+tolerance), axis=1)
    return out