diff --git a/autofit/graph_spec.py b/autofit/graph_spec.py index 22622012b..2a58688e5 100644 --- a/autofit/graph_spec.py +++ b/autofit/graph_spec.py @@ -72,9 +72,13 @@ ``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 + supplies the domain rules), ``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*). + ``model.info`` prints as *Prior Missing: Enter Manually or Add to Config*) + or ``observed`` (the data an ``AnalysisFactor``'s analysis carries -- not a + parameter at all, and emitted only by the graphical pass below, because + observed data and a fixed model constant are different concepts and must + not share an encoding). ``sharing`` ``prior_id`` plus :attr:`ParamRow.occurrences`, *every* path at which the same ``Prior`` object appears, and :attr:`ParamRow.direct_occurrences`, the @@ -111,12 +115,58 @@ A row a *class* declared through ``__solved_parameters__``, or a ``solved_paths=`` entry that matched no row and was synthesised. 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``). +``hierarchical-draw`` + A parameter **drawn** from a hierarchical factor's distribution: it carries + the expression ``"~ GaussianPrior(mean, sigma)"`` and, as its one operand, + the dotted path of the hyper node it is drawn from. Emitted by the + graphical pass below, and paired with a :class:`DrawEdge`. A draw is + **not** sharing. +``observed`` + The observed data an analysis carries, emitted by the graphical pass. Not + part of the model, hence ``in_model_info=False``. +``user-prior``, ``assertion`` + **Reserved and not emitted.** ``assertion`` operands are carried by + :class:`AssertionEdge` (assertions are edges, never rows). + +The graphical pass +------------------ + +A ``FactorGraphModel``'s ``global_prior_model`` is a ``GlobalPriorModel``: a +``Collection`` of one prior model per *model factor*, carrying the declarative +factor ``graph`` it was built from. When the root is one, +:meth:`_Extractor._graphical_pass` rewrites the raw walk as **plate notation**, +after the walk and before the collapse. Nothing of the ``graphical`` package is +imported: the factor graph is duck-typed exactly as ``__solved_parameters__`` is +probed, and ``factor.graph`` -- which **rebuilds on every access** and renames +its ``PriorFactor``s -- is read **exactly once**. + +*A draw is not sharing.* A ``HierarchicalFactor`` generates one +``_HierarchicalFactor`` per drawn variable, and each is a ``Collection`` of the +shared ``distribution_model`` and the ``drawn_prior`` -- and that drawn prior +**is the dataset model's own parameter object**. Left alone, the walk therefore +reports the dataset's ``centre`` as a prior shared with the factor collection, +which claims the exact opposite of what a draw says: sharing means *the same +number in every dataset*, a draw means *a different number in every dataset, +from a common population*. So those occurrences are stripped from the +occurrence maps (no :class:`SharedEdge`, no broken plate), the row is re-tagged +``hierarchical-draw`` while staying ``free``, and the relationship is carried by +a :class:`DrawEdge` instead. + +*Hyper nodes are hoisted.* The per-draw collections are dropped and replaced by +**one** ``kind="hyper"`` node per distinct distribution model, emitted at the +**front** of the root's children. This is the single documented exception to +the ordering contract above, and it applies to the graphical view only; the +``model.info`` paths each hyper node stands for are recorded in +:attr:`GraphSpec.path_index`. + +*Observed data is its own state.* Each ``AnalysisFactor`` child records a +:class:`FactorInfo`, and an analysis exposing ``data`` / ``dataset`` contributes +one ``observed`` row. + +The counts gain ``datasets``, ``hyper_parameters``, ``shared_across_datasets``, +``per_dataset`` and ``observed``, so a footer can say *two free +hyper-parameters* **plus** *three parameters per dataset* rather than one +undifferentiated total. Class-declared semantics -- the ``__solved_parameters__`` protocol ------------------------------------------------------------------ @@ -294,10 +344,12 @@ "Provenance", "ParamRow", "PlateInfo", + "FactorInfo", "ComponentNode", "SharedEdge", "RelationEdge", "AssertionEdge", + "DrawEdge", "GraphSpec", "graph_spec_from", ] @@ -487,6 +539,25 @@ def to_dict(self) -> dict: } +@dataclass(frozen=True) +class FactorInfo: + """ + The declarative factor a node stands for (the graphical pass only). + + ``kind`` is ``analysis`` for an ``AnalysisFactor``'s dataset model and + ``hierarchical`` for the hyper-parameter node a ``HierarchicalFactor``'s + distribution model becomes. ``name`` is the factor's own name + (``AnalysisFactor0``, ``HierarchicalFactor0``), which is stable and unique + for an ``AnalysisFactor``. + """ + + name: str + kind: str + + def to_dict(self) -> dict: + return {"name": self.name, "kind": self.kind} + + @dataclass(frozen=True) class ComponentNode: """ @@ -497,6 +568,10 @@ class ComponentNode: ``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. + + ``kind`` is ``model`` / ``collection`` / ``global`` / ``hyper``, the last + being a hyper-parameter node synthesised by the graphical pass (the module + docstring). ``factor`` is set by that pass only. """ path: Path @@ -507,6 +582,7 @@ class ComponentNode: rows: Tuple[ParamRow, ...] = () children: Tuple["ComponentNode", ...] = () plate: Optional[PlateInfo] = None + factor: Optional[FactorInfo] = None def to_dict(self) -> dict: return { @@ -518,6 +594,7 @@ def to_dict(self) -> dict: "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, + "factor": self.factor.to_dict() if self.factor is not None else None, } @@ -553,6 +630,31 @@ def to_dict(self) -> dict: } +@dataclass(frozen=True) +class DrawEdge: + """ + A hierarchical **draw**: ``target_path`` is drawn *from* the distribution + parameterised at ``source_path``. + + A draw is **not** sharing (module docstring, "The graphical pass"): the two + claims are opposites, so a drawn parameter never carries a + :class:`SharedEdge` for the draw and its row is not ``shared``. + """ + + source_path: Path + target_path: Path + prior_id: Optional[int] = None + expression: Optional[str] = None + + def to_dict(self) -> dict: + return { + "source_path": list(self.source_path), + "target_path": list(self.target_path), + "prior_id": self.prior_id, + "expression": self.expression, + } + + @dataclass(frozen=True) class AssertionEdge: """ @@ -861,6 +963,125 @@ def __init__(self, model, analysis=None, solved_paths: Sequence = ()): self.prior_config[prior.id] = _prior_configuration(prior) self._known_component_paths = set() + self._read_factor_graph() + self._rewrite_graphical_occurrences() + + # -- the graphical pass ------------------------------------------------- + + def _read_factor_graph(self) -> None: + """ + Read the declarative factor graph **exactly once**, if there is one. + + ``FactorGraphModel.graph`` rebuilds on every access and renames its + ``PriorFactor``s, so a second read would silently change the names a + figure quotes. ``hasattr(type(factor), "graph")`` probes the *class*, + which does not invoke the property -- nothing here imports the + ``graphical`` package (duck typing, exactly as the + ``__solved_parameters__`` protocol probes a class attribute). + """ + self.graph = None + self.model_factors: List[Any] = [] + #: ``(dataset index, distribution model, drawn prior)`` per draw. + self.draws: List[Tuple[int, Any, Prior]] = [] + #: distribution model -> the path its hyper node is emitted at. + self.hyper_models: List[Any] = [] + self.hyper_paths: Dict[int, Path] = {} + #: hyper node path -> the ``model.info`` paths it replaces. + self.hyper_info_paths: Dict[Path, Tuple[Path, ...]] = {} + #: one edge per draw, in dataset order; filled by :meth:`_tag_draws`. + self.draw_edges: Tuple[DrawEdge, ...] = () + + if _kind(self.model) != "global": + return + factor = getattr(self.model, "factor", None) + if factor is None or not hasattr(type(factor), "graph"): + return + self.graph = factor.graph + self.model_factors = list(getattr(factor, "model_factors", ()) or ()) + + for index, model_factor in enumerate(self.model_factors): + distribution = getattr(model_factor, "distribution_model", None) + drawn = getattr(model_factor, "drawn_prior", None) + if distribution is not None and isinstance(drawn, Prior): + self.draws.append((index, distribution, drawn)) + + # One hyper node per *distinct* distribution model, in the order the + # graph declares its hierarchical factors (falling back to the order the + # draws appear in). + declared = list(getattr(self.graph, "hierarchical_factors", ()) or ()) + ordered: List[Any] = [] + for distribution in declared + [draw[1] for draw in self.draws]: + if not any(distribution is seen for seen in ordered): + ordered.append(distribution) + ordered = [ + distribution + for distribution in ordered + if any(distribution is draw[1] for draw in self.draws) + ] + self.hyper_models = ordered + + used: set = set() + for number, distribution in enumerate(ordered): + name = str(getattr(distribution, "name", "") or "") or f"hyper_{number}" + while name in used: + name = f"{name}_{number}" + used.add(name) + self.hyper_paths[id(distribution)] = (name,) + self.hyper_info_paths = { + self.hyper_paths[id(distribution)]: tuple( + (str(index), "distribution_model") + for index, drawn_from, _ in self.draws + if drawn_from is distribution + ) + for distribution in ordered + } + + def _rewrite_graphical_occurrences(self) -> None: + """ + Fold the ``_HierarchicalFactor`` collections out of the occurrence maps. + + Two rewrites, both of them statements about *sharing*: + + * every occurrence under ``("i", "drawn_prior")`` is **dropped** -- the + draw is carried by a :class:`DrawEdge` and the ``hierarchical-draw`` + provenance, and counting it as a second use of the parameter would + emit a :class:`SharedEdge` claiming the opposite (the datasets have + *the same* centre) of what a draw says, and would break the dataset + plate's safety condition into the bargain; + * every occurrence under ``("i", "distribution_model")`` is **rewritten** + onto the one hyper node those collections collapse into, so the + distribution's own ``mean`` and ``sigma`` are one occurrence each + rather than one per draw. + """ + if not self.draws: + return + drop: List[Path] = [] + rewrite: List[Tuple[Path, Path]] = [] + for index, distribution, _ in self.draws: + drop.append((str(index), "drawn_prior")) + rewrite.append( + ( + (str(index), "distribution_model"), + self.hyper_paths[id(distribution)], + ) + ) + + def _rewritten(paths: Tuple[Path, ...]) -> Tuple[Path, ...]: + out: List[Path] = [] + for path in paths: + if any(path[: len(prefix)] == prefix for prefix in drop): + continue + for prefix, replacement in rewrite: + if path[: len(prefix)] == prefix: + path = replacement + path[len(prefix) :] + break + if path not in out: + out.append(path) + return tuple(out) + + for mapping in (self.occurrences, self.direct_occurrences): + for prior_id, paths in list(mapping.items()): + mapping[prior_id] = _rewritten(paths) # -- components --------------------------------------------------------- @@ -904,10 +1125,170 @@ def build_root(self) -> ComponentNode: 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 + return self._graphical_pass( + self._node( + (), by_path[()], "model", by_path=by_path, children_of=children_of + ) ) + # -- the graphical pass ------------------------------------------------- + + def _graphical_pass(self, root: ComponentNode) -> ComponentNode: + """ + Rewrite the raw walk of a ``GlobalPriorModel`` as plate notation. + + Runs **after** the walk and **before** the collapse, so the plate rules + read a tree in which a draw is already a draw rather than a shared + prior. Four things happen, and nothing happens at all when the model is + not a factor graph: + + 1. the ``_HierarchicalFactor`` children -- one ``Collection`` per drawn + variable -- are dropped, and one ``hyper`` node per distinct + distribution model is emitted at the **front** of the root's + children. This hoist is the one documented exception to the + ordering contract, and it applies to the graphical view only; + 2. every drawn row is re-tagged ``hierarchical-draw`` and gains a + :class:`DrawEdge`, keeping ``sampling="free"`` -- it is still a + sampled parameter; + 3. each ``AnalysisFactor`` child records its :class:`FactorInfo`; + 4. an analysis exposing ``data`` / ``dataset`` contributes an + ``observed`` row, so observed data is never encoded as ``fixed``. + """ + if not self.model_factors: + return root + + drawn_children = {str(index) for index, _, _ in self.draws} + children = [ + self._dataset_child(child) + for child in root.children + if child.name not in drawn_children + ] + hyper_nodes = [ + self._hyper_node(distribution) for distribution in self.hyper_models + ] + root = replace(root, children=tuple(hyper_nodes) + tuple(children)) + return self._tag_draws(root, hyper_nodes) + + def _hyper_node(self, distribution) -> ComponentNode: + """ + The hyper-parameter node one ``HierarchicalFactor`` becomes. + + Its rows are the distribution model's own priors, walked exactly as any + other component's are -- ``mean`` and ``sigma`` of the + ``GaussianPrior`` the drawn variables come from. + """ + path = self.hyper_paths[id(distribution)] + node = self._node(path, distribution, path[-1], by_path={}, children_of={}) + return replace( + node, + kind="hyper", + factor=FactorInfo(name=path[-1], kind="hierarchical"), + ) + + def _dataset_child(self, child: ComponentNode) -> ComponentNode: + """The ``AnalysisFactor`` info, and the observed-data row if there is one.""" + model_factor = self._model_factor_for(child) + if model_factor is None: + return child + rows = list(child.rows) + analysis = getattr(model_factor, "analysis", None) + if analysis is not None and analysis is not model_factor: + for attribute in ("data", "dataset"): + try: + observed = getattr(analysis, attribute, None) + except Exception: # pragma: no cover - a broken analysis + observed = None + if observed is None: + continue + rows.append( + ParamRow( + name=attribute, + path=child.path + (attribute,), + sampling="observed", + provenance=Provenance("observed"), + in_model_info=False, + ) + ) + break + return replace( + child, + rows=tuple(rows), + factor=FactorInfo( + name=str(getattr(model_factor, "name", "") or child.name), + kind="analysis", + ), + ) + + def _model_factor_for(self, child: ComponentNode): + """The model factor a root child was built from, by position.""" + if not child.path or not child.name.isdigit(): + return None + index = int(child.name) + if index >= len(self.model_factors): + return None + return self.model_factors[index] + + def _tag_draws( + self, root: ComponentNode, hyper_nodes: List[ComponentNode] + ) -> ComponentNode: + """ + Re-tag every drawn row and record one :class:`DrawEdge` per draw. + + The drawn ``Prior`` *is* the dataset model's own parameter object, so + the row is found by prior id inside the dataset child the draw names. + """ + by_distribution = { + id(distribution): node + for distribution, node in zip(self.hyper_models, hyper_nodes) + } + targets: Dict[int, Tuple[Path, Provenance]] = {} + for index, distribution, prior in self.draws: + hyper = by_distribution.get(id(distribution)) + if hyper is None: # pragma: no cover - defensive + continue + expression = "~ {}({})".format( + hyper.cls_name, ", ".join(row.name for row in hyper.rows) + ) + targets[prior.id] = ( + hyper.path, + Provenance( + "hierarchical-draw", + expression=expression, + operands=(_dotted(hyper.path),), + ), + ) + + drawn_paths: Dict[int, Path] = {} + + def _row(row: ParamRow) -> ParamRow: + target = targets.get(row.prior_id) + if target is None or row.provenance.kind != "config-default": + return row + drawn_paths.setdefault(row.prior_id, row.path) + return replace(row, provenance=target[1]) + + def _walk(node: ComponentNode) -> ComponentNode: + if node.kind == "hyper": + return node + return replace( + node, + rows=tuple(_row(row) for row in node.rows), + children=tuple(_walk(child) for child in node.children), + ) + + root = _walk(root) + self.draw_edges = tuple( + DrawEdge( + source_path=targets[prior.id][0], + target_path=drawn_paths[prior.id], + prior_id=prior.id, + expression=targets[prior.id][1].expression, + ) + for _, _, prior in self.draws + if prior.id in drawn_paths and prior.id in targets + ) + return root + def _node(self, path: Path, obj, name: str, by_path, children_of) -> ComponentNode: rows: List[ParamRow] = [] children: List[ComponentNode] = [] @@ -1355,6 +1736,69 @@ def attach_latents(self, root: ComponentNode) -> ComponentNode: ) return _attach_rows(root, by_owner) + # -- graphical counts --------------------------------------------------- + + def graphical_counts(self, raw_root: ComponentNode) -> Dict[str, int]: + """ + The graphical half of the reconciling counts, of the **uncollapsed** + tree -- so they are the same whether or not the plate formed. + + ``hyper_parameters`` + ``shared_across_datasets`` + + ``per_dataset`` x ``datasets`` reconciles to + ``unique_sampled_scalars``: the point of the split is that a + hyper-parameter is *not* one of the per-dataset parameters, and the + footer must say so (review: "include the two free hyperparameters in + the accounting, separately from the three parameters per dataset"). + + A prior counts as **shared across datasets** when it occurs under every + dataset child -- through a relation too, which is how + ``sigma = sigma_m * x + sigma_c`` adds no parameters per dataset. + """ + if not self.model_factors: + return {} + datasets = [ + child + for child in raw_root.children + if child.factor is not None and child.factor.kind == "analysis" + ] + if not datasets: + return {} + + owners: Dict[int, set] = {} + for prior_id, paths in self.occurrences.items(): + for path in paths: + if path and any(path[0] == child.name for child in datasets): + owners.setdefault(prior_id, set()).add(path[0]) + shared = { + prior_id + for prior_id, names in owners.items() + if len(names) == len(datasets) and len(datasets) > 1 + } + first = datasets[0].name + per_dataset = len( + { + prior_id + for prior_id, names in owners.items() + if first in names and prior_id not in shared + } + ) + hyper = sum( + _free_scalars(child) for child in raw_root.children if child.kind == "hyper" + ) + observed = sum( + 1 + for node in _walk_nodes(raw_root) + for row in node.rows + if row.provenance.kind == "observed" + ) + return { + "datasets": len(datasets), + "hyper_parameters": hyper, + "shared_across_datasets": len(shared), + "per_dataset": per_dataset, + "observed": observed, + } + # -- solved paths ------------------------------------------------------- def attach_solved_paths(self, root: ComponentNode) -> ComponentNode: @@ -1389,6 +1833,20 @@ def attach_solved_paths(self, root: ComponentNode) -> ComponentNode: return _attach_rows(root, by_owner) +def _free_scalars(node: ComponentNode) -> int: + """Every sampled scalar in a subtree, tuple slots counted one by one.""" + total = 0 + for current in _walk_nodes(node): + for row in current.rows: + if row.dimensionality == "tuple": + total += sum( + 1 for component in row.components if component.sampling == "free" + ) + elif row.sampling == "free": + total += 1 + return total + + def _tuple_sampling(components: Tuple[ParamRow, ...]) -> str: """ A tuple row's own sampling status: ``free`` if any slot is sampled, else @@ -1744,7 +2202,12 @@ def _repeats( prior_ids = {row.prior_id} | { component.prior_id for component in row.components } - if prior_ids & shared_within: + if row.provenance.kind == "hierarchical-draw": + # A draw is not sharing, so it is never described as one. + described.append(f"{name} \u25c2 drawn") + elif row.provenance.kind == "observed": + described.append(f"{name} observed") + elif 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)") @@ -1888,6 +2351,8 @@ class GraphSpec: shared: Tuple[SharedEdge, ...] = () relations: Tuple[RelationEdge, ...] = () assertions: Tuple[AssertionEdge, ...] = () + #: hierarchical draws, in dataset order (the graphical pass only). + draws: Tuple[DrawEdge, ...] = () #: 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) @@ -1941,9 +2406,14 @@ def from_model( shared=extractor.shared_edges(), relations=extractor.relation_edges(), assertions=extractor.assertion_edges(), + draws=extractor.draw_edges, + ) + object.__setattr__( + spec, "path_index", _path_index(spec, model, extractor.hyper_info_paths) ) - object.__setattr__(spec, "path_index", _path_index(spec, model)) - object.__setattr__(spec, "counts", _counts(model, spec, raw_root)) + counts = _counts(model, spec, raw_root) + counts.update(extractor.graphical_counts(raw_root)) + object.__setattr__(spec, "counts", counts) return spec # -- convenience -------------------------------------------------------- @@ -1991,6 +2461,7 @@ def to_dict(self) -> 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], + "draws": [edge.to_dict() for edge in self.draws], "path_index": { key: ( entry if isinstance(entry, dict) else [list(path) for path in entry] @@ -2061,7 +2532,7 @@ def _group_paths(paths: Sequence[Path]) -> Tuple[Path, ...]: ) -def _path_index(spec: GraphSpec, model) -> Dict[str, Any]: +def _path_index(spec: GraphSpec, model, hyper_paths=None) -> Dict[str, Any]: """ element key -> the ``model.info`` paths it resolves to. @@ -2080,6 +2551,7 @@ def _path_index(spec: GraphSpec, model) -> Dict[str, Any]: than hiding it"). When the two agree the plain tuple shape is used. """ index: Dict[str, Any] = {} + hyper_paths = hyper_paths or {} info_map = _info_group_map(model) if _has_plate(spec.root) else {} def _entry(concrete: Tuple[Path, ...]) -> Any: @@ -2118,6 +2590,13 @@ def _walk(node: ComponentNode, concrete: Tuple[Path, ...]): suffix = row.path[len(node.path) :] _add_row(row, tuple(path + suffix for path in concrete)) for child in node.children: + if child.path in hyper_paths: + # The correspondence contract for a hoisted hyper node: it + # stands for the ``_HierarchicalFactor`` collections + # ``model.info`` prints, one per draw, and that mapping is + # recorded rather than hidden. + _walk(child, hyper_paths[child.path]) + continue if child.plate is not None: suffixes = [ member[len(node.path) :] for member in child.plate.member_paths diff --git a/autofit/model_figure/layout.py b/autofit/model_figure/layout.py index 9ac704c40..5f3454d01 100644 --- a/autofit/model_figure/layout.py +++ b/autofit/model_figure/layout.py @@ -574,6 +574,17 @@ def _walk(card, top): for card in cards: _walk(card, card) + + # A card is an anchor too: a hierarchical draw leaves the hyper card as a + # whole (its parameters *jointly* define the distribution) and lands on one + # pill. Pills win any collision, so this only ever adds anchors. + def _anchor(card, top): + index.setdefault(card.key, (card, top)) + for child in card.children: + _anchor(child, top) + + for card in cards: + _anchor(card, card) return index @@ -601,10 +612,24 @@ def _route(links, cards, content_right: float, style: Style): continue sy = round(source[0].y + source[0].height / 2, 4) ty = round(target[0].y + target[0].height / 2, 4) - if abs(sy - ty) < source[0].height: + if abs(sy - ty) < min(source[0].height, target[0].height): # Same visual row: the route would collapse to a meaningless stub in # the gutter, and the pill's own badge already names its owner. + # (``min`` so that a link anchored on a *card* -- a draw -- is judged + # by the pill it lands on, not by the height of the whole card.) continue + if link.kind == "draw": + route = _draw_route(source, target, style) + if route is not None: + routes.append( + LinkRoute( + source_key=link.source_key, + target_key=link.target_key, + kind=link.kind, + points=route, + ) + ) + continue lane = round(content_right + 0.12 + (number % lanes) * 0.17, 4) # Each end touches the right edge of the top-level card that holds its # pill, so the bracket is visibly attached to the frame it belongs to -- @@ -623,6 +648,34 @@ def _route(links, cards, content_right: float, style: Style): return tuple(routes) +def _draw_route(source, target, style: Style): + """ + A hierarchical draw's route: **into the plate, onto the pill**. + + The review is explicit that the parent distribution connects to ``centre_i`` + and not to the dataset frame, so this route does what the right-hand gutter + never does -- it crosses one card boundary and ends on the pill itself. It + hooks down the narrow lane in the left margin, which no card occupies, and + is used only when the pill starts its row, so the last segment runs over the + card's padding and nothing else. Any other pill falls back to the ordinary + gutter route (``None``). + """ + pill, top = target + if pill.x - (top.x + top.pad) > 0.03: + return None + lane = round(max(0.06, style.margin - 0.1), 4) + if source[1].x - lane < 0.05: # pragma: no cover - defensive + return None + sy = round(source[0].y + source[0].height / 2, 4) + ty = round(pill.y + pill.height / 2, 4) + return ( + (round(source[1].x, 4), sy), + (lane, sy), + (lane, ty), + (round(pill.x, 4), ty), + ) + + def _exit_edge(card: CardBox, cards, y: float) -> float: """ Where a link leaves ``card``: its right edge, unless a sibling top-level card @@ -660,11 +713,18 @@ def build_layout(presentation, style: Optional[Style] = None) -> LayoutTree: x = style.margin y = style.margin row_height = 0.0 + hoisted = False for card in measured: + # Plate notation draws what is *above* the plate above it: the hoisted + # shared priors and the hyper-parameter nodes take the first row, and + # the plate starts the next one. + above = card.kind in ("hoist", "hyper") if ( placed and x > style.margin - and x + card.width > style.margin + budget + 1e-9 + and ( + x + card.width > style.margin + budget + 1e-9 or (hoisted and not above) + ) ): x = style.margin y += row_height + style.card_gap @@ -672,6 +732,7 @@ def build_layout(presentation, style: Optional[Style] = None) -> LayoutTree: placed.append(_translate(card, x, y)) x += card.width + style.card_gap row_height = max(row_height, card.height) + hoisted = above content_bottom = y + row_height content_right = max((card.x + card.width for card in placed), default=style.margin) diff --git a/autofit/model_figure/presentation.py b/autofit/model_figure/presentation.py index 7fca54b47..3ba23e3ac 100644 --- a/autofit/model_figure/presentation.py +++ b/autofit/model_figure/presentation.py @@ -24,6 +24,29 @@ ``fixed, varies by member``; a free prior repeated independently across a plate's members is badged ``independent``. +Plate notation for a factor graph +--------------------------------- + +When the spec's root is a ``GlobalPriorModel`` (``kind == "global"``) the same +vocabulary is arranged as **plate notation**, and three further claims are kept +apart: + +* **a draw is not sharing.** A ``hierarchical-draw`` row is a violet + ``centre . drawn`` pill badged with the hyper node it came from, and a violet + **arrow** lands on that pill. ``-> shared`` says *the same number in every + dataset*; the draw arrow says *a different number in every dataset, from a + common population*. They never share a colour or a marker. +* **what is shared is drawn once, above the plate.** The priors every dataset + carries move into a hoisted ``shared across datasets`` card + (``kind="hoist"``) and the plate's own pill becomes a blue reference to it. +* **observed data is not a fixed constant.** An ``observed`` row is a green + ``data . observed`` pill, never the grey fixed one. + +The plate reads ``3 datasets`` / ``dataset 0 - 2``, the hyper nodes are +``kind="hyper"`` cards titled ``HierarchicalFactor0 . GaussianPrior``, and the +footer counts hyper-parameters separately from the per-dataset parameters. +Nothing above applies to a non-graphical model, whose presentation is unchanged. + Everything a card or pill stands for is keyed by its :attr:`~autofit.graph_spec.GraphSpec.path_index` key (the ``"/"``-joined path), so a static PNG stays navigable against ``model.info``. @@ -53,8 +76,8 @@ "compact_prior", ] -#: Pill states. ``observed`` and ``drawn`` are reserved for phases 4/5 and are -#: emitted only if layer 1 ever reports the matching provenance kinds. +#: Pill states. ``observed`` and ``drawn`` come from the graphical pass' own +#: provenance kinds, and appear only on a factor graph's figure. STATES = ( "free", "fixed", @@ -332,10 +355,28 @@ def __init__(self, spec, priors, detail): self.order.setdefault(_key(component.path), len(self.order)) self._record_occurrences(component) + #: row key -> the row itself, for the rules that need it back. + self.row_of: Dict[str, Any] = {} + for node, _, _ in _walk(spec.root): + for row in node.rows: + self.row_of.setdefault(_key(row.path), row) + for component in row.components: + self.row_of.setdefault(_key(component.path), component) + + #: drawn pill key -> the key of the hyper card it is drawn from. The + #: draw is looked up on the *representative*, because a plate draws only + #: its first member (the draw is the same statement for every member). + self.draws: Dict[str, str] = {} + for edge in getattr(spec, "draws", ()) or (): + target = _key(self.representative(edge.target_path)) + self.draws.setdefault(target, _key(edge.source_path)) + self.states: set = set() self.badges: set = set() #: referring pill key -> owner pill key, for the cross links. self.references: Dict[str, str] = {} + #: drawn pill key -> hyper card key, for the violet draw links. + self.draw_references: Dict[str, str] = {} def _record_occurrences(self, row): key = _key(row.path) @@ -482,8 +523,31 @@ def _is_group_shared(row, plate, context) -> bool: return False +def _draw_descriptor(row, context) -> Optional[str]: + """ + The badge a hierarchically drawn row carries: ``↗ HierarchicalFactor0``. + + It is deliberately *not* blue -- the pill is violet and so is its arrow, + because "drawn from a common population" and "the same number" are opposite + claims (review: "replace the shared marker with a hierarchical-draw + annotation"). + """ + if row.provenance.kind != "hierarchical-draw": + return None + key = _key(row.path) + source = context.draws.get(key) + if source is None: + return None + context.draw_references[key] = source + return f"↗ {_dotted(source)}" + + def _badge(row, node, plate, context) -> Optional[str]: - """The badge of a single (scalar) row: sharing first, independence second.""" + """The badge of a single (scalar) row: a draw first, then sharing, then + independence.""" + drawn = _draw_descriptor(row, context) + if drawn is not None: + return drawn shared = _shared_descriptor(row, node, plate, context) if shared is not None: return shared @@ -535,6 +599,12 @@ def _text(row, state, context) -> str: row.provenance.expression, row.provenance.operands ) return f"{name} = {expression}" + if state == "drawn": + # "drawn", never a sharing marker: a drawn parameter is a *different* + # number in every dataset, from a common population. + return f"{name} · drawn" + if state == "observed": + return f"{name} · observed" if state == "missing": return f"{name} · missing" if state == "solved": @@ -583,12 +653,24 @@ def _pill(row, node, plate, context) -> Pill: ) context.states.add(state) if pill.badge: - context.badges.add( - pill.badge.split(" ")[0] if pill.badge.startswith("↗") else pill.badge - ) + context.badges.add(_badge_token(pill)) return pill +def _badge_token(pill) -> str: + """ + The legend token a badge contributes. + + A draw badge is ``draw``, never ``↗``: it must not make the legend claim a + blue sharing badge is on the figure when nothing on it is shared. + """ + if pill.state == "drawn": + return "draw" + if pill.badge.startswith("↗"): + return "↗" + return pill.badge + + def _tuple_is_uniform(row, node, plate, context) -> bool: """ Whether a tuple's components agree on sampling *and* sharing. @@ -702,6 +784,12 @@ def _fold_summary(node) -> str: return f"… {components} components / {priors} priors" +def _is_dataset_plate(node) -> bool: + """Whether this plate's members are one ``AnalysisFactor``'s model each.""" + factor = getattr(node, "factor", None) + return node.plate is not None and factor is not None and factor.kind == "analysis" + + def _card(node, plate, depth, context, show_fixed, max_depth) -> Tuple[Card, int]: pills, hidden, redshift = _pills(node, plate, context, show_fixed) @@ -724,9 +812,16 @@ def _card(node, plate, depth, context, show_fixed, max_depth) -> Tuple[Card, int children.append(card) hidden += child_hidden + datasets = _is_dataset_plate(node) + subtitle = None if node.plate is not None: + # A plate over a factor graph's model factors repeats *datasets*, and a + # reader looking for dataset 2 must be able to find it: "dataset 0 - 2", + # not a bare index range. subtitle = node.plate.representative_key + if datasets and subtitle: + subtitle = f"dataset {subtitle}" if redshift: subtitle = f"{subtitle} · {redshift}" if subtitle else redshift elif redshift: @@ -741,9 +836,9 @@ def _card(node, plate, depth, context, show_fixed, max_depth) -> Tuple[Card, int if node.plate is not None: # "30 components", never "x30": a plate counts components, a badge on a # parameter counts uses of a parameter (review point 2). - badge = f"{node.plate.count} components" + badge = _plural(node.plate.count, "dataset" if datasets else "component") note = node.plate.repeats[0] if node.plate.repeats else None - context.badges.add("plate") + context.badges.add("datasets" if datasets else "plate") return ( Card( @@ -866,6 +961,15 @@ def _links(spec, presentation_keys, context) -> Tuple[Link, ...]: if pill_key in drawn and target in context.order: seen.add((pill_key, target)) links.append(Link(pill_key, target, "shared")) + for pill_key in sorted( + context.draw_references, key=lambda key: context.order.get(key, 0) + ): + # The arrow runs *from* the hyper card *to* the drawn pill, and lands on + # the pill -- not on the dataset frame (review, A_08). Its target is a + # card key, which the layout resolves like any other anchor. + source = context.draw_references[pill_key] + if pill_key in drawn: + links.append(Link(source, pill_key, "draw")) for relation in spec.relations: target = context.rendered(relation.target_path) if target is None: @@ -881,6 +985,126 @@ def _links(spec, presentation_keys, context) -> Tuple[Link, ...]: return tuple(links) +# -- rule: hoisting the shared priors of a factor graph ---------------------- + + +#: The key of the synthetic hoisted card. It cannot collide with a model path: +#: a ``GlobalPriorModel``'s children are list indices. +HOIST_KEY = "shared across datasets" + + +def _dataset_nodes(spec) -> List[Any]: + """The root children that stand for an ``AnalysisFactor``'s dataset model.""" + return [ + child + for child in spec.root.children + if getattr(child, "factor", None) is not None + and child.factor.kind == "analysis" + ] + + +def _shared_across_datasets(spec, nodes) -> List[int]: + """ + The prior ids drawn **once** above the plate. + + From the dataset plate's ``shared_in_all`` when the plate formed -- the ids + every member carries, which is exactly "one prior, N datasets" -- and + otherwise from the ids every dataset child holds directly. + """ + plate = next((node for node in nodes if node.plate is not None), None) + if plate is not None: + return list(plate.plate.shared_in_all) + if len(nodes) < 2: + return [] + per_node = [] + for node in nodes: + ids = set() + for current, _, _ in _walk(node): + for row in current.rows: + for candidate in (row,) + tuple(row.components): + if candidate.prior_id is not None and candidate.shared: + ids.add(candidate.prior_id) + per_node.append(ids) + common = set.intersection(*per_node) + return sorted(common) + + +def _hoist_shared(spec, cards, context) -> Tuple[Tuple[Card, ...], Tuple[Link, ...]]: + """ + Draw a factor graph's shared priors **once**, above the plate. + + Plate notation's whole point: a parameter outside the plate is one number + for every dataset. The owning pill moves to a hoisted + ``shared across datasets`` card and the plate's own pill becomes a + reference (``↗ shared``) with a blue link to it, so the figure states the + sharing in its layout rather than only in a badge. + """ + if spec.root.kind != "global": + return cards, () + nodes = _dataset_nodes(spec) + if not nodes: + return cards, () + shared_ids = _shared_across_datasets(spec, nodes) + if not shared_ids: + return cards, () + + drawn_pills = {pill.key: pill for card in _cards_of(cards) for pill in card.pills} + hoisted: List[Pill] = [] + links: List[Link] = [] + moved: Dict[str, Pill] = {} + keys_of: Dict[int, str] = {} + for key, pill in drawn_pills.items(): + row = context.row_of.get(key) + if row is None or row.prior_id not in shared_ids: + continue + hoist_key = keys_of.get(row.prior_id) + if hoist_key is None: + hoist_key = f"{HOIST_KEY}/{row.name}" + while any(existing.key == hoist_key for existing in hoisted): + hoist_key = f"{hoist_key}'" + keys_of[row.prior_id] = hoist_key + hoisted.append( + Pill(text=pill.text, state=pill.state, dim2d=pill.dim2d, key=hoist_key) + ) + # *Every* occurrence points at the hoisted pill, not at whichever member + # happened to come first: the parameter now lives above the plate. + moved[key] = Pill( + text=pill.text, + state=pill.state, + dim2d=pill.dim2d, + badge="↗ shared", + key=key, + ) + context.references.pop(key, None) + links.append(Link(key, hoist_key, "shared")) + if not hoisted: + return cards, () + + context.badges.add("↗") + + def _rewrite(card: Card) -> Card: + return Card( + title=card.title, + kind=card.kind, + subtitle=card.subtitle, + pills=tuple(moved.get(pill.key, pill) for pill in card.pills), + children=tuple(_rewrite(child) for child in card.children), + badge=card.badge, + note=card.note, + key=card.key, + ) + + hoist = Card( + title=HOIST_KEY, + kind="hoist", + subtitle="one value across " + + _plural(spec.counts.get("datasets", len(nodes)), "dataset"), + pills=tuple(hoisted), + key=HOIST_KEY, + ) + return (hoist,) + tuple(_rewrite(card) for card in cards), tuple(links) + + # -- rule: legend and footer ------------------------------------------------- _LEGEND_WORDS = { @@ -900,10 +1124,14 @@ def _legend(context, constraints=()) -> str: parts = [_LEGEND_WORDS[state] for state in STATES if state in context.states] if any(badge.startswith("shared") or badge == "↗" for badge in context.badges): parts.append("blue badge = shared prior") + if "draw" in context.badges: + parts.append("violet arrow = the distribution it is drawn from") if "independent" in context.badges: parts.append("independent = one prior per member") if "plate" in context.badges: parts.append("dashed frame = repeated components") + if "datasets" in context.badges: + parts.append("dashed frame = one component per dataset") if constraints: parts.append("dashed orange = constraint (assertion)") return "Legend: " + " · ".join(parts) @@ -914,14 +1142,41 @@ def _plate_members(spec) -> int: return sum(node.plate.count for node in spec.components() if node.plate is not None) +def _graphical_footer_parts(counts) -> List[str]: + """ + The graphical split of the accounting. + + ``hyper-parameters`` are counted **separately** from the per-dataset + parameters (review, A_08: "include the two free hyperparameters in the + accounting, separately from the three parameters per dataset"), and the + three terms reconcile to the unique sampled total that follows them. + """ + parts: List[str] = [] + if counts.get("hyper_parameters"): + parts.append(_plural(counts["hyper_parameters"], "hyper-parameter")) + parts.append(f"{counts.get('shared_across_datasets', 0)} shared across datasets") + parts.append( + f"{counts.get('per_dataset', 0)} per dataset × " + f"{_plural(counts.get('datasets', 0), 'dataset')}" + ) + return parts + + def _footer(spec, hidden_fixed: int) -> str: counts = spec.counts - parts = [ - _plural(counts.get("unique_sampled_scalars", 0), "unique sampled scalar"), - _plural(counts.get("fixed_leaf_slots", 0), "fixed leaf slot"), - _plural(counts.get("shared_priors", 0), "shared prior") - + " (unique variables, not references)", - ] + graphical = "datasets" in counts + parts = _graphical_footer_parts(counts) if graphical else [] + parts.append( + _plural(counts.get("unique_sampled_scalars", 0), "unique sampled scalar") + ) + parts.append(_plural(counts.get("fixed_leaf_slots", 0), "fixed leaf slot")) + if not graphical: + parts.append( + _plural(counts.get("shared_priors", 0), "shared prior") + + " (unique variables, not references)" + ) + if counts.get("observed"): + parts.append(_plural(counts["observed"], "observed dataset")) if counts.get("missing"): parts.append(f"{counts['missing']} missing") if counts.get("solved"): @@ -991,7 +1246,7 @@ def build_presentation( hidden_fixed = 0 cards: List[Card] = [] - if root.kind == "collection" and not root.rows and root.children: + if root.kind in ("collection", "global") and not root.rows and root.children: for child in root.children: plate = child if child.plate is not None else None card, hidden = _card(child, plate, 1, context, show_fixed, max_depth) @@ -1002,14 +1257,19 @@ def build_presentation( card, hidden_fixed = _card(root, plate, 1, context, show_fixed, max_depth) cards.append(card) + cards, hoist_links = _hoist_shared(spec, tuple(cards), context) + cards = list(cards) presentation_keys = [ (pill.key, pill.badge) for card in _cards_of(cards) for pill in card.pills ] drawn = {key for key, _ in presentation_keys} + # A draw link lands on a pill but leaves a *card*, so card keys are anchors + # too; every other link kind resolves to a pill at both ends. + anchors = drawn | {card.key for card in _cards_of(cards)} links = tuple( link - for link in _links(spec, presentation_keys, context) - if link.source_key in drawn and link.target_key in drawn + for link in _links(spec, presentation_keys, context) + hoist_links + if link.source_key in anchors and link.target_key in anchors ) constraints = _constraints(spec, cards, context) diff --git a/autofit/model_figure/render.py b/autofit/model_figure/render.py index dd1675dbc..4d0d2dc5f 100644 --- a/autofit/model_figure/render.py +++ b/autofit/model_figure/render.py @@ -41,6 +41,9 @@ "pill_border": "#b4b4c0", "red": "#a81f16", "red_fill": "#fceceb", + "violet": "#6a4b8c", + "violet_fill": "#f1eaf8", + "green": "#3c6b3c", "tag_fill": "#ececf1", } @@ -57,8 +60,8 @@ "relation": (PALETTE["cream"], PALETTE["orange"], PALETTE["text"], False), "solved": ("#ffffff", PALETTE["muted"], PALETTE["text"], True), "missing": (PALETTE["red_fill"], PALETTE["red"], PALETTE["red"], False), - "observed": ("#e9f1e9", "#3c6b3c", PALETTE["text"], False), - "drawn": ("#f1eaf8", "#6a4b8c", PALETTE["text"], False), + "observed": ("#e9f1e9", PALETTE["green"], PALETTE["text"], False), + "drawn": (PALETTE["violet_fill"], PALETTE["violet"], PALETTE["text"], False), "folded": ("#f4f4f8", PALETTE["pill_border"], PALETTE["muted"], True), } @@ -98,8 +101,14 @@ def _text(ax, x, y, text, *, size, colour, weight="normal", z=3): ) -def _badge_colours(badge: str): - """Blue for sharing; neutral for everything else (repetition is not sharing).""" +def _badge_colours(badge: str, state: str = "free"): + """ + Blue for sharing; **violet** for a hierarchical draw; neutral for everything + else (repetition is not sharing, and a draw is not sharing either -- the two + say opposite things, so they never share a colour). + """ + if state == "drawn": + return PALETTE["violet_fill"], PALETTE["violet"] if badge.startswith("shared") or badge.startswith("↗"): return PALETTE["blue_fill"], PALETTE["blue"] return PALETTE["tag_fill"], PALETTE["muted"] @@ -157,7 +166,7 @@ def _draw_pill(ax, pill, style, card_level=1): z=60 + card_level, ) if pill.badge_offset is not None: - fill, colour = _badge_colours(pill.badge) + fill, colour = _badge_colours(pill.badge, pill.state) _box( ax, pill.x + pill.badge_offset, @@ -185,6 +194,16 @@ def _draw_card(ax, card, style): tint = PALETTE["tints"][min(card.level - 1, len(PALETTE["tints"]) - 1)] plate = card.kind == "plate" + # A hyper card is the source of every violet draw arrow, and a hoisted card + # holds what is shared: each is outlined in its own edge's colour so the + # reader can follow the arrow back to the box it comes from. + edge = PALETTE["border"] + if plate: + edge = PALETTE["plate_border"] + elif card.kind == "hyper": + edge = PALETTE["violet"] + elif card.kind == "hoist": + edge = PALETTE["blue"] _box( ax, card.x, @@ -192,7 +211,7 @@ def _draw_card(ax, card, style): card.width, card.height, face=tint, - edge=PALETTE["plate_border"] if plate else PALETTE["border"], + edge=edge, dashed=plate, lw=1.1 if card.level == 1 or plate else 0.8, z=card.level, @@ -289,28 +308,54 @@ def _draw_card(ax, card, style): _draw_card(ax, child, style) +_LINK_COLOURS = { + "shared": PALETTE["blue"], + "draw": PALETTE["violet"], + "relation": PALETTE["orange"], +} + + def _draw_link(ax, route): from matplotlib.lines import Line2D + from matplotlib.patches import FancyArrowPatch - colour = PALETTE["blue"] if route.kind == "shared" else PALETTE["orange"] + draw = route.kind == "draw" + colour = _LINK_COLOURS.get(route.kind, PALETTE["orange"]) xs = [x for x, _ in route.points] ys = [y for _, y in route.points] + # A draw is **directed**: the last segment carries an arrowhead that lands + # on the drawn pill, because "centre_i is drawn from this distribution" is a + # claim with a direction, unlike sharing. ax.add_line( Line2D( - xs, - ys, + xs[:-1] if draw else xs, + ys[:-1] if draw else ys, color=colour, - linewidth=0.9 if route.kind == "shared" else 0.7, - linestyle="solid" if route.kind == "shared" else (0, (3, 1.6)), + linewidth=0.9 if route.kind in ("shared", "draw") else 0.7, + linestyle="solid" if route.kind in ("shared", "draw") else (0, (3, 1.6)), solid_capstyle="round", zorder=80, ) ) + if draw: + ax.add_patch( + FancyArrowPatch( + (xs[-2], ys[-2]), + (xs[-1], ys[-1]), + arrowstyle="-|>", + mutation_scale=7.0, + linewidth=0.9, + color=colour, + shrinkA=0.0, + shrinkB=0.0, + zorder=81, + ) + ) # A filled dot where each end touches the card it belongs to. ax.add_line( Line2D( - [xs[0], xs[-1]], - [ys[0], ys[-1]], + [xs[0]] if draw else [xs[0], xs[-1]], + [ys[0]] if draw else [ys[0], ys[-1]], linestyle="none", marker="o", markersize=2.6, diff --git a/docs/features/graphical.md b/docs/features/graphical.md index 7f83dcb62..c7dcd7642 100644 --- a/docs/features/graphical.md +++ b/docs/features/graphical.md @@ -141,8 +141,23 @@ We combine our `AnalysisFactor`'s into one, to compose the factor graph. factor_graph = g.FactorGraphModel(*analysis_factor_list) ``` -So, what does our factor graph looks like? Unfortunately, we haven't yet build visualization of this into **PyAutoFit**, -so you'll have to make do with a description for now. +So, what does our factor graph look like? The `ModelPlotter` draws it, taking the factor graph's global model exactly +like it takes an ordinary model: + +```bash +af.ModelPlotter(factor_graph.global_prior_model).figure() +``` + +```{image} https://raw.githubusercontent.com/PyAutoLabs/PyAutoFit/main/docs/images/model_figures/graphical_variable.png +:alt: The model figure of the graphical model above, with the shared centre hoisted into a card above a dashed plate standing for the three datasets. +:width: 600 +``` + +The dashed frame is a **plate**: one `Gaussian` drawn once, standing for all three datasets, labelled `3 datasets`. The +`centre` shared by every dataset is hoisted out into the card above, joined to the plate by a blue line, and its chip +inside the plate carries a blue `shared` badge. The `normalization` and `sigma` chips are marked `independent`, because +each dataset gets a prior of its own, and the green `data` chip is the observed dataset. The footer counts the fit the +prose below describes: 1 shared across datasets, 2 per dataset × 3 datasets, 7 unique sampled scalars. The factor graph above is made up of two components: @@ -171,6 +186,34 @@ This is all expanded upon in the [HowToFit chapter on graphical models](https:// more detailed description of why this approach to model-fitting extracts a lot more information than fitting each dataset one-by-one. +## Shared Or Hierarchical + +Sharing a parameter and drawing it hierarchically sound alike in words but are different models, and the figure is +the quickest way to tell them apart. + +A **shared** parameter is one prior object used by every dataset, so the datasets fit literally the same number. Share +all three of `centre`, `normalization` and `sigma` and every chip carries the blue `shared` badge, the hoisted card +holds all three, and 3 datasets cost 3 sampled scalars: + +```{image} https://raw.githubusercontent.com/PyAutoLabs/PyAutoFit/main/docs/images/model_figures/graphical_shared.png +:alt: The model figure of a fully shared graphical model, with centre, normalization and sigma hoisted into one shared card and each chip badged shared. +:width: 600 +``` + +A **hierarchical** parameter is different for every dataset, but each one is *drawn* from a parent distribution whose +own parameters are fitted. Drawn is not shared. Give each dataset's `centre` an `af.HierarchicalFactor` parent and the +figure hoists that parent into a violet card of its own, holding the `mean` and `sigma` of the distribution, with a +violet arrow running into the `centre` chip, which reads `centre · drawn`: + +```{image} https://raw.githubusercontent.com/PyAutoLabs/PyAutoFit/main/docs/images/model_figures/graphical_hierarchical.png +:alt: The model figure of a hierarchical graphical model, with a violet HierarchicalFactor card holding mean and sigma and a violet arrow into the drawn centre chip inside the plate. +:width: 600 +``` + +The footers say what this costs: the shared figure counts 3 unique sampled scalars, the hierarchical one 2 +hyper-parameters plus 3 per dataset × 3 datasets, so 11. This hierarchical composition is the model built in +[HowToFit chapter 3, tutorial 4](https://github.com/PyAutoLabs/HowToFit/blob/main/notebooks/chapter_3_graphical_models/tutorial_4_hierachical_models.ipynb). + ## Expectation Propagation For large datasets, a graphical model may have hundreds, thousands, or *hundreds of thousands* of parameters. The diff --git a/docs/images/model_figures/graphical_hierarchical.png b/docs/images/model_figures/graphical_hierarchical.png new file mode 100644 index 000000000..b931a41d9 Binary files /dev/null and b/docs/images/model_figures/graphical_hierarchical.png differ diff --git a/docs/images/model_figures/graphical_shared.png b/docs/images/model_figures/graphical_shared.png new file mode 100644 index 000000000..4a941edaa Binary files /dev/null and b/docs/images/model_figures/graphical_shared.png differ diff --git a/docs/images/model_figures/graphical_variable.png b/docs/images/model_figures/graphical_variable.png new file mode 100644 index 000000000..d3a61b691 Binary files /dev/null and b/docs/images/model_figures/graphical_variable.png differ diff --git a/docs/images/model_figures/make_figures.py b/docs/images/model_figures/make_figures.py index 328d73682..f095938aa 100644 --- a/docs/images/model_figures/make_figures.py +++ b/docs/images/model_figures/make_figures.py @@ -118,10 +118,15 @@ class _Analysis(af.Analysis): """ A do-nothing analysis. ``AnalysisFactor`` only needs an analysis object to pair with the model; nothing here is ever fitted. + + It carries a ``data`` attribute because that is what makes the figure draw + an **observed** node for the dataset: observed data and a fixed model + constant are different concepts and must not share the grey pill. """ def __init__(self, index): self.index = index + self.data = [0.0, 1.0, 2.0] def log_likelihood_function(self, instance): return 0.0 @@ -192,6 +197,82 @@ def multiple_datasets_relational(): return _factor_graph(model_list).global_prior_model +# -- the graphical models --------------------------------------------------- + + +def _graphical_model(): + """One dataset's ``Gaussian``, with a centre that a hyper-prior can draw.""" + model = af.Model(af.ex.Gaussian) + model.centre = af.TruncatedGaussianPrior( + mean=50.0, sigma=20.0, lower_limit=0.0, upper_limit=100.0 + ) + model.normalization = af.LogUniformPrior(lower_limit=1e-2, upper_limit=1e2) + model.sigma = af.GaussianPrior(mean=10.0, sigma=5.0) + return model + + +def graphical_shared(): + """ + Plate notation, **shared**: one ``centre``, ``normalization`` and ``sigma`` + for all three datasets -- literally the same three numbers. + """ + model = _graphical_model() + return _factor_graph([model, model, model]).global_prior_model + + +def graphical_variable(): + """ + Plate notation, **partly shared**: one ``centre`` for every dataset, with a + ``normalization`` and ``sigma`` of its own per dataset. + """ + model = _graphical_model() + + model_list = [] + for _ in range(3): + model_analysis = model.copy() + model_analysis.normalization = af.LogUniformPrior( + lower_limit=1e-2, upper_limit=1e2 + ) + model_analysis.sigma = af.GaussianPrior(mean=10.0, sigma=5.0) + model_list.append(model_analysis) + + return _factor_graph(model_list).global_prior_model + + +def graphical_hierarchical(): + """ + Plate notation, **hierarchical**: three *different* centres, each drawn from + one parent ``GaussianPrior`` whose ``mean`` and ``sigma`` are themselves + free (HowToFit chapter 3, tutorial 4). + + The teaching pair of the epic: put this figure beside ``graphical_shared`` + and the difference between "the same number" and "from a common population" + is the difference between a blue reference and a violet arrow. + """ + model_list = [_graphical_model() for _ in range(3)] + + hierarchical_factor = af.HierarchicalFactor( + af.GaussianPrior, + mean=af.TruncatedGaussianPrior( + mean=50.0, sigma=10, lower_limit=0.0, upper_limit=100.0 + ), + sigma=af.TruncatedGaussianPrior( + mean=10.0, sigma=5.0, lower_limit=0.0, upper_limit=100.0 + ), + ) + for model in model_list: + hierarchical_factor.add_drawn_variable(model.centre) + + factor_graph = af.FactorGraphModel( + *[ + af.AnalysisFactor(prior_model=model, analysis=_Analysis(index)) + for index, model in enumerate(model_list) + ], + hierarchical_factor, + ) + return factor_graph.global_prior_model + + def composite_shared_relation_assertion(): """ All three of sharing, relation and assertion at once -- acceptance case 3. @@ -232,6 +313,9 @@ def lens_models(): "multiple_datasets_variable": multiple_datasets_variable, "multiple_datasets_relational": multiple_datasets_relational, "composite_shared_relation_assertion": composite_shared_relation_assertion, + "graphical_shared": graphical_shared, + "graphical_variable": graphical_variable, + "graphical_hierarchical": graphical_hierarchical, } diff --git a/docs/images/model_figures/multiple_datasets_relational.png b/docs/images/model_figures/multiple_datasets_relational.png index 12962c594..7d26486a4 100644 Binary files a/docs/images/model_figures/multiple_datasets_relational.png and b/docs/images/model_figures/multiple_datasets_relational.png differ diff --git a/docs/images/model_figures/multiple_datasets_shared.png b/docs/images/model_figures/multiple_datasets_shared.png index 33b0c1c35..4a941edaa 100644 Binary files a/docs/images/model_figures/multiple_datasets_shared.png and b/docs/images/model_figures/multiple_datasets_shared.png differ diff --git a/docs/images/model_figures/multiple_datasets_variable.png b/docs/images/model_figures/multiple_datasets_variable.png index 311cf92ff..d3a61b691 100644 Binary files a/docs/images/model_figures/multiple_datasets_variable.png and b/docs/images/model_figures/multiple_datasets_variable.png differ diff --git a/test_autofit/graph_spec/conftest.py b/test_autofit/graph_spec/conftest.py index 8adb2bd6c..d03e22dbe 100644 --- a/test_autofit/graph_spec/conftest.py +++ b/test_autofit/graph_spec/conftest.py @@ -3,6 +3,7 @@ import pytest import autofit as af +from autofit.tools.namer import namer @pytest.fixture(autouse=True) @@ -11,9 +12,14 @@ 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``). + + ``namer`` is reset for the same reason: a declarative factor's name + (``AnalysisFactor0``, ``HierarchicalFactor0``) comes from that global + counter, and the graphical pass records it. """ af.ModelObject._ids = itertools.count() af.Prior._ids = itertools.count() + namer.reset() class NullAnalysis(af.Analysis): diff --git a/test_autofit/graph_spec/graphical_doubles.py b/test_autofit/graph_spec/graphical_doubles.py new file mode 100644 index 000000000..6b544223e --- /dev/null +++ b/test_autofit/graph_spec/graphical_doubles.py @@ -0,0 +1,103 @@ +""" +The four graphical models the phase-4 figures are asserted against. + +Three datasets each, so a plate can form, and one ``_Analysis`` per dataset that +carries ``data`` -- which is what makes the extraction emit an ``observed`` row. +They mirror ``docs/images/model_figures/make_figures.py``'s ``graphical_*`` +builders (the committed evidence PNGs) and the ``autofit_workspace`` +``multiple_datasets`` cookbook, so a test failure and a figure regression are +the same failure. +""" + +import autofit as af + + +class DataAnalysis(af.Analysis): + """An analysis that carries ``data`` -- and does nothing else.""" + + def __init__(self, index): + self.index = index + self.data = [0.0, 1.0, 2.0] + + def log_likelihood_function(self, instance): + return 0.0 + + +def dataset_model(): + """One dataset's ``Gaussian``, with a centre a hyper-prior can draw.""" + model = af.Model(af.ex.Gaussian) + model.centre = af.TruncatedGaussianPrior( + mean=50.0, sigma=20.0, lower_limit=0.0, upper_limit=100.0 + ) + model.normalization = af.LogUniformPrior(lower_limit=1e-2, upper_limit=1e2) + model.sigma = af.GaussianPrior(mean=10.0, sigma=5.0) + return model + + +def factor_graph(model_list, analysis_cls=DataAnalysis): + return af.FactorGraphModel( + *[ + af.AnalysisFactor(prior_model=model, analysis=analysis_cls(index)) + for index, model in enumerate(model_list) + ] + ) + + +def shared_graph(analysis_cls=DataAnalysis): + """One model object for all three datasets: every prior is literally shared.""" + model = dataset_model() + return factor_graph([model, model, model], analysis_cls) + + +def variable_graph(): + """A shared ``centre``; a ``normalization`` and ``sigma`` per dataset.""" + model = dataset_model() + model_list = [] + for _ in range(3): + copy = model.copy() + copy.normalization = af.LogUniformPrior(lower_limit=1e-2, upper_limit=1e2) + copy.sigma = af.GaussianPrior(mean=10.0, sigma=5.0) + model_list.append(copy) + return factor_graph(model_list) + + +def relational_graph(): + """``sigma`` follows ``sigma_m * x + sigma_c``, so datasets add no parameters.""" + model = af.Collection(gaussian=dataset_model()) + sigma_m = af.UniformPrior(lower_limit=-10.0, upper_limit=10.0) + sigma_c = af.UniformPrior(lower_limit=-10.0, upper_limit=10.0) + + model_list = [] + for x in [1.0, 2.0, 3.0]: + copy = model.copy() + copy.gaussian.sigma = (sigma_m * x) + sigma_c + model_list.append(copy) + return factor_graph(model_list) + + +def hierarchical_graph(): + """ + Three *different* centres, each drawn from one parent ``GaussianPrior`` + whose own ``mean`` and ``sigma`` are free (HowToFit chapter 3, tutorial 4). + """ + model_list = [dataset_model() for _ in range(3)] + + hierarchical_factor = af.HierarchicalFactor( + af.GaussianPrior, + mean=af.TruncatedGaussianPrior( + mean=50.0, sigma=10, lower_limit=0.0, upper_limit=100.0 + ), + sigma=af.TruncatedGaussianPrior( + mean=10.0, sigma=5.0, lower_limit=0.0, upper_limit=100.0 + ), + ) + for model in model_list: + hierarchical_factor.add_drawn_variable(model.centre) + + return af.FactorGraphModel( + *[ + af.AnalysisFactor(prior_model=model, analysis=DataAnalysis(index)) + for index, model in enumerate(model_list) + ], + hierarchical_factor, + ) diff --git a/test_autofit/graph_spec/test_determinism.py b/test_autofit/graph_spec/test_determinism.py index 64d25dbf2..13500d4b6 100644 --- a/test_autofit/graph_spec/test_determinism.py +++ b/test_autofit/graph_spec/test_determinism.py @@ -15,13 +15,24 @@ import autofit as af from autofit.example.model import PhysicalNFW from autofit.graph_spec import GraphSpec +from autofit.tools.namer import namer from .conftest import NullAnalysis def _reset_ids(): + """ + Reset the global counters a rebuilt model's serialisation depends on. + + ``namer`` is the third of them: a declarative factor's ``name`` -- which the + graphical pass records as :class:`~autofit.graph_spec.FactorInfo` and which + ``graph.info`` prints -- comes from it, so a model *rebuilt* without + resetting it is genuinely a model whose factors are named differently (this + is why ``test_autofit/graphical/info/conftest.py`` resets it too). + """ af.ModelObject._ids = itertools.count() af.Prior._ids = itertools.count() + namer.reset() class Wrapper: diff --git a/test_autofit/graph_spec/test_graphical.py b/test_autofit/graph_spec/test_graphical.py new file mode 100644 index 000000000..8619a8642 --- /dev/null +++ b/test_autofit/graph_spec/test_graphical.py @@ -0,0 +1,290 @@ +""" +The graphical pass -- plate notation over a ``FactorGraphModel``. + +The load-bearing assertion in this file is that **a draw is not sharing**: the +drawn ``Prior`` *is* the dataset model's own parameter object, so an extraction +that does nothing about it reports the three datasets as sharing one ``centre`` +-- the exact opposite of what a hierarchical model says. Everything else here +(hoisted hyper nodes, observed rows, the dataset plate, the split counts) exists +to make that statement drawable. +""" + +import itertools +import json +import subprocess +import sys + +import autofit as af +from autofit.graph_spec import GraphSpec +from autofit.tools.namer import namer + +from .conftest import NullAnalysis +from .graphical_doubles import ( + dataset_model, + hierarchical_graph, + relational_graph, + shared_graph, + variable_graph, +) + + +def _reset_ids(): + af.ModelObject._ids = itertools.count() + af.Prior._ids = itertools.count() + namer.reset() + + +# -- the hierarchical model ------------------------------------------------- + + +def test_one_hyper_node_is_hoisted_to_the_front(): + spec = GraphSpec.from_model(hierarchical_graph().global_prior_model) + + hyper = [child for child in spec.root.children if child.kind == "hyper"] + assert len(hyper) == 1 + # Hoisted: the one documented exception to declaration order. + assert spec.root.children[0] is hyper[0] + + node = hyper[0] + assert node.path == ("HierarchicalFactor0",) + assert node.cls_name == "GaussianPrior" + assert node.factor.kind == "hierarchical" + assert [row.name for row in node.rows] == ["mean", "sigma"] + # The per-draw `_HierarchicalFactor` collections are gone: one node stands + # for the one distribution they all point at. + assert [child.name for child in spec.root.children] == ["HierarchicalFactor0", "0"] + + +def test_a_draw_is_not_sharing(): + spec = GraphSpec.from_model(hierarchical_graph().global_prior_model) + + row = spec.row(("0", "centre")) + assert row.provenance.kind == "hierarchical-draw" + assert row.provenance.expression == "~ GaussianPrior(mean, sigma)" + assert row.provenance.operands == ("HierarchicalFactor0",) + # Still sampled: a draw is a provenance, never a sampling state. + assert row.sampling == "free" + # ... and never a sharing marker. + assert row.shared is False + assert row.direct_occurrences == (("0", "centre"),) + assert spec.shared == () + assert spec.counts["shared_priors"] == 0 + + +def test_one_draw_edge_per_dataset_in_dataset_order(): + spec = GraphSpec.from_model(hierarchical_graph().global_prior_model) + + assert len(spec.draws) == 3 + assert [edge.target_path for edge in spec.draws] == [ + ("0", "centre"), + ("1", "centre"), + ("2", "centre"), + ] + assert {edge.source_path for edge in spec.draws} == {("HierarchicalFactor0",)} + assert len({edge.prior_id for edge in spec.draws}) == 3 + for edge in spec.draws: + assert edge.expression == "~ GaussianPrior(mean, sigma)" + + +def test_the_dataset_plate_still_forms_around_a_draw(): + spec = GraphSpec.from_model(hierarchical_graph().global_prior_model) + + plate = spec.root.children[1] + assert plate.plate.count == 3 + assert plate.plate.representative_key == "0 - 2" + assert plate.factor.kind == "analysis" + # Nothing is shared in all, because nothing is shared at all. + assert plate.plate.shared_in_all == () + assert "centre ◂ drawn" in plate.plate.repeats[0] + + +def test_hierarchical_counts_reconcile(): + spec = GraphSpec.from_model(hierarchical_graph().global_prior_model) + + counts = spec.counts + assert counts["datasets"] == 3 + assert counts["hyper_parameters"] == 2 + assert counts["shared_across_datasets"] == 0 + assert counts["per_dataset"] == 3 + assert counts["observed"] == 3 + assert ( + counts["hyper_parameters"] + + counts["shared_across_datasets"] + + counts["per_dataset"] * counts["datasets"] + == counts["unique_sampled_scalars"] + ) + + +def test_the_hyper_node_records_the_model_info_paths_it_replaces(): + spec = GraphSpec.from_model(hierarchical_graph().global_prior_model) + + entry = spec.path_index["HierarchicalFactor0"] + paths = ( + entry["figure"] + if isinstance(entry, dict) + else ["/".join(path) for path in entry] + ) + # The three `_HierarchicalFactor` collections, grouped as `model.info` + # groups them -- recorded rather than hidden. + assert paths and all("distribution_model" in path for path in paths) + + +# -- the shared model ------------------------------------------------------- + + +def test_shared_model_collapses_to_one_plate_of_three(): + model = shared_graph().global_prior_model + spec = GraphSpec.from_model(model) + + assert len(spec.root.children) == 1 + plate = spec.root.children[0] + assert plate.plate.count == 3 + assert plate.plate.member_paths == (("0",), ("1",), ("2",)) + assert len(plate.plate.shared_in_all) == 3 + assert {row.prior_id for row in plate.rows if row.prior_id is not None} == set( + plate.plate.shared_in_all + ) + assert spec.draws == () + + counts = spec.counts + assert counts["datasets"] == 3 + assert counts["shared_across_datasets"] == 3 + assert counts["per_dataset"] == 0 + assert counts["hyper_parameters"] == 0 + + +def test_variable_model_shares_only_the_centre(): + spec = GraphSpec.from_model(variable_graph().global_prior_model) + + counts = spec.counts + assert counts["shared_across_datasets"] == 1 + assert counts["per_dataset"] == 2 + assert ( + counts["shared_across_datasets"] + counts["per_dataset"] * counts["datasets"] + == counts["unique_sampled_scalars"] + ) + + +def test_a_relation_across_datasets_counts_as_shared_across_datasets(): + """``sigma_m`` / ``sigma_c`` are one pair of numbers for every dataset.""" + spec = GraphSpec.from_model(relational_graph().global_prior_model) + + counts = spec.counts + assert counts["shared_across_datasets"] == 4 + assert counts["per_dataset"] == 0 + assert counts["unique_sampled_scalars"] == 4 + + +# -- observed data ---------------------------------------------------------- + + +def test_observed_rows_come_from_the_analysis(): + spec = GraphSpec.from_model(shared_graph().global_prior_model, collapse=False) + + for index in ("0", "1", "2"): + row = spec.row((index, "data")) + assert row.sampling == "observed" + assert row.provenance.kind == "observed" + # Not part of the model, so not part of `model.info`. + assert row.in_model_info is False + assert spec.path_index[f"{index}/data"] == () + assert spec.counts["observed"] == 3 + # An observed node is not a fixed constant. + assert spec.counts["fixed_leaf_slots"] == 0 + + +def test_an_analysis_without_data_contributes_no_observed_row(): + spec = GraphSpec.from_model( + shared_graph(analysis_cls=lambda index: NullAnalysis()).global_prior_model + ) + + assert spec.counts["observed"] == 0 + assert all( + row.provenance.kind != "observed" + for node in spec.components() + for row in node.rows + ) + # The factor is still recorded. + assert spec.root.children[0].factor.kind == "analysis" + + +# -- the factor graph is read once ------------------------------------------ + + +def test_the_factor_graph_is_read_exactly_once(): + """ + ``FactorGraphModel.graph`` rebuilds and renames its ``PriorFactor``s on every + access, so a second read would silently change the names the figure quotes. + """ + graph_model = hierarchical_graph() + model = graph_model.global_prior_model + + reads = [] + inherited = type(graph_model).graph + + def _counting(self): + reads.append(self) + return inherited.fget(self) + + type(graph_model).graph = property(_counting) + try: + spec = GraphSpec.from_model(model) + finally: + del type(graph_model).graph + + assert len(reads) == 1 + assert len(spec.draws) == 3 + + +# -- nothing changes for a model that is not a factor graph ----------------- + + +def test_a_plain_model_is_untouched_by_the_graphical_pass(): + spec = GraphSpec.from_model(af.Collection(one=dataset_model(), two=dataset_model())) + + assert spec.draws == () + assert all(node.factor is None for node in spec.components()) + assert all(node.kind != "hyper" for node in spec.components()) + for key in ("datasets", "hyper_parameters", "shared_across_datasets"): + assert key not in spec.counts + + +# -- determinism ------------------------------------------------------------ + + +def test_graphical_extraction_is_deterministic(): + first = json.dumps( + GraphSpec.from_model(hierarchical_graph().global_prior_model).to_dict() + ) + _reset_ids() + second = json.dumps( + GraphSpec.from_model(hierarchical_graph().global_prior_model).to_dict() + ) + + assert first == second + + +def test_graphical_extraction_is_deterministic_in_a_fresh_process(): + source = ( + "import json, sys;" + "sys.path.insert(0, %r);" + "from test_autofit.graph_spec.graphical_doubles import hierarchical_graph;" + "from autofit.graph_spec import GraphSpec;" + "print(json.dumps(GraphSpec.from_model(" + "hierarchical_graph().global_prior_model).to_dict()))" + ) % str(_repo_root()) + result = subprocess.run( + [sys.executable, "-c", source], capture_output=True, text=True, check=True + ) + + assert json.loads(result.stdout) == json.loads( + json.dumps( + GraphSpec.from_model(hierarchical_graph().global_prior_model).to_dict() + ) + ) + + +def _repo_root(): + from pathlib import Path + + return Path(__file__).resolve().parents[2] diff --git a/test_autofit/model_figure/conftest.py b/test_autofit/model_figure/conftest.py index 8156accae..2eb9a4f45 100644 --- a/test_autofit/model_figure/conftest.py +++ b/test_autofit/model_figure/conftest.py @@ -3,6 +3,7 @@ import pytest import autofit as af +from autofit.tools.namer import namer @pytest.fixture(autouse=True) @@ -11,6 +12,11 @@ def reset_ids(): Model object and prior ids are global counters and the spec records both, so they are reset before every test -- the figure is then a function of the model alone, which is what the determinism acceptance asserts. + + ``namer`` is reset for the same reason: a declarative factor's name + (``AnalysisFactor0``, ``HierarchicalFactor0``) comes from that global + counter, and the graphical pass records it. """ af.ModelObject._ids = itertools.count() af.Prior._ids = itertools.count() + namer.reset() diff --git a/test_autofit/model_figure/test_graphical_presentation.py b/test_autofit/model_figure/test_graphical_presentation.py new file mode 100644 index 000000000..4b087385e --- /dev/null +++ b/test_autofit/model_figure/test_graphical_presentation.py @@ -0,0 +1,275 @@ +""" +Plate notation -- the presentation of a ``FactorGraphModel``. + +The acceptance of the epic's phase 4, asserted on the figure: + +* a hierarchical model's figure shows ``centre · drawn`` with the parent arrow + landing **on the pill**, and **no** shared marker anywhere on it; +* a shared model's figure hoists the shared priors above the plate; +* observed data is visually distinct from a fixed constant; +* the footer separates hyper-parameters from the per-dataset parameters; +* and a model that is *not* a factor graph is presented exactly as before. +""" + +import hashlib +import itertools +import json + +import matplotlib + +matplotlib.use("Agg") + +import matplotlib.pyplot as plt + +import autofit as af +from autofit.graph_spec import GraphSpec +from autofit.model_figure.presentation import build_presentation, prior_summaries +from autofit.model_figure.render import PALETTE, _PILL_STYLE, _badge_colours + +from test_autofit.graph_spec.graphical_doubles import ( + hierarchical_graph, + relational_graph, + shared_graph, + variable_graph, +) +from test_autofit.graph_spec.lens_doubles import ( + group_model, + mge_model, + simple_lens_model, +) + + +def _presentation(model, **kwargs): + return af.ModelPlotter(model).presentation(**kwargs) + + +def _pill(presentation, key): + for pill in presentation.pills(): + if pill.key == key: + return pill + raise AssertionError(f"no pill at {key!r}") + + +def _card(presentation, key): + for card in presentation.walk(): + if card.key == key: + return card + raise AssertionError(f"no card at {key!r}") + + +# -- shared: the prior is drawn once, above the plate ----------------------- + + +def test_a_shared_model_hoists_its_priors_above_the_plate(): + presentation = _presentation(shared_graph().global_prior_model) + + hoist = presentation.cards[0] + assert hoist.kind == "hoist" + assert hoist.title == "shared across datasets" + assert hoist.subtitle == "one value across 3 datasets" + assert [pill.text for pill in hoist.pills] == ["centre", "normalization", "sigma"] + + plate = presentation.cards[1] + assert plate.kind == "plate" + assert plate.badge == "3 datasets" + assert plate.subtitle == "dataset 0 - 2" + + # Every member points at the hoisted pill, and nowhere else. + for name in ("centre", "normalization", "sigma"): + assert _pill(presentation, f"0/{name}").badge == "↗ shared" + assert ( + af.model_figure.presentation.Link( + f"0/{name}", f"shared across datasets/{name}", "shared" + ) + in presentation.links + ) + + +def test_every_occurrence_points_at_the_hoisted_card_not_at_a_member(): + """When no plate forms, the members still reference the hoisted card.""" + presentation = _presentation(relational_graph().global_prior_model) + + assert presentation.cards[0].kind == "hoist" + for index in ("0", "1", "2"): + assert _pill(presentation, f"{index}/gaussian/centre").badge == "↗ shared" + assert all( + link.target_key.startswith("shared across datasets/") + for link in presentation.links + if link.kind == "shared" + ) + + +def test_a_variable_model_hoists_only_what_is_shared(): + presentation = _presentation(variable_graph().global_prior_model) + + assert [pill.text for pill in presentation.cards[0].pills] == ["centre"] + assert _pill(presentation, "0/centre").badge == "↗ shared" + assert _pill(presentation, "0/normalization").badge == "independent" + + +# -- hierarchical: a draw, never a shared marker ---------------------------- + + +def test_a_hierarchical_model_draws_its_centre_and_never_shares_it(): + presentation = _presentation(hierarchical_graph().global_prior_model) + + hyper = presentation.cards[0] + assert hyper.kind == "hyper" + assert hyper.title == "HierarchicalFactor0 · GaussianPrior" + assert [pill.text for pill in hyper.pills] == ["mean", "sigma"] + + centre = _pill(presentation, "0/centre") + assert centre.state == "drawn" + assert centre.text == "centre · drawn" + assert centre.badge == "↗ HierarchicalFactor0" + + # The arrow leaves the hyper card and lands ON the pill. + draws = [link for link in presentation.links if link.kind == "draw"] + assert draws == [ + af.model_figure.presentation.Link("HierarchicalFactor0", "0/centre", "draw") + ] + + # No shared marker anywhere on the figure, and no hoisted card. + assert all(card.kind != "hoist" for card in presentation.walk()) + assert all( + link.kind != "shared" for link in presentation.links + ), "a draw must never be reported as sharing" + for pill in presentation.pills(): + assert pill.badge != "↗ shared" + assert not (pill.badge or "").startswith("shared") + + +def test_the_drawn_badge_is_violet_and_the_shared_badge_is_blue(): + """The two claims are opposites, so they never share a colour.""" + drawn = _pill(_presentation(hierarchical_graph().global_prior_model), "0/centre") + shared = _pill(_presentation(shared_graph().global_prior_model), "0/centre") + + assert _badge_colours(drawn.badge, drawn.state) == ( + PALETTE["violet_fill"], + PALETTE["violet"], + ) + assert _badge_colours(shared.badge, shared.state) == ( + PALETTE["blue_fill"], + PALETTE["blue"], + ) + + +def test_the_draw_arrow_ends_on_the_pill_inside_the_plate(): + layout = af.ModelPlotter(hierarchical_graph().global_prior_model).layout(width=14.0) + + route = next(link for link in layout.links if link.kind == "draw") + pill = next(pill for pill in layout.pills() if pill.key == "0/centre") + end_x, end_y = route.points[-1] + + assert end_x == round(pill.x, 4) + assert pill.y <= end_y <= pill.y + pill.height + + +# -- observed data is not a fixed constant ---------------------------------- + + +def test_observed_data_has_its_own_encoding(): + presentation = _presentation(shared_graph().global_prior_model) + + data = _pill(presentation, "0/data") + assert data.state == "observed" + assert data.text == "data · observed" + assert _PILL_STYLE["observed"] != _PILL_STYLE["fixed"] + assert "observed data" in presentation.legend + + +# -- the footer separates hyper-parameters from per-dataset parameters ------ + + +def test_the_hierarchical_footer_separates_the_hyper_parameters(): + presentation = _presentation(hierarchical_graph().global_prior_model) + + assert presentation.footer.startswith( + "2 hyper-parameters · 0 shared across datasets · " + "3 per dataset × 3 datasets · 11 unique sampled scalars" + ) + + +def test_the_shared_footer_says_nothing_is_per_dataset(): + presentation = _presentation(shared_graph().global_prior_model) + + assert presentation.footer.startswith( + "3 shared across datasets · 0 per dataset × 3 datasets · " + "3 unique sampled scalars" + ) + assert "3 observed datasets" in presentation.footer + + +def test_the_legend_names_only_what_is_on_the_figure(): + hierarchical = _presentation(hierarchical_graph().global_prior_model).legend + shared = _presentation(shared_graph().global_prior_model).legend + + assert "drawn from a hyper-prior" in hierarchical + assert "violet arrow = the distribution it is drawn from" in hierarchical + assert "blue badge = shared prior" not in hierarchical + + assert "blue badge = shared prior" in shared + assert "drawn from a hyper-prior" not in shared + + +# -- every graphical figure renders inside the width budget ---------------- + + +def test_every_graphical_figure_renders_within_the_width_budget(): + for builder in (shared_graph, variable_graph, relational_graph, hierarchical_graph): + af.ModelObject._ids = itertools.count() + af.Prior._ids = itertools.count() + plotter = af.ModelPlotter(builder().global_prior_model) + layout = plotter.layout(width=14.0) + + assert layout.width <= 14.0 + assert layout.width * layout.style.dpi <= 1400 + + figure = plotter.figure(width=14.0, format=None) + assert figure is not None + plt.close(figure) + + +# -- nothing changes for a model that is not a factor graph ---------------- + + +#: ``sha256[:16]`` of ``json.dumps(presentation.to_dict())`` for each lens +#: double, captured from the implementation **before** the graphical pass +#: existed. The phase-4 rules are all gated on a ``global`` root or on a +#: provenance kind only the graphical pass emits, so every one of these must +#: still hash the same: "non-graphical models are presented byte-identically". +_BEFORE_PHASE_4 = { + "simple_lens": { + "names": "f8131c06afad0cab", + "priors": "a80e3e969b507f8f", + }, + "mge_pixelized": { + "names": "fa9b8cc21fe33cf3", + "priors": "963a978c671cae28", + }, + "group_scale": { + "names": "48849168782d1068", + "priors": "ac258bec6dea2d7b", + }, +} + +_LENS_DOUBLES = { + "simple_lens": simple_lens_model, + "mge_pixelized": mge_model, + "group_scale": group_model, +} + + +def test_non_graphical_presentations_are_byte_identical_to_phase_3(): + for name, builder in _LENS_DOUBLES.items(): + af.ModelObject._ids = itertools.count() + af.Prior._ids = itertools.count() + model = builder() + spec = GraphSpec.from_model(model) + priors = prior_summaries(model) + for detail in ("names", "priors"): + blob = json.dumps( + build_presentation(spec, detail=detail, priors=priors).to_dict() + ) + digest = hashlib.sha256(blob.encode()).hexdigest()[:16] + assert digest == _BEFORE_PHASE_4[name][detail], (name, detail)