From f0e83792f559a215a66a0d83864816d15b55fe65 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 03:00:50 -0500 Subject: [PATCH 01/60] test(fitfunctions): name the fit uncertainty yerr, with yerr_min and yerr_max Target tests for renaming weights, wmin and wmax, marked xfail(strict=True) until the rename lands: yerr is stored as observations.raw.yerr, the two limits select inclusively, the old keywords raise TypeError, and TrendFit refuses yerr in trend_kwargs. Co-Authored-By: Claude Opus 5.5 --- tests/fitfunctions/test_core.py | 50 +++++++++++++++++++ .../fitfunctions/test_trend_fits_advanced.py | 16 ++++++ 2 files changed, 66 insertions(+) diff --git a/tests/fitfunctions/test_core.py b/tests/fitfunctions/test_core.py index cb3c690e7..b22a600ba 100644 --- a/tests/fitfunctions/test_core.py +++ b/tests/fitfunctions/test_core.py @@ -937,3 +937,53 @@ def test_xobs_that_is_not_1d_is_refused_with_its_shape(x): shape = re.escape(str(x.shape)) with pytest.raises(ValueError, match=rf"xobs must be 1-d.*{shape}"): LinearFit(x, 2.0 * x + 1.0, weights=np.full(x.shape, 0.5)) + + +# ============================================================================ +# yerr: the 1-sigma uncertainty of y, and its selection limits +# ============================================================================ + +_YERR_RENAME = pytest.mark.xfail( + strict=True, reason="weights, wmin and wmax are renamed yerr, yerr_min, yerr_max" +) + + +@_YERR_RENAME +def test_yerr_is_stored_as_the_observations_yerr(): + """``yerr`` is kept unchanged as ``observations.raw.yerr``. + + ON FAILURE: the code is wrong. + """ + raw = LinearFit([0, 1], [1, 2], yerr=[0.5, 0.25]).observations.raw + assert np.array_equal(raw.yerr, np.array([0.5, 0.25])) + + +@_YERR_RENAME +def test_yerr_min_and_yerr_max_keep_the_uncertainties_between_them(): + """``yerr_min`` and ``yerr_max`` keep ``yerr_min <= yerr <= yerr_max``. + + yerr = [1, 2, 3, 4] with limits 2 and 3 keeps x = 1 and 2: both bounds + are inclusive. + + ON FAILURE: the code is wrong. + """ + x = np.arange(4.0) + yerr = np.array([1.0, 2.0, 3.0, 4.0]) + lf = LinearFit(x, x, yerr=yerr, yerr_min=2.0, yerr_max=3.0) + assert np.array_equal(lf.observations.used.x, np.array([1.0, 2.0])) + assert np.array_equal(lf.observations.used.yerr, np.array([2.0, 3.0])) + + +@_YERR_RENAME +@pytest.mark.parametrize("old", ["weights", "wmin", "wmax"]) +def test_the_old_uncertainty_keywords_are_refused(old): + """``weights``, ``wmin`` and ``wmax`` are gone, with no alias. + + The author renamed them: elsewhere "weights" means 1/sigma, here the + value was always the 1-sigma uncertainty of y. + + ON FAILURE: the code is wrong. + """ + kwargs = {"weights": np.ones(2)} if old == "weights" else {old: 1.0} + with pytest.raises(TypeError, match=old): + LinearFit([0.0, 1.0], [1.0, 2.0], **kwargs) diff --git a/tests/fitfunctions/test_trend_fits_advanced.py b/tests/fitfunctions/test_trend_fits_advanced.py index 289010d31..bb42f5027 100644 --- a/tests/fitfunctions/test_trend_fits_advanced.py +++ b/tests/fitfunctions/test_trend_fits_advanced.py @@ -285,6 +285,22 @@ def test_make_fit_with_non_interval_index(self): # Verify the trend was created successfully assert isinstance(tf.trend, Line) + @pytest.mark.xfail(strict=True, reason="weights is renamed yerr") + def test_trend_kwargs_cannot_hold_yerr(self): + """``trend_kwargs`` holding ``yerr`` raises: TrendFit's ``yerr`` selects it. + + ON FAILURE: the code is wrong. + """ + with pytest.raises(ValueError, match="yerr selects the trend's uncertainties"): + TrendFit( + self.data_interval, + Gaussian, + Line, + y=MU, + yerr=SIGMA, + trend_kwargs=dict(yerr=np.ones(5)), + ) + def test_trend_weights_error(self): """Test TrendFit raises ValueError when trend weights are passed.""" # Passing weights should raise ValueError: yerr selects them From 73c7504985c155e0d7ed6946ab3868aace868501 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 03:05:56 -0500 Subject: [PATCH 02/60] refactor(fitfunctions)!: rename the fit uncertainty weights to yerr FitFunction took the 1-sigma uncertainty of y as weights, with wmin and wmax limiting it. Elsewhere weights usually means 1/sigma (lmfit, astropy, numpy.polyfit w), so the name invited passing the inverse. It is now yerr, with yerr_min and yerr_max, matching TrendFit's yerr; set_fit_obs, the observations namedtuple field (w -> yerr), FFPlot, TrendFit's pass-through and its trend_kwargs guard, docstrings, CONTRIBUTING, tests and the quickstart follow. No alias: the old keywords raise TypeError. BREAKING CHANGE: weights=, wmin= and wmax= are yerr=, yerr_min= and yerr_max=; observations.used.w and .raw.w are .yerr. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 ++ docs/source/tutorial/quickstart.rst | 4 +- src/solarwindpy/fitfunctions/CONTRIBUTING.md | 15 +- src/solarwindpy/fitfunctions/__init__.py | 9 +- src/solarwindpy/fitfunctions/core.py | 113 +++++++-------- src/solarwindpy/fitfunctions/plots.py | 23 +-- src/solarwindpy/fitfunctions/trend_fits.py | 28 ++-- tests/fitfunctions/test_core.py | 133 +++++++++--------- tests/fitfunctions/test_degeneracy.py | 8 +- tests/fitfunctions/test_exponentials.py | 2 +- tests/fitfunctions/test_hinge.py | 6 +- tests/fitfunctions/test_lines.py | 2 +- tests/fitfunctions/test_plots.py | 32 ++--- tests/fitfunctions/test_power_laws.py | 2 +- tests/fitfunctions/test_trend_fits.py | 2 +- .../fitfunctions/test_trend_fits_advanced.py | 14 -- tests/fitfunctions/test_trend_results.py | 8 +- 17 files changed, 205 insertions(+), 207 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 55ee9a030..8785924e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Changed - BREAKING CHANGES + +- A fit's measurement uncertainty is named `yerr`. Every `FitFunction` subclass takes + `yerr=` in place of `weights=`, and `yerr_min=` and `yerr_max=` in place of `wmin=` and `wmax=`; + `set_fit_obs` takes the same names. The value is unchanged: the 1-sigma uncertainty of each `y`, + as `scipy.optimize.curve_fit` takes `sigma` (elsewhere "weights" usually means 1/sigma). The + observations' third field is `yerr` (`fit.observations.used.yerr` and `.raw.yerr`, formerly + `.w`). `TrendFit` now refuses `yerr` in `trend_kwargs`, since its own `yerr=` selects the + trend's uncertainties. No aliases are kept; the old keywords raise `TypeError`. To migrate, + rename the keywords: `Line(x, y, weights=s, wmin=a)` becomes `Line(x, y, yerr=s, yerr_min=a)`. + ### Added - A quickstart page that runs end to end on `solarwindpy.examples.load_plasma`: the diff --git a/docs/source/tutorial/quickstart.rst b/docs/source/tutorial/quickstart.rst index ae77f7227..5396e02a8 100644 --- a/docs/source/tutorial/quickstart.rst +++ b/docs/source/tutorial/quickstart.rst @@ -183,11 +183,11 @@ random number generator: uncertainty is the square root of a diagonal element of the parameter covariance ``pcov``, and ``pcov`` is always rescaled by the fit's robust reduced chi-squared; ``make_fit(absolute_sigma=True)`` raises ``NotImplementedError``. -Measurement uncertainties enter through the ``weights`` argument, the 1-sigma +Measurement uncertainties enter through the ``yerr`` argument, the 1-sigma uncertainties of ``y``, one per observation. ``chisq_dof`` has two kinds. ``linear`` is the sum of squared residuals, -divided by ``weights`` when given, per degree of freedom. ``robust`` is the +divided by ``yerr`` when given, per degree of freedom. ``robust`` is the same sum after the fit's loss function (``make_fit`` uses a Huber loss by default), and it is the one that rescales ``pcov``: diff --git a/src/solarwindpy/fitfunctions/CONTRIBUTING.md b/src/solarwindpy/fitfunctions/CONTRIBUTING.md index d4b045158..9e86622c2 100644 --- a/src/solarwindpy/fitfunctions/CONTRIBUTING.md +++ b/src/solarwindpy/fitfunctions/CONTRIBUTING.md @@ -216,7 +216,8 @@ Every FitFunction MUST have tests in categories E1-E5. E6-E7 are recommended whe ### 4.2 Fixture Pattern -All fixtures MUST return `(x, y, w, true_params)`: +All fixtures MUST return `(x, y, yerr, true_params)`, where `yerr` is the 1-sigma +uncertainty of each `y`: ```python @pytest.fixture @@ -225,8 +226,8 @@ def clean_gaussian_data(): true_params = {"mu": 5.0, "sigma": 1.0, "A": 10.0} x = np.linspace(0, 10, 200) y = gaussian(x, **true_params) - w = np.ones_like(x) - return x, y, w, true_params + yerr = np.ones_like(x) + return x, y, yerr, true_params @pytest.fixture @@ -239,15 +240,15 @@ def noisy_gaussian_data(): x = np.linspace(0, 10, 200) y_true = gaussian(x, **true_params) y = y_true + rng.normal(0, noise_std, len(x)) - w = np.ones_like(x) / noise_std + yerr = np.full_like(x, noise_std) - return x, y, w, true_params + return x, y, yerr, true_params ``` **Conventions:** - Random seed: `np.random.default_rng(42)` for reproducibility - Noise level: 3-5% of signal amplitude -- Weights: `w = np.ones_like(x) / noise_std` for noisy data +- Uncertainties: `yerr = np.full_like(x, noise_std)` for noisy data ### 4.3 Assertion Patterns @@ -297,7 +298,7 @@ def test_gaussian_recovers_parameters(true_params): @pytest.mark.parametrize("cls", [Line, LineXintercept]) def test_make_fit_success(cls, simple_linear_data): """All line classes should fit successfully.""" - x, y, w, _ = simple_linear_data + x, y, yerr, _ = simple_linear_data fit = cls(x, y) fit.make_fit() assert np.isfinite(fit.popt['m']) diff --git a/src/solarwindpy/fitfunctions/__init__.py b/src/solarwindpy/fitfunctions/__init__.py index 659f6f4ae..bb86c4e13 100644 --- a/src/solarwindpy/fitfunctions/__init__.py +++ b/src/solarwindpy/fitfunctions/__init__.py @@ -21,7 +21,8 @@ Every subclass takes ``(xobs, yobs, **kwargs)``. The keyword arguments of :class:`~solarwindpy.fitfunctions.core.FitFunction` select which observations enter the fit (``xmin``, ``xmax``, ``xoutside``, ``ymin``, ``ymax``, -``youtside``, ``wmin``, ``wmax``) and supply 1-sigma ``weights``. A few +``youtside``, ``yerr_min``, ``yerr_max``) and supply 1-sigma uncertainties +``yerr``. A few subclasses add their own, such as the ``guess_xh`` hinge position that every subclass of :class:`~solarwindpy.fitfunctions.hinge.Hinge` takes. @@ -38,10 +39,10 @@ - The default loss is ``"huber"`` with ``f_scale=0.1``, method ``"trf"``; ``loss``, ``f_scale``, ``method``, ``bounds``, ``p0`` and other :func:`~scipy.optimize.least_squares` keywords pass through ``make_fit``. -- ``weights`` are treated as :func:`scipy.optimize.curve_fit` treats a 1-D +- ``yerr`` is treated as :func:`scipy.optimize.curve_fit` treats a 1-D ``sigma``: one 1-sigma uncertainty per observation, in the shape of the - 1-D ``xobs``. A covariance matrix is not supported; weights of any other - shape raise :class:`~solarwindpy.fitfunctions.core.InvalidParameterError`. + 1-D ``xobs``. A covariance matrix is not supported; ``yerr`` of any other + shape raises :class:`~solarwindpy.fitfunctions.core.InvalidParameterError`. ``absolute_sigma=True`` raises ``NotImplementedError``. - The covariance is the pseudo-inverse of :math:`J^T J` from the final Jacobian, scaled by the robust :math:`\chi^2_\nu`; ``psigma`` is the square diff --git a/src/solarwindpy/fitfunctions/core.py b/src/solarwindpy/fitfunctions/core.py index 6a0f54eeb..878396a5d 100644 --- a/src/solarwindpy/fitfunctions/core.py +++ b/src/solarwindpy/fitfunctions/core.py @@ -49,7 +49,7 @@ from .tex_info import TeXinfo from .plots import FFPlot -_Observations = namedtuple("_Observations", "x,y,w") +_Observations = namedtuple("_Observations", "x,y,yerr") _UsedRawObs = namedtuple("_UsedRawObs", "used,raw,tk_observed") _InitialGuessInfo = namedtuple("_InitialGuessInfo", "p0,bounds") _ChisqPerDegreeOfFreedom = namedtuple("_ChisqPerDegreeOfFreedom", "linear,robust") @@ -256,21 +256,23 @@ class FitFunction(ABC, metaclass=FitFunctionMeta): youtside : tuple(float, float), optional Include only data outside this range. Format: (lower, upper) where lower < upper. - weights : array-like, optional + yerr : array-like, optional 1-sigma uncertainties of the y values, used for weighted least squares fitting: one per observation, in xobs's - shape. A covariance matrix is not supported; weights of - any other shape raise InvalidParameterError. - wmin : float, optional - Lower weight limit. Observations with smaller weights - are excluded from the fit. - wmax : float, optional - Upper weight limit. Observations with larger weights - are excluded from the fit. + shape. Each residual is weighted by 1/yerr, as + :func:`scipy.optimize.curve_fit` weights by ``sigma``. A + covariance matrix is not supported; yerr of any other + shape raises InvalidParameterError. + yerr_min : float, optional + Lower limit on yerr used in fitting, inclusive (>=). + Observations with smaller uncertainties are excluded. + yerr_max : float, optional + Upper limit on yerr used in fitting, inclusive (<=). + Observations with larger uncertainties are excluded. logy : bool, default False - Whether to interpret y on a log10 scale. Weight selection - then uses w/(y*ln(10)) for proper error propagation in - log space. + Whether to interpret y on a log10 scale. The yerr_min and + yerr_max selection then uses yerr/(y*ln(10)), the + uncertainty of log10(y). See Also -------- @@ -328,9 +330,9 @@ def __init__( ymin=None, ymax=None, youtside=None, - weights=None, - wmin=None, - wmax=None, + yerr=None, + yerr_min=None, + yerr_max=None, logy=False, ): # Documented in the class docstring (see FitFunctionMeta). @@ -338,22 +340,22 @@ def __init__( self._set_argnames() self._forget_fit() - if weights is None: - assert wmin is None - assert wmax is None + if yerr is None: + assert yerr_min is None + assert yerr_max is None self.set_fit_obs( xobs, yobs, - weights, + yerr, xmin=xmin, xmax=xmax, xoutside=xoutside, ymin=ymin, ymax=ymax, youtside=youtside, - wmin=wmin, - wmax=wmax, + yerr_min=yerr_min, + yerr_max=yerr_max, logy=logy, ) @@ -845,8 +847,8 @@ def TeX_info(self): """ return self._fitted("_TeX_info") - def _clean_raw_obs(self, xobs, yobs, weights): - r"""Set the raw x- and y-values along with weights for the fit. + def _clean_raw_obs(self, xobs, yobs, yerr): + r"""Set the raw x- and y-values along with their uncertainties for the fit. Doesn't account for extrema, finite data, etc. @@ -855,12 +857,12 @@ def _clean_raw_obs(self, xobs, yobs, weights): ValueError If ``xobs`` is not 1-d: every model is a function of one variable. InvalidParameterError - If ``yobs`` or ``weights`` does not match ``xobs``'s shape. + If ``yobs`` or ``yerr`` does not match ``xobs``'s shape. """ xobs = np.asarray(xobs) yobs = np.asarray(yobs) - if weights is not None: - weights = np.asarray(weights) + if yerr is not None: + yerr = np.asarray(yerr) if xobs.ndim != 1: raise ValueError( @@ -871,13 +873,13 @@ def _clean_raw_obs(self, xobs, yobs, weights): raise InvalidParameterError(f"""xobs and yobs must have the same shape. xobs: {xobs.shape}, yobs: {yobs.shape}""") - if weights is not None and weights.shape != xobs.shape: - raise InvalidParameterError(f"""weights and xobs must have the same shape: \ -weights holds one 1-sigma uncertainty per observation, in xobs's shape, and a \ + if yerr is not None and yerr.shape != xobs.shape: + raise InvalidParameterError(f"""yerr and xobs must have the same shape: \ +yerr holds one 1-sigma uncertainty per observation, in xobs's shape, and a \ covariance matrix is not supported. -weights: {weights.shape}, xobs: {xobs.shape}""") +yerr: {yerr.shape}, xobs: {xobs.shape}""") - return xobs, yobs, weights + return xobs, yobs, yerr def _build_one_obs_mask(self, axis, x, xmin, xmax): """Build observation mask with in-place operations for efficiency.""" @@ -1040,15 +1042,15 @@ def set_fit_obs( self, xobs_raw, yobs_raw, - weights_raw, + yerr_raw, xmin=None, xmax=None, xoutside=None, ymin=None, ymax=None, youtside=None, - wmin=None, - wmax=None, + yerr_min=None, + yerr_max=None, logy=False, ): r"""Set the observed values we'll actually use in the fit. @@ -1057,7 +1059,8 @@ def set_fit_obs( All boundaries are inclusive <= or >=. - If logy, then make selection of `wmin` and `wmax` based on :math:`w/(y \ln(10))`. + If logy, then make selection of ``yerr_min`` and ``yerr_max`` based on + :math:`\sigma_y/(y \ln(10))`, the uncertainty of :math:`\log_{10} y`. Raises ------ @@ -1065,9 +1068,7 @@ def set_fit_obs( If ``xobs_raw`` is not 1-d. """ - xobs_raw, yobs_raw, weights_raw = self._clean_raw_obs( - xobs_raw, yobs_raw, weights_raw - ) + xobs_raw, yobs_raw, yerr_raw = self._clean_raw_obs(xobs_raw, yobs_raw, yerr_raw) xmask = self._build_one_obs_mask("xobs", xobs_raw, xmin, xmax) ymask = self._build_one_obs_mask("yobs", yobs_raw, ymin, ymax) @@ -1075,25 +1076,27 @@ def set_fit_obs( yout_mask = self._build_outside_mask("yobs", yobs_raw, youtside) mask = xmask & ymask & xout_mask & yout_mask - if weights_raw is not None: - weights_for_mask = weights_raw + if yerr_raw is not None: + yerr_for_mask = yerr_raw if logy: - # Enables picking weights based on normalized scale for log stuff - weights_for_mask = weights_for_mask / (yobs_raw * np.log(10)) + # Select on the uncertainty of log10(y). + yerr_for_mask = yerr_for_mask / (yobs_raw * np.log(10)) - wmask = self._build_one_obs_mask("weights", weights_for_mask, wmin, wmax) - mask = mask & wmask + yerr_mask = self._build_one_obs_mask( + "yerr", yerr_for_mask, yerr_min, yerr_max + ) + mask = mask & yerr_mask xobs = xobs_raw[mask] yobs = yobs_raw[mask] - weights = None - if weights_raw is not None: - weights = weights_raw[mask] + yerr = None + if yerr_raw is not None: + yerr = yerr_raw[mask] - used = _Observations(xobs, yobs, weights) + used = _Observations(xobs, yobs, yerr) self._check_used_obs(used) - raw = _Observations(xobs_raw, yobs_raw, weights_raw) + raw = _Observations(xobs_raw, yobs_raw, yerr_raw) usedrawobs = _UsedRawObs(used, raw, mask) self._observations = usedrawobs @@ -1108,7 +1111,7 @@ def _check_used_obs(self, used): Parameters ---------- used : _Observations - The ``(x, y, w)`` selected for the fit. + The ``(x, y, yerr)`` selected for the fit. """ def _run_least_squares(self, **kwargs): @@ -1146,10 +1149,10 @@ def _run_least_squares(self, **kwargs): xdata = self.observations.used.x ydata = self.observations.used.y - sigma = self.observations.used.w + sigma = self.observations.used.yerr # Adapted from `curve_fit` line 749 (20200527): 1-sigma uncertainties - # weight the residuals by 1/sigma. set_fit_obs selects x, y and w with + # weight the residuals by 1/sigma. set_fit_obs selects x, y and yerr with # one mask after _clean_raw_obs made their shapes equal, so sigma is # 1-d with one entry per used observation. transform = None if sigma is None else 1.0 / np.asarray(sigma) @@ -1186,7 +1189,7 @@ def _calc_popt_pcov_psigma_chisq(self, res, p0): xdata = self.observations.used.x ydata = self.observations.used.y - sigma = self.observations.used.w + sigma = self.observations.used.yerr # The following is from `curve_fit` line 801 and following. (20200625) # `cost` is the robust loss, i.e. residuals passed through loss funciton. @@ -1371,7 +1374,7 @@ def _prepare_fit(self, kwargs): def make_fit(self, **kwargs): """Fit the function with the independent `xobs` and dependent `yobs`. - Uses `least_squares`, but treats weights as in `curve_fit`. The + Uses `least_squares`, but treats ``yerr`` as `curve_fit` treats ``sigma``. The outcome is :attr:`results`, whether the fit succeeds or fails. Parameters diff --git a/src/solarwindpy/fitfunctions/plots.py b/src/solarwindpy/fitfunctions/plots.py index 64043cee2..ff883382d 100644 --- a/src/solarwindpy/fitfunctions/plots.py +++ b/src/solarwindpy/fitfunctions/plots.py @@ -288,18 +288,18 @@ def _plot_observations(self, kind, ax, plot_window, edge_kwargs, kwargs): obs = getattr(self.observations, kind) x = obs.x y = obs.y - w = obs.w + yerr = obs.yerr if not plot_window: - plotted = ax.errorbar(x, y, yerr=w, **style) + plotted = ax.errorbar(x, y, yerr=yerr, **style) self._format_hax(ax) return ax, plotted - if w is None: + if yerr is None: logging.getLogger().warning( - "No weights. Need weights to plot a window for FitFunction. Setting w to 0." + "No yerr. Need yerr to plot a window for FitFunction. Setting yerr to 0." ) - w = 0 + yerr = 0 window_kwargs = mpl.cbook.normalize_kwargs( window_kwargs, mpl.collections.Collection @@ -309,8 +309,8 @@ def _plot_observations(self, kind, ax, plot_window, edge_kwargs, kwargs): line = ax.plot(x, y, **style) - y1 = y - w - y2 = y + w + y1 = y - yerr + y2 = y + yerr window = ax.fill_between( x, y1, @@ -331,14 +331,14 @@ def plot_raw(self, ax=None, plot_window=True, edge_kwargs=None, **kwargs): r"""Plot the raw observations. Plot from ``observations.raw.x``, ``observations.raw.y``, and - ``observations.raw.w``. + ``observations.raw.yerr``. Parameters ---------- ax : matplotlib.axes.Axes, optional Axes to draw on. If None, a new figure and axes are created. plot_window : bool, default True - If True, draw a line with a ``y +- w`` window. Otherwise draw + If True, draw a line with a ``y +- yerr`` window. Otherwise draw error bars. edge_kwargs : dict, optional If not None, draw the window's edges as lines with these @@ -362,7 +362,7 @@ def plot_used(self, ax=None, plot_window=True, edge_kwargs=None, **kwargs): r"""Plot the observations used in the fit. Plot from ``observations.used.x``, ``observations.used.y``, and - ``observations.used.w``. Parameters and returns are those of + ``observations.used.yerr``. Parameters and returns are those of :py:meth:`plot_raw`; unless ``markevery`` is given, a marker is drawn on every :math:`10^{\lfloor \log_{10} N \rfloor - 1}`-th of the :math:`N` used points. @@ -661,7 +661,8 @@ def set_labels(self, **kwargs): def set_log(self, **kwargs): r"""Set :py:class:`~solarwindpy.plotting.base.LogAxes`. - Only used for determining if weights should be :math:`w/(y \ln(10))`. + Only used for determining if the uncertainties should be + :math:`\sigma_y/(y \ln(10))`. """ log = self._log._asdict() for k, v in kwargs.items(): diff --git a/src/solarwindpy/fitfunctions/trend_fits.py b/src/solarwindpy/fitfunctions/trend_fits.py index fc211c1d3..0e17e4050 100644 --- a/src/solarwindpy/fitfunctions/trend_fits.py +++ b/src/solarwindpy/fitfunctions/trend_fits.py @@ -50,7 +50,7 @@ class TrendFit(object): The :attr:`bin_results` column the trend fits, as ``(P, K)``: for example ``("mu", "value")``. Required: it is the scientific choice. yerr : tuple or None - The :attr:`bin_results` column giving the trend's 1-sigma weights, for + The :attr:`bin_results` column giving the trend's 1-sigma uncertainties, for example ``("sigma", "value")`` (each column's width) or ``("mu", "uncertainty")`` (the fitted uncertainty of ``mu``). None fits the trend unweighted. Required, like ``y``. @@ -60,7 +60,7 @@ class TrendFit(object): bin_kwargs, trend_kwargs : dict, optional Passed to the constructor of each bin fit and of the trend fit, for example ``xmax=`` or ``guess_xh=``. ``trend_kwargs`` cannot hold - ``weights``, which ``yerr`` selects. + ``yerr``, which the ``yerr`` argument selects. Raises ------ @@ -107,8 +107,10 @@ def __init__( if not (isinstance(cls, type) and issubclass(cls, core.FitFunction)): raise TypeError(f"{name} must be a FitFunction subclass, not {cls!r}") trend_kwargs = dict(trend_kwargs or {}) - if "weights" in trend_kwargs: - raise ValueError("yerr selects the trend's weights; drop weights=.") + if "yerr" in trend_kwargs: + raise ValueError( + "yerr selects the trend's uncertainties; drop yerr= from trend_kwargs." + ) self._agged = agged self._bin_function = bin_function @@ -165,7 +167,7 @@ def y(self): @property def yerr(self): - r"""The :attr:`bin_results` column of the trend's weights, or None.""" + r"""The :attr:`bin_results` column of the trend's uncertainties, or None.""" return self._yerr @property @@ -312,9 +314,9 @@ def make_fit(self, bin_fit_kwargs=None, trend_fit_kwargs=None): results.index = self.agged.columns y = self._column(results, self.y) - w = None if self.yerr is None else self._column(results, self.yerr) + yerr = None if self.yerr is None else self._column(results, self.yerr) trend = self.trend_function( - self._trend_x(), y, weights=w, **self._trend_kwargs + self._trend_x(), y, yerr=yerr, **self._trend_kwargs ) results[("in_trend", "")] = trend.observations.tk_observed @@ -422,7 +424,7 @@ def plot_bin_results( x = x[tk] y = results.loc[:, self.y] - w = None if self.yerr is None else results.loc[:, self.yerr] + yerr = None if self.yerr is None else results.loc[:, self.yerr] window_kwargs = kwargs.pop("window_kwargs", dict()) @@ -434,7 +436,7 @@ def plot_bin_results( label = kwargs.pop("label", "1D Fits") if plot_window: - if w is None: + if yerr is None: raise ValueError("plot_window needs yerr; this TrendFit has yerr=None.") window_kwargs = mpl.cbook.normalize_kwargs( @@ -449,8 +451,8 @@ def plot_bin_results( window = ax.fill_between( x, - y - w, - y + w, + y - yerr, + y + yerr, color=window_color, alpha=window_alpha, **window_kwargs, @@ -464,7 +466,7 @@ def plot_bin_results( plotted = ax.errorbar( x=x, y=y, - yerr=w, + yerr=yerr, color=color, linestyle=linestyle, label=label, @@ -473,7 +475,7 @@ def plot_bin_results( pl, cl, bl = plotted - if w is not None: + if yerr is not None: bl[0].set_linestyle(linestyle) return plotted diff --git a/tests/fitfunctions/test_core.py b/tests/fitfunctions/test_core.py index b22a600ba..cf3c52723 100644 --- a/tests/fitfunctions/test_core.py +++ b/tests/fitfunctions/test_core.py @@ -47,25 +47,25 @@ def TeX_function(self): def test_mismatched_observation_lengths_raise_invalid_parameter_error(): - """``y`` or ``weights`` of a different length than ``x`` is rejected. + """``y`` or ``yerr`` of a different length than ``x`` is rejected. ON FAILURE: the code is wrong. """ with pytest.raises(InvalidParameterError, match="xobs and yobs"): LinearFit([0, 1], [1]) - with pytest.raises(InvalidParameterError, match="weights and xobs"): - LinearFit([0, 1], [1, 2], weights=[1]) + with pytest.raises(InvalidParameterError, match="yerr and xobs"): + LinearFit([0, 1], [1, 2], yerr=[1]) def test_raw_observations_are_the_inputs_as_arrays(): - """The raw observations are the given x, y and weights, unchanged. + """The raw observations are the given x, y and yerr, unchanged. ON FAILURE: the code is wrong. """ - raw = LinearFit([0, 1], [1, 2], weights=[1, 1]).observations.raw + raw = LinearFit([0, 1], [1, 2], yerr=[1, 1]).observations.raw assert np.array_equal(raw.x, np.array([0, 1])) assert np.array_equal(raw.y, np.array([1, 2])) - assert np.array_equal(raw.w, np.array([1, 1])) + assert np.array_equal(raw.yerr, np.array([1, 1])) @pytest.mark.parametrize( @@ -104,7 +104,7 @@ def test_set_fit_obs_combined_masks(): x = np.array([0, 1, 2, 3, 4], dtype=float) y = np.array([10, 20, 30, 40, 50], dtype=float) w = np.array([0.5, 1, 2, 3, 4], dtype=float) - lf = LinearFit(x, y, weights=w) + lf = LinearFit(x, y, yerr=w) lf.set_fit_obs( x, y, @@ -113,13 +113,13 @@ def test_set_fit_obs_combined_masks(): xmax=3, ymin=15, ymax=45, - wmin=0.02, - wmax=0.03, + yerr_min=0.02, + yerr_max=0.03, logy=True, ) assert np.array_equal(lf.observations.used.x, np.array([1.0, 2.0])) assert np.array_equal(lf.observations.used.y, np.array([20.0, 30.0])) - assert np.array_equal(lf.observations.used.w, np.array([1.0, 2.0])) + assert np.array_equal(lf.observations.used.yerr, np.array([1.0, 2.0])) assert np.array_equal( lf.observations.tk_observed, np.array([False, True, True, False, False]) ) @@ -157,15 +157,15 @@ def test_make_fit_defaults_match_documented_least_squares_call(line_with_outlier """make_fit's result equals scipy's least_squares with the documented defaults. The ``make_fit`` docstring lists method="trf", loss="huber", - max_nfev=10000, f_scale=0.1, and weights act as ``sigma`` (residuals - divided by ``w``). The same problem solved by calling scipy directly with + max_nfev=10000, f_scale=0.1, and ``yerr`` acts as ``sigma`` (residuals + divided by ``yerr``). The same problem solved by calling scipy directly with those settings is the independent route. The outlier makes the huber and linear solutions differ by ~0.6 in slope, so a changed default loss fails. ON FAILURE: the code is wrong. """ x, y, w = line_with_outlier - lf = LinearFit(x, y, weights=w) + lf = LinearFit(x, y, yerr=w) lf.make_fit() p0 = np.array(lf.p0) documented = _direct_least_squares( @@ -187,7 +187,7 @@ def test_make_fit_records_the_initial_guess_and_rejects_args(simple_linear_data) ON FAILURE: the code is wrong. """ x, y, w = simple_linear_data - lf = LinearFit(x, y, weights=w) + lf = LinearFit(x, y, yerr=w) lf.make_fit() guess = lf.initial_guess_info assert [guess["m"].p0, guess["b"].p0] == list(lf.p0) @@ -220,7 +220,7 @@ def test_make_fit_success_failure(simple_linear_data, small_n): ON FAILURE: the code is wrong. """ x, y, w = simple_linear_data - lf = LinearFit(x, y, weights=w) + lf = LinearFit(x, y, yerr=w) lf.make_fit() assert isinstance(lf.fit_result, OptimizeResult) assert set(lf.popt) == {"m", "b"} @@ -230,12 +230,12 @@ def test_make_fit_success_failure(simple_linear_data, small_n): assert isinstance(lf.plotter, FFPlot) and isinstance(lf.TeX_info, TeXinfo) x, y, w = small_n - lf_small = LinearFit(x, y, weights=w) + lf_small = LinearFit(x, y, yerr=w) err = attempt_fit(lf_small) assert isinstance(err, InsufficientDataError) x, y, w = simple_linear_data - lf_fail = LinearFit(x, y, weights=w) + lf_fail = LinearFit(x, y, yerr=w) err = attempt_fit(lf_fail, max_nfev=1) assert isinstance(err, FitFailedError) assert "Optimal parameters not found" in str(err) @@ -246,7 +246,7 @@ def test_make_fit_success_failure(simple_linear_data, small_n): @pytest.fixture def fitted_linear(simple_linear_data): x, y, w = simple_linear_data - lf = LinearFit(x, y, weights=w) + lf = LinearFit(x, y, yerr=w) lf.make_fit() return lf @@ -298,7 +298,7 @@ class TestChisqDofBeforeFit: def test_chisq_dof_raises_before_fit(self, simple_linear_data): """Verify chisq_dof raises NotFittedError before make_fit.""" x, y, w = simple_linear_data - lf = LinearFit(x, y, weights=w) + lf = LinearFit(x, y, yerr=w) with pytest.raises(NotFittedError): lf.chisq_dof @@ -312,7 +312,7 @@ def test_initial_guess_info_raises_before_fit(self, simple_linear_data): ON FAILURE: the code is wrong -- an unfitted object reports a start. """ x, y, w = simple_linear_data - lf = LinearFit(x, y, weights=w) + lf = LinearFit(x, y, yerr=w) with pytest.raises(NotFittedError): lf.initial_guess_info @@ -321,15 +321,15 @@ class TestWeightShapeValidation: """Test weight shape validation in _clean_raw_obs (line 414).""" def test_weight_shape_mismatch_raises(self): - """Verify InvalidParameterError when weights shape mismatches x shape.""" + """Verify InvalidParameterError when yerr shape mismatches x shape.""" x = np.array([0.0, 1.0, 2.0]) y = np.array([1.0, 2.0, 3.0]) w = np.array([1.0, 1.0]) # Wrong shape with pytest.raises( - InvalidParameterError, match="weights and xobs must have the same shape" + InvalidParameterError, match="yerr and xobs must have the same shape" ): - LinearFit(x, y, weights=w) + LinearFit(x, y, yerr=w) class TestBoundsDictHandling: @@ -404,10 +404,10 @@ class TestCallableJacobian: """A callable jacobian is used in place of finite differences.""" def test_callable_jac_is_used_and_weighted(self): - """``res.jac`` is the caller's jacobian divided by the weights. + """``res.jac`` is the caller's jacobian divided by ``yerr``. The supplied jacobian is 3x the true one, so a finite-difference run - would leave ``res.jac`` a factor 3 away. Weights of 2 act as ``sigma``, + would leave ``res.jac`` a factor 3 away. A ``yerr`` of 2 acts as ``sigma``, so each row is divided by 2 (curve_fit's transform). With loss="linear" and a model linear in its parameters, ``res.jac`` is that constant matrix. @@ -416,7 +416,7 @@ def test_callable_jac_is_used_and_weighted(self): """ x = np.arange(10.0) w = np.full_like(x, 2.0) - lf = LinearFit(x, 2.0 * x + 1.0, weights=w) + lf = LinearFit(x, 2.0 * x + 1.0, yerr=w) def tripled_jac(x, m, b): return 3.0 * np.column_stack([x, np.ones_like(x)]) @@ -454,7 +454,7 @@ def test_make_fit_assertion_error_returned_as_insufficient_data( ON FAILURE: the code is wrong. """ x, y, w = simple_linear_data - lf = NeverEnoughData(x, y, weights=w) + lf = NeverEnoughData(x, y, yerr=w) err = attempt_fit(lf) assert isinstance(err, InsufficientDataError) @@ -470,7 +470,7 @@ def test_make_fit_assertion_error_raised_as_insufficient_data( ON FAILURE: the code is wrong. """ x, y, w = simple_linear_data - lf = NeverEnoughData(x, y, weights=w) + lf = NeverEnoughData(x, y, yerr=w) try: lf.make_fit() @@ -487,7 +487,7 @@ class TestAbsoluteSigmaNotImplemented: def test_make_fit_absolute_sigma_raises(self, simple_linear_data): """Verify make_fit raises NotImplementedError for absolute_sigma=True.""" x, y, w = simple_linear_data - lf = LinearFit(x, y, weights=w) + lf = LinearFit(x, y, yerr=w) with pytest.raises(NotImplementedError, match="rescale fit errors"): lf.make_fit(absolute_sigma=True) @@ -499,7 +499,7 @@ class TestResidualsAllOptions: def test_residuals_use_all_true(self, simple_linear_data): """Verify residuals calculates for all original data when use_all=True.""" x, y, w = simple_linear_data - lf = LinearFit(x, y, weights=w, xmin=0.2, xmax=0.8) + lf = LinearFit(x, y, yerr=w, xmin=0.2, xmax=0.8) lf.make_fit() r_used = lf.residuals(use_all=False) @@ -511,7 +511,7 @@ def test_residuals_use_all_true(self, simple_linear_data): def test_residuals_pct_true(self, simple_linear_data): """Verify residuals calculates percentage when pct=True.""" x, y, w = simple_linear_data - lf = LinearFit(x, y, weights=w) + lf = LinearFit(x, y, yerr=w) lf.make_fit() r_abs = lf.residuals(pct=False) @@ -536,7 +536,7 @@ def test_residuals_pct_handles_zero_fitted(self): def test_residuals_use_all_and_pct_together(self, simple_linear_data): """Verify residuals works with both use_all=True and pct=True.""" x, y, w = simple_linear_data - lf = LinearFit(x, y, weights=w, xmin=0.2, xmax=0.8) + lf = LinearFit(x, y, yerr=w, xmin=0.2, xmax=0.8) lf.make_fit() r_all_pct = lf.residuals(use_all=True, pct=True) @@ -573,26 +573,26 @@ def test_y_limits_select_the_used_observations(limits, expected): assert np.array_equal(lf.observations.used.x, np.array(expected)) -def test_wmin_alone_drops_smaller_weights(): - """``wmin`` with no ``wmax`` keeps ``w >= wmin``. +def test_yerr_min_alone_drops_smaller_uncertainties(): + """``yerr_min`` with no ``yerr_max`` keeps ``yerr >= yerr_min``. - w = [1, 2, 3, 4] with wmin=2: the sample with w = 1 is dropped and the + yerr = [1, 2, 3, 4] with yerr_min=2: the sample with yerr = 1 is dropped and the one on the bound stays. ON FAILURE: the code is wrong. """ x = np.arange(4.0) - lf = LinearFit(x, x, weights=np.array([1.0, 2.0, 3.0, 4.0]), wmin=2.0) + lf = LinearFit(x, x, yerr=np.array([1.0, 2.0, 3.0, 4.0]), yerr_min=2.0) assert np.array_equal(lf.observations.used.x, np.array([1.0, 2.0, 3.0])) def test_logy_selects_on_the_uncertainty_of_log10_y(): - """With ``logy`` the weight limits apply to ``w / (y ln 10)``. + """With ``logy`` the yerr limits apply to ``yerr / (y ln 10)``. - ``w / (y ln 10)`` is the one-sigma uncertainty of log10(y) propagated from - a one-sigma ``w`` on ``y`` (d log10 y = dy / (y ln 10)), as the class - docstring states. With y = 1 and w = ln(10) * [0.5, 0.97, 1.0, 1.03, 2.0] - that uncertainty is [0.5, 0.97, 1.0, 1.03, 2.0], so wmin=0.99, wmax=1.01 + ``yerr / (y ln 10)`` is the one-sigma uncertainty of log10(y) propagated from + a one-sigma ``yerr`` on ``y`` (d log10 y = dy / (y ln 10)), as the class + docstring states. With y = 1 and yerr = ln(10) * [0.5, 0.97, 1.0, 1.03, 2.0] + that uncertainty is [0.5, 0.97, 1.0, 1.03, 2.0], so yerr_min=0.99, yerr_max=1.01 keep only the middle sample. Any other logarithm base moves 1.0 out of the window (ln 10 / ln 11 = 0.96). @@ -601,15 +601,15 @@ def test_logy_selects_on_the_uncertainty_of_log10_y(): x = np.arange(5.0) y = np.ones(5) w = np.log(10.0) * np.array([0.5, 0.97, 1.0, 1.03, 2.0]) - lf = LinearFit(x, y, weights=w, wmin=0.99, wmax=1.01, logy=True) + lf = LinearFit(x, y, yerr=w, yerr_min=0.99, yerr_max=1.01, logy=True) assert np.array_equal(lf.observations.used.x, np.array([2.0])) -def test_set_fit_obs_selects_on_raw_weights_unless_logy_is_given(): - """Called without ``logy``, ``set_fit_obs`` applies ``wmin`` to the weights as given. +def test_set_fit_obs_selects_on_raw_yerr_unless_logy_is_given(): + """Called without ``logy``, ``set_fit_obs`` applies ``yerr_min`` to ``yerr`` as given. - y = 10 and w = [1, 2, 3] with wmin=1.5 keep w = 2 and 3. Under log - selection the compared values would be w / (10 ln 10) < 0.14 and nothing + y = 10 and yerr = [1, 2, 3] with yerr_min=1.5 keep yerr = 2 and 3. Under log + selection the compared values would be yerr / (10 ln 10) < 0.14 and nothing would be kept, so the default is observable. ON FAILURE: the code is wrong. @@ -617,9 +617,9 @@ def test_set_fit_obs_selects_on_raw_weights_unless_logy_is_given(): x = np.arange(3.0) y = np.full(3, 10.0) w = np.array([1.0, 2.0, 3.0]) - lf = LinearFit(x, y, weights=w) - lf.set_fit_obs(x, y, w, wmin=1.5) - assert np.array_equal(lf.observations.used.w, np.array([2.0, 3.0])) + lf = LinearFit(x, y, yerr=w) + lf.set_fit_obs(x, y, w, yerr_min=1.5) + assert np.array_equal(lf.observations.used.yerr, np.array([2.0, 3.0])) # ============================================================================ @@ -639,7 +639,7 @@ def test_make_fit_passes_the_method_to_scipy(line_with_outlier): ON FAILURE: the code is wrong. """ x, y, w = line_with_outlier - lf = LinearFit(x, y, weights=w) + lf = LinearFit(x, y, yerr=w) lf.make_fit(method="trf") with pytest.raises(ValueError): lf.make_fit(method="lm") @@ -659,7 +659,7 @@ def test_make_fit_passes_f_scale_to_scipy(line_with_outlier): ON FAILURE: the code is wrong. """ x, y, w = line_with_outlier - lf = LinearFit(x, y, weights=w) + lf = LinearFit(x, y, yerr=w) lf.make_fit(f_scale=1.0) p0 = np.array(lf.p0) defaults = dict(method="trf", loss="huber", max_nfev=10000) @@ -683,7 +683,7 @@ def test_make_fit_passes_other_keywords_to_scipy(line_with_outlier): """ x, y, w = line_with_outlier loose = dict(ftol=0.5, xtol=0.5, gtol=0.5) - lf = LinearFit(x, y, weights=w) + lf = LinearFit(x, y, yerr=w) lf.make_fit(**loose) p0 = np.array(lf.p0) defaults = dict(method="trf", loss="huber", max_nfev=10000, f_scale=0.1) @@ -717,7 +717,7 @@ def test_linear_loss_statistics_match_a_hand_computed_weighted_line(): """ x = np.array([0.0, 1.0, 2.0, 3.0]) y = np.array([0.0, 1.0, 1.0, 3.0]) - lf = LinearFit(x, y, weights=np.full(4, 2.0)) + lf = LinearFit(x, y, yerr=np.full(4, 2.0)) lf.make_fit(loss="linear") assert lf.popt == noise_free({"m": 0.9, "b": -0.1}) @@ -740,7 +740,7 @@ def test_huber_statistics_match_curve_fit_and_the_huber_cost(line_with_outlier): ON FAILURE: the code is wrong. """ x, y, w = line_with_outlier - lf = LinearFit(x, y, weights=w) + lf = LinearFit(x, y, yerr=w) lf.make_fit() p0 = np.array(lf.p0) _, pcov = curve_fit( @@ -867,7 +867,7 @@ def test_a_well_posed_fit_emits_no_optimize_warning(line_with_outlier): ON FAILURE: the code is wrong. """ x, y, w = line_with_outlier - lf = LinearFit(x, y, weights=w) + lf = LinearFit(x, y, yerr=w) with warnings.catch_warnings(): warnings.simplefilter("error", OptimizeWarning) lf.make_fit() @@ -903,23 +903,23 @@ def test_as_many_samples_as_parameters_leaves_the_covariance_infinite(): # ============================================================================ -def test_a_covariance_matrix_as_weights_is_refused(): - """A 6 x 6 covariance matrix as ``weights`` for six samples raises. +def test_a_covariance_matrix_as_yerr_is_refused(): + """A 6 x 6 covariance matrix as ``yerr`` for six samples raises. - ``weights`` holds one 1-sigma uncertainty per observation, in xobs's + ``yerr`` holds one 1-sigma uncertainty per observation, in xobs's shape; the author has decided a covariance matrix is not supported. ON FAILURE: the code is wrong, unless the author now accepts a covariance - matrix as ``weights``. + matrix as ``yerr``. """ x = np.arange(6.0) cov = np.diag(0.5 + 0.2 * x) ** 2 with pytest.raises( InvalidParameterError, - match="weights holds one 1-sigma uncertainty per observation, in " + match="yerr holds one 1-sigma uncertainty per observation, in " "xobs's shape, and a covariance matrix is not supported", ): - LinearFit(x, 2.0 * x + 1.0, weights=cov) + LinearFit(x, 2.0 * x + 1.0, yerr=cov) @pytest.mark.parametrize( @@ -929,26 +929,21 @@ def test_xobs_that_is_not_1d_is_refused_with_its_shape(x): """A fit refuses x that is not 1-d with a ValueError naming the shape. The author decided that 2-d x is refused: every model here is a function - of one variable. y and weights match x's shape, so only the 1-d rule can + of one variable. y and yerr match x's shape, so only the 1-d rule can refuse the input. ON FAILURE: the code is wrong. """ shape = re.escape(str(x.shape)) with pytest.raises(ValueError, match=rf"xobs must be 1-d.*{shape}"): - LinearFit(x, 2.0 * x + 1.0, weights=np.full(x.shape, 0.5)) + LinearFit(x, 2.0 * x + 1.0, yerr=np.full(x.shape, 0.5)) # ============================================================================ # yerr: the 1-sigma uncertainty of y, and its selection limits # ============================================================================ -_YERR_RENAME = pytest.mark.xfail( - strict=True, reason="weights, wmin and wmax are renamed yerr, yerr_min, yerr_max" -) - -@_YERR_RENAME def test_yerr_is_stored_as_the_observations_yerr(): """``yerr`` is kept unchanged as ``observations.raw.yerr``. @@ -958,7 +953,6 @@ def test_yerr_is_stored_as_the_observations_yerr(): assert np.array_equal(raw.yerr, np.array([0.5, 0.25])) -@_YERR_RENAME def test_yerr_min_and_yerr_max_keep_the_uncertainties_between_them(): """``yerr_min`` and ``yerr_max`` keep ``yerr_min <= yerr <= yerr_max``. @@ -974,7 +968,6 @@ def test_yerr_min_and_yerr_max_keep_the_uncertainties_between_them(): assert np.array_equal(lf.observations.used.yerr, np.array([2.0, 3.0])) -@_YERR_RENAME @pytest.mark.parametrize("old", ["weights", "wmin", "wmax"]) def test_the_old_uncertainty_keywords_are_refused(old): """``weights``, ``wmin`` and ``wmax`` are gone, with no alias. diff --git a/tests/fitfunctions/test_degeneracy.py b/tests/fitfunctions/test_degeneracy.py index 302dccb44..c4f29c60e 100644 --- a/tests/fitfunctions/test_degeneracy.py +++ b/tests/fitfunctions/test_degeneracy.py @@ -50,7 +50,7 @@ def _line_on(lo, seed): """A line 3x + 2 sampled on [lo, lo + 1] with 0.1 noise, weighted by it.""" x = np.linspace(lo, lo + 1, 21) y = 3 * x + 2 + np.random.default_rng(seed).normal(0, 0.1, x.size) - return Line(x, y, weights=np.full(x.size, 0.1)) + return Line(x, y, yerr=np.full(x.size, 0.1)) def _correlation(fit, a, b): @@ -227,7 +227,7 @@ def test_degeneracy_threshold_class_attribute_is_the_default(): x = np.linspace(2, 3, 21) y = 3 * x + 2 + np.random.default_rng(1).normal(0, 0.1, x.size) - fit = _StrictLine(x, y, weights=np.full(x.size, 0.1)) + fit = _StrictLine(x, y, yerr=np.full(x.size, 0.1)) with pytest.warns(FitDegeneracyWarning, match="m and b are degenerate"): fit.make_fit() @@ -269,7 +269,7 @@ class _Line(Line): x = np.linspace(2, 3, 21) y = 3 * x + 2 + np.random.default_rng(1).normal(0, 0.1, x.size) - fit = _Line(x, y, weights=np.full(x.size, 0.1)) + fit = _Line(x, y, yerr=np.full(x.size, 0.1)) fit.make_fit() assert fit.degenerate == [] @@ -290,7 +290,7 @@ class _Line(Line): x = np.linspace(2, 3, 21) y = 3 * x + 2 + np.random.default_rng(1).normal(0, 0.1, x.size) - fit = _Line(x, y, weights=np.full(x.size, 0.1)) + fit = _Line(x, y, yerr=np.full(x.size, 0.1)) with pytest.warns(FitDegeneracyWarning): fit.make_fit(degeneracy_threshold=0.99) _Line.degeneracy_threshold = 0.99999 diff --git a/tests/fitfunctions/test_exponentials.py b/tests/fitfunctions/test_exponentials.py index 8f6b2b8f3..3ebb3da95 100644 --- a/tests/fitfunctions/test_exponentials.py +++ b/tests/fitfunctions/test_exponentials.py @@ -264,7 +264,7 @@ def test_exponential_with_weights(): y = 3.0 * np.exp(-0.8 * x) + 0.01 * np.array([1, -1] * 6) sigma = np.linspace(0.5, 2.0, 12) - obj = Exponential(x, y, weights=sigma) + obj = Exponential(x, y, yerr=sigma) obj.make_fit() def model(x, k, A): diff --git a/tests/fitfunctions/test_hinge.py b/tests/fitfunctions/test_hinge.py index 01ef081fd..9c881b988 100644 --- a/tests/fitfunctions/test_hinge.py +++ b/tests/fitfunctions/test_hinge.py @@ -451,10 +451,10 @@ def test_hinge_point_is_continuous(clean_sloped_plateau_data): # ============================================================================= -def test_weighted_fit_respects_weights(): +def test_weighted_fit_respects_yerr(): """Weighted fitting should correctly use sigma to weight observations. - In FitFunction, weights are interpreted as uncertainties (sigma). Points + In FitFunction, ``yerr`` is the 1-sigma uncertainty of each y. Points with larger sigma have MORE uncertainty and thus LESS influence on the fit. Test strategy: Apply non-uniform sigma values and verify the fit converges @@ -479,7 +479,7 @@ def test_weighted_fit_respects_weights(): y = y_true + noise # Fit with correct sigma values - fit_weighted = HingeSaturation(x, y, weights=sigma_true, guess_xh=true_params["xh"]) + fit_weighted = HingeSaturation(x, y, yerr=sigma_true, guess_xh=true_params["xh"]) fit_weighted.make_fit() # Verify fit converged and parameters are accurate diff --git a/tests/fitfunctions/test_lines.py b/tests/fitfunctions/test_lines.py index f8242693f..6e45e9d7d 100644 --- a/tests/fitfunctions/test_lines.py +++ b/tests/fitfunctions/test_lines.py @@ -231,7 +231,7 @@ def test_line_with_weights(): y = 2.0 * x + 1.0 + np.array([0.02, -0.02, 0.02, -0.02, 0.02, -0.02]) sigma = np.array([0.5, 0.5, 1.0, 1.0, 2.0, 2.0]) - obj = Line(x, y, weights=sigma) + obj = Line(x, y, yerr=sigma) obj.make_fit() m_w, b_w = np.polyfit(x, y, 1, w=1.0 / sigma) diff --git a/tests/fitfunctions/test_plots.py b/tests/fitfunctions/test_plots.py index 2292723d5..4baa6a0b0 100644 --- a/tests/fitfunctions/test_plots.py +++ b/tests/fitfunctions/test_plots.py @@ -1,7 +1,7 @@ """Tests for :class:`solarwindpy.fitfunctions.plots.FFPlot`. The fixture is a ``Line`` fitted to ``y = 2x + 1`` at x = 0..5 with unit -weights and ``1 <= x <= 3``, so the used observations are x = 1, 2, 3 and the +uncertainties ``yerr`` and ``1 <= x <= 3``, so the used observations are x = 1, 2, 3 and the raw ones extend past them on both sides. The plotter is given a hand-chosen model ``Y_FIT``, a stand-in for the fit function's ``residuals`` that returns the residuals of that model, and a residual vector ``FUN``, so every residual @@ -72,10 +72,10 @@ } -def _fit(n=6, xmin=1, xmax=3, weights=True): +def _fit(n=6, xmin=1, xmax=3, yerr=True): x = np.arange(float(n)) - w = np.ones_like(x) if weights else None - fit = Line(x, 2.0 * x + 1.0, weights=w, xmin=xmin, xmax=xmax) + sigma = np.ones_like(x) if yerr else None + fit = Line(x, 2.0 * x + 1.0, yerr=sigma, xmin=xmin, xmax=xmax) fit.make_fit() return fit @@ -99,7 +99,7 @@ def residuals(pct=False, _simple=simple, _pct=pct): def make_ffplot( y_fit=Y_FIT, fun=FUN, - weights=True, + yerr=True, residuals_func=residuals_returning(SIMPLE, SIMPLE_PCT), ): """FFPlot of the fixture fit with model ``y_fit`` and residuals ``fun``. @@ -107,7 +107,7 @@ def make_ffplot( ``residuals_func`` stands in for the fit function's ``residuals``; by default it returns the residuals of ``Y_FIT``. """ - obs = _fit(weights=weights).observations + obs = _fit(yerr=yerr).observations tex = make_texinfo() plot = FFPlot( obs, @@ -403,7 +403,7 @@ def test_window_spans_y_minus_w_to_y_plus_w(kind): o = getattr(plot.observations, kind) ax, (line, window, edges) = getattr(plot, f"plot_{kind}")(edge_kwargs={}) vy = window.get_paths()[0].vertices[:, 1] - assert vy.min() == o.y.min() - 1.0 # unit weights + assert vy.min() == o.y.min() - 1.0 # unit yerr assert vy.max() == o.y.max() + 1.0 assert window.get_alpha() == 0.15 color = to_rgba(PINNED_STYLES[kind]["color"]) @@ -442,24 +442,24 @@ def test_window_and_edge_keywords_take_effect(kind): @pytest.mark.parametrize("kind", ["raw", "used"]) -def test_without_weights_the_window_collapses_onto_the_line(kind, caplog): - """No weights logs a warning and draws a zero-width window. +def test_without_yerr_the_window_collapses_onto_the_line(kind, caplog): + """No yerr logs a warning and draws a zero-width window. ON FAILURE: the code is wrong. """ - plot, *_ = make_ffplot(weights=False) + plot, *_ = make_ffplot(yerr=False) o = getattr(plot.observations, kind) with caplog.at_level(logging.WARNING): _, (_, window, _) = getattr(plot, f"plot_{kind}")() - assert "No weights" in caplog.text + assert "No yerr" in caplog.text vy = window.get_paths()[0].vertices[:, 1] assert vy.min() == o.y.min() assert vy.max() == o.y.max() @pytest.mark.parametrize("kind", ["raw", "used"]) -def test_without_a_window_error_bars_span_the_weights(kind): - """``plot_window=False`` draws error bars from ``y - w`` to ``y + w``. +def test_without_a_window_error_bars_span_the_yerr(kind): + """``plot_window=False`` draws error bars from ``y - yerr`` to ``y + yerr``. ON FAILURE: the code is wrong. """ @@ -592,7 +592,7 @@ def test_plot_raw_used_fit_passes_each_keyword_set_to_its_plot(): def _noisy_fit(): - """``Line`` fitted to ``2x + 1`` perturbed at the used points, unit weights. + """``Line`` fitted to ``2x + 1`` perturbed at the used points, unit yerr. The perturbations give residuals of order one, so a sign flip between two residual definitions cannot hide inside a tolerance. @@ -600,7 +600,7 @@ def _noisy_fit(): x = np.arange(10.0) y = 2.0 * x + 1.0 y[2:8] += np.array([1.0, -2.0, 0.5, 1.5, -1.0, 2.0]) - fit = Line(x, y, weights=np.ones_like(x), xmin=2, xmax=7) + fit = Line(x, y, yerr=np.ones_like(x), xmin=2, xmax=7) fit.make_fit() return fit @@ -643,7 +643,7 @@ def test_percent_residuals_are_the_simple_ones_relative_to_the_model(): def test_robust_residuals_share_the_sign_of_the_simple_ones(): """Robust residuals are ``-fit_result.fun``, observed minus fitted over sigma. - With unit weights they equal the simple residuals, so ``kind="both"`` + With unit yerr they equal the simple residuals, so ``kind="both"`` draws two lines of the same sign at every point. ON FAILURE: the code is wrong. diff --git a/tests/fitfunctions/test_power_laws.py b/tests/fitfunctions/test_power_laws.py index a4acacd47..ce333ad84 100644 --- a/tests/fitfunctions/test_power_laws.py +++ b/tests/fitfunctions/test_power_laws.py @@ -592,7 +592,7 @@ def test_power_law_with_weights(): y = 2.0 * x**-1.5 + 0.01 * np.array([1, -1] * 6) sigma = np.linspace(0.5, 2.0, 12) - obj = PowerLaw(x, y, weights=sigma) + obj = PowerLaw(x, y, yerr=sigma) obj.make_fit() def model(x, A, alpha): diff --git a/tests/fitfunctions/test_trend_fits.py b/tests/fitfunctions/test_trend_fits.py index 09f638ce5..d59968f55 100644 --- a/tests/fitfunctions/test_trend_fits.py +++ b/tests/fitfunctions/test_trend_fits.py @@ -386,7 +386,7 @@ def test_labels_instance_and_update(trend_fit): MUS = [5.0, 4.0, 5.5, 6.0, 7.0] SIGMAS = [1.0, 1.1, 1.3, 1.2, 1.2] IN_TREND = [False, True, True, True, False] -TREND_LIMITS = {"ymax": 6.5, "wmin": 1.05} +TREND_LIMITS = {"ymax": 6.5, "yerr_min": 1.05} def _agged5(): diff --git a/tests/fitfunctions/test_trend_fits_advanced.py b/tests/fitfunctions/test_trend_fits_advanced.py index bb42f5027..a6ebb2644 100644 --- a/tests/fitfunctions/test_trend_fits_advanced.py +++ b/tests/fitfunctions/test_trend_fits_advanced.py @@ -285,7 +285,6 @@ def test_make_fit_with_non_interval_index(self): # Verify the trend was created successfully assert isinstance(tf.trend, Line) - @pytest.mark.xfail(strict=True, reason="weights is renamed yerr") def test_trend_kwargs_cannot_hold_yerr(self): """``trend_kwargs`` holding ``yerr`` raises: TrendFit's ``yerr`` selects it. @@ -301,19 +300,6 @@ def test_trend_kwargs_cannot_hold_yerr(self): trend_kwargs=dict(yerr=np.ones(5)), ) - def test_trend_weights_error(self): - """Test TrendFit raises ValueError when trend weights are passed.""" - # Passing weights should raise ValueError: yerr selects them - with pytest.raises(ValueError, match="yerr selects the trend's weights"): - TrendFit( - self.data_interval, - Gaussian, - Line, - y=MU, - yerr=SIGMA, - trend_kwargs=dict(weights=np.ones(5)), - ) - class TestPlotAllPopt1DEdgeCases: """Test plot_bin_results edge cases (lines 411, 419-425, 428, 439-466).""" diff --git a/tests/fitfunctions/test_trend_results.py b/tests/fitfunctions/test_trend_results.py index 8988453ea..cd0cd96f8 100644 --- a/tests/fitfunctions/test_trend_results.py +++ b/tests/fitfunctions/test_trend_results.py @@ -90,7 +90,7 @@ def _noisy_agged5(): def _trend5(**kwargs): kwargs.setdefault("y", ("mu", "value")) kwargs.setdefault("yerr", ("sigma", "value")) - kwargs.setdefault("trend_kwargs", {"ymax": 6.5, "wmin": 1.05}) + kwargs.setdefault("trend_kwargs", {"ymax": 6.5, "yerr_min": 1.05}) tf = TrendFit(_agged5(), Gaussian, Line, **kwargs) tf.make_fit() return tf @@ -118,7 +118,7 @@ def test_the_authors_example_recovers_the_generating_hinge(): assert tf.bin_results.loc[:, ("mu", "value")].to_numpy() == noise_free(_hinge_mu(v)) np.testing.assert_array_equal(tf.trend.observations.raw.x, v) # column centers np.testing.assert_array_equal( - tf.trend.observations.raw.w, tf.bin_results.loc[:, ("sigma", "value")] + tf.trend.observations.raw.yerr, tf.bin_results.loc[:, ("sigma", "value")] ) hinge = tf.trend.results.xs("value", level="K", axis=1).iloc[0] assert [hinge["xh"], hinge["yh"]] == noise_free([H, YH]) # the generating hinge @@ -266,11 +266,11 @@ def test_yerr_can_be_the_uncertainty_of_mu_or_none(): tf.make_fit() psigma = tf.bin_results.loc[:, ("mu", "uncertainty")] assert (psigma > 0).all() # the noise exists to make these nonzero - np.testing.assert_array_equal(tf.trend.observations.raw.w, psigma) + np.testing.assert_array_equal(tf.trend.observations.raw.yerr, psigma) unweighted = TrendFit(_agged5(), Gaussian, Line, y=("mu", "value"), yerr=None) unweighted.make_fit() - assert unweighted.trend.observations.raw.w is None + assert unweighted.trend.observations.raw.yerr is None def test_an_unknown_key_raises_naming_the_available_ones(): From 94ddaf3f107315e716d53127da7deae2c91df9d4 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 03:13:32 -0500 Subject: [PATCH 03/60] test(plotting): a plot's repr summarises what it holds Target tests, marked xfail(strict=True) until the repr lands: class, labels, kept rows, log flags, bins per axis or mesh cells, axnorm, clim and alim once set, and path, on Hist1D, Hist2D, SpiralPlot2D and Scatter built before any plotting; str equals repr. A guard pins the one-line Hist1D z-label error, which reads str(self) today. Co-Authored-By: Claude Opus 5.5 --- tests/plotting/test_repr.py | 170 ++++++++++++++++++++++++++++++++++++ 1 file changed, 170 insertions(+) create mode 100644 tests/plotting/test_repr.py diff --git a/tests/plotting/test_repr.py b/tests/plotting/test_repr.py new file mode 100644 index 000000000..891b70e2a --- /dev/null +++ b/tests/plotting/test_repr.py @@ -0,0 +1,170 @@ +# Spent-When: PERMANENT(the plot classes stop defining a summary repr) +# Supersedes: none +"""Tests for the summary ``repr`` of the plot classes. + +``repr(plot)``, which ``print`` and Jupyter show, lists on one line each what +the plot holds: its class, the x, y (and z) labels, the number of rows it +keeps, its log flags, its binning (bins per axis on a fixed grid, cells on a +spiral mesh), ``axnorm``, ``clim`` and ``alim`` when set, and ``path``. Each +plot is built on a small hand-chosen frame whose kept rows are counted by hand. +""" + +import numpy as np +import pandas as pd +import pytest +import matplotlib + +matplotlib.use("Agg") + +from solarwindpy.plotting.hist1d import Hist1D # noqa: E402 +from solarwindpy.plotting.hist2d import Hist2D # noqa: E402 +from solarwindpy.plotting.scatter import Scatter # noqa: E402 +from solarwindpy.plotting.spiral import SpiralPlot2D # noqa: E402 + +_NO_REPR = pytest.mark.xfail(strict=True, reason="plots have no summary repr yet") + +# Six rows; row 2 has NaN x and row 4 NaN y, so a plot on x and y keeps 4 and +# a Hist1D of x alone keeps 5. +X = pd.Series([1.0, 2.0, np.nan, 3.0, 4.0, 5.0], name="x") +Y = pd.Series([1.0, 3.0, 2.0, 2.5, np.nan, 3.5], name="y") +Z = pd.Series([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], name="z") +KEPT = {"Hist1D": 5, "Hist2D": 4, "SpiralPlot2D": 4, "Scatter": 4} + +# The spiral's starting grid: 2 x-bins by 2 y-bins. min_per_bin=1 splits each +# cell with two or more points; the count is checked against the mesh itself. +XEDGES = np.array([0.0, 3.0, 6.0]) +YEDGES = np.array([0.0, 2.0, 4.0]) + + +def _lines(plot): + """``repr(plot)`` as its class line and a dict of its ``key: value`` lines.""" + first, *rest = repr(plot).splitlines() + return first, dict(line.strip().split(": ", 1) for line in rest) + + +def _build(name): + if name == "Hist1D": + return Hist1D(X, nbins=np.array([0.0, 2.0, 4.0, 6.0])) + if name == "Hist2D": + return Hist2D(X, Y, nbins=4, axnorm="t") + if name == "SpiralPlot2D": + return SpiralPlot2D(X, Y, initial_bins=(XEDGES, YEDGES), min_per_bin=1) + return Scatter(X, Y, Z) + + +@_NO_REPR +@pytest.mark.parametrize("name", list(KEPT)) +def test_repr_names_the_class_labels_rows_log_and_path(name): + """Every plot's repr names its class, labels, kept rows, log flags and path. + + It is built before any plotting, so repr must not need a drawn figure. + ``print`` shows the same text. + + ON FAILURE: the code is wrong. + """ + plot = _build(name) + first, fields = _lines(plot) + assert first == name + assert fields["x"] == str(plot.labels.x) + assert fields["y"] == str(plot.labels.y) + assert fields["observations"] == str(KEPT[name]) + assert fields["log"] == "x=False, y=False" + assert fields["path"] == str(plot.path) + assert str(plot) == repr(plot) + + +@pytest.mark.parametrize( + "name, has_z", [("Hist1D", False), ("Hist2D", True), ("Scatter", True)] +) +@_NO_REPR +def test_repr_shows_z_only_when_the_plot_has_one(name, has_z): + """A z label is listed for a 2-D histogram and a coloured scatter only. + + ON FAILURE: the code is wrong. + """ + plot = _build(name) + _, fields = _lines(plot) + assert {"x", "y", "path"} <= set(fields) + assert ("z" in fields) is has_z + if has_z: + assert fields["z"] == str(plot.labels.z) + + +@_NO_REPR +def test_hist1d_repr_counts_its_bins_and_axnorm(): + """Three bins from four edges; no ``axnorm`` reads ``None``. + + ON FAILURE: the code is wrong. + """ + _, fields = _lines(_build("Hist1D")) + assert fields["bins"] == "x: 3" + assert fields["axnorm"] == "None" + + +@_NO_REPR +def test_hist2d_repr_counts_its_bins_per_axis(): + """``nbins=4`` gives four bins on each axis, and ``axnorm="t"`` is shown. + + ON FAILURE: the code is wrong. + """ + _, fields = _lines(_build("Hist2D")) + assert fields["bins"] == "x: 4, y: 4" + assert fields["axnorm"] == "t" + + +@_NO_REPR +def test_spiral_repr_counts_its_mesh_cells(): + """A spiral's binning is its number of mesh cells, one per row of ``mesh.mesh``. + + ON FAILURE: the code is wrong. + """ + plot = _build("SpiralPlot2D") + _, fields = _lines(plot) + assert fields["bins"] == f"{plot.mesh.mesh.shape[0]} mesh cells" + + +@_NO_REPR +def test_scatter_repr_has_no_binning(): + """A scatter bins nothing, so its repr has no bins, axnorm or clim. + + ON FAILURE: the code is wrong. + """ + _, fields = _lines(_build("Scatter")) + assert {"x", "y", "z", "path"} <= set(fields) + assert not {"bins", "axnorm", "clim"} & set(fields) + + +@_NO_REPR +def test_clim_and_alim_appear_only_once_set(): + """Unset limits are left out; set ones are listed with their bounds. + + ON FAILURE: the code is wrong. + """ + plot = _build("Hist2D") + _, fields = _lines(plot) + assert "clim" not in fields and "alim" not in fields + plot.set_clim(2, None) + plot.set_alim(0.1, 0.9, kind="quantile") + _, fields = _lines(plot) + assert fields["clim"] == "lower=2, upper=None" + assert fields["alim"] == "lower=0.1, upper=0.9 (quantile)" + + +@_NO_REPR +def test_repr_reports_a_log_axis(): + """A logarithmic x is reported as ``x=True``. + + ON FAILURE: the code is wrong. + """ + plot = Hist2D(X, Y, nbins=4, logx=True) + _, fields = _lines(plot) + assert fields["log"] == "x=True, y=False" + + +def test_hist1d_z_label_error_still_names_the_class(): + """Setting a z label on a Hist1D names the class in one line. + + ON FAILURE: the code is wrong. + """ + with pytest.raises(ValueError, match=r"^Hist1D doesn't have a z-label$"): + _build("Hist1D").set_labels(z="z") From 43ff6c90c32a200381f55b1d229552b521d25835 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 03:18:31 -0500 Subject: [PATCH 04/60] feat(plotting): a summary repr for every plot print(plot) and Jupyter showed only the class name. Base.__repr__ now lists the class, the x, y and z labels, the rows kept, the log flags and the path; a cooperative _repr_fields hook adds the binning, axnorm and clim (BinnedPlot) and alim (ColorPlot), and each Binning describes its own cells (bins per axis on a FixedGrid, mesh cells on an AdaptiveMesh). __str__ is removed so print shows the summary. Its only reader was the Hist1D z-label error, which now names the class directly. Path building and loggers already used __class__.__name__. The label flattening shared with BinnedPlot.agg and the z-label test shared with path are extracted. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++ src/solarwindpy/plotting/base.py | 65 +++++++++++++++++++++++++++-- src/solarwindpy/plotting/binned.py | 5 +++ src/solarwindpy/plotting/binning.py | 8 ++++ src/solarwindpy/plotting/hist1d.py | 2 +- src/solarwindpy/plotting/spiral.py | 4 ++ tests/plotting/test_base.py | 4 +- tests/plotting/test_repr.py | 10 ----- 8 files changed, 85 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8785924e0..728141867 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - A quickstart page that runs end to end on `solarwindpy.examples.load_plasma`: the `M`/`C`/`S` columns, derived quantities with their units, an `"a+p1"` total, a `Hist2D` and a `Line` fit's `results`. It replaces the tutorial stub. +- A summary `repr` for every plot (`Hist1D`, `Hist2D`, `SpiralPlot2D`, `Scatter`), shown by + Jupyter and `print`: the class, the x, y and z labels, the number of rows kept, the log flags, + the bins per axis (or mesh cells for `SpiralPlot2D`), `axnorm`, `clim` and `alim` when set, + and `path`. `str(plot)` is that summary, no longer just the class name. ### Changed diff --git a/src/solarwindpy/plotting/base.py b/src/solarwindpy/plotting/base.py index a217e1c2a..dc229e2be 100644 --- a/src/solarwindpy/plotting/base.py +++ b/src/solarwindpy/plotting/base.py @@ -66,8 +66,45 @@ def __init__(self): self._labels = AxesLabels(x="x", y="y") self._log = LogAxes(x=False) - def __str__(self): - return self.__class__.__name__ + def __repr__(self): + r"""A summary of what the plot holds, one ``key: value`` per line. + + The class, then the x and y labels (and z when the plot has one), the + number of rows the plot keeps, the log flags, the fields + ``_repr_fields`` adds (binning, ``axnorm``, ``clim``, ``alim``), and + ``path``. ``print`` shows the same text. + """ + labels = self._flat_labels() + fields = {k: labels[k] for k in ("x", "y")} + if self._has_z_label(): + fields["z"] = labels["z"] + source = self.__dict__.get("_source") + fields["observations"] = "none" if source is None else source.n_kept + fields["log"] = ", ".join(f"{k}={v}" for k, v in self.log._asdict().items()) + fields.update(self._repr_fields()) + fields["path"] = self.path + lines = [f" {k}: {v}" for k, v in fields.items()] + return "\n".join([self.__class__.__name__, *lines]) + + def _repr_fields(self): + r"""Fields a subclass adds to ``repr`` before ``path``, as a dict; none here.""" + return {} + + @staticmethod + def _format_limits(limits): + r"""``RangeLimits`` as ``"lower=..., upper=..."``, or None when both are unset.""" + if limits.lower is None and limits.upper is None: + return None + return f"lower={limits.lower}, upper={limits.upper}" + + def _flat_labels(self): + r"""Each axis's label as one line of text, keyed ``x``, ``y`` and ``z``.""" + return {k: str(v).replace("\n", " ") for k, v in self.labels._asdict().items()} + + def _has_z_label(self): + r"""True when ``labels.z`` is set: neither None nor the string ``"None"``.""" + z = self.labels.z + return not (z is None or (isinstance(z, str) and z == "None")) @property def logger(self): @@ -181,7 +218,7 @@ def path(self): """ labels = self.labels parts = [self._path_part(labels.x, "x"), self._path_part(labels.y, "y")] - if not (labels.z is None or (isinstance(labels.z, str) and labels.z == "None")): + if self._has_z_label(): parts.append(self._path_part(labels.z, "z")) path = Path(self.__class__.__name__, *parts) @@ -395,6 +432,14 @@ def alim(self): r"""``RangeLimits`` on the aggregated value; see ``set_alim``.""" return self._alim + def _repr_fields(self): + r"""Add ``alim`` and its kind to ``repr`` when set.""" + fields = super()._repr_fields() + alim = self._format_limits(self.alim) + if alim is not None: + fields["alim"] = f"{alim} ({self.alim_kind})" + return fields + @property def alim_kind(self): r"""``"value"`` or ``"quantile"``: how ``alim`` is read; see ``set_alim``.""" @@ -722,6 +767,18 @@ def binning(self): r"""The ``Binning`` that places each kept row in a cell.""" return self._binning + def _repr_fields(self): + r"""Add the binning, ``axnorm`` and, when set, ``clim`` to ``repr``.""" + fields = super()._repr_fields() + binning = self.__dict__.get("_binning") + if binning is not None: + fields["bins"] = binning.describe() + fields["axnorm"] = self.axnorm + clim = self._format_limits(self.clim) + if clim is not None: + fields["clim"] = clim + return fields + @property def clim(self): r"""``RangeLimits`` of the minimum and maximum counts per cell; see ``set_clim``.""" @@ -853,7 +910,7 @@ def agg(self, fcn=None, **kwargs): """ tko = self.agg_axes - lbls = {k: str(v).replace("\n", " ") for k, v in self.labels._asdict().items()} + lbls = self._flat_labels() self.logger.info( f"Starting {self.__class__.__name__!s} aggregation of ({tko})\n%s", "\n".join([f"""{k!s}: {v!s}""" for k, v in lbls.items()]), diff --git a/src/solarwindpy/plotting/binned.py b/src/solarwindpy/plotting/binned.py index 7baff0dfe..0f294896f 100644 --- a/src/solarwindpy/plotting/binned.py +++ b/src/solarwindpy/plotting/binned.py @@ -401,6 +401,11 @@ def rows(self): r"""Boolean ndarray of the kept rows, or None when all are kept.""" return self._rows + @property + def n_kept(self): + r"""Number of rows the plot keeps.""" + return self._n_kept + @property def log_columns(self): r"""Coordinates given a log setting, True or False, when built. diff --git a/src/solarwindpy/plotting/binning.py b/src/solarwindpy/plotting/binning.py index 05316ee5e..512b91067 100644 --- a/src/solarwindpy/plotting/binning.py +++ b/src/solarwindpy/plotting/binning.py @@ -56,6 +56,10 @@ def cell_measure(self): ``log10`` of the data, so the size is measured in ``log10``. """ + def describe(self): + r"""One line naming how many cells there are, for a plot's ``repr``.""" + return f"{len(self.cells)} cells" + def postfilter(self, agg): r"""Drop cells of ``agg``, indexed by cell code, that fail a quality filter. @@ -558,6 +562,10 @@ def cells(self): return intervals[0] return pd.MultiIndex.from_product(intervals, names=list(self._axes)) + def describe(self): + r"""Bins per axis, e.g. ``"x: 4, y: 3"``, for a plot's ``repr``.""" + return ", ".join(f"{k}: {len(self.intervals[k])}" for k in self._axes) + def cell_measure(self): r"""Each bin's width in 1-D, its area in 2-D, on the binned scale.""" widths = [np.asarray(self.intervals[k].length) for k in self._axes] diff --git a/src/solarwindpy/plotting/hist1d.py b/src/solarwindpy/plotting/hist1d.py index 919b3d022..35102c87a 100644 --- a/src/solarwindpy/plotting/hist1d.py +++ b/src/solarwindpy/plotting/hist1d.py @@ -183,7 +183,7 @@ def set_labels(self, **kwargs): If a z label is passed: a ``Hist1D`` has none. """ if "z" in kwargs: - raise ValueError(r"{} doesn't have a z-label".format(self)) + raise ValueError(f"{self.__class__.__name__} doesn't have a z-label") super(Hist1D, self).set_labels(**kwargs) diff --git a/src/solarwindpy/plotting/spiral.py b/src/solarwindpy/plotting/spiral.py index dc16e6450..20bd598c0 100644 --- a/src/solarwindpy/plotting/spiral.py +++ b/src/solarwindpy/plotting/spiral.py @@ -826,6 +826,10 @@ def cells(self): r"""Every cell, a ``RangeIndex`` over the rows of ``mesh.mesh``.""" return pd.RangeIndex(self._mesh.mesh.shape[0]) + def describe(self): + r"""Number of mesh cells, e.g. ``"52 mesh cells"``, for a plot's ``repr``.""" + return f"{self._mesh.mesh.shape[0]} mesh cells" + def codes(self): r"""Cell of each kept row, -1 for a row outside the mesh.""" bin_id = self._mesh.bin_id diff --git a/tests/plotting/test_base.py b/tests/plotting/test_base.py index c4286d033..2f2dee226 100644 --- a/tests/plotting/test_base.py +++ b/tests/plotting/test_base.py @@ -143,12 +143,12 @@ def __init__(self): def test_str_and_logger_name_the_concrete_class(): - """``str(plot)`` is the class name and the logger sits under the package. + """``str(plot)`` opens with the class name and the logger sits under the package. ON FAILURE: the code is wrong. """ plot = LinePlot(X, Y) - assert str(plot) == "LinePlot" + assert str(plot).splitlines()[0] == "LinePlot" assert isinstance(plot.logger, logging.Logger) assert plot.logger.name.startswith("solarwindpy.plotting.") assert plot.logger.name.endswith(".LinePlot") diff --git a/tests/plotting/test_repr.py b/tests/plotting/test_repr.py index 891b70e2a..8590c9e18 100644 --- a/tests/plotting/test_repr.py +++ b/tests/plotting/test_repr.py @@ -21,8 +21,6 @@ from solarwindpy.plotting.scatter import Scatter # noqa: E402 from solarwindpy.plotting.spiral import SpiralPlot2D # noqa: E402 -_NO_REPR = pytest.mark.xfail(strict=True, reason="plots have no summary repr yet") - # Six rows; row 2 has NaN x and row 4 NaN y, so a plot on x and y keeps 4 and # a Hist1D of x alone keeps 5. X = pd.Series([1.0, 2.0, np.nan, 3.0, 4.0, 5.0], name="x") @@ -52,7 +50,6 @@ def _build(name): return Scatter(X, Y, Z) -@_NO_REPR @pytest.mark.parametrize("name", list(KEPT)) def test_repr_names_the_class_labels_rows_log_and_path(name): """Every plot's repr names its class, labels, kept rows, log flags and path. @@ -76,7 +73,6 @@ def test_repr_names_the_class_labels_rows_log_and_path(name): @pytest.mark.parametrize( "name, has_z", [("Hist1D", False), ("Hist2D", True), ("Scatter", True)] ) -@_NO_REPR def test_repr_shows_z_only_when_the_plot_has_one(name, has_z): """A z label is listed for a 2-D histogram and a coloured scatter only. @@ -90,7 +86,6 @@ def test_repr_shows_z_only_when_the_plot_has_one(name, has_z): assert fields["z"] == str(plot.labels.z) -@_NO_REPR def test_hist1d_repr_counts_its_bins_and_axnorm(): """Three bins from four edges; no ``axnorm`` reads ``None``. @@ -101,7 +96,6 @@ def test_hist1d_repr_counts_its_bins_and_axnorm(): assert fields["axnorm"] == "None" -@_NO_REPR def test_hist2d_repr_counts_its_bins_per_axis(): """``nbins=4`` gives four bins on each axis, and ``axnorm="t"`` is shown. @@ -112,7 +106,6 @@ def test_hist2d_repr_counts_its_bins_per_axis(): assert fields["axnorm"] == "t" -@_NO_REPR def test_spiral_repr_counts_its_mesh_cells(): """A spiral's binning is its number of mesh cells, one per row of ``mesh.mesh``. @@ -123,7 +116,6 @@ def test_spiral_repr_counts_its_mesh_cells(): assert fields["bins"] == f"{plot.mesh.mesh.shape[0]} mesh cells" -@_NO_REPR def test_scatter_repr_has_no_binning(): """A scatter bins nothing, so its repr has no bins, axnorm or clim. @@ -134,7 +126,6 @@ def test_scatter_repr_has_no_binning(): assert not {"bins", "axnorm", "clim"} & set(fields) -@_NO_REPR def test_clim_and_alim_appear_only_once_set(): """Unset limits are left out; set ones are listed with their bounds. @@ -150,7 +141,6 @@ def test_clim_and_alim_appear_only_once_set(): assert fields["alim"] == "lower=0.1, upper=0.9 (quantile)" -@_NO_REPR def test_repr_reports_a_log_axis(): """A logarithmic x is reported as ``x=True``. From bb3edeb86453caa03ccf809f2065c7fadba62f52 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 03:22:16 -0500 Subject: [PATCH 05/60] test(core): Plasma.info summarises a plasma in one table Target tests, marked xfail(strict=True) until info() lands: the example plasma reports PSP, HCI, its first and last times, three observations, species a, e, p1, p2 and no auxiliary data; without a spacecraft both spacecraft fields read "none"; set_aux turns auxiliary data to "yes". Co-Authored-By: Claude Opus 5.5 --- tests/core/test_plasma_info.py | 77 ++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 tests/core/test_plasma_info.py diff --git a/tests/core/test_plasma_info.py b/tests/core/test_plasma_info.py new file mode 100644 index 000000000..d85ef0919 --- /dev/null +++ b/tests/core/test_plasma_info.py @@ -0,0 +1,77 @@ +# Spent-When: PERMANENT(Plasma stops offering info) +# Supersedes: none +"""Tests for :meth:`solarwindpy.core.plasma.Plasma.info`. + +``info()`` is a one-column table, one row per field: the spacecraft and its +frame ("none" without one), the first and last observation time, the number +of observations, the species, and whether auxiliary data are attached. The +expected values are those the example's docstring documents +(``solarwindpy.examples.load_plasma``): PSP in HCI, three rows, species a, e, +p1 and p2, no auxiliary data. +""" + +import pandas as pd +import pytest + +import solarwindpy as swp +from solarwindpy.core.plasma import Plasma + +_NO_INFO = pytest.mark.xfail(strict=True, reason="Plasma has no info() yet") + +FIELDS = [ + "spacecraft", + "frame", + "start", + "end", + "observations", + "species", + "auxiliary data", +] + + +@_NO_INFO +def test_info_of_the_example_names_its_spacecraft_times_and_species(): + """The example plasma: PSP in HCI, three rows, four species, no aux. + + ON FAILURE: the code is wrong. + """ + plasma = swp.examples.load_plasma() + info = plasma.info() + assert isinstance(info, pd.DataFrame) + assert info.index.tolist() == FIELDS + assert info.columns.tolist() == ["value"] + value = info.loc[:, "value"] + assert value["spacecraft"] == "PSP" + assert value["frame"] == "HCI" + assert value["start"] == pd.Timestamp("1995-01-01 12:35:00") + assert value["end"] == pd.Timestamp("2022-10-09 01:47:01.234560") + assert value["observations"] == 3 + assert value["species"] == "a, e, p1, p2" + assert value["auxiliary data"] == "no" + + +@_NO_INFO +def test_info_without_a_spacecraft_says_none(): + """A plasma built without ``sc`` reports "none" for spacecraft and frame. + + ON FAILURE: the code is wrong. + """ + example = swp.examples.load_plasma() + plasma = Plasma(example.data, *example.species) + value = plasma.info().loc[:, "value"] + assert value["spacecraft"] == "none" + assert value["frame"] == "none" + assert value["observations"] == 3 + + +@_NO_INFO +def test_info_reports_attached_auxiliary_data(): + """After ``set_aux``, auxiliary data reads "yes". + + ON FAILURE: the code is wrong. + """ + plasma = swp.examples.load_plasma() + flags = pd.DataFrame({("quality", "", ""): [0, 1, 0]}, index=plasma.epoch) + flags.columns.names = ["M", "C", "S"] + plasma.set_aux(flags) + assert plasma.info().loc["auxiliary data", "value"] == "yes" From 425a143a849bdbbb56df77cb79d179b87d04be72 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 03:41:29 -0500 Subject: [PATCH 06/60] feat(core): Plasma.info, a one-table summary of a plasma info() returns a DataFrame with one value column and one row per field: spacecraft and frame ("none" without one), first and last observation times, the number of observations, the species, and whether auxiliary data are attached. It renders as a table in Jupyter and prints in a terminal; the Plasma repr is unchanged. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 ++ src/solarwindpy/core/plasma.py | 41 ++++++++++++++++++++++++++++ tests/core/test_plasma_info.py | 6 ---- tests/core/test_quantity_registry.py | 1 + 4 files changed, 45 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 728141867..7d55ded14 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 Jupyter and `print`: the class, the x, y and z labels, the number of rows kept, the log flags, the bins per axis (or mesh cells for `SpiralPlot2D`), `axnorm`, `clim` and `alim` when set, and `path`. `str(plot)` is that summary, no longer just the class name. +- `solarwindpy.core.plasma.Plasma.info` returns a one-column table summarising a plasma: the + spacecraft and its frame (or "none"), the first and last observation times, the number of + observations, the species, and whether auxiliary data are attached. ### Changed diff --git a/src/solarwindpy/core/plasma.py b/src/solarwindpy/core/plasma.py index a9d36a221..126ac9575 100644 --- a/src/solarwindpy/core/plasma.py +++ b/src/solarwindpy/core/plasma.py @@ -292,6 +292,47 @@ def aux(self): """ return self._aux + def info(self): + r"""Summarise the plasma in a one-column table, one row per field. + + The fields are the spacecraft and its coordinate frame ("none" for + both when no spacecraft is attached), the first and last observation + times, the number of observations, the species, and whether auxiliary + data are attached ("yes" or "no"). The plasma's own ``repr`` is + unchanged. + + Returns + ------- + pandas.DataFrame + Indexed by field name, with one ``value`` column. + + Examples + -------- + >>> import solarwindpy as swp + >>> plasma = swp.examples.load_plasma() + >>> plasma.info() + value + spacecraft PSP + frame HCI + start 1995-01-01 12:35:00 + end 2022-10-09 01:47:01.234560 + observations 3 + species a, e, p1, p2 + auxiliary data no + """ + sc = self.sc + epoch = self.epoch + fields = { + "spacecraft": "none" if sc is None else sc.name, + "frame": "none" if sc is None else sc.frame, + "start": epoch.min(), + "end": epoch.max(), + "observations": len(epoch), + "species": ", ".join(self.species), + "auxiliary data": "no" if self.aux is None else "yes", + } + return pd.DataFrame({"value": pd.Series(fields, dtype=object)}) + def save( self, fname, diff --git a/tests/core/test_plasma_info.py b/tests/core/test_plasma_info.py index d85ef0919..04596339f 100644 --- a/tests/core/test_plasma_info.py +++ b/tests/core/test_plasma_info.py @@ -11,13 +11,10 @@ """ import pandas as pd -import pytest import solarwindpy as swp from solarwindpy.core.plasma import Plasma -_NO_INFO = pytest.mark.xfail(strict=True, reason="Plasma has no info() yet") - FIELDS = [ "spacecraft", "frame", @@ -29,7 +26,6 @@ ] -@_NO_INFO def test_info_of_the_example_names_its_spacecraft_times_and_species(): """The example plasma: PSP in HCI, three rows, four species, no aux. @@ -50,7 +46,6 @@ def test_info_of_the_example_names_its_spacecraft_times_and_species(): assert value["auxiliary data"] == "no" -@_NO_INFO def test_info_without_a_spacecraft_says_none(): """A plasma built without ``sc`` reports "none" for spacecraft and frame. @@ -64,7 +59,6 @@ def test_info_without_a_spacecraft_says_none(): assert value["observations"] == 3 -@_NO_INFO def test_info_reports_attached_auxiliary_data(): """After ``set_aux``, auxiliary data reads "yes". diff --git a/tests/core/test_quantity_registry.py b/tests/core/test_quantity_registry.py index 5a901cc13..571ae56f8 100644 --- a/tests/core/test_quantity_registry.py +++ b/tests/core/test_quantity_registry.py @@ -168,6 +168,7 @@ def turbulence(plasma): "drop_species", "epoch", "estimate_electrons", + "info", "ions", "load_from_file", "save", From 8946674e80d129885a019a3d881648a7b778dd4d Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 03:48:43 -0500 Subject: [PATCH 07/60] fix(core): render the lnlambda equation and document s0, s1 Plasma.lnlambda wrote \ln_\lambda_{i,i}, a double subscript MathJax rejects, so its API page showed "Double subscripts: use braces to clarify" instead of the equation; it is \ln \lambda_{0,1}, matching the equation's 0 and 1. Its Parameters named a species argument the method does not take; they now document s0 and s1. tests/test_docstring_math.py reads every docstring under src with ast and rejects double subscripts, double superscripts and unbalanced braces in :math: roles and .. math:: blocks. lnlambda was the only offender. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 ++ src/solarwindpy/core/plasma.py | 8 +- tests/test_docstring_math.py | 145 +++++++++++++++++++++++++++++++++ 3 files changed, 156 insertions(+), 4 deletions(-) create mode 100644 tests/test_docstring_math.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d55ded14..580d8b018 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Read the Docs (https://solarwindpy.readthedocs.io) is the only documentation host. The package metadata lists it as the `Documentation` URL. +### Fixed + +- The API page of `Plasma.lnlambda` showed a MathJax error ("Double subscripts") in place of + its equation, and documented a `species` parameter it does not take; it documents `s0, s1`. + A test now rejects double subscripts, double superscripts and unbalanced braces in docstring + math. + ### Removed - The GitHub Pages deployment of the documentation (the `deploy` job in diff --git a/src/solarwindpy/core/plasma.py b/src/solarwindpy/core/plasma.py index 126ac9575..eaf31c921 100644 --- a/src/solarwindpy/core/plasma.py +++ b/src/solarwindpy/core/plasma.py @@ -1643,13 +1643,13 @@ def caani(self, *species, pdv=False): def lnlambda(self, s0, s1): r"""Calculate the Coulomb logarithm between species s0 and s1. - :math:`\ln_\lambda_{i,i} = 29.9 - \ln(\frac{z_0 * z_1 * (a_0 + a_1)}{a_0 * T_1 + a_1 * T_0} \sqrt{\frac{n_0 z_0^2}{T_0} + \frac{n_1 z_1^2}{T_1}})` + :math:`\ln \lambda_{0,1} = 29.9 - \ln(\frac{z_0 * z_1 * (a_0 + a_1)}{a_0 * T_1 + a_1 * T_0} \sqrt{\frac{n_0 z_0^2}{T_0} + \frac{n_1 z_1^2}{T_1}})` Parameters ---------- - species: str - Each species is a string. It cannot be a sum of species, - nor can it be an iterable of species. + s0, s1 : str + The two species, one each. Neither can be a sum of species + nor an iterable of species. Returns ------- diff --git a/tests/test_docstring_math.py b/tests/test_docstring_math.py new file mode 100644 index 000000000..33a124733 --- /dev/null +++ b/tests/test_docstring_math.py @@ -0,0 +1,145 @@ +# Spent-When: PERMANENT(the package stops writing TeX in its docstrings) +# Supersedes: none +r"""Docstring math is TeX that MathJax accepts. + +The API pages render each ``:math:`` role and ``.. math::`` block with +MathJax, which rejects a double subscript or superscript (``a_b_c``, +``x^2^3``, ``\ln_\lambda_{0,1}``: "Double subscripts: use braces to +clarify") and unbalanced braces, and shows the error in place of the +equation. Sphinx builds such a page without a warning, so the strict docs +build cannot catch it. This test reads every docstring under +``src/solarwindpy`` with :mod:`ast`, without importing the package. +""" + +import ast +import re +from pathlib import Path + +import pytest + +SRC = Path(__file__).resolve().parents[1] / "src" / "solarwindpy" + +_ROLE = re.compile(r":math:`([^`]*)`") +_DIRECTIVE = re.compile(r"^(\s*)\.\. math::(.*)$") + + +def _docstrings(path): + """Yield ``(qualified name, docstring)`` for a module and its classes and functions.""" + tree = ast.parse(path.read_text(encoding="utf-8")) + nodes = [(path.stem, tree)] + while nodes: + name, node = nodes.pop() + doc = ast.get_docstring(node, clean=False) + if doc: + yield name, doc + for child in ast.iter_child_nodes(node): + if isinstance(child, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)): + nodes.append((f"{name}.{child.name}", child)) + + +def _math(doc): + """Every TeX expression in ``doc``: role contents and directive bodies.""" + yield from _ROLE.findall(doc) + lines = doc.splitlines() + for i, line in enumerate(lines): + match = _DIRECTIVE.match(line) + if not match: + continue + indent = len(match.group(1)) + body = [match.group(2)] + for nxt in lines[i + 1 :]: + if nxt.strip() and len(nxt) - len(nxt.lstrip()) <= indent: + break + if not nxt.strip().startswith(":"): # directive options + body.append(nxt) + yield "\n".join(body) + + +def _argument_end(tex, i): + """Index after the sub- or superscript argument starting at ``tex[i]``.""" + while i < len(tex) and tex[i].isspace(): + i += 1 + if i >= len(tex): + return i + if tex[i] == "{": + depth = 0 + for j in range(i, len(tex)): + depth += {"{": 1, "}": -1}.get(tex[j], 0) + if depth == 0: + return j + 1 + return len(tex) + if tex[i] == "\\": + match = re.match(r"\\([A-Za-z]+|.)", tex[i:]) + return i + match.end() + return i + 1 + + +def problems(tex): + """What MathJax rejects in ``tex``: double sub/superscripts, unbalanced braces.""" + found = [] + # Escaped braces \{ \} are literal and do not group. + plain = re.sub(r"\\[{}]", "", tex) + if plain.count("{") != plain.count("}"): + found.append("unbalanced braces") + seen = set() # which of _ and ^ the current atom already has + i = 0 + while i < len(tex): + c = tex[i] + if c in "_^": + if c in seen: + kind = "subscript" if c == "_" else "superscript" + found.append(f"double {kind} at {tex[max(0, i - 12) : i + 6]!r}") + seen.add(c) + i = _argument_end(tex, i + 1) + continue + if c == "\\" and tex[i : i + 2] in ("\\{", "\\}"): + i += 2 + elif c == "\\": + i = _argument_end(tex, i) + elif c == "{": + i = _argument_end(tex, i) + else: + i += 1 + if not c.isspace(): + seen = set() + return found + + +@pytest.mark.parametrize( + "tex, expected", + [ + (r"a_b_c", ["double subscript"]), + (r"x^2^3", ["double superscript"]), + (r"\ln_\lambda_{i,i}", ["double subscript"]), + (r"x_{a}^{b}", []), + (r"x_a^b_c", ["double subscript"]), + (r"{x_a}_b", []), + (r"w_\parallel w_\perp^2", []), + (r"\frac{a}{b", ["unbalanced braces"]), + (r"\{a\}", []), + ], +) +def test_the_checker_finds_what_mathjax_rejects(tex, expected): + """Hand-written cases: each MathJax error is found, and valid TeX passes. + + ON FAILURE: the checker is wrong. + """ + found = problems(tex) + assert len(found) == len(expected) + for f, e in zip(found, expected): + assert f.startswith(e) + + +def test_docstring_math_has_no_tex_mathjax_rejects(): + """No docstring under src/solarwindpy holds math MathJax would reject. + + ON FAILURE: the code is wrong; brace the sub- or superscript, e.g. + ``a_{b_c}`` or ``{a_b}_c``. + """ + bad = [] + for path in sorted(SRC.rglob("*.py")): + for name, doc in _docstrings(path): + for tex in _math(doc): + for p in problems(tex): + bad.append(f"{path.relative_to(SRC)}::{name}: {p}") + assert bad == [] From ecd9f9ee5a595c3f5b2ee235ceeed3f0bd63596d Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 03:58:00 -0500 Subject: [PATCH 08/60] test(plotting): get_plotted_data returns the rows of the cells shown Target tests, marked xfail(strict=True) until the method lands, checked against numpy.histogram2d and numpy.histogram counts: clim, alim with the default and a given fcn, a log axis returning the caller's signed values on its labels, Hist1D, and a spiral whose rows number its shown cells' counts. Co-Authored-By: Claude Opus 5.5 --- tests/plotting/test_plotted_data.py | 148 ++++++++++++++++++++++++++++ 1 file changed, 148 insertions(+) create mode 100644 tests/plotting/test_plotted_data.py diff --git a/tests/plotting/test_plotted_data.py b/tests/plotting/test_plotted_data.py new file mode 100644 index 000000000..64351b9c4 --- /dev/null +++ b/tests/plotting/test_plotted_data.py @@ -0,0 +1,148 @@ +# Spent-When: PERMANENT(BinnedPlot stops offering get_plotted_data) +# Supersedes: none +"""Tests for ``BinnedPlot.get_plotted_data``: the rows in the cells a figure shows. + +A cell is shown when ``agg(fcn)`` is not NaN there, after ``clim``, ``alim``, +``axnorm`` and any cell filter. ``get_plotted_data`` returns the rows in those +cells: the caller's x, y (and z) values, sign included and never logged, on +the caller's index labels. Expected rows come from ``numpy.histogram2d`` or +``numpy.histogram`` counts on hand-chosen data that lies off every bin edge, +so the bins' closed side does not matter, never from the plot's own code. +""" + +import numpy as np +import pandas as pd +import pytest +import matplotlib + +matplotlib.use("Agg") + +from solarwindpy.plotting.hist1d import Hist1D # noqa: E402 +from solarwindpy.plotting.hist2d import Hist2D # noqa: E402 +from solarwindpy.plotting.spiral import SpiralPlot2D # noqa: E402 +from tests.tolerances import exact # noqa: E402 + +_NEW = pytest.mark.xfail(strict=True, reason="get_plotted_data does not exist yet") + +XEDGES = np.array([0.0, 1.0, 2.0, 3.0]) +YEDGES = np.array([0.0, 1.0, 2.0]) + +# Labels 10..: cell (x-bin, y-bin) noted beside each row. Cell (0, 0) holds 3 +# rows, (1, 1) 2, (2, 0) 1; label 16 has NaN y and is not kept. +ROWS = [ + (10, 0.5, 0.5, 1.0), # (0, 0) + (11, 0.2, 0.7, 2.0), # (0, 0) + (12, 0.8, 0.1, 3.0), # (0, 0) + (13, 1.5, 1.5, 4.0), # (1, 1) + (14, 1.2, 1.9, 8.0), # (1, 1) + (15, 2.5, 0.5, 9.0), # (2, 0) + (16, 2.5, np.nan, 9.0), +] +INDEX = pd.Index([r[0] for r in ROWS]) +X = pd.Series([r[1] for r in ROWS], index=INDEX, name="x") +Y = pd.Series([r[2] for r in ROWS], index=INDEX, name="y") +Z = pd.Series([r[3] for r in ROWS], index=INDEX, name="z") + + +def _cell_counts_2d(): + """Count per row's cell, from numpy.histogram2d; NaN rows get 0.""" + kept = X.notna() & Y.notna() + counts, _, _ = np.histogram2d(X[kept], Y[kept], bins=[XEDGES, YEDGES]) + ix = np.digitize(X[kept], XEDGES) - 1 + iy = np.digitize(Y[kept], YEDGES) - 1 + return pd.Series(counts[ix, iy], index=X.index[kept]).reindex(X.index, fill_value=0) + + +def _hist2d(z=None): + return Hist2D(X, Y, z, nbins=[XEDGES, YEDGES]) + + +@_NEW +@pytest.mark.parametrize("lower", [None, 2, 3]) +def test_hist2d_returns_the_rows_of_cells_meeting_clim(lower): + """With ``clim`` lower bound n, the rows of cells holding at least n rows. + + No bound keeps every non-NaN row (labels 10 to 15). + + ON FAILURE: the code is wrong. + """ + h = _hist2d() + h.set_clim(lower, None) + counts = _cell_counts_2d() + expected = counts.index[counts >= (lower or 1)] + got = h.get_plotted_data() + assert got.index.tolist() == expected.tolist() + assert got.loc[:, "x"].to_numpy() == exact(X[expected].to_numpy()) + assert got.loc[:, "y"].to_numpy() == exact(Y[expected].to_numpy()) + + +@_NEW +def test_alim_acts_on_the_aggregated_value_of_the_given_fcn(): + """``alim`` on z means hides cell (0, 0) (mean 2); ``fcn="max"`` keeps it (max 3). + + Means: (0, 0) 2, (1, 1) 6, (2, 0) 9. With alim lower 2.5 the default + (mean) keeps labels 13 to 15; with ``fcn="max"`` (0, 0) is 3 and stays. + + ON FAILURE: the code is wrong. + """ + h = _hist2d(Z) + h.set_alim(2.5, None) + assert h.get_plotted_data().index.tolist() == [13, 14, 15] + assert h.get_plotted_data(fcn="max").index.tolist() == [10, 11, 12, 13, 14, 15] + assert h.get_plotted_data().loc[:, "z"].tolist() == [4.0, 8.0, 9.0] + + +@_NEW +def test_a_log_axis_returns_the_callers_signed_values(): + """On a log x the rows hold the caller's x, negative ones included. + + x = -10, 100 bin by log10|x| = 1, 2 on edges [0, 1.5, 3]. + + ON FAILURE: the code is wrong. + """ + x = pd.Series([-10.0, 100.0], index=[5, 7]) + y = pd.Series([0.5, 0.5], index=[5, 7]) + h = Hist2D(x, y, logx=True, nbins=[np.array([0.0, 1.5, 3.0]), [0.0, 1.0]]) + got = h.get_plotted_data() + assert got.index.tolist() == [5, 7] + assert got.loc[:, "x"].tolist() == [-10.0, 100.0] + + +@_NEW +def test_hist1d_returns_the_rows_of_bins_meeting_clim(): + """Hist1D of x: bins hold 3, 2 and 1 rows; clim 2 keeps labels 10 to 14. + + Label 16 has x = 2.5 and no y, but a Hist1D of x alone keeps it, so the + third bin holds 2 rows (15, 16) and is kept as well. + + ON FAILURE: the code is wrong. + """ + h = Hist1D(X, nbins=XEDGES) + h.set_clim(2, None) + counts, _ = np.histogram(X, bins=XEDGES) + per_row = counts[np.digitize(X, XEDGES) - 1] + expected = X.index[per_row >= 2] + got = h.get_plotted_data() + assert got.index.tolist() == expected.tolist() + assert got.loc[:, "x"].tolist() == X[expected].tolist() + + +@_NEW +def test_spiral_returns_as_many_rows_as_its_shown_cells_count(): + """A spiral's plotted rows number the counts of the cells ``agg`` shows. + + 100 seeded points, min_per_bin=10, and clim 5 hide the sparse cells; the + rows returned equal the sum of ``agg("count")`` over the shown cells. + + ON FAILURE: the code is wrong. + """ + rng = np.random.default_rng(3) + x = pd.Series(rng.normal(size=100)) + y = pd.Series(rng.normal(size=100)) + h = SpiralPlot2D(x, y, initial_bins=3, min_per_bin=10) + h.set_clim(5, None) + counts = h.agg(fcn="count") + got = h.get_plotted_data() + assert len(got) == counts[counts.notna()].sum() + assert got.index.isin(x.index).all() + assert got.loc[:, "x"].to_numpy() == exact(x[got.index].to_numpy()) From ab69791a70f77b42f4b8d1914e9f8bfb154206b6 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 03:59:03 -0500 Subject: [PATCH 09/60] fix(plotting): fit the default edge smoothing window to the bins Hist2D.plot_edges raised "polyorder must be less than window_length" below 50 x-bins: the default Savitzky-Golay window, 10% of the edge's points made odd, fell to 3 or less, not above the default polyorder 3. The default window now rises to the smallest odd length above polyorder and is capped at the edge's length; an edge too short for any such window is drawn unsmoothed. A window the caller passes is used as given. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 +++ src/solarwindpy/plotting/hist2d.py | 42 ++++++++++++---- tests/plotting/test_hist2d_plotting.py | 66 +++++++++++++++++++++----- 3 files changed, 92 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 20688635f..b405ff270 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `.github/workflows/docs.yml`). The workflow still builds the docs with warnings as errors on every push and pull request. +### Fixed + +- `Hist2D.plot_edges` no longer raises below 50 x-bins. The default Savitzky-Golay window, + 10% of the edge's points, is raised to the smallest odd length above `polyorder`, and an + edge too short for any such window is drawn unsmoothed. + ## [0.4.0] - 2026-11-05 ### Changed - BREAKING CHANGES diff --git a/src/solarwindpy/plotting/hist2d.py b/src/solarwindpy/plotting/hist2d.py index c96570041..79e9d62e3 100644 --- a/src/solarwindpy/plotting/hist2d.py +++ b/src/solarwindpy/plotting/hist2d.py @@ -430,6 +430,26 @@ def get_border(self): border = Border(top, bottom) return border + @staticmethod + def _default_savgol_window(n, polyorder): + r"""Default Savitzky-Golay window for an edge of ``n`` points, or None. + + 10% of ``n``, made odd by subtracting 1 when even; raised to the + smallest odd length above ``polyorder`` when it is not above it; capped + at the largest odd length within ``n``. None when no odd length within + ``n`` exceeds ``polyorder``: the edge is too short to smooth. + """ + wlength = int(np.floor(n / 10)) + if not wlength % 2: + wlength -= 1 + if wlength <= polyorder: + wlength = polyorder + 1 + polyorder % 2 + if wlength > n: + wlength = n if n % 2 else n - 1 + if wlength <= polyorder: + return None + return wlength + def _plot_one_edge( self, ax, @@ -448,13 +468,13 @@ def _plot_one_edge( sg_kwargs = dict() if sg_kwargs is None else dict(sg_kwargs) if smooth: - wlength = sg_kwargs.pop("window_length", int(np.floor(y.shape[0] / 10))) polyorder = sg_kwargs.pop("polyorder", 3) + wlength = sg_kwargs.pop("window_length", None) + if wlength is None: + wlength = self._default_savgol_window(y.shape[0], polyorder) - if not wlength % 2: - wlength -= 1 - - y = savgol_filter(y, wlength, polyorder, **sg_kwargs) + if wlength is not None: + y = savgol_filter(y, wlength, polyorder, **sg_kwargs) if self.log.x: x = 10.0**x @@ -491,10 +511,14 @@ def plot_edges(self, ax, smooth=True, sg_kwargs=None, **kwargs): to the y-values before plotting to smooth the curve. sg_kwargs: dict, None If not None, dict of kwargs passed to Savitzky-Golay filter. Also allows - for setting of `window_length` and `polyorder` as kwargs. They default to - 10% of the number of observations (`window_length`) and 3 (`polyorder`). - Note that because `window_length` must be odd, if the 10% value is even, we - take 1-window_length. + for setting of `window_length` and `polyorder` as kwargs. `polyorder` + defaults to 3. `window_length` defaults to 10% of the number of points + on the edge, less 1 when even, as the filter needs an odd window. A + default window that is not above `polyorder`, as below 50 points + for `polyorder` 3, is raised to the smallest odd length above it, and + a window longer than the edge to the longest odd length within it. + When no odd length within the edge exceeds `polyorder` the edge is + drawn unsmoothed. A `window_length` the caller passes is used as given. xlim, ylim: tuple of (float or None, float or None), optional Inclusive ``(lower, upper)`` limits, in data coordinates, on the edge vertices drawn. A vertex outside a limit is dropped; a vertex exactly diff --git a/tests/plotting/test_hist2d_plotting.py b/tests/plotting/test_hist2d_plotting.py index 36154ca00..216db75be 100644 --- a/tests/plotting/test_hist2d_plotting.py +++ b/tests/plotting/test_hist2d_plotting.py @@ -134,23 +134,17 @@ def z_valued_hist(): return hist, counts, z_means -@pytest.fixture -def smoothable_hist(): - """A Hist2D wide enough in x that a savgol window of 5 is meaningful. +def _moving_band_hist(nx): + """A Hist2D with ``nx`` x-bins whose occupied y-band moves with x. - 61 x-bins is not arbitrary: `_plot_one_edge` defaults `window_length` to - floor(n / 10), decremented to the next odd number, and defaults - `polyorder` to 3. Fewer columns make the default window too narrow for that - polynomial order and scipy refuses outright, which would mask the parameter - mix-up this fixture exists to expose. + The occupied band moves up and down with x, so neither border is flat. + A flat border is invariant under savgol at any polynomial order, which + would make the smoothing comparisons vacuous. """ - xedges = np.round(np.linspace(0.0, 1.0, 62), 5) + xedges = np.round(np.linspace(0.0, 1.0, nx + 1), 5) yedges = np.round(np.linspace(0.0, 1.0, 9), 5) - ny, nx = len(yedges) - 1, len(xedges) - 1 + ny = len(yedges) - 1 - # The occupied band moves up and down with x, so neither border is flat. - # A flat border is invariant under savgol at any polynomial order, which - # would make the smoothing comparisons vacuous. counts = np.zeros((ny, nx), dtype=int) for j in range(nx): lo = j % 3 @@ -162,6 +156,16 @@ def smoothable_hist(): return Hist2D(x, y, nbins=[xedges, yedges]) +@pytest.fixture +def smoothable_hist(): + """A Hist2D wide enough in x that a savgol window of 5 is meaningful. + + 61 x-bins puts the default `window_length`, floor(n / 10) made odd, at 5: + above the default `polyorder` of 3 without raising it to the minimum. + """ + return _moving_band_hist(61) + + def _expected_grid(counts): """``counts`` with empty bins as NaN, matching an unstacked aggregation.""" expected = counts.astype(float) @@ -1472,6 +1476,42 @@ def test_both_edges_get_the_smoothing_the_caller_asked_for(self, smoothable_hist ) plt.close("all") + def test_default_smoothing_widens_the_window_for_few_bins(self): + """Below 50 x-bins the default window is the smallest that fits polyorder 3. + + floor(n / 10) is at most 3 there, which savgol rejects for polyorder 3; + the default window must be the smallest odd length above the + polynomial order, 5, so the edge is smoothed rather than refused. + + ON FAILURE: the code is wrong. + """ + hist = _moving_band_hist(20) + fig, ax = plt.subplots() + (raw,), _ = hist.plot_edges(ax, smooth=False) + (smoothed,), _ = hist.plot_edges(ax, smooth=True) + + expected = savgol_filter(np.asarray(raw.get_ydata(), float), 5, 3) + assert np.asarray(np.asarray(smoothed.get_ydata(), float)) == exact(expected) + plt.close("all") + + def test_default_smoothing_is_skipped_when_no_window_fits(self): + """With too few x-bins for any odd window above polyorder, draw the raw edge. + + Four x-bins admit odd windows of 1 and 3, neither above polyorder 3, so + the default smoothing has nothing to fit and leaves the edge as is. + + ON FAILURE: the code is wrong. + """ + hist = _moving_band_hist(4) + fig, ax = plt.subplots() + (raw,), _ = hist.plot_edges(ax, smooth=False) + (smoothed,), _ = hist.plot_edges(ax, smooth=True) + + assert np.asarray(np.asarray(smoothed.get_ydata(), float)) == exact( + np.asarray(raw.get_ydata(), float) + ) + plt.close("all") + class TestProject1D: """Projecting a 2D histogram is marginalisation, and must conserve counts.""" From 6f2ae49d175f676abef1409db39fc3263cbdde63 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:01:46 -0500 Subject: [PATCH 10/60] test(plotting): pin Scatter edges joining consecutive points Strict xfail until make_plot(edges=True) exists: segment count, colours as the mean endpoint z through the points' cmap and norm, NaN, mask and alim breaking the chain, row-position order, single colour without z, zorder and edge_kwargs, and the (ax, points, edges, cbar) return. Co-Authored-By: Claude Opus 5.5 --- tests/plotting/test_scatter.py | 182 +++++++++++++++++++++++++++++++++ 1 file changed, 182 insertions(+) diff --git a/tests/plotting/test_scatter.py b/tests/plotting/test_scatter.py index 06bc074f8..a8f676d1e 100644 --- a/tests/plotting/test_scatter.py +++ b/tests/plotting/test_scatter.py @@ -22,6 +22,7 @@ matplotlib.use("Agg") import matplotlib.pyplot as plt # noqa: E402 from matplotlib.axes import Axes # noqa: E402 +from matplotlib.collections import LineCollection, PathCollection # noqa: E402 from matplotlib.colorbar import Colorbar # noqa: E402 from solarwindpy.plotting.base import AxesLabels, ClipAxes, LogAxes # noqa: E402 @@ -378,3 +379,184 @@ def test_scatter_figure_renders_to_png(): finally: plt.close("all") assert buffer.getvalue().startswith(b"\x89PNG\r\n\x1a\n") # PNG signature + + +# --------------------------------------------------------------------------- +# edges: line segments joining consecutive points, in source row order. EZ is +# chosen so each segment's mean z, (z[i] + z[i+1]) / 2, is distinct. +# --------------------------------------------------------------------------- + +EX = np.array([0.0, 1.0, 2.0, 3.0, 4.0]) +EY = np.array([0.0, 1.0, 0.0, 1.0, 0.0]) +EZ = np.array([0.0, 2.0, 9.0, 6.0, 8.0]) + +_EDGES_PENDING = pytest.mark.xfail( + strict=True, reason="Scatter.make_plot(edges=True) is not implemented" +) + + +def _segments(x, y, pairs): + return [np.array([[x[i], y[i]], [x[j], y[j]]]) for i, j in pairs] + + +def _assert_segments(lc, x, y, pairs): + got = lc.get_segments() + assert len(got) == len(pairs) + for g, e in zip(got, _segments(x, y, pairs)): + np.testing.assert_array_equal(g, e) + + +@_EDGES_PENDING +def test_make_plot_returns_ax_points_edges_then_cbar(ax): + """``(ax, points, edges, cbar)``; edges is None unless ``edges=True``. + + ON FAILURE: the code is wrong. + """ + out = Scatter(EX, EY, EZ).make_plot(ax=ax) + assert len(out) == 4 + assert out[0] is ax + assert isinstance(out[1], PathCollection) + assert out[2] is None + assert isinstance(out[3], Colorbar) + assert not any(isinstance(c, LineCollection) for c in ax.collections) + + out = Scatter(EX, EY, EZ).make_plot(ax=ax, edges=True) + assert len(out) == 4 + assert isinstance(out[2], LineCollection) + assert out[2] in ax.collections + + +@_EDGES_PENDING +def test_edges_join_each_pair_of_consecutive_points(ax): + """n points in row order give n - 1 segments, point i to point i + 1. + + ON FAILURE: the code is wrong. + """ + _, _, lc, _ = Scatter(EX, EY, EZ).make_plot(ax=ax, edges=True) + _assert_segments(lc, EX, EY, [(0, 1), (1, 2), (2, 3), (3, 4)]) + + +@_EDGES_PENDING +def test_edge_colour_is_the_mean_endpoint_z_through_the_points_cmap_and_norm(ax): + """Segment i is ``cmap(norm((z[i] + z[i+1]) / 2))``: one colorbar serves both. + + ON FAILURE: the code is wrong. + """ + _, points, lc, cbar = Scatter(EX, EY, EZ).make_plot( + ax=ax, edges=True, cmap="plasma" + ) + mean = (EZ[:-1] + EZ[1:]) / 2 + np.testing.assert_array_equal(lc.get_array(), mean) + assert lc.norm is points.norm + assert lc.get_cmap() is points.get_cmap() + assert (points.norm.vmin, points.norm.vmax) == (EZ.min(), EZ.max()) + lc.update_scalarmappable() + expected = points.get_cmap()(points.norm(mean)) + np.testing.assert_allclose(lc.get_edgecolor(), expected) + assert cbar.mappable is points + + +@_EDGES_PENDING +def test_edges_follow_a_norm_the_caller_passes(ax): + """``vmin``/``vmax`` given to the points also set the edges' colours. + + ON FAILURE: the code is wrong. + """ + _, points, lc, _ = Scatter(EX, EY, EZ).make_plot( + ax=ax, edges=True, vmin=0.0, vmax=20.0 + ) + assert lc.norm is points.norm + assert (lc.norm.vmin, lc.norm.vmax) == (0.0, 20.0) + + +@_EDGES_PENDING +def test_a_point_with_nan_breaks_the_chain(ax): + """A dropped NaN point removes both its segments; no segment bridges it. + + ON FAILURE: the code is wrong. + """ + y = EY.copy() + y[2] = np.nan + _, _, lc, _ = Scatter(EX, y, EZ).make_plot(ax=ax, edges=True) + _assert_segments(lc, EX, y, [(0, 1), (3, 4)]) + np.testing.assert_array_equal(lc.get_array(), [1.0, 7.0]) + + +@_EDGES_PENDING +def test_a_point_outside_alim_breaks_the_chain(ax): + """A point ``alim`` hides drops both its segments, as a NaN point does. + + EZ[2] = 9 is the only z above 8, so two segments go, not one. + ON FAILURE: the code is wrong. + """ + sc = Scatter(EX, EY, EZ) + sc.set_alim(None, 8.0) + _, _, lc, _ = sc.make_plot(ax=ax, edges=True) + _assert_segments(lc, EX, EY, [(0, 1), (3, 4)]) + np.testing.assert_array_equal(lc.get_array(), [1.0, 7.0]) + + +@_EDGES_PENDING +def test_a_masked_point_breaks_the_chain(ax): + """A point ``mask`` excludes drops both its segments. + + ON FAILURE: the code is wrong. + """ + mask = pd.Series([True, True, True, False, True]) + _, _, lc, _ = Scatter(EX, EY, EZ, mask=mask).make_plot(ax=ax, edges=True) + _assert_segments(lc, EX, EY, [(0, 1), (1, 2)]) + + +@_EDGES_PENDING +def test_consecutive_is_row_position_not_label(ax): + """Rows are joined in the order given, even with repeated or unsorted labels. + + ON FAILURE: the code is wrong. + """ + index = [3, 3, 1, 0, 2] + x, y, z = (pd.Series(v, index=index) for v in (EX, EY, EZ)) + _, _, lc, _ = Scatter(x, y, z).make_plot(ax=ax, edges=True) + _assert_segments(lc, EX, EY, [(0, 1), (1, 2), (2, 3), (3, 4)]) + + +@_EDGES_PENDING +@pytest.mark.parametrize("z", [None, pd.Series(7.0, index=range(EX.size))]) +def test_edges_without_varying_z_have_one_colour(ax, z): + """With no z, or a constant one, every segment has the points' colour. + + ON FAILURE: the code is wrong. + """ + _, points, lc, cbar = Scatter(EX, EY, z).make_plot(ax=ax, edges=True) + assert cbar is None + assert lc.get_array() is None + _assert_segments(lc, EX, EY, [(0, 1), (1, 2), (2, 3), (3, 4)]) + colors = lc.get_edgecolor() + assert len(colors) == 1 + np.testing.assert_array_equal(colors[0], points.get_facecolor()[0]) + + +@_EDGES_PENDING +def test_edges_sit_below_the_points_and_take_edge_kwargs(ax): + """Edges default to beneath the markers; ``edge_kwargs`` styles them. + + ON FAILURE: the code is wrong. + """ + _, points, lc, _ = Scatter(EX, EY, EZ).make_plot(ax=ax, edges=True) + assert lc.get_zorder() < points.get_zorder() + + kwargs = {"linewidth": 3.0, "alpha": 0.4, "zorder": 5} + _, _, lc, _ = Scatter(EX, EY, EZ).make_plot(ax=ax, edges=True, edge_kwargs=kwargs) + assert kwargs == {"linewidth": 3.0, "alpha": 0.4, "zorder": 5} + np.testing.assert_array_equal(lc.get_linewidth(), [3.0]) + assert (lc.get_alpha(), lc.get_zorder()) == (0.4, 5) + + +@_EDGES_PENDING +def test_edges_do_not_change_the_axis_limits(ax): + """The view fits the points with or without edges. + + ON FAILURE: the code is wrong. + """ + Scatter(EX, EY, EZ).make_plot(ax=ax, edges=True) + assert ax.get_xlim() == (EX.min(), EX.max()) + assert ax.get_ylim() == (EY.min(), EY.max()) From fff5c7cf63b35bd2856ec258d7762b6be8ebf228 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:05:16 -0500 Subject: [PATCH 11/60] feat(plotting): get_plotted_data, the rows in the cells a figure shows BinnedPlot.get_plotted_data(fcn=None) returns the caller's x, y and z on the rows whose cell agg(fcn) leaves non-NaN, after clim, axnorm, any cell filter and alim. A lookup table indexed by the rows' cell codes replaces np.isin, and the codes are computed once per plot (cached on the binning and data, read-only) and shared with agg. Hist1D.construct_cdf and Hist2D.project_1d use the same mask. The old selection methods stay for now; on the evaluation datasets (NaN, log axes, values on edges, empty bins with clim, clip; Hist1D, Hist2D, SpiralPlot2D; 1e5 and 1e6 rows) the new rows equal theirs. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++ src/solarwindpy/plotting/base.py | 76 ++++++++++++++++++++++---- src/solarwindpy/plotting/hist1d.py | 6 +- src/solarwindpy/plotting/hist2d.py | 2 +- tests/plotting/test_plot_invariants.py | 6 ++ tests/plotting/test_plotted_data.py | 7 --- 6 files changed, 79 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 580d8b018..947a53d9c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `solarwindpy.core.plasma.Plasma.info` returns a one-column table summarising a plasma: the spacecraft and its frame (or "none"), the first and last observation times, the number of observations, the species, and whether auxiliary data are attached. +- `get_plotted_data(fcn=None)` on `Hist1D`, `Hist2D` and `SpiralPlot2D` returns the rows in the + cells the figure shows (cells whose `agg(fcn)` is not NaN after `clim`, `axnorm`, any cell + filter and `alim`), with the caller's x, y and z values on the caller's index. Pass the `fcn` + given to `make_plot`. Each plot computes its rows' cell codes once and reuses them in `agg`. ### Changed diff --git a/src/solarwindpy/plotting/base.py b/src/solarwindpy/plotting/base.py index dc229e2be..fec7d89f7 100644 --- a/src/solarwindpy/plotting/base.py +++ b/src/solarwindpy/plotting/base.py @@ -879,9 +879,25 @@ def agg_axes(self): r"""The axis to aggregate into, e.g. the z variable in an (x, y, z) heatmap.""" return self._source.columns[-1] + def _cell_codes(self): + r"""``binning.codes()``, computed once per binning and data, read-only. + + The binning and the data are each set once, by the constructor, but + the cache is keyed on both objects, so replacing either recomputes. + """ + binning = self.binning + source = self._source + cached = self.__dict__.get("_codes_cache") + if cached is None or cached[0] is not binning or cached[1] is not source: + codes = np.asarray(binning.codes()) + codes.setflags(write=False) + cached = (binning, source, codes) + self._codes_cache = cached + return cached[2] + def _grouped_by_cell(self): r"""The aggregated column on the rows in a cell, grouped by cell code.""" - codes = self.binning.codes() + codes = self._cell_codes() # By position: the groups are keyed by `codes`, never by row label. target = self._source.take(self.agg_axes, labels=False) inside = codes >= 0 @@ -964,10 +980,56 @@ def _rows_in_cells(self, positions): pd.Series On the index of ``data``. """ - codes = self.binning.codes() + codes = self._cell_codes() keep = np.isin(codes, positions) & (codes >= 0) return pd.Series(keep, index=self._kept_index()) + def _plotted_rows(self, fcn=None): + r"""Boolean array over the kept rows: True where the row's cell is shown. + + A cell is shown where ``agg(fcn)`` is not NaN. Looked up by cell code, + with code -1 (no cell) mapped to the appended False. + """ + shown = self.agg(fcn=fcn).notna().to_numpy() + return np.append(shown, False)[self._cell_codes()] + + def _kept_source_frame(self): + r"""The caller's values on the kept rows, one column per ``data`` column. + + No ``10**`` round trip: a logged axis holds the values as passed, + sign included. + """ + source = self._source + return pd.DataFrame( + {k: source.take(k) for k in source.columns}, + index=self._kept_index(), + copy=False, + ) + + def get_plotted_data(self, fcn=None): + r"""The rows in the cells the figure shows. + + A cell is shown when ``agg(fcn)`` is not NaN there: after ``clim``, + ``axnorm``, any cell filter (a spiral mesh's ``cell_filter``) and, on + a ``ColorPlot``, ``alim``. ``alim`` acts on the aggregated value, so + pass the ``fcn`` you gave ``make_plot``; the default is the same as + ``make_plot``'s. + + Parameters + ---------- + fcn : str or callable, optional + The aggregation, as ``agg`` takes it. + + Returns + ------- + pd.DataFrame + One column per column of ``data`` (``x``, ``y`` and, on a 2-D + plot, ``z``), on the caller's index labels, in the caller's row + order. The values are the caller's: never logged, sign included, + whatever ``log`` says. + """ + return self._kept_source_frame().loc[self._plotted_rows(fcn)] + def get_plotted_data_boolean_series(self): """Return a boolean ``pd.Series`` identifying each plotted measurement. @@ -1003,15 +1065,7 @@ def get_subset_above_threshold(self, threshold, fcn="count"): agg = self.agg(fcn=fcn) tk = self._rows_in_cells(np.flatnonzero((agg >= threshold).to_numpy())) - # The source's values on the kept rows: no 10** round trip, so only - # what was stored logged differs from `data`, and it is not inverted. - source = self._source - subset = pd.DataFrame( - {k: source.take(k) for k in source.columns}, - index=self._kept_index(), - copy=False, - ) - subset = subset.loc[tk.to_numpy(dtype=bool)] + subset = self._kept_source_frame().loc[tk.to_numpy(dtype=bool)] return subset, tk diff --git a/src/solarwindpy/plotting/hist1d.py b/src/solarwindpy/plotting/hist1d.py index 35102c87a..edacdd387 100644 --- a/src/solarwindpy/plotting/hist1d.py +++ b/src/solarwindpy/plotting/hist1d.py @@ -131,7 +131,7 @@ def construct_cdf(self, only_plotted=True): ---------- only_plotted : bool If True, use only the measurements in bins that survive - aggregation (see ``get_plotted_data_boolean_series``). Otherwise, + aggregation (see ``get_plotted_data``). Otherwise, use every measurement inside the bins. Returns @@ -149,9 +149,9 @@ def construct_cdf(self, only_plotted=True): cdf.plot(x="x", y="position") """ data = self.data - tk = self.cut.loc[:, "x"].notna() + tk = self.cut.loc[:, "x"].notna().to_numpy() if only_plotted: - tk = tk & self.get_plotted_data_boolean_series() + tk = tk & self._plotted_rows() x = data.loc[tk, "x"] # Stable sort, so tied x values keep their original label order. diff --git a/src/solarwindpy/plotting/hist2d.py b/src/solarwindpy/plotting/hist2d.py index c96570041..756996344 100644 --- a/src/solarwindpy/plotting/hist2d.py +++ b/src/solarwindpy/plotting/hist2d.py @@ -740,7 +740,7 @@ def project_1d(self, axis, only_plotted=True, project_counts=False, **kwargs): x = source.take(axis, labels=False) keep = np.ones(x.size, dtype=bool) if only_plotted: - keep &= self.get_plotted_data_boolean_series().to_numpy(dtype=bool) + keep &= self._plotted_rows() if not project_counts and other != "z": keep &= self.binning.axis_codes()[other] >= 0 diff --git a/tests/plotting/test_plot_invariants.py b/tests/plotting/test_plot_invariants.py index ea72bd066..5d21ea5b8 100644 --- a/tests/plotting/test_plot_invariants.py +++ b/tests/plotting/test_plot_invariants.py @@ -277,6 +277,11 @@ def _select_plotted(b): return [Selection(_where(b.h.get_plotted_data_boolean_series()), None, True)] +def _select_plotted_data(b): + rows = b.h.get_plotted_data() + return [Selection(rows.index, rows, True)] + + def _select_above_threshold(b): # The median bin count: some bins reach it, some do not. threshold = b.h.agg(fcn="count").dropna().median() @@ -363,6 +368,7 @@ def _select_projection(b): "data": _select_data, "cut": _select_cut, "get_plotted_data_boolean_series": _select_plotted, + "get_plotted_data": _select_plotted_data, "get_subset_above_threshold": _select_above_threshold, "id_data_above_contour": _select_above_contour, "take_data_in_yrange_across_x": _select_in_yrange, diff --git a/tests/plotting/test_plotted_data.py b/tests/plotting/test_plotted_data.py index 64351b9c4..3b4f0c4ac 100644 --- a/tests/plotting/test_plotted_data.py +++ b/tests/plotting/test_plotted_data.py @@ -22,8 +22,6 @@ from solarwindpy.plotting.spiral import SpiralPlot2D # noqa: E402 from tests.tolerances import exact # noqa: E402 -_NEW = pytest.mark.xfail(strict=True, reason="get_plotted_data does not exist yet") - XEDGES = np.array([0.0, 1.0, 2.0, 3.0]) YEDGES = np.array([0.0, 1.0, 2.0]) @@ -57,7 +55,6 @@ def _hist2d(z=None): return Hist2D(X, Y, z, nbins=[XEDGES, YEDGES]) -@_NEW @pytest.mark.parametrize("lower", [None, 2, 3]) def test_hist2d_returns_the_rows_of_cells_meeting_clim(lower): """With ``clim`` lower bound n, the rows of cells holding at least n rows. @@ -76,7 +73,6 @@ def test_hist2d_returns_the_rows_of_cells_meeting_clim(lower): assert got.loc[:, "y"].to_numpy() == exact(Y[expected].to_numpy()) -@_NEW def test_alim_acts_on_the_aggregated_value_of_the_given_fcn(): """``alim`` on z means hides cell (0, 0) (mean 2); ``fcn="max"`` keeps it (max 3). @@ -92,7 +88,6 @@ def test_alim_acts_on_the_aggregated_value_of_the_given_fcn(): assert h.get_plotted_data().loc[:, "z"].tolist() == [4.0, 8.0, 9.0] -@_NEW def test_a_log_axis_returns_the_callers_signed_values(): """On a log x the rows hold the caller's x, negative ones included. @@ -108,7 +103,6 @@ def test_a_log_axis_returns_the_callers_signed_values(): assert got.loc[:, "x"].tolist() == [-10.0, 100.0] -@_NEW def test_hist1d_returns_the_rows_of_bins_meeting_clim(): """Hist1D of x: bins hold 3, 2 and 1 rows; clim 2 keeps labels 10 to 14. @@ -127,7 +121,6 @@ def test_hist1d_returns_the_rows_of_bins_meeting_clim(): assert got.loc[:, "x"].tolist() == X[expected].tolist() -@_NEW def test_spiral_returns_as_many_rows_as_its_shown_cells_count(): """A spiral's plotted rows number the counts of the cells ``agg`` shows. From c4f111fc8357174ddbd050ac437564be62816ef4 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:05:22 -0500 Subject: [PATCH 12/60] fix(plotting): skip empty bins when smoothing a Hist2D's contours With gaussian_filter_std and the default nan_aware_filter=False, the plain scipy Gaussian filter spread each empty (NaN) bin over its kernel, blanking the bins around every gap; on a small or sparse grid no contour was left. One helper now smooths the grid for plot_contours and plot_hist_with_contours: the NaN-aware normalized convolution when the grid has empty bins, scipy.ndimage.gaussian_filter otherwise, so a grid without gaps gives exactly the previous result in every filter mode. The nan_aware_filter keyword is removed: the filter chooses on its own, and the False setting only selected the defect. SpiralPlot2D already rejects the keyword. The usage guide drops it, and its plot_edges note follows the previous commit's default window. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 + docs/source/usage.rst | 13 +- src/solarwindpy/plotting/hist2d.py | 72 +++++------ tests/plotting/test_hist2d_plotting.py | 169 ++++++++++++++----------- 4 files changed, 143 insertions(+), 117 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b405ff270..22e763d6e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `Hist2D.plot_edges` no longer raises below 50 x-bins. The default Savitzky-Golay window, 10% of the edge's points, is raised to the smallest odd length above `polyorder`, and an edge too short for any such window is drawn unsmoothed. +- `Hist2D.plot_contours` and `Hist2D.plot_hist_with_contours` with `gaussian_filter_std` + no longer erase the contours around empty bins. A grid with empty (NaN) bins is smoothed by + `solarwindpy.plotting.tools.nan_gaussian_filter`, which averages only the occupied bins; a + grid without them is filtered by `scipy.ndimage.gaussian_filter` as before, with unchanged + results. The `nan_aware_filter` keyword is removed: passing it raises an error from + matplotlib. ## [0.4.0] - 2026-11-05 diff --git a/docs/source/usage.rst b/docs/source/usage.rst index 3007a8086..28ad45824 100644 --- a/docs/source/usage.rst +++ b/docs/source/usage.rst @@ -197,15 +197,16 @@ draws a log axis. ``make_plot`` colors each cell by its count: :py:meth:`~solarwindpy.plotting.hist2d.Hist2D.plot_contours` draws the same histogram as contours. ``gaussian_filter_std`` smooths the values with a Gaussian whose standard deviation is in bins before the contours are drawn. -Set ``nan_aware_filter=True`` with it whenever the histogram has empty cells: -an empty cell is NaN, and the plain filter spreads each NaN over its -neighbours until no contour is left to draw. ``plot_edges=True`` also draws the +An empty cell is NaN; when there are any, the filter averages only the +occupied cells and leaves the empty ones empty, rather than spreading each NaN +over its neighbours. ``plot_edges=True`` also draws the edges of the occupied distribution (:py:meth:`~solarwindpy.plotting.hist2d.Hist2D.plot_edges`): in each column of ``x`` bins, the highest and the lowest occupied ``y`` bin, smoothed by a Savitzky-Golay filter unless ``edges_kwargs=dict(smooth=False)``. The -filter's default window is a tenth of the number of ``x`` bins, so with fewer -than 50 bins set ``window_length`` in ``edges_kwargs=dict(sg_kwargs=...)``. Here +filter's default window is a tenth of the number of ``x`` bins, widened to fit +its cubic polynomial when there are few bins; set ``window_length`` in +``edges_kwargs=dict(sg_kwargs=...)`` to choose another. Here ``axnorm="t"``, explained in `Normalizations`_, scales the peak to 1: .. plot:: @@ -223,7 +224,7 @@ than 50 bins set ``window_length`` in ``edges_kwargs=dict(sg_kwargs=...)``. Here h2 = Hist2D(v, n, logy=True, nbins=50, axnorm="t") h2.set_labels(x=TeXlabel(("v", "", "p1")), y=TeXlabel(("n", "", "p1"))) - h2.plot_contours(gaussian_filter_std=2, nan_aware_filter=True, plot_edges=True) + h2.plot_contours(gaussian_filter_std=2, plot_edges=True) :py:meth:`~solarwindpy.plotting.hist2d.Hist2D.make_joint_h2_h1_plot` draws the histogram with its projections on the top and right margins. Each margin is a diff --git a/src/solarwindpy/plotting/hist2d.py b/src/solarwindpy/plotting/hist2d.py index 79e9d62e3..c32c270c8 100644 --- a/src/solarwindpy/plotting/hist2d.py +++ b/src/solarwindpy/plotting/hist2d.py @@ -11,6 +11,7 @@ from matplotlib import pyplot as plt from collections import namedtuple +from scipy.ndimage import gaussian_filter from scipy.signal import savgol_filter @@ -193,9 +194,23 @@ def _prep_agg_for_plot(self, fcn=None, use_edges=True, mask_invalid=True): return C, x, y - def _nan_gaussian_filter(self, array, sigma, **kwargs): - """Wrapper for shared nan_gaussian_filter. See tools.nan_gaussian_filter.""" - return nan_gaussian_filter(array, sigma, **kwargs) + @staticmethod + def _gaussian_filter(array, sigma, kwargs): + r"""Smooth the grid ``array`` with a Gaussian of ``sigma`` bins. + + A grid without empty (NaN) bins is filtered by + :func:`scipy.ndimage.gaussian_filter`. A grid with empty bins is + filtered by :func:`~solarwindpy.plotting.tools.nan_gaussian_filter`, + which averages only the occupied neighbours and keeps the empty bins + empty: the plain filter spreads each NaN over the kernel, blanking the + bins around every gap. ``kwargs``, a dict or None, is passed to the + filter. + """ + kwargs = {} if kwargs is None else kwargs + array = np.asarray(array, dtype=float) + if np.isnan(array).any(): + return nan_gaussian_filter(array, sigma, **kwargs) + return gaussian_filter(array, sigma, **kwargs) def make_plot( self, @@ -280,7 +295,6 @@ def plot_hist_with_contours( contour_kwargs=None, gaussian_filter_std=0, gaussian_filter_kwargs=None, - nan_aware_filter=False, **kwargs, ): """Make a 2D pcolormesh plot with contour overlay. @@ -305,12 +319,11 @@ def plot_hist_with_contours( contour_kwargs : dict, None Additional kwargs passed to contour/contourf (e.g., linestyles, colors). gaussian_filter_std : int - If > 0, apply Gaussian filter to contour data. + If > 0, smooth the contour data with a Gaussian of this standard + deviation, in bins, as :py:meth:`plot_contours` does: the filter + skips empty bins. gaussian_filter_kwargs : dict, None - Kwargs passed to `scipy.ndimage.gaussian_filter`. - nan_aware_filter : bool - If True and gaussian_filter_std > 0, use NaN-aware filtering via - normalized convolution. Otherwise use standard scipy.ndimage.gaussian_filter. + Kwargs passed to the Gaussian filter. kwargs : Passed to `ax.pcolormesh`. `norm` defaults as in `make_plot` and is shared by the mesh and the contours. @@ -351,19 +364,9 @@ def plot_hist_with_contours( # Apply Gaussian filter if requested if needs_filter: - if gaussian_filter_kwargs is None: - gaussian_filter_kwargs = {} - - if nan_aware_filter: - C_centers = self._nan_gaussian_filter( - C_centers, gaussian_filter_std, **gaussian_filter_kwargs - ) - else: - from scipy.ndimage import gaussian_filter - - C_centers = gaussian_filter( - C_centers, gaussian_filter_std, **gaussian_filter_kwargs - ) + C_centers = self._gaussian_filter( + C_centers, gaussian_filter_std, gaussian_filter_kwargs + ) C_centers = np.ma.masked_invalid(C_centers) @@ -582,7 +585,6 @@ def plot_contours( use_contourf=False, gaussian_filter_std=0, gaussian_filter_kwargs=None, - nan_aware_filter=False, levels=None, **kwargs, ): @@ -605,13 +607,13 @@ def plot_contours( use_contourf: bool If True, use `ax.contourf`. Else use `ax.contour`. gaussian_filter_std: int - If > 0, apply `scipy.ndimage.gaussian_filter` to the z-values using the - standard deviation specified by `gaussian_filter_std`. + If > 0, smooth the z-values with a Gaussian of this standard + deviation, in bins. A grid without empty bins is filtered by + :func:`scipy.ndimage.gaussian_filter`; a grid with empty bins by + :func:`~solarwindpy.plotting.tools.nan_gaussian_filter`, which + averages only the occupied bins and leaves the empty ones empty. gaussian_filter_kwargs: None, dict - If not None and gaussian_filter_std > 0, passed to :func:`scipy.ndimage.gaussian_filter` - nan_aware_filter: bool - If True and gaussian_filter_std > 0, use NaN-aware filtering via - normalized convolution. Otherwise use standard scipy.ndimage.gaussian_filter. + If not None and gaussian_filter_std > 0, passed to the filter. levels: array-like, int, None Contour levels. If None, the default for the ``axnorm``, or matplotlib's choice when there is none. @@ -650,17 +652,7 @@ def plot_contours( C = agg.values if gaussian_filter_std: - if gaussian_filter_kwargs is None: - gaussian_filter_kwargs = dict() - - if nan_aware_filter: - C = self._nan_gaussian_filter( - C, gaussian_filter_std, **gaussian_filter_kwargs - ) - else: - from scipy.ndimage import gaussian_filter - - C = gaussian_filter(C, gaussian_filter_std, **gaussian_filter_kwargs) + C = self._gaussian_filter(C, gaussian_filter_std, gaussian_filter_kwargs) C = np.ma.masked_invalid(C) diff --git a/tests/plotting/test_hist2d_plotting.py b/tests/plotting/test_hist2d_plotting.py index 216db75be..29e56e495 100644 --- a/tests/plotting/test_hist2d_plotting.py +++ b/tests/plotting/test_hist2d_plotting.py @@ -166,6 +166,21 @@ def smoothable_hist(): return _moving_band_hist(61) +def _contour_set(hist, method, **kwargs): + """The contour set ``method`` (a contour-drawing method name) draws on ``hist``.""" + out = getattr(hist, method)(cbar=False, **kwargs) + return out[2] if method == "plot_hist_with_contours" else out[1] + + +def _assert_same_contours(got, want): + """``got`` and ``want`` hold the same vertices at every level.""" + assert len(got.allsegs) == len(want.allsegs) + for got_at_level, want_at_level in zip(got.allsegs, want.allsegs): + assert len(got_at_level) == len(want_at_level) + for g, w in zip(got_at_level, want_at_level): + assert np.asarray(g) == exact(w) + + def _expected_grid(counts): """``counts`` with empty bins as NaN, matching an unstacked aggregation.""" expected = counts.astype(float) @@ -342,50 +357,6 @@ def test_mesh_aggregates_with_the_callers_fcn(self, z_valued_hist): ) plt.close("all") - def test_nan_aware_filter_contours_the_normalised_convolution( - self, known_hist, known_counts - ): - """With ``nan_aware_filter`` the contours trace the normalised convolution. - - ``KNOWN_COUNTS`` leaves bins empty, so the grid has NaN gaps. The - expectation is computed here from the algorithm the docstring names - (Knutsson & Westin 1993, normalised convolution): smooth the grid with - gaps set to 0, divide by the smoothed validity mask, and keep the gaps - blank. Contouring that grid at the same levels must reproduce the - overlay vertex for vertex. - - ON FAILURE: the code is wrong. - """ - levels = [0.2, 0.4, 0.6] - sigma = 1.0 - known_hist.set_axnorm("t") - _, _, qset, _ = known_hist.plot_hist_with_contours( - cbar=False, - levels=levels, - use_contourf=True, - gaussian_filter_std=sigma, - nan_aware_filter=True, - ) - - # axnorm "t" divides every bin by the largest bin count in the grid. - grid = _expected_grid(known_counts) / known_counts.max() - valid = ~np.isnan(grid) - smoothed = gaussian_filter(np.where(valid, grid, 0.0), sigma) / gaussian_filter( - valid.astype(float), sigma - ) - smoothed[~valid] = np.nan - XX, YY = np.meshgrid(_bin_centers(XEDGES), _bin_centers(YEDGES)) - _, ref_ax = plt.subplots() - expected = ref_ax.contourf(XX, YY, np.ma.masked_invalid(smoothed), levels) - - assert sum(len(segs) for segs in expected.allsegs) > 0 # contours exist - assert len(qset.allsegs) == len(expected.allsegs) - for got_at_level, want_at_level in zip(qset.allsegs, expected.allsegs): - assert len(got_at_level) == len(want_at_level) - for got, want in zip(got_at_level, want_at_level): - assert np.asarray(got) == exact(want) - plt.close("all") - class TestPlotContours: """Tests for plot_contours method.""" @@ -2229,38 +2200,94 @@ def complete_hist(self): x, y = _points_from_counts(counts, edges, edges) return Hist2D(x, y, nbins=[edges, edges], axnorm="t") - def test_nan_aware_filter_reduces_to_the_plain_filter_without_gaps( - self, complete_hist + @pytest.mark.parametrize("method", ["plot_contours", "plot_hist_with_contours"]) + @pytest.mark.parametrize("mode", ["reflect", "constant"]) + def test_without_gaps_the_filter_is_scipy_gaussian_filter( + self, complete_hist, method, mode ): - """With no missing bins the two filters must agree exactly. + """With no empty bins the smoothing is exactly ``scipy.ndimage.gaussian_filter``. - `nan_aware_filter` is a normalised convolution: the weighted average is - divided by the summed weight of the *valid* neighbours. When every - neighbour is valid that divisor is the full kernel sum, and the - expression collapses to an ordinary Gaussian convolution. So this is an - identity the implementation has to satisfy, not a recorded agreement. + The expectation is the grid filtered by scipy directly, with the same + keywords, and contoured at the same levels. - ON FAILURE: the code is wrong -- one of the two filters is not doing - what its name says. + ON FAILURE: the code is wrong. """ - assert not np.isnan(complete_hist.agg().unstack("x").values).any() - - plain = complete_hist.plot_contours( - gaussian_filter_std=1.5, - nan_aware_filter=False, - cbar=False, - )[1] - nan_aware = complete_hist.plot_contours( + grid = complete_hist.agg().unstack("x").values + assert not np.isnan(grid).any() + levels = [0.3, 0.5, 0.7] + got = _contour_set( + complete_hist, + method, + levels=levels, + use_contourf=False, gaussian_filter_std=1.5, - nan_aware_filter=True, - cbar=False, - )[1] - - assert len(plain.allsegs) == len(nan_aware.allsegs) - for at_plain, at_nan_aware in zip(plain.allsegs, nan_aware.allsegs): - assert len(at_plain) == len(at_nan_aware) - for left, right in zip(at_plain, at_nan_aware): - np.testing.assert_allclose(left, right) + gaussian_filter_kwargs={"mode": mode}, + ) + + x = complete_hist.intervals["x"].mid + y = complete_hist.intervals["y"].mid + XX, YY = np.meshgrid(x, y) + _, ref_ax = plt.subplots() + want = ref_ax.contour(XX, YY, gaussian_filter(grid, 1.5, mode=mode), levels) + _assert_same_contours(got, want) + plt.close("all") + + @pytest.mark.parametrize("method", ["plot_contours", "plot_hist_with_contours"]) + def test_with_gaps_the_filter_is_the_normalised_convolution( + self, known_hist, known_counts, method + ): + """Empty bins are skipped by the smoothing, not spread over the grid. + + ``KNOWN_COUNTS`` leaves bins empty, so the grid has NaN gaps. A plain + Gaussian filter spreads each NaN over the kernel, and on this grid + erases every contour. The expectation is computed here from the + normalised convolution (Knutsson & Westin 1993): smooth the grid with + gaps set to 0, divide by the smoothed validity mask, and keep the gaps + blank. Contouring that grid at the same levels must reproduce the + contours vertex for vertex. + + ON FAILURE: the code is wrong. + """ + levels = [0.2, 0.4, 0.6] + sigma = 1.0 + known_hist.set_axnorm("t") + got = _contour_set( + known_hist, + method, + levels=levels, + use_contourf=True, + gaussian_filter_std=sigma, + ) + + # axnorm "t" divides every bin by the largest bin count in the grid. + grid = _expected_grid(known_counts) / known_counts.max() + valid = ~np.isnan(grid) + smoothed = gaussian_filter(np.where(valid, grid, 0.0), sigma) / gaussian_filter( + valid.astype(float), sigma + ) + smoothed[~valid] = np.nan + XX, YY = np.meshgrid(_bin_centers(XEDGES), _bin_centers(YEDGES)) + _, ref_ax = plt.subplots() + want = ref_ax.contourf(XX, YY, np.ma.masked_invalid(smoothed), levels) + + assert sum(len(segs) for segs in want.allsegs) > 0 # contours exist + _assert_same_contours(got, want) + plt.close("all") + + @pytest.mark.parametrize("method", ["plot_contours", "plot_hist_with_contours"]) + def test_nan_aware_filter_keyword_is_rejected(self, complete_hist, method): + """The removed ``nan_aware_filter`` keyword fails loudly. + + The filter skips empty bins on its own, so the switch is gone. An + unknown keyword reaches matplotlib's contour call, which raises. + + ON FAILURE: the code is wrong -- the keyword is accepted again, or + unknown keywords are swallowed silently. + """ + with pytest.raises((AttributeError, TypeError)): + _contour_set( + complete_hist, method, gaussian_filter_std=1, nan_aware_filter=True + ) plt.close("all") From 35c70cd6c85e0f9416b47612bada15b044894ea5 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:11:02 -0500 Subject: [PATCH 13/60] fix(plotting): log SpiralPlot2D's timing and bin statistics at DEBUG Every SpiralPlot2D construction logged three WARNING records from calculate_bin_number (start time, elapsed time, largest bin and empty bins), and every make_plot four more (patch timing). They report normal operation, so they are DEBUG records now. The record that points fell outside the mesh and were dropped stays a warning: it reports lost data. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +++ src/solarwindpy/plotting/spiral.py | 14 +++++++------- tests/plotting/test_spiral.py | 25 +++++++++++++++++++++++++ 3 files changed, 35 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 22e763d6e..d38c10e22 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 grid without them is filtered by `scipy.ndimage.gaussian_filter` as before, with unchanged results. The `nan_aware_filter` keyword is removed: passing it raises an error from matplotlib. +- `SpiralPlot2D` no longer logs warnings on every construction and draw. Its timing and + bin-population messages report normal operation and are now DEBUG records; the message + that points outside the mesh are dropped stays a warning. ## [0.4.0] - 2026-11-05 diff --git a/src/solarwindpy/plotting/spiral.py b/src/solarwindpy/plotting/spiral.py index dc16e6450..e92c65d5a 100644 --- a/src/solarwindpy/plotting/spiral.py +++ b/src/solarwindpy/plotting/spiral.py @@ -624,7 +624,7 @@ def calculate_bin_number(self): each cell. """ logger = logging.getLogger(__name__) - logger.warning( + logger.debug( f"Calculating {self.__class__.__name__} bin_number at {datetime.now()}" ) mesh = self.mesh @@ -644,7 +644,7 @@ def calculate_bin_number(self): zbin, fill, bin_visited = _calculate_bin_number_with_numba(mesh, x, y) stop = datetime.now() - logger.warning(f"Elapsed time {stop - start}") + logger.debug(f"Elapsed time {stop - start}") if (zbin == fill).any(): logger.warning( @@ -658,7 +658,7 @@ def calculate_bin_number(self): # `minlength=nbins` forces us to include empty bins at the end of the array. bin_frequency = np.bincount(zbin[~is_fill], minlength=nbins) n_empty = (bin_frequency == 0).sum() - logger.warning(f"""Largest bin population is {bin_frequency.max()} + logger.debug(f"""Largest bin population is {bin_frequency.max()} {n_empty} of {nbins} bins ({100 * n_empty / nbins:.1f}%) are empty """) @@ -1016,8 +1016,8 @@ def make_plot( ymesh = 10.0**ymesh start1 = datetime.now() - self.logger.warning("Making patches") - self.logger.warning(f"Start {start1}") + self.logger.debug("Making patches") + self.logger.debug(f"Start {start1}") # One (N, 4, 2) array of each cell's corners, counter-clockwise from # the lower left, as a Rectangle traces them. @@ -1034,8 +1034,8 @@ def make_plot( ) stop1 = datetime.now() - self.logger.warning(f"Stop {stop1}") - self.logger.warning(f"Elapsed {stop1 - start1}") + self.logger.debug(f"Stop {stop1}") + self.logger.debug(f"Elapsed {stop1 - start1}") edgecolors = "none" linewidth = 0.0 diff --git a/tests/plotting/test_spiral.py b/tests/plotting/test_spiral.py index bd253d3da..a5330916a 100644 --- a/tests/plotting/test_spiral.py +++ b/tests/plotting/test_spiral.py @@ -1234,6 +1234,31 @@ def test_constructor_builds_the_mesh_without_the_progress_table(self, capsys): splot.initial_bins["x"], splot.initial_bins["y"], _points(), 1 ) + def test_constructing_and_drawing_log_no_warning(self, caplog): + """Building a ``SpiralPlot2D`` and drawing it log nothing at WARNING. + + Timing and bin statistics report normal operation, so they are DEBUG + records. Every point here lies inside the mesh, so nothing is dropped. + + ON FAILURE: the code is wrong. + """ + logging.disable(logging.NOTSET) + with caplog.at_level(logging.DEBUG): + splot = SpiralPlot2D( + X, + Y, + Z, + initial_bins=(np.array(XEDGES), np.array(YEDGES)), + min_per_bin=1, + ) + splot.make_plot() + plt.close("all") + assert [r for r in caplog.records if r.levelno >= logging.WARNING] == [] + assert any( + r.name.startswith("solarwindpy") and r.levelno == logging.DEBUG + for r in caplog.records + ) + # --------------------------------------------------------------------------- # The top initial edge. From 89bdc44719dac0ce56d85313f8bd8a5e94e56848 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:11:21 -0500 Subject: [PATCH 14/60] refactor(plotting)!: remove the selection methods get_plotted_data replaces get_plotted_data_boolean_series() equalled the mask of get_subset_above_threshold(-inf, fcn=None), and both went through _rows_in_cells; get_plotted_data(fcn) covers both. Tests that used them now use get_plotted_data with clim where they used a count threshold. BREAKING CHANGE: get_plotted_data_boolean_series and get_subset_above_threshold are removed; see the changelog for the migration, including the normalized Hist1D threshold that has none. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 10 +++++ src/solarwindpy/plotting/base.py | 56 -------------------------- tests/plotting/test_agg_full_grid.py | 3 +- tests/plotting/test_agg_plot.py | 48 +++++++++++----------- tests/plotting/test_architecture.py | 5 +-- tests/plotting/test_binned_data.py | 5 +-- tests/plotting/test_hist1d.py | 4 +- tests/plotting/test_hist2d_defects.py | 28 ++++++------- tests/plotting/test_hist2d_plotting.py | 4 +- tests/plotting/test_plot_invariants.py | 27 ++----------- 10 files changed, 58 insertions(+), 132 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 947a53d9c..5b9071223 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `.w`). `TrendFit` now refuses `yerr` in `trend_kwargs`, since its own `yerr=` selects the trend's uncertainties. No aliases are kept; the old keywords raise `TypeError`. To migrate, rename the keywords: `Line(x, y, weights=s, wmin=a)` becomes `Line(x, y, yerr=s, yerr_min=a)`. +- `get_plotted_data_boolean_series()` and `get_subset_above_threshold()` are removed from the + binned plots (`Hist1D`, `Hist2D`, `SpiralPlot2D`); `get_plotted_data(fcn=None)` replaces both. + It returns the rows of the cells the figure shows, with the caller's values on the caller's + index, as the subset did; for a boolean mask use `data.index.isin(plot.get_plotted_data().index)`. + `get_subset_above_threshold(t)` compared each cell's aggregate after `axnorm`: with no + `axnorm` and a count, it is `plot.set_clim(t, None)` then `plot.get_plotted_data()`; on a + `Hist2D` or `SpiralPlot2D` with an `axnorm` or another `fcn`, use `plot.set_alim(t, None)` + then `plot.get_plotted_data(fcn)`. A `Hist1D` has no `alim`, so a threshold on a normalized or + non-count `Hist1D` has no direct replacement: filter `plot.agg(fcn)` and select the rows of + the kept bins through `plot.cut`. ### Added diff --git a/src/solarwindpy/plotting/base.py b/src/solarwindpy/plotting/base.py index fec7d89f7..dd1855814 100644 --- a/src/solarwindpy/plotting/base.py +++ b/src/solarwindpy/plotting/base.py @@ -967,23 +967,6 @@ def _kept_index(self): index = self._source.index return index if rows is None else index[rows] - def _rows_in_cells(self, positions): - r"""Boolean ``pd.Series`` marking each kept row whose cell is in ``positions``. - - Parameters - ---------- - positions : np.ndarray of int - Cell codes, positions in ``binning.cells``. - - Returns - ------- - pd.Series - On the index of ``data``. - """ - codes = self._cell_codes() - keep = np.isin(codes, positions) & (codes >= 0) - return pd.Series(keep, index=self._kept_index()) - def _plotted_rows(self, fcn=None): r"""Boolean array over the kept rows: True where the row's cell is shown. @@ -1030,45 +1013,6 @@ def get_plotted_data(self, fcn=None): """ return self._kept_source_frame().loc[self._plotted_rows(fcn)] - def get_plotted_data_boolean_series(self): - """Return a boolean ``pd.Series`` identifying each plotted measurement. - - A measurement is plotted when its cell (e.g. its joint (x, y) bin in - 2-D) survives aggregation. The series shares the same index as the - stored data. To align with a different index you may need to adjust - the returned series. - """ - agg = self.agg() - tk = self._rows_in_cells(np.flatnonzero(agg.notna().to_numpy())) - - self.logger.info( - f"Taking {tk.sum()!s} ({100 * tk.mean():.1f}%) {self.__class__.__name__} spectra" - ) - - return tk - - def get_subset_above_threshold(self, threshold, fcn="count"): - r"""Get the subset of data above a given threshold using `fcn` to. - - aggregate. If `axnorm` set, this is used. A row is kept when its cell - (e.g. its joint (x, y) bin in 2-D) meets `threshold`. - - Returns - ------- - subset : pd.DataFrame - The kept rows, one column per column of ``data``, holding the - values the caller passed: never logged, sign included, whatever - ``log`` says. - tk : pd.Series of bool - True for each kept row, on the index of ``data``. - """ - agg = self.agg(fcn=fcn) - tk = self._rows_in_cells(np.flatnonzero((agg >= threshold).to_numpy())) - - subset = self._kept_source_frame().loc[tk.to_numpy(dtype=bool)] - - return subset, tk - class _OnFixedGrid: r"""The bins of a plot whose ``binning`` is a ``FixedGrid``, and its rows in them. diff --git a/tests/plotting/test_agg_full_grid.py b/tests/plotting/test_agg_full_grid.py index 4c9100068..c91a9cf14 100644 --- a/tests/plotting/test_agg_full_grid.py +++ b/tests/plotting/test_agg_full_grid.py @@ -209,8 +209,7 @@ def test_the_plotted_rows_are_the_binned_rows(spec): ON FAILURE: the code is wrong. """ h = _hist(spec) - plotted = h.get_plotted_data_boolean_series() - assert plotted.index.equals(X.index) + plotted = X.index.isin(h.get_plotted_data().index) assert plotted.tolist() == spec["plotted"] diff --git a/tests/plotting/test_agg_plot.py b/tests/plotting/test_agg_plot.py index c19afdf40..8e5796dc9 100644 --- a/tests/plotting/test_agg_plot.py +++ b/tests/plotting/test_agg_plot.py @@ -497,8 +497,7 @@ def test_plotted_mask_marks_every_point_in_a_bin_that_survives_clim(self, xyz): x, y, _ = xyz h = Hist2D(x, y, nbins=[X_EDGES, Y_EDGES]) h.set_clim(self.CLIM, None) - mask = h.get_plotted_data_boolean_series() - assert mask.index.equals(h.data.index) + mask = x.index.isin(h.get_plotted_data().index) assert mask[_count_of_own_bin(x, y) >= self.CLIM].all() def test_plotted_mask_excludes_points_in_bins_dropped_by_clim(self, xyz): @@ -509,36 +508,36 @@ def test_plotted_mask_excludes_points_in_bins_dropped_by_clim(self, xyz): x, y, _ = xyz h = Hist2D(x, y, nbins=[X_EDGES, Y_EDGES]) h.set_clim(self.CLIM, None) - mask = h.get_plotted_data_boolean_series().to_numpy() + mask = x.index.isin(h.get_plotted_data().index) dropped = _count_of_own_bin(x, y) < self.CLIM if mask[dropped].any(): raise SelectedPointInDroppedBin(f"{mask[dropped].sum()} points") - def test_subset_above_threshold_holds_every_row_in_a_dense_bin(self, xyz): - """Every row whose bin count is >= 14 is in the subset, unchanged. + def test_plotted_data_with_clim_is_every_row_of_a_dense_bin(self, xyz): + """With clim (14, None) the rows are those whose bin holds >= 14, unchanged. ON FAILURE: the code is wrong. """ x, y, z = xyz h = Hist2D(x, y, z, nbins=[X_EDGES, Y_EDGES]) - subset, mask = h.get_subset_above_threshold(self.THRESHOLD) + h.set_clim(self.THRESHOLD, None) + subset = h.get_plotted_data() dense = _count_of_own_bin(x, y) >= self.THRESHOLD - assert mask[dense].all() - pd.testing.assert_frame_equal(subset, h.data.loc[mask]) expected = pd.DataFrame({"x": x, "y": y, "z": z})[dense] - pd.testing.assert_frame_equal(subset.loc[expected.index], expected) + pd.testing.assert_frame_equal(subset, expected) - def test_subset_above_threshold_excludes_rows_in_sparse_bins(self, xyz): - """No row whose bin count is < 14 is in the subset. + def test_plotted_data_with_clim_excludes_rows_in_sparse_bins(self, xyz): + """No row whose bin count is < 14 is returned. ON FAILURE: the code is wrong. """ x, y, z = xyz h = Hist2D(x, y, z, nbins=[X_EDGES, Y_EDGES]) - subset, mask = h.get_subset_above_threshold(self.THRESHOLD) + h.set_clim(self.THRESHOLD, None) + mask = x.index.isin(h.get_plotted_data().index) sparse = _count_of_own_bin(x, y) < self.THRESHOLD - if mask.to_numpy()[sparse].any(): - raise SelectedPointInDroppedBin(f"{mask.to_numpy()[sparse].sum()} rows") + if mask[sparse].any(): + raise SelectedPointInDroppedBin(f"{mask[sparse].sum()} rows") def test_1d_plotted_mask_follows_clim(self, xyz): """In 1-D a point is plotted iff its x bin holds >= 52 points. @@ -552,11 +551,11 @@ def test_1d_plotted_mask_follows_clim(self, xyz): assert 0 < expected.sum() < N h = Hist1D(x, nbins=X_EDGES) h.set_clim(52, None) - mask = h.get_plotted_data_boolean_series() - np.testing.assert_array_equal(mask.to_numpy(), expected) + mask = x.index.isin(h.get_plotted_data().index) + np.testing.assert_array_equal(mask, expected) - def test_1d_subset_above_threshold_keeps_rows_in_dense_bins(self, xyz): - """In 1-D the subset is the rows whose x bin holds >= 52 points. + def test_1d_plotted_data_with_clim_keeps_rows_in_dense_bins(self, xyz): + """In 1-D, with clim (52, None), the rows are those whose x bin holds >= 52. ON FAILURE: the code is wrong. """ @@ -564,20 +563,21 @@ def test_1d_subset_above_threshold_keeps_rows_in_dense_bins(self, xyz): counts, _ = np.histogram(x, bins=X_EDGES) expected = (counts >= 52)[_bin_index(x.to_numpy(), X_EDGES)] h = Hist1D(x, nbins=X_EDGES) - subset, mask = h.get_subset_above_threshold(52) - np.testing.assert_array_equal(mask.to_numpy(), expected) + h.set_clim(52, None) + subset = h.get_plotted_data() + np.testing.assert_array_equal(x.index.isin(subset.index), expected) np.testing.assert_array_equal(subset["x"].to_numpy(), x.to_numpy()[expected]) - def test_subset_above_threshold_returns_linear_values_for_log_axes(self, xyz): - """With log axes the subset holds x and y in linear units again. + def test_plotted_data_returns_linear_values_for_log_axes(self, xyz): + """With log axes the plotted rows hold x and y in linear units. ON FAILURE: the code is wrong. """ x, y, _ = xyz x, y = 10.0**x, 10.0**y h = Hist2D(x, y, logx=True, logy=True, nbins=[X_EDGES, Y_EDGES]) - subset, mask = h.get_subset_above_threshold(1) - assert mask.all() + subset = h.get_plotted_data() + assert len(subset) == len(x) assert np.asarray(subset["x"]) == exact(x) assert np.asarray(subset["y"]) == exact(y) # The histogram's own data stay log10 values: only the subset changed. diff --git a/tests/plotting/test_architecture.py b/tests/plotting/test_architecture.py index f14f8e77c..d61617ad5 100644 --- a/tests/plotting/test_architecture.py +++ b/tests/plotting/test_architecture.py @@ -242,9 +242,8 @@ def test_spiral_selects_the_rows_of_the_cells_it_plots(): for (x0, x1, y0, y1), n in zip(splot.mesh.mesh, _counts_per_cell(splot)): if n >= lower: expected |= (x0 <= x) & (x < x1) & (y0 <= y) & (y < y1) - plotted = splot.get_plotted_data_boolean_series() - assert plotted.index.equals(d.index) - assert plotted.to_numpy().tolist() == expected.tolist() + plotted = d.index.isin(splot.get_plotted_data().index) + assert plotted.tolist() == expected.tolist() assert 0 < expected.sum() < len(d) # the fixture keeps some rows, not all diff --git a/tests/plotting/test_binned_data.py b/tests/plotting/test_binned_data.py index e22df4ee6..1a97ad70e 100644 --- a/tests/plotting/test_binned_data.py +++ b/tests/plotting/test_binned_data.py @@ -855,11 +855,8 @@ def test_no_selection_returns_a_row_the_binned_data_excludes(self): ranges = pd.DataFrame( {"bottom": 0.0, "top": 3.0}, index=h.agg().unstack("x").columns ) - subset, kept = h.get_subset_above_threshold(1) selected = { - "plotted": h.get_plotted_data_boolean_series().index, - "above": subset.index, - "above mask": kept.index, + "plotted": h.get_plotted_data().index, "yrange": pd.Index( h.take_data_in_yrange_across_x( ranges, diff --git a/tests/plotting/test_hist1d.py b/tests/plotting/test_hist1d.py index 7ded072cb..36f2124ab 100644 --- a/tests/plotting/test_hist1d.py +++ b/tests/plotting/test_hist1d.py @@ -611,9 +611,7 @@ def test_nan_y_row_is_absent_from_data_and_every_selection(self): assert h.data.index.tolist() == self.KEPT assert h.cut.index.tolist() == self.KEPT assert h.agg().to_numpy() == exact([1.0, 5.0, 3.0, 4.0]) - assert h.get_plotted_data_boolean_series().index.tolist() == self.KEPT - above, _ = h.get_subset_above_threshold(1, fcn="count") - assert above.index.tolist() == self.KEPT + assert h.get_plotted_data().index.tolist() == self.KEPT cdf = h.construct_cdf(only_plotted=False) assert cdf["x"].to_numpy() == exact([0.5, 1.5, 2.5, 3.5]) ranges = pd.DataFrame({"bottom": 0.0, "top": 10.0}, index=h.agg().index) diff --git a/tests/plotting/test_hist2d_defects.py b/tests/plotting/test_hist2d_defects.py index abe55150c..e75891312 100644 --- a/tests/plotting/test_hist2d_defects.py +++ b/tests/plotting/test_hist2d_defects.py @@ -68,8 +68,8 @@ def test_projection_keeps_the_sign_of_a_negative_x_on_a_log_axis(): x = -2, -20, -200, 3 bin by log10|x| = 0.30, 1.30, 2.30, 0.48 on edges [0, 1, 2, 3]; y = 0.5, 0.5, 1.5, 1.5 on edges [0, 1, 2]. Projected on y, y-bin (0, 1] averages x = -2 and -20 to -11, (1, 2] averages -200 and 3 to - -98.5 (hand). Projected on x, the subset of rows in bins holding at least - one row is every row, with the caller's x. + -98.5 (hand). Projected on x, the plotted rows are every row, with the + caller's x. ON FAILURE: the code is wrong. """ @@ -79,8 +79,7 @@ def test_projection_keeps_the_sign_of_a_negative_x_on_a_log_axis(): assert h.project_1d("y").agg().to_numpy() == exact([-11.0, -98.5]) - subset, kept = h.project_1d("x", project_counts=True).get_subset_above_threshold(1) - assert kept.to_numpy().all() + subset = h.project_1d("x", project_counts=True).get_plotted_data() assert subset.x.to_numpy() == exact([-2.0, -20.0, -200.0, 3.0]) # the inputs @@ -111,17 +110,17 @@ def test_projected_counts_hold_the_row_the_parent_clipped_into_an_edge_bin(): # --------------------------------------------------------------------------- -# get_subset_above_threshold: the caller's values, never inverted +# get_plotted_data: the caller's values, never inverted # --------------------------------------------------------------------------- -def test_subset_above_threshold_leaves_a_linear_axis_alone(): - """A projection of a logy parent averages linear y; its subset holds that y. +def test_plotted_data_leaves_a_linear_axis_alone(): + """A projection of a logy parent averages linear y; its plotted rows hold that y. The parent bins log10(y) for y = 10, 1000 (log10 edges [0, 2, 4]); the projection on x sends the caller's y = 10, 1000, linear, and shows its y - axis on a log scale. Both rows are in bins of one row, so a threshold of - 1 keeps both, with x = 0.5, 1.5 and y = 10, 1000 as passed. + axis on a log scale. Both rows are in bins of one row, so every row is + plotted, with x = 0.5, 1.5 and y = 10, 1000 as passed. ON FAILURE: the code is wrong. """ @@ -130,18 +129,17 @@ def test_subset_above_threshold_leaves_a_linear_axis_alone(): h = Hist2D(x, y, logy=True, nbins=[np.array([0.0, 1.0, 2.0]), [0.0, 2, 4]]) projected = h.project_1d("x") - subset, kept = projected.get_subset_above_threshold(1) + subset = projected.get_plotted_data() - assert kept.to_numpy().all() assert subset.x.to_numpy() == exact([0.5, 1.5]) # the inputs assert subset.y.to_numpy() == exact([10.0, 1000.0]) # the inputs -def test_subset_above_threshold_returns_the_callers_signed_values_on_a_log_axis(): - """On a log axis the subset holds the caller's x, negative ones included. +def test_plotted_data_returns_the_callers_signed_values_on_a_log_axis(): + """On a log axis the plotted rows hold the caller's x, negative ones included. x = -10, 100 bin by log10|x| = 1, 2 on edges [0, 1.5, 3]; one row per - bin, so a threshold of 1 keeps both. + bin, so both are plotted. ON FAILURE: the code is wrong. """ @@ -149,7 +147,7 @@ def test_subset_above_threshold_returns_the_callers_signed_values_on_a_log_axis( y = pd.Series([0.5, 0.5]) h = Hist2D(x, y, logx=True, nbins=[np.array([0.0, 1.5, 3.0]), [0.0, 1]]) - subset, _ = h.get_subset_above_threshold(1) + subset = h.get_plotted_data() assert subset.x.to_numpy() == exact([-10.0, 100.0]) # the inputs assert subset.y.to_numpy() == exact([0.5, 0.5]) # the inputs diff --git a/tests/plotting/test_hist2d_plotting.py b/tests/plotting/test_hist2d_plotting.py index 36154ca00..5a63dfed4 100644 --- a/tests/plotting/test_hist2d_plotting.py +++ b/tests/plotting/test_hist2d_plotting.py @@ -1635,7 +1635,7 @@ def test_y_outside_the_edges_is_dropped_from_the_projection(self): [np.nan, 0.3, 0.5, np.nan], nan_ok=True ) assert list(projected.data.index) == [1, 2] - assert list(projected.get_plotted_data_boolean_series().index) == [1, 2] + assert list(projected.get_plotted_data().index) == [1, 2] @pytest.mark.parametrize( "y, nbins, kept, expected", @@ -1676,7 +1676,7 @@ def test_projection_keeps_exactly_the_rows_the_parent_bins_in_y( projected = h.project_1d("x", only_plotted=False) assert list(projected.data.index) == kept - assert list(projected.get_plotted_data_boolean_series().index) == kept + assert list(projected.get_plotted_data().index) == kept assert projected.agg().to_numpy() == exact(expected, nan_ok=True) def test_log_axes_round_trip_through_the_projection(self): diff --git a/tests/plotting/test_plot_invariants.py b/tests/plotting/test_plot_invariants.py index 5d21ea5b8..e82bde0cf 100644 --- a/tests/plotting/test_plot_invariants.py +++ b/tests/plotting/test_plot_invariants.py @@ -17,7 +17,7 @@ the caller asked to be logged, equal ``h.data`` there. Values a selection returns equal the caller's, in absolute value on a logged axis: a logged axis bins ``log10|v|``, so its sign is not part of what the plot carries. -- I4: counting the rows ``get_plotted_data_boolean_series`` keeps, bin by +- I4: counting the rows ``get_plotted_data`` returns, bin by bin through ``h.cut``, gives ``agg(fcn="count")`` on the plotted bins. - I5: the counts of ``project_1d`` equal the parent's counts summed over the other axis. @@ -273,28 +273,11 @@ def _select_cut(b): return [Selection(b.h.cut.index, None, True)] -def _select_plotted(b): - return [Selection(_where(b.h.get_plotted_data_boolean_series()), None, True)] - - def _select_plotted_data(b): rows = b.h.get_plotted_data() return [Selection(rows.index, rows, True)] -def _select_above_threshold(b): - # The median bin count: some bins reach it, some do not. - threshold = b.h.agg(fcn="count").dropna().median() - subset, kept = b.h.get_subset_above_threshold(threshold) - labels = _where(kept) - if not subset.index.sort_values().equals(labels.sort_values()): - raise InvariantViolation( - "get_subset_above_threshold returned a subset whose labels are not " - "the rows its boolean series keeps" - ) - return [Selection(labels, subset, True)] - - def _select_above_contour(b): # The median aggregate: some bins reach it, some do not. level = b.h.agg().dropna().median() @@ -341,7 +324,7 @@ def _select_cdf(b): # The rows the docstring says the CDF is built from. keep = h.cut.loc[:, "x"].notna() if only_plotted: - keep = keep & h.get_plotted_data_boolean_series() + keep = keep & h.cut.index.isin(h.get_plotted_data().index) values = pd.DataFrame({"x": cdf.loc[:, "x"].to_numpy(dtype=float)}) out.append(Selection(_where(keep), values, False)) return out @@ -367,9 +350,7 @@ def _select_projection(b): SELECTIONS = { "data": _select_data, "cut": _select_cut, - "get_plotted_data_boolean_series": _select_plotted, "get_plotted_data": _select_plotted_data, - "get_subset_above_threshold": _select_above_threshold, "id_data_above_contour": _select_above_contour, "take_data_in_yrange_across_x": _select_in_yrange, "construct_cdf": _select_cdf, @@ -645,13 +626,13 @@ def test_plotted_rows_counted_per_bin_equal_the_count_aggregate( """Counting the plotted rows bin by bin through ``cut`` gives ``agg("count")``. The plotted bins are the ones ``agg()`` leaves non-NaN, as - ``get_plotted_data_boolean_series`` documents; the rows in each are + ``get_plotted_data`` documents; the rows in each are counted here with ``collections.Counter`` over ``h.cut``. ON FAILURE: the code is wrong. """ h = build(cls, CASES[case_name], variant).h - plotted = _where(h.get_plotted_data_boolean_series()) + plotted = h.get_plotted_data().index cut = h.cut.loc[plotted] counted = Counter(zip(*(cut.loc[:, k].tolist() for k in cut.columns))) From fa7d2aecedc927d42f6c750221686035c206d93d Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:12:28 -0500 Subject: [PATCH 15/60] feat(plotting): join consecutive Scatter points with coloured edges Scatter.make_plot(edges=True, edge_kwargs=None) adds a LineCollection of segments between rows adjacent by source position. Segment i takes (z[i] + z[i+1]) / 2 through the points' own cmap and norm, so one colorbar reads both; without a varying z it takes the points' colour. A row that is not drawn (NaN, mask, alim) breaks the chain. The edges sit below the markers and do not set the axis limits. BREAKING: make_plot now returns (ax, points, edges_or_None, cbar), the fixed-shape convention Hist1D's band slot already follows. Callers in the plotting tests unpack four values. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 +++ src/solarwindpy/plotting/scatter.py | 102 +++++++++++++++++++++++++- tests/plotting/test_architecture.py | 2 +- tests/plotting/test_base.py | 6 +- tests/plotting/test_return_order.py | 24 ++++-- tests/plotting/test_scatter.py | 35 +++------ tests/test_source_plotting_defects.py | 6 +- 7 files changed, 145 insertions(+), 41 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 20688635f..ea2209856 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,17 @@ 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. +- `Scatter.make_plot(edges=True)` joins each pair of consecutive points, in the order the rows + were given, with a line segment colored by the mean z of its two points through the points' + colormap and norm, so one colorbar serves both and a path through time is visible. + `edge_kwargs` styles the segments. A point that is not drawn (NaN, outside `mask` or + outside `alim`) breaks the chain. Without a varying z, the segments take the points' color. + +### Changed - BREAKING CHANGES + +- `Scatter.make_plot` returns `(ax, points, edges, cbar)`: the `LineCollection` of the + segments, or None without `edges=True`, sits before the colorbar. Unpack four values where + three were unpacked before. ### Changed diff --git a/src/solarwindpy/plotting/scatter.py b/src/solarwindpy/plotting/scatter.py index a8f26ab11..c25cf6d72 100644 --- a/src/solarwindpy/plotting/scatter.py +++ b/src/solarwindpy/plotting/scatter.py @@ -5,7 +5,10 @@ "Scatter", ] +import numpy as np +from matplotlib import cbook from matplotlib import pyplot as plt +from matplotlib.collections import LineCollection from . import base @@ -64,7 +67,15 @@ def _format_axis(self, ax, collection, data): y = data.loc[:, "y"] self._fit_view(ax, collection, x.min(), x.max(), y.min(), y.max()) - def make_plot(self, ax=None, cbar=True, cbar_kwargs=None, **kwargs): + def make_plot( + self, + ax=None, + cbar=True, + cbar_kwargs=None, + edges=False, + edge_kwargs=None, + **kwargs, + ): r"""Make a scatter plot on `ax` using `ax.scatter`. Parameters @@ -75,6 +86,15 @@ def make_plot(self, ax=None, cbar=True, cbar_kwargs=None, **kwargs): If True, create color bar with `labels.z`. cbar_kwargs: dict, None If not None, kwargs passed to `self._make_cbar`. + edges: bool + If True, join each pair of consecutive points with a line segment + (see Notes), so a path through the data, e.g. through time, is + visible. + edge_kwargs: dict, None + Passed to :class:`~matplotlib.collections.LineCollection`, e.g. + ``linewidth``, ``alpha`` or ``zorder``. The defaults are a + ``linewidth`` of 0.75 and a ``zorder`` just below the points'. + Not modified. kwargs: Passed to `ax.scatter`. @@ -83,6 +103,9 @@ def make_plot(self, ax=None, cbar=True, cbar_kwargs=None, **kwargs): ax: mpl.axes.Axes collection: mpl.collections.PathCollection The points. + edges: matplotlib.collections.LineCollection or None + The segments joining consecutive points if `edges` is True, else + None. cbar: mpl.colorbar.Colorbar or None The colorbar if `cbar` is True and z varies, else None. @@ -91,6 +114,19 @@ def make_plot(self, ax=None, cbar=True, cbar_kwargs=None, **kwargs): Points whose z is outside ``alim`` (see ``set_alim``) are not drawn, do not enter the colour scale, and do not set the axis limits. With ``kind="quantile"`` the thresholds are quantiles of the plotted z. + + Consecutive points are adjacent rows in the order x, y and z were + given, by position, not by index label: sort time-indexed data by + time before building the plot to draw its path through time. A + segment joins two drawn points only. A row that is not drawn (NaN or + infinite, outside ``mask``, or outside ``alim``) breaks the chain: + neither of its segments is drawn and its neighbours are not joined. + + When z varies, segment i is coloured by ``(z[i] + z[i + 1]) / 2`` + through the points' colormap and norm, the same objects, so the one + colorbar reads both. Otherwise every segment has the points' colour, + unless ``edge_kwargs`` sets ``color``. The edges do not set the axis + limits. """ if ax is None: fig, ax = plt.subplots() @@ -100,7 +136,8 @@ def make_plot(self, ax=None, cbar=True, cbar_kwargs=None, **kwargs): if clip: data[k] = self.clip_data(data.loc[:, k], clip) - data = data.loc[self._apply_alim(data.loc[:, "z"]).notna()] + shown = self._apply_alim(data.loc[:, "z"]).notna() + data = data.loc[shown] if data.loc[:, "z"].unique().size > 1: zkey = "z" @@ -109,6 +146,12 @@ def make_plot(self, ax=None, cbar=True, cbar_kwargs=None, **kwargs): collection = ax.scatter(x="x", y="y", c=zkey, data=data, **kwargs) + lines = None + if edges: + lines = self._make_edges( + ax, collection, data, shown.to_numpy(), zkey, edge_kwargs + ) + if cbar and zkey is not None: cbar_kwargs = self._prepare_cbar_kwargs(cbar_kwargs, ax) cbar = self._make_cbar(collection, **cbar_kwargs) @@ -117,4 +160,57 @@ def make_plot(self, ax=None, cbar=True, cbar_kwargs=None, **kwargs): self._format_axis(ax, collection, data) - return ax, collection, cbar + return ax, collection, lines, cbar + + def _make_edges(self, ax, collection, data, shown, zkey, edge_kwargs): + r"""Add segments joining consecutive drawn points to `ax`; see `make_plot`. + + Parameters + ---------- + ax: mpl.axes.Axes + collection: mpl.collections.PathCollection + The points, whose colormap, norm and colour the segments share. + data: pd.DataFrame + The drawn points, in source row order. + shown: np.ndarray of bool + For each row of ``self.data``, True if ``alim`` keeps it. + zkey: str or None + ``"z"`` if the points are colour-mapped, else None. + edge_kwargs: Mapping or None + Passed to ``LineCollection``. + + Returns + ------- + matplotlib.collections.LineCollection + """ + rows = self._source.rows + if rows is None: + position = np.arange(self._source.index.size) + else: + position = np.flatnonzero(rows) + position = position[shown] + start = np.flatnonzero(np.diff(position) == 1) + + xy = data.loc[:, ["x", "y"]].to_numpy(dtype=float) + segments = np.stack([xy[start], xy[start + 1]], axis=1) + + kwargs = cbook.normalize_kwargs(edge_kwargs or {}, LineCollection) + kwargs.setdefault("linewidth", 0.75) + kwargs.setdefault("zorder", collection.get_zorder() - 0.5) + + if zkey is None: + kwargs.setdefault("color", collection.get_facecolor()[0]) + lines = LineCollection(segments, **kwargs) + else: + collection.autoscale_None() + lines = LineCollection( + segments, + cmap=collection.get_cmap(), + norm=collection.norm, + **kwargs, + ) + z = data.loc[:, zkey].to_numpy(dtype=float) + lines.set_array((z[start] + z[start + 1]) / 2) + + ax.add_collection(lines, autolim=False) + return lines diff --git a/tests/plotting/test_architecture.py b/tests/plotting/test_architecture.py index f14f8e77c..43f5c9e3f 100644 --- a/tests/plotting/test_architecture.py +++ b/tests/plotting/test_architecture.py @@ -321,6 +321,6 @@ def test_scatter_log_flags_set_the_axis_scales_and_keep_the_data_linear(): plot = Scatter(x, y, logx=True, logy=True) assert plot.log == base.LogAxes(True, True) assert plot.data.x.to_numpy() == exact(x.to_numpy()) # the chosen input - ax, _, _ = plot.make_plot() + ax, _, _, _ = plot.make_plot() assert (ax.get_xscale(), ax.get_yscale()) == ("log", "log") plt.close("all") diff --git a/tests/plotting/test_base.py b/tests/plotting/test_base.py index c4286d033..af0a674fc 100644 --- a/tests/plotting/test_base.py +++ b/tests/plotting/test_base.py @@ -447,7 +447,7 @@ def test_scatter_colorbar_maps_the_plotted_collection_labelled_z(ax): """ plot = Scatter(X, Y, Z) plot.set_labels(z="T") - _, _, cbar = plot.make_plot(ax, cbar_kwargs={"ax": ax}) + _, _, _, cbar = plot.make_plot(ax, cbar_kwargs={"ax": ax}) assert isinstance(cbar, Colorbar) assert cbar.mappable is ax.collections[0] assert cbar.ax.get_ylabel() == "T" @@ -462,7 +462,7 @@ def test_scatter_colorbar_draws_into_a_given_cax_with_a_given_label(ax): cax = ax.figure.add_axes((0.9, 0.1, 0.03, 0.8)) plot = Scatter(X, Y, Z) plot.set_labels(z="T") - _, _, cbar = plot.make_plot(ax, cbar_kwargs={"cax": cax, "label": "custom"}) + _, _, _, cbar = plot.make_plot(ax, cbar_kwargs={"cax": cax, "label": "custom"}) assert cbar.ax is cax assert cax.get_ylabel() == "custom" @@ -472,7 +472,7 @@ def test_scatter_colorbar_accepts_a_list_of_axes(ax): ON FAILURE: the code is wrong. """ - _, _, cbar = Scatter(X, Y, Z).make_plot(ax, cbar_kwargs={"ax": [ax]}) + _, _, _, cbar = Scatter(X, Y, Z).make_plot(ax, cbar_kwargs={"ax": [ax]}) assert cbar.ax.figure is ax.figure assert len(ax.figure.axes) == 2 diff --git a/tests/plotting/test_return_order.py b/tests/plotting/test_return_order.py index 41daa8007..f3c1f3e02 100644 --- a/tests/plotting/test_return_order.py +++ b/tests/plotting/test_return_order.py @@ -6,10 +6,11 @@ which is None when there is none: ``(ax, artists..., cbar_or_None)``. A contour method returns its contour set as the last artist, just before the colorbar. A method's tuple has the same length whether or not a colorbar -is drawn, whether a Scatter has z, and whether a Hist1D draws its -uncertainty window. Each position keeps its type too, with one exception: -Hist1D's line slot holds the ``ErrorbarContainer`` without the window and -the central ``Line2D`` with it, so the error-bar handles stay reachable. +is drawn, whether a Scatter has z or draws its edges, and whether a +Hist1D draws its uncertainty window. Each position keeps its type too, +with one exception: Hist1D's line slot holds the ``ErrorbarContainer`` +without the window and the central ``Line2D`` with it, so the error-bar +handles stay reachable. """ from types import SimpleNamespace @@ -24,6 +25,7 @@ import pytest # noqa: E402 from matplotlib.axes import Axes # noqa: E402 from matplotlib.collections import ( # noqa: E402 + LineCollection, PathCollection, PolyCollection, QuadMesh, @@ -112,7 +114,14 @@ def _close(): lambda: Scatter(X, Y, Z), "make_plot", {}, - (PathCollection,), + (PathCollection, NONE), + ), + ( + "Scatter.make_plot-edges", + lambda: Scatter(X, Y, Z), + "make_plot", + {"edges": True}, + (PathCollection, LineCollection), ), ] @@ -139,15 +148,16 @@ def test_color_plot_returns_ax_then_artists_then_cbar_or_none( def test_scatter_without_z_returns_its_collection_and_no_colorbar(): - """A Scatter without z keeps the same shape: its collection, then None. + """A Scatter without z keeps the same shape: points, edges or None, then None. ON FAILURE: the code is wrong. """ out = Scatter(X, Y).make_plot() - assert len(out) == 3 + assert len(out) == 4 assert isinstance(out[0], Axes) assert isinstance(out[1], PathCollection) assert out[2] is None + assert out[3] is None @pytest.mark.parametrize( diff --git a/tests/plotting/test_scatter.py b/tests/plotting/test_scatter.py index a8f676d1e..d963afde6 100644 --- a/tests/plotting/test_scatter.py +++ b/tests/plotting/test_scatter.py @@ -89,7 +89,7 @@ def test_varying_z_colours_points_and_draws_a_labelled_colorbar(ax): """ sc = Scatter(X, Y, Z) sc.set_labels(x="Vx", y="Np", z="T") - ret_ax, _, cbar = sc.make_plot(ax=ax) + ret_ax, _, _, cbar = sc.make_plot(ax=ax) coll = ax.collections[0] np.testing.assert_array_equal(coll.get_array(), _col(KEPT, 3)) assert ret_ax is ax @@ -107,7 +107,7 @@ def test_two_valued_z_is_colour_mapped_with_a_colorbar(ax): ON FAILURE: the code is wrong. """ z = pd.Series([0.5, 0.5, 0.9, 0.9, 0.5, 0.9]) - _, _, cbar = Scatter(X, Y, z).make_plot(ax=ax) + _, _, _, cbar = Scatter(X, Y, z).make_plot(ax=ax) kept_z = z.drop(1).to_numpy() # row 1 has NaN y (ROWS) np.testing.assert_array_equal(ax.collections[0].get_array(), kept_z) assert isinstance(cbar, Colorbar) @@ -119,7 +119,7 @@ def test_absent_or_constant_z_gives_uncoloured_points_and_no_colorbar(ax, z): ON FAILURE: the code is wrong. """ - _, _, cbar = Scatter(X, Y, z).make_plot(ax=ax) + _, _, _, cbar = Scatter(X, Y, z).make_plot(ax=ax) assert ax.collections[0].get_array() is None assert cbar is None assert ax.figure.axes == [ax] @@ -130,7 +130,7 @@ def test_cbar_false_colours_points_but_draws_no_colorbar(ax): ON FAILURE: the code is wrong. """ - _, _, cbar = Scatter(X, Y, Z).make_plot(ax=ax, cbar=False) + _, _, _, cbar = Scatter(X, Y, Z).make_plot(ax=ax, cbar=False) np.testing.assert_array_equal(ax.collections[0].get_array(), _col(KEPT, 3)) assert cbar is None assert ax.figure.axes == [ax] @@ -143,7 +143,7 @@ def test_without_ax_a_new_figure_is_made(): """ existing, _ = plt.subplots() try: - new_ax, _, _ = Scatter(X, Y).make_plot() + new_ax, _, _, _ = Scatter(X, Y).make_plot() assert isinstance(new_ax, Axes) assert new_ax.figure is not existing assert len(new_ax.collections) == 1 @@ -169,7 +169,7 @@ def test_cbar_kwargs_reach_the_colorbar(ax): ON FAILURE: the code is wrong. """ cax = ax.figure.add_axes((0.9, 0.1, 0.03, 0.8)) - _, _, cbar = Scatter(X, Y, Z).make_plot( + _, _, _, cbar = Scatter(X, Y, Z).make_plot( ax=ax, cbar_kwargs={"cax": cax, "label": "custom"} ) assert cbar.ax is cax @@ -245,7 +245,7 @@ def test_reused_cbar_kwargs_put_each_colorbar_beside_its_own_axes(): # that warning from pre-empting the assertion under ``-W error``. with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) - _, _, cbar2 = Scatter(X, Y, Z).make_plot(ax=ax2, cbar_kwargs=kwargs) + _, _, _, cbar2 = Scatter(X, Y, Z).make_plot(ax=ax2, cbar_kwargs=kwargs) if cbar2.ax.figure is not ax2.figure: raise CbarKwargsMutated("second colorbar drawn in the first plot's figure") finally: @@ -290,7 +290,7 @@ def test_value_alim_draws_only_points_with_z_inside_the_limits(ax, lower, upper) z = ALIM_Z[:-1] sc = Scatter(ALIM_X[:-1], ALIM_Y[:-1], z) sc.set_alim(lower, upper) - _, _, cbar = sc.make_plot(ax=ax) + _, _, _, cbar = sc.make_plot(ax=ax) keep = np.ones(z.size, dtype=bool) if lower is not None: keep &= z >= lower @@ -308,7 +308,7 @@ def test_quantile_alim_thresholds_are_quantiles_of_the_finite_plotted_z(ax): """ sc = Scatter(ALIM_X, ALIM_Y, ALIM_Z) sc.set_alim(0.2, 0.8, kind="quantile") - _, _, cbar = sc.make_plot(ax=ax) + _, _, _, cbar = sc.make_plot(ax=ax) lo, hi = np.quantile(ALIM_Z[np.isfinite(ALIM_Z)], [0.2, 0.8]) keep = (ALIM_Z >= lo) & (ALIM_Z <= hi) assert 2 < keep.sum() < ALIM_Z.size - 2 @@ -324,7 +324,7 @@ def test_quantile_alim_of_zero_is_the_smallest_finite_z(ax): """ sc = Scatter(ALIM_X, ALIM_Y, ALIM_Z) sc.set_alim(0.0, 0.5, kind="quantile") - _, _, cbar = sc.make_plot(ax=ax) + _, _, _, cbar = sc.make_plot(ax=ax) hi = np.quantile(ALIM_Z[np.isfinite(ALIM_Z)], 0.5) _assert_drawn(ax, cbar, ALIM_Z <= hi) @@ -390,10 +390,6 @@ def test_scatter_figure_renders_to_png(): EY = np.array([0.0, 1.0, 0.0, 1.0, 0.0]) EZ = np.array([0.0, 2.0, 9.0, 6.0, 8.0]) -_EDGES_PENDING = pytest.mark.xfail( - strict=True, reason="Scatter.make_plot(edges=True) is not implemented" -) - def _segments(x, y, pairs): return [np.array([[x[i], y[i]], [x[j], y[j]]]) for i, j in pairs] @@ -406,7 +402,6 @@ def _assert_segments(lc, x, y, pairs): np.testing.assert_array_equal(g, e) -@_EDGES_PENDING def test_make_plot_returns_ax_points_edges_then_cbar(ax): """``(ax, points, edges, cbar)``; edges is None unless ``edges=True``. @@ -426,7 +421,6 @@ def test_make_plot_returns_ax_points_edges_then_cbar(ax): assert out[2] in ax.collections -@_EDGES_PENDING def test_edges_join_each_pair_of_consecutive_points(ax): """n points in row order give n - 1 segments, point i to point i + 1. @@ -436,7 +430,6 @@ def test_edges_join_each_pair_of_consecutive_points(ax): _assert_segments(lc, EX, EY, [(0, 1), (1, 2), (2, 3), (3, 4)]) -@_EDGES_PENDING def test_edge_colour_is_the_mean_endpoint_z_through_the_points_cmap_and_norm(ax): """Segment i is ``cmap(norm((z[i] + z[i+1]) / 2))``: one colorbar serves both. @@ -456,7 +449,6 @@ def test_edge_colour_is_the_mean_endpoint_z_through_the_points_cmap_and_norm(ax) assert cbar.mappable is points -@_EDGES_PENDING def test_edges_follow_a_norm_the_caller_passes(ax): """``vmin``/``vmax`` given to the points also set the edges' colours. @@ -469,7 +461,6 @@ def test_edges_follow_a_norm_the_caller_passes(ax): assert (lc.norm.vmin, lc.norm.vmax) == (0.0, 20.0) -@_EDGES_PENDING def test_a_point_with_nan_breaks_the_chain(ax): """A dropped NaN point removes both its segments; no segment bridges it. @@ -482,7 +473,6 @@ def test_a_point_with_nan_breaks_the_chain(ax): np.testing.assert_array_equal(lc.get_array(), [1.0, 7.0]) -@_EDGES_PENDING def test_a_point_outside_alim_breaks_the_chain(ax): """A point ``alim`` hides drops both its segments, as a NaN point does. @@ -496,7 +486,6 @@ def test_a_point_outside_alim_breaks_the_chain(ax): np.testing.assert_array_equal(lc.get_array(), [1.0, 7.0]) -@_EDGES_PENDING def test_a_masked_point_breaks_the_chain(ax): """A point ``mask`` excludes drops both its segments. @@ -507,7 +496,6 @@ def test_a_masked_point_breaks_the_chain(ax): _assert_segments(lc, EX, EY, [(0, 1), (1, 2)]) -@_EDGES_PENDING def test_consecutive_is_row_position_not_label(ax): """Rows are joined in the order given, even with repeated or unsorted labels. @@ -519,7 +507,6 @@ def test_consecutive_is_row_position_not_label(ax): _assert_segments(lc, EX, EY, [(0, 1), (1, 2), (2, 3), (3, 4)]) -@_EDGES_PENDING @pytest.mark.parametrize("z", [None, pd.Series(7.0, index=range(EX.size))]) def test_edges_without_varying_z_have_one_colour(ax, z): """With no z, or a constant one, every segment has the points' colour. @@ -535,7 +522,6 @@ def test_edges_without_varying_z_have_one_colour(ax, z): np.testing.assert_array_equal(colors[0], points.get_facecolor()[0]) -@_EDGES_PENDING def test_edges_sit_below_the_points_and_take_edge_kwargs(ax): """Edges default to beneath the markers; ``edge_kwargs`` styles them. @@ -551,7 +537,6 @@ def test_edges_sit_below_the_points_and_take_edge_kwargs(ax): assert (lc.get_alpha(), lc.get_zorder()) == (0.4, 5) -@_EDGES_PENDING def test_edges_do_not_change_the_axis_limits(ax): """The view fits the points with or without edges. diff --git a/tests/test_source_plotting_defects.py b/tests/test_source_plotting_defects.py index dac6dd8be..973bfdf7a 100644 --- a/tests/test_source_plotting_defects.py +++ b/tests/test_source_plotting_defects.py @@ -47,7 +47,7 @@ def test_scatter_with_clip_data_plots_points_clipped_to_percentiles(): y = pd.Series(2.0 * raw) fig, ax = plt.subplots() - ax, _, cbar = Scatter(x, y, clip=True).make_plot(ax=ax) + ax, _, _, cbar = Scatter(x, y, clip=True).make_plot(ax=ax) offsets = ax.collections[0].get_offsets() expected_x = np.clip(raw, np.quantile(raw, Q_LOWER), np.quantile(raw, Q_UPPER)) @@ -70,7 +70,9 @@ def test_scatter_without_clip_data_plots_raw_points(): """ raw = np.concatenate([[-1e6], np.arange(10001.0), [1e6]]) fig, ax = plt.subplots() - ax, _, cbar = Scatter(pd.Series(raw), pd.Series(raw), clip=False).make_plot(ax=ax) + ax, _, _, cbar = Scatter(pd.Series(raw), pd.Series(raw), clip=False).make_plot( + ax=ax + ) np.testing.assert_array_equal( np.asarray(ax.collections[0].get_offsets()[:, 0]), raw ) From 809eb356ec6dfd02251476bd7679bc0bd4c76fb5 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:17:09 -0500 Subject: [PATCH 16/60] fix(fitfunctions): print a zero exponent as no exponent in TeXinfo With convert_pow_10, build_info turned "2.5e+00" into "2.5 \times 10^{+0}". The module compiled a pattern for "e+00" but never used it; the 10^{X} conversion now removes a zero exponent first, so the annotation reads "2.5 \pm 1 \times 10^{-1}". The eX notation is unchanged. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +++ src/solarwindpy/fitfunctions/tex_info.py | 7 ++++--- tests/fitfunctions/test_tex_info.py | 20 ++++++++++++++++++++ 3 files changed, 27 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d38c10e22..83f5177bf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,6 +45,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `SpiralPlot2D` no longer logs warnings on every construction and draw. Its timing and bin-population messages report normal operation and are now DEBUG records; the message that points outside the mesh are dropped stays a warning. +- The fit annotation (`TeXinfo.build_info` with `convert_pow_10`) prints a value or uncertainty + whose exponent is 0 without an exponent: `2.5 \pm 1 \times 10^{-1}`, not + `2.5 \times 10^{+0} \pm 1 \times 10^{-1}`. ## [0.4.0] - 2026-11-05 diff --git a/src/solarwindpy/fitfunctions/tex_info.py b/src/solarwindpy/fitfunctions/tex_info.py index 7c4226707..5b608e988 100644 --- a/src/solarwindpy/fitfunctions/tex_info.py +++ b/src/solarwindpy/fitfunctions/tex_info.py @@ -13,9 +13,8 @@ from numbers import Real from tabulate import tabulate -# Compile this once on import to save time. -_remove_exponential_pattern = r"e\+00+" # Replace the `e+00`for 2 or more zeros. -_remove_exponential_pattern = re.compile(_remove_exponential_pattern) +# A zero exponent, `e+00`, which the 10^{X} notation leaves out. +_zero_exponent_pattern = re.compile(r"e\+00(?![0-9])") class TeXinfo(object): @@ -300,6 +299,8 @@ def _build_fit_parameter_info( if convert_pow_10 and (not simplify_info_for_paper): # Convert to 10^X notation. info = "\n".join(info) + # A zero exponent prints as no exponent: 2.5, not 2.5 \times 10^{+0}. + info = _zero_exponent_pattern.sub("", info) info, eplus_cnt = re.subn(r"e\+", r" \\times 10^{+", info) info, eminus_cnt = re.subn(r"e-", r" \\times 10^{-", info) diff --git a/tests/fitfunctions/test_tex_info.py b/tests/fitfunctions/test_tex_info.py index d706f4d67..dc1320b9a 100644 --- a/tests/fitfunctions/test_tex_info.py +++ b/tests/fitfunctions/test_tex_info.py @@ -538,3 +538,23 @@ def test_offset_parameters_render_with_tex_subscripts(cls, x, y, expected): obj.make_fit() assert obj.TeX_info.TeX_argnames == expected assert set(expected.values()) <= set(obj.TeX_info.TeX_popt) + + +def test_a_zero_exponent_is_not_printed(): + r"""A value or uncertainty with exponent 0 prints without ``\times 10^{+0}``. + + 2.5 and 2.0 have exponent 0; 0.1 and 456 have exponents -1 and 2, which + still print. Each value reads back as the value given. + + ON FAILURE: the code is wrong. + """ + tex = TeXinfo( + {"a": 2.5, "b": 456.0}, {"a": 0.1, "b": 2.0}, "f(x)", CHISQ, RSQ, None + ) + info = tex.build_info() + assert "10^{+0" not in info and "10^{-0" not in info + a_line = _param_line(info, "a") + b_line = _param_line(info, "b") + assert r"10^{-1" in a_line and r"10^{+2" in b_line + assert _read_back(a_line) == (2.5, 0.1) + assert _read_back(b_line) == (456.0, 2.0) From d0fde70ef7750489c2727dc858fcf40c119eb5b6 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:17:11 -0500 Subject: [PATCH 17/60] test(plotting): one take_data_in_yrange_across_x for Hist1D and Hist2D Target tests marked xfail(strict=True) until the merge: neither class keeps its own copy, and a Hist1D hands expected_logy=False to the y callback as a Hist2D hands its log flag. Guards, passing on both copies today: overlapping x ranges take a row once per range, each range keeps its own y window, and the first invalid range in the caller's order is named. Co-Authored-By: Claude Opus 5.5 --- tests/plotting/test_take_data.py | 128 +++++++++++++++++++++++++++++++ 1 file changed, 128 insertions(+) create mode 100644 tests/plotting/test_take_data.py diff --git a/tests/plotting/test_take_data.py b/tests/plotting/test_take_data.py new file mode 100644 index 000000000..aa6bffd2f --- /dev/null +++ b/tests/plotting/test_take_data.py @@ -0,0 +1,128 @@ +# Spent-When: PERMANENT(the fixed-grid plots stop offering take_data_in_yrange_across_x) +# Supersedes: none +"""Tests for the one ``take_data_in_yrange_across_x`` that Hist1D and Hist2D share. + +The method selects, for each x range, the rows whose y lies in that range's +y window. Both histograms run the same code: the y-bounds callback gets +``expected_logy`` from either (False for a ``Hist1D``, whose y is never +logged), and ranges that overlap in x select a row once per range that holds +it. Expected labels are by hand on the rows written below. +""" + +import re + +import numpy as np +import pandas as pd +import pytest +import matplotlib + +matplotlib.use("Agg") + +from solarwindpy.plotting.hist1d import Hist1D # noqa: E402 +from solarwindpy.plotting.hist2d import Hist2D # noqa: E402 + +_MERGED = pytest.mark.xfail(strict=True, reason="two copies of the method today") + +# x in (0, 1], (1, 2], (2, 3] by explicit (right-closed) edges, one y each. +X = pd.Series([0.5, 1.5, 2.5, 0.9], index=[10, 11, 12, 13]) +Y = pd.Series([5.0, 6.0, 7.0, 8.0], index=[10, 11, 12, 13]) +EDGES = np.array([0.0, 1.0, 2.0, 3.0]) + + +def _build(cls): + if cls is Hist1D: + return Hist1D(X, Y, nbins=EDGES) + return Hist2D(X, Y, nbins=[EDGES, np.array([0.0, 10.0])]) + + +@_MERGED +def test_hist1d_and_hist2d_share_one_method(): + """Neither class defines its own copy; both use the fixed-grid one. + + ON FAILURE: the code is wrong. + """ + assert "take_data_in_yrange_across_x" not in Hist1D.__dict__ + assert "take_data_in_yrange_across_x" not in Hist2D.__dict__ + assert Hist1D.take_data_in_yrange_across_x is Hist2D.take_data_in_yrange_across_x + + +@_MERGED +def test_hist1d_hands_expected_logy_false_to_the_y_callback(): + """A Hist1D's y is never logged, so the y callback gets expected_logy=False. + + ON FAILURE: the code is wrong. + """ + h = _build(Hist1D) + ranges = pd.DataFrame({"bottom": 0.0, "top": 10.0}, index=h.intervals["x"]) + flags = [] + + def get_y_bounds(row, **kw): + flags.append(kw) + return row.bottom, row.top + + taken = h.take_data_in_yrange_across_x( + ranges, lambda k, expected_logx: (k.left, k.right), get_y_bounds + ) + assert flags == [{"expected_logy": False}] * 3 + assert list(taken) == [10, 11, 12, 13] + + +@pytest.mark.parametrize("cls", [Hist1D, Hist2D]) +def test_overlapping_x_ranges_select_a_row_once_per_range(cls): + """Ranges widened left by 0.2 overlap; label 13 (x = 0.9) lies in two. + + Range (0, 1] holds 10 and 13, (0.8, 2] holds 13 and 11, (1.8, 3] holds + 12: label 13 is taken twice. y windows (0, 10] keep every row. + + ON FAILURE: the code is wrong. + """ + h = _build(cls) + ranges = pd.DataFrame({"bottom": 0.0, "top": 10.0}, index=h.intervals["x"]) + + def get_x_bounds(k, expected_logx): + return (k.left - 0.2 if k.left > 0 else k.left), k.right + + def get_y_bounds(row, expected_logy=False): + return row.bottom, row.top + + taken = h.take_data_in_yrange_across_x(ranges, get_x_bounds, get_y_bounds) + assert list(taken) == [10, 11, 12, 13, 13] + + +@pytest.mark.parametrize("cls", [Hist1D, Hist2D]) +def test_each_range_keeps_its_own_y_window(cls): + """Windows (4, 5], (5, 6.5], (6.5, 7]: labels 10, 11, 12; 13 (y = 8) is out. + + ON FAILURE: the code is wrong. + """ + h = _build(cls) + ranges = pd.DataFrame( + {"bottom": [4.0, 5.0, 6.5], "top": [5.0, 6.5, 7.0]}, index=h.intervals["x"] + ) + taken = h.take_data_in_yrange_across_x( + ranges, + lambda k, expected_logx: (k.left, k.right), + lambda row, expected_logy=False: (row.bottom, row.top), + ) + assert list(taken) == [10, 11, 12] + + +@pytest.mark.parametrize("cls", [Hist1D, Hist2D]) +def test_the_first_invalid_range_in_the_callers_order_is_named(cls): + """Two inverted y windows: the error names the first one as given. + + ON FAILURE: the code is wrong. + """ + h = _build(cls) + iv = h.intervals["x"] + ranges = pd.DataFrame( + {"bottom": [0.0, 9.0, 8.0], "top": [10.0, 1.0, 1.0]}, index=iv[::-1] + ) + with pytest.raises( + ValueError, match=re.escape(f"Need bottom < top for x-bin {iv[1]}") + ): + h.take_data_in_yrange_across_x( + ranges, + lambda k, expected_logx: (k.left, k.right), + lambda row, expected_logy=False: (row.bottom, row.top), + ) From 2053d4300b175008d54563fadd34fbff53198048 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:18:34 -0500 Subject: [PATCH 18/60] fix(plotting): break Scatter edges at points a log axis drops Scatter keeps its data linear, so a value <= 0 on a log axis is a row matplotlib does not draw; its segments ran to the axis edge. Such a row now breaks the chain like a NaN, masked or alim-hidden one, read from self.log at draw time so set_log after construction counts. Co-Authored-By: Claude Opus 5.5 --- src/solarwindpy/plotting/scatter.py | 15 +++++++++++---- tests/plotting/test_scatter.py | 20 ++++++++++++++++++++ 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/src/solarwindpy/plotting/scatter.py b/src/solarwindpy/plotting/scatter.py index c25cf6d72..0c0ce1d13 100644 --- a/src/solarwindpy/plotting/scatter.py +++ b/src/solarwindpy/plotting/scatter.py @@ -119,8 +119,9 @@ def make_plot( given, by position, not by index label: sort time-indexed data by time before building the plot to draw its path through time. A segment joins two drawn points only. A row that is not drawn (NaN or - infinite, outside ``mask``, or outside ``alim``) breaks the chain: - neither of its segments is drawn and its neighbours are not joined. + infinite, outside ``mask``, outside ``alim``, or <= 0 on a log axis) + breaks the chain: neither of its segments is drawn and its neighbours + are not joined. When z varies, segment i is coloured by ``(z[i] + z[i + 1]) / 2`` through the points' colormap and norm, the same objects, so the one @@ -189,9 +190,15 @@ def _make_edges(self, ax, collection, data, shown, zkey, edge_kwargs): else: position = np.flatnonzero(rows) position = position[shown] - start = np.flatnonzero(np.diff(position) == 1) - xy = data.loc[:, ["x", "y"]].to_numpy(dtype=float) + # The data stay linear, so a log axis cannot show a value <= 0. + drawn = np.ones(position.size, dtype=bool) + for i, log in enumerate(self.log): + if log: + drawn &= xy[:, i] > 0 + joined = (np.diff(position) == 1) & drawn[:-1] & drawn[1:] + start = np.flatnonzero(joined) + segments = np.stack([xy[start], xy[start + 1]], axis=1) kwargs = cbook.normalize_kwargs(edge_kwargs or {}, LineCollection) diff --git a/tests/plotting/test_scatter.py b/tests/plotting/test_scatter.py index d963afde6..9f5d0bae9 100644 --- a/tests/plotting/test_scatter.py +++ b/tests/plotting/test_scatter.py @@ -545,3 +545,23 @@ def test_edges_do_not_change_the_axis_limits(ax): Scatter(EX, EY, EZ).make_plot(ax=ax, edges=True) assert ax.get_xlim() == (EX.min(), EX.max()) assert ax.get_ylim() == (EY.min(), EY.max()) + + +@pytest.mark.parametrize("axis", ["x", "y"]) +def test_a_point_a_log_axis_cannot_show_breaks_the_chain(ax, axis): + """A nonpositive value on a log axis is not drawn, so it breaks the chain. + + ``Scatter`` keeps such rows and matplotlib drops them from a log axis; + the edges must not run to them. ``set_log`` after construction counts. + ON FAILURE: the code is wrong. + """ + x, y = EX + 1.0, EY + 1.0 + if axis == "x": + x[2] = -1.0 + else: + y[2] = 0.0 + sc = Scatter(x, y, EZ) + sc.set_log(**{axis: True}) + _, _, lc, _ = sc.make_plot(ax=ax, edges=True) + _assert_segments(lc, x, y, [(0, 1), (3, 4)]) + np.testing.assert_array_equal(lc.get_array(), [1.0, 7.0]) From 0832b2324bbf5d3683cbc2aa9ab6f36cb5da810d Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:26:03 -0500 Subject: [PATCH 19/60] refactor(plotting)!: one take_data_in_yrange_across_x for the fixed grids Hist1D and Hist2D each kept a copy, and they had drifted: Hist1D no longer passed expected_logy to get_y_bounds, so callbacks written for Hist2D failed on it. One method on _OnFixedGrid now serves both, with _within moved to base. It lists x-bins from intervals["x"] instead of running agg(), validates every range in the caller's order as before, and finds each row's range with one searchsorted over the sorted left bounds when the ranges are disjoint, falling back to one pass per range when they overlap. On the evaluation datasets (1e5 and 1e6 rows; NaN, log axes, values on edges, empty bins, clip; disjoint, overlapping and partial ranges) the output equals the old methods'. BREAKING CHANGE: Hist1D calls get_y_bounds(row, expected_logy=False); a one-argument callback raises TypeError. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 + src/solarwindpy/plotting/base.py | 149 +++++++++++++++++++++++++ src/solarwindpy/plotting/hist1d.py | 84 -------------- src/solarwindpy/plotting/hist2d.py | 114 +------------------ tests/plotting/test_hist1d.py | 16 +-- tests/plotting/test_hist1d_defects.py | 2 +- tests/plotting/test_hist2d_defects.py | 2 +- tests/plotting/test_plot_invariants.py | 15 +-- tests/plotting/test_take_data.py | 4 - 9 files changed, 171 insertions(+), 221 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b9071223..3399aa4ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 then `plot.get_plotted_data(fcn)`. A `Hist1D` has no `alim`, so a threshold on a normalized or non-count `Hist1D` has no direct replacement: filter `plot.agg(fcn)` and select the rows of the kept bins through `plot.cut`. +- `Hist1D.take_data_in_yrange_across_x` calls `get_y_bounds(row, expected_logy=False)`, as + `Hist2D`'s calls it with its log flag; a callback written as `lambda row: ...` raises + `TypeError`. Accept the keyword, e.g. `lambda row, expected_logy=False: ...`. `Hist1D` and + `Hist2D` now share one implementation, which takes rows of disjoint x-ranges with one + `numpy.searchsorted` instead of a pass over the data per range (3 to 6 times faster at 1e5 + and 1e6 rows) and lists the x-bins from `intervals["x"]` instead of running `agg()`. ### Added diff --git a/src/solarwindpy/plotting/base.py b/src/solarwindpy/plotting/base.py index dd1855814..feeb68d04 100644 --- a/src/solarwindpy/plotting/base.py +++ b/src/solarwindpy/plotting/base.py @@ -43,6 +43,33 @@ RangeLimits = namedtuple("RangeLimits", "lower,upper", defaults=(None,)) +def _within(values, lower, upper, bins): + r"""Which ``values`` lie between ``lower`` and ``upper``, closed as ``bins`` are. + + Parameters + ---------- + values : pd.Series or np.ndarray + Values on the binned scale, ``log10(abs())`` on a log axis. + lower, upper : scalar + The bounds. + bins : pd.IntervalIndex + The axis's bins. Right-closed bins compare ``lower < v <= upper``; + left-closed bins compare ``lower <= v < upper`` and, as the last + left-closed bin also holds its right edge (``np.histogram``), keep + ``v == upper`` when ``upper`` is that edge. + + Returns + ------- + pd.Series or np.ndarray of bool + """ + if bins.closed == "left": + inside = (lower <= values) & (values < upper) + if upper == bins.right[-1]: + inside |= values == upper + return inside + return (lower < values) & (values <= upper) + + class Base(ABC): r"""Abstract base for SolarWindPy plots. @@ -1089,3 +1116,125 @@ def joint(self): def grouped(self): r"""`joint.groupby` with appropriate axes passes.""" return self.joint.groupby(list(self._grid_axes), observed=True) + + def take_data_in_yrange_across_x(self, ranges_by_x, get_x_bounds, get_y_bounds): + r"""Take the rows within a y-range in each of several x-ranges. + + Parameters + ---------- + ranges_by_x : pd.DataFrame + Indexed by x-bins of this plot (``intervals["x"]``); each row holds + what ``get_y_bounds`` reads for that bin. + get_x_bounds : callable + ``get_x_bounds(key, expected_logx=bool)`` returns ``left, right`` + for one index entry of `ranges_by_x`. ``expected_logx`` is + ``log.x``, so the bounds can be given as :math:`\log_{10} x` or + :math:`x` to match ``data``. + get_y_bounds : callable + ``get_y_bounds(row, expected_logy=bool)`` returns ``bottom, top`` + for one row of `ranges_by_x`. ``expected_logy`` is True only on a + ``Hist2D`` with a log y; a ``Hist1D`` stores y in linear units and + passes False. + + Returns + ------- + taken : np.ndarray + Sorted index labels of the rows with x between `left` and `right` + and y between `bottom` and `top`, once per range that holds them. + x compares on the side its bins close: ``left < x <= right`` for + right-closed bins (explicit edges), ``left <= x < right`` for + left-closed bins (an integer `nbins`), whose last bin also holds + its right edge, so ``x == right`` is kept when `right` is that + edge. A binned y (``Hist2D``) compares likewise with its y-bins; + a ``Hist1D``'s y is not binned and compares ``bottom < y <= top``. + + Raises + ------ + ValueError + If a range has ``left >= right`` or ``bottom >= top`` (the first + such range in the order of `ranges_by_x` is named), or if an entry + of `ranges_by_x` names an x-bin the plot does not have. x-bins + that `ranges_by_x` omits only log a warning. + + Notes + ----- + When the x-ranges do not overlap, each row's range is found with one + :func:`numpy.searchsorted` over the sorted left bounds; overlapping + ranges are taken one range at a time, so a row in two ranges is + taken twice. + """ + intervals = self.intervals + xbins = intervals["x"] + ybins = intervals.get("y") + if ranges_by_x.index.symmetric_difference(xbins).size: + drop = ranges_by_x.index.symmetric_difference(xbins) + if not drop.isin(xbins).all(): + raise ValueError( + "Need a way to drop values in selector that aren't available." + ) + self.logger.warning( + f"Dropping {drop.size} intervals from available for selecting." + ) + + logx = bool(self.log.x) + logy = bool(ybins is not None and self.log.y) + n = ranges_by_x.shape[0] + left, right = np.empty(n), np.empty(n) + bottom, top = np.empty(n), np.empty(n) + for i, (x, at_x) in enumerate(ranges_by_x.iterrows()): + lo, hi = get_x_bounds(x, expected_logx=logx) + b, t = get_y_bounds(at_x, expected_logy=logy) + if not lo < hi: + raise ValueError(f"Need left < right for x-bin {x}, got ({lo}, {hi}).") + if not b < t: + raise ValueError(f"Need bottom < top for x-bin {x}, got ({b}, {t}).") + left[i], right[i], bottom[i], top[i] = lo, hi, b, t + + data = self.data + xv = data.loc[:, "x"].to_numpy() + yv = data.loc[:, "y"].to_numpy() + labels = data.index.to_numpy() + + def in_y(values, b, t): + if ybins is None: + return (b < values) & (values <= t) + return _within(values, b, t, ybins) + + order = np.argsort(left, kind="stable") + left, right = left[order], right[order] + bottom, top = bottom[order], top[order] + last = xbins.right[-1] + overlap = np.any(right[:-1] > left[1:]) + if xbins.closed == "left": + # A range ending on the last edge also holds that edge, which the + # next range may start on. + overlap |= np.any((right[:-1] == last) & (left[1:] == last)) + if overlap: + taken = [ + labels[_within(xv, lo, hi, xbins) & in_y(yv, b, t)] + for lo, hi, b, t in zip(left, right, bottom, top) + ] + return np.sort(np.concatenate(taken)) if taken else labels[:0] + + # Disjoint ranges: each x is in at most one, found by its left bound. + # Left-closed: the range with the largest left <= x; right-closed: the + # largest left < x. + side = "right" if xbins.closed == "left" else "left" + j = np.searchsorted(left, xv, side) - 1 + inside = j >= 0 + jj = np.where(inside, j, 0) + if n == 0: + return labels[:0] + r = right[jj] + if xbins.closed == "left": + inside &= (xv < r) | ((xv == r) & (r == last)) + else: + inside &= xv <= r + b, t = bottom[jj], top[jj] + if ybins is None: + inside &= (b < yv) & (yv <= t) + elif ybins.closed == "left": + inside &= (b <= yv) & ((yv < t) | ((yv == t) & (t == ybins.right[-1]))) + else: + inside &= (b < yv) & (yv <= t) + return np.sort(labels[inside]) diff --git a/src/solarwindpy/plotting/hist1d.py b/src/solarwindpy/plotting/hist1d.py index edacdd387..f22c38feb 100644 --- a/src/solarwindpy/plotting/hist1d.py +++ b/src/solarwindpy/plotting/hist1d.py @@ -341,87 +341,3 @@ def make_plot( self._format_axis(ax, transpose_axes=transpose_axes) return ax, line, band, None - - def take_data_in_yrange_across_x( - self, - ranges_by_x, - get_x_bounds, - get_y_bounds, - ): - r"""Take data within y-ranges across x-values. - - Parameters - ---------- - ranges_by_x: iterable - An iterable with keys used to get the left and right bounds for the data - and values used to get the top and bottom bounds for the data. - - get_x_bounds: function - First argument is one key of `ranges_by_x` and returns `left, right`. - The keyword argument `expected_logx` is the bool ``self.log.x``, so - the returned values can be :math:`log(x)` or :math:`x` to match the - data stored in Hist1D. - - get_y_bounds: function - Takes one row of `ranges_by_x` and returns `bottom, top`. It gets - no log flag: Hist1D stores y in linear units. - - Returns - ------- - taken: np.ndarray 1D - Array of indices for selecting data in interval: the points with - x between `left` and `right` and ``bottom < y <= top``. x compares - on the side its bins close: ``left < x <= right`` for right-closed - bins (explicit edges), ``left <= x < right`` for left-closed bins - (an integer `nbins`), whose last bin also holds its right edge, so - ``x == right`` is kept when `right` is that edge. y is not binned, - so its range stays closed on the top. - - Raises - ------ - ValueError - If a range has ``left >= right`` or ``bottom >= top``, or if an - entry of `ranges_by_x` names an x-bin the histogram does not have. - Histogram x-bins that `ranges_by_x` omits only log a warning. - """ - - available_x = self.agg().index - if ranges_by_x.index.symmetric_difference(available_x).size: - drop = ranges_by_x.index.symmetric_difference(available_x) - if not drop.isin(available_x).all(): - raise ValueError( - "Need a way to drop values in selector that aren't available." - ) - else: - self.logger.warning( - f"Dropping {drop.size} intervals from available for selecting." - ) - - data = self.data - logx = self.log.x - - taken = [] - for x, at_x in ranges_by_x.iterrows(): - l, r = get_x_bounds(x, expected_logx=logx) - b, t = get_y_bounds(at_x) - - if not l < r: - raise ValueError(f"Need left < right for x-bin {x}, got ({l}, {r}).") - if not b < t: - raise ValueError(f"Need bottom < top for x-bin {x}, got ({b}, {t}).") - - bins = self.intervals["x"] - if bins.closed == "left": - tkx = (l <= data.x) & (data.x < r) - if r == bins.right[-1]: - # The last left-closed bin also holds its right edge. - tkx |= data.x == r - else: - tkx = (l < data.x) & (data.x <= r) - tky = (b < data.y) & (data.y <= t) - tk = tkx & tky - tk = tk.loc[tk].index - taken.append(tk) - - taken = np.sort(np.concatenate(taken)) - return taken diff --git a/src/solarwindpy/plotting/hist2d.py b/src/solarwindpy/plotting/hist2d.py index 756996344..6f8cb76cf 100644 --- a/src/solarwindpy/plotting/hist2d.py +++ b/src/solarwindpy/plotting/hist2d.py @@ -21,33 +21,6 @@ from .hist1d import Hist1D -def _within(values, lower, upper, bins): - r"""Which ``values`` lie between ``lower`` and ``upper``, closed as ``bins`` are. - - Parameters - ---------- - values : pd.Series - Values on the binned scale, ``log10(abs())`` on a log axis. - lower, upper : scalar - The bounds. - bins : pd.IntervalIndex - The axis's bins. Right-closed bins compare ``lower < v <= upper``; - left-closed bins compare ``lower <= v < upper`` and, as the last - left-closed bin also holds its right edge (``np.histogram``), keep - ``v == upper`` when ``upper`` is that edge. - - Returns - ------- - pd.Series of bool - """ - if bins.closed == "left": - inside = (lower <= values) & (values < upper) - if upper == bins.right[-1]: - inside |= values == upper - return inside - return (lower < values) & (values <= upper) - - class Hist2D(base._OnFixedGrid, base.ColorPlot, base.BinnedPlot): r"""2D histogram of (x, y), optionally aggregating a z-value in each bin. @@ -895,9 +868,9 @@ def id_data_above_contour(self, level): continue left, right = k.left, k.right bottom, top = v[tk].index.min().left, v[tk].index.max().right - above_contour_at_x = _within(x, left, right, intervals["x"]) & _within( - y, bottom, top, intervals["y"] - ) + above_contour_at_x = base._within( + x, left, right, intervals["x"] + ) & base._within(y, bottom, top, intervals["y"]) above_contour[above_contour_at_x] = k above_contour = pd.Series( @@ -905,84 +878,3 @@ def id_data_above_contour(self, level): ) return above_contour - - def take_data_in_yrange_across_x( - self, - ranges_by_x, - get_x_bounds, - get_y_bounds, - ): - r"""Take data within y-ranges across x-values. - - Parameters - ---------- - ranges_by_x: iterable - An iterable with keys used to get the left and right bounds for the data - and values used to get the top and bottom bounds for the data. - - get_x_bounds: function - First argument is one key of `ranges_by_x` and returns `left, right`. - The keyword argument `expected_logx` is the bool ``self.log.x``, so - the returned values can be :math:`log(x)` or :math:`x` to match the - data stored in Hist2D. - - get_y_bounds: functions - First argument is one row of `ranges_by_x` and returns - `bottom, top`. The keyword argument `expected_logy` is the bool - ``self.log.y``, so the returned values can be :math:`log(y)` or - :math:`y` to match the data stored in Hist2D. - - Returns - ------- - taken: np.ndarray 1D - Array of indices for selecting data in interval: the points with - x between `left` and `right` and y between `bottom` and `top`. - Each axis compares on the side its bins close: ``left < x <= - right`` for right-closed bins (explicit edges), ``left <= x < - right`` for left-closed bins (an integer `nbins`), whose last bin - also holds its right edge, so ``x == right`` is kept when `right` - is that edge. Likewise for y with the y-bins. - - Raises - ------ - ValueError - If a range has ``left >= right`` or ``bottom >= top``, or if an - entry of `ranges_by_x` names an x-bin the histogram does not have. - Histogram x-bins that `ranges_by_x` omits only log a warning. - """ - - available_x = self.agg().unstack("x").columns - if ranges_by_x.index.symmetric_difference(available_x).size: - drop = ranges_by_x.index.symmetric_difference(available_x) - if not drop.isin(available_x).all(): - raise ValueError( - "Need a way to drop values in selector that aren't available." - ) - else: - self.logger.warning( - f"Dropping {drop.size} intervals from available for selecting." - ) - - data = self.data - logx = self.log.x - logy = self.log.y - intervals = self.intervals - - taken = [] - for x, at_x in ranges_by_x.iterrows(): - l, r = get_x_bounds(x, expected_logx=logx) - b, t = get_y_bounds(at_x, expected_logy=logy) - - if not l < r: - raise ValueError(f"Need left < right for x-bin {x}, got ({l}, {r}).") - if not b < t: - raise ValueError(f"Need bottom < top for x-bin {x}, got ({b}, {t}).") - - tkx = _within(data.x, l, r, intervals["x"]) - tky = _within(data.y, b, t, intervals["y"]) - tk = tkx & tky - tk = tk.loc[tk].index - taken.append(tk) - - taken = np.sort(np.concatenate(taken)) - return taken diff --git a/tests/plotting/test_hist1d.py b/tests/plotting/test_hist1d.py index 36f2124ab..2d5f9cc1c 100644 --- a/tests/plotting/test_hist1d.py +++ b/tests/plotting/test_hist1d.py @@ -618,7 +618,7 @@ def test_nan_y_row_is_absent_from_data_and_every_selection(self): taken = h.take_data_in_yrange_across_x( ranges, lambda key, expected_logx=False: (key.left, key.right), - lambda row: (row.bottom, row.top), + lambda row, expected_logy: (row.bottom, row.top), ) assert list(taken) == self.KEPT @@ -749,8 +749,8 @@ def test_take_data_in_yrange_returns_labels_inside_each_bins_window(xy): Bottoms differ from bin to bin, so a window applied to the wrong bin selects a different set; the result is index labels, not positions. - ``get_y_bounds`` takes the row alone: Hist1D never log-transforms y, so it - hands no log flag. + ``get_y_bounds`` gets ``expected_logy=False``: Hist1D never log-transforms + y. ON FAILURE: the code is wrong. """ @@ -762,7 +762,7 @@ def test_take_data_in_yrange_returns_labels_inside_each_bins_window(xy): taken = hist.take_data_in_yrange_across_x( ranges, lambda interval, expected_logx: (interval.left, interval.right), - lambda row: (row["bottom"], row["top"]), + lambda row, expected_logy: (row["bottom"], row["top"]), ) xv, yv = x.values, y.values @@ -800,7 +800,7 @@ def test_take_data_in_yrange_windows_are_open_below_and_closed_above(): hist, ranges = _edge_hist_and_ranges() taken = hist.take_data_in_yrange_across_x( - ranges, _interval_bounds, lambda row: (row["bottom"], row["top"]) + ranges, _interval_bounds, lambda row, expected_logy: (row["bottom"], row["top"]) ) np.testing.assert_array_equal(taken, [10, 12, 13]) @@ -810,7 +810,7 @@ def test_take_data_in_yrange_windows_are_open_below_and_closed_above(): "x_bounds, y_bounds, match", [ (lambda iv, expected_logx: (iv.left, iv.left), None, "Need left < right"), - (None, lambda row: (5.0, 5.0), "Need bottom < top"), + (None, lambda row, expected_logy: (5.0, 5.0), "Need bottom < top"), ], ids=["zero-width-x", "zero-width-y"], ) @@ -823,7 +823,7 @@ def test_take_data_in_yrange_zero_width_range_raises_value_error( """ hist, ranges = _edge_hist_and_ranges() x_bounds = x_bounds or _interval_bounds - y_bounds = y_bounds or (lambda row: (row["bottom"], row["top"])) + y_bounds = y_bounds or (lambda row, expected_logy: (row["bottom"], row["top"])) with pytest.raises(ValueError, match=match + r" for x-bin .*, got \("): hist.take_data_in_yrange_across_x(ranges, x_bounds, y_bounds) @@ -843,7 +843,7 @@ def x_bounds(interval, expected_logx): return interval.left, interval.right hist.take_data_in_yrange_across_x( - ranges, x_bounds, lambda row: (row["bottom"], row["top"]) + ranges, x_bounds, lambda row, expected_logy: (row["bottom"], row["top"]) ) assert flags == [True, True] diff --git a/tests/plotting/test_hist1d_defects.py b/tests/plotting/test_hist1d_defects.py index 4a702e391..ffe30c7ba 100644 --- a/tests/plotting/test_hist1d_defects.py +++ b/tests/plotting/test_hist1d_defects.py @@ -119,7 +119,7 @@ def _interval_bounds(interval, expected_logx): return interval.left, interval.right -def _row_bounds(row): +def _row_bounds(row, expected_logy): return row["bottom"], row["top"] diff --git a/tests/plotting/test_hist2d_defects.py b/tests/plotting/test_hist2d_defects.py index e75891312..fb6f6ff42 100644 --- a/tests/plotting/test_hist2d_defects.py +++ b/tests/plotting/test_hist2d_defects.py @@ -180,7 +180,7 @@ def test_hist1d_yrange_selection_follows_left_closed_integer_bins(): taken = h.take_data_in_yrange_across_x( ranges, lambda key, expected_logx: (key.left, key.right), - lambda row: (row.bottom, row.top), + lambda row, expected_logy: (row.bottom, row.top), ) assert list(taken) == [0, 1, 2, 3, 4] diff --git a/tests/plotting/test_plot_invariants.py b/tests/plotting/test_plot_invariants.py index e82bde0cf..1267723f0 100644 --- a/tests/plotting/test_plot_invariants.py +++ b/tests/plotting/test_plot_invariants.py @@ -299,19 +299,10 @@ def x_bounds(interval, expected_logx): # The bins are on the stored scale, log10|x| when expected_logx. return interval.left, interval.right - if isinstance(h, Hist2D): - available = h.agg().unstack("x").columns + def y_bounds(at_x, expected_logy): + return at_x.bottom, at_x.top - def y_bounds(at_x, expected_logy): - return at_x.bottom, at_x.top - - else: - available = h.agg().index - - def y_bounds(at_x): - return at_x.bottom, at_x.top - - ranges = pd.DataFrame({"bottom": bottom, "top": top}, index=available) + ranges = pd.DataFrame({"bottom": bottom, "top": top}, index=h.intervals["x"]) taken = h.take_data_in_yrange_across_x(ranges, x_bounds, y_bounds) return [Selection(_as_labels(taken, data.index), None, True)] diff --git a/tests/plotting/test_take_data.py b/tests/plotting/test_take_data.py index aa6bffd2f..5439d6311 100644 --- a/tests/plotting/test_take_data.py +++ b/tests/plotting/test_take_data.py @@ -21,8 +21,6 @@ from solarwindpy.plotting.hist1d import Hist1D # noqa: E402 from solarwindpy.plotting.hist2d import Hist2D # noqa: E402 -_MERGED = pytest.mark.xfail(strict=True, reason="two copies of the method today") - # x in (0, 1], (1, 2], (2, 3] by explicit (right-closed) edges, one y each. X = pd.Series([0.5, 1.5, 2.5, 0.9], index=[10, 11, 12, 13]) Y = pd.Series([5.0, 6.0, 7.0, 8.0], index=[10, 11, 12, 13]) @@ -35,7 +33,6 @@ def _build(cls): return Hist2D(X, Y, nbins=[EDGES, np.array([0.0, 10.0])]) -@_MERGED def test_hist1d_and_hist2d_share_one_method(): """Neither class defines its own copy; both use the fixed-grid one. @@ -46,7 +43,6 @@ def test_hist1d_and_hist2d_share_one_method(): assert Hist1D.take_data_in_yrange_across_x is Hist2D.take_data_in_yrange_across_x -@_MERGED def test_hist1d_hands_expected_logy_false_to_the_y_callback(): """A Hist1D's y is never logged, so the y callback gets expected_logy=False. From c42ee79fc5b1add21e64d6181f07a1c1891514bd Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:26:59 -0500 Subject: [PATCH 20/60] fix(plotting): subscript vector components x, y, z lower case in labels TeXlabel rendered ("v", "x", "p1") as v_{X;p_1}: the registry mapped the x, y and z components to upper case. Vector components subscript lower case (v_x, B_z), so the registry maps them to x, y and z. A frame's coordinate axes are upper case by convention (X_GSE), so the gse and hci templates take the new $A placeholder, the component's code in upper case, and still render X_GSE. The r component keeps its R (RTN). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 ++ docs/source/usage.rst | 2 +- src/solarwindpy/core/quantities.py | 18 ++++---- src/solarwindpy/plotting/labels/base.py | 2 +- tests/plotting/labels/test_labels_base.py | 50 +++++++++++++++++------ tests/plotting/labels/test_special.py | 6 +-- 6 files changed, 57 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 83f5177bf..efc87dd5b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - The fit annotation (`TeXinfo.build_info` with `convert_pow_10`) prints a value or uncertainty whose exponent is 0 without an exponent: `2.5 \pm 1 \times 10^{-1}`, not `2.5 \times 10^{+0} \pm 1 \times 10^{-1}`. +- `TeXlabel` subscripts a vector's `x`, `y` and `z` components lower case, `v_x` rather than + `v_X`. A frame's position axes stay upper case, `X_\mathrm{GSE}`: a registry template + writes them with the new `$A` placeholder, the component's code in upper case. ## [0.4.0] - 2026-11-05 diff --git a/docs/source/usage.rst b/docs/source/usage.rst index 28ad45824..290a37e51 100644 --- a/docs/source/usage.rst +++ b/docs/source/usage.rst @@ -409,7 +409,7 @@ $n_{p_1} \; \left[\mathrm{cm}^{-3}\right]$ >>> print(TeXlabel(("b", "", ""))) $B \; \left[\mathrm{nT}\right]$ >>> print(TeXlabel(("v", "x", "a"))) -${v}_{{X};{\alpha}} \; \left[\mathrm{km \; s^{-1}}\right]$ +${v}_{{x};{\alpha}} \; \left[\mathrm{km \; s^{-1}}\right]$ A derived quantity uses its plasma method's name as ``M``. Methods such as :py:meth:`~solarwindpy.core.plasma.Plasma.T` and diff --git a/src/solarwindpy/core/quantities.py b/src/solarwindpy/core/quantities.py index f52579623..dd30121b2 100644 --- a/src/solarwindpy/core/quantities.py +++ b/src/solarwindpy/core/quantities.py @@ -15,7 +15,10 @@ each other. TeX templates are :class:`string.Template` strings: ``$C`` takes the TeX of the -component and ``$S`` the TeX of the species. +component, ``$A`` the component's code in upper case and ``$S`` the TeX of the +species. ``$A`` writes a frame's coordinate axes upper case, as is +conventional (:math:`X_\mathrm{GSE}`), where a vector's components are lower +case (:math:`v_x`). """ __all__ = [ @@ -85,8 +88,8 @@ class Quantity: # Coordinates and angles. # A frame's position is in its body's radius; `Spacecraft.distance2sun` # converts with it. - "gse": Quantity(r"{$C}_{\mathrm{GSE}}", _U["Re"], si=_EARTH_EQUATORIAL_RADIUS), - "hci": Quantity(r"{$C}_{\mathrm{HCI}}", _U["Rs"], si=_SOLAR_RADIUS), + "gse": Quantity(r"{$A}_{\mathrm{GSE}}", _U["Re"], si=_EARTH_EQUATORIAL_RADIUS), + "hci": Quantity(r"{$A}_{\mathrm{HCI}}", _U["Rs"], si=_SOLAR_RADIUS), "colat": Quantity(r"\theta_{$C}", _U["deg"]), "lat": Quantity(r"{lat}_{{$C};{$S}}", _U["deg"]), "lon": Quantity(r"{lon}_{{$C};{$S}}", _U["deg"]), @@ -193,10 +196,11 @@ class Quantity: #: TeX of each component (C level). COMPONENTS = MappingProxyType( { - # Coordinates. - "x": r"X", - "y": r"Y", - "z": r"Z", + # Cartesian components subscript lower case (v_x); a frame entry's + # template writes its axes upper case with `$A` (X_GSE). + "x": r"x", + "y": r"y", + "z": r"z", "r": r"R", # A vector's magnitude is its bare symbol: B, not B_mag. "mag": r"", diff --git a/src/solarwindpy/plotting/labels/base.py b/src/solarwindpy/plotting/labels/base.py index 5af1549ae..4ec0c3d8c 100644 --- a/src/solarwindpy/plotting/labels/base.py +++ b/src/solarwindpy/plotting/labels/base.py @@ -367,7 +367,7 @@ def _build_one_label(self, mcs): m1 = m c1 = _trans_component.get(c, c) s1 = self.make_species(s) - d = {"M": m1, "C": c1, "S": s1} + d = {"M": m1, "C": c1, "A": c.upper(), "S": s1} template_string = _template_of(m) template = Template(template_string) diff --git a/tests/plotting/labels/test_labels_base.py b/tests/plotting/labels/test_labels_base.py index bf2dfa5bb..abd16261b 100644 --- a/tests/plotting/labels/test_labels_base.py +++ b/tests/plotting/labels/test_labels_base.py @@ -58,23 +58,23 @@ def test_run_species_substitution(texlabel_basic): def test_texlabel_attributes(texlabel_basic): """Check attributes of a typical :class:`TeXlabel`.""" - assert texlabel_basic.tex == "{v}_{{X};{p}}" + assert texlabel_basic.tex == "{v}_{{x};{p}}" assert texlabel_basic.units == "\\mathrm{km \\; s^{-1}}" assert texlabel_basic.path == Path("v_x_p") assert ( texlabel_basic.with_units - == "${v}_{{X};{p}} \\; \\left[\\mathrm{km \\; s^{-1}}\\right]$" + == "${v}_{{x};{p}} \\; \\left[\\mathrm{km \\; s^{-1}}\\right]$" ) def test_texlabel_ratio_attributes(texlabel_ratio): """Check attributes of a ratio :class:`TeXlabel`.""" - assert texlabel_ratio.tex == "{v}_{{X};{p}}/n_{p}" + assert texlabel_ratio.tex == "{v}_{{x};{p}}/n_{p}" assert texlabel_ratio.units == "\\mathrm{km \\; s^{-1}}/\\mathrm{cm}^{-3}" assert texlabel_ratio.path == Path("v_x_p-OV-n_p") assert ( texlabel_ratio.with_units - == "${v}_{{X};{p}}/n_{p} \\; \\left[\\mathrm{km \\; s^{-1}}/\\mathrm{cm}^{-3}\\right]$" + == "${v}_{{x};{p}}/n_{p} \\; \\left[\\mathrm{km \\; s^{-1}}/\\mathrm{cm}^{-3}\\right]$" ) @@ -124,7 +124,7 @@ def test_texlabel_axnorm_types(labels_base): def test_texlabel_error_measurement(texlabel_with_error): """Test error measurement handling.""" assert "\\sigma" in texlabel_with_error.tex - assert "{v}_{{X};{p}}" in texlabel_with_error.tex + assert "{v}_{{x};{p}}" in texlabel_with_error.tex def test_texlabel_newline_units(texlabel_newline_units): @@ -177,9 +177,9 @@ def test_measurement_translation(labels_base): def test_component_translation(labels_base): """Test component translation.""" test_cases = { - ("v", "x", "p"): "X", - ("v", "y", "p"): "Y", - ("v", "z", "p"): "Z", + ("v", "x", "p"): "x", + ("v", "y", "p"): "y", + ("v", "z", "p"): "z", ("v", "r", "p"): "R", ("v", "per", "p"): "\\perp", ("v", "par", "p"): "\\parallel", @@ -242,7 +242,7 @@ def test_template_substitution(labels_base): # Test default template label = labels_base.TeXlabel(("unknown_measurement", "x", "p")) - assert "{unknown_measurement}_{{X};{p}}" in label.tex + assert "{unknown_measurement}_{{x};{p}}" in label.tex def test_tex_cleanup(labels_base): @@ -409,7 +409,7 @@ def test_format_with_description_none_unchanged(self, labels_base): label = labels_base.TeXlabel(("v", "x", "p")) assert label.description is None assert label.with_units == ( - "${v}_{{X};{p}} \\; \\left[\\mathrm{km \\; s^{-1}}\\right]$" + "${v}_{{x};{p}} \\; \\left[\\mathrm{km \\; s^{-1}}\\right]$" ) def test_format_with_description_adds_prefix(self, labels_base): @@ -534,11 +534,11 @@ def test_measurement_units_follow_author_decision(labels_base, mcs, units): # A component with no TeX translation is used as written. (("v", "w", "p"), "{v}_{{w};{p}}"), # "_err" wraps the label in sigma(). - (("v_err", "x", "p"), "\\sigma({v}_{{X};{p}})"), + (("v_err", "x", "p"), "\\sigma({v}_{{x};{p}})"), # "caani" template "... \; ($C)" with C empty drops "\; ()". (("caani", "", ""), "C^{(\\mathrm{Ani})}_{A}"), # "nuc" template "\nu_{$C,$S}": an empty side drops its comma. - (("nuc", "x", ""), "\\nu_{X}"), + (("nuc", "x", ""), "\\nu_{x}"), (("nuc", "", "p1"), "\\nu_{p_1}"), # "SEP_differential_flux" template "{{$S}} \: dJ/dE" with S empty # drops "{{}}" and the leading space. @@ -658,3 +658,29 @@ def test_logger_is_named_for_module_and_class(labels_base): """ label = labels_base.TeXlabel(("n", "", "p")) assert label.logger.name == "solarwindpy.plotting.labels.base.TeXlabel" + + +@pytest.mark.parametrize("c", ["x", "y", "z"]) +def test_cartesian_component_is_a_lowercase_subscript(labels_base, c): + """A vector's x, y and z components subscript as written: v_x, B_z. + + ON FAILURE: the code is wrong. + """ + assert labels_base.TeXlabel(("v", c, "p1")).tex == "{v}_{{%s};{p_1}}" % c + assert labels_base.TeXlabel(("b", c, "")).tex == "B_{%s}" % c + + +@pytest.mark.parametrize( + "mcs, tex", + [ + (("gse", "x", ""), r"{X}_{\mathrm{GSE}}"), + (("gse", "z", ""), r"{Z}_{\mathrm{GSE}}"), + (("hci", "y", ""), r"{Y}_{\mathrm{HCI}}"), + ], +) +def test_frame_position_axes_stay_upper_case(labels_base, mcs, tex): + """A frame's coordinate axes are upper case by convention: X_GSE, not x_GSE. + + ON FAILURE: the code is wrong. + """ + assert labels_base.TeXlabel(mcs).tex == tex diff --git a/tests/plotting/labels/test_special.py b/tests/plotting/labels/test_special.py index 2ee17f5fc..adb257f3b 100644 --- a/tests/plotting/labels/test_special.py +++ b/tests/plotting/labels/test_special.py @@ -1001,13 +1001,13 @@ def test_long_and_short_tex_from_labels(self, n_p1): """ v = labels_base.TeXlabel(("v", "x", "a")) long_form = labels_special.Xcorr(n_p1, v, "pearson") - assert long_form.tex == r"\mathrm{{Pearson}}(n_{p_1},{v}_{{X};{\alpha}})" + assert long_form.tex == r"\mathrm{{Pearson}}(n_{p_1},{v}_{{x};{\alpha}})" assert str(long_form) == ( - r"$\mathrm{{Pearson}}(n_{p_1},{v}_{{X};{\alpha}}) \; \left[\#\right]$" + r"$\mathrm{{Pearson}}(n_{p_1},{v}_{{x};{\alpha}}) \; \left[\#\right]$" ) assert long_form.path == Path("XcorrPearson-n_p1-v_x_a") short = labels_special.Xcorr(n_p1, v, "pearson", short_tex=True) - assert short.tex == r"\rho_{P}(n_{p_1},{v}_{{X};{\alpha}})" + assert short.tex == r"\rho_{P}(n_{p_1},{v}_{{x};{\alpha}})" def test_string_constituents_spaces_and_tex_spacing(self): r"""Spaces in string constituents become one ``\,`` in TeX and ``-`` in the path. From 41cbde3ed7b2ad6d88f136578d9e1df1cc8defa3 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:29:13 -0500 Subject: [PATCH 21/60] test(plotting): a count in agg equals a groupby count, without grouping Guards: agg(fcn="count") on Hist1D, Hist2D and SpiralPlot2D, with empty cells, clim and every axnorm the binning allows, equals a pandas groupby count on the plot's cell codes run through the same steps. Target, xfail(strict=True) until the fast path lands: a count does not call _grouped_by_cell, while a mean does. Co-Authored-By: Claude Opus 5.5 --- tests/plotting/test_agg_count.py | 100 +++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 tests/plotting/test_agg_count.py diff --git a/tests/plotting/test_agg_count.py b/tests/plotting/test_agg_count.py new file mode 100644 index 000000000..3befd055d --- /dev/null +++ b/tests/plotting/test_agg_count.py @@ -0,0 +1,100 @@ +# Spent-When: PERMANENT(agg stops counting cells with numpy.bincount) +# Supersedes: none +"""Tests for the count path of ``BinnedPlot.agg``. + +A count needs no groupby: ``numpy.bincount`` of the rows' cell codes gives it. +``agg`` takes that path when the aggregation is a count with no keywords, and +its result must equal what a pandas groupby count gives, the reference here, +built in the test from the plot's own cell codes and run through the same +``clim``, ``axnorm`` and cell filter. Empty cells stay NaN. +""" + +import numpy as np +import pandas as pd +import pytest +import matplotlib + +matplotlib.use("Agg") + +from solarwindpy.plotting.hist1d import Hist1D # noqa: E402 +from solarwindpy.plotting.hist2d import Hist2D # noqa: E402 +from solarwindpy.plotting.spiral import SpiralPlot2D # noqa: E402 + +RNG = np.random.default_rng(11) +N = 2000 +# A gap in x around 0 leaves empty bins in the middle of the grid. +_x = RNG.normal(size=N) +X = pd.Series(np.where(np.abs(_x) < 0.4, _x + 3, _x)) +Y = pd.Series(RNG.normal(size=N)) + + +def _plots(): + yield "Hist1D", Hist1D(X, nbins=20), ("t", "d") + yield "Hist2D", Hist2D(X, Y, nbins=15), ("t", "d", "c", "r", "cd", "rd") + yield ( + "SpiralPlot2D", + SpiralPlot2D(X, Y, initial_bins=4, min_per_bin=60), + ("t", "d"), + ) + + +def _groupby_reference(h): + """agg("count") rebuilt with a pandas groupby on the plot's cell codes.""" + codes = np.asarray(h.binning.codes()) + inside = codes >= 0 + cnt = ( + pd.Series(np.ones(inside.sum(), dtype=np.int64)).groupby(codes[inside]).count() + ) + agg = cnt.astype(np.int64) + c0, c1 = h.clim + if c0 is not None: + agg = agg.where(cnt >= c0) + if c1 is not None: + agg = agg.where(cnt <= c1) + agg = h.binning.postfilter(agg) + cells = h.binning.cells + positions = agg.index.to_numpy() + agg = agg.set_axis(cells[positions]) + agg = h.binning.normalize(agg, h.axnorm, positions) + return agg.reindex(cells) + + +CASES = [ + pytest.param(name, plot, axnorm, clim, id=f"{name}-{axnorm}-{clim}") + for name, plot, norms in _plots() + for axnorm in (None, *norms) + for clim in (None, 5) +] + + +@pytest.mark.parametrize("name, h, axnorm, clim", CASES) +def test_count_equals_a_groupby_count(name, h, axnorm, clim): + """``agg(fcn="count")`` equals the groupby reference, empty cells NaN. + + ON FAILURE: the code is wrong. + """ + h.set_clim(clim, None) + h.set_axnorm(axnorm) + got = h.agg(fcn="count") + expected = _groupby_reference(h) + np.testing.assert_array_equal(got.to_numpy(), expected.to_numpy()) + assert got.index.equals(expected.index) + assert got.isna().any() # the gap leaves empty cells + + +@pytest.mark.xfail(strict=True, reason="agg counts with a groupby today") +def test_a_count_does_not_group_the_rows(): + """A count runs without ``_grouped_by_cell``; a mean still uses it. + + ON FAILURE: the code is wrong. + """ + h = Hist2D(X, Y, nbins=15) + + def refuse(): + raise AssertionError("count went through the groupby") + + h._grouped_by_cell = refuse + counts = h.agg(fcn="count") + assert counts.sum() == N + with pytest.raises(AssertionError, match="groupby"): + h.agg(fcn="mean") From 60199d6775bea598bc9bb1bacfe32cf417e79669 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:30:06 -0500 Subject: [PATCH 22/60] test(plotting): pin Scatter connect joining points in increasing z Strict xfail until make_plot(connect=True, connect_kwargs=None) replaces edges: segments follow a stable sort on z, independent of row order; ties keep row order; points not drawn (NaN, mask, alim, <= 0 on a log axis) are skipped, not gaps; without a varying z, row order in one colour. Return is (ax, points, segments, cbar). Co-Authored-By: Claude Opus 5.5 --- tests/plotting/test_scatter.py | 186 +++++++++++++++++++-------------- 1 file changed, 108 insertions(+), 78 deletions(-) diff --git a/tests/plotting/test_scatter.py b/tests/plotting/test_scatter.py index 9f5d0bae9..f4d67c006 100644 --- a/tests/plotting/test_scatter.py +++ b/tests/plotting/test_scatter.py @@ -382,13 +382,20 @@ def test_scatter_figure_renders_to_png(): # --------------------------------------------------------------------------- -# edges: line segments joining consecutive points, in source row order. EZ is -# chosen so each segment's mean z, (z[i] + z[i+1]) / 2, is distinct. +# connect: line segments joining the drawn points in increasing z, row order +# without a varying z. EZ is not sorted, so z order differs from row order: +# rows by increasing z are 0, 1, 3, 4, 2, and each segment's mean z is +# distinct. # --------------------------------------------------------------------------- EX = np.array([0.0, 1.0, 2.0, 3.0, 4.0]) EY = np.array([0.0, 1.0, 0.0, 1.0, 0.0]) EZ = np.array([0.0, 2.0, 9.0, 6.0, 8.0]) +Z_ORDER = [(0, 1), (1, 3), (3, 4), (4, 2)] + +_CONNECT_PENDING = pytest.mark.xfail( + strict=True, reason="Scatter.make_plot(connect=True) is not implemented" +) def _segments(x, y, pairs): @@ -402,8 +409,13 @@ def _assert_segments(lc, x, y, pairs): np.testing.assert_array_equal(g, e) -def test_make_plot_returns_ax_points_edges_then_cbar(ax): - """``(ax, points, edges, cbar)``; edges is None unless ``edges=True``. +def _mean_z(z, pairs): + return [(z[i] + z[j]) / 2 for i, j in pairs] + + +@_CONNECT_PENDING +def test_make_plot_returns_ax_points_segments_then_cbar(ax): + """``(ax, points, segments, cbar)``; segments is None unless ``connect=True``. ON FAILURE: the code is wrong. """ @@ -415,30 +427,58 @@ def test_make_plot_returns_ax_points_edges_then_cbar(ax): assert isinstance(out[3], Colorbar) assert not any(isinstance(c, LineCollection) for c in ax.collections) - out = Scatter(EX, EY, EZ).make_plot(ax=ax, edges=True) + out = Scatter(EX, EY, EZ).make_plot(ax=ax, connect=True) assert len(out) == 4 assert isinstance(out[2], LineCollection) assert out[2] in ax.collections -def test_edges_join_each_pair_of_consecutive_points(ax): - """n points in row order give n - 1 segments, point i to point i + 1. +@_CONNECT_PENDING +def test_connect_joins_the_points_in_increasing_z(ax): + """n drawn points give n - 1 segments, each to the point next in z. + + ON FAILURE: the code is wrong. + """ + _, _, lc, _ = Scatter(EX, EY, EZ).make_plot(ax=ax, connect=True) + _assert_segments(lc, EX, EY, Z_ORDER) + + +@_CONNECT_PENDING +def test_connect_does_not_depend_on_row_order(ax): + """Shuffled rows, with shuffled labels, give the same segments in z order. ON FAILURE: the code is wrong. """ - _, _, lc, _ = Scatter(EX, EY, EZ).make_plot(ax=ax, edges=True) - _assert_segments(lc, EX, EY, [(0, 1), (1, 2), (2, 3), (3, 4)]) + perm = np.array([3, 0, 4, 2, 1]) + x, y, z = (pd.Series(v[perm], index=perm[::-1]) for v in (EX, EY, EZ)) + _, _, lc, _ = Scatter(x, y, z).make_plot(ax=ax, connect=True) + _assert_segments(lc, EX, EY, Z_ORDER) + np.testing.assert_array_equal(lc.get_array(), _mean_z(EZ, Z_ORDER)) -def test_edge_colour_is_the_mean_endpoint_z_through_the_points_cmap_and_norm(ax): - """Segment i is ``cmap(norm((z[i] + z[i+1]) / 2))``: one colorbar serves both. +@_CONNECT_PENDING +def test_points_with_equal_z_keep_their_row_order(ax): + """The sort on z is stable: tied points are joined in the order given. + + ON FAILURE: the code is wrong. + """ + z = np.array([1.0, 0.0, 1.0, 0.0, 2.0]) + _, _, lc, _ = Scatter(EX, EY, z).make_plot(ax=ax, connect=True) + _assert_segments(lc, EX, EY, [(1, 3), (3, 0), (0, 2), (2, 4)]) + + +@_CONNECT_PENDING +def test_segment_colour_is_the_mean_endpoint_z_through_the_points_cmap_and_norm( + ax, +): + """A segment is ``cmap(norm((z_a + z_b) / 2))``: one colorbar serves both. ON FAILURE: the code is wrong. """ _, points, lc, cbar = Scatter(EX, EY, EZ).make_plot( - ax=ax, edges=True, cmap="plasma" + ax=ax, connect=True, cmap="plasma" ) - mean = (EZ[:-1] + EZ[1:]) / 2 + mean = _mean_z(EZ, Z_ORDER) np.testing.assert_array_equal(lc.get_array(), mean) assert lc.norm is points.norm assert lc.get_cmap() is points.get_cmap() @@ -449,119 +489,109 @@ def test_edge_colour_is_the_mean_endpoint_z_through_the_points_cmap_and_norm(ax) assert cbar.mappable is points -def test_edges_follow_a_norm_the_caller_passes(ax): - """``vmin``/``vmax`` given to the points also set the edges' colours. +@_CONNECT_PENDING +def test_segments_follow_a_norm_the_caller_passes(ax): + """``vmin``/``vmax`` given to the points also set the segments' colours. ON FAILURE: the code is wrong. """ _, points, lc, _ = Scatter(EX, EY, EZ).make_plot( - ax=ax, edges=True, vmin=0.0, vmax=20.0 + ax=ax, connect=True, vmin=0.0, vmax=20.0 ) assert lc.norm is points.norm assert (lc.norm.vmin, lc.norm.vmax) == (0.0, 20.0) -def test_a_point_with_nan_breaks_the_chain(ax): - """A dropped NaN point removes both its segments; no segment bridges it. - - ON FAILURE: the code is wrong. - """ +def _nan_y_at_3(): y = EY.copy() - y[2] = np.nan - _, _, lc, _ = Scatter(EX, y, EZ).make_plot(ax=ax, edges=True) - _assert_segments(lc, EX, y, [(0, 1), (3, 4)]) - np.testing.assert_array_equal(lc.get_array(), [1.0, 7.0]) + y[3] = np.nan + return Scatter(EX, y, EZ), EX, y -def test_a_point_outside_alim_breaks_the_chain(ax): - """A point ``alim`` hides drops both its segments, as a NaN point does. - - EZ[2] = 9 is the only z above 8, so two segments go, not one. - ON FAILURE: the code is wrong. - """ +def _alim_hides_2(): sc = Scatter(EX, EY, EZ) sc.set_alim(None, 8.0) - _, _, lc, _ = sc.make_plot(ax=ax, edges=True) - _assert_segments(lc, EX, EY, [(0, 1), (3, 4)]) - np.testing.assert_array_equal(lc.get_array(), [1.0, 7.0]) + return sc, EX, EY -def test_a_masked_point_breaks_the_chain(ax): - """A point ``mask`` excludes drops both its segments. +def _mask_drops_1(): + mask = pd.Series([True, False, True, True, True]) + return Scatter(EX, EY, EZ, mask=mask), EX, EY - ON FAILURE: the code is wrong. - """ - mask = pd.Series([True, True, True, False, True]) - _, _, lc, _ = Scatter(EX, EY, EZ, mask=mask).make_plot(ax=ax, edges=True) - _assert_segments(lc, EX, EY, [(0, 1), (1, 2)]) +def _log_x_drops_3(): + x = EX + 1.0 + x[3] = -1.0 + sc = Scatter(x, EY, EZ) + sc.set_log(x=True) + return sc, x, EY -def test_consecutive_is_row_position_not_label(ax): - """Rows are joined in the order given, even with repeated or unsorted labels. + +@_CONNECT_PENDING +@pytest.mark.parametrize( + "build, pairs", + [ + (_nan_y_at_3, [(0, 1), (1, 4), (4, 2)]), + (_alim_hides_2, [(0, 1), (1, 3), (3, 4)]), + (_mask_drops_1, [(0, 3), (3, 4), (4, 2)]), + (_log_x_drops_3, [(0, 1), (1, 4), (4, 2)]), + ], + ids=["nan", "alim", "mask", "log-nonpositive"], +) +def test_a_point_not_drawn_is_skipped_not_a_gap(ax, build, pairs): + """A point that is not drawn is left out: its z neighbours are joined. ON FAILURE: the code is wrong. """ - index = [3, 3, 1, 0, 2] - x, y, z = (pd.Series(v, index=index) for v in (EX, EY, EZ)) - _, _, lc, _ = Scatter(x, y, z).make_plot(ax=ax, edges=True) - _assert_segments(lc, EX, EY, [(0, 1), (1, 2), (2, 3), (3, 4)]) + sc, x, y = build() + _, _, lc, _ = sc.make_plot(ax=ax, connect=True) + _assert_segments(lc, x, y, pairs) + np.testing.assert_array_equal(lc.get_array(), _mean_z(EZ, pairs)) +@_CONNECT_PENDING @pytest.mark.parametrize("z", [None, pd.Series(7.0, index=range(EX.size))]) -def test_edges_without_varying_z_have_one_colour(ax, z): - """With no z, or a constant one, every segment has the points' colour. +def test_without_varying_z_points_are_joined_in_row_order_in_one_colour(ax, z): + """With no z, or a constant one, segments follow the rows, in the points' colour. + A point that is not drawn (here a NaN y) is skipped there too. ON FAILURE: the code is wrong. """ - _, points, lc, cbar = Scatter(EX, EY, z).make_plot(ax=ax, edges=True) + y = EY.copy() + y[2] = np.nan + _, points, lc, cbar = Scatter(EX, y, z).make_plot(ax=ax, connect=True) assert cbar is None assert lc.get_array() is None - _assert_segments(lc, EX, EY, [(0, 1), (1, 2), (2, 3), (3, 4)]) + _assert_segments(lc, EX, y, [(0, 1), (1, 3), (3, 4)]) colors = lc.get_edgecolor() assert len(colors) == 1 np.testing.assert_array_equal(colors[0], points.get_facecolor()[0]) -def test_edges_sit_below_the_points_and_take_edge_kwargs(ax): - """Edges default to beneath the markers; ``edge_kwargs`` styles them. +@_CONNECT_PENDING +def test_segments_sit_below_the_points_and_take_connect_kwargs(ax): + """Segments default to beneath the markers; ``connect_kwargs`` styles them. ON FAILURE: the code is wrong. """ - _, points, lc, _ = Scatter(EX, EY, EZ).make_plot(ax=ax, edges=True) + _, points, lc, _ = Scatter(EX, EY, EZ).make_plot(ax=ax, connect=True) assert lc.get_zorder() < points.get_zorder() kwargs = {"linewidth": 3.0, "alpha": 0.4, "zorder": 5} - _, _, lc, _ = Scatter(EX, EY, EZ).make_plot(ax=ax, edges=True, edge_kwargs=kwargs) + _, _, lc, _ = Scatter(EX, EY, EZ).make_plot( + ax=ax, connect=True, connect_kwargs=kwargs + ) assert kwargs == {"linewidth": 3.0, "alpha": 0.4, "zorder": 5} np.testing.assert_array_equal(lc.get_linewidth(), [3.0]) assert (lc.get_alpha(), lc.get_zorder()) == (0.4, 5) -def test_edges_do_not_change_the_axis_limits(ax): - """The view fits the points with or without edges. +@_CONNECT_PENDING +def test_segments_do_not_change_the_axis_limits(ax): + """The view fits the points with or without segments. ON FAILURE: the code is wrong. """ - Scatter(EX, EY, EZ).make_plot(ax=ax, edges=True) + Scatter(EX, EY, EZ).make_plot(ax=ax, connect=True) assert ax.get_xlim() == (EX.min(), EX.max()) assert ax.get_ylim() == (EY.min(), EY.max()) - - -@pytest.mark.parametrize("axis", ["x", "y"]) -def test_a_point_a_log_axis_cannot_show_breaks_the_chain(ax, axis): - """A nonpositive value on a log axis is not drawn, so it breaks the chain. - - ``Scatter`` keeps such rows and matplotlib drops them from a log axis; - the edges must not run to them. ``set_log`` after construction counts. - ON FAILURE: the code is wrong. - """ - x, y = EX + 1.0, EY + 1.0 - if axis == "x": - x[2] = -1.0 - else: - y[2] = 0.0 - sc = Scatter(x, y, EZ) - sc.set_log(**{axis: True}) - _, _, lc, _ = sc.make_plot(ax=ax, edges=True) - _assert_segments(lc, x, y, [(0, 1), (3, 4)]) - np.testing.assert_array_equal(lc.get_array(), [1.0, 7.0]) From be19d6512a50acbca0168776b41afce806db72a9 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:36:38 -0500 Subject: [PATCH 23/60] feat(plotting): rename Scatter edges to connect, joined in increasing z Author decisions: the keyword is connect (connect_kwargs), since edges means bin edges elsewhere, and the returned artist is segments: (ax, points, segments, cbar). Points are joined in a stable sort on z, so rows need not be sorted and ties keep row order; with z = time the segments trace the trajectory. Points not drawn (NaN, mask, alim, <= 0 on a log axis) are skipped, not gaps. Without a varying z, row order. Skipping drops the read of the private _PlotSource rows. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 16 +++-- src/solarwindpy/plotting/scatter.py | 100 ++++++++++++---------------- tests/plotting/test_return_order.py | 8 +-- tests/plotting/test_scatter.py | 14 ---- 4 files changed, 57 insertions(+), 81 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ea2209856..ad8ce8dbd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,16 +16,18 @@ 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. -- `Scatter.make_plot(edges=True)` joins each pair of consecutive points, in the order the rows - were given, with a line segment colored by the mean z of its two points through the points' - colormap and norm, so one colorbar serves both and a path through time is visible. - `edge_kwargs` styles the segments. A point that is not drawn (NaN, outside `mask` or - outside `alim`) breaks the chain. Without a varying z, the segments take the points' color. +- `Scatter.make_plot(connect=True)` joins the drawn points with line segments in increasing + z, so with z the time of each point they trace its trajectory, and with another z how + (x, y) changes as z increases. Rows need not be sorted; equal z keep their row order. Each + segment is colored by the mean z of its two points through the points' colormap and norm, + so one colorbar serves both. `connect_kwargs` styles the segments. A point that is not drawn + (NaN, outside `mask` or `alim`, or <= 0 on a log axis) is skipped. Without a varying z, the + points are joined in row order in the points' color. ### Changed - BREAKING CHANGES -- `Scatter.make_plot` returns `(ax, points, edges, cbar)`: the `LineCollection` of the - segments, or None without `edges=True`, sits before the colorbar. Unpack four values where +- `Scatter.make_plot` returns `(ax, points, segments, cbar)`: the `LineCollection` of the + segments, or None without `connect=True`, sits before the colorbar. Unpack four values where three were unpacked before. ### Changed diff --git a/src/solarwindpy/plotting/scatter.py b/src/solarwindpy/plotting/scatter.py index 0c0ce1d13..398bc84b6 100644 --- a/src/solarwindpy/plotting/scatter.py +++ b/src/solarwindpy/plotting/scatter.py @@ -72,8 +72,8 @@ def make_plot( ax=None, cbar=True, cbar_kwargs=None, - edges=False, - edge_kwargs=None, + connect=False, + connect_kwargs=None, **kwargs, ): r"""Make a scatter plot on `ax` using `ax.scatter`. @@ -86,11 +86,10 @@ def make_plot( If True, create color bar with `labels.z`. cbar_kwargs: dict, None If not None, kwargs passed to `self._make_cbar`. - edges: bool - If True, join each pair of consecutive points with a line segment - (see Notes), so a path through the data, e.g. through time, is - visible. - edge_kwargs: dict, None + connect: bool + If True, join the drawn points with line segments in increasing + z (see Notes). + connect_kwargs: dict, None Passed to :class:`~matplotlib.collections.LineCollection`, e.g. ``linewidth``, ``alpha`` or ``zorder``. The defaults are a ``linewidth`` of 0.75 and a ``zorder`` just below the points'. @@ -103,9 +102,8 @@ def make_plot( ax: mpl.axes.Axes collection: mpl.collections.PathCollection The points. - edges: matplotlib.collections.LineCollection or None - The segments joining consecutive points if `edges` is True, else - None. + segments: matplotlib.collections.LineCollection or None + The segments joining the points if `connect` is True, else None. cbar: mpl.colorbar.Colorbar or None The colorbar if `cbar` is True and z varies, else None. @@ -115,19 +113,21 @@ def make_plot( do not enter the colour scale, and do not set the axis limits. With ``kind="quantile"`` the thresholds are quantiles of the plotted z. - Consecutive points are adjacent rows in the order x, y and z were - given, by position, not by index label: sort time-indexed data by - time before building the plot to draw its path through time. A - segment joins two drawn points only. A row that is not drawn (NaN or - infinite, outside ``mask``, outside ``alim``, or <= 0 on a log axis) - breaks the chain: neither of its segments is drawn and its neighbours - are not joined. - - When z varies, segment i is coloured by ``(z[i] + z[i + 1]) / 2`` - through the points' colormap and norm, the same objects, so the one - colorbar reads both. Otherwise every segment has the points' colour, - unless ``edge_kwargs`` sets ``color``. The edges do not set the axis - limits. + With ``connect=True`` each drawn point is joined to the drawn point + next in increasing z, a stable sort, so points with equal z keep the + order of their rows and the rows need not be sorted. With z the time + of each point, the segments trace its trajectory; with any other z + they trace how (x, y) changes as z increases. Without a varying z + (no z, or one value), the points are joined in row order. A point + that is not drawn (NaN or infinite, outside ``mask``, outside + ``alim``, or <= 0 on a log axis) is skipped, not a gap: the points + on either side of it are joined. + + When z varies, each segment is coloured by the mean z of its two + points, ``(z_a + z_b) / 2``, through the points' colormap and norm, + the same objects, so the one colorbar reads both. Otherwise every + segment has the points' colour, unless ``connect_kwargs`` sets + ``color``. The segments do not set the axis limits. """ if ax is None: fig, ax = plt.subplots() @@ -137,8 +137,7 @@ def make_plot( if clip: data[k] = self.clip_data(data.loc[:, k], clip) - shown = self._apply_alim(data.loc[:, "z"]).notna() - data = data.loc[shown] + data = data.loc[self._apply_alim(data.loc[:, "z"]).notna()] if data.loc[:, "z"].unique().size > 1: zkey = "z" @@ -147,11 +146,9 @@ def make_plot( collection = ax.scatter(x="x", y="y", c=zkey, data=data, **kwargs) - lines = None - if edges: - lines = self._make_edges( - ax, collection, data, shown.to_numpy(), zkey, edge_kwargs - ) + segments = None + if connect: + segments = self._connect(ax, collection, data, zkey, connect_kwargs) if cbar and zkey is not None: cbar_kwargs = self._prepare_cbar_kwargs(cbar_kwargs, ax) @@ -161,10 +158,10 @@ def make_plot( self._format_axis(ax, collection, data) - return ax, collection, lines, cbar + return ax, collection, segments, cbar - def _make_edges(self, ax, collection, data, shown, zkey, edge_kwargs): - r"""Add segments joining consecutive drawn points to `ax`; see `make_plot`. + def _connect(self, ax, collection, data, zkey, connect_kwargs): + r"""Add segments joining the drawn points to `ax`; see `make_plot`. Parameters ---------- @@ -172,52 +169,43 @@ def _make_edges(self, ax, collection, data, shown, zkey, edge_kwargs): collection: mpl.collections.PathCollection The points, whose colormap, norm and colour the segments share. data: pd.DataFrame - The drawn points, in source row order. - shown: np.ndarray of bool - For each row of ``self.data``, True if ``alim`` keeps it. + The points not hidden by ``alim``, in row order. zkey: str or None ``"z"`` if the points are colour-mapped, else None. - edge_kwargs: Mapping or None + connect_kwargs: Mapping or None Passed to ``LineCollection``. Returns ------- matplotlib.collections.LineCollection """ - rows = self._source.rows - if rows is None: - position = np.arange(self._source.index.size) - else: - position = np.flatnonzero(rows) - position = position[shown] xy = data.loc[:, ["x", "y"]].to_numpy(dtype=float) # The data stay linear, so a log axis cannot show a value <= 0. - drawn = np.ones(position.size, dtype=bool) + drawn = np.ones(xy.shape[0], dtype=bool) for i, log in enumerate(self.log): if log: drawn &= xy[:, i] > 0 - joined = (np.diff(position) == 1) & drawn[:-1] & drawn[1:] - start = np.flatnonzero(joined) - - segments = np.stack([xy[start], xy[start + 1]], axis=1) + xy = xy[drawn] - kwargs = cbook.normalize_kwargs(edge_kwargs or {}, LineCollection) + kwargs = cbook.normalize_kwargs(connect_kwargs or {}, LineCollection) kwargs.setdefault("linewidth", 0.75) kwargs.setdefault("zorder", collection.get_zorder() - 0.5) if zkey is None: kwargs.setdefault("color", collection.get_facecolor()[0]) - lines = LineCollection(segments, **kwargs) + segments = LineCollection(np.stack([xy[:-1], xy[1:]], axis=1), **kwargs) else: + z = data.loc[:, zkey].to_numpy(dtype=float)[drawn] + order = np.argsort(z, kind="stable") + xy, z = xy[order], z[order] collection.autoscale_None() - lines = LineCollection( - segments, + segments = LineCollection( + np.stack([xy[:-1], xy[1:]], axis=1), cmap=collection.get_cmap(), norm=collection.norm, **kwargs, ) - z = data.loc[:, zkey].to_numpy(dtype=float) - lines.set_array((z[start] + z[start + 1]) / 2) + segments.set_array((z[:-1] + z[1:]) / 2) - ax.add_collection(lines, autolim=False) - return lines + ax.add_collection(segments, autolim=False) + return segments diff --git a/tests/plotting/test_return_order.py b/tests/plotting/test_return_order.py index f3c1f3e02..8eecec8e5 100644 --- a/tests/plotting/test_return_order.py +++ b/tests/plotting/test_return_order.py @@ -6,7 +6,7 @@ which is None when there is none: ``(ax, artists..., cbar_or_None)``. A contour method returns its contour set as the last artist, just before the colorbar. A method's tuple has the same length whether or not a colorbar -is drawn, whether a Scatter has z or draws its edges, and whether a +is drawn, whether a Scatter has z or connects its points, and whether a Hist1D draws its uncertainty window. Each position keeps its type too, with one exception: Hist1D's line slot holds the ``ErrorbarContainer`` without the window and the central ``Line2D`` with it, so the error-bar @@ -117,10 +117,10 @@ def _close(): (PathCollection, NONE), ), ( - "Scatter.make_plot-edges", + "Scatter.make_plot-connect", lambda: Scatter(X, Y, Z), "make_plot", - {"edges": True}, + {"connect": True}, (PathCollection, LineCollection), ), ] @@ -148,7 +148,7 @@ def test_color_plot_returns_ax_then_artists_then_cbar_or_none( def test_scatter_without_z_returns_its_collection_and_no_colorbar(): - """A Scatter without z keeps the same shape: points, edges or None, then None. + """A Scatter without z keeps the same shape: points, segments or None, then None. ON FAILURE: the code is wrong. """ diff --git a/tests/plotting/test_scatter.py b/tests/plotting/test_scatter.py index f4d67c006..aaa18a263 100644 --- a/tests/plotting/test_scatter.py +++ b/tests/plotting/test_scatter.py @@ -393,10 +393,6 @@ def test_scatter_figure_renders_to_png(): EZ = np.array([0.0, 2.0, 9.0, 6.0, 8.0]) Z_ORDER = [(0, 1), (1, 3), (3, 4), (4, 2)] -_CONNECT_PENDING = pytest.mark.xfail( - strict=True, reason="Scatter.make_plot(connect=True) is not implemented" -) - def _segments(x, y, pairs): return [np.array([[x[i], y[i]], [x[j], y[j]]]) for i, j in pairs] @@ -413,7 +409,6 @@ def _mean_z(z, pairs): return [(z[i] + z[j]) / 2 for i, j in pairs] -@_CONNECT_PENDING def test_make_plot_returns_ax_points_segments_then_cbar(ax): """``(ax, points, segments, cbar)``; segments is None unless ``connect=True``. @@ -433,7 +428,6 @@ def test_make_plot_returns_ax_points_segments_then_cbar(ax): assert out[2] in ax.collections -@_CONNECT_PENDING def test_connect_joins_the_points_in_increasing_z(ax): """n drawn points give n - 1 segments, each to the point next in z. @@ -443,7 +437,6 @@ def test_connect_joins_the_points_in_increasing_z(ax): _assert_segments(lc, EX, EY, Z_ORDER) -@_CONNECT_PENDING def test_connect_does_not_depend_on_row_order(ax): """Shuffled rows, with shuffled labels, give the same segments in z order. @@ -456,7 +449,6 @@ def test_connect_does_not_depend_on_row_order(ax): np.testing.assert_array_equal(lc.get_array(), _mean_z(EZ, Z_ORDER)) -@_CONNECT_PENDING def test_points_with_equal_z_keep_their_row_order(ax): """The sort on z is stable: tied points are joined in the order given. @@ -467,7 +459,6 @@ def test_points_with_equal_z_keep_their_row_order(ax): _assert_segments(lc, EX, EY, [(1, 3), (3, 0), (0, 2), (2, 4)]) -@_CONNECT_PENDING def test_segment_colour_is_the_mean_endpoint_z_through_the_points_cmap_and_norm( ax, ): @@ -489,7 +480,6 @@ def test_segment_colour_is_the_mean_endpoint_z_through_the_points_cmap_and_norm( assert cbar.mappable is points -@_CONNECT_PENDING def test_segments_follow_a_norm_the_caller_passes(ax): """``vmin``/``vmax`` given to the points also set the segments' colours. @@ -527,7 +517,6 @@ def _log_x_drops_3(): return sc, x, EY -@_CONNECT_PENDING @pytest.mark.parametrize( "build, pairs", [ @@ -549,7 +538,6 @@ def test_a_point_not_drawn_is_skipped_not_a_gap(ax, build, pairs): np.testing.assert_array_equal(lc.get_array(), _mean_z(EZ, pairs)) -@_CONNECT_PENDING @pytest.mark.parametrize("z", [None, pd.Series(7.0, index=range(EX.size))]) def test_without_varying_z_points_are_joined_in_row_order_in_one_colour(ax, z): """With no z, or a constant one, segments follow the rows, in the points' colour. @@ -568,7 +556,6 @@ def test_without_varying_z_points_are_joined_in_row_order_in_one_colour(ax, z): np.testing.assert_array_equal(colors[0], points.get_facecolor()[0]) -@_CONNECT_PENDING def test_segments_sit_below_the_points_and_take_connect_kwargs(ax): """Segments default to beneath the markers; ``connect_kwargs`` styles them. @@ -586,7 +573,6 @@ def test_segments_sit_below_the_points_and_take_connect_kwargs(ax): assert (lc.get_alpha(), lc.get_zorder()) == (0.4, 5) -@_CONNECT_PENDING def test_segments_do_not_change_the_axis_limits(ax): """The view fits the points with or without segments. From 9da692c98341777bfcd7b408e90b2053f8709b75 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:37:03 -0500 Subject: [PATCH 24/60] perf(plotting): count cells with numpy.bincount in agg When the aggregation is a count with no keywords, agg counts each cell's rows with np.bincount of the cached cell codes, keeps the occupied cells as a groupby count would (so empty cells stay NaN), and reuses the counts for clim. Every other aggregation still groups. The output equals the groupby path exactly (values, dtype, index, name) on Hist1D, Hist2D and SpiralPlot2D with empty cells, clim and each axnorm. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +++ src/solarwindpy/plotting/base.py | 24 ++++++++++++++++++++---- tests/plotting/test_agg_count.py | 1 - 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3399aa4ba..f1345e609 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,6 +53,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- A count in `agg` (`fcn="count"`, or the default on a plot without z) counts each cell's rows + with `numpy.bincount` of the rows' cell codes instead of a pandas groupby: same result, about + twice as fast at 1e6 rows. - `pre-commit install` now installs the commit-message hook as well as the pre-commit hook (`default_install_hook_types` in `.pre-commit-config.yaml`), so the conventional-commit check runs without a separate `pre-commit install --hook-type commit-msg`. diff --git a/src/solarwindpy/plotting/base.py b/src/solarwindpy/plotting/base.py index feeb68d04..2b2d897aa 100644 --- a/src/solarwindpy/plotting/base.py +++ b/src/solarwindpy/plotting/base.py @@ -959,16 +959,32 @@ def agg(self, fcn=None, **kwargs): "\n".join([f"""{k!s}: {v!s}""" for k, v in lbls.items()]), ) - gb = self._grouped_by_cell() - if fcn is None: fcn = "count" if self._source.counts else "mean" - agg = gb.agg(fcn, **kwargs) + if isinstance(fcn, str) and fcn == "count" and not kwargs: + # Count fast path: rows per cell straight from the cell codes, no + # groupby. Keep only occupied cells, as a groupby count would, so + # empty cells stay NaN after the reindex below. The aggregated + # column has no NaN on kept rows, so this equals its groupby count. + codes = self._cell_codes() + n = np.bincount(codes[codes >= 0], minlength=len(self.binning.cells)) + occupied = np.flatnonzero(n) + cnt = pd.Series( + n[occupied].astype(np.int64), + index=pd.Index(occupied, dtype=np.int64), + name=self.agg_axes, + ) + agg = cnt + else: + gb = self._grouped_by_cell() + agg = gb.agg(fcn, **kwargs) + cnt = None c0, c1 = self.clim if c0 is not None or c1 is not None: - cnt = gb.agg("count") + if cnt is None: + cnt = gb.agg("count") tk = pd.Series(True, index=agg.index) if c0 is not None: tk = tk & (cnt >= c0) diff --git a/tests/plotting/test_agg_count.py b/tests/plotting/test_agg_count.py index 3befd055d..48af012f9 100644 --- a/tests/plotting/test_agg_count.py +++ b/tests/plotting/test_agg_count.py @@ -82,7 +82,6 @@ def test_count_equals_a_groupby_count(name, h, axnorm, clim): assert got.isna().any() # the gap leaves empty cells -@pytest.mark.xfail(strict=True, reason="agg counts with a groupby today") def test_a_count_does_not_group_the_rows(): """A count runs without ``_grouped_by_cell``; a mean still uses it. From ac3ad2174a8ca22c4b9351eebceff4d8bb973b03 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:37:13 -0500 Subject: [PATCH 25/60] fix(plotting): label a tensor quantity's scalar without a component TeXlabel(("T", "scalar", "p1")) read T_{\mathrm{scalar};p_1}: the registry gave the scalar component a literal "scalar" subscript. The scalar of a tensor quantity is its bare symbol, as a vector's magnitude is, so the component now renders empty and the label reads T_{p_1}, the same as with the component left empty. The save path still names the component. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 ++ docs/source/usage.rst | 7 ++----- src/solarwindpy/core/quantities.py | 3 ++- tests/plotting/labels/test_labels_base.py | 13 +++++++++++++ 4 files changed, 19 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index efc87dd5b..ffbdb8a73 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,6 +51,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `TeXlabel` subscripts a vector's `x`, `y` and `z` components lower case, `v_x` rather than `v_X`. A frame's position axes stay upper case, `X_\mathrm{GSE}`: a registry template writes them with the new `$A` placeholder, the component's code in upper case. +- `TeXlabel` renders the `scalar` component as no component, like `mag`: `("T", "scalar", "p1")` + reads `T_{p_1}`, not `T_{\mathrm{scalar};p_1}`. ## [0.4.0] - 2026-11-05 diff --git a/docs/source/usage.rst b/docs/source/usage.rst index 290a37e51..df1d651d9 100644 --- a/docs/source/usage.rst +++ b/docs/source/usage.rst @@ -414,15 +414,12 @@ ${v}_{{x};{\alpha}} \; \left[\mathrm{km \; s^{-1}}\right]$ A derived quantity uses its plasma method's name as ``M``. Methods such as :py:meth:`~solarwindpy.core.plasma.Plasma.T` and :py:meth:`~solarwindpy.core.plasma.Plasma.beta` return columns ``par``, -``per`` and ``scalar``, and the label prints the component as given, so the -scalar column's key gives a literal "scalar" subscript. For the scalar, leave -the component empty: +``per`` and ``scalar``. The scalar column's label is the bare symbol, the same +as with the component left empty: >>> print(TeXlabel(("T", "par", "p1"))) ${T}_{{\parallel};{p_1}} \; \left[10^5 \, \mathrm{K}\right]$ >>> print(TeXlabel(("T", "scalar", "p1"))) -${T}_{{\mathrm{scalar}};{p_1}} \; \left[10^5 \, \mathrm{K}\right]$ ->>> print(TeXlabel(("T", "", "p1"))) ${T}_{{p_1}} \; \left[10^5 \, \mathrm{K}\right]$ >>> print(TeXlabel(("beta", "", "p1"))) ${\beta}_{{p_1}} \; \left[\mathrm{\#}\right]$ diff --git a/src/solarwindpy/core/quantities.py b/src/solarwindpy/core/quantities.py index dd30121b2..7ce8c9c0e 100644 --- a/src/solarwindpy/core/quantities.py +++ b/src/solarwindpy/core/quantities.py @@ -209,7 +209,8 @@ class Quantity: "lat": r"\lambda", "lon": r"\phi", "R": r"\mathrm{R}", - "scalar": r"\mathrm{scalar}", + # A tensor quantity's scalar is its bare symbol, like a magnitude. + "scalar": r"", "theta": r"\theta", "phi": r"\phi", "per": r"\perp", diff --git a/tests/plotting/labels/test_labels_base.py b/tests/plotting/labels/test_labels_base.py index abd16261b..bb39bbe71 100644 --- a/tests/plotting/labels/test_labels_base.py +++ b/tests/plotting/labels/test_labels_base.py @@ -684,3 +684,16 @@ def test_frame_position_axes_stay_upper_case(labels_base, mcs, tex): ON FAILURE: the code is wrong. """ assert labels_base.TeXlabel(mcs).tex == tex + + +@pytest.mark.parametrize("m", ["T", "w", "beta", "p"]) +def test_scalar_component_renders_as_no_component(labels_base, m): + """The scalar column of a tensor quantity is the bare scalar: T_{p_1}. + + A scalar has no component, as the ``mag`` of a vector is its bare symbol. + + ON FAILURE: the code is wrong. + """ + scalar = labels_base.TeXlabel((m, "scalar", "p1")) + assert scalar.tex == labels_base.TeXlabel((m, "", "p1")).tex + assert "scalar" not in scalar.tex From ec8ffd078aafd0ab8ac36fd5152115779d16a09b Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:43:18 -0500 Subject: [PATCH 26/60] test(plotting): axnorm follows the aggregation, with w, wc and wr Target tests, xfail(strict=True) until the change: densities of a mean integrate to the mean z (overall, per column, per row, on linear and log grids); w, wc and wr sum to those means; a median's density integrates to the count-weighted median; a sum's shares add to 1 and a negative z raises for them; count weights are count fractions; t divides signed values by the largest magnitude; Hist1D takes d with a mean; the new keys are allowed and labelled. Expected values come from numpy on the inputs. Co-Authored-By: Claude Opus 5.5 --- tests/plotting/test_axnorm_by_fcn.py | 248 +++++++++++++++++++++++++++ 1 file changed, 248 insertions(+) create mode 100644 tests/plotting/test_axnorm_by_fcn.py diff --git a/tests/plotting/test_axnorm_by_fcn.py b/tests/plotting/test_axnorm_by_fcn.py new file mode 100644 index 000000000..047d32811 --- /dev/null +++ b/tests/plotting/test_axnorm_by_fcn.py @@ -0,0 +1,248 @@ +# Spent-When: PERMANENT(axnorm stops depending on the aggregation) +# Supersedes: none +"""Tests for ``axnorm`` applied according to the aggregation. + +Notation for one cell i: n_i rows, area A_i on the binned scale (log10 on a +log axis), aggregated value v_i; N is the number of rows in the shown cells, +N_col and N_row those in a column or row. + +- A count: d = n_i / (N A_i) and w = n_i / N, as before. +- A sum of z: d = S_i / (S A_i) and w = S_i / S, each cell's share of the + total z, S the total over the shown cells; a negative z raises. +- Any other aggregation (mean, median, a callable): d = v_i n_i / (N A_i) + and w = v_i n_i / N, so sum(d A) and sum(w) are the count-weighted average + of v. For a mean that is the mean z of the rows. +- cd, rd, wc and wr do the same within each column or row. +- t, c and r divide by the largest absolute value overall, per column or per + row. + +Every expected number is computed here with numpy from the inputs, which all +lie inside the grid, never from the plot's own code. +""" + +import numpy as np +import pandas as pd +import pytest +import matplotlib + +matplotlib.use("Agg") + +from solarwindpy.plotting.hist1d import Hist1D # noqa: E402 +from solarwindpy.plotting.hist2d import Hist2D # noqa: E402 +from solarwindpy.plotting.labels.base import TeXlabel # noqa: E402 +from solarwindpy.plotting.labels.special import Count # noqa: E402 +from solarwindpy.plotting.spiral import SpiralPlot2D # noqa: E402 +from tests.tolerances import exact # noqa: E402 + +_NEW = pytest.mark.xfail(strict=True, reason="axnorm ignores the aggregation today") + +RNG = np.random.default_rng(21) +N = 4000 +X = pd.Series(RNG.uniform(0.0, 3.0, N)) +Y = pd.Series(RNG.uniform(0.0, 2.0, N)) +Z = pd.Series(RNG.normal(1.0, 2.0, N)) # signed +ZPOS = pd.Series(RNG.lognormal(0.0, 1.0, N)) +XEDGES = np.linspace(0.0, 3.0, 7) # widths 0.5 +YEDGES = np.array([0.0, 0.3, 1.0, 2.0]) # unequal widths +# Log grid: x and y in (1, 1000), edges in log10. +LX = pd.Series(10 ** RNG.uniform(0.0, 3.0, N)) +LY = pd.Series(10 ** RNG.uniform(0.0, 3.0, N)) +LEDGES = np.array([0.0, 0.5, 1.5, 3.0]) + + +def _cell(x, y, xedges, yedges): + """x-bin and y-bin of each row, from numpy.digitize.""" + return np.digitize(x, xedges) - 1, np.digitize(y, yedges) - 1 + + +def _area(xedges, yedges): + return np.outer(np.diff(xedges), np.diff(yedges)) + + +def _h2(z, fcn, axnorm, log=False): + if log: + h = Hist2D(LX, LY, z, logx=True, logy=True, nbins=[LEDGES, LEDGES]) + else: + h = Hist2D(X, Y, z, nbins=[XEDGES, YEDGES]) + h.set_axnorm(axnorm) + agg = h.agg(fcn=fcn) + nx = len(h.intervals["x"]) + return agg.to_numpy().reshape(nx, -1) + + +def _inputs(log): + if log: + ix, iy = _cell(np.log10(LX), np.log10(LY), LEDGES, LEDGES) + return ix, iy, _area(LEDGES, LEDGES), np.diff(LEDGES), np.diff(LEDGES) + ix, iy = _cell(X, Y, XEDGES, YEDGES) + return ix, iy, _area(XEDGES, YEDGES), np.diff(XEDGES), np.diff(YEDGES) + + +@_NEW +@pytest.mark.parametrize( + "build, allowed", + [ + (lambda: Hist1D(X), ("d", "t", "w")), + ( + lambda: Hist2D(X, Y), + ("c", "r", "t", "d", "cd", "rd", "w", "wc", "wr"), + ), + ( + lambda: SpiralPlot2D(X, Y, initial_bins=3, min_per_bin=500), + ("d", "t", "w"), + ), + ], + ids=["Hist1D", "Hist2D", "SpiralPlot2D"], +) +def test_allowed_axnorm_adds_the_weight_keys(build, allowed): + """1-D and spiral allow d, t, w; the 2-D grid adds c, r, cd, rd, wc, wr. + + ON FAILURE: the code is wrong. + """ + assert tuple(build().binning.allowed_axnorm) == allowed + + +@_NEW +@pytest.mark.parametrize("log", [False, True], ids=["linear", "log"]) +def test_density_of_a_mean_integrates_to_the_mean_z(log): + """sum(d A) over the grid is the mean z of every row. + + ON FAILURE: the code is wrong. + """ + d = _h2(Z, "mean", "d", log) + _, _, area, _, _ = _inputs(log) + assert np.nansum(d * area) == exact(Z.mean()) + + +@_NEW +@pytest.mark.parametrize("log", [False, True], ids=["linear", "log"]) +def test_column_and_row_densities_of_a_mean_integrate_to_their_means(log): + """cd integrates over y to each column's mean z, rd over x to each row's. + + ON FAILURE: the code is wrong. + """ + ix, iy, _, dx, dy = _inputs(log) + cd = _h2(Z, "mean", "cd", log) + rd = _h2(Z, "mean", "rd", log) + col_means = Z.groupby(ix).mean().to_numpy() + row_means = Z.groupby(iy).mean().to_numpy() + assert np.nansum(cd * dy, axis=1) == exact(col_means) + assert np.nansum(rd * dx[:, None], axis=0) == exact(row_means) + + +@_NEW +def test_weights_of_a_mean_sum_to_the_means(): + """w sums to the mean z; wc over each column and wr over each row to theirs. + + ON FAILURE: the code is wrong. + """ + ix, iy, _, _, _ = _inputs(False) + w = _h2(Z, "mean", "w") + wc = _h2(Z, "mean", "wc") + wr = _h2(Z, "mean", "wr") + assert np.nansum(w) == exact(Z.mean()) + assert np.nansum(wc, axis=1) == exact(Z.groupby(ix).mean().to_numpy()) + assert np.nansum(wr, axis=0) == exact(Z.groupby(iy).mean().to_numpy()) + + +@_NEW +def test_density_of_a_median_integrates_to_the_count_weighted_median(): + """sum(d A) is sum(median_i n_i) / N over the cells, not the overall median. + + ON FAILURE: the code is wrong. + """ + ix, iy, area, _, _ = _inputs(False) + cells = pd.Series(Z.to_numpy()).groupby([ix, iy]) + expected = (cells.median() * cells.size()).sum() / N + d = _h2(Z, "median", "d") + assert np.nansum(d * area) == exact(expected) + assert abs(expected - Z.median()) > 0.01 # not the overall median + + +@_NEW +@pytest.mark.parametrize("fcn", ["sum", np.sum], ids=["str", "np.sum"]) +def test_shares_of_a_sum_add_to_one(fcn): + """For a sum, d A, w, cd dy per column and wr per row each add to 1. + + ON FAILURE: the code is wrong. + """ + _, _, area, _, dy = _inputs(False) + assert np.nansum(_h2(ZPOS, fcn, "d") * area) == exact(1.0) + assert np.nansum(_h2(ZPOS, fcn, "w")) == exact(1.0) + cd = np.nansum(_h2(ZPOS, fcn, "cd") * dy, axis=1) + assert cd == exact(np.ones_like(cd)) + wr = np.nansum(_h2(ZPOS, fcn, "wr"), axis=0) + assert wr == exact(np.ones_like(wr)) + + +@_NEW +def test_a_share_of_a_sum_with_a_negative_z_raises(): + """A sum's share needs z >= 0; t is a peak normalization and still works. + + ON FAILURE: the code is wrong. + """ + with pytest.raises(ValueError, match="negative"): + _h2(Z, "sum", "d") + t = _h2(Z, "sum", "t") + assert np.nanmax(np.abs(t)) == exact(1.0) + + +@_NEW +def test_count_weights_are_count_fractions(): + """For a count, w = n_i / N, wc = n_i / N_col and wr = n_i / N_row. + + ON FAILURE: the code is wrong. + """ + ix, iy, _, _, _ = _inputs(False) + n, _, _ = np.histogram2d(X, Y, bins=[XEDGES, YEDGES]) + assert _h2(None, None, "w") == exact(n / N) + assert _h2(None, None, "wc") == exact(n / n.sum(axis=1, keepdims=True)) + assert _h2(None, None, "wr") == exact(n / n.sum(axis=0)) + + +@_NEW +def test_peak_norms_of_signed_values_divide_by_the_largest_magnitude(): + """t of signed means: the largest |value| becomes 1 and signs are kept. + + ON FAILURE: the code is wrong. + """ + z = pd.Series(np.where(X < 1.5, -5.0, 1.0) + 0.1 * Z) + raw = _h2(z, "mean", None) + t = _h2(z, "mean", "t") + assert t == exact(raw / np.nanmax(np.abs(raw))) + assert np.nanmin(t) == exact(-1.0) + + +@_NEW +def test_hist1d_density_of_a_mean_integrates_to_the_mean(): + """A Hist1D of x averaging Z: sum(d width) is the mean of Z. + + ON FAILURE: the code is wrong. + """ + h = Hist1D(X, Z, nbins=XEDGES) + h.set_axnorm("d") + d = h.agg().to_numpy() + assert np.nansum(d * np.diff(XEDGES)) == exact(Z.mean()) + + +@_NEW +@pytest.mark.parametrize("key", ["w", "wc", "wr"]) +def test_labels_accept_the_weight_keys(key): + """Count and TeXlabel take w, wc and wr, and name them in the path. + + ON FAILURE: the code is wrong. + """ + count = Count(norm=key) + assert str(count.path).endswith(key.upper() + "norm") + label = TeXlabel(("n", "", "p1"), axnorm=key) + assert str(label.path).endswith(key.upper() + "norm") + + +@_NEW +def test_count_plot_with_a_weight_key_relabels_its_count(): + """A Hist2D count with axnorm="w" labels z as a count fraction. + + ON FAILURE: the code is wrong. + """ + h = Hist2D(X, Y, nbins=[XEDGES, YEDGES], axnorm="w") + assert "Fraction" in str(h.labels.z) From 4c9c5e4782f6928c45660eab198e0717d26d4f3c Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:43:28 -0500 Subject: [PATCH 27/60] fix(plotting): state one dimensionless unit across labels The registry's dimensionless unit was \mathrm{\#}, which beta and the other dimensionless quantities stated, while ratio, axnorm, count and composition labels each wrote a literal \#. The two render alike but are two spellings of one unit, so labels compared by string disagreed. The registry's UNIT_TEX["dimless"] is now \#, and every label reads it from there. The temperature anisotropy R, a ratio of temperatures, stated \perp/\parallel as its units; it is dimensionless and states the same. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 ++ docs/source/usage.rst | 2 +- src/solarwindpy/core/quantities.py | 4 +-- src/solarwindpy/plotting/labels/base.py | 4 +-- .../plotting/labels/composition.py | 4 +-- .../plotting/labels/elemental_abundance.py | 2 +- src/solarwindpy/plotting/labels/special.py | 10 +++--- tests/plotting/labels/test_labels_base.py | 33 ++++++++++++++++--- tests/plotting/labels/test_special.py | 16 ++++----- 9 files changed, 50 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ffbdb8a73..52998998b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,6 +53,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 writes them with the new `$A` placeholder, the component's code in upper case. - `TeXlabel` renders the `scalar` component as no component, like `mag`: `("T", "scalar", "p1")` reads `T_{p_1}`, not `T_{\mathrm{scalar};p_1}`. +- Labels state one dimensionless unit, `\#`, the registry's `UNIT_TEX["dimless"]`: beta and + the other dimensionless quantities wrote `\mathrm{\#}` while ratios and counts wrote `\#`. + The temperature anisotropy `R` states it too, in place of `\perp/\parallel`. ## [0.4.0] - 2026-11-05 diff --git a/docs/source/usage.rst b/docs/source/usage.rst index df1d651d9..0dd3233ef 100644 --- a/docs/source/usage.rst +++ b/docs/source/usage.rst @@ -422,7 +422,7 @@ ${T}_{{\parallel};{p_1}} \; \left[10^5 \, \mathrm{K}\right]$ >>> print(TeXlabel(("T", "scalar", "p1"))) ${T}_{{p_1}} \; \left[10^5 \, \mathrm{K}\right]$ >>> print(TeXlabel(("beta", "", "p1"))) -${\beta}_{{p_1}} \; \left[\mathrm{\#}\right]$ +${\beta}_{{p_1}} \; \left[\#\right]$ A dimensionless quantity, such as :math:`\beta`, has the units :math:`[\#]`. A second key makes a ratio: diff --git a/src/solarwindpy/core/quantities.py b/src/solarwindpy/core/quantities.py index 7ce8c9c0e..2a717487f 100644 --- a/src/solarwindpy/core/quantities.py +++ b/src/solarwindpy/core/quantities.py @@ -65,7 +65,7 @@ class Quantity: "kms": r"\mathrm{km \; s^{-1}}", "pPa": r"\mathrm{pPa}", "cm-3": r"\mathrm{cm}^{-3}", - "dimless": r"\mathrm{\#}", + "dimless": r"\#", "unknown": r"???", "km": r"\mathrm{km}", "deg": r"\mathrm{deg.}", @@ -132,7 +132,7 @@ class Quantity: "qhat": Quantity(r"{\widehat{q}}_{{$C};{$S}}", _U["dimless"]), "Qhat": Quantity(r"{\widehat{q}}_{{$C};{$S}}", _U["dimless"]), "Wk": Quantity(r"W_{K;{$S}}", _FLUX_DENSITY, si=1e-6), - "R": Quantity(r"{R}_{{$C};{$S}}", r"\perp/\parallel"), + "R": Quantity(r"{R}_{{$C};{$S}}", _U["dimless"]), "beta": Quantity(r"{\beta}_{{$C};{$S}}", _U["dimless"], si=1.0), "dbeta": Quantity(r"{\Delta \beta}_{{$C};{$S}}", _U["dimless"]), "pdv": Quantity(r"P_{\Delta v_{$S}}", _U["pPa"]), diff --git a/src/solarwindpy/plotting/labels/base.py b/src/solarwindpy/plotting/labels/base.py index 4ec0c3d8c..e0b3f0379 100644 --- a/src/solarwindpy/plotting/labels/base.py +++ b/src/solarwindpy/plotting/labels/base.py @@ -430,7 +430,7 @@ def _combine_tex_path_units_axnorm(self, tex, path, units): axnorm = self.axnorm tex_norm = _trans_axnorm[axnorm] if tex_norm: - units = r"\#" + units = _inU["dimless"] tex = r"\mathrm{%s \; Norm} \; %s" % (tex_norm, tex) # noqa: W605 path = path / (axnorm.upper() + "norm") @@ -457,7 +457,7 @@ def build_label(self): _units_of(m1.replace("_err", "")), ) if u0 == u1: - units = r"\#" + units = _inU["dimless"] else: units = r"{}/{}".format(u0, u1) diff --git a/src/solarwindpy/plotting/labels/composition.py b/src/solarwindpy/plotting/labels/composition.py index 48ab280f7..c3afd8c65 100644 --- a/src/solarwindpy/plotting/labels/composition.py +++ b/src/solarwindpy/plotting/labels/composition.py @@ -45,7 +45,7 @@ def tex(self): @property def units(self): r"""TeX of the count units.""" - return r"\#" # noqa: W605 + return base._inU["dimless"] @property def path(self): @@ -126,7 +126,7 @@ def units(self): uA = self.ionA.units uB = self.ionB.units - units = r"\#" + units = base._inU["dimless"] if uA != uB: units = f"{uA}/{uB}" diff --git a/src/solarwindpy/plotting/labels/elemental_abundance.py b/src/solarwindpy/plotting/labels/elemental_abundance.py index 0d0d49cf5..56e441d16 100644 --- a/src/solarwindpy/plotting/labels/elemental_abundance.py +++ b/src/solarwindpy/plotting/labels/elemental_abundance.py @@ -62,7 +62,7 @@ def units(self): if self.pct_unit: return r"\%" else: - return r"\#" # noqa: W605 + return base._inU["dimless"] @property def tex(self): diff --git a/src/solarwindpy/plotting/labels/special.py b/src/solarwindpy/plotting/labels/special.py index 7a9876ef6..b409c0c75 100644 --- a/src/solarwindpy/plotting/labels/special.py +++ b/src/solarwindpy/plotting/labels/special.py @@ -232,7 +232,7 @@ def __init__(self, short_label=True, description=None): self.set_description(description) def __str__(self): - result = base.format_with_units(self.tex, r"\#") + result = base.format_with_units(self.tex, base._inU["dimless"]) return self._format_with_description(result) @property @@ -284,7 +284,7 @@ def tex(self): @property def units(self): r"""TeX of the count units.""" - return r"\#" + return base._inU["dimless"] @property def path(self): @@ -474,7 +474,7 @@ def tex(self): @property def units(self): r"""TeX of the units.""" - return r"\#" + return base._inU["dimless"] @property def path(self): @@ -798,7 +798,7 @@ def __init__(self, key, description=None): self.set_description(description) def __str__(self): - result = base.format_with_units(self.tex, r"\#") + result = base.format_with_units(self.tex, base._inU["dimless"]) return self._format_with_description(result) @property @@ -1027,7 +1027,7 @@ def tex(self): @property def units(self): r"""TeX of the dimensionless count units.""" - return r"\#" + return base._inU["dimless"] @property def short_tex(self): diff --git a/tests/plotting/labels/test_labels_base.py b/tests/plotting/labels/test_labels_base.py index bb39bbe71..dacf7b9f2 100644 --- a/tests/plotting/labels/test_labels_base.py +++ b/tests/plotting/labels/test_labels_base.py @@ -197,7 +197,7 @@ def test_units_translation(labels_base): ("n", "", "p"): "\\mathrm{cm}^{-3}", ("b", "x", ""): "\\mathrm{nT}", ("T", "", "p"): "10^5 \\, \\mathrm{K}", - ("beta", "", "p"): "\\mathrm{\\#}", + ("beta", "", "p"): "\\#", } for mcs, expected_units in test_cases.items(): @@ -503,10 +503,10 @@ def test_latitude_is_lambda_and_colatitude_is_theta(labels_base, mcs, tex): @pytest.mark.parametrize( "mcs, units", [ - (("cos_phi", "", "p1"), "\\mathrm{\\#}"), - (("ratio", "", ""), "\\mathrm{\\#}"), - (("Qhat", "", "p1"), "\\mathrm{\\#}"), - (("dbeta", "", "p1"), "\\mathrm{\\#}"), + (("cos_phi", "", "p1"), "\\#"), + (("ratio", "", ""), "\\#"), + (("Qhat", "", "p1"), "\\#"), + (("dbeta", "", "p1"), "\\#"), (("eth", "", "p1"), "\\mathrm{eV}"), ], ids=["cos_phi", "ratio", "Qhat", "dbeta", "eth"], @@ -697,3 +697,26 @@ def test_scalar_component_renders_as_no_component(labels_base, m): scalar = labels_base.TeXlabel((m, "scalar", "p1")) assert scalar.tex == labels_base.TeXlabel((m, "", "p1")).tex assert "scalar" not in scalar.tex + + +def test_every_dimensionless_label_shares_one_unit_form(labels_base): + r"""Dimensionless quantities, ratios and counts all state the registry's one form. + + beta and the temperature anisotropy R are ratios of like quantities, as + a ratio label is; a count is a pure number. Each states + ``UNIT_TEX["dimless"]``, ``\#``. + + ON FAILURE: the code is wrong. + """ + from solarwindpy.core import quantities + from solarwindpy.plotting.labels.special import CarringtonRotation, Count + + dimless = quantities.UNIT_TEX["dimless"] + assert dimless == r"\#" + TeXlabel = labels_base.TeXlabel + assert TeXlabel(("beta", "", "p1")).units == dimless + assert TeXlabel(("R", "", "p1")).units == dimless + assert TeXlabel(("n", "", "a"), ("n", "", "p1")).units == dimless + assert TeXlabel(("n", "", "p1"), axnorm="t").units == dimless + assert Count().units == dimless + assert str(CarringtonRotation()).endswith(r"\left[%s\right]$" % dimless) diff --git a/tests/plotting/labels/test_special.py b/tests/plotting/labels/test_special.py index adb257f3b..9cdba541f 100644 --- a/tests/plotting/labels/test_special.py +++ b/tests/plotting/labels/test_special.py @@ -183,7 +183,7 @@ def test_properties(self): """Test Power label properties.""" power = labels_special.Power() assert power.tex == r"\mathrm{Power}" - assert power.units == r"\mathrm{\#}" + assert power.units == r"\#" assert str(power.path) == "power" def test_string_representation(self): @@ -191,7 +191,7 @@ def test_string_representation(self): power = labels_special.Power() result = str(power) assert "Power" in result - assert r"\left[\mathrm{\#}\right]" in result + assert r"\left[\#\right]" in result class TestProbability: @@ -276,7 +276,7 @@ def test_basic_math_function(self, basic_texlabel): math_fcn = labels_special.MathFcn("log", basic_texlabel) assert "log" in math_fcn.tex assert math_fcn.dimensionless is True - assert math_fcn.units == r"\mathrm{\#}" + assert math_fcn.units == r"\#" def test_non_dimensionless(self, basic_texlabel): """Test non-dimensionless math function.""" @@ -732,11 +732,9 @@ def test_math_fcn_tex_units_and_both_string_forms(n_p1): """ label = labels_special.MathFcn("log", n_p1) assert label.tex == r"\mathrm{log}(n_{p_1})" - assert str(label) == r"$\mathrm{log}(n_{p_1}) \; \left[\mathrm{\#}\right]$" + assert str(label) == r"$\mathrm{log}(n_{p_1}) \; \left[\#\right]$" two_lines = labels_special.MathFcn("log", n_p1, new_line_for_units=True) - assert str(two_lines) == ( - r"$\mathrm{log}(n_{p_1}) $" "\n" r"$ \left[\mathrm{\#}\right]$" - ) + assert str(two_lines) == (r"$\mathrm{log}(n_{p_1}) $" "\n" r"$ \left[\#\right]$") dimensional = labels_special.MathFcn("log", n_p1, dimensionless=False) assert dimensional.units == r"\mathrm{log}\left(\mathrm{cm}^{-3}\right)" @@ -805,9 +803,7 @@ def test_fixed_special_labels_print_exact_strings(): ) long_cr = labels_special.CarringtonRotation(short_label=False) assert long_cr.tex == r"\mathrm{Carrington \; Rotation}" - assert ( - str(labels_special.Power()) == r"$\mathrm{Power} \; \left[\mathrm{\#}\right]$" - ) + assert str(labels_special.Power()) == r"$\mathrm{Power} \; \left[\#\right]$" assert str(labels_special.Distance2Sun("m")) == ( r"$\mathrm{Distance \; to \; Sun} \; \left[\mathrm{m}\right]$" ) From d1b86296d98dab397c8fa13a3ef9122ebea63434 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:48:33 -0500 Subject: [PATCH 28/60] docs(usage): show Scatter colored by z, connected, and without z Individual points now covers the plain Scatter and its 4-tuple return, connect=True on shuffled rows (joined in increasing z, segments colored by the mean z of each pair, dropped points skipped, the z = time trajectory reading) and Scatter without z (one color, row order). Each figure is a standalone plot block. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 + docs/source/usage.rst | 86 +++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 84 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dc20d181b..7578f1121 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 so one colorbar serves both. `connect_kwargs` styles the segments. A point that is not drawn (NaN, outside `mask` or `alim`, or <= 0 on a log axis) is skipped. Without a varying z, the points are joined in row order in the points' color. +- The Usage guide's "Individual points" shows `Scatter` colored by z, with `connect=True` on + shuffled rows, and without z, each figure drawn by the block beside it. ### Changed - BREAKING CHANGES diff --git a/docs/source/usage.rst b/docs/source/usage.rst index b75e6c63a..13fdf2a81 100644 --- a/docs/source/usage.rst +++ b/docs/source/usage.rst @@ -322,9 +322,13 @@ Gaussian filter, by design. Individual points ~~~~~~~~~~~~~~~~~ -:py:class:`~solarwindpy.plotting.scatter.Scatter` colors each point by ``z``, -here the density of a few hundred points. Its ``logx`` and ``logy`` set only -the axis scale; the data stay linear. +``Scatter(x, y, z)`` draws one marker per point, colored by ``z`` through a +colormap, beside a colorbar labelled with ``labels.z``; here ``z`` is the +density of a few hundred points. Its ``logx`` and ``logy`` set only the axis +scale; the data stay linear. ``make_plot`` returns +``(ax, points, segments, cbar)``: the axes, the markers' ``PathCollection``, +the segments joining the points (None here, see below) and the colorbar (None +when ``cbar=False`` or ``z`` does not vary). .. plot:: @@ -346,7 +350,81 @@ the axis scale; the data stay linear. y=TeXlabel(("w", "", "p1")), z=TeXlabel(("n", "", "p1")), ) - sc.make_plot(s=8) + ax, points, segments, cbar = sc.make_plot(s=8) + +``make_plot(connect=True)`` also joins the points with line segments in +increasing ``z``. The sort is stable, so points with equal ``z`` keep the order +of their rows, and the rows need not be sorted: below they are shuffled. Each +segment is colored by the mean ``z`` of its two points, through the markers' +colormap and norm, so the one colorbar reads both. With ``z`` the time of each +point, as here, the segments trace the trajectory; with any other ``z`` they +trace how ``(x, y)`` changes as ``z`` increases. A point that is not drawn (NaN +or infinite, outside ``mask`` or ``alim``, or not positive on a log axis) is +skipped, not a gap: the points either side of it in ``z`` are joined. +``connect_kwargs`` styles the segments, which sit just below the markers. + +.. plot:: + + import numpy as np + import pandas as pd + from solarwindpy.plotting.scatter import Scatter + from solarwindpy.plotting.labels.base import TeXlabel + + rng = np.random.default_rng(1) + N = 120 + epoch = pd.date_range("2020-01-01", periods=N, freq="3D") + days = pd.Series((epoch - epoch[0]).days, index=epoch, name="days") + + # A slow drift through (v, n) with a solar-rotation wobble and noise. + phase = 2 * np.pi * days / 27 + v = pd.Series( + 400 + 1.2 * days.to_numpy() ** 0.8 + 60 * np.sin(phase) + rng.normal(0, 15, N), + index=epoch, + name="v", + ) + n = pd.Series( + 8 * np.exp(-days / 400) + 2 * np.cos(phase) + rng.normal(0, 0.4, N), + index=epoch, + name="n", + ) + + # Shuffle the rows: the points are joined in increasing z, not row order. + shuffled = rng.permutation(N) + v, n, days = v.iloc[shuffled], n.iloc[shuffled], days.iloc[shuffled] + + sc = Scatter(v, n, days) + sc.set_labels( + x=TeXlabel(("v", "", "p1")), + y=TeXlabel(("n", "", "p1")), + z="Days from start", + ) + ax, points, segments, cbar = sc.make_plot( + s=12, cmap="viridis", connect=True, connect_kwargs={"linewidth": 0.8, "alpha": 0.8} + ) + +Without ``z``, ``Scatter(x, y)`` draws every point in one color and no +colorbar, so ``cbar`` is None. ``connect=True`` then joins the points in the +order of their rows, in the markers' color, skipping any point that is not +drawn. Here the rows are in time order, so the segments trace the field's +rotation: + +.. plot:: + + import numpy as np + import pandas as pd + from solarwindpy.plotting.scatter import Scatter + from solarwindpy.plotting.labels.base import TeXlabel + + rng = np.random.default_rng(2) + N = 80 + epoch = pd.date_range("2020-01-01", periods=N, freq="15min") + angle = np.linspace(0, 1.5 * np.pi, N) + bx = pd.Series(5 * np.cos(angle) + rng.normal(0, 0.3, N), index=epoch, name="bx") + by = pd.Series(5 * np.sin(angle) + rng.normal(0, 0.3, N), index=epoch, name="by") + + sc = Scatter(bx, by) + sc.set_labels(x=TeXlabel(("b", "x", "")), y=TeXlabel(("b", "y", ""))) + ax, points, segments, cbar = sc.make_plot(s=12, connect=True) Bins ~~~~ From 58040de04a5ada0154a908db9acb9941a0d12b62 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:50:02 -0500 Subject: [PATCH 29/60] fix(plotting): name each axnorm by what it does, from one label table Count and TeXlabel each held their own axnorm names and their own set of accepted keys: TeXlabel asserted on "cd" and "rd", which Count and the 2-D binning accept. One table, labels.base.AXNORM, now names every key for both, and both validate against it with ValueError. A test checks that every key a binning's allowed_axnorm holds is in the table, so a new binning key needs only its table entry. The names say what each normalization does: "t" divides by the maximum and reads "Count / Max" (was "Total Norm Count"); "c" and "r" read "Count / Column Max" and "Count / Row Max"; "cd" and "rd", a density in each column or row, read "Column" and "Row Probability Density" (both were "1D Probability Density"). A density's units are 1 / (bin width or area in the axes' units), which no label knows, so a density label states no units instead of [#]; format_with_units writes no bracket for empty units, which ManualLabel previously stripped by string replace. Save paths are unchanged. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 10 +++ docs/source/usage.rst | 9 ++- src/solarwindpy/plotting/labels/base.py | 87 ++++++++++++++++------ src/solarwindpy/plotting/labels/special.py | 33 +++----- tests/plotting/labels/test_labels_base.py | 70 ++++++++++++++--- tests/plotting/labels/test_special.py | 53 +++++++++---- 6 files changed, 189 insertions(+), 73 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 52998998b..2683bd1ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -56,6 +56,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Labels state one dimensionless unit, `\#`, the registry's `UNIT_TEX["dimless"]`: beta and the other dimensionless quantities wrote `\mathrm{\#}` while ratios and counts wrote `\#`. The temperature anisotropy `R` states it too, in place of `\perp/\parallel`. +- Normalized labels say what the normalization is. `axnorm="t"` reads "Count / Max" (was + "Total Norm Count"), `"c"` and `"r"` "Count / Column Max" and "Count / Row Max"; a + normalized quantity reads `n_p / \mathrm{Max}`. A density no longer claims `\#` units: its + units are 1 / (bin width or area in the axes' units), which a label does not know, so it + states none. `"cd"` and `"rd"` read "Column Probability Density" and "Row Probability + Density" (both were "1D Probability Density"), and `TeXlabel(..., axnorm="d")` reads + "Density of n_p" (was "Density Norm n_p [#]"). +- `TeXlabel` accepts the `"cd"` and `"rd"` normalizations that `Count` accepts. Both read + the keys from one table, `solarwindpy.plotting.labels.base.AXNORM`, and raise `ValueError` + (was `AssertionError`) for any other key. ## [0.4.0] - 2026-11-05 diff --git a/docs/source/usage.rst b/docs/source/usage.rst index 0dd3233ef..683f6ed52 100644 --- a/docs/source/usage.rst +++ b/docs/source/usage.rst @@ -433,12 +433,17 @@ $n_{\alpha}/n_{p_1} \; \left[\#\right]$ A plot labels its axes ``x``, ``y`` and ``z`` until ``set_labels`` sets them. A histogram's counts carry the special label :py:class:`~solarwindpy.plotting.labels.special.Count`, which follows the -plot's ``axnorm``: +plot's ``axnorm``. A count divided by a maximum is a pure number, :math:`[\#]`; +a density is per unit width or area of the bins, in the axes' units, so its +label states no units: >>> from solarwindpy.plotting.hist2d import Hist2D +>>> h2 = Hist2D(v, (2 * v).rename("y"), axnorm="t") +>>> print(h2.labels.z) +$\mathrm{Count \, / \, Max} \; \left[\#\right]$ >>> h2 = Hist2D(v, (2 * v).rename("y"), axnorm="cd") >>> print(h2.labels.z) -$\mathrm{1D \, Probability \, Density} \; \left[\#\right]$ +$\mathrm{Column \, Probability \, Density}$ ``solarwindpy.plotting.labels.available()`` prints every measurement, component and species ``TeXlabel`` knows, and the special labels. diff --git a/src/solarwindpy/plotting/labels/base.py b/src/solarwindpy/plotting/labels/base.py index e0b3f0379..688cd65a0 100644 --- a/src/solarwindpy/plotting/labels/base.py +++ b/src/solarwindpy/plotting/labels/base.py @@ -2,6 +2,7 @@ r"""Tools for creating physical quantity plot labels.""" __all__ = [ + "AXNORM", "Base", "TeXlabel", "format_with_units", @@ -13,6 +14,7 @@ from pathlib import Path from string import Template from collections import namedtuple +from types import MappingProxyType from ...core import quantities @@ -25,15 +27,55 @@ _trans_component = quantities.COMPONENTS _inU = quantities.UNIT_TEX -_trans_axnorm = { - None: "", - "c": "Col.", - "r": "Row", - "t": "Total", - "d": "Density", - "rd": "1D Probability Density", - "cd": "1D Probability Density", -} +_AxisNorm = namedtuple("_AxisNorm", "count,quantity,density") + +#: How a label names each ``axnorm`` key, keyed by the key: the one table of +#: the keys ``Count`` and ``TeXlabel`` accept. ``count`` is the words of a +#: normalized ``Count``; ``quantity`` the TeX of a normalized quantity, with +#: ``%s`` for the quantity's TeX. ``density`` is True for a density: its units +#: are 1 / (bin width or area in the units of the binned axes, in decades on a +#: log axis), which a label does not know, so it states none. A count divided +#: by a maximum is a pure number and states ``\#``. Every key a binning's +#: ``allowed_axnorm`` holds is a key here. +AXNORM = MappingProxyType( + { + "c": _AxisNorm("Count / Column Max", r"%s / \mathrm{Column \; Max}", False), + "r": _AxisNorm("Count / Row Max", r"%s / \mathrm{Row \; Max}", False), + "t": _AxisNorm("Count / Max", r"%s / \mathrm{Max}", False), + "d": _AxisNorm("Probability Density", r"\mathrm{Density \; of} \; %s", True), + "cd": _AxisNorm( + "Column Probability Density", + r"\mathrm{Column \; Density \; of} \; %s", + True, + ), + "rd": _AxisNorm( + "Row Probability Density", r"\mathrm{Row \; Density \; of} \; %s", True + ), + } +) + + +def validate_axnorm(key): + r"""Return the ``axnorm`` key ``key`` in lower case, or None for None. + + Raises + ------ + TypeError + If ``key`` is neither a string nor None. + ValueError + If ``key`` is not a key of :data:`AXNORM`. + """ + if key is None: + return None + if not isinstance(key, str): + raise TypeError(f"axnorm must be a string or None; got {type(key).__name__}") + lower = key.lower() + if lower not in AXNORM: + raise ValueError( + f"Unrecognized axnorm '{key}'; expected one of: {', '.join(AXNORM)}" + ) + return lower + # Longest first, so a species is never matched by a code it starts with # (``a_bimax`` before ``a``, ``p1`` before ``p``). @@ -97,14 +139,14 @@ def format_with_units(tex, units, *, new_line=False): The one home of this form: every label class builds its string here. The brackets are sized, ``\left[ \right]``, so they grow with their content, - such as a fractional unit. + such as a fractional unit. Empty ``units`` state no units: ``$tex$``. Parameters ---------- tex : str TeX of the quantity, without ``$``. units : str - TeX of the units, without ``$``. + TeX of the units, without ``$``. Empty for a label without units. new_line : bool, default False If True, the units go on a new line; otherwise ``\;`` separates them. @@ -113,6 +155,8 @@ def format_with_units(tex, units, *, new_line=False): str The label as a TeX math string. """ + if not units: + return f"${tex}$" sep = "$\n$" if new_line else r"\;" left, right = r"\left[", r"\right]" return f"${tex} {sep} {left}{units}{right}$" @@ -237,8 +281,9 @@ def __init__( mcs1 : tuple of str or None, optional Denominator for fraction style labels. Units are compared and set to dimensionless when equal. - axnorm : {"c", "r", "t", "d"}, optional - Axis normalization used when building colorbar labels. + axnorm : str, optional + Axis normalization used when building colorbar labels, a key of + :data:`AXNORM`. new_line_for_units : bool, default ``False`` If ``True`` a newline separates label and units. description : str or None, optional @@ -312,13 +357,9 @@ def set_axnorm(self, new): Parameters ---------- new : str, optional - One of ``"c"``, ``"r"``, ``"t"``, ``"d"`` (case-insensitive), or None. + A key of :data:`AXNORM` (case-insensitive), or None. """ - if isinstance(new, str): - new = new.lower() - - assert new in (None, "c", "r", "t", "d") - self._axnorm = new + self._axnorm = validate_axnorm(new) def make_species(self, pattern): r"""Replace each species code in ``pattern`` that has a TeX translation. @@ -428,10 +469,10 @@ def _combine_tex_path_units_axnorm(self, tex, path, units): # display-focused method """Finalize label pieces with axis normalization.""" axnorm = self.axnorm - tex_norm = _trans_axnorm[axnorm] - if tex_norm: - units = _inU["dimless"] - tex = r"\mathrm{%s \; Norm} \; %s" % (tex_norm, tex) # noqa: W605 + if axnorm is not None: + norm = AXNORM[axnorm] + units = "" if norm.density else _inU["dimless"] + tex = norm.quantity % tex path = path / (axnorm.upper() + "norm") with_units = format_with_units(tex, units, new_line=self.new_line_for_units) diff --git a/src/solarwindpy/plotting/labels/special.py b/src/solarwindpy/plotting/labels/special.py index b409c0c75..133f0d8e4 100644 --- a/src/solarwindpy/plotting/labels/special.py +++ b/src/solarwindpy/plotting/labels/special.py @@ -161,7 +161,7 @@ def with_units(self): r"""Label with units, as a TeX math string; no units bracket if ``units`` is empty.""" result = base.format_with_units( r"\mathrm{%s}" % self.tex.replace(" ", r" \; "), self.units - ).replace(r" \; \left[\right]", "") + ) return self._format_with_description(result) @property @@ -283,7 +283,9 @@ def tex(self): @property def units(self): - r"""TeX of the count units.""" + r"""TeX of the units: ``\#``, or empty for a density; see ``base.AXNORM``.""" + if self.axnorm is not None and base.AXNORM[self.axnorm].density: + return "" return base._inU["dimless"] @property @@ -302,32 +304,15 @@ def set_axnorm(self, norm): Parameters ---------- norm : str, optional - One of ``"c"``, ``"r"``, ``"t"``, ``"d"``, ``"cd"``, ``"rd"`` - (case-insensitive), or None for raw counts. + A key of ``base.AXNORM`` (case-insensitive), or None for raw + counts. """ - if norm is not None: - norm = norm.lower() - - assert norm in base._trans_axnorm.keys() - self._axnorm = norm + self._axnorm = base.validate_axnorm(norm) def _build_tex(self): axnorm = self.axnorm - if axnorm: - if axnorm in ("r", "c", "t"): - tex = r"\mathrm{%s Norm Count}" % base._trans_axnorm.get(axnorm) - elif axnorm == "cd": - tex = r"\mathrm{1D Probability Density}" - elif axnorm == "rd": - tex = r"\mathrm{1D Probability Density}" - elif axnorm == "d": - tex = r"\mathrm{Probability Density}" - else: - raise ValueError(f"Unrecognized axis normalization `{axnorm}`") - else: - tex = r"\mathrm{Count}" - - return tex.replace(" ", r" \, ") + words = "Count" if axnorm is None else base.AXNORM[axnorm].count + return r"\mathrm{%s}" % words.replace(" ", r" \, ") def _build_path(self): path = Path("count") diff --git a/tests/plotting/labels/test_labels_base.py b/tests/plotting/labels/test_labels_base.py index dacf7b9f2..46db6d087 100644 --- a/tests/plotting/labels/test_labels_base.py +++ b/tests/plotting/labels/test_labels_base.py @@ -105,10 +105,9 @@ def test_texlabel_comparison_operators(texlabel_basic, labels_base): def test_texlabel_axnorm_types(labels_base): """Test different axis normalization types.""" test_cases = [ - ("c", "Col."), + ("c", "Column"), ("r", "Row"), - ("t", "Total"), - ("d", "Density"), + ("t", "Max"), (None, ""), ] @@ -307,14 +306,14 @@ def test_texlabel_set_methods(labels_base): def test_axnorm_validation(labels_base): """Test axis normalization validation.""" - valid_values = [None, "c", "r", "t", "d"] + valid_values = [None, "c", "r", "t", "d", "cd", "rd"] for val in valid_values: label = labels_base.TeXlabel(("v", "x", "p"), axnorm=val) assert label.axnorm == val # Test invalid axnorm - with pytest.raises(AssertionError): + with pytest.raises(ValueError): labels_base.TeXlabel(("v", "x", "p"), axnorm="invalid") @@ -431,7 +430,7 @@ def test_description_with_axnorm(self, labels_base): label = labels_base.TeXlabel(("n", "", "p"), axnorm="t", description="count") result = label.with_units assert result.startswith("count\n") - assert "Total" in result or "Norm" in result + assert "Max" in result def test_description_with_ratio_label(self, labels_base): """Description works with ratio-style labels.""" @@ -631,15 +630,68 @@ def test_ratio_units_look_up_each_measurement_without_err( def test_axnorm_label_names_the_normalization_in_tex_path_and_units(labels_base): - r"""A column-normalized label reads "Col. Norm", saves under ``Cnorm`` and counts ``\#``. + r"""A column-normalized label reads "/ Column Max", saves under ``Cnorm``, states ``\#``. ON FAILURE: the code is wrong. """ label = labels_base.TeXlabel(("n", "", "p"), axnorm="c") - assert label.tex == r"\mathrm{Col. \; Norm} \; n_{p}" + assert label.tex == r"n_{p} / \mathrm{Column \; Max}" assert label.path == Path("n_p/Cnorm") assert label.units == "\\#" - assert label.with_units == r"$\mathrm{Col. \; Norm} \; n_{p} \; \left[\#\right]$" + assert label.with_units == r"$n_{p} / \mathrm{Column \; Max} \; \left[\#\right]$" + + +@pytest.mark.parametrize( + "axnorm, tex", + [ + ("d", r"\mathrm{Density \; of} \; n_{p}"), + ("cd", r"\mathrm{Column \; Density \; of} \; n_{p}"), + ("rd", r"\mathrm{Row \; Density \; of} \; n_{p}"), + ], +) +def test_density_axnorm_label_states_no_units(labels_base, axnorm, tex): + """A density of a quantity is per unit of the binned axes: no units are stated. + + ON FAILURE: the code is wrong. + """ + label = labels_base.TeXlabel(("n", "", "p"), axnorm=axnorm) + assert label.tex == tex + assert label.units == "" + assert label.with_units == f"${tex}$" + + +def test_every_axnorm_a_plot_accepts_has_a_label(labels_base): + """Each binning's ``allowed_axnorm`` keys are keys of the one label table. + + ``Count`` and ``TeXlabel`` both accept exactly the table's keys, so a key + a binning adds needs one entry there, and this test names it. + + ON FAILURE: the code is wrong -- a binning accepts an ``axnorm`` no label + can name; add it to ``labels.base.AXNORM``. + """ + import numpy as np + import pandas as pd + from solarwindpy.plotting.hist1d import Hist1D + from solarwindpy.plotting.hist2d import Hist2D + from solarwindpy.plotting.labels.special import Count + from solarwindpy.plotting.spiral import SpiralPlot2D + + rng = np.random.default_rng(0) + x = pd.Series(rng.random(200), name="x") + y = pd.Series(rng.random(200), name="y") + plots = [ + Hist1D(x, nbins=5), + Hist2D(x, y, nbins=5), + SpiralPlot2D(x, y, x.rename("z"), min_per_bin=20), + ] + table = set(labels_base.AXNORM) + for plot in plots: + assert set(plot.binning.allowed_axnorm) <= table, type(plot).__name__ + for key in table: + assert Count(key).axnorm == key + assert labels_base.TeXlabel(("n", "", "p"), axnorm=key).axnorm == key + with pytest.raises(ValueError): + Count("nope") def test_new_line_for_units_splits_label_and_units_into_two_math_lines(labels_base): diff --git a/tests/plotting/labels/test_special.py b/tests/plotting/labels/test_special.py index 9cdba541f..2a4885528 100644 --- a/tests/plotting/labels/test_special.py +++ b/tests/plotting/labels/test_special.py @@ -140,19 +140,19 @@ def test_basic_count(self, count_label): def test_normalized_count(self, count_label_normalized): """Test normalized count label.""" - assert "Col." in count_label_normalized.tex - assert "Norm" in count_label_normalized.tex + assert "Column" in count_label_normalized.tex + assert "Max" in count_label_normalized.tex assert count_label_normalized.axnorm == "c" def test_all_normalization_types(self): """Test all normalization types.""" norm_types = { - "c": "Col.", + "c": "Column", "r": "Row", - "t": "Total", - "d": "Density", # Fixed - actual string is "Density" not "Probability Density" - "cd": "1D", # Just check for "1D" since spaces are escaped as \, - "rd": "1D", # Just check for "1D" since spaces are escaped as \, + "t": "Max", + "d": "Density", + "cd": "Column", + "rd": "Row", } for norm, expected in norm_types.items(): @@ -166,8 +166,8 @@ def test_path_with_normalization(self): assert "Cnorm" in path_str def test_invalid_normalization(self): - """Test invalid normalization raises assertion.""" - with pytest.raises(AssertionError): + """An unknown normalization raises ``ValueError``.""" + with pytest.raises(ValueError): labels_special.Count(norm="invalid") def test_set_axnorm_case_conversion(self, count_label): @@ -706,17 +706,16 @@ def test_count_other_without_comparison_stores_empty_string(n_p1): "norm, tex, path", [ (None, r"\mathrm{Count}", "count"), - ("c", r"\mathrm{Col. \, Norm \, Count}", "count/Cnorm"), - ("r", r"\mathrm{Row \, Norm \, Count}", "count/Rnorm"), - ("t", r"\mathrm{Total \, Norm \, Count}", "count/Tnorm"), - ("d", r"\mathrm{Probability \, Density}", "count/Dnorm"), - ("cd", r"\mathrm{1D \, Probability \, Density}", "count/CDnorm"), - ("rd", r"\mathrm{1D \, Probability \, Density}", "count/RDnorm"), + ("c", r"\mathrm{Count \, / \, Column \, Max}", "count/Cnorm"), + ("r", r"\mathrm{Count \, / \, Row \, Max}", "count/Rnorm"), + ("t", r"\mathrm{Count \, / \, Max}", "count/Tnorm"), ], ) def test_count_tex_and_path_per_normalization(norm, tex, path): r"""``Count`` names its normalization in ``tex`` (spaces as ``\,``) and in ``path``. + A count divided by a maximum is a pure number, so it states ``\#``. + ON FAILURE: the code is wrong. """ label = labels_special.Count(norm) @@ -725,6 +724,30 @@ def test_count_tex_and_path_per_normalization(norm, tex, path): assert str(label) == rf"${tex} \; \left[\#\right]$" +@pytest.mark.parametrize( + "norm, tex, path", + [ + ("d", r"\mathrm{Probability \, Density}", "count/Dnorm"), + ("cd", r"\mathrm{Column \, Probability \, Density}", "count/CDnorm"), + ("rd", r"\mathrm{Row \, Probability \, Density}", "count/RDnorm"), + ], +) +def test_count_density_states_no_units(norm, tex, path): + r"""A probability density is per unit of the binned axes, which ``Count`` cannot know. + + Its units are 1 / (bin width or area in the axis units, or in decades on a + log axis), so the label states none rather than ``\#``. A column and a + row density read differently. + + ON FAILURE: the code is wrong. + """ + label = labels_special.Count(norm) + assert label.tex == tex + assert label.path == Path(path) + assert label.units == "" + assert str(label) == f"${tex}$" + + def test_math_fcn_tex_units_and_both_string_forms(n_p1): r"""``MathFcn`` reads ``\mathrm{}()``, dimensionless unless told otherwise. From 2de3df1cc02222335e1b1027a60d30487717e6f1 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:50:33 -0500 Subject: [PATCH 30/60] feat(plotting)!: axnorm follows the aggregation; add w, wc and wr Every axnorm divided the aggregated value by its own total or peak, whatever the aggregation, so the density of a mean was meaningless. agg now classifies fcn as a count, a sum ("sum" or np.sum) or a value (anything else) and binning.normalize takes the cell counts and that kind. d, cd and rd give the count PDF for a count, each cell's share of the total z per unit area for a sum (z < 0 raises), and v_i n_i / (N A_i) for a value, which integrates to the count-weighted average of v. The new w, wc and wr are the same without the area. t, c and r divide by the largest magnitude. Count plots, and t, c and r of non-negative values, are unchanged on a 78-case baseline. Hist1D's refusal of d with another fcn is gone; Count and TeXlabel take the new keys; contours have no default levels for them. BREAKING CHANGE: d, cd and rd of a non-count aggregation, and t, c and r of negative values, return different numbers. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 19 +++- src/solarwindpy/plotting/base.py | 81 ++++++++++---- src/solarwindpy/plotting/binning.py | 117 ++++++++++++++------ src/solarwindpy/plotting/hist1d.py | 13 +-- src/solarwindpy/plotting/hist2d.py | 2 +- src/solarwindpy/plotting/labels/base.py | 13 ++- src/solarwindpy/plotting/labels/special.py | 11 +- src/solarwindpy/plotting/spiral.py | 9 +- tests/plotting/test_architecture.py | 10 +- tests/plotting/test_axnorm_by_fcn.py | 24 ++-- tests/plotting/test_hist2d_pandas_compat.py | 41 ++++--- tests/plotting/test_histograms.py | 17 ++- 12 files changed, 236 insertions(+), 121 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f1345e609..863421c16 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,7 +20,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `get_plotted_data_boolean_series()` and `get_subset_above_threshold()` are removed from the binned plots (`Hist1D`, `Hist2D`, `SpiralPlot2D`); `get_plotted_data(fcn=None)` replaces both. It returns the rows of the cells the figure shows, with the caller's values on the caller's - index, as the subset did; for a boolean mask use `data.index.isin(plot.get_plotted_data().index)`. + index, as the subset did; for a boolean mask on a unique index use + `data.index.isin(plot.get_plotted_data().index)`. `get_subset_above_threshold(t)` compared each cell's aggregate after `axnorm`: with no `axnorm` and a count, it is `plot.set_clim(t, None)` then `plot.get_plotted_data()`; on a `Hist2D` or `SpiralPlot2D` with an `axnorm` or another `fcn`, use `plot.set_alim(t, None)` @@ -33,6 +34,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `Hist2D` now share one implementation, which takes rows of disjoint x-ranges with one `numpy.searchsorted` instead of a pass over the data per range (3 to 6 times faster at 1e5 and 1e6 rows) and lists the x-bins from `intervals["x"]` instead of running `agg()`. +- `axnorm` now depends on the aggregation. For cell i with n_i rows, area A_i and value v_i, and + N the rows in the shown cells (per column for `cd`/`wc`, per row for `rd`/`wr`): + + | aggregation | `d`, `cd`, `rd` | `w`, `wc`, `wr` (new) | `t`, `c`, `r` | + |---|---|---|---| + | count | n_i / (N A_i), unchanged | n_i / N, the count fraction | v_i / max\|v\| | + | `"sum"` or `np.sum` | S_i / (S A_i), S the total z; z < 0 raises `ValueError` | S_i / S | v_i / max\|v\| | + | anything else | v_i n_i / (N A_i) | v_i n_i / N | v_i / max\|v\| | + + So a density of a mean integrates, and its weight sums, to the mean z (overall, per column or + per row), where it used to divide the means by their own total. `t`, `c` and `r` divide by the + largest absolute value, which differs from before only when values are negative. A custom + callable is a per-cell value even when it adds; pass `"sum"` for a sum. `Hist1D` no longer + raises "Unable to calculate a PDF with non-count aggregation" for `d` with another `fcn`. + `allowed_axnorm` adds `w` (1-D and `SpiralPlot2D`) and `w`, `wc`, `wr` (2-D); `Count` and + `TeXlabel` accept them. Count plots and `t`/`c`/`r` of non-negative values are unchanged. ### Added diff --git a/src/solarwindpy/plotting/base.py b/src/solarwindpy/plotting/base.py index 2b2d897aa..31bdb0377 100644 --- a/src/solarwindpy/plotting/base.py +++ b/src/solarwindpy/plotting/base.py @@ -70,6 +70,24 @@ def _within(values, lower, upper, bins): return (lower < values) & (values <= upper) +#: ``axnorm`` keys that give each cell a share of a total. +_SHARE_AXNORMS = ("d", "cd", "rd", "w", "wc", "wr") + + +def _aggregation_kind(fcn): + r"""``"count"``, ``"sum"`` or ``"value"``: how ``axnorm`` treats ``fcn``. + + Only ``"count"`` is a count and only ``"sum"`` or :func:`numpy.sum` a + sum; every other aggregation, a custom additive callable included, is a + per-cell value. + """ + if isinstance(fcn, str): + return {"count": "count", "sum": "sum"}.get(fcn, "value") + if fcn is np.sum: + return "sum" + return "value" + + class Base(ABC): r"""Abstract base for SolarWindPy plots. @@ -950,6 +968,19 @@ def agg(self, fcn=None, **kwargs): normalized by ``axnorm`` (``binning.normalize``). Every cell is in the result, indexed by ``binning.cells``; a cell no row falls in is NaN. A ``ColorPlot`` then sets the cells outside ``alim`` to NaN. + + How ``axnorm`` treats the result depends on the aggregation, which + is classified as a count (``"count"``), a sum (``"sum"`` or + :func:`numpy.sum`), or a value (anything else: ``"mean"``, + ``"median"``, any callable). A custom callable is a value even when + it adds, so pass ``"sum"`` for a sum. A share of a sum (``axnorm`` + ``"d"``, ``"cd"``, ``"rd"``, ``"w"``, ``"wc"`` or ``"wr"``) needs + every aggregated value in a cell to be >= 0. + + Raises + ------ + ValueError + For a share of a sum when a row in a cell has a negative value. """ tko = self.agg_axes @@ -961,30 +992,38 @@ def agg(self, fcn=None, **kwargs): if fcn is None: fcn = "count" if self._source.counts else "mean" + kind = _aggregation_kind(fcn) - if isinstance(fcn, str) and fcn == "count" and not kwargs: - # Count fast path: rows per cell straight from the cell codes, no - # groupby. Keep only occupied cells, as a groupby count would, so - # empty cells stay NaN after the reindex below. The aggregated - # column has no NaN on kept rows, so this equals its groupby count. - codes = self._cell_codes() - n = np.bincount(codes[codes >= 0], minlength=len(self.binning.cells)) - occupied = np.flatnonzero(n) - cnt = pd.Series( - n[occupied].astype(np.int64), - index=pd.Index(occupied, dtype=np.int64), - name=self.agg_axes, - ) + # Rows per cell straight from the cell codes, kept only for occupied + # cells, as a groupby count would, so empty cells stay NaN after the + # reindex below. The aggregated column has no NaN on kept rows, so + # this equals its groupby count. It serves clim and axnorm. + codes = self._cell_codes() + n = np.bincount(codes[codes >= 0], minlength=len(self.binning.cells)) + occupied = np.flatnonzero(n) + cnt = pd.Series( + n[occupied].astype(np.int64), + index=pd.Index(occupied, dtype=np.int64), + name=self.agg_axes, + ) + if kind == "count" and isinstance(fcn, str) and not kwargs: + # Count fast path: the counts are the aggregate; no groupby. agg = cnt else: - gb = self._grouped_by_cell() - agg = gb.agg(fcn, **kwargs) - cnt = None + agg = self._grouped_by_cell().agg(fcn, **kwargs) + + if kind == "sum" and self.axnorm in _SHARE_AXNORMS: + values = self._source.take(self.agg_axes, labels=False).to_numpy() + if (values[codes >= 0] < 0).any(): + raise ValueError( + f"axnorm={self.axnorm!r} on a sum gives each cell's share of " + f"the total {self.agg_axes}, which needs {self.agg_axes} >= 0; " + "some values in the cells are negative. Use a value " + "aggregation such as 'mean', or axnorm 't', 'c' or 'r'." + ) c0, c1 = self.clim if c0 is not None or c1 is not None: - if cnt is None: - cnt = gb.agg("count") tk = pd.Series(True, index=agg.index) if c0 is not None: tk = tk & (cnt >= c0) @@ -1000,8 +1039,10 @@ def agg(self, fcn=None, **kwargs): # NaN of an empty one; then fill in every cell. cells = binning.cells positions = agg.index.to_numpy() - agg = agg.set_axis(cells[positions]) - agg = binning.normalize(agg, self.axnorm, positions) + index = cells[positions] + agg = agg.set_axis(index) + counts = cnt.set_axis(index) + agg = binning.normalize(agg, self.axnorm, positions, counts=counts, kind=kind) return self._limit_values(agg.reindex(cells)) def _kept_index(self): diff --git a/src/solarwindpy/plotting/binning.py b/src/solarwindpy/plotting/binning.py index 512b91067..5bab4c9ad 100644 --- a/src/solarwindpy/plotting/binning.py +++ b/src/solarwindpy/plotting/binning.py @@ -68,9 +68,26 @@ def postfilter(self, agg): """ return agg - def normalize(self, agg, axnorm, positions): + def normalize(self, agg, axnorm, positions, counts=None, kind="count"): r"""Normalize ``agg``, the occupied cells, by ``axnorm``. + For cell i with n_i rows, measure A_i (``cell_measure``) and value + v_i, and N the rows in the cells ``agg`` shows (not NaN): + + ===== ======================================================= + key result + ===== ======================================================= + t v_i / max(abs(v)): the largest magnitude becomes 1 + d density: m_i / (B A_i), integrating to M / B + w weight: m_i / B, summing to M / B + ===== ======================================================= + + where, by ``kind``: a count has m_i = n_i and B = N, so d is the + count PDF and w the count fraction; a sum has m_i = S_i and B the + total S, each cell's share of it; a value has m_i = v_i n_i and + B = N, so d integrates and w sums to the count-weighted average of + v (the mean z, for a mean). + Parameters ---------- agg : pd.Series @@ -79,27 +96,45 @@ def normalize(self, agg, axnorm, positions): A key of ``allowed_axnorm``, or None. positions : np.ndarray Cell code of each entry of ``agg``. + counts : pd.Series, optional + Rows in each cell of ``agg``, on its index. Required when + ``kind`` is ``"value"``. + kind : {"count", "sum", "value"} + What ``agg`` aggregates; see ``BinnedPlot.agg``. Returns ------- pd.Series - ``"t"`` divides by the maximum, so the peak equals 1. ``"d"`` - divides by the total and by each cell's ``cell_measure``, so the - values integrate to 1 over the binned scale. Raises ------ ValueError - For any other key. + For a key not handled here. """ if axnorm is None: return agg if axnorm == "t": - return agg.divide(agg.max()) + return agg.divide(agg.abs().max()) + mass, basis = self._mass(agg, counts, kind) if axnorm == "d": - return agg.divide(self.cell_measure()[positions] * agg.sum()) + return mass.divide(self.cell_measure()[positions] * basis.sum()) + if axnorm == "w": + return mass.divide(basis.sum()) raise ValueError(f"{type(self).__name__} cannot normalize by {axnorm!r}.") + @staticmethod + def _mass(agg, counts, kind): + r"""Each cell's share numerator and the series whose total divides it. + + A count or a sum is its own: ``(agg, agg)``. A value v_i is weighted + by its cell's rows n_i and divided by their total: + ``(v n, n)``, with n NaN where ``agg`` is. + """ + if kind == "value": + n = counts.where(agg.notna()) + return agg.multiply(n), n + return agg, agg + class FixedGrid(Binning): r"""Bins on edges fixed before the rows are placed, in one or two dimensions. @@ -523,10 +558,10 @@ def axes(self): @property def allowed_axnorm(self): - r"""``d`` and ``t`` in 1-D; also the row and column norms in 2-D.""" + r"""``d``, ``t`` and ``w`` in 1-D; also the row and column norms in 2-D.""" if len(self._axes) == 1: - return ("d", "t") - return ("c", "r", "t", "d", "cd", "rd") + return ("d", "t", "w") + return ("c", "r", "t", "d", "cd", "rd", "w", "wc", "wr") @property def binned(self): @@ -617,39 +652,51 @@ def cut(self): copy=False, ) - def normalize(self, agg, axnorm, positions): + def normalize(self, agg, axnorm, positions, counts=None, kind="count"): r"""Normalize ``agg`` by ``axnorm``, including the 2-D row and column norms. - ===== ============================================================= - key description - ===== ============================================================= - c Column normalize: divide by each column's maximum - r Row normalize: divide by each row's maximum - t Divide by the maximum (peak equals 1) - d Density normalize over the binned scale - cd A PDF in each column - rd A PDF in each row - ===== ============================================================= + With m_i and B as in ``Binning.normalize`` (n_i for a count, the sum + S_i for a sum, v_i n_i for any other aggregation), and B taken over + all shown cells, a column (x-bin) or a row (y-bin): + + ===== =================================================================== + key description + ===== =================================================================== + t Divide by the largest absolute value (peak magnitude equals 1) + c Divide by each column's largest absolute value + r Divide by each row's largest absolute value + d Density: m_i / (B A_i); integrates to M / B over the grid + cd Density in each column: m_i / (B_col dy_i); integrates over y + rd Density in each row: m_i / (B_row dx_i); integrates over x + w Weight: m_i / B; sums to M / B over the grid + wc Weight in each column: m_i / B_col + wr Weight in each row: m_i / B_row + ===== =================================================================== + + For a count, d, cd and rd are probability densities and w, wc and wr + count fractions. For a sum they are each cell's share of the total z + (per unit area for d, cd and rd), which needs z >= 0. For any other + aggregation they integrate (d, cd, rd) or sum (w, wc, wr) to the + count-weighted average of the per-cell value: overall, per column or + per row. For a mean that is the mean z of those rows. On a log axis the densities ("d", "cd", "rd") are normalized over ``log10`` of that axis: the bins are log-space intervals, so cell - areas on the log axes sum to 1. + areas are measured in ``log10``. """ if axnorm == "c": - return agg.divide(agg.groupby(level="x").max(), level="x") + return agg.divide(agg.abs().groupby(level="x").max(), level="x") if axnorm == "r": - return agg.divide(agg.groupby(level="y").max(), level="y") - if axnorm == "cd": - N = agg.groupby(level="x").sum() - dy = self._widths("y") - # Divide by the total in each column and each row's width. - return agg.divide(N, level="x").divide(dy, level="y") - if axnorm == "rd": - N = agg.groupby(level="y").sum() - dx = self._widths("x") - # Divide by the total in each row and each column's width. - return agg.divide(N, level="y").divide(dx, level="x") - return super().normalize(agg, axnorm, positions) + return agg.divide(agg.abs().groupby(level="y").max(), level="y") + if axnorm in ("cd", "rd", "wc", "wr"): + mass, basis = self._mass(agg, counts, kind) + # cd and wc share each column (x-bin); rd and wr each row (y-bin). + within, across = ("x", "y") if axnorm in ("cd", "wc") else ("y", "x") + out = mass.divide(basis.groupby(level=within).sum(), level=within) + if axnorm in ("cd", "rd"): + out = out.divide(self._widths(across), level=across) + return out + return super().normalize(agg, axnorm, positions, counts=counts, kind=kind) def _widths(self, axis): r"""Width of each bin of ``axis``, a Series indexed by its intervals.""" diff --git a/src/solarwindpy/plotting/hist1d.py b/src/solarwindpy/plotting/hist1d.py index f22c38feb..85a5441f4 100644 --- a/src/solarwindpy/plotting/hist1d.py +++ b/src/solarwindpy/plotting/hist1d.py @@ -48,9 +48,10 @@ def __init__( If ``True``, compute bins in logarithmic space. None means False, or, with a ``BinnedData`` as ``nbins``, its setting for ``x``'s column. - axnorm : {"t", "d", None}, optional + axnorm : {"t", "d", "w", None}, optional Normalisation applied to the histogram. ``"t"`` divides by the - maximum (peak equals 1) and ``"d"`` yields a density. + largest magnitude (peak equals 1), ``"d"`` yields a density and + ``"w"`` a weight per bin; see ``FixedGrid.normalize``. clip : bool, str, Mapping or None, optional If True, clip x to its 0.01st and 99.99th percentiles before binning; ``"l"`` or ``"u"`` clips only the lower or upper tail @@ -166,14 +167,6 @@ def construct_cdf(self, only_plotted=True): return cdf - def agg(self, **kwargs): - if self.axnorm == "d": - fcn = kwargs.get("fcn", None) - if (fcn != "count") & (fcn is not None): - raise ValueError("Unable to calculate a PDF with non-count aggregation") - - return super(Hist1D, self).agg(**kwargs) - def set_labels(self, **kwargs): r"""Set the x or y label; see ``BinnedPlot.set_labels``. diff --git a/src/solarwindpy/plotting/hist2d.py b/src/solarwindpy/plotting/hist2d.py index 6f8cb76cf..6ce5d6c9b 100644 --- a/src/solarwindpy/plotting/hist2d.py +++ b/src/solarwindpy/plotting/hist2d.py @@ -503,7 +503,7 @@ def _get_contour_levels(self, levels): elif (levels is None) and (self.axnorm in ["r", "c"]): levels = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] - elif (levels is None) and (self.axnorm in ["cd", "rd"]): + elif (levels is None) and (self.axnorm in ["cd", "rd", "w", "wc", "wr"]): levels = None else: diff --git a/src/solarwindpy/plotting/labels/base.py b/src/solarwindpy/plotting/labels/base.py index 5af1549ae..f7a3227b3 100644 --- a/src/solarwindpy/plotting/labels/base.py +++ b/src/solarwindpy/plotting/labels/base.py @@ -33,6 +33,9 @@ "d": "Density", "rd": "1D Probability Density", "cd": "1D Probability Density", + "w": "Count-Weighted", + "wc": "Col. Count-Weighted", + "wr": "Row Count-Weighted", } # Longest first, so a species is never matched by a code it starts with @@ -237,8 +240,10 @@ def __init__( mcs1 : tuple of str or None, optional Denominator for fraction style labels. Units are compared and set to dimensionless when equal. - axnorm : {"c", "r", "t", "d"}, optional - Axis normalization used when building colorbar labels. + axnorm : str, optional + Axis normalization used when building colorbar labels: a key of + ``_trans_axnorm`` (``"c"``, ``"r"``, ``"t"``, ``"d"``, ``"cd"``, + ``"rd"``, ``"w"``, ``"wc"``, ``"wr"``), or None. new_line_for_units : bool, default ``False`` If ``True`` a newline separates label and units. description : str or None, optional @@ -312,12 +317,12 @@ def set_axnorm(self, new): Parameters ---------- new : str, optional - One of ``"c"``, ``"r"``, ``"t"``, ``"d"`` (case-insensitive), or None. + A key of ``_trans_axnorm`` (case-insensitive), or None. """ if isinstance(new, str): new = new.lower() - assert new in (None, "c", "r", "t", "d") + assert new in _trans_axnorm self._axnorm = new def make_species(self, pattern): diff --git a/src/solarwindpy/plotting/labels/special.py b/src/solarwindpy/plotting/labels/special.py index 7a9876ef6..144153324 100644 --- a/src/solarwindpy/plotting/labels/special.py +++ b/src/solarwindpy/plotting/labels/special.py @@ -302,8 +302,9 @@ def set_axnorm(self, norm): Parameters ---------- norm : str, optional - One of ``"c"``, ``"r"``, ``"t"``, ``"d"``, ``"cd"``, ``"rd"`` - (case-insensitive), or None for raw counts. + One of ``"c"``, ``"r"``, ``"t"``, ``"d"``, ``"cd"``, ``"rd"``, + ``"w"``, ``"wc"``, ``"wr"`` (case-insensitive), or None for raw + counts. """ if norm is not None: norm = norm.lower() @@ -322,6 +323,12 @@ def _build_tex(self): tex = r"\mathrm{1D Probability Density}" elif axnorm == "d": tex = r"\mathrm{Probability Density}" + elif axnorm == "w": + tex = r"\mathrm{Count Fraction}" + elif axnorm == "wc": + tex = r"\mathrm{Col. Count Fraction}" + elif axnorm == "wr": + tex = r"\mathrm{Row Count Fraction}" else: raise ValueError(f"Unrecognized axis normalization `{axnorm}`") else: diff --git a/src/solarwindpy/plotting/spiral.py b/src/solarwindpy/plotting/spiral.py index 20bd598c0..3579d94a0 100644 --- a/src/solarwindpy/plotting/spiral.py +++ b/src/solarwindpy/plotting/spiral.py @@ -818,8 +818,8 @@ def mesh(self): @property def allowed_axnorm(self): - r"""``d`` and ``t``: the mesh has no rows or columns to normalize.""" - return ("d", "t") + r"""``d``, ``t`` and ``w``: the mesh has no rows or columns to normalize.""" + return ("d", "t", "w") @property def cells(self): @@ -889,9 +889,10 @@ def __init__( logx, logy : bool or None If True, use ``log10(abs())`` of that coordinate. None means False. - axnorm : {"t", "d", None}, optional + axnorm : {"t", "d", "w", None}, optional Normalization of the aggregated values: ``"t"`` divides by the - maximum, ``"d"`` gives a density over the cells' areas. + largest magnitude, ``"d"`` gives a density over the cells' areas + and ``"w"`` a weight per cell; see ``Binning.normalize``. clip : bool, str, Mapping or None If True, clip x and y to their 0.01st and 99.99th percentiles (``Base.clip_data``) when placing points in the mesh; the diff --git a/tests/plotting/test_architecture.py b/tests/plotting/test_architecture.py index d61617ad5..0a92793ff 100644 --- a/tests/plotting/test_architecture.py +++ b/tests/plotting/test_architecture.py @@ -109,9 +109,13 @@ def cell_measure(self): @pytest.mark.parametrize( "build, strategy, allowed", [ - (lambda: Hist1D(X), "FixedGrid", ("d", "t")), - (lambda: Hist2D(X, Y), "FixedGrid", ("c", "r", "t", "d", "cd", "rd")), - (_spiral, "AdaptiveMesh", ("d", "t")), + (lambda: Hist1D(X), "FixedGrid", ("d", "t", "w")), + ( + lambda: Hist2D(X, Y), + "FixedGrid", + ("c", "r", "t", "d", "cd", "rd", "w", "wc", "wr"), + ), + (_spiral, "AdaptiveMesh", ("d", "t", "w")), ], ids=["Hist1D", "Hist2D", "SpiralPlot2D"], ) diff --git a/tests/plotting/test_axnorm_by_fcn.py b/tests/plotting/test_axnorm_by_fcn.py index 047d32811..faf799a86 100644 --- a/tests/plotting/test_axnorm_by_fcn.py +++ b/tests/plotting/test_axnorm_by_fcn.py @@ -34,8 +34,6 @@ from solarwindpy.plotting.spiral import SpiralPlot2D # noqa: E402 from tests.tolerances import exact # noqa: E402 -_NEW = pytest.mark.xfail(strict=True, reason="axnorm ignores the aggregation today") - RNG = np.random.default_rng(21) N = 4000 X = pd.Series(RNG.uniform(0.0, 3.0, N)) @@ -78,7 +76,6 @@ def _inputs(log): return ix, iy, _area(XEDGES, YEDGES), np.diff(XEDGES), np.diff(YEDGES) -@_NEW @pytest.mark.parametrize( "build, allowed", [ @@ -102,7 +99,6 @@ def test_allowed_axnorm_adds_the_weight_keys(build, allowed): assert tuple(build().binning.allowed_axnorm) == allowed -@_NEW @pytest.mark.parametrize("log", [False, True], ids=["linear", "log"]) def test_density_of_a_mean_integrates_to_the_mean_z(log): """sum(d A) over the grid is the mean z of every row. @@ -114,7 +110,6 @@ def test_density_of_a_mean_integrates_to_the_mean_z(log): assert np.nansum(d * area) == exact(Z.mean()) -@_NEW @pytest.mark.parametrize("log", [False, True], ids=["linear", "log"]) def test_column_and_row_densities_of_a_mean_integrate_to_their_means(log): """cd integrates over y to each column's mean z, rd over x to each row's. @@ -130,7 +125,6 @@ def test_column_and_row_densities_of_a_mean_integrate_to_their_means(log): assert np.nansum(rd * dx[:, None], axis=0) == exact(row_means) -@_NEW def test_weights_of_a_mean_sum_to_the_means(): """w sums to the mean z; wc over each column and wr over each row to theirs. @@ -145,21 +139,23 @@ def test_weights_of_a_mean_sum_to_the_means(): assert np.nansum(wr, axis=0) == exact(Z.groupby(iy).mean().to_numpy()) -@_NEW def test_density_of_a_median_integrates_to_the_count_weighted_median(): """sum(d A) is sum(median_i n_i) / N over the cells, not the overall median. ON FAILURE: the code is wrong. """ + # Positive on the left half, three times as large and negative on the + # right: the overall median lies between the halves, far from the + # count-weighted median of the cells. + z = pd.Series(np.where(X < 1.5, ZPOS, -3.0 * ZPOS)) ix, iy, area, _, _ = _inputs(False) - cells = pd.Series(Z.to_numpy()).groupby([ix, iy]) + cells = z.groupby([ix, iy]) expected = (cells.median() * cells.size()).sum() / N - d = _h2(Z, "median", "d") + d = _h2(z, "median", "d") assert np.nansum(d * area) == exact(expected) - assert abs(expected - Z.median()) > 0.01 # not the overall median + assert abs(expected - z.median()) > 0.5 # not the overall median -@_NEW @pytest.mark.parametrize("fcn", ["sum", np.sum], ids=["str", "np.sum"]) def test_shares_of_a_sum_add_to_one(fcn): """For a sum, d A, w, cd dy per column and wr per row each add to 1. @@ -175,7 +171,6 @@ def test_shares_of_a_sum_add_to_one(fcn): assert wr == exact(np.ones_like(wr)) -@_NEW def test_a_share_of_a_sum_with_a_negative_z_raises(): """A sum's share needs z >= 0; t is a peak normalization and still works. @@ -187,7 +182,6 @@ def test_a_share_of_a_sum_with_a_negative_z_raises(): assert np.nanmax(np.abs(t)) == exact(1.0) -@_NEW def test_count_weights_are_count_fractions(): """For a count, w = n_i / N, wc = n_i / N_col and wr = n_i / N_row. @@ -200,7 +194,6 @@ def test_count_weights_are_count_fractions(): assert _h2(None, None, "wr") == exact(n / n.sum(axis=0)) -@_NEW def test_peak_norms_of_signed_values_divide_by_the_largest_magnitude(): """t of signed means: the largest |value| becomes 1 and signs are kept. @@ -213,7 +206,6 @@ def test_peak_norms_of_signed_values_divide_by_the_largest_magnitude(): assert np.nanmin(t) == exact(-1.0) -@_NEW def test_hist1d_density_of_a_mean_integrates_to_the_mean(): """A Hist1D of x averaging Z: sum(d width) is the mean of Z. @@ -225,7 +217,6 @@ def test_hist1d_density_of_a_mean_integrates_to_the_mean(): assert np.nansum(d * np.diff(XEDGES)) == exact(Z.mean()) -@_NEW @pytest.mark.parametrize("key", ["w", "wc", "wr"]) def test_labels_accept_the_weight_keys(key): """Count and TeXlabel take w, wc and wr, and name them in the path. @@ -238,7 +229,6 @@ def test_labels_accept_the_weight_keys(key): assert str(label.path).endswith(key.upper() + "norm") -@_NEW def test_count_plot_with_a_weight_key_relabels_its_count(): """A Hist2D count with axnorm="w" labels z as a count fraction. diff --git a/tests/plotting/test_hist2d_pandas_compat.py b/tests/plotting/test_hist2d_pandas_compat.py index 143853f9b..4c951b43e 100644 --- a/tests/plotting/test_hist2d_pandas_compat.py +++ b/tests/plotting/test_hist2d_pandas_compat.py @@ -118,10 +118,10 @@ def test_total_normalize(self): ) def test_density_normalize(self): - """Test density normalize (axnorm='d'). + """Test density normalize (axnorm='d') of the mean z. - This should create a true 2D probability density function where - the integral over the entire domain equals 1. + A density of a mean integrates over the domain to the count-weighted + average of the cell means, which is the mean z of the binned rows. ON FAILURE: the code is wrong. """ @@ -154,9 +154,10 @@ def test_density_normalize(self): dy = dy_values[y_interval] total_integral += value * dx * dy - # A density integrates to 1 over the cell areas. - assert total_integral == exact(1.0), ( - f"Density integral is {total_integral}, expected 1.0" + # A density of the mean integrates to the mean z over the cell areas. + mean_z = hist.get_plotted_data().loc[:, "z"].mean() + assert total_integral == exact(mean_z), ( + f"Density integral is {total_integral}, expected {mean_z}" ) # Values should be non-negative @@ -166,9 +167,9 @@ def test_density_normalize(self): ) def test_pdfs_in_each_column(self): - """Test PDFs in each column (axnorm='cd'). + """Test densities in each column (axnorm='cd') of the mean z. - This creates PDFs in each column, so integrating over y for each x should give 1. + Integrating over y in each column gives that column's mean z. ON FAILURE: the code is wrong. """ @@ -178,6 +179,8 @@ def test_pdfs_in_each_column(self): # Get normalized aggregation agg = hist.agg() agg_unstacked = agg.unstack("x") + rows = hist.get_plotted_data() + column_means = rows.loc[:, "z"].groupby(hist.cut.loc[rows.index, "x"]).mean() # Get y bin widths for integration y_intervals = hist.intervals["y"] @@ -195,10 +198,10 @@ def test_pdfs_in_each_column(self): dy = dy_values[y_interval] integral += value * dy - # Each column should integrate to 1 (if it has data) - if integral > 0: # Only check columns with data - assert integral == exact(1.0), ( - f"Column {col} PDF integral is {integral}, expected 1.0" + # Each column with data integrates to its mean z. + if integral > 0: + assert integral == exact(column_means[col]), ( + f"Column {col} integral is {integral}, expected {column_means[col]}" ) # Values should be non-negative @@ -208,9 +211,9 @@ def test_pdfs_in_each_column(self): ) def test_pdfs_in_each_row(self): - """Test PDFs in each row (axnorm='rd'). + """Test densities in each row (axnorm='rd') of the mean z. - This creates PDFs in each row, so integrating over x for each y should give 1. + Integrating over x in each row gives that row's mean z. ON FAILURE: the code is wrong. """ @@ -220,6 +223,8 @@ def test_pdfs_in_each_row(self): # Get normalized aggregation agg = hist.agg() agg_unstacked = agg.unstack("x") + rows = hist.get_plotted_data() + row_means = rows.loc[:, "z"].groupby(hist.cut.loc[rows.index, "y"]).mean() # Get x bin widths for integration x_intervals = hist.intervals["x"] @@ -237,10 +242,10 @@ def test_pdfs_in_each_row(self): dx = dx_values[x_interval] integral += value * dx - # Each row should integrate to 1 (if it has data) - if integral > 0: # Only check rows with data - assert integral == exact(1.0), ( - f"Row {row} PDF integral is {integral}, expected 1.0" + # Each row with data integrates to its mean z. + if integral > 0: + assert integral == exact(row_means[row]), ( + f"Row {row} integral is {integral}, expected {row_means[row]}" ) # Values should be non-negative diff --git a/tests/plotting/test_histograms.py b/tests/plotting/test_histograms.py index 794d2c9c9..5f22b2b94 100644 --- a/tests/plotting/test_histograms.py +++ b/tests/plotting/test_histograms.py @@ -202,15 +202,20 @@ def test_agg_count_with_density_works(self): result = hist.agg(fcn="count") assert isinstance(result, pd.Series) - def test_agg_sum_with_density_raises_value_error(self): - """Test that agg(fcn='sum', axnorm='d') raises ValueError.""" + def test_agg_sum_with_density_is_each_bins_share(self): + """agg(fcn='sum') with axnorm='d' gives each bin's share per unit width. + + Without y every row aggregates the value 1, so a sum is a count and + the shares integrate to 1 over the bin widths. + + ON FAILURE: the code is wrong. + """ hist = Hist1D(self.x_data) hist.set_axnorm("d") - with pytest.raises( - ValueError, match="Unable to calculate a PDF with non-count aggregation" - ): - hist.agg(fcn="sum") + result = hist.agg(fcn="sum") + widths = hist.intervals["x"].length + assert np.nansum(result.to_numpy() * widths) == exact(1.0) def test_agg_reproduces_the_constructed_bin_counts(self): """Counts equal the population the test placed in each bin. From 5f3b3bf55845f39548ec757f026d7be460e952d8 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:58:37 -0500 Subject: [PATCH 31/60] test(docs): pin a sunspot-number snapshot the docs load without network Strict xfail until docs/source/_ssn_snapshot.py exists: the seed sits under SIDC("m13")'s URL and is fresh, the committed file names its source while the cached copy is data only, and SIDC("m13") parses it over 1994-2026. Any download attempt raises; a stale fallback is an error. Co-Authored-By: Claude Opus 5.5 --- tests/test_docs_ssn_snapshot.py | 99 +++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 tests/test_docs_ssn_snapshot.py diff --git a/tests/test_docs_ssn_snapshot.py b/tests/test_docs_ssn_snapshot.py new file mode 100644 index 000000000..4f36f8302 --- /dev/null +++ b/tests/test_docs_ssn_snapshot.py @@ -0,0 +1,99 @@ +# Spent-When: PERMANENT(the documentation stops plotting SILSO's sunspot number) +# Supersedes: none +"""The docs serve SILSO's 13-month smoothed sunspot number from a snapshot. + +``docs/source/_ssn_snapshot.py`` points SolarWindPy's download cache at a +private directory and seeds it with ``docs/source/_data``'s snapshot under the +URL ``SIDC("m13")`` fetches, so the docs build and the plot-block test load the +series without a download. Here any download attempt raises, and a stale-cache +fallback is an error, so a seed that ``fetch`` did not take as fresh fails. +""" + +import importlib.util +from pathlib import Path + +import pandas as pd +import pytest + +from solarwindpy.solar_activity import cache +from solarwindpy.solar_activity.sunspot_number.sidc import SIDC, SIDC_ID, SIDCLoader + +DOCS = Path(__file__).resolve().parents[1] / "docs" / "source" + +if not DOCS.is_dir(): + pytest.skip( + "docs/source is absent (e.g. testing from the sdist)", + allow_module_level=True, + ) + +pytestmark = pytest.mark.filterwarnings( + "error::solarwindpy.solar_activity.cache.StaleCacheWarning" +) + +_PENDING = pytest.mark.xfail( + strict=True, reason="the docs have no sunspot-number snapshot yet" +) + + +def _helper(): + spec = importlib.util.spec_from_file_location( + "_ssn_snapshot", DOCS / "_ssn_snapshot.py" + ) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _no_download(url, cache): + raise AssertionError(f"tried to download {url}") + + +@pytest.fixture +def seeded(tmp_path, monkeypatch): + """Seed a private cache from the snapshot; any download raises.""" + monkeypatch.setattr(cache, "_download_file", _no_download) + helper = _helper() + path = helper.seed_ssn_snapshot(tmp_path / "cache", monkeypatch.setenv) + return helper, path + + +@_PENDING +def test_snapshot_is_cached_fresh_under_the_m13_url(seeded): + """The seed is the loader's URL, younger than its freshness window. + + ON FAILURE: the code is wrong. + """ + helper, path = seeded + url = SIDC_ID("m13").url + assert helper.URL == url + assert cache.cache_contents().index.tolist() == [url] + assert cache.cached_age(url) < SIDCLoader("m13", url).max_age + assert cache.fetch(url, SIDCLoader("m13", url).max_age) == path + + +@_PENDING +def test_snapshot_names_its_source_and_caches_only_the_data(seeded): + """The committed file's header names the URL; the cached copy has no header. + + ON FAILURE: the code is wrong. + """ + helper, path = seeded + header = [ + line for line in helper.SNAPSHOT.read_text().splitlines() if line[:1] == "#" + ] + assert any(helper.URL in line for line in header) + assert not [line for line in path.read_text().splitlines() if line[:1] == "#"] + + +@_PENDING +def test_snapshot_parses_through_sidc_and_covers_1994_to_2026(seeded): + """``SIDC("m13")`` loads the seeded snapshot: months 1994-01 through 2026. + + The last months of a 13-month smoothed series are not yet defined, so the + sunspot number is required only through 2025. + ON FAILURE: the code is wrong. + """ + ssn = SIDC("m13").data.loc[:, "ssn"] + assert ssn.index.min() == pd.Timestamp("1994-01-01") + assert ssn.index.max() >= pd.Timestamp("2026-01-01") + assert ssn.loc["1994":"2025"].notna().all() From fe0a97e23f4da2f98f34f30880ad2a35765b3168 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:59:45 -0500 Subject: [PATCH 32/60] test(fitfunctions): a fit plot without yerr is silent Target test, xfail(strict=True) until the change: plotting a fit with no yerr logs nothing at INFO or above, writes nothing to stdout or stderr, and raises no warning. Today every plot logs a root WARNING. Co-Authored-By: Claude Opus 5.5 --- tests/fitfunctions/test_plots.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/tests/fitfunctions/test_plots.py b/tests/fitfunctions/test_plots.py index 4baa6a0b0..b75a1aa9d 100644 --- a/tests/fitfunctions/test_plots.py +++ b/tests/fitfunctions/test_plots.py @@ -11,6 +11,7 @@ import io import logging +import warnings from pathlib import Path import matplotlib.pyplot as plt @@ -962,3 +963,24 @@ def test_an_ffplot_figure_renders_to_png(): assert buf.getvalue().startswith(b"\x89PNG\r\n\x1a\n") pixels = render(hax.figure) assert len(np.unique(pixels.reshape(-1, 4), axis=0)) > 2 + + +@pytest.mark.xfail(strict=True, reason="FFPlot warns on every fit without yerr today") +def test_a_fit_plot_without_yerr_is_silent(capsys, caplog): + """Plotting a fit without yerr writes nothing and warns of nothing. + + A fit without uncertainties is ordinary, so its plot logs at most at + DEBUG: no record at INFO or above, nothing on stdout or stderr, and no + Python warning. + + ON FAILURE: the code is wrong. + """ + x = np.arange(10.0) + fit = Line(x, 2.0 * x + 1.0) + fit.make_fit() + with caplog.at_level(logging.DEBUG), warnings.catch_warnings(): + warnings.simplefilter("error") + fit.plotter.plot_raw_used_fit_resid() + assert [r for r in caplog.records if r.levelno >= logging.INFO] == [] + out, err = capsys.readouterr() + assert out == "" and err == "" From b1fd06609345356bd9ac9150ebead441871dbfa6 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:59:54 -0500 Subject: [PATCH 33/60] fix(plotting): group a normalized ratio label in parentheses TeXlabel(("n", "", "a"), ("n", "", "p1"), axnorm="t") read n_a/n_p1 / Max, which runs the ratio and the normalization together. The ratio is now grouped, (n_a/n_p1) / Max. validate_axnorm, which Count uses, joins the module's __all__. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 ++- src/solarwindpy/plotting/labels/base.py | 3 +++ tests/plotting/labels/test_labels_base.py | 10 ++++++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2683bd1ea..7da39fce9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -62,7 +62,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 units are 1 / (bin width or area in the axes' units), which a label does not know, so it states none. `"cd"` and `"rd"` read "Column Probability Density" and "Row Probability Density" (both were "1D Probability Density"), and `TeXlabel(..., axnorm="d")` reads - "Density of n_p" (was "Density Norm n_p [#]"). + "Density of n_p" (was "Density Norm n_p [#]"). A normalized ratio groups the ratio: + `(n_a/n_p) / \mathrm{Max}`. - `TeXlabel` accepts the `"cd"` and `"rd"` normalizations that `Count` accepts. Both read the keys from one table, `solarwindpy.plotting.labels.base.AXNORM`, and raise `ValueError` (was `AssertionError`) for any other key. diff --git a/src/solarwindpy/plotting/labels/base.py b/src/solarwindpy/plotting/labels/base.py index 688cd65a0..3d8b99e85 100644 --- a/src/solarwindpy/plotting/labels/base.py +++ b/src/solarwindpy/plotting/labels/base.py @@ -6,6 +6,7 @@ "Base", "TeXlabel", "format_with_units", + "validate_axnorm", ] import logging @@ -472,6 +473,8 @@ def _combine_tex_path_units_axnorm(self, tex, path, units): if axnorm is not None: norm = AXNORM[axnorm] units = "" if norm.density else _inU["dimless"] + if self.mcs1 is not None: + tex = f"({tex})" tex = norm.quantity % tex path = path / (axnorm.upper() + "norm") diff --git a/tests/plotting/labels/test_labels_base.py b/tests/plotting/labels/test_labels_base.py index 46db6d087..8da3b24b4 100644 --- a/tests/plotting/labels/test_labels_base.py +++ b/tests/plotting/labels/test_labels_base.py @@ -772,3 +772,13 @@ def test_every_dimensionless_label_shares_one_unit_form(labels_base): assert TeXlabel(("n", "", "p1"), axnorm="t").units == dimless assert Count().units == dimless assert str(CarringtonRotation()).endswith(r"\left[%s\right]$" % dimless) + + +def test_normalized_ratio_is_parenthesized(labels_base): + """A normalized ratio groups the ratio: (n_a/n_p) / Max, not n_a/n_p / Max. + + ON FAILURE: the code is wrong. + """ + label = labels_base.TeXlabel(("n", "", "a"), ("n", "", "p1"), axnorm="t") + assert label.tex == r"(n_{\alpha}/n_{p_1}) / \mathrm{Max}" + assert "validate_axnorm" in labels_base.__all__ From da25b394e53ab1110bd7d271f981bec97552a507 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 05:02:59 -0500 Subject: [PATCH 34/60] fix(fitfunctions): plot a fit without yerr silently FFPlot logged "No weights. Need weights to plot a window" (after the rename, "No yerr ...") as a root-logger WARNING on every plot of a fit without uncertainties, and with no handler Python printed it to stderr. A fit without yerr is ordinary: the zero-width window is now noted at DEBUG on the module logger. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +++ src/solarwindpy/fitfunctions/plots.py | 7 ++++--- tests/fitfunctions/test_plots.py | 8 ++++---- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 863421c16..ae3def52c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -81,6 +81,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- Plotting a fit without `yerr` no longer logs "No weights. Need weights to plot a window..." + as a warning on every plot; the zero-width window is noted at DEBUG on the + `solarwindpy.fitfunctions.plots` logger. - The API page of `Plasma.lnlambda` showed a MathJax error ("Double subscripts") in place of its equation, and documented a `species` parameter it does not take; it documents `s0, s1`. A test now rejects double subscripts, double superscripts and unbalanced braces in docstring diff --git a/src/solarwindpy/fitfunctions/plots.py b/src/solarwindpy/fitfunctions/plots.py index ff883382d..f2a0595ac 100644 --- a/src/solarwindpy/fitfunctions/plots.py +++ b/src/solarwindpy/fitfunctions/plots.py @@ -9,7 +9,7 @@ "FFPlot", ] -import logging # noqa: F401 +import logging import numpy as np import matplotlib as mpl @@ -296,8 +296,9 @@ def _plot_observations(self, kind, ax, plot_window, edge_kwargs, kwargs): return ax, plotted if yerr is None: - logging.getLogger().warning( - "No yerr. Need yerr to plot a window for FitFunction. Setting yerr to 0." + # A fit without uncertainties is ordinary: draw a zero-width window. + logging.getLogger(__name__).debug( + "No yerr: the %s window has zero width.", kind ) yerr = 0 diff --git a/tests/fitfunctions/test_plots.py b/tests/fitfunctions/test_plots.py index b75a1aa9d..6b4e69c51 100644 --- a/tests/fitfunctions/test_plots.py +++ b/tests/fitfunctions/test_plots.py @@ -444,15 +444,16 @@ def test_window_and_edge_keywords_take_effect(kind): @pytest.mark.parametrize("kind", ["raw", "used"]) def test_without_yerr_the_window_collapses_onto_the_line(kind, caplog): - """No yerr logs a warning and draws a zero-width window. + """No yerr draws a zero-width window and says so only at DEBUG. ON FAILURE: the code is wrong. """ plot, *_ = make_ffplot(yerr=False) o = getattr(plot.observations, kind) - with caplog.at_level(logging.WARNING): + with caplog.at_level(logging.DEBUG): _, (_, window, _) = getattr(plot, f"plot_{kind}")() - assert "No yerr" in caplog.text + records = [r for r in caplog.records if "No yerr" in r.getMessage()] + assert [r.levelno for r in records] == [logging.DEBUG] vy = window.get_paths()[0].vertices[:, 1] assert vy.min() == o.y.min() assert vy.max() == o.y.max() @@ -965,7 +966,6 @@ def test_an_ffplot_figure_renders_to_png(): assert len(np.unique(pixels.reshape(-1, 4), axis=0)) > 2 -@pytest.mark.xfail(strict=True, reason="FFPlot warns on every fit without yerr today") def test_a_fit_plot_without_yerr_is_silent(capsys, caplog): """Plotting a fit without yerr writes nothing and warns of nothing. From 84ac3123d258af82411e7609d5ad286b66f615ee Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 05:03:32 -0500 Subject: [PATCH 35/60] docs: serve SILSO's smoothed sunspot number from a committed snapshot docs/source/_data holds SILSO's 13-month smoothed series for 1994-01 to 2026-10 (15.5 kB), with a header naming its URL and download date. docs/source/_ssn_snapshot.py points the download cache at a private directory and stores the snapshot, header dropped, under SIDC("m13")'s URL, written now so fetch takes it as fresh. conf.py calls it before the plots build; the plot-block test calls it too, with downloads made to raise and stale-cache fallbacks made errors. The user's cache, which may hold the full series under the same URL, is never touched. Co-Authored-By: Claude Opus 5.5 --- docs/source/_data/SN_ms_tot_1994-2026.csv | 403 ++++++++++++++++++++++ docs/source/_ssn_snapshot.py | 50 +++ docs/source/conf.py | 14 + tests/test_docs_plot_blocks.py | 31 +- tests/test_docs_ssn_snapshot.py | 7 - 5 files changed, 496 insertions(+), 9 deletions(-) create mode 100644 docs/source/_data/SN_ms_tot_1994-2026.csv create mode 100644 docs/source/_ssn_snapshot.py diff --git a/docs/source/_data/SN_ms_tot_1994-2026.csv b/docs/source/_data/SN_ms_tot_1994-2026.csv new file mode 100644 index 000000000..0885e7a78 --- /dev/null +++ b/docs/source/_data/SN_ms_tot_1994-2026.csv @@ -0,0 +1,403 @@ +# SILSO 13-month smoothed total sunspot number (version 2.0), the file +# SolarWindPy's SIDC("m13") loader downloads from +# http://www.sidc.be/silso/INFO/snmstotcsv.php +# Downloaded 2026-11-05; trimmed to 1994-01 through 2026-10. Columns: year; +# month; decimal year; smoothed SSN (-1 = not yet defined); std; number of +# observations; definitive (1) or provisional (0). +# Source: WDC-SILSO, Royal Observatory of Belgium, Brussels. +# The docs build serves this snapshot through docs/source/_ssn_snapshot.py, +# which drops these comment lines before seeding the download cache. +1994;01;1994.042; 52.6; 4.9; 582;1 +1994;02;1994.123; 50.2; 4.8; 539;1 +1994;03;1994.204; 49.4; 4.8; 728;1 +1994;04;1994.288; 49.6; 4.7; 763;1 +1994;05;1994.371; 48.7; 4.6; 789;1 +1994;06;1994.455; 46.4; 4.6; 789;1 +1994;07;1994.538; 42.7; 4.4; 865;1 +1994;08;1994.623; 40.1; 4.3; 876;1 +1994;09;1994.707; 39.7; 4.2; 735;1 +1994;10;1994.790; 39.4; 4.2; 657;1 +1994;11;1994.874; 38.7; 4.1; 591;1 +1994;12;1994.958; 37.6; 4.0; 610;1 +1995;01;1995.042; 35.6; 3.9; 630;1 +1995;02;1995.123; 33.7; 3.9; 620;1 +1995;03;1995.204; 32.0; 3.9; 706;1 +1995;04;1995.288; 29.4; 3.8; 698;1 +1995;05;1995.371; 27.3; 3.7; 781;1 +1995;06;1995.455; 25.9; 3.7; 747;1 +1995;07;1995.538; 24.4; 3.6; 842;1 +1995;08;1995.623; 22.0; 3.5; 854;1 +1995;09;1995.707; 19.0; 3.4; 708;1 +1995;10;1995.790; 17.0; 3.4; 734;1 +1995;11;1995.874; 15.9; 3.3; 594;1 +1995;12;1995.958; 15.1; 3.3; 515;1 +1996;01;1996.042; 14.5; 3.3; 535;1 +1996;02;1996.124; 14.2; 3.2; 532;1 +1996;03;1996.206; 13.7; 3.2; 621;1 +1996;04;1996.290; 12.0; 3.1; 678;1 +1996;05;1996.373; 11.2; 3.1; 676;1 +1996;06;1996.456; 11.6; 3.1; 682;1 +1996;07;1996.540; 11.3; 3.1; 766;1 +1996;08;1996.624; 11.2; 3.0; 759;1 +1996;09;1996.708; 11.3; 3.0; 656;1 +1996;10;1996.791; 12.0; 3.0; 630;1 +1996;11;1996.874; 13.4; 3.0; 536;1 +1996;12;1996.958; 14.3; 3.0; 543;1 +1997;01;1997.042; 14.5; 3.1; 497;1 +1997;02;1997.123; 15.2; 3.1; 545;1 +1997;03;1997.204; 18.3; 3.3; 627;1 +1997;04;1997.288; 22.0; 3.4; 663;1 +1997;05;1997.371; 24.4; 3.5; 716;1 +1997;06;1997.455; 27.2; 3.6; 656;1 +1997;07;1997.538; 30.4; 3.7; 700;1 +1997;08;1997.623; 33.6; 3.9; 723;1 +1997;09;1997.707; 38.2; 4.1; 661;1 +1997;10;1997.790; 43.1; 4.4; 623;1 +1997;11;1997.874; 47.1; 4.7; 465;1 +1997;12;1997.958; 52.0; 4.9; 418;1 +1998;01;1998.042; 58.4; 5.1; 521;1 +1998;02;1998.123; 65.4; 5.3; 559;1 +1998;03;1998.204; 72.0; 5.7; 571;1 +1998;04;1998.288; 76.9; 6.0; 537;1 +1998;05;1998.371; 80.8; 6.2; 620;1 +1998;06;1998.455; 85.4; 6.5; 521;1 +1998;07;1998.538; 89.8; 6.8; 597;1 +1998;08;1998.623; 93.5; 7.0; 586;1 +1998;09;1998.707; 96.4; 7.2; 502;1 +1998;10;1998.790; 98.2; 7.2; 432;1 +1998;11;1998.874; 102.3; 7.3; 472;1 +1998;12;1998.958; 110.4; 7.7; 435;1 +1999;01;1999.042; 118.4; 8.0; 475;1 +1999;02;1999.123; 122.5; 8.4; 446;1 +1999;03;1999.204; 122.3; 8.6; 518;1 +1999;04;1999.288; 125.0; 8.7; 569;1 +1999;05;1999.371; 132.6; 9.1; 630;1 +1999;06;1999.455; 136.3; 9.3; 567;1 +1999;07;1999.538; 138.1; 9.4; 594;1 +1999;08;1999.623; 142.9; 9.6; 649;1 +1999;09;1999.707; 150.5; 10.0; 624;1 +1999;10;1999.790; 159.3; 10.3; 531;1 +1999;11;1999.874; 164.1; 10.4; 406;1 +1999;12;1999.958; 164.0; 10.4; 404;1 +2000;01;2000.042; 166.1; 10.5; 450;1 +2000;02;2000.124; 170.6; 10.4; 490;1 +2000;03;2000.206; 174.3; 10.4; 456;1 +2000;04;2000.290; 175.2; 10.5; 529;1 +2000;05;2000.373; 172.9; 10.3; 551;1 +2000;06;2000.456; 172.7; 10.1; 532;1 +2000;07;2000.540; 174.2; 10.0; 507;1 +2000;08;2000.624; 172.8; 9.9; 626;1 +2000;09;2000.708; 168.8; 9.8; 558;1 +2000;10;2000.791; 165.3; 9.8; 483;1 +2000;11;2000.874; 163.1; 9.7; 380;1 +2000;12;2000.958; 162.7; 9.7; 391;1 +2001;01;2001.042; 158.3; 9.6; 437;1 +2001;02;2001.123; 152.5; 9.4; 453;1 +2001;03;2001.204; 155.1; 9.5; 485;1 +2001;04;2001.288; 160.7; 9.7; 578;1 +2001;05;2001.371; 163.7; 10.0; 578;1 +2001;06;2001.455; 167.4; 10.4; 586;1 +2001;07;2001.538; 172.0; 10.6; 645;1 +2001;08;2001.623; 175.8; 10.9; 654;1 +2001;09;2001.707; 177.1; 10.9; 518;1 +2001;10;2001.790; 177.3; 10.8; 628;1 +2001;11;2001.874; 180.3; 10.8; 509;1 +2001;12;2001.958; 179.1; 10.8; 487;1 +2002;01;2002.042; 177.6; 10.7; 500;1 +2002;02;2002.123; 179.7; 10.9; 475;1 +2002;03;2002.204; 178.2; 10.8; 580;1 +2002;04;2002.288; 174.4; 10.6; 603;1 +2002;05;2002.371; 171.3; 10.2; 595;1 +2002;06;2002.455; 166.9; 9.9; 569;1 +2002;07;2002.538; 161.5; 9.6; 628;1 +2002;08;2002.623; 155.4; 9.2; 663;1 +2002;09;2002.707; 149.5; 8.9; 554;1 +2002;10;2002.790; 143.9; 8.7; 543;1 +2002;11;2002.874; 136.0; 8.5; 470;1 +2002;12;2002.958; 131.4; 8.4; 408;1 +2003;01;2003.042; 129.6; 8.2; 482;1 +2003;02;2003.123; 125.7; 8.0; 538;1 +2003;03;2003.204; 118.7; 7.7; 633;1 +2003;04;2003.288; 111.9; 7.5; 619;1 +2003;05;2003.371; 107.0; 7.5; 606;1 +2003;06;2003.455; 101.7; 7.2; 672;1 +2003;07;2003.538; 96.0; 6.9; 677;1 +2003;08;2003.623; 92.9; 6.8; 721;1 +2003;09;2003.707; 91.8; 6.7; 685;1 +2003;10;2003.790; 89.1; 6.6; 570;1 +2003;11;2003.874; 86.9; 6.5; 443;1 +2003;12;2003.958; 84.1; 6.4; 441;1 +2004;01;2004.042; 80.1; 6.4; 491;1 +2004;02;2004.124; 76.4; 6.4; 479;1 +2004;03;2004.206; 73.2; 6.3; 594;1 +2004;04;2004.290; 71.0; 6.1; 601;1 +2004;05;2004.373; 69.5; 5.9; 614;1 +2004;06;2004.456; 67.1; 5.8; 646;1 +2004;07;2004.540; 64.8; 5.8; 709;1 +2004;08;2004.624; 63.0; 5.7; 686;1 +2004;09;2004.708; 60.2; 5.6; 604;1 +2004;10;2004.791; 57.9; 5.5; 539;1 +2004;11;2004.874; 56.6; 5.4; 477;1 +2004;12;2004.958; 55.7; 5.4; 442;1 +2005;01;2005.042; 54.5; 5.1; 536;1 +2005;02;2005.123; 53.2; 5.0; 500;1 +2005;03;2005.204; 52.3; 4.9; 607;1 +2005;04;2005.288; 49.3; 4.8; 598;1 +2005;05;2005.371; 45.0; 4.7; 641;1 +2005;06;2005.455; 44.5; 4.6; 675;1 +2005;07;2005.538; 44.6; 4.6; 678;1 +2005;08;2005.623; 41.9; 4.5; 706;1 +2005;09;2005.707; 39.4; 4.5; 691;1 +2005;10;2005.790; 38.9; 4.6; 534;1 +2005;11;2005.874; 38.4; 4.6; 499;1 +2005;12;2005.958; 36.0; 4.4; 419;1 +2006;01;2006.042; 33.0; 4.2; 511;1 +2006;02;2006.123; 29.7; 3.9; 434;1 +2006;03;2006.204; 27.4; 3.7; 502;1 +2006;04;2006.288; 27.0; 3.6; 550;1 +2006;05;2006.371; 27.4; 3.6; 566;1 +2006;06;2006.455; 26.2; 3.5; 566;1 +2006;07;2006.538; 25.0; 3.5; 628;1 +2006;08;2006.623; 25.9; 3.4; 650;1 +2006;09;2006.707; 26.0; 3.3; 567;1 +2006;10;2006.790; 23.7; 3.1; 537;1 +2006;11;2006.874; 21.1; 2.9; 444;1 +2006;12;2006.958; 20.2; 2.9; 415;1 +2007;01;2007.042; 19.8; 2.9; 474;1 +2007;02;2007.123; 19.0; 2.9; 423;1 +2007;03;2007.204; 17.7; 2.8; 611;1 +2007;04;2007.288; 16.4; 2.8; 650;1 +2007;05;2007.371; 14.4; 2.8; 615;1 +2007;06;2007.455; 12.8; 2.7; 607;1 +2007;07;2007.538; 11.6; 2.7; 703;1 +2007;08;2007.623; 9.9; 2.7; 669;1 +2007;09;2007.707; 9.6; 2.6; 637;1 +2007;10;2007.790; 9.9; 2.6; 547;1 +2007;11;2007.874; 9.2; 2.6; 437;1 +2007;12;2007.958; 7.9; 2.6; 468;1 +2008;01;2008.042; 6.6; 2.5; 480;1 +2008;02;2008.124; 5.6; 2.5; 490;1 +2008;03;2008.206; 5.1; 2.5; 548;1 +2008;04;2008.290; 5.1; 2.6; 562;1 +2008;05;2008.373; 5.4; 2.6; 637;1 +2008;06;2008.456; 4.8; 2.5; 637;1 +2008;07;2008.540; 4.0; 2.4; 664;1 +2008;08;2008.624; 3.8; 2.4; 525;1 +2008;09;2008.708; 3.2; 2.4; 605;1 +2008;10;2008.791; 2.4; 2.3; 571;1 +2008;11;2008.874; 2.3; 2.3; 445;1 +2008;12;2008.958; 2.2; 2.3; 480;1 +2009;01;2009.042; 2.5; 2.3; 317;1 +2009;02;2009.123; 2.7; 2.3; 385;1 +2009;03;2009.204; 2.9; 2.3; 523;1 +2009;04;2009.288; 3.3; 2.3; 586;1 +2009;05;2009.371; 3.5; 2.3; 610;1 +2009;06;2009.455; 4.1; 2.4; 623;1 +2009;07;2009.538; 5.5; 2.5; 671;1 +2009;08;2009.623; 7.4; 2.6; 691;1 +2009;09;2009.707; 9.5; 2.7; 628;1 +2009;10;2009.790; 10.9; 2.8; 564;1 +2009;11;2009.874; 11.7; 2.9; 452;1 +2009;12;2009.958; 12.7; 2.9; 415;1 +2010;01;2010.042; 14.0; 3.0; 413;1 +2010;02;2010.123; 16.1; 3.1; 376;1 +2010;03;2010.204; 18.5; 3.2; 564;1 +2010;04;2010.288; 20.8; 3.3; 592;1 +2010;05;2010.371; 23.1; 3.4; 573;1 +2010;06;2010.455; 24.6; 3.4; 600;1 +2010;07;2010.538; 25.2; 3.4; 718;1 +2010;08;2010.623; 26.4; 3.6; 689;1 +2010;09;2010.707; 29.5; 3.9; 505;1 +2010;10;2010.790; 34.5; 4.2; 501;1 +2010;11;2010.874; 39.1; 4.4; 404;1 +2010;12;2010.958; 42.5; 4.5; 393;1 +2011;01;2011.042; 45.7; 4.6; 417;1 +2011;02;2011.123; 48.8; 4.8; 399;1 +2011;03;2011.204; 53.8; 5.1; 566;1 +2011;04;2011.288; 61.1; 5.6; 557;1 +2011;05;2011.371; 69.3; 6.1; 607;1 +2011;06;2011.455; 77.2; 6.6; 544;1 +2011;07;2011.538; 83.6; 6.9; 549;1 +2011;08;2011.623; 86.3; 7.0; 605;1 +2011;09;2011.707; 86.6; 7.0; 535;1 +2011;10;2011.790; 87.4; 7.1; 503;1 +2011;11;2011.874; 89.4; 7.2; 434;1 +2011;12;2011.958; 92.5; 7.3; 361;1 +2012;01;2012.042; 95.5; 7.4; 386;1 +2012;02;2012.124; 98.1; 7.5; 388;1 +2012;03;2012.206; 98.3; 7.5; 500;1 +2012;04;2012.290; 95.1; 7.3; 479;1 +2012;05;2012.373; 90.9; 7.0; 543;1 +2012;06;2012.456; 86.6; 6.7; 498;1 +2012;07;2012.540; 84.5; 6.5; 601;1 +2012;08;2012.624; 85.1; 6.5; 612;1 +2012;09;2012.708; 85.3; 6.5; 511;1 +2012;10;2012.791; 85.8; 6.4; 493;1 +2012;11;2012.874; 87.7; 6.5; 382;1 +2012;12;2012.958; 88.1; 6.5; 360;1 +2013;01;2013.042; 86.8; 6.4; 362;1 +2013;02;2013.123; 86.1; 6.4; 363;1 +2013;03;2013.204; 84.4; 6.2; 429;1 +2013;04;2013.288; 84.3; 6.2; 509;1 +2013;05;2013.371; 87.0; 6.5; 487;1 +2013;06;2013.455; 90.9; 6.7; 469;1 +2013;07;2013.538; 94.6; 7.0; 575;1 +2013;08;2013.623; 99.0; 7.3; 563;1 +2013;09;2013.707; 104.6; 7.7; 446;1 +2013;10;2013.790; 107.0; 7.8; 421;1 +2013;11;2013.874; 106.9; 7.8; 321;1 +2013;12;2013.958; 107.6; 7.8; 402;1 +2014;01;2014.042; 109.3; 7.9; 398;1 +2014;02;2014.123; 110.5; 8.0; 384;1 +2014;03;2014.204; 114.3; 8.2; 493;1 +2014;04;2014.288; 116.4; 8.2; 486;1 +2014;05;2014.371; 115.0; 8.2; 493;1 +2014;06;2014.455; 114.1; 8.1; 469;1 +2014;07;2014.538; 112.6; 8.0; 477;1 +2014;08;2014.623; 108.3; 7.8; 486;1 +2014;09;2014.707; 101.9; 7.4; 419;1 +2014;10;2014.790; 97.3; 7.3; 440;1 +2014;11;2014.874; 94.7; 7.4; 397;1 +2014;12;2014.958; 92.2; 7.4; 331;1 +2015;01;2015.042; 89.3; 7.3; 546;1 +2015;02;2015.123; 86.1; 7.2; 442;1 +2015;03;2015.204; 82.1; 7.0; 628;1 +2015;04;2015.288; 78.9; 6.8; 847;1 +2015;05;2015.371; 76.1; 6.6; 895;1 +2015;06;2015.455; 72.1; 6.4; 826;1 +2015;07;2015.538; 68.3; 6.2; 977;1 +2015;08;2015.623; 66.4; 6.0; 892;1 +2015;09;2015.707; 65.9; 6.0; 862;1 +2015;10;2015.790; 64.3; 5.9; 662;1 +2015;11;2015.874; 61.2; 5.5; 622;1 +2015;12;2015.958; 57.8; 5.1; 704;1 +2016;01;2016.042; 54.4; 4.9; 634;1 +2016;02;2016.124; 52.5; 4.8; 662;1 +2016;03;2016.206; 50.4; 4.6; 873;1 +2016;04;2016.288; 47.8; 4.4; 865;1 +2016;05;2016.373; 44.8; 4.2; 878;1 +2016;06;2016.455; 41.5; 4.0; 942;1 +2016;07;2016.540; 38.5; 3.8; 1025;1 +2016;08;2016.624; 36.0; 3.6; 1067;1 +2016;09;2016.706; 33.2; 3.5; 900;1 +2016;10;2016.791; 31.5; 3.4; 782;1 +2016;11;2016.873; 29.9; 3.3; 689;1 +2016;12;2016.958; 28.5; 3.1; 623;1 +2017;01;2017.042; 27.8; 3.1; 830;1 +2017;02;2017.122; 26.5; 2.9; 542;1 +2017;03;2017.204; 25.7; 2.9; 1011;1 +2017;04;2017.286; 24.8; 2.8; 920;1 +2017;05;2017.371; 23.3; 2.7; 1101;1 +2017;06;2017.453; 22.2; 2.6; 1136;1 +2017;07;2017.538; 21.0; 2.6; 1093;1 +2017;08;2017.623; 19.6; 2.4; 1002;1 +2017;09;2017.705; 18.3; 2.2; 973;1 +2017;10;2017.790; 16.7; 2.1; 1125;1 +2017;11;2017.873; 15.4; 1.9; 997;1 +2017;12;2017.958; 15.1; 1.9; 714;1 +2018;01;2018.042; 14.2; 1.9; 701;1 +2018;02;2018.122; 12.6; 1.7; 917;1 +2018;03;2018.204; 9.9; 1.4; 1081;1 +2018;04;2018.286; 7.8; 1.1; 996;1 +2018;05;2018.371; 7.5; 1.1; 1234;1 +2018;06;2018.453; 7.2; 1.1; 1070;1 +2018;07;2018.538; 7.0; 1.1; 1438;1 +2018;08;2018.623; 6.7; 1.0; 1297;1 +2018;09;2018.705; 6.5; 1.0; 1223;1 +2018;10;2018.790; 6.8; 1.0; 1097;1 +2018;11;2018.873; 6.7; 0.9; 771;1 +2018;12;2018.958; 6.0; 0.8; 786;1 +2019;01;2019.042; 5.4; 0.7; 841;1 +2019;02;2019.122; 5.0; 0.7; 1042;1 +2019;03;2019.204; 4.6; 0.7; 995;1 +2019;04;2019.286; 4.3; 0.6; 1039;1 +2019;05;2019.371; 3.9; 0.6; 1159;1 +2019;06;2019.453; 3.7; 0.5; 1273;1 +2019;07;2019.538; 3.5; 0.5; 1214;1 +2019;08;2019.623; 3.4; 0.5; 1344;1 +2019;09;2019.705; 3.1; 0.5; 1225;1 +2019;10;2019.790; 2.6; 0.4; 1065;1 +2019;11;2019.873; 2.0; 0.4; 832;1 +2019;12;2019.958; 1.8; 0.4; 855;1 +2020;01;2020.042; 2.2; 0.8; 795;1 +2020;02;2020.124; 2.7; 1.4; 967;1 +2020;03;2020.206; 3.0; 1.7; 1055;1 +2020;04;2020.288; 3.6; 2.3; 1234;1 +2020;05;2020.373; 5.6; 3.2; 1363;1 +2020;06;2020.455; 7.9; 3.8; 1196;1 +2020;07;2020.540; 9.0; 4.2; 1548;1 +2020;08;2020.624; 9.5; 4.4; 1587;1 +2020;09;2020.706; 10.5; 4.7; 1244;1 +2020;10;2020.791; 11.9; 5.1; 1215;1 +2020;11;2020.873; 13.6; 5.4; 1238;1 +2020;12;2020.958; 15.3; 5.6; 998;1 +2021;01;2021.042; 17.3; 6.0; 1036;1 +2021;02;2021.122; 19.0; 6.4; 1122;1 +2021;03;2021.204; 21.7; 6.8; 1322;1 +2021;04;2021.286; 24.8; 7.1; 1441;1 +2021;05;2021.371; 25.8; 7.1; 1411;1 +2021;06;2021.453; 27.6; 7.7; 1411;1 +2021;07;2021.538; 31.4; 8.4; 1424;1 +2021;08;2021.623; 35.4; 8.9; 1447;1 +2021;09;2021.705; 40.2; 9.5; 1361;1 +2021;10;2021.790; 45.2; 10.2; 1347;1 +2021;11;2021.873; 50.8; 11.0; 1066;1 +2021;12;2021.958; 55.9; 11.7; 845;1 +2022;01;2022.042; 60.1; 12.1; 1176;1 +2022;02;2022.122; 64.7; 12.3; 1146;1 +2022;03;2022.204; 68.7; 12.7; 1413;1 +2022;04;2022.286; 73.0; 13.3; 1376;1 +2022;05;2022.371; 77.4; 13.9; 1401;1 +2022;06;2022.453; 81.1; 14.3; 1403;1 +2022;07;2022.538; 86.7; 15.3; 1487;1 +2022;08;2022.623; 92.6; 16.7; 1470;1 +2022;09;2022.705; 96.5; 17.2; 1264;1 +2022;10;2022.790; 98.9; 17.5; 1215;1 +2022;11;2022.873; 101.2; 17.7; 1047;1 +2022;12;2022.958; 106.7; 18.1; 860;1 +2023;01;2023.042; 113.3; 18.6; 968;1 +2023;02;2023.122; 117.8; 18.9; 1014;1 +2023;03;2023.204; 121.1; 19.1; 1081;1 +2023;04;2023.286; 122.9; 19.2; 1132;1 +2023;05;2023.371; 124.2; 19.2; 1240;1 +2023;06;2023.453; 125.3; 19.3; 1248;1 +2023;07;2023.538; 124.6; 18.8; 1278;1 +2023;08;2023.623; 124.3; 18.3; 1247;1 +2023;09;2023.705; 124.0; 18.3; 1261;1 +2023;10;2023.790; 124.8; 18.4; 1104;1 +2023;11;2023.873; 127.9; 18.8; 928;1 +2023;12;2023.958; 129.5; 19.0; 785;1 +2024;01;2024.042; 131.2; 19.4; 890;1 +2024;02;2024.124; 136.9; 20.1; 806;1 +2024;03;2024.206; 141.4; 20.5; 1071;1 +2024;04;2024.288; 144.4; 20.8; 1094;1 +2024;05;2024.373; 149.1; 21.3; 1215;1 +2024;06;2024.455; 152.8; 21.7; 1186;1 +2024;07;2024.540; 155.0; 22.1; 1218;1 +2024;08;2024.624; 156.8; 22.3; 1279;1 +2024;09;2024.706; 159.4; 22.5; 1047;1 +2024;10;2024.791; 160.9; 22.5; 1013;1 +2024;11;2024.873; 157.2; 22.0; 793;1 +2024;12;2024.958; 151.2; 21.3; 653;1 +2025;01;2025.042; 146.2; 20.8; 772;1 +2025;02;2025.122; 139.8; 20.2; 791;1 +2025;03;2025.204; 135.9; 19.8; 1136;1 +2025;04;2025.286; 133.3; 19.3; 1199;1 +2025;05;2025.371; 128.6; 18.8; 1225;1 +2025;06;2025.453; 124.7; 18.3; 1231;1 +2025;07;2025.538; 122.5; 18.1; 1278;1 +2025;08;2025.623; 118.4; 17.6; 1248;1 +2025;09;2025.705; 113.1; 16.8; 1046;1 +2025;10;2025.790; 108.5; 16.3; 929;1 +2025;11;2025.873; 106.9; 16.2; 882;1 +2025;12;2025.958; 107.0; 16.3; 736;1 +2026;01;2026.042; 104.1; 16.1; 802;0 +2026;02;2026.122; 99.7; 15.7; 870;0 +2026;03;2026.204; 94.4; 15.4; 1308;0 +2026;04;2026.286; 88.6; 15.0; 1345;0 +2026;05;2026.371; -1.0; -1.0; 1319;0 +2026;06;2026.453; -1.0; -1.0; 1316;0 +2026;07;2026.538; -1.0; -1.0; 1371;0 +2026;08;2026.623; -1.0; -1.0; 1248;0 +2026;09;2026.705; -1.0; -1.0; 1117;0 +2026;10;2026.790; -1.0; -1.0; 1126;0 diff --git a/docs/source/_ssn_snapshot.py b/docs/source/_ssn_snapshot.py new file mode 100644 index 000000000..879f340c6 --- /dev/null +++ b/docs/source/_ssn_snapshot.py @@ -0,0 +1,50 @@ +"""Serve SILSO's 13-month smoothed sunspot number to the docs from a snapshot. + +A plot block in the Usage guide calls ``SIDC("m13")``, which downloads the +series from SILSO, as a reader's session does. The docs build (``conf.py``) +and ``tests/test_docs_plot_blocks.py`` instead call :func:`seed_ssn_snapshot`, +which points SolarWindPy's download cache at a private directory and stores the +committed snapshot there under the URL the loader fetches. ``fetch`` finds a +copy younger than the loader's freshness window and returns it without a +download. The user's own cache, which may hold the full series under the same +URL, is never touched. +""" + +from pathlib import Path + +from astropy.utils.data import import_file_to_cache + +from solarwindpy.solar_activity.cache import PKGNAME +from solarwindpy.solar_activity.sunspot_number.sidc import SIDC_ID + +#: The committed snapshot; its ``#`` lines name the source and download date. +SNAPSHOT = Path(__file__).resolve().parent / "_data" / "SN_ms_tot_1994-2026.csv" + +#: The URL ``SIDC("m13")`` downloads, the cache key the snapshot is stored under. +URL = SIDC_ID("m13").url + + +def seed_ssn_snapshot(root, setenv): + """Make ``root`` SolarWindPy's download cache, holding the snapshot as ``URL``. + + Parameters + ---------- + root : str or pathlib.Path + Directory that plays the role of ``~/.cache``; it is created if absent. + setenv : callable + Called as ``setenv("XDG_CACHE_HOME", str(root))``, e.g. + ``os.environ.__setitem__`` or pytest's ``monkeypatch.setenv``. + + Returns + ------- + pathlib.Path + The cached copy: the snapshot without its ``#`` lines, which the + loader would not parse, written now, so it is fresh. + """ + root = Path(root) + (root / PKGNAME).mkdir(parents=True, exist_ok=True) + setenv("XDG_CACHE_HOME", str(root)) + lines = SNAPSHOT.read_text().splitlines(keepends=True) + data = root / "snmstotcsv.csv" + data.write_text("".join(line for line in lines if not line.startswith("#"))) + return Path(import_file_to_cache(URL, str(data), pkgname=PKGNAME)) diff --git a/docs/source/conf.py b/docs/source/conf.py index 222fd2bc2..6b4149043 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -12,6 +12,20 @@ sys.path.insert(0, os.path.abspath("../../src")) import solarwindpy +# A plot block in the Usage guide loads SIDC("m13"), which downloads from +# SILSO. Serve it from the committed snapshot through a private download cache, +# so the build needs no network and leaves the user's own cache alone. +import atexit +import shutil +import tempfile + +sys.path.insert(0, os.path.abspath(".")) +from _ssn_snapshot import seed_ssn_snapshot + +_ssn_cache = tempfile.mkdtemp(prefix="solarwindpy-docs-cache-") +atexit.register(shutil.rmtree, _ssn_cache, ignore_errors=True) +seed_ssn_snapshot(_ssn_cache, os.environ.__setitem__) + # -- Project information ----------------------------------------------------- diff --git a/tests/test_docs_plot_blocks.py b/tests/test_docs_plot_blocks.py index 34ddeee0b..e5a50a974 100644 --- a/tests/test_docs_plot_blocks.py +++ b/tests/test_docs_plot_blocks.py @@ -7,9 +7,12 @@ ``plot_pre_code = ""``, so the docs build already runs each block without hidden setup; this module runs each block in a namespace of its own under the ``Agg`` backend, so the default suite catches a block that stops running -without a docs build. +without a docs build. A block that loads ``SIDC("m13")`` gets the committed +snapshot from a private download cache, as in the docs build, never the +network. """ +import importlib.util import re from pathlib import Path @@ -19,6 +22,8 @@ matplotlib.use("Agg") from matplotlib import pyplot as plt # noqa: E402 +from solarwindpy.solar_activity import cache # noqa: E402 + DOCS = Path(__file__).resolve().parents[1] / "docs" / "source" if not DOCS.is_dir(): @@ -74,8 +79,30 @@ def test_every_plot_block_holds_its_code_inline(): assert not named, named +def _no_download(url, cache): + raise AssertionError(f"a plot block tried to download {url}") + + +@pytest.fixture +def ssn_snapshot(tmp_path, monkeypatch): + """Serve ``SIDC("m13")`` from the docs' snapshot, as ``conf.py`` does. + + Both seed a private download cache with ``_ssn_snapshot.seed_ssn_snapshot``. + Any download raises, and a stale-cache fallback is an error, so a block + never reaches the network. + """ + spec = importlib.util.spec_from_file_location( + "_ssn_snapshot", DOCS / "_ssn_snapshot.py" + ) + helper = importlib.util.module_from_spec(spec) + spec.loader.exec_module(helper) + monkeypatch.setattr(cache, "_download_file", _no_download) + helper.seed_ssn_snapshot(tmp_path / "cache", monkeypatch.setenv) + + +@pytest.mark.filterwarnings("error::solarwindpy.solar_activity.cache.StaleCacheWarning") @pytest.mark.parametrize("code", BLOCKS) -def test_plot_block_runs_alone(code, request): +def test_plot_block_runs_alone(code, request, ssn_snapshot): """A block runs with nothing defined beforehand and draws a figure.""" assert code, f"{request.node.callspec.id}: the plot block is empty" try: diff --git a/tests/test_docs_ssn_snapshot.py b/tests/test_docs_ssn_snapshot.py index 4f36f8302..87076e787 100644 --- a/tests/test_docs_ssn_snapshot.py +++ b/tests/test_docs_ssn_snapshot.py @@ -30,10 +30,6 @@ "error::solarwindpy.solar_activity.cache.StaleCacheWarning" ) -_PENDING = pytest.mark.xfail( - strict=True, reason="the docs have no sunspot-number snapshot yet" -) - def _helper(): spec = importlib.util.spec_from_file_location( @@ -57,7 +53,6 @@ def seeded(tmp_path, monkeypatch): return helper, path -@_PENDING def test_snapshot_is_cached_fresh_under_the_m13_url(seeded): """The seed is the loader's URL, younger than its freshness window. @@ -71,7 +66,6 @@ def test_snapshot_is_cached_fresh_under_the_m13_url(seeded): assert cache.fetch(url, SIDCLoader("m13", url).max_age) == path -@_PENDING def test_snapshot_names_its_source_and_caches_only_the_data(seeded): """The committed file's header names the URL; the cached copy has no header. @@ -85,7 +79,6 @@ def test_snapshot_names_its_source_and_caches_only_the_data(seeded): assert not [line for line in path.read_text().splitlines() if line[:1] == "#"] -@_PENDING def test_snapshot_parses_through_sidc_and_covers_1994_to_2026(seeded): """``SIDC("m13")`` loads the seeded snapshot: months 1994-01 through 2026. From 3695891f267f7f72a38fef55c9549a201bd88541 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 05:06:12 -0500 Subject: [PATCH 36/60] feat(core): give every registry quantity a display name Quantity takes a required keyword-only field, name: the quantity in a few title-case words, such as "Number Density", for the first line of a publication-format label. It names the quantity only; the symbol line carries species and component. Being required, a new entry without a name fails at import. Names follow the docstrings of the methods that compute each quantity. The module docstring now distinguishes the canonical key from the display name and says entries carry a short name but no description. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 + src/solarwindpy/core/quantities.py | 270 ++++++++++++++++++--------- tests/core/test_quantity_registry.py | 46 +++++ 3 files changed, 232 insertions(+), 87 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7da39fce9..14540d50d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,9 @@ 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. +- Every quantity in the registry has a display name: `solarwindpy.core.quantities.Quantity` + takes a required keyword `name`, a few words in title case such as "Number Density" or + "Temperature". It names the quantity only, without species or component. ### Changed diff --git a/src/solarwindpy/core/quantities.py b/src/solarwindpy/core/quantities.py index 2a717487f..6b8222701 100644 --- a/src/solarwindpy/core/quantities.py +++ b/src/solarwindpy/core/quantities.py @@ -1,13 +1,15 @@ #!/usr/bin/env python -r"""The quantity registry: one entry per quantity, keyed by its canonical name. +r"""The quantity registry: one entry per quantity, keyed by its canonical key. -A name is canonical when it is the same string at every layer: the attribute or +A key is canonical when it is the same string at every layer: the attribute or method that computes the quantity, the returned Series ``.name``, the M- or C-level column label, and the key here. Each :class:`Quantity` holds the SI -value of the quantity's display unit, the TeX template of its symbol and the TeX -of its display unit. Stored data stay in display units: ``core`` multiplies by -``si`` to convert, and ``plotting`` reads ``tex`` and ``units`` to label. The -method docstring is the one explanation of each quantity, so entries carry no +value of the quantity's display unit, the TeX template of its symbol, the TeX +of its display unit and its display name, a few words such as "Number Density" +that a publication-format label prints above the symbol. Stored data stay in +display units: ``core`` multiplies by ``si`` to convert, and ``plotting`` reads +``tex``, ``units`` and ``name`` to label. The method docstring is the one +explanation of each quantity, so entries carry a short display name but no description. This module sits at the bottom layer and imports nothing from the rest of @@ -29,7 +31,7 @@ "UNIT_TEX", ] -from dataclasses import dataclass +from dataclasses import KW_ONLY, dataclass from types import MappingProxyType from scipy import constants @@ -49,11 +51,17 @@ class Quantity: si : float or None, optional SI value of one display unit, for quantities ``core`` converts. None for a quantity only labels use. + name : str + Keyword only. The quantity's display name, a few words in title case, + such as "Number Density": the first line of a publication-format + label. The quantity only, without species or component. """ tex: str | None units: str | None si: float | None = None + _: KW_ONLY + name: str #: TeX of the display units several quantities share. @@ -82,114 +90,202 @@ class Quantity: _KMS_SQ = r"(%s)^2" % _U["kms"] _FLUX_DENSITY = r"\mathrm{\mu W \, m^{-2}}" -#: Every quantity, keyed by canonical name (M level). +#: Every quantity, keyed by canonical key (M level). QUANTITIES = MappingProxyType( { # Coordinates and angles. # A frame's position is in its body's radius; `Spacecraft.distance2sun` # converts with it. - "gse": Quantity(r"{$A}_{\mathrm{GSE}}", _U["Re"], si=_EARTH_EQUATORIAL_RADIUS), - "hci": Quantity(r"{$A}_{\mathrm{HCI}}", _U["Rs"], si=_SOLAR_RADIUS), - "colat": Quantity(r"\theta_{$C}", _U["deg"]), - "lat": Quantity(r"{lat}_{{$C};{$S}}", _U["deg"]), - "lon": Quantity(r"{lon}_{{$C};{$S}}", _U["deg"]), - "carr": Quantity(r"{$C}_\mathrm{Carrington}", _U["deg"]), + "gse": Quantity( + r"{$A}_{\mathrm{GSE}}", + _U["Re"], + si=_EARTH_EQUATORIAL_RADIUS, + name="GSE Position", + ), + "hci": Quantity( + r"{$A}_{\mathrm{HCI}}", _U["Rs"], si=_SOLAR_RADIUS, name="HCI Position" + ), + "colat": Quantity(r"\theta_{$C}", _U["deg"], name="Colatitude"), + "lat": Quantity(r"{lat}_{{$C};{$S}}", _U["deg"], name="Latitude"), + "lon": Quantity(r"{lon}_{{$C};{$S}}", _U["deg"], name="Longitude"), + "carr": Quantity( + r"{$C}_\mathrm{Carrington}", _U["deg"], name="Carrington Coordinate" + ), # The unit depends on the frame, so the entry states none: the frame # entries (gse, hci) carry it, and `Spacecraft.pos_units` exposes it. - "pos": Quantity(r"\mathbf{r}_{$C}", None), + "pos": Quantity(r"\mathbf{r}_{$C}", None, name="Position"), "distance2sun": Quantity( - r"\mathrm{Distance \; to \; Sun}", r"\mathrm{m}", si=1.0 + r"\mathrm{Distance \; to \; Sun}", + r"\mathrm{m}", + si=1.0, + name="Distance to Sun", ), # Trigonometry. - "theta": Quantity(r"{\theta}_{{$C};{$S}}", _U["deg"]), - "phi": Quantity(r"{phi}_{{$C};{$S}}", _U["deg"]), - "deg": Quantity(r"{deg}_{{$C};{$S}}", _U["deg"]), - "cos": Quantity(r"\cos", _U["dimless"]), - "cos_theta": Quantity(r"\cos \theta_{{$C}_{$S}}", _U["dimless"]), - "cos_phi": Quantity(r"\cos \phi_{{$C}_{$S}}", _U["dimless"]), - "ratio": Quantity(r"\mathrm{Ratio}", _U["dimless"]), + "theta": Quantity(r"{\theta}_{{$C};{$S}}", _U["deg"], name="Polar Angle"), + "phi": Quantity(r"{phi}_{{$C};{$S}}", _U["deg"], name="Azimuthal Angle"), + "deg": Quantity(r"{deg}_{{$C};{$S}}", _U["deg"], name="Angle"), + "cos": Quantity(r"\cos", _U["dimless"], name="Cosine"), + "cos_theta": Quantity( + r"\cos \theta_{{$C}_{$S}}", _U["dimless"], name="Angle Cosine" + ), + "cos_phi": Quantity( + r"\cos \phi_{{$C}_{$S}}", _U["dimless"], name="Azimuthal Angle Cosine" + ), + "ratio": Quantity(r"\mathrm{Ratio}", _U["dimless"], name="Ratio"), # Timestamps. - "year": Quantity(r"\mathrm{Year}", r"\mathrm{Year}"), - "fdoy": Quantity(r"\mathrm{Fractional \; Day \; of \; Year}", r"\mathrm{fdoy}"), + "year": Quantity(r"\mathrm{Year}", r"\mathrm{Year}", name="Year"), + "fdoy": Quantity( + r"\mathrm{Fractional \; Day \; of \; Year}", + r"\mathrm{fdoy}", + name="Fractional Day of Year", + ), # Plasma measurements. - "b": Quantity(r"B_{$C}", _U["b"], si=1e-9), - "pb": Quantity(r"P_B", _U["pPa"]), - "n": Quantity(r"n_{$S}", _U["cm-3"], si=1e6), - "rho": Quantity(r"\rho_{$S}", r"m_p \; " + _U["cm-3"], si=1e6 * constants.m_p), - "v": Quantity(r"{v}_{{$C};{$S}}", _U["kms"], si=1e3), - "w": Quantity(r"{w}_{{$C};{$S}}", _U["kms"], si=1e3), - "dv": Quantity(r"{\Delta v}_{{$C};{$S}}", _U["kms"], si=1e3), - "dn": Quantity(r"\delta n_{{$S}}", _U["cm-3"]), - "cs": Quantity(r"C_{s;$S}", _U["kms"], si=1e3), - "ca": Quantity(r"C_{A;$S}", _U["kms"], si=1e3), - "afsq": Quantity(r"\mathrm{Anisotropy \, Factor}^2_{$S}", _U["dimless"]), - "caani": Quantity(r"C^{(\mathrm{Ani})}_{A;$S} \; ($C)", _U["kms"]), + "b": Quantity(r"B_{$C}", _U["b"], si=1e-9, name="Magnetic Field"), + "pb": Quantity(r"P_B", _U["pPa"], name="Magnetic Pressure"), + "n": Quantity(r"n_{$S}", _U["cm-3"], si=1e6, name="Number Density"), + "rho": Quantity( + r"\rho_{$S}", + r"m_p \; " + _U["cm-3"], + si=1e6 * constants.m_p, + name="Mass Density", + ), + "v": Quantity(r"{v}_{{$C};{$S}}", _U["kms"], si=1e3, name="Velocity"), + "w": Quantity(r"{w}_{{$C};{$S}}", _U["kms"], si=1e3, name="Thermal Speed"), + "dv": Quantity( + r"{\Delta v}_{{$C};{$S}}", _U["kms"], si=1e3, name="Differential Flow" + ), + "dn": Quantity(r"\delta n_{{$S}}", _U["cm-3"], name="Density Fluctuation"), + "cs": Quantity(r"C_{s;$S}", _U["kms"], si=1e3, name="Sound Speed"), + "ca": Quantity(r"C_{A;$S}", _U["kms"], si=1e3, name="Alfven Speed"), + "afsq": Quantity( + r"\mathrm{Anisotropy \, Factor}^2_{$S}", + _U["dimless"], + name="Anisotropy Factor Squared", + ), + "caani": Quantity( + r"C^{(\mathrm{Ani})}_{A;$S} \; ($C)", + _U["kms"], + name="Anisotropic Alfven Speed", + ), # Temperatures, pressures, anisotropies and fluxes. - "p": Quantity(r"{p}_{{$C};{$S}}", _U["pPa"]), - "pth": Quantity(r"{P}_{{$C};{$S}}", _U["pPa"], si=1e-12), - "T": Quantity(r"{T}_{{$C};{$S}}", r"10^5 \, \mathrm{K}", si=1e5), - "qpar": Quantity(r"q_{{\parallel};{$S}}", _FLUX_DENSITY, si=1e-6), - "qhat": Quantity(r"{\widehat{q}}_{{$C};{$S}}", _U["dimless"]), - "Qhat": Quantity(r"{\widehat{q}}_{{$C};{$S}}", _U["dimless"]), - "Wk": Quantity(r"W_{K;{$S}}", _FLUX_DENSITY, si=1e-6), - "R": Quantity(r"{R}_{{$C};{$S}}", _U["dimless"]), - "beta": Quantity(r"{\beta}_{{$C};{$S}}", _U["dimless"], si=1.0), - "dbeta": Quantity(r"{\Delta \beta}_{{$C};{$S}}", _U["dimless"]), - "pdv": Quantity(r"P_{\Delta v_{$S}}", _U["pPa"]), - "edv": Quantity(r"P_{\Delta v}/P_\mathrm{th}|_{$S}", _U["dimless"]), + "p": Quantity(r"{p}_{{$C};{$S}}", _U["pPa"], name="Pressure"), + "pth": Quantity( + r"{P}_{{$C};{$S}}", _U["pPa"], si=1e-12, name="Thermal Pressure" + ), + "T": Quantity( + r"{T}_{{$C};{$S}}", r"10^5 \, \mathrm{K}", si=1e5, name="Temperature" + ), + "qpar": Quantity( + r"q_{{\parallel};{$S}}", _FLUX_DENSITY, si=1e-6, name="Parallel Heat Flux" + ), + "qhat": Quantity( + r"{\widehat{q}}_{{$C};{$S}}", _U["dimless"], name="Normalized Heat Flux" + ), + "Qhat": Quantity( + r"{\widehat{q}}_{{$C};{$S}}", _U["dimless"], name="Normalized Heat Flux" + ), + "Wk": Quantity( + r"W_{K;{$S}}", _FLUX_DENSITY, si=1e-6, name="Kinetic Energy Flux" + ), + "R": Quantity(r"{R}_{{$C};{$S}}", _U["dimless"], name="Temperature Anisotropy"), + "beta": Quantity( + r"{\beta}_{{$C};{$S}}", _U["dimless"], si=1.0, name="Plasma Beta" + ), + "dbeta": Quantity( + r"{\Delta \beta}_{{$C};{$S}}", _U["dimless"], name="Beta Difference" + ), + "pdv": Quantity(r"P_{\Delta v_{$S}}", _U["pPa"], name="Drift Pressure"), + "edv": Quantity( + r"P_{\Delta v}/P_\mathrm{th}|_{$S}", + _U["dimless"], + name="Drift to Thermal Pressure", + ), "flux": Quantity( r"\mathrm{Flux}_{$C}({$S})", r"10^{-9} \, %s \, s^{-1}" % _U["cm-3"].replace("-3", "-2"), + name="Particle Flux", ), # Collisions. - "lnlambda": Quantity(r"\ln\Lambda_{$S}", _U["dimless"], si=1.0), - "nuc": Quantity(r"\nu_{$C,$S}", r"10^{-7} \mathrm{Hz}", si=1e-7), - "nc": Quantity(r"N_{C;$S}", _U["dimless"], si=1.0), + "lnlambda": Quantity( + r"\ln\Lambda_{$S}", _U["dimless"], si=1.0, name="Coulomb Logarithm" + ), + "nuc": Quantity( + r"\nu_{$C,$S}", r"10^{-7} \mathrm{Hz}", si=1e-7, name="Collision Rate" + ), + "nc": Quantity(r"N_{C;$S}", _U["dimless"], si=1.0, name="Coulomb Number"), # Fits and distributions. - "chisq": Quantity(r"\chi^2", _U["dimless"]), - "chisqnu": Quantity(r"\chi^2_\nu", _U["dimless"]), + "chisq": Quantity(r"\chi^2", _U["dimless"], name="Chi-Squared"), + "chisqnu": Quantity(r"\chi^2_\nu", _U["dimless"], name="Reduced Chi-Squared"), "vdf_ratio": Quantity( - r"\mathrm{ln}(\frac{f_i}{f_j} \left(v_i\right)_{$S})", _U["dimless"] + r"\mathrm{ln}(\frac{f_i}{f_j} \left(v_i\right)_{$S})", + _U["dimless"], + name="VDF Ratio", ), - "ab": Quantity(r"A_{$S}", r"\%"), - "e": Quantity(r"e\left({$C}_{$S}\right)", _U["kms"]), + "ab": Quantity(r"A_{$S}", r"\%", name="Abundance"), + "e": Quantity(r"e\left({$C}_{$S}\right)", _U["kms"], name="E Term"), # Alfvenic turbulence. - "zp": Quantity(r"Z^+_{{$S}}", _U["kms"]), - "zm": Quantity(r"Z^-_{{$S}}", _U["kms"]), - "ep": Quantity(r"e^+_{{$S}}", _KMS_SQ), - "em": Quantity(r"e^-_{{$S}}", _KMS_SQ), - "ev": Quantity(r"e^v_{{$S}}", _KMS_SQ), - "eb": Quantity(r"e^b_{{$S}}", _KMS_SQ), - "etot": Quantity(r"E_{{$S}}", _KMS_SQ), - "eres": Quantity(r"e^r_{{$S}}", _KMS_SQ), - "cross_helicity": Quantity(r"e^c_{{$S}}", _KMS_SQ), - "sigma_m": Quantity(r"\sigma_{m}", _U["dimless"]), - "sigma_c": Quantity(r"\sigma_{c;{$S}}", _U["dimless"]), - "sigma_r": Quantity(r"\sigma_{r;{$S}}", _U["dimless"]), - "sigma_xy": Quantity(r"\sigma_{\parallel}", _U["dimless"]), - "rA": Quantity(r"r_{A;{$S}}", _U["dimless"]), - "rE": Quantity(r"r_{E;{$S}}", _U["dimless"]), + "zp": Quantity(r"Z^+_{{$S}}", _U["kms"], name="Elsasser Variable Z+"), + "zm": Quantity(r"Z^-_{{$S}}", _U["kms"], name="Elsasser Variable Z-"), + "ep": Quantity(r"e^+_{{$S}}", _KMS_SQ, name="Z+ Energy"), + "em": Quantity(r"e^-_{{$S}}", _KMS_SQ, name="Z- Energy"), + "ev": Quantity(r"e^v_{{$S}}", _KMS_SQ, name="Kinetic Fluctuation Energy"), + "eb": Quantity(r"e^b_{{$S}}", _KMS_SQ, name="Magnetic Fluctuation Energy"), + "etot": Quantity(r"E_{{$S}}", _KMS_SQ, name="Total Fluctuation Energy"), + "eres": Quantity(r"e^r_{{$S}}", _KMS_SQ, name="Residual Energy"), + "cross_helicity": Quantity(r"e^c_{{$S}}", _KMS_SQ, name="Cross Helicity"), + "sigma_m": Quantity( + r"\sigma_{m}", _U["dimless"], name="Normalized Magnetic Helicity" + ), + "sigma_c": Quantity( + r"\sigma_{c;{$S}}", _U["dimless"], name="Normalized Cross Helicity" + ), + "sigma_r": Quantity( + r"\sigma_{r;{$S}}", _U["dimless"], name="Normalized Residual Energy" + ), + "sigma_xy": Quantity( + r"\sigma_{\parallel}", _U["dimless"], name="Parallel Sigma" + ), + "rA": Quantity(r"r_{A;{$S}}", _U["dimless"], name="Alfven Ratio"), + "rE": Quantity(r"r_{E;{$S}}", _U["dimless"], name="Elsasser Ratio"), # Instabilities. - "Wn": Quantity(r"\mathrm{W_n}", _U["dimless"]), - "omegaR": Quantity(r"\omega_R", _U["Hz"]), - "gamma": Quantity(r"\gamma", _U["Hz"]), - "gamma_max": Quantity(r"\gamma_\mathrm{max}", _U["Hz"]), - "gyro_freq": Quantity(r"\Omega_{{$S}}", _U["Hz"]), - "eth": Quantity(r"\eth", r"\mathrm{eV}"), - "kvec": Quantity(r"\mathbf{k}_{$C}\rho_{$S}", _U["dimless"]), - "k": Quantity(r"k_{$C}\rho_{$S}", _U["dimless"]), - "insta_power": Quantity(r"\mathcal{P}_{{$S}}", _U["unknown"]), + "Wn": Quantity(r"\mathrm{W_n}", _U["dimless"], name="Wn"), + "omegaR": Quantity(r"\omega_R", _U["Hz"], name="Real Frequency"), + "gamma": Quantity(r"\gamma", _U["Hz"], name="Growth Rate"), + "gamma_max": Quantity( + r"\gamma_\mathrm{max}", _U["Hz"], name="Maximum Growth Rate" + ), + "gyro_freq": Quantity(r"\Omega_{{$S}}", _U["Hz"], name="Gyrofrequency"), + "eth": Quantity(r"\eth", r"\mathrm{eV}", name="Eth"), + "kvec": Quantity( + r"\mathbf{k}_{$C}\rho_{$S}", _U["dimless"], name="Wave Vector" + ), + "k": Quantity(r"k_{$C}\rho_{$S}", _U["dimless"], name="Wavenumber"), + "insta_power": Quantity( + r"\mathcal{P}_{{$S}}", _U["unknown"], name="Instability Power" + ), # Spectra and energetic particles. - "spectral_exponent": Quantity(r"\mathrm{Spectral \, Exponent}", _U["dimless"]), - "MeV/nuc": Quantity(r"\mathrm{Energy}", r"\mathrm{MeV/nuc}"), + "spectral_exponent": Quantity( + r"\mathrm{Spectral \, Exponent}", _U["dimless"], name="Spectral Exponent" + ), + "MeV/nuc": Quantity( + r"\mathrm{Energy}", r"\mathrm{MeV/nuc}", name="Energy per Nucleon" + ), "SEP_differential_flux": Quantity( - r"{{$S}} \: dJ/dE", r"\mathrm{\frac{\#}{cm^2 \, sr \, s \, MeV/nuc}}" + r"{{$S}} \: dJ/dE", + r"\mathrm{\frac{\#}{cm^2 \, sr \, s \, MeV/nuc}}", + name="SEP Differential Flux", ), "SEP_intensity": Quantity( - r"{{$S}} \: \mathrm{Intensity}", r"\mathrm{cm^2 \, sr \, s \, MeV/nuc}" + r"{{$S}} \: \mathrm{Intensity}", + r"\mathrm{cm^2 \, sr \, s \, MeV/nuc}", + name="SEP Intensity", + ), + "SEP_energy": Quantity( + r"{{$S}} \: \mathrm{Energy}", r"\mathrm{MeV/nuc}", name="SEP Energy" + ), + "SEP_spectrum_index": Quantity( + r"\gamma_{{$S}}", _U["dimless"], name="SEP Spectral Index" ), - "SEP_energy": Quantity(r"{{$S}} \: \mathrm{Energy}", r"\mathrm{MeV/nuc}"), - "SEP_spectrum_index": Quantity(r"\gamma_{{$S}}", _U["dimless"]), } ) diff --git a/tests/core/test_quantity_registry.py b/tests/core/test_quantity_registry.py index 5a901cc13..c8866ffb6 100644 --- a/tests/core/test_quantity_registry.py +++ b/tests/core/test_quantity_registry.py @@ -465,3 +465,49 @@ def test_bimax_species_have_their_own_tex(species, tex): from solarwindpy.plotting.labels.base import TeXlabel assert TeXlabel(("n", "", species)).tex == tex + + +# --- display names ----------------------------------------------------------- + +# Words a title-case name keeps lower case after its first word. +_MINOR_WORDS = {"of", "to", "per", "and", "in", "the"} + + +def _is_title_case(name): + """Each word capitalized, a minor word lower case after the first, any acronym.""" + words = name.split(" ") + for i, word in enumerate(words): + if not word: + return False + if i and word in _MINOR_WORDS: + continue + if not (word[0].isupper() or word[0].isdigit()): + return False + return True + + +def test_every_quantity_has_a_short_title_case_name(): + """Each registry entry carries a short display name in title case. + + The name is the quantity in two to four words at most (one, as + "Temperature", is fine); it is not a description. + + ON FAILURE: the code is wrong -- an entry lacks its ``name``, or the name + is not title case or is too long. + """ + for key, entry in _quantities().QUANTITIES.items(): + name = entry.name + assert isinstance(name, str) and name, key + assert 1 <= len(name.split(" ")) <= 4, (key, name) + assert _is_title_case(name), (key, name) + + +def test_name_is_a_required_keyword(): + """A ``Quantity`` without a ``name`` fails at construction. + + ON FAILURE: the code is wrong -- an entry could silently lack its name. + """ + Quantity = _quantities().Quantity + with pytest.raises(TypeError): + Quantity(r"x", r"\mathrm{m}") + assert Quantity(r"x", r"\mathrm{m}", name="Distance").name == "Distance" From 43362eda0bc6b85c84e6de8dd53d12a512459901 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 05:08:21 -0500 Subject: [PATCH 37/60] docs(usage): draw the smoothed sunspot number on a Scatter's time colorbar After the connect example, a Scatter over 1994-2026 with z the time in matplotlib's date units, the units SIDC.plot_on_colorbar plots in, a "Year" colorbar, and SIDC("m13")'s sunspot number along it, titled SSN with its tick labels removed. Readers download the series from SILSO; the build reads the committed snapshot. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++++ docs/source/usage.rst | 47 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7578f1121..1f6b22427 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 points are joined in row order in the points' color. - The Usage guide's "Individual points" shows `Scatter` colored by z, with `connect=True` on shuffled rows, and without z, each figure drawn by the block beside it. +- The Usage guide draws SILSO's 13-month smoothed sunspot number on a connected `Scatter`'s + time colorbar with `SIDC("m13").plot_on_colorbar`. The docs build and the plot-block test + read the series from a snapshot in `docs/source/_data` through a private download cache, so + neither needs the network. ### Changed - BREAKING CHANGES diff --git a/docs/source/usage.rst b/docs/source/usage.rst index 13fdf2a81..b441e7a80 100644 --- a/docs/source/usage.rst +++ b/docs/source/usage.rst @@ -402,6 +402,53 @@ skipped, not a gap: the points either side of it in ``z`` are joined. s=12, cmap="viridis", connect=True, connect_kwargs={"linewidth": 0.8, "alpha": 0.8} ) +Over decades, the colorbar can carry the solar cycle. With ``z`` the time of +each point in matplotlib's date units, ``SIDC("m13").plot_on_colorbar`` draws +the 13-month smoothed sunspot number along the colorbar, so each segment's +color places it in the cycle. ``SIDC("m13")`` downloads the series from SILSO +(https://www.sidc.be/SILSO/) and keeps it in SolarWindPy's download cache for +a day. The sunspot number's own scale is left unlabelled here: the line shows +the cycle's phase, not its amplitude. + +.. plot:: + + import matplotlib.dates as mdates + import numpy as np + import pandas as pd + from solarwindpy.plotting.scatter import Scatter + from solarwindpy.plotting.labels.base import TeXlabel + from solarwindpy.solar_activity.sunspot_number.sidc import SIDC + + rng = np.random.default_rng(3) + epoch = pd.date_range("1994-01-01", "2026-01-01", freq="QS") + N = epoch.size + + # Quarterly means that circle once per 11-year cycle, peaking near 2002, + # 2013 and 2024. + year = epoch.year + (epoch.month - 1) / 12 + phase = 2 * np.pi * (year - 1996.5) / 11 + v = pd.Series(440 + 50 * np.sin(phase) + rng.normal(0, 6, N), index=epoch, name="v") + b = pd.Series( + 5.75 - 1.25 * np.cos(phase) + rng.normal(0, 0.15, N), index=epoch, name="b" + ) + # Time as z, in matplotlib's date units: the units the colorbar's SSN uses. + t = pd.Series(mdates.date2num(epoch), index=epoch, name="t") + + sc = Scatter(v, b, t) + sc.set_labels(x=TeXlabel(("v", "", "p1")), y=TeXlabel(("b", "", "")), z="Year") + ax, points, segments, cbar = sc.make_plot( + s=14, cmap="viridis", connect=True, cbar_kwargs={"aspect": 8} + ) + cbar.ax.yaxis.set_major_locator(mdates.YearLocator(4)) + cbar.ax.yaxis.set_major_formatter(mdates.DateFormatter("%Y")) + + # The 13-month smoothed sunspot number along the colorbar, downloaded from SILSO. + SIDC("m13").plot_on_colorbar(cbar.ax, epoch[0], epoch[-1]) + cbar.ax.set_xlabel("") + cbar.ax.xaxis.set_major_locator(mdates.ticker.NullLocator()) + cbar.ax.xaxis.set_minor_locator(mdates.ticker.NullLocator()) + cbar.ax.set_title("SSN", fontsize="medium") + Without ``z``, ``Scatter(x, y)`` draws every point in one color and no colorbar, so ``cbar`` is None. ``connect=True`` then joins the points in the order of their rows, in the markers' color, skipping any point that is not From 31911bb8bd2a7ea69a6dc2e85441a04a80cec02c Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 05:12:34 -0500 Subject: [PATCH 38/60] feat(plotting): add a publication format for labels In publication format a label is two lines: the quantity's name in words over its usual TeX symbol and units. The name is the registry's display name; TeXlabel(..., name=...) replaces it. A ratio reads " Ratio" for like quantities, otherwise " / "; Count reads "Count" or its normalization's name, which AXNORM now carries; a measurement the registry does not name keeps one line. The normalization stays on the symbol line, as species and component do. labels.base.set_publication_format sets the module default and labels.base.publication_format reads it; a label's own publication_format overrides it, and None follows it. The lines are added when a label is read, in Base._format_with_description, which every label class uses, so the default also reaches labels that plots already hold. TeXlabel therefore no longer caches its description in with_units. A description keeps its line above the name. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 + src/solarwindpy/plotting/labels/base.py | 169 ++++++++++++-- src/solarwindpy/plotting/labels/special.py | 6 + .../labels/test_publication_format.py | 208 ++++++++++++++++++ 4 files changed, 375 insertions(+), 17 deletions(-) create mode 100644 tests/plotting/labels/test_publication_format.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 14540d50d..6fda674ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Every quantity in the registry has a display name: `solarwindpy.core.quantities.Quantity` takes a required keyword `name`, a few words in title case such as "Number Density" or "Temperature". It names the quantity only, without species or component. +- Publication-format labels: a label is its name in words over its usual TeX symbol and + units, e.g. "Number Density" over `n_{p_1} [cm^-3]`. Turn it on for every label with + `solarwindpy.plotting.labels.base.set_publication_format` (read the default with + `solarwindpy.plotting.labels.base.publication_format`), or per label with + `TeXlabel(..., publication_format=True)`, which overrides the default. The name is the + registry's; `TeXlabel(..., name="Solar Wind Speed")` replaces it. A ratio reads + " Ratio" or " / ", and `Count` names its normalization ("Count", + "Normalized Count", "Probability Density"). Labels read the default when they render, so + it also applies to plots already built. ### Changed diff --git a/src/solarwindpy/plotting/labels/base.py b/src/solarwindpy/plotting/labels/base.py index 3d8b99e85..c416e1038 100644 --- a/src/solarwindpy/plotting/labels/base.py +++ b/src/solarwindpy/plotting/labels/base.py @@ -6,6 +6,8 @@ "Base", "TeXlabel", "format_with_units", + "publication_format", + "set_publication_format", "validate_axnorm", ] @@ -28,34 +30,85 @@ _trans_component = quantities.COMPONENTS _inU = quantities.UNIT_TEX -_AxisNorm = namedtuple("_AxisNorm", "count,quantity,density") +_AxisNorm = namedtuple("_AxisNorm", "count,quantity,density,name") #: How a label names each ``axnorm`` key, keyed by the key: the one table of #: the keys ``Count`` and ``TeXlabel`` accept. ``count`` is the words of a #: normalized ``Count``; ``quantity`` the TeX of a normalized quantity, with -#: ``%s`` for the quantity's TeX. ``density`` is True for a density: its units +#: ``%s`` for the quantity's TeX. ``name`` is the plain-text name of a +#: normalized ``Count`` in publication format. ``density`` is True for a density: its units #: are 1 / (bin width or area in the units of the binned axes, in decades on a #: log axis), which a label does not know, so it states none. A count divided #: by a maximum is a pure number and states ``\#``. Every key a binning's #: ``allowed_axnorm`` holds is a key here. AXNORM = MappingProxyType( { - "c": _AxisNorm("Count / Column Max", r"%s / \mathrm{Column \; Max}", False), - "r": _AxisNorm("Count / Row Max", r"%s / \mathrm{Row \; Max}", False), - "t": _AxisNorm("Count / Max", r"%s / \mathrm{Max}", False), - "d": _AxisNorm("Probability Density", r"\mathrm{Density \; of} \; %s", True), + "c": _AxisNorm( + "Count / Column Max", + r"%s / \mathrm{Column \; Max}", + False, + "Column-Normalized Count", + ), + "r": _AxisNorm( + "Count / Row Max", + r"%s / \mathrm{Row \; Max}", + False, + "Row-Normalized Count", + ), + "t": _AxisNorm("Count / Max", r"%s / \mathrm{Max}", False, "Normalized Count"), + "d": _AxisNorm( + "Probability Density", + r"\mathrm{Density \; of} \; %s", + True, + "Probability Density", + ), "cd": _AxisNorm( "Column Probability Density", r"\mathrm{Column \; Density \; of} \; %s", True, + "Column Probability Density", ), "rd": _AxisNorm( - "Row Probability Density", r"\mathrm{Row \; Density \; of} \; %s", True + "Row Probability Density", + r"\mathrm{Row \; Density \; of} \; %s", + True, + "Row Probability Density", ), } ) +#: The module default of ``publication_format``; read and set it with +#: :func:`publication_format` and :func:`set_publication_format`. +_publication_format = False + + +def publication_format(): + r"""Return the default publication format of every label, True or False. + + A label whose own ``publication_format`` is None follows it. See + :func:`set_publication_format`. + """ + return _publication_format + + +def set_publication_format(on): + r"""Set whether labels default to publication format. + + In publication format a label is two lines: its name in words, such as + "Number Density", over its usual TeX symbol and units. A label without a + name keeps one line. Labels read the default when they render, so this + also changes labels that plots already hold. + + Parameters + ---------- + on : bool + True for publication format; False, the initial default, for one line. + """ + global _publication_format + _publication_format = bool(on) + + def validate_axnorm(key): r"""Return the ``axnorm`` key ``key`` in lower case, or None for None. @@ -127,6 +180,12 @@ def _template_of(m): return _default_template_string +def _name_of(key): + """Return the registry display name of ``key``, or None if it has none.""" + entry = quantities.QUANTITIES.get(key) + return None if entry is None else entry.name + + def _units_of(key): """Return the TeX of the display unit of ``key``, or ``???`` if it has none.""" entry = quantities.QUANTITIES.get(key) @@ -166,6 +225,9 @@ def format_with_units(tex, units, *, new_line=False): class Base(ABC): """Base class for all label objects.""" + _name = None + _publication_format = None + def __init__(self): """Initialize the logger.""" self._init_logger() @@ -217,8 +279,46 @@ def set_description(self, new): new = str(new) self._description = new + @property + def name(self): + r"""Plain-text name, the first line in publication format, or None. + + The name given with ``set_name``, otherwise the label's own default + (``_default_name``), None when it has none. + """ + if self._name is not None: + return self._name + return self._default_name() + + def _default_name(self): + r"""Name of a label given none; None here.""" + return None + + def set_name(self, new): + r"""Set the name, or None for the label's default name.""" + if new is not None: + new = str(new) + self._name = new + + @property + def publication_format(self): + r"""If True, the label is its name over its symbol line. + + The label's own setting, or the module default + (:func:`publication_format`) when that is None. + """ + if self._publication_format is None: + return publication_format() + return self._publication_format + + def set_publication_format(self, new): + r"""Set this label's publication format: True, False, or None to follow the default.""" + if new is not None: + new = bool(new) + self._publication_format = new + def _format_with_description(self, label_str): - """Prepend description to label string if set. + """Prepend the description and, in publication format, the name. Parameters ---------- @@ -228,11 +328,15 @@ def _format_with_description(self, label_str): Returns ------- str - Label with description prepended if set, otherwise unchanged. + The description if set, then the name in publication format if + the label has one, each on its own line above ``label_str``. """ + lines = [] if self.description: - return f"{self.description}\n{label_str}" - return label_str + lines.append(self.description) + if self.publication_format and self.name: + lines.append(self.name) + return "\n".join(lines + [label_str]) @property def with_units(self): @@ -269,7 +373,14 @@ class TeXlabel(Base): """ def __init__( - self, mcs0, mcs1=None, axnorm=None, new_line_for_units=False, description=None + self, + mcs0, + mcs1=None, + axnorm=None, + new_line_for_units=False, + description=None, + name=None, + publication_format=None, ): """Instantiate the label. @@ -289,12 +400,20 @@ def __init__( If ``True`` a newline separates label and units. description : str or None, optional Human-readable description displayed above the mathematical label. + name : str or None, optional + The first line in publication format. None uses the quantity's + registry name, a ratio's " Ratio" or " / ". + publication_format : bool or None, optional + If True, the label is its name over its symbol line. None follows + the module default, :func:`publication_format`. """ super(TeXlabel, self).__init__() self.set_axnorm(axnorm) self.set_mcs(mcs0, mcs1) self.set_new_line_for_units(new_line_for_units) self.set_description(description) + self.set_name(name) + self.set_publication_format(publication_format) self.build_label() @property @@ -324,8 +443,26 @@ def units(self): @property def with_units(self): - r"""Label with units, set by ``build_label``.""" - return self._with_units + r"""Label with units, from ``build_label``, under its description and name.""" + return self._format_with_description(self._with_units) + + def _default_name(self): + r"""The registry name; for a ratio, " Ratio" or " / ". + + None when the registry does not name a measurement. + """ + names = [ + _name_of(mcs.m.replace("_err", "")) + for mcs in (self.mcs0, self.mcs1) + if mcs is not None + ] + if None in names: + return None + if len(names) == 1: + return names[0] + if names[0] == names[1]: + return f"{names[0]} Ratio" + return " / ".join(names) @property def path(self): @@ -478,11 +615,9 @@ def _combine_tex_path_units_axnorm(self, tex, path, units): tex = norm.quantity % tex path = path / (axnorm.upper() + "norm") + # The description and name lines are added when the label is read. with_units = format_with_units(tex, units, new_line=self.new_line_for_units) - # Apply description formatting - with_units = self._format_with_description(with_units) - return tex, path, units, with_units def build_label(self): diff --git a/src/solarwindpy/plotting/labels/special.py b/src/solarwindpy/plotting/labels/special.py index 133f0d8e4..6d8d4017d 100644 --- a/src/solarwindpy/plotting/labels/special.py +++ b/src/solarwindpy/plotting/labels/special.py @@ -309,6 +309,12 @@ def set_axnorm(self, norm): """ self._axnorm = base.validate_axnorm(norm) + def _default_name(self): + r"""Name "Count", or the normalized count's name from ``base.AXNORM``.""" + if self.axnorm is None: + return "Count" + return base.AXNORM[self.axnorm].name + def _build_tex(self): axnorm = self.axnorm words = "Count" if axnorm is None else base.AXNORM[axnorm].count diff --git a/tests/plotting/labels/test_publication_format.py b/tests/plotting/labels/test_publication_format.py new file mode 100644 index 000000000..29d3dd1f9 --- /dev/null +++ b/tests/plotting/labels/test_publication_format.py @@ -0,0 +1,208 @@ +# Spent-When: PERMANENT(the repository stops maintaining a test suite) +# Supersedes: none +"""Publication-format labels: a display name over the usual symbol line. + +In publication format a label is two lines: the quantity's name in words, from +the quantity registry, over the TeX symbol with its units. A per-label +``publication_format`` overrides the module default that +``set_publication_format`` sets. +""" + +import pytest + +from solarwindpy.plotting.labels import base +from solarwindpy.plotting.labels.base import TeXlabel +from solarwindpy.plotting.labels.special import Count + + +@pytest.fixture +def restore_default(): + """Restore the module default after a test that changes it.""" + before = base.publication_format() + try: + yield + finally: + base.set_publication_format(before) + + +@pytest.mark.parametrize( + "mcs, name, symbol", + [ + ( + ("n", "", "p1"), + "Number Density", + r"$n_{p_1} \; \left[\mathrm{cm}^{-3}\right]$", + ), + ( + ("T", "par", "p1"), + "Temperature", + r"${T}_{{\parallel};{p_1}} \; \left[10^5 \, \mathrm{K}\right]$", + ), + ( + ("v", "x", "a"), + "Velocity", + r"${v}_{{x};{\alpha}} \; \left[\mathrm{km \; s^{-1}}\right]$", + ), + ( + ("sigma_c", "", "p1"), + "Normalized Cross Helicity", + r"$\sigma_{c;{p_1}} \; \left[\#\right]$", + ), + ], +) +def test_label_is_its_name_over_its_symbol(mcs, name, symbol): + """The first line is the registry name, the second the default label. + + ON FAILURE: the code is wrong. + """ + label = TeXlabel(mcs, publication_format=True) + assert label.name == name + assert str(label) == f"{name}\n{symbol}" + assert str(label).split("\n")[1] == str(TeXlabel(mcs)) + + +def test_name_overrides_the_registry_name(): + """``name=`` replaces the first line only. + + ON FAILURE: the code is wrong. + """ + label = TeXlabel(("v", "", "p1"), name="Solar Wind Speed", publication_format=True) + assert str(label) == ( + "Solar Wind Speed\n" + r"${v}_{{p_1}} \; \left[\mathrm{km \; s^{-1}}\right]$" + ) + + +def test_description_stays_above_the_name(): + """A description keeps its own line, above the name. + + ON FAILURE: the code is wrong. + """ + label = TeXlabel(("n", "", "p1"), description="Wind", publication_format=True) + assert str(label).split("\n") == [ + "Wind", + "Number Density", + r"$n_{p_1} \; \left[\mathrm{cm}^{-3}\right]$", + ] + + +def test_per_label_setting_overrides_the_module_default(restore_default): + """True or False on a label wins; None follows the module default. + + ON FAILURE: the code is wrong. + """ + base.set_publication_format(True) + assert base.publication_format() is True + assert "\n" in str(TeXlabel(("n", "", "p1"))) + assert "\n" not in str(TeXlabel(("n", "", "p1"), publication_format=False)) + + base.set_publication_format(False) + assert base.publication_format() is False + assert "\n" not in str(TeXlabel(("n", "", "p1"))) + assert "\n" in str(TeXlabel(("n", "", "p1"), publication_format=True)) + + +def test_module_default_applies_to_labels_already_built(restore_default): + """A label reads the default when it renders, so existing plots follow it. + + ON FAILURE: the code is wrong -- the format is fixed when the label is + built, so ``set_publication_format`` misses labels a plot already holds. + """ + label = TeXlabel(("n", "", "p1")) + count = Count("t") + one_line = (str(label), str(count)) + base.set_publication_format(True) + assert str(label) == "Number Density\n" + one_line[0] + assert str(count) == "Normalized Count\n" + one_line[1] + base.set_publication_format(False) + assert (str(label), str(count)) == one_line + + +def test_ratio_names(): + """A ratio of one quantity is " Ratio"; of two, " / ". + + ON FAILURE: the code is wrong. + """ + same = TeXlabel(("n", "", "a"), ("n", "", "p1"), publication_format=True) + mixed = TeXlabel(("v", "", "p1"), ("n", "", "p1"), publication_format=True) + assert same.name == "Number Density Ratio" + assert mixed.name == "Velocity / Number Density" + assert str(same).split("\n")[0] == "Number Density Ratio" + + +def test_normalization_stays_on_the_symbol_line(): + """An ``axnorm`` changes the symbol line; the name is the quantity's. + + ON FAILURE: the code is wrong. + """ + label = TeXlabel(("n", "", "p1"), axnorm="t", publication_format=True) + assert str(label) == ( + "Number Density\n" + r"$n_{p_1} / \mathrm{Max} \; \left[\#\right]$" + ) + + +def test_unregistered_quantity_has_no_name_line(): + """A measurement the registry does not know renders on one line. + + ON FAILURE: the code is wrong. + """ + label = TeXlabel(("not_a_quantity", "", "p1"), publication_format=True) + assert label.name is None + assert "\n" not in str(label) + + +@pytest.mark.parametrize( + "norm, name", + [ + (None, "Count"), + ("t", "Normalized Count"), + ("c", "Column-Normalized Count"), + ("r", "Row-Normalized Count"), + ("d", "Probability Density"), + ("cd", "Column Probability Density"), + ("rd", "Row Probability Density"), + ], +) +def test_count_names_follow_the_normalization(norm, name, restore_default): + """``Count`` names its normalization in words, from ``AXNORM``. + + ON FAILURE: the code is wrong. + """ + base.set_publication_format(True) + label = Count(norm) + assert label.name == name + assert str(label).split("\n")[0] == name + + +@pytest.mark.parametrize( + "label, expected", + [ + ( + lambda: TeXlabel(("v", "x", "p1")), + r"${v}_{{x};{p_1}} \; \left[\mathrm{km \; s^{-1}}\right]$", + ), + ( + lambda: TeXlabel(("T", "scalar", "p1")), + r"${T}_{{p_1}} \; \left[10^5 \, \mathrm{K}\right]$", + ), + ( + lambda: TeXlabel(("n", "", "a"), ("n", "", "p1")), + r"$n_{\alpha}/n_{p_1} \; \left[\#\right]$", + ), + ( + lambda: TeXlabel(("n", "", "p1"), axnorm="d"), + r"$\mathrm{Density \; of} \; n_{p_1}$", + ), + (lambda: Count(), r"$\mathrm{Count} \; \left[\#\right]$"), + ( + lambda: Count("t"), + r"$\mathrm{Count \, / \, Max} \; \left[\#\right]$", + ), + ], +) +def test_default_format_is_unchanged(label, expected): + """With the default off, labels render on one line, as before. + + ON FAILURE: the code is wrong. + """ + assert base.publication_format() is False + assert str(label()) == expected From 4e05f06fe88a8966fe1fa0df81e498f8428955ec Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 05:12:40 -0500 Subject: [PATCH 39/60] test(plotting): the plot repr shows bin and data ranges per axis Target tests, xfail(strict=True) until the change: each axis line shows its bin count and range (the mesh extent on a spiral) and the range of the data binned, in data units on a log axis, without NaN rows, to four significant figures; z shows its data range; a scatter shows data ranges only; an unbuilt plot still has a repr. Guard: a count axis shows no data range. Existing label checks read the label part of each line. Co-Authored-By: Claude Opus 5.5 --- tests/plotting/test_repr.py | 101 ++++++++++++++++++++++++++++++++++-- 1 file changed, 98 insertions(+), 3 deletions(-) diff --git a/tests/plotting/test_repr.py b/tests/plotting/test_repr.py index 8590c9e18..2da6aa3dc 100644 --- a/tests/plotting/test_repr.py +++ b/tests/plotting/test_repr.py @@ -62,8 +62,8 @@ def test_repr_names_the_class_labels_rows_log_and_path(name): plot = _build(name) first, fields = _lines(plot) assert first == name - assert fields["x"] == str(plot.labels.x) - assert fields["y"] == str(plot.labels.y) + assert fields["x"].split(" ")[0] == str(plot.labels.x) + assert fields["y"].split(" ")[0] == str(plot.labels.y) assert fields["observations"] == str(KEPT[name]) assert fields["log"] == "x=False, y=False" assert fields["path"] == str(plot.path) @@ -83,7 +83,7 @@ def test_repr_shows_z_only_when_the_plot_has_one(name, has_z): assert {"x", "y", "path"} <= set(fields) assert ("z" in fields) is has_z if has_z: - assert fields["z"] == str(plot.labels.z) + assert fields["z"].split(" ")[0] == str(plot.labels.z) def test_hist1d_repr_counts_its_bins_and_axnorm(): @@ -158,3 +158,98 @@ def test_hist1d_z_label_error_still_names_the_class(): """ with pytest.raises(ValueError, match=r"^Hist1D doesn't have a z-label$"): _build("Hist1D").set_labels(z="z") + + +# --------------------------------------------------------------------------- +# Ranges: each axis line shows its bin range and the range of the data binned +# --------------------------------------------------------------------------- + +_NO_RANGES = pytest.mark.xfail(strict=True, reason="the repr shows no ranges yet") + + +@_NO_RANGES +def test_hist2d_axes_show_bin_and_data_ranges_without_the_nan_rows(): + """Edges [0, 2, 4, 6] on both axes: 3 bins over [0, 6] each. + + The kept rows (labels 0, 1, 3, 5; rows 2 and 4 hold a NaN) have x 1, 2, + 3, 5, y 1, 3, 2.5, 3.5 and z 1, 2, 4, 6. + + ON FAILURE: the code is wrong. + """ + edges = np.array([0.0, 2.0, 4.0, 6.0]) + _, fields = _lines(Hist2D(X, Y, Z, nbins=[edges, edges])) + assert fields["x"] == "x bins 3 [0, 6] data [1, 5]" + assert fields["y"] == "y bins 3 [0, 6] data [1, 3.5]" + assert fields["z"] == "z data [1, 6]" + + +@_NO_RANGES +def test_a_log_axis_shows_its_ranges_in_data_units(): + """log10 edges [0, 1, 2, 3] are bins over [1, 1000]; x spans 2 to 500. + + ON FAILURE: the code is wrong. + """ + x = pd.Series([2.0, 30.0, np.nan, 500.0]) + y = pd.Series([1.0, 2.0, 3.0, 4.0]) + h = Hist2D(x, y, logx=True, nbins=[np.array([0.0, 1.0, 2.0, 3.0]), [0.0, 5.0]]) + _, fields = _lines(h) + assert fields["x"] == "x bins 3 [1, 1000] data [2, 500]" + + +@_NO_RANGES +def test_numbers_are_shown_to_four_significant_figures(): + """x from 251.33 to 898.71 on edges 250 to 900 reads [251.3, 898.7]. + + ON FAILURE: the code is wrong. + """ + x = pd.Series([251.33, 600.0, 898.71]) + h = Hist1D(x, nbins=np.array([250.0, 575.0, 900.0])) + _, fields = _lines(h) + assert fields["x"] == "x bins 2 [250, 900] data [251.3, 898.7]" + + +def test_a_count_axis_has_no_data_range(): + """A count's z is the constant 1, so its line is the label alone. + + ON FAILURE: the code is wrong. + """ + h = Hist2D(X, Y, nbins=4) + _, fields = _lines(h) + assert fields["z"] == str(h.labels.z) + + +@_NO_RANGES +def test_spiral_axes_show_the_mesh_extent_and_data_ranges(): + """The mesh spans the initial edges, [0, 6] in x and [0, 4] in y. + + The top edge of each axis is raised 1% so the largest value lies inside: + x to 6.06 and y to 4.04 (``AdaptiveMesh.initial_edges``). + + ON FAILURE: the code is wrong. + """ + _, fields = _lines(_build("SpiralPlot2D")) + assert fields["x"] == "x mesh [0, 6.06] data [1, 5]" + assert fields["y"] == "y mesh [0, 4.04] data [1, 3.5]" + + +@_NO_RANGES +def test_scatter_axes_show_data_ranges(): + """A scatter bins nothing: each axis shows its data range alone. + + ON FAILURE: the code is wrong. + """ + _, fields = _lines(_build("Scatter")) + assert fields["x"] == "x data [1, 5]" + assert fields["y"] == "y data [1, 3.5]" + assert fields["z"] == "z data [1, 6]" + + +@_NO_RANGES +@pytest.mark.parametrize("cls", [Hist1D, Hist2D, SpiralPlot2D, Scatter]) +def test_repr_of_an_unbuilt_plot_does_not_raise(cls): + """A plot whose constructor never ran still has a one-line repr. + + ON FAILURE: the code is wrong. + """ + text = repr(cls.__new__(cls)) + assert text.startswith(cls.__name__) From 160eb9fcbf5ebb23d983df3c1a640bc32ff0d4b3 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 05:17:26 -0500 Subject: [PATCH 40/60] feat(plotting): the plot repr shows bin and data ranges per axis Each axis line of the repr now reads label, then the bin count and range (a spiral's mesh extent), then the range of the data on it, all in data units on a log axis and to four significant figures. The binning supplies its extent through axis_extent, read by one shared _axis_line in Base via the _axis_extent hook BinnedPlot overrides; a scatter shows data ranges only and a count axis none. An unbuilt plot reads " (not built)" instead of raising. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 ++- src/solarwindpy/plotting/base.py | 58 +++++++++++++++++++++++++---- src/solarwindpy/plotting/binned.py | 11 +++++- src/solarwindpy/plotting/binning.py | 15 ++++++++ src/solarwindpy/plotting/spiral.py | 8 ++++ tests/plotting/test_repr.py | 8 ---- 6 files changed, 88 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ae3def52c..7d85de69a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,8 +57,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `M`/`C`/`S` columns, derived quantities with their units, an `"a+p1"` total, a `Hist2D` and a `Line` fit's `results`. It replaces the tutorial stub. - A summary `repr` for every plot (`Hist1D`, `Hist2D`, `SpiralPlot2D`, `Scatter`), shown by - Jupyter and `print`: the class, the x, y and z labels, the number of rows kept, the log flags, - the bins per axis (or mesh cells for `SpiralPlot2D`), `axnorm`, `clim` and `alim` when set, + Jupyter and `print`: the class; per axis its label, bin count and range (the mesh's extent on a + `SpiralPlot2D`) and the range of the data on it, in data units on a log axis, to four + significant figures (e.g. `x: v bins 60 [250, 900] data [251.3, 898.7]`); the number of rows + kept, the log flags, the bins per axis (or mesh cells), `axnorm`, `clim` and `alim` when set, and `path`. `str(plot)` is that summary, no longer just the class name. - `solarwindpy.core.plasma.Plasma.info` returns a one-column table summarising a plasma: the spacecraft and its frame (or "none"), the first and last observation times, the number of diff --git a/src/solarwindpy/plotting/base.py b/src/solarwindpy/plotting/base.py index 31bdb0377..ca931ae7f 100644 --- a/src/solarwindpy/plotting/base.py +++ b/src/solarwindpy/plotting/base.py @@ -114,15 +114,18 @@ def __init__(self): def __repr__(self): r"""A summary of what the plot holds, one ``key: value`` per line. - The class, then the x and y labels (and z when the plot has one), the - number of rows the plot keeps, the log flags, the fields - ``_repr_fields`` adds (binning, ``axnorm``, ``clim``, ``alim``), and - ``path``. ``print`` shows the same text. + The class, then one line per axis (x, y, and z when the plot has + one): its label, its bins (``_axis_extent``) and the range of the + data on it, then the number of rows the plot keeps, the log flags, + the fields ``_repr_fields`` adds (binning, ``axnorm``, ``clim``, + ``alim``), and ``path``. ``print`` shows the same text. A plot whose + constructor has not run shows its class and "(not built)". """ + if "_labels" not in self.__dict__: + return f"{self.__class__.__name__} (not built)" labels = self._flat_labels() - fields = {k: labels[k] for k in ("x", "y")} - if self._has_z_label(): - fields["z"] = labels["z"] + axes = ["x", "y", "z"] if self._has_z_label() else ["x", "y"] + fields = {k: self._axis_line(k, labels[k]) for k in axes} source = self.__dict__.get("_source") fields["observations"] = "none" if source is None else source.n_kept fields["log"] = ", ".join(f"{k}={v}" for k, v in self.log._asdict().items()) @@ -135,6 +138,42 @@ def _repr_fields(self): r"""Fields a subclass adds to ``repr`` before ``path``, as a dict; none here.""" return {} + def _axis_extent(self, axis): + r"""``(prefix, lower, upper)`` of ``axis``'s bins on the binned scale, or None. + + None here: the plot bins nothing. ``BinnedPlot`` asks its binning. + """ + return None + + def _axis_line(self, axis, label): + r"""One axis's ``repr`` line: label, bin range and data range. + + Ranges are in data units: on a log axis the bins' edges and the binned + ``log10(abs())`` values are shown as 10 to that power, so the data + range is that of ``abs()``. Numbers have four significant figures. + The aggregated column shows no data range when the caller gave none + (a count). + """ + parts = [label] + source = self.__dict__.get("_source") + logged = source is not None and source.is_logged(axis) + + def fmt(v): + return f"{10.0**v if logged else v:.4g}" + + extent = self._axis_extent(axis) + if extent is not None: + prefix, lower, upper = extent + parts.append(f"{prefix} [{fmt(lower)}, {fmt(upper)}]") + if source is not None and axis in source.columns: + coords = source.columns[:-1] + if axis in coords or source.has_value: + values = source.logged(axis, labels=False).to_numpy(dtype=float) + parts.append( + f"data [{fmt(np.nanmin(values))}, {fmt(np.nanmax(values))}]" + ) + return " ".join(parts) + @staticmethod def _format_limits(limits): r"""``RangeLimits`` as ``"lower=..., upper=..."``, or None when both are unset.""" @@ -812,6 +851,11 @@ def binning(self): r"""The ``Binning`` that places each kept row in a cell.""" return self._binning + def _axis_extent(self, axis): + r"""The binning's ``axis_extent``; None before the binning is built.""" + binning = self.__dict__.get("_binning") + return None if binning is None else binning.axis_extent(axis) + def _repr_fields(self): r"""Add the binning, ``axnorm`` and, when set, ``clim`` to ``repr``.""" fields = super()._repr_fields() diff --git a/src/solarwindpy/plotting/binned.py b/src/solarwindpy/plotting/binned.py index 0f294896f..be76bacb2 100644 --- a/src/solarwindpy/plotting/binned.py +++ b/src/solarwindpy/plotting/binned.py @@ -406,6 +406,15 @@ def n_kept(self): r"""Number of rows the plot keeps.""" return self._n_kept + @property + def has_value(self): + r"""True if the caller gave the aggregated column; False for a count.""" + return self._value is not None + + def is_logged(self, col): + r"""True if ``col`` is held as ``log10(abs())``.""" + return bool(self._log.get(col, False)) + @property def log_columns(self): r"""Coordinates given a log setting, True or False, when built. @@ -489,7 +498,7 @@ def logged(self, col, *, labels=True): ``labels`` is True, it shares the source's values and index. """ values = self.take(col, labels=labels) - if self._log.get(col, False): + if self.is_logged(col): values = np.log10(np.abs(values)) return values diff --git a/src/solarwindpy/plotting/binning.py b/src/solarwindpy/plotting/binning.py index 5bab4c9ad..082cf396f 100644 --- a/src/solarwindpy/plotting/binning.py +++ b/src/solarwindpy/plotting/binning.py @@ -60,6 +60,14 @@ def describe(self): r"""One line naming how many cells there are, for a plot's ``repr``.""" return f"{len(self.cells)} cells" + def axis_extent(self, axis): + r"""``(prefix, lower, upper)`` of the cells along ``axis``, for ``repr``. + + On the binned scale (``log10`` on a log axis). None here, and for an + axis the binning does not bin. + """ + return None + def postfilter(self, agg): r"""Drop cells of ``agg``, indexed by cell code, that fail a quality filter. @@ -601,6 +609,13 @@ def describe(self): r"""Bins per axis, e.g. ``"x: 4, y: 3"``, for a plot's ``repr``.""" return ", ".join(f"{k}: {len(self.intervals[k])}" for k in self._axes) + def axis_extent(self, axis): + r"""``("bins n", first edge, last edge)`` of a binned axis, else None.""" + if axis not in self._axes: + return None + edges = self.edges[axis] + return f"bins {len(edges) - 1}", edges[0], edges[-1] + def cell_measure(self): r"""Each bin's width in 1-D, its area in 2-D, on the binned scale.""" widths = [np.asarray(self.intervals[k].length) for k in self._axes] diff --git a/src/solarwindpy/plotting/spiral.py b/src/solarwindpy/plotting/spiral.py index 3579d94a0..87e92f36b 100644 --- a/src/solarwindpy/plotting/spiral.py +++ b/src/solarwindpy/plotting/spiral.py @@ -830,6 +830,14 @@ def describe(self): r"""Number of mesh cells, e.g. ``"52 mesh cells"``, for a plot's ``repr``.""" return f"{self._mesh.mesh.shape[0]} mesh cells" + def axis_extent(self, axis): + r"""``("mesh", lowest edge, highest edge)`` of the mesh along x or y.""" + columns = {"x": (0, 1), "y": (2, 3)}.get(axis) + if columns is None: + return None + m = self._mesh.mesh + return "mesh", m[:, columns[0]].min(), m[:, columns[1]].max() + def codes(self): r"""Cell of each kept row, -1 for a row outside the mesh.""" bin_id = self._mesh.bin_id diff --git a/tests/plotting/test_repr.py b/tests/plotting/test_repr.py index 2da6aa3dc..5c90a8cac 100644 --- a/tests/plotting/test_repr.py +++ b/tests/plotting/test_repr.py @@ -164,10 +164,7 @@ def test_hist1d_z_label_error_still_names_the_class(): # Ranges: each axis line shows its bin range and the range of the data binned # --------------------------------------------------------------------------- -_NO_RANGES = pytest.mark.xfail(strict=True, reason="the repr shows no ranges yet") - -@_NO_RANGES def test_hist2d_axes_show_bin_and_data_ranges_without_the_nan_rows(): """Edges [0, 2, 4, 6] on both axes: 3 bins over [0, 6] each. @@ -183,7 +180,6 @@ def test_hist2d_axes_show_bin_and_data_ranges_without_the_nan_rows(): assert fields["z"] == "z data [1, 6]" -@_NO_RANGES def test_a_log_axis_shows_its_ranges_in_data_units(): """log10 edges [0, 1, 2, 3] are bins over [1, 1000]; x spans 2 to 500. @@ -196,7 +192,6 @@ def test_a_log_axis_shows_its_ranges_in_data_units(): assert fields["x"] == "x bins 3 [1, 1000] data [2, 500]" -@_NO_RANGES def test_numbers_are_shown_to_four_significant_figures(): """x from 251.33 to 898.71 on edges 250 to 900 reads [251.3, 898.7]. @@ -218,7 +213,6 @@ def test_a_count_axis_has_no_data_range(): assert fields["z"] == str(h.labels.z) -@_NO_RANGES def test_spiral_axes_show_the_mesh_extent_and_data_ranges(): """The mesh spans the initial edges, [0, 6] in x and [0, 4] in y. @@ -232,7 +226,6 @@ def test_spiral_axes_show_the_mesh_extent_and_data_ranges(): assert fields["y"] == "y mesh [0, 4.04] data [1, 3.5]" -@_NO_RANGES def test_scatter_axes_show_data_ranges(): """A scatter bins nothing: each axis shows its data range alone. @@ -244,7 +237,6 @@ def test_scatter_axes_show_data_ranges(): assert fields["z"] == "z data [1, 6]" -@_NO_RANGES @pytest.mark.parametrize("cls", [Hist1D, Hist2D, SpiralPlot2D, Scatter]) def test_repr_of_an_unbuilt_plot_does_not_raise(cls): """A plot whose constructor never ran still has a one-line repr. From 521e334f0c8bb38eba76b4e81da3d52693dae18f Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 05:17:31 -0500 Subject: [PATCH 41/60] docs(plotting): qualify the label module's new cross-references The AXNORM and publication-format references in labels.base resolved by short name only; under the docs' nitpicky build a short :func: or :data: target inside a class docstring can resolve to the class member of the same name. They now name the module, and two long docstring lines are rewrapped. Co-Authored-By: Claude Opus 5.5 --- src/solarwindpy/plotting/labels/base.py | 27 +++++++++++++++---------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/src/solarwindpy/plotting/labels/base.py b/src/solarwindpy/plotting/labels/base.py index c416e1038..1a9505ca9 100644 --- a/src/solarwindpy/plotting/labels/base.py +++ b/src/solarwindpy/plotting/labels/base.py @@ -36,9 +36,10 @@ #: the keys ``Count`` and ``TeXlabel`` accept. ``count`` is the words of a #: normalized ``Count``; ``quantity`` the TeX of a normalized quantity, with #: ``%s`` for the quantity's TeX. ``name`` is the plain-text name of a -#: normalized ``Count`` in publication format. ``density`` is True for a density: its units -#: are 1 / (bin width or area in the units of the binned axes, in decades on a -#: log axis), which a label does not know, so it states none. A count divided +#: normalized ``Count`` in publication format. ``density`` is True for a +#: density: its units are 1 / (bin width or area in the units of the binned +#: axes, in decades on a log axis), which a label does not know, so it states +#: none. A count divided #: by a maximum is a pure number and states ``\#``. Every key a binning's #: ``allowed_axnorm`` holds is a key here. AXNORM = MappingProxyType( @@ -79,7 +80,8 @@ #: The module default of ``publication_format``; read and set it with -#: :func:`publication_format` and :func:`set_publication_format`. +#: :func:`~solarwindpy.plotting.labels.base.publication_format` and +#: :func:`~solarwindpy.plotting.labels.base.set_publication_format`. _publication_format = False @@ -87,7 +89,7 @@ def publication_format(): r"""Return the default publication format of every label, True or False. A label whose own ``publication_format`` is None follows it. See - :func:`set_publication_format`. + :func:`~solarwindpy.plotting.labels.base.set_publication_format`. """ return _publication_format @@ -117,7 +119,7 @@ def validate_axnorm(key): TypeError If ``key`` is neither a string nor None. ValueError - If ``key`` is not a key of :data:`AXNORM`. + If ``key`` is not a key of :data:`~solarwindpy.plotting.labels.base.AXNORM`. """ if key is None: return None @@ -305,14 +307,15 @@ def publication_format(self): r"""If True, the label is its name over its symbol line. The label's own setting, or the module default - (:func:`publication_format`) when that is None. + (:func:`~solarwindpy.plotting.labels.base.publication_format`) when that is + None. """ if self._publication_format is None: return publication_format() return self._publication_format def set_publication_format(self, new): - r"""Set this label's publication format: True, False, or None to follow the default.""" + r"""Set this label's publication format: True, False, or None for the default.""" if new is not None: new = bool(new) self._publication_format = new @@ -395,7 +398,7 @@ def __init__( to dimensionless when equal. axnorm : str, optional Axis normalization used when building colorbar labels, a key of - :data:`AXNORM`. + :data:`~solarwindpy.plotting.labels.base.AXNORM`. new_line_for_units : bool, default ``False`` If ``True`` a newline separates label and units. description : str or None, optional @@ -405,7 +408,8 @@ def __init__( registry name, a ratio's " Ratio" or " / ". publication_format : bool or None, optional If True, the label is its name over its symbol line. None follows - the module default, :func:`publication_format`. + the module default, + :func:`~solarwindpy.plotting.labels.base.publication_format`. """ super(TeXlabel, self).__init__() self.set_axnorm(axnorm) @@ -495,7 +499,8 @@ def set_axnorm(self, new): Parameters ---------- new : str, optional - A key of :data:`AXNORM` (case-insensitive), or None. + A key of :data:`~solarwindpy.plotting.labels.base.AXNORM` + (case-insensitive), or None. """ self._axnorm = validate_axnorm(new) From 77631d272a570423c0ec8c67ada87e39f3027561 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 05:21:14 -0500 Subject: [PATCH 42/60] test(plotting): signed values default to a centred diverging scale Target tests, xfail(strict=True) until the change: a Hist2D of signed means under any axnorm, a spiral, a scatter and both contour methods default to a zero-centred norm with RdBu_r. Guards: non-negative values keep the bands, the LogNorm or matplotlib's default, and a caller's norm and cmap win. Co-Authored-By: Claude Opus 5.5 --- tests/plotting/test_color_scale.py | 126 +++++++++++++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 tests/plotting/test_color_scale.py diff --git a/tests/plotting/test_color_scale.py b/tests/plotting/test_color_scale.py new file mode 100644 index 000000000..b22aedc6b --- /dev/null +++ b/tests/plotting/test_color_scale.py @@ -0,0 +1,126 @@ +# Spent-When: PERMANENT(color plots stop choosing a default colour scale) +# Supersedes: none +"""Tests for the default colour scale of the colour plots. + +When the plotted values hold both signs, a ``Hist2D``, ``SpiralPlot2D`` or +``Scatter`` defaults to a zero-centred norm (vcenter 0) and the diverging +colormap ``RdBu_r``. Values of one sign keep the defaults they had: a +``LogNorm`` for densities, colour bands on [0, 1] for row and column norms, +matplotlib's own otherwise. A ``norm`` or ``cmap`` the caller passes always +wins. Contours use the same default. +""" + +import numpy as np +import pandas as pd +import pytest +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt # noqa: E402 +from matplotlib.colors import ( # noqa: E402 + BoundaryNorm, + CenteredNorm, + LogNorm, + Normalize, +) + +from solarwindpy.plotting.hist2d import Hist2D # noqa: E402 +from solarwindpy.plotting.scatter import Scatter # noqa: E402 +from solarwindpy.plotting.spiral import SpiralPlot2D # noqa: E402 + +_NEW = pytest.mark.xfail(strict=True, reason="no signed default colour scale yet") + +RNG = np.random.default_rng(4) +N = 3000 +X = pd.Series(RNG.normal(size=N)) +Y = pd.Series(RNG.normal(size=N)) +SIGNED = pd.Series(RNG.normal(size=N)) # both signs in every cell's mean +POSITIVE = pd.Series(RNG.lognormal(size=N)) + + +@pytest.fixture(autouse=True) +def _close(): + yield + plt.close("all") + + +def _centred(mappable): + norm = mappable.norm + return isinstance(norm, (CenteredNorm,)) and norm.vcenter == 0 + + +def _hist2d(z, **kw): + return Hist2D(X, Y, z, nbins=12, **kw) + + +def _spiral(z): + return SpiralPlot2D(X, Y, z, initial_bins=4, min_per_bin=100) + + +@_NEW +@pytest.mark.parametrize("axnorm", [None, "t", "c", "d"]) +def test_hist2d_of_signed_values_gets_a_centred_diverging_scale(axnorm): + """Signed means get vcenter 0 and RdBu_r, whatever the axnorm. + + ON FAILURE: the code is wrong. + """ + _, pc, _ = _hist2d(SIGNED, axnorm=axnorm).make_plot(cbar=False) + assert _centred(pc) + assert pc.get_cmap().name == "RdBu_r" + + +@_NEW +def test_spiral_and_scatter_of_signed_values_get_a_centred_scale(): + """The same default holds for a spiral mesh and for coloured points. + + ON FAILURE: the code is wrong. + """ + _, collection, _ = _spiral(SIGNED).make_plot(cbar=False) + assert _centred(collection) + assert collection.get_cmap().name == "RdBu_r" + _, points, _ = Scatter(X, Y, SIGNED).make_plot(cbar=False) + assert _centred(points) + assert points.get_cmap().name == "RdBu_r" + + +@_NEW +def test_contours_of_signed_values_get_a_centred_scale(): + """Hist2D and spiral contours default to the centred norm too. + + ON FAILURE: the code is wrong. + """ + _, qset, *_ = _hist2d(SIGNED).plot_contours(cbar=False) + assert _centred(qset) + _, qset, _ = _spiral(SIGNED).plot_contours(cbar=False) + assert _centred(qset) + + +@pytest.mark.parametrize( + "axnorm, kind", + [("c", BoundaryNorm), ("d", LogNorm), (None, Normalize)], + ids=["c", "d", "none"], +) +def test_non_negative_values_keep_todays_defaults(axnorm, kind): + """One-signed values keep the bands, the LogNorm, or matplotlib's default. + + ON FAILURE: the code is wrong. + """ + _, pc, _ = _hist2d(POSITIVE, axnorm=axnorm).make_plot(cbar=False) + assert type(pc.norm) is kind + assert pc.get_cmap().name == plt.rcParams["image.cmap"] + + +@pytest.mark.parametrize( + "build", + [lambda: _hist2d(SIGNED), lambda: _spiral(SIGNED)], + ids=["Hist2D", "SpiralPlot2D"], +) +def test_a_callers_norm_and_cmap_win(build): + """An explicit norm and cmap are used as given, even for signed values. + + ON FAILURE: the code is wrong. + """ + norm = Normalize(-0.5, 0.5) + _, mappable, _ = build().make_plot(cbar=False, norm=norm, cmap="viridis") + assert mappable.norm is norm + assert mappable.get_cmap().name == "viridis" From a6a8cef73e2b5dcb4bf6cf459aba114021b2bff6 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 05:24:43 -0500 Subject: [PATCH 43/60] feat(plotting): a centred diverging default for signed colour values Now that densities and peak norms of signed means are meaningful, the default LogNorm masked their negative cells and the [0, 1] bands clipped them. ColorPlot._color_scale is the one place a colour plot picks norm and cmap: when the plotted values hold both signs it defaults to a CenteredNorm about 0 with RdBu_r, else to _default_norm as before; a caller's norm or cmap (None included) wins. Hist2D make_plot, plot_hist_with_contours and plot_contours, SpiralPlot2D make_plot and plot_contours, and Scatter make_plot all go through it. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 +++ src/solarwindpy/plotting/base.py | 56 +++++++++++++++++++++++++---- src/solarwindpy/plotting/hist2d.py | 34 +++++++++--------- src/solarwindpy/plotting/scatter.py | 3 ++ src/solarwindpy/plotting/spiral.py | 6 ++-- tests/plotting/test_color_scale.py | 5 --- 6 files changed, 77 insertions(+), 32 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d85de69a..b74784b91 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -72,6 +72,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- Colour plots (`Hist2D`, `SpiralPlot2D`, `Scatter`, and their contours) default to a + zero-centred `matplotlib.colors.CenteredNorm` and the diverging colormap `RdBu_r` when the + plotted values hold both signs, whatever the `axnorm`. Values of one sign keep the previous + defaults (bands on [0, 1] for `c`/`r`, `LogNorm` for densities, matplotlib's otherwise). A + `norm` or `cmap` passed by the caller is used as given. - A count in `agg` (`fcn="count"`, or the default on a plot without z) counts each cell's rows with `numpy.bincount` of the rows' cell codes instead of a pandas groupby: same result, about twice as fast at 1e6 rows. diff --git a/src/solarwindpy/plotting/base.py b/src/solarwindpy/plotting/base.py index ca931ae7f..7819f972a 100644 --- a/src/solarwindpy/plotting/base.py +++ b/src/solarwindpy/plotting/base.py @@ -716,24 +716,68 @@ def _apply_alpha_fcn(self, artist, alpha_fcn, face_values): colors[:, 3] = alpha artist.set_facecolor(colors) + #: Default colormap for values of both signs. + _diverging_cmap = "RdBu_r" + + def _color_scale(self, kwargs, values): + r"""Pop ``norm`` and ``cmap`` from ``kwargs``, defaulting them by ``values``. + + The one place every colour plot chooses its colour scale. A ``norm`` + or ``cmap`` in ``kwargs`` is used as given, None included. Otherwise, + when the finite ``values`` hold both signs, the default is a + :class:`~matplotlib.colors.CenteredNorm` about 0 and the diverging + colormap ``_diverging_cmap``; values of one sign get + ``_default_norm`` and matplotlib's colormap. + + Parameters + ---------- + kwargs : dict + The caller's keywords; ``norm`` and ``cmap`` are removed. + values : array-like + The values to colour, NaN or masked where none. + + Returns + ------- + norm, cmap + """ + v = np.ma.filled(np.ma.asarray(values, dtype=float), np.nan) + v = v[np.isfinite(v)] + signed = bool((v < 0).any() and (v > 0).any()) + axnorm = getattr(self, "axnorm", None) + if "norm" in kwargs: + norm = kwargs.pop("norm") + else: + norm = self._default_norm(axnorm, signed) + if "cmap" in kwargs: + cmap = kwargs.pop("cmap") + else: + cmap = self._diverging_cmap if signed else None + return norm, cmap + @staticmethod - def _default_norm(axnorm): + def _default_norm(axnorm, signed=False): r"""The colour normalisation a plot uses when the caller passes no ``norm``. Parameters ---------- axnorm : str or None The plot's ``axnorm``. + signed : bool, default False + True when the values hold both signs. Returns ------- matplotlib.colors.Normalize or None - Column- and row-normalised values lie in [0, 1], so ``"c"`` and - ``"r"`` get ten equal colour bands on [0, 1]. Densities (``"d"``, - ``"cd"``, ``"rd"``) span decades, so they get a clipped - :class:`~matplotlib.colors.LogNorm`. Otherwise None, leaving the - choice to matplotlib. + Values of both signs get a + :class:`~matplotlib.colors.CenteredNorm` about 0, whatever the + ``axnorm``. Otherwise column- and row-normalised values lie in + [0, 1], so ``"c"`` and ``"r"`` get ten equal colour bands on + [0, 1]; densities (``"d"``, ``"cd"``, ``"rd"``) span decades, so + they get a clipped :class:`~matplotlib.colors.LogNorm`; anything + else gets None, leaving the choice to matplotlib. """ + if signed: + return mpl.colors.CenteredNorm(vcenter=0.0) if axnorm in ("c", "r"): return mpl.colors.BoundaryNorm(np.linspace(0, 1, 11), 256, clip=True) if axnorm in ("d", "cd", "rd"): diff --git a/src/solarwindpy/plotting/hist2d.py b/src/solarwindpy/plotting/hist2d.py index 6ce5d6c9b..84d2aaeaf 100644 --- a/src/solarwindpy/plotting/hist2d.py +++ b/src/solarwindpy/plotting/hist2d.py @@ -196,9 +196,11 @@ def make_plot( value; see ``ColorPlot._apply_alpha_fcn``. Ignored, with a warning, when the plot counts points. kwargs: - Passed to `ax.pcolormesh`. `norm` defaults to ten colour bands on - [0, 1] for row or column normalized data and to a `LogNorm` for - densities ("d", "cd", "rd"). + Passed to `ax.pcolormesh`. For values of both signs, `norm` + defaults to a `CenteredNorm` about 0 and `cmap` to "RdBu_r"; + otherwise `norm` defaults to ten colour bands on [0, 1] for row or + column normalized data and to a `LogNorm` for densities ("d", + "cd", "rd"). See ``ColorPlot._color_scale``. Returns ------- @@ -218,11 +220,10 @@ def make_plot( x, y = self._maybe_convert_to_log_scale(x, y) - norm = kwargs.pop("norm", self._default_norm(self.axnorm)) - C = np.ma.masked_invalid(agg.values) + norm, cmap = self._color_scale(kwargs, C) XX, YY = np.meshgrid(x, y) - pc = ax.pcolormesh(XX, YY, C, norm=norm, **kwargs) + pc = ax.pcolormesh(XX, YY, C, norm=norm, cmap=cmap, **kwargs) if cbar: cbar_kwargs = self._prepare_cbar_kwargs(cbar_kwargs, ax) @@ -304,14 +305,12 @@ def plot_hist_with_contours( if contour_kwargs is None: contour_kwargs = {} - norm = kwargs.pop("norm", self._default_norm(self.axnorm)) - - # Get cmap from kwargs (shared between pcolormesh and contour) - cmap = kwargs.pop("cmap", None) - # --- 1. Plot pcolormesh background --- C_edges, x_edges, y_edges = self._prep_agg_for_plot(fcn=fcn, use_edges=True) + # norm and cmap are shared between pcolormesh and contour. + norm, cmap = self._color_scale(kwargs, C_edges) + XX_edges, YY_edges = np.meshgrid(x_edges, y_edges) pc = ax.pcolormesh(XX_edges, YY_edges, C_edges, norm=norm, cmap=cmap, **kwargs) @@ -566,10 +565,12 @@ def plot_contours( matplotlib's choice when there is none. kwargs: Passed to :meth:`matplotlib.axes.Axes.contour` or - :meth:`matplotlib.axes.Axes.contourf`. `norm` defaults to ten - colour bands on [0, 1] for row or column normalized data and to a - `LogNorm` for densities ("d", "cd", "rd"); otherwise, with at - least two levels, to a `BoundaryNorm` on the levels. + :meth:`matplotlib.axes.Axes.contourf`. For values of both signs, + `norm` defaults to a `CenteredNorm` about 0 and `cmap` to + "RdBu_r". Otherwise `norm` defaults to ten colour bands on [0, 1] + for row or column normalized data and to a `LogNorm` for + densities ("d", "cd", "rd"); otherwise, with at least two levels, + to a `BoundaryNorm` on the levels. Returns ------- @@ -578,8 +579,6 @@ def plot_contours( cbar : colorbar.Colorbar or None The colorbar if `cbar` is True, else None. """ - cmap = kwargs.pop("cmap", None) - norm = kwargs.pop("norm", self._default_norm(self.axnorm)) linestyles = kwargs.pop("linestyles", list(self._contour_linestyles)) if ax is None: @@ -612,6 +611,7 @@ def plot_contours( C = gaussian_filter(C, gaussian_filter_std, **gaussian_filter_kwargs) C = np.ma.masked_invalid(C) + norm, cmap = self._color_scale(kwargs, C) assert XX.shape == C.shape assert YY.shape == C.shape diff --git a/src/solarwindpy/plotting/scatter.py b/src/solarwindpy/plotting/scatter.py index a8f26ab11..70f21e9b4 100644 --- a/src/solarwindpy/plotting/scatter.py +++ b/src/solarwindpy/plotting/scatter.py @@ -104,6 +104,9 @@ def make_plot(self, ax=None, cbar=True, cbar_kwargs=None, **kwargs): if data.loc[:, "z"].unique().size > 1: zkey = "z" + kwargs["norm"], kwargs["cmap"] = self._color_scale( + kwargs, data.loc[:, "z"].to_numpy() + ) else: zkey = None diff --git a/src/solarwindpy/plotting/spiral.py b/src/solarwindpy/plotting/spiral.py index 87e92f36b..ab7790835 100644 --- a/src/solarwindpy/plotting/spiral.py +++ b/src/solarwindpy/plotting/spiral.py @@ -1058,8 +1058,7 @@ def make_plot( collection.set_array(C) - cmap = kwargs.pop("cmap", None) - norm = kwargs.pop("norm", self._default_norm(self.axnorm)) + norm, cmap = self._color_scale(kwargs, C) if len(kwargs): raise ValueError(f"Unexpected kwargs {kwargs.keys()}") @@ -1182,12 +1181,11 @@ def plot_contours( >>> splot = SpiralPlot2D(x, y, z, initial_bins=5, min_per_bin=10) >>> ax, qset, cbar = splot.plot_contours(levels=[-0.5, 0.0, 0.5]) """ - cmap = kwargs.pop("cmap", None) - norm = kwargs.pop("norm", self._default_norm(self.axnorm)) linestyles = kwargs.pop("linestyles", list(self._contour_linestyles)) # Get aggregated data and mesh cell centers C = self.agg(fcn=fcn).values + norm, cmap = self._color_scale(kwargs, C) # Cell centers in plot coordinates: log10 on a log axis, as the mesh. tk_finite = np.isfinite(C) diff --git a/tests/plotting/test_color_scale.py b/tests/plotting/test_color_scale.py index b22aedc6b..e57a22778 100644 --- a/tests/plotting/test_color_scale.py +++ b/tests/plotting/test_color_scale.py @@ -28,8 +28,6 @@ from solarwindpy.plotting.scatter import Scatter # noqa: E402 from solarwindpy.plotting.spiral import SpiralPlot2D # noqa: E402 -_NEW = pytest.mark.xfail(strict=True, reason="no signed default colour scale yet") - RNG = np.random.default_rng(4) N = 3000 X = pd.Series(RNG.normal(size=N)) @@ -57,7 +55,6 @@ def _spiral(z): return SpiralPlot2D(X, Y, z, initial_bins=4, min_per_bin=100) -@_NEW @pytest.mark.parametrize("axnorm", [None, "t", "c", "d"]) def test_hist2d_of_signed_values_gets_a_centred_diverging_scale(axnorm): """Signed means get vcenter 0 and RdBu_r, whatever the axnorm. @@ -69,7 +66,6 @@ def test_hist2d_of_signed_values_gets_a_centred_diverging_scale(axnorm): assert pc.get_cmap().name == "RdBu_r" -@_NEW def test_spiral_and_scatter_of_signed_values_get_a_centred_scale(): """The same default holds for a spiral mesh and for coloured points. @@ -83,7 +79,6 @@ def test_spiral_and_scatter_of_signed_values_get_a_centred_scale(): assert points.get_cmap().name == "RdBu_r" -@_NEW def test_contours_of_signed_values_get_a_centred_scale(): """Hist2D and spiral contours default to the centred norm too. From d3aa929dc73307561c582488b227e3b866718810 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 05:27:34 -0500 Subject: [PATCH 44/60] feat(plotting): give a count a symbol line in publication format In publication format a Count's second line repeated its first in other words ("Normalized Count" over "Count / Max [#]"). The count now has a symbol, as every quantity does: N for a plain count, N / N_max for "t", N / N_{max,col} and N / N_{max,row} for "c" and "r", and p, p_col and p_row for the densities. AXNORM carries the symbol beside the name. A count divided by a maximum states [#] and a density states no units, as in the one-line labels, which are unchanged. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 +-- src/solarwindpy/plotting/labels/base.py | 38 +++++++++++++------ src/solarwindpy/plotting/labels/special.py | 12 +++++- .../labels/test_publication_format.py | 36 ++++++++++++------ 4 files changed, 65 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6fda674ce..430fde50f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,9 +25,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `solarwindpy.plotting.labels.base.publication_format`), or per label with `TeXlabel(..., publication_format=True)`, which overrides the default. The name is the registry's; `TeXlabel(..., name="Solar Wind Speed")` replaces it. A ratio reads - " Ratio" or " / ", and `Count` names its normalization ("Count", - "Normalized Count", "Probability Density"). Labels read the default when they render, so - it also applies to plots already built. + " Ratio" or " / ". A `Count` is its normalization's name over a symbol: + "Count" over `N [#]`, "Normalized Count" over `N / N_max [#]`, "Probability Density" over + `p`. Labels read the default when they render, so it also applies to plots already built. ### Changed diff --git a/src/solarwindpy/plotting/labels/base.py b/src/solarwindpy/plotting/labels/base.py index 1a9505ca9..a0a32adf8 100644 --- a/src/solarwindpy/plotting/labels/base.py +++ b/src/solarwindpy/plotting/labels/base.py @@ -30,18 +30,23 @@ _trans_component = quantities.COMPONENTS _inU = quantities.UNIT_TEX -_AxisNorm = namedtuple("_AxisNorm", "count,quantity,density,name") +_AxisNorm = namedtuple("_AxisNorm", "count,quantity,density,name,symbol") #: How a label names each ``axnorm`` key, keyed by the key: the one table of -#: the keys ``Count`` and ``TeXlabel`` accept. ``count`` is the words of a -#: normalized ``Count``; ``quantity`` the TeX of a normalized quantity, with -#: ``%s`` for the quantity's TeX. ``name`` is the plain-text name of a -#: normalized ``Count`` in publication format. ``density`` is True for a -#: density: its units are 1 / (bin width or area in the units of the binned -#: axes, in decades on a log axis), which a label does not know, so it states -#: none. A count divided -#: by a maximum is a pure number and states ``\#``. Every key a binning's -#: ``allowed_axnorm`` holds is a key here. +#: the keys ``Count`` and ``TeXlabel`` accept. A new key a binning accepts +#: needs one entry here. +#: +#: - ``count``: the words of a normalized ``Count``. +#: - ``quantity``: the TeX of a normalized quantity, with ``%s`` for the +#: quantity's TeX. +#: - ``density``: True for a density. Its units are 1 / (bin width or area in +#: the units of the binned axes, in decades on a log axis), which a label +#: does not know, so it states none. A count divided by a maximum is a pure +#: number and states ``\#``. +#: - ``name``: the plain-text name of a normalized ``Count`` in publication +#: format, its first line. +#: - ``symbol``: the TeX symbol of a normalized ``Count`` in publication +#: format, its second line; a plain count is ``N``. AXNORM = MappingProxyType( { "c": _AxisNorm( @@ -49,31 +54,42 @@ r"%s / \mathrm{Column \; Max}", False, "Column-Normalized Count", + r"N / N_{\max,\mathrm{col}}", ), "r": _AxisNorm( "Count / Row Max", r"%s / \mathrm{Row \; Max}", False, "Row-Normalized Count", + r"N / N_{\max,\mathrm{row}}", + ), + "t": _AxisNorm( + "Count / Max", + r"%s / \mathrm{Max}", + False, + "Normalized Count", + r"N / N_{\max}", ), - "t": _AxisNorm("Count / Max", r"%s / \mathrm{Max}", False, "Normalized Count"), "d": _AxisNorm( "Probability Density", r"\mathrm{Density \; of} \; %s", True, "Probability Density", + r"p", ), "cd": _AxisNorm( "Column Probability Density", r"\mathrm{Column \; Density \; of} \; %s", True, "Column Probability Density", + r"p_{\mathrm{col}}", ), "rd": _AxisNorm( "Row Probability Density", r"\mathrm{Row \; Density \; of} \; %s", True, "Row Probability Density", + r"p_{\mathrm{row}}", ), } ) diff --git a/src/solarwindpy/plotting/labels/special.py b/src/solarwindpy/plotting/labels/special.py index 6d8d4017d..883723ceb 100644 --- a/src/solarwindpy/plotting/labels/special.py +++ b/src/solarwindpy/plotting/labels/special.py @@ -273,7 +273,10 @@ def __init__(self, norm=None, description=None): self.build_label() def __str__(self): - result = base.format_with_units(self.tex, self.units) + # In publication format the name line says the words, so the second + # line is the count's symbol rather than the words again. + tex = self.symbol if self.publication_format else self.tex + result = base.format_with_units(tex, self.units) return self._format_with_description(result) @property @@ -281,6 +284,13 @@ def tex(self): r"""TeX of the label, set by ``build_label``.""" return self._tex + @property + def symbol(self): + r"""TeX symbol of the count: ``N``, or the normalization's from ``base.AXNORM``.""" + if self.axnorm is None: + return "N" + return base.AXNORM[self.axnorm].symbol + @property def units(self): r"""TeX of the units: ``\#``, or empty for a density; see ``base.AXNORM``.""" diff --git a/tests/plotting/labels/test_publication_format.py b/tests/plotting/labels/test_publication_format.py index 29d3dd1f9..35d3d3112 100644 --- a/tests/plotting/labels/test_publication_format.py +++ b/tests/plotting/labels/test_publication_format.py @@ -112,7 +112,7 @@ def test_module_default_applies_to_labels_already_built(restore_default): one_line = (str(label), str(count)) base.set_publication_format(True) assert str(label) == "Number Density\n" + one_line[0] - assert str(count) == "Normalized Count\n" + one_line[1] + assert str(count) == "Normalized Count\n" + r"$N / N_{\max} \; \left[\#\right]$" base.set_publication_format(False) assert (str(label), str(count)) == one_line @@ -151,26 +151,38 @@ def test_unregistered_quantity_has_no_name_line(): @pytest.mark.parametrize( - "norm, name", + "norm, name, symbol_line", [ - (None, "Count"), - ("t", "Normalized Count"), - ("c", "Column-Normalized Count"), - ("r", "Row-Normalized Count"), - ("d", "Probability Density"), - ("cd", "Column Probability Density"), - ("rd", "Row Probability Density"), + (None, "Count", r"$N \; \left[\#\right]$"), + ("t", "Normalized Count", r"$N / N_{\max} \; \left[\#\right]$"), + ( + "c", + "Column-Normalized Count", + r"$N / N_{\max,\mathrm{col}} \; \left[\#\right]$", + ), + ( + "r", + "Row-Normalized Count", + r"$N / N_{\max,\mathrm{row}} \; \left[\#\right]$", + ), + ("d", "Probability Density", r"$p$"), + ("cd", "Column Probability Density", r"$p_{\mathrm{col}}$"), + ("rd", "Row Probability Density", r"$p_{\mathrm{row}}$"), ], ) -def test_count_names_follow_the_normalization(norm, name, restore_default): - """``Count`` names its normalization in words, from ``AXNORM``. +def test_count_is_its_name_over_its_symbol(norm, name, symbol_line, restore_default): + r"""A ``Count`` in publication format is its name over the symbol ``N`` or ``p``. + + The second line is a symbol, as for any quantity, rather than the words + of the one-line label, which would repeat the name. A count divided by a + maximum is a pure number, ``\#``; a density states no units. ON FAILURE: the code is wrong. """ base.set_publication_format(True) label = Count(norm) assert label.name == name - assert str(label).split("\n")[0] == name + assert str(label) == f"{name}\n{symbol_line}" @pytest.mark.parametrize( From 760a3fe01e9be3916d7283a05c05d96cb4a917fb Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 05:31:25 -0500 Subject: [PATCH 45/60] test(plotting): Hist1D takes the alim every binned plot has Target tests, xfail(strict=True) until alim moves to a shared home: alim masks Hist1D bins after axnorm, as values or quantiles, get_plotted_data honours it, the repr shows it, and Hist1D, Hist2D and Scatter share one set_alim, _apply_alim, alim and alim_kind. Co-Authored-By: Claude Opus 5.5 --- tests/plotting/test_hist1d_alim.py | 95 ++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 tests/plotting/test_hist1d_alim.py diff --git a/tests/plotting/test_hist1d_alim.py b/tests/plotting/test_hist1d_alim.py new file mode 100644 index 000000000..39aca4018 --- /dev/null +++ b/tests/plotting/test_hist1d_alim.py @@ -0,0 +1,95 @@ +# Spent-When: PERMANENT(Hist1D stops offering alim) +# Supersedes: none +"""Tests for ``alim`` on ``Hist1D``, the same limits every binned plot has. + +``alim`` limits the aggregated value of a bin after ``axnorm`` and ``clim``, +bounds inclusive, read as values or as quantiles of the aggregated values. +The bins below hold 3, 2 and 1 rows by hand (edges 0, 1, 2, 3, right-closed). +""" + +import numpy as np +import pandas as pd +import pytest +import matplotlib + +matplotlib.use("Agg") + +from solarwindpy.plotting.hist1d import Hist1D # noqa: E402 +from solarwindpy.plotting.hist2d import Hist2D # noqa: E402 +from solarwindpy.plotting.scatter import Scatter # noqa: E402 +from tests.tolerances import exact # noqa: E402 + +_NEW = pytest.mark.xfail(strict=True, reason="Hist1D has no alim yet") + +X = pd.Series([0.2, 0.5, 0.8, 1.3, 1.7, 2.5], index=[10, 11, 12, 13, 14, 15]) +EDGES = np.array([0.0, 1.0, 2.0, 3.0]) + + +def _hist(): + return Hist1D(X, nbins=EDGES) + + +@_NEW +def test_alim_masks_the_bins_outside_it(): + """alim (2, None) keeps the bins of 3 and 2 rows; the bin of 1 is NaN. + + ON FAILURE: the code is wrong. + """ + h = _hist() + h.set_alim(2, None) + assert h.agg().to_numpy() == exact([3.0, 2.0, np.nan], nan_ok=True) + + +@_NEW +def test_alim_applies_after_axnorm(): + """With axnorm "t" the bins read 1, 2/3, 1/3; alim (0.5, None) keeps two. + + ON FAILURE: the code is wrong. + """ + h = _hist() + h.set_axnorm("t") + h.set_alim(0.5, None) + assert h.agg().to_numpy() == exact([1.0, 2.0 / 3.0, np.nan], nan_ok=True) + + +@_NEW +def test_get_plotted_data_honours_alim(): + """The rows of the bins alim keeps: labels 10 to 14. + + ON FAILURE: the code is wrong. + """ + h = _hist() + h.set_alim(2, None) + assert h.get_plotted_data().index.tolist() == [10, 11, 12, 13, 14] + + +@_NEW +def test_a_quantile_alim_reads_quantiles_of_the_bins(): + """The 0.5 quantile of the counts 3, 2, 1 is 2: the upper bound keeps 2 and 1. + + ON FAILURE: the code is wrong. + """ + h = _hist() + h.set_alim(None, 0.5, kind="quantile") + assert h.agg().to_numpy() == exact([np.nan, 2.0, 1.0], nan_ok=True) + + +@_NEW +def test_every_plot_shares_one_alim(): + """Hist1D, Hist2D and Scatter set and apply alim with the same methods. + + ON FAILURE: the code is wrong. + """ + for name in ("set_alim", "_apply_alim", "alim", "alim_kind"): + assert getattr(Hist1D, name) is getattr(Hist2D, name) is getattr(Scatter, name) + + +@_NEW +def test_hist1d_repr_shows_its_alim(): + """A set alim appears in the repr, as on the colour plots. + + ON FAILURE: the code is wrong. + """ + h = _hist() + h.set_alim(2, None) + assert " alim: lower=2, upper=None (value)" in repr(h).splitlines() From 7ec0d304efeff406869e2a7e55dc5200a1ef6604 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 05:33:37 -0500 Subject: [PATCH 46/60] fix(plotting): state a density's units from the plot's binned axes A density Count label stated no units. binning.normalize divides a density by the measure of the bins it is taken over: "d" by each cell's width or area, "cd" by the y-widths within a column, "rd" by the x-widths within a row, measured in log10 on a log axis. One helper, labels.base.density_units, now builds the inverse of each such axis's units from its label, dex^-1 for a log axis, and omits an axis whose label states no units. AXNORM records the axes each density is per. BinnedPlot hands its binned axes' labels and log scales to its Count in _count_with_axnorm, and set_labels now updates the Count after storing the labels, so the units follow labels set after the plot is built. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 +- docs/source/usage.rst | 5 +- src/solarwindpy/plotting/base.py | 21 ++-- src/solarwindpy/plotting/labels/base.py | 59 ++++++++++- src/solarwindpy/plotting/labels/special.py | 13 ++- tests/plotting/test_density_units.py | 118 +++++++++++++++++++++ 6 files changed, 205 insertions(+), 18 deletions(-) create mode 100644 tests/plotting/test_density_units.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 430fde50f..d75a333cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -70,9 +70,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 The temperature anisotropy `R` states it too, in place of `\perp/\parallel`. - Normalized labels say what the normalization is. `axnorm="t"` reads "Count / Max" (was "Total Norm Count"), `"c"` and `"r"` "Count / Column Max" and "Count / Row Max"; a - normalized quantity reads `n_p / \mathrm{Max}`. A density no longer claims `\#` units: its - units are 1 / (bin width or area in the axes' units), which a label does not know, so it - states none. `"cd"` and `"rd"` read "Column Probability Density" and "Row Probability + normalized quantity reads `n_p / \mathrm{Max}`. A density's `Count` label no longer claims + `\#` units: it states the inverse of the bins it is per, from the plot's axis labels, e.g. + `(km s^-1)^-1 (cm^-3)^-1` for `"d"` on a 2-D plot, `dex^-1` for a log axis; an axis whose + label states no units contributes nothing. `"cd"` and `"rd"` read "Column Probability Density" and "Row Probability Density" (both were "1D Probability Density"), and `TeXlabel(..., axnorm="d")` reads "Density of n_p" (was "Density Norm n_p [#]"). A normalized ratio groups the ratio: `(n_a/n_p) / \mathrm{Max}`. diff --git a/docs/source/usage.rst b/docs/source/usage.rst index 683f6ed52..9820b2a5f 100644 --- a/docs/source/usage.rst +++ b/docs/source/usage.rst @@ -434,8 +434,9 @@ A plot labels its axes ``x``, ``y`` and ``z`` until ``set_labels`` sets them. A histogram's counts carry the special label :py:class:`~solarwindpy.plotting.labels.special.Count`, which follows the plot's ``axnorm``. A count divided by a maximum is a pure number, :math:`[\#]`; -a density is per unit width or area of the bins, in the axes' units, so its -label states no units: +a density is per unit width or area of the bins, so its label states the +inverse of the binned axes' units, :math:`\mathrm{dex}^{-1}` for a log axis. Here +the axes are labelled by plain strings, which state no units: >>> from solarwindpy.plotting.hist2d import Hist2D >>> h2 = Hist2D(v, (2 * v).rename("y"), axnorm="t") diff --git a/src/solarwindpy/plotting/base.py b/src/solarwindpy/plotting/base.py index a217e1c2a..e5eb92d86 100644 --- a/src/solarwindpy/plotting/base.py +++ b/src/solarwindpy/plotting/base.py @@ -764,22 +764,31 @@ def set_axnorm(self, new): self._count_with_axnorm(getattr(self.labels, self.agg_axes)) def _count_with_axnorm(self, label): - r"""Rebuild ``label`` with ``axnorm`` if it is a ``Count``; return it.""" + r"""Rebuild ``label`` with ``axnorm`` and the binned axes if it is a ``Count``. + + The binned axes' labels and log scales give a density its units; see + ``labels.base.density_units``. Returns ``label``. + """ if isinstance(label, labels.special.Count): label.set_axnorm(self.axnorm) + label.set_binned_axes( + { + axis: (getattr(self.labels, axis), getattr(self.log, axis)) + for axis in self._source.columns + if axis != self.agg_axes + } + ) label.build_label() return label def set_labels(self, **kwargs): r"""Set axis labels; a ``Count`` label of the aggregated axis follows ``axnorm``. - See ``Base.set_labels``. + The ``Count`` is updated after the labels are set, so a density's + units follow new labels of the binned axes. See ``Base.set_labels``. """ - axis = self.agg_axes - kwargs[axis] = self._count_with_axnorm( - kwargs.get(axis, getattr(self.labels, axis)) - ) super().set_labels(**kwargs) + self._count_with_axnorm(getattr(self.labels, self.agg_axes)) @staticmethod def _validate_axnorm(new, allowed): diff --git a/src/solarwindpy/plotting/labels/base.py b/src/solarwindpy/plotting/labels/base.py index a0a32adf8..eedfcac5a 100644 --- a/src/solarwindpy/plotting/labels/base.py +++ b/src/solarwindpy/plotting/labels/base.py @@ -5,6 +5,7 @@ "AXNORM", "Base", "TeXlabel", + "density_units", "format_with_units", "publication_format", "set_publication_format", @@ -30,7 +31,7 @@ _trans_component = quantities.COMPONENTS _inU = quantities.UNIT_TEX -_AxisNorm = namedtuple("_AxisNorm", "count,quantity,density,name,symbol") +_AxisNorm = namedtuple("_AxisNorm", "count,quantity,density,name,symbol,per") #: How a label names each ``axnorm`` key, keyed by the key: the one table of #: the keys ``Count`` and ``TeXlabel`` accept. A new key a binning accepts @@ -39,14 +40,16 @@ #: - ``count``: the words of a normalized ``Count``. #: - ``quantity``: the TeX of a normalized quantity, with ``%s`` for the #: quantity's TeX. -#: - ``density``: True for a density. Its units are 1 / (bin width or area in -#: the units of the binned axes, in decades on a log axis), which a label -#: does not know, so it states none. A count divided by a maximum is a pure -#: number and states ``\#``. +#: - ``density``: True for a density. Its units are the inverse of the bin +#: measure it is taken over; see ``per``. A count divided by a maximum is a +#: pure number and states ``\#``. #: - ``name``: the plain-text name of a normalized ``Count`` in publication #: format, its first line. #: - ``symbol``: the TeX symbol of a normalized ``Count`` in publication #: format, its second line; a plain count is ``N``. +#: - ``per``: the binned axes a density is per, as ``binning.normalize`` +#: divides by their widths; empty for a normalization that is no density. +#: :func:`~solarwindpy.plotting.labels.base.density_units` reads it. AXNORM = MappingProxyType( { "c": _AxisNorm( @@ -55,6 +58,7 @@ False, "Column-Normalized Count", r"N / N_{\max,\mathrm{col}}", + (), ), "r": _AxisNorm( "Count / Row Max", @@ -62,6 +66,7 @@ False, "Row-Normalized Count", r"N / N_{\max,\mathrm{row}}", + (), ), "t": _AxisNorm( "Count / Max", @@ -69,6 +74,7 @@ False, "Normalized Count", r"N / N_{\max}", + (), ), "d": _AxisNorm( "Probability Density", @@ -76,6 +82,7 @@ True, "Probability Density", r"p", + ("x", "y"), ), "cd": _AxisNorm( "Column Probability Density", @@ -83,6 +90,7 @@ True, "Column Probability Density", r"p_{\mathrm{col}}", + ("y",), ), "rd": _AxisNorm( "Row Probability Density", @@ -90,6 +98,7 @@ True, "Row Probability Density", r"p_{\mathrm{row}}", + ("x",), ), } ) @@ -127,6 +136,46 @@ def set_publication_format(on): _publication_format = bool(on) +def density_units(axnorm, axes): + r"""Return the TeX units of the ``axnorm`` density over the binned ``axes``. + + A density is divided by the measure of the bins it is taken over (see + ``AXNORM[axnorm].per``), so its units are the inverse of each such axis's + units, joined by ``\,``: ``\left(u\right)^{-1}`` for a linear axis whose + label states units ``u``, and ``\mathrm{dex}^{-1}`` for a log axis, whose + bins are measured in ``log10``. An axis whose label states no units (a + plain string, no ``units``, ``???``) or is dimensionless contributes no + factor, so the result is empty when no axis does. + + Parameters + ---------- + axnorm : str or None + A key of ``AXNORM``, or None. + axes : dict + Each binned axis, ``"x"`` or ``"y"``, mapped to ``(label, log)``: its + label and whether it is on a log scale. + + Returns + ------- + str + The units, or ``""`` when ``axnorm`` is no density. + """ + if axnorm is None or not AXNORM[axnorm].density: + return "" + factors = [] + for axis in AXNORM[axnorm].per: + if axis not in axes: + continue + label, log = axes[axis] + if log: + factors.append(r"\mathrm{dex}^{-1}") + continue + units = getattr(label, "units", "") + if units and units not in ("???", _inU["dimless"]): + factors.append(r"\left(%s\right)^{-1}" % units) + return r" \, ".join(factors) + + def validate_axnorm(key): r"""Return the ``axnorm`` key ``key`` in lower case, or None for None. diff --git a/src/solarwindpy/plotting/labels/special.py b/src/solarwindpy/plotting/labels/special.py index 883723ceb..baa42a595 100644 --- a/src/solarwindpy/plotting/labels/special.py +++ b/src/solarwindpy/plotting/labels/special.py @@ -269,6 +269,7 @@ def __init__(self, norm=None, description=None): """ super().__init__() self.set_axnorm(norm) + self.set_binned_axes({}) self.set_description(description) self.build_label() @@ -293,11 +294,19 @@ def symbol(self): @property def units(self): - r"""TeX of the units: ``\#``, or empty for a density; see ``base.AXNORM``.""" + r"""TeX of the units: ``\#``, or a density's from ``base.density_units``. + + A density's units are those of the binned axes ``set_binned_axes`` + gave; without them it states none. + """ if self.axnorm is not None and base.AXNORM[self.axnorm].density: - return "" + return base.density_units(self.axnorm, self._binned_axes) return base._inU["dimless"] + def set_binned_axes(self, axes): + r"""Store the plot's binned axes, ``{axis: (label, log)}``, for density units.""" + self._binned_axes = dict(axes) + @property def path(self): r"""Save path, set by ``build_label``.""" diff --git a/tests/plotting/test_density_units.py b/tests/plotting/test_density_units.py new file mode 100644 index 000000000..0623b3374 --- /dev/null +++ b/tests/plotting/test_density_units.py @@ -0,0 +1,118 @@ +# Spent-When: PERMANENT(the repository stops maintaining a test suite) +# Supersedes: none +r"""A density's ``Count`` label states the units of the bins it is per. + +``binning.normalize`` divides a density by the bin measure it is taken over: +"d" by each cell's width (1-D) or area (2-D), "cd" by each row's y-width +within a column, "rd" by each column's x-width within a row. On a log axis the +bins are measured in ``log10`` of the data. So the density's units are the +inverse of each such axis's units, ``dex^{-1}`` for a log axis, and an axis +whose label states no units contributes no factor. +""" + +import numpy as np +import pandas as pd +import pytest + +from solarwindpy.plotting.hist1d import Hist1D +from solarwindpy.plotting.hist2d import Hist2D +from solarwindpy.plotting.labels.base import TeXlabel +from solarwindpy.plotting.spiral import SpiralPlot2D + +KMS = r"\left(\mathrm{km \; s^{-1}}\right)^{-1}" +PER_CC = r"\left(\mathrm{cm}^{-3}\right)^{-1}" +DEX = r"\mathrm{dex}^{-1}" +V = TeXlabel(("v", "", "p1")) +N = TeXlabel(("n", "", "p1")) + + +def _data(): + rng = np.random.default_rng(3) + v = pd.Series(rng.normal(400, 50, 2000), name="v") + n = pd.Series(10 ** rng.normal(0.8, 0.2, 2000), name="n") + return v, n + + +@pytest.mark.parametrize( + "axnorm, logy, units", + [ + ("d", False, rf"{KMS} \, {PER_CC}"), + ("d", True, rf"{KMS} \, {DEX}"), + ("cd", False, PER_CC), + ("cd", True, DEX), + ("rd", True, KMS), + ], +) +def test_hist2d_density_units(axnorm, logy, units): + """A 2-D density is per x and y units; "cd" per y, "rd" per x. + + ON FAILURE: the code is wrong. + """ + v, n = _data() + h = Hist2D(v, n, logy=logy, nbins=10, axnorm=axnorm) + h.set_labels(x=V, y=N) + assert h.labels.z.units == units + assert str(h.labels.z).endswith(r"\; \left[%s\right]$" % units) + + +@pytest.mark.parametrize("logx, units", [(False, KMS), (True, DEX)]) +def test_hist1d_density_units(logx, units): + """A 1-D density is per x units, or per dex on a log axis. + + ON FAILURE: the code is wrong. + """ + v, _ = _data() + h = Hist1D(v, logx=logx, nbins=10, axnorm="d") + h.set_labels(x=V) + assert h.labels.y.units == units + + +def test_spiral_density_units(): + """An adaptive-mesh density is per cell area, x units times y units. + + ON FAILURE: the code is wrong. + """ + v, n = _data() + sp = SpiralPlot2D(v, n, logy=True, axnorm="d", min_per_bin=100) + sp.set_labels(x=V, y=N) + assert sp.labels.z.units == rf"{KMS} \, {DEX}" + + +def test_axis_without_units_contributes_no_factor(): + """An axis labelled by a plain string has no known units; it is left out. + + A log axis is per dex whatever its label. + + ON FAILURE: the code is wrong. + """ + v, n = _data() + linear = Hist2D(v, n, nbins=10, axnorm="d") + assert linear.labels.z.units == "" + assert str(linear.labels.z) == r"$\mathrm{Probability \, Density}$" + logy = Hist2D(v, n, logy=True, nbins=10, axnorm="d") + assert logy.labels.z.units == DEX + + +def test_units_follow_axis_labels_set_later(): + """Setting the axis labels after the plot is built updates the density units. + + ON FAILURE: the code is wrong. + """ + v, n = _data() + h = Hist2D(v, n, nbins=10, axnorm="d") + assert h.labels.z.units == "" + h.set_labels(x=V) + assert h.labels.z.units == KMS + h.set_labels(y=N) + assert h.labels.z.units == rf"{KMS} \, {PER_CC}" + + +def test_non_density_normalizations_are_unchanged(): + """A count divided by a maximum stays a pure number. + + ON FAILURE: the code is wrong. + """ + v, n = _data() + h = Hist2D(v, n, nbins=10, axnorm="t") + h.set_labels(x=V, y=N) + assert h.labels.z.units == r"\#" From 28131d4c7ca1451a54ac5221ed26d44bc7029858 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 05:35:53 -0500 Subject: [PATCH 47/60] refactor(plotting): one alim for every plot, Hist1D included alim lived on ColorPlot, so a Hist1D had none and a threshold on a normalized or non-count Hist1D had no replacement for the removed get_subset_above_threshold. alim, alim_kind, set_alim, _apply_alim and the repr field move to _AggregateLimits, the base of both ColorPlot and BinnedPlot; BinnedPlot._limit_values applies alim after axnorm and clim, and Scatter still applies it to each point's z. Hist2D and SpiralPlot2D behave as before. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 12 +++--- src/solarwindpy/plotting/base.py | 66 +++++++++++++++++------------- tests/plotting/test_hist1d_alim.py | 9 ---- 3 files changed, 45 insertions(+), 42 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b74784b91..d597bc3bf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,11 +23,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 index, as the subset did; for a boolean mask on a unique index use `data.index.isin(plot.get_plotted_data().index)`. `get_subset_above_threshold(t)` compared each cell's aggregate after `axnorm`: with no - `axnorm` and a count, it is `plot.set_clim(t, None)` then `plot.get_plotted_data()`; on a - `Hist2D` or `SpiralPlot2D` with an `axnorm` or another `fcn`, use `plot.set_alim(t, None)` - then `plot.get_plotted_data(fcn)`. A `Hist1D` has no `alim`, so a threshold on a normalized or - non-count `Hist1D` has no direct replacement: filter `plot.agg(fcn)` and select the rows of - the kept bins through `plot.cut`. + `axnorm` and a count, it is `plot.set_clim(t, None)` then `plot.get_plotted_data()`; with an + `axnorm` or another `fcn`, use `plot.set_alim(t, None)` then `plot.get_plotted_data(fcn)` on + any binned plot, `Hist1D` included. - `Hist1D.take_data_in_yrange_across_x` calls `get_y_bounds(row, expected_logy=False)`, as `Hist2D`'s calls it with its log flag; a callback written as `lambda row: ...` raises `TypeError`. Accept the keyword, e.g. `lambda row, expected_logy=False: ...`. `Hist1D` and @@ -69,6 +67,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 cells the figure shows (cells whose `agg(fcn)` is not NaN after `clim`, `axnorm`, any cell filter and `alim`), with the caller's x, y and z values on the caller's index. Pass the `fcn` given to `make_plot`. Each plot computes its rows' cell codes once and reuses them in `agg`. +- `Hist1D.set_alim` (with `alim` and `alim_kind`): the limits on the aggregated value of a bin, + after `axnorm` and `clim`, as on `Hist2D` and `SpiralPlot2D`, which `get_plotted_data` + honours. Every plot with `alim` now shares one implementation; `Scatter` still applies it to + the z of each point. ### Changed diff --git a/src/solarwindpy/plotting/base.py b/src/solarwindpy/plotting/base.py index 7819f972a..7dcd95b31 100644 --- a/src/solarwindpy/plotting/base.py +++ b/src/solarwindpy/plotting/base.py @@ -488,28 +488,16 @@ def make_plot(self): pass -class ColorPlot(Base): - r"""Base for plots of x and y coloured by a z value, with a colorbar. +class _AggregateLimits(Base): + r"""``alim``: limits on a plot's aggregated or coloured values. - Holds the data intake of (x, y, z), the z label the colorbar shows, and - ``alim``, the limits on the coloured values. + The one home of ``alim`` for every plot that has it. A ``BinnedPlot`` + applies it to each cell's aggregated value (``_limit_values``); a + ``Scatter`` to the z of each point. """ _alim = RangeLimits(None, None) _alim_kind = "value" - #: Default linestyles of the contour levels, cycled when there are more. - _contour_linestyles = ( - "-", - ":", - "--", - (0, (7, 3, 1, 3, 1, 3, 1, 3, 1, 3)), - "--", - ":", - "-", - (0, (7, 3, 1, 3, 1, 3)), - ) - # True where ``_set_data`` stores x and y as ``log10(abs())`` per ``self.log``. - _log_data = False @property def alim(self): @@ -613,9 +601,28 @@ def _apply_alim(self, agg): return agg.where(keep) - def _limit_values(self, agg): - r"""Apply ``alim`` to the aggregated values; see ``BinnedPlot.agg``.""" - return self._apply_alim(agg) + +class ColorPlot(_AggregateLimits): + r"""Base for plots of x and y coloured by a z value, with a colorbar. + + Holds the data intake of (x, y, z) and the z label the colorbar shows; + ``alim``, the limits on the coloured values, comes from + ``_AggregateLimits``. + """ + + #: Default linestyles of the contour levels, cycled when there are more. + _contour_linestyles = ( + "-", + ":", + "--", + (0, (7, 3, 1, 3, 1, 3, 1, 3, 1, 3)), + "--", + ":", + "-", + (0, (7, 3, 1, 3, 1, 3)), + ) + # True where ``_set_data`` stores x and y as ``log10(abs())`` per ``self.log``. + _log_data = False def _set_data(self, x, y, z=None, clip=None, mask=None, within=None): r"""Store x, y and z as the plot's source, keeping rows without NaN or inf. @@ -877,14 +884,14 @@ def _make_cbar(self, mappable, **kwargs): return cbar -class BinnedPlot(Base): +class BinnedPlot(_AggregateLimits): r"""Base for plots that aggregate a value in the cells of a ``Binning``. The plot's ``binning`` places each kept row in one cell. ``agg`` groups the aggregated column by cell, applies ``clim`` to the count in each cell, drops the cells the binning filters out, normalizes by ``axnorm`` - with the cells' measure, and returns every cell. A ``ColorPlot`` then - applies ``alim``. + with the cells' measure, applies ``alim`` to the result, and returns + every cell. """ _axnorm = None @@ -910,6 +917,9 @@ def _repr_fields(self): clim = self._format_limits(self.clim) if clim is not None: fields["clim"] = clim + if "alim" in fields: + # Show alim after clim, the order they apply in. + fields["alim"] = fields.pop("alim") return fields @property @@ -1040,8 +1050,8 @@ def _grouped_by_cell(self): return target.groupby(codes) def _limit_values(self, agg): - r"""Limits on the final aggregated values: none here; ``ColorPlot`` has ``alim``.""" - return agg + r"""Apply ``alim`` to the final aggregated values; see ``agg``.""" + return self._apply_alim(agg) def agg(self, fcn=None, **kwargs): r"""Aggregate the values in each cell. @@ -1055,7 +1065,7 @@ def agg(self, fcn=None, **kwargs): binning's ``postfilter`` drops. The occupied cells are then normalized by ``axnorm`` (``binning.normalize``). Every cell is in the result, indexed by ``binning.cells``; a cell no row falls in is - NaN. A ``ColorPlot`` then sets the cells outside ``alim`` to NaN. + NaN. The cells outside ``alim`` are then set to NaN. How ``axnorm`` treats the result depends on the aggregation, which is classified as a count (``"count"``), a sum (``"sum"`` or @@ -1165,8 +1175,8 @@ def get_plotted_data(self, fcn=None): r"""The rows in the cells the figure shows. A cell is shown when ``agg(fcn)`` is not NaN there: after ``clim``, - ``axnorm``, any cell filter (a spiral mesh's ``cell_filter``) and, on - a ``ColorPlot``, ``alim``. ``alim`` acts on the aggregated value, so + ``axnorm``, any cell filter (a spiral mesh's ``cell_filter``) and + ``alim``. ``alim`` acts on the aggregated value, so pass the ``fcn`` you gave ``make_plot``; the default is the same as ``make_plot``'s. diff --git a/tests/plotting/test_hist1d_alim.py b/tests/plotting/test_hist1d_alim.py index 39aca4018..d6afce7a9 100644 --- a/tests/plotting/test_hist1d_alim.py +++ b/tests/plotting/test_hist1d_alim.py @@ -9,7 +9,6 @@ import numpy as np import pandas as pd -import pytest import matplotlib matplotlib.use("Agg") @@ -19,8 +18,6 @@ from solarwindpy.plotting.scatter import Scatter # noqa: E402 from tests.tolerances import exact # noqa: E402 -_NEW = pytest.mark.xfail(strict=True, reason="Hist1D has no alim yet") - X = pd.Series([0.2, 0.5, 0.8, 1.3, 1.7, 2.5], index=[10, 11, 12, 13, 14, 15]) EDGES = np.array([0.0, 1.0, 2.0, 3.0]) @@ -29,7 +26,6 @@ def _hist(): return Hist1D(X, nbins=EDGES) -@_NEW def test_alim_masks_the_bins_outside_it(): """alim (2, None) keeps the bins of 3 and 2 rows; the bin of 1 is NaN. @@ -40,7 +36,6 @@ def test_alim_masks_the_bins_outside_it(): assert h.agg().to_numpy() == exact([3.0, 2.0, np.nan], nan_ok=True) -@_NEW def test_alim_applies_after_axnorm(): """With axnorm "t" the bins read 1, 2/3, 1/3; alim (0.5, None) keeps two. @@ -52,7 +47,6 @@ def test_alim_applies_after_axnorm(): assert h.agg().to_numpy() == exact([1.0, 2.0 / 3.0, np.nan], nan_ok=True) -@_NEW def test_get_plotted_data_honours_alim(): """The rows of the bins alim keeps: labels 10 to 14. @@ -63,7 +57,6 @@ def test_get_plotted_data_honours_alim(): assert h.get_plotted_data().index.tolist() == [10, 11, 12, 13, 14] -@_NEW def test_a_quantile_alim_reads_quantiles_of_the_bins(): """The 0.5 quantile of the counts 3, 2, 1 is 2: the upper bound keeps 2 and 1. @@ -74,7 +67,6 @@ def test_a_quantile_alim_reads_quantiles_of_the_bins(): assert h.agg().to_numpy() == exact([np.nan, 2.0, 1.0], nan_ok=True) -@_NEW def test_every_plot_shares_one_alim(): """Hist1D, Hist2D and Scatter set and apply alim with the same methods. @@ -84,7 +76,6 @@ def test_every_plot_shares_one_alim(): assert getattr(Hist1D, name) is getattr(Hist2D, name) is getattr(Scatter, name) -@_NEW def test_hist1d_repr_shows_its_alim(): """A set alim appears in the repr, as on the colour plots. From d466c357254b79956f6057732508ba5635c26418 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 05:39:36 -0500 Subject: [PATCH 48/60] docs: let the show-inheritance line name the private alim base ColorPlot and BinnedPlot now derive from the private _AggregateLimits, which the strict build could not link. It joins _OnFixedGrid and _ComponentFrame in nitpick_ignore, with the same reason. Co-Authored-By: Claude Opus 5.5 --- docs/source/conf.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/source/conf.py b/docs/source/conf.py index 2af0b693d..91248dea1 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -179,6 +179,9 @@ # Private names are not documented, so the show-inheritance line cannot # link it. ("py:class", "solarwindpy.plotting.base._OnFixedGrid"), + # Private base holding ``alim`` for plotting.base.ColorPlot and BinnedPlot, + # named on their show-inheritance line for the same reason. + ("py:class", "solarwindpy.plotting.base._AggregateLimits"), # Private base of core.vector.Vector and core.tensor.Tensor, named on # their show-inheritance line for the same reason. ("py:class", "solarwindpy.core.base._ComponentFrame"), From 982cd6e4f2b84116d7930d67b993abf14fd60ecd Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 05:41:59 -0500 Subject: [PATCH 49/60] refactor(plotting)!: merge a label's description into its name A label had two optional lines above its symbol: description, printed in every format, and name, printed in publication format. They are one concept, the label's first line, so description is removed: the description= keyword of every label class, the description property, set_description and its rendering path. Every label class now takes name= and publication_format=, and Base._format_with_name prints the name above the label in publication format. BREAKING CHANGE: description= is removed from every plot label class. Migrate description="text" to name="text", publication_format=True. The name is not printed in the default one-line format. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 + src/solarwindpy/plotting/labels/base.py | 45 ++---- .../plotting/labels/composition.py | 22 ++- src/solarwindpy/plotting/labels/datetime.py | 63 +++++--- .../plotting/labels/elemental_abundance.py | 12 +- src/solarwindpy/plotting/labels/special.py | 145 ++++++++++++------ tests/plotting/labels/test_labels_base.py | 128 +++++----------- .../labels/test_publication_format.py | 12 +- tests/plotting/labels/test_special.py | 83 ++++++---- tests/plotting/test_integration.py | 2 +- 10 files changed, 263 insertions(+), 256 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d75a333cd..1ca872a77 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Removed +- BREAKING: the `description=` keyword, `description` property and `set_description` of every + plot label class. A label's one optional first line is now its `name`, which the + publication format prints above the symbol line; every label class takes `name=` and + `publication_format=`. Migrate `description="text"` to `name="text", + publication_format=True` (or `set_publication_format(True)` for every label). Unlike a + description, the name is not printed in the default one-line format. + - The GitHub Pages deployment of the documentation (the `deploy` job in `.github/workflows/docs.yml`). The workflow still builds the docs with warnings as errors on every push and pull request. diff --git a/src/solarwindpy/plotting/labels/base.py b/src/solarwindpy/plotting/labels/base.py index eedfcac5a..202ad50a5 100644 --- a/src/solarwindpy/plotting/labels/base.py +++ b/src/solarwindpy/plotting/labels/base.py @@ -298,7 +298,6 @@ class Base(ABC): def __init__(self): """Initialize the logger.""" self._init_logger() - self._description = None def __str__(self): return self.with_units @@ -329,23 +328,6 @@ def _init_logger(self, handlers=None): logger = logging.getLogger("{}.{}".format(__name__, self.__class__.__name__)) self._logger = logger - @property - def description(self): - """Optional human-readable description shown above the label.""" - return self._description - - def set_description(self, new): - """Set the description string. - - Parameters - ---------- - new : str or None - Human-readable description. None disables the description. - """ - if new is not None: - new = str(new) - self._description = new - @property def name(self): r"""Plain-text name, the first line in publication format, or None. @@ -385,8 +367,8 @@ def set_publication_format(self, new): new = bool(new) self._publication_format = new - def _format_with_description(self, label_str): - """Prepend the description and, in publication format, the name. + def _format_with_name(self, label_str): + """Prepend the name in publication format. Parameters ---------- @@ -396,21 +378,18 @@ def _format_with_description(self, label_str): Returns ------- str - The description if set, then the name in publication format if - the label has one, each on its own line above ``label_str``. + ``label_str`` under the name and a newline when the label is in + publication format and has a name, otherwise unchanged. """ - lines = [] - if self.description: - lines.append(self.description) if self.publication_format and self.name: - lines.append(self.name) - return "\n".join(lines + [label_str]) + return f"{self.name}\n{label_str}" + return label_str @property def with_units(self): r"""Label with units, as a TeX math string.""" result = format_with_units(self.tex, self.units) - return self._format_with_description(result) + return self._format_with_name(result) @property def tex(self): @@ -446,7 +425,6 @@ def __init__( mcs1=None, axnorm=None, new_line_for_units=False, - description=None, name=None, publication_format=None, ): @@ -466,8 +444,6 @@ def __init__( :data:`~solarwindpy.plotting.labels.base.AXNORM`. new_line_for_units : bool, default ``False`` If ``True`` a newline separates label and units. - description : str or None, optional - Human-readable description displayed above the mathematical label. name : str or None, optional The first line in publication format. None uses the quantity's registry name, a ratio's " Ratio" or " / ". @@ -480,7 +456,6 @@ def __init__( self.set_axnorm(axnorm) self.set_mcs(mcs0, mcs1) self.set_new_line_for_units(new_line_for_units) - self.set_description(description) self.set_name(name) self.set_publication_format(publication_format) self.build_label() @@ -512,8 +487,8 @@ def units(self): @property def with_units(self): - r"""Label with units, from ``build_label``, under its description and name.""" - return self._format_with_description(self._with_units) + r"""Label with units, from ``build_label``, under its name in publication format.""" + return self._format_with_name(self._with_units) def _default_name(self): r"""The registry name; for a ratio, " Ratio" or " / ". @@ -685,7 +660,7 @@ def _combine_tex_path_units_axnorm(self, tex, path, units): tex = norm.quantity % tex path = path / (axnorm.upper() + "norm") - # The description and name lines are added when the label is read. + # The name line is added when the label is read. with_units = format_with_units(tex, units, new_line=self.new_line_for_units) return tex, path, units, with_units diff --git a/src/solarwindpy/plotting/labels/composition.py b/src/solarwindpy/plotting/labels/composition.py index c3afd8c65..386056a16 100644 --- a/src/solarwindpy/plotting/labels/composition.py +++ b/src/solarwindpy/plotting/labels/composition.py @@ -11,7 +11,7 @@ class Ion(base.Base): """Represent a single ion.""" - def __init__(self, species, charge, description=None): + def __init__(self, species, charge, name=None, publication_format=None): """Instantiate the ion. Parameters @@ -20,12 +20,15 @@ def __init__(self, species, charge, description=None): The element symbol, e.g. ``"He"``, ``"O"``, ``"Fe"``. charge : int or str The ion charge state, e.g. ``6``, ``"7"``, ``"i"``. - description : str or None, optional - Human-readable description displayed above the mathematical label. + name : str or None, optional + The first line in publication format; None for the label's default. + publication_format : bool or None, optional + If True, the name heads the label; None follows the module default. """ super().__init__() self.set_species_charge(species, charge) - self.set_description(description) + self.set_name(name) + self.set_publication_format(publication_format) @property def species(self): @@ -84,7 +87,7 @@ def set_species_charge(self, species, charge): class ChargeStateRatio(base.Base): """Ratio of two ion abundances.""" - def __init__(self, ionA, ionB, description=None): + def __init__(self, ionA, ionB, name=None, publication_format=None): """Instantiate the charge-state ratio. Parameters @@ -93,12 +96,15 @@ def __init__(self, ionA, ionB, description=None): The numerator ion. If tuple, passed to Ion constructor. ionB : Ion or tuple The denominator ion. If tuple, passed to Ion constructor. - description : str or None, optional - Human-readable description displayed above the mathematical label. + name : str or None, optional + The first line in publication format; None for the label's default. + publication_format : bool or None, optional + If True, the name heads the label; None follows the module default. """ super().__init__() self.set_ions(ionA, ionB) - self.set_description(description) + self.set_name(name) + self.set_publication_format(publication_format) @property def ionA(self): diff --git a/src/solarwindpy/plotting/labels/datetime.py b/src/solarwindpy/plotting/labels/datetime.py index 9b93f5eb5..afc00b687 100644 --- a/src/solarwindpy/plotting/labels/datetime.py +++ b/src/solarwindpy/plotting/labels/datetime.py @@ -18,19 +18,22 @@ class Timedelta(special.ArbitraryLabel): """Label for a time interval.""" - def __init__(self, offset, description=None): + def __init__(self, offset, name=None, publication_format=None): """Instantiate the label. Parameters ---------- offset : str or pandas offset Value convertible via :func:`pandas.tseries.frequencies.to_offset`. - description : str or None, optional - Human-readable description displayed above the mathematical label. + name : str or None, optional + The first line in publication format; None for the label's default. + publication_format : bool or None, optional + If True, the name heads the label; None follows the module default. """ super().__init__() self.set_offset(offset) - self.set_description(description) + self.set_name(name) + self.set_publication_format(publication_format) def __str__(self): return self.with_units @@ -39,7 +42,7 @@ def __str__(self): def with_units(self): r"""Label with units, as a TeX math string.""" result = base.format_with_units(self.tex, self.units) - return self._format_with_description(result) + return self._format_with_name(result) @property def offset(self): @@ -83,19 +86,22 @@ def set_offset(self, new): class DateTime(special.ArbitraryLabel): """Generic datetime label.""" - def __init__(self, kind, description=None): + def __init__(self, kind, name=None, publication_format=None): """Instantiate the label. Parameters ---------- kind : str Text used to build the label, e.g. ``"Year"`` or ``"Month"``. - description : str or None, optional - Human-readable description displayed above the mathematical label. + name : str or None, optional + The first line in publication format; None for the label's default. + publication_format : bool or None, optional + If True, the name heads the label; None follows the module default. """ super().__init__() self.set_kind(kind) - self.set_description(description) + self.set_name(name) + self.set_publication_format(publication_format) def __str__(self): return self.with_units @@ -104,7 +110,7 @@ def __str__(self): def with_units(self): r"""Label as a TeX math string; it has no units.""" result = r"$%s$" % self.tex - return self._format_with_description(result) + return self._format_with_name(result) @property def kind(self): @@ -129,7 +135,7 @@ def set_kind(self, new): class Epoch(special.ArbitraryLabel): r"""Create epoch analysis labels, e.g. ``Hour of Day``.""" - def __init__(self, kind, of_thing, space=r"\,", description=None): + def __init__(self, kind, of_thing, space=r"\,", name=None, publication_format=None): r"""Instantiate the label. Parameters @@ -140,14 +146,17 @@ def __init__(self, kind, of_thing, space=r"\,", description=None): The larger time unit, e.g. ``"Day"``. space : str, default ``"\,"`` TeX spacing command placed between words. - description : str or None, optional - Human-readable description displayed above the mathematical label. + name : str or None, optional + The first line in publication format; None for the label's default. + publication_format : bool or None, optional + If True, the name heads the label; None follows the module default. """ super().__init__() self.set_smaller(kind) self.set_larger(of_thing) self.set_space(space) - self.set_description(description) + self.set_name(name) + self.set_publication_format(publication_format) def __str__(self): return self.with_units @@ -186,7 +195,7 @@ def tex(self): def with_units(self): r"""Label as a TeX math string; it has no units.""" result = r"$%s$" % self.tex - return self._format_with_description(result) + return self._format_with_name(result) def set_larger(self, new): r"""Store the larger time unit, title-cased.""" @@ -213,19 +222,22 @@ def set_space(self, new): class Frequency(special.ArbitraryLabel): """Frequency of another quantity.""" - def __init__(self, other, description=None): + def __init__(self, other, name=None, publication_format=None): """Instantiate the label. Parameters ---------- other : Timedelta or str The time interval for frequency calculation. - description : str or None, optional - Human-readable description displayed above the mathematical label. + name : str or None, optional + The first line in publication format; None for the label's default. + publication_format : bool or None, optional + If True, the name heads the label; None follows the module default. """ super().__init__() self.set_other(other) - self.set_description(description) + self.set_name(name) + self.set_publication_format(publication_format) self.build_label() def __str__(self): @@ -274,16 +286,19 @@ def build_label(self): class January1st(special.ArbitraryLabel): """Label for the first day of the year.""" - def __init__(self, description=None): + def __init__(self, name=None, publication_format=None): """Instantiate the label. Parameters ---------- - description : str or None, optional - Human-readable description displayed above the mathematical label. + name : str or None, optional + The first line in publication format; None for the label's default. + publication_format : bool or None, optional + If True, the name heads the label; None follows the module default. """ super().__init__() - self.set_description(description) + self.set_name(name) + self.set_publication_format(publication_format) def __str__(self): return self.with_units @@ -292,7 +307,7 @@ def __str__(self): def with_units(self): r"""Label as a TeX math string; it has no units.""" result = r"$%s$" % self.tex - return self._format_with_description(result) + return self._format_with_name(result) @property def tex(self): diff --git a/src/solarwindpy/plotting/labels/elemental_abundance.py b/src/solarwindpy/plotting/labels/elemental_abundance.py index 56e441d16..3cced8d82 100644 --- a/src/solarwindpy/plotting/labels/elemental_abundance.py +++ b/src/solarwindpy/plotting/labels/elemental_abundance.py @@ -18,7 +18,8 @@ def __init__( reference_species, pct_unit=False, photospheric=True, - description=None, + name=None, + publication_format=None, ): """Instantiate the abundance label. @@ -32,14 +33,17 @@ def __init__( If True, use percent units instead of #. photospheric : bool, default True If True, label indicates ratio to photospheric value. - description : str or None, optional - Human-readable description displayed above the mathematical label. + name : str or None, optional + The first line in publication format; None for the label's default. + publication_format : bool or None, optional + If True, the name heads the label; None follows the module default. """ super().__init__() self.set_species(species, reference_species) self._pct_unit = bool(pct_unit) self._photospheric = bool(photospheric) - self.set_description(description) + self.set_name(name) + self.set_publication_format(publication_format) @property def species(self): diff --git a/src/solarwindpy/plotting/labels/special.py b/src/solarwindpy/plotting/labels/special.py index baa42a595..1df2818a7 100644 --- a/src/solarwindpy/plotting/labels/special.py +++ b/src/solarwindpy/plotting/labels/special.py @@ -122,7 +122,7 @@ class ArbitraryLabel(base.Base): """Abstract base class for custom labels.""" def __init__(self): - r"""Initialize the logger and an empty description.""" + r"""Initialize the logger.""" super().__init__() @abstractmethod @@ -133,7 +133,7 @@ def __str__(self): class ManualLabel(ArbitraryLabel): r"""Label defined by raw LaTeX text and unit.""" - def __init__(self, tex, unit, path=None, description=None): + def __init__(self, tex, unit, path=None, name=None, publication_format=None): r"""Instantiate the label. Parameters @@ -144,14 +144,17 @@ def __init__(self, tex, unit, path=None, description=None): Units, either a key of the module's units table or raw TeX. path : str or Path, optional Save path. If None, ``tex`` with spaces replaced by ``-``. - description : str, optional - Human-readable description shown above the label. + name : str or None, optional + The first line in publication format; None for the label's default. + publication_format : bool or None, optional + If True, the name heads the label; None follows the module default. """ super().__init__() self.set_tex(tex) self.set_unit(unit) self._path = path - self.set_description(description) + self.set_name(name) + self.set_publication_format(publication_format) def __str__(self): return self.with_units @@ -162,7 +165,7 @@ def with_units(self): result = base.format_with_units( r"\mathrm{%s}" % self.tex.replace(" ", r" \; "), self.units ) - return self._format_with_description(result) + return self._format_with_name(result) @property def tex(self): @@ -201,10 +204,11 @@ def set_unit(self, unit): class Vsw(base.Base): """Solar wind speed.""" - def __init__(self, description=None): - r"""Instantiate the label with an optional description.""" + def __init__(self, name=None, publication_format=None): + r"""Instantiate the label with an optional name.""" super().__init__() - self.set_description(description) + self.set_name(name) + self.set_publication_format(publication_format) @property def tex(self): @@ -225,15 +229,16 @@ def path(self): class CarringtonRotation(ArbitraryLabel): """Carrington rotation count.""" - def __init__(self, short_label=True, description=None): + def __init__(self, short_label=True, name=None, publication_format=None): """Instantiate the label.""" super().__init__() self._short_label = bool(short_label) - self.set_description(description) + self.set_name(name) + self.set_publication_format(publication_format) def __str__(self): result = base.format_with_units(self.tex, base._inU["dimless"]) - return self._format_with_description(result) + return self._format_with_name(result) @property def short_label(self): @@ -257,20 +262,23 @@ def path(self): class Count(ArbitraryLabel): """Count histogram label.""" - def __init__(self, norm=None, description=None): + def __init__(self, norm=None, name=None, publication_format=None): r"""Instantiate the label. Parameters ---------- norm : str, optional Axis normalization key; see ``set_axnorm``. - description : str, optional - Human-readable description shown above the label. + name : str or None, optional + The first line in publication format; None for the label's default. + publication_format : bool or None, optional + If True, the name heads the label; None follows the module default. """ super().__init__() self.set_axnorm(norm) self.set_binned_axes({}) - self.set_description(description) + self.set_name(name) + self.set_publication_format(publication_format) self.build_label() def __str__(self): @@ -278,7 +286,7 @@ def __str__(self): # line is the count's symbol rather than the words again. tex = self.symbol if self.publication_format else self.tex result = base.format_with_units(tex, self.units) - return self._format_with_description(result) + return self._format_with_name(result) @property def tex(self): @@ -357,14 +365,15 @@ def build_label(self): class Power(ArbitraryLabel): """Power spectrum label.""" - def __init__(self, description=None): - r"""Instantiate the label with an optional description.""" + def __init__(self, name=None, publication_format=None): + r"""Instantiate the label with an optional name.""" super().__init__() - self.set_description(description) + self.set_name(name) + self.set_publication_format(publication_format) def __str__(self): result = base.format_with_units(self.tex, self.units) - return self._format_with_description(result) + return self._format_with_name(result) @property def tex(self): @@ -385,17 +394,20 @@ def path(self): class Probability(ArbitraryLabel): """Probability that a quantity meets a comparison criterion.""" - def __init__(self, other_label, comparison=None, description=None): + def __init__( + self, other_label, comparison=None, name=None, publication_format=None + ): """Instantiate the label.""" super().__init__() self.set_other_label(other_label) self.set_comparison(comparison) - self.set_description(description) + self.set_name(name) + self.set_publication_format(publication_format) self.build_label() def __str__(self): result = base.format_with_units(self.tex, self.units) - return self._format_with_description(result) + return self._format_with_name(result) @property def tex(self): @@ -459,14 +471,20 @@ class CountOther(ArbitraryLabel): """Count of samples of another label fulfilling a comparison.""" def __init__( - self, other_label, comparison=None, new_line_for_units=False, description=None + self, + other_label, + comparison=None, + new_line_for_units=False, + name=None, + publication_format=None, ): """Instantiate the label.""" super().__init__() self.set_other_label(other_label) self.set_comparison(comparison) self.set_new_line_for_units(new_line_for_units) - self.set_description(description) + self.set_name(name) + self.set_publication_format(publication_format) self.build_label() @@ -474,7 +492,7 @@ def __str__(self): result = base.format_with_units( self.tex, self.units, new_line=self.new_line_for_units ) - return self._format_with_description(result) + return self._format_with_name(result) @property def tex(self): @@ -552,7 +570,8 @@ def __init__( other_label, dimensionless=True, new_line_for_units=False, - description=None, + name=None, + publication_format=None, ): """Instantiate the label.""" super().__init__() @@ -560,14 +579,15 @@ def __init__( self.set_function(fcn) self.set_dimensionless(dimensionless) self.set_new_line_for_units(new_line_for_units) - self.set_description(description) + self.set_name(name) + self.set_publication_format(publication_format) self.build_label() def __str__(self): result = base.format_with_units( self.tex, self.units, new_line=self.new_line_for_units ) - return self._format_with_description(result) + return self._format_with_name(result) @property def tex(self): @@ -659,7 +679,9 @@ class AbsoluteValue(ArbitraryLabel): :math:`|x|` has the same dimensions as :math:`x`. """ - def __init__(self, other_label, new_line_for_units=False, description=None): + def __init__( + self, other_label, new_line_for_units=False, name=None, publication_format=None + ): r"""Instantiate the label. Parameters @@ -668,8 +690,10 @@ def __init__(self, other_label, new_line_for_units=False, description=None): The label to wrap with absolute value bars. new_line_for_units : bool, default False If True, place units on a new line. - description : str or None, optional - Human-readable description displayed above the mathematical label. + name : str or None, optional + The first line in publication format; None for the label's default. + publication_format : bool or None, optional + If True, the name heads the label; None follows the module default. Notes ----- @@ -681,14 +705,15 @@ def __init__(self, other_label, new_line_for_units=False, description=None): super().__init__() self.set_other_label(other_label) self.set_new_line_for_units(new_line_for_units) - self.set_description(description) + self.set_name(name) + self.set_publication_format(publication_format) self.build_label() def __str__(self): result = base.format_with_units( self.tex, self.units, new_line=self.new_line_for_units ) - return self._format_with_description(result) + return self._format_with_name(result) @property def tex(self): @@ -739,23 +764,26 @@ def build_label(self): class Distance2Sun(ArbitraryLabel): """Distance to the Sun.""" - def __init__(self, units, description=None): + def __init__(self, units, name=None, publication_format=None): r"""Instantiate the label. Parameters ---------- units : str ``"rs"``, ``"re"``, ``"au"`` (case-insensitive), ``"m"`` or ``"km"``. - description : str, optional - Human-readable description shown above the label. + name : str or None, optional + The first line in publication format; None for the label's default. + publication_format : bool or None, optional + If True, the name heads the label; None follows the module default. """ super().__init__() self.set_units(units) - self.set_description(description) + self.set_name(name) + self.set_publication_format(publication_format) def __str__(self): result = base.format_with_units(self.tex, r"\mathrm{%s}" % self.units) - return self._format_with_description(result) + return self._format_with_name(result) @property def units(self): @@ -793,23 +821,26 @@ def set_units(self, units): class SSN(ArbitraryLabel): """Sunspot number label.""" - def __init__(self, key, description=None): + def __init__(self, key, name=None, publication_format=None): r"""Instantiate the label. Parameters ---------- key : str Sunspot number kind; see ``set_kind``. - description : str, optional - Human-readable description shown above the label. + name : str or None, optional + The first line in publication format; None for the label's default. + publication_format : bool or None, optional + If True, the name heads the label; None follows the module default. """ super().__init__() self.set_kind(key) - self.set_description(description) + self.set_name(name) + self.set_publication_format(publication_format) def __str__(self): result = base.format_with_units(self.tex, base._inU["dimless"]) - return self._format_with_description(result) + return self._format_with_name(result) @property def kind(self): @@ -865,17 +896,20 @@ def set_kind(self, new): class ComparisonLabel(ArbitraryLabel): """Label comparing two other labels via a function.""" - def __init__(self, labelA, labelB, fcn_name, fcn=None, description=None): + def __init__( + self, labelA, labelB, fcn_name, fcn=None, name=None, publication_format=None + ): """Instantiate the label.""" super().__init__() self.set_constituents(labelA, labelB) self.set_function(fcn_name, fcn) - self.set_description(description) + self.set_name(name) + self.set_publication_format(publication_format) self.build_label() def __str__(self): result = base.format_with_units(self.tex, self.units) - return self._format_with_description(result) + return self._format_with_name(result) @property def tex(self): @@ -1016,18 +1050,27 @@ def build_label(self): class Xcorr(ArbitraryLabel): """Cross-correlation coefficient between two labels.""" - def __init__(self, labelA, labelB, method, short_tex=False, description=None): + def __init__( + self, + labelA, + labelB, + method, + short_tex=False, + name=None, + publication_format=None, + ): """Instantiate the label.""" super().__init__() self.set_constituents(labelA, labelB) self.set_method(method) self.set_short_tex(short_tex) - self.set_description(description) + self.set_name(name) + self.set_publication_format(publication_format) self.build_label() def __str__(self): result = base.format_with_units(self.tex, self.units) - return self._format_with_description(result) + return self._format_with_name(result) @property def tex(self): diff --git a/tests/plotting/labels/test_labels_base.py b/tests/plotting/labels/test_labels_base.py index 8da3b24b4..ad71eaae0 100644 --- a/tests/plotting/labels/test_labels_base.py +++ b/tests/plotting/labels/test_labels_base.py @@ -347,111 +347,57 @@ def test_empty_string_handling(labels_base): assert hasattr(label, "path") -class TestDescriptionFeature: - """Tests for the description property on Base/TeXlabel classes. +class TestNameFeature: + """``name``: the first line of a label in publication format. - The description feature allows human-readable text to be prepended - above the mathematical LaTeX label for axis/colorbar labels. + ON FAILURE: the code is wrong. """ - def test_description_default_none(self, labels_base): - """Default description is None when not specified.""" - label = labels_base.TeXlabel(("v", "x", "p")) - assert label.description is None + def test_default_name_is_the_registry_name(self, labels_base): + assert labels_base.TeXlabel(("v", "x", "p")).name == "Velocity" - def test_set_description_stores_value(self, labels_base): - """set_description() stores the given string.""" + def test_set_name_stores_a_string(self, labels_base): label = labels_base.TeXlabel(("v", "x", "p")) - label.set_description("Test description") - assert label.description == "Test description" + label.set_name(42) + assert label.name == "42" - def test_set_description_converts_to_string(self, labels_base): - """set_description() converts non-string values to string.""" - label = labels_base.TeXlabel(("v", "x", "p")) - label.set_description(42) - assert label.description == "42" - assert isinstance(label.description, str) + def test_set_name_none_restores_the_default(self, labels_base): + label = labels_base.TeXlabel(("v", "x", "p"), name="Speed") + assert label.name == "Speed" + label.set_name(None) + assert label.name == "Velocity" - def test_set_description_none_clears(self, labels_base): - """set_description(None) clears the description.""" - label = labels_base.TeXlabel(("v", "x", "p")) - label.set_description("Some text") - assert label.description == "Some text" - label.set_description(None) - assert label.description is None - - def test_description_init_parameter(self, labels_base): - """TeXlabel accepts description in __init__.""" - label = labels_base.TeXlabel(("n", "", "p"), description="density") - assert label.description == "density" - - def test_description_appears_in_with_units(self, labels_base): - """Description is prepended to with_units output.""" - label = labels_base.TeXlabel(("v", "x", "p"), description="velocity") - result = label.with_units - assert result.startswith("velocity\n") - assert "$" in result # Still contains the TeX label - - def test_description_with_newline_separator(self, labels_base): - """Description uses newline to separate from label.""" - label = labels_base.TeXlabel(("T", "", "p"), description="temperature") - result = label.with_units - lines = result.split("\n") - assert len(lines) >= 2 - assert lines[0] == "temperature" - - def test_format_with_description_none_unchanged(self, labels_base): - """Without a description, ``with_units`` is the bare TeX label. - - ON FAILURE: the code is wrong. - """ - label = labels_base.TeXlabel(("v", "x", "p")) - assert label.description is None + def test_name_is_not_shown_in_the_default_format(self, labels_base): + label = labels_base.TeXlabel(("v", "x", "p"), name="Speed") assert label.with_units == ( "${v}_{{x};{p}} \\; \\left[\\mathrm{km \\; s^{-1}}\\right]$" ) - def test_format_with_description_adds_prefix(self, labels_base): - """A description set and built prepends itself and a newline to ``with_units``. + def test_name_heads_the_label_in_publication_format(self, labels_base): + label = labels_base.TeXlabel( + ("v", "x", "p"), name="Speed", publication_format=True + ) + assert str(label) == "Speed\n" + str(labels_base.TeXlabel(("v", "x", "p"))) + + def test_name_with_axnorm_and_ratio(self, labels_base): + norm = labels_base.TeXlabel( + ("n", "", "p"), axnorm="t", name="count", publication_format=True + ) + assert norm.with_units.startswith("count\n") + assert "Max" in norm.with_units + ratio = labels_base.TeXlabel( + ("v", "x", "p"), ("n", "", "p"), name="v/n", publication_format=True + ) + assert ratio.with_units.startswith("v/n\n") - ``with_units`` is documented as set by ``build_label``, so the label is - rebuilt after ``set_description``. + def test_empty_name_adds_no_line(self, labels_base): + label = labels_base.TeXlabel(("v", "x", "p"), name="", publication_format=True) + assert "\n" not in label.with_units - ON FAILURE: the code is wrong. - """ + def test_description_is_gone(self, labels_base): label = labels_base.TeXlabel(("v", "x", "p")) - bare = label.with_units - label.set_description("info") - label.build_label() - assert label.with_units == "info\n" + bare - - def test_description_with_axnorm(self, labels_base): - """Description works correctly with axis normalization.""" - label = labels_base.TeXlabel(("n", "", "p"), axnorm="t", description="count") - result = label.with_units - assert result.startswith("count\n") - assert "Max" in result - - def test_description_with_ratio_label(self, labels_base): - """Description works with ratio-style labels.""" - label = labels_base.TeXlabel( - ("v", "x", "p"), ("n", "", "p"), description="v/n ratio" - ) - result = label.with_units - assert result.startswith("v/n ratio\n") - assert "/" in result # Contains ratio - - def test_description_empty_string_treated_as_falsy(self, labels_base): - """Empty string description is treated as no description.""" - label = labels_base.TeXlabel(("v", "x", "p"), description="") - result = label.with_units - # Empty string is falsy, so _format_with_description returns unchanged - assert not result.startswith("\n") - - def test_str_includes_description(self, labels_base): - """__str__ returns with_units which includes description.""" - label = labels_base.TeXlabel(("v", "x", "p"), description="speed") - assert str(label).startswith("speed\n") + assert not hasattr(label, "description") + assert not hasattr(label, "set_description") @pytest.mark.parametrize( diff --git a/tests/plotting/labels/test_publication_format.py b/tests/plotting/labels/test_publication_format.py index 35d3d3112..e9a54d0e7 100644 --- a/tests/plotting/labels/test_publication_format.py +++ b/tests/plotting/labels/test_publication_format.py @@ -72,17 +72,13 @@ def test_name_overrides_the_registry_name(): ) -def test_description_stays_above_the_name(): - """A description keeps its own line, above the name. +def test_description_keyword_is_removed(): + """``description`` was merged into ``name``: one optional first line. ON FAILURE: the code is wrong. """ - label = TeXlabel(("n", "", "p1"), description="Wind", publication_format=True) - assert str(label).split("\n") == [ - "Wind", - "Number Density", - r"$n_{p_1} \; \left[\mathrm{cm}^{-3}\right]$", - ] + with pytest.raises(TypeError): + TeXlabel(("n", "", "p1"), description="Wind") def test_per_label_setting_overrides_the_module_default(restore_default): diff --git a/tests/plotting/labels/test_special.py b/tests/plotting/labels/test_special.py index 2a4885528..0ff2105e0 100644 --- a/tests/plotting/labels/test_special.py +++ b/tests/plotting/labels/test_special.py @@ -1041,51 +1041,66 @@ def test_string_constituents_spaces_and_tex_spacing(self): def _all_label_factories(): - """One factory per public label class, each taking ``description``.""" + """One factory per public label class; each passes its keywords to the class.""" from solarwindpy.plotting.labels import composition, datetime from solarwindpy.plotting.labels.elemental_abundance import ElementalAbundance n = labels_base.TeXlabel(_N_P1) return { - "TeXlabel": lambda d: labels_base.TeXlabel(_N_P1, description=d), - "ManualLabel": lambda d: labels_special.ManualLabel("M", "b", description=d), - "Vsw": lambda d: labels_special.Vsw(description=d), - "CarringtonRotation": lambda d: labels_special.CarringtonRotation( - description=d + "TeXlabel": lambda **kw: labels_base.TeXlabel(_N_P1, **kw), + "ManualLabel": lambda **kw: labels_special.ManualLabel("M", "b", **kw), + "Vsw": lambda **kw: labels_special.Vsw(**kw), + "CarringtonRotation": lambda **kw: labels_special.CarringtonRotation(**kw), + "Count": lambda **kw: labels_special.Count(**kw), + "Power": lambda **kw: labels_special.Power(**kw), + "Probability": lambda **kw: labels_special.Probability(n, "> 5", **kw), + "CountOther": lambda **kw: labels_special.CountOther(n, "> 5", **kw), + "MathFcn": lambda **kw: labels_special.MathFcn("log", n, **kw), + "AbsoluteValue": lambda **kw: labels_special.AbsoluteValue(n, **kw), + "Distance2Sun": lambda **kw: labels_special.Distance2Sun("m", **kw), + "SSN": lambda **kw: labels_special.SSN("M", **kw), + "ComparisonLabel": lambda **kw: labels_special.ComparisonLabel( + n, n, "subtract", **kw ), - "Count": lambda d: labels_special.Count(description=d), - "Power": lambda d: labels_special.Power(description=d), - "Probability": lambda d: labels_special.Probability(n, "> 5", description=d), - "CountOther": lambda d: labels_special.CountOther(n, "> 5", description=d), - "MathFcn": lambda d: labels_special.MathFcn("log", n, description=d), - "AbsoluteValue": lambda d: labels_special.AbsoluteValue(n, description=d), - "Distance2Sun": lambda d: labels_special.Distance2Sun("m", description=d), - "SSN": lambda d: labels_special.SSN("M", description=d), - "ComparisonLabel": lambda d: labels_special.ComparisonLabel( - n, n, "subtract", description=d + "Xcorr": lambda **kw: labels_special.Xcorr(n, n, "pearson", **kw), + "Timedelta": lambda **kw: datetime.Timedelta("1h", **kw), + "DateTime": lambda **kw: datetime.DateTime("Year", **kw), + "Epoch": lambda **kw: datetime.Epoch("hour", "day", **kw), + "Frequency": lambda **kw: datetime.Frequency("1h", **kw), + "January1st": lambda **kw: datetime.January1st(**kw), + "Ion": lambda **kw: composition.Ion("O", 6, **kw), + "ChargeStateRatio": lambda **kw: composition.ChargeStateRatio( + ("O", 7), ("O", 6), **kw ), - "Xcorr": lambda d: labels_special.Xcorr(n, n, "pearson", description=d), - "Timedelta": lambda d: datetime.Timedelta("1h", description=d), - "DateTime": lambda d: datetime.DateTime("Year", description=d), - "Epoch": lambda d: datetime.Epoch("hour", "day", description=d), - "Frequency": lambda d: datetime.Frequency("1h", description=d), - "January1st": lambda d: datetime.January1st(description=d), - "Ion": lambda d: composition.Ion("O", 6, description=d), - "ChargeStateRatio": lambda d: composition.ChargeStateRatio( - ("O", 7), ("O", 6), description=d - ), - "ElementalAbundance": lambda d: ElementalAbundance("Fe", "O", description=d), + "ElementalAbundance": lambda **kw: ElementalAbundance("Fe", "O", **kw), } -@pytest.mark.parametrize("name", sorted(_all_label_factories())) -def test_description_argument_is_printed_above_the_label(name): - """A ``description`` passed to the constructor heads the label on its own line. +@pytest.mark.parametrize("label", sorted(_all_label_factories())) +def test_name_argument_heads_the_label_in_publication_format(label): + """A ``name`` passed to the constructor heads the label in publication format. - The expected string is the same label built without a description, - prefixed by the description and a newline (``Base._format_with_description``). + Below it is the label's one-line form, except for ``Count``, whose second + line in publication format is its symbol (``N``) rather than its words. ON FAILURE: the code is wrong. """ - factory = _all_label_factories()[name] - assert str(factory("Protons")) == "Protons\n" + str(factory(None)) + factory = _all_label_factories()[label] + one_line = str(factory(name="Protons", publication_format=False)) + assert "Protons" not in one_line + head, rest = str(factory(name="Protons", publication_format=True)).split("\n", 1) + assert head == "Protons" + if label == "Count": + assert rest == r"$N \; \left[\#\right]$" + else: + assert rest == one_line + + +@pytest.mark.parametrize("label", sorted(_all_label_factories())) +def test_description_keyword_is_removed(label): + """``description`` was merged into ``name``; passing it raises. + + ON FAILURE: the code is wrong -- a label still accepts ``description``. + """ + with pytest.raises(TypeError): + _all_label_factories()[label](description="Protons") diff --git a/tests/plotting/test_integration.py b/tests/plotting/test_integration.py index 6d2df8c44..0d58eaea6 100644 --- a/tests/plotting/test_integration.py +++ b/tests/plotting/test_integration.py @@ -155,7 +155,7 @@ def test_every_listed_species_renders_as_a_math_axis_label(species): _STRUCTURED_LABELS = { "TeXlabel-ratio": lambda: TeXlabel(_N_A, _N_P1), "TeXlabel-new-line-for-units": lambda: TeXlabel(_N_P1, new_line_for_units=True), - "TeXlabel-description": lambda: TeXlabel(_N_P1, description="Protons"), + "TeXlabel-name": lambda: TeXlabel(_N_P1, name="Protons", publication_format=True), **{ f"TeXlabel-axnorm-{norm}": (lambda norm=norm: TeXlabel(_N_P1, axnorm=norm)) for norm in ("c", "r", "t", "d") From d5c8e39eca870bf725544833dd21ea468a07e9aa Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 06:01:10 -0500 Subject: [PATCH 50/60] refactor(plotting): check axnorm keys in one place BinnedPlot._validate_axnorm duplicated labels.base.validate_axnorm (same messages, a different key set). validate_axnorm takes the accepted keys, defaulting to AXNORM, and set_axnorm passes the binning's allowed_axnorm. Co-Authored-By: Claude Opus 5.5 --- src/solarwindpy/plotting/base.py | 38 +---------------------- src/solarwindpy/plotting/labels/base.py | 22 ++++++++++--- tests/plotting/labels/test_labels_base.py | 18 +++++++++++ 3 files changed, 37 insertions(+), 41 deletions(-) diff --git a/src/solarwindpy/plotting/base.py b/src/solarwindpy/plotting/base.py index c976c6f2e..992394610 100644 --- a/src/solarwindpy/plotting/base.py +++ b/src/solarwindpy/plotting/base.py @@ -960,7 +960,7 @@ def set_axnorm(self, new): ValueError If ``new`` is not a key the cells support. """ - self._axnorm = self._validate_axnorm(new, self.binning.allowed_axnorm) + self._axnorm = labels.base.validate_axnorm(new, self.binning.allowed_axnorm) self._count_with_axnorm(getattr(self.labels, self.agg_axes)) def _count_with_axnorm(self, label): @@ -990,42 +990,6 @@ def set_labels(self, **kwargs): super().set_labels(**kwargs) self._count_with_axnorm(getattr(self.labels, self.agg_axes)) - @staticmethod - def _validate_axnorm(new, allowed): - r"""Check an ``axnorm`` key and return it in its normalized form. - - Parameters - ---------- - new : str or None - The requested key. Matching is case-insensitive and exact. - allowed : tuple of str - The lowercase keys the plot's cells support. - - Returns - ------- - str or None - ``None`` unchanged, otherwise the lowercase key. - - Raises - ------ - TypeError - If `new` is neither a string nor None. - ValueError - If `new` is not one of `allowed`. - """ - if new is None: - return None - if not isinstance(new, str): - raise TypeError( - f"axnorm must be a string or None; got {type(new).__name__}" - ) - key = new.lower() - if key not in allowed: - raise ValueError( - f"Unrecognized axnorm '{new}'; expected one of: {', '.join(allowed)}" - ) - return key - @property def agg_axes(self): r"""The axis to aggregate into, e.g. the z variable in an (x, y, z) heatmap.""" diff --git a/src/solarwindpy/plotting/labels/base.py b/src/solarwindpy/plotting/labels/base.py index 3710ffef6..fb478864c 100644 --- a/src/solarwindpy/plotting/labels/base.py +++ b/src/solarwindpy/plotting/labels/base.py @@ -220,24 +220,38 @@ def density_units(axnorm, axes): return r" \, ".join(factors) -def validate_axnorm(key): +def validate_axnorm(key, allowed=None): r"""Return the ``axnorm`` key ``key`` in lower case, or None for None. + The one check of an ``axnorm`` key, shared by the labels and the plots. + Matching is case-insensitive and exact. + + Parameters + ---------- + key : str or None + The requested key. + allowed : iterable of str, optional + The lowercase keys accepted, e.g. a binning's ``allowed_axnorm``. + None accepts every key of + :data:`~solarwindpy.plotting.labels.base.AXNORM`. + Raises ------ TypeError If ``key`` is neither a string nor None. ValueError - If ``key`` is not a key of :data:`~solarwindpy.plotting.labels.base.AXNORM`. + If ``key`` is not one of ``allowed``. """ + if allowed is None: + allowed = AXNORM if key is None: return None if not isinstance(key, str): raise TypeError(f"axnorm must be a string or None; got {type(key).__name__}") lower = key.lower() - if lower not in AXNORM: + if lower not in allowed: raise ValueError( - f"Unrecognized axnorm '{key}'; expected one of: {', '.join(AXNORM)}" + f"Unrecognized axnorm '{key}'; expected one of: {', '.join(allowed)}" ) return lower diff --git a/tests/plotting/labels/test_labels_base.py b/tests/plotting/labels/test_labels_base.py index ad71eaae0..8cafc917f 100644 --- a/tests/plotting/labels/test_labels_base.py +++ b/tests/plotting/labels/test_labels_base.py @@ -728,3 +728,21 @@ def test_normalized_ratio_is_parenthesized(labels_base): label = labels_base.TeXlabel(("n", "", "a"), ("n", "", "p1"), axnorm="t") assert label.tex == r"(n_{\alpha}/n_{p_1}) / \mathrm{Max}" assert "validate_axnorm" in labels_base.__all__ + + +def test_plots_and_labels_share_one_axnorm_check(labels_base): + """A plot checks ``axnorm`` with the labels' ``validate_axnorm``, against its keys. + + ON FAILURE: the code is wrong -- a second copy of the check exists, or the + plot no longer limits the keys to its binning's ``allowed_axnorm``. + """ + import pandas as pd + from solarwindpy.plotting import base as plot_base + from solarwindpy.plotting.hist1d import Hist1D + + assert not hasattr(plot_base.BinnedPlot, "_validate_axnorm") + assert labels_base.validate_axnorm("W", ("d", "t", "w")) == "w" + with pytest.raises(ValueError, match="expected one of: d, t, w"): + Hist1D(pd.Series([1.0, 2.0, 3.0], name="x"), axnorm="c") + with pytest.raises(ValueError, match="expected one of: c, r, t, d"): + labels_base.validate_axnorm("q") From d8bebcd653bc2efd50fc8a14ffb0b9cd8b7b8490 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 06:14:52 -0500 Subject: [PATCH 51/60] test(fitfunctions): drop the unused weights from the hinge fixtures Every hinge fixture built w = 1 / noise_std (or ones), which no test used; with the yerr rename it also read as an inverted uncertainty. The fixtures return (x, y, true_params[, derived]). Co-Authored-By: Claude Opus 5.5 --- tests/fitfunctions/test_hinge.py | 163 ++++++++++++++----------------- 1 file changed, 72 insertions(+), 91 deletions(-) diff --git a/tests/fitfunctions/test_hinge.py b/tests/fitfunctions/test_hinge.py index 9c881b988..8ea83f734 100644 --- a/tests/fitfunctions/test_hinge.py +++ b/tests/fitfunctions/test_hinge.py @@ -49,8 +49,7 @@ def clean_saturation_data(): m1 * (x - true_params["x1"]), true_params["yh"], # m2=0 means flat plateau at yh ) - w = np.ones_like(x) - return x, y, w, true_params + return x, y, true_params @pytest.fixture @@ -70,8 +69,7 @@ def clean_sloped_plateau_data(): m1 * (x - true_params["x1"]), true_params["m2"] * (x - x2), ) - w = np.ones_like(x) - return x, y, w, true_params + return x, y, true_params @pytest.fixture @@ -92,8 +90,7 @@ def noisy_saturation_data(): ) noise_std = 0.5 y = y_true + rng.normal(0, noise_std, len(x)) - w = np.ones_like(x) / noise_std - return x, y, w, true_params + return x, y, true_params @pytest.fixture @@ -111,8 +108,7 @@ def offset_x1_data(): m1 * (x - true_params["x1"]), true_params["yh"], ) - w = np.ones_like(x) - return x, y, w, true_params + return x, y, true_params # ============================================================================= @@ -193,7 +189,7 @@ def test_func_evaluates_sloped_plateau_correctly(): def test_fit_recovers_exact_parameters_from_clean_data(clean_saturation_data): """Fitting noise-free data should recover parameters within 1%.""" - x, y, w, true_params = clean_saturation_data + x, y, true_params = clean_saturation_data obj = HingeSaturation(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -216,7 +212,7 @@ def test_fit_recovers_exact_parameters_from_clean_data(clean_saturation_data): def test_fit_recovers_sloped_plateau_parameters(clean_sloped_plateau_data): """Fitting clean data with m2≠0 should recover parameters within 2%.""" - x, y, w, true_params = clean_sloped_plateau_data + x, y, true_params = clean_sloped_plateau_data obj = HingeSaturation(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -237,7 +233,7 @@ def test_fit_recovers_sloped_plateau_parameters(clean_sloped_plateau_data): def test_fit_recovers_offset_x1_parameters(offset_x1_data): """Fitting clean data with x1≠0 should recover parameters within 2%.""" - x, y, w, true_params = offset_x1_data + x, y, true_params = offset_x1_data obj = HingeSaturation(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -318,7 +314,7 @@ def test_fit_with_noise_recovers_parameters_within_2sigma(noisy_saturation_data) For well-behaved Gaussian noise, we expect deviations < 2σ with high confidence. """ - x, y, w, true_params = noisy_saturation_data + x, y, true_params = noisy_saturation_data obj = HingeSaturation(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -374,7 +370,7 @@ def test_fit_uncertainty_scales_with_noise(): def test_p0_returns_list_with_correct_length(clean_saturation_data): """p0 should return a list with 4 elements.""" - x, y, w, true_params = clean_saturation_data + x, y, true_params = clean_saturation_data obj = HingeSaturation(x, y, guess_xh=true_params["xh"]) p0 = obj.p0 @@ -384,7 +380,7 @@ def test_p0_returns_list_with_correct_length(clean_saturation_data): def test_p0_enables_successful_convergence(noisy_saturation_data): """Fit should converge when initialized with estimated p0.""" - x, y, w, true_params = noisy_saturation_data + x, y, true_params = noisy_saturation_data obj = HingeSaturation(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -405,7 +401,7 @@ def test_fitted_m1_is_consistent_with_xh_yh_x1(offset_x1_data): ON FAILURE: the code is wrong. """ - x, y, w, true_params = offset_x1_data + x, y, true_params = offset_x1_data # True m1 = 10 / (5 - 1) = 2.5 obj = HingeSaturation(x, y, guess_xh=true_params["xh"]) @@ -431,7 +427,7 @@ def test_hinge_point_is_continuous(clean_sloped_plateau_data): ON FAILURE: the code is wrong. """ - x, y, w, true_params = clean_sloped_plateau_data + x, y, true_params = clean_sloped_plateau_data obj = HingeSaturation(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -546,7 +542,7 @@ def test_tex_function_property(): def test_callable_interface(clean_saturation_data): """Test that fitted object is callable and returns correct shape.""" - x, y, w, true_params = clean_saturation_data + x, y, true_params = clean_saturation_data obj = HingeSaturation(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -563,7 +559,7 @@ def test_callable_interface(clean_saturation_data): def test_popt_has_correct_keys(clean_saturation_data): """Test that popt contains expected parameter names.""" - x, y, w, true_params = clean_saturation_data + x, y, true_params = clean_saturation_data obj = HingeSaturation(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -578,7 +574,7 @@ def test_popt_has_correct_keys(clean_saturation_data): def test_psigma_has_same_keys_as_popt(noisy_saturation_data): """Test that psigma has same keys as popt.""" - x, y, w, true_params = noisy_saturation_data + x, y, true_params = noisy_saturation_data obj = HingeSaturation(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -591,7 +587,7 @@ def test_psigma_has_same_keys_as_popt(noisy_saturation_data): def test_psigma_values_are_positive(noisy_saturation_data): """Test that all parameter uncertainties are positive.""" - x, y, w, true_params = noisy_saturation_data + x, y, true_params = noisy_saturation_data obj = HingeSaturation(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -645,8 +641,7 @@ def clean_twoline_data(): y1 = true_params["m1"] * (x - true_params["x1"]) y2 = true_params["m2"] * (x - true_params["x2"]) y = np.minimum(y1, y2) - w = np.ones_like(x) - return x, y, w, true_params + return x, y, true_params @pytest.fixture @@ -664,8 +659,7 @@ def noisy_twoline_data(): y_true = np.minimum(y1, y2) noise_std = 0.5 y = y_true + rng.normal(0, noise_std, len(x)) - w = np.ones_like(x) / noise_std - return x, y, w, true_params + return x, y, true_params @pytest.fixture @@ -682,8 +676,7 @@ def twoline_parallel_slopes_data(): y1 = true_params["m1"] * (x - true_params["x1"]) y2 = true_params["m2"] * (x - true_params["x2"]) y = np.minimum(y1, y2) - w = np.ones_like(x) - return x, y, w, true_params + return x, y, true_params # ----------------------------------------------------------------------------- @@ -764,7 +757,7 @@ def test_twoline_func_evaluates_intersection_correctly(): def test_twoline_fit_recovers_exact_parameters_from_clean_data(clean_twoline_data): """Fitting noise-free TwoLine data should recover parameters within 2%.""" - x, y, w, true_params = clean_twoline_data + x, y, true_params = clean_twoline_data obj = TwoLine(x, y, guess_xh=5.0) obj.make_fit() @@ -786,7 +779,7 @@ def test_twoline_fit_recovers_exact_parameters_from_clean_data(clean_twoline_dat def test_twoline_fit_recovers_parallel_slopes_parameters(twoline_parallel_slopes_data): """Fitting TwoLine with same-sign slopes should recover parameters within 2%.""" - x, y, w, true_params = twoline_parallel_slopes_data + x, y, true_params = twoline_parallel_slopes_data obj = TwoLine(x, y, guess_xh=-2.0) obj.make_fit() @@ -815,7 +808,7 @@ def test_twoline_fit_with_noise_recovers_parameters_within_2sigma(noisy_twoline_ With 4 parameters at 2sigma (95%), joint probability is (0.95)^4 = 81%. """ - x, y, w, true_params = noisy_twoline_data + x, y, true_params = noisy_twoline_data obj = TwoLine(x, y, guess_xh=5.0) obj.make_fit() @@ -844,7 +837,7 @@ def test_twoline_xs_property_is_consistent(clean_twoline_data): ON FAILURE: the code is wrong. """ - x, y, w, true_params = clean_twoline_data + x, y, true_params = clean_twoline_data obj = TwoLine(x, y, guess_xh=5.0) obj.make_fit() @@ -869,7 +862,7 @@ def test_twoline_s_property_is_consistent(clean_twoline_data): ON FAILURE: the code is wrong. """ - x, y, w, true_params = clean_twoline_data + x, y, true_params = clean_twoline_data obj = TwoLine(x, y, guess_xh=5.0) obj.make_fit() @@ -891,7 +884,7 @@ def test_twoline_theta_property_is_positive_for_converging_lines(clean_twoline_d ON FAILURE: the code is wrong. """ - x, y, w, true_params = clean_twoline_data + x, y, true_params = clean_twoline_data obj = TwoLine(x, y, guess_xh=5.0) obj.make_fit() @@ -933,7 +926,7 @@ def test_twoline_function_signature(): def test_twoline_popt_has_correct_keys(clean_twoline_data): """Test that TwoLine popt contains expected parameter names.""" - x, y, w, true_params = clean_twoline_data + x, y, true_params = clean_twoline_data obj = TwoLine(x, y, guess_xh=5.0) obj.make_fit() @@ -948,7 +941,7 @@ def test_twoline_popt_has_correct_keys(clean_twoline_data): def test_twoline_callable_interface(clean_twoline_data): """Test that fitted TwoLine object is callable and returns correct shape.""" - x, y, w, true_params = clean_twoline_data + x, y, true_params = clean_twoline_data obj = TwoLine(x, y, guess_xh=5.0) obj.make_fit() @@ -1006,8 +999,7 @@ def clean_saturation_twoline_data(): y1 = m1 * (x - true_params["x1"]) y2 = m2 * (x - x2) y = np.minimum(y1, y2) - w = np.ones_like(x) - return x, y, w, true_params, {"m1": m1, "m2": m2, "x2": x2} + return x, y, true_params, {"m1": m1, "m2": m2, "x2": x2} @pytest.fixture @@ -1028,8 +1020,7 @@ def noisy_saturation_twoline_data(): y_true = np.minimum(y1, y2) noise_std = 0.5 y = y_true + rng.normal(0, noise_std, len(x)) - w = np.ones_like(x) / noise_std - return x, y, w, true_params + return x, y, true_params @pytest.fixture @@ -1047,8 +1038,7 @@ def saturation_small_theta_data(): y1 = m1 * (x - true_params["x1"]) y2 = m2 * (x - x2) y = np.minimum(y1, y2) - w = np.ones_like(x) - return x, y, w, true_params + return x, y, true_params # ----------------------------------------------------------------------------- @@ -1128,7 +1118,7 @@ def test_saturation_fit_recovers_exact_parameters_from_clean_data( clean_saturation_twoline_data, ): """Fitting noise-free Saturation data should recover parameters within 2%.""" - x, y, w, true_params, derived = clean_saturation_twoline_data + x, y, true_params, derived = clean_saturation_twoline_data obj = Saturation(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -1149,7 +1139,7 @@ def test_saturation_fit_recovers_exact_parameters_from_clean_data( def test_saturation_fit_recovers_small_theta_parameters(saturation_small_theta_data): """Fitting Saturation with small theta should recover parameters within 5%.""" - x, y, w, true_params = saturation_small_theta_data + x, y, true_params = saturation_small_theta_data obj = Saturation(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -1178,7 +1168,7 @@ def test_saturation_fit_with_noise_recovers_parameters_within_2sigma( noisy_saturation_twoline_data, ): """Fitted Saturation parameters should be within 2sigma of true values.""" - x, y, w, true_params = noisy_saturation_twoline_data + x, y, true_params = noisy_saturation_twoline_data obj = Saturation(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -1204,7 +1194,7 @@ def test_saturation_m1_property_is_consistent(clean_saturation_twoline_data): ON FAILURE: the code is wrong. """ - x, y, w, true_params, derived = clean_saturation_twoline_data + x, y, true_params, derived = clean_saturation_twoline_data obj = Saturation(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -1223,7 +1213,7 @@ def test_saturation_m2_property_is_consistent(clean_saturation_twoline_data): ON FAILURE: the code is wrong. """ - x, y, w, true_params, derived = clean_saturation_twoline_data + x, y, true_params, derived = clean_saturation_twoline_data obj = Saturation(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -1243,7 +1233,7 @@ def test_saturation_x2_property_is_consistent(clean_saturation_twoline_data): ON FAILURE: the code is wrong. """ - x, y, w, true_params, derived = clean_saturation_twoline_data + x, y, true_params, derived = clean_saturation_twoline_data obj = Saturation(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -1282,7 +1272,7 @@ def test_saturation_function_signature(): def test_saturation_popt_has_correct_keys(clean_saturation_twoline_data): """Test that Saturation popt contains expected parameter names.""" - x, y, w, true_params, derived = clean_saturation_twoline_data + x, y, true_params, derived = clean_saturation_twoline_data obj = Saturation(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -1297,7 +1287,7 @@ def test_saturation_popt_has_correct_keys(clean_saturation_twoline_data): def test_saturation_callable_interface(clean_saturation_twoline_data): """Test that fitted Saturation object is callable and returns correct shape.""" - x, y, w, true_params, derived = clean_saturation_twoline_data + x, y, true_params, derived = clean_saturation_twoline_data obj = Saturation(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -1361,8 +1351,7 @@ def clean_hingemin_data(): y1 = true_params["m1"] * (x - true_params["x1"]) y2 = m2 * (x - true_params["x2"]) y = np.minimum(y1, y2) - w = np.ones_like(x) - return x, y, w, true_params, {"m2": m2, "yh": yh} + return x, y, true_params, {"m2": m2, "yh": yh} @pytest.fixture @@ -1385,8 +1374,7 @@ def noisy_hingemin_data(): y_true = np.minimum(y1, y2) noise_std = 0.5 y = y_true + rng.normal(0, noise_std, len(x)) - w = np.ones_like(x) / noise_std - return x, y, w, true_params + return x, y, true_params @pytest.fixture @@ -1410,8 +1398,7 @@ def hingemin_positive_slopes_data(): y1 = true_params["m1"] * (x - true_params["x1"]) y2 = m2 * (x - true_params["x2"]) y = np.minimum(y1, y2) - w = np.ones_like(x) - return x, y, w, true_params + return x, y, true_params # ----------------------------------------------------------------------------- @@ -1490,7 +1477,7 @@ def test_hingemin_func_evaluates_line2_region_correctly(): def test_hingemin_fit_recovers_exact_parameters_from_clean_data(clean_hingemin_data): """Fitting noise-free HingeMin data should recover parameters within 2%.""" - x, y, w, true_params, derived = clean_hingemin_data + x, y, true_params, derived = clean_hingemin_data obj = HingeMin(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -1513,7 +1500,7 @@ def test_hingemin_fit_recovers_positive_slopes_parameters( hingemin_positive_slopes_data, ): """Fitting HingeMin with positive slopes should recover parameters within 2%.""" - x, y, w, true_params = hingemin_positive_slopes_data + x, y, true_params = hingemin_positive_slopes_data obj = HingeMin(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -1539,7 +1526,7 @@ def test_hingemin_fit_recovers_positive_slopes_parameters( def test_hingemin_fit_with_noise_recovers_parameters_within_2sigma(noisy_hingemin_data): """Fitted HingeMin parameters should be within 2sigma of true values.""" - x, y, w, true_params = noisy_hingemin_data + x, y, true_params = noisy_hingemin_data obj = HingeMin(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -1567,7 +1554,7 @@ def test_hingemin_m2_property_is_consistent(clean_hingemin_data): ON FAILURE: the code is wrong. """ - x, y, w, true_params, derived = clean_hingemin_data + x, y, true_params, derived = clean_hingemin_data obj = HingeMin(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -1587,7 +1574,7 @@ def test_hingemin_theta_property_is_consistent(clean_hingemin_data): ON FAILURE: the code is wrong. """ - x, y, w, true_params, derived = clean_hingemin_data + x, y, true_params, derived = clean_hingemin_data obj = HingeMin(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -1606,7 +1593,7 @@ def test_hingemin_lines_intersect_at_hinge(clean_hingemin_data): ON FAILURE: the code is wrong. """ - x, y, w, true_params, derived = clean_hingemin_data + x, y, true_params, derived = clean_hingemin_data obj = HingeMin(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -1650,7 +1637,7 @@ def test_hingemin_function_signature(): def test_hingemin_popt_has_correct_keys(clean_hingemin_data): """Test that HingeMin popt contains expected parameter names.""" - x, y, w, true_params, derived = clean_hingemin_data + x, y, true_params, derived = clean_hingemin_data obj = HingeMin(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -1665,7 +1652,7 @@ def test_hingemin_popt_has_correct_keys(clean_hingemin_data): def test_hingemin_callable_interface(clean_hingemin_data): """Test that fitted HingeMin object is callable and returns correct shape.""" - x, y, w, true_params, derived = clean_hingemin_data + x, y, true_params, derived = clean_hingemin_data obj = HingeMin(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -1729,8 +1716,7 @@ def clean_hingemax_data(): y1 = true_params["m1"] * (x - true_params["x1"]) y2 = m2 * (x - true_params["x2"]) y = np.maximum(y1, y2) - w = np.ones_like(x) - return x, y, w, true_params, {"m2": m2, "yh": yh} + return x, y, true_params, {"m2": m2, "yh": yh} @pytest.fixture @@ -1753,8 +1739,7 @@ def noisy_hingemax_data(): y_true = np.maximum(y1, y2) noise_std = 0.5 y = y_true + rng.normal(0, noise_std, len(x)) - w = np.ones_like(x) / noise_std - return x, y, w, true_params + return x, y, true_params @pytest.fixture @@ -1778,8 +1763,7 @@ def hingemax_negative_slopes_data(): y1 = true_params["m1"] * (x - true_params["x1"]) y2 = m2 * (x - true_params["x2"]) y = np.maximum(y1, y2) - w = np.ones_like(x) - return x, y, w, true_params + return x, y, true_params # ----------------------------------------------------------------------------- @@ -1858,7 +1842,7 @@ def test_hingemax_func_evaluates_line2_region_correctly(): def test_hingemax_fit_recovers_exact_parameters_from_clean_data(clean_hingemax_data): """Fitting noise-free HingeMax data should recover parameters within 2%.""" - x, y, w, true_params, derived = clean_hingemax_data + x, y, true_params, derived = clean_hingemax_data obj = HingeMax(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -1881,7 +1865,7 @@ def test_hingemax_fit_recovers_negative_slopes_parameters( hingemax_negative_slopes_data, ): """Fitting HingeMax with negative slopes should recover parameters within 2%.""" - x, y, w, true_params = hingemax_negative_slopes_data + x, y, true_params = hingemax_negative_slopes_data obj = HingeMax(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -1907,7 +1891,7 @@ def test_hingemax_fit_recovers_negative_slopes_parameters( def test_hingemax_fit_with_noise_recovers_parameters_within_2sigma(noisy_hingemax_data): """Fitted HingeMax parameters should be within 2sigma of true values.""" - x, y, w, true_params = noisy_hingemax_data + x, y, true_params = noisy_hingemax_data obj = HingeMax(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -1935,7 +1919,7 @@ def test_hingemax_m2_property_is_consistent(clean_hingemax_data): ON FAILURE: the code is wrong. """ - x, y, w, true_params, derived = clean_hingemax_data + x, y, true_params, derived = clean_hingemax_data obj = HingeMax(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -1955,7 +1939,7 @@ def test_hingemax_theta_property_is_consistent(clean_hingemax_data): ON FAILURE: the code is wrong. """ - x, y, w, true_params, derived = clean_hingemax_data + x, y, true_params, derived = clean_hingemax_data obj = HingeMax(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -1974,7 +1958,7 @@ def test_hingemax_lines_intersect_at_hinge(clean_hingemax_data): ON FAILURE: the code is wrong. """ - x, y, w, true_params, derived = clean_hingemax_data + x, y, true_params, derived = clean_hingemax_data obj = HingeMax(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -2018,7 +2002,7 @@ def test_hingemax_function_signature(): def test_hingemax_popt_has_correct_keys(clean_hingemax_data): """Test that HingeMax popt contains expected parameter names.""" - x, y, w, true_params, derived = clean_hingemax_data + x, y, true_params, derived = clean_hingemax_data obj = HingeMax(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -2033,7 +2017,7 @@ def test_hingemax_popt_has_correct_keys(clean_hingemax_data): def test_hingemax_callable_interface(clean_hingemax_data): """Test that fitted HingeMax object is callable and returns correct shape.""" - x, y, w, true_params, derived = clean_hingemax_data + x, y, true_params, derived = clean_hingemax_data obj = HingeMax(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -2091,8 +2075,7 @@ def clean_hingeatpoint_data(): y1 = true_params["m1"] * (x - x1) y2 = true_params["m2"] * (x - x2) y = np.minimum(y1, y2) - w = np.ones_like(x) - return x, y, w, true_params, {"x1": x1, "x2": x2} + return x, y, true_params, {"x1": x1, "x2": x2} @pytest.fixture @@ -2112,8 +2095,7 @@ def noisy_hingeatpoint_data(): y_true = np.minimum(y1, y2) noise_std = 0.5 y = y_true + rng.normal(0, noise_std, len(x)) - w = np.ones_like(x) / noise_std - return x, y, w, true_params + return x, y, true_params @pytest.fixture @@ -2132,8 +2114,7 @@ def hingeatpoint_positive_slopes_data(): y1 = true_params["m1"] * (x - x1) y2 = true_params["m2"] * (x - x2) y = np.minimum(y1, y2) - w = np.ones_like(x) - return x, y, w, true_params + return x, y, true_params # ----------------------------------------------------------------------------- @@ -2215,7 +2196,7 @@ def test_hingeatpoint_fit_recovers_exact_parameters_from_clean_data( clean_hingeatpoint_data, ): """Fitting noise-free HingeAtPoint data should recover parameters within 2%.""" - x, y, w, true_params, derived = clean_hingeatpoint_data + x, y, true_params, derived = clean_hingeatpoint_data obj = HingeAtPoint(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -2238,7 +2219,7 @@ def test_hingeatpoint_fit_recovers_positive_slopes_parameters( hingeatpoint_positive_slopes_data, ): """Fitting HingeAtPoint with positive slopes should recover parameters within 2%.""" - x, y, w, true_params = hingeatpoint_positive_slopes_data + x, y, true_params = hingeatpoint_positive_slopes_data obj = HingeAtPoint(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -2266,7 +2247,7 @@ def test_hingeatpoint_fit_with_noise_recovers_parameters_within_2sigma( noisy_hingeatpoint_data, ): """Fitted HingeAtPoint parameters should be within 2sigma of true values.""" - x, y, w, true_params = noisy_hingeatpoint_data + x, y, true_params = noisy_hingeatpoint_data obj = HingeAtPoint(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -2294,7 +2275,7 @@ def test_hingeatpoint_x_intercepts_property_has_correct_values(clean_hingeatpoin ON FAILURE: the code is wrong. """ - x, y, w, true_params, derived = clean_hingeatpoint_data + x, y, true_params, derived = clean_hingeatpoint_data obj = HingeAtPoint(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -2317,7 +2298,7 @@ def test_hingeatpoint_x_intercepts_property_has_correct_values(clean_hingeatpoin def test_hingeatpoint_x_intercepts_is_namedtuple(clean_hingeatpoint_data): """Verify x_intercepts is a namedtuple with x1 and x2 attributes.""" - x, y, w, true_params, derived = clean_hingeatpoint_data + x, y, true_params, derived = clean_hingeatpoint_data obj = HingeAtPoint(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -2331,7 +2312,7 @@ def test_hingeatpoint_lines_pass_through_hinge(clean_hingeatpoint_data): ON FAILURE: the code is wrong. """ - x, y, w, true_params, derived = clean_hingeatpoint_data + x, y, true_params, derived = clean_hingeatpoint_data obj = HingeAtPoint(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -2375,7 +2356,7 @@ def test_hingeatpoint_function_signature(): def test_hingeatpoint_popt_has_correct_keys(clean_hingeatpoint_data): """Test that HingeAtPoint popt contains expected parameter names.""" - x, y, w, true_params, derived = clean_hingeatpoint_data + x, y, true_params, derived = clean_hingeatpoint_data obj = HingeAtPoint(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -2390,7 +2371,7 @@ def test_hingeatpoint_popt_has_correct_keys(clean_hingeatpoint_data): def test_hingeatpoint_callable_interface(clean_hingeatpoint_data): """Test that fitted HingeAtPoint object is callable and returns correct shape.""" - x, y, w, true_params, derived = clean_hingeatpoint_data + x, y, true_params, derived = clean_hingeatpoint_data obj = HingeAtPoint(x, y, guess_xh=true_params["xh"]) obj.make_fit() @@ -2417,7 +2398,7 @@ def test_hingeatpoint_insufficient_data_raises_error(): def test_hingeatpoint_psigma_values_are_positive(noisy_hingeatpoint_data): """Test that all parameter uncertainties are positive.""" - x, y, w, true_params = noisy_hingeatpoint_data + x, y, true_params = noisy_hingeatpoint_data obj = HingeAtPoint(x, y, guess_xh=true_params["xh"]) obj.make_fit() From ad0696432e8add9e0637f35dfffd59f38a09ef78 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 06:18:15 -0500 Subject: [PATCH 52/60] fix(solar_activity): sort and index SIDC frames without inplace pandas deprecates inplace=True on sort_index and set_index (PDEP-8), and warned on every SIDC load and normalization. The loader rebinds the returned frames, and run_normalization replaces the loader's frame with the sorted one. Co-Authored-By: Claude Opus 5.5 --- .../solar_activity/sunspot_number/sidc.py | 8 +++++--- .../solar_activity/sunspot_number/test_sidc.py | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/solarwindpy/solar_activity/sunspot_number/sidc.py b/src/solarwindpy/solar_activity/sunspot_number/sidc.py index c60ae6a40..4d0e6dc9c 100644 --- a/src/solarwindpy/solar_activity/sunspot_number/sidc.py +++ b/src/solarwindpy/solar_activity/sunspot_number/sidc.py @@ -280,9 +280,9 @@ def read_data(self, path): csv.loc[:, "n_obs"].apply(np.sqrt), axis=0 ) csv.loc[:, "std_error"] = std_error - csv.sort_index(axis=1, inplace=True) + csv = csv.sort_index(axis=1) - csv.set_index(ts, inplace=True) + csv = csv.set_index(ts) self.convert_nans(csv) return csv @@ -449,7 +449,9 @@ def norm_fcn(g): normed = self._run_normalization(ssn, norm_fcn) self.data.loc[:, "nssn"] = normed - self.data.sort_index(axis=1, inplace=True) + # The loader holds the frame; sorting returns a new one (pandas deprecates + # inplace=True), which replaces it. + self.loader._data = self.data.sort_index(axis=1) try: interpolated = self.interpolated.loc[:, "ssn"] diff --git a/tests/solar_activity/sunspot_number/test_sidc.py b/tests/solar_activity/sunspot_number/test_sidc.py index ebdbe9835..1b156807b 100644 --- a/tests/solar_activity/sunspot_number/test_sidc.py +++ b/tests/solar_activity/sunspot_number/test_sidc.py @@ -418,6 +418,23 @@ def test_normalization_by_max_gives_each_cycle_a_unit_maximum(sidc): np.testing.assert_allclose(group.max(), 1.0) +@pytest.mark.filterwarnings("error:The inplace keyword") +def test_normalization_sorts_the_columns_without_inplace(sidc): + """``run_normalization`` adds ``nssn`` and keeps the columns sorted. + + pandas deprecates ``inplace=True``; the filter turns its warning into a + failure, so the sort must return a new frame. + + ON FAILURE: the code is wrong -- it sorts in place again, or the sorted + frame does not replace the loader's. + """ + sidc.run_normalization(norm_by="max") + + columns = list(sidc.data.columns) + assert "nssn" in columns + assert columns == sorted(columns) + + def test_normalization_by_max_preserves_the_ratio_to_the_peak(sidc): """Each normalized value is its share of its own cycle's peak. From 3f53b51fecc2154d46b16f4350bafed3b3b04dd3 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 06:24:48 -0500 Subject: [PATCH 53/60] fix(plotting): compute cell codes per call instead of caching them The get_plotted_data work cached each plot's cell codes as an int64 per row, so a plot on a shared BinnedData kept 8 B per row after agg where it kept about 1: ten Hist2D over 1e6 rows kept 83 MB against 3 MB, and the Usage guide's BinnedData numbers no longer held. agg computes the codes once per call and hands them to the groupby; get_plotted_data computes them once for the aggregate and the row lookup. A budget test now covers plots that have aggregated. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 ++- src/solarwindpy/plotting/base.py | 36 +++++++++++++----------------- tests/plotting/test_agg_count.py | 2 +- tests/plotting/test_plot_budget.py | 23 +++++++++++++++++++ 4 files changed, 42 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ef0c49f7..ffb8c6d16 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -72,7 +72,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `get_plotted_data(fcn=None)` on `Hist1D`, `Hist2D` and `SpiralPlot2D` returns the rows in the cells the figure shows (cells whose `agg(fcn)` is not NaN after `clim`, `axnorm`, any cell filter and `alim`), with the caller's x, y and z values on the caller's index. Pass the `fcn` - given to `make_plot`. Each plot computes its rows' cell codes once and reuses them in `agg`. + given to `make_plot`. Each call computes the rows' cell codes once, for the count, the + aggregation and the row lookup, and keeps none, so plots on a shared `BinnedData` stay small. - `Hist1D.set_alim` (with `alim` and `alim_kind`): the limits on the aggregated value of a bin, after `axnorm` and `clim`, as on `Hist2D` and `SpiralPlot2D`, which `get_plotted_data` honours. Every plot with `alim` now shares one implementation; `Scatter` still applies it to diff --git a/src/solarwindpy/plotting/base.py b/src/solarwindpy/plotting/base.py index 992394610..01ca80bca 100644 --- a/src/solarwindpy/plotting/base.py +++ b/src/solarwindpy/plotting/base.py @@ -996,24 +996,16 @@ def agg_axes(self): return self._source.columns[-1] def _cell_codes(self): - r"""``binning.codes()``, computed once per binning and data, read-only. + r"""``binning.codes()``: each kept row's cell, -1 in none. - The binning and the data are each set once, by the constructor, but - the cache is keyed on both objects, so replacing either recomputes. + Not cached: a code per row in a wide integer type would cost each plot + 8 B per row, where a plot on a shared ``BinnedData`` keeps about 1. + ``agg`` computes the codes once per call and passes them on. """ - binning = self.binning - source = self._source - cached = self.__dict__.get("_codes_cache") - if cached is None or cached[0] is not binning or cached[1] is not source: - codes = np.asarray(binning.codes()) - codes.setflags(write=False) - cached = (binning, source, codes) - self._codes_cache = cached - return cached[2] - - def _grouped_by_cell(self): - r"""The aggregated column on the rows in a cell, grouped by cell code.""" - codes = self._cell_codes() + return np.asarray(self.binning.codes()) + + def _grouped_by_cell(self, codes): + r"""The aggregated column on the rows in a cell, grouped by ``codes``.""" # By position: the groups are keyed by `codes`, never by row label. target = self._source.take(self.agg_axes, labels=False) inside = codes >= 0 @@ -1053,6 +1045,10 @@ def agg(self, fcn=None, **kwargs): ValueError For a share of a sum when a row in a cell has a negative value. """ + return self._agg(fcn, self._cell_codes(), **kwargs) + + def _agg(self, fcn, codes, **kwargs): + r"""``agg`` on the rows' cell ``codes``, which the caller computed.""" tko = self.agg_axes lbls = self._flat_labels() @@ -1069,7 +1065,6 @@ def agg(self, fcn=None, **kwargs): # cells, as a groupby count would, so empty cells stay NaN after the # reindex below. The aggregated column has no NaN on kept rows, so # this equals its groupby count. It serves clim and axnorm. - codes = self._cell_codes() n = np.bincount(codes[codes >= 0], minlength=len(self.binning.cells)) occupied = np.flatnonzero(n) cnt = pd.Series( @@ -1081,7 +1076,7 @@ def agg(self, fcn=None, **kwargs): # Count fast path: the counts are the aggregate; no groupby. agg = cnt else: - agg = self._grouped_by_cell().agg(fcn, **kwargs) + agg = self._grouped_by_cell(codes).agg(fcn, **kwargs) if kind == "sum" and self.axnorm in _SHARE_AXNORMS: values = self._source.take(self.agg_axes, labels=False).to_numpy() @@ -1128,8 +1123,9 @@ def _plotted_rows(self, fcn=None): A cell is shown where ``agg(fcn)`` is not NaN. Looked up by cell code, with code -1 (no cell) mapped to the appended False. """ - shown = self.agg(fcn=fcn).notna().to_numpy() - return np.append(shown, False)[self._cell_codes()] + codes = self._cell_codes() + shown = self._agg(fcn, codes).notna().to_numpy() + return np.append(shown, False)[codes] def _kept_source_frame(self): r"""The caller's values on the kept rows, one column per ``data`` column. diff --git a/tests/plotting/test_agg_count.py b/tests/plotting/test_agg_count.py index 48af012f9..67677e0e4 100644 --- a/tests/plotting/test_agg_count.py +++ b/tests/plotting/test_agg_count.py @@ -89,7 +89,7 @@ def test_a_count_does_not_group_the_rows(): """ h = Hist2D(X, Y, nbins=15) - def refuse(): + def refuse(*args): raise AssertionError("count went through the groupby") h._grouped_by_cell = refuse diff --git a/tests/plotting/test_plot_budget.py b/tests/plotting/test_plot_budget.py index 3a991448d..bb34da0ac 100644 --- a/tests/plotting/test_plot_budget.py +++ b/tests/plotting/test_plot_budget.py @@ -164,6 +164,29 @@ def test_plots_on_one_shared_binned_data_cost_about_one_byte_per_row_each( # 0.5 B headroom: the plan's 1.5 per extra plot (measured 1.02). assert per_row / plots <= 1.5, f"{per_row / plots:.2f} B/row per plot" + def test_aggregating_keeps_no_per_row_codes(self, with_nan): + """``agg`` and ``get_plotted_data`` keep the shared plots' budget. + + Each call computes the rows' cell codes and lets them go, so a plot on + a shared BinnedData still keeps at most 1.5 B/row after it aggregates. + A cached int64 code per row would keep 8. + + ON FAILURE: the code is wrong, unless the author changes the budget. + """ + f = with_nan + shared = BinnedData(f, {"x": EDGES, "y": EDGES}) + plots = 4 + + def build(): + built = [Hist2D(f.x, f.y, nbins=shared) for _ in range(plots)] + for plot in built: + plot.agg() + plot.get_plotted_data() + return built + + per_row = _retained_per_row(build) + assert per_row / plots <= 1.5, f"{per_row / plots:.2f} B/row per plot" + def test_scatter_keeps_only_a_row_mask(self, with_nan): """Scatter keeps at most 1.5 B/row: a mask, not a copy of x and y. From bc2c745ad1b726d271ae842e2cdc2db63d8b11f8 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 06:27:16 -0500 Subject: [PATCH 54/60] test(docs): prove the plot-block guards fire The guards against an empty block and a block that names a script read a collector no test exercised on a bad page. They are now functions of the collected blocks, the empty-block guard is a test of its own, and a test feeds them a temporary page holding one of each. Co-Authored-By: Claude Opus 5.5 --- tests/test_docs_plot_blocks.py | 64 ++++++++++++++++++++++++++++++---- 1 file changed, 58 insertions(+), 6 deletions(-) diff --git a/tests/test_docs_plot_blocks.py b/tests/test_docs_plot_blocks.py index e5a50a974..6b374be2f 100644 --- a/tests/test_docs_plot_blocks.py +++ b/tests/test_docs_plot_blocks.py @@ -60,11 +60,26 @@ def _plot_blocks(path): yield i + 1, match.group(2).strip(), code + "\n" if code else "" -FOUND = [ - (f"{path.relative_to(DOCS)}:{line}", argument, code) - for path in sorted(DOCS.rglob("*.rst")) - for line, argument, code in _plot_blocks(path) -] +def _found(root): + """``(where, argument, code)`` of every ``.. plot::`` block under ``root``.""" + return [ + (f"{path.relative_to(root)}:{line}", argument, code) + for path in sorted(root.rglob("*.rst")) + for line, argument, code in _plot_blocks(path) + ] + + +def _named(found): + """The blocks that name a script instead of holding their code.""" + return [f"{where}: plot:: {argument}" for where, argument, _ in found if argument] + + +def _empty(found): + """The inline blocks with no code.""" + return [where for where, argument, code in found if not argument and not code] + + +FOUND = _found(DOCS) BLOCKS = [pytest.param(code, id=where) for where, _, code in FOUND] @@ -75,10 +90,47 @@ def test_the_guide_has_plot_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] + named = _named(FOUND) assert not named, named +def test_no_plot_block_is_empty(): + """Every inline block holds code, so each figure has code beside it.""" + empty = _empty(FOUND) + assert not empty, empty + + +def test_the_guards_catch_an_empty_and_a_named_block(tmp_path): + """The collector and both guards fire on a page that breaks them. + + A page with an empty inline block (options only), a block naming a + script, and one good block: the guards name exactly the two bad ones. + + ON FAILURE: the code is wrong -- the collector misreads a block, so the + guards above can pass on a page that breaks them. + """ + (tmp_path / "page.rst").write_text( + "Title\n" + "=====\n" + "\n" + ".. plot::\n" + " :include-source: false\n" + "\n" + "Some text.\n" + "\n" + ".. plot:: figure.py\n" + "\n" + ".. plot::\n" + "\n" + " import matplotlib.pyplot as plt\n" + " plt.plot([0, 1])\n" + ) + found = _found(tmp_path) + assert len(found) == 3 + assert _empty(found) == ["page.rst:4"] + assert _named(found) == ["page.rst:9: plot:: figure.py"] + + def _no_download(url, cache): raise AssertionError(f"a plot block tried to download {url}") From 19d3bf744e5e01deb2491faabee126a939f2f14b Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 06:29:15 -0500 Subject: [PATCH 55/60] docs(usage): reproducible BinnedData numbers and the unnamed-Series pitfall The shared-bins doctest pinned a slow-wind count of 6947; every point lies inside the edges, so it now states the relation: each plot counts the rows it keeps. A doctest shows the KeyError an unnamed Series raises. The time and memory figures come from scripts/benchmark_binned_data.py, which the guide links, rerun on this branch. Co-Authored-By: Claude Opus 5.5 --- docs/source/usage.rst | 33 +++++++--- scripts/benchmark_binned_data.py | 104 +++++++++++++++++++++++++++++++ 2 files changed, 127 insertions(+), 10 deletions(-) create mode 100644 scripts/benchmark_binned_data.py diff --git a/docs/source/usage.rst b/docs/source/usage.rst index aeb99320e..f77c8e87d 100644 --- a/docs/source/usage.rst +++ b/docs/source/usage.rst @@ -540,16 +540,29 @@ dtype('int8') >>> 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. +>>> int(counts.agg().sum()) == N +True +>>> int(slow.agg().sum()) == int((frame["v"] < 500).sum()) +True + +Every point lies inside the edges, so the counts add up to the rows a plot +keeps. A plot passed an unnamed Series, or one renamed after the +``BinnedData`` was built, cannot find its column: + +>>> Hist2D(pd.Series(speed), frame["n"], nbins=binned) +Traceback (most recent call last): +... +KeyError: "The BinnedData has no column None, the name of x; its columns are ('v', 'n')." + +Sharing saves time and memory. Building and aggregating ten ``Hist2D`` of +different ``z`` over one 70 by 50 grid of :math:`10^6` points took 0.17 s with +a shared ``BinnedData`` and 0.34 s when each plot binned its own columns, the +median of three runs on an Apple M3 (Python 3.12, pandas 3.1, NumPy 2.5). +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 52 MB against 71 MB. The script that measures them, +:download:`benchmark_binned_data.py <../../scripts/benchmark_binned_data.py>`, +prints the numbers for your machine. Two plots on one ``BinnedData``, the counts and the mean thermal speed in each cell: diff --git a/scripts/benchmark_binned_data.py b/scripts/benchmark_binned_data.py new file mode 100644 index 000000000..e95ea564a --- /dev/null +++ b/scripts/benchmark_binned_data.py @@ -0,0 +1,104 @@ +# Spent-When: PERMANENT(the Usage guide stops quoting BinnedData timings) +# Supersedes: none +"""Measure what sharing one ``BinnedData`` across plots saves. + +Builds and aggregates ten ``Hist2D`` of different ``z`` over one 70 by 50 grid +of 10**6 points, once with a shared ``BinnedData`` and once with each plot +binning its own columns. Prints the median wall time of three runs, and, from +:mod:`tracemalloc` (Python and NumPy allocations), the memory the ten plots +and their aggregates keep and the peak during the build. + +The Usage guide ("Share bins across plots") quotes these numbers. Run it from +the repository root in the ``solarwindpy`` environment:: + + python scripts/benchmark_binned_data.py +""" + +import gc +import platform +import statistics +import time +import tracemalloc + +import numpy as np +import pandas as pd + +from solarwindpy.plotting.binned import BinnedData +from solarwindpy.plotting.hist2d import Hist2D + +N = 1_000_000 +N_PLOTS = 10 +RUNS = 3 +EDGES = {"v": np.linspace(150, 950, 71), "n": np.linspace(-0.5, 2.0, 51)} + + +def make_frame(seed=0): + """Return ``N`` rows of ``v``, ``n`` and ``N_PLOTS`` z columns.""" + rng = np.random.default_rng(seed) + fast = rng.random(N) < 0.3 + v = np.where(fast, rng.normal(650, 60, N), rng.normal(380, 50, N)) + columns = { + "v": v, + "n": 8 * 10 ** (-0.0015 * (v - 400) + rng.normal(0, 0.15, N)), + } + for i in range(N_PLOTS): + columns[f"z{i}"] = rng.normal(i, 1, N) + return pd.DataFrame(columns) + + +def build_shared(frame): + """Ten plots on one ``BinnedData``; return the plots and their aggregates.""" + binned = BinnedData(frame[["v", "n"]], EDGES, log={"n": True}) + plots = [ + Hist2D(frame["v"], frame["n"], frame[f"z{i}"], nbins=binned) + for i in range(N_PLOTS) + ] + return plots, [p.agg() for p in plots] + + +def build_separate(frame): + """Ten plots that each bin their own columns on the same edges.""" + nbins = (EDGES["v"], EDGES["n"]) + plots = [ + Hist2D(frame["v"], frame["n"], frame[f"z{i}"], nbins=nbins, logy=True) + for i in range(N_PLOTS) + ] + return plots, [p.agg() for p in plots] + + +def wall_time(build, frame): + """Median seconds of ``RUNS`` builds.""" + times = [] + for _ in range(RUNS): + gc.collect() + start = time.perf_counter() + build(frame) + times.append(time.perf_counter() - start) + return statistics.median(times) + + +def memory(build, frame): + """MB kept by the result and MB at the peak of one build.""" + gc.collect() + tracemalloc.start() + kept = build(frame) + current, peak = tracemalloc.get_traced_memory() + tracemalloc.stop() + del kept + return current / 1e6, peak / 1e6 + + +def main(): + frame = make_frame() + print( + f"{platform.machine()} Python {platform.python_version()}, " + f"pandas {pd.__version__}, NumPy {np.__version__}" + ) + for name, build in [("shared", build_shared), ("separate", build_separate)]: + seconds = wall_time(build, frame) + kept, peak = memory(build, frame) + print(f"{name:9s} {seconds:.2f} s kept {kept:.0f} MB peak {peak:.0f} MB") + + +if __name__ == "__main__": + main() From bd7d8229e546276e715b079c52f01a39f4181b5f Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 06:31:29 -0500 Subject: [PATCH 56/60] docs(conf): alias mpl.collections.LineCollection like its siblings Scatter.make_plot's Returns names the segments as mpl.collections.LineCollection, as it names the points and colorbar. Co-Authored-By: Claude Opus 5.5 --- docs/source/conf.py | 1 + src/solarwindpy/plotting/scatter.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/source/conf.py b/docs/source/conf.py index aa914cf8f..89d92ac7e 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -156,6 +156,7 @@ "mpl.collections.QuadMesh": "matplotlib.collections.QuadMesh", "mpl.collections.PathCollection": "matplotlib.collections.PathCollection", "mpl.collections.PolyCollection": "matplotlib.collections.PolyCollection", + "mpl.collections.LineCollection": "matplotlib.collections.LineCollection", "mpl.container.ErrorbarContainer": "matplotlib.container.ErrorbarContainer", "mpl.lines.Line2D": "matplotlib.lines.Line2D", "mpl.colorbar.Colorbar": "matplotlib.colorbar.Colorbar", diff --git a/src/solarwindpy/plotting/scatter.py b/src/solarwindpy/plotting/scatter.py index a7b4d40d7..a864fcf0e 100644 --- a/src/solarwindpy/plotting/scatter.py +++ b/src/solarwindpy/plotting/scatter.py @@ -102,7 +102,7 @@ def make_plot( ax: mpl.axes.Axes collection: mpl.collections.PathCollection The points. - segments: matplotlib.collections.LineCollection or None + segments: mpl.collections.LineCollection or None The segments joining the points if `connect` is True, else None. cbar: mpl.colorbar.Colorbar or None The colorbar if `cbar` is True and z varies, else None. From 73854255583a4c9c0bec78358c1324d07a6dbcb7 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 06:38:07 -0500 Subject: [PATCH 57/60] docs: normalizations, data selection, publication format, repr, info, yerr Usage guide: - Normalizations states what d, w and t compute for a count, a sum and any other aggregation, with the cell math, the column and row variants, doctests that the density integrates and the weights sum, and a figure contrasting a count PDF with the weight of a signed mean on the centred diverging colour scale. - A new "Select the data a figure shows" covers clim, alim (Hist1D included) and get_plotted_data(fcn), which replace the removed selection methods. - A new "Publication format" covers set_publication_format, the per-label override, name=, the count symbols and density units, with a figure. - Plot a Fit fits with yerr and draws the error bars. Quickstart: Plasma.info() on the example plasma, the printed summary of a Hist2D, and a Line fit with yerr. Co-Authored-By: Claude Opus 5.5 --- docs/source/tutorial/quickstart.rst | 50 +++++- docs/source/usage.rst | 238 +++++++++++++++++++++++++--- 2 files changed, 268 insertions(+), 20 deletions(-) diff --git a/docs/source/tutorial/quickstart.rst b/docs/source/tutorial/quickstart.rst index bda109115..2012e209d 100644 --- a/docs/source/tutorial/quickstart.rst +++ b/docs/source/tutorial/quickstart.rst @@ -37,6 +37,20 @@ display: The species are alphas (``a``), electrons (``e``), the proton core (``p1``) and a proton beam (``p2``), a second proton population. +:py:meth:`~solarwindpy.core.plasma.Plasma.info` summarises a plasma in one +table: its spacecraft and frame, the first and last times, the number of +observations, the species and whether auxiliary data are attached: + +>>> plasma.info() + value +spacecraft PSP +frame HCI +start 1995-01-01 12:35:00 +end 2022-10-09 01:47:01.234560 +observations 3 +species a, e, p1, p2 +auxiliary data no + The measurements live in one pandas DataFrame, ``plasma.data``. Its columns are a three-level MultiIndex: @@ -167,6 +181,22 @@ rows make only a demonstration, so this histogram uses three bins per axis: >>> int(h.agg().sum()) 3 +Printing a plot, or leaving it as the last line of a Jupyter cell, shows a +summary: per axis its label, its bins and their range, and the range of the +data on it, then the rows kept, the log flags, the bins per axis, ``axnorm`` +and the ``path``. The axes are labelled ``x`` and ``y`` until labels are set: + +>>> print(h) +Hist2D + x: x bins 3 [1, 3] data [1, 3] + y: y bins 3 [458.3, 1044] data [458.3, 1044] + z: $\mathrm{Count} \; \left[\#\right]$ + observations: 3 + log: x=False, y=False + bins: x: 3, y: 3 + axnorm: None + path: Hist2D/x/y/count/linX-linY + Without a ``z`` value, :py:meth:`~solarwindpy.plotting.hist2d.Hist2D.agg` counts the points in each bin. Axis labels name the quantities, and the plot's ``path`` is built from them: @@ -221,7 +251,25 @@ uncertainty is the square root of a diagonal element of the parameter covariance ``pcov``, and ``pcov`` is always rescaled by the fit's robust reduced chi-squared; ``make_fit(absolute_sigma=True)`` raises ``NotImplementedError``. Measurement uncertainties enter through the ``yerr`` argument, the 1-sigma -uncertainties of ``y``, one per observation. +uncertainties of ``y``, one per observation, as +:func:`scipy.optimize.curve_fit` takes ``sigma``. The noise above has a +standard deviation of 0.5, so with ``yerr=0.5`` for every point the linear +reduced chi-squared is near 1, as it should be for a good fit with the right +uncertainties. The fitted parameters are the same, since equal uncertainties +weight every point alike: + +>>> yerr = np.full(x.size, 0.5) +>>> weighted = swp.fitfunctions.lines.Line(x, y, yerr=yerr) +>>> weighted.make_fit() +>>> {name: round(float(value), 2) for name, value in weighted.popt.items()} +{'m': 1.99, 'b': 1.1} +>>> round(float(weighted.chisq_dof.linear), 2) +0.8 +>>> weighted.observations.used.yerr[:3] +array([0.5, 0.5, 0.5]) + +``yerr_min`` and ``yerr_max`` drop the observations whose uncertainty is +outside those bounds, as ``xmin`` and ``xmax`` do for ``x``. ``chisq_dof`` has two kinds. ``linear`` is the sum of squared residuals, divided by ``yerr`` when given, per degree of freedom. ``robust`` is the diff --git a/docs/source/usage.rst b/docs/source/usage.rst index f77c8e87d..29cbf087d 100644 --- a/docs/source/usage.rst +++ b/docs/source/usage.rst @@ -604,24 +604,71 @@ cell: Normalizations ~~~~~~~~~~~~~~ -``axnorm`` normalizes the aggregated values: - -- ``None``: no normalization; counts, or the aggregated ``y`` or ``z``. -- ``"t"``: divide by the maximum, so the peak is 1. -- ``"d"``: divide by the total and by each bin's width (1-D) or area (2-D), a - probability density. On a log axis the width is measured in - :math:`\log_{10}`. -- ``"c"`` and ``"r"``: divide each column (``x`` bin) or row (``y`` bin) by its - own maximum, so every column or row peaks at 1. Use them to compare shapes - across ``x`` when the counts vary greatly with ``x``. -- ``"cd"`` and ``"rd"``: make each column or row a probability density along - the other axis: divide by its total and by the bin width along that axis. +``axnorm`` normalizes the aggregated values, and what it computes depends on +the aggregation, ``make_plot``'s ``fcn``. For cell :math:`i`, let +:math:`n_i` be its rows, :math:`A_i` its area (its width in 1-D, measured in +:math:`\log_{10}` along a log axis), :math:`v_i` its aggregated value and +:math:`S_i` the sum of ``z`` over its rows; :math:`N = \sum_i n_i` and +:math:`S = \sum_i S_i` run over the cells the plot shows. There are three +families, a density ``"d"``, a weight ``"w"`` and a scaling ``"t"``: + +.. list-table:: + :header-rows: 1 + + * - aggregation + - ``"d"`` + - ``"w"`` + - ``"t"`` + * - a count (no ``z``, or ``fcn="count"``) + - :math:`n_i / (N A_i)` + - :math:`n_i / N` + - :math:`n_i / \max_j n_j` + * - a sum (``fcn="sum"`` or :func:`numpy.sum`) + - :math:`S_i / (S A_i)` + - :math:`S_i / S` + - :math:`S_i / \max_j |S_j|` + * - any other (``"mean"``, ``"median"``, a callable) + - :math:`v_i n_i / (N A_i)` + - :math:`v_i n_i / N` + - :math:`v_i / \max_j |v_j|` + +- A count's ``"d"`` is the probability density, :math:`\sum_i d_i A_i = 1`, + and its ``"w"`` the fraction of the rows in each cell, which sums to 1. +- A sum's ``"d"`` and ``"w"`` are each cell's share of the total ``z``, per + unit area for ``"d"``. A share needs ``z`` >= 0, so a negative ``z`` in a + cell raises ``ValueError``. A callable that adds is still "any other"; pass + ``"sum"`` for a share. +- Any other aggregation is weighted by its rows: ``"d"`` integrates, and + ``"w"`` sums, to :math:`\sum_i v_i n_i / N`, the count-weighted average of + :math:`v`. For a mean that is the mean ``z`` of the rows shown, so ``"w"`` + shows how much each cell contributes to it. +- ``"t"`` divides by the largest magnitude, so the peak is 1, or -1 when the + largest value is negative. + +``"cd"``, ``"wc"`` and ``"c"`` do the same within each column (``x`` bin): +:math:`N` and :math:`S` are the column's, the area is the bin's height, and +``"c"`` divides by the column's largest magnitude. ``"rd"``, ``"wr"`` and +``"r"`` do it within each row (``y`` bin). Use ``"c"`` or ``"cd"`` to compare +the shape of ``y`` across ``x`` when the counts vary greatly with ``x``. The +sums hold to rounding: + +>>> from solarwindpy.plotting.hist2d import Hist2D +>>> h1 = Hist1D(v, nbins=20, axnorm="d") +>>> round(float((h1.agg() * h1.intervals["x"].length).sum()), 6) +1.0 +>>> y = (v / 100 + rng.normal(0, 0.5, v.size)).rename("y") +>>> round(float(Hist2D(v, y, nbins=10, axnorm="w").agg().sum()), 6) +1.0 +>>> z = (v - 400).rename("z") +>>> mean_z = Hist2D(v, y, z, nbins=10, axnorm="w").agg(fcn="mean") +>>> bool(np.isclose(mean_z.sum(), z.mean())) +True The binning decides which keys a plot accepts. -:py:class:`~solarwindpy.plotting.hist2d.Hist2D` accepts all six; +:py:class:`~solarwindpy.plotting.hist2d.Hist2D` accepts all nine; :py:class:`~solarwindpy.plotting.hist1d.Hist1D` and -:py:class:`~solarwindpy.plotting.spiral.SpiralPlot2D` accept ``"d"`` and -``"t"``, since they have no rows or columns; a +:py:class:`~solarwindpy.plotting.spiral.SpiralPlot2D` accept ``"d"``, ``"t"`` +and ``"w"``, since they have no rows or columns; a :py:class:`~solarwindpy.plotting.scatter.Scatter` has no bins and no ``axnorm``. Any other key raises: @@ -632,8 +679,12 @@ Traceback (most recent call last): ... ValueError: Unrecognized axnorm 'c'; expected one of: d, t, w -With ``"c"`` or ``"r"`` the colorbar defaults to ten bands on [0, 1]; with the -densities it is logarithmic. Four normalizations of the same data: +The colour scale follows the values. Values of both signs get a scale centred +on zero, :class:`~matplotlib.colors.CenteredNorm` with the diverging colormap +``RdBu_r``, whatever the ``axnorm``. Otherwise ``"c"`` and ``"r"`` get ten +bands on [0, 1] and the densities a logarithmic scale. A ``norm`` or ``cmap`` +passed to ``make_plot`` is used as given. Four normalizations of the same +counts: .. plot:: @@ -658,6 +709,82 @@ densities it is logarithmic. Four normalizations of the same data: ax.label_outer() fig.tight_layout() +A density of the counts against the weight of a signed mean: the left panel +is where the rows are, and the right is how much each cell adds to the mean +:math:`B_x`, here positive in the fast wind and negative in the slow. Its +values hold both signs, so the scale is centred on zero, and its cells sum to +the mean :math:`B_x` of all the rows: + +.. plot:: + + import numpy as np + import pandas as pd + import matplotlib.pyplot as plt + 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 = pd.Series(np.where(fast, rng.normal(650, 60, N), rng.normal(380, 50, N)), name="v") + n = (8 * 10 ** (-0.0015 * (v - 400) + rng.normal(0, 0.15, N))).rename("n") + bx = (0.01 * (v - 450) + rng.normal(0, 2, N)).rename("bx") + + pdf = Hist2D(v, n, logy=True, nbins=40, axnorm="d") + weight = Hist2D(v, n, bx, logy=True, nbins=40, axnorm="w") + weight.set_labels(z=TeXlabel(("b", "x", ""), axnorm="w")) + + fig, axes = plt.subplots(1, 2, figsize=(10, 4), sharey=True) + for h2, ax in zip([pdf, weight], axes): + h2.set_labels(x=TeXlabel(("v", "", "p1")), y=TeXlabel(("n", "", "p1"))) + pdf.make_plot(ax=axes[0]) + weight.make_plot(ax=axes[1], fcn="mean") + axes[0].set_title('count, axnorm="d"') + axes[1].set_title('mean $B_x$, axnorm="w"') + axes[1].set_ylabel("") + fig.tight_layout() + +Select the data a figure shows +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Two limits decide which cells a binned plot shows. ``set_clim`` bounds the +number of rows in a cell; ``set_alim`` bounds the aggregated value, after +``axnorm`` and ``clim``. Bounds are inclusive and None leaves a side open; +``set_alim(..., kind="quantile")`` reads them as quantiles of the aggregated +values. A cell outside either limit is NaN in ``agg`` and blank in the figure. +Every binned plot, ``Hist1D`` included, has both. Here the bins with at least +20 rows, then the bins at least a tenth of the peak: + +>>> h1 = Hist1D(v, nbins=20) +>>> counts = h1.agg() +>>> h1.set_clim(20, None) +>>> int(h1.agg().notna().sum()), int(counts[counts >= 20].sum()) +(11, 953) +>>> h1 = Hist1D(v, nbins=20, axnorm="t") +>>> h1.set_alim(0.1, None) +>>> int(h1.agg().notna().sum()) +11 + +``get_plotted_data`` returns the rows in the cells the figure shows: the +values you passed, on your index, in your order. ``alim`` acts on the +aggregated value, so pass the ``fcn`` you give ``make_plot``. Here the cells +with at least 10 rows whose mean ``z`` is not negative: + +>>> len(h1.get_plotted_data()) +953 +>>> h2 = Hist2D(v, y, z, nbins=10) +>>> h2.set_clim(10, None) +>>> h2.set_alim(0, None) +>>> rows = h2.get_plotted_data(fcn="mean") +>>> list(rows.columns) +['x', 'y', 'z'] +>>> shown = h2.agg(fcn="mean").notna() +>>> len(rows) == int(Hist2D(v, y, nbins=10).agg()[shown].sum()) +True + +For a boolean mask over your data, use ``v.index.isin(rows.index)`` on a +unique index. + Labels ~~~~~~ @@ -714,6 +841,77 @@ $\mathrm{Column \, Probability \, Density}$ ``solarwindpy.plotting.labels.available()`` prints every measurement, component and species ``TeXlabel`` knows, and the special labels. +Publication format +~~~~~~~~~~~~~~~~~~ + +In publication format a label is two lines: its name in words over its symbol +and units. Turn it on for one label with ``publication_format=True``, or for +every label with +:py:func:`~solarwindpy.plotting.labels.base.set_publication_format`, which +:py:func:`~solarwindpy.plotting.labels.base.publication_format` reads back. A +label's own setting overrides the default. The name comes from the quantity +registry; ``name=`` replaces it, and a ratio is named after its parts: + +>>> print(TeXlabel(("n", "", "p1"), publication_format=True)) +Number Density +$n_{p_1} \; \left[\mathrm{cm}^{-3}\right]$ +>>> print(TeXlabel(("v", "", "p1"), name="Solar Wind Speed", publication_format=True)) +Solar Wind Speed +${v}_{{p_1}} \; \left[\mathrm{km \; s^{-1}}\right]$ +>>> print(TeXlabel(("n", "", "a"), ("n", "", "p1"), publication_format=True)) +Number Density Ratio +$n_{\alpha}/n_{p_1} \; \left[\#\right]$ + +A :py:class:`~solarwindpy.plotting.labels.special.Count` in publication format +is its normalization's name over a symbol: :math:`N` for a count, +:math:`N / N_{\max}` for ``"t"``, :math:`N / N_{\mathrm{tot}}` for ``"w"`` +and :math:`p` for a probability density. A density's units are the inverse of +the binned axes' units, :math:`\mathrm{dex}^{-1}` along a log axis, read from +the plot's axis labels: + +>>> from solarwindpy.plotting.labels.base import set_publication_format +>>> from solarwindpy.plotting.labels.special import Count +>>> print(Count(norm="w", publication_format=True)) +Count Fraction +$N / N_{\mathrm{tot}} \; \left[\#\right]$ +>>> h2 = Hist2D(v, y, logy=True, axnorm="d") +>>> h2.set_labels(x=TeXlabel(("v", "", "p1")), y=TeXlabel(("n", "", "p1"))) +>>> set_publication_format(True) +>>> print(h2.labels.z) +Probability Density +$p \; \left[\left(\mathrm{km \; s^{-1}}\right)^{-1} \, \mathrm{dex}^{-1}\right]$ +>>> print(TeXlabel(("n", "", "p1"), publication_format=False)) +$n_{p_1} \; \left[\mathrm{cm}^{-3}\right]$ +>>> set_publication_format(False) + +Labels read the default when they are drawn, so ``set_publication_format`` +also changes the labels of plots already built. A figure in publication +format, its speed axis renamed: + +.. plot:: + + import numpy as np + import pandas as pd + from solarwindpy.plotting.hist2d import Hist2D + from solarwindpy.plotting.labels.base import TeXlabel, set_publication_format + + set_publication_format(True) # every label: its name over its symbol + + rng = np.random.default_rng(0) + N = 20_000 + fast = rng.random(N) < 0.3 + v = pd.Series(np.where(fast, rng.normal(650, 60, N), rng.normal(380, 50, N)), name="v") + n = (8 * 10 ** (-0.0015 * (v - 400) + rng.normal(0, 0.15, N))).rename("n") + + h2 = Hist2D(v, n, logy=True, nbins=50, axnorm="d") + h2.set_labels( + x=TeXlabel(("v", "", "p1"), name="Solar Wind Speed"), # replaces the name + y=TeXlabel(("n", "", "p1")), # the registry's name, "Number Density" + ) + h2.make_plot() + + set_publication_format(False) # restore the one-line default + Plot a Fit ---------- @@ -743,7 +941,9 @@ in percent of the fit instead, which is large wherever the fit nears zero. The plotter labels its axes ``x`` and ``y`` until its ``set_labels`` sets them, as for the plots above; here the counts of a velocity component. The Gaussian is the seeded, noisy one whose results table -:doc:`tutorial/quickstart` prints: +:doc:`tutorial/quickstart` prints, fitted with ``yerr``, the 1-sigma +uncertainty of each ``y`` (the noise's 0.3), which the plot draws as error +bars: .. plot:: @@ -755,7 +955,7 @@ Gaussian is the seeded, noisy one whose results table rng = np.random.default_rng(1) x = np.linspace(-5, 5, 41) y = 10.0 * np.exp(-0.5 * ((x - 0.5) / 1.2) ** 2) + rng.normal(0.0, 0.3, x.size) - fit = Gaussian(x, y) + fit = Gaussian(x, y, yerr=np.full(x.size, 0.3)) fit.make_fit() fit.plotter.set_labels(x=TeXlabel(("v", "x", "p1")), y=Count()) fit.plotter.plot_raw_used_fit_resid(resid_kwargs=dict(resid_pct=False)) From 91da03605170db4c216632ae05b0ba5cb12a8cb2 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 06:43:20 -0500 Subject: [PATCH 58/60] docs(changelog): record the integration follow-ups Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ffb8c6d16..df7bec454 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -103,6 +103,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 time colorbar with `SIDC("m13").plot_on_colorbar`. The docs build and the plot-block test read the series from a snapshot in `docs/source/_data` through a private download cache, so neither needs the network. +- The Usage guide documents what each `axnorm` computes for a count, a sum and any other + aggregation, with a figure of the weight of a signed mean on the centred colour scale; + selecting cells with `clim` and `alim` and their rows with `get_plotted_data`; and the + publication format. The quickstart shows `Plasma.info`, a plot's printed summary and a fit + with `yerr`. `scripts/benchmark_binned_data.py` measures the time and memory a shared + `BinnedData` saves, the numbers the Usage guide quotes. ### Changed @@ -114,6 +120,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - A count in `agg` (`fcn="count"`, or the default on a plot without z) counts each cell's rows with `numpy.bincount` of the rows' cell codes instead of a pandas groupby: same result, about twice as fast at 1e6 rows. +- `solarwindpy.plotting.labels.base.validate_axnorm` takes the accepted keys, `allowed` + (default every key of `AXNORM`), and is the one check of an `axnorm` key: the plots call it + with their binning's `allowed_axnorm`, with the same messages as before. ### Fixed @@ -163,6 +172,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `TeXlabel` accepts the `"cd"` and `"rd"` normalizations that `Count` accepts. Both read the keys from one table, `solarwindpy.plotting.labels.base.AXNORM`, and raise `ValueError` (was `AssertionError`) for any other key. +- `SIDC` no longer warns that pandas deprecates `inplace=True` each time it loads or + normalizes the sunspot number. ## [0.4.1] - 2026-11-05 From b3c620bd94fd4c1877d0257a016bee1061df473d Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 06:46:57 -0500 Subject: [PATCH 59/60] docs: correct the yerr text and state the selection doctests as relations - Quickstart: a uniform yerr moves the parameters, because the default Huber loss acts on residuals divided by yerr; the text said they stay the same, against its own doctest. - Plot a Fit: the plot shades the observations +/- yerr (a window, not error bars), and the annotation is the weighted fit's, not the quickstart table's. - Select the data: the clim, alim and get_plotted_data doctests state relations to the counts instead of pinned numbers. - The benchmark script checks that both builds aggregate the same grid. Co-Authored-By: Claude Opus 5.5 --- docs/source/tutorial/quickstart.rst | 6 ++++-- docs/source/usage.rst | 33 +++++++++++++++++------------ scripts/benchmark_binned_data.py | 10 +++++++++ 3 files changed, 33 insertions(+), 16 deletions(-) diff --git a/docs/source/tutorial/quickstart.rst b/docs/source/tutorial/quickstart.rst index 2012e209d..da5ac475a 100644 --- a/docs/source/tutorial/quickstart.rst +++ b/docs/source/tutorial/quickstart.rst @@ -255,8 +255,10 @@ uncertainties of ``y``, one per observation, as :func:`scipy.optimize.curve_fit` takes ``sigma``. The noise above has a standard deviation of 0.5, so with ``yerr=0.5`` for every point the linear reduced chi-squared is near 1, as it should be for a good fit with the right -uncertainties. The fitted parameters are the same, since equal uncertainties -weight every point alike: +uncertainties. The parameters move a little: the default Huber loss acts on +each residual divided by its ``yerr``, so the uncertainties change which +residuals count as large. With ``make_fit(loss="linear")``, equal +uncertainties would leave them unchanged: >>> yerr = np.full(x.size, 0.5) >>> weighted = swp.fitfunctions.lines.Line(x, y, yerr=yerr) diff --git a/docs/source/usage.rst b/docs/source/usage.rst index 29cbf087d..975699057 100644 --- a/docs/source/usage.rst +++ b/docs/source/usage.rst @@ -758,20 +758,24 @@ Every binned plot, ``Hist1D`` included, has both. Here the bins with at least >>> h1 = Hist1D(v, nbins=20) >>> counts = h1.agg() >>> h1.set_clim(20, None) ->>> int(h1.agg().notna().sum()), int(counts[counts >= 20].sum()) -(11, 953) ->>> h1 = Hist1D(v, nbins=20, axnorm="t") ->>> h1.set_alim(0.1, None) ->>> int(h1.agg().notna().sum()) -11 +>>> h1.agg().notna().equals(counts >= 20) +True +>>> peak = Hist1D(v, nbins=20, axnorm="t") +>>> peak.set_alim(0.1, None) +>>> peak.agg().notna().equals(counts >= 0.1 * counts.max()) +True ``get_plotted_data`` returns the rows in the cells the figure shows: the -values you passed, on your index, in your order. ``alim`` acts on the -aggregated value, so pass the ``fcn`` you give ``make_plot``. Here the cells -with at least 10 rows whose mean ``z`` is not negative: +values you passed, on your index, in your order. Its rows are the ones the +shown bins count: + +>>> len(h1.get_plotted_data()) == int(counts[counts >= 20].sum()) +True + +``alim`` acts on the aggregated value, so pass the ``fcn`` you give +``make_plot``. Here the cells with at least 10 rows whose mean ``z`` is not +negative: ->>> len(h1.get_plotted_data()) -953 >>> h2 = Hist2D(v, y, z, nbins=10) >>> h2.set_clim(10, None) >>> h2.set_alim(0, None) @@ -941,9 +945,10 @@ in percent of the fit instead, which is large wherever the fit nears zero. The plotter labels its axes ``x`` and ``y`` until its ``set_labels`` sets them, as for the plots above; here the counts of a velocity component. The Gaussian is the seeded, noisy one whose results table -:doc:`tutorial/quickstart` prints, fitted with ``yerr``, the 1-sigma -uncertainty of each ``y`` (the noise's 0.3), which the plot draws as error -bars: +fitted to the data whose unweighted results table :doc:`tutorial/quickstart` +prints, here with ``yerr``, the 1-sigma uncertainty of each ``y`` (the +noise's 0.3). The plot shades the observations :math:`\pm` ``yerr``, and the +annotation is this weighted fit's: .. plot:: diff --git a/scripts/benchmark_binned_data.py b/scripts/benchmark_binned_data.py index e95ea564a..561bbac99 100644 --- a/scripts/benchmark_binned_data.py +++ b/scripts/benchmark_binned_data.py @@ -88,8 +88,18 @@ def memory(build, frame): return current / 1e6, peak / 1e6 +def check_same_grid(frame): + """Raise unless both builds give the same aggregate on the same cells.""" + (_, (shared, *_)), (_, (separate, *_)) = ( + build_shared(frame), + build_separate(frame), + ) + np.testing.assert_allclose(shared.to_numpy(), separate.to_numpy()) + + def main(): frame = make_frame() + check_same_grid(frame) print( f"{platform.machine()} Python {platform.python_version()}, " f"pandas {pd.__version__}, NumPy {np.__version__}" From 8a305a517204af4786dd5a313984023cc4241d01 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 06:48:45 -0500 Subject: [PATCH 60/60] docs(changelog): list the removed nan_aware_filter and the required Quantity name as breaking Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index df7bec454..527a85d42 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,6 +54,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `publication_format=`. Migrate `description="text"` to `name="text", publication_format=True` (or `set_publication_format(True)` for every label). Unlike a description, the name is not printed in the default one-line format. +- The `nan_aware_filter` keyword of `Hist2D.plot_contours` and + `Hist2D.plot_hist_with_contours` is removed: a grid with empty bins is now always smoothed + NaN-aware (see Fixed). Passing it raises an error from matplotlib; delete the keyword. +- `solarwindpy.core.quantities.Quantity` takes a required keyword `name`, its display name. + A `Quantity` built without it raises `TypeError`; pass `name="..."`. - `Scatter.make_plot` returns `(ax, points, segments, cbar)`: the `LineCollection` of the segments, or None without `connect=True`, sits before the colorbar. Unpack four values where three were unpacked before. @@ -78,9 +83,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 after `axnorm` and `clim`, as on `Hist2D` and `SpiralPlot2D`, which `get_plotted_data` honours. Every plot with `alim` now shares one implementation; `Scatter` still applies it to the z of each point. -- Every quantity in the registry has a display name: `solarwindpy.core.quantities.Quantity` - takes a required keyword `name`, a few words in title case such as "Number Density" or - "Temperature". It names the quantity only, without species or component. +- Every quantity in the registry has a display name, a few words in title case such as + "Number Density" or "Temperature". It names the quantity only, without species or + component. - Publication-format labels: a label is its name in words over its usual TeX symbol and units, e.g. "Number Density" over `n_{p_1} [cm^-3]`. Turn it on for every label with `solarwindpy.plotting.labels.base.set_publication_format` (read the default with @@ -140,8 +145,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 no longer erase the contours around empty bins. A grid with empty (NaN) bins is smoothed by `solarwindpy.plotting.tools.nan_gaussian_filter`, which averages only the occupied bins; a grid without them is filtered by `scipy.ndimage.gaussian_filter` as before, with unchanged - results. The `nan_aware_filter` keyword is removed: passing it raises an error from - matplotlib. + results. - `SpiralPlot2D` no longer logs warnings on every construction and draw. Its timing and bin-population messages report normal operation and are now DEBUG records; the message that points outside the mesh are dropped stays a warning.