Skip to content

API

Signatures and docstrings are read out of skill/scripts/ when this page builds, so what is shown is what the code has.

Installed and vendored copies have the same signatures. Only the import line differs, and Choose your import line gives it.

Not on this page: the thresholds. They are module-level constants, one table per module on the gates, with the measurement behind each on the style guide. Read them as cf.TYPE_FLOOR_PT.

Everything else is here, including the 21 gate functions, at the bottom. audit is what most callers want: it runs all 21 and computes the renderer, canvas and scale arguments they take. Call one directly and that is yours to reproduce, which the how-to covers.

Three ways to take the same verdict out: audit returns the rows, report prints them for a person, and audit_json serialises them for a build. check_palette.check and check_palette.check_json are the same pair on the colour side, and both JSON documents carry the same schema string, so a CI step collecting figure and palette verdicts reads ok and rows out of either.

check_figure

Composition. Takes a built figure, measures what it renders at print size.

check_figure.audit

audit(fig: Figure, scale: float | None = None, placed_frac: float = 1.0, *, context_axes: Sequence[Axes] | None = None, venue: str | None = None) -> tuple[bool, list[tuple[str, bool | str, str]]]

Run every gate over a figure. Returns (ok, rows).

check_palette.check returns the same shape.

rows are (label, status, detail), one per gate, in the order the report prints them. status is True, False, or the string "warn"; only a hard False sets ok to False, so an advisory row reports without gating a build.

placed_frac is the fraction of the content width the figure is placed at, and venue names a row of VENUE_WIDTH_PT instead of setting CONTENT_WIDTH_PT by hand; between them they decide the page scale every type and stroke measurement runs through. scale overrides that calculation outright. context_axes names axes whose fill is a context surface rather than data ink, which is what stops a filled contourf panel reading as saturated.

context_axes and venue are keyword-only. context_axes is iterated and a string is iterable, so a venue in that slot would be read as axes rather than raise, and the figure measured at the wrong width.

Parameters:

Name Type Description Default
fig Figure

The built figure. Measured through an Agg canvas at MEASURE_DPI and handed back on the dpi it arrived on, as savefig does, so the verdict depends on neither the backend it was made on nor the resolution it was set to. Under a HiDPI backend that is the authored dpi times the device pixel ratio; _original_dpi stays the authored one.

required
scale float | None

Placed size over authored size, overriding page_scale outright.

None
placed_frac float

Fraction of the content width the figure is placed at.

1.0
venue str | None

A key of VENUE_WIDTH_PT, overriding CONTENT_WIDTH_PT.

None
context_axes Sequence[Axes] | None

Axes whose fill is a context surface, not data ink.

None

Returns:

Type Description
bool

(ok, rows). rows are (label, status, detail), one per gate, in

list[tuple[str, bool | str, str]]

report order; ok is False only when a row is a hard False.

Source code in skill/scripts/check_figure.py
def audit(fig: Figure, scale: float | None = None, placed_frac: float = 1.0,
          *,
          context_axes: Sequence[Axes] | None = None,
          venue: str | None = None,
          ) -> tuple[bool, list[tuple[str, bool | str, str]]]:
    """Run every gate over a figure. Returns `(ok, rows)`.

    `check_palette.check` returns the same shape.

    `rows` are `(label, status, detail)`, one per gate, in the order the report
    prints them. `status` is True, False, or the string "warn"; only a hard
    False sets `ok` to False, so an advisory row reports without gating a
    build.

    `placed_frac` is the fraction of the content width the figure is placed at,
    and `venue` names a row of `VENUE_WIDTH_PT` instead of setting
    `CONTENT_WIDTH_PT` by hand; between them they decide the page scale every
    type and stroke measurement runs through. `scale` overrides that
    calculation outright. `context_axes` names axes whose fill is a context
    surface rather than data ink, which is what stops a filled contourf panel
    reading as saturated.

    `context_axes` and `venue` are keyword-only. `context_axes` is iterated and
    a string is iterable, so a venue in that slot would be read as axes rather
    than raise, and the figure measured at the wrong width.

    Args:
        fig: The built figure. Measured through an Agg canvas at `MEASURE_DPI`
            and handed back on the dpi it arrived on, as `savefig` does, so the
            verdict depends on neither the backend it was made on nor the
            resolution it was set to. Under a HiDPI backend that is the
            authored dpi times the device pixel ratio; `_original_dpi` stays
            the authored one.
        scale: Placed size over authored size, overriding `page_scale`
            outright.
        placed_frac: Fraction of the content width the figure is placed at.
        venue: A key of `VENUE_WIDTH_PT`, overriding `CONTENT_WIDTH_PT`.
        context_axes: Axes whose fill is a context surface, not data ink.

    Returns:
        `(ok, rows)`. `rows` are `(label, status, detail)`, one per gate, in
        report order; `ok` is False only when a row is a hard False.
    """
    with _measuring(fig):
        rows = _rows(fig, scale, placed_frac, venue, context_axes)
    return all(s is not False for _, s, _ in rows), rows

check_figure.report

report(fig: Figure, name: str = '', scale: float | None = None, placed_frac: float = 1.0, *, context_axes: Sequence[Axes] | None = None, venue: str | None = None, suggest: bool = False) -> bool

audit(), printed. Returns the same ok bool and nothing else.

The arguments are audit's, plus name for the heading. Advisory rows print as WARN and do not change the verdict, so a figure can be COMPOSED with advisories; only a hard FAIL makes this return False.

suggest=True prints what suggest_fixes.py has to offer for the marked rows, under the table. Off by default and kept in that file rather than this one: a gate measures, and what to do about it is a separate claim that can be wrong on its own. Several rows get more than one suggestion, because the choice between them is the author's.

This is what the examples and the CLI call. Use audit() when the rows themselves are wanted rather than a printed table.

context_axes, venue and suggest are keyword-only, for the reason audit gives.

Parameters:

Name Type Description Default
fig Figure

The built figure.

required
name str

A heading for the table.

''
scale float | None

Placed size over authored size, overriding page_scale outright.

None
placed_frac float

Fraction of the content width the figure is placed at.

1.0
venue str | None

A key of VENUE_WIDTH_PT, overriding CONTENT_WIDTH_PT.

None
context_axes Sequence[Axes] | None

Axes whose fill is a context surface, not data ink.

None
suggest bool

Print suggest_fixes remedies under the table.

False

Returns:

Type Description
bool

audit's ok bool. Advisory rows print as WARN without changing it.

Source code in skill/scripts/check_figure.py
def report(fig: Figure, name: str = "", scale: float | None = None,
           placed_frac: float = 1.0,
           *,
           context_axes: Sequence[Axes] | None = None,
           venue: str | None = None, suggest: bool = False) -> bool:
    """`audit()`, printed. Returns the same `ok` bool and nothing else.

    The arguments are `audit`'s, plus `name` for the heading. Advisory rows
    print as WARN and do not change the verdict, so a figure can be COMPOSED
    with advisories; only a hard FAIL makes this return False.

    `suggest=True` prints what `suggest_fixes.py` has to offer for the marked
    rows, under the table. Off by default and kept in that file rather than
    this one: a gate measures, and what to do about it is a separate claim that
    can be wrong on its own. Several rows get more than one suggestion, because
    the choice between them is the author's.

    This is what the examples and the CLI call. Use `audit()` when the rows
    themselves are wanted rather than a printed table.

    `context_axes`, `venue` and `suggest` are keyword-only, for the reason
    `audit` gives.

    Args:
        fig: The built figure.
        name: A heading for the table.
        scale: Placed size over authored size, overriding `page_scale`
            outright.
        placed_frac: Fraction of the content width the figure is placed at.
        venue: A key of `VENUE_WIDTH_PT`, overriding `CONTENT_WIDTH_PT`.
        context_axes: Axes whose fill is a context surface, not data ink.
        suggest: Print `suggest_fixes` remedies under the table.

    Returns:
        `audit`'s `ok` bool. Advisory rows print as WARN without changing it.
    """
    ok, rows = audit(fig, scale, placed_frac,
                     context_axes=context_axes, venue=venue)
    print(f"\nComposition audit{': ' + name if name else ''}")
    warned = False
    for label, status, detail in rows:
        tag = "WARN" if status == "warn" else ("PASS" if status else "FAIL")
        warned = warned or status == "warn"
        print(f"  [{tag}] {label:<18} {detail}")
    verdict = "COMPOSED" if ok else "FIX THE MARKED CHECKS"
    if ok and warned:
        verdict += " (with advisories)"
    print(f"\n  -> {verdict}\n")
    if suggest:
        _print_suggestions(rows)
    return ok

check_figure.audit_json

audit_json(fig: Figure, scale: float | None = None, placed_frac: float = 1.0, *, name: str = '', context_axes: Sequence[Axes] | None = None, venue: str | None = None) -> str

audit(), as a JSON document. Returns the text, and prints nothing.

report is for a person reading a terminal; this is for a build that has to decide something. The arguments are audit's, plus name, and the verdict is the same object audit computed: this function serialises, it does not re-measure.

The document carries the measurement context as well as the rows, because a verdict without the width it was measured against cannot be read later. A figure that passes at venue="neurips" and fails at icml-column is one figure and two true answers, and a stored artifact that records only the answer is the one that gets quoted at the wrong width. scale is the one the gates actually ran at, resolved from placed_frac and venue rather than echoed from the argument, so it is filled in even when the caller passed neither.

scale is page_scale's number, which is a ratio and not a length: placed size over authored size, 1.0 for a figure measured as authored. The field is named for the argument rather than for a unit, because there is no unit to name.

status is "pass", "fail" or "warn", not the tuple API's True/False/"warn". A JSON consumer should not have to know that one field holds a bool for two of the three cases, and ok is already the bool worth branching on.

schema is AUDIT_SCHEMA, and check_palette.check_json emits the same one. The two documents differ only in tool and inputs, so a CI step that collects both can read ok and rows out of either without asking which checker produced it.

Parameters:

Name Type Description Default
fig Figure

The built figure, measured exactly as audit measures it.

required
scale float | None

Placed size over authored size, overriding page_scale outright.

None
placed_frac float

Fraction of the content width the figure is placed at.

1.0
name str

Recorded as inputs.name, for telling stored artifacts apart.

''
venue str | None

A key of VENUE_WIDTH_PT, overriding CONTENT_WIDTH_PT.

None
context_axes Sequence[Axes] | None

Axes whose fill is a context surface, not data ink.

None

Returns:

Type Description
str

A JSON object as text, with schema, tool, ok, inputs and rows.

Source code in skill/scripts/check_figure.py
def audit_json(fig: Figure, scale: float | None = None,
               placed_frac: float = 1.0,
               *,
               name: str = "",
               context_axes: Sequence[Axes] | None = None,
               venue: str | None = None) -> str:
    """`audit()`, as a JSON document. Returns the text, and prints nothing.

    `report` is for a person reading a terminal; this is for a build that has to
    decide something. The arguments are `audit`'s, plus `name`, and the verdict
    is the same object `audit` computed: this function serialises, it does not
    re-measure.

    The document carries the measurement context as well as the rows, because a
    verdict without the width it was measured against cannot be read later. A
    figure that passes at `venue="neurips"` and fails at `icml-column` is one
    figure and two true answers, and a stored artifact that records only the
    answer is the one that gets quoted at the wrong width. `scale` is the one the
    gates actually ran at, resolved from `placed_frac` and `venue` rather than
    echoed from the argument, so it is filled in even when the caller passed
    neither.

    `scale` is `page_scale`'s number, which is a ratio and not a length: placed
    size over authored size, `1.0` for a figure measured as authored. The field
    is named for the argument rather than for a unit, because there is no unit to
    name.

    `status` is `"pass"`, `"fail"` or `"warn"`, not the tuple API's
    `True`/`False`/`"warn"`. A JSON consumer should not have to know that one
    field holds a bool for two of the three cases, and `ok` is already the bool
    worth branching on.

    `schema` is `AUDIT_SCHEMA`, and `check_palette.check_json` emits the same
    one. The two documents differ only in `tool` and `inputs`, so a CI step that
    collects both can read `ok` and `rows` out of either without asking which
    checker produced it.

    Args:
        fig: The built figure, measured exactly as `audit` measures it.
        scale: Placed size over authored size, overriding `page_scale`
            outright.
        placed_frac: Fraction of the content width the figure is placed at.
        name: Recorded as `inputs.name`, for telling stored artifacts apart.
        venue: A key of `VENUE_WIDTH_PT`, overriding `CONTENT_WIDTH_PT`.
        context_axes: Axes whose fill is a context surface, not data ink.

    Returns:
        A JSON object as text, with `schema`, `tool`, `ok`, `inputs` and `rows`.
    """
    import json

    ok, rows = audit(fig, scale, placed_frac,
                     context_axes=context_axes, venue=venue)
    return json.dumps({
        "schema": AUDIT_SCHEMA,
        "tool": "check_figure",
        "ok": ok,
        "inputs": {
            "name": name,
            "placed_frac": placed_frac,
            "venue": venue,
            "content_width_pt": content_width_pt(venue),
            "scale": (scale if scale is not None
                      else page_scale(fig, placed_frac, venue)),
            "figsize_in": list(fig.get_size_inches()),
            "context_axes": 0 if context_axes is None else len(context_axes),
        },
        "rows": _rows_json(rows),
    }, indent=2)

check_figure.describe

describe(fig: Figure, text: str) -> Figure

Attach a text description to a figure, for readers who cannot see it.

Across 100,000 public Jupyter notebooks, 99.81% of programmatically generated images shipped with no alt text at all, and the overwhelming majority of them were matplotlib. Matplotlib has no field for this, so the description is stashed on the figure and handed to savefig:

describe(fig, "Validation loss against training epoch for three "
              "optimisers. All three fall; the Bayesian run reaches "
              "0.05 by epoch 6, the baseline is still at 0.25 at 12.")
fig.savefig(path, metadata=alt_metadata(fig, path))

Say what the reader would have taken from looking, not what the figure is made of. "A line chart with three lines" describes the file; the numbers and the direction describe the finding.

Parameters:

Name Type Description Default
fig Figure

The figure to attach the description to.

required
text str

The description. ALT_TEXT_MIN_CHARS is the gate's floor. It is stashed on fig for alt_metadata to read.

required

Returns:

Type Description
Figure

fig, as 0.10.0 did.

Source code in skill/scripts/check_figure.py
def describe(fig: Figure, text: str) -> Figure:
    """Attach a text description to a figure, for readers who cannot see it.

    Across 100,000 public Jupyter notebooks, 99.81% of programmatically
    generated images shipped with no alt text at all, and the overwhelming
    majority of them were matplotlib. Matplotlib has no field for this, so the
    description is stashed on the figure and handed to `savefig`:

        describe(fig, "Validation loss against training epoch for three "
                      "optimisers. All three fall; the Bayesian run reaches "
                      "0.05 by epoch 6, the baseline is still at 0.25 at 12.")
        fig.savefig(path, metadata=alt_metadata(fig, path))

    Say what the reader would have taken from looking, not what the figure is
    made of. "A line chart with three lines" describes the file; the numbers
    and the direction describe the finding.

    Args:
        fig: The figure to attach the description to.
        text: The description. `ALT_TEXT_MIN_CHARS` is the gate's floor. It
            is stashed on `fig` for `alt_metadata` to read.

    Returns:
        `fig`, as 0.10.0 did.
    """
    setattr(fig, ALT_TEXT_ATTR, str(text))
    return fig

check_figure.alt_metadata

alt_metadata(fig: Figure, path: Any = None) -> dict[str, str] | None

The metadata= dict for savefig, carrying whatever describe set.

Pass the same path you are about to save to, so the description lands in a field the target format actually has:

fig.savefig(path, metadata=alt_metadata(fig, path))

PNG, PDF and SVG all keep a description and none of them agrees with the others about what to call it, so the key is chosen from the suffix.

For a format that carries no description -- ps, or any of the rasters -- this returns None rather than an empty dict, and the difference is not cosmetic. matplotlib's guard is elif metadata is not None: raise, so an empty dict is rejected exactly as hard as a full one; savefig(path, metadata={}) on a jpeg is a traceback. None is savefig's own default for the argument and the only value those formats accept.

Called without a path, or with a buffer whose format cannot be read, it returns Description. That is right for PNG and SVG and is what every earlier version returned unconditionally.

Parameters:

Name Type Description Default
fig Figure

The figure describe was called on.

required
path Any

The path about to be saved to. The suffix picks the key.

None

Returns:

Type Description
dict[str, str] | None

A dict for savefig(metadata=), or None for a format that carries

dict[str, str] | None

no description. Empty when describe was never called.

Source code in skill/scripts/check_figure.py
def alt_metadata(fig: Figure, path: Any = None) -> dict[str, str] | None:
    """The `metadata=` dict for `savefig`, carrying whatever `describe` set.

    Pass the same `path` you are about to save to, so the description lands in
    a field the target format actually has:

        fig.savefig(path, metadata=alt_metadata(fig, path))

    PNG, PDF and SVG all keep a description and none of them agrees with the
    others about what to call it, so the key is chosen from the suffix.

    For a format that carries no description -- ps, or any of the rasters --
    this returns `None` rather than an empty dict, and the difference is not
    cosmetic. matplotlib's guard is `elif metadata is not None: raise`, so an
    empty dict is rejected exactly as hard as a full one; `savefig(path,
    metadata={})` on a jpeg is a traceback. `None` is `savefig`'s own default
    for the argument and the only value those formats accept.

    Called without a path, or with a buffer whose format cannot be read, it
    returns `Description`. That is right for PNG and SVG and is what every
    earlier version returned unconditionally.

    Args:
        fig: The figure `describe` was called on.
        path: The path about to be saved to. The suffix picks the key.

    Returns:
        A dict for `savefig(metadata=)`, or `None` for a format that carries
        no description. Empty when `describe` was never called.
    """
    # Before the empty-description check, because a format that rejects the
    # kwarg rejects `{}` too -- the figure having nothing to say does not make
    # the jpeg save survive.
    suffix = _savefig_suffix(path) if path is not None else None
    if suffix in ALT_TEXT_UNSUPPORTED_SUFFIXES:
        return None
    text = getattr(fig, ALT_TEXT_ATTR, None)
    if not text:
        return {}
    if suffix is None:
        return {ALT_TEXT_KEY_DEFAULT: text}
    return {ALT_TEXT_KEY_BY_SUFFIX.get(suffix, ALT_TEXT_KEY_DEFAULT): text}

check_figure.page_scale

page_scale(fig: Figure, placed_frac: float = 1.0, venue: str | None = None) -> float

Scale from the authored figure to the one placed on the page.

placed_frac is the fraction of the content width the figure is placed at, so it reads like the call site: \includegraphics[width=0.48\textwidth] is placed_frac=0.48. Without it every figure is measured as if it were full width, and a half-width figure is certified at twice the type size it actually ships at - which is the wrong direction for a legibility gate to be wrong in.

venue names a row of VENUE_WIDTH_PT and overrides CONTENT_WIDTH_PT for this call, which is the usual way in: the width is a property of the document, not of the checkout.

Parameters:

Name Type Description Default
fig Figure

The figure, read for its authored width in inches.

required
placed_frac float

Fraction of the content width the figure is placed at.

1.0
venue str | None

A key of VENUE_WIDTH_PT, overriding CONTENT_WIDTH_PT.

None

Returns:

Type Description
float

Placed size over authored size: a ratio, not a length. 1.0 when no

float

content width is set, which measures the figure at the size it was

float

authored.

Raises:

Type Description
ValueError

placed_frac is not 1.0 and no content width is set.

Source code in skill/scripts/check_figure.py
def page_scale(fig: Figure, placed_frac: float = 1.0,
               venue: str | None = None) -> float:
    """Scale from the authored figure to the one placed on the page.

    `placed_frac` is the fraction of the content width the figure is placed at,
    so it reads like the call site: `\\includegraphics[width=0.48\\textwidth]`
    is `placed_frac=0.48`. Without it every figure is measured as if it were
    full width, and a half-width figure is certified at twice the type size it
    actually ships at - which is the wrong direction for a legibility gate to
    be wrong in.

    `venue` names a row of `VENUE_WIDTH_PT` and overrides `CONTENT_WIDTH_PT` for
    this call, which is the usual way in: the width is a property of the
    document, not of the checkout.

    Args:
        fig: The figure, read for its authored width in inches.
        placed_frac: Fraction of the content width the figure is placed at.
        venue: A key of `VENUE_WIDTH_PT`, overriding `CONTENT_WIDTH_PT`.

    Returns:
        Placed size over authored size: a ratio, not a length. `1.0` when no
        content width is set, which measures the figure at the size it was
        authored.

    Raises:
        ValueError: `placed_frac` is not 1.0 and no content width is set.
    """
    width = content_width_pt(venue)
    if width is None:
        if placed_frac != 1.0:
            raise ValueError(
                "placed_frac requires a content width. With CONTENT_WIDTH_PT "
                "None and no venue= the checker assumes you authored the "
                "figure at the width it is placed at, which already makes the "
                "scale 1.0; a fractional placement contradicts that. Pass "
                "venue=, set CONTENT_WIDTH_PT, or author at the placed width "
                "and drop placed_frac.")
        return 1.0
    return width * placed_frac / (fig.get_size_inches()[0] * 72)

check_figure.content_width_pt

content_width_pt(venue: str | None = None) -> float | None

The usable page width to measure against, in points.

Parameters:

Name Type Description Default
venue str | None

A key of VENUE_WIDTH_PT. None reads CONTENT_WIDTH_PT.

None

Returns:

Type Description
float | None

The width in points, or None when neither is set.

Raises:

Type Description
KeyError

The venue is not in VENUE_WIDTH_PT.

Source code in skill/scripts/check_figure.py
def content_width_pt(venue: str | None = None) -> float | None:
    """The usable page width to measure against, in points.

    Args:
        venue: A key of `VENUE_WIDTH_PT`. `None` reads `CONTENT_WIDTH_PT`.

    Returns:
        The width in points, or `None` when neither is set.

    Raises:
        KeyError: The venue is not in `VENUE_WIDTH_PT`.
    """
    if venue is None:
        return CONTENT_WIDTH_PT
    try:
        return VENUE_WIDTH_PT[venue]
    except KeyError:
        raise KeyError(
            f"unknown venue {venue!r}. Known: "
            f"{', '.join(sorted(VENUE_WIDTH_PT))}. For anything else, put "
            "\\the\\textwidth in the document, read the log, and set "
            "CONTENT_WIDTH_PT to what it says.") from None

check_figure.type_ceiling_pt

type_ceiling_pt(venue: str | None = None, *, panel_label: bool = False) -> float

The largest text size, in points on the page, in force for venue.

The stricter of TYPE_CEILING_PT and the venue's published maximum. A venue passed here replaces the one a configuration file named, the way it replaces CONTENT_WIDTH_PT; TYPE_CEILING_PT holds for both.

Parameters:

Name Type Description Default
venue str | None

A key of VENUE_WIDTH_PT. None uses the venue the last load_config read, if any.

None
panel_label bool

Use the venue's VENUE_PANEL_LABEL_PT row, where it has one, in place of its VENUE_TYPE_CEILING_PT row.

False

Returns:

Type Description
float

The ceiling in points, math.inf when nothing sets one.

Source code in skill/scripts/check_figure.py
def type_ceiling_pt(venue: str | None = None, *,
                    panel_label: bool = False) -> float:
    """The largest text size, in points on the page, in force for `venue`.

    The stricter of `TYPE_CEILING_PT` and the venue's published maximum. A
    `venue` passed here replaces the one a configuration file named, the way
    it replaces `CONTENT_WIDTH_PT`; `TYPE_CEILING_PT` holds for both.

    Args:
        venue: A key of `VENUE_WIDTH_PT`. `None` uses the `venue` the last
            `load_config` read, if any.
        panel_label: Use the venue's `VENUE_PANEL_LABEL_PT` row, where it has
            one, in place of its `VENUE_TYPE_CEILING_PT` row.

    Returns:
        The ceiling in points, `math.inf` when nothing sets one.
    """
    if venue is None:
        venue = _CONFIG_VENUE
    elif venue not in VENUE_WIDTH_PT:
        content_width_pt(venue)  # raises, naming the known venues
    published = VENUE_TYPE_CEILING_PT.get(venue or "", math.inf)
    if panel_label:
        published = VENUE_PANEL_LABEL_PT.get(venue or "", published)
    return min(TYPE_CEILING_PT, published)

check_figure.x_height_fraction cached

x_height_fraction(path: str) -> float | None

The height of a font's x over its em, read from the font file.

Parameters:

Name Type Description Default
path str

A font file, as font_manager.findfont returns.

required

Returns:

Type Description
float | None

The fraction, or None when the font has no x or cannot be read.

