File size: 14,810 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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
#!/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()