Download scripts/validation/compute_ns_derivative_lhs.py from santicas/cjfp-data: direct link, hf CLI and curl.
- Browser
- Download file 14.8 kB
-
https://huggingface.co/datasets/santicas/cjfp-data/resolve/main/scripts/validation/compute_ns_derivative_lhs.py
- Command line
-
hf download hf://datasets/santicas/cjfp-data/scripts/validation/compute_ns_derivative_lhs.py
-
curl -L -o compute_ns_derivative_lhs.py https://huggingface.co/datasets/santicas/cjfp-data/resolve/main/scripts/validation/compute_ns_derivative_lhs.py
14.8 kB
| #!/usr/bin/env python3 | |
| """Resumable CLASS+EE2/SYREN-NEW ns-response Latin hypercube; see ns_derivative_lhs.md.""" | |
| from __future__ import annotations | |
| import argparse | |
| import contextlib | |
| import hashlib | |
| import importlib | |
| import importlib.metadata | |
| import json | |
| import multiprocessing as mp | |
| import os | |
| from pathlib import Path | |
| import sys | |
| import time | |
| import traceback | |
| for variable in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"): | |
| os.environ[variable] = "1" | |
| import numpy as np # noqa: E402 -- thread limits must precede numerical imports | |
| from scipy.stats import qmc # noqa: E402 | |
| ROOT = ( | |
| Path( | |
| os.environ.get( | |
| "COSMICFISHPIE_REPO_ROOT", Path(__file__).resolve().parents[2].parent / "cosmicfishpie" | |
| ) | |
| ) | |
| .expanduser() | |
| .resolve() | |
| ) | |
| PROFILE_ROOT = Path(__file__).resolve().parent / "configs" | |
| sys.path.insert(0, str(ROOT)) | |
| NAMES = ("10^9As", "Omegam", "Omegab", "h", "ns", "w0", "wa", "mnu") | |
| BOUNDS = np.array( | |
| [ | |
| [1.7, 2.5], | |
| [0.24, 0.40], | |
| [0.04, 0.06], | |
| [0.61, 0.73], | |
| [0.92, 1.00], | |
| [-1.3, -0.7], | |
| [-0.7, 0.5], | |
| [0.0, 0.15], | |
| ] | |
| ) | |
| BACKENDS = ("class_ee2", "syren_new") | |
| PROFILES = ("class/ee2_ns_lhs.yaml", "symbolic/syren_new_photo.yaml") | |
| def stencil(ns: float, relative_step: float) -> tuple[str, float]: | |
| """Choose CFP's centered stencil or an inward four-point signed stencil.""" | |
| step = relative_step | |
| if ns * (1 - step) < BOUNDS[4, 0]: | |
| return "4PT_FWD", step | |
| if ns * (1 + step) > BOUNDS[4, 1]: | |
| return "4PT_FWD", -step | |
| return "3PT", step | |
| def differentiate(observable, parameters, relative_step, configuration): | |
| """Evaluate d/dns through the package's validated array derivative interface.""" | |
| from cosmicfishpie.fishermatrix.derivatives import derivatives | |
| method, signed_step = stencil(parameters["ns"], relative_step) | |
| result = derivatives( | |
| observable=observable, | |
| fiducial=parameters, | |
| freeparams={"ns": signed_step}, | |
| derivatives_type=method, | |
| observables_type=("plain",), | |
| feed_lvl=0, | |
| configuration=configuration, | |
| ).result["ns"] | |
| return result, method, parameters["ns"] * signed_step | |
| def sample_power(cosmology, h, k, redshifts): | |
| """Return [linear/nonlinear,z,k] total-matter power, in (Mpc/h)^3.""" | |
| physical_k = k * h | |
| values = [] | |
| for nonlinear, name in ((False, "Pk_l"), (True, "Pk_nl")): | |
| zs, ks = getattr(cosmology.results, name).get_knots() | |
| tolerance = 1e-12 | |
| if ( | |
| physical_k[0] < ks[0] - tolerance | |
| or physical_k[-1] > ks[-1] + tolerance | |
| or redshifts[0] < zs[0] - tolerance | |
| or redshifts[-1] > zs[-1] + tolerance | |
| ): | |
| raise ValueError( | |
| f"{name}: requested grid exceeds spline support: " | |
| f"k=[{ks[0]}, {ks[-1]}], z=[{zs[0]}, {zs[-1]}]" | |
| ) | |
| values.append([cosmology.Pmm(z, physical_k, nonlinear=nonlinear) * h**3 for z in redshifts]) | |
| values = np.asarray(values) | |
| if not np.all(np.isfinite(values) & (values > 0)): | |
| raise FloatingPointError("Non-positive/non-finite power") | |
| return values | |
| def compute_backend(parameters, backend, k, zs, relative_step): | |
| """Compute one backend, caching the fiducial and all stencil evaluations.""" | |
| from cosmicfishpie.configs.context import build_analysis_context | |
| from cosmicfishpie.cosmology.cosmology import cosmo_functions | |
| index = BACKENDS.index(backend) | |
| if index == 0: | |
| parameters = {**parameters, "P_k_max_1/Mpc": 7.0 * parameters["h"]} | |
| profile = PROFILE_ROOT / PROFILES[index] | |
| yaml_key = "class_config_yaml" if index == 0 else "symbolic_config_yaml" | |
| context = build_analysis_context( | |
| options={ | |
| "code": "class" if index == 0 else "symbolic", | |
| yaml_key: str(profile), | |
| "cosmo_model": "w0waCDM", | |
| "nonlinear": True, | |
| "feedback": 0, | |
| "specs_dir": str(ROOT / "cosmicfishpie/configs/default_survey_specifications") + "/", | |
| }, | |
| observables=["GCph", "WL"], | |
| freepars={}, | |
| fiducialpars=parameters, | |
| survey_name="Euclid", | |
| cosmo_model="w0waCDM", | |
| ) | |
| fid = sample_power(context.fiducialcosmo, parameters["h"], k, zs) | |
| cache = {parameters["ns"]: fid} | |
| def observable(varied): | |
| ns = varied["ns"] | |
| if ns not in cache: | |
| cosmology = cosmo_functions(varied, configuration=context) | |
| cache[ns] = sample_power(cosmology, varied["h"], k, zs) | |
| power = cache[ns] | |
| return np.stack([power, np.log(power)]) | |
| result, method, step = differentiate(observable, parameters, relative_step, context) | |
| if not np.all(np.isfinite(result)): | |
| raise FloatingPointError("Non-finite derivative") | |
| return fid, result[0], result[1], method, step | |
| def worker(task): | |
| """Contain failures per backend; keep the other reference even on failure.""" | |
| index, row, k, zs, relative_step, log_dir = task | |
| parameters = dict(zip(NAMES, row.tolist())) | |
| effective_mnu = parameters["mnu"] | |
| records = [] | |
| for backend in BACKENDS: | |
| started = time.monotonic() | |
| log = Path(log_dir) / f"{index:04d}_{backend}.log" | |
| with ( | |
| log.open("w") as stream, | |
| contextlib.redirect_stdout(stream), | |
| contextlib.redirect_stderr(stream), | |
| ): | |
| try: | |
| result = compute_backend(parameters, backend, k, zs, relative_step) | |
| records.append({"status": 1, "result": result}) | |
| except Exception as exc: | |
| # Exact zero is not normally drawn by a scrambled LHS. Only retry | |
| # massless/near-massless failures, and record the changed input. | |
| if backend == "class_ee2" and parameters["mnu"] <= 1e-6: | |
| try: | |
| effective_mnu = 1e-6 | |
| result = compute_backend( | |
| {**parameters, "mnu": effective_mnu}, backend, k, zs, relative_step | |
| ) | |
| records.append({"status": 1, "result": result, "fallback": str(exc)}) | |
| except Exception: | |
| traceback.print_exc() | |
| records.append({"status": -1, "error": traceback.format_exc()}) | |
| else: | |
| traceback.print_exc() | |
| records.append({"status": -1, "error": traceback.format_exc()}) | |
| records[-1]["seconds"] = time.monotonic() - started | |
| return index, records, effective_mnu | |
| def identity(path): | |
| """Record a source file's identity for reproducibility.""" | |
| return {"path": str(path), "sha256": hashlib.sha256(path.read_bytes()).hexdigest()} | |
| def run(args): | |
| """Create or resume memory-mapped arrays; only the parent writes checkpoints.""" | |
| output = args.output_dir.resolve() | |
| output.mkdir(parents=True, exist_ok=True) | |
| log_dir = output / "logs" | |
| log_dir.mkdir(exist_ok=True) | |
| k, zs = np.geomspace(0.009, 6.8, args.k_samples), np.linspace(0, 3, 10) | |
| settings = { | |
| "n_points": args.n_points, | |
| "seed": args.seed, | |
| "k_samples": args.k_samples, | |
| "relative_step": args.relative_step, | |
| } | |
| metadata_file = output / "metadata.json" | |
| shape = (args.n_points, 2, 2, len(zs), len(k)) | |
| specs = { | |
| "power": (shape, "f8", np.nan), | |
| "dP_dns": (shape, "f8", np.nan), | |
| "dlnP_dns": (shape, "f8", np.nan), | |
| "status": ((args.n_points, 2), "i1", 0), | |
| "seconds": ((args.n_points, 2), "f8", np.nan), | |
| "signed_step": ((args.n_points, 2), "f8", np.nan), | |
| "effective_mnu": ((args.n_points, 2), "f8", np.nan), | |
| } | |
| if metadata_file.exists(): | |
| if not args.resume: | |
| raise ValueError("Output exists; choose a fresh directory or --resume") | |
| metadata = json.loads(metadata_file.read_text()) | |
| if metadata["settings"] != settings: | |
| raise ValueError("Resume settings differ from original campaign") | |
| for record in metadata["sources"].values(): | |
| if identity(Path(record["path"])) != record: | |
| raise ValueError(f"Source changed since campaign: {record['path']}") | |
| points = np.load(output / "params.npy") | |
| arrays = {name: np.load(output / f"{name}.npy", mmap_mode="r+") for name in specs} | |
| else: | |
| if args.resume: | |
| raise ValueError("Cannot resume: metadata.json missing") | |
| points = qmc.scale( | |
| qmc.LatinHypercube(d=8, seed=args.seed).random(args.n_points), | |
| BOUNDS[:, 0], | |
| BOUNDS[:, 1], | |
| ) | |
| for name, values in (("params", points), ("k_hmpc", k), ("redshifts", zs)): | |
| np.save(output / f"{name}.npy", values) | |
| arrays = {} | |
| for name, (size, dtype, fill) in specs.items(): | |
| arrays[name] = np.lib.format.open_memmap( | |
| output / f"{name}.npy", mode="w+", dtype=dtype, shape=size | |
| ) | |
| arrays[name][:] = fill | |
| arrays[name].flush() | |
| packages = {} | |
| for name in ("numpy", "scipy", "classy", "euclidemu2", "symbolic_pofk"): | |
| module = importlib.import_module(name) | |
| try: | |
| version = importlib.metadata.version(name) | |
| except importlib.metadata.PackageNotFoundError: | |
| version = getattr(module, "__version__", "unknown") | |
| packages[name] = {"version": version, "file": module.__file__} | |
| source_paths = {"runner": Path(__file__)} | |
| for name in ( | |
| "cosmicfishpie.fishermatrix.derivatives", | |
| "cosmicfishpie.cosmology.cosmology", | |
| "cosmicfishpie.cosmology.ee2", | |
| "cosmicfishpie.cosmology.symbolic_new", | |
| "symbolic_pofk.syren_new", | |
| "symbolic_pofk.linear_new", | |
| ): | |
| source_paths[name] = Path(importlib.import_module(name).__file__) | |
| for profile in PROFILES: | |
| source_paths[profile] = PROFILE_ROOT / profile | |
| metadata = { | |
| "settings": settings, | |
| "parameter_names": NAMES, | |
| "bounds": BOUNDS.tolist(), | |
| "backends": BACKENDS, | |
| "axes": ["point", "backend", "linear/nonlinear", "z", "k"], | |
| "power_units": "(Mpc/h)^3", | |
| "derivative": "fixed As, d/dns", | |
| "status_codes": {"0": "pending", "1": "success", "-1": "failed"}, | |
| "packages": packages, | |
| "sources": {n: identity(p) for n, p in source_paths.items()}, | |
| "python": sys.executable, | |
| "created_unix": time.time(), | |
| "workers": args.workers, | |
| "paper": "https://arxiv.org/html/2410.14623v1#S3", | |
| } | |
| metadata_file.write_text(json.dumps(metadata, indent=2) + "\n") | |
| pending = np.flatnonzero(np.any(arrays["status"] == 0, axis=1)) | |
| tasks = [(i, points[i], k, zs, args.relative_step, str(log_dir)) for i in pending] | |
| started = time.monotonic() | |
| print(f"Starting {len(tasks)} points, {args.workers} workers, output={output}", flush=True) | |
| # Spawn avoids sharing CLASS/global configuration state across workers. | |
| with mp.get_context("spawn").Pool(args.workers, maxtasksperchild=5) as pool: | |
| for count, (index, records, effective_mnu) in enumerate( | |
| pool.imap_unordered(worker, tasks, chunksize=1), 1 | |
| ): | |
| for b, record in enumerate(records): | |
| if arrays["status"][index, b] != 0: | |
| continue | |
| arrays["seconds"][index, b] = record["seconds"] | |
| arrays["effective_mnu"][index, b] = effective_mnu if b == 0 else points[index, -1] | |
| if record["status"] == 1: | |
| fid, derivative, response, method, step = record["result"] | |
| for name, values in ( | |
| ("power", fid), | |
| ("dP_dns", derivative), | |
| ("dlnP_dns", response), | |
| ("signed_step", step), | |
| ): | |
| arrays[name][index, b] = values | |
| else: | |
| print( | |
| f"FAILED point={index} backend={BACKENDS[b]} " | |
| f"{record['error'].splitlines()[-1]}", | |
| flush=True, | |
| ) | |
| with (output / "events.jsonl").open("a") as stream: | |
| stream.write( | |
| json.dumps( | |
| { | |
| "point": int(index), | |
| "backend": BACKENDS[b], | |
| **{key: value for key, value in record.items() if key != "result"}, | |
| } | |
| ) | |
| + "\n" | |
| ) | |
| # Flush data before status: an interrupted write is safely recomputed. | |
| for name, array in arrays.items(): | |
| if name != "status": | |
| array.flush() | |
| arrays["status"][index, b] = record["status"] | |
| arrays["status"].flush() | |
| if count % 10 == 0 or count == len(tasks): | |
| ok = (arrays["status"] == 1).sum(axis=0).tolist() | |
| failed = (arrays["status"] == -1).sum(axis=0).tolist() | |
| print( | |
| f"{count}/{len(tasks)} new points; successes={ok}; failures={failed}; " | |
| f"elapsed={(time.monotonic()-started)/60:.1f} min", | |
| flush=True, | |
| ) | |
| metadata["finished_unix"] = time.time() | |
| metadata["successes"] = (arrays["status"] == 1).sum(axis=0).tolist() | |
| metadata["failures"] = (arrays["status"] == -1).sum(axis=0).tolist() | |
| metadata_file.write_text(json.dumps(metadata, indent=2) + "\n") | |
| def main(): | |
| """Parse the command line and start the campaign.""" | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--output-dir", type=Path, required=True) | |
| parser.add_argument("--n-points", type=int, default=1000) | |
| parser.add_argument("--seed", type=int, default=241014623) | |
| parser.add_argument("--k-samples", type=int, default=240) | |
| parser.add_argument("--workers", type=int, default=8) | |
| parser.add_argument("--relative-step", type=float, default=0.01) | |
| parser.add_argument("--resume", action="store_true") | |
| args = parser.parse_args() | |
| if min(args.n_points, args.workers) < 1 or args.k_samples < 4: | |
| parser.error("Positive point/worker counts and at least four k samples required") | |
| if not 0 < args.relative_step <= 0.01: | |
| parser.error("Use 0 < relative-step <= .01 to keep inward stencils in the EE2 box") | |
| run(args) | |
| if __name__ == "__main__": | |
| main() | |