Source code in skill/scripts/check_figure.py
@functools.cache
def x_height_fraction(path: str) -> float | None:
    """The height of a font's `x` over its em, read from the font file.

    Args:
        path: A font file, as `font_manager.findfont` returns.

    Returns:
        The fraction, or None when the font has no `x` or cannot be read.
    """
    from matplotlib import ft2font

    no_scale = (ft2font.LoadFlags.NO_SCALE if hasattr(ft2font, "LoadFlags")
                else ft2font.LOAD_NO_SCALE)
    try:
        font = ft2font.FT2Font(str(path))
        if not font.get_char_index(ord("x")):
            return None
        top = font.load_char(ord("x"), flags=no_scale).bbox[3]
    except Exception:                                            # noqa: BLE001
        return None
    return top / font.units_per_EM if top > 0 else None

check_figure.load_config

load_config(path: Any = None, *, start: Any = None) -> dict[str, Any]

Apply a configuration file to the threshold constants.

Assigns the module-level constants the file names, in check_palette as well as here. That is what cf.TYPE_FLOOR_PT = 9.0 does by hand: the gates read the global when they run. Call it once, before audit.

Every key is checked before any is assigned, so a file with one bad key changes nothing. A key that names no constant raises rather than being skipped, unless a released version accepted it: a RETIRED_KEYS key warns and is skipped. A venue naming no row of VENUE_WIDTH_PT comes back as the KeyError content_width_pt raises, which lists the rows it knows.

Parameters:

Name Type Description Default
path Any

The file to read. None searches with find_config.

None
start Any

Directory to search from when path is None.

None

Returns:

Type Description
dict[str, Any]

{name: value} for every constant assigned, CONTENT_WIDTH_PT

dict[str, Any]

included when the file set it through venue. Empty when there is no

dict[str, Any]

file to read.

Warns:

Type Description
FutureWarning

A key is in RETIRED_KEYS.

Raises:

Type Description
ValueError

A key names no settable constant, a value has the wrong type, a value for an integer constant is not a whole number, or the file sets both venue and CONTENT_WIDTH_PT.

Source code in skill/scripts/check_figure.py
def load_config(path: Any = None, *, start: Any = None) -> dict[str, Any]:
    """Apply a configuration file to the threshold constants.

    Assigns the module-level constants the file names, in `check_palette` as well
    as here. That is what `cf.TYPE_FLOOR_PT = 9.0` does by hand: the gates read
    the global when they run. Call it once, before `audit`.

    Every key is checked before any is assigned, so a file with one bad key
    changes nothing. A key that names no constant raises rather than being
    skipped, unless a released version accepted it: a `RETIRED_KEYS` key
    warns and is skipped. A `venue` naming no row of `VENUE_WIDTH_PT` comes back as the
    `KeyError` `content_width_pt` raises, which lists the rows it knows.

    Args:
        path: The file to read. `None` searches with `find_config`.
        start: Directory to search from when `path` is `None`.

    Returns:
        `{name: value}` for every constant assigned, `CONTENT_WIDTH_PT`
        included when the file set it through `venue`. Empty when there is no
        file to read.

    Warns:
        FutureWarning: A key is in `RETIRED_KEYS`.

    Raises:
        ValueError: A key names no settable constant, a value has the wrong
            type, a value for an integer constant is not a whole number, or
            the file sets both `venue` and `CONTENT_WIDTH_PT`.
    """
    if path is None:
        path = find_config(start)
        if path is None:
            return {}
    table = _config_table(path)
    if table is None:
        raise ValueError(
            f"{path} carries no keys for this tool. A figure-gate.toml holds "
            "them at its top level; a pyproject.toml holds them under "
            "[tool.figure-gate]")

    targets = _config_targets()
    if "venue" in table and "CONTENT_WIDTH_PT" in table:
        raise ValueError(
            f"{path} sets both venue and CONTENT_WIDTH_PT, which are the same "
            "width written twice. Keep one")

    planned: dict[str, Any] = {}
    for key, value in table.items():
        if key in RETIRED_KEYS and key not in targets:
            warnings.warn(f"{path} sets {key}, which v0.10.0 accepted and this "
                          f"version ignores: {RETIRED_KEYS[key]}",
                          FutureWarning, stacklevel=2)
            continue
        if key == "venue":
            if not isinstance(value, str):
                raise ValueError(
                    f"{path}: venue is {type(value).__name__}, expected a "
                    "string naming a row of VENUE_WIDTH_PT")
            planned["CONTENT_WIDTH_PT"] = content_width_pt(value)
            continue
        if key not in targets:
            pinned = _pinned_reason(key)
            if pinned is not None:
                raise ValueError(
                    f"{path} sets {key!r}, which is not a threshold: {pinned}. "
                    f"Assign the global before calling audit if you mean it")
            raise ValueError(
                f"{path} sets {key!r}, which names no threshold. "
                f"`python check_figure.py --config` lists every key this "
                f"version accepts. Known: {', '.join(config_keys())}")
        if key == "STYLE_SHEET":
            if not isinstance(value, str):
                raise ValueError(
                    f"{path}: STYLE_SHEET is {type(value).__name__}, expected "
                    "a string naming a .mplstyle file")
            planned[key] = value
            continue
        # Typed by name, not by the current value, which is None until set.
        current = (0.0 if key == "CONTENT_WIDTH_PT"
                   else getattr(targets[key], key))
        if isinstance(value, bool) or not isinstance(value, (int, float)):
            raise ValueError(
                f"{path}: {key} is {type(value).__name__}, expected a "
                f"number ({key} is {getattr(targets[key], key)!r})")
        # An int constant is a count or a window size, and TOML writes `9.0`
        # as a float, which `range` and slicing refuse.
        if isinstance(current, int):
            if not float(value).is_integer():
                raise ValueError(
                    f"{path}: {key} is {value!r}, expected a whole number "
                    f"({key} is {current!r})")
            value = int(value)
        planned[key] = value

    for key, value in planned.items():
        setattr(targets.get(key, sys.modules[__name__]), key, value)
    # A file that sets the width names the document, so the venue's maxima
    # follow it: `venue = "science"` after `venue = "nature"` drops Nature's.
    global _CONFIG_VENUE
    if "venue" in table:
        _CONFIG_VENUE = table["venue"]
    elif "CONTENT_WIDTH_PT" in table:
        _CONFIG_VENUE = None
    return planned

check_figure.find_config

find_config(start: Any = None) -> Any

The nearest configuration file at or above start, or None.

Walks up from start (the current directory when it is None) to the filesystem root, and at each level takes figure-gate.toml before pyproject.toml. A pyproject.toml with no [tool.figure-gate] table is not a configuration file and the walk continues past it: a project that keeps its figures in a subdirectory with its own file is the ordinary case, and stopping at the first pyproject.toml would find the wrong one.

Parameters:

Name Type Description Default
start Any

Directory to search from. None means the current directory.

None

Returns:

Type Description
Any

A pathlib.Path, or None when no file above start carries the keys.

Source code in skill/scripts/check_figure.py
def find_config(start: Any = None) -> Any:
    """The nearest configuration file at or above `start`, or `None`.

    Walks up from `start` (the current directory when it is `None`) to the
    filesystem root, and at each level takes `figure-gate.toml` before
    `pyproject.toml`. A `pyproject.toml` with no `[tool.figure-gate]` table is
    not a configuration file and the walk continues past it: a project that
    keeps its figures in a subdirectory with its own file is the ordinary case,
    and stopping at the first `pyproject.toml` would find the wrong one.

    Args:
        start: Directory to search from. `None` means the current directory.

    Returns:
        A `pathlib.Path`, or `None` when no file above `start` carries the keys.
    """
    here = Path(start if start is not None else ".").resolve()
    for folder in (here, *here.parents):
        for name in CONFIG_FILENAMES:
            candidate = folder / name
            if candidate.is_file() and _config_table(candidate) is not None:
                return candidate
    return None

check_figure.config_keys

config_keys() -> list[str]

Every key a configuration file may set, sorted.

venue is in the list and is not a constant: it sets CONTENT_WIDTH_PT from VENUE_WIDTH_PT, and type_ceiling_pt reads the venue's maxima.

A palette key is only here when check_palette.py is importable. Naming one without it raises rather than being ignored.

Source code in skill/scripts/check_figure.py
def config_keys() -> list[str]:
    """Every key a configuration file may set, sorted.

    `venue` is in the list and is not a constant: it sets `CONTENT_WIDTH_PT`
    from `VENUE_WIDTH_PT`, and `type_ceiling_pt` reads the venue's maxima.

    A palette key is only here when `check_palette.py` is importable. Naming one
    without it raises rather than being ignored.
    """
    return sorted(set(_config_targets()) | set(CONFIG_ALIASES))

check_figure.scatter_diameter_pt

scatter_diameter_pt(size: float | ndarray) -> float | ndarray

The diameter in points that scatter(s=size) actually draws.

matplotlib documents s as "the marker size in points**2", which reads as an area and is not one. The unit marker path for 'o' is a circle of radius 0.5, and scatter scales it by sqrt(s): the drawn diameter is sqrt(s) points and the drawn area is pi * s / 4, a factor 4/pi below the nominal number.

Measured rather than inferred. At 200 dpi, scatter(s=100) and plot(markersize=10) each lay down 741 pixels of ink, which is what makes markersize and sqrt(s) the same quantity and s an area only up to that constant. test_scatter_size_is_a_squared_diameter pins it against matplotlib rather than against this docstring.

Parameters:

Name Type Description Default
size float | ndarray

The value passed to scatter(s=). A float or a numpy array.

required

Returns:

Type Description
float | ndarray

The drawn diameter in points, sqrt(size), in the same shape as

float | ndarray

size was given.

Public because both check_mark_ratio and check_overplotting decide on it.

Source code in skill/scripts/check_figure.py
def scatter_diameter_pt(size: float | np.ndarray) -> float | np.ndarray:
    """The diameter in points that `scatter(s=size)` actually draws.

    matplotlib documents `s` as "the marker size in points**2", which reads as
    an area and is not one. The unit marker path for 'o' is a circle of radius
    0.5, and scatter scales it by `sqrt(s)`: the drawn diameter is `sqrt(s)`
    points and the drawn area is `pi * s / 4`, a factor 4/pi below the nominal
    number.

    Measured rather than inferred. At 200 dpi, `scatter(s=100)` and
    `plot(markersize=10)` each lay down 741 pixels of ink, which is what makes
    `markersize` and `sqrt(s)` the same quantity and `s` an area only up to
    that constant. `test_scatter_size_is_a_squared_diameter` pins it against
    matplotlib rather than against this docstring.

    Args:
        size: The value passed to `scatter(s=)`. A float or a numpy array.

    Returns:
        The drawn diameter in points, `sqrt(size)`, in the same shape as
        `size` was given.

    Public because both `check_mark_ratio` and `check_overplotting` decide on
    it.
    """
    return size ** 0.5

check_figure.marker_extent_pt

marker_extent_pt(line: Any, dpi: float, stroked: bool = True) -> tuple[float, float]

The width and height in points that a plot marker actually draws.

markersize is a diameter in points, which is the honest half of the story and the half that made scatter_diameter_pt necessary on the other side. The rest is that matplotlib does not draw every marker at that diameter:

  • "," ignores markersize outright. lines.py special-cases it and skips the scale, so the mark is one device pixel however large the number is: measured here at ms 1, 3, 6, 12 and 24, every one laid down exactly 1 pixel of ink.
  • "." carries a scale(0.5) in its own transform, so it draws at half the diameter asked for; ms=6 and "o" at ms=3 each put down 101 pixels.
  • "|" and "_" are one segment. Their path has zero extent across the stroke, so what they draw across it is markeredgewidth and nothing else - 2px wide against 10px tall at ms 5, mew 1.

So the extent is the marker's own unit path, transformed the way the marker will transform it, scaled by markersize. Checked against the render for o . s ^ D * | _ , across two sizes; every prediction landed within a pixel of the drawn bounding box.

The edge stroke is counted, and where it lands is measured rather than assumed. A stroke is centred on the path, so it puts half its width outside the outline on each side and widens the bounding box by one full markeredgewidth; but marker strokes are butt-capped, so it does not reach past the ends of an open path. Rendered at 600 dpi, ink minus path:

"o"  mew 1  +1.12 across  +1.12 down     "|"  mew 1  +1.20 across  +0.04 down
"o"  mew 2  +2.08 across  +2.08 down     "|"  mew 2  +2.04 across  +0.16 down

One rule covers both: the stroke widens an axis exactly when the path has extent in the other one. A disc has extent in both, so both grow. A bar marker is a segment with extent in one, so it grows across the stroke and not along it. That subsumes the older special case, which returned the stroke as a fallback for an axis of zero extent and arrived at the same number by a narrower argument.

Counting it is what makes this agree with the render rather than with scatter_diameter_pt. The two were once left to under-report together on the theory that a row reading the two spellings differently is a defect, but that symmetry is a property of two rcParams and not of the two APIs: under bare matplotlib defaults lines.markeredgewidth and patch.linewidth are both 1.0 and one 4pt mark draws 5.16pt either way, while under this project's own figure.mplstyle they are 0.0 and 0.7 and the same mark draws 4.20pt from plot against 4.92pt from scatter. Leaving the stroke out bought agreement in the case that already agreed and manufactured it in the case that does not. check_overplotting states what the corpus paid for the change, which was nothing.

An edge that is not drawn adds nothing: a zero width, or an edge colour that is transparent or "none", is the artist declining to stroke rather than a stroke of no consequence.

Parameters:

Name Type Description Default
line Any

A Line2D.

required
dpi float

The resolution the figure will be measured at, needed only for ",", whose size is a device pixel rather than a length.

required
stroked bool

Count the edge stroke. check_mark_ratio passes False, because its scatter side reads s alone.

True

Returns:

Type Description
tuple[float, float]

(width_pt, height_pt) of the drawn mark's bounding box.

Source code in skill/scripts/check_figure.py
def marker_extent_pt(line: Any, dpi: float,
                     stroked: bool = True) -> tuple[float, float]:
    """The width and height in points that a `plot` marker actually draws.

    `markersize` is a diameter in points, which is the honest half of the
    story and the half that made `scatter_diameter_pt` necessary on the other
    side. The rest is that matplotlib does not draw every marker at that
    diameter:

    - `","` ignores `markersize` outright. `lines.py` special-cases it and
      skips the scale, so the mark is one device pixel however large the
      number is: measured here at ms 1, 3, 6, 12 and 24, every one laid down
      exactly 1 pixel of ink.
    - `"."` carries a `scale(0.5)` in its own transform, so it draws at half
      the diameter asked for; `ms=6` and `"o"` at `ms=3` each put down 101
      pixels.
    - `"|"` and `"_"` are one segment. Their path has zero extent across the
      stroke, so what they draw across it is `markeredgewidth` and nothing
      else - 2px wide against 10px tall at ms 5, mew 1.

    So the extent is the marker's own unit path, transformed the way the
    marker will transform it, scaled by `markersize`. Checked against the
    render for `o . s ^ D * | _ ,` across two sizes; every prediction landed
    within a pixel of the drawn bounding box.

    The edge stroke is counted, and where it lands is measured rather than
    assumed. A stroke is centred on the path, so it puts half its width
    outside the outline on each side and widens the bounding box by one full
    `markeredgewidth`; but marker strokes are butt-capped, so it does not
    reach past the *ends* of an open path. Rendered at 600 dpi, ink minus path:

    ```text
    "o"  mew 1  +1.12 across  +1.12 down     "|"  mew 1  +1.20 across  +0.04 down
    "o"  mew 2  +2.08 across  +2.08 down     "|"  mew 2  +2.04 across  +0.16 down
    ```

    One rule covers both: **the stroke widens an axis exactly when the path has
    extent in the other one.** A disc has extent in both, so both grow. A bar
    marker is a segment with extent in one, so it grows across the stroke and
    not along it. That subsumes the older special case, which returned the
    stroke as a fallback for an axis of zero extent and arrived at the same
    number by a narrower argument.

    Counting it is what makes this agree with the render rather than with
    `scatter_diameter_pt`. The two were once left to under-report together on
    the theory that a row reading the two spellings differently is a defect,
    but that symmetry is a property of two rcParams and not of the two APIs:
    under bare matplotlib defaults `lines.markeredgewidth` and
    `patch.linewidth` are both 1.0 and one 4pt mark draws 5.16pt either way,
    while under this project's own `figure.mplstyle` they are 0.0 and 0.7 and
    the same mark draws 4.20pt from `plot` against 4.92pt from `scatter`.
    Leaving the stroke out bought agreement in the case that already agreed
    and manufactured it in the case that does not. `check_overplotting` states
    what the corpus paid for the change, which was nothing.

    An edge that is not drawn adds nothing: a zero width, or an edge colour
    that is transparent or `"none"`, is the artist declining to stroke rather
    than a stroke of no consequence.

    Args:
        line: A `Line2D`.
        dpi: The resolution the figure will be measured at, needed only for
            `","`, whose size is a device pixel rather than a length.
        stroked: Count the edge stroke. `check_mark_ratio` passes False,
            because its `scatter` side reads `s` alone.

    Returns:
        `(width_pt, height_pt)` of the drawn mark's bounding box.
    """
    from matplotlib.markers import MarkerStyle

    marker = line.get_marker()
    if _str_equal(marker, ","):
        one_pixel = 72.0 / dpi
        return one_pixel, one_pixel
    style = MarkerStyle(marker)
    box = style.get_path().transformed(style.get_transform()).get_extents()
    size = float(line.get_markersize())
    stroke = marker_stroke_pt(line) if stroked else 0.0
    width, height = box.width * size, box.height * size
    return (width + (stroke if height else 0.0),
            height + (stroke if width else 0.0))

check_figure.marker_stroke_pt

marker_stroke_pt(line: Any) -> float

The stroke line actually lays down around each marker, in points.

Zero when the edge is not drawn at all, which figure.mplstyle is the reason to care about: it ships lines.markeredgewidth: 0.0, so every plot marker in this project's own gallery is unstroked and any widening read off the width alone would be measuring ink that is not on the page.

get_markeredgecolor resolves "auto" to a real colour itself, so the only strings that reach to_rgba here are ones it understands, "none" among them at alpha 0.

Parameters:

Name Type Description Default
line Any

A Line2D.

required

Returns:

Type Description
float

markeredgewidth in points, or 0.0 if nothing is stroked.

Source code in skill/scripts/check_figure.py
def marker_stroke_pt(line: Any) -> float:
    """The stroke `line` actually lays down around each marker, in points.

    Zero when the edge is not drawn at all, which `figure.mplstyle` is the
    reason to care about: it ships `lines.markeredgewidth: 0.0`, so every
    `plot` marker in this project's own gallery is unstroked and any widening
    read off the width alone would be measuring ink that is not on the page.

    `get_markeredgecolor` resolves `"auto"` to a real colour itself, so the
    only strings that reach `to_rgba` here are ones it understands, `"none"`
    among them at alpha 0.

    Args:
        line: A `Line2D`.

    Returns:
        `markeredgewidth` in points, or 0.0 if nothing is stroked.
    """
    from matplotlib.colors import to_rgba

    width = float(line.get_markeredgewidth())
    if width <= 0.0:
        return 0.0
    try:
        if to_rgba(line.get_markeredgecolor())[3] <= 0.0:
            return 0.0
    except (ValueError, TypeError):        # an exotic colour spec; it draws
        return width
    return width

check_figure.collection_stroke_pt

collection_stroke_pt(coll: Any) -> float

The stroke a scatter actually lays down around each mark, in points.

The scatter half of marker_stroke_pt, and the reason it is a separate function is that a Collection says "nothing is stroked" a third way that a Line2D has no equivalent of. edgecolors="none" leaves get_edgecolors() an empty (0, 4) array while get_linewidths() keeps reporting the patch.linewidth default, so a width read on its own is a width for a stroke that never happens.

That case is not hypothetical. gallery-parity is spelled exactly this way, and taking its reported 0.70pt as drawn moves it from 48.8% contact to 58.3% and past OVERPLOT_THRESHOLD - a hard false positive, on the one corpus figure the question reaches at all, off ink the render does not contain.

Parameters:

Name Type Description Default
coll Any

A Collection, normally the PathCollection from scatter.

required

Returns:

Type Description
float

The drawn stroke width in points, or 0.0 if nothing is stroked.

Source code in skill/scripts/check_figure.py
def collection_stroke_pt(coll: Any) -> float:
    """The stroke a scatter actually lays down around each mark, in points.

    The `scatter` half of `marker_stroke_pt`, and the reason it is a separate
    function is that a `Collection` says "nothing is stroked" a third way that
    a `Line2D` has no equivalent of. `edgecolors="none"` leaves
    `get_edgecolors()` an empty `(0, 4)` array while `get_linewidths()` keeps
    reporting the `patch.linewidth` default, so a width read on its own is a
    width for a stroke that never happens.

    That case is not hypothetical. `gallery-parity` is spelled exactly this
    way, and taking its reported 0.70pt as drawn moves it from 48.8% contact
    to 58.3% and past `OVERPLOT_THRESHOLD` - a hard false positive, on the one
    corpus figure the question reaches at all, off ink the render does not
    contain.

    Args:
        coll: A `Collection`, normally the `PathCollection` from `scatter`.

    Returns:
        The drawn stroke width in points, or 0.0 if nothing is stroked.
    """
    import numpy as np

    edges = np.asarray(coll.get_edgecolors(), dtype=float)
    if edges.size == 0:                          # edgecolors="none"
        return 0.0
    if edges.ndim == 2 and edges[:, 3].max() <= 0.0:
        return 0.0
    widths = np.asarray(coll.get_linewidths(), dtype=float)
    if widths.size == 0:
        return 0.0
    return max(float(widths.max()), 0.0)

check_figure.bars_rest_on_a_shared_edge

bars_rest_on_a_shared_edge(ax: Axes, vertical: bool) -> bool

Whether these bars stand on one edge or each carries its own offset.

What separates a bar chart from a Gantt chart or a waterfall, and the only thing check_form needs to know once a BarContainer has already said these are bars.

A bar chart's lengths are all measured from one edge, so cutting that edge misstates every one of them. A Gantt bar's length is a duration and its position is a start date; a waterfall segment's length is a delta and its base is the running total. Neither is measured from the axis edge, so neither has a baseline to truncate, and the row's own advice - "the fix is the form, not the axis" - is not actionable against them.

The shared edge is the modal one rather than a unanimous one, so a stacked chart is read by its bottom row rather than not at all. On its own that is too loose: a four-step waterfall had two segments land on the same edge by arithmetic. So every rectangle off the modal edge has to stand on the top of another one in its own column, which is what stacking is and what floating is not.

This is deliberately narrower than the detection path that reads a heap of loose rectangles, which has to decide whether they are a bar chart at all and carries two guards for that: at least FORM_BAR_MIN_PATCHES of them, and more than one distinct length. Both are right for detection and wrong once a container has already answered the question. A single truncated bar and a row of equal truncated bars are bar charts on the container's own word, and they still misstate their values; measured, both pass check_form if the detection guards are reused for this question.

Parameters:

Name Type Description Default
ax Axes

The panel.

required
vertical bool

The bar direction, from the container.

required

Returns:

Type Description
bool

True when the bars share a baseline, including by stacking on it, and

bool

when there is nothing here to judge.

Source code in skill/scripts/check_figure.py
def bars_rest_on_a_shared_edge(ax: Axes, vertical: bool) -> bool:
    """Whether these bars stand on one edge or each carries its own offset.

    What separates a bar chart from a Gantt chart or a waterfall, and the only
    thing `check_form` needs to know once a `BarContainer` has already said
    these are bars.

    A bar chart's lengths are all measured from one edge, so cutting that edge
    misstates every one of them. A Gantt bar's length is a duration and its
    position is a start date; a waterfall segment's length is a delta and its
    base is the running total. Neither is measured from the axis edge, so
    neither has a baseline to truncate, and the row's own advice - "the fix is
    the form, not the axis" - is not actionable against them.

    The shared edge is the modal one rather than a unanimous one, so a stacked
    chart is read by its bottom row rather than not at all. On its own that is
    too loose: a four-step waterfall had two segments land on the same edge by
    arithmetic. So every rectangle off the modal edge has to *stand on* the top
    of another one in its own column, which is what stacking is and what
    floating is not.

    This is deliberately narrower than the detection path that reads a heap of
    loose rectangles, which has to decide whether they are a bar chart *at all*
    and carries two guards for that: at least `FORM_BAR_MIN_PATCHES` of them,
    and more than one distinct length. Both are right for detection and wrong
    once a container has already answered the question. A single truncated bar
    and a row of equal truncated bars are bar charts on the container's own
    word, and they still misstate their values; measured, both pass
    `check_form` if the detection guards are reused for this question.

    Args:
        ax: The panel.
        vertical: The bar direction, from the container.

    Returns:
        True when the bars share a baseline, including by stacking on it, and
        when there is nothing here to judge.
    """
    rects = _bar_rects(ax)
    if not rects:
        return True                          # the container's word stands
    base_of, span_of, cross_of, lim = _bar_axis(ax, vertical)
    lo, hi = lim
    tol = abs(hi - lo) * FORM_BAR_BASELINE_TOL
    if not tol:
        return True
    key, _ = Counter(round(base_of(p) / tol) for p in rects).most_common(1)[0]
    tops = {(cross_of(p), round((base_of(p) + span_of(p)) / tol)) for p in rects}
    return all(round(base_of(p) / tol) == key
               or (cross_of(p), round(base_of(p) / tol)) in tops
               for p in rects)

