nicefigs 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
nicefigs/__init__.py ADDED
@@ -0,0 +1,259 @@
1
+ """nicefigs — publication-grade, modular plotting for geoscience.
2
+
3
+ Quickstart::
4
+
5
+ import nicefigs as nf
6
+
7
+ nf.set_theme("paper") # house style, globally
8
+ fig, ax, m = nf.map(lon, lat, values) # Robinson map + inset histogram
9
+ nf.save(fig, "figures/map", formats=("pdf", "png"))
10
+
11
+ Every helper takes an existing ``ax`` where it makes sense, so you can compose
12
+ nicefigs pieces into your own matplotlib layouts. The :mod:`nicefigs.data`
13
+ submodule provides deterministic example data for the gallery, docs, and tests.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from . import data
19
+ from .animation import animate_maps, render_animation, save_animation, stitch_frames
20
+ from .artists import ARTIST_PALETTES, HOCKNEY_CANYON, NICE, artist_cmap, artist_palette
21
+ from .bars import grouped as grouped_bars
22
+ from .bars import stacked as stacked_bars
23
+ from .colorbars import colorbar, inset_histogram_colorbar, make_mappable
24
+ from .colormaps2d import (
25
+ bivariate_cmap,
26
+ bivariate_legend,
27
+ flat_cmap,
28
+ flat_legend,
29
+ hsv_cmap,
30
+ hsv_legend,
31
+ )
32
+ from .comparison import model_comparison
33
+ from .figure import TextIssue, check_text_overlaps, figure, figure_size, save, subplots
34
+ from .hovmoller import hovmoller, hovmoller_panels
35
+ from .images import heatmap, image, image_grid, overlay_grid, pca_rgb
36
+ from .kde import agreement
37
+ from .lines import lines
38
+ from .maps import (
39
+ binned_map,
40
+ categorical_map,
41
+ draw_background,
42
+ from_xarray,
43
+ hatch_region,
44
+ make_map_axes,
45
+ map,
46
+ raster_map,
47
+ scatter_map,
48
+ tri_map,
49
+ )
50
+ from .palettes import (
51
+ CATEGORICAL,
52
+ CUSTOM_CMAPS,
53
+ DEFAULTS,
54
+ ROLES,
55
+ SCORECARD_DIVERGING_BOUNDARIES,
56
+ Categorical,
57
+ Role,
58
+ categorical,
59
+ cmap,
60
+ diverging_norm,
61
+ elevation_cmap,
62
+ qualitative,
63
+ robust_limits,
64
+ role_color,
65
+ role_style,
66
+ scorecard_diverging_cmap,
67
+ symmetric_limits,
68
+ )
69
+ from .panels import (
70
+ clean_title,
71
+ col_labels,
72
+ despine,
73
+ facet,
74
+ grid,
75
+ label_panels,
76
+ panel_label,
77
+ reference_line,
78
+ row_labels,
79
+ )
80
+ from .pareto import frontier, pareto
81
+ from .ranking import caterpillar
82
+ from .scatter import scatter
83
+ from .sections import cross_section, cross_section_panels, profile
84
+ from .spectra import spectrum
85
+ from .style import (
86
+ COLORS,
87
+ PALETTE_BRIGHT,
88
+ PALETTE_HIGH_CONTRAST,
89
+ PALETTE_MUTED,
90
+ THEMES,
91
+ Theme,
92
+ get_theme,
93
+ set_theme,
94
+ style,
95
+ )
96
+ from .tables import scorecard, skill_gap
97
+ from .taylor import taylor
98
+ from .ternary import (
99
+ TERNARY_PALETTES,
100
+ ternary_axes,
101
+ ternary_image,
102
+ ternary_legend,
103
+ ternary_map,
104
+ ternary_scatter,
105
+ )
106
+ from .ternary import color as ternary_color
107
+ from .timeseries import timeseries
108
+ from .units import (
109
+ DIRECTIONS,
110
+ METRIC_DIRECTION,
111
+ METRIC_NAMES,
112
+ axis_label,
113
+ fmt_pval,
114
+ fmt_val,
115
+ metric_label,
116
+ prettify_unit,
117
+ set_labels,
118
+ )
119
+ from .verification import (
120
+ precision_recall,
121
+ rank_histogram,
122
+ rank_histogram_panels,
123
+ reliability,
124
+ )
125
+
126
+ __version__ = "1.0.0"
127
+
128
+ __all__ = [
129
+ "data",
130
+ # style
131
+ "set_theme",
132
+ "style",
133
+ "Theme",
134
+ "THEMES",
135
+ "get_theme",
136
+ "COLORS",
137
+ "PALETTE_BRIGHT",
138
+ "PALETTE_MUTED",
139
+ "PALETTE_HIGH_CONTRAST",
140
+ # figure
141
+ "figure",
142
+ "subplots",
143
+ "figure_size",
144
+ "save",
145
+ "check_text_overlaps",
146
+ "TextIssue",
147
+ # panels
148
+ "grid",
149
+ "panel_label",
150
+ "label_panels",
151
+ "clean_title",
152
+ "despine",
153
+ "reference_line",
154
+ "facet",
155
+ "row_labels",
156
+ "col_labels",
157
+ # palettes
158
+ "cmap",
159
+ "categorical",
160
+ "Categorical",
161
+ "CATEGORICAL",
162
+ "DEFAULTS",
163
+ "elevation_cmap",
164
+ "qualitative",
165
+ "diverging_norm",
166
+ "robust_limits",
167
+ "symmetric_limits",
168
+ "scorecard_diverging_cmap",
169
+ "SCORECARD_DIVERGING_BOUNDARIES",
170
+ # role palette
171
+ "ROLES",
172
+ "Role",
173
+ "role_color",
174
+ "role_style",
175
+ # artist palettes
176
+ "artist_palette",
177
+ "artist_cmap",
178
+ "ARTIST_PALETTES",
179
+ "HOCKNEY_CANYON",
180
+ "NICE",
181
+ # colorbars
182
+ "colorbar",
183
+ "inset_histogram_colorbar",
184
+ "make_mappable",
185
+ # units
186
+ "axis_label",
187
+ "metric_label",
188
+ "set_labels",
189
+ "prettify_unit",
190
+ "fmt_val",
191
+ "fmt_pval",
192
+ "METRIC_NAMES",
193
+ "METRIC_DIRECTION",
194
+ # maps
195
+ "map",
196
+ "scatter_map",
197
+ "binned_map",
198
+ "categorical_map",
199
+ "raster_map",
200
+ "tri_map",
201
+ "make_map_axes",
202
+ "draw_background",
203
+ "from_xarray",
204
+ # images
205
+ "image",
206
+ "heatmap",
207
+ "overlay_grid",
208
+ "image_grid",
209
+ "pca_rgb",
210
+ # relational
211
+ "scatter",
212
+ "agreement",
213
+ "timeseries",
214
+ "lines",
215
+ "spectrum",
216
+ "model_comparison",
217
+ "pareto",
218
+ "frontier",
219
+ "caterpillar",
220
+ "grouped_bars",
221
+ "stacked_bars",
222
+ "scorecard",
223
+ "skill_gap",
224
+ "DIRECTIONS",
225
+ "cross_section",
226
+ "cross_section_panels",
227
+ "profile",
228
+ "hatch_region",
229
+ "taylor",
230
+ "hovmoller",
231
+ "hovmoller_panels",
232
+ # verification / generative-model evaluation
233
+ "reliability",
234
+ "rank_histogram",
235
+ "rank_histogram_panels",
236
+ "precision_recall",
237
+ # 2D colormaps
238
+ "bivariate_cmap",
239
+ "hsv_cmap",
240
+ "flat_cmap",
241
+ "bivariate_legend",
242
+ "hsv_legend",
243
+ "flat_legend",
244
+ "CUSTOM_CMAPS",
245
+ # ternary
246
+ "ternary_scatter",
247
+ "ternary_map",
248
+ "ternary_image",
249
+ "ternary_legend",
250
+ "ternary_axes",
251
+ "ternary_color",
252
+ "TERNARY_PALETTES",
253
+ # animation
254
+ "animate_maps",
255
+ "save_animation",
256
+ "render_animation",
257
+ "stitch_frames",
258
+ "__version__",
259
+ ]
nicefigs/animation.py ADDED
@@ -0,0 +1,327 @@
1
+ """Animations of map and image sequences, saved as MP4 (ffmpeg) or GIF (pillow).
2
+
3
+ :func:`animate_maps` builds an in-process :class:`~matplotlib.animation.FuncAnimation`
4
+ over a ``(T, H, W)`` stack with one fixed colour scale; save it with
5
+ :func:`save_animation`. :func:`render_animation` instead draws each frame with a
6
+ ``draw(i) -> Figure`` callback, optionally across processes, and stitches the frames
7
+ with :func:`stitch_frames`; use it for expensive or multi-panel frames.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import subprocess
14
+ from collections.abc import Callable, Sequence
15
+ from pathlib import Path
16
+ from typing import TYPE_CHECKING, Literal
17
+
18
+ import matplotlib.pyplot as plt
19
+ import numpy as np
20
+ from numpy.typing import ArrayLike
21
+
22
+ from .palettes import cmap as resolve_cmap
23
+ from .palettes import robust_limits
24
+ from .style import get_theme
25
+
26
+ if TYPE_CHECKING:
27
+ from matplotlib.animation import Animation, FuncAnimation
28
+ from matplotlib.axes import Axes
29
+ from matplotlib.figure import Figure
30
+
31
+
32
+ def animate_maps(
33
+ lon: ArrayLike,
34
+ lat: ArrayLike,
35
+ frames: ArrayLike,
36
+ *,
37
+ cmap: str = "inferno",
38
+ vmin: float | None = None,
39
+ vmax: float | None = None,
40
+ robust: bool = True,
41
+ diverging: bool = False,
42
+ projection: str = "robinson",
43
+ antarctica_cutoff: bool = True,
44
+ extent: Sequence[float] | None = None,
45
+ land: bool = True,
46
+ coastline: bool = True,
47
+ titles: Sequence[str] | None = None,
48
+ suptitle: str = "",
49
+ colorbar_label: str = "",
50
+ fps: float = 8,
51
+ width: str | float = "half",
52
+ aspect: float = 0.62,
53
+ as_map: bool = True,
54
+ ) -> tuple[Figure, Axes, FuncAnimation]:
55
+ """Animate a ``(T, H, W)`` stack of gridded fields with one fixed colour scale.
56
+
57
+ Args:
58
+ lon: Longitudes in degrees east, 1-D ``(W,)`` or 2-D ``(H, W)``.
59
+ lat: Latitudes in degrees north, 1-D ``(H,)`` or 2-D ``(H, W)``.
60
+ frames: Field stack of shape ``(T, H, W)``.
61
+ cmap: Colormap name; ``"inferno"`` becomes ``"RdBu_r"`` when ``diverging``.
62
+ vmin: Lower colour limit; computed over all frames if ``None``.
63
+ vmax: Upper colour limit; computed over all frames if ``None``.
64
+ robust: Use the 2nd/98th percentiles rather than min/max for missing limits.
65
+ diverging: Use limits symmetric about zero and a diverging colormap.
66
+ projection: Map projection name, as in :func:`nicefigs.make_map_axes`.
67
+ antarctica_cutoff: Crop the southern edge when ``extent`` is ``None``.
68
+ extent: ``(lon_min, lon_max, lat_min, lat_max)`` in degrees.
69
+ land: Draw the land background.
70
+ coastline: Draw coastlines.
71
+ titles: Per-frame titles (e.g. dates), one per frame.
72
+ suptitle: Figure title, constant across frames.
73
+ colorbar_label: Colorbar label.
74
+ fps: Playback rate in frames per second.
75
+ width: Figure width, a named width or inches (see :func:`nicefigs.figure_size`).
76
+ aspect: Figure height / width.
77
+ as_map: Draw on projected map axes; ``False`` draws a plain image.
78
+
79
+ Returns:
80
+ ``(fig, ax, anim)``; keep a reference to ``anim`` until it is saved.
81
+ """
82
+ from matplotlib.animation import FuncAnimation
83
+
84
+ th = get_theme()
85
+ frames = np.asarray(frames, dtype=float)
86
+ if cmap == "inferno" and diverging:
87
+ cmap = "RdBu_r"
88
+ if vmin is None or vmax is None:
89
+ if diverging:
90
+ from .palettes import symmetric_limits
91
+
92
+ lo, hi = symmetric_limits(frames)
93
+ elif robust:
94
+ lo, hi = robust_limits(frames)
95
+ else:
96
+ lo, hi = float(np.nanmin(frames)), float(np.nanmax(frames))
97
+ vmin = lo if vmin is None else vmin
98
+ vmax = hi if vmax is None else vmax
99
+
100
+ from .figure import figure_size
101
+
102
+ fig = plt.figure(figsize=figure_size(width, aspect=aspect), dpi=th.dpi)
103
+
104
+ lon = np.asarray(lon)
105
+ lat = np.asarray(lat)
106
+
107
+ if as_map:
108
+ from .maps import _apply_extent, draw_background, make_map_axes
109
+
110
+ ax, ccrs = make_map_axes(fig, 111, projection=projection)
111
+ draw_background(ax, ccrs, land=land, coastline=coastline)
112
+ _apply_extent(ax, ccrs, extent, antarctica_cutoff and extent is None)
113
+ tkw = {"transform": ccrs.PlateCarree()} if ccrs is not None else {}
114
+ mesh = ax.pcolormesh(
115
+ lon, lat, frames[0], cmap=resolve_cmap(cmap), vmin=vmin, vmax=vmax, shading="nearest", **tkw
116
+ )
117
+ is_mesh = True
118
+ else:
119
+ ax = fig.add_subplot(111)
120
+ ax.set_xticks([])
121
+ ax.set_yticks([])
122
+ mesh = ax.imshow(frames[0], cmap=resolve_cmap(cmap), vmin=vmin, vmax=vmax, animated=True)
123
+ is_mesh = False
124
+
125
+ from .colorbars import colorbar
126
+
127
+ colorbar(mesh, ax, label=colorbar_label)
128
+ ttl = ax.set_title(titles[0] if titles else "", fontsize=th.fs_title, loc="left", pad=3)
129
+ if suptitle:
130
+ fig.suptitle(suptitle, fontsize=th.fs_title)
131
+
132
+ def update(i: int) -> tuple:
133
+ if is_mesh:
134
+ mesh.set_array(frames[i].ravel())
135
+ else:
136
+ mesh.set_data(frames[i])
137
+ if titles:
138
+ ttl.set_text(titles[i])
139
+ return (mesh, ttl)
140
+
141
+ anim = FuncAnimation(fig, update, frames=len(frames), interval=1000 / fps, blit=False)
142
+ return fig, ax, anim
143
+
144
+
145
+ def save_animation(anim: Animation, path: str | os.PathLike, *, fps: float = 8, dpi: float = 120) -> Path:
146
+ """Save an animation as GIF (pillow) or, for any other suffix, as video via ffmpeg.
147
+
148
+ Args:
149
+ anim: Animation to save, e.g. from :func:`animate_maps`.
150
+ path: Output path; parent directories are created.
151
+ fps: Frames per second.
152
+ dpi: Resolution in dots per inch.
153
+
154
+ Returns:
155
+ The path written; a ``.gif`` next to ``path`` if ffmpeg is unavailable or fails.
156
+ """
157
+ p = Path(path)
158
+ p.parent.mkdir(parents=True, exist_ok=True)
159
+ if p.suffix.lower() == ".gif":
160
+ from matplotlib.animation import PillowWriter
161
+
162
+ anim.save(str(p), writer=PillowWriter(fps=fps), dpi=dpi)
163
+ else:
164
+ try:
165
+ from matplotlib.animation import FFMpegWriter
166
+
167
+ anim.save(str(p), writer=FFMpegWriter(fps=fps, bitrate=2400), dpi=dpi)
168
+ except (OSError, RuntimeError, subprocess.CalledProcessError):
169
+ gif = p.with_suffix(".gif")
170
+ from matplotlib.animation import PillowWriter
171
+
172
+ anim.save(str(gif), writer=PillowWriter(fps=fps), dpi=dpi)
173
+ return gif
174
+ return p
175
+
176
+
177
+ def stitch_frames(
178
+ frame_dir: str | os.PathLike,
179
+ path: str | os.PathLike,
180
+ *,
181
+ fps: float = 8,
182
+ pattern: str = "frame_%06d.png",
183
+ crf: int = 18,
184
+ preset: str = "medium",
185
+ ) -> Path:
186
+ """Stitch a directory of PNG frames into an MP4 (ffmpeg) or GIF (pillow).
187
+
188
+ An ``.mp4`` target is encoded with ffmpeg (libx264, yuv420p, padded to even
189
+ dimensions); any other suffix, or a missing or failing ffmpeg, produces a GIF.
190
+
191
+ Args:
192
+ frame_dir: Directory holding frames named per ``pattern``.
193
+ path: Output path; parent directories are created.
194
+ fps: Frames per second.
195
+ pattern: ``printf``-style frame filename with one integer field.
196
+ crf: ffmpeg constant rate factor; lower is higher quality.
197
+ preset: ffmpeg x264 speed preset.
198
+
199
+ Returns:
200
+ The path written; its suffix is ``.gif`` on the GIF fallback.
201
+
202
+ Raises:
203
+ FileNotFoundError: No frames match ``pattern`` (GIF path).
204
+ """
205
+ path = Path(path)
206
+ path.parent.mkdir(parents=True, exist_ok=True)
207
+ if path.suffix.lower() == ".mp4":
208
+ try:
209
+ subprocess.run(
210
+ [
211
+ "ffmpeg",
212
+ "-y",
213
+ "-framerate",
214
+ str(fps),
215
+ "-i",
216
+ os.path.join(str(frame_dir), pattern),
217
+ "-vf",
218
+ "pad=ceil(iw/2)*2:ceil(ih/2)*2",
219
+ "-c:v",
220
+ "libx264",
221
+ "-pix_fmt",
222
+ "yuv420p",
223
+ "-preset",
224
+ preset,
225
+ "-crf",
226
+ str(crf),
227
+ str(path),
228
+ ],
229
+ capture_output=True,
230
+ text=True,
231
+ check=True,
232
+ )
233
+ return path
234
+ except (FileNotFoundError, subprocess.CalledProcessError):
235
+ path = path.with_suffix(".gif")
236
+ return _stitch_gif(frame_dir, path, fps=fps, pattern=pattern)
237
+
238
+
239
+ def _stitch_gif(frame_dir: str | os.PathLike, path: Path, *, fps: float, pattern: str) -> Path:
240
+ import glob
241
+
242
+ from PIL import Image
243
+
244
+ path = Path(path)
245
+ glob_pat = pattern
246
+ if "%" in pattern: # frame_%06d.png -> frame_*.png
247
+ pre, _, post = pattern.partition("%")
248
+ glob_pat = pre + "*" + post[post.index("d") + 1 :] if "d" in post else pre + "*"
249
+ files = sorted(glob.glob(os.path.join(str(frame_dir), glob_pat)))
250
+ if not files:
251
+ raise FileNotFoundError(f"no frames matching {glob_pat!r} in {frame_dir}")
252
+ imgs = [Image.open(f).convert("RGB") for f in files]
253
+ imgs[0].save(path, save_all=True, append_images=imgs[1:], duration=max(int(1000 / fps), 1), loop=0)
254
+ return path
255
+
256
+
257
+ def _render_one(draw: Callable[[int], Figure], i: int, out_path: str, dpi: float, headless: bool) -> str:
258
+ """Draw frame ``i`` and save it to ``out_path``; module-level so it pickles to workers."""
259
+ import gc
260
+
261
+ if headless:
262
+ import matplotlib
263
+
264
+ matplotlib.use("Agg")
265
+ fig = draw(i)
266
+ fig.savefig(out_path, dpi=dpi)
267
+ plt.close(fig)
268
+ del fig
269
+ gc.collect()
270
+ return out_path
271
+
272
+
273
+ def render_animation(
274
+ draw: Callable[[int], Figure],
275
+ n_frames: int,
276
+ path: str | os.PathLike,
277
+ *,
278
+ fps: float = 8,
279
+ dpi: float = 120,
280
+ max_workers: int | None = None,
281
+ method: Literal["parallel", "sequential"] = "parallel",
282
+ pattern: str = "frame_%06d.png",
283
+ crf: int = 18,
284
+ preset: str = "medium",
285
+ ) -> Path:
286
+ """Render frames with a ``draw(i) -> Figure`` callback and stitch them into a video.
287
+
288
+ Each returned figure is saved and closed, then all frames are stitched with
289
+ :func:`stitch_frames`. Unlike :func:`animate_maps`, a frame may contain anything.
290
+
291
+ Args:
292
+ draw: Callable returning the figure for frame ``i``. With
293
+ ``method="parallel"`` it must be picklable: a module-level function or
294
+ a :func:`functools.partial` of one, not a lambda or closure.
295
+ n_frames: Number of frames.
296
+ path: Output path (``.mp4`` preferred, GIF fallback).
297
+ fps: Frames per second.
298
+ dpi: Frame resolution in dots per inch.
299
+ max_workers: Process cap for ``"parallel"``; default ``min(n_frames, cpus, 8)``.
300
+ method: ``"parallel"`` renders in a process pool, ``"sequential"`` in-process.
301
+ pattern: ``printf``-style frame filename, as in :func:`stitch_frames`.
302
+ crf: ffmpeg constant rate factor, as in :func:`stitch_frames`.
303
+ preset: ffmpeg x264 preset, as in :func:`stitch_frames`.
304
+
305
+ Returns:
306
+ The path written, as returned by :func:`stitch_frames`.
307
+ """
308
+ import tempfile
309
+
310
+ path = Path(path)
311
+ path.parent.mkdir(parents=True, exist_ok=True)
312
+ with tempfile.TemporaryDirectory(prefix="nicefigs_anim_") as td:
313
+ if method == "parallel" and n_frames > 1:
314
+ from concurrent.futures import ProcessPoolExecutor
315
+
316
+ mw = max_workers or min(n_frames, (os.cpu_count() or 4), 8)
317
+ with ProcessPoolExecutor(max_workers=mw) as ex:
318
+ futures = [
319
+ ex.submit(_render_one, draw, i, os.path.join(td, pattern % i), dpi, True)
320
+ for i in range(n_frames)
321
+ ]
322
+ for f in futures:
323
+ f.result()
324
+ else:
325
+ for i in range(n_frames):
326
+ _render_one(draw, i, os.path.join(td, pattern % i), dpi, False)
327
+ return stitch_frames(td, path, fps=fps, pattern=pattern, crf=crf, preset=preset)