Skip to content

Commit 52343c7

Browse files
Jammy2211claude
andcommitted
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 <noreply@anthropic.com>
1 parent 3ba1e6c commit 52343c7

4 files changed

Lines changed: 146 additions & 5 deletions

File tree

‎autofit/mapper/prior/arithmetic/compound.py‎

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,8 @@ def dict(self) -> dict:
102102
"right": self._right.dict()
103103
if isinstance(self._right, ModelObject)
104104
else self._right,
105+
"left_name": self._left_name,
106+
"right_name": self._right_name,
105107
}
106108

107109
@classmethod
@@ -113,10 +115,36 @@ def from_dict(
113115
):
114116
from autofit import ModelObject
115117

116-
return cls(
118+
compound = cls(
117119
ModelObject.from_dict(d["left"], reference, loaded_ids),
118120
ModelObject.from_dict(d["right"], reference, loaded_ids),
119121
)
122+
compound._set_operand_names(d.get("left_name"), d.get("right_name"))
123+
return compound
124+
125+
def _set_operand_names(
126+
self, left_name: Optional[str], right_name: Optional[str]
127+
):
128+
"""
129+
Restore the attribute names the operands were stored under when the
130+
compound was serialised.
131+
132+
The names are found by inspecting the caller's frames when the
133+
compound is first built, so a compound rebuilt by ``from_dict`` would
134+
otherwise get different names. They are part of the model identifier,
135+
so a reloaded model must keep them. Dictionaries written before the
136+
names were serialised carry none and keep the rebuilt names.
137+
"""
138+
left_name = left_name or self._left_name
139+
right_name = right_name or self._right_name
140+
141+
for name in {self._left_name, self._right_name} - {left_name, right_name}:
142+
self.__dict__.pop(name, None)
143+
144+
self._left_name = left_name
145+
self._right_name = right_name
146+
setattr(self, left_name, self._left)
147+
setattr(self, right_name, self._right)
120148

121149
@property
122150
def left(self):
@@ -359,12 +387,14 @@ def __init__(self, prior, name=None):
359387
self.prior = prior
360388

361389
def dict(self):
390+
from autofit import ModelObject
391+
362392
return {
363393
"type": "modified",
364394
"modified_type": self.__class__.__name__,
365395
"name": self._prior_name,
366396
"prior": self.prior.dict()
367-
if isinstance(self.prior, AbstractPriorModel)
397+
if isinstance(self.prior, ModelObject)
368398
else self.prior,
369399
}
370400

@@ -393,7 +423,9 @@ def __add__(self, other):
393423

394424
@property
395425
def cls(self):
396-
return self.prior.cls
426+
if isinstance(self.prior, AbstractPriorModel):
427+
return self.prior.cls
428+
return float
397429

398430
@property
399431
def prior(self):

‎test_autofit/serialise/test_assertions.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,15 @@ def make_model():
5858
def test_to_dict(model_dict, model):
5959
model.add_assertion(model.centre > 0)
6060

61-
assert model.dict() == model_dict
61+
d = model.dict()
62+
63+
# The operand names are found by inspecting the caller's frames, so their
64+
# values depend on the call stack; check they are written, not what they are.
65+
(assertion,) = d["assertions"]
66+
assert isinstance(assertion.pop("left_name"), str)
67+
assert isinstance(assertion.pop("right_name"), str)
68+
69+
assert d == model_dict
6270

6371

6472
def test_from_dict(assertion_dict):
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
import json
2+
3+
import pytest
4+
5+
import autofit as af
6+
from autofit.mapper.prior.arithmetic.compound import NegativePrior
7+
from autonerves.dictable import to_dict, from_dict
8+
9+
10+
@pytest.fixture(name="model")
11+
def make_model():
12+
"""
13+
A model where two priors are shared by two components through arithmetic,
14+
like a stellar mass ``(1 - f) * m`` and a dark mass ``f * m``.
15+
"""
16+
m = af.UniformPrior(lower_limit=0.0, upper_limit=10.0)
17+
f = af.UniformPrior(lower_limit=0.0, upper_limit=1.0)
18+
19+
stars = af.Model(af.ex.Gaussian)
20+
halo = af.Model(af.ex.Gaussian)
21+
22+
stars.normalization = (1.0 - f) * m
23+
halo.normalization = f * m
24+
25+
for component in (stars, halo):
26+
component.centre = 50.0
27+
component.sigma = 10.0
28+
29+
return af.Collection(stars=stars, halo=halo)
30+
31+
32+
@pytest.fixture(name="loaded")
33+
def make_loaded(model):
34+
return from_dict(json.loads(json.dumps(to_dict(model))))
35+
36+
37+
def test_dict_is_json_serialisable(model):
38+
json.dumps(to_dict(model))
39+
40+
41+
def test_round_trip_keeps_shared_priors(model, loaded):
42+
assert loaded.prior_count == model.prior_count == 2
43+
44+
45+
def test_round_trip_keeps_identifier(model, loaded):
46+
assert loaded.identifier == model.identifier
47+
48+
49+
def test_round_trip_gives_same_instance(model, loaded):
50+
values = {"m": 7.0, "f": 0.3}
51+
52+
def instance(m):
53+
arguments = {
54+
prior: values[prior_name(m, prior)] for prior in m.priors_ordered_by_id
55+
}
56+
return m.instance_for_arguments(arguments)
57+
58+
def prior_name(m, prior):
59+
(name,) = {path[-1] for path, p in m.path_priors_tuples if p is prior}
60+
return name
61+
62+
original = instance(model)
63+
reloaded = instance(loaded)
64+
65+
assert reloaded.stars.normalization == pytest.approx(original.stars.normalization) == 4.9
66+
assert reloaded.halo.normalization == pytest.approx(original.halo.normalization) == 2.1
67+
68+
69+
def test_modified_prior_of_a_prior_serialises():
70+
f = af.UniformPrior(lower_limit=0.0, upper_limit=1.0)
71+
negative = -f
72+
73+
assert isinstance(negative, NegativePrior)
74+
assert negative.dict()["prior"]["type"] == "Uniform"
75+
assert negative.cls is float
76+
77+
loaded = af.ModelObject.from_dict(json.loads(json.dumps(negative.dict())))
78+
assert isinstance(loaded, NegativePrior)
79+
assert loaded.instance_from_prior_medians() == -0.5
80+
81+
82+
def test_info(model):
83+
assert "MultiplePrior" in model.info
84+
85+
86+
def test_dict_without_operand_names_loads():
87+
d = {
88+
"type": "compound",
89+
"compound_type": "SumPrior",
90+
"left": 1.0,
91+
"right": {"type": "Uniform", "id": 0, "lower_limit": 0.0, "upper_limit": 1.0},
92+
}
93+
loaded = af.ModelObject.from_dict(d)
94+
assert loaded.instance_from_prior_medians() == 1.5

‎test_autofit/serialise/test_sum_prior.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,14 @@ def test_sum_prior(prior_dict):
3232

3333
sum_prior = prior + prior
3434

35-
assert sum_prior.dict() == prior_dict
35+
d = sum_prior.dict()
36+
37+
# The operand names are found by inspecting the caller's frames, so their
38+
# values depend on the call stack; check they are written, not what they are.
39+
assert isinstance(d.pop("left_name"), str)
40+
assert isinstance(d.pop("right_name"), str)
41+
42+
assert d == prior_dict
3643

3744

3845
def test_sum_prior_from_dict(prior_dict):

0 commit comments

Comments
 (0)