check_palette

Colour. Standard library only, so these are also the functions to port when the checks are reimplemented elsewhere.

check_palette.check

check(colors: Sequence[str], surface: str = '#ffffff', all_pairs: bool = False, ordinal: bool = False, ink: Collection[str] = frozenset()) -> tuple[bool, list[tuple[str, bool | str, str]]]

Gate a palette. Returns (ok, rows).

check_figure.audit returns the same shape.

rows are (name, status, detail), one per gate. status is True, False, or the string "warn" for the advisory contrast row, and only a hard False sets ok to False.

colors are hex strings. surface is the page they are drawn on and sets what the contrast row measures against. all_pairs gates every pair rather than adjacent ones, which is what a scatter needs and a line chart does not. ordinal swaps the categorical separation rows for the ramp rows: monotone lightness, even steps, a light end that still holds contrast. ink names colours to treat as furniture rather than data.

Parameters:

Name Type Description Default
colors Sequence[str]

Hex strings, the palette to gate.

required
surface str

The page colour they are drawn on.

'#ffffff'
all_pairs bool

Gate every pair rather than adjacent ones.

False
ordinal bool

Swap the categorical rows for the ramp rows.

False
ink Collection[str]

Colours to treat as furniture rather than data.

frozenset()

Returns:

Type Description
bool

(ok, rows). rows are (name, status, detail), one per gate;

list[tuple[str, bool | str, str]]

status is True, False or "warn", and ok is False only when a

tuple[bool, list[tuple[str, bool | str, str]]]

row is a hard False.

Source code in skill/scripts/check_palette.py
def check(colors: Sequence[str], surface: str = "#ffffff",
          all_pairs: bool = False, ordinal: bool = False,
          ink: Collection[str] = frozenset(),
          ) -> tuple[bool, list[tuple[str, bool | str, str]]]:
    """Gate a palette. Returns `(ok, rows)`.

    `check_figure.audit` returns the same shape.

    `rows` are `(name, status, detail)`, one per gate. `status` is True,
    False, or the string "warn" for the advisory contrast row, and only a
    hard False sets `ok` to False.

    `colors` are hex strings. `surface` is the page they are drawn on and sets
    what the contrast row measures against. `all_pairs` gates every pair rather
    than adjacent ones, which is what a scatter needs and a line chart does
    not. `ordinal` swaps the categorical separation rows for the ramp rows:
    monotone lightness, even steps, a light end that still holds contrast.
    `ink` names colours to treat as furniture rather than data.

    Args:
        colors: Hex strings, the palette to gate.
        surface: The page colour they are drawn on.
        all_pairs: Gate every pair rather than adjacent ones.
        ordinal: Swap the categorical rows for the ramp rows.
        ink: Colours to treat as furniture rather than data.

    Returns:
        `(ok, rows)`. `rows` are `(name, status, detail)`, one per gate;
        `status` is True, False or "warn", and `ok` is False only when a
        row is a hard False.
    """
    lin = [hex_to_linear(c) for c in colors]
    lab = [linear_to_oklab(v) for v in lin]
    rows: list[tuple[str, bool | str, str]] = []
    ok = True

    if ordinal:
        ls = [v[0] for v in lab]
        mono = all(x > y for x, y in zip(ls, ls[1:])) or all(x < y for x, y in zip(ls, ls[1:]))
        rows.append(("Lightness monotone", mono, "steps read light->dark" if mono
                     else "steps are not monotone in lightness"))
        gaps = [abs(x - y) for x, y in zip(ls, ls[1:])]
        gap_ok = all(g >= ORDINAL_DL_MIN for g in gaps)
        rows.append(("Adjacent dL", gap_ok,
                     f"min gap {min(gaps):.3f}" if gaps else "single step"))
        light_end = max(colors, key=lambda c: linear_to_oklab(hex_to_linear(c))[0])
        cr = contrast(light_end, surface)
        rows.append(("Light-end contrast", cr >= ORDINAL_LIGHT_END_CONTRAST_MIN,
                     f"{light_end} at {cr:.2f}:1 vs surface"))
        # Step uniformity replaced an earlier "Single hue" gate (hue spread <= 20
        # degrees). That gate was a proxy for the property actually wanted, and it
        # rejected perceptually uniform multi-hue ramps such as viridis while
        # accepting a single-hue ramp with wildly uneven steps. What makes a ramp
        # readable is monotone lightness in even increments, which the three rows
        # above plus this one measure directly. The rainbow failure mode the old
        # gate was aimed at (jet) is caught by "Lightness monotone".
        ratio = max(gaps) / min(gaps) if gaps and min(gaps) > 0 else float("inf")
        rows.append(("Step uniformity", ratio <= ORDINAL_STEP_RATIO_MAX,
                     f"largest/smallest dL {ratio:.2f}" if gaps else "single step"))
        return all(r[1] for r in rows), rows

    # Hex is case-insensitive and its `#` optional, as `hex_to_linear` reads
    # it, so `#52514E`, `#52514e` and `52514e` are one ink.
    def key(c: str) -> str:
        return c.strip().lower().lstrip("#")
    ink_set = {key(c) for c in ink}
    band = [c for c, v in zip(colors, lab)
            if key(c) not in ink_set and not (L_MIN <= v[0] <= L_MAX)]
    n_exempt_band = sum(1 for c in colors if key(c) in ink_set and
                        not (L_MIN <= linear_to_oklab(hex_to_linear(c))[0] <= L_MAX))
    rows.append(("Lightness band", not band,
                 f"all {len(colors)} inside L {L_MIN}-{L_MAX}" if not band
                 else f"outside: {band}"
                 + (f" ({n_exempt_band} ink tokens exempted)" if n_exempt_band else "")))

    chroma = [c for c, v in zip(colors, lab)
              if key(c) not in ink_set and math.hypot(v[1], v[2]) < CHROMA_MIN]
    n_exempt_chroma = sum(1 for c in colors if key(c) in ink_set and
                          math.hypot(*linear_to_oklab(hex_to_linear(c))[1:]) < CHROMA_MIN)
    rows.append(("Chroma floor", not chroma,
                 f"all {len(colors)} >= {CHROMA_MIN}" if not chroma
                 else f"too gray: {chroma}"
                 + (f" ({n_exempt_chroma} ink tokens exempted)" if n_exempt_chroma else "")))

    pairs = (list(itertools.combinations(range(len(colors)), 2)) if all_pairs
             else [(i, i + 1) for i in range(len(colors) - 1)])
    label = "all-pairs" if all_pairs else "adjacent"

    # Gate on protanopia and deuteranopia (~8% of males between them). Tritan is
    # reported but not gated: it is ~0.01% prevalence, and no floor for it has
    # been measured against the corpus.
    #
    # Swept over severity, not read at the endpoint: dichromacy is not the worst
    # case. Dichromacy is read under both models, Vienot's and Machado's own
    # severity 1.0, so the sweep has one model from end to end and the worst
    # case covers the disagreement between the two. MACHADO's comment has the
    # measurement.
    numbers = {(i, j): _separation_numbers(lin[i], lin[j]) for i, j in pairs}
    worst_cvd, worst_cvd_at = float("inf"), None
    for (i, j), (d, kind, at, _, _) in numbers.items():
        if d < worst_cvd:
            worst_cvd, worst_cvd_at = d, (colors[i], colors[j], kind, at)
    worst_tri = min((n[3] for n in numbers.values()), default=float("nan"))
    if worst_cvd_at:
        a, b, kind, at = worst_cvd_at
        rows.append((f"CVD separation ({label})", worst_cvd >= CVD_TARGET,
                     _cvd_detail(a, b, worst_cvd, kind, at, worst_tri)))

    worst_n, worst_n_at = float("inf"), None
    for (i, j), n in numbers.items():
        if n[4] < worst_n:
            worst_n, worst_n_at = n[4], (colors[i], colors[j])
    if worst_n_at:
        a, b = worst_n_at
        rows.append((f"Normal-vision floor ({label})", worst_n >= NORMAL_FLOOR,
                     _normal_detail(a, b, worst_n)))

    # Advisory, not a gate: a sub-3:1 hue is legal, it just obligates a visible
    # direct label. Reporting it as FAIL while the run still passes reads as a
    # contradiction, so it carries its own status.
    low = [(c, round(contrast(c, surface), 2)) for c in colors if contrast(c, surface) < CONTRAST_MIN]
    rows.append(("Contrast vs surface", "warn" if low else True,
                 f"all >= {CONTRAST_MIN}:1" if not low
                 else f"under {CONTRAST_MIN}:1, each needs a visible direct label: {low}"))

    ok = all(r[1] is True for r in rows if r[1] != "warn")
    return ok, rows

check_palette.check_json

check_json(colors: Sequence[str], surface: str = '#ffffff', all_pairs: bool = False, ordinal: bool = False, ink: Collection[str] = frozenset()) -> str

check(), as a JSON document. Returns the text, and prints nothing.

What --json prints, and what to call from a build that has to decide something rather than show someone a table. The arguments are check's, and the verdict is the object check computed: this function serialises, it does not re-gate.

The document carries the inputs as well as the rows. A palette verdict is a verdict about a palette on a surface, gated as categorical or as a ramp, and one that records only ok cannot be read a month later: the same eight hexes pass on white and fail on a tinted page, and both answers are true.

status is "pass", "fail" or "warn", not the tuple API's True/False/"warn", and schema is the one check_figure.audit_json emits, so a CI step collecting both reads ok and rows out of either without asking which checker wrote it.

Parameters:

Name Type Description Default
colors Sequence[str]

Hex strings, the palette to gate.

required
surface str

The page colour they are drawn on.

'#ffffff'
all_pairs bool

Gate every pair rather than adjacent ones.

False
ordinal bool

Swap the categorical rows for the ramp rows.

False
ink Collection[str]

Colours to treat as furniture rather than data.

frozenset()

Returns:

Type Description
str

A JSON object as text, with schema, tool, ok, inputs and rows.

Source code in skill/scripts/check_palette.py
def check_json(colors: Sequence[str], surface: str = "#ffffff",
               all_pairs: bool = False, ordinal: bool = False,
               ink: Collection[str] = frozenset()) -> str:
    """`check()`, as a JSON document. Returns the text, and prints nothing.

    What `--json` prints, and what to call from a build that has to decide
    something rather than show someone a table. The arguments are `check`'s, and
    the verdict is the object `check` computed: this function serialises, it does
    not re-gate.

    The document carries the inputs as well as the rows. A palette verdict is a
    verdict about a palette *on a surface*, gated as categorical or as a ramp,
    and one that records only `ok` cannot be read a month later: the same eight
    hexes pass on white and fail on a tinted page, and both answers are true.

    `status` is `"pass"`, `"fail"` or `"warn"`, not the tuple API's
    `True`/`False`/`"warn"`, and `schema` is the one
    `check_figure.audit_json` emits, so a CI step collecting both reads `ok` and
    `rows` out of either without asking which checker wrote it.

    Args:
        colors: Hex strings, the palette to gate.
        surface: The page colour they are drawn on.
        all_pairs: Gate every pair rather than adjacent ones.
        ordinal: Swap the categorical rows for the ramp rows.
        ink: Colours to treat as furniture rather than data.

    Returns:
        A JSON object as text, with `schema`, `tool`, `ok`, `inputs` and `rows`.
    """
    import json

    ok, rows = check(colors, surface, all_pairs, ordinal, ink)
    return json.dumps({
        "schema": AUDIT_SCHEMA,
        "tool": "check_palette",
        "ok": ok,
        "inputs": {
            "colors": list(colors),
            "surface": surface,
            "pairs": "all" if all_pairs else "adjacent",
            "ordinal": ordinal,
            # Sorted, not insertion-ordered: `ink` is a set in the signature, so
            # the order a caller happened to pass is not information, and an
            # unsorted dump makes two identical runs produce two different files.
            "ink": sorted(ink),
        },
        "rows": [{"name": name, "status": _STATUS_JSON[status],
                  "detail": detail} for name, status, detail in rows],
    }, indent=2)

check_palette.pair_separation

pair_separation(color_a: str, color_b: str) -> dict[str, float | str]

The numbers behind check's two separation rows, for one pair.

Parameters:

Name Type Description Default
color_a str

A hex string.

required
color_b str

A hex string.

required

Returns:

Type Description
dict[str, float | str]

{"cvd", "cvd_kind", "cvd_severity", "tritan", "normal"}. cvd is

dict[str, float | str]

the CAM02-UCS dE the CVD row gates against CVD_TARGET, at the

dict[str, float | str]

deficiency and severity named; normal is the dE the normal-vision

dict[str, float | str]

row gates against NORMAL_FLOOR; tritan is reported, not gated.

Source code in skill/scripts/check_palette.py
def pair_separation(color_a: str, color_b: str) -> dict[str, float | str]:
    """The numbers behind `check`'s two separation rows, for one pair.

    Args:
        color_a: A hex string.
        color_b: A hex string.

    Returns:
        `{"cvd", "cvd_kind", "cvd_severity", "tritan", "normal"}`. `cvd` is
        the CAM02-UCS dE the CVD row gates against `CVD_TARGET`, at the
        deficiency and severity named; `normal` is the dE the normal-vision
        row gates against `NORMAL_FLOOR`; `tritan` is reported, not gated.
    """
    cvd, kind, at, tritan, normal = _separation_numbers(
        hex_to_linear(color_a), hex_to_linear(color_b))
    return {"cvd": cvd, "cvd_kind": kind, "cvd_severity": at,
            "tritan": tritan, "normal": normal}

check_palette.cmap_kind

cmap_kind(samples: Sequence[str]) -> str

Classify hex samples as qualitative, sequential, diverging, cyclic or misc.

misc is the failure: the lightness reverses, or its span is flat, or its halves are monotone and its ends match neither cyclic nor diverging. A colormap in that state encodes nothing the reader can order.

Fewer than CMAP_QUALITATIVE_N = 40 samples is read as a set of category colours rather than a ramp, and gated on separation instead.

Parameters:

Name Type Description Default
samples Sequence[str]

Hex strings sampled along the colormap, in order.

required

Returns:

Type Description
str

One of "qualitative", "sequential", "diverging", "cyclic" or

str

"misc".

Source code in skill/scripts/check_palette.py
def cmap_kind(samples: Sequence[str]) -> str:
    """Classify hex samples as `qualitative`, `sequential`, `diverging`,
    `cyclic` or `misc`.

    `misc` is the failure: the lightness reverses, or its span is flat, or its
    halves are monotone and its ends match neither cyclic nor diverging. A
    colormap in that state encodes nothing the reader can order.

    Fewer than `CMAP_QUALITATIVE_N = 40` samples is read as a set of category
    colours rather than a ramp, and gated on separation instead.

    Args:
        samples: Hex strings sampled along the colormap, in order.

    Returns:
        One of `"qualitative"`, `"sequential"`, `"diverging"`, `"cyclic"` or
        `"misc"`.
    """
    if len(samples) < CMAP_QUALITATIVE_N:
        return "qualitative"

    ls = [linear_to_oklab(hex_to_linear(h))[0] for h in samples]

    if max(ls) - min(ls) < CMAP_SPAN_MIN:
        return "misc"

    if _back_travel(ls) < CMAP_BACKTRAVEL_MAX:
        return "sequential"

    half = len(ls) // 2
    if (_back_travel(ls[:half + 1]) < CMAP_BACKTRAVEL_MAX
            and _back_travel(ls[half:]) < CMAP_BACKTRAVEL_MAX):
        wrap = delta_e(hex_to_linear(samples[0]), hex_to_linear(samples[-1]))
        return "cyclic" if wrap < CMAP_WRAP_DE_MAX else "diverging"

    return "misc"

check_palette.cmap_kind_rgb

cmap_kind_rgb(samples: Sequence[tuple[float, float, float]]) -> str

cmap_kind on float sRGB. See cmap_back_travel_rgb for why.

Source code in skill/scripts/check_palette.py
def cmap_kind_rgb(samples: Sequence[tuple[float, float, float]]) -> str:
    """`cmap_kind` on float sRGB. See `cmap_back_travel_rgb` for why."""
    if len(samples) < CMAP_QUALITATIVE_N:
        return "qualitative"
    ls = [_lightness_rgb(s) for s in samples]
    if max(ls) - min(ls) < CMAP_SPAN_MIN:
        return "misc"
    if _back_travel(ls) < CMAP_BACKTRAVEL_MAX:
        return "sequential"
    half = len(ls) // 2
    if (_back_travel(ls[:half + 1]) < CMAP_BACKTRAVEL_MAX
            and _back_travel(ls[half:]) < CMAP_BACKTRAVEL_MAX):
        first = tuple(_srgb_to_linear(float(c)) for c in samples[0])
        last = tuple(_srgb_to_linear(float(c)) for c in samples[-1])
        wrap = delta_e(first, last)
        return "cyclic" if wrap < CMAP_WRAP_DE_MAX else "diverging"
    return "misc"

check_palette.cmap_back_travel

cmap_back_travel(samples: Sequence[str]) -> float

How much of a ramp's lightness runs backwards, as a fraction of its span.

0.0 is monotone. CMAP_BACKTRAVEL_MAX = 0.02 is where a ramp stops counting as ordered, because lightness that reverses makes two different values render at the same lightness.

Parameters:

Name Type Description Default
samples Sequence[str]

Hex strings sampled along the ramp, in ramp order.

required

Returns:

Type Description
float

Backward lightness travel as a fraction of the ramp's span. 0.0 is

float

monotone.

Source code in skill/scripts/check_palette.py
def cmap_back_travel(samples: Sequence[str]) -> float:
    """How much of a ramp's lightness runs backwards, as a fraction of its span.

    0.0 is monotone. `CMAP_BACKTRAVEL_MAX = 0.02` is where a ramp stops
    counting as ordered, because lightness that reverses makes two different
    values render at the same lightness.

    Args:
        samples: Hex strings sampled along the ramp, in ramp order.

    Returns:
        Backward lightness travel as a fraction of the ramp's span. 0.0 is
        monotone.
    """
    return _back_travel([linear_to_oklab(hex_to_linear(h))[0] for h in samples])

check_palette.cmap_back_travel_rgb

cmap_back_travel_rgb(samples: Sequence[tuple[float, float, float]]) -> float

cmap_back_travel on float sRGB, without the 8-bit round trip.

The hex API rounds every channel to 1/255 before lightness is computed. On a smooth ramp those roundings are oscillations of about 0.001 OKLab that accumulate into the measure: winter reads 0.0343 through hex against 0.0139 in float, which straddles the 0.02 floor and made a sequential map classify misc. Maps that genuinely reverse are unaffected, because their reversals are orders of magnitude larger than the rounding.

Parameters:

Name Type Description Default
samples Sequence[tuple[float, float, float]]

(r, g, b) floats in 0..1, in ramp order.

required

Returns:

Type Description
float

Backward lightness travel as a fraction of the ramp's span.

Source code in skill/scripts/check_palette.py
def cmap_back_travel_rgb(samples: Sequence[tuple[float, float, float]]) -> float:
    """`cmap_back_travel` on float sRGB, without the 8-bit round trip.

    The hex API rounds every channel to 1/255 before lightness is computed. On
    a smooth ramp those roundings are oscillations of about 0.001 OKLab that
    accumulate into the measure: `winter` reads 0.0343 through hex against
    0.0139 in float, which straddles the 0.02 floor and made a sequential map
    classify `misc`. Maps that genuinely reverse are unaffected, because their
    reversals are orders of magnitude larger than the rounding.

    Args:
        samples: `(r, g, b)` floats in 0..1, in ramp order.

    Returns:
        Backward lightness travel as a fraction of the ramp's span.
    """
    return _back_travel([_lightness_rgb(s) for s in samples])

check_palette.contrast

contrast(hex_a: str, hex_b: str) -> float

WCAG contrast ratio between two hex colours, from 1.0 to 21.0.

The floors it is compared against: 4.5 for text, 3.0 for a hue against the surface it sits on.

Parameters:

Name Type Description Default
hex_a str

A #rrggbb string.

required
hex_b str

The colour to measure it against.

required

Returns:

Type Description
float

The ratio, 1.0 (identical) to 21.0 (black on white).

Source code in skill/scripts/check_palette.py
def contrast(hex_a: str, hex_b: str) -> float:
    """WCAG contrast ratio between two hex colours, from 1.0 to 21.0.

    The floors it is compared against: 4.5 for text, 3.0 for a hue against the
    surface it sits on.

    Args:
        hex_a: A `#rrggbb` string.
        hex_b: The colour to measure it against.

    Returns:
        The ratio, 1.0 (identical) to 21.0 (black on white).
    """
    la, lb = relative_luminance(hex_to_linear(hex_a)), relative_luminance(hex_to_linear(hex_b))
    hi, lo = max(la, lb), min(la, lb)
    return (hi + 0.05) / (lo + 0.05)

check_palette.delta_e

delta_e(rgb_a: Sequence[float], rgb_b: Sequence[float]) -> float

CAM02-UCS colour difference between two linear-light colours.

Euclidean distance in CAM02-UCS, which is the space's intended use: Luo, Cui & Li (2006) fitted it so that this distance predicts perceived difference, so the number carries a unit somebody measured. CVD_TARGET and NORMAL_FLOOR are quoted in it.

Not a CIELAB dEab and not a CIEDE2000. Over the gamut this file gates as series slots, one CAM02-UCS unit is a median 1.99 CIELAB dEab, but the ratio runs 1.72-2.24 across the interquartile range, so the two are not interconvertible at a fixed rate and a threshold quoted in one does not transfer to the other.

Before 0.8.0 this returned OKLab distance x100. See the CIECAM02 section above for why that number could not support a threshold.

Parameters:

Name Type Description Default
rgb_a Sequence[float]

Linear-light (r, g, b).

required
rgb_b Sequence[float]

The colour to measure it against.

required

Returns:

Type Description
float

CAM02-UCS euclidean distance.

Source code in skill/scripts/check_palette.py
def delta_e(rgb_a: Sequence[float], rgb_b: Sequence[float]) -> float:
    """CAM02-UCS colour difference between two linear-light colours.

    Euclidean distance in CAM02-UCS, which is the space's intended use: Luo,
    Cui & Li (2006) fitted it so that this distance predicts perceived
    difference, so the number carries a unit somebody measured. `CVD_TARGET`
    and `NORMAL_FLOOR` are quoted in it.

    Not a CIELAB dE*ab and not a CIEDE2000. Over the gamut this file gates as
    series slots, one CAM02-UCS unit is a median 1.99 CIELAB dE*ab, but the
    ratio runs 1.72-2.24 across the interquartile range, so the two are not
    interconvertible at a fixed rate and a threshold quoted in one does not
    transfer to the other.

    Before 0.8.0 this returned OKLab distance x100. See the CIECAM02 section
    above for why that number could not support a threshold.

    Args:
        rgb_a: Linear-light `(r, g, b)`.
        rgb_b: The colour to measure it against.

    Returns:
        CAM02-UCS euclidean distance.
    """
    a, b = linear_to_cam02ucs(rgb_a), linear_to_cam02ucs(rgb_b)
    return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b)))

check_palette.simulate

simulate(rgb: Sequence[float], kind: str) -> tuple[float, float, float]

Linear-light RGB as a "protan", "deutan" or "tritan" viewer sees it.

Protan and deutan use Vienot, Brettel & Mollon (1999); tritan uses Brettel, Vienot & Mollon (1997). Both run on linear light. Protan and deutan are what the gates decide on; tritan distances are printed and never gated.

Parameters:

Name Type Description Default
rgb Sequence[float]

Linear-light (r, g, b), each channel in 0..1.

required
kind str

"protan", "deutan" or "tritan".

required

Returns:

Type Description
tuple[float, float, float]

Linear-light (r, g, b) as that viewer sees it.

Source code in skill/scripts/check_palette.py
def simulate(rgb: Sequence[float], kind: str) -> tuple[float, float, float]:
    """Linear-light RGB as a `"protan"`, `"deutan"` or `"tritan"` viewer sees it.

    Protan and deutan use Vienot, Brettel & Mollon (1999); tritan uses Brettel,
    Vienot & Mollon (1997). Both run on linear light. Protan and deutan are
    what the gates decide on; tritan distances are printed and never gated.

    Args:
        rgb: Linear-light `(r, g, b)`, each channel in 0..1.
        kind: `"protan"`, `"deutan"` or `"tritan"`.

    Returns:
        Linear-light `(r, g, b)` as that viewer sees it.
    """
    if kind == "tritan":
        return _brettel_tritan(rgb)
    m = CVD[kind]
    r, g, b = (max(0.0, min(1.0, sum(m[i][j] * rgb[j] for j in range(3))))
               for i in range(3))
    return r, g, b

check_palette.simulate_anomalous

simulate_anomalous(rgb: Sequence[float], kind: str, severity: float) -> tuple[float, float, float]

Linear-light RGB as an anomalous trichromat of this severity sees it.

