"""Compare spherical patch constructions in the metric of Proposition 14.6.""" import argparse import json from pathlib import Path import numpy as np from scipy.spatial import ConvexHull from sphere_trials import CELL_ENERGY, heavy_mesh, pair_energy, relax, unit MARGINS = (0.274514572525, 0.5, 1.0) RANGES = (0.20, 0.12, 0.075, 0.047, 0.030, 0.019) BASIS = np.array(((1.0, 0.0), (0.5, np.sqrt(3) / 2))) def patches(subdivisions): """Yield a center, tangent frame, and supporting hemispheres for each tile.""" grid = np.linspace(-1.0, 1.0, subdivisions + 1) for axis in range(3): tangent_axes = [i for i in range(3) if i != axis] for sign in (-1, 1): for a, b in zip(grid[:-1], grid[1:]): for c, d in zip(grid[:-1], grid[1:]): corners = np.zeros((4, 3)) corners[:, axis] = sign corners[:, tangent_axes] = ((a, c), (b, c), (b, d), (a, d)) center = unit(np.mean(corners, axis=0)) corners = unit(corners) left = np.eye(3)[tangent_axes[0]] left = unit(left - np.dot(left, center) * center) right = np.cross(center, left) inward = unit(np.cross(corners, np.roll(corners, -1, axis=0))) inward[inward @ center < 0] *= -1 cap_radius = np.arccos(np.clip(np.min(corners @ center), -1, 1)) yield center, left, right, inward, cap_radius def lattice_points(patch, theta, phases, gaps): center, left, right, inward, cap_radius = patch projected_radius = np.sin(cap_radius) limit = int(np.ceil(2 * projected_radius / theta)) + 2 axis = np.arange(-limit, limit + 1) grid = np.stack(np.meshgrid(axis, axis, indexing="ij"), axis=-1).reshape(-1, 2) projected = theta * ((grid + phases) @ BASIS) length2 = np.sum(projected**2, axis=1) near = length2 <= projected_radius**2 + 1e-14 projected = projected[near] points = ( np.sqrt(1 - length2[near])[:, None] * center + projected[:, :1] * left + projected[:, 1:] * right ) distance_from_halfspace = np.min(points @ inward.T, axis=1) return [points[distance_from_halfspace >= np.sin(gap * theta / 2)] for gap in gaps] def mesh_statistics(sites, theta): hull = ConvexHull(sites) if np.any(hull.equations[:, 3] >= 0) or len(hull.vertices) != len(sites): raise ValueError("sites do not give an embedded spherical Delaunay triangulation") faces = hull.simplices edges = np.unique(np.sort( np.concatenate((faces[:, :2], faces[:, 1:], faces[:, ::2])), axis=1 ), axis=0) i, j = edges.T lengths = 2 * np.arcsin(np.clip(np.linalg.norm(sites[i] - sites[j], axis=1) / 2, 0, 1)) degree = np.bincount(edges.ravel(), minlength=len(sites)) assert np.sum(6 - degree) == 12 cover = np.max(np.arccos(np.clip(-hull.equations[:, 3], -1, 1))) strain = theta**2 * np.sum(np.abs(lengths / theta - 1)) return { "sites": len(sites), "strain": strain, "defects": int(np.count_nonzero(degree != 6)), "min_spacing_over_theta": np.min(lengths) / theta, "cover_radius_over_theta": cover / theta, } def run(radii, replicates, seed, relax_iterations=0): rng = np.random.default_rng(seed) margins = MARGINS[:1] if relax_iterations else MARGINS records = [] for theta in radii: subdivisions = max(2, round(theta**(-1 / 3))) tiles = list(patches(subdivisions)) for replicate in range(replicates): groups = [[] for _ in margins] for tile in tiles: # Common phases allow a paired comparison of the margin widths. for group, sites in zip(groups, lattice_points(tile, theta, rng.random(2), margins)): group.append(sites) for gap, group in zip(margins, groups): sites = np.concatenate(group, axis=0) weights = np.full(len(sites), 1 / len(sites)) energy = pair_energy(sites, weights, theta) stats = mesh_statistics(sites, theta) assert stats["min_spacing_over_theta"] >= gap - 1e-10 if gap == 1.0: diagonal = 4 * np.sin(theta / 2)**2 / (len(sites) * theta**4) assert abs(energy - diagonal) < 1e-10 record = { "theta": theta, "subdivisions": subdivisions, "margin": gap, "replicate": replicate, "causal_excess": energy - CELL_ENERGY, **stats, } if relax_iterations: relaxed_energy, relaxed_sites, relaxed_weights, evaluations = relax( sites, theta, relax_iterations ) selected_sites, _ = heavy_mesh(relaxed_sites, relaxed_weights, theta) relaxed_stats = mesh_statistics(selected_sites, theta) record.update({ "relaxed_excess": relaxed_energy - CELL_ENERGY, "relaxed_evaluations": evaluations, **{f"relaxed_{key}": value for key, value in relaxed_stats.items()}, }) records.append(record) print(f"theta={theta:.4f}, {len(tiles)} tiles, {replicates} paired phases", flush=True) return records def plot_comparison(records, path): import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from matplotlib.ticker import NullLocator colors = ("#087f7d", "#bb671b", "#343d64") markers = ("o", "s", "^") labels = ("gap 0.275 θ", "gap 0.50 θ", "gap 1.00 θ") ranges = sorted({row["theta"] for row in records}, reverse=True) inverse_ranges = 1 / np.array(ranges) figure, axes = plt.subplots(1, 2, figsize=(8.2, 3.7), layout="constrained") for panel, metric, axis_label in ( (axes[0], "causal_excess", r"Causal trial excess $I_h/\theta^4-b/A$"), (axes[1], "strain", r"Delaunay strain $S_\theta$"), ): for gap, color, marker, label in zip(MARGINS, colors, markers, labels): samples = np.array([ [row[metric] for row in records if row["theta"] == theta and row["margin"] == gap] for theta in ranges ]) panel.fill_between(inverse_ranges, samples.min(axis=1), samples.max(axis=1), color=color, alpha=0.13) panel.plot(inverse_ranges, samples.mean(axis=1), marker=marker, color=color, linewidth=1.5, markersize=4, label=label) panel.set_xscale("log") panel.set_yscale("log") panel.set_xticks(inverse_ranges, [f"{value:.1f}" for value in inverse_ranges]) panel.xaxis.set_minor_locator(NullLocator()) low, high = panel.get_ylim() candidates = (0.005, 0.010, 0.020, 0.040, 0.060) if metric == "causal_excess" else (1, 2, 4, 6, 10) ticks = [value for value in candidates if low < value < high] if len(ticks) >= 2: panel.set_yticks(ticks, [f"{value:g}" for value in ticks]) panel.yaxis.set_minor_locator(NullLocator()) panel.set_xlabel(r"Inverse interaction range $1/\theta$") panel.set_ylabel(axis_label) panel.grid(color="#dfe3e8", linewidth=0.5) panel.set_axisbelow(True) panel.spines[["right", "top"]].set_visible(False) axes[1].legend(frameon=False, fontsize=8) figure.savefig(path, dpi=220) plt.close(figure) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--radii", type=float, nargs="+", default=RANGES) parser.add_argument("--replicates", type=int, default=5) parser.add_argument("--seed", type=int, default=1947) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--plot", type=Path) parser.add_argument("--relax-iterations", type=int, default=0, help="relax only the optimized-margin seed, with this many iterations per cutoff") args = parser.parse_args() if args.replicates < 1 or any(not 0 < theta <= 0.25 for theta in args.radii): parser.error("require positive replicates and radii in (0, 0.25]") if args.relax_iterations < 0 or (args.relax_iterations and args.plot): parser.error("use nonnegative relaxation iterations and reserve --plot for gap comparison") trials = run(args.radii, args.replicates, args.seed, args.relax_iterations) metadata = {"seed": args.seed, "replicates_per_range": args.replicates} if args.relax_iterations: metadata["relax_iterations_per_stage"] = args.relax_iterations args.output.write_text(json.dumps( {**metadata, "trials": trials}, indent=2, allow_nan=False, ) + "\n", encoding="utf-8") if args.plot: plot_comparison(trials, args.plot) if __name__ == "__main__": main()