#!/usr/bin/env python3 """Numerical checks of the exact changes of variables in strebel_measures.tex. These checks verify formulas and normalizations; the manuscript proofs do not depend on the Monte Carlo experiment. Dependencies: numpy, scipy. """ from __future__ import annotations import argparse import json from pathlib import Path import numpy as np from scipy.integrate import quad from scipy.optimize import brentq from scipy.special import beta, gamma from scipy.stats import kstest def square_lengths(t: float, u: float, v: float) -> np.ndarray: """Normalized lengths (12,23,34,14), for normalized perimeters u,v,1-u,1-v.""" disc = (1 + (u - v) * t) ** 2 - 4 * u * (1 - v) * t if disc > 2e-9 * max(1.0, t * t): raise ValueError("Outside the square cell") z = (1 + (u - v) * t + 1j * np.sqrt(max(0.0, -disc))) / (2 * (1 - v)) a = ( u * np.angle(z) - v * np.angle(z - 1) + (1 - u) * np.angle(z - t) ) / np.pi + u + v - 1 return np.array([a, v - a, 1 - u - v + a, u - a]) def inverse_square_cross_ratio(lengths: np.ndarray) -> float: a, b, c, d = lengths / np.sum(lengths) u, v = a + d, a + b middle = u + v - 2 * u * v radius = 2 * np.sqrt(u * v * (1 - u) * (1 - v)) lo, hi = max(0.0, middle - radius), min(1.0, middle + radius) pad = 1e-10 * (hi - lo) return brentq( lambda k: square_lengths(1 / k, u, v)[0] - a, lo + pad, hi - pad, xtol=2e-13, ) def path_density(t: float, shapes=(1.0, 1.0, 1.0), rates=(1.0, 1.0, 1.0)) -> float: m1, m2, m3 = shapes l1, l2, l3 = rates total = m1 + m2 + m3 w = np.arccosh(np.sqrt(t)) def integrand(u): v = w - u return ( np.sinh(2 * u) * np.sinh(2 * v) * np.sinh(u) ** (2 * m1 - 2) * np.sinh(v) ** (2 * m3 - 2) / (l1 * np.sinh(u) ** 2 + l2 + l3 * np.sinh(v) ** 2) ** total ) integral = quad(integrand, 0, w, epsabs=1e-12, epsrel=1e-10)[0] return ( gamma(total) * integral / (2 * np.sqrt(t * (t - 1)) * gamma(m1) * gamma(m2) * gamma(m3)) ) def path_closed_density(t: float) -> float: z = np.sqrt(t - 1) return (1 + (t - 2) * np.arctan(z) / z) / (2 * t * t) def star_cross_ratio(a: float, b: float, c: float) -> complex: return (a - b * c + 2j * np.sqrt(a * b * c)) / (a + b) ** 2 def star_inverse(z: complex) -> np.ndarray: r, s = abs(z), abs(1 - z) return np.array([1 + r - s, 1 - r + s, r + s - 1]) / (1 + r + s) def checks(samples: int, seed: int) -> dict: rng = np.random.default_rng(seed) max_derivative_error = 0.0 for _ in range(100): t = 1 + np.exp(rng.uniform(-2, 3)) radius = 0.8 * np.sqrt(rng.random()) angle = rng.uniform(0, 2 * np.pi) x, y = radius * np.cos(angle), radius * np.sin(angle) u = (1 + np.sqrt((t - 1) / t) * x + y / np.sqrt(t)) / 2 v = (1 + np.sqrt((t - 1) / t) * x - y / np.sqrt(t)) / 2 lengths = square_lengths(t, u, v) assert np.min(lengths) > 0 assert abs(np.sum(lengths) - 1) < 1e-12 h = 1e-5 * min(1.0, t - 1) numerical = (square_lengths(t + h, u, v)[0] - square_lengths(t - h, u, v)[0]) / (2 * h) disc = (1 + (u - v) * t) ** 2 - 4 * u * (1 - v) * t exact = np.sqrt(-disc) / (2 * np.pi * t * (t - 1)) max_derivative_error = max(max_derivative_error, abs(numerical - exact) / exact) inverse_cross_ratios = [] max_reconstruction_error = 0.0 for lengths in rng.dirichlet(np.ones(4), samples): k = inverse_square_cross_ratio(lengths) a, b, c, d = lengths reconstructed = square_lengths(1 / k, a + d, a + b) max_reconstruction_error = max(max_reconstruction_error, np.max(abs(reconstructed - lengths))) inverse_cross_ratios.append(k) inverse_cross_ratios = np.array(inverse_cross_ratios) statistic = kstest(inverse_cross_ratios, "uniform") max_star_error = 0.0 for lengths in rng.dirichlet(np.ones(3), 200): z = star_cross_ratio(*lengths) max_star_error = max(max_star_error, np.max(abs(star_inverse(z) - lengths))) path_errors = { str(t): abs(path_density(t) - path_closed_density(t)) for t in [1.001, 1.1, 2.0, 5.0, 10.0] } path_mass, path_mass_error = quad(path_closed_density, 1, np.inf, epsabs=1e-10) shapes, rates = (2.0, 3.0, 1.0), (1.2, 0.7, 2.1) m1, m2, m3 = shapes l1, l2, l3 = rates total = sum(shapes) shape_factor = gamma(m1) * gamma(m2) * gamma(m3) left_constant = 2 * gamma(total) * beta(2 * m1, 2 * m3) / (shape_factor * l2**total) right_constant = ( 2 ** (m2 - 1) * gamma(m1 + m2 / 2) * gamma(m3 + m2 / 2) / (shape_factor * l1 ** (m1 + m2 / 2) * l3 ** (m3 + m2 / 2)) ) left_t, right_t = 1.0001, 1e6 assert max_derivative_error < 1e-6 assert max_reconstruction_error < 1e-8 assert max_star_error < 1e-10 assert max(path_errors.values()) < 1e-10 assert abs(path_mass - 1) < 1e-8 return { "seed": seed, "square": { "samples": samples, "max_relative_derivative_error": float(max_derivative_error), "max_length_reconstruction_error": float(max_reconstruction_error), "inverse_cross_ratio_mean": float(np.mean(inverse_cross_ratios)), "inverse_cross_ratio_variance": float(np.var(inverse_cross_ratios)), "uniform_reference_mean": 0.5, "uniform_reference_variance": 1 / 12, "histogram_ten_equal_bins": np.histogram(inverse_cross_ratios, bins=10, range=(0, 1))[0].tolist(), "ks_statistic": float(statistic.statistic), "ks_pvalue_diagnostic_only": float(statistic.pvalue), }, "star": {"max_inverse_error": float(max_star_error)}, "path": { "closed_formula_absolute_errors": path_errors, "closed_formula_total_mass": path_mass, "quadrature_error_estimate": path_mass_error, "asymptotic_shapes": shapes, "asymptotic_rates": rates, "left_asymptotic_ratio_at_1_0001": path_density(left_t, shapes, rates) / (left_constant * (left_t - 1) ** (m1 + m3 - 1)), "right_asymptotic_ratio_at_1e6": path_density(right_t, shapes, rates) / (right_constant * right_t ** (-1 - m2 / 2)), }, } def main(): parser = argparse.ArgumentParser() parser.add_argument("--samples", type=int, default=4000) parser.add_argument("--seed", type=int, default=38271) parser.add_argument("--output", type=Path) args = parser.parse_args() result = checks(args.samples, args.seed) payload = json.dumps(result, indent=2, sort_keys=True) if args.output: args.output.write_text(payload + "\n", encoding="utf-8") print(payload) if __name__ == "__main__": main()