"""Plot the archived local causal-action trials without rerunning optimization.""" import argparse import csv import json from pathlib import Path import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np from matplotlib.collections import LineCollection from matplotlib.lines import Line2D from scipy.optimize import linear_sum_assignment from scipy.sparse import csr_matrix from scipy.sparse.csgraph import maximum_bipartite_matching from scipy.spatial import ConvexHull from scipy.spatial.distance import cdist from sphere_trials import heavy_mesh HERE = Path(__file__).resolve().parent PAIR_RADIUS = 1.5 POSITIVE = "#B64538" NEGATIVE = "#206E99" LINK = "#527765" MESH = "#AAB7B9" INK = "#203138" def key(trial): return f"n{trial['nominal_count']}_{trial['seed']}_{trial['support']}" def load_mesh(archive, trial): name = key(trial) sites, weights = archive[f"{name}_sites"], archive[f"{name}_weights"] mesh, charge = heavy_mesh(sites, weights, trial["theta"]) actual = (len(mesh), np.count_nonzero(charge), charge[charge > 0].sum(), -charge[charge < 0].sum()) expected = tuple(trial[name] for name in ( "mesh_sites", "defects", "positive_units", "negative_units" )) if actual != expected: raise ValueError(f"Recomputed mesh does not match the recorded counts for {key(trial)}") return mesh, charge def pair_distances(mesh, charge, theta): pos = np.repeat(np.flatnonzero(charge > 0), charge[charge > 0]) neg = np.repeat(np.flatnonzero(charge < 0), -charge[charge < 0]) chords = cdist(mesh[neg], mesh[pos]) distances = 2 * np.arcsin(np.clip(chords / 2, 0, 1)) / theta return pos, neg, distances def shortest_maximum_matching(pos, neg, distances, radius): """Maximize the number of matched units, then minimize total distance.""" if not len(neg): return np.empty((0, 2), dtype=int), 0 penalty = 1 + len(neg) * radius real = np.where(distances <= radius, distances, 2 * penalty) dummy = np.full((len(neg), len(neg)), penalty) rows, columns = linear_sum_assignment(np.concatenate((real, dummy), axis=1)) matched = columns < len(pos) pairs = np.column_stack((pos[columns[matched]], neg[rows[matched]])) return np.unique(pairs, axis=0), int(matched.sum()) def matching_curve(distances, radius): """Return the exact jump radii for the maximum matched fraction.""" if not len(distances): return np.array([0.0, radius]), np.array([1.0, 1.0]) edges = np.sort(np.unique(distances[distances <= radius])) radii, fractions = [0.0], [0.0] matched = 0 for edge in edges: graph = csr_matrix(distances <= edge) count = np.count_nonzero(maximum_bipartite_matching(graph) >= 0) if count > matched: radii.append(edge) fractions.append(count / len(distances)) matched = count if count == len(distances): break radii.append(radius) fractions.append(fractions[-1]) return np.asarray(radii), np.asarray(fractions) def normal_coordinates(points, center, scale): east = np.cross([0, 0, 1], center) if np.linalg.norm(east) < 1e-8: east = np.array([0.0, 1.0, 0.0]) east /= np.linalg.norm(east) north = np.cross(center, east) tangent = points @ np.stack((east, north)).T radii = np.arctan2(np.linalg.norm(tangent, axis=1), points @ center) return tangent / np.sinc(radii[:, None] / np.pi) / scale def lon_lat(points, meridian): longitude = (np.arctan2(points[:, 1], points[:, 0]) - meridian + np.pi) % (2 * np.pi) - np.pi latitude = np.arcsin(np.clip(points[:, 2], -1, 1)) return np.column_stack((longitude, latitude)) def geodesic_arcs(mesh, pairs, meridian): arcs = [] for i, j in pairs: start, stop = mesh[i], mesh[j] steps = np.linspace(0, 1, 25)[:, None] path = (1 - steps) * start + steps * stop path /= np.linalg.norm(path, axis=1)[:, None] coordinates = lon_lat(path, meridian) jumps = np.flatnonzero(np.abs(np.diff(coordinates[:, 0])) > np.pi) + 1 arcs.extend(segment for segment in np.split(coordinates, jumps) if len(segment) > 1) return arcs def scatter_mesh(ax, coords, charge, *, zoom=False): ax.scatter(*coords[charge == 0].T, s=12 if zoom else 1.6, c=MESH, alpha=0.72 if zoom else 0.58, edgecolors="none", zorder=1) for sign, color, marker in ((1, POSITIVE, "o"), (-1, NEGATIVE, "^")): selected = charge * sign > 0 ax.scatter(*coords[selected].T, s=(38 if zoom else 13) * np.abs(charge[selected]), c=color, marker=marker, edgecolors="white", linewidths=0.4, alpha=0.95, zorder=3) def save_defects(record, archive, output): mesh, charge = load_mesh(archive, record) theta = record["theta"] pos, neg, distances = pair_distances(mesh, charge, theta) pairs, matched = shortest_maximum_matching(pos, neg, distances, PAIR_RADIUS) if len(pos) + len(neg) - 2 * matched != record["unmatched_units"][str(PAIR_RADIUS)]: raise ValueError("Recomputed matching cardinality disagrees with the trial record") defects = mesh[charge != 0] neighborhood_radius = 4 local_count = np.count_nonzero( cdist(defects, defects) <= 2 * np.sin(neighborhood_radius * theta / 2), axis=1 ) center = defects[np.argmax(local_count)] meridian = np.arctan2(center[1], center[0]) coordinates = lon_lat(mesh, meridian) zoom_coordinates = normal_coordinates(mesh, center, theta) fig = plt.figure(figsize=(13, 5.5)) grid = fig.add_gridspec(1, 2, width_ratios=[1.9, 1], left=0.055, right=0.955, top=0.80, bottom=0.24, wspace=0.25) sphere = fig.add_subplot(grid[0, 0], projection="mollweide") sphere.set_title("A Spherical defect map", loc="left", pad=12, fontweight="bold") sphere.grid(color="#DFE6E5", linewidth=0.65) sphere.set_xticklabels([]) sphere.set_yticklabels([]) sphere.set_facecolor("#F6F8F7") sphere.add_collection(LineCollection(geodesic_arcs(mesh, pairs, meridian), colors=LINK, linewidths=0.8, alpha=0.68, zorder=2)) scatter_mesh(sphere, coordinates, charge) zoom = fig.add_subplot(grid[0, 1]) zoom.set_title("B Detail of the outlined window", loc="left", pad=12, fontweight="bold") zoom.set_facecolor("#F6F8F7") zoom.set_aspect("equal") zoom.add_patch(plt.Circle((0, 0), neighborhood_radius, fill=False, linewidth=1, linestyle="--", edgecolor=INK, alpha=0.72, zorder=4)) zoom.add_collection(LineCollection(zoom_coordinates[pairs], colors=LINK, linewidths=1.7, alpha=0.8, zorder=2)) scatter_mesh(zoom, zoom_coordinates, charge, zoom=True) zoom.set(xlim=(-4.25, 4.25), ylim=(-4.25, 4.25), xlabel="East / θ", ylabel="North / θ") zoom.set_xticks([-4, -2, 0, 2, 4]) zoom.set_yticks([-4, -2, 0, 2, 4]) zoom.grid(color="#DFE6E5", linewidth=0.6) east = np.cross([0, 0, 1], center) if np.linalg.norm(east) < 1e-8: east = np.array([0.0, 1.0, 0.0]) east /= np.linalg.norm(east) north = np.cross(center, east) angles = np.linspace(0, 2 * np.pi, 181) radius = neighborhood_radius * theta outline = np.cos(radius) * center + np.sin(radius) * ( np.cos(angles[:, None]) * east + np.sin(angles[:, None]) * north ) xy = lon_lat(outline, meridian) sphere.plot(*xy.T, linestyle="--", color=INK, linewidth=1, alpha=0.72, zorder=4) fig.text(0.055, 0.945, "Coordination defects at the smallest sampled range", fontsize=21, fontweight="bold", color=INK) fig.text(0.055, 0.880, f"Lowest energy at nominal count {record['nominal_count']:,} | " f"θ = {theta:.5f} rad | {record['defects']} charged mesh vertices", fontsize=10.5, color=INK) handles = [ Line2D([], [], marker="o", linestyle="none", color=MESH, label="Degree six"), Line2D([], [], marker="o", linestyle="none", color=POSITIVE, label="Positive charge"), Line2D([], [], marker="^", linestyle="none", color=NEGATIVE, label="Negative charge"), Line2D([], [], color=LINK, lw=1.5, label="Matched pair at radius 1.5θ"), ] fig.legend(handles=handles, loc="lower left", bbox_to_anchor=(0.047, 0.093), frameon=False, ncol=4, fontsize=9.5) fig.text(0.055, 0.039, f"{matched}/{len(neg)} negative units matched; {len(pos) + len(neg) - 2 * matched} " "units remain. The detail centers on the most populated 4θ defect window.", fontsize=9, color=INK) fig.savefig(output, dpi=180, facecolor="white") plt.close(fig) def scatter_trials(axis, trials, best, value): counts = [trial["nominal_count"] for trial in best] for index, trial in enumerate(best): group = [row for row in trials if row["nominal_count"] == trial["nominal_count"]] for seed, style, color in (("icosphere", "s", NEGATIVE), ("fibonacci", "o", MESH)): values = [value(row) for row in group if row["seed"] == seed] if not values: continue positions = index + (np.linspace(-0.12, 0.12, len(values)) if len(values) > 1 else 0) axis.scatter(positions, values, marker=style, color=color, s=34, edgecolors="white", linewidths=0.4, zorder=2) axis.scatter(index, value(trial), marker="D", color=POSITIVE, s=34, edgecolors="white", linewidths=0.6, zorder=3) axis.set(xticks=range(len(counts)), xticklabels=[f"{n:,}" for n in counts], xlabel="Nominal site count") def trial_legend(): return [ Line2D([], [], linestyle="none", marker="s", color=NEGATIVE, label="Icosahedral"), Line2D([], [], linestyle="none", marker="o", color=MESH, label="Fibonacci"), Line2D([], [], linestyle="none", marker="D", color=POSITIVE, label="Lowest-energy trial"), ] def style_axes(axes): for axis in axes: axis.spines[["top", "right"]].set_visible(False) axis.set_axisbelow(True) axis.grid(axis="y", color="#E1E7E5", linewidth=0.7) def save_diagnostics(trials, best, archive, output): fig, (energies, matching) = plt.subplots(1, 2, figsize=(12.4, 5.3)) fig.subplots_adjust(left=0.08, right=0.965, top=0.77, bottom=0.25, wspace=0.31) fig.text(0.08, 0.935, "Energy spread and short-range charge matching", fontsize=21, fontweight="bold", color=INK) fig.text(0.08, 0.868, "Archived local optimization trials on the sphere", fontsize=10.5, color=INK) scatter_trials(energies, trials, best, lambda row: 1e3 * row["trial_excess"]) energies.set_title("A Final energy by starting family", loc="left", fontweight="bold") energies.set_ylabel("Normalized trial excess × 10³") energies.legend(handles=trial_legend(), loc="upper right", frameon=False, fontsize=8.5) colors = plt.colormaps["viridis"](np.linspace(0.08, 0.86, len(best))) for trial, color in zip(best, colors): mesh, charge = load_mesh(archive, trial) _, neg, distances = pair_distances(mesh, charge, trial["theta"]) if not len(neg): continue radii, fractions = matching_curve(distances, PAIR_RADIUS) expected = trial["positive_units"] + len(neg) - 2 * round(fractions[-1] * len(neg)) if expected != trial["unmatched_units"][str(PAIR_RADIUS)]: raise ValueError(f"Matching curve failed the recorded-radius check for {key(trial)}") matching.step(radii, 100 * fractions, where="post", color=color, lw=1.6, label=f"{trial['nominal_count']:,}") matching.set_title("B Maximum matching by radius", loc="left", fontweight="bold") matching.set(xlim=(0.65, 1.5), ylim=(-1, 105), xlabel="Allowed geodesic distance / θ", ylabel="Negative units matched (%)") matching.legend(loc="lower right", frameon=False, fontsize=7.5, ncol=2, title="Nominal count", title_fontsize=8) style_axes((energies, matching)) fig.text(0.08, 0.100, "A compares all runs at each range. Some Fibonacci starts use different support sizes.", color=INK, fontsize=9) fig.text(0.08, 0.059, "B uses the lowest-energy trial at each range. Steps are exact matching thresholds for the stored points.", color=INK, fontsize=9) fig.savefig(output, dpi=180, facecolor="white") plt.close(fig) def save_strain(trials, best, archive, output_dir): """Evaluate the edge-departure expression in Proposition 14.6.""" best_keys = {key(trial) for trial in best} rows = [] for trial in trials: mesh, charge = load_mesh(archive, trial) theta = trial["theta"] faces = ConvexHull(mesh).simplices edges = np.unique(np.sort( np.concatenate((faces[:, :2], faces[:, 1:], faces[:, ::2])), axis=1, ), axis=0) if len(edges) != 3 * len(mesh) - 6: raise ValueError(f"Unexpected edge count for {key(trial)}") chords = np.linalg.norm(mesh[edges[:, 0]] - mesh[edges[:, 1]], axis=1) lengths = 2 * np.arcsin(np.clip(chords / 2, 0, 1)) strain = float(theta**2 * np.sum(np.abs(lengths / theta - 1))) if not 0 < theta < 1: raise ValueError("The logarithmic normalization requires 0 < theta < 1") rows.append({ "nominal_count": trial["nominal_count"], "seed": trial["seed"], "support": trial["support"], "theta": theta, "trial_excess": trial["trial_excess"], "mesh_sites": len(mesh), "mesh_edges": len(edges), "charged_vertices": np.count_nonzero(charge), "lowest_energy_at_range": key(trial) in best_keys, "edge_departure": strain, "over_theta_sqrt_log": strain / (theta * np.sqrt(np.log(1 / theta))), "over_theta_power_two_thirds": strain / theta**(2 / 3), }) with (output_dir / "trial_strain.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=list(rows[0])) writer.writeheader() writer.writerows(rows) best_rows = [row for row in rows if row["lowest_energy_at_range"]] best_rows.sort(key=lambda row: row["nominal_count"]) fig, axes = plt.subplots(1, 2, figsize=(12.4, 5.3)) fig.subplots_adjust(left=0.08, right=0.965, top=0.73, bottom=0.26, wspace=0.3) fig.text(0.08, 0.935, "Delaunay edge departures across starting configurations", fontsize=20, fontweight="bold", color=INK) fig.text(0.08, 0.858, r"$S_\theta=\theta^2\sum_e |d_S(e)/\theta-1|$ on the heavy-site meshes " f"of all {len(trials)} trials", fontsize=10.5, color=INK) for axis, metric, label in zip( axes, ("over_theta_sqrt_log", "over_theta_power_two_thirds"), (r"$S_\theta/[\theta\sqrt{\log(1/\theta)}]$", r"$S_\theta/\theta^{2/3}$"), ): scatter_trials(axis, rows, best_rows, lambda row: row[metric]) axis.set_ylabel(label) style_axes(axes) fig.legend(handles=trial_legend(), loc="upper left", bbox_to_anchor=(0.072, 0.815), frameon=False, ncol=3, fontsize=9) fig.text(0.08, 0.103, "The marked trial minimizes recorded energy at its range, with no selection by mesh departure.", color=INK, fontsize=9) fig.text(0.08, 0.061, "Ratios describe the archived finite-range trials. No asymptotic scaling exponent is fitted.", color=INK, fontsize=9) fig.savefig(output_dir / "trial_strain.png", dpi=180, facecolor="white") plt.close(fig) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--results", type=Path, default=HERE / "trial_results.json") parser.add_argument("--archive", type=Path, default=HERE / "trial_configurations.npz") parser.add_argument("--output-dir", type=Path, default=HERE) args = parser.parse_args() trials = json.loads(args.results.read_text(encoding="utf-8"))["trials"] counts = sorted({trial["nominal_count"] for trial in trials}) best = [min((trial for trial in trials if trial["nominal_count"] == count), key=lambda trial: trial["trial_energy"]) for count in counts] args.output_dir.mkdir(parents=True, exist_ok=True) with np.load(args.archive) as archive: save_defects(best[-1], archive, args.output_dir / "trial_defect_map.png") save_diagnostics(trials, best, archive, args.output_dir / "trial_diagnostics.png") save_strain(trials, best, archive, args.output_dir) if __name__ == "__main__": main()