"""Direct, feasibility-checked Delaunay strain searches on the sphere.""" import argparse import json from pathlib import Path import numpy as np from scipy.optimize import minimize from scipy.spatial import ConvexHull, cKDTree from patch_seam_trials import MARGINS, RANGES, lattice_points, patches from sphere_trials import CELL_ENERGY, chord, pair_energy, unit SMOOTHING = (0.12, 0.05, 0.02, 0.006, 0.002) MIN_SPACING = 0.25 MAX_COVER = 2.0 def departure_mesh(sites, theta): hull = ConvexHull(sites) if np.any(hull.equations[:, 3] >= 0) or len(hull.vertices) != len(sites): raise ValueError("point set is not an embedded spherical Delaunay mesh") faces = hull.simplices sides = np.concatenate((faces[:, :2], faces[:, 1:], faces[:, ::2]), axis=0) edges = np.unique(np.sort(sides, axis=1), axis=0) degree = np.bincount(edges.ravel(), minlength=len(sites)) charge = 6 - degree assert charge.sum() == 12 and len(edges) == 3 * len(sites) - 6 difference = sites[edges[:, 0]] - sites[edges[:, 1]] lengths = 2 * np.arcsin(np.clip(np.linalg.norm(difference, axis=1) / 2, 0, 1)) nearest = cKDTree(sites).query(sites, k=2)[0][:, 1] stats = { "strain": float(theta**2 * np.sum(np.abs(lengths / theta - 1))), "positive_vertices": int(np.count_nonzero(charge > 0)), "negative_vertices": int(np.count_nonzero(charge < 0)), "min_spacing_over_theta": float(2 * np.arcsin(np.min(nearest) / 2) / theta), "cover_radius_over_theta": float( np.max(np.arccos(np.clip(-hull.equations[:, 3], -1, 1))) / theta ), } return edges, stats def edge_objective(base, edges, theta, epsilon): """Smooth the absolute value only on the current edge graph.""" axes = np.eye(3)[np.argmin(np.abs(base), axis=1)] left = unit(np.cross(base, axes)) right = np.cross(base, left) i, j = edges.T count = len(base) def state(variables): u, v = variables.reshape(2, count) points = base + theta * (u[:, None] * left + v[:, None] * right) lengths = np.linalg.norm(points, axis=1) return points / lengths[:, None], lengths def objective(variables): points, scales = state(variables) difference = points[i] - points[j] distances = np.linalg.norm(difference, axis=1) half = np.clip(distances / 2, 0, 1 - 1e-12) residual = 2 * np.arcsin(half) / theta - 1 loss = np.hypot(residual, epsilon) slope = residual / loss scale = slope / (theta * np.maximum(distances, 1e-12) * np.sqrt(1 - half**2)) ambient = np.column_stack([ np.bincount(i, scale * component, minlength=count) - np.bincount(j, scale * component, minlength=count) for component in difference.T ]) ambient -= np.sum(ambient * points, axis=1)[:, None] * points ambient *= (theta / scales)[:, None] derivative = np.concatenate(( np.sum(ambient * left, axis=1), np.sum(ambient * right, axis=1) )) return float(np.sum(loss - epsilon)), derivative return state, objective def admissible(stats): return (stats["min_spacing_over_theta"] >= MIN_SPACING - 1e-10 and stats["cover_radius_over_theta"] <= MAX_COVER + 1e-10) def refine(sites, theta, iterations, sweeps): edges, previous = departure_mesh(sites, theta) if not admissible(previous): raise ValueError("seed violates the requested separation or covering constraint") history = [previous["strain"]] evaluations = 0 for epsilon in SMOOTHING: for _ in range(sweeps): state, objective = edge_objective(sites, edges, theta, epsilon) initial = np.zeros(2 * len(sites)) fit = minimize( objective, initial, jac=True, method="L-BFGS-B", bounds=[(-0.24, 0.24)] * len(initial), options={"maxiter": iterations, "ftol": 1e-11, "gtol": 1e-6, "maxcor": 8}, ) evaluations += fit.nfev for step in (1, 0.5, 0.25, 0.125, 0.0625, 0.03125): proposal, _ = state(step * fit.x) if cKDTree(proposal).query_pairs(chord(MIN_SPACING * theta), output_type="ndarray").size: continue new_edges, current = departure_mesh(proposal, theta) if admissible(current) and current["strain"] < previous["strain"] - 1e-10: sites, edges, previous = proposal, new_edges, current history.append(current["strain"]) break else: break return sites, previous, history, evaluations def run(radii, replicates, seed, iterations, sweeps): rng = np.random.default_rng(seed) trials = [] for theta in radii: subdivisions = max(2, round(theta**(-1 / 3))) tiles = list(patches(subdivisions)) for replicate in range(replicates): initial = np.concatenate([ lattice_points(tile, theta, rng.random(2), MARGINS[:1])[0] for tile in tiles ]) _, before = departure_mesh(initial, theta) weights = np.full(len(initial), 1 / len(initial)) refined, after, history, evaluations = refine(initial, theta, iterations, sweeps) trial = { "theta": theta, "replicate": replicate, "support": len(initial), "initial_excess": float(pair_energy(initial, weights, theta) - CELL_ENERGY), "final_excess": float(pair_energy(refined, weights, theta) - CELL_ENERGY), "initial": before, "final": after, "accepted_strain": history, "evaluations": evaluations, } trials.append(trial) print(f"theta={theta:.4f} phase={replicate} n={len(initial):5d} " f"strain={before['strain']:.5f}->{after['strain']:.5f} " f"excess={trial['initial_excess']:.6f}->{trial['final_excess']:.6f}", flush=True) return trials def self_test(): from sphere_trials import icosphere sites = icosphere(4) theta = 0.30 edges, before = departure_mesh(sites, theta) _, objective = edge_objective(sites, edges, theta, .05) rng = np.random.default_rng(194) variables = rng.normal(0, .02, 2 * len(sites)) direction = unit(rng.normal(size=len(variables))) _, gradient = objective(variables) step = 2e-6 numerical = (objective(variables + step * direction)[0] - objective(variables - step * direction)[0]) / (2 * step) assert np.isclose(numerical, gradient @ direction, rtol=1e-5, atol=1e-7) sites_after, after, history, _ = refine(sites, theta, 8, 1) assert len(sites_after) == len(sites) and admissible(after) assert after["strain"] < before["strain"] and np.all(np.diff(history) < 0) print("Fixed-edge derivative, feasibility checks and exact rebuilt-mesh descent passed.") def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--radii", type=float, nargs="+", default=RANGES) parser.add_argument("--replicates", type=int, default=2) parser.add_argument("--seed", type=int, default=1947) parser.add_argument("--iterations", type=int, default=35) parser.add_argument("--sweeps", type=int, default=2) parser.add_argument("--output", type=Path) parser.add_argument("--self-test", action="store_true") args = parser.parse_args() if args.self_test: self_test() return if (args.output is None or min(args.replicates, args.iterations, args.sweeps) < 1 or any(not 0 < theta <= 0.25 for theta in args.radii)): parser.error("provide an output, positive iterations and phases, and radii in (0, 0.25]") trials = run(args.radii, args.replicates, args.seed, args.iterations, args.sweeps) args.output.write_text(json.dumps({ "seed": args.seed, "replicates": args.replicates, "iterations": args.iterations, "sweeps": args.sweeps, "min_spacing_over_theta": MIN_SPACING, "max_cover_radius_over_theta": MAX_COVER, "trials": trials, }, indent=2, allow_nan=False) + "\n", encoding="utf-8") if __name__ == "__main__": main()