Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions autofit/mapper/identifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,31 @@ def __set__(self, obj, value):
setattr(obj, self.private, value)


def _assertion_operands(assertion) -> list:
"""
The operands of an assertion, in order.

A `CompoundAssertion` joins two assertions as `assertion_1` and `assertion_2`. Every
other assertion is a `CompoundPrior`, which holds its two sides in `_left` and
`_right`; its public aliases are named after the caller's local variables, so they
are not a stable component of an identifier.

Parameters
----------
assertion
An assertion attached to a model.

Returns
-------
The operands of the assertion, in order.
"""
if hasattr(assertion, "assertion_1"):
return [assertion.assertion_1, assertion.assertion_2]
if hasattr(assertion, "_left"):
return [assertion._left, assertion._right]
return []


class Identifier:
def __init__(self, obj):
"""
Expand Down Expand Up @@ -131,6 +156,7 @@ def _add_value_to_hash_list(self, value):

d = {k: v for k, v in d.items() if k not in excluded_fields}
self.add_value_to_hash_list(d)
self._add_assertions_to_hash_list(value)
elif isinstance(value, dict):
for key, value in value.items():
key = str(key)
Expand All @@ -150,6 +176,68 @@ def _add_value_to_hash_list(self, value):
for value in value:
self.add_value_to_hash_list(value)

def _add_assertions_to_hash_list(self, model):
"""
Add the assertions attached to a model to the hash_list.

Assertions live in the underscore prefixed `_assertions` attribute, which the
attribute walk above skips. Without this a model carrying an ordering assertion
hashes identically to the same model without it, so an ordered fit is written to
the unordered fit's output directory and loads its completed result instead of
running.

Nothing at all is added for a model with no assertions, so the identifier of
every model which does not use them is unchanged.

Parameters
----------
model
An object which may be an `AbstractPriorModel` carrying assertions.
"""
assertions = getattr(model, "_assertions", None)
if not assertions:
return

self.hash_list.append("assertions")

prior_paths = {
id(prior): ".".join(path) for path, prior in model.path_priors_tuples
}

for assertion in assertions:
self._add_assertion_to_hash_list(assertion, prior_paths)

def _add_assertion_to_hash_list(self, assertion, prior_paths):
"""
Add a single assertion to the hash_list as its class name followed by its
operands in order, so that `a < b` and `b < a` hash differently.

An operand which is a prior of the model is identified by its path (e.g.
"gaussian.sigma") rather than by its value, because two priors with identical
limits hash identically and a value based hash could not tell the two directions
apart. An operand which is itself compound (a chained assertion, or arithmetic on
priors) is recursed into for the same reason: its own operands are underscore
prefixed and would otherwise be skipped.

