Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,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

Expand Down
9 changes: 3 additions & 6 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
6 changes: 5 additions & 1 deletion docs/source/tutorial/quickstart.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
88 changes: 88 additions & 0 deletions docs/source/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
~~~~~~~~~~~~~~

Expand Down
29 changes: 21 additions & 8 deletions tests/test_docs_plot_blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -46,25 +50,34 @@ 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():
"""The collector finds blocks, so an empty parametrization cannot pass."""
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, "<plot block>", "exec"), {"__name__": "__main__"})
assert plt.get_fignums(), "the block drew no figure"
Expand Down
Loading