From a29157c71ac1aae97b20988597520817336fe0c3 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:06:43 -0500 Subject: [PATCH 1/4] test(docs): name empty and file-argument plot blocks An empty .. plot:: block now fails with its file and line rather than a ValueError from min(), and a block that names a script (.. plot:: x.py) fails, since the guide keeps every figure's code inline. Co-Authored-By: Claude Opus 5.5 --- tests/test_docs_plot_blocks.py | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/tests/test_docs_plot_blocks.py b/tests/test_docs_plot_blocks.py index 8ce3f9158..34ddeee0b 100644 --- a/tests/test_docs_plot_blocks.py +++ b/tests/test_docs_plot_blocks.py @@ -27,11 +27,15 @@ allow_module_level=True, ) -_DIRECTIVE = re.compile(r"^(\s*)\.\. plot::\s*$") +_DIRECTIVE = re.compile(r"^(\s*)\.\. plot::(.*)$") def _plot_blocks(path): - """Yield ``(line, code)`` for each inline ``.. plot::`` block in ``path``.""" + """Yield ``(line, argument, code)`` for each ``.. plot::`` block in ``path``. + + ``argument`` is the text after ``plot::``, empty for an inline block, and + ``code`` is the block's body without its options. + """ lines = path.read_text().splitlines() for i, line in enumerate(lines): match = _DIRECTIVE.match(line) @@ -46,15 +50,17 @@ def _plot_blocks(path): # Drop the directive's options, then the blank line after them. while body and (not body[0].strip() or body[0].strip().startswith(":")): body.pop(0) - width = min(len(b) - len(b.lstrip()) for b in body if b.strip()) - yield i + 1, "\n".join(b[width:] for b in body).strip() + "\n" + width = min((len(b) - len(b.lstrip()) for b in body if b.strip()), default=0) + code = "\n".join(b[width:] for b in body).strip() + yield i + 1, match.group(2).strip(), code + "\n" if code else "" -BLOCKS = [ - pytest.param(code, id=f"{path.relative_to(DOCS)}:{line}") +FOUND = [ + (f"{path.relative_to(DOCS)}:{line}", argument, code) for path in sorted(DOCS.rglob("*.rst")) - for line, code in _plot_blocks(path) + for line, argument, code in _plot_blocks(path) ] +BLOCKS = [pytest.param(code, id=where) for where, _, code in FOUND] def test_the_guide_has_plot_blocks(): @@ -62,9 +68,16 @@ def test_the_guide_has_plot_blocks(): assert BLOCKS +def test_every_plot_block_holds_its_code_inline(): + """No block names a script: the code a reader copies is on the page.""" + named = [f"{where}: plot:: {argument}" for where, argument, _ in FOUND if argument] + assert not named, named + + @pytest.mark.parametrize("code", BLOCKS) -def test_plot_block_runs_alone(code): +def test_plot_block_runs_alone(code, request): """A block runs with nothing defined beforehand and draws a figure.""" + assert code, f"{request.node.callspec.id}: the plot block is empty" try: exec(compile(code, "", "exec"), {"__name__": "__main__"}) assert plt.get_fignums(), "the block drew no figure" From bfdc0ca8d8520c1d5839ee55a52f4d00643f8242 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:11:45 -0500 Subject: [PATCH 2/4] docs(quickstart): state the plasma beta each column holds beta = n k_B T / (B^2 / 2 mu_0) = 2 mu_0 p_th / B^2, with p_th = rho w^2 / 2 from the component's thermal speed, as Plasma.beta computes it. Co-Authored-By: Claude Opus 5.5 --- docs/source/tutorial/quickstart.rst | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/source/tutorial/quickstart.rst b/docs/source/tutorial/quickstart.rst index a16f9888d..dedb50174 100644 --- a/docs/source/tutorial/quickstart.rst +++ b/docs/source/tutorial/quickstart.rst @@ -115,7 +115,11 @@ epoch 2022-10-09 01:47:01.234560 49800.0 Name: scalar, dtype: float64 -The plasma beta and the anisotropy ``R`` are dimensionless. ``R`` is the +The plasma beta and the anisotropy ``R`` are dimensionless. Each column of +``beta`` is the thermal pressure of that component over the magnetic pressure, +:math:`\beta = n k_B T / (B^2 / 2 \mu_0) = 2 \mu_0 p_{th} / B^2`, where +:math:`p_{th} = \rho w^2 / 2 = n k_B T` uses the parallel, perpendicular or +scalar thermal speed and :math:`B` is the field magnitude. ``R`` is the perpendicular over the parallel pressure; for one species it is :math:`(w_\perp / w_\parallel)^2`, so :math:`7^2 / 10^2 = 0.49` at the first time: From 0b7768f312c2e79ac756b21ae9b102683c733e1f Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:11:46 -0500 Subject: [PATCH 3/4] docs(readme): point to .pre-commit-config.yaml for the hook list Co-Authored-By: Claude Opus 5.5 --- README.rst | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/README.rst b/README.rst index 6c844f99c..f2130e438 100644 --- a/README.rst +++ b/README.rst @@ -110,12 +110,9 @@ Development pre-commit install - Each commit then runs ``ruff check``, ``ruff format`` and whitespace, - merge-conflict and large-file checks on staged Python files, ``doc8`` on - staged ``.rst``, ``.md`` and ``.py`` files, and the conventional-commit check - on the message. A commit that stages a ``.py`` file also runs the full test - suite with a coverage floor (``.claude/hooks/pre-commit-tests.sh``), and one - that stages a Python file under ``src/solarwindpy`` runs an import test. + Each commit then runs the hooks that ``.pre-commit-config.yaml`` lists, and + that file is the full list. Expect a commit that stages a ``.py`` file to + run the full test suite. 5. Build the documentation and fail on warnings: From 100ffb49cd3780a3eaa62d635dd8ff894d1e9a6c Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:13:29 -0500 Subject: [PATCH 4/4] docs(usage): share one BinnedData across plots A section after Bins builds one BinnedData and passes it to a count histogram, a mean-z histogram and a masked one, with a two-panel figure. It states the time and memory saved as measured: ten Hist2D of different z on 10^6 points, 0.28 s and 3 MB retained shared against 0.57 s and 21 MB private (Apple M3, median of three, tracemalloc). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 + docs/source/usage.rst | 88 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 20688635f..16295d2ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 and `Scatter`, their bins, `axnorm` normalizations, contour smoothing, distribution edges and `TeXlabel` labels, with figures drawn at build time by the code shown beside them. A test runs each of those code blocks on its own. +- The Usage guide shows how to share one `BinnedData` across several plots, with a + measurement of the time and memory it saves. ### Changed diff --git a/docs/source/usage.rst b/docs/source/usage.rst index 7d1eceb90..b75e6c63a 100644 --- a/docs/source/usage.rst +++ b/docs/source/usage.rst @@ -377,6 +377,94 @@ Edges given as an array are used as given: >>> Hist1D(v, nbins=[250, 350, 450, 550]).intervals["x"] IntervalIndex([(250, 350], (350, 450], (450, 550]], dtype='interval[int64, right]') +Share bins across plots +~~~~~~~~~~~~~~~~~~~~~~~ + +Plots over the same columns and bins can share one +:py:class:`~solarwindpy.plotting.binned.BinnedData`. It bins each column once, +when it is built, and stores the bin of every row as a small integer code. +Passed as ``nbins``, it gives a :py:class:`~solarwindpy.plotting.hist1d.Hist1D` +or :py:class:`~solarwindpy.plotting.hist2d.Hist2D` its bins and codes, so the +plot neither bins nor stores its own. A plot finds its columns by the names of +its inputs, so build the ``BinnedData`` from a DataFrame whose columns carry +those names, and pass that frame's columns. It takes explicit edges only: a +count or a rule would give each plot edges that depend on the rows it keeps. +``log`` names the columns binned in :math:`\log_{10}`, and the plots take +their log axes from it. A plot's ``mask`` keeps a subset of the rows on the +same bins: + +>>> import numpy as np +>>> import pandas as pd +>>> from solarwindpy.plotting.binned import BinnedData +>>> from solarwindpy.plotting.hist2d import Hist2D +>>> rng = np.random.default_rng(0) +>>> N = 10_000 +>>> fast = rng.random(N) < 0.3 +>>> speed = np.where(fast, rng.normal(650, 60, N), rng.normal(380, 50, N)) +>>> frame = pd.DataFrame( +... { +... "v": speed, +... "n": 8 * 10 ** (-0.0015 * (speed - 400) + rng.normal(0, 0.15, N)), +... "w": 0.1 * speed + rng.normal(0, 5, N), +... } +... ) +>>> edges = {"v": np.linspace(0, 1000, 51), "n": np.linspace(-1, 2.5, 36)} +>>> binned = BinnedData(frame, edges, log={"n": True}) +>>> binned.codes("v").dtype +dtype('int8') +>>> counts = Hist2D(frame["v"], frame["n"], nbins=binned) +>>> mean_w = Hist2D(frame["v"], frame["n"], frame["w"], nbins=binned) +>>> slow = Hist2D(frame["v"], frame["n"], nbins=binned, mask=frame["v"] < 500) +>>> counts.agg().index.equals(mean_w.agg().index) +True +>>> int(counts.agg().sum()), int(slow.agg().sum()) +(10000, 6947) + +Sharing saves time and memory. On an Apple M3 (Python 3.12, pandas 3.1, +NumPy 2.5), building and aggregating ten ``Hist2D`` of different ``z`` over +one 70 by 50 grid of :math:`10^6` points took 0.28 s with a shared +``BinnedData`` and 0.57 s when each plot binned its own columns, the median of +three runs. Measured with :mod:`tracemalloc`, which counts Python and NumPy +allocations, the ten plots and their aggregates kept 3 MB against 21 MB, and +the build peaked at 60 MB against 79 MB. + +Two plots on one ``BinnedData``, the counts and the mean thermal speed in each +cell: + +.. plot:: + + import numpy as np + import pandas as pd + import matplotlib.pyplot as plt + from solarwindpy.plotting.binned import BinnedData + from solarwindpy.plotting.hist2d import Hist2D + from solarwindpy.plotting.labels.base import TeXlabel + + rng = np.random.default_rng(0) + N = 20_000 + fast = rng.random(N) < 0.3 + v = np.where(fast, rng.normal(650, 60, N), rng.normal(380, 50, N)) + frame = pd.DataFrame( + { + "v": v, + "n": 8 * 10 ** (-0.0015 * (v - 400) + rng.normal(0, 0.15, N)), + "w": 0.1 * v + rng.normal(0, 5, N), + } + ) + edges = {"v": np.linspace(150, 950, 51), "n": np.linspace(-0.2, 1.8, 41)} + binned = BinnedData(frame, edges, log={"n": True}) + + counts = Hist2D(frame["v"], frame["n"], nbins=binned) + mean_w = Hist2D(frame["v"], frame["n"], frame["w"], nbins=binned) + mean_w.set_labels(z=TeXlabel(("w", "", "p1"))) + + fig, axes = plt.subplots(1, 2, figsize=(9, 4), sharey=True) + for h2, ax in zip([counts, mean_w], axes): + h2.set_labels(x=TeXlabel(("v", "", "p1")), y=TeXlabel(("n", "", "p1"))) + h2.make_plot(ax=ax) + axes[1].set_ylabel("") + fig.tight_layout() + Normalizations ~~~~~~~~~~~~~~