diff --git a/README.md b/README.md index 36d5589e..48edc5ea 100644 --- a/README.md +++ b/README.md @@ -96,18 +96,6 @@ uv venv --python 3.12 uv pip install -e '.[test]' ``` -To also install the data-vector blinding stack (Smokescreen + firecrown, PRD -[#241](https://github.com/CosmoStat/sp_validation/issues/241)), pass the -dependency-override file — firecrown is not pip-resolvable without it (see -`uv-overrides.txt` for why): - -```bash -uv pip install --overrides uv-overrides.txt -e '.[test,blinding]' -python scripts/patch_firecrown.py # make pip-installed firecrown importable without NumCosmo -``` - - - ## Flow chart The following flow chart illustrates the steps required to go from ShapePipe output products diff --git a/cosmo_inference/cosmosis_config/cosmosis_pipeline_A_ia.ini b/cosmo_inference/cosmosis_config/cosmosis_pipeline_A_ia.ini new file mode 100644 index 00000000..eb3ab166 --- /dev/null +++ b/cosmo_inference/cosmosis_config/cosmosis_pipeline_A_ia.ini @@ -0,0 +1,108 @@ +#parameters used elsewhere in this file +[DEFAULT] +COSMOSIS_DIR = /n23data1/n06data/lgoh/scratch/cosmosis-standard-library_lisa + + +[pipeline] +modules = consistency sample_S8 camb load_nz_fits photoz_bias linear_alignment projection add_intrinsic 2pt_shear shear_m_bias 2pt_like +likelihoods = 2pt_like +extra_output = cosmological_parameters/omega_lambda cosmological_parameters/S_8 cosmological_parameters/sigma_8 cosmological_parameters/omega_m +timing = T +debug = T + +[runtime] +sampler = polychord +verbosity = debug + +[polychord] +live_points = 192 +feedback = 3 +resume = T +base_dir = %(SCRATCH)s/polychord + +[test] + +[output] +format = text +lock = F + +[consistency] +file = %(COSMOSIS_DIR)s/utility/consistency/consistency_interface.py +verbose = F + +[sample_S8] +file = %(COSMOSIS_DIR)s/utility/sample_sigma8/sample_S8.py + +[camb] +file = %(COSMOSIS_DIR)s/boltzmann/camb/camb_interface.py +mode=power +lmax=2508 +feedback=0 +do_reionization=F +kmin=1e-5 +kmax=20.0 +nk=200 +zmax=5.0 +zmax_background=5.0 +nz_background=500 +halofit_version=mead2020_feedback +nonlinear=pk +neutrino_hierarchy=normal +kmax_extrapolate = 500.0 + +[load_nz_fits] +file = %(COSMOSIS_DIR)s/number_density/load_nz_fits/load_nz_fits.py +nz_file =%(FITS_FILE)s +data_sets = SOURCE + +[photoz_bias] +file = %(COSMOSIS_DIR)s/number_density/photoz_bias/photoz_bias.py +mode = additive +sample = nz_source +bias_section = nofz_shifts +interpolation = cubic +output_deltaz_section_name = delta_z_out + +[linear_alignment] +file = %(COSMOSIS_DIR)s/intrinsic_alignments/la_model/linear_alignments_interface_znla.py +method = bk_corrected + +[projection] +file = %(COSMOSIS_DIR)s/structure/projection/project_2d.py +ell_min_logspaced = 1.0 +ell_max_logspaced = 25000.0 +n_ell_logspaced = 400 +shear-shear = source-source +shear-intrinsic = source-source +intrinsic-intrinsic = source-source +get_kernel_peaks = F +verbose = F + +[add_intrinsic] +file = %(COSMOSIS_DIR)s/shear/add_intrinsic/add_intrinsic.py +shear-shear=T +position-shear=F +perbin=F + +[2pt_shear] +file = %(COSMOSIS_DIR)s/shear/cl_to_xi_nicaea/nicaea_interface.so +corr_type = 0 ; shear_cl -> shear_xi + +[shear_m_bias] +file = %(COSMOSIS_DIR)s/shear/shear_bias/shear_m_bias.py +m_per_bin = True +; Despite the parameter name, this can operate on xi as well as C_ell. +cl_section = shear_xi_plus shear_xi_minus +verbose = F + +[2pt_like] +file = %(COSMOSIS_DIR)s/likelihood/2pt/2pt_like.py +data_file=%(FITS_FILE)s +gaussian_covariance=F +covmat_name=COVMAT +cut_zeros=F +data_sets=XI_PLUS XI_MINUS +like_name=2pt_like + +angle_range_XI_PLUS_1_1= 10.0 200.0 +angle_range_XI_MINUS_1_1= 20.0 200.0 \ No newline at end of file diff --git a/cosmo_inference/cosmosis_config/cosmosis_pipeline_A_ia_sacc.ini b/cosmo_inference/cosmosis_config/cosmosis_pipeline_A_ia_sacc.ini new file mode 100644 index 00000000..5c31a476 --- /dev/null +++ b/cosmo_inference/cosmosis_config/cosmosis_pipeline_A_ia_sacc.ini @@ -0,0 +1,110 @@ +#parameters used elsewhere in this file +[DEFAULT] +COSMOSIS_DIR = /n23data1/n06data/lgoh/scratch/cosmosis-standard-library_lisa + + +[pipeline] +modules = consistency sample_S8 camb load_nz_sacc photoz_bias linear_alignment projection add_intrinsic 2pt_shear shear_m_bias sacc_like +likelihoods = 2pt_like +extra_output = cosmological_parameters/omega_lambda cosmological_parameters/S_8 cosmological_parameters/sigma_8 cosmological_parameters/omega_m +timing = T +debug = T + +[runtime] +sampler = polychord +verbosity = debug + +[polychord] +live_points = 192 +feedback = 3 +resume = T +base_dir = %(SCRATCH)s/polychord + +[test] + +[output] +format = text +lock = F + +[consistency] +file = %(COSMOSIS_DIR)s/utility/consistency/consistency_interface.py +verbose = F + +[sample_S8] +file = %(COSMOSIS_DIR)s/utility/sample_sigma8/sample_S8.py + +[camb] +file = %(COSMOSIS_DIR)s/boltzmann/camb/camb_interface.py +mode=power +lmax=2508 +feedback=0 +do_reionization=F +kmin=1e-5 +kmax=20.0 +nk=200 +zmax=5.0 +zmax_background=5.0 +nz_background=500 +halofit_version=mead2020_feedback +nonlinear=pk +neutrino_hierarchy=normal +kmax_extrapolate = 500.0 + +[load_nz_sacc] +file = %(COSMOSIS_DIR)s/number_density/load_nz_sacc/load_nz_sacc.py +nz_file = %(SACC_FILE)s +data_sets = source + +[photoz_bias] +file = %(COSMOSIS_DIR)s/number_density/photoz_bias/photoz_bias.py +mode = additive +sample = nz_source +bias_section = nofz_shifts +interpolation = cubic +output_deltaz_section_name = delta_z_out + +[linear_alignment] +file = %(COSMOSIS_DIR)s/intrinsic_alignments/la_model/linear_alignments_interface_znla.py +method = bk_corrected + +[projection] +file = %(COSMOSIS_DIR)s/structure/projection/project_2d.py +ell_min_logspaced = 1.0 +ell_max_logspaced = 25000.0 +n_ell_logspaced = 400 +shear-shear = source-source +shear-intrinsic = source-source +intrinsic-intrinsic = source-source +get_kernel_peaks = F +verbose = F + +[add_intrinsic] +file = %(COSMOSIS_DIR)s/shear/add_intrinsic/add_intrinsic.py +shear-shear=T +position-shear=F +perbin=F + +[2pt_shear] +file = %(COSMOSIS_DIR)s/shear/cl_to_xi_nicaea/nicaea_interface.so +corr_type = 0 ; shear_cl -> shear_xi + +[shear_m_bias] +file = %(COSMOSIS_DIR)s/shear/shear_bias/shear_m_bias.py +m_per_bin = True +; Despite the parameter name, this can operate on xi as well as C_ell. +cl_section = shear_xi_plus shear_xi_minus +verbose = F + +; Native SACC likelihood via the sp_validation shim (arcmin->rad + ordering +; guard over CosmoSIS's SaccClLikelihood). data_sets/angle ranges use the SACC +; grammar (full data-type names + tracer pairs). like_name=2pt_like keeps the +; block keys identical to the 2pt_like path so chain post-processing is unchanged. +[sacc_like] +file = %(SP_VALIDATION_MODULES)s/sacc_like_unions.py +csl_dir = %(COSMOSIS_DIR)s +data_file = %(SACC_FILE)s +data_sets = galaxy_shear_xi_plus galaxy_shear_xi_minus +like_name = 2pt_like + +angle_range_galaxy_shear_xi_plus_source_0_source_0 = 10.0 200.0 +angle_range_galaxy_shear_xi_minus_source_0_source_0 = 20.0 200.0 diff --git a/papers/cosmo_val/config/config.yaml b/papers/cosmo_val/config/config.yaml index 89425ff0..024b7c85 100644 --- a/papers/cosmo_val/config/config.yaml +++ b/papers/cosmo_val/config/config.yaml @@ -121,11 +121,14 @@ harmonic: binning: powspace nbins: 32 -# Cosmological inference data-product locations (dormant subsystem). +# Cosmological inference data-product locations + tooling. inference: chains_dir: "/n09data/guerrini/output_chains" glass_mock_data_dir: "/n09data/guerrini/glass_mock_v1.4.6/results" glass_mock_chains_dir: "/n09data/guerrini/glass_mock_chains" + # CosmoSIS Standard Library checkout — fills COSMOSIS_DIR in the generated + # pipeline inis (the module `file =` paths and the sacc_like shim's csl_dir). + csl_dir: "/n23data1/n06data/lgoh/scratch/cosmosis-standard-library_lisa" cosebis: theta_min: 1.0 diff --git a/pyproject.toml b/pyproject.toml index d278d3f7..572b1394 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -160,6 +160,14 @@ workflow = [ # published or resolvable (no public repo found) — left undeclared pending # its source. Same for `unions_wl` (scripts/check_footprint.py). ] +# Native SACC inference likelihood (sp_validation.sacc_like_unions), which +# subclasses CosmoSIS's SaccClLikelihood. The engine modules it needs are pure +# python, so tests/test_sacc_like.py runs with just this extra plus a CosmoSIS +# Standard Library checkout pointed at by CSL_DIR: +# git clone --depth 1 https://github.com/joezuntz/cosmosis-standard-library CSL +# CSL_DIR=/path/to/CSL pytest ... test_sacc_like.py +# Not installed by the container image, so inert in CI. +cosmosis = ["cosmosis>=3.25"] develop = ["sp_validation[test,docs]"] [tool.pytest.ini_options] diff --git a/src/sp_validation/sacc_like_unions.py b/src/sp_validation/sacc_like_unions.py new file mode 100644 index 00000000..ec6e8722 --- /dev/null +++ b/src/sp_validation/sacc_like_unions.py @@ -0,0 +1,225 @@ +"""SACC likelihood shim for CosmoSIS — the sp_validation-owned native path. + +This module is a thin subclass of CosmoSIS's ``SaccClLikelihood`` (from the +CosmoSIS Standard Library, ``likelihood/sacc/sacc_like.py``) that fixes two +upstream defects so the native SACC likelihood matches the converter → +``2pt_like`` path bit for bit on our real-space ξ± analysis file. It exists as a +CosmoSIS *module file* (``setup``/``execute``/``cleanup`` at module scope), loaded +via ``file = .../sacc_like_unions.py`` in an ini, and is NOT imported by +``sp_validation/__init__`` (cosmosis is an optional dependency). + +Why the shim exists +------------------- +Two things in upstream ``sacc_like`` break a real-space ξ likelihood; both are +documented and empirically verified (probe: Δχ²=3184 raw vs Δχ²=0 shimmed on the +single-bin analysis file), and both are fixed here by overriding ``build_data``: + +1. **No arcmin→radian conversion (the killer).** + ``sacc_likelihoods/twopoint.py`` (L74-90 at CSL commit 4fd2f1c) builds a + ``SpectrumInterp`` over ``block[section, "theta"]`` — theory θ in *radians* + (CosmoSIS convention) — and evaluates it at each data point's raw ``theta`` + tag, which our SACC files store in *arcmin*. ``2pt_like.py`` + (L179-183) converts its real-space data to radians for exactly this reason; + ``sacc_like`` never does, so the spline is evaluated ~3437× outside its grid, + ``SpectrumInterp`` returns 0 there, and χ² silently collapses to dᵀC⁻¹d. The + only prior use was the ℓ-space (unit-free) Cℓ path, which is why it was never + caught. We evaluate the theory against a radian-θ *copy* of the loaded SACC, + keeping ``self.sacc_data`` in arcmin so upstream's save_theory / + save_realization paths (which copy it and overwrite only values) never write + radian tags into a file downstream consumers read as arcmin. + +2. **Theory↔data ordering is assumed, never enforced.** + The data vector is ``sacc.get_mean()`` (insertion order); the theory vector is + built by looping ``get_data_types() × get_tracer_combinations() × points``. + A comment in ``twopoint.py`` (L35) claims ``to_canonical_order`` was called on + load — it is not. The two orders agree only when the file is grouped + type-major (all of one data type, then the next). Our single-pair + ``[ξ+; ξ−]`` files satisfy this; a tomographic *pair-major* file (ξ+/ξ− per + pair) would silently misalign theory against data. We reconstruct the + theory-loop index order and require it equals ``arange`` — a hard ValueError + otherwise (see ``test_ordering_guard_raises_pair_major_tomographic``). + +When upstream fixes the units, this shim dies: the tripwire test +``test_upstream_unit_gap_tripwire`` in ``tests/test_sacc_like.py`` fails the day +raw ``sacc_like`` stops producing a wildly different χ², signalling the shim can +be retired. + +Requires a CSL checkout: ``setup`` reads ``csl_dir`` from the module options and +imports the upstream ``sacc_like`` from ``/likelihood/sacc``. The tests +locate it via the ``CSL_DIR`` environment variable (see the test module docstring +for the checkout recipe). +""" + +import os +import sys + +import numpy as np + +# cosmosis is an OPTIONAL dependency: this module is a CosmoSIS module file, but +# importing it must succeed without cosmosis installed (the CI image has the +# science stack but no cosmosis, and test_imports.py bare-imports every module). +# So every cosmosis touch is deferred into setup() — nothing at top level imports +# it. numpy is fine at top level (always present). + +# arcmin → radian: the conversion 2pt_like applies to real-space data and that +# sacc_like omits. Applied only to `theta` tags of `real`-category data types. +ARCMIN_TO_RAD = np.pi / (180.0 * 60.0) + + +def _import_upstream_sacc_like(csl_dir): + """Import the upstream ``sacc_like`` module from a CSL checkout. + + ``/likelihood/sacc`` is prepended to ``sys.path`` so both + ``sacc_like`` and its sibling ``sacc_likelihoods`` package (imported by + ``sacc_like`` for the theory-extraction functions) resolve. Idempotent: the + path is only inserted once. + """ + sacc_dir = os.path.join(csl_dir, "likelihood", "sacc") + if not os.path.isdir(sacc_dir): + raise ValueError( + f"csl_dir={csl_dir!r} has no likelihood/sacc directory; point csl_dir " + "at a CosmoSIS Standard Library checkout (see module docstring)" + ) + if sacc_dir not in sys.path: + sys.path.insert(0, sacc_dir) + import sacc_like # noqa: E402 — resolved from the sys.path insertion above + + return sacc_like + + +def _make_subclass(sacc_like): + """Build ``SaccLikeUnions`` as a subclass of the upstream ``SaccClLikelihood``. + + A factory (not an import-time ``class ... :`` statement) so importing this + module never requires the upstream class — that dependency is deferred to + ``setup``, which has ``csl_dir`` in hand. Only ``build_data`` is overridden; + scale cuts, covariance handling (Sellentin/Hartlap), theory extraction and + ``save_theory`` all ride upstream unmodified. + """ + + class SaccLikeUnions(sacc_like.SaccClLikelihood): + """CSL ``SaccClLikelihood`` with the arcmin→rad + ordering-guard fixes.""" + + def build_data(self): + # Run the upstream build FIRST: it loads the SACC, applies data_sets + # selection and the arcmin-grammar scale cuts (matching 2pt_like's + # angle_range convention and the ini ergonomics), populates + # self.sacc_data / self.sections_for_names, and returns the + # (unit-independent) data vector we pass straight through. + x, data_vector = super().build_data() + + # self.sacc_data STAYS in arcmin — save_theory / save_realization copy + # it and only overwrite point values, so its θ tags must remain the + # units the file was written in (any consumer, incl. re-ingesting the + # saved SACC as a data_file, assumes arcmin). The radian conversion the + # theory spline needs lives on a separate copy, swapped in only for the + # extraction (see extract_theory_points). + self._sacc_data_rad = self._radian_theta_copy(self.sacc_data) + self._assert_theory_order_matches_data() + + return x, data_vector + + def _radian_theta_copy(self, sacc_data): + """A copy of ``sacc_data`` with ``real``-category θ tags in radians. + + The theory spline is built on ``block[section, "theta"]`` in radians, + so the ``theta`` tag each point is evaluated against must be radians + too. Scoped to data types whose category + (``sections_for_names[dt][0]``) is ``real``: cosebis ``n`` tags and + spectrum ``ell`` tags are unit-free and left untouched, and only the + ``theta`` tag is scaled (``theta_nom`` etc. are metadata the likelihood + never evaluates). Operates on a ``.copy()`` so the original stays + arcmin for the save paths. + """ + real_types = { + dt + for dt, (category, _section) in self.sections_for_names.items() + if category == "real" + } + converted = sacc_data.copy() + for point in converted.data: + if point.data_type in real_types and "theta" in point.tags: + point.tags["theta"] = point.tags["theta"] * ARCMIN_TO_RAD + return converted + + def extract_theory_points(self, block): + """Extract theory against the radian-θ copy, then restore the original. + + Upstream ``extract_theory_points`` reads ``self.sacc_data`` (the θ tag + per point) to evaluate the theory spline; that read needs radians. + Swap in ``self._sacc_data_rad`` for the duration of the upstream call + and restore in ``finally`` so everything else — including the + save_theory / save_realization copies that run afterward in + ``do_likelihood`` — sees the untouched arcmin ``self.sacc_data``. + """ + original = self.sacc_data + self.sacc_data = self._sacc_data_rad + try: + return super().extract_theory_points(block) + finally: + self.sacc_data = original + + def _assert_theory_order_matches_data(self): + """Require the theory-loop order to equal the data-vector order. + + The data vector is ``sacc.get_mean()`` (insertion order); upstream + builds theory by looping data types, then tracer combinations, then + points, and concatenating — assuming (never enforcing) that this + reproduces insertion order. It does only for type-major files. We + reconstruct that loop's index order and require it be ``arange``; + otherwise theory and data would be silently misaligned (the same bug + class the PR-2/PR-3 reviews caught for the converter). + """ + order = [ + int(i) + for dt in self.sacc_data.get_data_types() + for tracers in self.sacc_data.get_tracer_combinations(dt) + for i in self.sacc_data.indices(dt, tracers) + ] + expected = np.arange(len(self.sacc_data.mean)) + if not np.array_equal(order, expected): + raise ValueError( + "SACC data/theory ordering mismatch: the theory loop " + "(get_data_types × get_tracer_combinations × points) does not " + "reproduce the get_mean() insertion order, so sacc_like would " + "compare theory against data point-by-point in the WRONG order " + "and return a silently wrong χ². This happens when the file is " + "grouped pair-major (ξ+/ξ− interleaved per tracer pair) rather " + "than type-major (all ξ+, then all ξ−). Upstream assumes " + "to_canonical_order() was applied on load but never calls it; " + "write the SACC type-major, or call to_canonical_order() before " + "saving." + ) + + return SaccLikeUnions + + +def setup(options): + """CosmoSIS ``setup`` — build and instantiate the shimmed likelihood. + + Mirrors ``GaussianLikelihood.build_module``'s setup: wrap the raw options in + ``SectionOptions`` and instantiate the likelihood (whose ``__init__`` calls + ``build_data``). The one addition is reading ``csl_dir`` from the module + options to locate and import the upstream class before subclassing it. The + cosmosis import is deferred to here (call time) so importing this module never + requires cosmosis. + """ + from cosmosis.datablock import SectionOptions, option_section + + csl_dir = options.get_string(option_section, "csl_dir") + sacc_like = _import_upstream_sacc_like(csl_dir) + likelihood_class = _make_subclass(sacc_like) + return likelihood_class(SectionOptions(options)) + + +def execute(block, config): + """CosmoSIS ``execute`` — run the likelihood (mirrors ``build_module``).""" + likelihood_calculator = config + likelihood_calculator.do_likelihood(block) + return 0 + + +def cleanup(config): + """CosmoSIS ``cleanup`` — mirror of ``build_module``'s cleanup.""" + likelihood_calculator = config + likelihood_calculator.cleanup() diff --git a/src/sp_validation/tests/test_bmodes_workflow_dry_run.py b/src/sp_validation/tests/test_bmodes_workflow_dry_run.py index fa963b55..793a70e2 100644 --- a/src/sp_validation/tests/test_bmodes_workflow_dry_run.py +++ b/src/sp_validation/tests/test_bmodes_workflow_dry_run.py @@ -86,3 +86,32 @@ def test_cosmo_val_workflow_assemble_dry_runs(): assert f"pseudo_cl_cov_{version}_blind=A_powspace_nbins=32.fits" in out, out for part in ("_xi_minsep=", "_cosebis.sacc", "_pure_eb.sacc", "rho_tau_"): assert part in out, f"missing {part} part in assemble DAG:\n{out}" + + +@requires_candide_data +def test_cosmo_val_inference_prep_dry_runs(): + """The inference_prep DAG resolves end to end from the assembled SACC. + + inference_fiducial must pull inference_prep, which consumes the assembled + {version}.sacc and emits the converter 2pt-FITS plus BOTH generated pipeline + inis (2pt_like and the native sacc_like). The old cosmosis_fitting.py real- + data assembly is retired from this path; the glass-mock rules keep it. + """ + version = "SP_v1.4.6.3_leak_corr" + result = _dry_run(_repo_root() / "papers/cosmo_val", ["inference_fiducial"]) + assert result.returncode == 0, result.stdout + out = result.stdout + assert "rule inference_prep:" in out, out + assert "rule inference_fiducial:" in out, out + # inference_prep consumes the assembled analysis SACC (not per-sign xi FITS). + assert f"{version}.sacc" in out, out + # ...and both ini templates, bound as inputs so a template edit regenerates + # the configs (as params they would give no DAG edge). + assert "cosmosis_pipeline_A_ia.ini" in out, out + assert "cosmosis_pipeline_A_ia_sacc.ini" in out, out + # It emits the converter FITS + both engine inis. + assert f"cosmosis_{version}.fits" in out, out + assert f"cosmosis_pipeline_{version}_A_ia.ini" in out, out + assert f"cosmosis_pipeline_{version}_A_ia_sacc.ini" in out, out + # The retired real-data assembly script must not appear in this DAG's prep. + assert "cosmosis_fitting.py --cosmosis-root" not in out, out diff --git a/src/sp_validation/tests/test_generate_inference_config.py b/src/sp_validation/tests/test_generate_inference_config.py new file mode 100644 index 00000000..4fbbb98d --- /dev/null +++ b/src/sp_validation/tests/test_generate_inference_config.py @@ -0,0 +1,138 @@ +"""Tests for the CosmoSIS inference-config generator. + +The generator (:mod:`workflow.scripts.generate_inference_config`) fills a +pipeline ini template's ``[DEFAULT]`` section with concrete paths so CosmoSIS's +ConfigParser resolves the template's ``%(KEY)s`` placeholders. These tests need +no cosmosis: they check that the substituted DEFAULT keys land, that the module +file paths the templates reference exist on disk, and that no ``%(...)s`` +placeholder is left unresolved after filling. +""" + +import configparser +import importlib.util +from pathlib import Path + +import pytest + +_REPO = Path(__file__).resolve().parents[3] +_SCRIPT = _REPO / "workflow" / "scripts" / "generate_inference_config.py" +_CONFIG_DIR = _REPO / "cosmo_inference" / "cosmosis_config" +_SACC_TEMPLATE = _CONFIG_DIR / "cosmosis_pipeline_A_ia_sacc.ini" +_FITS_TEMPLATE = _CONFIG_DIR / "cosmosis_pipeline_A_ia.ini" + + +def _load_generator(): + spec = importlib.util.spec_from_file_location("gen_inference_cfg", _SCRIPT) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +gen = _load_generator() + + +def _read_interpolated(ini_path): + """Parse the generated ini with interpolation ON (the way CosmoSIS reads it). + + CosmoSIS uses ``%(KEY)s`` BasicInterpolation with case-*preserved* keys, so + set ``optionxform = str`` (stdlib configparser lowercases keys by default, + which would break the uppercase ``%(FITS_FILE)s`` / ``%(SACC_FILE)s`` + lookups). The default BasicInterpolation then raises if a referenced key is + missing — exactly the failure we want to catch. + """ + parser = configparser.ConfigParser() + parser.optionxform = str + parser.read(ini_path) + return parser + + +def test_sacc_template_defaults_filled(tmp_path): + """The generated sacc ini carries the substituted DEFAULT keys and resolves.""" + out = tmp_path / "gen_sacc.ini" + gen.generate_inference_config( + _SACC_TEMPLATE, + out, + gen._substitutions( + scratch="/scratch/run", + cosmosis_dir="/csl", + sacc_file="/data/v1.sacc", + ), + ) + text = out.read_text() + assert "SCRATCH = /scratch/run" in text + assert "SACC_FILE = /data/v1.sacc" in text + assert "COSMOSIS_DIR = /csl" in text + assert "SP_VALIDATION_MODULES = " in text + # FITS_FILE is None for the sacc path — must be dropped, not written as "None". + assert "FITS_FILE" not in text + + parser = _read_interpolated(out) + # The sacc_like data_file interpolates SACC_FILE; load_nz_sacc too. + assert parser["sacc_like"]["data_file"] == "/data/v1.sacc" + assert parser["load_nz_sacc"]["nz_file"] == "/data/v1.sacc" + assert parser["sacc_like"]["csl_dir"] == "/csl" + + +def test_fits_template_defaults_filled(tmp_path): + """The generated 2pt_like ini carries the substituted DEFAULT keys and resolves.""" + out = tmp_path / "gen_fits.ini" + gen.generate_inference_config( + _FITS_TEMPLATE, + out, + gen._substitutions( + scratch="/scratch/run", + cosmosis_dir="/csl", + fits_file="/data/v1.fits", + ), + ) + text = out.read_text() + assert "SCRATCH = /scratch/run" in text + assert "FITS_FILE = /data/v1.fits" in text + assert "SACC_FILE" not in text + + parser = _read_interpolated(out) + assert parser["2pt_like"]["data_file"] == "/data/v1.fits" + assert parser["load_nz_fits"]["nz_file"] == "/data/v1.fits" + + +def test_sacc_template_module_file_exists(): + """The sacc_like module file the generated ini points at exists on disk. + + ``SP_VALIDATION_MODULES`` resolves to the installed package dir; + ``sacc_like_unions.py`` must live there (it is the shim CosmoSIS loads). + """ + modules = Path(gen._sp_validation_modules()) + assert (modules / "sacc_like_unions.py").is_file() + + +def test_all_placeholders_resolve(tmp_path): + """No ``%(...)s`` placeholder survives interpolation in either template. + + A missing DEFAULT key would make ConfigParser raise on access; iterate every + option in every section to force resolution of all placeholders. + """ + for template, subs in ( + ( + _SACC_TEMPLATE, + gen._substitutions(scratch="/s", cosmosis_dir="/csl", sacc_file="/d.sacc"), + ), + ( + _FITS_TEMPLATE, + gen._substitutions(scratch="/s", cosmosis_dir="/csl", fits_file="/d.fits"), + ), + ): + out = tmp_path / (template.stem + ".gen.ini") + gen.generate_inference_config(template, out, subs) + parser = _read_interpolated(out) + for section in parser.sections(): + for key in parser[section]: + value = parser[section][key] # raises if a placeholder is unresolved + assert "%(" not in value, f"[{section}] {key} = {value}" + + +def test_no_default_section_raises(tmp_path): + """A template with no [DEFAULT] section is a loud error.""" + bad = tmp_path / "bad.ini" + bad.write_text("[pipeline]\nmodules = a b c\n") + with pytest.raises(ValueError, match="DEFAULT"): + gen.generate_inference_config(bad, tmp_path / "out.ini", {"SCRATCH": "/s"}) diff --git a/src/sp_validation/tests/test_pseudo_cl.py b/src/sp_validation/tests/test_pseudo_cl.py index 6fa15d0e..2d3879e0 100644 --- a/src/sp_validation/tests/test_pseudo_cl.py +++ b/src/sp_validation/tests/test_pseudo_cl.py @@ -169,6 +169,7 @@ def cv(tmp_path): power=0.5, n_ell_bins=N_ELL_BINS, pol_factor=True, + run_type="mock", ) cv._test_version = version return cv diff --git a/src/sp_validation/tests/test_sacc_like.py b/src/sp_validation/tests/test_sacc_like.py new file mode 100644 index 00000000..11f8c320 --- /dev/null +++ b/src/sp_validation/tests/test_sacc_like.py @@ -0,0 +1,565 @@ +"""Equality tests: the sp_validation SACC-likelihood shim vs CosmoSIS ``2pt_like``. + +The ξ± inference path uses CosmoSIS's native ``SaccClLikelihood`` through the +shim :mod:`sp_validation.sacc_like_unions` (which fixes the upstream +arcmin→rad gap and adds an ordering guard). The contract is *in-process module +equality*: run the shimmed ``sacc_like`` on the analysis SACC and CosmoSIS's +``2pt_like`` on the converter's 2pt-FITS against an identical synthetic +theory DataBlock, and require the same χ², log-likelihood, theory vector and +post-cut point count. Equality is exact (Δχ²=0, Δtheory=0), so the tests assert +``array_equal`` / rtol=1e-12. + +Environment +----------- +Both engines are pure-python CosmoSIS module files (no CAMB, no compiled CSL +modules), so they run in the shared venv with ``cosmosis`` installed. They need a +checkout of the CosmoSIS Standard Library, located via the ``CSL_DIR`` env var; +the module is skipped when cosmosis is absent (CI image) or ``CSL_DIR`` is unset +or missing. Recipe:: + + git clone --depth 1 https://github.com/joezuntz/cosmosis-standard-library CSL + CSL_DIR=/path/to/CSL pytest ... test_sacc_like.py + +The pyproject ``cosmosis`` extra pins ``cosmosis>=3.25`` for the engine itself; +the CI image does not install it, so this module is inert there. +""" + +import importlib.util +import os +from pathlib import Path + +import numpy as np +import pytest + +cosmosis = pytest.importorskip("cosmosis") + +# The upstream CSL checkout carrying likelihood/sacc + likelihood/2pt. Skip the +# whole module (not error) when it is not configured, mirroring the cosmo_numba +# env-gated precedent. +_CSL_DIR = os.environ.get("CSL_DIR") +if not _CSL_DIR or not Path(_CSL_DIR, "likelihood", "sacc").is_dir(): + pytest.skip( + "CSL_DIR unset or has no likelihood/sacc — set CSL_DIR to a CosmoSIS " + "Standard Library checkout to run the sacc_like equality tests", + allow_module_level=True, + ) + +from cosmosis.datablock import DataBlock, option_section # noqa: E402 + +from sp_validation import sacc_io # noqa: E402 + +# Reuse the angular-bin count from the converter tests so the two suites' single- +# bin shapes stay in lockstep. (The χ²-dynamics builders here need a covariance +# commensurate with the data, which the converter's byte-compare _sacc is not.) +from sp_validation.tests.test_sacc_io_twopoint import N_ANG # noqa: E402 + +CSL = Path(_CSL_DIR) +ARCMIN_TO_RAD = np.pi / (180.0 * 60.0) + +# The like_name both engines are configured with, so both write identical block +# keys (_CHI2, _LIKE, _theory) — the parity the design mandates. +LIKE_NAME = "2pt_like" + + +# --------------------------------------------------------------------------- +# Shared engine harness +# --------------------------------------------------------------------------- +def _load_module_file(path, name): + """Import a CosmoSIS module file (``setup``/``execute``/``cleanup``) by path. + + ``likelihood/sacc`` and ``likelihood/2pt`` are added to ``sys.path`` so the + upstream modules resolve their siblings (``sacc_likelihoods``, ``spec_tools``, + ``twopoint_cosmosis``, …). Loading ``2pt_like.py`` runs its + ``build_module()`` at import (module-level ``setup, execute, cleanup``); + ``sacc_like_unions.py`` defines those functions directly. + """ + import sys + + for sub in ("likelihood/sacc", "likelihood/2pt"): + p = str(CSL / sub) + if p not in sys.path: + sys.path.insert(0, p) + spec = importlib.util.spec_from_file_location(name, path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def _theory_block(): + """A DataBlock carrying the synthetic ξ± theory both engines interpolate. + + Mirrors the probe: the theory θ grid is in *radians* (CosmoSIS convention), + and the ξ+/ξ− predictions are smooth power laws sampled on it. Both engines + build a spline over this grid and evaluate it at each data point's angular + tag — so as long as both see the same block, the interpolated theory (and + hence χ²) must agree. + """ + theta_arcmin = np.geomspace(0.3, 400.0, 300) + + def t_xip(th): + return 2e-4 * (th / 10.0) ** -0.8 + + def t_xim(th): + return 1e-4 * (th / 10.0) ** -0.5 + + b = DataBlock() + for section, f in (("shear_xi_plus", t_xip), ("shear_xi_minus", t_xim)): + b[section, "theta"] = theta_arcmin * ARCMIN_TO_RAD + b[section, "bin_1_1"] = f(theta_arcmin) + b[section, "is_auto"] = True + b[section, "nbin_a"] = 1 + b[section, "nbin_b"] = 1 + b[section, "sample_a"] = "nz_source" + b[section, "sample_b"] = "nz_source" + b[section, "sep_name"] = "theta" + b[section, "save_name"] = "" + return b + + +def _run(mod, options): + """Run a CosmoSIS likelihood module file standalone; return (like, chi2, theory, n). + + Builds the options DataBlock (module options live under ``option_section``), + calls ``setup`` → ``execute`` on a fresh theory block, and reads the standard + Gaussian-likelihood outputs back out under the shared ``LIKE_NAME`` keys. + """ + opt = DataBlock() + for key, value in options.items(): + opt[option_section, key] = value + config = mod.setup(opt) + block = _theory_block() + mod.execute(block, config) + like = block["likelihoods", f"{LIKE_NAME}_LIKE"] + chi2 = block["data_vector", f"{LIKE_NAME}_CHI2"] + theory = block["data_vector", f"{LIKE_NAME}_theory"] + return like, chi2, np.asarray(theory), len(theory) + + +# --------------------------------------------------------------------------- +# The two engine module files + their options +# --------------------------------------------------------------------------- +_SHIM_PATH = Path(__file__).resolve().parents[1] / "sacc_like_unions.py" + + +@pytest.fixture(scope="module") +def m_shim(): + return _load_module_file(_SHIM_PATH, "sacc_like_unions_test") + + +@pytest.fixture(scope="module") +def m_2pt(): + return _load_module_file(CSL / "likelihood/2pt/2pt_like.py", "twopt_like_test") + + +@pytest.fixture(scope="module") +def m_raw_sacc(): + return _load_module_file(CSL / "likelihood/sacc/sacc_like.py", "raw_sacc_like_test") + + +def _shim_opts(sacc_path, **extra): + return { + "csl_dir": str(CSL), + "data_file": sacc_path, + "data_sets": "galaxy_shear_xi_plus galaxy_shear_xi_minus", + "like_name": LIKE_NAME, + **extra, + } + + +def _twopt_opts(fits_path, **extra): + return { + "data_file": fits_path, + "data_sets": "XI_PLUS XI_MINUS", + "covmat_name": "COVMAT", + "like_name": LIKE_NAME, + "gaussian_covariance": False, + "cut_zeros": False, + **extra, + } + + +def _realistic_sacc(seed=0, *, xip=None): + """A single-bin ξ± SACC with data + covariance sized like the real product. + + The converter-test ``_sacc`` builder uses a covariance ~14 orders of + magnitude larger than the ξ values (fine for byte-comparing the converter, + where covariance *content* is irrelevant), which makes every χ² collapse to + numerical zero — no teeth for the unit-gap tripwire. This builder instead + lays down realistic ξ± power laws and a covariance ~ ``(0.1·|ξ|)²`` (the + probe's recipe), so χ² is O(1)-scale and the raw-vs-shim gap is visible. + + ``xip`` overrides the ξ+ values (perturbation teeth). + """ + rng = np.random.default_rng(seed) + n = N_ANG + theta = np.geomspace(1.0, 250.0, n) # arcmin + z = np.linspace(0.01, 3.0, 200) + nz = z**2 * np.exp(-((z / 0.5) ** 1.5)) + + xip_vals = 2e-4 * (theta / 10.0) ** -0.8 * (1 + 0.05 * rng.standard_normal(n)) + xim_vals = 1e-4 * (theta / 10.0) ** -0.5 * (1 + 0.05 * rng.standard_normal(n)) + if xip is not None: + xip_vals = xip + + s = sacc_io.new_sacc({0: (z, nz)}, {"catalogue_version": "test"}) + sacc_io.add_xi(s, (0, 0), theta, xip_vals, xim_vals, grid="reporting") + + sig = 0.1 * np.abs(np.concatenate([xip_vals, xim_vals])) + a = rng.standard_normal((2 * n, 3 * n)) + cov = (a @ a.T / (3 * n)) * np.outer(sig, sig) * 0.3 + np.diag(sig**2) + s.add_covariance(cov) + return s, theta + + +def _write_pair(tmp_path, seed=0, name="probe", *, xip=None): + """Write a realistic analysis SACC and its PR-3 converter 2pt-FITS. + + Returns ``(sacc_path, fits_path)``. The SACC carries the arcmin ξ± tags the + shim converts; the FITS is the byte-compatible product ``2pt_like`` reads. + """ + s, _theta = _realistic_sacc(seed, xip=xip) + sacc_path = str(tmp_path / f"{name}.sacc") + sacc_io.save(s, sacc_path, type="mock") + fits_path = str(tmp_path / f"{name}_2pt.fits") + sacc_io.sacc_to_twopoint_fits(sacc_io.load(sacc_path), fits_path, n_bins=1) + return sacc_path, fits_path + + +# --------------------------------------------------------------------------- +# 1. Core equality: shim on SACC ≡ 2pt_like on converter FITS +# --------------------------------------------------------------------------- +def test_shimmed_equals_2pt_like_exact(tmp_path, m_shim, m_2pt): + """The shimmed sacc_like and 2pt_like agree exactly on the same data+theory. + + Same synthetic theory block, the SACC through the shim vs the converter FITS + through 2pt_like: χ², log-likelihood and the theory vector must match to + numerical precision (the probe observed exact equality). This is the PR's + central contract — the native path reproduces the validated converter path. + """ + sacc_path, fits_path = _write_pair(tmp_path, seed=0) + + like_s, chi2_s, theory_s, n_s = _run(m_shim, _shim_opts(sacc_path)) + like_t, chi2_t, theory_t, n_t = _run(m_2pt, _twopt_opts(fits_path)) + + assert n_s == n_t == 2 * N_ANG + np.testing.assert_allclose(chi2_s, chi2_t, rtol=1e-12) + np.testing.assert_allclose(like_s, like_t, rtol=1e-12) + np.testing.assert_allclose(theory_s, theory_t, rtol=1e-12) + + +# --------------------------------------------------------------------------- +# 2. Tripwire: raw upstream sacc_like is broken on arcmin tags +# --------------------------------------------------------------------------- +def test_upstream_unit_gap_tripwire(tmp_path, m_raw_sacc, m_2pt): + """RAW upstream sacc_like (no shim) gives a wildly wrong χ² on arcmin tags. + + Documents and guards the arcmin→rad gap the shim fixes: with raw ``theta`` + tags the theory spline is evaluated outside its (radian) grid and returns 0, + collapsing χ² to dᵀC⁻¹d. We assert the relative χ² difference against + 2pt_like exceeds 10 (the probe saw Δχ²≈3184). + + IF THIS TEST EVER FAILS: upstream ``sacc_like`` has fixed its units — the + shim's arcmin→rad conversion is now redundant and the shim can be retired. + """ + sacc_path, fits_path = _write_pair(tmp_path, seed=0) + + _like_r, chi2_raw, _theory_r, _n_r = _run(m_raw_sacc, _shim_opts(sacc_path)) + _like_t, chi2_t, _theory_t, _n_t = _run(m_2pt, _twopt_opts(fits_path)) + + rel = abs(chi2_raw - chi2_t) / abs(chi2_t) + assert rel > 10, ( + f"raw sacc_like χ²={chi2_raw:.6g} is within 10× of 2pt_like χ²={chi2_t:.6g} " + f"(rel diff {rel:.3g}) — the upstream unit gap appears fixed; retire the shim" + ) + + +# --------------------------------------------------------------------------- +# 3. Scale cuts equivalent through both engines +# --------------------------------------------------------------------------- +def test_scale_cuts_equivalent(tmp_path, m_shim, m_2pt): + """The same arcmin scale cuts give the same post-cut N and χ² on both engines. + + Cuts are expressed in the each engine's grammar but the SAME numeric arcmin + values (shim cuts run before the arcmin→rad conversion, so they take arcmin + just like 2pt_like's angle_range). ξ+ ∈ [10, 200], ξ− ∈ [20, 200] arcmin. + """ + sacc_path, fits_path = _write_pair(tmp_path, seed=1) + + shim_cuts = _shim_opts( + sacc_path, + **{ + "angle_range_galaxy_shear_xi_plus_source_0_source_0": np.array( + [10.0, 200.0] + ), + "angle_range_galaxy_shear_xi_minus_source_0_source_0": np.array( + [20.0, 200.0] + ), + }, + ) + twopt_cuts = _twopt_opts( + fits_path, + **{ + "angle_range_XI_PLUS_1_1": np.array([10.0, 200.0]), + "angle_range_XI_MINUS_1_1": np.array([20.0, 200.0]), + }, + ) + + _like_s, chi2_s, _theory_s, n_s = _run(m_shim, shim_cuts) + _like_t, chi2_t, _theory_t, n_t = _run(m_2pt, twopt_cuts) + + assert n_s == n_t + assert n_s < 2 * N_ANG # the cuts actually removed points + np.testing.assert_allclose(chi2_s, chi2_t, rtol=1e-12) + + +# --------------------------------------------------------------------------- +# 4. Perturbation moves both engines identically +# --------------------------------------------------------------------------- +def test_perturbation_moves_both_identically(tmp_path, m_shim, m_2pt): + """Perturbing one data value shifts both engines' χ² by the identical amount. + + Teeth: build the base pair and a pair whose first ξ+ value is bumped, and + require Δχ²(shim) == Δχ²(2pt_like). If either engine ignored the perturbed + point (e.g. a misaligned data vector), the deltas would diverge. + """ + # Base pair, then a pair whose first ξ+ value is bumped. Rebuild the base ξ+ + # from the same seed so only the one perturbed entry differs. + base_s, theta = _realistic_sacc(seed=2) + base_xip = np.array( + [p.value for p in base_s.data if p.data_type == sacc_io.XI_PLUS] + ) + sacc_b, fits_b = _write_pair(tmp_path, seed=2, name="base") + + pert_xip = base_xip.copy() + pert_xip[0] += 5e-5 + sacc_p, fits_p = _write_pair(tmp_path, seed=2, name="pert", xip=pert_xip) + + _l, chi2_shim_b, _t, _n = _run(m_shim, _shim_opts(sacc_b)) + _l, chi2_shim_p, _t, _n = _run(m_shim, _shim_opts(sacc_p)) + _l, chi2_2pt_b, _t, _n = _run(m_2pt, _twopt_opts(fits_b)) + _l, chi2_2pt_p, _t, _n = _run(m_2pt, _twopt_opts(fits_p)) + + d_shim = chi2_shim_p - chi2_shim_b + d_2pt = chi2_2pt_p - chi2_2pt_b + assert abs(d_shim) > 0 # the perturbation actually moved χ² + np.testing.assert_allclose(d_shim, d_2pt, rtol=1e-10) + + +# --------------------------------------------------------------------------- +# 5. Ordering guard raises on a pair-major tomographic file +# --------------------------------------------------------------------------- +def test_ordering_guard_raises_pair_major_tomographic(tmp_path, m_shim): + """A pair-major 2-bin SACC trips the shim's ordering guard at setup. + + Inserting ξ± per pair — (0,0), then (0,1), then (1,1) — lays the data vector + out pair-major ([ξ+;ξ−] per pair), while ``get_data_types()`` groups the + theory loop type-major (all ξ+ pairs, then all ξ− pairs). The two orders + disagree (verified empirically), so the guard must raise a ValueError + mentioning the ordering hazard rather than silently mis-comparing. + """ + theta = np.geomspace(1.0, 250.0, N_ANG) # arcmin + z = np.linspace(0.01, 3.0, 200) + nz = z**2 * np.exp(-((z / 0.5) ** 1.5)) + xip = np.ones(N_ANG) * 1e-4 + xim = np.ones(N_ANG) * 1e-4 + s = sacc_io.new_sacc({0: (z, nz), 1: (z, nz)}) + for pair in [(0, 0), (0, 1), (1, 1)]: + sacc_io.add_xi(s, pair, theta, xip, xim, grid="reporting") + s.add_covariance(np.eye(len(s.mean))) + sacc_path = str(tmp_path / "pair_major.sacc") + sacc_io.save(s, sacc_path, type="mock") + + with pytest.raises(ValueError, match="ordering"): + m_shim.setup(_as_option_block(_shim_opts(sacc_path))) + + +def _as_option_block(options): + """Build a raw options DataBlock (keys under ``option_section``) for setup().""" + opt = DataBlock() + for key, value in options.items(): + opt[option_section, key] = value + return opt + + +# --------------------------------------------------------------------------- +# 6. theta conversion scoped to real-category types (COSEBIs untouched) +# --------------------------------------------------------------------------- +def test_theta_conversion_scoped_to_real_types(tmp_path, m_shim): + """The shim converts ξ ``theta`` tags but leaves cosebi ``n`` tags untouched. + + Build a SACC carrying both ξ± (real) and COSEBIs (a non-real ``cosebis`` + category with integer ``n`` tags). After the shim's ``build_data``, the ξ + ``theta`` tags must be scaled arcmin→rad (so they equal the original arcmin + values times the conversion factor), and the cosebi ``n`` tags must be + numerically unchanged. + """ + # Build ξ± + COSEBIs, then attach the covariance last (sacc forbids adding + # points after add_covariance). + theta = np.geomspace(1.0, 250.0, N_ANG) # arcmin + z = np.linspace(0.01, 3.0, 200) + nz = z**2 * np.exp(-((z / 0.5) ** 1.5)) + n_modes = 5 + En = np.arange(1.0, n_modes + 1) + Bn = np.arange(1.0, n_modes + 1) * 0.1 + + s = sacc_io.new_sacc({0: (z, nz)}) + sacc_io.add_xi( + s, (0, 0), theta, np.ones(N_ANG) * 1e-4, np.ones(N_ANG) * 1e-4, grid="reporting" + ) + sacc_io.add_cosebis(s, (0, 0), En, (1.0, 250.0), Bn=Bn) + s.add_covariance(np.eye(len(s.mean))) + + sacc_path = str(tmp_path / "with_cosebis.sacc") + sacc_io.save(s, sacc_path, type="mock") + + # data_sets keeps the cosebis in (so we can check its tags survive); cosebi's + # section/category resolve from sacc_like's default_sections, so build_data + # needs no extra ini config. Only setup() runs (build_data); the theory loop + # (which would want a cosebi theory block) runs at execute, not here. + config = m_shim.setup( + _as_option_block( + _shim_opts( + sacc_path, + data_sets=( + "galaxy_shear_xi_plus galaxy_shear_xi_minus " + "galaxy_shear_cosebi_ee galaxy_shear_cosebi_bb" + ), + ) + ) + ) + + # The conversion lives on the radian copy (_sacc_data_rad); the original + # self.sacc_data stays arcmin (so save_theory writes arcmin tags — Finding 1). + rad_xi_thetas = [ + p.tags["theta"] + for p in config._sacc_data_rad.data + if p.data_type == sacc_io.XI_PLUS + ] + rad_cosebi_ns = [ + p.tags["n"] + for p in config._sacc_data_rad.data + if p.data_type == sacc_io.COSEBI_EE + ] + orig_xi_thetas = [ + p.tags["theta"] for p in config.sacc_data.data if p.data_type == sacc_io.XI_PLUS + ] + # rad copy: ξ theta scaled to radians (original arcmin × ARCMIN_TO_RAD). + np.testing.assert_allclose( + np.sort(rad_xi_thetas), np.sort(theta * ARCMIN_TO_RAD), rtol=1e-12 + ) + # rad copy: cosebi n tags untouched (still integer modes 1..n_modes). + np.testing.assert_array_equal(np.sort(rad_cosebi_ns), np.arange(1, n_modes + 1)) + # original sacc_data: ξ theta still in arcmin (unmutated). + np.testing.assert_allclose(np.sort(orig_xi_thetas), np.sort(theta), rtol=1e-12) + + +# --------------------------------------------------------------------------- +# 6b. save_theory writes arcmin tags, and re-execute is stable (Finding 1) +# --------------------------------------------------------------------------- +def test_save_theory_writes_arcmin_and_reexecute_stable(tmp_path, m_shim): + """save_theory must write a SACC whose θ tags are still arcmin, not radians. + + Finding 1: because upstream save_theory copies self.sacc_data and overwrites + only point values, self.sacc_data must stay arcmin — otherwise the saved file + carries radian θ tags and any arcmin-assuming consumer (sacc_io.get_xi, or + re-ingesting it as a data_file, which would double-convert to ~8.5e-8) is + silently off by 3437×. Assert the saved θ tags match the input file's tags + exactly (arcmin) and that the saved values equal the theory vector. Also run + execute() twice and require identical χ² — a guard against any accidental + double-conversion creeping back in. + """ + s, theta = _realistic_sacc(seed=5) + sacc_path = str(tmp_path / "in.sacc") + sacc_io.save(s, sacc_path, type="mock") + input_theta = np.array( + [p.tags["theta"] for p in sacc_io.load(sacc_path).data if "theta" in p.tags] + ) + + save_path = str(tmp_path / "saved_theory.sacc") + opt = _as_option_block(_shim_opts(sacc_path, save_theory=save_path)) + config = m_shim.setup(opt) + + block1 = _theory_block() + m_shim.execute(block1, config) + chi2_1 = block1["data_vector", f"{LIKE_NAME}_CHI2"] + theory = np.asarray(block1["data_vector", f"{LIKE_NAME}_theory"]) + + saved = sacc_io.load(save_path) + saved_theta = np.array([p.tags["theta"] for p in saved.data if "theta" in p.tags]) + saved_values = np.array(saved.mean) + + # θ tags in the saved file are arcmin — identical to the input file's tags. + np.testing.assert_array_equal(saved_theta, input_theta) + # and are NOT the radian conversion (guards against the leak explicitly). + assert not np.allclose(saved_theta, input_theta * ARCMIN_TO_RAD) + # saved values are the theory vector (save_theory overwrites values in order). + np.testing.assert_allclose(saved_values, theory, rtol=1e-12) + + # A second execute() yields the identical χ² — no cumulative mutation. + block2 = _theory_block() + m_shim.execute(block2, config) + chi2_2 = block2["data_vector", f"{LIKE_NAME}_CHI2"] + np.testing.assert_allclose(chi2_2, chi2_1, rtol=1e-12) + + +# --------------------------------------------------------------------------- +# 7. Real-data equality (candide-gated) +# --------------------------------------------------------------------------- +_REALDATA = ( + Path("/automnt/n17data/cdaley/unions/code/sp_validation/cosmo_inference/data") + / "SP_v1.4.6_leak_corr_A_minsep=1.0_maxsep=250.0_nbins=20_npatch=1" + / "cosmosis_SP_v1.4.6_leak_corr_A_minsep=1.0_maxsep=250.0_nbins=20_npatch=1.fits" +) + + +@pytest.mark.skipif( + not _REALDATA.exists(), reason=f"real 2pt-FITS not on disk: {_REALDATA}" +) +def test_realdata_shim_equals_2pt_like(tmp_path, m_shim, m_2pt): + """On a real product, the shim on its SACC equals 2pt_like on the FITS. + + Builds a ξ-only analysis SACC from the real 2pt-FITS's own ξ± values and + covariance sub-block (via the converter test's ``_sacc_from_2pt_fits``, then + strip to ξ±), writes it, converts it to a plain-ξ FITS, and runs both engines + against the synthetic theory block. Scoping to ξ± isolates the shear + likelihood equality on the true (20-point-per-sign) data-vector shape — the + IA-only inference scope this PR targets — and keeps ``2pt_like``'s + ``twopoint.from_fits`` from tripping over the real file's separate + COVMAT_CELL / τ blocks. + """ + from astropy.io import fits + + from sp_validation.tests.test_sacc_io_realdata import _sacc_from_2pt_fits + + with fits.open(_REALDATA) as hdul: + full_s, _rho_hdu, _tau_hdu = _sacc_from_2pt_fits(hdul) + + # Rebuild a ξ-only SACC: same n(z), ξ± values and ξ± covariance sub-block. + source = sacc_io.source_name(0) + z, nz = sacc_io.get_nz(full_s, 0) + theta, xip, xim = sacc_io.get_xi(full_s, (0, 0), grid="reporting") + xi_idx = np.concatenate( + [ + full_s.indices(sacc_io.XI_PLUS, (source, source)), + full_s.indices(sacc_io.XI_MINUS, (source, source)), + ] + ) + xi_cov = full_s.covariance.dense[np.ix_(xi_idx, xi_idx)] + + s = sacc_io.new_sacc({0: (z, nz)}) + sacc_io.add_xi(s, (0, 0), theta, xip, xim, grid="reporting") + s.add_covariance(xi_cov) + + sacc_path = str(tmp_path / "real_xi.sacc") + sacc_io.save(s, sacc_path, type="mock") + fits_path = str(tmp_path / "real_xi_2pt.fits") + sacc_io.sacc_to_twopoint_fits(sacc_io.load(sacc_path), fits_path, n_bins=1) + + like_s, chi2_s, theory_s, n_s = _run(m_shim, _shim_opts(sacc_path)) + like_t, chi2_t, theory_t, n_t = _run(m_2pt, _twopt_opts(fits_path)) + + assert n_s == n_t + assert n_s == 2 * len(theta) + np.testing.assert_allclose(chi2_s, chi2_t, rtol=1e-10) + np.testing.assert_allclose(like_s, like_t, rtol=1e-10) + np.testing.assert_allclose(theory_s, theory_t, rtol=1e-10) diff --git a/workflow/rules/inference.smk b/workflow/rules/inference.smk index d2847976..42724077 100644 --- a/workflow/rules/inference.smk +++ b/workflow/rules/inference.smk @@ -1,21 +1,25 @@ -# Imports from Snakefile: FIDUCIAL, COSMO_INFERENCE, COSMO_VAL, covariance_path, build_redshift_path, fiducial_binning_suffix -# NOTE: dormant subsystem. The file-name plumbing (config-driven paths + the -# producer-tagged pseudo-Cl names) is fixed and the DAG is valid, but it has not -# been run end-to-end. Reviving it still needs the FITS-CONTENT plumbing -# reconciled: cosmosis_fitting.py reads ELL/EE/BB + COVAR_FULL, while the -# producers write PSEUDO_CELL/ELL + COVAR_BB_BB. +# Imports from common (via `from common import *`): FIDUCIAL, COSMO_INFERENCE, +# COSMO_VAL, WORKFLOW_SCRIPTS, covariance_path, build_redshift_path, +# fiducial_binning_suffix. cv_analysis_sacc arrives from cosmo_val.smk (resolved +# lazily at DAG time, since that file is included after this one). +# +# Two paths live here: +# * Real-data inference_prep — live: consumes the assembled {version}.sacc and +# emits the converter 2pt-FITS + both engine inis (2pt_like, sacc_like). +# * glass-mock rules — still cosmosis_fitting.py-based (their SACC migration is +# out of scope); the pseudo-Cl file-name plumbing they depend on stays below. # Output root for CosmoSIS data products + configs. COSMO_INFERENCE (common.py) # already resolves to THIS repo's cosmo_inference dir, so the products land # beside the code that builds them rather than in a contributor's home. COSMO_INFERENCE_PROD = COSMO_INFERENCE -# Working directory for the cosmosis_fitting.py invocation — the same repo dir. +# Working directory for the (glass-mock) cosmosis_fitting.py invocation. COSMO_INFERENCE_RUNDIR = str(COSMO_INFERENCE) # External chain/mock locations are deployment-specific, so they live in config. INFERENCE = config["inference"] -CHAINS_DIR = INFERENCE["chains_dir"] # CosmoSIS chain output root (real data) GLASS_MOCK_DATA_DIR = INFERENCE["glass_mock_data_dir"] # precomputed mock xi/Cl products +CHAINS_DIR = INFERENCE["chains_dir"] # CosmoSIS chain output root (real data) GLASS_MOCK_CHAINS_DIR = INFERENCE["glass_mock_chains_dir"] # mock chain output root PSEUDO_CL_DIR = COSMO_VAL # producer (twopoint.smk) writes pseudo_cl* here @@ -29,99 +33,132 @@ GLASS_MOCK_FITS_PATTERN = str( ) GLASS_MOCK_CONFIG_PATTERN = str( COSMO_INFERENCE_PROD - / f"cosmosis_config/output/cosmosis_pipeline_glass_mocks_{GLASS_MOCK_VERSION}_glass_mock_{{mock_id}}.ini" + / f"cosmosis_config/cosmosis_pipeline_glass_mocks_{GLASS_MOCK_VERSION}_glass_mock_{{mock_id}}.ini" ) -# Fiducial harmonic-binning tag the pseudo-Cl producer (twopoint.smk) stamps -# into the filename. These are NOT inference_prep wildcards, so the consumer -# reads them from config to reconstruct the exact name the producer emits -# (canonical: blind=A, powspace, nbins=32 — see twopoint.smk pseudo_cl_all). -HARMONIC_FIDUCIAL = config["harmonic"]["fiducial"] -PSEUDO_CL_TAG = ( - f"blind={HARMONIC_FIDUCIAL['blind']}" - f"_{HARMONIC_FIDUCIAL['binning']}" - f"_nbins={HARMONIC_FIDUCIAL['nbins']}" -) +PSEUDO_CL_TAG = pseudo_cl_tag(config) def pseudo_cl_assets(version): - """Return pseudo-Cl and covariance paths for the requested catalog version. + """Pseudo-Cl and covariance paths for a catalog version. - The producer (twopoint.smk rules pseudo_cl / pseudo_cl_cov) writes - wildcard-tagged names; the consumer reconstructs them from the fiducial - harmonic-binning config so the requested path matches byte-for-byte. + The producer (twopoint.smk) writes wildcard-tagged names; the consumer + reconstructs them from the fiducial harmonic-binning config. """ cl_path = PSEUDO_CL_DIR / f"pseudo_cl_{version}_{PSEUDO_CL_TAG}.fits" cov_path = PSEUDO_CL_DIR / f"pseudo_cl_cov_{version}_{PSEUDO_CL_TAG}.fits" return str(cl_path), str(cov_path) +# --------------------------------------------------------------------------- +# Real-data inference prep (native SACC). Consumes the assembled +# analysis {version}.sacc (cosmo_val.smk's assemble_sacc rule) and emits the two +# file-prep products the A_ia (IA-only, ξ±) fiducial pipeline needs: +# (a) the converter 2pt-FITS (sacc_to_twopoint_fits) + a generated 2pt_like ini +# — the validating/legacy path (retiring cosmosis_fitting.py's assembly), +# (b) a generated sacc_like ini pointing at the SACC directly — the native path +# validated bit-for-bit against (a) (test_sacc_like.py). +# The converter is A_ia-scoped: no rho/tau sidecars, so it emits a pure-ξ FITS +# (it ignores the SACC's extra data types). This is file-prep only — the actual +# CosmoSIS sampling still runs via pipeline.sh against these products. +# +# The glass-mock rules below stay cosmosis_fitting.py-based; their SACC migration +# is tracked separately. +# --------------------------------------------------------------------------- +# Generated per-version configs land in the (env-overridable) output root. +INFERENCE_CONFIG_OUT = COSMO_INFERENCE_PROD / "cosmosis_config" +# The ini TEMPLATES are source files: anchor them on the running checkout (repo +# root = the workflow dir's parent, via WORKFLOW_SCRIPTS), NOT on the output root +# — so a template edit in this checkout drives the DAG even when COSMO_INFERENCE +# points elsewhere. In a normal (non-worktree) run the two roots coincide. +INFERENCE_TEMPLATE_DIR = ( + Path(os.path.dirname(WORKFLOW_SCRIPTS)).parent / "cosmo_inference" / "cosmosis_config" +) + + +def _csl_dir(): + """The CSL checkout that fills COSMOSIS_DIR / sacc_like csl_dir in the inis. + + Read lazily (at DAG time, inside inference_prep's params) rather than at + module parse time: inference.smk is included by every paper workflow, but + only papers that run inference (cosmo_val) carry inference.csl_dir. A missing + key still fails loudly — just when the real-data inference is actually built, + not when an unrelated (bmodes) workflow merely parses this file. + """ + return INFERENCE["csl_dir"] + + rule inference_prep: input: - # Processed covariance matrix - use centralized covariance_path() - cov_matrix=lambda w: covariance_path(w.version, w.blind, min_sep=w.min_sep, max_sep=w.max_sep, nbins=w.nbins), - # Xi FITS files - xi_plus=str(COSMO_VAL / "xi_plus_{version}_minsep={min_sep}_maxsep={max_sep}_nbins={nbins}_npatch={npatch}.fits"), - xi_minus=str(COSMO_VAL / "xi_minus_{version}_minsep={min_sep}_maxsep={max_sep}_nbins={nbins}_npatch={npatch}.fits"), - # n(z) file (using new location with base version mapping) - nz_file=lambda w: build_redshift_path(w.version, w.blind), - # rho/tau stats - rho_stats=str(COSMO_VAL / "rho_tau_stats/rho_stats_{version}_minsep={min_sep}_maxsep={max_sep}_nbins={nbins}_npatch={npatch}.fits"), - tau_stats=str(COSMO_VAL / "rho_tau_stats/tau_stats_{version}_minsep={min_sep}_maxsep={max_sep}_nbins={nbins}_npatch={npatch}.fits"), - # tau covariance (tracked as dependency) - tau_cov=str(COSMO_VAL / "rho_tau_stats/cov_tau_{version}_minsep={min_sep}_maxsep={max_sep}_nbins={nbins}_npatch={npatch}_th.npy"), - pseudo_cl=lambda w: pseudo_cl_assets(w.version)[0], - pseudo_cl_cov=lambda w: pseudo_cl_assets(w.version)[1], + # The terminal assembled analysis SACC (cosmo_val.smk assemble_sacc). Bound + # lazily through its helper so the filename tracks that rule, not a literal. + sacc=lambda w: cv_analysis_sacc(w.version), + # The two pipeline ini templates are static repo files, but binding them as + # inputs (not params) puts them in the DAG, so editing a template + # regenerates the configs rather than leaving stale output on disk. + template_2pt=str(INFERENCE_TEMPLATE_DIR / "cosmosis_pipeline_A_ia.ini"), + template_sacc=str(INFERENCE_TEMPLATE_DIR / "cosmosis_pipeline_A_ia_sacc.ini"), output: - fits_file=str( - COSMO_INFERENCE_PROD - / "data/{version}_{blind}_minsep={min_sep}_maxsep={max_sep}_nbins={nbins}_npatch={npatch}/cosmosis_{version}_{blind}_minsep={min_sep}_maxsep={max_sep}_nbins={nbins}_npatch={npatch}.fits" + fits_file=str(COSMO_INFERENCE_PROD / "data/{version}/cosmosis_{version}.fits"), + config_file_2pt=str( + INFERENCE_CONFIG_OUT / "cosmosis_pipeline_{version}_A_ia.ini" + ), + config_file_sacc=str( + INFERENCE_CONFIG_OUT / "cosmosis_pipeline_{version}_A_ia_sacc.ini" ), - config_file=str( - COSMO_INFERENCE_PROD - / "cosmosis_config/output/cosmosis_pipeline_{version}_{blind}_minsep={min_sep}_maxsep={max_sep}_nbins={nbins}_npatch={npatch}.ini" - ) params: - cosmosis_root="{version}_{blind}_minsep={min_sep}_maxsep={max_sep}_nbins={nbins}_npatch={npatch}", - data_dir=f"{CHAINS_DIR}/{{version}}_{{blind}}_minsep={{min_sep}}_maxsep={{max_sep}}_nbins={{nbins}}_npatch={{npatch}}", - output_root=str(COSMO_INFERENCE_PROD), + # SCRATCH = the per-version chain output root the generated inis point at. + scratch=lambda w: f"{CHAINS_DIR}/{w.version}", + cosmosis_dir=lambda w: _csl_dir(), threads: 1 resources: mem_mb=8000, runtime=10, - shell: - """ - cd {COSMO_INFERENCE_RUNDIR} + run: + import os + import sys - # Run inference preparation step with cosmosis_fitting.py - python scripts/cosmosis_fitting.py \ - --cosmosis-root {params.cosmosis_root} \ - --nz-file {input.nz_file} \ - --data-dir {params.data_dir} \ - --output-root {params.output_root} \ - --xi {input.xi_plus} {input.xi_minus} \ - --cov-xi {input.cov_matrix} \ - --use-rho-tau \ - --rho-stats {input.rho_stats} \ - --tau-stats {input.tau_stats} \ - --cov-tau {input.tau_cov} \ - --cl-file {input.pseudo_cl} \ - --cov-cl {input.pseudo_cl_cov} - """ + from sp_validation import sacc_io + from sp_validation.sacc_io import sacc_to_twopoint_fits + + os.makedirs(os.path.dirname(output.fits_file), exist_ok=True) + + # (a) converter 2pt-FITS — pure ξ (A_ia scope; no rho/tau sidecars). + sacc_to_twopoint_fits(sacc_io.load(input.sacc), output.fits_file, n_bins=1) + + # (b) + (c) the two generated pipeline inis, from the template inputs. + # WORKFLOW_SCRIPTS (common.py) is the absolute generic-workflow scripts dir. + sys.path.insert(0, WORKFLOW_SCRIPTS) + from generate_inference_config import ( + _substitutions, + generate_inference_config, + ) + + generate_inference_config( + input.template_2pt, + output.config_file_2pt, + _substitutions( + scratch=params.scratch, + cosmosis_dir=params.cosmosis_dir, + fits_file=output.fits_file, + ), + ) + generate_inference_config( + input.template_sacc, + output.config_file_sacc, + _substitutions( + scratch=params.scratch, + cosmosis_dir=params.cosmosis_dir, + sacc_file=input.sacc, + ), + ) rule inference_fiducial: input: - # Use the same output patterns as inference_prep with FIDUCIAL params - rules.inference_prep.output.fits_file.format( - version=FIDUCIAL["version"], blind=FIDUCIAL["blind"], - min_sep=FIDUCIAL["min_sep"], max_sep=FIDUCIAL["max_sep"], - nbins=FIDUCIAL["nbins"], npatch=FIDUCIAL["npatch"] - ), - rules.inference_prep.output.config_file.format( - version=FIDUCIAL["version"], blind=FIDUCIAL["blind"], - min_sep=FIDUCIAL["min_sep"], max_sep=FIDUCIAL["max_sep"], - nbins=FIDUCIAL["nbins"], npatch=FIDUCIAL["npatch"] - ) + # The fiducial version's prep products (both engine inis + the FITS). + rules.inference_prep.output.fits_file.format(version=FIDUCIAL["version"]), + rules.inference_prep.output.config_file_2pt.format(version=FIDUCIAL["version"]), + rules.inference_prep.output.config_file_sacc.format(version=FIDUCIAL["version"]), rule inference_glass_mocks: @@ -179,7 +216,5 @@ rule inference_prep_glass_mock: """ localrules: - inference_prep, inference_prep_glass_mock, - inference_fiducial, inference_glass_mocks, diff --git a/workflow/scripts/generate_inference_config.py b/workflow/scripts/generate_inference_config.py new file mode 100644 index 00000000..8b7ace43 --- /dev/null +++ b/workflow/scripts/generate_inference_config.py @@ -0,0 +1,159 @@ +"""Generate a CosmoSIS pipeline ini by filling a template's ``[DEFAULT]`` section. + +Dual-mode, like ``assemble_sacc.py``. Under Snakemake (``script:`` directive) the +injected ``snakemake`` object supplies the template, output path and DEFAULT +substitutions; as a standalone CLI (argparse) the same fill runs from explicit +flags. + +The template carries ``%(KEY)s`` interpolation placeholders (SCRATCH, FITS_FILE +or SACC_FILE, COSMOSIS_DIR, SP_VALIDATION_MODULES) in its module sections; this +script prepends the concrete ``KEY = value`` lines into ``[DEFAULT]`` so +CosmoSIS's ConfigParser resolves them at load. It is deliberately plain text +processing — appending lines after the ``[DEFAULT]`` header, the same idiom as +``pipeline.sh``'s ``sed -i "/^\\[DEFAULT\\]/a\\KEY = value"`` — rather than a +configparser round-trip, which would strip the template's comments and its +``%(...)s`` interpolation. + +``SP_VALIDATION_MODULES`` is resolved from ``sp_validation.__file__``'s parent so +the generated ini points at the installed package's module directory (where +``sacc_like_unions.py`` lives) regardless of checkout location. +""" + +import argparse +from pathlib import Path + + +def _sp_validation_modules(): + """The directory holding the sp_validation CosmoSIS module files. + + Resolved from the installed package so the generated ini finds + ``sacc_like_unions.py`` wherever sp_validation is installed. + """ + import sp_validation + + return str(Path(sp_validation.__file__).resolve().parent) + + +def generate_inference_config(template_path, out_path, substitutions): + """Write ``out_path`` from ``template_path`` with ``substitutions`` in DEFAULT. + + Parameters + ---------- + template_path : str or Path + The pipeline ini template (carries ``%(KEY)s`` placeholders). + out_path : str or Path + Destination ini. + substitutions : dict + ``{KEY: value}`` lines prepended into the template's ``[DEFAULT]`` + section. Every referenced ``%(KEY)s`` in the template must have a value + here (COSMOSIS_DIR already sits in the template's DEFAULT and may be + overridden). ``None`` values are dropped (an absent optional key). + """ + lines = Path(template_path).read_text().splitlines(keepends=True) + + header = "[DEFAULT]" + default_idx = next( + (i for i, line in enumerate(lines) if line.strip() == header), None + ) + if default_idx is None: + raise ValueError(f"template {template_path} has no [DEFAULT] section") + + # The end of the DEFAULT section: the next `[section]` header, or EOF. + section_end = next( + ( + i + for i in range(default_idx + 1, len(lines)) + if lines[i].lstrip().startswith("[") + ), + len(lines), + ) + + # A key the template already declares in DEFAULT is REPLACED in place (e.g. the + # template's placeholder COSMOSIS_DIR); a genuinely-new key is prepended just + # after the header. This avoids a duplicate DEFAULT key, which CosmoSIS's + # ConfigParser (strict) rejects. + wanted = {key: value for key, value in substitutions.items() if value is not None} + remaining = dict(wanted) + for i in range(default_idx + 1, section_end): + stripped = lines[i].lstrip() + if not stripped or stripped.startswith(("#", ";", "[")): + continue + existing_key = stripped.split("=", 1)[0].strip() + if existing_key in remaining: + lines[i] = f"{existing_key} = {remaining.pop(existing_key)}\n" + + prepended = [f"{key} = {value}\n" for key, value in remaining.items()] + out_lines = lines[: default_idx + 1] + prepended + lines[default_idx + 1 :] + + out_path = Path(out_path) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text("".join(out_lines)) + print( + f"Wrote {out_path} from {template_path} " + f"({len(wanted)} DEFAULT keys, {len(prepended)} new)" + ) + return str(out_path) + + +def _substitutions(scratch, cosmosis_dir, *, fits_file=None, sacc_file=None): + """Assemble the DEFAULT substitution dict, resolving SP_VALIDATION_MODULES. + + ``fits_file`` (2pt_like path) and ``sacc_file`` (sacc_like path) are the + data-file placeholders of their respective templates; whichever the template + references is filled, the other is left absent. + """ + return { + "SCRATCH": scratch, + "FITS_FILE": fits_file, + "SACC_FILE": sacc_file, + "COSMOSIS_DIR": cosmosis_dir, + "SP_VALIDATION_MODULES": _sp_validation_modules(), + } + + +def _from_snakemake(smk): + p = smk.params + generate_inference_config( + template_path=smk.input[0] + if not hasattr(smk.input, "template") + else smk.input.template, + out_path=str(smk.output[0]), + substitutions=_substitutions( + scratch=p["scratch"], + cosmosis_dir=p["cosmosis_dir"], + fits_file=p.get("fits_file", None), + sacc_file=p.get("sacc_file", None), + ), + ) + + +def _from_cli(argv=None): + ap = argparse.ArgumentParser( + description="Generate a CosmoSIS pipeline ini from a template + DEFAULT subs." + ) + ap.add_argument("--template", required=True, help="Pipeline ini template") + ap.add_argument("--out", required=True, help="Output ini path") + ap.add_argument("--scratch", required=True, help="SCRATCH value") + ap.add_argument("--cosmosis-dir", required=True, help="COSMOSIS_DIR value") + ap.add_argument("--fits-file", default=None, help="FITS_FILE (2pt_like path)") + ap.add_argument("--sacc-file", default=None, help="SACC_FILE (sacc_like path)") + a = ap.parse_args(argv) + generate_inference_config( + template_path=a.template, + out_path=a.out, + substitutions=_substitutions( + scratch=a.scratch, + cosmosis_dir=a.cosmosis_dir, + fits_file=a.fits_file, + sacc_file=a.sacc_file, + ), + ) + + +if __name__ == "__main__": + try: + snakemake # noqa: F821 — injected by Snakemake's script: directive + except NameError: + _from_cli() + else: + _from_snakemake(snakemake) # noqa: F821