kind is "protan" or "deutan". severity runs 0.0 (normal vision) to 1.0 (dichromacy) and is read at the nearest tenth, which is where Machado, Oliveira & Fernandes publish the table. No interpolation between two published matrices, because that is a modelling claim the paper does not make and this file would then be asserting.

simulate is the dichromacy model check reports as severity 1.0; this function at 1.0 is the second one, reported as "1.0, Machado". Below 1.0 is anomalous trichromacy.

Parameters:

Name Type Description Default
rgb Sequence[float]

Linear-light (r, g, b), each channel in 0..1.

required
kind str

"protan" or "deutan".

required
severity float

0.0 (normal vision) to 1.0 (dichromacy), read at the nearest tenth.

required

Returns:

Type Description
tuple[float, float, float]

Linear-light (r, g, b) as that viewer sees it.

Source code in skill/scripts/check_palette.py
def simulate_anomalous(rgb: Sequence[float], kind: str,
                       severity: float) -> tuple[float, float, float]:
    """Linear-light RGB as an anomalous trichromat of this severity sees it.

    `kind` is `"protan"` or `"deutan"`. `severity` runs 0.0 (normal vision) to
    1.0 (dichromacy) and is read at the nearest tenth, which is where Machado,
    Oliveira & Fernandes publish the table. No interpolation between two
    published matrices, because that is a modelling claim the paper does not
    make and this file would then be asserting.

    `simulate` is the dichromacy model `check` reports as severity 1.0; this
    function at 1.0 is the second one, reported as "1.0, Machado". Below 1.0
    is anomalous trichromacy.

    Args:
        rgb: Linear-light `(r, g, b)`, each channel in 0..1.
        kind: `"protan"` or `"deutan"`.
        severity: 0.0 (normal vision) to 1.0 (dichromacy), read at the
            nearest tenth.

    Returns:
        Linear-light `(r, g, b)` as that viewer sees it.
    """
    if kind not in MACHADO:
        raise ValueError(f"severity is modelled for protan and deutan only, "
                         f"not {kind!r} - see the note above MACHADO")
    if not 0.0 <= severity <= 1.0:
        raise ValueError(f"severity runs 0.0 to 1.0, got {severity!r}")
    # Half up. `round` is half-to-even and read 0.05, 0.25, 0.45, 0.65 and 0.85
    # a tenth low.
    tenths = math.floor(severity * 10 + 0.5)
    if tenths == 0:
        r, g, b = (max(0.0, min(1.0, c)) for c in rgb)
        return r, g, b
    m = MACHADO[kind][tenths]
    r, g, b = (max(0.0, min(1.0, sum(m[i][j] * rgb[j] for j in range(3))))
               for i in range(3))
    return r, g, b

check_palette.hex_to_linear

hex_to_linear(h: str) -> tuple[float, float, float]

A #rrggbb string as linear-light RGB, each channel in 0..1.

Linear light, not the 0..255 the hex digits carry: every distance and luminance below is defined on it, and averaging or mixing gamma-encoded values is the usual source of a wrong answer that looks plausible.

Parameters:

Name Type Description Default
h str

A #rrggbb string. The leading # is optional.

required

Returns:

Type Description
tuple[float, float, float]

(r, g, b), each channel linear-light in 0..1.

Source code in skill/scripts/check_palette.py
def hex_to_linear(h: str) -> tuple[float, float, float]:
    """A `#rrggbb` string as linear-light RGB, each channel in 0..1.

    Linear light, not the 0..255 the hex digits carry: every distance and
    luminance below is defined on it, and averaging or mixing gamma-encoded
    values is the usual source of a wrong answer that looks plausible.

    Args:
        h: A `#rrggbb` string. The leading `#` is optional.

    Returns:
        `(r, g, b)`, each channel linear-light in 0..1.
    """
    h = h.lstrip("#")
    if len(h) != 6:
        raise ValueError(f"expected 6-digit hex, got {h!r}")
    r, g, b = (_srgb_to_linear(int(h[i:i + 2], 16) / 255) for i in (0, 2, 4))
    return r, g, b

check_palette.oklab_distance

oklab_distance(rgb_a: Sequence[float], rgb_b: Sequence[float]) -> float

OKLab distance between two linear-light colours, x100.

What delta_e measured before 0.8.0, kept because the lightness rows still reason in OKLab and because a caller comparing against a number this project published earlier needs the old scale to do it.

It is not a colour difference in any calibrated sense: OKLab was fitted for hue uniformity, not for discrimination, so distances in it have no published referent. Gate on delta_e.

Parameters:

Name Type Description Default
rgb_a Sequence[float]

Linear-light (r, g, b).

required
rgb_b Sequence[float]

The colour to measure it against.

required

Returns:

Type Description
float

OKLab euclidean distance, x100.

Source code in skill/scripts/check_palette.py
def oklab_distance(rgb_a: Sequence[float], rgb_b: Sequence[float]) -> float:
    """OKLab distance between two linear-light colours, x100.

    What `delta_e` measured before 0.8.0, kept because the lightness rows still
    reason in OKLab and because a caller comparing against a number this project
    published earlier needs the old scale to do it.

    It is not a colour difference in any calibrated sense: OKLab was fitted for
    hue uniformity, not for discrimination, so distances in it have no published
    referent. Gate on `delta_e`.

    Args:
        rgb_a: Linear-light `(r, g, b)`.
        rgb_b: The colour to measure it against.

    Returns:
        OKLab euclidean distance, x100.
    """
    a, b = linear_to_oklab(rgb_a), linear_to_oklab(rgb_b)
    return 100 * math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b)))

check_palette.linear_to_oklab

linear_to_oklab(rgb: Sequence[float]) -> tuple[float, float, float]

Linear-light RGB as OKLab (L, a, b).

OKLab rather than CIELAB because its lightness tracks perceived lightness across hues, which is what every gate here asks about. l, m, s below are the cone responses the published matrix names, not a lint slip.

Parameters:

Name Type Description Default
rgb Sequence[float]

Linear-light (r, g, b), each channel in 0..1.

required

Returns:

Type Description
tuple[float, float, float]

(L, a, b) in OKLab. L is 0..1.

Source code in skill/scripts/check_palette.py
def linear_to_oklab(rgb: Sequence[float]) -> tuple[float, float, float]:
    """Linear-light RGB as OKLab `(L, a, b)`.

    OKLab rather than CIELAB because its lightness tracks perceived lightness
    across hues, which is what every gate here asks about. `l, m, s` below are
    the cone responses the published matrix names, not a lint slip.

    Args:
        rgb: Linear-light `(r, g, b)`, each channel in 0..1.

    Returns:
        `(L, a, b)` in OKLab. `L` is 0..1.
    """
    r, g, b = rgb
    l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b
    m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b
    s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b
    l_, m_, s_ = (math.copysign(abs(v) ** (1 / 3), v) for v in (l, m, s))
    return (
        0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_,
        1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_,
        0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_,
    )

check_palette.linear_to_cam02ucs

linear_to_cam02ucs(rgb: Sequence[float]) -> tuple[float, float, float]

