diff --git a/CHANGELOG.md b/CHANGELOG.md index db219d3..fbdaf84 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,13 @@ to [Semantic Versioning](https://semver.org/). ### Added +- Concept-figure primitives in `nicefigs.schematic`: `schematic_axes` (a figure of the printed size + whose data units are inches), `numbered_disc`, `group_band`, `label_pair`, `grid_cells`, + `folder_icon` and the colour helpers `tint`, `shade` and `soft_color`. They draw with the active + theme and the `NICE_COLORS` of the house palette, and combine with `diagram_box` and + `diagram_arrow`. `NICE_COLORS` is now exported at the top level. +- `save(..., check_text=True)` runs `check_text_overlaps` first and raises `ValueError` on a problem. +- Gallery example `35_schematic`. - The font chain reaches metric-compatible Helvetica clones (TeX Gyre Heros, Nimbus Sans, Liberation Sans) before DejaVu Sans. - `register_fonts(dir)` (default `$NICEFIGS_FONT_DIR`) makes a folder of fonts available to a theme; the themes' fonts are unchanged. SVG text is written as paths (`svg.fonttype="path"` in every theme and in `save`); text diff --git a/docs/api.md b/docs/api.md index 828bf12..a34a04c 100644 --- a/docs/api.md +++ b/docs/api.md @@ -92,6 +92,10 @@ and the [Gallery](gallery.md) for runnable examples. ::: nicefigs.diagrams +## `nicefigs.schematic` + +::: nicefigs.schematic + ## `nicefigs.sections` ::: nicefigs.sections diff --git a/docs/gallery.md b/docs/gallery.md index fce9b72..1a118c0 100644 --- a/docs/gallery.md +++ b/docs/gallery.md @@ -473,3 +473,19 @@ spot. ```python --8<-- "examples/31_panel_label_with_title.py" ``` + +### 35 — Concept figure from schematic primitives {#schematic} + +[`schematic_axes`][nicefigs.schematic_axes] gives a figure of the printed size whose data units +are inches, on which [`diagram_box`][nicefigs.diagram_box] and +[`diagram_arrow`][nicefigs.diagram_arrow] draw the flow, and +[`numbered_disc`][nicefigs.numbered_disc], [`group_band`][nicefigs.group_band], +[`label_pair`][nicefigs.label_pair], [`grid_cells`][nicefigs.grid_cells] and +[`folder_icon`][nicefigs.folder_icon] add the numbering, grouping, labels and glyphs. Colours come +from the active theme and the `NICE_COLORS`. + +![Schematic](gallery/35_schematic.png) + +```python +--8<-- "examples/35_schematic.py" +``` diff --git a/docs/gallery/35_schematic.png b/docs/gallery/35_schematic.png new file mode 100644 index 0000000..809e2e5 Binary files /dev/null and b/docs/gallery/35_schematic.png differ diff --git a/examples/35_schematic.py b/examples/35_schematic.py new file mode 100644 index 0000000..c002842 --- /dev/null +++ b/examples/35_schematic.py @@ -0,0 +1,37 @@ +"""Schematic: a small pipeline drawn at its printed size from boxes, arrows, discs, bands and glyphs.""" + +import nicefigs as nf + + +def make(): + nf.set_theme(nf.Theme.from_base(7.2)) + fig, ax = nf.schematic_axes(5.5, 1.9) + th = nf.get_theme() + blue, orange = nf.NICE_COLORS["blue"], nf.NICE_COLORS["orange"] + nf.group_band(ax, (1.7, 0.1), 2.4, 1.7, "run chunk by chunk") + steps = [ + (0.8, "read", "target and prediction"), + (2.9, "compare", "view, then metric"), + (4.7, "store", "one folder each"), + ] + for k, (x, name, detail) in enumerate(steps): + fill = nf.tint(blue, 0.2) if k == 1 else "white" + nf.diagram_box( + ax, (x, 1.2), 1.3, 0.5, facecolor=fill, edgecolor=th.text_color, linewidth=0.7, rounding=0.03 + ) + nf.label_pair(ax, (x, 1.2), name, detail, bold=True) + nf.numbered_disc(ax, (x - 0.65, 1.45), k + 1) + for x0, x1 in ((1.45, 2.25), (3.55, 4.05)): + nf.diagram_arrow(ax, (x0, 1.2), (x1, 1.2), style="line", width=0.7, head_length=3.4, head_width=3.0) + nf.grid_cells(ax, (0.3, 0.2), 5, 3, 0.15) + nf.grid_cells(ax, (2.15, 0.2), 5, 3, 0.15, fills={(2, 1): nf.tint(orange, 0.5)}) + for k in range(3): + nf.folder_icon(ax, (4.2 + k * 0.3, 0.3), 0.24, 0.18) + return fig + + +if __name__ == "__main__": + import matplotlib + + matplotlib.use("Agg") + nf.save(make(), "35_schematic", formats=("png", "pdf"), check_text=True) diff --git a/src/nicefigs/__init__.py b/src/nicefigs/__init__.py index d4b30b9..9712d43 100644 --- a/src/nicefigs/__init__.py +++ b/src/nicefigs/__init__.py @@ -17,7 +17,7 @@ from . import data from .animation import animate_maps, render_animation, save_animation, stitch_frames -from .artists import ARTIST_PALETTES, HOCKNEY_CANYON, NICE, artist_cmap, artist_palette +from .artists import ARTIST_PALETTES, HOCKNEY_CANYON, NICE, NICE_COLORS, artist_cmap, artist_palette from .bars import grouped as grouped_bars from .bars import histogram from .bars import stacked as stacked_bars @@ -94,6 +94,17 @@ from .pareto import frontier, pareto from .ranking import caterpillar from .scatter import scatter +from .schematic import ( + folder_icon, + grid_cells, + group_band, + label_pair, + numbered_disc, + schematic_axes, + shade, + soft_color, + tint, +) from .sections import cross_section, cross_section_panels, profile from .shapes import polygon_mesh from .spectra import spectrum @@ -200,6 +211,7 @@ "ARTIST_PALETTES", "HOCKNEY_CANYON", "NICE", + "NICE_COLORS", # colorbars "colorbar", "inset_histogram_colorbar", @@ -249,6 +261,16 @@ "scorecard", "skill_gap", "diagram_box", + # schematics + "schematic_axes", + "numbered_disc", + "group_band", + "label_pair", + "grid_cells", + "folder_icon", + "tint", + "shade", + "soft_color", "diagram_arrow", "flux_diagram", "flux_legend", diff --git a/src/nicefigs/figure.py b/src/nicefigs/figure.py index e17a6c3..f12bb65 100644 --- a/src/nicefigs/figure.py +++ b/src/nicefigs/figure.py @@ -199,6 +199,7 @@ def save( dpi: int | None = None, transparent: bool = False, close: bool = False, + check_text: bool = False, ) -> list[Path]: """Save ``fig`` with a tight bounding box, creating parent directories. @@ -209,14 +210,20 @@ def save( dpi: Raster resolution; defaults to the active theme's ``savedpi``. transparent: Transparent background. close: Close the figure after saving. + check_text: Run :func:`check_text_overlaps` first and raise if it finds a problem. Returns: The written paths, one per format, in the order of ``formats``. + Raises: + ValueError: ``check_text`` is set and some text overlaps another or leaves the figure. + Example:: nf.save(fig, "figures/fig01", formats=("pdf", "png")) """ + if check_text and (issues := check_text_overlaps(fig)): + raise ValueError(f"text layout problems: {issues}") p = Path(path) th = get_theme() dpi = dpi or th.savedpi diff --git a/src/nicefigs/schematic.py b/src/nicefigs/schematic.py new file mode 100644 index 0000000..30585cd --- /dev/null +++ b/src/nicefigs/schematic.py @@ -0,0 +1,360 @@ +"""Primitives for concept figures: schematics drawn in inches on one axes. + +A concept figure (a pipeline, a data layout, a tree of merges) is built at its printed size, so a +7 pt label is 7 pt on the page. :func:`schematic_axes` makes the canvas, with the x and y data +coordinates in inches; :func:`~nicefigs.diagram_box` and :func:`~nicefigs.diagram_arrow` draw +boxes and connectors on it, and this module adds the remaining pieces: :func:`numbered_disc`, +:func:`group_band`, :func:`label_pair`, :func:`grid_cells`, :func:`folder_icon`, and the colour +helpers :func:`tint` and :func:`shade`. Every colour defaults to the active theme and the +:data:`~nicefigs.NICE_COLORS`: ink is the theme's text colour, secondary text the neutral grey, +the accent the orange of the house palette. + +Example:: + + import nicefigs as nf + + nf.set_theme(nf.Theme.from_base(7.2)) + fig, ax = nf.schematic_axes(3.2, 1.0) + nf.diagram_box(ax, (0.7, 0.5), 1.0, 0.5, text="read") + nf.diagram_arrow(ax, (1.25, 0.5), (1.95, 0.5), style="line", width=0.7) + nf.numbered_disc(ax, (0.25, 0.8), 1) + nf.check_text_overlaps(fig) +""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any + +import numpy as np +from matplotlib.colors import to_rgb +from matplotlib.patches import Circle, FancyBboxPatch, Polygon, Rectangle + +from .artists import NICE_COLORS +from .figure import figure +from .style import COLORS, get_theme + +if TYPE_CHECKING: + from matplotlib.axes import Axes + from matplotlib.figure import Figure + from matplotlib.text import Text + +__all__ = [ + "folder_icon", + "grid_cells", + "group_band", + "label_pair", + "numbered_disc", + "schematic_axes", + "shade", + "soft_color", + "tint", +] + + +def tint(color: Any, amount: float) -> tuple[float, float, float]: + """Blend ``color`` with white. + + Args: + color: Any matplotlib colour. + amount: Share of ``color`` that stays; 0 is white and 1 is ``color``. + + Returns: + An RGB tuple. + """ + rgb = np.asarray(to_rgb(color)) + r, g, b = 1 - amount * (1 - rgb) + return float(r), float(g), float(b) + + +def shade(color: Any, amount: float = 0.35) -> tuple[float, float, float]: + """Blend ``color`` with black, for text that sits next to an object of that colour. + + Args: + color: Any matplotlib colour. + amount: Share of black; 0 is ``color`` and 1 is black. + + Returns: + An RGB tuple. + """ + rgb = np.asarray(to_rgb(color)) + r, g, b = rgb * (1 - amount) + return float(r), float(g), float(b) + + +def soft_color() -> str: + """Colour of secondary text and quiet lines: the neutral grey of the house style.""" + return COLORS["neutral"] + + +def schematic_axes(width: float, height: float, *, theme: Any = None, **kwargs: Any) -> tuple[Figure, Axes]: + """Create a figure of the printed size with one axes whose data units are inches. + + Args: + width: Figure width in inches. + height: Figure height in inches. + theme: Theme name or :class:`~nicefigs.Theme`; ``None`` uses the active theme. + **kwargs: Forwarded to :func:`nicefigs.figure`. + + Returns: + The figure and its axes, which has no frame and spans the figure: x runs 0 to ``width`` + and y 0 to ``height``. + """ + fig = figure(width=width, height=height, theme=theme, **kwargs) + ax = fig.add_axes((0, 0, 1, 1)) + ax.set_xlim(0, width) + ax.set_ylim(0, height) + ax.axis("off") + return fig, ax + + +def numbered_disc( + ax: Axes, + xy: tuple[float, float], + n: int | str, + *, + radius: float = 0.07, + color: Any = None, + zorder: float = 12.0, +) -> Circle: + """Draw a filled disc with a white digit, to tie a figure to the steps of a text. + + Args: + ax: Axes to draw on. + xy: Centre, in data coordinates. + n: The number or letter shown. + radius: Disc radius, in data units. + color: Fill colour; the orange of the house palette by default. + zorder: Drawing order; the digit draws above. + + Returns: + The disc patch. + """ + th = get_theme() + disc = Circle( + xy, + radius, + facecolor=NICE_COLORS["orange"] if color is None else color, + edgecolor="white", + linewidth=0.5, + zorder=zorder, + ) + ax.add_patch(disc) + ax.text( + xy[0], + xy[1] - 0.004, + str(n), + ha="center", + va="center", + color="white", + fontsize=th.fs_annot, + fontweight="bold", + zorder=zorder + 0.1, + ) + return disc + + +def group_band( + ax: Axes, + xy: tuple[float, float], + width: float, + height: float, + title: str = "", + *, + color: Any = None, + rounding: float = 0.04, + zorder: float = 0.5, +) -> FancyBboxPatch: + """Draw a quiet filled band that groups objects, with its title at the top left. + + Args: + ax: Axes to draw on. + xy: Lower-left corner, in data coordinates. + width: Band width, in data units. + height: Band height, in data units. + title: Title in secondary text; empty for none. + color: Fill colour; a light tint of the theme's text colour by default. + rounding: Corner radius, in data units. + zorder: Drawing order; keep it below the grouped objects. + + Returns: + The band patch. + """ + th = get_theme() + band = FancyBboxPatch( + (xy[0], xy[1]), + width, + height, + boxstyle=f"round,pad=0,rounding_size={rounding}", + facecolor=tint(th.text_color, 0.06) if color is None else color, + edgecolor="none", + zorder=zorder, + ) + ax.add_patch(band) + if title: + ax.text( + xy[0] + 0.08, + xy[1] + height - 0.1, + title, + ha="left", + va="center", + color=soft_color(), + fontsize=th.fs_annot, + zorder=zorder + 1, + ) + return band + + +def label_pair( + ax: Axes, + xy: tuple[float, float], + name: str, + detail: str, + *, + color: Any = None, + ha: str = "center", + gap: float = 0.055, + bold: bool = False, + zorder: float = 6.0, +) -> tuple[Text, Text]: + """Write a name in ink with a detail in secondary text underneath, centred on ``xy``. + + Args: + ax: Axes to draw on. + xy: Anchor of the pair, in data coordinates. + name: First line, in ``color``. + detail: Second line, in the neutral grey and the smaller annotation size. + color: Colour of the name; the theme's text colour by default. + ha: Horizontal alignment of both lines. + gap: Distance of each line from ``xy``, in data units. + bold: Set the name in bold. + zorder: Drawing order. + + Returns: + The two text artists, name first. + """ + th = get_theme() + top = ax.text( + xy[0], + xy[1] + gap, + name, + ha=ha, + va="center", + color=th.text_color if color is None else color, + fontsize=th.fs_legend, + fontweight="bold" if bold else "normal", + zorder=zorder, + ) + bottom = ax.text( + xy[0], + xy[1] - gap, + detail, + ha=ha, + va="center", + color=soft_color(), + fontsize=th.fs_annot, + zorder=zorder, + ) + return top, bottom + + +def grid_cells( + ax: Axes, + xy: tuple[float, float], + nx: int, + ny: int, + cell: float, + *, + fills: Mapping[tuple[int, int], Any] | None = None, + facecolor: Any = None, + edgecolor: Any = None, + linewidth: float = 0.4, + zorder: float = 2.0, +) -> list[Rectangle]: + """Draw a grid of ``nx`` by ``ny`` square cells, e.g. a model grid. + + Args: + ax: Axes to draw on. + xy: Lower-left corner of the grid, in data coordinates. + nx: Cells along x. + ny: Cells along y. + cell: Cell edge, in data units. + fills: Face colour of single cells, keyed by ``(i, j)`` with ``i`` along x and ``j`` + along y from the bottom. + facecolor: Face colour of the other cells; a light tint of the blue of the house palette + by default. + edgecolor: Cell edge colour; a lighter tint of the same blue by default. + linewidth: Edge width (pt). + zorder: Drawing order. + + Returns: + The cell patches, column by column. + """ + base = NICE_COLORS["blue"] + fc = tint(base, 0.12) if facecolor is None else facecolor + ec = tint(base, 0.4) if edgecolor is None else edgecolor + fills = fills or {} + cells = [] + for i in range(nx): + for j in range(ny): + r = Rectangle( + (xy[0] + i * cell, xy[1] + j * cell), + cell, + cell, + facecolor=fills.get((i, j), fc), + edgecolor=ec, + linewidth=linewidth, + zorder=zorder, + ) + ax.add_patch(r) + cells.append(r) + return cells + + +def folder_icon( + ax: Axes, + xy: tuple[float, float], + width: float, + height: float, + *, + facecolor: Any = None, + edgecolor: Any = None, + linewidth: float = 0.6, + zorder: float = 3.0, +) -> Polygon: + """Draw a folder icon, to stand for a directory of stored results. + + Args: + ax: Axes to draw on. + xy: Lower-left corner, in data coordinates. + width: Icon width, in data units. + height: Icon height, in data units. + facecolor: Fill colour; a light tint of the theme's text colour by default. + edgecolor: Outline colour; the theme's text colour by default. + linewidth: Outline width (pt). + zorder: Drawing order. + + Returns: + The icon patch. + """ + th = get_theme() + x, y = xy + tab = height * 0.22 + pts = [ + (x, y), + (x, y + height), + (x + width * 0.4, y + height), + (x + width * 0.5, y + height - tab), + (x + width, y + height - tab), + (x + width, y), + ] + icon = Polygon( + pts, + closed=True, + facecolor=tint(th.text_color, 0.12) if facecolor is None else facecolor, + edgecolor=th.text_color if edgecolor is None else edgecolor, + linewidth=linewidth, + zorder=zorder, + ) + ax.add_patch(icon) + return icon diff --git a/tests/test_api.py b/tests/test_api.py index c284f0a..9762f71 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -31,6 +31,7 @@ def test_callables_are_callable(): "PALETTE_MUTED", "PALETTE_HIGH_CONTRAST", "CATEGORICAL", + "NICE_COLORS", "DEFAULTS", "TERNARY_PALETTES", "METRIC_NAMES", diff --git a/tests/test_schematic.py b/tests/test_schematic.py new file mode 100644 index 0000000..60e8ba2 --- /dev/null +++ b/tests/test_schematic.py @@ -0,0 +1,96 @@ +"""Contract of the concept-figure primitives: inch canvas, theme colours, drawn objects and checked save.""" + +from __future__ import annotations + +import matplotlib.pyplot as plt +import numpy as np +import pytest + +import nicefigs as nf +from nicefigs.artists import NICE_COLORS + + +def test_canvas_data_units_are_inches(): + fig, ax = nf.schematic_axes(3.0, 1.5) + assert tuple(fig.get_size_inches()) == (3.0, 1.5) + assert ax.get_xlim() == (0.0, 3.0) + assert ax.get_ylim() == (0.0, 1.5) + # one data unit is one inch on the page + x0, y0 = ax.transData.transform((0, 0)) + x1, y1 = ax.transData.transform((1, 1)) + assert (x1 - x0) / fig.dpi == pytest.approx(1.0) + assert (y1 - y0) / fig.dpi == pytest.approx(1.0) + + +def test_tint_and_shade_blend_toward_white_and_black(): + assert nf.tint("#336699", 0.0) == pytest.approx((1, 1, 1)) + assert nf.tint("#336699", 1.0) == pytest.approx(plt.matplotlib.colors.to_rgb("#336699")) + assert nf.shade("#336699", 1.0) == pytest.approx((0, 0, 0)) + assert nf.shade("#336699", 0.0) == pytest.approx(plt.matplotlib.colors.to_rgb("#336699")) + lighter = np.asarray(nf.tint("#336699", 0.3)) + assert (lighter > np.asarray(plt.matplotlib.colors.to_rgb("#336699"))).all() + + +def test_numbered_disc_defaults_to_the_house_orange_and_shows_its_number(): + fig, ax = nf.schematic_axes(1.0, 1.0) + disc = nf.numbered_disc(ax, (0.5, 0.5), 3) + assert disc.get_facecolor()[:3] == pytest.approx(plt.matplotlib.colors.to_rgb(NICE_COLORS["orange"])) + assert [t.get_text() for t in ax.texts] == ["3"] + + +def test_group_band_sits_below_what_it_groups_and_carries_its_title(): + fig, ax = nf.schematic_axes(2.0, 1.0) + box = nf.diagram_box(ax, (1.0, 0.5), 0.5, 0.3, text="x") + band = nf.group_band(ax, (0.2, 0.1), 1.6, 0.8, "streamed") + assert band.get_zorder() < box.get_zorder() + assert "streamed" in [t.get_text() for t in ax.texts] + assert nf.check_text_overlaps(fig) == [] + + +def test_label_pair_stacks_name_over_detail(): + fig, ax = nf.schematic_axes(2.0, 1.0) + name, detail = nf.label_pair(ax, (1.0, 0.5), "read", "from zarr") + assert name.get_position()[1] > detail.get_position()[1] + assert detail.get_fontsize() < name.get_fontsize() + + +def test_grid_cells_tile_the_requested_rectangle_and_colour_single_cells(): + fig, ax = nf.schematic_axes(2.0, 2.0) + cells = nf.grid_cells(ax, (0.5, 0.25), 4, 3, 0.2, fills={(1, 2): "red"}) + assert len(cells) == 12 + xs = sorted({round(c.get_x(), 6) for c in cells}) + ys = sorted({round(c.get_y(), 6) for c in cells}) + assert xs == pytest.approx([0.5, 0.7, 0.9, 1.1]) + assert ys == pytest.approx([0.25, 0.45, 0.65]) + red = [c for c in cells if c.get_facecolor()[:3] == (1.0, 0.0, 0.0)] + assert len(red) == 1 + assert (red[0].get_x(), red[0].get_y()) == pytest.approx((0.7, 0.65)) + + +def test_folder_icon_stays_inside_its_box(): + fig, ax = nf.schematic_axes(1.0, 1.0) + icon = nf.folder_icon(ax, (0.2, 0.3), 0.4, 0.3) + pts = np.asarray(icon.get_xy()) + assert pts[:, 0].min() == pytest.approx(0.2) + assert pts[:, 0].max() == pytest.approx(0.6) + assert pts[:, 1].min() == pytest.approx(0.3) + assert pts[:, 1].max() == pytest.approx(0.6) + + +def test_save_with_check_text_refuses_overlapping_text(tmp_path): + fig, ax = nf.schematic_axes(2.0, 1.0) + ax.text(1.0, 0.5, "first label") + ax.text(1.02, 0.5, "second label") + with pytest.raises(ValueError, match="text layout"): + nf.save(fig, tmp_path / "bad", formats=("png",), check_text=True) + assert not (tmp_path / "bad.png").exists() + + +def test_save_with_check_text_writes_a_clean_figure(tmp_path): + fig, ax = nf.schematic_axes(2.0, 1.0) + nf.diagram_box(ax, (1.0, 0.5), 1.0, 0.4, text="ok") + paths = nf.save(fig, tmp_path / "good", formats=("svg", "png"), check_text=True) + assert [p.suffix for p in paths] == [".svg", ".png"] + assert all(p.stat().st_size > 0 for p in paths) + # SVG text is converted to paths, so no element refers to an installed font + assert "