"""Reproducible local trial searches for the spherical causal action.""" import argparse import json from pathlib import Path import numpy as np from scipy.optimize import minimize from scipy.sparse import csr_matrix from scipy.sparse.csgraph import maximum_bipartite_matching from scipy.spatial import ConvexHull, cKDTree CELL_ENERGY = np.sqrt(3) / (8 * np.pi) SMOOTHING = (0.12, 0.045, 0.016, 0.005, 0.0015) MATCH_RADII = (1.5, 3.0, 6.0) def unit(vectors): return vectors / np.linalg.norm(vectors, axis=-1, keepdims=True) def icosphere(frequency): phi = (1 + np.sqrt(5)) / 2 vertices = unit(np.array([ (0, a, b * phi) if axis == 0 else (b * phi, 0, a) if axis == 1 else (a, b * phi, 0) for axis in range(3) for a in (-1, 1) for b in (-1, 1) ])) sites = [] for p, q, r in vertices[ConvexHull(vertices).simplices]: for i in range(frequency + 1): for j in range(frequency + 1 - i): sites.append(i * p + j * q + (frequency - i - j) * r) sites = unit(np.unique(np.round(unit(np.array(sites)), 12), axis=0)) assert len(sites) == 10 * frequency**2 + 2 return sites def fibonacci(count): k = np.arange(count) z = 1 - (2 * k + 1) / count azimuth = np.pi * (3 - np.sqrt(5)) * k radius = np.sqrt(1 - z * z) return np.column_stack((radius * np.cos(azimuth), radius * np.sin(azimuth), z)) def chord(radius): return 2 * np.sin(min(radius, np.pi) / 2) def pair_energy(sites, weights, theta, epsilon=0.0, gradient=False): """Return I_h/theta**4, using a smoothed positive part only if epsilon > 0.""" cutoff_depth = 2 * np.sin(theta / 2)**2 diagonal = 2 * cutoff_depth / theta**2 pairs = cKDTree(sites).query_pairs( np.sqrt(2 * cutoff_depth * (1 + epsilon)), output_type="ndarray" ) i, j = pairs.T difference = sites[i] - sites[j] depth = np.sum(difference**2, axis=1) / 2 s = 1 - depth / cutoff_depth hinge = np.maximum(s, 0) slope = (s > 0).astype(float) if epsilon > 0: smooth = np.abs(s) < epsilon hinge[smooth] = (s[smooth] + epsilon)**2 / (4 * epsilon) slope[smooth] = (s[smooth] + epsilon) / (2 * epsilon) scaled = cutoff_depth / theta**2 values = (2 - depth) * scaled * hinge pair_mass = weights[i] * weights[j] energy = (diagonal * np.dot(weights, weights) + 2 * np.dot(pair_mass, values)) / theta**2 if not gradient: return energy # Differentiate squared chord lengths in ambient coordinates, then retract. force = -2 * pair_mass * (scaled * hinge + (2 - depth) * slope / theta**2) / theta**2 ambient = np.column_stack([ np.bincount(i, force * component, minlength=len(sites)) - np.bincount(j, force * component, minlength=len(sites)) for component in difference.T ]).astype(float, copy=False) weight_gradient = 2 * ( diagonal * weights + np.bincount(i, values * weights[j], minlength=len(sites)) + np.bincount(j, values * weights[i], minlength=len(sites)) ) / theta**2 return energy, ambient, weight_gradient def stage_objective(base, theta, epsilon, weight_floor): axis = np.eye(3)[np.argmin(np.abs(base), axis=1)] left = unit(np.cross(base, axis)) right = np.cross(base, left) count = len(base) def state(variables): u, v, logits = variables.reshape(3, count) points = base + theta * (u[:, None] * left + v[:, None] * right) lengths = np.linalg.norm(points, axis=1) points /= lengths[:, None] raw = np.exp(logits - np.max(logits)) raw /= raw.sum() weights = (1 - weight_floor) * raw + weight_floor / count return points, weights, raw, lengths def objective(variables): points, weights, raw, lengths = state(variables) energy, grad_x, grad_w = pair_energy(points, weights, theta, epsilon, gradient=True) grad_x -= np.sum(points * grad_x, axis=1)[:, None] * points grad_x *= (theta / lengths)[:, None] grad_u = np.sum(grad_x * left, axis=1) grad_v = np.sum(grad_x * right, axis=1) grad_logits = (1 - weight_floor) * raw * (grad_w - np.dot(grad_w, raw)) return count * energy, count * np.concatenate((grad_u, grad_v, grad_logits)) return state, objective def relax(seed, theta, iterations): sites = seed count = len(seed) weights = np.full(count, 1 / count) best = (pair_energy(sites, weights, theta), sites, weights) weight_floor = 1e-5 evaluations = 0 for epsilon in SMOOTHING: state, objective = stage_objective(sites, theta, epsilon, weight_floor) raw = (weights - weight_floor / count) / (1 - weight_floor) logits = np.log(np.maximum(raw, np.finfo(float).tiny)) variables = np.concatenate((np.zeros(2 * count), logits)) result = minimize( objective, variables, jac=True, method="L-BFGS-B", options={"maxiter": iterations, "gtol": 2e-7, "ftol": 1e-14, "maxcor": 12}, ) evaluations += result.nfev sites, weights, _, _ = state(result.x) energy = pair_energy(sites, weights, theta) if energy < best[0]: best = (energy, sites, weights) return *best, evaluations def heavy_mesh(sites, weights, theta): eligible = np.flatnonzero(weights >= 0.02 * CELL_ENERGY * theta**2) order = eligible[np.argsort(-weights[eligible], kind="stable")] neighbors = cKDTree(sites[order]).query_ball_point(sites[order], chord(theta / 4)) excluded = np.zeros(len(order), dtype=bool) keep = [] for index, adjacent in enumerate(neighbors): if not excluded[index]: keep.append(order[index]) excluded[adjacent] = True mesh = sites[keep] hull = ConvexHull(mesh) if np.any(hull.equations[:, 3] >= 0) or len(hull.vertices) != len(mesh): raise ValueError("trial does not give a spherical mesh containing the origin") faces = hull.simplices edges = np.unique(np.sort( np.concatenate((faces[:, :2], faces[:, 1:], faces[:, ::2])), axis=1 ), axis=0) degree = np.bincount(edges.ravel(), minlength=len(mesh)) charge = 6 - degree assert charge.sum() == 12 return mesh, charge def charge_diagnostics(mesh, charge, theta): bad = charge != 0 sites = mesh[bad] units = charge[bad] positive = np.repeat(sites[units > 0], units[units > 0], axis=0) negative = np.repeat(sites[units < 0], -units[units < 0], axis=0) unmatched = {} for radius in MATCH_RADII: count = 0 if len(negative) > 0: neighbors = cKDTree(negative).query_ball_point(positive, chord(radius * theta)) rows = np.repeat(np.arange(len(positive)), [len(row) for row in neighbors]) columns = np.array([j for row in neighbors for j in row], dtype=int) graph = csr_matrix( (np.ones(len(rows), dtype=bool), (rows, columns)), shape=(len(positive), len(negative)), ) count = np.count_nonzero(maximum_bipartite_matching(graph) >= 0) unmatched[str(radius)] = int(len(positive) + len(negative) - 2 * count) tree = cKDTree(sites) nearby, indices = tree.query(sites, k=3) partners = indices[:, 1] third = np.minimum(nearby[:, 2], nearby[partners, 2]) isolated = ( (indices[partners, 1] == np.arange(len(sites))) & (units[partners] == -units) & (nearby[:, 1] <= chord(1.5 * theta)) ) mean_spacing = 0.5 * np.sqrt(4 * np.pi / len(sites)) return { "mesh_sites": len(mesh), "defects": len(sites), "degree_5": int(np.count_nonzero(charge == 1)), "degree_7": int(np.count_nonzero(charge == -1)), "positive_units": len(positive), "negative_units": len(negative), "unmatched_units": unmatched, "isolated_vertices_at_3theta": int(np.count_nonzero(isolated & (third >= chord(3 * theta)))), "isolated_vertices_at_half_mean_spacing": int(np.count_nonzero( isolated & (nearby[:, 1] < chord(mean_spacing)) & (third >= chord(mean_spacing)) )), } def run(frequencies, ratios, iterations): results = [] configurations = {} for frequency in frequencies: nominal_count = 10 * frequency**2 + 2 theta = np.sqrt(4 * np.pi / (np.sqrt(3) / 2 * nominal_count)) seeds = [("icosphere", icosphere(frequency))] for ratio in ratios: count = round(ratio * nominal_count) seeds.append(("fibonacci", fibonacci(count))) for family, seed in seeds: initial_energy = pair_energy(seed, np.full(len(seed), 1 / len(seed)), theta) energy, sites, weights, evaluations = relax(seed, theta, iterations) mesh, charge = heavy_mesh(sites, weights, theta) record = { "nominal_count": nominal_count, "support": len(seed), "theta": theta, "seed": family, "initial_energy": initial_energy, "trial_energy": energy, "trial_excess": energy - CELL_ENERGY, "evaluations": evaluations, **charge_diagnostics(mesh, charge, theta), } results.append(record) name = f"n{nominal_count}_{family}_{len(seed)}" configurations[f"{name}_sites"] = sites configurations[f"{name}_weights"] = weights print( f"{nominal_count:5} {family:9} N={len(seed):5} " f"excess={record['trial_excess']:.6f} defects={record['defects']:3}", flush=True, ) return results, configurations def self_test(): octahedron = np.concatenate((np.eye(3), -np.eye(3))) weights = np.full(6, 1 / 6) assert np.isclose(pair_energy(octahedron, weights, np.pi / 2), (1 / 3) / (np.pi / 2)**4) rng = np.random.default_rng(4919) sites = fibonacci(48) theta = 0.55 state, objective = stage_objective(sites, theta, 0.06, 1e-5) variables = rng.normal(0, 0.04, 3 * len(sites)) direction = unit(rng.normal(size=variables.size)) _, gradient = objective(variables) step = 2e-6 finite = (objective(variables + step * direction)[0] - objective(variables - step * direction)[0]) / (2 * step) assert np.isclose(finite, gradient @ direction, rtol=3e-6, atol=1e-8) points, mass, _, _ = state(variables) scalar_products = np.clip(points @ points.T, -1, 1) dense = (1 + scalar_products) * np.maximum(scalar_products - np.cos(theta), 0) assert np.isclose(pair_energy(points, mass, theta), mass @ dense @ mass / theta**4) _, empty_gradient, _ = pair_energy(octahedron, weights, 0.1, 0.01, gradient=True) assert empty_gradient.dtype.kind == "f" and not np.any(empty_gradient) assert np.count_nonzero(heavy_mesh(icosphere(3), np.full(92, 1 / 92), theta)[1]) == 12 print("Octahedron, sparse energy, gradient, and mesh checks passed.") def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--frequencies", type=int, nargs="+", default=[3, 4, 6, 8, 10, 14, 18, 22]) parser.add_argument("--ratios", type=float, nargs="+", default=[0.91, 0.94, 0.97, 1.0, 1.02]) parser.add_argument("--iterations", type=int, default=150) parser.add_argument("--output", type=Path) parser.add_argument("--archive", type=Path) parser.add_argument("--self-test", action="store_true") args = parser.parse_args() if args.self_test: self_test() return if any(frequency < 2 for frequency in args.frequencies) or args.iterations < 1: parser.error("frequencies must be at least two and iterations must be positive") if any(round(ratio * (10 * min(args.frequencies)**2 + 2)) < 8 for ratio in args.ratios): parser.error("each support ratio must give at least eight sites") trials, configurations = run(args.frequencies, args.ratios, args.iterations) if args.output: args.output.write_text(json.dumps( {"iterations_per_stage": args.iterations, "smoothing": SMOOTHING, "trials": trials}, indent=2, allow_nan=False, ) + "\n", encoding="utf-8") if args.archive: np.savez_compressed(args.archive, **configurations) if __name__ == "__main__": main()