glass.ext.extend 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,16 @@
1
+ """
2
+ glass.ext.extend: conditional sampling for the high-redshift extension of N-body lightcones.
3
+
4
+ Implements the method of "Conditional random field sampling for high-redshift
5
+ extensions of lightcone simulations with application to CMB lensing"
6
+ (Fusari, Jeffrey, Joachimi, in prep).
7
+
8
+ The production and validation drivers are base-suite-agnostic; suite-specific
9
+ knowledge lives in the loaders:
10
+ glass.ext.extend.loaders.gowerstreet Gower Street loader (shells, edges, HDF5-first
11
+ cosmology with hard stops on missing parameters)
12
+ glass.ext.extend.loaders.gowerstreet2 Gower Street 2 loader (same interface)
13
+ glass.ext.extend.loaders.cosmogrid CosmoGridV1 loader (same interface)
14
+ glass.ext.extend.loaders.agora Agora loader (same interface)
15
+ glass.ext.extend.paths dispatches base-simulation resolution to the loaders
16
+ """
@@ -0,0 +1,169 @@
1
+ """glass.ext.extend.cli: the one-call user entry point.
2
+
3
+ `glass-extend` runs production plus validation in one command (README: Usage).
4
+ It runs the two drivers as subprocesses so each stage keeps its own logs, flags
5
+ and exit codes; a validation failure never masks a production success.
6
+
7
+ `glass-extend-produce` / `glass-extend-validate` expose the drivers standalone via runpy passthrough.
8
+ """
9
+
10
+ import argparse
11
+ import runpy
12
+ import subprocess
13
+ import sys
14
+
15
+ VALIDATION_FLAVOURS = {
16
+ # name -> (extra validate flags, output tag)
17
+ "uncorrected": (["--no-corrected-theory"], "uncorr"),
18
+ "corrected": (["--corrected-theory"], "corr"),
19
+ }
20
+
21
+ MATTER_CLS_FLAGS = {
22
+ # --matter-cls choice -> producer flags, both always explicit
23
+ "biaskz": ["--matter-cls-biaskz", "--no-matter-cls-total"],
24
+ "total": ["--matter-cls-total", "--no-matter-cls-biaskz"],
25
+ "cdm": ["--no-matter-cls-biaskz", "--no-matter-cls-total"],
26
+ }
27
+
28
+
29
+ def build_parser():
30
+ p = argparse.ArgumentParser(
31
+ prog="glass-extend",
32
+ description="glass.ext.extend one-call runner: production + validation.")
33
+ p.add_argument("--sim", required=True,
34
+ help="base-simulation directory (e.g. data_gower/sim00230)")
35
+ p.add_argument("--suite", default="gowerstreet",
36
+ choices=["gowerstreet", "gowerstreet2", "cosmogrid", "agora"],
37
+ help="base-simulation suite (selects the per-suite loader)")
38
+ p.add_argument("--out", default=None,
39
+ help="output directory (default: auto-derived production_runs/grid_... name)")
40
+ # physics flags, passed straight through to the producer
41
+ p.add_argument("--nside", type=int, default=2048)
42
+ p.add_argument("--num-shells", type=int, default=100)
43
+ p.add_argument("--delta-chi", type=float, default=400.0)
44
+ p.add_argument("--shift", type=float, default=1.0)
45
+ p.add_argument("--ladder-theory", default="nonlinear",
46
+ choices=["linear", "nonlinear"],
47
+ help="theory spectra used by the ladder recipe (default nonlinear)")
48
+ p.add_argument("--ladder-pixwin", action=argparse.BooleanOptionalAction, default=True,
49
+ help="imprint the pixel window on the ladder recipe (on by default)")
50
+ p.add_argument("--matter-cls", default="biaskz", choices=list(MATTER_CLS_FLAGS),
51
+ help="shell spectra: biaskz = total matter via a CAMB b(k,z) table, the "
52
+ "form of glass.ext.camb pull request 23 (default); total = total "
53
+ "matter via sqrt(R_i R_j) scaling of the pairs; cdm = cold dark "
54
+ "matter only")
55
+ p.add_argument("--autocal", action=argparse.BooleanOptionalAction, default=False,
56
+ help="auto-calibrate A_s on the base shells (off by default: "
57
+ "the simulation's stated A_s is used)")
58
+ p.add_argument("--tag", default="")
59
+ # validation plan
60
+ p.add_argument("--validations", default="corrected",
61
+ help="comma list from: %s (or 'none')" % ",".join(VALIDATION_FLAVOURS))
62
+ p.add_argument("--theory-mode", default="class_hmcode")
63
+ p.add_argument("--ell-cutoff", type=int, default=1500)
64
+ p.add_argument("--skip-produce", action="store_true",
65
+ help="rerun validations on an existing --out directory")
66
+ return p
67
+
68
+
69
+ def derive_output_dir(args):
70
+ """Mirror the producer's auto-naming when --out is not given."""
71
+ if args.out:
72
+ out = args.out
73
+ else:
74
+ import os
75
+ if getattr(args, "suite", "gowerstreet") == "cosmogrid":
76
+ # mirror the producer: cosmogrid dirs are named by the loader's short
77
+ # name (run_0009 -> cg0009) so the validator can recognise the suite
78
+ from glass.ext.extend.loaders.cosmogrid import resolve as _cg_resolve
79
+ _, sim_name = _cg_resolve(args.sim)
80
+ elif getattr(args, "suite", "gowerstreet") == "agora":
81
+ # mirror the producer: agora.resolve always returns the fixed short
82
+ # name 'agora' regardless of the directory's actual basename (e.g.
83
+ # data_agora), so the validator's --input must match that, not
84
+ # os.path.basename(args.sim)
85
+ from glass.ext.extend.loaders.agora import resolve as _agora_resolve
86
+ _, sim_name = _agora_resolve(sim_dir=args.sim)
87
+ else:
88
+ sim_name = os.path.basename(os.path.normpath(args.sim))
89
+ # the suite always leads the name, mirroring the producer
90
+ parts = [getattr(args, "suite", "gowerstreet"),
91
+ f"grid_{args.nside}", f"dchi{int(args.delta_chi)}", f"sh{args.num_shells}"]
92
+ if args.shift != 1.0:
93
+ parts.append(f"shift{args.shift}")
94
+ out = "production_runs/" + "_".join(parts + [sim_name])
95
+ if args.tag:
96
+ out = out if out.endswith(args.tag) else f"{out}_{args.tag}"
97
+ return out
98
+
99
+
100
+ def build_plan(args):
101
+ """Pure: turn parsed args into the ordered list of subprocess argv lists."""
102
+ plan = []
103
+ py = sys.executable
104
+ if not args.skip_produce:
105
+ cmd = [py, "-m", "glass.ext.extend.produce",
106
+ "--sim-dir", args.sim,
107
+ "--nside", str(args.nside),
108
+ "--num-shells", str(args.num_shells),
109
+ "--delta-chi", str(args.delta_chi),
110
+ "--shift", str(args.shift)]
111
+ if getattr(args, "suite", "gowerstreet") != "gowerstreet":
112
+ cmd += ["--suite", args.suite]
113
+ # recipe flags are always passed explicitly, so the producer's log
114
+ # records the full recipe
115
+ cmd += ["--ladder-theory", args.ladder_theory,
116
+ "--ladder-pixwin" if args.ladder_pixwin else "--no-ladder-pixwin",
117
+ *MATTER_CLS_FLAGS[args.matter_cls],
118
+ "--autocal" if args.autocal else "--no-autocal"]
119
+ if args.tag:
120
+ cmd += ["--tag", args.tag]
121
+ if args.out:
122
+ cmd += ["--out", args.out]
123
+ plan.append(("produce", cmd))
124
+
125
+ out_dir = derive_output_dir(args)
126
+ if args.validations.strip().lower() != "none":
127
+ for name in [v.strip() for v in args.validations.split(",") if v.strip()]:
128
+ if name not in VALIDATION_FLAVOURS:
129
+ raise SystemExit(f"glass-extend: unknown validation flavour '{name}' "
130
+ f"(choose from {', '.join(VALIDATION_FLAVOURS)})")
131
+ extra, tag = VALIDATION_FLAVOURS[name]
132
+ cmd = [py, "-m", "glass.ext.extend.validate",
133
+ "--input", out_dir,
134
+ "--theory-mode", args.theory_mode,
135
+ "--ell-cutoff", str(args.ell_cutoff),
136
+ "--tag", tag] + extra
137
+ if getattr(args, "suite", "gowerstreet") != "gowerstreet":
138
+ cmd += ["--suite", args.suite]
139
+ plan.append((f"validate[{name}]", cmd))
140
+ return plan
141
+
142
+
143
+ def main(argv=None):
144
+ args = build_parser().parse_args(argv)
145
+ plan = build_plan(args)
146
+ print(f"glass-extend: {len(plan)} stages planned")
147
+ for stage, cmd in plan:
148
+ print(f"glass-extend: --- {stage} ---")
149
+ rc = subprocess.call(cmd)
150
+ if rc != 0:
151
+ print(f"glass-extend: stage '{stage}' failed (exit {rc}); stopping here. "
152
+ f"Completed stages are preserved.", file=sys.stderr)
153
+ return rc
154
+ print("glass-extend: all stages complete")
155
+ return 0
156
+
157
+
158
+ def produce_passthrough():
159
+ """Console entry `glass-extend-produce`: run the producer with sys.argv passthrough."""
160
+ runpy.run_module("glass.ext.extend.produce", run_name="__main__")
161
+
162
+
163
+ def validate_passthrough():
164
+ """Console entry `glass-extend-validate`: run the validator with sys.argv passthrough."""
165
+ runpy.run_module("glass.ext.extend.validate", run_name="__main__")
166
+
167
+
168
+ if __name__ == "__main__":
169
+ sys.exit(main())
@@ -0,0 +1,121 @@
1
+ """glass.ext.extend.corrections: Takahashi-style benchmark correction (shared).
2
+
3
+ theory × pixwin²(NSIDE) + Born-weighted base shot noise: known measurement
4
+ effects are added to the benchmark (correcting it, not replacing it; cf.
5
+ Takahashi et al. 2017, Eq. 5). Used by both the validator (--corrected-theory)
6
+ and glass-extend-pilotfig (--target corrected), so the physics lives in one place.
7
+ """
8
+
9
+ import os
10
+ import re
11
+
12
+ import numpy as np
13
+ import healpy as hp
14
+
15
+
16
+ def born_base_shot_noise(production_dir, nside, suite="gowerstreet"):
17
+ """Born-weighted shot-noise floor of the base-simulation shells (kappa C_SN).
18
+
19
+ Reads the run's cosmology_used.txt for the cosmology and the base-sim
20
+ source path; per-shell counts come from the suite loader (cosmogrid) or
21
+ the mean-density volume estimate (gowerstreet). Raises on any missing
22
+ ingredient; the caller decides whether that is fatal.
23
+ """
24
+ import camb
25
+ import glass as _glass
26
+
27
+ txt = open(os.path.join(production_dir, "cosmology_used.txt")).read()
28
+
29
+ def _g(pat, default=None):
30
+ mm = re.search(pat, txt, re.MULTILINE)
31
+ return float(mm.group(1)) if mm else default
32
+
33
+ h = _g(r"^h:\s*([\d.eE+-]+)")
34
+ # base/ladder boundary of the run (runs written before the flag existed used 2.0)
35
+ z_max_base = _g(r"^z_max_base:\s*([\d.eE+-]+)", 2.0)
36
+ sim_dir = None
37
+ for line in txt.splitlines():
38
+ if line.startswith("Source:"):
39
+ sim_dir = line.split("Source:", 1)[1].strip()
40
+ break
41
+
42
+ pars = camb.set_params(
43
+ H0=100 * h, ombh2=_g(r"^omega_b:\s*([\d.eE+-]+)") * h ** 2,
44
+ omch2=_g(r"^omega_cdm:\s*([\d.eE+-]+)") * h ** 2,
45
+ ns=_g(r"^n_s:\s*([\d.eE+-]+)"), As=2.1e-9,
46
+ mnu=_g(r"^mnu:\s*([\d.eE+-]+)"),
47
+ # runs written before num_massive_nu was recorded all used 3
48
+ num_massive_neutrinos=int(_g(r"^num_massive_nu:\s*(\d+)", 3)))
49
+ w0 = _g(r"^w0:\s*([+-]?[\d.eE+-]+)")
50
+ if w0 is not None and w0 != -1.0:
51
+ pars.set_dark_energy(w=w0)
52
+ res = camb.get_background(pars)
53
+
54
+ if suite == "cosmogrid":
55
+ from glass.ext.extend.loaders.cosmogrid import get_shell_zgrid, get_shell_totals
56
+ base_z = get_shell_zgrid(sim_dir)
57
+ totals = get_shell_totals(sim_dir, nside)
58
+ elif suite == "agora":
59
+ # Exact per-shell counts, as for cosmogrid. Agora's shells are full
60
+ # density (the measured mean matches the particle-density-times-volume
61
+ # prediction to 0.03%), so the shot-noise term is small either way.
62
+ # Measured totals from get_shell_totals are still preferred over the
63
+ # gowerstreet-style theoretical estimate in the `else` branch below,
64
+ # as for cosmogrid.
65
+ from glass.ext.extend.loaders.agora import get_shell_zgrid, get_shell_totals
66
+ base_z = get_shell_zgrid(sim_dir)
67
+ totals = get_shell_totals(sim_dir, nside)
68
+ else:
69
+ import glass.ext.pkdgrav as _gep
70
+ base_z = np.asarray(_gep.load(os.path.join(sim_dir, "control.par")).redshifts)
71
+ totals = None
72
+ ngrid = _g(r"^n_grid:\s*([\d.eE+-]+)", 1080.0)
73
+ box = _g(r"^box_size:\s*([\d.eE+-]+)", 1250.0)
74
+
75
+ wins = list(_glass.tophat_windows(base_z))
76
+ chi_s = res.comoving_radial_distance(1100.0)
77
+ c_sn = 0.0
78
+ for iw, w in enumerate(wins):
79
+ if w.zeff > z_max_base: # only base shells carry particle shot noise
80
+ continue
81
+ z = w.zeff
82
+ chi = res.comoving_radial_distance(z) * h
83
+ dchi = (res.comoving_radial_distance(float(np.max(w.za)))
84
+ - res.comoving_radial_distance(float(np.min(w.za)))) * h
85
+ if dchi <= 0 or chi <= 0 or chi >= chi_s * h:
86
+ continue
87
+ wk = (1.5 * pars.omegam * (1.0 / 2997.92458) ** 2
88
+ * (1 + z) * chi * (1 - chi / (chi_s * h)) * dchi)
89
+ if totals is not None:
90
+ n_shell = float(totals[iw])
91
+ else:
92
+ vol = 4 * np.pi / 3 * ((chi + dchi / 2) ** 3 - (chi - dchi / 2) ** 3)
93
+ n_shell = ngrid ** 3 * vol / box ** 3
94
+ c_sn += wk ** 2 * 4 * np.pi / n_shell
95
+ return c_sn
96
+
97
+
98
+ def corrected_benchmark(cl_theory, nside, production_dir, suite="gowerstreet",
99
+ warn=None):
100
+ """theory × pixwin² + C_SN. Returns (cl_corrected, C_SN).
101
+
102
+ C_SN is best-effort: on failure it is 0.0 and `warn` (if given) is called
103
+ with the reason. The pixwin² part always applies.
104
+ """
105
+ lmax = len(cl_theory) - 1
106
+ if lmax > 1.5 * nside and warn is not None:
107
+ # At l/NSIDE ~ 2 the map no longer loses the full pixwin factor
108
+ # (aliasing + shot-noise floor) and the corrected ratio rises by ~20%
109
+ # (NSIDE 512); the model is only reliable up to l ~ 1.5 NSIDE.
110
+ warn(f"lmax={lmax} > 1.5*NSIDE={int(1.5 * nside)}: pixwin correction is "
111
+ f"outside its validity range; judge only l <~ {int(1.4 * nside)}")
112
+ pw2 = hp.pixwin(nside, lmax=lmax) ** 2
113
+ cl = cl_theory * pw2[:len(cl_theory)]
114
+ c_sn = 0.0
115
+ try:
116
+ c_sn = born_base_shot_noise(production_dir, nside, suite)
117
+ cl = cl + c_sn
118
+ except Exception as e:
119
+ if warn is not None:
120
+ warn(f"shot-noise term skipped ({e}); pixwin^2 only")
121
+ return cl, c_sn
File without changes