Download scripts/validation/plot_ns_derivative_lhs.py from santicas/cjfp-data: direct link, hf CLI and curl.
- Browser
- Download file 5.47 kB
-
https://huggingface.co/datasets/santicas/cjfp-data/resolve/main/scripts/validation/plot_ns_derivative_lhs.py
- Command line
-
hf download hf://datasets/santicas/cjfp-data/scripts/validation/plot_ns_derivative_lhs.py
-
curl -L -o plot_ns_derivative_lhs.py https://huggingface.co/datasets/santicas/cjfp-data/resolve/main/scripts/validation/plot_ns_derivative_lhs.py
5.47 kB
| #!/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) | |