diff --git a/autofit/__init__.py b/autofit/__init__.py index 1f7742b9d..553afd3a7 100644 --- a/autofit/__init__.py +++ b/autofit/__init__.py @@ -121,6 +121,7 @@ from .text import formatter from .text import samples_text from .visualise import VisualiseGraph +from .graph_spec import GraphSpec, graph_spec_from from .interpolator import ( LinearInterpolator, SplineInterpolator, diff --git a/autofit/graph_spec.py b/autofit/graph_spec.py new file mode 100644 index 000000000..654b8976a --- /dev/null +++ b/autofit/graph_spec.py @@ -0,0 +1,2030 @@ +""" +Semantic extraction of a model's structure -- the ``graph_spec``. + +Three layers, one of them here +------------------------------ + +The model-figure machinery is deliberately split into three layers, and this +module is the **first** of them: + +1. **Semantic extraction** (*this module*) -- paths, object identity, parameter + states, relationships and provenance, as plain frozen dataclasses. It knows + nothing about pixels, fonts, colours, grouping-for-looks or detail levels, + and it imports no drawing library (there is a test that asserts importing + this module does not import ``matplotlib``). +2. **Presentation transformation** -- grouping (plates), omission, ordering and + detail level. +3. **Layout and rendering** -- measurement, placement, routing and drawing. + +Nothing below layer 1 may leak upward into it: a renderer consumes a +:class:`GraphSpec`, and a :class:`GraphSpec` never consults a renderer. + +The ordering contract +--------------------- + +**Visual order is the order of** ``model.info``'s **parameter-detail section**, +which is the walk order of:: + + model.path_instance_tuples_for_class(..., ignore_children=True) + +i.e. plain ``__dict__`` (declaration) order, depth first. Children of a +component and rows within a component are emitted in exactly that order, and a +renderer is forbidden from reordering them for packing. + +``model.info`` prints *two* sections in two different orders, so the choice +matters. The other candidate -- the structural summary ``model.parameterization`` +-- is **rejected**: it reorders its lines through ``find_groups(..., limit=0)``, +which collapses sibling paths by suffix and therefore does not preserve +declaration order (this is exactly the defect that floated ``shear`` above +``mass`` in the prototype). + +The ``model.info`` correspondence contract +------------------------------------------ + + Every displayed model element resolves to its corresponding path or grouped + paths in ``model.info``; every omission and every added annotation + (``solved``, ``missing``) is explicit. + +This is *not* a line-for-line claim. :attr:`GraphSpec.path_index` is the +machine-readable half of it: a mapping from a stable element key to the tuple of +``model.info`` paths that element resolves to. An element that is **not** in +``model.info`` -- a ``solved`` row, a ``latent`` row, an assertion -- is recorded +with an empty tuple and carries ``in_model_info=False``. A ``missing`` row *is* +in ``model.info`` (it is the line ``Prior Missing: Enter Manually or Add to +Config``) and so keeps ``in_model_info=True``. + +A **plate** stands for many paths at once, and the figure's partition can be +*finer* than ``model.info``'s grouping: the MGE splits into two 30-member +plates on ``ell_comps`` while ``model.info`` groups the shared ``centre`` of all +sixty as ``0 - 59``. That mapping is recorded rather than hidden -- such an +entry is a ``{"figure": [...], "info": [...]}`` dict of ``"/"``-joined paths +instead of the plain tuple. Both shapes are JSON-stable; see +:func:`_path_index`. + +Properties, not one exclusive kind +---------------------------------- + +A :class:`ParamRow` carries **independent properties** rather than a single +``kind``. A shared prior is still sampled; a tuple is still free. So: + +``sampling`` + ``free`` (a :class:`Prior` leaf), ``fixed`` (a ``Constant`` / plain + ``float`` / plain ``int`` / plain ``tuple`` leaf, or a raw instance), + ``solved`` (a quantity the fit determines that is absent from the model -- + supplied by ``solved_paths=`` or by an analysis' latent catalogue; phase 3 + supplies the domain rules) or ``missing`` (a required configuration value + that is unset, i.e. a ``ConfigException`` sitting in the model tree, which + ``model.info`` prints as *Prior Missing: Enter Manually or Add to Config*). +``sharing`` + ``prior_id`` plus :attr:`ParamRow.occurrences`, *every* path at which the + same ``Prior`` object appears, and :attr:`ParamRow.direct_occurrences`, the + subset of those that do not pass through a relation. + :attr:`ParamRow.shared` is derived from the latter. **Sharing is never a + sampling state.** +``dimensionality`` + ``scalar`` or ``tuple``. A tuple row carries :attr:`ParamRow.components`, + one :class:`ParamRow` per slot (``centre_0``, ``centre_1``, ...), each with + its own sampling status, ``prior_id`` and occurrences -- so a partially + fixed or partially shared tuple is representable as a mixed state rather + than being flattened. A **fixed tuple constant** (a plain ``tuple`` of + floats, e.g. ``centre=(0.1, 0.2)``) is *also* a tuple row, with fixed + components; it is never dropped. +``provenance`` + :class:`Provenance`, see below. + +Provenance kinds +---------------- + +``config-default`` + A prior that came from the prior configuration. **Known gap:** phase 1 + cannot distinguish a user-set prior from the configured default -- nothing + on a ``Prior`` records where it came from -- so *every* prior is emitted as + ``config-default``. ``user-prior`` is reserved for when a config diff (or a + provenance field on ``Prior``) makes the distinction available. +``relation`` + A ``CompoundPrior`` / ``ModifiedPrior``: carries its defining + ``expression`` (e.g. ``"normalization + sigma"``) and its ``operands``. +``latent`` + A row derived from ``type(analysis).Latent.keys(analysis)``. Not part of + the model, hence ``in_model_info=False``. +``user-prior``, ``assertion``, ``hierarchical-draw``, ``observed`` + **Reserved and not emitted by phase 1.** ``assertion`` operands are carried + by :class:`AssertionEdge` (assertions are edges, never rows); + ``hierarchical-draw`` is phase 4 (a ``_HierarchicalFactor`` draw is *not* a + sharing marker); ``observed`` is phase 4/5 (observed data must not be + encoded as ``fixed``). + +Relations and the ``sampling`` axis +----------------------------------- + +The sampling axis is fixed to ``free | fixed | solved | missing`` and a relation +is modelled under *provenance*, so a relation row still needs a sampling status. +The rule: a relation is ``free`` when **any** operand is a free prior (its value +varies during sampling) and ``fixed`` when **every** operand is a constant. + +Sharing and relation operands +----------------------------- + +``all_paths_prior_tuples`` is the sharing detector, and it reports *every* path +at which a prior object sits. A relation's operands are real attributes of the +``CompoundPrior``, so ``m.centre = m.normalization + m.sigma`` puts prior *n* at +both ``('normalization',)`` and ``('centre', 'self')``. Both paths are genuine +and both are kept, in :attr:`ParamRow.occurrences`. + +But a prior used once directly and once *inside a relation* is **related, not +shared**: the second path is the relation's own operand slot, not a second use +of the parameter, and counting it as sharing would draw a sharing edge for every +relation and would split plates that are genuine replicates. So +:attr:`ParamRow.direct_occurrences` drops every occurrence whose path passes +through a relation object, and it -- not ``occurrences`` -- is what +:attr:`ParamRow.shared`, :class:`SharedEdge` emission, +``counts["shared_priors"]`` and rule R2's partition read. The relation itself is +carried as a :class:`RelationEdge`. + +Collapse: rules R1 and R2, and the safety condition +--------------------------------------------------- + +``GraphSpec.from_model(model, collapse=True)`` (the default) collapses repeated +sibling components into **plates**, recursively and bottom-up, over every node's +``children``. Only ``kind="model"`` siblings collapse: a ``Collection`` is a +*frame*, not a repeated component -- but its model children do. Every rule reads +the **uncollapsed** subtrees, because a plate hides the very prior ids and rows +the rules partition on. + +**R1, the soft-plate signature.** A member's signature is the recursive tuple +of its class name and kind, each row's ``(name, sampling, dimensionality, prior +class, provenance kind, prior configuration)`` -- and the same per component for +a tuple row -- and its children's signatures in order. The prior's +configuration comes from its own public attributes (``__identifier_fields__`` +plus its limits), never from ``repr``. Prior **identity**, prior ``_label`` +(which carries a per-instance counter) and constant **values** are all ignored, +so Gaussians differing only in a fixed ``sigma`` are still plate-mates. Equal +signatures make candidate plate-mates. + +**R2, the shared split.** Within a candidate plate, each member is keyed by the +set of prior ids it shares with at least one *other* member. Ids present in +**every** member do not discriminate (the MGE centre) and are dropped from every +key; a prior shared only *inside* one member is not cross-member at all and +never reaches the key -- without that qualifier the group model's eight extra +galaxies fall back to eight boxes. The members are then partitioned by the +remaining key, which is what gives ``Gaussian x30`` + ``Gaussian x30`` rather +than one ``x60``. + +**The safety condition** (Codex review point 7, mandatory). A plate must +preserve **sharing, relations, assertions and exceptions** across its members. +A member also leaves the plate when its relation set (:class:`RelationEdge` s +whose target is inside it), its assertion set (:class:`AssertionEdge` s touching +it) or its external-sharing profile (the prior ids it shares with anything +*outside* the plate, keyed by the row path relative to the member) differs from +the others'. Relations and assertions are keyed by their footprint *relative to +the member*, so eight galaxies carrying the same relation stay together while +one carrying it alone does not. Exceptions -- the ``missing`` state -- are +already carried by R1, which compares every row's ``sampling``. A member that +leaves is emitted as its own node, in declaration order. + +A plate of two or more members becomes **one** :class:`ComponentNode` -- the +first member, rows and children -- carrying a :class:`PlateInfo`. Its +``representative_key`` comes from ``find_groups`` over the member paths, so it +reads exactly as ``model.info`` prints it (``"0 - 29"``); the collapse never +invents a second notion of sameness. Nothing depends on set iteration order: +every grouping is keyed by declaration order, so the output is byte-stable. + +``counts`` reconcile both trees: ``components`` after collapse, +``components_raw`` before, ``plates`` how many of the former stand for more than +one of the latter. The row-derived counts (``fixed_leaf_slots``, ``missing``) +are always of the **uncollapsed** tree -- collapsing must never make a fixed +value look absent from the model. + +Traps this module already handles +--------------------------------- + +* ``TuplePrior`` is **not** an ``AbstractPriorModel``: a walk over + ``direct_prior_tuples`` + ``direct_prior_model_tuples`` silently loses every + tuple parameter. Tuple priors are extracted explicitly. +* ``CompoundPrior`` / ``ModifiedPrior`` / ``ComparisonAssertion`` **are** + ``AbstractPriorModel`` s with ``cls = float``, so they masquerade as + components. They are filtered out of the component walk. +* ``repr()`` of a ``CompoundPrior`` subclass without ``__str__`` recurses + forever (``compound.py``). **Nothing here ever calls ``str()`` or ``repr()`` + on a compound prior or an assertion** -- expressions are built from a symbol + table. +* ``Model(int)`` / ``Model(float)`` wrappers (e.g. ``Delaunay.pixels``) are rows + on their owner, never components (rule R7). +* ``gathered_assertions()`` is a **method**; ``assertions`` is a property that + only sees the model's own list. +* ``obj_id`` is the ``ModelObject`` id counter, not ``id(obj)``: a memory + address is not stable across processes and would break the determinism + contract. + +Entry points +------------ + +``GraphSpec.from_model(model, analysis=None, collapse=True, solved_paths=())`` +and the module-level ``graph_spec_from(model, **kwargs)``. ``collapse=False`` +returns the uncollapsed tree -- the tree the construct catalogue is asserted +against; ``collapse=True`` (the default) applies :func:`_collapse_siblings`. +""" + +from dataclasses import dataclass, field, replace +from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple + +from autonerves.exc import ConfigException + +from autofit.mapper.prior.abstract import Prior +from autofit.mapper.prior.arithmetic.assertion import ( + ComparisonAssertion, + CompoundAssertion, + GreaterThanLessThanAssertion, + GreaterThanLessThanEqualAssertion, +) +from autofit.mapper.prior.arithmetic.compound import ( + AbsolutePrior, + CompoundPrior, + DivisionPrior, + FloorDivPrior, + Log, + Log10, + ModPrior, + ModifiedPrior, + MultiplePrior, + NegativePrior, + PowerPrior, + SumPrior, +) +from autofit.mapper.prior.constant import Constant +from autofit.mapper.prior.tuple_prior import TuplePrior +from autofit.mapper.prior_model.abstract import AbstractPriorModel +from autofit.mapper.prior_model.collection import Collection +from autofit.mapper.prior_model.prior_model import Model +from autofit.mapper.prior_model.representative import ( + find_groups, + integers_representative_key, +) + +__all__ = [ + "Path", + "Provenance", + "ParamRow", + "PlateInfo", + "ComponentNode", + "SharedEdge", + "RelationEdge", + "AssertionEdge", + "GraphSpec", + "graph_spec_from", +] + +Path = Tuple[str, ...] + +#: Attribute names that are never parameter slots. +_SKIP_ATTRIBUTES = frozenset({"id", "item_number", "cls"}) + +#: Per-class extra skips, matched anywhere in a component's MRO by class name +#: (so no import of the ``graphical`` layer is needed here). ``Array`` carries +#: ``shape`` / ``indices`` as bookkeeping, and ``GlobalPriorModel`` carries the +#: declarative factor graph it was built from; none of the three is a slot. +_SKIP_BY_CLASS_NAME = { + "Array": frozenset({"shape", "indices"}), + "GlobalPriorModel": frozenset({"factor"}), +} + +#: Binary compound priors, mapped to their infix symbol. +_BINARY_SYMBOLS = { + SumPrior: "+", + MultiplePrior: "*", + DivisionPrior: "/", + FloorDivPrior: "//", + ModPrior: "%", + PowerPrior: "**", +} + +#: Unary modified priors, mapped to a format template. +_UNARY_TEMPLATES = { + NegativePrior: "-({})", + AbsolutePrior: "abs({})", + Log: "log({})", + Log10: "log10({})", +} + +#: Assertion classes, mapped to the operator they assert. +_ASSERTION_OPERATORS = { + GreaterThanLessThanAssertion: "<", + GreaterThanLessThanEqualAssertion: "<=", + CompoundAssertion: "and", +} + +_RELATION_CLASSES = (CompoundPrior, ModifiedPrior) +_NOT_A_COMPONENT = ( + CompoundPrior, + ModifiedPrior, + ComparisonAssertion, + CompoundAssertion, +) + + +# ---------------------------------------------------------------------------- +# data model +# ---------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class Provenance: + """ + Where a parameter slot's value came from. + + Parameters + ---------- + kind + One of ``config-default``, ``user-prior``, ``relation``, ``assertion``, + ``hierarchical-draw``, ``observed``, ``latent``. Phase 1 emits only + ``config-default``, ``relation`` and ``latent``; the rest are reserved + (see the module docstring). + expression + For ``relation``, the defining expression, e.g. ``"sigma * 2.0"``. + operands + For ``relation``, the operand names -- a dotted ``model.info`` path when + the operand is a prior found in the model, otherwise the attribute name + the compound prior recorded for it, otherwise the rendered constant. + """ + + kind: str + expression: Optional[str] = None + operands: Tuple[str, ...] = () + + def to_dict(self) -> dict: + return { + "kind": self.kind, + "expression": self.expression, + "operands": list(self.operands), + } + + +@dataclass(frozen=True) +class ParamRow: + """ + One parameter slot. + + See the module docstring for the property axes. ``occurrences`` is every + path at which this row's ``Prior`` object appears; ``shared`` is derived from + it and is *never* a sampling state. + """ + + name: str + path: Path + sampling: str + prior_id: Optional[int] = None + occurrences: Tuple[Path, ...] = () + direct_occurrences: Tuple[Path, ...] = () + dimensionality: str = "scalar" + components: Tuple["ParamRow", ...] = () + provenance: Provenance = field(default_factory=lambda: Provenance("config-default")) + value: Any = None + prior_cls_name: Optional[str] = None + in_model_info: bool = True + is_instance: bool = False + + @property + def shared(self) -> bool: + """ + Whether this row's prior object appears at more than one **direct** path. + + Derived from :attr:`direct_occurrences`, not :attr:`occurrences`: a prior + used once directly and once as the operand of a relation is *related*, + not shared (see the module docstring, "Sharing and relation operands"). + """ + return len(self.direct_occurrences) > 1 + + def to_dict(self) -> dict: + return { + "name": self.name, + "path": list(self.path), + "sampling": self.sampling, + "prior_id": self.prior_id, + "occurrences": [list(path) for path in self.occurrences], + "direct_occurrences": [list(path) for path in self.direct_occurrences], + "shared": self.shared, + "dimensionality": self.dimensionality, + "components": [component.to_dict() for component in self.components], + "provenance": self.provenance.to_dict(), + "value": self.value, + "prior_cls_name": self.prior_cls_name, + "in_model_info": self.in_model_info, + "is_instance": self.is_instance, + } + + +@dataclass(frozen=True) +class PlateInfo: + """ + What a collapsed plate repeats. + + Parameters + ---------- + count + How many components the plate stands for. + member_paths + The path of every member, in declaration order. The first is the + representative whose rows and children the plate's + :class:`ComponentNode` carries. + representative_key + The key ``find_groups`` puts in place of the member index, so it reads + exactly as ``model.info`` prints it (``"0 - 29"``). + repeats + One line naming what is repeated, built mechanically from the + representative's own rows, e.g. ``"Gaussian with priors centre + \u21c4 shared, sigma fixed (varies by member)"``. + shared_in_all + Prior **ids** carried by *every* member (these do not discriminate, so + they never split a plate -- the MGE centre). Ascending. + varies_by_member + Dotted row paths, relative to a member, whose fixed value differs + between members. + """ + + count: int + member_paths: Tuple[Path, ...] = () + representative_key: Optional[str] = None + repeats: Tuple[str, ...] = () + shared_in_all: Tuple[int, ...] = () + varies_by_member: Tuple[str, ...] = () + + def to_dict(self) -> dict: + return { + "count": self.count, + "member_paths": [list(path) for path in self.member_paths], + "representative_key": self.representative_key, + "repeats": list(self.repeats), + "shared_in_all": list(self.shared_in_all), + "varies_by_member": list(self.varies_by_member), + } + + +@dataclass(frozen=True) +class ComponentNode: + """ + One ``Model`` / ``Collection`` / ``GlobalPriorModel`` in the nesting tree. + + ``name`` is the exact attribute spelling, or the list index as a string + (``"0"``, ``"1"``) for a list-built ``Collection``. The root node has + ``path=()`` and ``name="model"``. ``obj_id`` is the ``ModelObject`` id + counter: the same ``obj_id`` at several paths is how a component shared + across datasets is detected. + """ + + path: Path + name: str + cls_name: str + kind: str + obj_id: Optional[int] + rows: Tuple[ParamRow, ...] = () + children: Tuple["ComponentNode", ...] = () + plate: Optional[PlateInfo] = None + + def to_dict(self) -> dict: + return { + "path": list(self.path), + "name": self.name, + "cls_name": self.cls_name, + "kind": self.kind, + "obj_id": self.obj_id, + "rows": [row.to_dict() for row in self.rows], + "children": [child.to_dict() for child in self.children], + "plate": self.plate.to_dict() if self.plate is not None else None, + } + + +@dataclass(frozen=True) +class SharedEdge: + """One ``Prior`` object appearing at more than one path.""" + + prior_id: int + occurrences: Tuple[Path, ...] + + def to_dict(self) -> dict: + return { + "prior_id": self.prior_id, + "occurrences": [list(path) for path in self.occurrences], + } + + +@dataclass(frozen=True) +class RelationEdge: + """A ``CompoundPrior`` / ``ModifiedPrior`` and the operands it is built from.""" + + target_path: Path + expression: str + operand_paths: Tuple[Path, ...] = () + prior_id: Optional[int] = None + + def to_dict(self) -> dict: + return { + "target_path": list(self.target_path), + "expression": self.expression, + "operand_paths": [list(path) for path in self.operand_paths], + "prior_id": self.prior_id, + } + + +@dataclass(frozen=True) +class AssertionEdge: + """ + An assertion attached anywhere in the model tree. + + Assertions are **not** part of the tree and are **not** in ``model.info``; + they are edges only. + """ + + op: str + left: str + right: str + name: Optional[str] = None + + def to_dict(self) -> dict: + return { + "op": self.op, + "left": self.left, + "right": self.right, + "name": self.name, + } + + +# ---------------------------------------------------------------------------- +# helpers +# ---------------------------------------------------------------------------- + + +def _as_path(path: Iterable) -> Path: + """Normalise a model path to a tuple of strings (list indices become ``"0"``).""" + return tuple(str(step) for step in path) + + +def _dotted(path: Path) -> str: + return ".".join(path) + + +def _key(path: Path) -> str: + """The stable element key used by :attr:`GraphSpec.path_index`.""" + return "/".join(path) + + +def _numeric(value) -> Optional[float]: + """The float behind a ``Constant`` / ``float`` / ``int``, else ``None``.""" + if isinstance(value, Constant): + return float(value.value) + if isinstance(value, bool): + return None + if isinstance(value, (int, float)): + return float(value) + return None + + +def _is_dropped_model(obj) -> bool: + """ + Rule R7 -- ``Model(int)`` / ``Model(float)`` is a row on its owner, never a + component of its own. + """ + return isinstance(obj, Model) and getattr(obj, "cls", None) in (int, float) + + +def _cls_name(obj) -> str: + """The displayed class name of a component.""" + cls = getattr(obj, "cls", None) + if cls is not None: + # `Model(function)` keeps the function itself in `cls`, and a function + # has a `__name__` just as a class does. + name = getattr(cls, "__name__", None) + if name is not None: + return name + return type(obj).__name__ + + +def _kind(obj) -> str: + """``model`` / ``collection`` / ``global``.""" + if type(obj).__name__ == "GlobalPriorModel": + return "global" + if isinstance(obj, Collection): + return "collection" + return "model" + + +def _skipped_attributes(obj) -> frozenset: + """Attribute names that are not parameter slots on this component.""" + skipped = set(_SKIP_ATTRIBUTES) + for cls in type(obj).__mro__: + skipped |= _SKIP_BY_CLASS_NAME.get(cls.__name__, frozenset()) + # Honour `__exclude_identifier_fields__` exactly as `AbstractPriorModel.info` + # does: attributes a class has already declared "not part of the model's + # identity" do not leak into the figure either. + skipped |= set(getattr(type(obj), "__exclude_identifier_fields__", ()) or ()) + names = getattr(type(obj), "_cached_property_names", None) + if callable(names): + try: + skipped |= set(names()) + except Exception: # pragma: no cover - defensive + pass + return frozenset(skipped) + + +def _attribute_items(obj) -> List[Tuple[str, Any]]: + """ + The component's direct attributes, in declaration (``__dict__``) order. + + This is the union of ``direct_prior_tuples``, ``direct_tuple_priors`` / + ``tuple_prior_tuples`` and ``direct_instance_tuples`` -- read straight off + ``__dict__`` so that (a) declaration order is preserved, (b) the known + double-count of ``Constant`` s in ``direct_instance_tuples`` (a ``Constant`` + is a ``float``, so it is returned by both halves of that property) cannot + happen, since each attribute name is visited exactly once, and (c) raw + instance leaves -- which no ``direct_*`` property reports -- are seen. + """ + skipped = _skipped_attributes(obj) + return [ + (name, value) + for name, value in obj.__dict__.items() + if not name.startswith("_") and name not in skipped + ] + + +# ---------------------------------------------------------------------------- +# relation expressions +# ---------------------------------------------------------------------------- + + +def _operand_name(value, model, fallback: Optional[str]) -> str: + """ + Render one operand of a compound prior. + + A prior that is in the model renders as its dotted path; any other prior + renders as the attribute name the compound recorded for it; a constant + renders as its float. ``str()`` / ``repr()`` is never called on a compound + prior or an assertion. + """ + if isinstance(value, Prior): + path = model.path_for_prior(value) + if path is not None: + return _dotted(_as_path(path)) + return fallback or f"prior_{value.id}" + number = _numeric(value) + if number is not None: + return repr(number) + if fallback: + return fallback + return type(value).__name__ + + +def _expression(obj, model, top: bool = True) -> str: + """ + The defining expression of a compound / modified prior, built from a symbol + table. Never calls ``str()``/``repr()`` on a compound (which recurses + forever, ``compound.py``). + """ + for cls, symbol in _BINARY_SYMBOLS.items(): + if isinstance(obj, cls): + left = _render_operand(obj._left, model, getattr(obj, "_left_name", None)) + right = _render_operand( + obj._right, model, getattr(obj, "_right_name", None) + ) + rendered = f"{left} {symbol} {right}" + return rendered if top else f"({rendered})" + for cls, template in _UNARY_TEMPLATES.items(): + if isinstance(obj, cls): + inner = _render_operand( + getattr(obj, obj._prior_name, None), + model, + getattr(obj, "_prior_name", None), + ) + return template.format(inner) + if isinstance(obj, ComparisonAssertion): + operator = _ASSERTION_OPERATORS.get(type(obj), type(obj).__name__) + left = _render_operand(obj._left, model, getattr(obj, "_left_name", None)) + right = _render_operand(obj._right, model, getattr(obj, "_right_name", None)) + return f"{left} {operator} {right}" + if isinstance(obj, CompoundAssertion): + left = _expression(obj.assertion_1, model, top=False) + right = _expression(obj.assertion_2, model, top=False) + return f"{left} and {right}" + # An unrecognised compound subclass: name it rather than risk `repr`. + return type(obj).__name__ + + +def _render_operand(value, model, fallback: Optional[str]) -> str: + if isinstance(value, _RELATION_CLASSES + (ComparisonAssertion, CompoundAssertion)): + return _expression(value, model, top=False) + return _operand_name(value, model, fallback) + + +def _operand_pairs(obj, model) -> List[Tuple[str, Any]]: + """ + ``(rendered name, operand)`` for every leaf operand of a compound, left to + right, recursing through nested compounds. + """ + pairs: List[Tuple[str, Any]] = [] + + def _walk(node, fallback): + if isinstance(node, _RELATION_CLASSES): + if isinstance(node, ModifiedPrior): + _walk( + getattr(node, node._prior_name, None), + getattr(node, "_prior_name", None), + ) + return + _walk(node._left, getattr(node, "_left_name", None)) + _walk(node._right, getattr(node, "_right_name", None)) + return + pairs.append((_operand_name(node, model, fallback), node)) + + _walk(obj, None) + return pairs + + +def _relation_provenance(obj, model) -> Tuple[Provenance, Tuple[Path, ...], str]: + """The provenance, prior operand paths and sampling status of a relation.""" + expression = _expression(obj, model) + pairs = _operand_pairs(obj, model) + + operands: List[str] = [] + operand_paths: List[Path] = [] + has_free = False + for name, operand in pairs: + if name not in operands: + operands.append(name) + if isinstance(operand, Prior): + has_free = True + path = model.path_for_prior(operand) + if path is not None: + path = _as_path(path) + if path not in operand_paths: + operand_paths.append(path) + + sampling = "free" if has_free else "fixed" + return ( + Provenance("relation", expression, tuple(operands)), + tuple(operand_paths), + sampling, + ) + + +# ---------------------------------------------------------------------------- +# extraction +# ---------------------------------------------------------------------------- + + +class _Extractor: + def __init__(self, model, analysis=None, solved_paths: Sequence = ()): + self.model = model + self.analysis = analysis + self.solved_paths = { + _as_path(path.split(".")) if isinstance(path, str) else _as_path(path) + for path in (solved_paths or ()) + } + + #: Every path a prior sits at, and the subset of those that do not pass + #: through a relation object (see the module docstring). + self.occurrences: Dict[int, Tuple[Path, ...]] = {} + self.direct_occurrences: Dict[int, Tuple[Path, ...]] = {} + #: ``prior id -> the prior's configuration arguments``, for rule R1. + self.prior_config: Dict[int, Tuple] = {} + + self.relation_paths = frozenset( + _as_path(path) + for path, _ in model.path_instance_tuples_for_class(_RELATION_CLASSES) + ) + for paths, prior in model.all_paths_prior_tuples: + paths = tuple(_as_path(path) for path in paths) + self.occurrences[prior.id] = paths + self.direct_occurrences[prior.id] = tuple( + path + for path in paths + if not _passes_through_relation(path, self.relation_paths) + ) + self.prior_config[prior.id] = _prior_configuration(prior) + + self._known_component_paths = set() + + # -- components --------------------------------------------------------- + + def _component_paths(self) -> List[Path]: + """ + The component walk, in its returned order, with the root included and + the non-components filtered out. + """ + raw = self.model.path_instance_tuples_for_class( + (Model, Collection), ignore_children=False + ) + entries: List[Tuple[Path, Any]] = [(_as_path(path), obj) for path, obj in raw] + if not entries or entries[0][0] != (): + entries.insert(0, ((), self.model)) + + kept: List[Tuple[Path, Any]] = [] + dropped: List[Path] = [] + for path, obj in entries: + if any(path[: len(prefix)] == prefix for prefix in dropped): + dropped.append(path) + continue + if path != () and isinstance(obj, _NOT_A_COMPONENT): + dropped.append(path) + continue + if path != () and _is_dropped_model(obj): + dropped.append(path) + continue + kept.append((path, obj)) + self._known_component_paths = {path for path, _ in kept} + return kept + + def build_root(self) -> ComponentNode: + entries = self._component_paths() + by_path = {path: obj for path, obj in entries} + children_of: Dict[Path, List[Path]] = {path: [] for path, _ in entries} + for path, _ in entries: + if path == (): + continue + for length in range(len(path) - 1, -1, -1): + parent = path[:length] + if parent in children_of: + children_of[parent].append(path) + break + return self._node( + (), by_path[()], "model", by_path=by_path, children_of=children_of + ) + + def _node(self, path: Path, obj, name: str, by_path, children_of) -> ComponentNode: + rows: List[ParamRow] = [] + children: List[ComponentNode] = [] + child_paths = list(children_of.get(path, ())) + + for attribute, value in _attribute_items(obj): + child_path = path + (attribute,) + if child_path in by_path: + children.append( + self._node( + child_path, + by_path[child_path], + attribute, + by_path=by_path, + children_of=children_of, + ) + ) + if child_path in child_paths: + child_paths.remove(child_path) + continue + row = self._row(attribute, child_path, value) + if row is not None: + rows.append(row) + continue + if isinstance(value, AbstractPriorModel): + # An `AbstractPriorModel` that the mandated `(Model, Collection)` + # walk cannot see -- an `af.Array`, say -- is promoted to a + # component here rather than dropped, so no parameter is lost. + promoted = { + p: o for p, o in self._promoted_entries(child_path, value).items() + } + by_path.update(promoted) + sub_children: Dict[Path, List[Path]] = {p: [] for p in promoted} + for p in promoted: + if p == child_path: + continue + for length in range(len(p) - 1, -1, -1): + parent = p[:length] + if parent in sub_children: + sub_children[parent].append(p) + break + merged = dict(children_of) + merged.update(sub_children) + children.append( + self._node( + child_path, + value, + attribute, + by_path=by_path, + children_of=merged, + ) + ) + + # Any component the walk found under this node whose owning attribute + # was not visible in `__dict__` (a list entry, say) still belongs here. + for child_path in child_paths: + children.append( + self._node( + child_path, + by_path[child_path], + child_path[-1], + by_path=by_path, + children_of=children_of, + ) + ) + + return ComponentNode( + path=path, + name=name, + cls_name=_cls_name(obj), + kind=_kind(obj), + obj_id=getattr(obj, "id", None), + rows=tuple(rows), + children=tuple(children), + ) + + def _promoted_entries(self, path: Path, obj) -> Dict[Path, Any]: + entries = {path: obj} + for sub_path, sub_obj in obj.path_instance_tuples_for_class( + (Model, Collection), ignore_children=False + ): + sub_path = _as_path(sub_path) + if sub_path == (): + continue + if isinstance(sub_obj, _NOT_A_COMPONENT) or _is_dropped_model(sub_obj): + continue + entries[path + sub_path] = sub_obj + return entries + + # -- rows --------------------------------------------------------------- + + def _occurrences(self, prior) -> Tuple[Path, ...]: + return self.occurrences.get(prior.id, ()) + + def _direct_occurrences(self, prior) -> Tuple[Path, ...]: + return self.direct_occurrences.get(prior.id, ()) + + def _solved(self, row: ParamRow) -> ParamRow: + if row.path in self.solved_paths: + return replace(row, sampling="solved", in_model_info=False) + return row + + def _row(self, name: str, path: Path, value) -> Optional[ParamRow]: + """ + A row for a direct attribute, or ``None`` when the attribute is not a + parameter slot (i.e. it is a child component). + """ + if isinstance(value, Prior): + return self._solved( + ParamRow( + name=name, + path=path, + sampling="free", + prior_id=value.id, + occurrences=self._occurrences(value), + direct_occurrences=self._direct_occurrences(value), + prior_cls_name=type(value).__name__, + ) + ) + + if isinstance(value, TuplePrior): + components = tuple( + self._tuple_component(path + (sub_name,), sub_name, sub_value) + for sub_name, sub_value in sorted( + ( + (k, v) + for k, v in value.__dict__.items() + if not k.startswith("_") and k != "id" + ), + key=lambda item: item[0], + ) + ) + return self._solved( + ParamRow( + name=name, + path=path, + sampling=_tuple_sampling(components), + dimensionality="tuple", + components=components, + prior_cls_name="TuplePrior", + ) + ) + + if isinstance(value, _RELATION_CLASSES): + provenance, _, sampling = _relation_provenance(value, self.model) + return self._solved( + ParamRow( + name=name, + path=path, + sampling=sampling, + provenance=provenance, + prior_cls_name=type(value).__name__, + ) + ) + + if isinstance(value, ConfigException): + # Exactly what `model.info` prints as + # "Prior Missing: Enter Manually or Add to Config". + return ParamRow( + name=name, + path=path, + sampling="missing", + prior_cls_name="ConfigException", + ) + + if isinstance(value, tuple): + components = tuple( + ParamRow( + name=f"{name}_{index}", + path=path + (f"{name}_{index}",), + sampling="fixed", + value=_numeric(item), + prior_cls_name=type(item).__name__, + ) + for index, item in enumerate(value) + ) + return self._solved( + ParamRow( + name=name, + path=path, + sampling="fixed", + dimensionality="tuple", + components=components, + value=[_numeric(item) for item in value], + prior_cls_name="tuple", + ) + ) + + number = _numeric(value) + if number is not None: + return self._solved( + ParamRow( + name=name, + path=path, + sampling="fixed", + value=number, + prior_cls_name=type(value).__name__, + ) + ) + + if _is_dropped_model(value): + return self._solved(self._int_model_row(name, path, value)) + + if isinstance(value, AbstractPriorModel): + return None + + if value is None: + # An unset optional attribute (e.g. ``Basis(regularization=None)``). + # ``model.info`` prints nothing for it, so it is not a slot at all -- + # emitting a row would violate the correspondence contract. + return None + + # A raw Python object assigned into a Collection/Model. + return self._solved( + ParamRow( + name=name, + path=path, + sampling="fixed", + prior_cls_name=type(value).__name__, + is_instance=True, + ) + ) + + def _tuple_component(self, path: Path, name: str, value) -> ParamRow: + if isinstance(value, Prior): + return ParamRow( + name=name, + path=path, + sampling="free", + prior_id=value.id, + occurrences=self._occurrences(value), + direct_occurrences=self._direct_occurrences(value), + prior_cls_name=type(value).__name__, + ) + if isinstance(value, _RELATION_CLASSES): + provenance, _, sampling = _relation_provenance(value, self.model) + return ParamRow( + name=name, + path=path, + sampling=sampling, + provenance=provenance, + prior_cls_name=type(value).__name__, + ) + if isinstance(value, ConfigException): + return ParamRow( + name=name, + path=path, + sampling="missing", + prior_cls_name="ConfigException", + ) + return ParamRow( + name=name, + path=path, + sampling="fixed", + value=_numeric(value), + prior_cls_name=type(value).__name__, + ) + + def _int_model_row(self, name: str, path: Path, value) -> ParamRow: + """ + Rule R7 -- an ``af.Model(int)`` / ``af.Model(float)`` wrapper is a row on + its owner. Its single prior, constant or ``ConfigException``, if it has + one, *is* that row; a wrapper with no leaf at all carries no value and is + absent from ``model.info``, so it is recorded with ``value=None`` and + ``in_model_info=False`` rather than dropped. + """ + cls_name = _cls_name(value) + for attribute, leaf in _attribute_items(value): + if isinstance(leaf, Prior): + return ParamRow( + name=name, + path=path, + sampling="free", + prior_id=leaf.id, + occurrences=self._occurrences(leaf), + direct_occurrences=self._direct_occurrences(leaf), + prior_cls_name=type(leaf).__name__, + ) + if isinstance(leaf, ConfigException): + return ParamRow( + name=name, + path=path, + sampling="missing", + prior_cls_name="ConfigException", + ) + number = _numeric(leaf) + if number is not None: + return ParamRow( + name=name, + path=path, + sampling="fixed", + value=number, + prior_cls_name=cls_name, + ) + return ParamRow( + name=name, + path=path, + sampling="fixed", + value=None, + prior_cls_name=cls_name, + in_model_info=False, + ) + + # -- edges -------------------------------------------------------------- + + def shared_edges(self) -> Tuple[SharedEdge, ...]: + """ + One edge per prior that sits at more than one **direct** path. A path + that passes through a relation object is an operand of that relation, + not a second use of the prior, and is carried by a + :class:`RelationEdge` instead (module docstring, "Sharing and relation + operands"). + """ + edges = [] + for _, prior in self.model.all_paths_prior_tuples: + paths = self.direct_occurrences.get(prior.id, ()) + if len(paths) > 1: + edges.append(SharedEdge(prior.id, paths)) + return tuple(edges) + + def relation_edges(self) -> Tuple[RelationEdge, ...]: + edges = [] + for path, obj in self.model.path_instance_tuples_for_class(_RELATION_CLASSES): + provenance, operand_paths, _ = _relation_provenance(obj, self.model) + edges.append( + RelationEdge( + target_path=_as_path(path), + expression=provenance.expression or "", + operand_paths=operand_paths, + prior_id=None, + ) + ) + return tuple(edges) + + def assertion_edges(self) -> Tuple[AssertionEdge, ...]: + edges = [] + for assertion in self.model.gathered_assertions(): + if assertion is True or assertion is False: + continue + operator = _ASSERTION_OPERATORS.get(type(assertion)) + if operator is None: + for cls, symbol in _ASSERTION_OPERATORS.items(): + if isinstance(assertion, cls): + operator = symbol + break + if operator is None: + operator = type(assertion).__name__ + if isinstance(assertion, CompoundAssertion): + left = _expression(assertion.assertion_1, self.model, top=False) + right = _expression(assertion.assertion_2, self.model, top=False) + else: + left = _render_operand( + getattr(assertion, "_left", None), + self.model, + getattr(assertion, "_left_name", None), + ) + right = _render_operand( + getattr(assertion, "_right", None), + self.model, + getattr(assertion, "_right_name", None), + ) + edges.append( + AssertionEdge( + op=operator, + left=left, + right=right, + name=getattr(assertion, "_name", "") or None, + ) + ) + return tuple(edges) + + # -- latents ------------------------------------------------------------ + + def latent_keys(self) -> List[str]: + if self.analysis is None: + return [] + latent = getattr(type(self.analysis), "Latent", None) + if latent is None: + return [] + try: + return list(latent.keys(self.analysis)) + except Exception: # pragma: no cover - a broken analysis is not our error + return [] + + def attach_latents(self, root: ComponentNode) -> ComponentNode: + keys = self.latent_keys() + if not keys: + return root + by_path: Dict[Path, List[ParamRow]] = {} + for key in keys: + parts = tuple(key.split(".")) + owner, name = parts[:-1], parts[-1] + by_path.setdefault(owner, []).append( + ParamRow( + name=name, + path=owner + (name,), + sampling="solved", + provenance=Provenance("latent"), + in_model_info=False, + ) + ) + known = _paths_of(root) + + def _attach(node: ComponentNode) -> ComponentNode: + extra = list(by_path.get(node.path, ())) + if node.path == (): + for owner, rows in by_path.items(): + if owner not in known: + extra.extend(rows) + return replace( + node, + rows=node.rows + tuple(extra), + children=tuple(_attach(child) for child in node.children), + ) + + return _attach(root) + + +def _tuple_sampling(components: Tuple[ParamRow, ...]) -> str: + """ + A tuple row's own sampling status: ``free`` if any slot is sampled, else + ``missing`` if any slot is unset, else ``fixed``. The mixed state lives in + the per-slot ``components``. + """ + if any(component.sampling == "free" for component in components): + return "free" + if any(component.sampling == "missing" for component in components): + return "missing" + if any(component.sampling == "solved" for component in components): + return "solved" + return "fixed" + + +def _paths_of(node: ComponentNode) -> set: + paths = {node.path} + for child in node.children: + paths |= _paths_of(child) + return paths + + +# ---------------------------------------------------------------------------- +# collapse -- rules R1 / R2 and the safety condition +# ---------------------------------------------------------------------------- + +#: Prior attributes that are configuration on every prior family, whatever +#: ``__identifier_fields__`` says. ``_label`` (a per-instance counter) and the +#: prior id are deliberately absent: rule R1 ignores both. +_ALWAYS_CONFIGURATION = ("lower_limit", "upper_limit") + + +def _passes_through_relation(path: Path, relation_paths) -> bool: + """Whether any proper prefix of ``path`` is a relation object.""" + return any(path[:length] in relation_paths for length in range(1, len(path))) + + +def _prior_configuration(prior) -> Tuple[Tuple[str, Any], ...]: + """ + A prior's **configuration arguments** -- what rule R1 compares. + + Read from the prior's own public attributes (``__identifier_fields__``, + which is exactly the set autofit already treats as a prior's identity, plus + its limits). Never ``repr``: a compound prior's ``repr`` recurses forever. + """ + names: List[str] = [] + for name in getattr(type(prior), "__identifier_fields__", ()) or (): + if name not in names: + names.append(name) + for name in _ALWAYS_CONFIGURATION: + if name not in names: + names.append(name) + + configuration: List[Tuple[str, Any]] = [] + for name in names: + value = getattr(prior, name, None) + number = _numeric(value) + configuration.append((name, number if number is not None else None)) + return tuple(configuration) + + +def _assertion_prior_ids(assertion) -> frozenset: + """ + The ids of every prior an assertion touches, walked from the symbol table + rather than through ``repr`` (which recurses forever on a compound). + """ + ids = set() + + def _walk(node): + if isinstance(node, Prior): + ids.add(node.id) + return + if isinstance(node, CompoundAssertion): + _walk(node.assertion_1) + _walk(node.assertion_2) + return + if isinstance(node, ModifiedPrior): + _walk(getattr(node, node._prior_name, None)) + return + if isinstance(node, _RELATION_CLASSES + (ComparisonAssertion,)): + _walk(getattr(node, "_left", None)) + _walk(getattr(node, "_right", None)) + return + + _walk(assertion) + return frozenset(ids) + + +class _CollapseContext: + """Everything the collapse rules need that is not on the tree itself.""" + + def __init__(self, extractor: "_Extractor"): + self.direct_occurrences = extractor.direct_occurrences + self.prior_config = extractor.prior_config + self.relations = extractor.relation_edges() + self.assertions = tuple( + _assertion_prior_ids(assertion) + for assertion in extractor.model.gathered_assertions() + if assertion is not True and assertion is not False + ) + + +def _all_rows(node: ComponentNode, base: int = None): + """ + ``(relative dotted path, row)`` for every row in a subtree, tuple slots + included, in visual order. Paths are relative to ``node``. + """ + prefix = len(node.path) if base is None else base + + def _walk(current: ComponentNode): + for row in current.rows: + yield _dotted(row.path[prefix:]), row + for component in row.components: + yield _dotted(component.path[prefix:]), component + for child in current.children: + yield from _walk(child) + + return list(_walk(node)) + + +def _prior_ids_in(node: ComponentNode) -> set: + return {row.prior_id for _, row in _all_rows(node) if row.prior_id is not None} + + +def _row_signature(row: ParamRow, context: _CollapseContext) -> Tuple: + """ + Rule R1's per-row signature: everything but prior **identity**, prior + ``_label`` and constant **values**. + """ + return ( + row.name, + row.sampling, + row.dimensionality, + row.prior_cls_name, + row.provenance.kind, + row.in_model_info, + row.is_instance, + () if row.prior_id is None else context.prior_config.get(row.prior_id, ()), + tuple(_row_signature(component, context) for component in row.components), + ) + + +def _signature(node: ComponentNode, context: _CollapseContext) -> Tuple: + """ + Rule R1's **soft-plate signature**: the class tree and prior configuration, + recursively, ignoring prior identity, prior ``_label`` and constant values. + """ + return ( + node.cls_name, + node.kind, + tuple(_row_signature(row, context) for row in node.rows), + tuple(_signature(child, context) for child in node.children), + ) + + +def _relative(path: Path, member: ComponentNode) -> Optional[Path]: + """``path`` relative to ``member``, or ``None`` when it is outside it.""" + prefix = member.path + if path[: len(prefix)] == prefix: + return path[len(prefix) :] + return None + + +def _safety_profile( + member: ComponentNode, + members: List[ComponentNode], + context: _CollapseContext, +) -> Tuple: + """ + The safety condition (Codex review point 7): a plate must preserve + **sharing, relations, assertions and exceptions** across its members. + + Relations and assertions are keyed by their footprint *relative to the + member*, so eight galaxies carrying the same relation stay together while a + single galaxy that carries one on its own leaves. External sharing is keyed + by the relative row path, so a member that shares a prior with something + outside the plate leaves it. (Exceptions -- the ``missing`` state -- are + already part of the R1 signature, which carries every row's ``sampling``.) + """ + relations = [] + for edge in context.relations: + target = _relative(edge.target_path, member) + if target is None: + continue + operands = [] + for operand in edge.operand_paths: + relative = _relative(operand, member) + operands.append( + relative if relative is not None else ("",) + operand + ) + operands = tuple(operands) + relations.append((target, operands)) + + own_ids = _prior_ids_in(member) + assertions = [] + for prior_ids in context.assertions: + inside = sorted( + relative for relative, row in _all_rows(member) if row.prior_id in prior_ids + ) + if not inside: + continue + assertions.append((tuple(inside), bool(prior_ids - own_ids))) + + member_paths = [other.path for other in members] + external = set() + for relative, row in _all_rows(member): + if row.prior_id is None: + continue + for occurrence in context.direct_occurrences.get(row.prior_id, ()): + if not any(occurrence[: len(path)] == path for path in member_paths): + external.add(relative) + break + + return ( + tuple(sorted(relations)), + tuple(sorted(assertions)), + tuple(sorted(external)), + ) + + +def _shared_split(members: List[ComponentNode]) -> Tuple[List[Tuple], Tuple[int, ...]]: + """ + Rule R2: partition a candidate plate by the **cross-member** priors its + members carry. + + A prior in *every* member does not discriminate (the MGE centre) and is + dropped from every set; a prior shared only *inside* one member is not + cross-member at all and never reaches the partition. + """ + ids_per_member = [_prior_ids_in(member) for member in members] + counts: Dict[int, int] = {} + for ids in ids_per_member: + for prior_id in ids: + counts[prior_id] = counts.get(prior_id, 0) + 1 + + universal = tuple( + sorted( + prior_id + for prior_id, count in counts.items() + if count == len(members) and count > 1 + ) + ) + keys = [ + tuple( + sorted( + prior_id + for prior_id in ids + if counts[prior_id] > 1 and prior_id not in universal + ) + ) + for ids in ids_per_member + ] + return keys, universal + + +def _representative_key(member_paths: List[Path], position: int) -> Optional[str]: + """ + The key ``find_groups`` puts in place of the member index -- ``"0 - 29"``, + exactly as ``model.info`` prints it. + """ + grouped = find_groups([(path, 0) for path in member_paths], limit=0) + if len(grouped) != 1: # pragma: no cover - defensive + return None + path = grouped[0][0] + if position >= len(path): # pragma: no cover - defensive + return None + return str(path[position]) + + +def _varies_by_member(members: List[ComponentNode]) -> Tuple[str, ...]: + """ + Dotted row paths, relative to a member, whose **fixed value** differs + between members -- the MGE's per-Gaussian ``sigma``, the group model's + per-galaxy ``mass.centre``. + """ + per_member = [dict(_all_rows(member)) for member in members] + varies: List[str] = [] + for relative, row in _all_rows(members[0]): + if row.dimensionality == "tuple": + values = [ + tuple( + component.value for component in rows.get(relative, row).components + ) + for rows in per_member + ] + else: + values = [rows.get(relative, row).value for rows in per_member] + if any(value != values[0] for value in values[1:]): + varies.append(relative) + # A tuple row that varies already names the tuple; drop its slots. + tuples = { + relative + for relative, row in _all_rows(members[0]) + if row.dimensionality == "tuple" + } + return tuple( + relative + for relative in varies + if not any(relative.startswith(f"{name}.") for name in tuples) + ) + + +def _repeats( + member: ComponentNode, + shared_within: set, + varies: Tuple[str, ...], +) -> Tuple[str, ...]: + """ + One line naming what the plate repeats, built mechanically from the + representative's own rows. + """ + described = [] + for row in member.rows: + name = row.name + prior_ids = {row.prior_id} | { + component.prior_id for component in row.components + } + if prior_ids & shared_within: + described.append(f"{name} \u21c4 shared") + elif row.sampling == "fixed" and name in varies: + described.append(f"{name} fixed (varies by member)") + else: + described.append(f"{name} {row.sampling}") + if not described: + return (f"{member.cls_name}",) + return (f"{member.cls_name} with priors " + ", ".join(described),) + + +def _plate( + members: List[ComponentNode], + representative: ComponentNode, + context: _CollapseContext, +) -> ComponentNode: + """ + One :class:`ComponentNode` standing for every member of a plate. + + ``members`` are the **uncollapsed** member subtrees -- the rules read the + model as declared -- while ``representative`` is the first member as it + comes out of the bottom-up pass, i.e. with its own children already + collapsed. + """ + member_paths = [member.path for member in members] + position = len(representative.path) - 1 + + _, universal = _shared_split(members) + ids_per_member = [_prior_ids_in(member) for member in members] + counts: Dict[int, int] = {} + for ids in ids_per_member: + for prior_id in ids: + counts[prior_id] = counts.get(prior_id, 0) + 1 + shared_within = {prior_id for prior_id, count in counts.items() if count > 1} + + varies = _varies_by_member(members) + return replace( + representative, + plate=PlateInfo( + count=len(members), + member_paths=tuple(member_paths), + representative_key=_representative_key(member_paths, position), + repeats=_repeats(members[0], shared_within, varies), + shared_in_all=universal, + varies_by_member=varies, + ), + ) + + +def _collapse_siblings( + node: ComponentNode, + collapsed_children: Tuple[ComponentNode, ...], + context: _CollapseContext, +) -> ComponentNode: + """ + Rules R1 (soft plate) and R2 (shared split) plus their safety condition, + applied to one node's ``children``. + + Only ``kind="model"`` siblings collapse: a ``Collection`` is a *frame*, not + a repeated component, so it never collapses -- but its model children do. + + ``node`` is the **uncollapsed** node, so every rule reads the model as + declared: after the bottom-up pass a member's own children may already be a + plate, and a plate hides the very prior ids and rows R2 and the safety + condition partition on. ``collapsed_children`` are the same children after + that pass, and are what is actually emitted. + + Everything is ordered by declaration, never by set iteration, so the result + is deterministic. + """ + children = node.children + candidates = [ + index for index, child in enumerate(children) if child.kind == "model" + ] + if len(candidates) < 2: + return replace(node, children=collapsed_children) + + by_signature: Dict[Tuple, List[int]] = {} + for index in candidates: + by_signature.setdefault(_signature(children[index], context), []).append(index) + + groups: List[List[int]] = [] + for indices in by_signature.values(): + if len(indices) < 2: + groups.append(indices) + continue + members = [children[index] for index in indices] + keys, _ = _shared_split(members) + buckets: Dict[Tuple, List[int]] = {} + for index, member, key in zip(indices, members, keys): + buckets.setdefault( + (key, _safety_profile(member, members, context)), [] + ).append(index) + groups.extend(buckets.values()) + + group_of: Dict[int, List[int]] = {} + for indices in groups: + for index in indices: + group_of[index] = indices + + emitted: List[ComponentNode] = [] + for index in range(len(children)): + indices = group_of.get(index) + if indices is None or len(indices) == 1: + emitted.append(collapsed_children[index]) + continue + if index != indices[0]: + continue + emitted.append( + _plate( + [children[i] for i in indices], + collapsed_children[indices[0]], + context, + ) + ) + + return replace(node, children=tuple(emitted)) + + +def _collapse_tree(node: ComponentNode, context: _CollapseContext) -> ComponentNode: + """Apply :func:`_collapse_siblings` recursively, bottom-up.""" + return _collapse_siblings( + node, + tuple(_collapse_tree(child, context) for child in node.children), + context, + ) + + +# ---------------------------------------------------------------------------- +# the spec +# ---------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class GraphSpec: + """ + The semantic layer: a nesting tree plus the three edge kinds, a path index + and the reconciling counts. + """ + + root: ComponentNode + shared: Tuple[SharedEdge, ...] = () + relations: Tuple[RelationEdge, ...] = () + assertions: Tuple[AssertionEdge, ...] = () + #: element key -> the ``model.info`` paths it resolves to. See + #: :func:`_path_index` for the two value shapes. + path_index: Dict[str, Any] = field(default_factory=dict) + counts: Dict[str, int] = field(default_factory=dict) + + @classmethod + def from_model( + cls, + model, + analysis=None, + collapse: bool = True, + solved_paths: Sequence = (), + ) -> "GraphSpec": + """ + Extract the spec of a model. + + Parameters + ---------- + model + Any ``AbstractPriorModel`` -- ``af.Model``, ``af.Collection``, + ``af.Array`` or a ``FactorGraphModel``'s ``global_prior_model``. + analysis + An optional ``af.Analysis``. When given, its latent catalogue + (``type(analysis).Latent.keys(analysis)``) is attached as ``solved`` + rows with ``in_model_info=False``. Without it, latents are simply + absent. + collapse + Whether to apply rules R1/R2 and their safety condition, collapsing + repeated sibling components into plates (see + :func:`_collapse_siblings`). ``collapse=False`` returns the + uncollapsed tree. + solved_paths + Paths -- tuples or dotted strings -- whose rows are re-stated as + ``solved`` and marked absent from ``model.info``. Phase 3 supplies + the domain rules that populate this. + """ + extractor = _Extractor(model, analysis=analysis, solved_paths=solved_paths) + raw_root = extractor.attach_latents(extractor.build_root()) + root = ( + _collapse_tree(raw_root, _CollapseContext(extractor)) + if collapse + else raw_root + ) + spec = cls( + root=root, + shared=extractor.shared_edges(), + relations=extractor.relation_edges(), + assertions=extractor.assertion_edges(), + ) + object.__setattr__(spec, "path_index", _path_index(spec, model)) + object.__setattr__(spec, "counts", _counts(model, spec, raw_root)) + return spec + + # -- convenience -------------------------------------------------------- + + def components(self) -> List[ComponentNode]: + """Every component node, in visual order.""" + + def _walk(node): + yield node + for child in node.children: + yield from _walk(child) + + return list(_walk(self.root)) + + def node(self, path) -> Optional[ComponentNode]: + """The component node at ``path``, or ``None``.""" + path = _as_path(path) + for node in self.components(): + if node.path == path: + return node + return None + + def rows(self) -> List[ParamRow]: + """Every top-level row of every component, in visual order.""" + return [row for node in self.components() for row in node.rows] + + def row(self, path) -> Optional[ParamRow]: + """The row at ``path`` (top-level rows and tuple components), or ``None``.""" + path = _as_path(path) + for row in self.rows(): + if row.path == path: + return row + for component in row.components: + if component.path == path: + return component + return None + + def to_dict(self) -> dict: + """ + An insertion-ordered, JSON-serialisable dict. ``json.dumps`` of it is + byte-stable across extractions of the same model. + """ + return { + "root": self.root.to_dict(), + "shared": [edge.to_dict() for edge in self.shared], + "relations": [edge.to_dict() for edge in self.relations], + "assertions": [edge.to_dict() for edge in self.assertions], + "path_index": { + key: ( + entry if isinstance(entry, dict) else [list(path) for path in entry] + ) + for key, entry in self.path_index.items() + }, + "counts": dict(self.counts), + } + + +def _info_group_map(model) -> Dict[Path, Path]: + """ + ``concrete leaf path -> the grouped path`` ``model.info`` prints for it. + + A faithful replay of ``AbstractPriorModel.info``'s own + ``find_groups(..., limit=1)`` pass, but carrying each group's *members* + along so the mapping can be read back. (``info`` additionally honours a + parent's ``__exclude_identifier_fields__``; those attributes are skipped + from the spec too, so they never reach this map.) + """ + entries: List[Tuple[Path, Any, List[Path]]] = [] + for path, value in model.path_instance_tuples_for_class( + (Prior, float, Constant, int, tuple, ConfigException), ignore_children=True + ): + if path[-1] in ("id", "item_number"): + continue + concrete = _as_path(path) + entries.append((concrete, value, [concrete])) + + if not entries: + return {} + + longest = max(len(path) for path, _, _ in entries) + for position in range(longest - 1): + grouped: Dict[Any, List] = {} + carried: List[Tuple[Path, Any, List[Path]]] = [] + for path, value, sources in entries: + if position >= len(path): + carried.append((path, value, sources)) + continue + key = (path[:position], path[position + 1 :], value) + try: + bucket = grouped.setdefault(key, [[], []]) + except TypeError: # pragma: no cover - an unhashable leaf value + carried.append((path, value, sources)) + continue + bucket[0].append(path[position]) + bucket[1].extend(sources) + for (before, after, value), (names, sources) in grouped.items(): + try: + key = integers_representative_key(list(map(int, names))) + except ValueError: + key = ( + f"{min(names)} - {max(names)}" if len(set(names)) > 1 else names[0] + ) + carried.append(((*before, key, *after), value, sources)) + entries = carried + + return {source: path for path, _, sources in entries for source in sources} + + +def _group_paths(paths: Sequence[Path]) -> Tuple[Path, ...]: + """The figure's own grouping of a plate's member paths, via ``find_groups``.""" + if len(paths) < 2: + return tuple(paths) + return tuple( + path for path, _ in find_groups([(path, 0) for path in paths], limit=0) + ) + + +def _path_index(spec: GraphSpec, model) -> Dict[str, Any]: + """ + element key -> the ``model.info`` paths it resolves to. + + Two value shapes, both JSON-stable: + + * a **tuple of paths** for an element standing for exactly one path -- the + ordinary case, and the phase-1 shape. An element absent from + ``model.info`` (a ``solved`` row, a ``latent`` row, an assertion) is the + empty tuple; a ``missing`` row *is* in ``model.info`` and keeps its path. + * a ``{"figure": [...], "info": [...]}`` **dict** of ``"/"``-joined paths + for an element inside a plate whose figure partition is *finer* than + ``model.info``'s grouping -- the MGE's two 30-member plates against + ``model.info``'s single ``0 - 59`` centre. ``figure`` is the plate's own + grouping of the member paths, ``info`` is what ``model.info`` prints. The + mapping is recorded rather than hidden (epic: "record the mapping rather + than hiding it"). When the two agree the plain tuple shape is used. + """ + index: Dict[str, Any] = {} + info_map = _info_group_map(model) if _has_plate(spec.root) else {} + + def _entry(concrete: Tuple[Path, ...]) -> Any: + figure = _group_paths(concrete) + if len(concrete) < 2: + return figure + info: List[Path] = [] + for path in concrete: + grouped = info_map.get(path, path) + if grouped not in info: + info.append(grouped) + if tuple(info) == figure: + return figure + return { + "figure": [_key(path) for path in figure], + "info": [_key(path) for path in info], + } + + def _add_row(row: ParamRow, concrete: Tuple[Path, ...]): + index[_key(row.path)] = _entry(concrete) if row.in_model_info else () + for component in row.components: + leaf = component.path[len(row.path) :] + if not component.in_model_info: + index[_key(component.path)] = () + elif row.dimensionality == "tuple" and row.prior_cls_name == "tuple": + # A fixed tuple constant is one grouped line in `model.info`. + index[_key(component.path)] = index[_key(row.path)] + else: + index[_key(component.path)] = _entry( + tuple(path + leaf for path in concrete) + ) + + def _walk(node: ComponentNode, concrete: Tuple[Path, ...]): + index[_key(node.path)] = _entry(concrete) + for row in node.rows: + suffix = row.path[len(node.path) :] + _add_row(row, tuple(path + suffix for path in concrete)) + for child in node.children: + if child.plate is not None: + suffixes = [ + member[len(node.path) :] for member in child.plate.member_paths + ] + else: + suffixes = [child.path[len(node.path) :]] + _walk( + child, + tuple(path + suffix for path in concrete for suffix in suffixes), + ) + + _walk(spec.root, (spec.root.path,)) + for number, _ in enumerate(spec.assertions): + index[f"assertion/{number}"] = () + return index + + +def _has_plate(node: ComponentNode) -> bool: + return node.plate is not None or any(_has_plate(child) for child in node.children) + + +def _node_count(node: ComponentNode) -> int: + return 1 + sum(_node_count(child) for child in node.children) + + +def _plate_count(node: ComponentNode) -> int: + return (node.plate is not None) + sum( + _plate_count(child) for child in node.children + ) + + +def _counts(model, spec: GraphSpec, raw_root: ComponentNode) -> Dict[str, int]: + """ + The reconciling counts. + + The row-derived counts (``fixed_leaf_slots``, ``missing``) are of the + **uncollapsed** tree: a plate stands for every one of its members, so + collapsing must not make a fixed value look absent from the model. Only the + component counts are of both trees -- ``components`` after collapse, + ``components_raw`` before, and ``plates`` how many of the former stand for + more than one of the latter. + """ + fixed_leaf_slots = 0 + missing = 0 + for node in _walk_nodes(raw_root): + for row in node.rows: + if row.dimensionality == "tuple": + for component in row.components: + if component.sampling == "fixed": + fixed_leaf_slots += 1 + if component.sampling == "missing": + missing += 1 + continue + if row.sampling == "fixed": + fixed_leaf_slots += 1 + if row.sampling == "missing": + missing += 1 + return { + "unique_sampled_scalars": model.prior_count, + "fixed_leaf_slots": fixed_leaf_slots, + "shared_priors": len(spec.shared), + "missing": missing, + "components_raw": _node_count(raw_root), + "components": _node_count(spec.root), + "plates": _plate_count(spec.root), + } + + +def _walk_nodes(node: ComponentNode): + yield node + for child in node.children: + yield from _walk_nodes(child) + + +def graph_spec_from(model, **kwargs) -> GraphSpec: + """Module-level alias for :meth:`GraphSpec.from_model`.""" + return GraphSpec.from_model(model, **kwargs) diff --git a/test_autofit/graph_spec/__init__.py b/test_autofit/graph_spec/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/test_autofit/graph_spec/conftest.py b/test_autofit/graph_spec/conftest.py new file mode 100644 index 000000000..8adb2bd6c --- /dev/null +++ b/test_autofit/graph_spec/conftest.py @@ -0,0 +1,33 @@ +import itertools + +import pytest + +import autofit as af + + +@pytest.fixture(autouse=True) +def reset_ids(): + """ + Model object and prior ids are global counters, and the spec records both. + Reset them before every test so ids -- and therefore the serialised spec -- + are a function of the model alone (copied from ``test_autofit/test_visualise.py``). + """ + af.ModelObject._ids = itertools.count() + af.Prior._ids = itertools.count() + + +class NullAnalysis(af.Analysis): + """The smallest possible analysis: enough to build an ``af.AnalysisFactor``.""" + + def log_likelihood_function(self, instance): + return 0.0 + + +class FwhmLatent(af.Analysis.Latent): + @staticmethod + def keys(analysis): + return ["gaussian.fwhm"] + + +class LatentAnalysis(NullAnalysis): + Latent = FwhmLatent diff --git a/test_autofit/graph_spec/lens_doubles.py b/test_autofit/graph_spec/lens_doubles.py new file mode 100644 index 000000000..cfed4c32d --- /dev/null +++ b/test_autofit/graph_spec/lens_doubles.py @@ -0,0 +1,455 @@ +""" +Structural doubles of the lens model classes, for the epic's three acceptance +models. + +autofit imports **autonerves only** -- never autogalaxy or autolens, not even in +a test (``AGENTS.md``). So the acceptance models are built from plain Python +classes defined here that carry the *same class names, attribute names and +constructor signatures* as the real profiles, and are composed exactly as the +current workspace scripts compose them: + +* ``autolens_workspace/scripts/imaging/start_here.py`` and + ``scripts/guides/modeling/cookbook.py`` -- (a) the simple lens; +* ``scripts/imaging/features/multi_gaussian_expansion/modeling.py`` lines + 209-261 -- (b) the MGE; +* ``scripts/group/modeling.py`` lines 288-345 -- (e) the group model. + +The doubles have no prior configuration, so ``af.Model(Cls)`` stores a +``ConfigException`` for every parameter (``prior_model.py`` +:meth:`Model.make_prior`). Every parameter is therefore given an explicit prior +here, mirroring the limits in ``pyautogalaxy/autogalaxy/config/priors/*.yaml`` -- +with one deliberate exception, ``Hilbert.areas_factor``, which is left unset so +the acceptance can assert the ``missing`` state. + +Known divergences from today's libraries, kept because the epic's acceptance +model needs them (see ``PyAutoFit#1605``): + +* ``Hilbert`` no longer takes ``areas_factor`` in autoarray -- the modern + signature is ``(pixels, weight_power, weight_floor)``. The epic's ``missing`` + case is that parameter, so the double keeps it. +* the group dataset shipped with the workspace has *two* extra-galaxy centres; + the epic's acceptance model has **eight**, so eight distinct fixed centres are + used here. +""" + +from typing import Optional, Tuple + +import autofit as af + +# ---------------------------------------------------------------------------- +# priors, mirroring pyautogalaxy/autogalaxy/config/priors/*.yaml +# ---------------------------------------------------------------------------- + + +def _gaussian(mean, sigma): + return af.GaussianPrior(mean=mean, sigma=sigma) + + +def _uniform(lower, upper): + return af.UniformPrior(lower_limit=lower, upper_limit=upper) + + +def _log_uniform(lower, upper): + return af.LogUniformPrior(lower_limit=lower, upper_limit=upper) + + +def _ell_comp(): + """``TruncatedGaussian`` (0.0, 0.3) on [-1, 1] -- every ``ell_comps`` slot.""" + return af.TruncatedGaussianPrior( + mean=0.0, sigma=0.3, lower_limit=-1.0, upper_limit=1.0 + ) + + +def _set_tuple(model, name, priors): + """ + Set a tuple parameter's slots. + + ``Model.__setattr__`` routes an underscored name into its tuple prior by + splitting on the *first* underscore, so ``model.ell_comps_0 = ...`` looks for + a tuple prior called ``ell`` and silently creates a stray attribute instead. + Reaching the ``TuplePrior`` directly is the reliable form. + """ + tuple_prior = getattr(model, name) + for index, prior in enumerate(priors): + setattr(tuple_prior, f"{name}_{index}", prior) + + +# ---------------------------------------------------------------------------- +# the doubles +# ---------------------------------------------------------------------------- + + +class AbstractRegularization: + """Stand-in for ``aa.AbstractRegularization``, only ever an annotation.""" + + +class Sersic: + def __init__( + self, + centre: Tuple[float, float] = (0.0, 0.0), + ell_comps: Tuple[float, float] = (0.0, 0.0), + intensity: float = 0.1, + effective_radius: float = 0.6, + sersic_index: float = 4.0, + ): + self.centre = centre + self.ell_comps = ell_comps + self.intensity = intensity + self.effective_radius = effective_radius + self.sersic_index = sersic_index + + +class SersicSph: + def __init__( + self, + centre: Tuple[float, float] = (0.0, 0.0), + intensity: float = 0.1, + effective_radius: float = 0.6, + sersic_index: float = 4.0, + ): + self.centre = centre + self.intensity = intensity + self.effective_radius = effective_radius + self.sersic_index = sersic_index + + +class SersicCore: + def __init__( + self, + centre: Tuple[float, float] = (0.0, 0.0), + ell_comps: Tuple[float, float] = (0.0, 0.0), + effective_radius: float = 0.6, + sersic_index: float = 4.0, + radius_break: float = 0.025, + intensity: float = 0.05, + gamma: float = 0.25, + alpha: float = 3.0, + ): + self.centre = centre + self.ell_comps = ell_comps + self.effective_radius = effective_radius + self.sersic_index = sersic_index + self.radius_break = radius_break + self.intensity = intensity + self.gamma = gamma + self.alpha = alpha + + +class Gaussian: + """``al.lp_linear.Gaussian`` -- linear, so there is no ``intensity``.""" + + def __init__( + self, + centre: Tuple[float, float] = (0.0, 0.0), + ell_comps: Tuple[float, float] = (0.0, 0.0), + sigma: float = 1.0, + ): + self.centre = centre + self.ell_comps = ell_comps + self.sigma = sigma + + +class Basis: + def __init__( + self, + profile_list: list = None, + regularization: Optional[AbstractRegularization] = None, + ): + self.profile_list = profile_list + self.regularization = regularization + + +class Isothermal: + def __init__( + self, + centre: Tuple[float, float] = (0.0, 0.0), + ell_comps: Tuple[float, float] = (0.0, 0.0), + einstein_radius: float = 1.0, + ): + self.centre = centre + self.ell_comps = ell_comps + self.einstein_radius = einstein_radius + + +class ExternalShear: + def __init__(self, gamma_1: float = 0.0, gamma_2: float = 0.0): + self.gamma_1 = gamma_1 + self.gamma_2 = gamma_2 + + +class dPIEMassSph: + def __init__( + self, + centre: Tuple[float, float] = (0.0, 0.0), + sigma: float = 200.0, + r_core: float = 0.1, + r_cut: float = 20.0, + redshift_object: float = 0.5, + redshift_source: float = 1.0, + H0: float = 67.66, + Om0: float = 0.30966, + ): + self.centre = centre + self.sigma = sigma + self.r_core = r_core + self.r_cut = r_cut + self.redshift_object = redshift_object + self.redshift_source = redshift_source + self.H0 = H0 + self.Om0 = Om0 + + +class Hilbert: + """ + The epic-era ``al.image_mesh.Hilbert``. ``areas_factor`` is deliberately + left without a prior wherever this is used, so it sits in the tree as a + ``ConfigException`` -- the ``missing`` state. + """ + + def __init__(self, pixels: int = 1000, areas_factor: float = 1.0): + self.pixels = pixels + self.areas_factor = areas_factor + + +class Delaunay: + def __init__(self): + pass + + +class AdaptiveBrightnessSplit: + def __init__( + self, + inner_coefficient: float = 1.0, + outer_coefficient: float = 1.0, + signal_scale: float = 0.1, + ): + self.inner_coefficient = inner_coefficient + self.outer_coefficient = outer_coefficient + self.signal_scale = signal_scale + + +class Pixelization: + def __init__(self, image_mesh=None, mesh=None, regularization=None): + self.image_mesh = image_mesh + self.mesh = mesh + self.regularization = regularization + + +class Galaxy(af.ModelObject): + """``al.Galaxy`` -- a ``ModelObject`` whose extra kwargs become attributes.""" + + def __init__(self, redshift: float, **kwargs): + super().__init__() + self.redshift = redshift + for name, value in kwargs.items(): + setattr(self, name, value) + + +# ---------------------------------------------------------------------------- +# configured models +# ---------------------------------------------------------------------------- + + +def sersic(): + model = af.Model(Sersic) + _set_tuple(model, "centre", (_gaussian(0.0, 0.3), _gaussian(0.0, 0.3))) + _set_tuple(model, "ell_comps", (_ell_comp(), _ell_comp())) + model.intensity = _log_uniform(1e-06, 1e06) + model.effective_radius = _uniform(0.0, 30.0) + model.sersic_index = _uniform(0.8, 5.0) + return model + + +def sersic_sph(): + model = af.Model(SersicSph) + _set_tuple(model, "centre", (_gaussian(0.0, 0.3), _gaussian(0.0, 0.3))) + model.intensity = _log_uniform(1e-06, 1e06) + model.effective_radius = _uniform(0.0, 30.0) + model.sersic_index = _uniform(0.8, 5.0) + return model + + +def sersic_core(): + model = af.Model(SersicCore) + _set_tuple(model, "centre", (_gaussian(0.0, 0.3), _gaussian(0.0, 0.3))) + _set_tuple(model, "ell_comps", (_ell_comp(), _ell_comp())) + model.effective_radius = _uniform(0.0, 30.0) + model.sersic_index = _uniform(0.8, 5.0) + # `radius_break`, `gamma` and `alpha` are `Constant` in the real config. + model.radius_break = 0.025 + model.intensity = _log_uniform(1e-05, 1000.0) + model.gamma = 0.25 + model.alpha = 3.0 + return model + + +def linear_gaussian(): + model = af.Model(Gaussian) + _set_tuple(model, "centre", (_gaussian(0.0, 0.3), _gaussian(0.0, 0.3))) + _set_tuple(model, "ell_comps", (_ell_comp(), _ell_comp())) + model.sigma = _uniform(0.0, 25.0) + return model + + +def isothermal(): + model = af.Model(Isothermal) + _set_tuple(model, "centre", (_gaussian(0.0, 0.1), _gaussian(0.0, 0.1))) + _set_tuple(model, "ell_comps", (_ell_comp(), _ell_comp())) + model.einstein_radius = _uniform(0.0, 8.0) + return model + + +def external_shear(): + model = af.Model(ExternalShear) + model.gamma_1 = _uniform(-0.3, 0.3) + model.gamma_2 = _uniform(-0.3, 0.3) + return model + + +def dpie_mass_sph(): + model = af.Model(dPIEMassSph) + _set_tuple(model, "centre", (_gaussian(0.0, 0.1), _gaussian(0.0, 0.1))) + model.sigma = _uniform(0.0, 1000.0) + model.r_core = _uniform(0.0, 10.0) + model.r_cut = _uniform(0.0, 100.0) + model.redshift_object = _uniform(0.0, 1.0) + model.redshift_source = _uniform(0.0, 1.0) + model.H0 = _uniform(0.0, 100.0) + model.Om0 = _uniform(0.0, 1.0) + return model + + +# ---------------------------------------------------------------------------- +# (a) the simple lens +# ---------------------------------------------------------------------------- + + +def simple_lens_model(): + """ + ``lens = Galaxy(redshift=0.5, bulge=Sersic, mass=Isothermal, + shear=ExternalShear)``, ``source = Galaxy(redshift=1.0, bulge=Sersic)``. + """ + lens = af.Model( + Galaxy, + redshift=0.5, + bulge=sersic(), + mass=isothermal(), + shear=external_shear(), + ) + source = af.Model(Galaxy, redshift=1.0, bulge=sersic()) + return af.Collection(galaxies=af.Collection(lens=lens, source=source)) + + +# ---------------------------------------------------------------------------- +# (b) the MGE, 2 x 30, with a pixelized source +# ---------------------------------------------------------------------------- + + +def mge_model(total_gaussians: int = 30, gaussian_per_basis: int = 2): + """ + The MGE composition of + ``scripts/imaging/features/multi_gaussian_expansion/modeling.py``: two bases + of ``total_gaussians`` linear Gaussians, one shared ``centre`` across *all* + of them, one shared ``ell_comps`` *per basis*, and a per-Gaussian fixed + ``sigma``. + """ + log10_sigma_list = [ + -1.0 + (index * (1.0 - -1.0) / (total_gaussians - 1)) + for index in range(total_gaussians) + ] + + centre_0 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1) + centre_1 = af.UniformPrior(lower_limit=-0.1, upper_limit=0.1) + + bulge_gaussian_list = [] + for _ in range(gaussian_per_basis): + gaussian_list = af.Collection(linear_gaussian() for _ in range(total_gaussians)) + for index, gaussian in enumerate(gaussian_list): + gaussian.centre.centre_0 = centre_0 + gaussian.centre.centre_1 = centre_1 + gaussian.ell_comps = gaussian_list[0].ell_comps + gaussian.sigma = 10 ** log10_sigma_list[index] + bulge_gaussian_list += gaussian_list + + bulge = af.Model(Basis, profile_list=bulge_gaussian_list) + + lens = af.Model( + Galaxy, + redshift=0.5, + bulge=bulge, + mass=isothermal(), + shear=external_shear(), + ) + + image_mesh = af.Model(Hilbert, pixels=1000) + # `areas_factor` is deliberately left as its `ConfigException`. + mesh = af.Model(Delaunay) + regularization = af.Model(AdaptiveBrightnessSplit) + regularization.inner_coefficient = _log_uniform(1e-04, 1e04) + regularization.outer_coefficient = _log_uniform(1e-04, 1e04) + regularization.signal_scale = _uniform(0.0, 10.0) + + source = af.Model( + Galaxy, + redshift=1.0, + pixelization=af.Model( + Pixelization, + image_mesh=image_mesh, + mesh=mesh, + regularization=regularization, + ), + ) + return af.Collection(galaxies=af.Collection(lens=lens, source=source)) + + +# ---------------------------------------------------------------------------- +# (e) the group model, eight extra galaxies +# ---------------------------------------------------------------------------- + +#: Eight distinct fixed ``(y, x)`` centres -- the epic's acceptance model. The +#: dataset shipped with `scripts/group/modeling.py` has two. +EXTRA_GALAXY_CENTRES = ( + (1.0, 3.5), + (-2.0, -3.5), + (3.1, -1.4), + (-1.7, 2.6), + (0.6, -4.2), + (4.3, 0.9), + (-3.8, -0.4), + (2.2, 2.2), +) + + +def group_model(centres=EXTRA_GALAXY_CENTRES): + """The composition of ``scripts/group/modeling.py`` lines 288-345.""" + lens_0 = af.Model( + Galaxy, + redshift=0.5, + bulge=sersic(), + mass=isothermal(), + shear=external_shear(), + ) + + extra_galaxies_list = [] + for centre in centres: + mass = dpie_mass_sph() + mass.centre = centre + mass.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=300.0) + mass.r_core = 0.0 + mass.r_cut = 10.0 + mass.redshift_object = 0.5 + mass.redshift_source = 1.0 + mass.H0 = 67.66 + mass.Om0 = 0.30966 + + extra_galaxies_list.append( + af.Model(Galaxy, redshift=0.5, bulge=sersic_sph(), mass=mass) + ) + + extra_galaxies = af.Collection(extra_galaxies_list) + source = af.Model(Galaxy, redshift=1.0, bulge=sersic_core()) + + return af.Collection( + galaxies=af.Collection(lens_0=lens_0, source=source), + extra_galaxies=extra_galaxies, + ) diff --git a/test_autofit/graph_spec/test_acceptance_lens.py b/test_autofit/graph_spec/test_acceptance_lens.py new file mode 100644 index 000000000..24ef34676 --- /dev/null +++ b/test_autofit/graph_spec/test_acceptance_lens.py @@ -0,0 +1,254 @@ +""" +The epic's three acceptance models (``PyAutoMind/active/model_figures_1_graph_spec.md``, +"Acceptance -- the three lens models"), built from the structural doubles in +:mod:`lens_doubles` because autofit may never import autogalaxy or autolens. + +**Honesty rule.** The epic's numbers were measured on the human's real science +models in a throwaway prototype. Where a double faithful to today's workspace +script cannot reproduce one, the *measured* value is pinned with a +``# epic target: N -- measured M ...`` comment and the gap is reported rather +than the double or the rule being bent. Every *structural* invariant -- plate +counts and splits, shared multiplicities, the ``missing`` state, fixed tuple +rows, ``varies_by_member``, determinism -- is asserted unconditionally. +""" + +import json + +from autofit.graph_spec import GraphSpec + +from . import lens_doubles as doubles + + +def _boxes(spec): + """Component *boxes*: the epic counts ``Model`` nodes, not collection frames.""" + return [node for node in spec.components() if node.kind == "model"] + + +def _plates(spec): + return [node for node in spec.components() if node.plate is not None] + + +def _twice(build): + """The same model extracted twice, as two serialised specs.""" + model = build() + return ( + json.dumps(GraphSpec.from_model(model).to_dict()), + json.dumps(GraphSpec.from_model(model).to_dict()), + ) + + +# ------------------------------------------------------------------ (a) + + +def test_a_simple_lens(): + model = doubles.simple_lens_model() + spec = GraphSpec.from_model(model) + + # 8 raw component nodes -- the epic's figure, exactly. + assert spec.counts["components_raw"] == 8 + # epic target: 48 info lines -- measured 47 on the structural double; see + # PyAutoFit#1605. + assert len(model.info.splitlines()) == 47 + + # 6 component boxes after collapse: the two `Collection` frames are not + # boxes, and nothing in this model repeats. + assert len(_boxes(spec)) == 6 + assert spec.counts["plates"] == 0 + assert spec.counts["components"] == spec.counts["components_raw"] == 8 + + assert [(node.path[-1], node.cls_name) for node in _boxes(spec)] == [ + ("lens", "Galaxy"), + ("bulge", "Sersic"), + ("mass", "Isothermal"), + ("shear", "ExternalShear"), + ("source", "Galaxy"), + ("bulge", "Sersic"), + ] + # Declaration order, `bulge, mass, shear` -- never `shear` above `mass`. + assert [node.name for node in spec.node(("galaxies", "lens")).children] == [ + "bulge", + "mass", + "shear", + ] + + # epic target: 13 rows -- measured 17 on the structural double (the two + # `redshift` rows and both `Sersic` intensities are rows here); see + # PyAutoFit#1605. + assert len(spec.rows()) == 17 + assert spec.counts["unique_sampled_scalars"] == 21 + assert spec.counts["fixed_leaf_slots"] == 2 + assert spec.counts["shared_priors"] == 0 + assert spec.counts["missing"] == 0 + + +def test_a_simple_lens_is_deterministic(): + first, second = _twice(doubles.simple_lens_model) + assert first == second + + +# ------------------------------------------------------------------ (b) + + +def test_b_mge_two_by_thirty_with_a_pixelized_source(): + model = doubles.mge_model() + spec = GraphSpec.from_model(model) + + # epic target: 73 raw nodes -- measured 72 on the structural double, which + # is 73 minus the `af.Model(int)` node R7 drops: today's `Delaunay` takes no + # `pixels` argument, so the composition no longer has one. See + # PyAutoFit#1605. + assert spec.counts["components_raw"] == 72 + # epic target: 178 info lines -- measured 173 on the structural double. + assert len(model.info.splitlines()) == 173 + + # *** The epic's headline: 11 components after collapse. *** + assert len(_boxes(spec)) == 11 + + # Two x30 plates, split on `ell_comps` -- never one merged x60. + plates = _plates(spec) + assert [plate.plate.count for plate in plates] == [30, 30] + assert [plate.plate.representative_key for plate in plates] == [ + "0 - 29", + "30 - 59", + ] + assert [plate.path for plate in plates] == [ + ("galaxies", "lens", "bulge", "profile_list", "0"), + ("galaxies", "lens", "bulge", "profile_list", "30"), + ] + assert all(plate.cls_name == "Gaussian" for plate in plates) + + # The centre is in every one of the 60, so it does not discriminate; each + # basis's `ell_comps` is in exactly its own 30, so it does. + for plate in plates: + assert len(plate.plate.shared_in_all) == 4 + # The per-Gaussian fixed sigma is named, never silently merged away. + assert plate.plate.varies_by_member == ("sigma",) + assert "sigma fixed (varies by member)" in plate.plate.repeats[0] + assert "centre ⇄ shared" in plate.plate.repeats[0] + assert "ell_comps ⇄ shared" in plate.plate.repeats[0] + + # 6 shared priors: centre_0 and centre_1 across all 60, then each basis's + # ell_comps_0 / ell_comps_1 across its own 30. + assert spec.counts["shared_priors"] == 6 + assert sorted((len(edge.occurrences) for edge in spec.shared), reverse=True) == [ + 60, + 60, + 30, + 30, + 30, + 30, + ] + + # 16 unique sampled scalars. + assert spec.counts["unique_sampled_scalars"] == 16 + + # `areas_factor` is unset: `missing`, not `solved`, and never absent. + areas_factor = spec.row( + ("galaxies", "source", "pixelization", "image_mesh", "areas_factor") + ) + assert areas_factor is not None + assert areas_factor.sampling == "missing" + assert areas_factor.prior_cls_name == "ConfigException" + assert areas_factor.in_model_info is True + assert spec.counts["missing"] == 1 + # ... while `pixels` beside it is a plain fixed value. + pixels = spec.row(("galaxies", "source", "pixelization", "image_mesh", "pixels")) + assert pixels.sampling == "fixed" + assert pixels.value == 1000.0 + + # Nothing fixed is dropped by the plates: 60 sigmas plus `pixels` and the + # two redshifts (`Basis.regularization=None` is unset, not a slot). + assert spec.counts["fixed_leaf_slots"] == 63 + + +def test_b_mge_path_index_records_the_finer_partition(): + spec = GraphSpec.from_model(doubles.mge_model()) + + # `model.info` groups the shared centre across all 60; the figure's + # partition is finer (two plates of 30), so the entry records both. + entry = spec.path_index["galaxies/lens/bulge/profile_list/0/centre/centre_0"] + assert entry == { + "figure": ["galaxies/lens/bulge/profile_list/0 - 29/centre/centre_0"], + "info": ["galaxies/lens/bulge/profile_list/0 - 59/centre/centre_0"], + } + # `ell_comps` is shared by exactly one plate's members, so the two agree and + # the plain tuple-of-paths shape is kept. + assert spec.path_index[ + "galaxies/lens/bulge/profile_list/30/ell_comps/ell_comps_0" + ] == ( + ( + "galaxies", + "lens", + "bulge", + "profile_list", + "30 - 59", + "ell_comps", + "ell_comps_0", + ), + ) + + +def test_b_mge_is_deterministic(): + first, second = _twice(doubles.mge_model) + assert first == second + + +# ------------------------------------------------------------------ (e) + + +def test_e_group_scale_with_eight_extra_galaxies(): + model = doubles.group_model() + spec = GraphSpec.from_model(model) + + # epic target: 166 raw nodes -- measured 33 on the structural double. The + # epic's group model is bigger than today's `scripts/group/modeling.py` + # composition (one main lens, one source, eight extra galaxies); see + # PyAutoFit#1605. + assert spec.counts["components_raw"] == 33 + # epic target: 418 info lines -- measured 199 on the structural double. + assert len(model.info.splitlines()) == 199 + # epic target: 15 components (16 before R7) -- measured 9 boxes. + assert len(_boxes(spec)) == 9 + + # *** The structural invariant: the eight extra galaxies are ONE plate. *** + (plate,) = _plates(spec) + assert plate.path == ("extra_galaxies", "0") + assert plate.cls_name == "Galaxy" + assert plate.plate.count == 8 + assert plate.plate.representative_key == "0 - 7" + assert plate.plate.member_paths == tuple( + ("extra_galaxies", str(index)) for index in range(8) + ) + + # The per-galaxy fixed `centre` tuple is a row, and its variation is named. + assert plate.plate.varies_by_member == ("mass.centre",) + centre = spec.row(("extra_galaxies", "0", "mass", "centre")) + assert centre is not None + assert centre.dimensionality == "tuple" + assert centre.sampling == "fixed" + assert [component.name for component in centre.components] == [ + "centre_0", + "centre_1", + ] + assert [component.value for component in centre.components] == [1.0, 3.5] + # ... and the eight distinct centres are recorded, not hidden behind the + # representative's. + assert spec.path_index["extra_galaxies/0/mass/centre"] == { + "figure": ["extra_galaxies/0 - 7/mass/centre"], + "info": [f"extra_galaxies/{index}/mass/centre" for index in range(8)], + } + + # Nothing fixed is dropped: every member's slots are still counted. + # epic target: 291 fixed leaf slots -- measured 77 on the structural double. + assert spec.counts["fixed_leaf_slots"] == 77 + # epic target: 41 unique sampled scalars -- measured 69. + assert spec.counts["unique_sampled_scalars"] == 69 + # epic target: 22 shared priors -- measured 0: today's group script shares + # no prior between galaxies. + assert spec.counts["shared_priors"] == 0 + assert spec.counts["missing"] == 0 + + +def test_e_group_scale_is_deterministic(): + first, second = _twice(doubles.group_model) + assert first == second diff --git a/test_autofit/graph_spec/test_catalogue.py b/test_autofit/graph_spec/test_catalogue.py new file mode 100644 index 000000000..a20686501 --- /dev/null +++ b/test_autofit/graph_spec/test_catalogue.py @@ -0,0 +1,546 @@ +""" +The 18-construct catalogue. + +One test per model construct from the phase-1 prompt +(``PyAutoMind/active/model_figures_1_graph_spec.md``). Every assertion is on +the extracted :class:`~autofit.graph_spec.GraphSpec` -- never on a picture: +phase 1 draws nothing. +""" + +import itertools + +import pytest + +import autofit as af +from autofit.example.model import PhysicalNFW +from autofit.graph_spec import GraphSpec, graph_spec_from + +from .conftest import LatentAnalysis, NullAnalysis + + +def _reset_ids(): + af.ModelObject._ids = itertools.count() + af.Prior._ids = itertools.count() + + +# ---------------------------------------------------------------- 1 + + +def test_01_model_with_default_priors(): + spec = GraphSpec.from_model(af.Model(af.ex.Gaussian)) + + assert spec.root.path == () + assert spec.root.name == "model" + assert spec.root.cls_name == "Gaussian" + assert spec.root.kind == "model" + assert spec.root.children == () + + assert [row.name for row in spec.root.rows] == ["centre", "normalization", "sigma"] + for row in spec.root.rows: + assert row.sampling == "free" + assert row.dimensionality == "scalar" + assert row.provenance.kind == "config-default" + assert row.prior_cls_name == "UniformPrior" + assert row.shared is False + assert row.in_model_info is True + + assert spec.counts["unique_sampled_scalars"] == 3 + assert spec.counts["fixed_leaf_slots"] == 0 + assert spec.counts["components"] == 1 + assert spec.path_index["centre"] == (("centre",),) + + +# ---------------------------------------------------------------- 2 + + +def _row_fingerprint(row): + """Everything about a row except the identity of its prior object.""" + data = row.to_dict() + data.pop("prior_id") + data.pop("occurrences") + return data + + +def test_02_overridden_prior_is_indistinguishable_from_the_default(): + """ + KNOWN GAP: nothing on a ``Prior`` records whether it came from the config or + from the user, so ``provenance`` is ``config-default`` either way. This test + pins the gap rather than papering over it -- ``user-prior`` is a reserved + kind, not an emitted one. + """ + default = GraphSpec.from_model(af.Model(af.ex.Gaussian)) + + _reset_ids() + overridden_model = af.Model(af.ex.Gaussian) + overridden_model.centre = af.UniformPrior(lower_limit=0.0, upper_limit=1.0) + overridden = GraphSpec.from_model(overridden_model) + + default_row = default.row(("centre",)) + overridden_row = overridden.row(("centre",)) + + assert overridden_row.provenance.kind == "config-default" + assert _row_fingerprint(default_row) == _row_fingerprint(overridden_row) + + +# ---------------------------------------------------------------- 3 + + +@pytest.mark.parametrize("build", ["assignment", "keyword"]) +def test_03_fixed_float(build): + if build == "assignment": + model = af.Model(af.ex.Gaussian) + model.centre = 0.0 + else: + model = af.Model(af.ex.Gaussian, centre=0.0) + + spec = GraphSpec.from_model(model) + row = spec.row(("centre",)) + + assert row.sampling == "fixed" + assert row.value == 0.0 + assert row.prior_cls_name == "Constant" + assert row.prior_id is None + assert row.dimensionality == "scalar" + # Absent from the priors, present in `model.info`. + assert ("centre",) not in [path for path, _ in model.path_priors_tuples] + assert "centre" in model.info + assert row.in_model_info is True + assert spec.path_index["centre"] == (("centre",),) + assert spec.counts["unique_sampled_scalars"] == 2 + assert spec.counts["fixed_leaf_slots"] == 1 + + +# ---------------------------------------------------------------- 4 + + +def test_04_shared_prior(): + model = af.Collection( + a=af.Model(af.ex.Gaussian), + b=af.Model(af.ex.Gaussian), + ) + model.a.centre = model.b.centre + + # The raw tree: `a` and `b` are plate-mates under rule R1/R2, so the + # collapsed spec draws them once (see `test_collapse.py`). This construct + # is about *extraction*, so it is asserted uncollapsed. + spec = GraphSpec.from_model(model, collapse=False) + + a_centre = spec.row(("a", "centre")) + b_centre = spec.row(("b", "centre")) + + assert a_centre.prior_id == b_centre.prior_id + assert a_centre.occurrences == (("a", "centre"), ("b", "centre")) + assert a_centre.shared is True + # Sharing is never a sampling state. + assert a_centre.sampling == "free" + assert b_centre.sampling == "free" + + assert len(spec.shared) == 1 + assert spec.shared[0].prior_id == a_centre.prior_id + assert spec.shared[0].occurrences == (("a", "centre"), ("b", "centre")) + assert spec.counts["shared_priors"] == 1 + assert spec.counts["unique_sampled_scalars"] == 5 + + +# ---------------------------------------------------------------- 5 + + +def test_05_relation(): + model = af.Model(af.ex.Gaussian) + model.centre = model.normalization + model.sigma + + spec = GraphSpec.from_model(model) + row = spec.row(("centre",)) + + assert row.prior_id is None + assert row.prior_cls_name == "SumPrior" + assert row.provenance.kind == "relation" + assert row.provenance.expression == "normalization + sigma" + assert row.provenance.operands == ("normalization", "sigma") + # Its value varies during sampling, so its sampling status is free. + assert row.sampling == "free" + + # `normalization` sits at ('normalization',) *and* at ('centre', 'self'), + # because a compound prior's operands are real attributes of it. The second + # path passes through the relation, so it is not a second *use* of the + # prior: the row is related, not shared, and there is no `SharedEdge`. + normalization = spec.row(("normalization",)) + assert set(normalization.occurrences) == {("normalization",), ("centre", "self")} + assert normalization.direct_occurrences == (("normalization",),) + assert normalization.shared is False + assert spec.shared == () + assert spec.counts["shared_priors"] == 0 + + assert len(spec.relations) == 1 + edge = spec.relations[0] + assert edge.target_path == ("centre",) + assert edge.expression == "normalization + sigma" + assert edge.operand_paths == (("normalization",), ("sigma",)) + assert edge.prior_id is None + + # The compound prior has `cls == float` and is not a component. + assert spec.node(("centre",)) is None + assert [node.path for node in spec.components()] == [()] + + +def test_05b_relation_over_constants_is_fixed(): + model = af.Model(af.ex.Gaussian) + model.centre = model.sigma * 2.0 + spec = GraphSpec.from_model(model) + assert spec.row(("centre",)).provenance.expression == "sigma * 2.0" + + _reset_ids() + other = af.Model(af.ex.Gaussian) + other.centre = -other.sigma + assert GraphSpec.from_model(other).row(("centre",)).provenance.expression == ( + "-(sigma)" + ) + + +# ---------------------------------------------------------------- 6 + + +def test_06_assertion(): + model = af.Model(af.ex.Gaussian) + model.add_assertion(model.sigma > 0.5, name="sigma is large") + + spec = GraphSpec.from_model(model) + + assert len(spec.assertions) == 1 + edge = spec.assertions[0] + assert edge.op == "<" + assert edge.left == "0.5" + assert edge.right == "sigma" + # `add_assertion(name=)` is silently dropped by `AbstractPriorModel.name` + # having no setter (a separately filed bug), so the name is absent. + assert edge.name is None + + # Assertions are edges: not in the tree, and not in `model.info`. + assert [row.name for row in spec.root.rows] == ["centre", "normalization", "sigma"] + assert spec.path_index["assertion/0"] == () + assert "assert" not in model.info + + +# ---------------------------------------------------------------- 7 + + +def test_07_tuple_parameter(): + model = af.Model(PhysicalNFW) + spec = GraphSpec.from_model(model) + + assert [row.name for row in spec.root.rows] == [ + "centre", + "ell_comps", + "log10m", + "concentration", + ] + + centre = spec.row(("centre",)) + assert centre.dimensionality == "tuple" + assert centre.prior_cls_name == "TuplePrior" + assert centre.sampling == "free" + assert [component.name for component in centre.components] == [ + "centre_0", + "centre_1", + ] + assert [component.path for component in centre.components] == [ + ("centre", "centre_0"), + ("centre", "centre_1"), + ] + for component in centre.components: + assert component.sampling == "free" + assert component.prior_cls_name == "GaussianPrior" + assert component.prior_id is not None + + assert spec.path_index["centre/centre_0"] == (("centre", "centre_0"),) + assert spec.counts["unique_sampled_scalars"] == 6 + + +def test_07b_partially_fixed_tuple_is_a_mixed_state(): + model = af.Model(PhysicalNFW) + model.centre.centre_1 = 0.5 + + spec = GraphSpec.from_model(model) + centre = spec.row(("centre",)) + + assert [component.sampling for component in centre.components] == ["free", "fixed"] + assert centre.components[1].value == 0.5 + assert centre.sampling == "free" + assert spec.counts["fixed_leaf_slots"] == 1 + + +# ---------------------------------------------------------------- 8 + + +def test_08_named_collection(): + model = af.Collection(a=af.Model(af.ex.Gaussian), b=af.Model(af.ex.Gaussian)) + # Two identical siblings collapse into a plate; the construct under test is + # the named-attribute children, so assert the uncollapsed tree. + spec = GraphSpec.from_model(model, collapse=False) + + assert spec.root.kind == "collection" + assert spec.root.cls_name == "Collection" + assert [child.name for child in spec.root.children] == ["a", "b"] + assert [child.path for child in spec.root.children] == [("a",), ("b",)] + assert spec.root.rows == () + assert spec.counts["components"] == 3 + + +# ---------------------------------------------------------------- 9 + + +def test_09_list_collection(): + model = af.Collection( + [af.Model(af.ex.Gaussian), af.Model(af.ex.Gaussian), af.Model(af.ex.Gaussian)] + ) + spec = GraphSpec.from_model(model, collapse=False) + + assert [child.name for child in spec.root.children] == ["0", "1", "2"] + assert [child.path for child in spec.root.children] == [("0",), ("1",), ("2",)] + # `item_number` is bookkeeping, never a parameter slot. + assert spec.root.rows == () + assert spec.counts["unique_sampled_scalars"] == 9 + + +# ---------------------------------------------------------------- 10 + + +def test_10_nested_collections(): + model = af.Collection( + outer=af.Collection(inner=af.Collection(g=af.Model(af.ex.Gaussian))) + ) + spec = GraphSpec.from_model(model) + + assert [node.path for node in spec.components()] == [ + (), + ("outer",), + ("outer", "inner"), + ("outer", "inner", "g"), + ] + assert [node.kind for node in spec.components()] == [ + "collection", + "collection", + "collection", + "model", + ] + assert spec.row(("outer", "inner", "g", "sigma")).sampling == "free" + + +# ---------------------------------------------------------------- 11 + + +class MultiLevel: + def __init__(self, gaussian_list, normalization=1.0): + self.gaussian_list = gaussian_list + self.normalization = normalization + + +def test_11_multi_level_model(): + model = af.Model( + MultiLevel, + gaussian_list=[af.Model(af.ex.Gaussian), af.Model(af.ex.Gaussian)], + normalization=af.UniformPrior(lower_limit=0.0, upper_limit=1.0), + ) + spec = GraphSpec.from_model(model, collapse=False) + + assert spec.root.cls_name == "MultiLevel" + # The list became a child Collection at ('gaussian_list',). + assert [child.path for child in spec.root.children] == [("gaussian_list",)] + collection = spec.node(("gaussian_list",)) + assert collection.kind == "collection" + assert [child.name for child in collection.children] == ["0", "1"] + assert [row.name for row in spec.root.rows] == ["normalization"] + assert spec.counts["unique_sampled_scalars"] == 7 + + +# ---------------------------------------------------------------- 12 + + +def test_12_instance_leaf(): + instance = af.ex.Gaussian(centre=1.0, normalization=2.0, sigma=3.0) + model = af.Collection(a=af.Model(af.ex.Gaussian), b=instance) + + spec = GraphSpec.from_model(model) + + assert [child.name for child in spec.root.children] == ["a"] + row = spec.row(("b",)) + assert row is not None + assert row.is_instance is True + assert row.sampling == "fixed" + assert row.dimensionality == "scalar" + assert row.prior_cls_name == "Gaussian" + assert row.value is None + assert row.prior_id is None + # `model.info` shows it as `Gaussian (N=0)`. + assert "Gaussian (N=0)" in model.info + assert spec.counts["unique_sampled_scalars"] == 3 + + +# ---------------------------------------------------------------- 13 + + +def a_function(centre=0.0, normalization=1.0): + return centre + normalization + + +def test_13_model_of_a_function(): + """ + Config priors cannot be resolved for a function (separately filed bug), so + the priors are supplied explicitly. ``model.cls`` is the function itself and + ``cls.__name__`` still works. + """ + model = af.Model( + a_function, + centre=af.UniformPrior(lower_limit=0.0, upper_limit=1.0), + normalization=af.UniformPrior(lower_limit=0.0, upper_limit=1.0), + ) + spec = GraphSpec.from_model(model) + + assert spec.root.cls_name == "a_function" + assert spec.root.kind == "model" + assert [row.name for row in spec.root.rows] == ["centre", "normalization"] + assert all(row.sampling == "free" for row in spec.root.rows) + assert spec.counts["unique_sampled_scalars"] == 2 + + +# ---------------------------------------------------------------- 14 + + +def test_14_array(): + model = af.Array( + shape=(2, 2), prior=af.UniformPrior(lower_limit=0.0, upper_limit=1.0) + ) + spec = GraphSpec.from_model(model) + + assert spec.root.cls_name == "Array" + assert [row.name for row in spec.root.rows] == [ + "prior_0_0", + "prior_0_1", + "prior_1_0", + "prior_1_1", + ] + # `shape` and `indices` are bookkeeping noise and are skipped. + assert spec.row(("shape",)) is None + assert spec.row(("indices",)) is None + assert spec.counts["unique_sampled_scalars"] == 4 + + +# ---------------------------------------------------------------- 15 + + +def test_15_factor_graph_fully_shared(): + model = af.Model(af.ex.Gaussian) + factor_graph = af.FactorGraphModel( + af.AnalysisFactor(prior_model=model, analysis=NullAnalysis()), + af.AnalysisFactor(prior_model=model, analysis=NullAnalysis()), + af.AnalysisFactor(prior_model=model, analysis=NullAnalysis()), + ) + spec = GraphSpec.from_model(factor_graph.global_prior_model, collapse=False) + + assert spec.root.kind == "global" + assert spec.root.cls_name == "GlobalPriorModel" + assert [child.name for child in spec.root.children] == ["0", "1", "2"] + # Every child is the *same* model object. + assert len({child.obj_id for child in spec.root.children}) == 1 + # Every parameter is one prior appearing at three paths. + assert spec.counts["unique_sampled_scalars"] == 3 + assert spec.counts["shared_priors"] == 3 + for edge in spec.shared: + assert len(edge.occurrences) == 3 + # The declarative factor graph itself is not a parameter slot. + assert spec.row(("factor",)) is None + + +# ---------------------------------------------------------------- 16 + + +def test_16_factor_graph_per_dataset_free_parameters(): + model_1 = af.Model(af.ex.Gaussian) + model_2 = model_1.copy() + model_2.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=1.0) + + factor_graph = af.FactorGraphModel( + af.AnalysisFactor(prior_model=model_1, analysis=NullAnalysis()), + af.AnalysisFactor(prior_model=model_2, analysis=NullAnalysis()), + ) + spec = GraphSpec.from_model(factor_graph.global_prior_model, collapse=False) + + # Shared parameters keep one prior id; the freed one gets a new id. + assert spec.row(("0", "centre")).prior_id == spec.row(("1", "centre")).prior_id + assert spec.row(("0", "sigma")).prior_id != spec.row(("1", "sigma")).prior_id + assert spec.row(("0", "sigma")).shared is False + assert spec.row(("1", "sigma")).shared is False + assert spec.counts["shared_priors"] == 2 + assert spec.counts["unique_sampled_scalars"] == 4 + + +# ---------------------------------------------------------------- 17 + + +def test_17_cross_dataset_relation(): + sm = af.UniformPrior(lower_limit=0.0, upper_limit=1.0) + sc = af.UniformPrior(lower_limit=0.0, upper_limit=1.0) + x = af.UniformPrior(lower_limit=0.0, upper_limit=1.0) + + model_1 = af.Model(af.ex.Gaussian) + model_2 = af.Model(af.ex.Gaussian) + model_2.sigma = sm * x + sc + + factor_graph = af.FactorGraphModel( + af.AnalysisFactor(prior_model=model_1, analysis=NullAnalysis()), + af.AnalysisFactor(prior_model=model_2, analysis=NullAnalysis()), + ) + spec = GraphSpec.from_model(factor_graph.global_prior_model) + + row = spec.row(("1", "sigma")) + assert row.prior_cls_name == "SumPrior" + assert row.provenance.kind == "relation" + assert row.sampling == "free" + # Nested SumPrior(MultiplePrior(sm, x), sc): the nesting is parenthesised + # and each operand resolves to its dotted path in the model. + assert row.provenance.expression == ( + "(1.sigma.self.sm * 1.sigma.self.x) + 1.sigma.sc" + ) + assert row.provenance.operands == ( + "1.sigma.self.sm", + "1.sigma.self.x", + "1.sigma.sc", + ) + + assert len(spec.relations) == 1 + edge = spec.relations[0] + assert edge.target_path == ("1", "sigma") + assert edge.operand_paths == ( + ("1", "sigma", "self", "sm"), + ("1", "sigma", "self", "x"), + ("1", "sigma", "sc"), + ) + assert spec.counts["unique_sampled_scalars"] == 8 + + +# ---------------------------------------------------------------- 18 + + +def test_18_latent_variables(): + model = af.Collection(gaussian=af.Model(af.ex.Gaussian)) + + without = GraphSpec.from_model(model) + assert [row.name for row in without.node(("gaussian",)).rows] == [ + "centre", + "normalization", + "sigma", + ] + assert without.row(("gaussian", "fwhm")) is None + + with_analysis = graph_spec_from(model, analysis=LatentAnalysis()) + row = with_analysis.row(("gaussian", "fwhm")) + + assert row is not None + assert row.sampling == "solved" + assert row.provenance.kind == "latent" + # A latent is not part of the model at all. + assert row.in_model_info is False + assert with_analysis.path_index["gaussian/fwhm"] == () + assert "fwhm" not in model.info + # Latents do not change the model's own counts. + assert with_analysis.counts["unique_sampled_scalars"] == 3 diff --git a/test_autofit/graph_spec/test_collapse.py b/test_autofit/graph_spec/test_collapse.py new file mode 100644 index 000000000..596fc07df --- /dev/null +++ b/test_autofit/graph_spec/test_collapse.py @@ -0,0 +1,391 @@ +""" +The collapse rules -- R1 (soft plate), R2 (shared split) and the mandatory +safety condition -- from the phase-1 prompt +(``PyAutoMind/active/model_figures_1_graph_spec.md``, "Collapse rules R1/R2, +with the safety condition"). + +Every assertion is on the extracted :class:`~autofit.graph_spec.GraphSpec`. +""" + +import json + +import autofit as af +from autofit.graph_spec import GraphSpec + +# `af.ex.Gaussian`'s configured priors, repeated verbatim so a prior assigned +# by hand is *configuration-identical* to the default one and rule R1 cannot +# tell them apart. +CONFIGURED_SIGMA = dict(lower_limit=0.0, upper_limit=25.0) +CONFIGURED_CENTRE = dict(lower_limit=0.0, upper_limit=100.0) + + +class Scale: + """A one-parameter component that is *not* a Gaussian, so it never joins.""" + + def __init__(self, factor=1.0): + self.factor = factor + + +class Blob: + """A component with a tuple parameter and an ``af.Model(int)`` slot.""" + + def __init__(self, centre=(0.0, 0.0), intensity=1.0, pixels=1): + self.centre = centre + self.intensity = intensity + self.pixels = pixels + + +class Pair: + """Two sub-components, so a prior can be shared *inside* one member.""" + + def __init__(self, first=None, second=None): + self.first = first + self.second = second + + +def _gaussians(count): + return [af.Model(af.ex.Gaussian) for _ in range(count)] + + +def _plates(spec): + return [node for node in spec.components() if node.plate is not None] + + +# ------------------------------------------------------------------ R1 + + +def test_r1_collapses_identical_siblings_into_one_plate(): + spec = GraphSpec.from_model(af.Collection(_gaussians(3))) + + (plate,) = _plates(spec) + assert plate.plate.count == 3 + assert plate.plate.member_paths == (("0",), ("1",), ("2",)) + # The key `model.info` itself prints for the group, via `find_groups`. + assert plate.plate.representative_key == "0 - 2" + assert plate.plate.repeats == ( + "Gaussian with priors centre free, normalization free, sigma free", + ) + + # The representative is the first member, rows and all. + assert [child.path for child in spec.root.children] == [("0",)] + assert [row.name for row in plate.rows] == ["centre", "normalization", "sigma"] + + assert spec.counts["components_raw"] == 4 + assert spec.counts["components"] == 2 + assert spec.counts["plates"] == 1 + # Collapsing never changes what the model actually samples. + assert spec.counts["unique_sampled_scalars"] == 9 + + +def test_r1_a_different_prior_configuration_stays_out_of_the_plate(): + first, odd, third, fourth = _gaussians(4) + odd.centre = af.UniformPrior(lower_limit=0.0, upper_limit=2.0) + spec = GraphSpec.from_model(af.Collection([first, odd, third, fourth])) + + # Declaration order is preserved: the plate takes its first member's slot. + assert [child.path for child in spec.root.children] == [("0",), ("1",)] + plate, loner = spec.root.children + assert plate.plate.count == 3 + assert plate.plate.member_paths == (("0",), ("2",), ("3",)) + assert plate.plate.representative_key == "0, 2 - 3" + assert loner.plate is None + assert loner.path == ("1",) + + +def test_r1_ignores_prior_label_and_constant_values(): + models = _gaussians(3) + for index, model in enumerate(models): + # A hand-assigned prior picks up its own `_label` counter; R1 must not + # see it, and the configuration is identical to the default. + model.normalization = af.LogUniformPrior( + lower_limit=1e-06, upper_limit=1000000.0 + ) + model.sigma = float(index + 1) + + labels = {model.normalization._label for model in models} + assert len(labels) == 3 + + spec = GraphSpec.from_model(af.Collection(models)) + (plate,) = _plates(spec) + + assert plate.plate.count == 3 + # The differing constants are *named*, never silently merged away. + assert plate.plate.varies_by_member == ("sigma",) + assert "sigma fixed (varies by member)" in plate.plate.repeats[0] + assert plate.rows[-1].value == 1.0 + # Every member's fixed slot is still counted. + assert spec.counts["fixed_leaf_slots"] == 3 + + +# ------------------------------------------------------------------ R2 + + +def test_r2_cross_member_sharing_splits_the_plate(): + models = _gaussians(4) + centre = af.UniformPrior(**CONFIGURED_CENTRE) + left = af.UniformPrior(**CONFIGURED_SIGMA) + right = af.UniformPrior(**CONFIGURED_SIGMA) + for model in models: + model.centre = centre + models[0].sigma = left + models[1].sigma = left + models[2].sigma = right + models[3].sigma = right + + spec = GraphSpec.from_model(af.Collection(models)) + plates = _plates(spec) + + assert [plate.plate.count for plate in plates] == [2, 2] + assert [plate.plate.representative_key for plate in plates] == ["0 - 1", "2 - 3"] + assert [plate.plate.member_paths for plate in plates] == [ + (("0",), ("1",)), + (("2",), ("3",)), + ] + # The centre is in *every* member of the candidate plate, so it does not + # discriminate and never splits it; what splits is `left` against `right`. + # `shared_in_all` is then reported for each *resulting* plate, where the + # discriminating prior is itself carried by every member. + assert plates[0].plate.shared_in_all == tuple(sorted((centre.id, left.id))) + assert plates[1].plate.shared_in_all == tuple(sorted((centre.id, right.id))) + + +def test_r2_a_prior_in_every_member_does_not_split(): + models = _gaussians(4) + centre = af.UniformPrior(**CONFIGURED_CENTRE) + for model in models: + model.centre = centre + + spec = GraphSpec.from_model(af.Collection(models)) + (plate,) = _plates(spec) + + assert plate.plate.count == 4 + assert plate.plate.shared_in_all == (centre.id,) + assert "centre ⇄ shared" in plate.plate.repeats[0] + + +def test_r2_a_prior_shared_only_inside_one_member_does_not_split(): + pairs = [ + af.Model( + Pair, + first=af.Model(af.ex.Gaussian), + second=af.Model(af.ex.Gaussian), + ) + for _ in range(3) + ] + # Both occurrences are inside member 0, so this is not cross-member sharing. + pairs[0].first.centre = pairs[0].second.centre + + spec = GraphSpec.from_model(af.Collection(pairs)) + outer = [node for node in _plates(spec) if node.cls_name == "Pair"] + + assert len(outer) == 1 + assert outer[0].plate.count == 3 + assert outer[0].plate.shared_in_all == () + + +# ------------------------------------------------------------------ safety + + +def test_safety_a_member_with_a_relation_leaves_the_plate(): + models = _gaussians(3) + models[1].centre = models[1].normalization + models[1].sigma + + spec = GraphSpec.from_model(af.Collection(models)) + + assert [child.path for child in spec.root.children] == [("0",), ("1",)] + plate, relation_member = spec.root.children + assert plate.plate.count == 2 + assert plate.plate.member_paths == (("0",), ("2",)) + assert relation_member.plate is None + assert relation_member.rows[0].provenance.kind == "relation" + + +def test_safety_relations_that_differ_only_in_operand_location_split(): + """ + The safety condition, not R1: both members carry a ``MultiplePrior`` at the + same relative path with the same configuration, so their *rows* are + indistinguishable. What differs is where the operand lives -- inside the + member for one, outside the plate for the other -- and a plate must preserve + relations across its members. + """ + inside, outside, plain = _gaussians(3) + scale = af.Model(Scale, factor=af.UniformPrior(**CONFIGURED_SIGMA)) + + inside.centre = inside.sigma * 2.0 + outside.centre = scale.factor * 2.0 + + spec = GraphSpec.from_model( + af.Collection(inside=inside, outside=outside, plain=plain, scale=scale) + ) + + assert [child.path for child in spec.root.children] == [ + ("inside",), + ("outside",), + ("plain",), + ("scale",), + ] + assert all(child.plate is None for child in spec.root.children) + + +def test_safety_a_member_touched_by_an_assertion_leaves_the_plate(): + models = _gaussians(3) + model = af.Collection(models) + model.add_assertion(models[0].sigma > 0.5) + + spec = GraphSpec.from_model(model) + + assert len(spec.assertions) == 1 + assert [child.path for child in spec.root.children] == [("0",), ("1",)] + asserted, plate = spec.root.children + assert asserted.plate is None + assert plate.plate.count == 2 + assert plate.plate.member_paths == (("1",), ("2",)) + + +def test_safety_a_member_sharing_outside_the_plate_leaves_it(): + models = _gaussians(3) + scale = af.Model(Scale, factor=af.UniformPrior(**CONFIGURED_SIGMA)) + model = af.Collection(a=models[0], b=models[1], c=models[2], scale=scale) + model.a.sigma = model.scale.factor + + spec = GraphSpec.from_model(model) + + assert [child.path for child in spec.root.children] == [ + ("a",), + ("b",), + ("scale",), + ] + leaver, plate, _ = spec.root.children + assert leaver.plate is None + assert plate.plate.count == 2 + assert plate.plate.member_paths == (("b",), ("c",)) + assert spec.counts["shared_priors"] == 1 + + +# ------------------------------------------------------------------ traps + + +def test_fixed_tuple_constants_and_model_int_survive_a_plate(): + blobs = [] + for index in range(3): + blob = af.Model( + Blob, + centre=(0.1 * index, 0.2 * index), + intensity=af.UniformPrior(lower_limit=0.0, upper_limit=1.0), + pixels=af.Model(int), + ) + blobs.append(blob) + + spec = GraphSpec.from_model(af.Collection(blobs)) + (plate,) = _plates(spec) + + assert plate.plate.count == 3 + assert plate.plate.varies_by_member == ("centre",) + + centre = spec.row(("0", "centre")) + assert centre.dimensionality == "tuple" + assert centre.sampling == "fixed" + assert [component.value for component in centre.components] == [0.0, 0.0] + assert [component.name for component in centre.components] == [ + "centre_0", + "centre_1", + ] + + # Rule R7: `af.Model(int)` is a row on its owner, never a component. + assert spec.node(("0", "pixels")) is None + assert spec.row(("0", "pixels")) is not None + assert [row.name for row in plate.rows] == ["centre", "intensity", "pixels"] + + # Nothing fixed is dropped: three members x (two tuple slots + `pixels`). + assert spec.counts["fixed_leaf_slots"] == 9 + + +def test_collections_are_frames_and_never_collapse(): + spec = GraphSpec.from_model( + af.Collection( + a=af.Collection(g=af.Model(af.ex.Gaussian)), + b=af.Collection(g=af.Model(af.ex.Gaussian)), + ) + ) + + assert [child.path for child in spec.root.children] == [("a",), ("b",)] + assert all(child.plate is None for child in spec.root.children) + # ... but the model children *inside* a collection still do. + assert spec.counts["plates"] == 0 + assert spec.counts["components"] == spec.counts["components_raw"] == 5 + + +def test_a_collections_model_children_do_collapse(): + spec = GraphSpec.from_model(af.Collection(outer=af.Collection(_gaussians(4)))) + (plate,) = _plates(spec) + + assert plate.path == ("outer", "0") + assert plate.plate.count == 4 + assert plate.plate.representative_key == "0 - 3" + + +# ------------------------------------------------------------------ contract + + +def test_collapse_false_leaves_everything_expanded(): + model = af.Collection(_gaussians(3)) + spec = GraphSpec.from_model(model, collapse=False) + + assert [child.path for child in spec.root.children] == [("0",), ("1",), ("2",)] + assert all(node.plate is None for node in spec.components()) + assert spec.counts["components"] == spec.counts["components_raw"] == 4 + assert spec.counts["plates"] == 0 + + +def test_the_path_index_records_both_partitions_for_a_plate(): + models = _gaussians(4) + centre = af.UniformPrior(**CONFIGURED_CENTRE) + left = af.UniformPrior(**CONFIGURED_SIGMA) + right = af.UniformPrior(**CONFIGURED_SIGMA) + for model in models: + model.centre = centre + models[0].sigma = models[1].sigma = left + models[2].sigma = models[3].sigma = right + + spec = GraphSpec.from_model(af.Collection(models)) + + # `model.info` groups the shared centre across all four; the figure's + # partition is finer (two plates), so both are recorded. + assert spec.path_index["0/centre"] == { + "figure": ["0 - 1/centre"], + "info": ["0 - 3/centre"], + } + # Where the two agree -- `sigma` is shared by exactly this plate's members, + # so `model.info` groups it the same way -- the plain tuple-of-paths shape + # is kept. + assert spec.path_index["0/sigma"] == (("0 - 1", "sigma"),) + # A row that resolves to exactly one path keeps the phase-1 shape too. + assert spec.path_index["0/normalization"] == { + "figure": ["0 - 1/normalization"], + "info": ["0/normalization", "1/normalization"], + } + + +def test_collapse_is_deterministic(): + def build(): + models = _gaussians(6) + centre = af.UniformPrior(**CONFIGURED_CENTRE) + for model in models: + model.centre = centre + left = af.UniformPrior(**CONFIGURED_SIGMA) + right = af.UniformPrior(**CONFIGURED_SIGMA) + for model in models[:3]: + model.sigma = left + for model in models[3:]: + model.sigma = right + return af.Collection(models) + + model = build() + first = json.dumps(GraphSpec.from_model(model).to_dict()) + second = json.dumps(GraphSpec.from_model(model).to_dict()) + + assert first == second + assert [plate.plate.count for plate in _plates(GraphSpec.from_model(model))] == [ + 3, + 3, + ] diff --git a/test_autofit/graph_spec/test_determinism.py b/test_autofit/graph_spec/test_determinism.py new file mode 100644 index 000000000..64d25dbf2 --- /dev/null +++ b/test_autofit/graph_spec/test_determinism.py @@ -0,0 +1,214 @@ +""" +Determinism and layer-purity of the semantic extraction. + +Determinism is part of the epic's acceptance: the same model must serialise to +byte-identical output every time, including ordering, and the *same model built +again* (after an id reset) must too -- otherwise no figure can be diffed or +committed as evidence. +""" + +import itertools +import json +import subprocess +import sys + +import autofit as af +from autofit.example.model import PhysicalNFW +from autofit.graph_spec import GraphSpec + +from .conftest import NullAnalysis + + +def _reset_ids(): + af.ModelObject._ids = itertools.count() + af.Prior._ids = itertools.count() + + +class Wrapper: + def __init__(self, centre=(0.0, 0.0), pixels=10, normalization=1.0): + self.centre = centre + self.pixels = pixels + self.normalization = normalization + + +def _rich_model(): + """ + One model exercising every extraction path: nesting, sharing, a relation, an + assertion, tuple priors, a fixed tuple constant, a ``Model(int)`` and an + instance leaf. + """ + first = af.Model(af.ex.Gaussian) + second = af.Model(af.ex.Gaussian) + second.centre = first.centre + second.sigma = first.normalization * 2.0 + + nfw = af.Model(PhysicalNFW) + wrapper = af.Model( + Wrapper, + centre=(0.1, 0.2), + pixels=af.Model(int), + normalization=af.UniformPrior(lower_limit=0.0, upper_limit=1.0), + ) + + model = af.Collection( + first=first, + second=second, + nfw=nfw, + wrapper=wrapper, + instance=af.ex.Gaussian(centre=1.0, normalization=2.0, sigma=3.0), + ) + model.add_assertion(first.sigma > 0.5) + return model + + +def test_extracting_twice_is_byte_identical(): + model = _rich_model() + + first = json.dumps(GraphSpec.from_model(model).to_dict()) + second = json.dumps(GraphSpec.from_model(model).to_dict()) + + assert first == second + + +def test_rebuilding_the_model_is_byte_identical(): + first = json.dumps(GraphSpec.from_model(_rich_model()).to_dict()) + + _reset_ids() + second = json.dumps(GraphSpec.from_model(_rich_model()).to_dict()) + + assert first == second + + +def test_factor_graph_extraction_is_deterministic(): + def build(): + model_1 = af.Model(af.ex.Gaussian) + model_2 = model_1.copy() + model_2.sigma = af.UniformPrior(lower_limit=0.0, upper_limit=1.0) + return af.FactorGraphModel( + af.AnalysisFactor(prior_model=model_1, analysis=NullAnalysis()), + af.AnalysisFactor(prior_model=model_2, analysis=NullAnalysis()), + ).global_prior_model + + first = json.dumps(GraphSpec.from_model(build()).to_dict()) + _reset_ids() + second = json.dumps(GraphSpec.from_model(build()).to_dict()) + + assert first == second + + +def test_fixed_tuple_constant_and_model_int_are_never_dropped(): + """ + Both vanished from the prototype's figure, and their absence reads as + absence from the model. They are rows. + """ + spec = GraphSpec.from_model( + af.Model( + Wrapper, + centre=(0.1, 0.2), + pixels=af.Model(int), + normalization=af.UniformPrior(lower_limit=0.0, upper_limit=1.0), + ) + ) + + centre = spec.row(("centre",)) + assert centre is not None + assert centre.dimensionality == "tuple" + assert centre.sampling == "fixed" + assert [component.value for component in centre.components] == [0.1, 0.2] + assert [component.name for component in centre.components] == [ + "centre_0", + "centre_1", + ] + # `model.info` prints the whole tuple on one line, so both slots resolve to + # the grouped parent path. + assert spec.path_index["centre/centre_0"] == (("centre",),) + + pixels = spec.row(("pixels",)) + assert pixels is not None + # Rule R7: `Model(int)` is a row on its owner, never a component. + assert spec.node(("pixels",)) is None + assert pixels.prior_cls_name == "int" + # A zero-parameter `Model(int)` prints nothing in `model.info`, so the row + # is an explicit added annotation. + assert pixels.in_model_info is False + assert spec.path_index["pixels"] == () + + # Two fixed tuple slots + the `Model(int)` slot. + assert spec.counts["fixed_leaf_slots"] == 3 + assert spec.counts["unique_sampled_scalars"] == 1 + + +def test_missing_configuration_is_its_own_state(): + class Unconfigured: + def __init__(self, areas_factor=1.0): + self.areas_factor = areas_factor + + spec = GraphSpec.from_model(af.Model(Unconfigured)) + row = spec.row(("areas_factor",)) + + assert row.sampling == "missing" + assert row.prior_cls_name == "ConfigException" + # A missing value *is* in `model.info` -- it is never silently absent. + assert row.in_model_info is True + assert spec.path_index["areas_factor"] == (("areas_factor",),) + assert spec.counts["missing"] == 1 + + +def test_solved_paths_are_marked_absent_from_model_info(): + spec = GraphSpec.from_model( + af.Collection(gaussian=af.Model(af.ex.Gaussian)), + solved_paths=("gaussian.normalization",), + ) + row = spec.row(("gaussian", "normalization")) + + assert row.sampling == "solved" + assert row.in_model_info is False + assert spec.path_index["gaussian/normalization"] == () + + +def test_collapse_is_on_by_default_and_can_be_turned_off(): + """ + Phase 1 accepted ``collapse`` and ignored it; the collapse phase fills it in. + ``collapse=False`` must still return the *uncollapsed* tree unchanged -- it + is the tree every catalogue construct is asserted against. + """ + model = af.Collection( + a=af.Model(af.ex.Gaussian), + b=af.Model(af.ex.Gaussian), + ) + collapsed = GraphSpec.from_model(model, collapse=True) + expanded = GraphSpec.from_model(model, collapse=False) + + assert json.dumps(collapsed.to_dict()) != json.dumps(expanded.to_dict()) + assert json.dumps(GraphSpec.from_model(model).to_dict()) == json.dumps( + collapsed.to_dict() + ) + + assert all(node.plate is None for node in expanded.components()) + assert expanded.counts["components"] == expanded.counts["components_raw"] == 3 + assert expanded.counts["plates"] == 0 + + assert [node.plate.count for node in collapsed.components() if node.plate] == [2] + assert collapsed.counts["components"] == 2 + assert collapsed.counts["components_raw"] == 3 + assert collapsed.counts["plates"] == 1 + + +def test_importing_graph_spec_does_not_import_matplotlib(): + """ + Layer 1 knows nothing about pixels: importing it must not drag a drawing + library in. Checked in a *fresh* interpreter, since the test session has + already imported matplotlib. + """ + result = subprocess.run( + [ + sys.executable, + "-c", + "import sys; import autofit.graph_spec; " + "print([m for m in sys.modules if m.split('.')[0] == 'matplotlib'])", + ], + capture_output=True, + text=True, + check=True, + ) + assert result.stdout.strip() == "[]"