"""Replot the direct strain-relaxation trials from their archived JSON records.""" import argparse import json from math import isfinite, log, sqrt from pathlib import Path import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from matplotlib.lines import Line2D from matplotlib.ticker import FixedLocator, NullLocator HERE = Path(__file__).resolve().parent SOURCES = (HERE / "strain_relaxation_results.json", HERE / "strain_fine_results.json") INK = "#1e3037" TEAL = "#176b75" ORANGE = "#ad491f" GRID = "#dde7e8" def read_trials(paths): trials = [] for path in paths: data = json.loads(path.read_text(encoding="utf-8")) for trial in data["trials"]: theta = trial["theta"] values = (trial["initial"]["strain"], trial["final"]["strain"], trial["initial_excess"], trial["final_excess"]) if not 0 < theta < 1 or not all(isfinite(value) and value > 0 for value in values): raise ValueError(f"Invalid radius, strain or excess for a log axis in {path}") for stage in ("initial", "final"): mesh = trial[stage] if (mesh["min_spacing_over_theta"] < data["min_spacing_over_theta"] - 1e-10 or mesh["cover_radius_over_theta"] > data["max_cover_radius_over_theta"] + 1e-10): raise ValueError(f"Mesh violates the archived admissibility bounds in {path}") trials.append(trial) if not trials: raise ValueError("The input archives contain no trials") return sorted(trials, key=lambda trial: (-trial["theta"], trial["replicate"])) def paired_marks(ax, start, end, color, arrow=False): if arrow: ax.annotate("", xy=end, xytext=start, arrowprops={ "arrowstyle": "->", "color": color, "alpha": 0.72, "linewidth": 1.1, "shrinkA": 4, "shrinkB": 4, }) else: ax.plot((start[0], end[0]), (start[1], end[1]), color=color, lw=1, alpha=0.52) ax.scatter(*start, marker="o", s=31, facecolors="white", edgecolors=color, linewidths=1.3, zorder=3) ax.scatter(*end, marker="s", s=25, color=color, zorder=4) def plot_trials(trials, destination): radii = sorted({trial["theta"] for trial in trials}, reverse=True) finest = min(radii) plt.rcParams.update({ "font.family": "DejaVu Sans", "font.size": 10.5, "text.color": INK, "axes.labelcolor": INK, "axes.titlecolor": INK, "xtick.color": INK, "ytick.color": INK, "axes.edgecolor": "#869b9f", "mathtext.default": "regular", }) fig, ((raw, change), (log_scale, patch_scale)) = plt.subplots(2, 2, figsize=(11.6, 8.5)) fig.subplots_adjust(left=0.10, right=0.98, bottom=0.153, top=0.849, wspace=0.31, hspace=0.54) fig.text(0.10, 0.955, "Direct relaxation of spherical Delaunay strain", fontsize=20, weight="bold") fig.text(0.10, 0.913, f"{len(trials)} paired trials at {len(radii)} interaction ranges", color="#455e65", fontsize=11) for ax, letter, title in zip( (raw, change, log_scale, patch_scale), "ABCD", ("Strain and causal energy", "Change within each trial", "Logarithmic lower reference scale", "Constructive upper reference scale"), ): ax.set_title(f"{letter} {title}", loc="left", weight="bold", fontsize=11.5, pad=10) ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) ax.set_axisbelow(True) ax.grid(axis="y", color=GRID, linewidth=0.8) raw.set(xscale="log", yscale="log", xlabel=r"Integrated strain $S_\theta$", ylabel=r"Causal trial excess above $b/(4\pi)$") for axis, ticks in ((raw.xaxis, (0.8, 1, 1.5, 2, 3, 4, 5)), (raw.yaxis, (0.003, 0.004, 0.006, 0.01, 0.015, 0.025))): axis.set_major_locator(FixedLocator(ticks)) axis.set_major_formatter(lambda value, _: f"{value:g}") axis.set_minor_locator(NullLocator()) change.set(xlabel="Strain reduction (%)", ylabel="Causal excess change (%)") change.axhline(0, color="#879b9e", lw=1, ls="--", zorder=1) normalizers = ( (log_scale, lambda theta: theta * sqrt(log(1 / theta)), r"$S_\theta/[\theta\sqrt{\log(1/\theta)}]$"), (patch_scale, lambda theta: theta ** (2 / 3), r"$S_\theta/\theta^{2/3}$"), ) for ax, _, label in normalizers: ax.set(xscale="log", xlim=(radii[0] * 1.16, finest / 1.16), xlabel=r"Interaction range $\theta$", ylabel=label) ax.set_xticks(radii, [f"{theta:g}" for theta in radii]) ax.xaxis.set_minor_locator(NullLocator()) for trial in trials: theta = trial["theta"] color = ORANGE if theta == finest else TEAL before, after = (trial[stage]["strain"] for stage in ("initial", "final")) excess_before, excess_after = (trial[f"{stage}_excess"] for stage in ("initial", "final")) paired_marks(raw, (before, excess_before), (after, excess_after), color, arrow=True) reduction = 100 * (1 - after / before) excess_change = 100 * (excess_after / excess_before - 1) change.scatter(reduction, excess_change, color=color, s=34, zorder=3) for ax, scale, _ in normalizers: divisor = scale(theta) paired_marks(ax, (theta, before / divisor), (theta, after / divisor), color) legend = [ Line2D([], [], marker="o", linestyle="none", markerfacecolor="white", markeredgecolor=TEAL, label="Initial mesh"), Line2D([], [], marker="s", linestyle="none", color=TEAL, label="Refined mesh"), Line2D([], [], linestyle="-", linewidth=2, color=ORANGE, label=rf"Finest range $\theta={finest:g}$"), ] fig.legend(handles=legend, loc="upper right", bbox_to_anchor=(0.984, 0.922), frameon=False, ncol=3, handletextpad=0.3, columnspacing=1.2, fontsize=9.5) fig.text(0.10, 0.036, "Each pair uses the same number of equally weighted sites. The search accepts updates by strain reduction.\n" "The reference scales normalize finite-range trial data.", color="#455e65", fontsize=9.5, linespacing=1.45) fig.savefig(destination, dpi=180, facecolor="white") plt.close(fig) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--input", nargs="+", type=Path, default=SOURCES) parser.add_argument("--output", type=Path, default=HERE / "direct_strain_trials.png") args = parser.parse_args() plot_trials(read_trials(args.input), args.output) if __name__ == "__main__": main()