diff --git a/autofit/__init__.py b/autofit/__init__.py index 553afd3a7..59e7ef4d5 100644 --- a/autofit/__init__.py +++ b/autofit/__init__.py @@ -122,6 +122,7 @@ from .text import samples_text from .visualise import VisualiseGraph from .graph_spec import GraphSpec, graph_spec_from +from .model_figure import ModelPlotter from .interpolator import ( LinearInterpolator, SplineInterpolator, diff --git a/autofit/config/output.yaml b/autofit/config/output.yaml index 52c885954..19f16e975 100644 --- a/autofit/config/output.yaml +++ b/autofit/config/output.yaml @@ -101,4 +101,10 @@ noise_map: true # `noise_map.json`: The value of every RMS noise map value. search_log: true # `search.log`: logging produced whilst running the fit method -model_graph: false # `model.graph`: graphical-model factor graph summary. Only meaningful for graphical models (autofit.graphical); empty for ordinary PriorModel/Collection fits, so disabled by default. \ No newline at end of file +model_graph: false # `model.graph`: graphical-model factor graph summary. Only meaningful for graphical models (autofit.graphical); empty for ordinary PriorModel/Collection fits, so disabled by default. + +# `model.png`: the model figure drawn beside `model.info` (autofit.model_figure / af.ModelPlotter). +# Opt-in until the lens acceptance renders pass (model-figures epic phase 3). Unlike other keys this +# one does NOT fall back to `default` when absent -- an absent key means off. + +model_figure: false diff --git a/autofit/model_figure/__init__.py b/autofit/model_figure/__init__.py new file mode 100644 index 000000000..98d8c1ecb --- /dev/null +++ b/autofit/model_figure/__init__.py @@ -0,0 +1,19 @@ +""" +The model figure -- a containment picture of a model's structure. + +``model.info`` is the legend; this package draws the map. Three layers, each +importable and testable on its own: + +* :mod:`autofit.model_figure.presentation` -- what is drawn and what it says. +* :mod:`autofit.model_figure.layout` -- where it goes, measured in inches. +* :mod:`autofit.model_figure.render` -- matplotlib. + +:class:`~autofit.model_figure.plotter.ModelPlotter` is the public entry point +and is re-exported as ``af.ModelPlotter``. Importing this package does **not** +import matplotlib: every drawing import is inside a function, so +``import autofit`` stays drawing-free. +""" + +from .plotter import ModelPlotter + +__all__ = ["ModelPlotter"] diff --git a/autofit/model_figure/layout.py b/autofit/model_figure/layout.py new file mode 100644 index 000000000..9ac704c40 --- /dev/null +++ b/autofit/model_figure/layout.py @@ -0,0 +1,711 @@ +""" +Layer 3a of the model figure -- measurement and placement. + +Everything here is in **inches**, so the drawing layer is a straight +transcription and the figure size falls out of the content rather than being +guessed. The two rules the epic's prototype broke, and that this module exists +to keep: + +* **Measure bottom-up, place top-down.** Text is measured with + ``Text.get_window_extent`` on a scratch Agg canvas -- the prototype's width + *estimator* was 11 % short on bold headers and the figure clipped. +* **Fixed text size; collapse, never shrink.** Every font size lives on + :class:`Style` and is the same for the toy Gaussian and the group-scale + model. Scalability comes from the presentation layer collapsing content, and + from top-level cards **wrapping** onto a new row when the width budget is + exhausted -- never from scaling the figure down. + +Declaration order is inviolable: pills flow in the order the presentation +emitted them and children stack in the order they were declared. Nothing is +reordered to fill space (the prototype's masonry floated ``shear`` above +``mass``). + +:meth:`LayoutTree.to_dict` is the determinism artefact: every coordinate is +rounded to 4 dp, so ``json.dumps`` of it is byte-stable for a given model. + +matplotlib is imported **inside** :func:`measure_text`, never at module import, +so ``import autofit`` stays drawing-free. +""" + +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Tuple + +__all__ = [ + "Style", + "PillBox", + "CardBox", + "ConstraintBox", + "LinkRoute", + "LayoutTree", + "measure_text", + "build_layout", +] + + +@dataclass(frozen=True) +class Style: + """ + Fixed geometry and typography. + + Font sizes never vary with model size. ``pad`` *decreases* per nesting + level (review: "reduce padding progressively through nested containers"), + and ``gutter`` inches of the right-hand edge are reserved for cross links + and drawn on by nothing else. + """ + + width: float = 14.0 + dpi: int = 100 + + title_size: float = 9.0 + pill_size: float = 8.0 + badge_size: float = 7.0 + note_size: float = 7.0 + footer_size: float = 7.5 + + margin: float = 0.2 + gutter: float = 0.9 + + max_links: int = 12 + + base_pad: float = 0.17 + pad_shrink: float = 0.7 + min_pad: float = 0.055 + + pill_pad_x: float = 0.075 + pill_pad_y: float = 0.05 + pill_gap: float = 0.07 + inner_gap: float = 0.06 + card_gap: float = 0.13 + title_gap: float = 0.07 + section_gap: float = 0.09 + legend_gap: float = 0.22 + + def pad(self, level: int) -> float: + """Padding of a card at nesting ``level`` (1 = top level).""" + return round( + max(self.min_pad, self.base_pad * self.pad_shrink ** (level - 1)), 4 + ) + + def to_dict(self) -> dict: + return { + "width": self.width, + "dpi": self.dpi, + "title_size": self.title_size, + "pill_size": self.pill_size, + "badge_size": self.badge_size, + "note_size": self.note_size, + "footer_size": self.footer_size, + "gutter": self.gutter, + "max_links": self.max_links, + } + + +# ---------------------------------------------------------------------------- +# text measurement +# ---------------------------------------------------------------------------- + +_CACHE: Dict[Tuple[str, float, str], Tuple[float, float]] = {} +_FIGURE = None + + +def measure_text(text: str, fontsize: float, weight: str = "normal"): + """ + The ``(width, height)`` of ``text`` in **inches**, measured, never estimated. + + A scratch ``FigureCanvasAgg`` is used rather than the live figure so the + measurement is backend independent and available before any figure exists. + Results are cached per ``(text, size, weight)``. + """ + key = (text, round(float(fontsize), 3), weight) + cached = _CACHE.get(key) + if cached is not None: + return cached + + global _FIGURE + if _FIGURE is None: + from matplotlib.backends.backend_agg import FigureCanvasAgg + from matplotlib.figure import Figure + + _FIGURE = Figure(figsize=(1.0, 1.0), dpi=100) + FigureCanvasAgg(_FIGURE) + + renderer = _FIGURE.canvas.get_renderer() + artist = _FIGURE.text(0.0, 0.0, text, fontsize=fontsize, fontweight=weight) + extent = artist.get_window_extent(renderer) + artist.remove() + size = ( + round(extent.width / _FIGURE.dpi, 4), + round(extent.height / _FIGURE.dpi, 4), + ) + _CACHE[key] = size + return size + + +def _line_height(fontsize: float) -> float: + """A stable line height -- ``get_window_extent`` of a glyph-free string is 0.""" + return round(measure_text("Ag", fontsize)[1] * 1.35, 4) + + +# ---------------------------------------------------------------------------- +# boxes +# ---------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class PillBox: + key: str + text: str + state: str + dim2d: bool + badge: Optional[str] + x: float = 0.0 + y: float = 0.0 + width: float = 0.0 + height: float = 0.0 + text_offset: float = 0.0 + tag_offset: Optional[float] = None + badge_offset: Optional[float] = None + + def to_dict(self) -> dict: + return { + "key": self.key, + "text": self.text, + "state": self.state, + "dim2d": self.dim2d, + "badge": self.badge, + "x": round(self.x, 4), + "y": round(self.y, 4), + "width": round(self.width, 4), + "height": round(self.height, 4), + } + + +@dataclass(frozen=True) +class ConstraintBox: + text: str + x: float = 0.0 + y: float = 0.0 + width: float = 0.0 + height: float = 0.0 + + def to_dict(self) -> dict: + return { + "text": self.text, + "x": round(self.x, 4), + "y": round(self.y, 4), + "width": round(self.width, 4), + "height": round(self.height, 4), + } + + +@dataclass(frozen=True) +class CardBox: + key: str + kind: str + title: str + subtitle: Optional[str] = None + badge: Optional[str] = None + note: Optional[str] = None + level: int = 1 + x: float = 0.0 + y: float = 0.0 + width: float = 0.0 + height: float = 0.0 + title_y: float = 0.0 + subtitle_y: Optional[float] = None + note_y: Optional[float] = None + pad: float = 0.0 + pills: Tuple[PillBox, ...] = () + children: Tuple["CardBox", ...] = () + constraints: Tuple[ConstraintBox, ...] = () + + def to_dict(self) -> dict: + return { + "key": self.key, + "kind": self.kind, + "title": self.title, + "subtitle": self.subtitle, + "badge": self.badge, + "note": self.note, + "level": self.level, + "x": round(self.x, 4), + "y": round(self.y, 4), + "width": round(self.width, 4), + "height": round(self.height, 4), + "pad": round(self.pad, 4), + "pills": [pill.to_dict() for pill in self.pills], + "children": [child.to_dict() for child in self.children], + "constraints": [box.to_dict() for box in self.constraints], + } + + +@dataclass(frozen=True) +class LinkRoute: + source_key: str + target_key: str + kind: str + points: Tuple[Tuple[float, float], ...] = () + + def to_dict(self) -> dict: + return { + "source_key": self.source_key, + "target_key": self.target_key, + "kind": self.kind, + "points": [[round(x, 4), round(y, 4)] for x, y in self.points], + } + + +@dataclass(frozen=True) +class LayoutTree: + """Every box of the figure, in inches, with the origin at the top left.""" + + width: float + height: float + cards: Tuple[CardBox, ...] = () + links: Tuple[LinkRoute, ...] = () + legend: str = "" + footer: str = "" + legend_y: float = 0.0 + footer_y: float = 0.0 + style: Style = field(default_factory=Style) + + def walk(self): + def _walk(card): + yield card + for child in card.children: + yield from _walk(child) + + for card in self.cards: + yield from _walk(card) + + def pills(self): + return [pill for card in self.walk() for pill in card.pills] + + def to_dict(self) -> dict: + return { + "width": round(self.width, 4), + "height": round(self.height, 4), + "cards": [card.to_dict() for card in self.cards], + "links": [link.to_dict() for link in self.links], + "legend": self.legend, + "footer": self.footer, + "legend_y": round(self.legend_y, 4), + "footer_y": round(self.footer_y, 4), + "style": self.style.to_dict(), + } + + +# ---------------------------------------------------------------------------- +# measurement +# ---------------------------------------------------------------------------- + +#: The tag drawn on a tuple pill so a pill count reconciles with the footer. +TAG_2D = "2D" + + +def _measure_pill(pill, style: Style) -> PillBox: + text_w, _ = measure_text(pill.text, style.pill_size) + height = round(_line_height(style.pill_size) + 2 * style.pill_pad_y, 4) + + x = style.pill_pad_x + text_offset = x + x += text_w + + tag_offset = None + if pill.dim2d: + x += style.inner_gap + tag_offset = x + x += measure_text(TAG_2D, style.badge_size)[0] + 2 * 0.03 + + badge_offset = None + if pill.badge: + x += style.inner_gap + badge_offset = x + x += measure_text(pill.badge, style.badge_size)[0] + 2 * 0.04 + + return PillBox( + key=pill.key, + text=pill.text, + state=pill.state, + dim2d=pill.dim2d, + badge=pill.badge, + width=round(x + style.pill_pad_x, 4), + height=height, + text_offset=round(text_offset, 4), + tag_offset=None if tag_offset is None else round(tag_offset, 4), + badge_offset=None if badge_offset is None else round(badge_offset, 4), + ) + + +def _wrap(pills: List[PillBox], available: float, style: Style): + """ + Flow ``pills`` into rows no wider than ``available``. + + Greedy and order preserving: a pill never jumps a row to fill a gap. + """ + rows: List[List[PillBox]] = [] + current: List[PillBox] = [] + used = 0.0 + for pill in pills: + step = pill.width if not current else pill.width + style.pill_gap + if current and used + step > available + 1e-9: + rows.append(current) + current = [pill] + used = pill.width + continue + current.append(pill) + used += step + if current: + rows.append(current) + return rows + + +def _row_width(row, style: Style) -> float: + return sum(pill.width for pill in row) + style.pill_gap * (len(row) - 1) + + +def _measure_card( + card, level: int, available: float, style: Style, attached +) -> CardBox: + """ + Size one card and everything inside it. + + ``available`` is the content width this card may occupy. Children are + measured first (bottom-up), the pills are wrapped against the widest of the + title / children / their own natural run, and the card takes the maximum. + """ + pad = style.pad(level) + inner = max(available - 2 * pad, 0.6) + + children = [ + _measure_card(child, level + 1, inner, style, attached) + for child in card.children + ] + widest_child = max((child.width for child in children), default=0.0) + + title_w = measure_text(card.title, style.title_size, "bold")[0] + if card.badge: + title_w += style.inner_gap + measure_text(card.badge, style.badge_size)[0] + 0.1 + subtitle_w = ( + measure_text(card.subtitle, style.badge_size)[0] if card.subtitle else 0.0 + ) + note_w = measure_text(card.note, style.note_size)[0] if card.note else 0.0 + + pills = [_measure_pill(pill, style) for pill in card.pills] + natural = _row_width(pills, style) if pills else 0.0 + target = min(inner, max(natural, widest_child, title_w)) + rows = _wrap(pills, max(target, 0.6), style) if pills else [] + + constraints = [] + for constraint in attached.get(card.key, ()): + width, _ = measure_text(constraint.text, style.badge_size) + constraints.append( + ConstraintBox( + text=constraint.text, + width=round(width + 0.16, 4), + height=round(_line_height(style.badge_size) + 0.08, 4), + ) + ) + + content = max( + [title_w, subtitle_w, note_w, widest_child] + + [_row_width(row, style) for row in rows] + + [box.width for box in constraints] + + [0.6] + ) + + # -- place, top down -------------------------------------------------- + y = pad + title_h = _line_height(style.title_size) + title_y = y + y += title_h + + subtitle_y = None + if card.subtitle: + y += style.title_gap * 0.4 + subtitle_y = y + y += _line_height(style.badge_size) + + if rows: + y += style.title_gap + placed: List[PillBox] = [] + for row in rows: + x = pad + for pill in row: + placed.append( + PillBox( + key=pill.key, + text=pill.text, + state=pill.state, + dim2d=pill.dim2d, + badge=pill.badge, + x=round(x, 4), + y=round(y, 4), + width=pill.width, + height=pill.height, + text_offset=pill.text_offset, + tag_offset=pill.tag_offset, + badge_offset=pill.badge_offset, + ) + ) + x += pill.width + style.pill_gap + y += row[0].height + style.pill_gap + y -= style.pill_gap + pills = placed + else: + pills = [] + + if children: + y += style.section_gap + placed_children = [] + for child in children: + placed_children.append(_translate(child, pad, y)) + y += child.height + style.card_gap + y -= style.card_gap + children = placed_children + + if constraints: + y += style.section_gap + placed_constraints = [] + for box in constraints: + placed_constraints.append( + ConstraintBox( + box.text, round(pad, 4), round(y, 4), box.width, box.height + ) + ) + y += box.height + style.inner_gap + y -= style.inner_gap + constraints = placed_constraints + + note_y = None + if card.note: + y += style.inner_gap + note_y = y + y += _line_height(style.note_size) + + return CardBox( + key=card.key, + kind=card.kind, + title=card.title, + subtitle=card.subtitle, + badge=card.badge, + note=card.note, + level=level, + width=round(content + 2 * pad, 4), + height=round(y + pad, 4), + title_y=round(title_y, 4), + subtitle_y=None if subtitle_y is None else round(subtitle_y, 4), + note_y=None if note_y is None else round(note_y, 4), + pad=pad, + pills=tuple(pills), + children=tuple(children), + constraints=tuple(constraints), + ) + + +def _translate(card: CardBox, dx: float, dy: float) -> CardBox: + """Shift a measured card (and its contents) into its parent's frame.""" + return CardBox( + key=card.key, + kind=card.kind, + title=card.title, + subtitle=card.subtitle, + badge=card.badge, + note=card.note, + level=card.level, + x=round(card.x + dx, 4), + y=round(card.y + dy, 4), + width=card.width, + height=card.height, + title_y=round(card.title_y + dy, 4), + subtitle_y=None if card.subtitle_y is None else round(card.subtitle_y + dy, 4), + note_y=None if card.note_y is None else round(card.note_y + dy, 4), + pad=card.pad, + pills=tuple( + PillBox( + key=pill.key, + text=pill.text, + state=pill.state, + dim2d=pill.dim2d, + badge=pill.badge, + x=round(pill.x + dx, 4), + y=round(pill.y + dy, 4), + width=pill.width, + height=pill.height, + text_offset=pill.text_offset, + tag_offset=pill.tag_offset, + badge_offset=pill.badge_offset, + ) + for pill in card.pills + ), + children=tuple(_translate(child, dx, dy) for child in card.children), + constraints=tuple( + ConstraintBox( + box.text, + round(box.x + dx, 4), + round(box.y + dy, 4), + box.width, + box.height, + ) + for box in card.constraints + ), + ) + + +# ---------------------------------------------------------------------------- +# the figure +# ---------------------------------------------------------------------------- + + +def _pill_index(cards) -> Dict[str, Tuple[PillBox, CardBox]]: + """``pill key -> (the pill, the TOP-LEVEL card it lives in)``. + + The top-level card, not the immediate parent: a link leaves the figure's + content at the outermost frame's edge, because anything closer would have to + cross that frame's boundary to reach the gutter. + """ + index: Dict[str, Tuple[PillBox, CardBox]] = {} + + def _walk(card, top): + for pill in card.pills: + index.setdefault(pill.key, (pill, top)) + for child in card.children: + _walk(child, top) + + for card in cards: + _walk(card, card) + return index + + +def _route(links, cards, content_right: float, style: Style): + """ + Route every cross link through the right-hand gutter. + + The gutter is reserved: nothing else is drawn in it, so a link never runs + alongside a card boundary (review nit: "A_05's blue connector grazes the + plate boundary; give it a dedicated gutter"). Each link gets its own lane, + and every segment is orthogonal. + """ + if len(links) > style.max_links: + # "Use labelled references when links become numerous" -- past a dozen + # routes the gutter is noise, and every referring pill already carries + # its owner's name. + return () + index = _pill_index(cards) + routes: List[LinkRoute] = [] + lanes = max(1, int(style.gutter / 0.17)) + for number, link in enumerate(links): + source = index.get(link.source_key) + target = index.get(link.target_key) + if source is None or target is None: + 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: + # Same visual row: the route would collapse to a meaningless stub in + # the gutter, and the pill's own badge already names its owner. + 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 -- + # clamped rightwards past anything sharing that wrap row, so the segment + # still never enters a card. + start = round(_exit_edge(source[1], cards, sy), 4) + end = round(_exit_edge(target[1], cards, ty), 4) + routes.append( + LinkRoute( + source_key=link.source_key, + target_key=link.target_key, + kind=link.kind, + points=((start, sy), (lane, sy), (lane, ty), (end, ty)), + ) + ) + return tuple(routes) + + +def _exit_edge(card: CardBox, cards, y: float) -> float: + """ + Where a link leaves ``card``: its right edge, unless a sibling top-level card + sits further right at the same height, in which case past that one too. + """ + edge = card.x + card.width + for other in cards: + if other is card: + continue + if other.y <= y <= other.y + other.height and other.x + other.width > edge: + edge = other.x + other.width + return edge + + +def build_layout(presentation, style: Optional[Style] = None) -> LayoutTree: + """ + Measure and place a :class:`~autofit.model_figure.presentation.Presentation`. + + Top-level cards run left to right in declaration order and wrap onto a new + row when the width budget is exhausted -- reading order is across, then + down, and no card is ever moved to fill a gap. + """ + style = style or Style() + budget = max(style.width - 2 * style.margin - style.gutter, 2.0) + + attached: Dict[str, List] = {} + for constraint in presentation.constraints: + attached.setdefault(constraint.key, []).append(constraint) + + measured = [ + _measure_card(card, 1, budget, style, attached) for card in presentation.cards + ] + + placed: List[CardBox] = [] + x = style.margin + y = style.margin + row_height = 0.0 + for card in measured: + if ( + placed + and x > style.margin + and x + card.width > style.margin + budget + 1e-9 + ): + x = style.margin + y += row_height + style.card_gap + row_height = 0.0 + placed.append(_translate(card, x, y)) + x += card.width + style.card_gap + row_height = max(row_height, card.height) + content_bottom = y + row_height + content_right = max((card.x + card.width for card in placed), default=style.margin) + + links = _route(presentation.links, placed, content_right, style) + + bottom = content_bottom + style.legend_gap + legend_y = bottom + bottom += _line_height(style.footer_size) + 0.04 + footer_y = bottom + bottom += _line_height(style.footer_size) + style.margin + + # The legend and footer are content too: a figure sized only to its cards + # clips them (the epic's "no clipped text"). + text_right = style.margin + max( + ( + measure_text(presentation.legend, style.footer_size)[0] + if presentation.legend + else 0.0 + ), + ( + measure_text(presentation.footer, style.footer_size)[0] + if presentation.footer + else 0.0 + ), + ) + width = round(max(content_right + style.gutter, text_right) + style.margin, 4) + return LayoutTree( + width=width, + height=round(bottom, 4), + cards=tuple(placed), + links=links, + legend=presentation.legend, + footer=presentation.footer, + legend_y=round(legend_y, 4), + footer_y=round(footer_y, 4), + style=style, + ) diff --git a/autofit/model_figure/plotter.py b/autofit/model_figure/plotter.py new file mode 100644 index 000000000..42d65027a --- /dev/null +++ b/autofit/model_figure/plotter.py @@ -0,0 +1,174 @@ +""" +The public entry point -- ``af.ModelPlotter(model).figure()``. + +The plotter owns the three layers and nothing else: it builds the +:class:`~autofit.graph_spec.GraphSpec` once (lazily, cached per ``collapse`` +setting), transforms it into a +:class:`~autofit.model_figure.presentation.Presentation`, measures it into a +:class:`~autofit.model_figure.layout.LayoutTree` and draws it. Each step is +also exposed on its own so tests can assert the vocabulary and the geometry +without rendering a pixel. + +The name mirrors the ``*Plotter`` convention used across the organism, and the +signature mirrors ``autofit``'s own plotting convention -- ``path`` is a +directory and ``format`` is one of ``show | png | svg | pdf``, exactly as +``autofit/non_linear/plot/plot_util.py:output_figure`` has it. +""" + +from typing import Optional, Sequence + +__all__ = ["ModelPlotter"] + + +class ModelPlotter: + """ + Draw a model's structure -- the map of which ``model.info`` is the legend. + + Parameters + ---------- + model + Any ``AbstractPriorModel``: ``af.Model``, ``af.Collection``, ``af.Array`` + or a ``FactorGraphModel``'s ``global_prior_model``. + analysis + An optional ``af.Analysis``; its latent catalogue is drawn as ``solved`` + pills marked absent from ``model.info``. + solved_paths + Paths whose rows are re-stated as *solved during fitting*. Phase 3 + supplies the domain rules that populate this. + + Examples + -------- + .. code-block:: python + + af.ModelPlotter(model).figure(path="output", format="png") + af.ModelPlotter(model).figure(detail="priors", show_fixed=False) + """ + + def __init__(self, model, analysis=None, solved_paths: Sequence = ()): + self.model = model + self.analysis = analysis + self.solved_paths = tuple(solved_paths) + self._specs = {} + self._priors = None + + # -- the layers --------------------------------------------------------- + + def spec(self, collapse: bool = True): + """The (cached) semantic tree of the model.""" + from autofit.graph_spec import GraphSpec + + if collapse not in self._specs: + self._specs[collapse] = GraphSpec.from_model( + self.model, + analysis=self.analysis, + collapse=collapse, + solved_paths=self.solved_paths, + ) + return self._specs[collapse] + + def prior_summaries(self): + """``{prior id: "U(0, 100)"}`` -- what ``detail="priors"`` prints.""" + from .presentation import prior_summaries + + if self._priors is None: + self._priors = prior_summaries(self.model) + return self._priors + + def presentation( + self, + detail: str = "names", + collapse: bool = True, + max_depth: Optional[int] = None, + show_fixed: bool = True, + ): + """Layer 2 -- cards, pills, links, constraints, legend and footer.""" + from .presentation import build_presentation + + return build_presentation( + self.spec(collapse=collapse), + detail=detail, + max_depth=max_depth, + show_fixed=show_fixed, + priors=self.prior_summaries() if detail == "priors" else None, + ) + + def layout( + self, + detail: str = "names", + collapse: bool = True, + max_depth: Optional[int] = None, + show_fixed: bool = True, + width: float = 14.0, + style=None, + ): + """Layer 3a -- every box of the figure, in inches.""" + from .layout import Style, build_layout + + style = style or Style(width=width) + return build_layout( + self.presentation( + detail=detail, + collapse=collapse, + max_depth=max_depth, + show_fixed=show_fixed, + ), + style=style, + ) + + # -- the figure --------------------------------------------------------- + + def figure( + self, + path=None, + filename: str = "model", + format: str = "show", + detail: str = "names", + collapse: bool = True, + max_depth: Optional[int] = None, + show_fixed: bool = True, + width: float = 14.0, + style=None, + ): + """ + Draw the model figure and show or save it. + + Parameters + ---------- + path + The **directory** the file is written to (as everywhere else in + autofit). ``None`` writes nothing. + filename + The file's stem; the extension comes from ``format``. + format + ``show`` | ``png`` | ``svg`` | ``pdf``, or ``None`` to build the + figure without showing or writing it. + detail + ``names`` (the map) or ``priors`` (the map with the legend's numbers + on it). + collapse + Whether repeated sibling components collapse into plates. + max_depth + Fold anything deeper into one ``… N components / M priors`` row. + show_fixed + Fixed parameters are shown by default; hiding them prints a visible + hidden count in the footer. + width + The width budget in inches. Top-level cards wrap within it; text is + never scaled down to fit. + + Returns + ------- + The ``matplotlib`` ``Figure``. + """ + from .render import draw, save + + layout = self.layout( + detail=detail, + collapse=collapse, + max_depth=max_depth, + show_fixed=show_fixed, + width=width, + style=style, + ) + figure = draw(layout, layout.style) + return save(figure, path=path, filename=filename, format=format) diff --git a/autofit/model_figure/presentation.py b/autofit/model_figure/presentation.py new file mode 100644 index 000000000..c86bec62e --- /dev/null +++ b/autofit/model_figure/presentation.py @@ -0,0 +1,1010 @@ +""" +Layer 2 of the model figure -- the presentation transformation. + +This module turns a :class:`~autofit.graph_spec.GraphSpec` (layer 1, the +semantic tree) into a :class:`Presentation` (cards, pills, links, constraints, +legend, footer). It decides **what is drawn and what it says**; it decides +nothing about **where** anything goes and it imports no drawing library -- +``layout.py`` measures and places, ``render.py`` draws. + +The vocabulary +-------------- + +The encoding is the epic's v2 vocabulary as amended by the independent review +(``PyAutoMind/draft/feature/autofit/model_figures_epic.md``). Its two load +bearing ideas: + +* **Sharing is a property, not a state.** A shared prior is still sampled, so + it keeps its ``free`` pill and gains a blue *badge*. The first occurrence in + visual order owns the parameter (``shared across group`` inside a plate, + ``shared x k`` otherwise); every later occurrence carries ``-> owner.path`` + and a :class:`Link`. +* **Repetition is not sharing.** A plate badge reads ``30 components``, never + ``x30``; a constant that differs between plate members reads + ``fixed, varies by member``; a free prior repeated independently across a + plate's members is badged ``independent``. + +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``. + +Known limitation carried from layer 1 +------------------------------------- + +A :class:`~autofit.graph_spec.ParamRow` records ``prior_cls_name`` but not the +prior's *parameters*, so ``detail="priors"`` cannot be served from the spec +alone. :func:`prior_summaries` builds a ``{prior id: "U(0, 100)"}`` map from the +model itself and :func:`build_presentation` accepts it as ``priors=``; +``ModelPlotter`` supplies it. Without it ``detail="priors"`` degrades to the +prior's class initial rather than inventing numbers. +""" + +from dataclasses import dataclass +from typing import Any, Dict, List, Optional, Sequence, Tuple + +__all__ = [ + "Pill", + "Card", + "Constraint", + "Link", + "Presentation", + "build_presentation", + "prior_summaries", + "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. +STATES = ( + "free", + "fixed", + "fixed-varies", + "relation", + "solved", + "missing", + "observed", + "drawn", + "folded", +) + +#: ``Prior`` class name -> the compact symbol the figure prints. +_PRIOR_SYMBOLS = { + "UniformPrior": "U", + "GaussianPrior": "N", + "LogUniformPrior": "LogU", + "LogGaussianPrior": "LogN", + "TruncatedGaussianPrior": "TN", +} + +#: The parameters printed for each compact symbol, in order. +_PRIOR_FIELDS = { + "U": ("lower_limit", "upper_limit"), + "N": ("mean", "sigma"), + "LogU": ("lower_limit", "upper_limit"), + "LogN": ("mean", "sigma"), + "TN": ("mean", "sigma", "lower_limit", "upper_limit"), +} + + +# ---------------------------------------------------------------------------- +# formatting helpers +# ---------------------------------------------------------------------------- + + +def _value(value) -> str: + """ + A value written as Python writes it -- ``1.0`` stays ``1.0``. + + Used where the value *is* the statement (the ``redshift = 0.5`` subtitle): + a redshift printed as ``1`` reads like an index, not a redshift. + """ + if isinstance(value, bool) or not isinstance(value, (int, float)): + return str(value) + return repr(value) + + +def _plural(count: int, singular: str, plural: Optional[str] = None) -> str: + """``1 plate`` / ``2 plates`` / ``0 shared priors``.""" + return f"{count} {singular if count == 1 else (plural or singular + 's')}" + + +def _number(value) -> str: + """A compact, locale-free rendering of a number (``100.0`` -> ``100``).""" + if value is None: + return "?" + if isinstance(value, bool): + return str(value) + if isinstance(value, (int, float)): + return f"{value:g}" + return str(value) + + +def compact_prior(prior) -> str: + """ + ``U(0, 100)`` / ``N(0.5, 0.1)`` / ``LogU(1e-06, 1e+06)`` / ``TN(...)``. + + A presentation-layer mapping of the strings ``model.info`` already prints + (``Prior.parameter_string``) -- never a second source of truth for the + numbers themselves. + """ + name = type(prior).__name__ + symbol = _PRIOR_SYMBOLS.get(name) + if symbol is None: + return name.replace("Prior", "") + values = [ + _number(getattr(prior, field_name, None)) + for field_name in _PRIOR_FIELDS[symbol] + ] + return f"{symbol}({', '.join(values)})" + + +def prior_summaries(model) -> Dict[int, str]: + """ + ``{prior id: compact summary}`` for every prior in ``model``. + + Layer 1 does not carry prior parameters (see the module docstring), so this + reads them from the model and hands them to :func:`build_presentation`. + """ + summaries: Dict[int, str] = {} + for prior in getattr(model, "priors", ()): + summaries[prior.id] = compact_prior(prior) + return summaries + + +# ---------------------------------------------------------------------------- +# the presentation data model +# ---------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class Pill: + """One parameter slot as it will be drawn.""" + + text: str + state: str + dim2d: bool = False + badge: Optional[str] = None + key: str = "" + + def to_dict(self) -> dict: + return { + "text": self.text, + "state": self.state, + "dim2d": self.dim2d, + "badge": self.badge, + "key": self.key, + } + + +@dataclass(frozen=True) +class Card: + """One component, collection frame or plate as it will be drawn.""" + + title: str + kind: str + subtitle: Optional[str] = None + pills: Tuple[Pill, ...] = () + children: Tuple["Card", ...] = () + badge: Optional[str] = None + note: Optional[str] = None + key: str = "" + + def to_dict(self) -> dict: + return { + "title": self.title, + "kind": self.kind, + "subtitle": self.subtitle, + "pills": [pill.to_dict() for pill in self.pills], + "children": [child.to_dict() for child in self.children], + "badge": self.badge, + "note": self.note, + "key": self.key, + } + + +@dataclass(frozen=True) +class Constraint: + """ + An assertion, drawn as a compact label carrying both operand paths. + + ``key`` is the key of the card it is attached to -- the deepest card + containing both operands, or the first top-level card when neither operand + resolves into the tree. Assertions are never edges (review: "long orange + routes past several junctions are not acceptable"). + """ + + text: str + left: str + right: str + key: str = "" + + def to_dict(self) -> dict: + return { + "text": self.text, + "left": self.left, + "right": self.right, + "key": self.key, + } + + +@dataclass(frozen=True) +class Link: + """A cross reference drawn through the figure's right-hand gutter.""" + + source_key: str + target_key: str + kind: str + + def to_dict(self) -> dict: + return { + "source_key": self.source_key, + "target_key": self.target_key, + "kind": self.kind, + } + + +@dataclass(frozen=True) +class Presentation: + """Everything the layout engine needs, and nothing about pixels.""" + + cards: Tuple[Card, ...] = () + links: Tuple[Link, ...] = () + constraints: Tuple[Constraint, ...] = () + legend: str = "" + footer: str = "" + hidden_fixed: int = 0 + + def to_dict(self) -> dict: + return { + "cards": [card.to_dict() for card in self.cards], + "links": [link.to_dict() for link in self.links], + "constraints": [constraint.to_dict() for constraint in self.constraints], + "legend": self.legend, + "footer": self.footer, + "hidden_fixed": self.hidden_fixed, + } + + def walk(self): + """Every card, depth first, in visual order.""" + + def _walk(card): + yield card + for child in card.children: + yield from _walk(child) + + for card in self.cards: + yield from _walk(card) + + def pills(self): + """Every pill of every card, in visual order.""" + return [pill for card in self.walk() for pill in card.pills] + + +# ---------------------------------------------------------------------------- +# the transformation +# ---------------------------------------------------------------------------- + + +def _dotted(key: str) -> str: + return key.replace("/", ".") + + +def _key(path) -> str: + return "/".join(path) + + +class _Context: + """ + Everything the per-rule functions need to look at the whole spec at once. + + Built once per :func:`build_presentation` call: the member -> representative + prefix map a collapse leaves behind, the visual order of every row, and the + plate each node sits in. + """ + + def __init__(self, spec, priors, detail): + self.spec = spec + self.priors = priors or {} + self.detail = detail + + self.plates = [node for node in spec.components() if node.plate is not None] + #: member path -> the representative (plate) path it collapses onto. + self.representatives: List[Tuple[tuple, tuple]] = [] + for plate in self.plates: + for member in plate.plate.member_paths[1:]: + self.representatives.append((member, plate.path)) + + self.order: Dict[str, int] = {} + self.plate_of: Dict[str, Any] = {} + self.node_depth: Dict[str, int] = {} + #: every path a drawn row's prior occupies -> that row's key. Layer 1 + #: names a relation operand by the slot the *compound prior* holds it in + #: (``b.sigma.self``), which is a real path but not the one the reader + #: knows; this maps it back onto the row that is drawn (``a.sigma``). + self.by_occurrence: Dict[str, str] = {} + for node, plate, depth in _walk(spec.root): + self.plate_of[_key(node.path)] = plate + self.node_depth[_key(node.path)] = depth + for row in node.rows: + self.order.setdefault(_key(row.path), len(self.order)) + self._record_occurrences(row) + for component in row.components: + self.order.setdefault(_key(component.path), len(self.order)) + self._record_occurrences(component) + + self.states: set = set() + self.badges: set = set() + #: referring pill key -> owner pill key, for the cross links. + self.references: Dict[str, str] = {} + + def _record_occurrences(self, row): + key = _key(row.path) + for occurrence in row.occurrences: + self.by_occurrence.setdefault(_key(occurrence), key) + + # -- collapse-aware path resolution ------------------------------------- + + def representative(self, path) -> tuple: + """ + ``path`` with any collapsed-member prefix replaced by its plate's. + + An occurrence inside member 7 of an 8-member plate is drawn on the + representative, so that is the path a link must point at. + """ + for member, plate_path in self.representatives: + if len(path) >= len(member) and tuple(path[: len(member)]) == member: + return tuple(plate_path) + tuple(path[len(member) :]) + return tuple(path) + + def rendered(self, path) -> Optional[str]: + """The key ``path`` is drawn at, or ``None`` if it is not drawn.""" + key = _key(self.representative(path)) + if key in self.order: + return key + owner = self.by_occurrence.get(key) + if owner is not None: + return owner + if path and path[-1] == "self": + return self.rendered(tuple(path)[:-1]) + return None + + def resolve(self, operand: str) -> str: + """ + An operand name rewritten as the dotted path the figure actually draws. + + ``b.sigma.self * 2.0`` is what layer 1 emits for ``b.sigma = a.sigma * + 2.0``; the reader is looking for ``a.sigma``. + """ + if not operand: + return operand + key = self.rendered(tuple(operand.split("."))) + return _dotted(key) if key else operand + + def resolve_expression(self, expression: str, operands) -> str: + """``expression`` with every operand rewritten by :meth:`resolve`.""" + if not expression: + return expression + for operand in sorted(operands or (), key=len, reverse=True): + resolved = self.resolve(operand) + if resolved != operand: + expression = expression.replace(operand, resolved) + return expression + + +def _walk(node, plate=None, depth=1): + """``(node, enclosing plate node, depth)`` for every node, in visual order.""" + plate = node if node.plate is not None else plate + yield node, plate, depth + for child in node.children: + yield from _walk(child, plate, depth + 1) + + +# -- rule: sharing ----------------------------------------------------------- + + +def _owner_key(row, context) -> Optional[str]: + """ + The key of the *first* occurrence of this row's prior, in visual order. + + That occurrence owns the parameter; every later one refers back to it. + """ + if not row.shared: + return None + keys = [] + for occurrence in row.direct_occurrences: + key = context.rendered(occurrence) + if key is not None and key not in keys: + keys.append(key) + if not keys: + return None + return min(keys, key=lambda key: context.order[key]) + + +def _reference(source: str, owner: str) -> str: + """ + ``owner`` written relative to ``source`` -- a *labelled reference*. + + The review asks for "labelled references when links become numerous", and + the full path of a plate member's owner + (``galaxies.lens.bulge.profile_list.0.centre``) is wider than the card that + carries it. The shared prefix is dropped; :attr:`Link.target_key` keeps the + whole key, so the presentation stays navigable. + """ + source_parts = source.split("/") + owner_parts = owner.split("/") + common = 0 + while ( + common < len(source_parts) - 1 + and common < len(owner_parts) - 1 + and source_parts[common] == owner_parts[common] + ): + common += 1 + return ".".join(owner_parts[common:]) or _dotted(owner) + + +def _shared_descriptor(row, node, plate, context) -> Optional[str]: + """ + The blue badge a shared row carries, or ``None``. + + ``shared across group`` is used when every occurrence lies inside one + plate's members (or the prior is one the plate shares in all of them) -- the + review's separation of repetition from sharing. Otherwise the owner is + badged ``shared ×k`` and every other occurrence points back at it. + """ + owner = _owner_key(row, context) + if owner is None: + return None + key = _key(row.path) + if owner != key: + return f"↗ {_reference(key, owner)}" + if _is_group_shared(row, plate, context): + return "shared across group" + return f"shared ×{len(row.direct_occurrences)}" + + +def _is_group_shared(row, plate, context) -> bool: + if plate is not None and row.prior_id is not None: + if row.prior_id in plate.plate.shared_in_all: + return True + for candidate in context.plates: + members = candidate.plate.member_paths + if len(members) < 2: + continue + if all( + any( + len(occurrence) >= len(member) + and tuple(occurrence[: len(member)]) == member + for member in members + ) + for occurrence in row.direct_occurrences + ): + return True + return False + + +def _badge(row, node, plate, context) -> Optional[str]: + """The badge of a single (scalar) row: sharing first, independence second.""" + shared = _shared_descriptor(row, node, plate, context) + if shared is not None: + return shared + if ( + plate is not None + and plate.plate.count > 1 + and row.sampling == "free" + and row.provenance.kind != "relation" + and not row.shared + ): + # Distinct prior objects with identical configuration, one per member -- + # repetition, never sharing (review point 2). + return "independent" + return None + + +# -- rule: state ------------------------------------------------------------- + + +def _varies(row, plate) -> bool: + if plate is None: + return False + relative = ".".join(row.path[len(plate.path) :]) + return relative in plate.plate.varies_by_member + + +def _state(row, plate) -> str: + kind = row.provenance.kind + if kind == "relation": + return "relation" + if kind == "hierarchical-draw": + return "drawn" + if kind == "observed": + return "observed" + if row.sampling == "solved": + return "solved" + if row.sampling == "missing": + return "missing" + if row.sampling == "fixed": + return "fixed-varies" if _varies(row, plate) else "fixed" + return "free" + + +def _text(row, state, context) -> str: + """The pill's text -- name first, always.""" + name = row.name + if state == "relation": + expression = context.resolve_expression( + row.provenance.expression, row.provenance.operands + ) + return f"{name} = {expression}" + if state == "missing": + return f"{name} · missing" + if state == "fixed-varies": + return f"{name} · fixed, varies by member" + if context.detail != "priors": + return name + if state == "fixed": + if row.dimensionality == "tuple": + values = ", ".join(_number(component.value) for component in row.components) + return f"{name} = ({values})" + if row.is_instance: + return f"{name} = {row.prior_cls_name}" + return f"{name} = {_number(row.value)}" + summary = context.priors.get(row.prior_id) + if summary is None and row.components: + summary = context.priors.get(row.components[0].prior_id) + if summary is None: + summary = _PRIOR_SYMBOLS.get(row.prior_cls_name or "", "") + return f"{name} {summary}".rstrip() + + +# -- rule: rows -> pills ----------------------------------------------------- + + +def _leaf_slots(row) -> int: + return len(row.components) if row.dimensionality == "tuple" else 1 + + +def _pill(row, node, plate, context) -> Pill: + state = _state(row, plate) + key = _key(row.path) + owner = _owner_key(row, context) + if owner is not None and owner != key: + context.references[key] = owner + pill = Pill( + text=_text(row, state, context), + state=state, + dim2d=row.dimensionality == "tuple", + badge=_badge(row, node, plate, context), + key=key, + ) + context.states.add(state) + if pill.badge: + context.badges.add( + pill.badge.split(" ")[0] if pill.badge.startswith("↗") else pill.badge + ) + return pill + + +def _tuple_is_uniform(row, node, plate, context) -> bool: + """ + Whether a tuple's components agree on sampling *and* sharing. + + They must, or the tuple is expanded: a partially fixed or partially shared + tuple flattened into one pill is a lie (review, "Encoding critique"). + """ + descriptors = { + ( + _state(component, plate), + _shared_descriptor(component, node, plate, context) is not None, + (_shared_descriptor(component, node, plate, context) or "").startswith("↗"), + ) + for component in row.components + } + return len(descriptors) == 1 + + +def _tuple_badge(row, node, plate, context) -> Optional[str]: + """The merged tuple pill's badge, derived from its (agreeing) components.""" + badges = [_badge(component, node, plate, context) for component in row.components] + badge = badges[0] + if badge is None: + return None + if badge.startswith("↗"): + # A component's owner is a slot (``...centre.centre_0``); the merged + # pill stands for the whole tuple, so it points at the owning tuple. + component_owner = _owner_key(row.components[0], context) + if component_owner is None: + return badge + owner = component_owner.rsplit("/", 1)[0] + key = _key(row.path) + context.references[key] = owner + return f"↗ {_reference(key, owner)}" + return badge + + +def _pills(node, plate, context, show_fixed) -> Tuple[List[Pill], int, Optional[str]]: + """ + Every drawn pill of one component, the fixed slots hidden, and the redshift + subtitle when the redshift exception applies. + """ + pills: List[Pill] = [] + hidden = 0 + redshift = None + for row in node.rows: + state = _state(row, plate) + if ( + node.kind == "model" + and row.name == "redshift" + and state == "fixed" + and row.dimensionality == "scalar" + ): + # A presentation convenience, not a different semantic rule: a free + # redshift keeps the ordinary sampled-parameter pill. + redshift = f"redshift = {_value(row.value)}" + continue + if not show_fixed and state in ("fixed", "fixed-varies"): + hidden += _leaf_slots(row) + continue + if row.dimensionality == "tuple" and row.components: + if _tuple_is_uniform(row, node, plate, context): + # One pill with a `2D` tag: the components agree, so merging + # them hides nothing. + badge = _tuple_badge(row, node, plate, context) + pills.append( + Pill( + text=_text(row, state, context), + state=state, + dim2d=True, + badge=badge, + key=_key(row.path), + ) + ) + context.states.add(state) + if badge: + context.badges.add("↗" if badge.startswith("↗") else badge) + continue + # Mixed sampling or mixed sharing: expand rather than lie. + for component in row.components: + pills.append(_pill(component, node, plate, context)) + continue + pills.append(_pill(row, node, plate, context)) + return pills, hidden, redshift + + +# -- rule: components -> cards ---------------------------------------------- + + +def _title(node) -> str: + if node.plate is not None: + # The member index ("0") is meaningless for a plate; the class is not. + return node.cls_name + if node.kind == "collection": + return node.name + return f"{node.name} · {node.cls_name}" + + +def _fold_summary(node) -> str: + components = 0 + priors = 0 + for child, _, _ in _walk(node): + components += 1 + for row in child.rows: + if row.dimensionality == "tuple": + priors += sum( + 1 for component in row.components if component.sampling == "free" + ) + elif row.sampling == "free": + priors += 1 + return f"… {components} components / {priors} priors" + + +def _card(node, plate, depth, context, show_fixed, max_depth) -> Tuple[Card, int]: + pills, hidden, redshift = _pills(node, plate, context, show_fixed) + + children: List[Card] = [] + for child in node.children: + child_plate = child if child.plate is not None else plate + if max_depth is not None and depth + 1 > max_depth: + pills.append( + Pill( + text=_fold_summary(child), + state="folded", + key=_key(child.path), + ) + ) + context.states.add("folded") + continue + card, child_hidden = _card( + child, child_plate, depth + 1, context, show_fixed, max_depth + ) + children.append(card) + hidden += child_hidden + + subtitle = None + if node.plate is not None: + subtitle = node.plate.representative_key + if redshift: + subtitle = f"{subtitle} · {redshift}" if subtitle else redshift + elif redshift: + subtitle = redshift + + badge = None + note = None + if not pills and not children and node.plate is None: + # An empty card is not an error and must say so: the review's + # "A_06's empty Hilbert card needs an explicit explanation". + note = "no parameters" + 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" + note = node.plate.repeats[0] if node.plate.repeats else None + context.badges.add("plate") + + return ( + Card( + title=_title(node), + kind="plate" if node.plate is not None else node.kind, + subtitle=subtitle, + pills=tuple(pills), + children=tuple(children), + badge=badge, + note=note, + key=_key(node.path), + ), + hidden, + ) + + +# -- rule: assertions and relations ----------------------------------------- + + +def _operand_key(operand: str, context) -> Optional[str]: + """The drawn key an assertion / relation operand resolves to, if any.""" + if not operand: + return None + path = tuple(operand.split(".")) + for candidate in (path, path[:-1] if path[-1] == "self" else path): + key = context.rendered(candidate) + if key is not None: + return key + return None + + +def _deepest_card(keys: Sequence[str], cards: Sequence[Card]) -> str: + """ + The key of the deepest card containing every key in ``keys``. + + Falls back to the first top-level card, so a constraint whose operands do + not resolve into the tree is still drawn rather than dropped. + """ + candidates = [] + for card in _cards_of(cards): + prefix = card.key + if all( + key == prefix or (prefix == "" or key.startswith(f"{prefix}/")) + for key in keys + ): + candidates.append(card.key) + if not candidates: + return cards[0].key if cards else "" + return max(candidates, key=len) + + +def _cards_of(cards): + for card in cards: + yield card + yield from _cards_of(card.children) + + +#: Comparison operators, mapped to the operator that says the same thing with +#: the operands the other way round. +_INVERTED_OPERATORS = {"<": ">", "<=": ">=", ">": "<", ">=": "<="} + + +def _oriented(left: str, op: str, right: str, context): + """ + The assertion with its **model-side operand first**, when that is unambiguous. + + Layer 1 emits ``5.0 < a.sigma`` for ``add_assertion(a.sigma > 5.0)`` -- true, + but back to front for a reader looking for ``a.sigma``. The operands are + swapped (and the operator inverted) only when exactly one side resolves to a + drawn parameter and the operator has an inverse; anything else keeps the + spec's order rather than guessing. + """ + if op not in _INVERTED_OPERATORS: + return left, op, right + left_is_model = _operand_key(left, context) is not None + right_is_model = _operand_key(right, context) is not None + if right_is_model and not left_is_model: + return right, _INVERTED_OPERATORS[op], left + return left, op, right + + +def _constraints(spec, cards, context) -> Tuple[Constraint, ...]: + constraints = [] + for assertion in spec.assertions: + left, op, right = _oriented( + context.resolve(assertion.left), + assertion.op, + context.resolve(assertion.right), + context, + ) + keys = [ + key + for key in ( + _operand_key(left, context), + _operand_key(right, context), + ) + if key is not None + ] + constraints.append( + Constraint( + # "assert" in the label, a dashed outline in the drawing: a + # constraint is not a relation, and must not read as one. + text=f"assert {left} {op} {right}", + left=left, + right=right, + key=_deepest_card(keys, cards) if cards else "", + ) + ) + return tuple(constraints) + + +def _links(spec, presentation_keys, context) -> Tuple[Link, ...]: + links: List[Link] = [] + seen = set() + drawn = {key for key, _ in presentation_keys} + for pill_key in sorted( + context.references, key=lambda key: context.order.get(key, 0) + ): + target = context.references[pill_key] + if pill_key in drawn and target in context.order: + seen.add((pill_key, target)) + links.append(Link(pill_key, target, "shared")) + for relation in spec.relations: + target = context.rendered(relation.target_path) + if target is None: + continue + for operand in relation.operand_paths: + source = context.rendered(operand) + if source is None or source == target: + continue + if (target, source) in seen: + continue + seen.add((target, source)) + links.append(Link(target, source, "relation")) + return tuple(links) + + +# -- rule: legend and footer ------------------------------------------------- + +_LEGEND_WORDS = { + "free": "free prior", + "fixed": "fixed value", + "fixed-varies": "fixed, varies by member", + "relation": "relation (expression shown)", + "solved": "solved during fitting (dashed)", + "missing": "missing configuration (red)", + "observed": "observed data", + "drawn": "drawn from a hyper-prior", + "folded": "folded subtree", +} + + +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 "independent" in context.badges: + parts.append("independent = one prior per member") + if "plate" in context.badges: + parts.append("dashed frame = repeated components") + if constraints: + parts.append("dashed orange = constraint (assertion)") + return "Legend: " + " · ".join(parts) + + +def _plate_members(spec) -> int: + """How many components the plates stand for -- the sum of their counts.""" + return sum(node.plate.count for node in spec.components() if node.plate is not None) + + +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)", + ] + if counts.get("missing"): + parts.append(f"{counts['missing']} missing") + plates = counts.get("plates") or 0 + if plates: + # What the plates stand for, not how many boxes the tree lost: the + # latter counts collection frames and muddles the 11-boxes acceptance. + parts.append( + f"{_plural(plates, 'plate')} standing for " + f"{_plural(_plate_members(spec), 'component')}" + ) + if hidden_fixed: + parts.append(_plural(hidden_fixed, "fixed parameter") + " hidden") + else: + parts.append("totals include every hidden and collapsed element") + return " · ".join(parts) + + +# -- the entry point --------------------------------------------------------- + + +def build_presentation( + spec, + detail: str = "names", + max_depth: Optional[int] = None, + show_fixed: bool = True, + priors: Optional[Dict[int, str]] = None, +) -> Presentation: + """ + Turn a :class:`~autofit.graph_spec.GraphSpec` into a :class:`Presentation`. + + Parameters + ---------- + spec + The semantic tree (layer 1). + detail + ``"names"`` -- the default map, name-only pills -- or ``"priors"``, + which adds each pill's compact prior summary or fixed value. + max_depth + Cards deeper than this fold into one ``… N components / M priors`` row. + show_fixed + Fixed pills are shown by default because they explain model structure. + Hiding them prints a visible hidden count in the footer. + priors + ``{prior id: "U(0, 100)"}``, from :func:`prior_summaries`. Required for + ``detail="priors"`` (layer 1 does not carry prior parameters). + + Notes + ----- + The outer frame is dropped when it adds no branching information -- a root + ``Collection`` that carries no rows of its own contributes nothing but a box + around its children, so its children become the top-level cards. A root + ``Model`` keeps its card: it owns rows. + """ + if detail not in ("names", "priors"): + raise ValueError(f"detail must be 'names' or 'priors', not {detail!r}") + + context = _Context(spec, priors, detail) + root = spec.root + + hidden_fixed = 0 + cards: List[Card] = [] + if root.kind == "collection" 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) + cards.append(card) + hidden_fixed += hidden + else: + plate = root if root.plate is not None else None + card, hidden_fixed = _card(root, plate, 1, context, show_fixed, max_depth) + cards.append(card) + + presentation_keys = [ + (pill.key, pill.badge) for card in _cards_of(cards) for pill in card.pills + ] + drawn = {key for key, _ in presentation_keys} + links = tuple( + link + for link in _links(spec, presentation_keys, context) + if link.source_key in drawn and link.target_key in drawn + ) + constraints = _constraints(spec, cards, context) + + return Presentation( + cards=tuple(cards), + links=links, + constraints=constraints, + legend=_legend(context, constraints), + footer=_footer(spec, hidden_fixed), + hidden_fixed=hidden_fixed, + ) diff --git a/autofit/model_figure/render.py b/autofit/model_figure/render.py new file mode 100644 index 000000000..dd1675dbc --- /dev/null +++ b/autofit/model_figure/render.py @@ -0,0 +1,403 @@ +""" +Layer 3b of the model figure -- drawing. + +Pure matplotlib: rounded ``FancyBboxPatch`` cards and pills, ``ax.text`` labels +and ``Line2D`` cross links. **Zero new dependencies** -- graphviz is +deliberately not adopted (the ``dot`` binary is absent locally, on the GitHub +``ubuntu-24.04`` runner and often on Colab, and its rank layout is wasted on a +containment figure). + +The layout has already decided every coordinate, in inches, so the axes are set +up as one inch per data unit with the y axis inverted: what :mod:`layout` calls +``y`` grows downward, as reading order does. + +matplotlib is imported inside the functions, following +``autofit/non_linear/plot/plot_util.py``, so importing :mod:`autofit` never +drags a drawing library in. + +Palette: near monochrome, **three card tints only** (review: "let boundaries, +indentation and labels carry hierarchy; tint should assist"). Blue is sharing +and nothing else; orange is relations and constraints and nothing else; red is +missing configuration. +""" + +import os +from pathlib import Path + +__all__ = ["draw", "save", "PALETTE"] + + +PALETTE = { + "tints": ("#ffffff", "#f5f5f9", "#ebebf1"), + "border": "#9c9ca8", + "plate_border": "#6f6f7d", + "text": "#17171d", + "muted": "#4c4c57", + "blue": "#15539e", + "blue_fill": "#e2ecfb", + "orange": "#9c4a06", + "cream": "#fdf3e1", + "grey_fill": "#e3e3e9", + "pill_border": "#b4b4c0", + "red": "#a81f16", + "red_fill": "#fceceb", + "tag_fill": "#ececf1", +} + +#: ``state -> (face colour, edge colour, text colour, dashed)`` +_PILL_STYLE = { + "free": ("#ffffff", PALETTE["pill_border"], PALETTE["text"], False), + "fixed": (PALETTE["grey_fill"], PALETTE["pill_border"], PALETTE["muted"], False), + "fixed-varies": ( + PALETTE["grey_fill"], + PALETTE["plate_border"], + PALETTE["muted"], + False, + ), + "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), + "folded": ("#f4f4f8", PALETTE["pill_border"], PALETTE["muted"], True), +} + + +def _box( + ax, x, y, width, height, *, face, edge, dashed=False, lw=0.8, radius=0.045, z=1 +): + from matplotlib.patches import FancyBboxPatch + + patch = FancyBboxPatch( + (x, y), + width, + height, + boxstyle=f"round,pad=0,rounding_size={radius}", + linewidth=lw, + facecolor=face, + edgecolor=edge, + linestyle=(0, (2.4, 1.6)) if dashed else "solid", + mutation_aspect=1.0, + zorder=z, + ) + ax.add_patch(patch) + return patch + + +def _text(ax, x, y, text, *, size, colour, weight="normal", z=3): + ax.text( + x, + y, + text, + fontsize=size, + color=colour, + fontweight=weight, + ha="left", + va="center", + zorder=z, + ) + + +def _badge_colours(badge: str): + """Blue for sharing; neutral for everything else (repetition is not sharing).""" + if badge.startswith("shared") or badge.startswith("↗"): + return PALETTE["blue_fill"], PALETTE["blue"] + return PALETTE["tag_fill"], PALETTE["muted"] + + +def _draw_pill(ax, pill, style, card_level=1): + from .layout import TAG_2D + + face, edge, colour, dashed = _PILL_STYLE.get(pill.state, _PILL_STYLE["free"]) + _box( + ax, + pill.x, + pill.y, + pill.width, + pill.height, + face=face, + edge=edge, + dashed=dashed, + lw=1.1 if pill.state == "missing" else 0.8, + radius=0.035, + z=40 + card_level, + ) + middle = pill.y + pill.height / 2 + _text( + ax, + pill.x + pill.text_offset, + middle, + pill.text, + size=style.pill_size, + colour=colour, + z=60 + card_level, + ) + if pill.tag_offset is not None: + tag_w = pill.width - pill.tag_offset - style.pill_pad_x + if pill.badge_offset is not None: + tag_w = pill.badge_offset - pill.tag_offset - style.inner_gap + _box( + ax, + pill.x + pill.tag_offset, + pill.y + 0.035, + max(tag_w, 0.05), + pill.height - 0.07, + face=PALETTE["tag_fill"], + edge=PALETTE["tag_fill"], + radius=0.02, + z=50 + card_level, + ) + _text( + ax, + pill.x + pill.tag_offset + 0.03, + middle, + TAG_2D, + size=style.badge_size, + colour=PALETTE["muted"], + z=60 + card_level, + ) + if pill.badge_offset is not None: + fill, colour = _badge_colours(pill.badge) + _box( + ax, + pill.x + pill.badge_offset, + pill.y + 0.035, + pill.width - pill.badge_offset - style.pill_pad_x, + pill.height - 0.07, + face=fill, + edge=fill, + radius=0.02, + z=50 + card_level, + ) + _text( + ax, + pill.x + pill.badge_offset + 0.04, + middle, + pill.badge, + size=style.badge_size, + colour=colour, + z=60 + card_level, + ) + + +def _draw_card(ax, card, style): + from .layout import _line_height, measure_text + + tint = PALETTE["tints"][min(card.level - 1, len(PALETTE["tints"]) - 1)] + plate = card.kind == "plate" + _box( + ax, + card.x, + card.y, + card.width, + card.height, + face=tint, + edge=PALETTE["plate_border"] if plate else PALETTE["border"], + dashed=plate, + lw=1.1 if card.level == 1 or plate else 0.8, + z=card.level, + ) + + title_middle = card.title_y + _line_height(style.title_size) / 2 + _text( + ax, + card.x + card.pad, + title_middle, + card.title, + size=style.title_size, + colour=PALETTE["text"], + weight="bold", + z=card.level + 0.5, + ) + if card.badge: + width = measure_text(card.title, style.title_size, "bold")[0] + badge_w = measure_text(card.badge, style.badge_size)[0] + 0.1 + badge_x = card.x + card.pad + width + style.inner_gap + _box( + ax, + badge_x, + card.title_y + 0.03, + badge_w, + _line_height(style.title_size) - 0.06, + face=PALETTE["tag_fill"], + edge=PALETTE["plate_border"], + radius=0.02, + lw=0.6, + z=card.level + 0.4, + ) + _text( + ax, + badge_x + 0.05, + title_middle, + card.badge, + size=style.badge_size, + colour=PALETTE["muted"], + z=card.level + 0.5, + ) + if card.subtitle: + _text( + ax, + card.x + card.pad, + card.subtitle_y + _line_height(style.badge_size) / 2, + card.subtitle, + size=style.badge_size, + colour=PALETTE["muted"], + z=card.level + 0.5, + ) + + for pill in card.pills: + _draw_pill(ax, pill, style, card.level) + + for box in card.constraints: + # Dashed outline, no fill: a constraint is not a relation, and the solid + # cream relation pill must stay distinguishable from it. + _box( + ax, + box.x, + box.y, + box.width, + box.height, + face="none", + edge=PALETTE["orange"], + dashed=True, + radius=0.025, + lw=0.9, + z=70, + ) + _text( + ax, + box.x + 0.08, + box.y + box.height / 2, + box.text, + size=style.badge_size, + colour=PALETTE["orange"], + z=71, + ) + + if card.note: + _text( + ax, + card.x + card.pad, + card.note_y + _line_height(style.note_size) / 2, + card.note, + size=style.note_size, + colour=PALETTE["muted"], + z=card.level + 0.5, + ) + + for child in card.children: + _draw_card(ax, child, style) + + +def _draw_link(ax, route): + from matplotlib.lines import Line2D + + colour = PALETTE["blue"] if route.kind == "shared" else PALETTE["orange"] + xs = [x for x, _ in route.points] + ys = [y for _, y in route.points] + ax.add_line( + Line2D( + xs, + ys, + color=colour, + linewidth=0.9 if route.kind == "shared" else 0.7, + linestyle="solid" if route.kind == "shared" else (0, (3, 1.6)), + solid_capstyle="round", + zorder=80, + ) + ) + # A filled dot where each end touches the card it belongs to. + ax.add_line( + Line2D( + [xs[0], xs[-1]], + [ys[0], ys[-1]], + linestyle="none", + marker="o", + markersize=2.6, + markerfacecolor=colour, + markeredgecolor=colour, + color=colour, + zorder=81, + ) + ) + + +def draw(layout, style=None): + """ + Draw a measured :class:`~autofit.model_figure.layout.LayoutTree`. + + One axes, one inch per data unit, y inverted and the axis off, so every + coordinate the layout computed is used verbatim. + """ + import matplotlib.pyplot as plt + from .layout import _line_height + + style = style or layout.style + + figure = plt.figure(figsize=(layout.width, layout.height), dpi=style.dpi) + ax = figure.add_axes([0.0, 0.0, 1.0, 1.0]) + ax.set_xlim(0.0, layout.width) + ax.set_ylim(layout.height, 0.0) + ax.set_aspect("equal") + ax.axis("off") + figure.patch.set_facecolor("#ffffff") + + for card in layout.cards: + _draw_card(ax, card, style) + for route in layout.links: + _draw_link(ax, route) + + if layout.legend: + _text( + ax, + style.margin, + layout.legend_y + _line_height(style.footer_size) / 2, + layout.legend, + size=style.footer_size, + colour=PALETTE["muted"], + z=90, + ) + if layout.footer: + _text( + ax, + style.margin, + layout.footer_y + _line_height(style.footer_size) / 2, + layout.footer, + size=style.footer_size, + colour=PALETTE["text"], + z=90, + ) + return figure + + +def save(figure, path=None, filename="model", format="show"): + """ + Show or write the figure, mirroring + ``autofit/non_linear/plot/plot_util.py:output_figure`` with ``svg`` added. + + ``format=None`` builds the figure and neither shows nor writes it; any other + unrecognised format raises rather than silently doing nothing. + + ``metadata={"Software": None}`` keeps PNG bytes identical between two saves + of the same model, which the determinism acceptance needs. + """ + import matplotlib.pyplot as plt + + if format is None: + # Built, neither shown nor written -- the caller owns the figure and is + # responsible for closing it. + return figure + if format == "show": + plt.show() + return figure + if format not in ("png", "pdf", "svg"): + raise ValueError( + f"format must be one of None, 'show', 'png', 'svg', 'pdf', not {format!r}" + ) + if path is not None: + os.makedirs(path, exist_ok=True) + target = Path(path) / f"{filename}.{format}" + metadata = {"Software": None} if format == "png" else None + figure.savefig(target, format=format, metadata=metadata) + plt.close(figure) + return figure diff --git a/autofit/non_linear/paths/directory.py b/autofit/non_linear/paths/directory.py index e82cb7b6e..0b432c479 100644 --- a/autofit/non_linear/paths/directory.py +++ b/autofit/non_linear/paths/directory.py @@ -16,6 +16,8 @@ from autofit.tools.util import open_, open_atomic, NumpyEncoder from autofit.non_linear.samples.samples import Samples +from autofit.non_linear.test_mode import skip_visualization + from .abstract import AbstractPaths, _test_mode_segment from ..samples import load_from_table @@ -27,6 +29,26 @@ logger = logging.getLogger(__name__) +def _model_figure_enabled() -> bool: + """ + Whether `model.png` -- the model figure drawn beside `model.info` -- is written. + + The `output.yaml` key `model_figure` is read **strictly**: an absent key means + off. + + This deliberately does NOT use `autonerves.output.should_output` + (`autonerves/output.py:should_output`), which falls back to `output.yaml`'s + `default:` entry whenever a key is absent. That entry is `true` in every + workspace, so a brand new key that so far only exists in the library's own + default config would silently switch the figure ON in every config which has + not yet added it. Only a config that explicitly opts in writes the file. + """ + try: + return bool(conf.instance["output"]["model_figure"]) + except KeyError: + return False + + class DirectoryPaths(AbstractPaths): def _path_for_pickle(self, name: str, prefix: str = "") -> Path: return self._files_path / prefix / f"{name}.pickle" @@ -502,6 +524,18 @@ def _save_model_info(self, model): with open_(self.output_path / "model.graph", "w+") as f: f.write(model.graph_info) + if _model_figure_enabled() and not skip_visualization(): + try: + from autofit.model_figure import ModelPlotter + + ModelPlotter(model).figure( + path=self.output_path, + filename="model", + format="png", + ) + except Exception as e: + logger.info(f"model.png not written: {e!r}") + def _save_model_start_point(self, info): """ Save the model.start file, which summarises the start point of every parameter. diff --git a/docs/cookbooks/model.md b/docs/cookbooks/model.md index 02853d8b4..34e4cfac6 100644 --- a/docs/cookbooks/model.md +++ b/docs/cookbooks/model.md @@ -111,6 +111,25 @@ normalization LogUniformPrior [2], lower_limit = 1e-06, upper_li sigma UniformPrior [3], lower_limit = 0.0, upper_limit = 25.0 ``` +We can also draw the model, via `af.ModelPlotter`: + +```python +af.ModelPlotter(model).figure() +``` + +```{image} https://raw.githubusercontent.com/PyAutoLabs/PyAutoFit/main/docs/images/model_figures/gaussian.png +:alt: The model figure of a single Gaussian, drawn as one component card containing a pill for each of its three free parameters. +:width: 600 +``` + +The figure is the **map** of a model and the `info` above is its **legend**: the map shows the structure, meaning +which components own which parameters and which of those parameters are fixed, shared, related to one another or +constrained, whereas the `info` lists the priors and values themselves. For a model this simple the two say much the +same thing, but the map is what stays readable as models grow. + +Setting `model_figure: true` in a workspace's `config/output.yaml` writes this figure as a `model.png` beside +`model.info` for every search, so every fit keeps its own map. + ## Priors (Model) The model has a set of default priors, which have been loaded from a config file in the PyAutoFit workspace. @@ -286,6 +305,25 @@ normalization LogUniformPrior [14], lower_limit = 1e-06, uppe sigma UniformPrior [15], lower_limit = 0.0, upper_limit = 25.0 ``` +Customization is where the model figure starts to earn its place, because fixing a parameter or overwriting a prior +changes a model's structure and not just its numbers: + +```python +model = af.Model(Gaussian) +model.centre = 0.0 +model.normalization = af.UniformPrior(lower_limit=0.0, upper_limit=10.0) + +af.ModelPlotter(model).figure() +``` + +```{image} https://raw.githubusercontent.com/PyAutoLabs/PyAutoFit/main/docs/images/model_figures/gaussian_customised.png +:alt: The model figure of a customized Gaussian, with the fixed centre drawn as a greyed out pill and normalization and sigma left as free white pills. +:width: 600 +``` + +The fixed `centre` is drawn greyed out and the footer counts it as a fixed leaf slot rather than a sampled scalar, so +the map says at a glance that this model is fitted with two free parameters and not three. + The overwriting of priors shown above can be achieved via the following alternative API: ```python @@ -627,6 +665,21 @@ Total Free Parameters = 4 > normalization LogUniformPrior [72], lower_limit = 1e-06, upper_limit = 1000000.0 > rate UniformPrior [73], lower_limit = 0.0, upper_limit = 1.0 +A `Collection` is drawn as one card per component, with any assertion attached to the component it constrains: + +```python +af.ModelPlotter(model).figure() +``` + +```{image} https://raw.githubusercontent.com/PyAutoLabs/PyAutoFit/main/docs/images/model_figures/gaussian_collection.png +:alt: The model figure of a Collection of a Gaussian and an Exponential, with their fixed parameters greyed out and the rate assertion drawn inside the Exponential card. +:width: 600 +``` + +The map puts the two fixed values (`gaussian.normalization` and `exponential.centre`) and the assertion +`exponential.rate > 5.0` into a single read. The assertion in particular does not appear in the `info` above at all, +which is the clearest case of the map carrying something the legend cannot. + Below is an alternative API that can be used to create the same model as above. Which API is used is up to the user and which they find most intuitive. diff --git a/docs/cookbooks/multi_level_model.md b/docs/cookbooks/multi_level_model.md index 81e1c5472..c232fc4d7 100644 --- a/docs/cookbooks/multi_level_model.md +++ b/docs/cookbooks/multi_level_model.md @@ -107,6 +107,23 @@ gaussian_list sigma UniformPrior [4], lower_limit = 0.0, upper_limit = 25.0 ``` +The hierarchy the `info` indents is what the model figure draws as containment: + +```python +af.ModelPlotter(model).figure() +``` + +```{image} https://raw.githubusercontent.com/PyAutoLabs/PyAutoFit/main/docs/images/model_figures/multi_level.png +:alt: The model figure of a multi-level model, with the gaussian_list frame and its repeated Gaussian components nested inside the MultiLevelGaussians card that owns higher_level_centre. +:width: 600 +``` + +The figure is the **map** of the model and the `info` above is its **legend**: the map shows which component owns +which parameters, so `higher_level_centre` sits in the outer `MultiLevelGaussians` card while the two `Gaussian`'s +sit inside the `gaussian_list` frame nested within it. That is exactly the reason to use a multi-level model, drawn +rather than indented, and the repeated `Gaussian`'s are collapsed into a single frame labelled with how many +components it stands for. + ## Instances Instances of a multi-level model can be created, where an input `vector` of parameters is mapped to create an instance diff --git a/docs/cookbooks/multiple_datasets.md b/docs/cookbooks/multiple_datasets.md index 4ea94cfa2..bbbad7a20 100644 --- a/docs/cookbooks/multiple_datasets.md +++ b/docs/cookbooks/multiple_datasets.md @@ -172,6 +172,22 @@ To inspect the model, we print `factor_graph.global_prior_model.info`. print(factor_graph.global_prior_model.info) ``` +The figure is the **map** of this global model and the `info` is its **legend**: the map shows the structure, meaning +which dataset gets which component and which parameters are shared between them, while the `info` lists the priors. + +```python +af.ModelPlotter(factor_graph.global_prior_model).figure() +``` + +```{image} https://raw.githubusercontent.com/PyAutoLabs/PyAutoFit/main/docs/images/model_figures/multiple_datasets_shared.png +:alt: The model figure of a global model in which one Gaussian is shared by all three datasets, drawn as a single collapsed frame whose parameters each carry a shared badge. +:width: 600 +``` + +Because every dataset is fitted by the same `Gaussian`, the three components collapse into one frame and each of +`centre`, `normalization` and `sigma` carries a shared badge, which is the picture of a three-parameter fit to three +datasets. + To fit multiple datasets, we pass the `FactorGraphModel` to a non-linear search. Unlike single-dataset fitting, we now pass the `factor_graph.global_prior_model` as the model and @@ -395,6 +411,20 @@ model sigma GaussianPrior [11], mean = 10.0, sigma = 5.0 ``` +The map shows the same thing without the indentation having to be read: + +```python +af.ModelPlotter(factor_graph.global_prior_model).figure() +``` + +```{image} https://raw.githubusercontent.com/PyAutoLabs/PyAutoFit/main/docs/images/model_figures/multiple_datasets_variable.png +:alt: The model figure of a global model whose centre is shared across the three datasets while normalization and sigma are independent per dataset. +:width: 600 +``` + +Only `centre` now carries the shared badge; `normalization` and `sigma` are marked as independent, meaning one prior +per dataset, and the footer counts the seven unique sampled scalars this makes. + Fit this model to the data using dynesty. ```python @@ -530,6 +560,21 @@ factor x 3.0 ``` +The relational model is the case where the map is worth the most, because the relation is structure and the `info` +can only express it as nesting: + +```python +af.ModelPlotter(factor_graph.global_prior_model).figure() +``` + +```{image} https://raw.githubusercontent.com/PyAutoLabs/PyAutoFit/main/docs/images/model_figures/multiple_datasets_relational.png +:alt: The model figure of a relational model, with one card per dataset whose sigma pill carries the sigma_m times x plus sigma_c expression and whose centre and normalization carry shared badges. +:width: 600 +``` + +Each dataset's `sigma` pill states the expression that defines it, and `centre` and `normalization` are badged as +shared, so the map says directly that adding a fourth dataset would add a fourth card and no new parameters. + We can fit the model as per usual. ```python diff --git a/docs/images/model_figures/composite_shared_relation_assertion.png b/docs/images/model_figures/composite_shared_relation_assertion.png new file mode 100644 index 000000000..fa8571327 Binary files /dev/null and b/docs/images/model_figures/composite_shared_relation_assertion.png differ diff --git a/docs/images/model_figures/gaussian.png b/docs/images/model_figures/gaussian.png new file mode 100644 index 000000000..d61f5efae Binary files /dev/null and b/docs/images/model_figures/gaussian.png differ diff --git a/docs/images/model_figures/gaussian_collection.png b/docs/images/model_figures/gaussian_collection.png new file mode 100644 index 000000000..8680d48e7 Binary files /dev/null and b/docs/images/model_figures/gaussian_collection.png differ diff --git a/docs/images/model_figures/gaussian_customised.png b/docs/images/model_figures/gaussian_customised.png new file mode 100644 index 000000000..0d345cc01 Binary files /dev/null and b/docs/images/model_figures/gaussian_customised.png differ diff --git a/docs/images/model_figures/group_scale.png b/docs/images/model_figures/group_scale.png new file mode 100644 index 000000000..ef6f6a6bf Binary files /dev/null and b/docs/images/model_figures/group_scale.png differ diff --git a/docs/images/model_figures/make_figures.py b/docs/images/model_figures/make_figures.py new file mode 100644 index 000000000..328d73682 --- /dev/null +++ b/docs/images/model_figures/make_figures.py @@ -0,0 +1,247 @@ +""" +Regenerate the committed model-figure evidence renders. + +Run from the PyAutoFit repo root, with the worktree environment active:: + + python docs/images/model_figures/make_figures.py + +Every PNG in this directory is written by this script at ``width=14.0`` inches +and DPI 100, so none exceeds the 1400 px width budget. The figures are the +acceptance evidence for the ``model-figures`` epic's phase 2 and the images the +cookbook docs pages embed. + +Most models here are lifted from the PyAutoFit cookbooks (``autofit_workspace`` +``scripts/cookbooks/{model,multi_level_model,multiple_datasets}.py``) so the +figure a reader sees in the docs is the model the surrounding code composes. + +The three lens figures (``simple_lens``, ``mge_pixelized``, ``group_scale``) are +built from ``test_autofit/graph_spec/lens_doubles.py``. Those are **structural +doubles** -- classes with the same constructor signatures, priors and +composition as the real PyAutoLens components, so PyAutoFit can render them +without depending on PyAutoLens. Phase 3 of the epic renders the real models and +replaces them. +""" + +import sys +from pathlib import Path +from typing import List + +import matplotlib + +matplotlib.use("Agg") + +REPO_ROOT = Path(__file__).resolve().parents[3] +sys.path.insert(0, str(REPO_ROOT)) + +import autofit as af + +OUTPUT_PATH = Path(__file__).resolve().parent +WIDTH = 14.0 + + +def write(model, name: str, **kwargs): + """Render one model to ``.png`` in this directory.""" + af.ModelPlotter(model).figure( + path=str(OUTPUT_PATH), + filename=name, + format="png", + width=WIDTH, + **kwargs, + ) + print(f"wrote {name}.png") + + +# -- the cookbook models ---------------------------------------------------- + + +def gaussian(): + """``scripts/cookbooks/model.py`` -- the plain ``af.Model``.""" + return af.Model(af.ex.Gaussian) + + +def gaussian_customised(): + """ + ``scripts/cookbooks/model.py`` -- "Model Customization (Model)". + + ``centre`` is fixed, ``normalization`` is given a new prior and ``sigma`` + keeps the prior its configuration file supplies. + """ + model = af.Model(af.ex.Gaussian) + model.centre = 0.0 + model.normalization = af.UniformPrior(lower_limit=0.0, upper_limit=10.0) + return model + + +def gaussian_collection(): + """ + ``scripts/cookbooks/model.py`` -- "Model Customization (Collection)". + """ + gaussian = af.Model(af.ex.Gaussian) + gaussian.normalization = 1.0 + gaussian.sigma = af.GaussianPrior(mean=0.0, sigma=1.0) + + exponential = af.Model(af.ex.Exponential) + exponential.centre = 50.0 + exponential.add_assertion(exponential.rate > 5.0) + + return af.Collection(gaussian=gaussian, exponential=exponential) + + +class MultiLevelGaussian: + def __init__(self, normalization=1.0, sigma=5.0): + self.normalization = normalization + self.sigma = sigma + + +class MultiLevelGaussians: + def __init__( + self, + higher_level_centre: float = 50.0, + gaussian_list: List[MultiLevelGaussian] = None, + ): + self.higher_level_centre = higher_level_centre + self.gaussian_list = gaussian_list + + +def multi_level(): + """ + ``scripts/cookbooks/multi_level_model.py`` -- the multi-level composition: + two ``Gaussian``s whose centre is a parameter of the level above them. + """ + return af.Model( + MultiLevelGaussians, + gaussian_list=[af.Model(MultiLevelGaussian), af.Model(MultiLevelGaussian)], + ) + + +class _Analysis(af.Analysis): + """ + A do-nothing analysis. ``AnalysisFactor`` only needs an analysis object to + pair with the model; nothing here is ever fitted. + """ + + def __init__(self, index): + self.index = index + + def log_likelihood_function(self, instance): + return 0.0 + + +def _factor_graph(model_list): + return af.FactorGraphModel( + *[ + af.AnalysisFactor(prior_model=model, analysis=_Analysis(index)) + for index, model in enumerate(model_list) + ] + ) + + +def _multiple_datasets_model(): + model = af.Model(af.ex.Gaussian) + model.centre = af.UniformPrior(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 multiple_datasets_shared(): + """ + ``scripts/cookbooks/multiple_datasets.py`` -- one model shared by all three + datasets. + """ + model = _multiple_datasets_model() + return _factor_graph([model, model, model]).global_prior_model + + +def multiple_datasets_variable(): + """ + ``scripts/cookbooks/multiple_datasets.py`` -- a shared ``centre`` with a + ``normalization`` and ``sigma`` free per dataset. + """ + model = _multiple_datasets_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 multiple_datasets_relational(): + """ + ``scripts/cookbooks/multiple_datasets.py`` -- ``sigma`` follows the relation + ``sigma_m * x + sigma_c`` across the datasets, so adding datasets adds no + parameters. + """ + model = af.Collection(gaussian=af.Model(af.ex.Gaussian)) + + 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]: + model_analysis = model.copy() + model_analysis.gaussian.sigma = (sigma_m * x) + sigma_c + model_list.append(model_analysis) + + return _factor_graph(model_list).global_prior_model + + +def composite_shared_relation_assertion(): + """ + All three of sharing, relation and assertion at once -- acceptance case 3. + """ + model = af.Collection( + a=af.Model(af.ex.Gaussian), + b=af.Model(af.ex.Gaussian), + ) + model.b.centre = model.a.centre + model.b.sigma = model.a.sigma * 2.0 + model.add_assertion(model.a.sigma > 5.0) + return model + + +# -- the lens structural doubles -------------------------------------------- + + +def lens_models(): + from test_autofit.graph_spec.lens_doubles import ( + simple_lens_model, + mge_model, + group_model, + ) + + return { + "simple_lens": simple_lens_model(), + "mge_pixelized": mge_model(), + "group_scale": group_model(), + } + + +FIGURES = { + "gaussian": gaussian, + "gaussian_customised": gaussian_customised, + "gaussian_collection": gaussian_collection, + "multi_level": multi_level, + "multiple_datasets_shared": multiple_datasets_shared, + "multiple_datasets_variable": multiple_datasets_variable, + "multiple_datasets_relational": multiple_datasets_relational, + "composite_shared_relation_assertion": composite_shared_relation_assertion, +} + + +def main(): + for name, builder in FIGURES.items(): + write(builder(), name) + + for name, model in lens_models().items(): + write(model, name) + + +if __name__ == "__main__": + main() diff --git a/docs/images/model_figures/mge_pixelized.png b/docs/images/model_figures/mge_pixelized.png new file mode 100644 index 000000000..9bf71d67b Binary files /dev/null and b/docs/images/model_figures/mge_pixelized.png differ diff --git a/docs/images/model_figures/multi_level.png b/docs/images/model_figures/multi_level.png new file mode 100644 index 000000000..571835ff2 Binary files /dev/null and b/docs/images/model_figures/multi_level.png differ diff --git a/docs/images/model_figures/multiple_datasets_relational.png b/docs/images/model_figures/multiple_datasets_relational.png new file mode 100644 index 000000000..12962c594 Binary files /dev/null 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 new file mode 100644 index 000000000..33b0c1c35 Binary files /dev/null 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 new file mode 100644 index 000000000..311cf92ff Binary files /dev/null and b/docs/images/model_figures/multiple_datasets_variable.png differ diff --git a/docs/images/model_figures/simple_lens.png b/docs/images/model_figures/simple_lens.png new file mode 100644 index 000000000..00c3dbfab Binary files /dev/null and b/docs/images/model_figures/simple_lens.png differ diff --git a/test_autofit/config/output.yaml b/test_autofit/config/output.yaml index d6cc60eed..40914a94e 100644 --- a/test_autofit/config/output.yaml +++ b/test_autofit/config/output.yaml @@ -45,3 +45,8 @@ derived_quantities: true # `latent/samples.csv`: Values of every derived quantit data: true # `data.json`: The value of every data point in the data. noise_map: true # `noise_map.json`: The value of every RMS noise map value. +# `model.png`: the model figure drawn beside `model.info`. Absent key means off (read strictly). + +model_figure: false + + diff --git a/test_autofit/model_figure/__init__.py b/test_autofit/model_figure/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/test_autofit/model_figure/conftest.py b/test_autofit/model_figure/conftest.py new file mode 100644 index 000000000..8156accae --- /dev/null +++ b/test_autofit/model_figure/conftest.py @@ -0,0 +1,16 @@ +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, so + they are reset before every test -- the figure is then a function of the + model alone, which is what the determinism acceptance asserts. + """ + af.ModelObject._ids = itertools.count() + af.Prior._ids = itertools.count() diff --git a/test_autofit/model_figure/test_acceptance_figures.py b/test_autofit/model_figure/test_acceptance_figures.py new file mode 100644 index 000000000..bc289bbb0 --- /dev/null +++ b/test_autofit/model_figure/test_acceptance_figures.py @@ -0,0 +1,205 @@ +""" +The epic's acceptance cases, asserted on the figure rather than on the spec. + +(a) the simple lens, (b) the MGE 2x30 with a pixelized source and (e) the group +model come from the structural doubles in ``test_autofit/graph_spec/lens_doubles.py`` +(autofit may never import autogalaxy or autolens). The toy Gaussian and a +shared / relation / assertion composite complete the set. +""" + +import matplotlib + +matplotlib.use("Agg") + +import matplotlib.pyplot as plt + +import autofit as af +from autofit.graph_spec import GraphSpec + +from test_autofit.graph_spec.lens_doubles import ( + group_model, + mge_model, + simple_lens_model, +) + + +def _plotter(model, **kwargs): + return af.ModelPlotter(model, **kwargs) + + +def _boxes(presentation): + """Component *boxes* -- models and plates, never collection frames.""" + return [card for card in presentation.walk() if card.kind in ("model", "plate")] + + +def _pill(presentation, key): + for pill in presentation.pills(): + if pill.key == key: + return pill + raise AssertionError(f"no pill at {key!r}") + + +# ------------------------------------------------------------------ (a) + + +def test_a_simple_lens_draws_six_component_cards_in_model_info_order(): + model = simple_lens_model() + presentation = _plotter(model).presentation() + + boxes = _boxes(presentation) + assert [box.title for box in boxes] == [ + "lens · Galaxy", + "bulge · Sersic", + "mass · Isothermal", + "shear · ExternalShear", + "source · Galaxy", + "bulge · Sersic", + ] + # The same six the spec counts, in the same order. + spec = GraphSpec.from_model(model) + assert len(boxes) == len( + [node for node in spec.components() if node.kind == "model"] + ) + + figure = _plotter(model).figure(format=None) + assert figure is not None + plt.close(figure) + + +def test_a_simple_lens_renders_within_the_width_budget(): + layout = _plotter(simple_lens_model()).layout(width=14.0) + + assert layout.width <= 14.0 + assert layout.width * layout.style.dpi <= 1400 + + +# ------------------------------------------------------------------ (b) + + +def test_b_mge_draws_eleven_components_and_two_thirty_member_plates(): + model = mge_model() + presentation = _plotter(model).presentation() + + assert len(_boxes(presentation)) == 11 + + plates = [card for card in presentation.walk() if card.kind == "plate"] + assert [plate.badge for plate in plates] == ["30 components", "30 components"] + assert [plate.subtitle for plate in plates] == ["0 - 29", "30 - 59"] + + assert "16 unique sampled scalars" in presentation.footer + + owner = _pill(presentation, "galaxies/lens/bulge/profile_list/0/centre") + assert owner.badge == "shared across group" + assert owner.dim2d is True + + +def test_b_mge_shows_the_unset_areas_factor_in_the_missing_state(): + presentation = _plotter(mge_model()).presentation() + pill = _pill(presentation, "galaxies/source/pixelization/image_mesh/areas_factor") + + assert pill.state == "missing" + assert "missing configuration" in presentation.legend + + +def test_b_mge_stays_inside_the_budget_expanded_as_well_as_collapsed(): + plotter = _plotter(mge_model()) + + collapsed = plotter.layout(width=14.0) + expanded = plotter.layout(width=14.0, collapse=False) + + assert collapsed.width <= 14.0 + assert expanded.width <= 14.0 + # Collapse, never shrink: the expanded figure is taller, not smaller-typed. + assert expanded.height > collapsed.height + assert expanded.style.pill_size == collapsed.style.pill_size + + +# ------------------------------------------------------------------ (e) + + +def test_e_group_scale_shows_every_per_galaxy_fixed_centre(): + """ + Their absence from the prototype read as absence from the model (review, + "Show fixed parameters by default"). + """ + presentation = _plotter(group_model()).presentation() + pill = _pill(presentation, "extra_galaxies/0/mass/centre") + + assert pill.state == "fixed-varies" + assert pill.text == "centre · fixed, varies by member" + assert pill.dim2d is True + assert "77 fixed leaf slots" in presentation.footer + + +def test_e_group_scale_collapses_eight_galaxies_into_one_plate(): + presentation = _plotter(group_model()).presentation() + plates = [card for card in presentation.walk() if card.kind == "plate"] + + assert len(plates) == 1 + assert plates[0].badge == "8 components" + + +# ------------------------------------------------------------------ toy + + +def test_the_toy_gaussian_renders(): + presentation = _plotter(af.Model(af.ex.Gaussian)).presentation() + + assert [pill.text for pill in presentation.pills()] == [ + "centre", + "normalization", + "sigma", + ] + figure = _plotter(af.Model(af.ex.Gaussian)).figure(format=None) + assert figure is not None + plt.close(figure) + + +def test_a_collection_of_gaussians_collapses_into_a_plate(): + model = af.Collection(a=af.Model(af.ex.Gaussian), b=af.Model(af.ex.Gaussian)) + presentation = _plotter(model).presentation() + + (plate,) = [card for card in presentation.walk() if card.kind == "plate"] + assert plate.badge == "2 components" + + +# ------------------------------------------------------------------ composite + + +def test_shared_relation_and_assertion_are_all_legible_at_once(): + first = af.Model(af.ex.Gaussian) + second = af.Model(af.ex.Gaussian) + second.centre = first.centre + second.sigma = first.sigma * 2.0 + model = af.Collection(a=first, b=second) + model.add_assertion(first.sigma > 5.0) + + presentation = _plotter(model).presentation() + + # sharing: a badge on the owner, a labelled reference and a link + assert _pill(presentation, "a/centre").badge == "shared ×2" + assert _pill(presentation, "b/centre").badge == "↗ a.centre" + assert [ + (link.source_key, link.target_key, link.kind) for link in presentation.links + ] == [ + ("b/centre", "a/centre", "shared"), + ("b/sigma", "a/sigma", "relation"), + ] + + # relation: the defining expression is the pill + relation = _pill(presentation, "b/sigma") + assert relation.state == "relation" + assert relation.text == "sigma = a.sigma * 2.0" + + # assertion: one compact constraint label carrying both operands + (constraint,) = presentation.constraints + assert constraint.text == "assert a.sigma > 5.0" + + # and all three are in one legend line + assert "relation (expression shown)" in presentation.legend + assert "blue badge = shared prior" in presentation.legend + assert "dashed orange = constraint (assertion)" in presentation.legend + + figure = _plotter(model).figure(format=None) + assert figure is not None + plt.close(figure) diff --git a/test_autofit/model_figure/test_determinism.py b/test_autofit/model_figure/test_determinism.py new file mode 100644 index 000000000..a69d14e94 --- /dev/null +++ b/test_autofit/model_figure/test_determinism.py @@ -0,0 +1,108 @@ +""" +Determinism -- the same model must give the same figure, twice and everywhere. + +Part of the epic's acceptance: a figure that is not byte-reproducible cannot be +diffed or committed as evidence. The layout dict is the artefact (every +coordinate rounded to 4 dp), and the PNG bytes are checked directly. +""" + +import hashlib +import itertools +import json +import subprocess +import sys +import textwrap + +import matplotlib + +matplotlib.use("Agg") + +import autofit as af + +from test_autofit.graph_spec.lens_doubles import mge_model, simple_lens_model + + +def _reset_ids(): + af.ModelObject._ids = itertools.count() + af.Prior._ids = itertools.count() + + +def _layout_json(model): + return json.dumps(af.ModelPlotter(model).layout().to_dict()) + + +def test_laying_out_the_same_model_twice_is_byte_identical(): + model = mge_model() + + assert _layout_json(model) == _layout_json(model) + + +def test_rebuilding_the_model_is_byte_identical(): + first = _layout_json(mge_model()) + + _reset_ids() + second = _layout_json(mge_model()) + + assert first == second + + +def test_the_layout_is_identical_in_a_fresh_interpreter(tmp_path): + """ + Text metrics come from a scratch Agg canvas, so they must not depend on + anything the test session has already done to matplotlib. + """ + expected = _layout_json(simple_lens_model()) + + # Written to a file rather than stdout: importing the model doubles prints. + target = tmp_path / "layout.json" + script = textwrap.dedent( + f""" + import itertools, json, pathlib + import matplotlib + matplotlib.use("Agg") + import autofit as af + from test_autofit.graph_spec.lens_doubles import simple_lens_model + af.ModelObject._ids = itertools.count() + af.Prior._ids = itertools.count() + pathlib.Path({str(target)!r}).write_text( + json.dumps(af.ModelPlotter(simple_lens_model()).layout().to_dict()) + ) + """ + ) + subprocess.run( + [sys.executable, "-c", script], capture_output=True, text=True, check=True + ) + + assert target.read_text() == expected + + +def test_png_bytes_are_identical_across_two_saves(tmp_path): + model = simple_lens_model() + + af.ModelPlotter(model).figure(path=tmp_path, filename="first", format="png") + af.ModelPlotter(model).figure(path=tmp_path, filename="second", format="png") + + first = hashlib.sha256((tmp_path / "first.png").read_bytes()).hexdigest() + second = hashlib.sha256((tmp_path / "second.png").read_bytes()).hexdigest() + assert first == second + + +def test_importing_the_model_figure_package_does_not_import_matplotlib(): + """ + ``af.ModelPlotter`` is exported from ``autofit/__init__.py``, so the drawing + imports must all sit inside functions -- otherwise every ``import autofit`` + pays for matplotlib and ``test_autofit/graph_spec`` layer purity breaks. + """ + result = subprocess.run( + [ + sys.executable, + "-c", + "import sys, autofit.model_figure; " + "print([m for m in sys.modules if m.split('.')[0] == 'matplotlib'])", + ], + capture_output=True, + text=True, + check=True, + ) + + assert result.stdout.strip() == "[]" diff --git a/test_autofit/model_figure/test_figure_output.py b/test_autofit/model_figure/test_figure_output.py new file mode 100644 index 000000000..2a194c3e9 --- /dev/null +++ b/test_autofit/model_figure/test_figure_output.py @@ -0,0 +1,72 @@ +""" +``ModelPlotter.figure`` output -- the ``show | png | svg | pdf`` branching of +``autofit/non_linear/plot/plot_util.py:output_figure``, with ``svg`` added. +""" + +import matplotlib + +matplotlib.use("Agg") + +import matplotlib.pyplot as plt +import pytest + +import autofit as af + + +@pytest.fixture +def model(): + return af.Model(af.ex.Gaussian) + + +@pytest.mark.parametrize("format", ["png", "svg", "pdf"]) +def test_figure_writes_the_file(model, tmp_path, format): + figure = af.ModelPlotter(model).figure( + path=tmp_path, filename="model", format=format + ) + + written = tmp_path / f"model.{format}" + assert written.exists() + assert written.stat().st_size > 0 + assert figure is not None + + +def test_filename_is_honoured(model, tmp_path): + af.ModelPlotter(model).figure(path=tmp_path, filename="my_model", format="png") + + assert (tmp_path / "my_model.png").exists() + + +def test_a_missing_directory_is_created(model, tmp_path): + target = tmp_path / "deep" / "nested" + af.ModelPlotter(model).figure(path=target, format="png") + + assert (target / "model.png").exists() + + +def test_show_returns_a_figure_and_writes_nothing(model, tmp_path, monkeypatch): + shown = [] + monkeypatch.setattr(plt, "show", lambda *args, **kwargs: shown.append(True)) + + figure = af.ModelPlotter(model).figure(path=tmp_path, format="show") + + assert shown == [True] + assert figure is not None + assert list(tmp_path.iterdir()) == [] + plt.close(figure) + + +def test_an_unknown_format_raises_rather_than_silently_doing_nothing(model, tmp_path): + with pytest.raises(ValueError): + af.ModelPlotter(model).figure(path=tmp_path, format="jpeg") + + +def test_the_spec_is_built_once_and_cached(model): + plotter = af.ModelPlotter(model) + + assert plotter.spec() is plotter.spec() + assert plotter.spec(collapse=False) is not plotter.spec(collapse=True) + + +def test_detail_must_be_names_or_priors(model): + with pytest.raises(ValueError): + af.ModelPlotter(model).presentation(detail="everything") diff --git a/test_autofit/model_figure/test_layout.py b/test_autofit/model_figure/test_layout.py new file mode 100644 index 000000000..b1efc9508 --- /dev/null +++ b/test_autofit/model_figure/test_layout.py @@ -0,0 +1,197 @@ +""" +Layer 3a -- the geometry invariants the epic's prototype broke. + +Text is never scaled down (so the toy Gaussian and the group-scale model share +every font size), nothing exceeds the width budget, top-level cards wrap rather +than running off the page, declaration order survives placement, and padding +decreases with nesting depth. +""" + +import matplotlib + +matplotlib.use("Agg") + +import pytest + +import autofit as af +from autofit.model_figure.layout import Style, build_layout, measure_text +from autofit.model_figure.presentation import build_presentation +from autofit.graph_spec import GraphSpec + +from test_autofit.graph_spec.lens_doubles import ( + group_model, + mge_model, + simple_lens_model, +) + + +def _layout(model, width=14.0, **kwargs): + style = Style(width=width) + return build_layout( + build_presentation(GraphSpec.from_model(model), **kwargs), style + ) + + +MODELS = { + "gaussian": lambda: af.Model(af.ex.Gaussian), + "simple_lens": simple_lens_model, + "mge": mge_model, + "group": group_model, +} + + +@pytest.mark.parametrize("name", sorted(MODELS)) +def test_no_box_exceeds_the_width_budget(name): + layout = _layout(MODELS[name]()) + style = layout.style + + assert layout.width <= style.width + 1e-6 + for card in layout.walk(): + assert card.x >= style.margin - 1e-9 + assert card.x + card.width <= style.width - style.gutter + 1e-6 + for pill in layout.pills(): + assert pill.x + pill.width <= style.width - style.gutter + 1e-6 + + +@pytest.mark.parametrize("name", sorted(MODELS)) +def test_nothing_is_clipped_vertically(name): + layout = _layout(MODELS[name]()) + + for card in layout.walk(): + assert card.y + card.height <= layout.height + 1e-6 + assert layout.footer_y < layout.height + + +def test_font_sizes_are_identical_for_the_smallest_and_largest_model(): + """ "Keep text size fixed and collapse content" -- not shrink the figure.""" + styles = [_layout(build()).style.to_dict() for build in MODELS.values()] + + assert all(style == styles[0] for style in styles) + assert styles[0]["title_size"] == 9.0 + assert styles[0]["pill_size"] == 8.0 + + +def test_top_level_cards_wrap_onto_a_new_row_for_the_group_model(): + layout = _layout(group_model()) + + rows = sorted({card.y for card in layout.cards}) + assert len(rows) > 1 + # Reading order across, then down: the first card of every row is flush left. + assert all( + any(card.x == layout.style.margin and card.y == row for card in layout.cards) + for row in rows + ) + + +def test_wrapping_preserves_declaration_order(): + layout = _layout(group_model()) + + positions = [(card.y, card.x) for card in layout.cards] + assert positions == sorted(positions) + assert [card.key for card in layout.cards] == ["galaxies", "extra_galaxies"] + + +def test_children_stack_in_declaration_order(): + layout = _layout(simple_lens_model()) + (galaxies,) = layout.cards + lens = galaxies.children[0] + + assert [child.key for child in lens.children] == [ + "galaxies/lens/bulge", + "galaxies/lens/mass", + "galaxies/lens/shear", + ] + ys = [child.y for child in lens.children] + assert ys == sorted(ys) + + +def test_pills_flow_in_declaration_order_and_wrap_within_the_card(): + layout = _layout(simple_lens_model()) + bulge = next(card for card in layout.walk() if card.key == "galaxies/lens/bulge") + + positions = [(pill.y, pill.x) for pill in bulge.pills] + assert positions == sorted(positions) + for pill in bulge.pills: + assert pill.x + pill.width <= bulge.x + bulge.width - bulge.pad + 1e-6 + + +def test_padding_decreases_with_nesting_depth(): + style = Style() + pads = [style.pad(level) for level in range(1, 5)] + + assert pads[0] > pads[1] > pads[2] + assert pads[-1] >= style.min_pad + + layout = _layout(mge_model()) + by_level = {} + for card in layout.walk(): + by_level.setdefault(card.level, card.pad) + assert by_level[1] > by_level[2] > by_level[3] + + +def test_a_narrow_budget_wraps_rather_than_shrinking_text(): + wide = _layout(group_model(), width=14.0) + narrow = _layout(group_model(), width=9.0) + + assert narrow.style.pill_size == wide.style.pill_size + assert narrow.height > wide.height + for card in narrow.walk(): + assert card.x + card.width <= 9.0 - narrow.style.gutter + 1e-6 + + +def test_text_is_measured_not_estimated(): + """The prototype's estimator was 11 % short on bold headers.""" + bold = measure_text("bulge · Sersic", 9.0, "bold")[0] + plain = measure_text("bulge · Sersic", 9.0)[0] + + assert bold > plain > 0.0 + # The cache returns the identical object for the identical query. + assert measure_text("bulge · Sersic", 9.0, "bold") == ( + bold, + measure_text("bulge · Sersic", 9.0, "bold")[1], + ) + + +def test_links_are_routed_only_through_the_gutter(): + layout = _layout(mge_model()) + card_right = max(card.x + card.width for card in layout.walk()) + + assert layout.links + for route in layout.links: + assert all(x >= card_right for x, _ in route.points) + assert all(x <= layout.width for x, _ in route.points) + # Orthogonal: every segment changes exactly one coordinate. + for (x0, y0), (x1, y1) in zip(route.points, route.points[1:]): + assert x0 == x1 or y0 == y1 + + +def test_link_ends_touch_the_top_level_card_that_holds_the_pill(): + layout = _layout(mge_model()) + tops = {card.key: card for card in layout.cards} + + assert layout.links + for route in layout.links: + for key, (x, y) in ( + (route.source_key, route.points[0]), + (route.target_key, route.points[-1]), + ): + owner = next(top for top in tops.values() if key.startswith(f"{top.key}/")) + assert x >= owner.x + owner.width - 1e-6 + # Touching, not floating: exactly the rightmost card edge at this + # height, so the segment is attached and still enters no card. + assert x == max( + other.x + other.width + for other in layout.cards + if other.y <= y <= other.y + other.height + ) + + +def test_a_large_number_of_links_falls_back_to_labelled_references(): + """ "Use labelled references when links become numerous" (the review).""" + expanded = build_layout( + build_presentation(GraphSpec.from_model(mge_model(), collapse=False)), + Style(), + ) + + assert expanded.links == () + assert any(pill.badge and pill.badge.startswith("↗") for pill in expanded.pills()) diff --git a/test_autofit/model_figure/test_presentation.py b/test_autofit/model_figure/test_presentation.py new file mode 100644 index 000000000..1e02d5e0b --- /dev/null +++ b/test_autofit/model_figure/test_presentation.py @@ -0,0 +1,449 @@ +""" +Layer 2 -- one test per rule of the visual vocabulary. + +The vocabulary is the epic's v2 as amended by the independent review +(``PyAutoMind/draft/feature/autofit/model_figures_epic.md``, sections 2 and +"Independent review"). Every rule the review made binding has a test here, and +every assertion is on the :class:`Presentation` -- never on a picture. +""" + +import json + +import matplotlib + +matplotlib.use("Agg") + +import autofit as af +from autofit.graph_spec import GraphSpec +from autofit.model_figure.presentation import ( + build_presentation, + compact_prior, + prior_summaries, +) + +from test_autofit.graph_spec.lens_doubles import ( + group_model, + mge_model, + sersic, + simple_lens_model, +) + + +def _presentation(model, **kwargs): + priors = prior_summaries(model) if kwargs.get("detail") == "priors" else None + collapse = kwargs.pop("collapse", True) + solved_paths = kwargs.pop("solved_paths", ()) + spec = GraphSpec.from_model(model, collapse=collapse, solved_paths=solved_paths) + return build_presentation(spec, priors=priors, **kwargs) + + +def _cards(presentation): + return list(presentation.walk()) + + +def _card(presentation, key): + for card in presentation.walk(): + if card.key == key: + return card + raise AssertionError(f"no card at {key!r}") + + +def _pill(presentation, key): + for pill in presentation.pills(): + if pill.key == key: + return pill + raise AssertionError(f"no pill at {key!r}") + + +def _composite(): + """Sharing, a relation and an assertion in one model.""" + first = af.Model(af.ex.Gaussian) + second = af.Model(af.ex.Gaussian) + second.centre = first.centre + second.sigma = first.sigma * 2.0 + model = af.Collection(a=first, b=second) + model.add_assertion(first.sigma > 5.0) + return model + + +# ---------------------------------------------------------------- structure + + +def test_root_collection_frame_is_dropped_when_it_adds_no_branching(): + """The review's "remove redundant outer framing where it adds no branching".""" + presentation = _presentation(af.Collection(a=af.Model(af.ex.Gaussian))) + + assert [card.key for card in presentation.cards] == ["a"] + assert presentation.cards[0].title == "a · Gaussian" + + +def test_root_model_keeps_its_card_because_it_owns_rows(): + presentation = _presentation(af.Model(af.ex.Gaussian)) + + assert [card.key for card in presentation.cards] == [""] + assert presentation.cards[0].title == "model · Gaussian" + assert [pill.text for pill in presentation.cards[0].pills] == [ + "centre", + "normalization", + "sigma", + ] + + +def test_collection_is_a_frame_titled_with_its_attribute_name(): + presentation = _presentation(simple_lens_model()) + + (galaxies,) = presentation.cards + assert galaxies.kind == "collection" + assert galaxies.title == "galaxies" + assert [child.title for child in galaxies.children] == [ + "lens · Galaxy", + "source · Galaxy", + ] + + +def test_declaration_order_is_never_reordered(): + """``model.info`` says ``bulge, mass, shear``; so does the figure.""" + presentation = _presentation(simple_lens_model()) + lens = _card(presentation, "galaxies/lens") + + assert [child.title for child in lens.children] == [ + "bulge · Sersic", + "mass · Isothermal", + "shear · ExternalShear", + ] + + +def test_every_key_is_the_path_index_key(): + model = simple_lens_model() + spec = GraphSpec.from_model(model) + presentation = build_presentation(spec) + + for card in presentation.walk(): + assert card.key in spec.path_index + for pill in presentation.pills(): + assert pill.key in spec.path_index + + +def test_to_dict_is_json_stable(): + model = simple_lens_model() + first = json.dumps(_presentation(model).to_dict()) + second = json.dumps(_presentation(model).to_dict()) + + assert first == second + + +# ---------------------------------------------------------------- plates + + +def test_plate_badge_counts_components_and_never_reads_times_n(): + """Review point 2: ``x30`` on a plate and on a parameter meant two things.""" + presentation = _presentation(mge_model()) + plate = _card(presentation, "galaxies/lens/bulge/profile_list/0") + + assert plate.kind == "plate" + assert plate.badge == "30 components" + assert "×" not in plate.badge + assert plate.subtitle == "0 - 29" + assert plate.note.startswith("Gaussian with priors") + + +def test_plate_note_says_what_is_repeated(): + presentation = _presentation(group_model()) + plate = _card(presentation, "extra_galaxies/0") + + assert plate.badge == "8 components" + assert plate.subtitle.startswith("0 - 7") + assert plate.note is not None + + +# ---------------------------------------------------------------- states + + +def test_free_pill_is_name_only(): + presentation = _presentation(af.Model(af.ex.Gaussian)) + pill = _pill(presentation, "sigma") + + assert pill.state == "free" + assert pill.text == "sigma" + assert pill.badge is None + + +def test_fixed_pill_is_shown_by_default(): + """Review point 4: fixed values explain model structure.""" + model = af.Model(af.ex.Gaussian) + model.sigma = 3.0 + presentation = _presentation(model) + + assert _pill(presentation, "sigma").state == "fixed" + + +def test_fixed_that_varies_by_member_says_so(): + """A single grey pill otherwise suggests one common fixed value.""" + presentation = _presentation(group_model()) + pill = _pill(presentation, "extra_galaxies/0/mass/centre") + + assert pill.state == "fixed-varies" + assert pill.text == "centre · fixed, varies by member" + + +def test_missing_configuration_is_its_own_state(): + """``areas_factor`` is unset: absence from the picture is not acceptable.""" + presentation = _presentation(mge_model()) + pill = _pill(presentation, "galaxies/source/pixelization/image_mesh/areas_factor") + + assert pill.state == "missing" + assert pill.text == "areas_factor · missing" + + +def test_solved_is_a_state_and_the_legend_qualifies_it(): + presentation = _presentation( + af.Collection(gaussian=af.Model(af.ex.Gaussian)), + solved_paths=("gaussian.normalization",), + ) + pill = _pill(presentation, "gaussian/normalization") + + assert pill.state == "solved" + assert "solved during fitting" in presentation.legend + + +def test_relation_pill_carries_its_defining_expression(): + """The expression IS the pill (review: it is the one permitted number).""" + presentation = _presentation(_composite()) + pill = _pill(presentation, "b/sigma") + + assert pill.state == "relation" + assert pill.text == "sigma = a.sigma * 2.0" + + +# ---------------------------------------------------------------- sharing + + +def test_sharing_is_a_property_not_a_state(): + presentation = _presentation(_composite()) + + owner = _pill(presentation, "a/centre") + reference = _pill(presentation, "b/centre") + + # Both are still *sampled*. + assert owner.state == "free" + assert reference.state == "free" + assert owner.badge == "shared ×2" + assert reference.badge == "↗ a.centre" + + +def test_a_later_occurrence_gets_a_link_back_to_its_owner(): + presentation = _presentation(_composite()) + + assert any( + link.source_key == "b/centre" + and link.target_key == "a/centre" + and link.kind == "shared" + for link in presentation.links + ) + + +def test_group_sharing_inside_a_plate_reads_shared_across_group(): + """Never ``×30``, which means a different thing on a plate.""" + presentation = _presentation(mge_model()) + + owner = _pill(presentation, "galaxies/lens/bulge/profile_list/0/centre") + assert owner.badge == "shared across group" + + # The second basis' `ell_comps` is shared only within its own 30. + assert ( + _pill(presentation, "galaxies/lens/bulge/profile_list/30/ell_comps").badge + == "shared across group" + ) + # ... while its `centre` is the same prior as the first basis' and points at it. + reference = _pill(presentation, "galaxies/lens/bulge/profile_list/30/centre") + assert reference.badge.startswith("↗") + assert reference.badge.endswith("0.centre") + + +def test_independent_repeated_priors_are_marked_as_such(): + """Distinct prior objects, identical configuration -- repetition, not sharing.""" + presentation = _presentation(group_model()) + pill = _pill(presentation, "extra_galaxies/0/mass/sigma") + + assert pill.state == "free" + assert pill.badge == "independent" + + +# ---------------------------------------------------------------- tuples + + +def test_tuple_pill_carries_a_two_dimensional_cue(): + presentation = _presentation(simple_lens_model()) + pill = _pill(presentation, "galaxies/lens/bulge/centre") + + assert pill.dim2d is True + assert pill.text == "centre" + + +def test_a_mixed_tuple_expands_rather_than_flattening(): + model = sersic() + model.centre.centre_1 = 0.5 + presentation = _presentation(model) + + assert _pill(presentation, "centre/centre_0").state == "free" + assert _pill(presentation, "centre/centre_1").state == "fixed" + assert all(pill.key != "centre" for pill in presentation.pills()) + + +# ---------------------------------------------------------------- redshift + + +def test_fixed_redshift_becomes_a_card_subtitle(): + presentation = _presentation(simple_lens_model()) + lens = _card(presentation, "galaxies/lens") + + assert lens.subtitle == "redshift = 0.5" + # A float stays a float: `redshift = 1` reads like an index. + assert _card(presentation, "galaxies/source").subtitle == "redshift = 1.0" + assert all(pill.key != "galaxies/lens/redshift" for pill in presentation.pills()) + + +def test_free_redshift_keeps_the_ordinary_pill(): + from test_autofit.graph_spec.lens_doubles import Galaxy, sersic + + model = af.Collection( + galaxies=af.Collection( + lens=af.Model( + Galaxy, + redshift=af.UniformPrior(lower_limit=0.0, upper_limit=1.0), + bulge=sersic(), + ) + ) + ) + presentation = _presentation(model) + + assert _card(presentation, "galaxies/lens").subtitle is None + assert _pill(presentation, "galaxies/lens/redshift").state == "free" + + +# ---------------------------------------------------------------- detail + + +def test_detail_priors_adds_the_compact_prior_summary(): + model = af.Model(af.ex.Gaussian) + presentation = _presentation(model, detail="priors") + + # The numbers are the model's own, never re-derived by the figure. + assert ( + _pill(presentation, "centre").text == f"centre {compact_prior(model.centre)}" + ) + assert _pill(presentation, "sigma").text == f"sigma {compact_prior(model.sigma)}" + assert _pill(presentation, "centre").text.startswith("centre U(") + + +def test_detail_priors_prints_the_fixed_value(): + model = af.Model(af.ex.Gaussian) + model.sigma = 3.0 + presentation = _presentation(model, detail="priors") + + assert _pill(presentation, "sigma").text == "sigma = 3" + + +def test_compact_prior_maps_every_family(): + assert ( + compact_prior(af.UniformPrior(lower_limit=0.0, upper_limit=100.0)) + == "U(0, 100)" + ) + assert compact_prior(af.GaussianPrior(mean=0.5, sigma=0.1)) == "N(0.5, 0.1)" + assert ( + compact_prior(af.LogUniformPrior(lower_limit=1e-06, upper_limit=1e06)) + == "LogU(1e-06, 1e+06)" + ) + assert ( + compact_prior( + af.TruncatedGaussianPrior( + mean=0.0, sigma=0.3, lower_limit=-1.0, upper_limit=1.0 + ) + ) + == "TN(0, 0.3, -1, 1)" + ) + + +def test_show_fixed_false_hides_pills_and_prints_the_hidden_count(): + presentation = _presentation(mge_model(), show_fixed=False) + + assert presentation.hidden_fixed > 0 + assert f"{presentation.hidden_fixed} fixed parameters hidden" in presentation.footer + assert all( + pill.state not in ("fixed", "fixed-varies") for pill in presentation.pills() + ) + + +def test_max_depth_folds_a_subtree_into_one_row(): + presentation = _presentation(simple_lens_model(), max_depth=2) + lens = _card(presentation, "galaxies/lens") + + assert lens.children == () + folded = [pill for pill in lens.pills if pill.state == "folded"] + assert [pill.key for pill in folded] == [ + "galaxies/lens/bulge", + "galaxies/lens/mass", + "galaxies/lens/shear", + ] + assert folded[0].text == "… 1 components / 7 priors" + + +# ---------------------------------------------------------------- assertions + + +def test_an_assertion_is_a_compact_constraint_label_not_an_edge(): + presentation = _presentation(_composite()) + + (constraint,) = presentation.constraints + # Labelled `assert`, so it can never be read as a relation, and written the + # way it was declared -- `add_assertion(first.sigma > 5.0)`. + assert constraint.text == "assert a.sigma > 5.0" + assert constraint.left == "a.sigma" + assert constraint.right == "5.0" + assert constraint.key == "a" + assert all(link.kind != "assertion" for link in presentation.links) + assert "dashed orange = constraint (assertion)" in presentation.legend + + +def test_the_constraint_legend_entry_appears_only_when_a_constraint_does(): + assert "constraint" not in _presentation(af.Model(af.ex.Gaussian)).legend + + +def test_an_assertion_between_two_parameters_keeps_the_spec_order(): + """Both sides resolve, so there is nothing to disambiguate -- do not guess.""" + model = af.Model(af.ex.Gaussian) + model.add_assertion(model.sigma > model.normalization) + presentation = _presentation(model) + + (constraint,) = presentation.constraints + assert constraint.text == "assert normalization < sigma" + + +# ---------------------------------------------------------------- legend, footer + + +def test_the_footer_is_singular_for_a_count_of_one(): + model = af.Collection(a=af.Model(af.ex.Gaussian), b=af.Model(af.ex.Gaussian)) + model.b.centre = model.a.centre + presentation = _presentation(model) + + assert "1 shared prior (unique variables, not references)" in presentation.footer + assert "1 plate standing for 2 components" in presentation.footer + assert "0 fixed leaf slots" in presentation.footer + + +def test_the_legend_is_one_line_of_only_the_states_present(): + presentation = _presentation(af.Model(af.ex.Gaussian)) + + assert presentation.legend.count("\n") == 0 + assert presentation.legend == "Legend: free prior" + + +def test_the_footer_defines_its_counts(): + presentation = _presentation(mge_model()) + + assert "16 unique sampled scalars" in presentation.footer + assert "63 fixed leaf slots" in presentation.footer + assert "6 shared priors (unique variables, not references)" in presentation.footer + assert "2 plates standing for 60 components" in presentation.footer + assert "totals include every hidden and collapsed element" in presentation.footer diff --git a/test_autofit/non_linear/paths/test_model_figure_output.py b/test_autofit/non_linear/paths/test_model_figure_output.py new file mode 100644 index 000000000..57c05eb8a --- /dev/null +++ b/test_autofit/non_linear/paths/test_model_figure_output.py @@ -0,0 +1,175 @@ +""" +The per-search ``model.png`` hook in ``DirectoryPaths._save_model_info``. + +The figure is opt-in: ``output.yaml``'s ``model_figure`` key is read strictly, +so a config which has never heard of the key writes no figure even though its +``default:`` is ``true``. And a figure bug must never kill a fit, so a renderer +which raises leaves ``model.info`` written and the exception swallowed into the +log. +""" + +from contextlib import contextmanager +from pathlib import Path + +import matplotlib + +matplotlib.use("Agg") + +import pytest + +import autofit as af +from autonerves import conf + +from autofit.non_linear.paths.directory import _model_figure_enabled + + +@contextmanager +def model_figure_key(value): + """ + Set ``output.yaml``'s ``model_figure`` key for the duration of a test, or + remove it entirely when ``value`` is ``None`` (the "config has never heard + of this key" case, which must still be off). + """ + output = conf.instance["output"] + missing = object() + original = output["model_figure"] if "model_figure" in output else missing + + if value is None: + if original is not missing: + del output["model_figure"] + else: + output["model_figure"] = value + + try: + yield + finally: + if original is missing: + if "model_figure" in output: + del output["model_figure"] + else: + output["model_figure"] = original + + +@contextmanager +def output_path(tmp_path): + """Point ``conf.instance.output_path`` at a temporary directory.""" + original = conf.instance.output_path + conf.instance.output_path = str(tmp_path) + try: + yield + finally: + conf.instance.output_path = original + + +@pytest.fixture(name="model") +def make_model(): + return af.Model(af.ex.Gaussian) + + +def _paths_for(model): + paths = af.DirectoryPaths(name="model_figure") + paths.model = model + paths.search = af.DynestyStatic() + return paths + + +def _written(paths) -> Path: + return Path(paths.output_path) + + +class TestModelFigureEnabled: + def test__key_true(self): + with model_figure_key(True): + assert _model_figure_enabled() is True + + def test__key_false(self): + with model_figure_key(False): + assert _model_figure_enabled() is False + + def test__key_absent_is_off_even_though_default_is_true(self): + """ + ``autonerves.output.should_output`` would return ``default`` here, which + is ``true``. The hook must not: an absent key means off. + """ + with model_figure_key(None): + assert conf.instance["output"]["default"] is True + assert _model_figure_enabled() is False + + +class TestModelPngOutput: + def test__key_true__model_png_written_beside_model_info(self, model, tmp_path): + with output_path(tmp_path), model_figure_key(True): + paths = _paths_for(model) + paths._save_model_info(model=model) + + directory = _written(paths) + assert (directory / "model.info").exists() + assert (directory / "model.png").exists() + assert (directory / "model.png").stat().st_size > 0 + + def test__key_false__no_model_png(self, model, tmp_path): + with output_path(tmp_path), model_figure_key(False): + paths = _paths_for(model) + paths._save_model_info(model=model) + + directory = _written(paths) + assert (directory / "model.info").exists() + assert not (directory / "model.png").exists() + + def test__key_absent__no_model_png(self, model, tmp_path): + with output_path(tmp_path), model_figure_key(None): + paths = _paths_for(model) + paths._save_model_info(model=model) + + directory = _written(paths) + assert (directory / "model.info").exists() + assert not (directory / "model.png").exists() + + def test__skip_visualization__no_model_png(self, model, tmp_path, monkeypatch): + monkeypatch.setenv("PYAUTO_SKIP_VISUALIZATION", "1") + + with output_path(tmp_path), model_figure_key(True): + paths = _paths_for(model) + paths._save_model_info(model=model) + + directory = _written(paths) + assert (directory / "model.info").exists() + assert not (directory / "model.png").exists() + + def test__renderer_raises__model_info_still_written_and_nothing_propagates( + self, model, tmp_path, monkeypatch + ): + """ + A figure bug must never kill a fit. + """ + from autofit.model_figure import ModelPlotter + + def raise_(*args, **kwargs): + raise RuntimeError("the renderer blew up") + + monkeypatch.setattr(ModelPlotter, "figure", raise_) + + with output_path(tmp_path), model_figure_key(True): + paths = _paths_for(model) + paths._save_model_info(model=model) + + directory = _written(paths) + assert (directory / "model.info").exists() + assert not (directory / "model.png").exists() + + def test__renderer_failure_is_logged(self, model, tmp_path, monkeypatch, caplog): + import logging + + from autofit.model_figure import ModelPlotter + + def raise_(*args, **kwargs): + raise RuntimeError("the renderer blew up") + + monkeypatch.setattr(ModelPlotter, "figure", raise_) + + with output_path(tmp_path), model_figure_key(True): + paths = _paths_for(model) + with caplog.at_level(logging.INFO): + paths._save_model_info(model=model) + + assert "model.png not written" in caplog.text