Skip to content

fix: ModelPlotter.figure() draws the figure twice in a notebook #1622

Closed

Description

@Jammy2211

Overview

Reported from a HowToFit tutorial run in Google Colab: the model figure drawn by af.ModelPlotter appears twice, one identical image directly below the other.

autofit/model_figure/render.py:save() both calls plt.show() (the inline backend publishes the figure as a display_data PNG) and returns the Figure. Because the tutorial cells end on af.ModelPlotter(model).figure(), IPython's registered image/png formatter for Figure renders the same figure a second time as the cell's execute_result. Reproduced with nbclient on an identically-shaped cell: two outputs, display_data['image/png'] and execute_result['image/png'].

The same save() is shared by af.EPPlotter, so both plotters are affected, as is every model-figure cell the model-figures rollout added across HowToFit, autofit_workspace and autolens_workspace. Scripts run outside a notebook are unaffected (nothing echoes the return value there). Secondary defect in the same branch: format="show" never calls plt.close(figure), unlike every other branch, so figures leak under a non-inline backend.

Plan

  • Make the format="show" branch of save() show the figure, close it, and return nothing — matching autofit/non_linear/plot/plot_util.py:output_figure, the convention save()'s own docstring cites and which returns nothing and always closes.
  • Leave every other branch (png/svg/pdf/None) returning the Figure exactly as today, so the one in-tree caller (non_linear/paths/directory.py, format="png") and the acceptance tests are untouched.
  • Update the Returns docstrings on ModelPlotter.figure, EPPlotter.figure and save to say the show path returns None.
  • Replace the existing test that pins the current behaviour (test_show_returns_a_figure_and_writes_nothing) with one that pins the fix: the show path returns None and leaves no open figure.
Detailed implementation plan

Affected Repositories

  • PyAutoFit (primary) — library-only fix; the workspace notebooks need no change, they are correct as written.

Branch Survey

Repository Current Branch Dirty?
./PyAutoFit main clean

Suggested branch: claude/howtofit-modelplotter-duplicate-eqr6gk

Implementation Steps

  1. autofit/model_figure/render.py — in save(), change

    if format == "show":
        plt.show()
        return figure

    to show, plt.close(figure), and return None. Update the function docstring: it already promises to mirror output_figure, and output_figure returns nothing and always closes.

  2. autofit/model_figure/plotter.py — ModelPlotter.figure's Returns section becomes "The matplotlib Figure, or None when format="show" (the figure has been shown and closed; returning it makes a notebook draw it a second time)."

  3. autofit/model_figure/ep/plotter.py — same Returns amendment on EPPlotter.figure; it imports the same save, so no code change.

  4. test_autofit/model_figure/test_figure_output.py — rewrite test_show_returns_a_figure_and_writes_nothing as test_show_returns_nothing_so_a_notebook_draws_it_once: monkeypatch plt.show, assert it was called once, assert the return value is None, assert nothing was written to path, and assert plt.get_fignums() == [].

  5. Add the EP equivalent in test_autofit/model_figure/ep/test_acceptance_ep.py (or beside it) so the shared branch is guarded from both entry points.

  6. Run python -m pytest test_autofit/model_figure/ plus the full suite.

Witness

The prompt's witness — a notebook cell whose only content is af.ModelPlotter(model).figure() produces exactly one image/png output — is checked by hand with nbclient against the patched library and reported on the PR. It is deliberately not added to the suite: executing a real kernel per assertion is a slow test for a branch the unit test above already pins exactly.

Key Files

  • autofit/model_figure/render.py — save(), the shared show/write branch (the defect).
  • autofit/model_figure/plotter.py — ModelPlotter.figure, the public entry point.
  • autofit/model_figure/ep/plotter.py — EPPlotter.figure, same save().
  • autofit/non_linear/plot/plot_util.py — output_figure, the convention being matched.
  • test_autofit/model_figure/test_figure_output.py — the test that currently pins the bug.

Original Prompt

Click to expand starting prompt
# ModelPlotter.figure() draws twice in a notebook

Type: bug
Target: PyAutoFit
Repos:
- PyAutoFit
- autofit_workspace
- autolens_workspace
- HowToFit
Difficulty: small
Autonomy: supervised
Priority: normal
Status: formalised
Consequence: glance
Witness: a notebook cell whose only content is `af.ModelPlotter(model).figure()`, executed with nbclient, produces exactly one `image/png` output (today it produces two).
Review-minutes: 3
Unattended: ready

Reported from a HowToFit tutorial run in a Google Colab notebook: the model figure
drawn by `af.ModelPlotter` appears twice, one identical image directly below the
other.

Cause, confirmed by reading the source and reproducing it. `autofit/model_figure/render.py:save()`
does two things on the default `format="show"` path:

    if format == "show":
        plt.show()      # (1) inline backend emits the figure as `display_data`
        return figure   # (2) IPython's PNG formatter for `Figure` emits it again

`plt.show()` under the inline backend (Colab's default) publishes the figure as a
`display_data` message. `figure()` then returns the matplotlib `Figure`, and because
the tutorial cells end on that call, IPython's registered `image/png` formatter for
`Figure` renders the very same figure a second time as the cell's `execute_result`.
Reproduced with nbclient on a cell shaped exactly like the tutorial ones: two outputs,
`display_data['image/png']` and `execute_result['image/png']`.

Every cell whose last expression is a `ModelPlotter` call is affected, i.e. all the
model-figure cells the model-figures rollout added: HowToFit chapter_1 tutorials 1, 3,
4, 7 and the optional Bayesian-formalism tutorial, chapter_advanced tutorials 2, 3, 4,
5, and the equivalent cells across autofit_workspace and autolens_workspace. Scripts
run outside a notebook are unaffected (nothing echoes the return value there).

Secondary defect in the same branch: `format="show"` never calls `plt.close(figure)`,
unlike every other branch of `save()`. Under a non-inline backend the figures stay
open, so a script that draws a model per stage leaks them.

Fix: the `format="show"` path should not hand a renderable `Figure` back to the
notebook. Returning `None` there is the simplest and matches what the caller can do
with it (nothing — it has already been shown); closing the figure on that path too
fixes the leak. `ModelPlotter.figure()`'s docstring ("Returns: The matplotlib Figure")
and any caller that relies on the return value need checking first —
`autofit/non_linear/paths/directory.py:519` calls it with `format="png"`, which is
unaffected. Guard it with a regression test at the level the Witness states.

Activity

  1. Jammy2211 commented on Sep 14, 2026

    @Jammy2211
    CollaboratorAuthor

    Shipped — #1623 merged (6fd754b).

    save()'s format="show" path now shows, closes and returns None, matching non_linear/plot/plot_util.py:output_figure, the convention it was written to mirror. EPPlotter shares the same save and is fixed with it; every other format still returns the Figure, so paths/directory.py (format="png") is untouched. Closing also fixes the leak that branch had under non-inline backends.

    • CI: 4/4 checks green on be80052 (unittest 3.12 / 3.13 / nojax, docs-build); local pytest test_autofit/ -x 2796 passed, 45 skipped.
    • Witness: an nbclient-executed cell whose only content is af.ModelPlotter(model).figure() emitted 2 image/png outputs before the fix (display_data + execute_result) and 1 after.
    • Workspace impact: none. All 153 ModelPlotter/EPPlotter call sites across HowToFit, autofit_workspace and autolens_workspace are bare statements; none binds the return value.

    The PR keeps the pending-release label — the fix reaches Colab users at the next PyAutoFit release.


    Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions