From 3c542421d89e6940095304c79b64ce425445313f Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 16 Sep 2026 09:17:44 +0100 Subject: [PATCH] =?UTF-8?q?fix(config):=20prior=20yaml=20drift=20=E2=80=94?= =?UTF-8?q?=20stale=20classes,=20paths,=20params=20+=20walker=20test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `autonerves.JSONPriorConfig` resolves a prior by asking whether `{cls.__module__}.{cls.__name__}.{param}` ends with the dotted path of a yaml under `config/priors/` plus its key, so a yaml at the wrong path, a typo'd class key or a param the class no longer takes is silently dead rather than an error. Fix every such row in the packaged config: - light/operated/sersic.yaml: `ersic` -> `Sersic` (operated Sersic priors were dead and fell back to the standard Sersic file) - mass/dark: move `NFWTruncatedMCRScatterLudlowSph` from nfw_truncated_mcr.yaml to nfw_truncated_mcr_scatter.yaml, matching its module; `af.Model(NFWTruncatedMCRScatterLudlowSph)` raised ConfigException - light/linear/chameleon.yaml, eff.yaml: delete — no linear Chameleon or ElsonFreeFall class exists - point_sources.yaml: drop `PointSourceChi` (class removed) - mass/stellar/sersic_core.yaml: drop `SersicCoreSph.mass_to_light_ratio` (not an __init__ argument) - light/linear_operated/gaussian.yaml: drop `Gaussian.intensity` (linear profiles have no intensity) - ellipse/ellipse_multipole.yaml: `EllipseMultipoleRelative` -> `EllipseMultipoleScaled`, `gaussian_limits` -> `limits` - mesh/delaunay.yaml: drop the empty `DelaunayNN` key (module is delaunay_nn); mesh/README.md no longer mentions the removed Voronoi mesh Add test_autogalaxy/test_priors_config.py: walks the packaged priors and asserts every top-level key suffix-matches a real PyAuto class and every param is an __init__ argument, plus model-construction regressions for NFWTruncatedMCRScatterLudlowSph and EllipseMultipoleScaled. All four new assertions fail on the unfixed config. Refs #618 (stays open for the workspace follow-up PRs) Co-Authored-By: Claude Fable 5.1 --- .../priors/ellipse/ellipse_multipole.yaml | 6 +- .../config/priors/light/linear/chameleon.yaml | 106 -------- .../config/priors/light/linear/eff.yaml | 106 -------- .../light/linear_operated/gaussian.yaml | 10 - .../config/priors/light/operated/sersic.yaml | 2 +- .../priors/mass/dark/nfw_truncated_mcr.yaml | 61 ----- .../mass/dark/nfw_truncated_mcr_scatter.yaml | 61 +++++ .../priors/mass/stellar/sersic_core.yaml | 10 - autogalaxy/config/priors/mesh/README.md | 2 +- autogalaxy/config/priors/mesh/delaunay.yaml | 1 - autogalaxy/config/priors/point_sources.yaml | 21 -- test_autogalaxy/test_priors_config.py | 238 ++++++++++++++++++ 12 files changed, 304 insertions(+), 320 deletions(-) delete mode 100644 autogalaxy/config/priors/light/linear/chameleon.yaml delete mode 100644 autogalaxy/config/priors/light/linear/eff.yaml create mode 100644 autogalaxy/config/priors/mass/dark/nfw_truncated_mcr_scatter.yaml create mode 100644 test_autogalaxy/test_priors_config.py diff --git a/autogalaxy/config/priors/ellipse/ellipse_multipole.yaml b/autogalaxy/config/priors/ellipse/ellipse_multipole.yaml index f921c392c..676a90a27 100644 --- a/autogalaxy/config/priors/ellipse/ellipse_multipole.yaml +++ b/autogalaxy/config/priors/ellipse/ellipse_multipole.yaml @@ -20,7 +20,7 @@ EllipseMultipole: lower: -inf upper: inf -EllipseMultipoleRelative: +EllipseMultipoleScaled: scaled_multipole_comps_0: type: Uniform lower_limit: -0.1 @@ -28,7 +28,7 @@ EllipseMultipoleRelative: width_modifier: type: Absolute value: 0.05 - gaussian_limits: + limits: lower: -inf upper: inf scaled_multipole_comps_1: @@ -38,6 +38,6 @@ EllipseMultipoleRelative: width_modifier: type: Absolute value: 0.05 - gaussian_limits: + limits: lower: -inf upper: inf diff --git a/autogalaxy/config/priors/light/linear/chameleon.yaml b/autogalaxy/config/priors/light/linear/chameleon.yaml deleted file mode 100644 index d5aa1b21b..000000000 --- a/autogalaxy/config/priors/light/linear/chameleon.yaml +++ /dev/null @@ -1,106 +0,0 @@ -Chameleon: - centre_0: - type: Gaussian - mean: 0.0 - sigma: 0.3 - width_modifier: - type: Absolute - value: 0.05 - limits: - lower: -inf - upper: inf - centre_1: - type: Gaussian - mean: 0.0 - sigma: 0.3 - width_modifier: - type: Absolute - value: 0.05 - limits: - lower: -inf - upper: inf - core_radius_0: - type: Uniform - lower_limit: 0.0 - upper_limit: 30.0 - width_modifier: - type: Absolute - value: 0.3 - limits: - lower: 0.0 - upper: inf - core_radius_1: - type: Uniform - lower_limit: 0.0 - upper_limit: 30.0 - width_modifier: - type: Absolute - value: 0.3 - limits: - lower: 0.0 - upper: inf - ell_comps_0: - type: TruncatedGaussian - mean: 0.0 - sigma: 0.3 - lower_limit: -1.0 - upper_limit: 1.0 - width_modifier: - type: Absolute - value: 0.2 - limits: - lower: -1.0 - upper: 1.0 - ell_comps_1: - type: TruncatedGaussian - mean: 0.0 - sigma: 0.3 - lower_limit: -1.0 - upper_limit: 1.0 - width_modifier: - type: Absolute - value: 0.2 - limits: - lower: -1.0 - upper: 1.0 -ChameleonSph: - centre_0: - type: Gaussian - mean: 0.0 - sigma: 0.3 - width_modifier: - type: Absolute - value: 0.05 - limits: - lower: -inf - upper: inf - centre_1: - type: Gaussian - mean: 0.0 - sigma: 0.3 - width_modifier: - type: Absolute - value: 0.05 - limits: - lower: -inf - upper: inf - core_radius_0: - type: Uniform - lower_limit: 0.0 - upper_limit: 30.0 - width_modifier: - type: Absolute - value: 0.3 - limits: - lower: 0.0 - upper: inf - core_radius_1: - type: Uniform - lower_limit: 0.0 - upper_limit: 30.0 - width_modifier: - type: Absolute - value: 0.3 - limits: - lower: 0.0 - upper: inf diff --git a/autogalaxy/config/priors/light/linear/eff.yaml b/autogalaxy/config/priors/light/linear/eff.yaml deleted file mode 100644 index 325eb2eea..000000000 --- a/autogalaxy/config/priors/light/linear/eff.yaml +++ /dev/null @@ -1,106 +0,0 @@ -ElsonFreeFall: - centre_0: - type: Gaussian - mean: 0.0 - sigma: 0.3 - width_modifier: - type: Absolute - value: 0.05 - limits: - lower: -inf - upper: inf - centre_1: - type: Gaussian - mean: 0.0 - sigma: 0.3 - width_modifier: - type: Absolute - value: 0.05 - limits: - lower: -inf - upper: inf - effective_radius: - type: Uniform - lower_limit: 0.0 - upper_limit: 30.0 - width_modifier: - type: Relative - value: 1.0 - limits: - lower: 0.0 - upper: inf - ell_comps_0: - type: TruncatedGaussian - mean: 0.0 - sigma: 0.3 - lower_limit: -1.0 - upper_limit: 1.0 - width_modifier: - type: Absolute - value: 0.2 - limits: - lower: -1.0 - upper: 1.0 - ell_comps_1: - type: TruncatedGaussian - mean: 0.0 - sigma: 0.3 - lower_limit: -1.0 - upper_limit: 1.0 - width_modifier: - type: Absolute - value: 0.2 - limits: - lower: -1.0 - upper: 1.0 - eta: - type: Uniform - lower_limit: 0.5 - upper_limit: 3.0 - width_modifier: - type: Absolute - value: 1.5 - limits: - lower: 0.0 - upper: 5.0 -ElsonFreeFallSph: - centre_0: - type: Gaussian - mean: 0.0 - sigma: 0.3 - width_modifier: - type: Absolute - value: 0.05 - limits: - lower: -inf - upper: inf - centre_1: - type: Gaussian - mean: 0.0 - sigma: 0.3 - width_modifier: - type: Absolute - value: 0.05 - limits: - lower: -inf - upper: inf - effective_radius: - type: Uniform - lower_limit: 0.0 - upper_limit: 30.0 - width_modifier: - type: Relative - value: 1.0 - limits: - lower: 0.0 - upper: inf - eta: - type: Uniform - lower_limit: 0.5 - upper_limit: 3.0 - width_modifier: - type: Absolute - value: 1.5 - limits: - lower: 0.0 - upper: 5.0 diff --git a/autogalaxy/config/priors/light/linear_operated/gaussian.yaml b/autogalaxy/config/priors/light/linear_operated/gaussian.yaml index ff5544cbb..e6ee9de71 100644 --- a/autogalaxy/config/priors/light/linear_operated/gaussian.yaml +++ b/autogalaxy/config/priors/light/linear_operated/gaussian.yaml @@ -53,13 +53,3 @@ Gaussian: limits: lower: -1.0 upper: 1.0 - intensity: - type: LogUniform - lower_limit: 1.0e-06 - upper_limit: 1000000.0 - width_modifier: - type: Relative - value: 0.5 - limits: - lower: 0.0 - upper: inf diff --git a/autogalaxy/config/priors/light/operated/sersic.yaml b/autogalaxy/config/priors/light/operated/sersic.yaml index 7279c953f..04a692e70 100644 --- a/autogalaxy/config/priors/light/operated/sersic.yaml +++ b/autogalaxy/config/priors/light/operated/sersic.yaml @@ -1,4 +1,4 @@ -ersic: +Sersic: centre_0: type: Gaussian mean: 0.0 diff --git a/autogalaxy/config/priors/mass/dark/nfw_truncated_mcr.yaml b/autogalaxy/config/priors/mass/dark/nfw_truncated_mcr.yaml index 667c798db..6c2d1e8cc 100644 --- a/autogalaxy/config/priors/mass/dark/nfw_truncated_mcr.yaml +++ b/autogalaxy/config/priors/mass/dark/nfw_truncated_mcr.yaml @@ -100,64 +100,3 @@ NFWTruncatedMCRLudlowSph: limits: lower: 0.0 upper: inf -NFWTruncatedMCRScatterLudlowSph: - centre_0: - type: Gaussian - mean: 0.0 - sigma: 0.1 - width_modifier: - type: Absolute - value: 0.05 - limits: - lower: -inf - upper: inf - centre_1: - type: Gaussian - mean: 0.0 - sigma: 0.1 - width_modifier: - type: Absolute - value: 0.05 - limits: - lower: -inf - upper: inf - mass_at_200: - type: LogUniform - lower_limit: 100000000.0 - upper_limit: 1000000000000000.0 - width_modifier: - type: Relative - value: 0.5 - limits: - lower: 0.0 - upper: inf - redshift_object: - type: Uniform - lower_limit: 0.0 - upper_limit: 1.0 - width_modifier: - type: Relative - value: 0.5 - limits: - lower: 0.0 - upper: inf - redshift_source: - type: Uniform - lower_limit: 0.0 - upper_limit: 1.0 - width_modifier: - type: Relative - value: 0.5 - limits: - lower: 0.0 - upper: inf - scatter_sigma: - type: Gaussian - mean: 0.0 - sigma: 3.0 - width_modifier: - type: Absolute - value: 1.0 - limits: - lower: -inf - upper: inf diff --git a/autogalaxy/config/priors/mass/dark/nfw_truncated_mcr_scatter.yaml b/autogalaxy/config/priors/mass/dark/nfw_truncated_mcr_scatter.yaml new file mode 100644 index 000000000..1aa55e274 --- /dev/null +++ b/autogalaxy/config/priors/mass/dark/nfw_truncated_mcr_scatter.yaml @@ -0,0 +1,61 @@ +NFWTruncatedMCRScatterLudlowSph: + centre_0: + type: Gaussian + mean: 0.0 + sigma: 0.1 + width_modifier: + type: Absolute + value: 0.05 + limits: + lower: -inf + upper: inf + centre_1: + type: Gaussian + mean: 0.0 + sigma: 0.1 + width_modifier: + type: Absolute + value: 0.05 + limits: + lower: -inf + upper: inf + mass_at_200: + type: LogUniform + lower_limit: 100000000.0 + upper_limit: 1000000000000000.0 + width_modifier: + type: Relative + value: 0.5 + limits: + lower: 0.0 + upper: inf + redshift_object: + type: Uniform + lower_limit: 0.0 + upper_limit: 1.0 + width_modifier: + type: Relative + value: 0.5 + limits: + lower: 0.0 + upper: inf + redshift_source: + type: Uniform + lower_limit: 0.0 + upper_limit: 1.0 + width_modifier: + type: Relative + value: 0.5 + limits: + lower: 0.0 + upper: inf + scatter_sigma: + type: Gaussian + mean: 0.0 + sigma: 3.0 + width_modifier: + type: Absolute + value: 1.0 + limits: + lower: -inf + upper: inf diff --git a/autogalaxy/config/priors/mass/stellar/sersic_core.yaml b/autogalaxy/config/priors/mass/stellar/sersic_core.yaml index f3917e763..d77992e83 100644 --- a/autogalaxy/config/priors/mass/stellar/sersic_core.yaml +++ b/autogalaxy/config/priors/mass/stellar/sersic_core.yaml @@ -139,16 +139,6 @@ SersicCoreSph: limits: lower: 0.0 upper: inf - mass_to_light_ratio: - type: LogUniform - lower_limit: 1.0e-06 - upper_limit: 1000000.0 - width_modifier: - type: Relative - value: 0.3 - limits: - lower: 0.0 - upper: inf radius_break: type: Constant value: 0.025 diff --git a/autogalaxy/config/priors/mesh/README.md b/autogalaxy/config/priors/mesh/README.md index ac0d7fc93..78e5f03f3 100644 --- a/autogalaxy/config/priors/mesh/README.md +++ b/autogalaxy/config/priors/mesh/README.md @@ -1,3 +1,3 @@ The `mesh` folder contains configuration files for the default priors assumed for `mesh` objects. -These model components reconstruct a galaxy's emission using a rectangular grid, Delaunay triangulation or Voronoi mesh. +These model components reconstruct a galaxy's emission using a rectangular grid or Delaunay triangulation. diff --git a/autogalaxy/config/priors/mesh/delaunay.yaml b/autogalaxy/config/priors/mesh/delaunay.yaml index f8a9f390f..604de83de 100644 --- a/autogalaxy/config/priors/mesh/delaunay.yaml +++ b/autogalaxy/config/priors/mesh/delaunay.yaml @@ -1,2 +1 @@ Delaunay: -DelaunayNN: diff --git a/autogalaxy/config/priors/point_sources.yaml b/autogalaxy/config/priors/point_sources.yaml index b589b2fdf..ee3763c64 100644 --- a/autogalaxy/config/priors/point_sources.yaml +++ b/autogalaxy/config/priors/point_sources.yaml @@ -50,24 +50,3 @@ PointFlux: limits: lower: 0.0 upper: inf -PointSourceChi: - centre_0: - type: Gaussian - mean: 0.0 - sigma: 0.3 - width_modifier: - type: Absolute - value: 0.05 - limits: - lower: -inf - upper: inf - centre_1: - type: Gaussian - mean: 0.0 - sigma: 0.3 - width_modifier: - type: Absolute - value: 0.05 - limits: - lower: -inf - upper: inf diff --git a/test_autogalaxy/test_priors_config.py b/test_autogalaxy/test_priors_config.py new file mode 100644 index 000000000..b1e25791f --- /dev/null +++ b/test_autogalaxy/test_priors_config.py @@ -0,0 +1,238 @@ +""" +Tests that guard the packaged `autogalaxy/config/priors` yaml files against drift. + +`autonerves.JSONPriorConfig` turns every yaml file under `config/priors` into a +dotted path built from the file's location relative to `priors`, and looks a +prior up by asking whether `f"{cls.__module__}.{cls.__name__}"` ends with that +path. A yaml file in the wrong folder, a mistyped class key or a parameter that +is no longer an `__init__` argument is therefore silently dead: no error is +raised, the default prior is simply never used. + +These tests walk the packaged yaml files directly (not via `conf.instance`, +which the test suite pushes to `test_autogalaxy/config`) and assert that every +key resolves to a real class and every parameter is a real `__init__` argument. +""" + +import importlib +import inspect +import pkgutil +from pathlib import Path +from typing import Dict, Iterator, List, Tuple + +import yaml + +import autofit as af +import autogalaxy as ag + +PRIORS_PATH = Path(ag.__file__).parent / "config" / "priors" + +CENSUS_PACKAGES = ("autogalaxy", "autoarray", "autofit") + +# Class-path suffixes that are known not to resolve, mapped to the reason. The +# goal is for this to stay empty -- every entry is prior configuration that is +# silently dead. +ALLOWLIST: Dict[str, str] = {} + +_CENSUS: Dict[str, type] = {} +_CENSUS_SKIPPED: List[Tuple[str, str]] = [] + + +def class_census() -> Dict[str, type]: + """ + Every class defined by the PyAuto packages, keyed by its fully qualified + `module.Name` path. Built once and cached, as walking the packages imports + every submodule. + """ + if _CENSUS: + return _CENSUS + + for package_name in CENSUS_PACKAGES: + package = importlib.import_module(package_name) + modules = [package] + + walker = pkgutil.walk_packages( + package.__path__, + prefix=f"{package.__name__}.", + onerror=lambda name: _CENSUS_SKIPPED.append((name, "walk_packages")), + ) + + while True: + try: + info = next(walker) + except StopIteration: + break + except Exception as e: + _CENSUS_SKIPPED.append(("", repr(e))) + continue + + if info.name.split(".")[-1] == "__main__": + # `__main__` modules are command line entry points which run on + # import (e.g. `autofit.mcp.__main__` starts a stdio server and + # re-pins `conf.instance`), so they must never be imported here. + continue + + try: + modules.append(importlib.import_module(info.name)) + except Exception as e: + _CENSUS_SKIPPED.append((info.name, repr(e))) + + for module in modules: + # `vars` rather than `inspect.getmembers`, as the top level packages + # define a lazy `__getattr__` which would import optional + # dependencies on attribute access. + for obj in list(vars(module).values()): + if ( + inspect.isclass(obj) + and getattr(obj, "__module__", None) == module.__name__ + ): + _CENSUS[f"{obj.__module__}.{obj.__qualname__}"] = obj + + return _CENSUS + + +def prior_blocks() -> Iterator[Tuple[Path, str, str, dict]]: + """ + Yield `(path, relative_dotted_path, top_level_key, block)` for every top + level key of every yaml file under the packaged priors folder. + """ + for path in sorted(PRIORS_PATH.rglob("*.yaml")): + relative = ".".join(path.relative_to(PRIORS_PATH).with_suffix("").parts) + config = yaml.safe_load(path.read_text()) or {} + + for key, block in config.items(): + yield path, relative, key, block + + +def class_path_suffix(relative: str, key: str) -> str: + """ + The class path a `JSONPriorConfig` lookup must end with for this key, e.g. + `mass.dark.nfw.NFWSph`. Keys may themselves be dotted, e.g. + `model.FlatLambdaCDM` in `cosmology.yaml`. + """ + return f"{relative}.{key}" + + +def matching_classes(suffix: str) -> List[str]: + return [ + name for name in class_census() if name == suffix or name.endswith(f".{suffix}") + ] + + +def init_parameters(cls: type) -> Tuple[set, bool]: + """ + The `__init__` argument names of `cls` (excluding `self`) and whether the + signature accepts arbitrary keyword arguments. + """ + try: + signature = inspect.signature(cls.__init__) + except (TypeError, ValueError): + return set(), True + + names = set() + has_var_keyword = False + + for name, parameter in signature.parameters.items(): + if parameter.kind is parameter.VAR_KEYWORD: + has_var_keyword = True + names.add(name) + + names.discard("self") + + return names, has_var_keyword + + +def parameter_base_name(parameter: str) -> str: + """ + Tuple arguments are flattened in the yaml with an index suffix, e.g. + `centre` is configured as `centre_0` and `centre_1`. + """ + head, _, tail = parameter.rpartition("_") + + if head and tail.isdigit(): + return head + + return parameter + + +def test__priors_path_is_the_packaged_config(): + assert PRIORS_PATH.is_dir() + assert any(PRIORS_PATH.rglob("*.yaml")) + + +def test__every_prior_key_resolves_to_a_class(): + misses = [] + + for path, relative, key, _ in prior_blocks(): + suffix = class_path_suffix(relative, key) + + if suffix in ALLOWLIST: + continue + + if not matching_classes(suffix): + misses.append( + f"{path.relative_to(PRIORS_PATH)} :: {key} " + f"(no class path ends with '{suffix}')" + ) + + assert not misses, ( + "Prior configuration keys which do not resolve to any class, and are " + "therefore silently dead:\n " + "\n ".join(misses) + ) + + +def test__every_prior_parameter_is_an_init_argument(): + misses = [] + + for path, relative, key, block in prior_blocks(): + suffix = class_path_suffix(relative, key) + + if suffix in ALLOWLIST or not isinstance(block, dict): + continue + + matches = matching_classes(suffix) + + if not matches: + continue + + names = set() + has_var_keyword = False + + for name in matches: + class_names, class_var_keyword = init_parameters(class_census()[name]) + names |= class_names + has_var_keyword |= class_var_keyword + + if has_var_keyword: + continue + + for parameter in block: + if parameter in names or parameter_base_name(parameter) in names: + continue + + misses.append( + f"{path.relative_to(PRIORS_PATH)} :: {key} :: {parameter} " + f"(__init__ arguments are {sorted(names)})" + ) + + assert not misses, ( + "Prior configuration parameters which are not `__init__` arguments of " + "their class, and are therefore silently dead:\n " + "\n ".join(misses) + ) + + +def test__nfw_truncated_mcr_scatter_ludlow_sph_model_resolves(): + model = af.Model(ag.mp.NFWTruncatedMCRScatterLudlowSph) + + assert model.prior_count == 6 + + model.instance_from_prior_medians() + + +def test__ellipse_multipole_scaled_model_resolves(): + # `m` and `major_axis` have no configured prior, exactly as for the parent + # `EllipseMultipole`, so they are passed as fixed values here. + model = af.Model(ag.EllipseMultipoleScaled, m=4, major_axis=1.0) + + assert model.prior_count == 2 + + model.instance_from_prior_medians()