Parameters
----------
assertion
An assertion attached to a model.
prior_paths
A map from the id of each prior in the model to its path in that model.
"""
from autofit.mapper.prior.arithmetic.compound import Compound

self.hash_list.append(type(assertion).__name__)

for operand in _assertion_operands(assertion):
if id(operand) in prior_paths:
self.hash_list.append(prior_paths[id(operand)])
elif isinstance(operand, Compound):
self._add_assertion_to_hash_list(operand, prior_paths)
else:
self.add_value_to_hash_list(operand)

def add_value_to_hash_list(self, value):
if isinstance(value, property):
return
Expand Down
6 changes: 6 additions & 0 deletions autofit/mapper/prior_model/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -627,6 +627,12 @@ def add_assertion(self, assertion, name=""):
model checks its own as its instance is built, JAX because `gathered_assertions` collects
them from the whole tree.

Assertions are part of the model's identifier
(:class:`~autofit.mapper.identifier.Identifier`), so a model with an assertion is written
to a different output directory than the same model without it and does not resume its
result. The identifier records the assertion's type and the paths of its operands, not the
``name``.

Parameters
----------
assertion
Expand Down
115 changes: 115 additions & 0 deletions test_autofit/database/identifier/test_identifiers.py
Original file line number Diff line number Diff line change
Expand Up @@ -516,3 +516,118 @@ def test_drawer_identifier_ignores_clipper():
assert Identifier(af.Drawer(clipper=af.ClipperPriorBox())) == Identifier(
af.Drawer()
)


def _gaussian_with_explicit_priors():
"""
A Gaussian whose priors are all given explicitly, so that its identifier does not
move when the test configuration's default priors are edited.
"""
return af.Model(
af.ex.Gaussian,
centre=af.UniformPrior(lower_limit=0.0, upper_limit=1.0),
normalization=af.UniformPrior(lower_limit=0.0, upper_limit=1.0),
sigma=af.UniformPrior(lower_limit=0.0, upper_limit=1.0),
)


def test_assertion_free_model_identifier_unchanged():
"""
Tripwire: hashing assertions must not re-key the models which carry none. These are
the identifiers captured from `main` before assertions entered the identifier, and a
change here orphans every result on disk.
"""
assert (
str(Identifier(_gaussian_with_explicit_priors()))
== "9929b2be4248f0d116f5c1c034bda870"
)
assert (
str(Identifier(af.Collection(g=_gaussian_with_explicit_priors())))
== "5b45f48f8ab1205471ce531904ace327"
)


def _asserted_collection(reverse=False):
a = af.Model(af.ex.Gaussian)
b = af.Model(af.ex.Gaussian)
collection = af.Collection(a=a, b=b)
if reverse:
collection.add_assertion(b.sigma < a.sigma)
else:
collection.add_assertion(a.sigma < b.sigma)
return collection


def test_assertion_changes_identifier():
"""
Without this a model ordered by an assertion targets the output directory of the
unordered model and loads its completed result instead of running.
"""
unordered = af.Collection(a=af.Model(af.ex.Gaussian), b=af.Model(af.ex.Gaussian))
assert Identifier(_asserted_collection()) != Identifier(unordered)


def test_assertion_direction_changes_identifier():
assert Identifier(_asserted_collection()) != Identifier(
_asserted_collection(reverse=True)
)


def test_assertion_identifier_is_deterministic():
assert Identifier(_asserted_collection()) == Identifier(_asserted_collection())


def test_number_of_assertions_changes_identifier():
a = af.Model(af.ex.Gaussian)
b = af.Model(af.ex.Gaussian)
collection = af.Collection(a=a, b=b)
collection.add_assertion(a.sigma < b.sigma)
one = str(Identifier(collection))

collection.add_assertion(a.centre < b.centre)
assert str(Identifier(collection)) != one


def test_assertion_on_child_changes_collection_identifier():
gaussian = af.Model(af.ex.Gaussian)
gaussian.add_assertion(gaussian.centre < gaussian.sigma)

assert Identifier(af.Collection(gaussian=gaussian)) != Identifier(
af.Collection(gaussian=af.Model(af.ex.Gaussian))
)


def test_compound_assertion_changes_identifier():
"""
A chained assertion is a `CompoundAssertion`, whose operands are themselves
assertions held in public attributes, and an arithmetic operand is a `CompoundPrior`
holding its sides in underscore prefixed attributes. Both must reach the hash.
"""
a = af.Model(af.ex.Gaussian)
b = af.Model(af.ex.Gaussian)
chained = af.Collection(a=a, b=b)
chained.add_assertion((a.sigma < b.sigma) < b.centre)

c = af.Model(af.ex.Gaussian)
d = af.Model(af.ex.Gaussian)
arithmetic = af.Collection(a=c, b=d)
arithmetic.add_assertion(c.sigma * 2 < d.sigma)

identifiers = {
str(Identifier(chained)),
str(Identifier(arithmetic)),
str(Identifier(_asserted_collection())),
}
assert len(identifiers) == 3


def test_assertion_name_does_not_change_identifier():
"""
The name is logged when an assertion is violated and cannot change the fit.
"""
a = af.Model(af.ex.Gaussian)
b = af.Model(af.ex.Gaussian)
collection = af.Collection(a=a, b=b)
collection.add_assertion(a.sigma < b.sigma, name="ordered")

assert Identifier(collection) == Identifier(_asserted_collection())
Loading