From 52343c7972d56dc8cd43635a32702895a82c5900 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 18 Nov 2026 15:04:40 +0000 Subject: [PATCH 1/2] fix: compound-prior models serialise to model.json and reload with the same identifier A model such as stars.mass = (1 - f) * m, halo.mass = f * m failed in search.fit when paths.save_all wrote model.json: TypeError: Object of type UniformPrior is not JSON serializable. - ModifiedPrior.dict (NegativePrior, AbsolutePrior, Log, ...) serialised its operand only when it was an AbstractPriorModel; a plain Prior is a ModelObject, so the raw prior was written. Check ModelObject, as CompoundPrior.dict already does. - ModifiedPrior.cls returned self.prior.cls, which a plain Prior lacks, so search.fit then failed in superscripts/prior_class_dict. Return float for a plain prior, as CompoundPrior does. - CompoundPrior.dict now saves the operand attribute names and from_dict restores them. They are part of the model identifier, so a reloaded model keeps its identifier. Dicts written before this load as before. Fixes #1782 Co-Authored-By: Claude Opus 5.5 --- autofit/mapper/prior/arithmetic/compound.py | 38 +++++++- test_autofit/serialise/test_assertions.py | 10 +- test_autofit/serialise/test_compound_model.py | 94 +++++++++++++++++++ test_autofit/serialise/test_sum_prior.py | 9 +- 4 files changed, 146 insertions(+), 5 deletions(-) create mode 100644 test_autofit/serialise/test_compound_model.py diff --git a/autofit/mapper/prior/arithmetic/compound.py b/autofit/mapper/prior/arithmetic/compound.py index c5805cc2b..a919c0d5a 100644 --- a/autofit/mapper/prior/arithmetic/compound.py +++ b/autofit/mapper/prior/arithmetic/compound.py @@ -102,6 +102,8 @@ def dict(self) -> dict: "right": self._right.dict() if isinstance(self._right, ModelObject) else self._right, + "left_name": self._left_name, + "right_name": self._right_name, } @classmethod @@ -113,10 +115,36 @@ def from_dict( ): from autofit import ModelObject - return cls( + compound = cls( ModelObject.from_dict(d["left"], reference, loaded_ids), ModelObject.from_dict(d["right"], reference, loaded_ids), ) + compound._set_operand_names(d.get("left_name"), d.get("right_name")) + return compound + + def _set_operand_names( + self, left_name: Optional[str], right_name: Optional[str] + ): + """ + Restore the attribute names the operands were stored under when the + compound was serialised. + + The names are found by inspecting the caller's frames when the + compound is first built, so a compound rebuilt by ``from_dict`` would + otherwise get different names. They are part of the model identifier, + so a reloaded model must keep them. Dictionaries written before the + names were serialised carry none and keep the rebuilt names. + """ + left_name = left_name or self._left_name + right_name = right_name or self._right_name + + for name in {self._left_name, self._right_name} - {left_name, right_name}: + self.__dict__.pop(name, None) + + self._left_name = left_name + self._right_name = right_name + setattr(self, left_name, self._left) + setattr(self, right_name, self._right) @property def left(self): @@ -359,12 +387,14 @@ def __init__(self, prior, name=None): self.prior = prior def dict(self): + from autofit import ModelObject + return { "type": "modified", "modified_type": self.__class__.__name__, "name": self._prior_name, "prior": self.prior.dict() - if isinstance(self.prior, AbstractPriorModel) + if isinstance(self.prior, ModelObject) else self.prior, } @@ -393,7 +423,9 @@ def __add__(self, other): @property def cls(self): - return self.prior.cls + if isinstance(self.prior, AbstractPriorModel): + return self.prior.cls + return float @property def prior(self): diff --git a/test_autofit/serialise/test_assertions.py b/test_autofit/serialise/test_assertions.py index c386a780c..28bae67f8 100644 --- a/test_autofit/serialise/test_assertions.py +++ b/test_autofit/serialise/test_assertions.py @@ -58,7 +58,15 @@ def make_model(): def test_to_dict(model_dict, model): model.add_assertion(model.centre > 0) - assert model.dict() == model_dict + d = model.dict() + + # The operand names are found by inspecting the caller's frames, so their + # values depend on the call stack; check they are written, not what they are. + (assertion,) = d["assertions"] + assert isinstance(assertion.pop("left_name"), str) + assert isinstance(assertion.pop("right_name"), str) + + assert d == model_dict def test_from_dict(assertion_dict): diff --git a/test_autofit/serialise/test_compound_model.py b/test_autofit/serialise/test_compound_model.py new file mode 100644 index 000000000..01622df4f --- /dev/null +++ b/test_autofit/serialise/test_compound_model.py @@ -0,0 +1,94 @@ +import json + +import pytest + +import autofit as af +from autofit.mapper.prior.arithmetic.compound import NegativePrior +from autonerves.dictable import to_dict, from_dict + + +@pytest.fixture(name="model") +def make_model(): + """ + A model where two priors are shared by two components through arithmetic, + like a stellar mass ``(1 - f) * m`` and a dark mass ``f * m``. + """ + m = af.UniformPrior(lower_limit=0.0, upper_limit=10.0) + f = af.UniformPrior(lower_limit=0.0, upper_limit=1.0) + + stars = af.Model(af.ex.Gaussian) + halo = af.Model(af.ex.Gaussian) + + stars.normalization = (1.0 - f) * m + halo.normalization = f * m + + for component in (stars, halo): + component.centre = 50.0 + component.sigma = 10.0 + + return af.Collection(stars=stars, halo=halo) + + +@pytest.fixture(name="loaded") +def make_loaded(model): + return from_dict(json.loads(json.dumps(to_dict(model)))) + + +def test_dict_is_json_serialisable(model): + json.dumps(to_dict(model)) + + +def test_round_trip_keeps_shared_priors(model, loaded): + assert loaded.prior_count == model.prior_count == 2 + + +def test_round_trip_keeps_identifier(model, loaded): + assert loaded.identifier == model.identifier + + +def test_round_trip_gives_same_instance(model, loaded): + values = {"m": 7.0, "f": 0.3} + + def instance(m): + arguments = { + prior: values[prior_name(m, prior)] for prior in m.priors_ordered_by_id + } + return m.instance_for_arguments(arguments) + + def prior_name(m, prior): + (name,) = {path[-1] for path, p in m.path_priors_tuples if p is prior} + return name + + original = instance(model) + reloaded = instance(loaded) + + assert reloaded.stars.normalization == pytest.approx(original.stars.normalization) == 4.9 + assert reloaded.halo.normalization == pytest.approx(original.halo.normalization) == 2.1 + + +def test_modified_prior_of_a_prior_serialises(): + f = af.UniformPrior(lower_limit=0.0, upper_limit=1.0) + negative = -f + + assert isinstance(negative, NegativePrior) + assert negative.dict()["prior"]["type"] == "Uniform" + assert negative.cls is float + + loaded = af.ModelObject.from_dict(json.loads(json.dumps(negative.dict()))) + assert isinstance(loaded, NegativePrior) + assert loaded.instance_from_prior_medians() == -0.5 + + +def test_info(model): + assert "MultiplePrior" in model.info + + +def test_dict_without_operand_names_loads(): + d = { + "type": "compound", + "compound_type": "SumPrior", + "left": 1.0, + "right": {"type": "Uniform", "id": 0, "lower_limit": 0.0, "upper_limit": 1.0}, + } + loaded = af.ModelObject.from_dict(d) + assert loaded.instance_from_prior_medians() == 1.5 diff --git a/test_autofit/serialise/test_sum_prior.py b/test_autofit/serialise/test_sum_prior.py index 6ca13ecd0..6b96981de 100644 --- a/test_autofit/serialise/test_sum_prior.py +++ b/test_autofit/serialise/test_sum_prior.py @@ -32,7 +32,14 @@ def test_sum_prior(prior_dict): sum_prior = prior + prior - assert sum_prior.dict() == prior_dict + d = sum_prior.dict() + + # The operand names are found by inspecting the caller's frames, so their + # values depend on the call stack; check they are written, not what they are. + assert isinstance(d.pop("left_name"), str) + assert isinstance(d.pop("right_name"), str) + + assert d == prior_dict def test_sum_prior_from_dict(prior_dict): From ec11c36d600e3bdda786f719a56d81e154f230c5 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 18 Nov 2026 15:10:40 +0000 Subject: [PATCH 2/2] fix: modified priors set directly on a model reload from model.json The "modified" dict type (NegativePrior, AbsolutePrior, Log, ...) had no parser registered with autonerves, so a model attribute such as model.sigma = -f fell through to a class_path lookup, raised KeyError, and the model loader silently kept the default prior. Register ModelObject.from_dict for "modified" as it is for "compound". Tests: a modified prior on a model round-trips with the same type, prior count and identifier; search.fit runs on a shared compound-prior model; paths.save_all writes a model.json that reloads with the same identifier. Found by the independent adversary review. Refs #1782 Co-Authored-By: Claude Opus 5.5 --- autofit/__init__.py | 1 + test_autofit/serialise/test_compound_model.py | 43 +++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/autofit/__init__.py b/autofit/__init__.py index e439692bf..7948c3eda 100644 --- a/autofit/__init__.py +++ b/autofit/__init__.py @@ -158,6 +158,7 @@ "LogGaussian", "TruncatedGaussian", "compound", + "modified", "Constant", ): register_parser(type_, ModelObject.from_dict) diff --git a/test_autofit/serialise/test_compound_model.py b/test_autofit/serialise/test_compound_model.py index 01622df4f..ac508fec1 100644 --- a/test_autofit/serialise/test_compound_model.py +++ b/test_autofit/serialise/test_compound_model.py @@ -92,3 +92,46 @@ def test_dict_without_operand_names_loads(): } loaded = af.ModelObject.from_dict(d) assert loaded.instance_from_prior_medians() == 1.5 + + +@pytest.mark.parametrize("modify", [lambda p: -p, lambda p: abs(-p)]) +def test_modified_prior_in_model_round_trips(modify): + f = af.UniformPrior(lower_limit=0.0, upper_limit=1.0) + + model = af.Model(af.ex.Gaussian) + model.centre = 50.0 + model.normalization = f + model.sigma = modify(f) + + loaded = from_dict(json.loads(json.dumps(to_dict(model)))) + + assert type(loaded.sigma) is type(model.sigma) + assert loaded.prior_count == model.prior_count == 1 + assert loaded.identifier == model.identifier + + +class Analysis(af.Analysis): + def log_likelihood_function(self, instance): + return -((instance.stars.normalization - 3.0) ** 2) + + +def test_search_fit_starts(model): + search = af.Drawer(name="test_compound_model_fit", total_draws=2) + + result = search.fit(model=model, analysis=Analysis()) + + assert result.max_log_likelihood_instance.stars.normalization is not None + + +def test_save_all_writes_model_json(model): + search = af.Drawer(name="test_compound_model_json") + search.paths.model = model + search.paths.search = search + + search.paths.save_all() + + with open(search.paths._files_path / "model.json") as f: + loaded = from_dict(json.load(f)) + + assert loaded.prior_count == model.prior_count + assert loaded.identifier == model.identifier