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/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..ac508fec1 --- /dev/null +++ b/test_autofit/serialise/test_compound_model.py @@ -0,0 +1,137 @@ +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 + + +@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 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):