"""Explicit D4 realization on the unit square; no affine-box search. The fundamental boundary sector is q(t)=(1/2,t), 0 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