File size: 5,465 Bytes
c7c67ef | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 | #!/usr/bin/env python3
"""Plot the saved LHS response distribution and paired backend discrepancies."""
from __future__ import annotations
import argparse
import json
from pathlib import Path
import time
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
def plot(output: Path) -> dict:
"""Make figures using successful backend pairs only; never call a solver."""
status = np.load(output / "status.npy")
valid = np.all(status == 1, axis=1)
if not valid.any():
raise ValueError("No successful backend pairs to plot")
response = np.load(output / "dlnP_dns.npy", mmap_mode="r")[valid]
params = np.load(output / "params.npy")[valid]
k, zs = np.load(output / "k_hmpc.npy"), np.load(output / "redshifts.npy")
metadata = json.loads((output / "metadata.json").read_text())
plotdir = output / "plots"
plotdir.mkdir(exist_ok=True)
colors = ("#0072B2", "#D55E00")
plt.rcParams.update({"font.size": 11, "axes.grid": True, "grid.alpha": 0.2})
percentiles = [2.5, 16, 50, 84, 97.5]
quantiles = np.percentile(response, percentiles, axis=0)
for kind, label in enumerate(("linear", "nonlinear")):
fig, axes = plt.subplots(2, 5, figsize=(19, 7), sharex=True, sharey=True)
for j, (z, ax) in enumerate(zip(zs, axes.flat)):
for b, name in enumerate(("CLASS + EE2", "SYREN-NEW")):
q = quantiles[:, b, kind, j]
ax.fill_between(k, q[0], q[4], color=colors[b], alpha=0.08)
ax.fill_between(k, q[1], q[3], color=colors[b], alpha=0.19)
ax.semilogx(k, q[2], color=colors[b], label=name)
ax.axhline(0, color=".5", lw=0.6)
ax.set_title(f"z = {z:.2f}")
ax.set_xlim(k[0], k[-1])
axes[0, 0].legend(fontsize=9)
fig.supxlabel(r"$k\ [h\,\mathrm{Mpc}^{-1}]$")
fig.supylabel(r"$\partial\ln P/\partial n_s$ (fixed $A_s$)")
fig.suptitle(
f"{label.capitalize()} response — {valid.sum()} paired cosmologies; "
"median, 68% and 95% LHS bands"
)
fig.tight_layout(rect=(0.02, 0.03, 1, 0.94))
fig.savefig(plotdir / f"{label}_response.png", dpi=160)
plt.close(fig)
# Additive differences are defined even where the ns response crosses zero.
residual = response[:, 1] - response[:, 0]
qdiff = np.percentile(residual, percentiles, axis=0)
fig, axes = plt.subplots(2, 5, figsize=(19, 7), sharex=True, sharey=True)
for j, (z, ax) in enumerate(zip(zs, axes.flat)):
for kind, label in enumerate(("Linear", "Nonlinear")):
q = qdiff[:, kind, j]
ax.fill_between(k, q[0], q[4], color=colors[kind], alpha=0.08)
ax.fill_between(k, q[1], q[3], color=colors[kind], alpha=0.19)
ax.semilogx(k, q[2], color=colors[kind], label=label)
ax.axhline(0, color=".3", lw=0.8)
ax.set_title(f"z = {z:.2f}")
ax.set_xlim(k[0], k[-1])
axes[0, 0].legend(fontsize=9)
fig.supxlabel(r"$k\ [h\,\mathrm{Mpc}^{-1}]$")
fig.supylabel(r"$\Delta(\partial\ln P/\partial n_s)$: SYREN-NEW minus CLASS+EE2")
fig.suptitle("Paired response differences — median, 68% and 95% LHS bands")
fig.tight_layout(rect=(0.02, 0.03, 1, 0.94))
fig.savefig(plotdir / "paired_response_difference.png", dpi=160)
plt.close(fig)
band = (k >= 0.2) & (k <= 1)
rms = np.sqrt(np.mean(residual[:, 1, 0, band] ** 2, axis=-1))
fig, axes = plt.subplots(2, 4, figsize=(15, 7))
for i, (name, ax) in enumerate(zip(metadata["parameter_names"], axes.flat)):
ax.scatter(params[:, i], rms, s=9, alpha=0.35, color=colors[1], rasterized=True)
ax.set_xlabel(name)
ax.set_ylabel("RMS response difference")
fig.suptitle(r"Nonlinear mismatch at $z=0$, $0.2\leq k\leq1\ h/\mathrm{Mpc}$")
fig.tight_layout(rect=(0, 0, 1, 0.94))
fig.savefig(plotdir / "parameter_dependence.png", dpi=160)
plt.close(fig)
anchors = {}
for target in (0.2, 0.5, 1):
ik = int(np.argmin(abs(k - target)))
anchors[str(target)] = {
"actual_k_hmpc": float(k[ik]),
"nonlinear_z0_difference_percentiles": np.percentile(
residual[:, 1, 0, ik], percentiles
).tolist(),
}
summary = {
"paired_successes": int(valid.sum()),
"successes": (status == 1).sum(axis=0).tolist(),
"failures": (status == -1).sum(axis=0).tolist(),
"pending": (status == 0).sum(axis=0).tolist(),
"percentiles": percentiles,
"anchors": anchors,
"rms_z0_k02_to1_percentiles": np.percentile(rms, percentiles).tolist(),
}
(output / "summary.json").write_text(json.dumps(summary, indent=2) + "\n")
print(json.dumps(summary, indent=2), flush=True)
return summary
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("output_dir", type=Path)
parser.add_argument("--wait", action="store_true", help="Wait for all point statuses to finish")
args = parser.parse_args()
if args.wait:
while True:
statuses = np.load(args.output_dir / "status.npy", mmap_mode="r")
remaining = int(np.any(statuses == 0, axis=1).sum())
if remaining == 0:
break
print(f"Waiting: {remaining} points pending", flush=True)
time.sleep(60)
plot(args.output_dir)
|