Linear-light RGB as CAM02-UCS (J', a', b').

The space delta_e measures in. Euclidean distance here is a perceived colour difference in the units Luo, Cui & Li (2006) fitted, which is what lets the floors in this file cite a measurement instead of a preference.

Parameters:

Name Type Description Default
rgb Sequence[float]

Linear-light (r, g, b), each channel in 0..1.

required

Returns:

Type Description
tuple[float, float, float]

(J', a', b') in CAM02-UCS. J' runs 0..100 for in-gamut colours.

Source code in skill/scripts/check_palette.py
def linear_to_cam02ucs(rgb: Sequence[float]) -> tuple[float, float, float]:
    """Linear-light RGB as CAM02-UCS `(J', a', b')`.

    The space `delta_e` measures in. Euclidean distance here is a perceived
    colour difference in the units Luo, Cui & Li (2006) fitted, which is what
    lets the floors in this file cite a measurement instead of a preference.

    Args:
        rgb: Linear-light `(r, g, b)`, each channel in 0..1.

    Returns:
        `(J', a', b')` in CAM02-UCS. `J'` runs 0..100 for in-gamut colours.
    """
    xyz = tuple(100.0 * v for v in _mul3(_M_XYZ, rgb))
    rgb_c = tuple(dr * v for dr, v in zip(_D_RGB, _mul3(_M_CAT02, xyz)))
    return _cam02ucs_from_post_adapted(
        _post_adapt(_mul3(_M_HPE, _mul3(_M_CAT02_INV, rgb_c)), _F_L))

check_palette.relative_luminance

relative_luminance(rgb: Sequence[float]) -> float

WCAG relative luminance of linear-light RGB.

The WCAG coefficients, and deliberately not OKLab's L: the contrast ratios this project cites are defined against this number, so computing them from a perceptual lightness would report figures no standard backs.

Parameters:

Name Type Description Default
rgb Sequence[float]

Linear-light (r, g, b), each channel in 0..1.

required

Returns:

Type Description
float

Relative luminance in 0..1, by the WCAG coefficients.

Source code in skill/scripts/check_palette.py
def relative_luminance(rgb: Sequence[float]) -> float:
    """WCAG relative luminance of linear-light RGB.

    The WCAG coefficients, and deliberately not OKLab's `L`: the contrast
    ratios this project cites are defined against this number, so computing
    them from a perceptual lightness would report figures no standard backs.

    Args:
        rgb: Linear-light `(r, g, b)`, each channel in 0..1.

    Returns:
        Relative luminance in 0..1, by the WCAG coefficients.
    """
    r, g, b = rgb
    return 0.2126 * r + 0.7152 * g + 0.0722 * b

suggest_fixes

Remedies. Both take the rows audit returned, not the figure.

suggest_fixes.suggest

suggest(rows: Sequence[tuple[str, bool | str, str]]) -> list[tuple[str, list[Remedy]]]

Remedies for the rows of an audit that are not passing.

Takes rows rather than the figure: what is on offer depends on which gates fired, and nothing here needs to look at the figure again. Returns [(gate_name, [Remedy, ...]), ...] in the order the gates reported, and skips gates with nothing to offer rather than padding them with a restatement of the failure.

A row whose detail opens with DID_NOT_RUN is skipped as well. The remedies here answer the question a gate asks when it runs, and three rows can report that they did not: no style sheet to compare against, and no check_palette to classify a colour with. "Apply the sheet inside the same rc_context" is the wrong answer to "there is no sheet", and each of those rows already carries the right one in its own [FIX] clause. A row opening with GATE_RAISED is skipped for the same reason: the gate crashed and measured nothing about the figure.

Parameters:

Name Type Description Default
rows Sequence[tuple[str, bool | str, str]]

(label, status, detail) triples, as audit or check returned them. Passing rows are ignored.

required

Returns:

Type Description
list[tuple[str, list[Remedy]]]

[(gate_name, [Remedy, ...]), ...], in the order the gates reported.

list[tuple[str, list[Remedy]]]

Empty when nothing fired that this file has an answer for.

Source code in skill/scripts/suggest_fixes.py
def suggest(rows: Sequence[tuple[str, bool | str, str]],
            ) -> list[tuple[str, list[Remedy]]]:
    """Remedies for the rows of an `audit` that are not passing.

    Takes `rows` rather than the figure: what is on offer depends on which
    gates fired, and nothing here needs to look at the figure again. Returns
    `[(gate_name, [Remedy, ...]), ...]` in the order the gates reported, and
    skips gates with nothing to offer rather than padding them with a
    restatement of the failure.

    A row whose detail opens with `DID_NOT_RUN` is skipped as well. The remedies
    here answer the question a gate asks when it runs, and three rows can report
    that they did not: no style sheet to compare against, and no `check_palette`
    to classify a colour with. "Apply the sheet inside the same rc_context" is
    the wrong answer to "there is no sheet", and each of those rows already
    carries the right one in its own `[FIX]` clause. A row opening with
    `GATE_RAISED` is skipped for the same reason: the gate crashed and measured
    nothing about the figure.

    Args:
        rows: `(label, status, detail)` triples, as `audit` or `check`
            returned them. Passing rows are ignored.

    Returns:
        `[(gate_name, [Remedy, ...]), ...]`, in the order the gates reported.
        Empty when nothing fired that this file has an answer for.
    """
    marked = [name for name, status, detail in rows
              if status is not True
              and not detail.startswith((DID_NOT_RUN, GATE_RAISED))]
    out = []
    for name in marked:
        found = [r for r in REMEDIES if r.gate == name]
        if found:
            out.append((name, found))
    return out

suggest_fixes.format_suggestions

format_suggestions(rows: Sequence[tuple[str, bool | str, str]], indent: str = '      ') -> list[str]

suggest, as lines ready to print under a report.

Parameters:

Name Type Description Default
rows Sequence[tuple[str, bool | str, str]]

(label, status, detail) triples, as audit returned them.

required
indent str

Leading whitespace for each line.

' '

Returns:

Type Description
list[str]

A list of lines. Empty when nothing fired that this file has an

list[str]

answer for.

Source code in skill/scripts/suggest_fixes.py
def format_suggestions(rows: Sequence[tuple[str, bool | str, str]],
                       indent: str = "      ") -> list[str]:
    """`suggest`, as lines ready to print under a report.

    Args:
        rows: `(label, status, detail)` triples, as `audit` returned them.
        indent: Leading whitespace for each line.

    Returns:
        A list of lines. Empty when nothing fired that this file has an
        answer for.
    """
    lines = []
    for name, remedies in suggest(rows):
        lines.append(f"{indent}{name}:")
        for remedy in remedies:
            lines.append(f"{indent}  - {remedy.suggestion}")
            for code_line in remedy.code.splitlines():
                lines.append(f"{indent}      {code_line}")
    return lines

The gate functions

One row each, in the order audit runs them, which is the order the gates tables them in and the order a report prints. Every one returns (status, detail), where status is True, False or "warn".

The signature says what the gate needs beyond the figure. A r parameter is a renderer, canvas an already-drawn canvas, and scale/placed_frac/venue the page arithmetic. audit supplies all of them.

check_figure.check_clipping

check_clipping(fig: Figure, r: Any) -> tuple[bool | str, str]

Text that runs off the canvas.

Reads the axis-aligned box and is correct to: an AABB is the bounding box of the oriented box's own corners, so its extremes are attained by real corners of the label and a min/max test against the canvas gives the same answer either way. Rotation costs this gate nothing. check_collisions cannot take the same shortcut, because two AABBs can overlap where the boxes inside them do not.

Source code in skill/scripts/check_figure.py
def check_clipping(fig: Figure, r: Any) -> tuple[bool | str, str]:
    """Text that runs off the canvas.

    Reads the axis-aligned box and is correct to: an AABB is the bounding box
    of the oriented box's own corners, so its extremes are attained by real
    corners of the label and a min/max test against the canvas gives the same
    answer either way. Rotation costs this gate nothing. `check_collisions`
    cannot take the same shortcut, because two AABBs can overlap where the
    boxes inside them do not.
    """
    w, h = fig.canvas.get_width_height()
    ghosts = _ghost_ticks(fig)
    bad = []
    for t, bb in _texts(fig, r):
        if id(t) in ghosts:
            continue
        if bb.x0 < -1 or bb.y0 < -1 or bb.x1 > w + 1 or bb.y1 > h + 1:
            bad.append(str(t.get_text())[:32])
    return (not bad,
            "no text past the canvas" if not bad
            else f"clipped: {bad}  [FIX] add constrained_layout or widen the figure")

check_figure.check_collisions

check_collisions(fig: Figure, r: Any) -> tuple[bool | str, str]

Text-on-text overlap. Tick labels on a shared axis are exempt: matplotlib lays those out itself and a 1px touch there is not a defect.

Compared as oriented boxes, because the axis-aligned one is 5x the ink at 45 degrees and the extra area is two empty triangles. Two parallel oblique labels with clear page between them collided on that box, which is the shape of false positive that teaches people to skim the row.

Source code in skill/scripts/check_figure.py
def check_collisions(fig: Figure, r: Any) -> tuple[bool | str, str]:
    """Text-on-text overlap. Tick labels on a shared axis are exempt: matplotlib
    lays those out itself and a 1px touch there is not a defect.

    Compared as oriented boxes, because the axis-aligned one is 5x the ink at
    45 degrees and the extra area is two empty triangles. Two parallel oblique
    labels with clear page between them collided on that box, which is the shape
    of false positive that teaches people to skim the row."""
    ticks = _tick_texts(fig)
    items = [(t, _corners(t, bb, r))
             for t, bb in _texts(fig, r) if id(t) not in ticks]
    hits = []
    for (ta, ba), (tb, bb) in itertools.combinations(items, 2):
        if _overlap(ba, bb):
            hits.append((str(ta.get_text())[:22], str(tb.get_text())[:22]))
    return (not hits,
            f"{len(items)} text objects, none overlapping" if not hits
            else f"overlapping: {hits[:4]}")

check_figure.check_text_readability

check_text_readability(fig: Figure, r: Any, canvas: Any = None, scale: float | None = None, placed_frac: float = 1.0, venue: str | None = None) -> tuple[bool | str, str]

Whether each string can be read where it sits.

check_label_attribution asks which curve a label belongs to. This asks the prior question — whether the label is legible at all — and the two come apart hard: a label printed on its own curve is attributed perfectly, and is read through the line crossing its letterforms.

Both clauses are measured off rendered pixels, because both depend on what happened to land behind the glyphs and no artist knows that about itself. The figure is drawn a second time with every string hidden; that render is the backdrop each label was placed onto.

Clutter. Inside a label's box the backdrop should be one surface. Pixels that no blend of {that surface, the grid, the axis rule} explains are data ink passing through the text — a curve, a marker, a spike between the strokes. Measuring the backdrop rather than the finished render is the whole trick: casing hides the evidence, because a white halo over an orange curve renders as clean white while punching a visible gap through the data. Both halves of that are defects and this sees them as one number.

Uniform data ink is not clutter. A label on a heatmap cell has the cell as its surface, so it is the contrast clause that governs there, which is the correct division: a flat fill is a background, a curve is not.

Contrast. The text against the backdrop it actually got, at the WCAG text threshold (4.5:1, or 3:1 for large text) rather than the 3:1 mark threshold, because a glyph stem is thinner than a mark. Casing counts: a black label with a white halo on a dark field is read against the halo.

Both clauses are measured over the pixels the label covers, not over the box that contains it. A 45-degree string reports an axis-aligned extent five times its own ink, and the extra area is two triangles nothing is drawn in; strokes laid in one of them read as ink on the label, and a dark field in one of them sets the contrast verdict for a string sitting on light ground. See _oriented_mask.

Tick labels are included. They sit outside the axes on most figures and cost nothing to check there, and on the figures where they do not — an inset, a twinned frame, a label moved inside — that is exactly where they get crossed.

Source code in skill/scripts/check_figure.py
def check_text_readability(fig: Figure, r: Any, canvas: Any = None,
                           scale: float | None = None,
                           placed_frac: float = 1.0,
                           venue: str | None = None) -> tuple[bool | str, str]:
    """Whether each string can be read where it sits.

    `check_label_attribution` asks which curve a label belongs to. This asks the
    prior question — whether the label is legible at all — and the two come
    apart hard: a label printed *on* its own curve is attributed perfectly, and
    is read through the line crossing its letterforms.

    Both clauses are measured off rendered pixels, because both depend on what
    happened to land behind the glyphs and no artist knows that about itself.
    The figure is drawn a second time with every string hidden; that render is
    the backdrop each label was placed onto.

    *Clutter.* Inside a label's box the backdrop should be one surface. Pixels
    that no blend of {that surface, the grid, the axis rule} explains are data
    ink passing through the text — a curve, a marker, a spike between the
    strokes. Measuring the backdrop rather than the finished render is the whole
    trick: casing hides the evidence, because a white halo over an orange curve
    renders as clean white while punching a visible gap through the data. Both
    halves of that are defects and this sees them as one number.

    Uniform data ink is not clutter. A label on a heatmap cell has the cell as
    its surface, so it is the contrast clause that governs there, which is the
    correct division: a flat fill is a background, a curve is not.

    *Contrast.* The text against the backdrop it actually got, at the WCAG text
    threshold (4.5:1, or 3:1 for large text) rather than the 3:1 mark threshold,
    because a glyph stem is thinner than a mark. Casing counts: a black label
    with a white halo on a dark field is read against the halo.

    Both clauses are measured over the pixels the label covers, not over the box
    that contains it. A 45-degree string reports an axis-aligned extent five
    times its own ink, and the extra area is two triangles nothing is drawn in;
    strokes laid in one of them read as ink on the label, and a dark field in one
    of them sets the contrast verdict for a string sitting on light ground. See
    `_oriented_mask`.

    Tick labels are included. They sit outside the axes on most figures and cost
    nothing to check there, and on the figures where they do not — an inset, a
    twinned frame, a label moved inside — that is exactly where they get
    crossed.
    """
    import numpy as np
    from matplotlib.colors import to_rgb, to_rgba

    items = _texts(fig, r)
    if not items:
        return True, "no text to read"
    if canvas is None:
        # Called on its own rather than through `audit`, so nobody has put the
        # figure on `MEASURE_DPI` yet and the pixel fractions below would be
        # read against whatever resolution the author set. Do it here and
        # re-enter, so the whole body runs at the one resolution and `r` is
        # remeasured against it.
        #
        # `_measuring` also pins the font list, as `audit` does. A figure
        # whose builder reported on it has a record, and reading this gate
        # under the caller's font list instead would put the two routes on two
        # different faces: measured on `gallery-density` under
        # matplotlib 3.8.4, ax0's ink fraction came back 0.07 through `audit`
        # and 0.08 here.
        with _measuring(fig):
            r, canvas = _renderer(fig)
            return check_text_readability(fig, r, canvas, scale, placed_frac,
                                          venue)

    # Hiding text changes what constrained_layout has to fit, so the second
    # render would come back with every artist in a slightly different place and
    # the backdrop would not line up with the boxes measured against the first.
    # Pin the layout for the duration; the engine is put back before returning.
    engine = fig.get_layout_engine()
    fig.set_layout_engine("none")
    visible = [t.get_visible() for t, _ in items]
    try:
        for t, _ in items:
            t.set_visible(False)
        canvas.draw()
        backdrop = np.asarray(
            canvas.buffer_rgba())[:, :, :3].astype(np.int16).copy()
    finally:
        for (t, _), v in zip(items, visible):
            t.set_visible(v)
        canvas.draw()
        if engine is not None:
            fig.set_layout_engine(engine)

    if scale is None:
        scale = page_scale(fig, placed_frac, venue)
    H, W = backdrop.shape[:2]
    furniture = _furniture(fig)
    # Ticks that exist on the axes but never reach the page — a hidden axes, a
    # location outside the view, or a schematic that draws no axes but still
    # carries the tick Text objects matplotlib made for it. `check_clipping`
    # and `check_type_size` skip the same set.
    ghosts = _ghost_ticks(fig)
    radial = _polar_radial_ticks(fig)
    cluttered, faint, checked, unjudged = [], [], 0, 0

    for t, bb in items:
        if id(t) in ghosts:
            continue
        if id(t) in radial:
            unjudged += 1
            continue
        xa, xb = max(int(bb.x0) - 1, 0), min(int(bb.x1) + 2, W)
        ya, yb = max(int(bb.y0) - 1, 0), min(int(bb.y1) + 2, H)
        # Agg's origin is top-left, the figure's is bottom-left
        block = backdrop[slice(H - yb, H - ya), slice(xa, xb)]
        # An oblique label covers a band across that block and nothing in the
        # two triangles either side of it. At 45 degrees those triangles are
        # four fifths of what was sliced, and strokes laid in one of them were
        # reported as ink on the label. Upright labels get no mask: `_corners`
        # hands back the axis-aligned box for them, so a mask would only shave
        # off the 1px ring the slice adds, and that is a number nobody measured.
        angle = float(t.get_rotation()) % 180.0
        mask = (None if angle in (0.0, 90.0)
                else _oriented_mask(_corners(t, bb, r), xa, yb,
                                    block.shape[:2]))
        # Below this the fractions are counting antialiasing, not measuring.
        covered = block.size // 3 if mask is None else int(mask.sum())
        if covered < TEXT_FOOTPRINT_MIN_PX:
            continue
        checked += 1

        rgba = to_rgba(t.get_color(), t.get_alpha())
        fg, alpha = np.array(rgba[:3]) * 255.0, float(rgba[3])
        halo_color, _ = _halo(t)
        # The foreground may be any colour spec, an array included, so the
        # test is for presence and not truthiness.
        cased = halo_color is not None
        name = str(t.get_text())[:22]

        frac = _foreign_ink(block, furniture, TEXT_BLEND_TOL, mask)
        if frac > TEXT_CLUTTER_MAX:
            cluttered.append(
                f"{name!r} sits on data ink over {frac:.0%} of its box"
                + (" — the casing hides it by erasing the data underneath"
                   if cased else " and wears no casing"))

        pt = t.get_fontsize() * scale
        bold = _is_bold(t)
        floor = (TEXT_CONTRAST_MIN_LARGE
                 if pt >= LARGE_TEXT_PT or (pt >= LARGE_TEXT_BOLD_PT and bold)
                 else TEXT_CONTRAST_MIN)
        if cased:
            # Casing replaces the backdrop under the strokes, so that is what
            # the reader reads against, laid over it at the opacity Agg draws
            # it with.
            ground = _over(np.array(to_rgb(halo_color)) * 255.0,
                           _halo_alpha(t, halo_color), block)
            _, ratio = _worst_backdrop(ground, fg, TEXT_BACKDROP_MIN_SHARE,
                                       mask, alpha)
        else:
            _, ratio = _worst_backdrop(block, fg, TEXT_BACKDROP_MIN_SHARE,
                                       mask, alpha)
        if ratio < floor:
            faint.append(f"{name!r} at {ratio:.1f}:1 on its backdrop "
                         f"(text needs {floor}:1)")

    skipped = (f"; {unjudged} polar radial labels not judged (matplotlib "
               "places them on the data and offers nowhere else to put them)"
               if unjudged else "")
    if not checked:
        return True, "no text large enough to measure" + skipped
    bad = cluttered + faint
    if not bad:
        return True, (f"{checked} strings read clean against their backdrop"
                      + skipped)
    return False, ("; ".join(bad[:3])
                   + "  [FIX] move the label to clear ground; casing rescues a "
                     "gridline, not a curve")

check_figure.check_contrast_stack

check_contrast_stack(fig: Figure) -> tuple[bool | str, str]

A figure where nothing is at full opacity has no focal point, and a long tail of alpha values reads as haze rather than hierarchy.

Neither half fires on the two forms where alpha is doing real work rather than decorating.

A graded run of one colour is one decision, not one per band. An alpha array on a single artist counts once, because "a continuous encoding is a single decision", and a fan chart is that same encoding spelled across separate artists. So non-opaque alphas on artists sharing a colour collapse to one level once there are ALPHA_RAMP_MIN_STEPS of them. Counted per band, ALPHA_LEVELS_MAX of 3, less the opaque median line the row itself demands, would allow a fan chart two bands. Artists of different colours never collapse, so five series at five alphas still reads as five decisions, which is the case this half is for.

A single alpha is not a stack. "Nothing is opaque, so the figure has no focal point" presupposes something to focus on among alternatives. A density scatter drawn wholly at alpha=0.3 asserts no hierarchy and has no ranking to top out, and raising the artist that carries the point to alpha 1 destroys the encoding it is aimed at. The opacity test applies only where there is more than one level, which is where an author has built a hierarchy and left it headless. Two levels with nothing opaque still fail.

Whether a pale figure is visible at all is check_ink's question, not this one, and it is measured off pixels rather than guessed from alpha. Measured: a 3000-point scatter at alpha=0.01 still lays 12% ink across the panel and is perfectly readable as a density field, while three lines at alpha=0.02 reach 1% and Ink coverage warns. Alpha alone cannot tell those apart and the render can.

A contrast floor is the wrong tool. Compositing each artist over its panel and requiring WCAG 2.1's 3:1 non-text ratio sounds principled and condemns the project's own palette: Okabe-Ito orange #E69F00 measures 2.25:1 on white at full opacity and can never clear the floor at any alpha, and the green needs 0.9. That floor is also one this project deliberately keeps advisory, in check_palette, where a sub-3:1 hue is legal and merely obligates a second channel. Borrowing it as a hard gate here would be the same category error as judging a mathtext script against the body type floor.

Source code in skill/scripts/check_figure.py
def check_contrast_stack(fig: Figure) -> tuple[bool | str, str]:
    """A figure where nothing is at full opacity has no focal point, and a long
    tail of alpha values reads as haze rather than hierarchy.

    Neither half fires on the two forms where alpha is doing real work rather
    than decorating.

    **A graded run of one colour is one decision, not one per band.** An alpha
    array on a single artist counts once, because "a continuous encoding is a
    single decision", and a fan chart is that same encoding spelled across
    separate artists. So non-opaque alphas on artists sharing a colour collapse
    to one level once there are `ALPHA_RAMP_MIN_STEPS` of them. Counted per
    band, `ALPHA_LEVELS_MAX` of 3, less the opaque median line the row itself
    demands, would allow a fan chart two bands.
    Artists of different colours never collapse, so five series at five alphas
    still reads as five decisions, which is the case this half is for.

    **A single alpha is not a stack.** "Nothing is opaque, so the figure has no
    focal point" presupposes something to focus on among alternatives. A
    density scatter drawn wholly at `alpha=0.3` asserts no hierarchy and has no
    ranking to top out, and raising the artist that carries the point to
    alpha 1 destroys the encoding it is aimed at. The opacity test
    applies only where there is more than one level, which is where an author
    has built a hierarchy and left it headless. Two levels with nothing opaque
    still fail.

    **Whether a pale figure is visible at all is `check_ink`'s question, not
    this one, and it is measured off pixels rather than guessed from alpha.**
    Measured: a 3000-point scatter at `alpha=0.01` still lays 12% ink across
    the panel and is perfectly readable as a density field, while three lines
    at `alpha=0.02` reach 1% and `Ink coverage` warns. Alpha alone cannot tell
    those apart and the render can.

    A contrast floor is the wrong tool. Compositing
    each artist over its panel and requiring WCAG 2.1's 3:1 non-text ratio
    sounds principled and condemns the project's own palette: Okabe-Ito orange
    `#E69F00` measures **2.25:1 on white at full opacity** and can never clear
    the floor at any alpha, and the green needs 0.9. That floor is also one
    this project deliberately keeps advisory, in `check_palette`, where a
    sub-3:1 hue is legal and merely obligates a second channel. Borrowing it as
    a hard gate here would be the same category error as judging a
    mathtext script against the body type floor.
    """
    import numpy as np

    alphas: list[float] = []
    members: dict[Any, list[int]] = {}    # indices into `alphas`, per family
    ranked = False
    from matplotlib.collections import Collection, PathCollection
    from matplotlib.patches import Patch
    for ax in _all_axes(fig):
        for a in list(ax.collections) + list(ax.lines) + _drawn_patches(ax):
            if not a.get_visible():
                continue
            before = len(alphas)
            al = a.get_alpha()
            # An unset alpha does not mean opaque; it means opacity was not
            # passed as a keyword, and it may still be baked into the colour.
            # Read the colours, and fall back to 1.0 only when they say
            # nothing, which is what an artist drawn in a plain named colour
            # does.
            if al is None:
                baked = _baked_alphas(a)
                if baked:
                    alphas.extend(round(v, 2) for v in baked)
                else:
                    alphas.append(1.0)
            elif np.ndim(al) == 0:
                alphas.append(round(float(al), 2))
            else:
                # matplotlib has taken a per-point alpha array since 3.4, so
                # `al` may be an array, and `float()` raises on one.
                #
                # A ramp across one artist is ONE level, not one per value: the
                # question this row asks is how many separate alpha decisions
                # the reader has to resolve, and a continuous encoding is a
                # single decision. Counting each value would make an ordinary
                # `pcolormesh` report sixteen levels of haze.
                #
                # Opacity is the exception and is read per value, because
                # "is anything solid" is a fact about pixels rather than about
                # how many choices were made.
                values = np.atleast_1d(al).ravel()
                if values.size:
                    solid_here = float(values.max())
                    alphas.append(round(solid_here if solid_here >= OPAQUE_ALPHA_MIN
                                        else float(values.min()), 2))
                    if float(values.min()) != solid_here:
                        ranked = True       # the ramp itself is the hierarchy
            # Only filled regions are grouped, overlapping or not. A run of
            # fills in one colour is one opacity encoding, whether it is a fan
            # chart or bars graded by alpha, and matplotlib spells the same
            # bars as one `PatchCollection` with an alpha per face, which counts
            # once; grouping is what gives every spelling one verdict
            # (`test_contrast_stack_reads_every_spelling_of_graded_fills_alike`).
            # A run of LINES in one colour is several series told apart by
            # opacity, which is the haze this row exists to catch, and
            # `test_contrast_stack_counts_alpha_levels_inside_an_inset` pins
            # exactly that at six lines of one colour. A scatter is marks, so
            # it is not grouped either. `fill_between` and `stackplot` are
            # filled collections; `fill`, `axvspan` and `bar` add filled
            # patches. A patch with `facecolor="none"` is an outline (`_fills`).
            filled = (isinstance(a, (Collection, Patch))
                      and not isinstance(a, PathCollection) and _fills(a))
            if filled:
                key = _artist_rgb(a)
                if key is not None:
                    members.setdefault(key, []).extend(
                        i for i in range(before, len(alphas))
                        if alphas[i] < OPAQUE_ALPHA_MIN)
    if not alphas:
        return True, "no data artists"

    solid = any(x >= OPAQUE_ALPHA_MIN for x in alphas)
    families = {key: {alphas[i] for i in run} for key, run in members.items()}
    # A graded run of one colour is one decision. Drop every member of such a
    # run and put back a single representative, so the run costs one slot
    # rather than one per band. Opacity is read off the raw values above,
    # because whether anything is solid is a fact about pixels. The run's own
    # entries are dropped, not its values: a line at a value some graded bar
    # also has is still a level of its own.
    graded = {i for key, run in families.items()
              if len(run) >= ALPHA_RAMP_MIN_STEPS for i in members[key]}
    if graded:
        ranked = True
    kept = {v for i, v in enumerate(alphas) if i not in graded}
    for run in families.values():
        if len(run) >= ALPHA_RAMP_MIN_STEPS:
            kept.add(max(run))
    levels = sorted(kept)

    # A flat alpha is not a stack: one level and no ramp anywhere means no
    # hierarchy is being asserted, so there is nothing to leave headless.
    # `ranked` is what keeps this narrow. A per-point alpha array also lands at
    # one level, and there the ramp IS the hierarchy, so nothing opaque really
    # is a defect. Whether a pale figure is visible at all is `check_ink`'s
    # question, and it reads pixels rather than alphas.
    if len(levels) == 1 and not solid and not ranked:
        return True, f"alpha levels {levels} (one flat level, so no stack to rank)"

    note = ""
    ok = len(levels) <= ALPHA_LEVELS_MAX and solid
    if not solid:
        note = ("  [FIX] raise the artist that carries the point to alpha 1"
                "  [WHY] nothing is opaque, so the figure has no focal point")
    elif len(levels) > ALPHA_LEVELS_MAX:
        note = f"  [FIX] {len(levels)} levels reads as haze; keep to {ALPHA_LEVELS_MAX}"
    return ok, f"alpha levels {levels}{note}"

check_figure.check_mark_ratio

check_mark_ratio(fig: Figure) -> tuple[bool | str, str]

One mark far larger than the rest stops reading as a mark and starts reading as an ornament stuck on top of the plot.

Reads scatter sizes and line markers, both converted to the area of the disc actually drawn. Bars and other patches are deliberately NOT counted: a bar thirty times another bar is the encoding working, not a defect.

The bar exemption is about the channel, not about whether size carries a value. A size-encoded scatter is not exempt. Cleveland and McGill ranked the elementary perceptual tasks and put position and length near the top and area near the bottom; references/choosing-a-form.md states it and cites them. A bar thirty times another bar is read as thirty because length is judged well. A mark thirty times another mark is not read as thirty by anybody, whether or not the author meant it as the encoding. A bubble chart is precisely the case where the reader is asked to decode a number off the weak channel, so it is the last figure that should be exempt.

What the size distribution does change is the advice. When the largest mark exceeds the next largest by MARK_ORNAMENT_GAP it is one ornament stuck on top of a plot, and capping the size range is the fix. When the sizes are graded the figure is encoding something, and clipping the array silently flattens the values it encodes: measured on a 60-mark bubble chart, capping the size range collapsed 52 of the 60 onto one size, drew every value from 5.8 to 39.9 identically, and turned the row green. There the fix is the form, not the numbers.

Both operands go through one conversion because the two APIs take different quantities and neither is an area. markersize is a diameter in points. scatter(s=...) is a squared diameter, not the area its own documentation calls it - see scatter_diameter_pt. Converting one side and not the other leaves a standing 4/pi = 1.27x error on any figure mixing scatter with plot(marker=...), which is enough against a 5.0 threshold to fail a legal figure at a true 3.9x and pass a bad one at 6.4x.

Source code in skill/scripts/check_figure.py
@_measured
def check_mark_ratio(fig: Figure) -> tuple[bool | str, str]:
    """One mark far larger than the rest stops reading as a mark and starts
    reading as an ornament stuck on top of the plot.

    Reads scatter sizes and line markers, both converted to the area of the
    disc actually drawn. Bars and other patches are deliberately NOT counted: a
    bar thirty times another bar is the encoding working, not a defect.

    **The bar exemption is about the channel, not about whether size carries a
    value.** A size-encoded scatter is not exempt. Cleveland and McGill ranked the elementary
    perceptual tasks and put position and length near the top and area near the
    bottom; `references/choosing-a-form.md` states it and cites them. A bar
    thirty times another bar is read as thirty because length is judged well. A
    mark thirty times another mark is not read as thirty by anybody, whether or
    not the author meant it as the encoding. A bubble chart is precisely the
    case where the reader is asked to decode a number off the weak channel, so
    it is the last figure that should be exempt.

    What the size distribution does change is the *advice*. When the largest
    mark exceeds the next largest by `MARK_ORNAMENT_GAP` it is one ornament
    stuck on top of a plot, and capping the size range is the fix. When the
    sizes are graded the figure is encoding something, and clipping the array
    silently flattens the values it encodes: measured on a 60-mark bubble
    chart, capping the size range collapsed 52 of the 60 onto one size, drew every value from 5.8 to 39.9 identically, and
    turned the row green. There the fix is the form, not the numbers.

    Both operands go through one conversion because the two APIs take different
    quantities and neither is an area. `markersize` is a diameter in points.
    `scatter(s=...)` is a *squared* diameter, not the area its own
    documentation calls it - see `scatter_diameter_pt`. Converting one side and
    not the other leaves a standing 4/pi = 1.27x error on any figure mixing
    `scatter` with `plot(marker=...)`, which is enough against a 5.0 threshold
    to fail a legal figure at a true 3.9x and pass a bad one at 6.4x.
    """
    worst = None
    for ax in _all_axes(fig):
        sizes: list[float] = []
        for c in ax.collections:
            if not c.get_visible():
                continue
            s: Any = getattr(c, "get_sizes", lambda: [])()
            unit = _marker_path_extent(c)
            sizes.extend(
                math.pi * (unit * scatter_diameter_pt(float(v)) / 2.0) ** 2
                for v in s if v > 0)
        for ln in ax.lines:
            if not ln.get_visible() or _no_marker(ln.get_marker()):
                continue
            if float(ln.get_markersize()) <= 0:
                continue
            # The drawn path, as `check_overplotting` reads it: `"."` draws
            # at half its markersize and `","` at one pixel. The long side is
            # the diameter, so a `"|"` counts as long as it is. Unstroked, to
            # match the `scatter` side above.
            d = float(max(marker_extent_pt(ln, fig.dpi, stroked=False)))
            if d > 0:
                sizes.append(math.pi * (d / 2.0) ** 2)
        if len(sizes) < 2:
            continue
        sizes.sort()
        ratio = sizes[-1] / sizes[0]
        if worst is None or ratio > worst[0]:
            worst = (ratio, sizes[0], sizes[-1], sizes[-1] / sizes[-2])
    if worst is None:
        return True, "fewer than two mark sizes"
    ratio, lo, hi, gap = worst
    if ratio <= MARK_RATIO_MAX:
        fix = ""
    elif gap > MARK_ORNAMENT_GAP:
        fix = f"  [FIX] cap at {MARK_RATIO_MAX}x"
    else:
        fix = ("  [FIX] the fix is the form, not the sizes - these are graded, "
               "so they are encoding something, and clipping the array flattens "
               "the values it encodes. Carry the quantity by position instead")
    return (ratio <= MARK_RATIO_MAX,
            f"largest/smallest mark area {ratio:.1f}x  "
            f"(drawn area {lo:.0f} to {hi:.0f} pt^2)" + fix)

check_figure.check_overplotting

check_overplotting(fig: Figure) -> tuple[bool | str, str]

Warn when scatter points overlap into an unreadable mass.

For each PathCollection with offsets (a scatter), the fraction of points whose nearest neighbour in display pixels sits closer than the two marks' radii summed - which is exactly when the two discs intersect on the page. Above the threshold the marks merge into a blob: thin the count or switch to hexbin. Fill and partial alpha are not read, so transparency and hollow markers leave the number where it was.

ax.plot(x, y, "o") draws the same cloud through a different API, and for seven releases this row could not see it: a marker-only Line2D has no offsets, so a figure spelled that way was answered "no scatter overplotting" without a tree ever being built. Lines whose marker is drawn with no connecting segment are now measured too, and the two spellings agree exactly: plot(x, y, "o", ms=4) and scatter(x, y, s=16) are the same 4pt disc and report the same number on the same points. A marked line ("o-") is left alone: its marks are stops on a path the eye is already following along, and the path carries the ordering that touching marks would otherwise lose.

The mark's size comes from marker_extent_pt, not from markersize, because the two are not the same number for every marker and the difference is not small. Taking markersize as the diameter put gallery-orbit - 168000 points at marker=",", which matplotlib draws one pixel wide whatever size is asked for - at a radius 17x its own, and reported 100% contact off it. The narrower of the two extents is the radius, so a bar marker is not read as a disc of its long axis: "|" at ms=5, mew=1 is a tick two pixels across, and nineteen censoring ticks spread along a survival curve are not nineteen five-point discs.

Every one of the three corpus figures this newly reaches was checked against the render before it was allowed to fire, by counting the connected components of each artist's own ink: gallery-forms draws 14 marks as 7 blobs and 12 as 8, gallery-survival 19 ticks as 12, and gallery-orbit is the case its own comment in examples/gallery.py predicted and accepted, where the density IS the finding. The row warns rather than fails for that reason.

Both sides count the edge stroked around the mark, because that stroke is ink and two marks whose strokes meet have met. marker_stroke_pt and collection_stroke_pt are the two halves, and each answers "is an edge drawn at all" before it answers "how wide", which is the whole difficulty: a Line2D under figure.mplstyle reports markeredgewidth 0.0, and a scatter spelled edgecolors="none" keeps reporting a patch.linewidth of 0.70 for a stroke it never lays down.

What the corpus holds, every mark-drawing artist on all 21 figures:

mark-cloud artists                10
  with a stroke actually drawn     2   both gallery-survival's "|" and "_"
  verdict changes                  0

Both of the two are bar markers, where the stroke was already the whole measured width, so nothing on the corpus moves. The change is a correctness one and its exposure is honestly near zero; the figure that would have moved is the one that proves the naive version wrong.

Two marks touch when their centres are closer than the sum of their two radii. One radius would test whether a mark's centre is swallowed. Each radius comes from scatter_diameter_pt, because s is not an area.

Nearest is the wrong neighbour to ask about once radii vary. Contact is d < r_i + r_j, and the j that minimises d need not be the j that maximises r_j, so a mark can clear its nearest neighbour and be swallowed whole by a larger one further off. Measured on a fixture of 60 marks - 40 small ones in pairs 8px apart, each pair under a 120px disc centred 20px away - every mark is in contact and 40 of them are not visible in the render at all, while the 1-NN test reported 33% and the gate returned "no scatter overplotting".

Where every mark is the same size, nearest is the right neighbour: r_i + r_j is then a constant, so some mark is within it exactly when the nearest one is, and the 1-NN query answers the question outright. That is the common case and it keeps the cheap path. Where radii differ the marks are grouped into radius octaves and each group is asked separately; see _contact_fraction for why the bound has to be the group's largest radius rather than the scatter's, and what enumerating candidate pairs at 2 * r_max cost on a figure with one oversized mark in it.

Source code in skill/scripts/check_figure.py
@_measured
def check_overplotting(fig: Figure) -> tuple[bool | str, str]:
    """Warn when scatter points overlap into an unreadable mass.

    For each PathCollection with offsets (a scatter), the fraction of points
    whose nearest neighbour in display pixels sits closer than the two marks'
    radii summed - which is exactly when the two discs intersect on the page.
    Above the threshold the marks merge into a blob: thin the count or switch
    to hexbin. Fill and partial alpha are not read, so transparency and hollow
    markers leave the number where it was.

    `ax.plot(x, y, "o")` draws the same cloud through a different API, and for
    seven releases this row could not see it: a marker-only `Line2D` has no
    offsets, so a figure spelled that way was answered "no scatter
    overplotting" without a tree ever being built. Lines whose marker is drawn
    with no connecting segment are now measured too, and the two spellings
    agree exactly: `plot(x, y, "o", ms=4)` and `scatter(x, y, s=16)` are the
    same 4pt disc and report the same number on the same points. A marked line
    (`"o-"`) is left alone: its marks are stops on a path the eye is already
    following along, and the path carries the ordering that touching marks
    would otherwise lose.

    The mark's size comes from `marker_extent_pt`, not from `markersize`,
    because the two are not the same number for every marker and the
    difference is not small. Taking `markersize` as the diameter put
    `gallery-orbit` - 168000 points at `marker=","`, which matplotlib draws
    one pixel wide whatever size is asked for - at a radius 17x its own, and
    reported 100% contact off it. The narrower of the two extents is the
    radius, so a bar marker is not read as a disc of its long axis: `"|"` at
    `ms=5, mew=1` is a tick two pixels across, and nineteen censoring ticks
    spread along a survival curve are not nineteen five-point discs.

    Every one of the three corpus figures this newly reaches was checked
    against the render before it was allowed to fire, by counting the
    connected components of each artist's own ink: `gallery-forms` draws 14
    marks as 7 blobs and 12 as 8, `gallery-survival` 19 ticks as 12, and
    `gallery-orbit` is the case its own comment in `examples/gallery.py`
    predicted and accepted, where the density IS the finding. The row warns
    rather than fails for that reason.

    Both sides count the edge stroked around the mark, because that stroke is
    ink and two marks whose strokes meet have met. `marker_stroke_pt` and
    `collection_stroke_pt` are the two halves, and each answers "is an edge
    drawn at all" before it answers "how wide", which is the whole difficulty:
    a `Line2D` under `figure.mplstyle` reports `markeredgewidth` 0.0, and a
    `scatter` spelled `edgecolors="none"` keeps reporting a `patch.linewidth`
    of 0.70 for a stroke it never lays down.

    What the corpus holds, every mark-drawing
    artist on all 21 figures:

    ```text
    mark-cloud artists                10
      with a stroke actually drawn     2   both gallery-survival's "|" and "_"
      verdict changes                  0
    ```

    Both of the two are bar markers, where the stroke was already the whole
    measured width, so nothing on the corpus moves. The change is a
    correctness one and its exposure is honestly near zero; the figure that
    would have moved is the one that proves the naive version wrong.

    Two marks touch when their centres are closer than the sum of their two
    radii. One radius would test whether a mark's *centre* is swallowed. Each
    radius comes from `scatter_diameter_pt`, because `s` is not an area.

    Nearest is the wrong neighbour to ask about once radii vary. Contact is
    `d < r_i + r_j`, and the `j` that minimises `d` need not be the `j` that
    maximises `r_j`, so a mark can clear its nearest neighbour and be swallowed
    whole by a larger one further off. Measured on a fixture of 60 marks - 40
    small ones in pairs 8px apart, each pair under a 120px disc centred 20px
    away - every mark is in contact and 40 of them are not visible in the render
    at all, while the 1-NN test reported 33% and the gate returned "no scatter
    overplotting".

    Where every mark is the same size, nearest *is* the right neighbour: `r_i +
    r_j` is then a constant, so some mark is within it exactly when the nearest
    one is, and the 1-NN query answers the question outright. That is the common
    case and it keeps the cheap path. Where radii differ the marks are grouped
    into radius octaves and each group is asked separately; see
    `_contact_fraction` for why the bound has to be the group's largest radius
    rather than the scatter's, and what enumerating candidate pairs at
    `2 * r_max` cost on a figure with one oversized mark in it.
    """
    import numpy as np
    try:
        from scipy.spatial import cKDTree
    except ImportError:                      # optional, see `_box_blur`
        cKDTree = None

    dpi = fig.dpi

    bad = []
    for i, ax in enumerate(_all_axes(fig)):
        for j, coll in enumerate(ax.collections):
            try:
                offsets = coll.get_offsets()
            except Exception:
                continue
            if offsets.size < 2:
                continue
            # The offsets live in whatever space the artist was placed in;
            # `transform=ax.transAxes` puts them in axes fractions.
            try:
                xy = coll.get_offset_transform().transform(offsets)
            except Exception:
                continue
            sizes: Any = getattr(coll, "get_sizes", lambda: [])()
            if len(sizes) == 0:
                continue
            sizes = np.asarray(sizes, dtype=float)
            n = len(xy)
            if n < 2:
                continue
            # A Collection cycles a short size list over its offsets, so the
            # sizes it was handed are not the sizes it drew unless the lengths
            # already match. `np.resize` tiles, which is that same cycle.
            if sizes.size != n:
                sizes = np.resize(sizes, n)
            # The narrower side, as for `plot` markers below.
            drawn = (_marker_path_extent(coll, short=True)
                     * scatter_diameter_pt(sizes) + collection_stroke_pt(coll))
            radius_px = drawn / 2.0 * dpi / 72.0

            frac = _contact_fraction(xy, radius_px, cKDTree)
            if frac > OVERPLOT_THRESHOLD:
                bad.append((i, f"col{j}", frac))

        for j, line in enumerate(ax.lines):
            if not line.get_visible():
                continue
            if _no_marker(line.get_marker()):
                continue
            # A line drawn through its marks is a path, not a cloud. Only the
            # marker-only spelling is the one `scatter` has an equivalent of.
            if str(line.get_linestyle()) not in ("", "None", "none", " "):
                continue
            # `get_xydata` is after unit conversion, so a date axis reads as
            # floats; `get_xdata` hands back the datetimes themselves.
            try:
                xy = line.get_transform().transform(
                    np.asarray(line.get_xydata(), dtype=float))
            except Exception:
                continue
            xy = xy[np.isfinite(xy).all(axis=1)]
            n = len(xy)
            if n < 2:
                continue
            width_pt, height_pt = marker_extent_pt(line, dpi)
            radius = min(width_pt, height_pt) / 2.0 * dpi / 72.0
            if radius <= 0.0:
                continue
            frac = _contact_fraction(xy, np.full(n, radius), cKDTree)
            if frac > OVERPLOT_THRESHOLD:
                bad.append((i, f"line{j}", frac))

    if not bad:
        return True, "no scatter overplotting"
    detail = "; ".join(f"ax{i}.{a} {f:.0%}" for i, a, f in bad)
    return "warn", (f"overplotting: {detail} — marks merge into blob"
                    "  [FIX] thin counts or switch to hexbin. This measures how "
                    "close the marks are, so transparency and hollow markers "
                    "do not move it")

check_figure.check_redundancy

check_redundancy(fig: Figure, r: Any) -> tuple[bool | str, str]

Panels on the same scale should share their axis furniture.

Same-row panels are compared on their y axis and same-column panels on their x axis. A repeated axis label, or a repeated run of tick labels on the same limits, scale and label, is duplicated ink.

Source code in skill/scripts/check_figure.py
def check_redundancy(fig: Figure, r: Any) -> tuple[bool | str, str]:
    """Panels on the same scale should share their axis furniture.

    Same-row panels are compared on their y axis and same-column panels on
    their x axis. A repeated axis label, or a repeated run of tick labels on
    the same limits, scale and label, is duplicated ink.
    """
    # Only same-row panels can share a y axis, and only same-column panels can
    # share an x axis. Two panels side by side each legitimately need their own
    # x label; repeating the y label between them is the duplication.
    rows: dict[Any, list[Any]] = {}
    cols: dict[Any, list[Any]] = {}
    for ax in fig.axes:
        ss = ax.get_subplotspec()
        if ss is None:
            continue
        # A panel at `axis("off")` shows no furniture to duplicate, though its
        # tick Text objects still exist and still carry their strings.
        if not ax.axison:
            continue
        r_, c_ = ss.rowspan.start, ss.colspan.start
        rows.setdefault(r_, []).append(ax)
        cols.setdefault(c_, []).append(ax)

    # Keyed on scale and on limits that could share an axis, as well as the
    # label: the remedy is `sharey`, and two panels at 0-1 and 0-1000 that name
    # the same quantity cannot share one without flattening a panel. Exact
    # limits are too strict a key, because autoscaled panels differ by a few
    # hundredths; `SHARE_SPAN_RATIO_MAX` says how far apart is too far.
    dupes = []
    for group, getter, axis in ((rows, "get_ylabel", "y"),
                                (cols, "get_xlabel", "x")):
        for _, axes in group.items():
            keyed: dict[tuple[str, str], list[Any]] = {}
            for a in axes:
                label = getattr(a, getter)().strip()
                if label:
                    scale = getattr(a, f"get_{axis}scale")()
                    keyed.setdefault((label, scale), []).append(a)
            for (label, _scale), same in keyed.items():
                n = _largest_sharable(same, axis)
                if n > 1:
                    dupes.append(f"{axis}label {label!r} x{n}")

    # Both directions, on the same terms. A column of panels repeating its x
    # tick row is the same duplicated ink as a row of panels repeating its y
    # tick column. The grouping mirrors the label check above, `rows` for y and
    # `cols` for x.
    #
    # Grouped by the scale as well as the tick strings, because `docs/gates.md`
    # promises this row fires on "panels on a shared scale". Two panels in
    # different units whose tick strings happen to coincide do not share one,
    # and telling them to use `sharey` would put unrelated data on one axis.
    #
    # The axis label is part of the key because limits and scale type alone
    # do not settle it: two panels can carry 0 to 2 kilometres and 0 to 2
    # seconds and agree on every number while sharing no scale at all. What
    # a reader reads as one scale is one quantity, and the label is where
    # the figure says which quantity that is. Panels that name the same
    # quantity, or name none, still group together, which is the
    # small-multiples case this row exists for.
    dup_ticks: dict[str, int] = {"y": 0, "x": 0}
    for group, axis, lim_of, scale_of, label_of, ticks_of in (
            (rows, "y", "get_ylim", "get_yscale", "get_ylabel",
             "get_yticklabels"),
            (cols, "x", "get_xlim", "get_xscale", "get_xlabel",
             "get_xticklabels")):
        for _, axes in group.items():
            seen = Counter(
                (getattr(a, lim_of)(), getattr(a, scale_of)(),
                 getattr(a, label_of)().strip(),
                 tuple(t.get_text() for t in getattr(a, ticks_of)()
                       if t.get_text() and t.get_visible()))
                for a in axes)
            dup_ticks[axis] += sum(
                n - 1 for (_lim, _scale, _label, v), n in seen.items()
                if v and n > 1)

    ok = not dupes and not any(dup_ticks.values())
    if ok:
        return True, "axis furniture not duplicated"
    # "column" for y and "row" for x: a repeated y axis is a column of numbers
    # standing beside a panel, and a repeated x axis is a row of them under it.
    bits = dupes + [f"repeated {axis} tick {shape} x{dup_ticks[axis]}"
                    for axis, shape in (("y", "column"), ("x", "row"))
                    if dup_ticks[axis]]
    return False, "; ".join(bits) + "  [FIX] use sharex/sharey"

check_figure.check_type_size

check_type_size(fig: Figure, r: Any, scale: float | None = None, placed_frac: float = 1.0, venue: str | None = None) -> tuple[bool | str, str]

Every rendered string clears the legibility floor once the figure is scaled into the document.

Reads get_fontsize() off the artists that actually rendered, so a size set through rcParams, computed, or set by a helper is measured like one written as fontsize=.

Mathtext is measured rather than read, against its own floor. A script is drawn at 0.7 of the level above it, so the property is not the size on the page, and the sizes a script legitimately reaches are below what body text may. Both halves matter: reading the property let a 3.77pt glyph pass, and judging a script against the body floor failed matplotlib's own log tick labels. See MATH_SCRIPT_FLOOR_PT.

Source code in skill/scripts/check_figure.py
def check_type_size(fig: Figure, r: Any, scale: float | None = None,
                    placed_frac: float = 1.0,
                    venue: str | None = None) -> tuple[bool | str, str]:
    """Every rendered string clears the legibility floor once the figure is
    scaled into the document.

    Reads `get_fontsize()` off the artists that actually rendered, so a size
    set through rcParams, computed, or set by a helper is measured like one
    written as `fontsize=`.

    Mathtext is measured rather than read, against its own floor. A script is
    drawn at 0.7 of the level above it, so the property is not the size on the
    page, and the sizes a script legitimately reaches are below what body text
    may. Both halves matter: reading the property let a 3.77pt glyph pass, and
    judging a script against the body floor failed matplotlib's own log tick
    labels. See `MATH_SCRIPT_FLOOR_PT`.
    """
    scale = page_scale(fig, placed_frac, venue) if scale is None else scale
    ghosts = _ghost_ticks(fig)
    texts = [t for t, _ in _texts(fig, r) if id(t) not in ghosts]
    scale = float(scale)
    # Compared unrounded, the case docs/design.md gives.
    sizes = [(float(t.get_fontsize()) * scale, str(t.get_text())[:22])
             for t in texts]
    if not sizes:
        return True, "no text"

    ceiling = type_ceiling_pt(venue)
    label_ceiling = type_ceiling_pt(venue, panel_label=True)
    floor = min(TYPE_FLOOR_PT, ceiling)

    scripts = []
    can_raise = True
    for t in texts:
        pt = _script_min_pt(t)
        if pt is not None and _below_floor(pt * scale, MATH_SCRIPT_FLOOR_PT):
            scripts.append((_round_down(pt * scale, 2), str(t.get_text())[:22]))
            # The base on the page that lifts this script to the floor. Under
            # Nature's 7pt maximum a first-level script tops out at 4.9pt.
            base = float(t.get_fontsize()) * MATH_SCRIPT_FLOOR_PT / pt
            can_raise = can_raise and not _above_ceiling(base, ceiling)

    small = sorted({(_round_down(pt, 2), s) for pt, s in sizes
                    if _below_floor(pt, floor)})
    large = sorted({(_round_up(pt, 2), s) for t, (pt, s) in zip(texts, sizes)
                    if _above_ceiling(pt, label_ceiling if _is_panel_label(t)
                                      else ceiling)},
                   reverse=True)
    mn = min(pt for pt, _ in sizes)
    if small or large or scripts:
        bits = []
        if small:
            bits.append(f"under {floor}pt on page at scale {scale:.2f}: "
                        f"{small[:4]}  [FIX] cut words, do not shrink type")
        if large:
            authored = _advise_at_most(ceiling, scale)
            fix = (f"set text at {authored}pt as authored, "
                   f"{ceiling}pt on the page")
            if label_ceiling > ceiling:
                fix += (f"; a panel label may be {label_ceiling}pt, bold and "
                        "one lowercase letter")
            bits.append(f"over the {ceiling}pt maximum on page at scale "
                        f"{scale:.2f}: {large[:4]}  [FIX] {fix}")
        if scripts:
            fix = ("cut a level of nesting, or raise the base size" if can_raise
                   else f"no base under the {ceiling}pt maximum lifts the "
                   "script to the floor: cut the script, e.g. "
                   "`set_major_formatter(LogFormatter())` for log ticks, or "
                   "set `text.usetex`, whose scripts stop at 5pt")
            bits.append(
                f"mathtext script under {MATH_SCRIPT_FLOOR_PT}pt on page at "
                f"scale {scale:.2f}: {sorted(set(scripts))[:4]}  [FIX] {fix}"
                "  [WHY] matplotlib shrinks 0.7 per script level with no "
                "floor. LaTeX stops at scriptscript and never sets math type "
                "under 5pt")
        return False, "; ".join(bits)

    # The advisory: lowercase x-height against the start of fluent reading.
    low = []
    for t in texts:
        frac = _x_height_fraction_of(t)
        if frac is None:
            continue
        x_pt = float(t.get_fontsize()) * scale * frac
        if _below_floor(x_pt, XHEIGHT_FLOOR_PT):
            cap = label_ceiling if _is_panel_label(t) else ceiling
            low.append((_round_down(x_pt, 2), str(t.get_text())[:22],
                        XHEIGHT_FLOOR_PT / frac, cap))

    detail = f"smallest {mn:.1f}pt on page (floor {floor})"
    if ceiling < math.inf:
        detail += f", largest {max(pt for pt, _ in sizes):.1f}pt (ceiling {ceiling})"
    warnings = []
    if low:
        low.sort()
        # One size per maximum: the largest need under it, not the need of
        # the smallest x-height, since fonts differ in their fractions. Body
        # text and panel labels are advised apart, so a label's need is not
        # pushed onto body text over the body maximum.
        parts = []
        fits = True
        for cap in sorted({c for _, _, _, c in low}):
            need = max(n for _, _, n, c in low if c == cap)
            label = cap > ceiling
            # Rounded once, from the exact need. In 0.01pt where 0.1pt
            # overshoots a maximum the exact size fits under.
            authored = _advise_at_least(need, scale)
            if _above_ceiling(authored * scale, cap):
                authored = _advise_at_least(need, scale, 2)
            if _above_ceiling(authored * scale, cap):
                fits = False
                parts.append(f"the {cap}pt {'panel-label ' * label}maximum "
                             "allows no larger: use a face with a taller "
                             "x-height")
            else:
                parts.append(f"set {'a panel label' if label else 'it'} at "
                             f"{authored}pt as authored, "
                             f"{_round_down(authored * scale, 2)}pt on the page")
        fix = "; ".join(parts)
        if fits:
            fix += ", or use a face with a taller x-height"
        shown = [(s, x) for x, s, _, _ in low][:4]
        warnings.append(
            f"x-height under {XHEIGHT_FLOOR_PT}pt on page: {shown}  [FIX] {fix}"
            "  [WHY] Legge & Bigelow (2011): fluent reading starts at an "
            "x-height of 0.2 degrees, 4pt at 40cm")
    if placed_frac < PLACED_FRAC_WARN:
        warnings.append(f"placed at {placed_frac:.0%} of content width"
                        " — labels may be too small to read; author at the"
                        " width it ships at")
    if warnings:
        return "warn", "; ".join([detail] + warnings)
    return True, detail

check_figure.check_line_weight

check_line_weight(fig: Figure, scale: float | None = None, placed_frac: float = 1.0, venue: str | None = None) -> tuple[bool | str, str]

Every drawn stroke against the printer's floor, measured ON THE PAGE.

SIAM's instructions for authors ask for lines one point or thicker, because thinner lines break up or disappear. A stroke shrinks with the figure as type does -- 0.8pt authored in a 9-inch figure placed at 5.5 inches prints at 0.49pt -- so every width is multiplied by the page scale before it is judged.

Data strokes are held to LINE_FLOOR_PT: lines, line collections, unfilled contour sets, stroked patch edges and annotation arrows. Furniture is held to the lower FURNITURE_FLOOR_PT: spines, the major and minor gridlines and the major and minor tick marks. So are marker outlines that carry the mark (see _marker_outline_pt): an outline is not a line, and Science's 0.5pt minimum covers every line width. A gridline that drops out costs the reader a reference; a data curve that drops out costs them the finding.

Not measured: colorbar axes, whose dividers are matplotlib's and not the author's; filled contour sets, whose linewidth is the seam between two fills; and any artist that is invisible or draws no stroke.

Parameters:

Name Type Description Default
fig Figure

The figure to read strokes from.

required
scale float | None

Placed size over authored size, overriding page_scale.

None
placed_frac float

Fraction of the content width the figure is placed at.

1.0
venue str | None

A key of VENUE_WIDTH_PT, overriding CONTENT_WIDTH_PT.

None

Returns:

Type Description
bool | str

(False, detail) naming up to four strokes under a floor, data

str

first, then marker outlines, then furniture. Otherwise (True, detail) with the thinnest width of each

tuple[bool | str, str]

kind measured.

Source code in skill/scripts/check_figure.py
@_measured
def check_line_weight(fig: Figure, scale: float | None = None,
                      placed_frac: float = 1.0,
                      venue: str | None = None) -> tuple[bool | str, str]:
    """Every drawn stroke against the printer's floor, measured ON THE PAGE.

    SIAM's instructions for authors ask for lines one point or thicker, because
    thinner lines break up or disappear. A stroke shrinks with the figure as
    type does -- 0.8pt authored in a 9-inch figure placed at 5.5 inches prints
    at 0.49pt -- so every width is multiplied by the page scale before it is
    judged.

    Data strokes are held to `LINE_FLOOR_PT`: lines, line collections, unfilled
    contour sets, stroked patch edges and annotation arrows. Furniture is held
    to the lower `FURNITURE_FLOOR_PT`: spines, the major and minor gridlines
    and the major and minor tick marks. So are marker outlines that carry the
    mark (see `_marker_outline_pt`): an outline is not a line, and Science's
    0.5pt minimum covers every line width. A gridline that drops out costs the
    reader a reference; a data curve that drops out costs them the finding.

    Not measured: colorbar axes, whose dividers are matplotlib's and not the
    author's; filled contour sets, whose linewidth is the seam between two
    fills; and any artist that is invisible or draws no stroke.

    Args:
        fig: The figure to read strokes from.
        scale: Placed size over authored size, overriding `page_scale`.
        placed_frac: Fraction of the content width the figure is placed at.
        venue: A key of `VENUE_WIDTH_PT`, overriding `CONTENT_WIDTH_PT`.

    Returns:
        `(False, detail)` naming up to four strokes under a floor, data
        first, then marker outlines, then furniture. Otherwise `(True, detail)` with the thinnest width of each
        kind measured.
    """
    from matplotlib.lines import Line2D
    from matplotlib.collections import LineCollection, PathCollection

    if scale is None:
        scale = page_scale(fig, placed_frac, venue)

    thin: list[str] = []          # data strokes under LINE_FLOOR_PT
    thin_furniture: list[str] = []   # furniture under FURNITURE_FLOOR_PT
    thin_outline: list[str] = []     # marker outlines under FURNITURE_FLOOR_PT
    widths: list[float] = []
    furniture_widths: list[float] = []

    def measure(width: Any, name: str) -> None:
        """Put one authored data width on the page and judge it there."""
        on_page = float(width) * scale
        if on_page <= 0:
            return
        widths.append(on_page)
        if _below_floor(on_page, LINE_FLOOR_PT):
            thin.append(f"{name} at {_round_down(on_page, 2):.2f}pt")

    def measure_furniture(width: Any, name: str) -> None:
        """The same, against the lower floor furniture is held to."""
        on_page = float(width) * scale
        if on_page <= 0:
            return
        furniture_widths.append(on_page)
        if _below_floor(on_page, FURNITURE_FLOOR_PT):
            thin_furniture.append(f"{name} at {_round_down(on_page, 2):.2f}pt")

    def measure_outline(width: float, name: str) -> None:
        """A marker outline, against the furniture floor."""
        on_page = width * scale
        if on_page <= 0:
            return
        furniture_widths.append(on_page)
        if _below_floor(on_page, FURNITURE_FLOOR_PT):
            thin_outline.append(f"the marker outlines of {name} at "
                                f"{_round_down(on_page, 2):.2f}pt")

    def stroked(artist: Any) -> bool:
        """Whether this patch actually puts an edge on the page.

        Three ways it does not, and all three are ordinary: `edgecolor="none"`
        or a fully transparent one, a zero linewidth, and `linestyle="none"`.
        A bar drawn with no edge is the default `ax.bar` gives, so reading its
        `patch.linewidth` of 1.0 as a stroke would count ink nobody drew.
        """
        from matplotlib.colors import to_rgba
        try:
            if to_rgba(artist.get_edgecolor())[3] <= 0:
                return False
        except (ValueError, TypeError):
            return False
        if str(artist.get_linestyle()).strip().lower() in ("none", "", " "):
            return False
        return float(artist.get_linewidth() or 0.0) > 0.0

    forward = _ForwardGround()

    def ground(ax: Axes, artist: Any) -> tuple[float, float, float]:
        """`_ground` round an artist's marks (`_marks_rim`): what Agg draws
        before them, an image under a scatter and a line under its own
        markers included."""
        return _ground(ax, _marks_rim(artist, ax), forward.image(ax, artist))

    for ax in _all_axes(fig):
        # A colorbar's dividers ship at 0.4pt and are matplotlib's, not
        # anybody's design decision — the same reason `check_ink` skips this
        # axes entirely.
        if ax.get_label() == "<colorbar>":
            continue
        gridlines = {id(g) for axis in (ax.xaxis, ax.yaxis)
                     for g in axis.get_gridlines()}
        for artist in list(ax.lines) + list(ax.collections):
            if not artist.get_visible() or id(artist) in gridlines:
                continue
            label = str(artist.get_label() or "")
            named = label if label and not label.startswith("_") else None
            if isinstance(artist, (Line2D, PathCollection)):
                measure_outline(_marker_outline_pt(
                    artist, functools.partial(ground, ax, artist)),
                                named or "a series")
            name = named or "a stroke"
            if isinstance(artist, Line2D):
                stroke = str(artist.get_linestyle()).strip().lower()
                if stroke in ("none", "", " "):
                    continue
                raw = [artist.get_linewidth()]
            elif isinstance(artist, LineCollection):
                raw = _collection_widths(artist)
            elif getattr(artist, "filled", None) is False:
                # An unfilled ContourSet is strokes. A *filled* one is bands
                # whose linewidth is the seam between two fills, which no
                # reader is being asked to see.
                raw = _collection_widths(artist)
            else:
                continue
            for w in raw:
                measure(w, name)

        # Patch edges and the arrow on an annotation. A schematic is drawn
        # entirely out of these, and none of it reached the loop above.
        for patch in _drawn_patches(ax):
            if patch.get_visible() and stroked(patch):
                measure(patch.get_linewidth(),
                        f"a {type(patch).__name__} edge")
        for text in ax.texts:
            arrow = getattr(text, "arrow_patch", None)
            if arrow is not None and arrow.get_visible() and stroked(arrow):
                measure(arrow.get_linewidth(), "an annotation arrow")

        # Furniture: the axis rule, the ticks and the grid, against the lower
        # floor. `set_axis_off` stops `Axes.draw` drawing any of it, and a
        # hidden axis draws neither its ticks nor its grid.
        if not ax.axison:
            continue
        for side, spine in ax.spines.items():
            if spine.get_visible():
                measure_furniture(spine.get_linewidth(), f"the {side} spine")
        for axis_name, axis in (("x", ax.xaxis), ("y", ax.yaxis)):
            if not axis.get_visible():
                continue
            # Both grids. `get_gridlines` is the major one only, and a minor
            # grid is authored the same way and drops out the same way, so
            # reading only the majors would leave the second half of the grid
            # at a floor of zero.
            for which, grid in (
                    ("", axis.get_gridlines()),
                    (" minor", [t.gridline for t in axis.get_minor_ticks()])):
                for gridline in grid:
                    if not gridline.get_visible():
                        continue
                    if str(gridline.get_linestyle()).strip().lower() in (
                            "none", "", " "):
                        continue
                    measure_furniture(gridline.get_linewidth(),
                                      f"an {axis_name}{which} gridline")
            # A tick mark is a marker: its width is the stroke
            # `marker_stroke_pt` reads, zero for `color="none"`. Only the
            # ticks at a located position are drawn; the rest of
            # `get_major_ticks()` is matplotlib's spare template.
            for which, locs, get in (
                    ("major", axis.get_majorticklocs(), axis.get_major_ticks),
                    ("minor", axis.get_minorticklocs(), axis.get_minor_ticks)):
                for tick in get(len(locs)):
                    for mark in (tick.tick1line, tick.tick2line):
                        if mark.get_visible() and mark.get_markersize() > 0:
                            measure_furniture(
                                marker_stroke_pt(mark),
                                f"the {axis_name} {which} tick marks")

    if not widths and not furniture_widths:
        return True, "no strokes to measure"

    if thin:
        seen = list(dict.fromkeys(thin))
        return False, (f"under {LINE_FLOOR_PT}pt on page at scale {scale:.2f}: "
                       f"{seen[:4]}  [FIX] set linewidth to at least "
                       f"{_advise_at_least(LINE_FLOOR_PT, scale, 2):.2f} at "
                       "this scale"
                       "  [WHY] SIAM: lines thinner than one point break up or "
                       "disappear in print")
    if thin_outline:
        seen = list(dict.fromkeys(thin_outline))
        return False, (f"under {FURNITURE_FLOOR_PT}pt on page at scale "
                       f"{scale:.2f}: {seen[:4]}  [FIX] set markeredgewidth "
                       "to at least "
                       f"{_advise_at_least(FURNITURE_FLOOR_PT, scale, 2):.2f} "
                       "at this scale  [WHY] Science: line widths have a "
                       "minimum of 0.5 point at the final reduced size")
    if thin_furniture:
        seen = list(dict.fromkeys(thin_furniture))
        how = ("linewidth, or `tick_params(which=\"both\", width=...)` for "
               "ticks," if any("tick marks" in s for s in seen[:4])
               else "linewidth")
        return False, (f"furniture under {FURNITURE_FLOOR_PT}pt on page at "
                       f"scale {scale:.2f}: {seen[:4]}  [FIX] set {how} to "
                       "at least "
                       f"{_advise_at_least(FURNITURE_FLOOR_PT, scale, 2):.2f} "
                       "at this scale  [WHY] Science: line widths have a "
                       "minimum of 0.5 point at the final reduced size")

    data = (f"{len(widths)} strokes, thinnest {min(widths):.2f}pt on page "
            f"(floor {LINE_FLOOR_PT})" if widths else
            "no data strokes to measure")
    if not furniture_widths:
        return True, data
    return True, (f"{data}; {len(furniture_widths)} furniture, thinnest "
                  f"{min(furniture_widths):.2f}pt (floor {FURNITURE_FLOOR_PT})")

check_figure.check_banking

check_banking(fig: Figure) -> tuple[bool | str, str]

Whether a panel's aspect ratio lets the reader compare rates of change.

Banking to 45 degrees is Cleveland's: slope discrimination is most accurate near 45 and falls away either side of it, so the aspect should put the strokes there. The aspect that does it is Talbot, Gerth & Hanrahan's, the one minimising the strokes' arc length at constant area; _banking_factor says why that and not the median slope. A cycle that is plain in one aspect ratio is invisible in another, and the wrong one is usually the one the default produced.

The failure is a resolution failure, and it is measurable. On a saw wave whose decay limbs alternate between two rates, one exactly twice the other: at 2.4 x 5.2 inches the two limbs land 1.6 degrees apart on the page and the alternation cannot be seen at all; at 6.4 x 1.9 they land 10.6 degrees apart and it is the first thing you see. Same data, same axes, same limits.

Advisory, and loose, because the right aspect is a judgement about what the reader's job is and this cannot know that. BANKING_SLOPE_MAX is a factor of ten either side of banked, which for one straight line is a stroke steeper than 84 degrees or flatter than 6. See _banking_segments for what is excluded and why; a scatter, a map at fixed aspect and a parametric curve are all cases where banking means nothing.

Source code in skill/scripts/check_figure.py
@_measured
def check_banking(fig: Figure) -> tuple[bool | str, str]:
    """Whether a panel's aspect ratio lets the reader compare rates of change.

    Banking to 45 degrees is Cleveland's: slope discrimination is most accurate
    near 45 and falls away either side of it, so the aspect should put the
    strokes there. The aspect that does it is Talbot, Gerth & Hanrahan's, the
    one minimising the strokes' arc length at constant area; `_banking_factor`
    says why that and not the median slope. A cycle that is plain in one aspect
    ratio is invisible in another, and the wrong one is usually the one the
    default produced.

    The failure is a resolution failure, and it is measurable. On a saw wave
    whose decay limbs alternate between two rates, one exactly twice the other:
    at 2.4 x 5.2 inches the two limbs land 1.6 degrees apart on the page and the
    alternation cannot be seen at all; at 6.4 x 1.9 they land 10.6 degrees
    apart and it is the first thing you see. Same data, same axes, same limits.

    Advisory, and loose, because the right aspect is a judgement about what the
    reader's job is and this cannot know that. `BANKING_SLOPE_MAX` is a factor
    of ten either side of banked, which for one straight line is a stroke
    steeper than 84 degrees or flatter than 6. See `_banking_segments` for what
    is excluded and why; a scatter, a map at fixed aspect and a parametric curve
    are all cases where banking means nothing.
    """
    floor = 1.0 / BANKING_SLOPE_MAX
    bad, seen = [], []
    for i, ax in enumerate(_all_axes(fig)):
        factor = _banking_factor(ax)
        if factor is None:
            continue
        # A factor over 1 multiplies the height-to-width ratio: the panel
        # should be taller. Under 1 it should be wider by the reciprocal.
        by = max(factor, 1.0 / factor)
        seen.append(by)
        if floor <= factor <= BANKING_SLOPE_MAX:
            continue
        bad.append(f"ax{i} banking wants the panel {by:.3g}x "
                   + ("taller" if factor > 1 else "wider"))
    if not seen:
        return True, "no line panel whose aspect encodes a rate"
    if not bad:
        lo, hi = f"{min(seen):.2g}", f"{max(seen):.2g}"
        return True, (f"{len(seen)} line panel"
                      f"{'s' if len(seen) != 1 else ''}, "
                      f"{lo if lo == hi else lo + '-' + hi}x from banked")
    return "warn", ("; ".join(bad)
                    + "  [FIX] set the panel aspect, or the figure size, to the "
                      "ratio named above"
                      "  [WHY] Cleveland banks to 45 degrees, where slope "
                      "discrimination is most accurate; at this aspect two "
                      "rates that differ by a factor of two can land under 2 "
                      "degrees apart")

check_figure.check_ink

check_ink(fig: Figure, context_axes: Sequence[Axes] | None = None, canvas: Any = None) -> tuple[bool | str, str]

Ink as a fraction of each plotting area, measured off the rendered pixels rather than estimated from artist properties.

Near zero means a panel that did not need to be a panel. Very high means a panel with no ground left in it. Reported per-axes, and advisory only: the right density genuinely depends on the form, so this flags panels worth a second look rather than declaring them wrong.

Pass context_axes — a list of Axes whose fill is a context surface (e.g. a contourf landscape) rather than data-ink. For those axes, the ink fraction measures only marks ON TOP of the surface by separating the pixel values into two clusters (k-means with k=2) and removing the larger cluster (the surface). A figure with a filled terrain plus a few sparse marks will PASS rather than WARN.

Pass canvas — an already-drawn Agg canvas — to avoid a second render.

Source code in skill/scripts/check_figure.py
def check_ink(fig: Figure, context_axes: Sequence[Axes] | None = None,
              canvas: Any = None) -> tuple[bool | str, str]:
    """Ink as a fraction of each plotting area, measured off the rendered
    pixels rather than estimated from artist properties.

    Near zero means a panel that did not need to be a panel. Very high means a
    panel with no ground left in it. Reported per-axes, and advisory only: the
    right density genuinely depends on the form, so this flags panels worth a
    second look rather than declaring them wrong.

    Pass `context_axes` — a list of Axes whose fill is a context surface (e.g. a
    contourf landscape) rather than data-ink. For those axes, the ink fraction
    measures only marks ON TOP of the surface by separating the pixel values
    into two clusters (k-means with k=2) and removing the larger cluster (the
    surface). A figure with a filled terrain plus a few sparse marks will PASS
    rather than WARN.

    Pass `canvas` — an already-drawn Agg canvas — to avoid a second render.
    """
    import numpy as np

    if canvas is None:
        # Same reason as `check_text_readability`: an ink fraction is a count
        # of pixels, and a count of pixels is only a measurement at a fixed
        # resolution and a fixed font list. See `MEASURE_DPI` and `METRIC_RC_KEYS`.
        with _measuring(fig):
            _, canvas = _renderer(fig)
            return check_ink(fig, context_axes, canvas)
    buf = np.asarray(canvas.buffer_rgba())[:, :, :3].astype(int)
    h = buf.shape[0]

    ground = _ground_image(fig, buf.shape[:2]).astype(int)

    if context_axes is None:
        context_axes = []
    context_ids = frozenset(id(ax) for ax in context_axes)

    rows = []
    for i, ax in enumerate(_all_axes(fig)):
        # A colorbar is a solid ramp by construction: 100% ink, always, on
        # every figure that has one. Measuring it means every heatmap in the
        # world stands at WARN for the one axes in it whose density is not a
        # choice anybody made. matplotlib labels the axes it creates.
        if ax.get_label() == "<colorbar>":
            continue
        bb = ax.get_window_extent(renderer=canvas.get_renderer())
        x0, x1 = int(max(bb.x0, 0)), int(min(bb.x1, buf.shape[1]))
        y0, y1 = int(max(bb.y0, 0)), int(min(bb.y1, h))
        # Agg's origin is top-left, the figure's is bottom-left
        block = buf[h - y1:h - y0, x0:x1]
        sub = (np.abs(block - ground[h - y1:h - y0, x0:x1]).sum(axis=2)
               > INK_DELTA_MIN)
        if sub.size == 0:
            continue

        if id(ax) in context_ids:
            # Separate surface pixels from mark pixels via 2-means on color.
            flat = block.astype(float).reshape(-1, 3)
            m1 = flat.mean(axis=0)
            # Seeded apart from the mean: two equal centroids never split.
            m2 = m1 + 30.0
            for _ in range(12):
                d1 = np.abs(flat - m1).sum(axis=1)
                d2 = np.abs(flat - m2).sum(axis=1)
                c1 = d1 <= d2
                c2 = ~c1
                if c1.sum() == 0 or c2.sum() == 0:
                    break
                nm1 = flat[c1].mean(axis=0)
                nm2 = flat[c2].mean(axis=0)
                if (np.abs(nm1 - m1).sum() < 0.5
                        and np.abs(nm2 - m2).sum() < 0.5):
                    break
                m1, m2 = nm1, nm2
            surf = c1 if c1.sum() > c2.sum() else c2
            surf_mask = surf.reshape(sub.shape)
            frac = float((sub & ~surf_mask).mean())
        else:
            frac = float(sub.mean())
        # An empty panel is structural, not a low number. Furniture is a
        # perimeter and the panel is an area, so what a blank axes measures on
        # its own depends on how big it is: at `MEASURE_DPI`, the blank half of
        # a 3x1.5in pair reads 0.03, over the 0.02 floor, and the blank half of
        # a 6x3in pair reads 0.01, under it. The first read as merely sparse and
        # the second is caught by the floor for a reason that has nothing to do
        # with it being empty. Ask whether anything was drawn.
        rows.append((i, frac,
                     _axes_drew_anything(ax) and INK_MIN <= frac <= INK_MAX))

    if not rows:
        return True, "no measurable axes"
    detail = ", ".join(f"ax{i} {f:.2f}" for i, f, _ in rows)
    odd = [i for i, _, g in rows if not g]
    if not odd:
        return True, f"ink fraction: {detail} (typical {INK_MIN}-{INK_MAX})"
    return "warn", (f"ink fraction: {detail} (typical {INK_MIN}-{INK_MAX})"
                    f"  [FIX] look at ax{odd}: empty panels and saturated ones both"
                    " read badly, though a heatmap legitimately runs high")

check_figure.check_series_color

check_series_color(fig: Figure) -> tuple[bool | str, str]

The hues actually drawn, put through the palette gates.

The hole this closes: check_palette.py judges a list of hexes someone remembered to paste into a terminal, and this file never looked at color at all. A figure on matplotlib's default tab10 cycle - whose orange and green measure CAM02-UCS dE 1.6 under protanopia, against a floor of 10.5 - passed every composition check clean. Two scripts in one project that never spoke.

Only what is never legitimate is gated: separation under color blindness, and separation in normal vision. The lightness-band and chroma-floor rows are deliberately not applied to harvested colors. A black or gray series is legal - a reference curve, a control group - and failing it is precisely the noise that teaches people to skim past the row.

Scoped per panel. The comparison, the hue count and the all-pairs mode are all asked of one axes at a time, because the panel is the unit a reader separates hues within - a figure-wide bag gated hues that never share a frame against each other.

A single-hue ordinal ramp is judged categorically here on purpose, and the standing complaint about it does not survive measurement. The complaint is that this rejects every 4-step single-hue ramp, leaving ordered stacks unconditionally red. It does not. Measured on an ordered stacked bar chart, #0c0c0c #595959 #a5a5a5 #f2f2f2 passes both separation rows, and so does a 3-step blue. What fails is a scheme whose steps are too close: ColorBrewer Blues 4 fails because #eff3ff and #bdd7e7 are dE 9.5 apart under protanopia, and check_palette's ordinal rows fail the same end independently, for contrast against the surface. The row is asking for wider steps, which is what its own advice says, and that is achievable.

There is a real ceiling underneath, worth stating rather than leaving to be rediscovered: one hue has a finite lightness range and the adjacent floors want about 21 dE, so a single-hue ordinal encoding runs out of room at five steps even in grey.

The exemption was built and thrown away, which is the part to keep. Detecting "these hues are a ramp" and swapping in the ordinal rows sounds obvious, and at these lengths a colour-only detector is a coin flip: reaching past cmap_kind's CMAP_QUALITATIVE_N guard to the underlying monotone-lightness test calls random draws from an Okabe-Ito/tab10/Set2/Dark2 pool a ramp about 2/k! of the time, which is just the chance that k arbitrary colours come out sorted - 35% at three steps and 10% at four. Each false positive silently disables the CVD separation gate, which is the only reason this row exists. That guard is a decision, not an oversight. check_series_color's four single_hue/ramp_detector tests pin both halves.

The escape hatch _data_colors_by_axes documents - draw an ordinal ramp as c=values, cmap=... and it is read as the value it is - is genuinely unavailable to a stacked bar chart, which has no colormap route. That is the grain of truth in the complaint, and the answer to it is to step the ramp wider rather than to guess at intent from four hexes.

Source code in skill/scripts/check_figure.py
@_measured
def check_series_color(fig: Figure) -> tuple[bool | str, str]:
    """The hues actually drawn, put through the palette gates.

    The hole this closes: `check_palette.py` judges a list of hexes someone
    remembered to paste into a terminal, and this file never looked at color at
    all. A figure on matplotlib's default `tab10` cycle - whose orange and green
    measure CAM02-UCS dE 1.6 under protanopia, against a floor of 10.5 - passed
    every composition check
    clean. Two scripts in one project that never spoke.

    Only what is never legitimate is gated: separation under color blindness,
    and separation in normal vision. The lightness-band and chroma-floor rows
    are deliberately *not* applied to harvested colors. A black or gray series
    is legal - a reference curve, a control group - and failing it is precisely
    the noise that teaches people to skim past the row.

    Scoped per panel. The comparison, the hue count and the all-pairs mode are
    all asked of one axes at a time, because the panel is the unit a reader
    separates hues within - a figure-wide bag gated hues that never share a
    frame against each other.

    **A single-hue ordinal ramp is judged categorically here on purpose, and
    the standing complaint about it does not survive measurement.** The
    complaint is that this rejects every 4-step single-hue ramp, leaving
    ordered stacks unconditionally red. It does not. Measured on an ordered
    stacked bar chart, `#0c0c0c #595959 #a5a5a5 #f2f2f2` passes both separation
    rows, and so does a 3-step blue. What fails is a scheme whose steps are too
    close: ColorBrewer Blues 4 fails because `#eff3ff` and `#bdd7e7` are dE 9.5
    apart under protanopia, and `check_palette`'s *ordinal* rows fail the same
    end independently, for contrast against the surface. The row is asking for
    wider steps, which is what its own advice says, and that is achievable.

    There is a real ceiling underneath, worth stating rather than leaving to be
    rediscovered: one hue has a finite lightness range and the adjacent floors
    want about 21 dE, so a single-hue ordinal encoding runs out of room at five
    steps even in grey.

    The exemption was built and thrown away, which is the part to keep.
    Detecting "these hues are a ramp" and swapping in the ordinal rows sounds
    obvious, and at these lengths a colour-only detector is a coin flip:
    reaching past `cmap_kind`'s `CMAP_QUALITATIVE_N` guard to the underlying
    monotone-lightness test calls random draws from an
    Okabe-Ito/tab10/Set2/Dark2 pool a ramp about **2/k!** of the time, which is
    just the chance that k arbitrary colours come out sorted - 35% at three
    steps and 10% at four. Each false positive silently disables the CVD
    separation gate, which is the only reason this row exists. That guard is a
    decision, not an oversight. `check_series_color`'s four
    `single_hue`/`ramp_detector` tests pin both halves.

    The escape hatch `_data_colors_by_axes` documents - draw an ordinal ramp as
    `c=values, cmap=...` and it is read as the value it is - is genuinely
    unavailable to a stacked bar chart, which has no colormap route. That is
    the grain of truth in the complaint, and the answer to it is to step the
    ramp wider rather than to guess at intent from four hexes.
    """
    artists_by_ax = _data_artists_by_axes(fig)
    by_ax = {ax: _flatten(artists) for ax, artists in artists_by_ax.items()}
    if not by_ax:
        return True, "no categorical series colors"

    fails, notes = [], []
    cp: Any = _sibling("check_palette")
    if cp is None:
        notes.append("check_palette.py is not importable beside this file, "
                     "so separation went unchecked")
    else:
        # Vendored one file at a time, the sibling can be older than this file.
        missing = [n for n in ("pair_separation", "_cvd_detail",
                               "_normal_detail") if not hasattr(cp, n)]
        if missing:
            notes.append("check_palette.py beside this file has no "
                         + ", ".join(missing)
                         + ", so separation went unchecked")
            cp = None

    for ax, items in by_ax.items():
        distinct = list(dict.fromkeys(h for h, _, _ in items))

        if len(distinct) > MAX_SERIES_HUES:
            fails.append(f"{len(distinct)} distinct data hues in one panel, "
                         f"theme has {MAX_SERIES_HUES}  [FIX] fold the tail into "
                         "'Other' or facet")

        # One hue carrying two identities is what a seventh series looks like
        # once the cycler wraps: matplotlib reuses slot 1 without complaint and
        # the legend confidently lists both. Narrowed to labels on artists of the
        # *same kind*: a wrap reuses one artist type, whereas a band, its mean
        # line and its points in one hue is one series shown three ways, each
        # legitimately labelled. Keyed on kind, that reads as one identity.
        by_hue_kind: dict[Any, set[Any]] = {}
        for h, label, kind in items:
            if label:
                by_hue_kind.setdefault((h, kind), set()).add(label)
        for (h, kind), labels in sorted(by_hue_kind.items()):
            if len(labels) > 1:
                fails.append(f"{h} carries {len(labels)} identities "
                             f"{sorted(labels)} on {kind} artists"
                             "  [FIX] set an explicit color per series, or facet"
                             "  [WHY] the color cycle wrapped")

        if len(distinct) >= 2 and cp is not None:
            fails_ax, notes_ax = _separation(cp, ax, distinct,
                                             artists_by_ax[ax])
            fails += fails_ax
            notes += notes_ax

    max_per_panel = max(
        (len(list(dict.fromkeys(h for h, _, _ in items)))
         for items in by_ax.values()), default=0)
    head = f"up to {max_per_panel} data hues per panel"
    if fails:
        return False, f"{head}: " + "; ".join(fails)
    if cp is None:
        # The hue-count and identity-collision checks above ran; separation,
        # the reason this row exists, did not. A pass would say otherwise.
        return "warn", (DID_NOT_RUN + f"{head}: " + "; ".join(notes)
                        + "  [FIX] copy check_palette.py in beside it, or "
                        "install the package")
    return True, f"{head}: " + ("; ".join(notes) if notes else "nothing to compare")

check_figure.check_dual_axis

check_dual_axis(fig: Figure) -> tuple[bool | str, str]

Two data scales in one frame: axes at the same position, both drawing data. twinx and twiny both land here.

Both scales are set by the author, so the crossing point of the two curves is an artifact of the limits chosen rather than anything in the data. Move the limits and the story changes; a reader cannot tell that from the figure.

The escape hatch is the one legitimate case: a pure unit relabel - degrees C against degrees F, eV against nm - where the twin is furniture and carries no data of its own. So the discriminator is data on both, not a shared frame, which keeps the gate off secondary_yaxis and off correct work.

Source code in skill/scripts/check_figure.py
def check_dual_axis(fig: Figure) -> tuple[bool | str, str]:
    """Two data scales in one frame: axes at the same position, both drawing
    data. `twinx` and `twiny` both land here.

    Both scales are set by the author, so the crossing point of the two curves
    is an artifact of the limits chosen rather than anything in the data. Move
    the limits and the story changes; a reader cannot tell that from the figure.

    The escape hatch is the one legitimate case: a *pure unit relabel* - degrees
    C against degrees F, eV against nm - where the twin is furniture and carries
    no data of its own. So the discriminator is data on both, not a shared
    frame, which keeps the gate off `secondary_yaxis` and off correct work.
    """
    pairs = []
    axes = _all_axes(fig)
    for i, j in itertools.combinations(range(len(axes)), 2):
        a, b = axes[i], axes[j]
        if any(abs(x - y) > FRAME_TOL for x, y in
               zip(a.get_position().bounds, b.get_position().bounds)):
            continue
        if _has_data(a) and _has_data(b):
            pairs.append(f"ax{i}+ax{j}")
    if not pairs:
        return True, "one data scale per frame"
    # "two scales", not "two y scales": `twiny` lands here on exactly the same
    # argument, and naming the wrong axis sends the reader looking for a defect
    # on the one that is fine.
    return False, (f"two data scales sharing a frame: {', '.join(pairs)}  [FIX] "
                   "the crossing point is set by the limits, not the data. Two "
                   "panels, small multiples, or index both to a common base")

check_figure.check_form

check_form(fig: Figure) -> tuple[bool | str, str]

The mechanical subset of form choice - the three cases where the form is wrong no matter what the data is: a pie or donut (any Wedge), a 3D axes, and bars standing on a shared baseline along a linear axis that starts above zero. references/choosing-a-form.md carries the judgement calls this cannot make.

Returns False naming each case found, else True.

Source code in skill/scripts/check_figure.py
@_measured
def check_form(fig: Figure) -> tuple[bool | str, str]:
    """The mechanical subset of form choice - the three cases where the form is
    wrong no matter what the data is: a pie or donut (any `Wedge`), a 3D axes,
    and bars standing on a shared baseline along a linear axis that starts above
    zero. `references/choosing-a-form.md` carries the judgement calls this
    cannot make.

    Returns False naming each case found, else True.
    """
    from matplotlib.container import BarContainer
    from matplotlib.patches import Wedge

    bad = []
    for i, ax in enumerate(_all_axes(fig)):
        if any(isinstance(p, Wedge) for p in ax.patches):
            bad.append(f"ax{i} pie/donut: angle and area are the two tasks the "
                       "eye judges worst - a dot plot or a bar reads as position")
        if hasattr(ax, "get_zlim"):
            bad.append(f"ax{i} 3D: perspective makes the encoding unreadable and "
                       "occludes data - facet or use color for the third variable")
        orientation = next(
            (getattr(con, "orientation", "vertical")
             for con in getattr(ax, "containers", [])
             if isinstance(con, BarContainer)), None)
        # Bars drawn by hand leave no container behind, so the patches are read
        # directly when there is none. Same verdict either way, which is the
        # point: the two spellings draw the identical figure.
        if orientation is None:
            orientation = _baselined_bars(ax)
        # A container says these are bars; it does not say they stand on a
        # baseline. `ax.barh(left=...)` draws a Gantt chart and
        # `ax.bar(bottom=...)` draws a waterfall, and each bar there carries
        # its own offset, so there is no shared edge for a truncated axis to
        # cut. `_baselined_bars` excludes both on the hand-drawn route.
        elif not bars_rest_on_a_shared_edge(ax, orientation == "vertical"):
            orientation = None
        if orientation is None:
            continue

        vertical = orientation == "vertical"
        lim = ax.get_ylim() if vertical else ax.get_xlim()
        scale = ax.get_yscale() if vertical else ax.get_xscale()
        # A log axis cannot include zero, so a log bar chart is truncated by
        # construction and this gate has nothing to say about it.
        # Negative bars hang from zero too, so an axis that stops short of
        # zero from below cuts them the same way.
        if scale == "linear" and (min(lim) > 0 or max(lim) < 0):
            axis = "y" if vertical else "x"
            edge = min(lim) if min(lim) > 0 else max(lim)
            bad.append(
                f"ax{i} bars on a truncated {axis} axis (stops at "
                f"{edge:.4g}, short of zero): bar length encodes the value, so a "
                "cut baseline misstates every ratio  [FIX] the fix is the "
                "form, not the axis - use a dot plot")
    if not bad:
        return True, "no pie, no 3D, no truncated bar baseline"
    return False, "; ".join(bad)

check_figure.check_identity_channel

check_identity_channel(fig: Figure) -> tuple[bool | str, str]

Identity carried by color and nothing else.

A warning rather than a gate, and the reason is honesty about what the script can see: it can count the hues, but it cannot tell a direct label from any other piece of text in the axes. Failing on that guess would fire on correct work, and a gate people learn to skip is worse than no gate.

Source code in skill/scripts/check_figure.py
def check_identity_channel(fig: Figure) -> tuple[bool | str, str]:
    """Identity carried by color and nothing else.

    A warning rather than a gate, and the reason is honesty about what the
    script can see: it can count the hues, but it cannot tell a direct label
    from any other piece of text in the axes. Failing on that guess would fire
    on correct work, and a gate people learn to skip is worse than no gate.
    """
    labeled = {h for h, label in _data_colors(fig) if label}
    if len(labeled) < 2:
        return True, "fewer than two identified series"
    panels = _all_axes(fig)
    if (any(f.legends for f in _all_figures(fig))
            or any(ax.get_legend() is not None for ax in panels)):
        return True, f"{len(labeled)} series, legend present"
    if any(ax.texts for ax in panels):
        return True, f"{len(labeled)} series, in-axes text (assumed direct labels)"
    return "warn", (f"{len(labeled)} series told apart by hue alone - no legend "
                    "and no text in the axes"
                    "  [FIX] add direct labels rather than a legend: they remove "
                    "the match-the-swatch step, and orange and sky blue are "
                    "under 3:1 on white, where that step is hardest")

check_figure.check_label_attribution

check_label_attribution(fig: Figure, r: Any) -> tuple[bool | str, str]

A direct label sitting nearer some other series than the one it names.

check_collisions compares text against text, so a label that clears every other label and still floats in the corridor between two curves passes it clean. That is not hypothetical: examples/demo.py shipped with "Tuned" closer to a neighbouring curve than to its own and the whole suite was green. Text against text and text against data are different questions.

Harvested narrowly on purpose - only text whose string matches exactly one series label is judged, because only there is the intent known. A callout, a panel letter, an "n = 300" attributes nothing to a curve, and failing those is the noise that teaches people to skim the row.

The threshold is a ratio rather than a distance because the judgement the reader makes is comparative: a label is unambiguous when its own curve is plainly the closest thing to it, not when it is some absolute number of points away.

Scatters count as series alongside lines, and so do the path-drawn ones: step's staircase, a stackplot band, a contour set. Reading ax.lines and offsets alone left a label sitting on top of a dense point cloud or inside a stacked band invisible to the gate twice over: the series could not own a label, and it could not be the neighbour that made one ambiguous. The premise here is that a reader resolves a direct label by proximity, and a reader does not know what artist class drew the ink.

A filled region that encloses the named series is not a rival for its label, and neither is a series enclosed by a named region. A confidence band lies on top of the curve it belongs to, so on distance alone it is always tied with that curve at zero and every direct label under a band failed. The test is _encloses, and it is geometric: an unlabelled band and one labelled for the legend get the same answer, which the label-based test this replaced did not - it passed _child3 and failed 95% CI.

Source code in skill/scripts/check_figure.py
def check_label_attribution(fig: Figure, r: Any) -> tuple[bool | str, str]:
    """A direct label sitting nearer some other series than the one it names.

    `check_collisions` compares text against text, so a label that clears every
    other label and still floats in the corridor between two curves passes it
    clean. That is not hypothetical: `examples/demo.py` shipped with "Tuned"
    closer to a neighbouring curve than to its own and the whole suite was
    green. Text against text and text against data are different questions.

    Harvested narrowly on purpose - only text whose string matches exactly one
    series label is judged, because only there is the intent known. A callout,
    a panel letter, an "n = 300" attributes nothing to a curve, and failing
    those is the noise that teaches people to skim the row.

    The threshold is a ratio rather than a distance because the judgement the
    reader makes is comparative: a label is unambiguous when its own curve is
    plainly the closest thing to it, not when it is some absolute number of
    points away.

    Scatters count as series alongside lines, and so do the path-drawn ones:
    `step`'s staircase, a `stackplot` band, a contour set. Reading `ax.lines`
    and offsets alone left a label sitting on top of a dense point cloud or
    inside a stacked band invisible to the gate twice over: the series could not
    own a label, and it could not be the neighbour that made one ambiguous. The
    premise here is that a reader resolves a direct label by proximity, and a
    reader does not know what artist class drew the ink.

    A filled region that encloses the named series is not a rival for its label,
    and neither is a series enclosed by a named region. A confidence band lies
    on top of the curve it belongs to, so on distance alone it is always tied
    with that curve at zero and every direct label under a band failed. The test
    is `_encloses`, and it is geometric: an unlabelled band and one labelled for
    the legend get the same answer, which the label-based test this replaced did
    not - it passed `_child3` and failed `95% CI`.
    """
    bad, checked = [], 0
    legend_ids = _legend_text_ids(fig) | _furniture_text_ids(fig)
    all_texts = _texts(fig, r)
    for ax in _all_axes(fig):
        px = {}
        for artist in (*ax.lines, *ax.collections):
            if not artist.get_visible():
                continue
            p = _series_px(artist, ax)
            if p is not None and len(p):
                px[artist] = p
        if len(px) < 2:
            continue

        lines_list = list(px.keys())
        owners: dict[Any, Any] = {}
        for i, line in enumerate(lines_list):
            owners.setdefault(str(line.get_label()).strip(), []).append(i)

        for t, bb in all_texts:
            if t.axes is not ax or id(t) in legend_ids:
                continue
            match = owners.get(str(t.get_text()).strip())
            if not match or len(match) != 1:
                continue
            own_line = lines_list[match[0]]
            checked += 1
            # An annotation with a leader is judged at its anchor, not at its
            # string. See `_attribution_box`.
            bb = _attribution_box(t, r, bb)
            # A floor on the own-curve distance: without it a label printed
            # directly on its line divides by ~zero, and every other line in
            # the figure reads as infinitely far.
            d_own = max(_series_distance(own_line, bb, px[own_line]), 0.5)
            # The minimum over every OTHER curve, box-to-polyline, taken per
            # curve. A KD-tree over the pooled points is the wrong tool: it
            # returns the nearest *points*, and beside a dense own curve every
            # near point is the label's own, so `d_other` never leaves
            # infinity and the label passes.
            # Rivals only. A band that encloses this series, or a series this
            # one encloses, is the same thing on the page and cannot be the
            # neighbour a reader confuses it with.
            rivals = [(line, p) for line, p in px.items()
                      if line is not own_line
                      and not _encloses(line, px[own_line])
                      and not _encloses(own_line, p)
                      and not _rides_on(line, own_line, px[own_line], ax)]
            if not rivals:
                continue
            d_other = min(_series_distance(line, bb, p) for line, p in rivals)
            if d_other < LABEL_MARGIN * d_own:
                bad.append(f"{str(t.get_text())[:22]!r} is {d_own:.0f}px from "
                           f"its own curve and {d_other:.0f}px from another")
    if not checked:
        return True, "no direct labels matched to a series"
    if not bad:
        return True, f"{checked} direct label{'s' if checked != 1 else ''}, "\
                     f"each nearest the curve it names"
    return False, ("; ".join(bad) + "  [FIX] the reader resolves a direct label "
                   "by proximity, so it has to be plainly nearest its own "
                   "curve. Move it to where that curve is furthest from its "
                   "neighbours, or draw a leader line to the anchor")

check_figure.check_style_sheet

check_style_sheet(fig: Figure) -> tuple[bool | str, str]

Every key in the sheet against the rcParams that are actually in effect.

Three separate silent failures land here at once: a color written with a leading #, a forgotten plt.style.use, and an rcParams override applied later. All three ship stock matplotlib while every other check passes.

The first cannot be seen by comparing values. # starts a comment in this format, so grid.color: #e1e0d9 parses to no value and matplotlib drops the key: the sheet and the live rcParams agree on its absence. So the keys the file names are read off its text as well, and any that matplotlib knows but did not parse are reported as dropped.

A warning, not a gate, for one honest reason: a figure built on a different project's sheet is correct work, and this compares against the global rcParams rather than what the figure was drawn under, so a figure built inside an rc_context that has since exited reads as drift when it is not. Both make a hard failure the wrong instrument. The row names the keys.

Finding no sheet at all warns too, as a STYLE_SHEET pointing at a missing file does: either way the figure may be stock matplotlib, the case this gate was written for. Installed, the sheet is inside the package and is always found; only a vendored copy that took the script without it reaches this.

Source code in skill/scripts/check_figure.py
def check_style_sheet(fig: Figure) -> tuple[bool | str, str]:
    """Every key in the sheet against the rcParams that are actually in effect.

    Three separate silent failures land here at once: a color written with a
    leading `#`, a forgotten `plt.style.use`, and an rcParams override applied
    later. All three ship stock matplotlib while every other check passes.

    The first cannot be seen by comparing values. `#` starts a comment in this
    format, so `grid.color: #e1e0d9` parses to no value and matplotlib drops
    the key: the sheet and the live rcParams agree on its absence. So the keys
    the file names are read off its text as well, and any that matplotlib
    knows but did not parse are reported as dropped.

    A warning, not a gate, for one honest reason: a figure built on a *different*
    project's sheet is correct work, and this compares against the global
    rcParams rather than what the figure was drawn under, so a figure built
    inside an `rc_context` that has since exited reads as drift when it is not.
    Both make a hard failure the wrong instrument. The row names the keys.

    Finding no sheet at all warns too, as a `STYLE_SHEET` pointing at a
    missing file does: either way the figure may be stock matplotlib, the case
    this gate was written for. Installed, the sheet is inside the package and
    is always found; only a vendored copy that took the script without it
    reaches this.
    """
    import matplotlib as mpl
    path = _style_sheet()
    if path is None:
        return "warn", (DID_NOT_RUN + "no figure.mplstyle beside this script "
                        "or in assets/, so nothing was compared and a "
                        "forgotten plt.style.use would read clean  [FIX] copy "
                        "figure.mplstyle in beside it, or set STYLE_SHEET")
    if not path.is_file():
        return "warn", (f"STYLE_SHEET is set to {path}, which is not a file: "
                        "nothing was compared, and the sheet you meant is not "
                        "the one in effect either")
    written = mpl.rc_params_from_file(path, use_default_template=False)
    named = []
    for line in path.read_text(encoding="utf-8").splitlines():
        before_comment = line.split("#", 1)[0]
        if ":" in before_comment:
            named.append(before_comment.split(":", 1)[0].strip())
    dropped = sorted({k for k in named if k in mpl.rcParams
                      and k not in written})
    drift = []
    for key, value in written.items():
        try:
            same = mpl.rcParams[key] == value
        except KeyError:
            continue
        if not isinstance(same, bool):        # a numpy array of comparisons
            # B023 reads the lambda as capturing the loop variable late. It is
            # called on the same line it is built, before the loop advances, so
            # there is no later binding for it to see.
            same = bool(getattr(same, "all", lambda: same)())  # noqa: B023
        if not same:
            drift.append(key)
    if dropped:
        return "warn", (f"{len(dropped)} keys in {path.name} did not parse and "
                        f"were dropped: {dropped[:5]}"
                        f"{' ...' if len(dropped) > 5 else ''}  [FIX] write "
                        "colors bare, e1e0d9 not #e1e0d9: # starts a comment "
                        "in a style sheet")
    if not drift:
        return True, f"all {len(written)} keys match {path.name}"
    return "warn", (f"{len(drift)} of {len(written)} keys differ from "
                    f"{path.name}: {sorted(drift)[:5]}"
                    f"{' ...' if len(drift) > 5 else ''}  [FIX] the sheet is not "
                    "the one in effect: check plt.style.use, and check no color "
                    "in the sheet was written with a leading #")

check_figure.check_contour_dash

check_contour_dash(fig: Figure) -> tuple[bool | str, str]

Warns when a monochrome contour set draws its negative levels dashed.

In a monochrome contour, rcParams["contour.negative_linestyle"] is "dashed" by default, so negative-Z contours ship dashed isolines nobody chose. The skill's own convention is dashing = unobserved / projected / threshold, making this a silent semantic error every existing gate misses.

Non-monochrome (colored) contours are always solid and unaffected.

The rule is "any negative level", asked of the drawn strokes, not "every level non-positive": contour over data spanning zero draws levels either side of it and matplotlib dashes the negative half, and that signed field is the case this gate is for.

Source code in skill/scripts/check_figure.py
def check_contour_dash(fig: Figure) -> tuple[bool | str, str]:
    """Warns when a monochrome contour set draws its negative levels dashed.

    In a monochrome contour, `rcParams["contour.negative_linestyle"]` is
    "dashed" by default, so negative-Z contours ship dashed isolines nobody
    chose. The skill's own convention is dashing = unobserved / projected /
    threshold, making this a silent semantic error every existing gate misses.

    Non-monochrome (colored) contours are always solid and unaffected.

    The rule is "any negative level", asked of the drawn strokes, not "every
    level non-positive": `contour` over data spanning zero draws levels either
    side of it and matplotlib dashes the negative half, and that signed field
    is the case this gate is for.
    """
    from matplotlib.contour import ContourSet

    warned = []
    for i, ax in enumerate(_all_axes(fig)):
        for c in ax.collections:
            if not isinstance(c, ContourSet):
                continue
            if _negative_levels_are_dashed(c):
                warned.append(
                    f"ax{i}: negative-level contours auto-dashed — dashing "
                    "reads as projected/unobserved here"
                    '  [FIX] pass linestyles="solid" to contour on signed data')
                break

    if not warned:
        return True, "no auto-dashed negative contours"
    return "warn", "; ".join(warned)

check_figure.check_colormap

check_colormap(fig: Figure) -> tuple[bool | str, str]

Whether each colormap in the figure encodes what its data is.

Samples every named colormap an artist actually draws with, hands the samples to check_palette.cmap_kind, and fails the two kinds that are not an encoding. misc is a ramp whose lightness reverses, or is flat, or ends somewhere neither cyclic nor diverging would: a reader cannot put two of its values in order. A qualitative map is judged by the same all-pairs separation floor a hand-built palette is, because an image puts every category beside every other one.

A ramp the author evaluated themselves is caught too, by reverse lookup rather than by classification: six jet steps handed to ax.plot as plain colours carry no array, so the sampling above finds nothing to judge and every row on the figure passes. See _sampled_ramp for how a sampled ramp is told from a categorical palette, which is the whole difficulty.

One way this row passes without having judged anything, and it is deliberate: a colormap matplotlib built from colours the author set on an artist is skipped, since contour(colors=[...]) is three levels of one hue rather than three categories, and classifying it qualitative would fail it.

The other way was not. The row needs check_palette.py importable beside this file, and without it there is nothing to classify with, so the row warns rather than passing a gate that never ran. The warn cannot fail a build -- ok turns on hard False only -- so a vendored copy that deliberately left the palette module out still audits, and says which rows went unjudged.

Source code in skill/scripts/check_figure.py
def check_colormap(fig: Figure) -> tuple[bool | str, str]:
    """Whether each colormap in the figure encodes what its data is.

    Samples every named colormap an artist actually draws with, hands the
    samples to `check_palette.cmap_kind`, and fails the two kinds that are not
    an encoding. `misc` is a ramp whose lightness reverses, or is flat, or ends
    somewhere neither cyclic nor diverging would: a reader cannot put two of its
    values in order. A qualitative map is judged by the same all-pairs
    separation floor a hand-built palette is, because an image puts every
    category beside every other one.

    A ramp the author evaluated themselves is caught too, by reverse lookup
    rather than by classification: six `jet` steps handed to `ax.plot` as plain
    colours carry no array, so the sampling above finds nothing to judge and
    every row on the figure passes. See `_sampled_ramp` for how a sampled ramp
    is told from a categorical palette, which is the whole difficulty.

    One way this row passes without having judged anything, and it is
    deliberate: a colormap matplotlib built from colours the author set on an
    artist is skipped, since `contour(colors=[...])` is three levels of one hue
    rather than three categories, and classifying it qualitative would fail it.

    The other way was not. The row needs `check_palette.py` importable beside
    this file, and without it there is nothing to classify with, so the row
    warns rather than passing a gate that never ran. The warn cannot fail a
    build -- `ok` turns on
    hard `False` only -- so a vendored copy that deliberately left the palette
    module out still audits, and says which rows went unjudged.
    """
    cp = _sibling("check_palette")
    if cp is None:
        return "warn", (DID_NOT_RUN + "check_palette.py is not importable "
                        "beside this file, so no colormap was classified  "
                        "[FIX] copy check_palette.py in beside it, or install "
                        "the package")

    import matplotlib as mpl
    from matplotlib.colors import to_hex

    seen: dict[Any, Any] = {}
    for ax in _all_axes(fig):
        if ax.get_label() == "<colorbar>":
            continue
        for artist in list(ax.images) + list(ax.collections):
            if not artist.get_visible():
                continue
            if getattr(artist, "get_array", lambda: None)() is None:
                continue
            cmap = getattr(artist, "get_cmap", lambda: None)()
            if cmap is not None:
                name = getattr(cmap, "name", "")
                # An unnamed colormap means the artist has explicit colours set
                # (e.g. `contour(colors="black")`), rather than a continuous
                # encoding named by the author.
                if not name or name in ANONYMOUS_CMAP_NAMES:
                    continue
                seen.setdefault(name, cmap)

    fails, notes = [], []

    # A ramp the author sampled themselves never reaches the loop above, so it
    # is looked for in the drawn colours instead. See `_sampled_ramp`.
    panel = {ax: i for i, ax in enumerate(_all_axes(fig))}
    for ax, items in _data_colors_by_axes(fig).items():
        distinct = list(dict.fromkeys(h for h, _, _ in items))
        name = _sampled_ramp(distinct)
        if name is None:
            continue
        ramp = mpl.colormaps[name]
        floats = [tuple(ramp(i / (cp.CMAP_SAMPLES - 1))[:3])
                  for i in range(cp.CMAP_SAMPLES)]
        fails.append(
            f"ax{panel.get(ax, '?')}: {len(distinct)} series colors are "
            f"{name} sampled at even steps, and its lightness reverses over "
            f"{cp.cmap_back_travel_rgb(floats):.0%} of its span  [FIX] a "
            "reader cannot order two values in it. Draw the ramp as data - "
            "c=values, cmap='viridis' - so it carries a colorbar, or step a "
            "sequential map  [WHY] evaluating a colormap yourself hands over "
            "plain colors, and the encoding stops being visible to anything "
            "downstream, this row included")

    if not seen:
        if fails:
            return False, "; ".join(fails)
        return True, "no colormapped artists"

    for name, cmap in sorted(seen.items()):
        if cmap.N < cp.CMAP_QUALITATIVE_N:
            levels = [to_hex(cmap(i)) for i in range(cmap.N)]
            floats = [tuple(cmap(i)[:3]) for i in range(cmap.N)]
        else:
            levels = [to_hex(cmap(i / (cp.CMAP_SAMPLES - 1)))
                      for i in range(cp.CMAP_SAMPLES)]
            # Classified before the 8-bit round trip. Rounding each channel to
            # 1/255 puts oscillations of about 0.001 OKLab into a smooth ramp,
            # and back travel divides by the lightness span, so a narrow-span
            # map turns that wobble into a large fraction: `winter` measured
            # 0.0343 through hex against 0.0139 in float, straddling the 0.02
            # floor, so a sequential map classified `misc`. `levels` stays hex
            # because the qualitative branch below hands it to `cp.check`,
            # which takes hex.
            floats = [tuple(cmap(i / (cp.CMAP_SAMPLES - 1))[:3])
                      for i in range(cp.CMAP_SAMPLES)]

        kind = cp.cmap_kind_rgb(floats)

        if kind == "misc":
            fails.append(
                f"{name}: lightness reverses over "
                f"{cp.cmap_back_travel_rgb(floats):.0%} of its span  [FIX] a "
                "reader cannot order two values in it. viridis for sequential, "
                "RdBu for diverging, twilight for cyclic")
            continue

        if kind == "qualitative":
            _, rows = cp.check(levels, all_pairs=True)
            bad = [detail.split("  [FIX]")[0].strip()
                   for row_name, status, detail in rows
                   if row_name.startswith(("CVD separation",
                                            "Normal-vision floor"))
                   and status is False]
            if bad:
                fails.append(f"{name} ({cmap.N} categories): " + "; ".join(bad)
                             + "  [FIX] re-step the categories onto hues that "
                               "separate at every pair, or cut their number"
                               "  [WHY] an image puts every category beside every "
                               "other, so every pair has to separate")
                continue

        notes.append(f"{name} {kind}")

    if fails:
        return False, "; ".join(fails)
    return True, ", ".join(notes)

check_figure.check_fonts

check_fonts(fig: Figure) -> tuple[bool | str, str]

Two silent failures between the figure on screen and the file you submit.

Type 3. Matplotlib defaults pdf.fonttype and ps.fonttype to 3. IEEE PDF eXpress requires embedded Type 1 or TrueType and does not accept Type 3, so the upload is refused before a reviewer sees it. ACM and Elsevier check embedding in production instead, which is the same problem surfacing after acceptance rather than a milder one. Neither publishes a rule rejecting a submission for it, and this docstring said they did until the prose audit read the sources. Nothing warns you either way: the figure renders identically, and the paper bounces at the latest and most expensive possible moment. Type 42 embeds TrueType outlines instead. figure.mplstyle sets it; this catches the project that did not copy the sheet, and the notebook that called rcParams.update afterwards.

Silent substitution. When none of the faces named in font.<family> is installed, matplotlib falls back to its own default and logs nothing at default verbosity. The guide calls the typeface the single largest visual lever in the whole method, so a figure set in DejaVu because someone named "Times New Roman" on a machine that does not have it is the lever quietly disengaged. Falling back within the named list is not flagged — that is what a fallback list is for, and the sheet ships one on purpose.

A warning rather than a gate, for the same reason check_style_sheet is: both read the global rcParams rather than anything the figure carries, so neither can tell a figure built under someone else's settings from a figure built under none. A figure that will only ever be a PNG in a README is also genuinely unaffected by the PDF font type. What is gated instead is the thing this repo controls — the shipped figure.mplstyle declares 42, and the suite fails if that line ever goes missing.

Source code in skill/scripts/check_figure.py
def check_fonts(fig: Figure) -> tuple[bool | str, str]:
    """Two silent failures between the figure on screen and the file you submit.

    *Type 3.* Matplotlib defaults `pdf.fonttype` and `ps.fonttype` to 3. IEEE
    PDF eXpress requires embedded Type 1 or TrueType and does not accept Type 3,
    so the upload is refused before a reviewer sees it. ACM and Elsevier check
    embedding in production instead, which is the same problem surfacing after
    acceptance rather than a milder one. Neither publishes a rule rejecting a
    submission for it, and this docstring said they did until the prose audit
    read the sources. Nothing warns you either way: the figure renders
    identically, and the paper bounces at the latest and most expensive possible
    moment. Type 42 embeds TrueType outlines instead. `figure.mplstyle` sets it;
    this catches the project that did not copy the sheet, and the notebook that
    called `rcParams.update` afterwards.

    *Silent substitution.* When none of the faces named in `font.<family>` is
    installed, matplotlib falls back to its own default and logs nothing at
    default verbosity. The guide calls the typeface the single largest visual
    lever in the whole method, so a figure set in DejaVu because someone named
    "Times New Roman" on a machine that does not have it is the lever quietly
    disengaged. Falling back *within* the named list is not flagged — that is
    what a fallback list is for, and the sheet ships one on purpose.

    A warning rather than a gate, for the same reason `check_style_sheet` is:
    both read the *global* rcParams rather than anything the figure carries, so
    neither can tell a figure built under someone else's settings from a figure
    built under none. A figure that will only ever be a PNG in a README is also
    genuinely unaffected by the PDF font type. What is gated instead is the
    thing this repo controls — the shipped `figure.mplstyle` declares 42, and
    the suite fails if that line ever goes missing.
    """
    import matplotlib as mpl
    from matplotlib.font_manager import FontProperties, findfont, get_font

    notes = []
    type3 = [k for k in ("pdf.fonttype", "ps.fonttype")
             if int(mpl.rcParams[k]) == 3]
    if type3:
        notes.append(f"{' and '.join(type3)} = 3 (Type 3)  [FIX] IEEE PDF eXpress "
                     "refuses the upload and ACM/Elsevier catch it in "
                     "production; set both to 42")

    family = mpl.rcParams["font.family"]
    families = ([family] if isinstance(family, str) else list(family)) or [
        "sans-serif"]
    generic = families[0]
    # `font.family` holds generic names, concrete face names, or both. A
    # generic name stands for its `font.<generic>` list; a concrete one is
    # itself, and when it is missing nothing else in the list says so.
    wanted = []
    for name in families:
        key = {"sans": "sans-serif", "sans serif": "sans-serif"}.get(
            name.lower(), name.lower())
        if key in ("serif", "sans-serif", "cursive", "fantasy", "monospace"):
            wanted.extend(mpl.rcParams.get(f"font.{key}", []))
        else:
            wanted.append(name)
    if wanted:
        try:
            got = get_font(findfont(FontProperties(family=families))).family_name
        except Exception:
            got = None
        if got is not None and not any(got.lower() == w.lower() for w in wanted):
            notes.append(f"asked for {wanted[:3]}, rendering in {got!r} — none "
                         "of the named faces is installed on this machine")

    if notes:
        return "warn", "; ".join(notes)
    return True, f"Type 42 embedding, {generic} face resolves within the list"

check_figure.check_alt_text

check_alt_text(fig: Figure) -> tuple[bool | str, str]

Whether the figure carries a description for a reader who cannot see it.

A warning rather than a gate, and deliberately: on a paper the description frequently is the caption, and the caption lives in the .tex file where this cannot see it. Hard-failing every figure in that entirely reasonable setup is how a row becomes something everyone learns to skip, which is worse than not having it. Where there is no caption — a notebook, a README, a slide, a web page — nothing else is carrying this and the row is the only thing that will say so.

Source code in skill/scripts/check_figure.py
def check_alt_text(fig: Figure) -> tuple[bool | str, str]:
    """Whether the figure carries a description for a reader who cannot see it.

    A warning rather than a gate, and deliberately: on a paper the description
    frequently *is* the caption, and the caption lives in the .tex file where
    this cannot see it. Hard-failing every figure in that entirely reasonable
    setup is how a row becomes something everyone learns to skip, which is worse
    than not having it. Where there is no caption — a notebook, a README, a
    slide, a web page — nothing else is carrying this and the row is the only
    thing that will say so.
    """
    text = str(getattr(fig, ALT_TEXT_ATTR, "") or "").strip()
    if not text:
        return "warn", ("no description attached  [FIX] describe(fig, \"...\") "
                        "and pass alt_metadata(fig, path) to savefig; if the "
                        "document's caption carries it, this row is discharged")
    if len(text) < ALT_TEXT_MIN_CHARS:
        return "warn", (f"description is {len(text)} characters — that is a "
                        "title, not a description of what the reader would "
                        "have seen")
    return True, f"described in {len(text)} characters"