diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e71be5ba..527a85d42 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,178 @@ 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)`. +- `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 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()`; 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 + `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. +- The `description=` keyword, `description` property and `set_description` of every + plot label class is removed. 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 `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. + +### Added + +- A summary `repr` for every plot (`Hist1D`, `Hist2D`, `SpiralPlot2D`, `Scatter`), shown by + 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 + 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 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 + the z of each point. +- 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 + `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 " / ". 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. +- `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. +- 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. +- 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 + +- 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. +- `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 + +- 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 + math. +- `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. +- `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}`. +- `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}`. +- 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'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}`. The weights read "Count Fraction" (`w`), "Column Count Fraction" + (`wc`) and "Row Count Fraction" (`wr`) on a `Count`, and "Weight of n_p" on a `TeXlabel`, + whose value is the weight of another aggregation. A `TeXlabel` normalized by a maximum states + `\#`; a density or weight of a quantity states no units, since they depend on the + aggregation. +- `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 ### Added 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..89d92ac7e 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 ----------------------------------------------------- @@ -142,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", @@ -212,6 +227,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"), diff --git a/docs/source/tutorial/quickstart.rst b/docs/source/tutorial/quickstart.rst index dedb50174..da5ac475a 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: @@ -220,11 +250,31 @@ 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 -uncertainties of ``y``, one per observation. +Measurement uncertainties enter through the ``yerr`` argument, the 1-sigma +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 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) +>>> 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 ``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/docs/source/usage.rst b/docs/source/usage.rst index b75e6c63a..975699057 100644 --- a/docs/source/usage.rst +++ b/docs/source/usage.rst @@ -209,15 +209,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, and ``use_contourf=True`` fills the contours: @@ -236,9 +237,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( - use_contourf=True, gaussian_filter_std=2, nan_aware_filter=True, plot_edges=True - ) + h2.plot_contours(use_contourf=True, gaussian_filter_std=2, plot_edges=True) :py:meth:`~solarwindpy.plotting.hist2d.Hist2D.plot_hist_with_contours` draws the histogram and its smoothed contours on the same axes, with one colorbar, @@ -264,7 +263,6 @@ stand out over the colored cells; the line style changes with the level: use_contourf=False, contour_kwargs=dict(colors="k"), gaussian_filter_std=2, - nan_aware_filter=True, ) :py:meth:`~solarwindpy.plotting.hist2d.Hist2D.make_joint_h2_h1_plot` draws the @@ -322,9 +320,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 +348,128 @@ 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} + ) + +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 +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 ~~~~ @@ -417,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) +>>> 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: -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. +>>> 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: @@ -468,36 +604,87 @@ cell: Normalizations ~~~~~~~~~~~~~~ -``axnorm`` normalizes the aggregated values: +``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: -- ``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. +>>> 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: >>> Hist1D(v).binning.allowed_axnorm -('d', 't') +('d', 't', 'w') >>> Hist1D(v, axnorm="c") Traceback (most recent call last): ... -ValueError: Unrecognized axnorm 'c'; expected one of: d, t +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:: @@ -522,6 +709,86 @@ 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) +>>> 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. 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: + +>>> 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 ~~~~~~ @@ -538,23 +805,20 @@ $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 :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]$ +${\beta}_{{p_1}} \; \left[\#\right]$ A dimensionless quantity, such as :math:`\beta`, has the units :math:`[\#]`. A second key makes a ratio: @@ -565,16 +829,93 @@ $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, 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") +>>> 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. +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 ---------- @@ -604,7 +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 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:: @@ -616,7 +960,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)) diff --git a/scripts/benchmark_binned_data.py b/scripts/benchmark_binned_data.py new file mode 100644 index 000000000..561bbac99 --- /dev/null +++ b/scripts/benchmark_binned_data.py @@ -0,0 +1,114 @@ +# 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 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__}" + ) + 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() diff --git a/src/solarwindpy/core/plasma.py b/src/solarwindpy/core/plasma.py index a9d36a221..eaf31c921 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, @@ -1602,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/src/solarwindpy/core/quantities.py b/src/solarwindpy/core/quantities.py index f52579623..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 @@ -15,7 +17,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__ = [ @@ -26,7 +31,7 @@ "UNIT_TEX", ] -from dataclasses import dataclass +from dataclasses import KW_ONLY, dataclass from types import MappingProxyType from scipy import constants @@ -46,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. @@ -62,7 +73,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.}", @@ -79,124 +90,213 @@ 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"{$C}_{\mathrm{GSE}}", _U["Re"], si=_EARTH_EQUATORIAL_RADIUS), - "hci": Quantity(r"{$C}_{\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}}", r"\perp/\parallel"), - "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"]), } ) #: 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"", @@ -205,7 +305,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/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..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 @@ -288,18 +288,19 @@ 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: - logging.getLogger().warning( - "No weights. Need weights to plot a window for FitFunction. Setting w to 0." + if yerr is None: + # A fit without uncertainties is ordinary: draw a zero-width window. + logging.getLogger(__name__).debug( + "No yerr: the %s window has zero width.", kind ) - w = 0 + yerr = 0 window_kwargs = mpl.cbook.normalize_kwargs( window_kwargs, mpl.collections.Collection @@ -309,8 +310,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 +332,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 +363,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 +662,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/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/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/src/solarwindpy/plotting/base.py b/src/solarwindpy/plotting/base.py index a217e1c2a..01ca80bca 100644 --- a/src/solarwindpy/plotting/base.py +++ b/src/solarwindpy/plotting/base.py @@ -43,6 +43,51 @@ 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) + + +#: ``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. @@ -66,8 +111,84 @@ 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 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() + 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()) + 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 {} + + 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.""" + 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 +302,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) @@ -367,34 +488,30 @@ 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): 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``.""" @@ -484,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. @@ -587,24 +723,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"): @@ -704,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 @@ -722,6 +902,26 @@ 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() + 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 + if "alim" in fields: + # Show alim after clim, the order they apply in. + fields["alim"] = fields.pop("alim") + return fields + @property def clim(self): r"""``RangeLimits`` of the minimum and maximum counts per cell; see ``set_clim``.""" @@ -760,71 +960,52 @@ 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): - 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) - - @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 + self._count_with_axnorm(getattr(self.labels, self.agg_axes)) @property 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 _grouped_by_cell(self): - r"""The aggregated column on the rows in a cell, grouped by cell code.""" - codes = self.binning.codes() + def _cell_codes(self): + r"""``binning.codes()``: each kept row's cell, -1 in none. + + 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. + """ + 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 @@ -834,8 +1015,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. @@ -849,26 +1030,66 @@ 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 + :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. """ + 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 = {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()]), ) - gb = self._grouped_by_cell() - if fcn is None: fcn = "count" if self._source.counts else "mean" + kind = _aggregation_kind(fcn) + + # 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. + 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: + agg = self._grouped_by_cell(codes).agg(fcn, **kwargs) - agg = gb.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: - cnt = gb.agg("count") tk = pd.Series(True, index=agg.index) if c0 is not None: tk = tk & (cnt >= c0) @@ -884,8 +1105,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): @@ -894,69 +1117,52 @@ 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``. + def _plotted_rows(self, fcn=None): + r"""Boolean array over the kept rows: True where the row's cell is shown. - Parameters - ---------- - positions : np.ndarray of int - Cell codes, positions in ``binning.cells``. - - Returns - ------- - pd.Series - On the index of ``data``. + 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. """ - codes = self.binning.codes() - keep = np.isin(codes, positions) & (codes >= 0) - return pd.Series(keep, index=self._kept_index()) + codes = self._cell_codes() + shown = self._agg(fcn, codes).notna().to_numpy() + return np.append(shown, False)[codes] - def get_plotted_data_boolean_series(self): - """Return a boolean ``pd.Series`` identifying each plotted measurement. + def _kept_source_frame(self): + r"""The caller's values on the kept rows, one column per ``data`` column. - 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. + No ``10**`` round trip: a logged axis holds the values as passed, + sign included. """ - 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" + source = self._source + return pd.DataFrame( + {k: source.take(k) for k in source.columns}, + index=self._kept_index(), + copy=False, ) - return tk + def get_plotted_data(self, fcn=None): + r"""The rows in the cells the figure shows. - def get_subset_above_threshold(self, threshold, fcn="count"): - r"""Get the subset of data above a given threshold using `fcn` to. + A cell is shown when ``agg(fcn)`` is not NaN there: after ``clim``, + ``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. - 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`. + Parameters + ---------- + fcn : str or callable, optional + The aggregation, as ``agg`` takes it. 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``. + 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. """ - 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)] - - return subset, tk + return self._kept_source_frame().loc[self._plotted_rows(fcn)] class _OnFixedGrid: @@ -1034,3 +1240,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/binned.py b/src/solarwindpy/plotting/binned.py index 7baff0dfe..be76bacb2 100644 --- a/src/solarwindpy/plotting/binned.py +++ b/src/solarwindpy/plotting/binned.py @@ -401,6 +401,20 @@ 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 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. @@ -484,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 05316ee5e..082cf396f 100644 --- a/src/solarwindpy/plotting/binning.py +++ b/src/solarwindpy/plotting/binning.py @@ -56,6 +56,18 @@ 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 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. @@ -64,9 +76,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 @@ -75,27 +104,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. @@ -519,10 +566,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): @@ -558,6 +605,17 @@ 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 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] @@ -609,39 +667,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 919b3d022..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 @@ -131,7 +132,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 +150,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. @@ -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``. @@ -183,7 +176,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) @@ -341,87 +334,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 c96570041..20ba2d007 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 @@ -21,33 +22,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. @@ -193,9 +167,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, @@ -223,9 +211,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 ------- @@ -245,11 +235,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) @@ -280,7 +269,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 +293,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. @@ -331,14 +318,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) @@ -351,19 +336,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) @@ -430,6 +405,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 +443,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 +486,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 @@ -530,7 +529,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: @@ -558,7 +557,6 @@ def plot_contours( use_contourf=False, gaussian_filter_std=0, gaussian_filter_kwargs=None, - nan_aware_filter=False, levels=None, **kwargs, ): @@ -581,22 +579,24 @@ 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. 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 ------- @@ -605,8 +605,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: @@ -626,19 +624,10 @@ 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) + norm, cmap = self._color_scale(kwargs, C) assert XX.shape == C.shape assert YY.shape == C.shape @@ -740,7 +729,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 @@ -895,9 +884,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 +894,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/src/solarwindpy/plotting/labels/base.py b/src/solarwindpy/plotting/labels/base.py index 5af1549ae..fb478864c 100644 --- a/src/solarwindpy/plotting/labels/base.py +++ b/src/solarwindpy/plotting/labels/base.py @@ -2,9 +2,14 @@ r"""Tools for creating physical quantity plot labels.""" __all__ = [ + "AXNORM", "Base", "TeXlabel", + "density_units", "format_with_units", + "publication_format", + "set_publication_format", + "validate_axnorm", ] import logging @@ -13,6 +18,7 @@ from pathlib import Path from string import Template from collections import namedtuple +from types import MappingProxyType from ...core import quantities @@ -25,15 +31,230 @@ _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,name,symbol,per,pure") + +#: 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 +#: 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 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. +#: - ``pure``: True when the normalized value is a pure number whatever the +#: aggregation: a ratio to a maximum, which a ``TeXlabel`` states as ``\#``. +#: Otherwise the units of a normalized quantity depend on the aggregation (a +#: weight of a mean carries the mean's units, of a sum it is a fraction), so +#: a ``TeXlabel`` states none. +#: +#: A normalized ``Count`` is a count aggregation, so ``count``, ``name`` and +#: ``symbol`` name counts. A ``TeXlabel`` is the aggregated value of another +#: aggregation, so ``quantity`` names the normalization without saying count: +#: ``d`` is the density and ``w`` the weight of the quantity, as +#: ``binning.normalize`` defines them. +AXNORM = MappingProxyType( + { + "c": _AxisNorm( + "Count / Column Max", + r"%s / \mathrm{Column \; Max}", + False, + "Column-Normalized Count", + r"N / N_{\max,\mathrm{col}}", + (), + True, + ), + "r": _AxisNorm( + "Count / Row Max", + r"%s / \mathrm{Row \; Max}", + False, + "Row-Normalized Count", + r"N / N_{\max,\mathrm{row}}", + (), + True, + ), + "t": _AxisNorm( + "Count / Max", + r"%s / \mathrm{Max}", + False, + "Normalized Count", + r"N / N_{\max}", + (), + True, + ), + "d": _AxisNorm( + "Probability Density", + r"\mathrm{Density \; of} \; %s", + True, + "Probability Density", + r"p", + ("x", "y"), + False, + ), + "cd": _AxisNorm( + "Column Probability Density", + r"\mathrm{Column \; Density \; of} \; %s", + True, + "Column Probability Density", + r"p_{\mathrm{col}}", + ("y",), + False, + ), + "rd": _AxisNorm( + "Row Probability Density", + r"\mathrm{Row \; Density \; of} \; %s", + True, + "Row Probability Density", + r"p_{\mathrm{row}}", + ("x",), + False, + ), + "w": _AxisNorm( + "Count Fraction", + r"\mathrm{Weight \; of} \; %s", + False, + "Count Fraction", + r"N / N_{\mathrm{tot}}", + (), + False, + ), + "wc": _AxisNorm( + "Column Count Fraction", + r"\mathrm{Column \; Weight \; of} \; %s", + False, + "Column Count Fraction", + r"N / N_{\mathrm{tot,col}}", + (), + False, + ), + "wr": _AxisNorm( + "Row Count Fraction", + r"\mathrm{Row \; Weight \; of} \; %s", + False, + "Row Count Fraction", + r"N / N_{\mathrm{tot,row}}", + (), + False, + ), + } +) + + +#: The module default of ``publication_format``; read and set it with +#: :func:`~solarwindpy.plotting.labels.base.publication_format` and +#: :func:`~solarwindpy.plotting.labels.base.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:`~solarwindpy.plotting.labels.base.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 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, 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 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 allowed: + raise ValueError( + f"Unrecognized axnorm '{key}'; expected one of: {', '.join(allowed)}" + ) + return lower + # Longest first, so a species is never matched by a code it starts with # (``a_bimax`` before ``a``, ``p1`` before ``p``). @@ -84,6 +305,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) @@ -97,14 +324,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 +340,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}$" @@ -121,10 +350,12 @@ 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() - self._description = None def __str__(self): return self.with_units @@ -156,24 +387,46 @@ def _init_logger(self, handlers=None): 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. + def name(self): + r"""Plain-text name, the first line in publication format, or None. - Parameters - ---------- - new : str or None - Human-readable description. None disables the description. + 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._description = 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:`~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 for 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. + def _format_with_name(self, label_str): + """Prepend the name in publication format. Parameters ---------- @@ -183,17 +436,18 @@ def _format_with_description(self, label_str): Returns ------- str - Label with description prepended if set, otherwise unchanged. + ``label_str`` under the name and a newline when the label is in + publication format and has a name, otherwise unchanged. """ - if self.description: - return f"{self.description}\n{label_str}" + if self.publication_format and self.name: + 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): @@ -224,7 +478,13 @@ 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, + name=None, + publication_format=None, ): """Instantiate the label. @@ -237,18 +497,25 @@ 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:`~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 " / ". + publication_format : bool or None, optional + If True, the label is its name over its symbol line. None follows + the module default, + :func:`~solarwindpy.plotting.labels.base.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 @@ -278,8 +545,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 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 " / ". + + 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): @@ -312,13 +597,10 @@ def set_axnorm(self, new): Parameters ---------- new : str, optional - One of ``"c"``, ``"r"``, ``"t"``, ``"d"`` (case-insensitive), or None. + A key of :data:`~solarwindpy.plotting.labels.base.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. @@ -367,7 +649,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) @@ -428,17 +710,17 @@ 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 = r"\#" - tex = r"\mathrm{%s \; Norm} \; %s" % (tex_norm, tex) # noqa: W605 + if axnorm is not None: + norm = AXNORM[axnorm] + units = _inU["dimless"] if norm.pure else "" + if self.mcs1 is not None: + tex = f"({tex})" + tex = norm.quantity % tex path = path / (axnorm.upper() + "norm") + # The name line is 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): @@ -457,7 +739,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..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): @@ -45,7 +48,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): @@ -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): @@ -126,7 +132,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/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 0d0d49cf5..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): @@ -62,7 +66,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..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 @@ -161,8 +164,8 @@ 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) + ) + 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, r"\#") - return self._format_with_description(result) + result = base.format_with_units(self.tex, base._inU["dimless"]) + return self._format_with_name(result) @property def short_label(self): @@ -257,34 +262,58 @@ 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_description(description) + self.set_binned_axes({}) + 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) + # 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_name(result) @property 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 count units.""" - return r"\#" + 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 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): @@ -302,32 +331,21 @@ 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() + self._axnorm = base.validate_axnorm(norm) - assert norm in base._trans_axnorm.keys() - self._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 - 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") @@ -347,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): @@ -375,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): @@ -449,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() @@ -464,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): @@ -474,7 +502,7 @@ def tex(self): @property def units(self): r"""TeX of the units.""" - return r"\#" + return base._inU["dimless"] @property def path(self): @@ -542,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__() @@ -550,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): @@ -649,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 @@ -658,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 ----- @@ -671,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): @@ -729,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): @@ -783,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, r"\#") - return self._format_with_description(result) + result = base.format_with_units(self.tex, base._inU["dimless"]) + return self._format_with_name(result) @property def kind(self): @@ -855,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): @@ -1006,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): @@ -1027,7 +1080,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/src/solarwindpy/plotting/scatter.py b/src/solarwindpy/plotting/scatter.py index a8f26ab11..a864fcf0e 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, + connect=False, + connect_kwargs=None, + **kwargs, + ): r"""Make a scatter plot on `ax` using `ax.scatter`. Parameters @@ -75,6 +86,14 @@ 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`. + 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'. + Not modified. kwargs: Passed to `ax.scatter`. @@ -83,6 +102,8 @@ def make_plot(self, ax=None, cbar=True, cbar_kwargs=None, **kwargs): ax: mpl.axes.Axes collection: mpl.collections.PathCollection The points. + 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. @@ -91,6 +112,22 @@ 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. + + 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() @@ -104,11 +141,18 @@ 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 collection = ax.scatter(x="x", y="y", c=zkey, data=data, **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) cbar = self._make_cbar(collection, **cbar_kwargs) @@ -117,4 +161,54 @@ 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, segments, cbar + + def _connect(self, ax, collection, data, zkey, connect_kwargs): + r"""Add segments joining the 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 points not hidden by ``alim``, in row order. + zkey: str or None + ``"z"`` if the points are colour-mapped, else None. + connect_kwargs: Mapping or None + Passed to ``LineCollection``. + + Returns + ------- + matplotlib.collections.LineCollection + """ + 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(xy.shape[0], dtype=bool) + for i, log in enumerate(self.log): + if log: + drawn &= xy[:, i] > 0 + xy = xy[drawn] + + 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]) + 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() + segments = LineCollection( + np.stack([xy[:-1], xy[1:]], axis=1), + cmap=collection.get_cmap(), + norm=collection.norm, + **kwargs, + ) + segments.set_array((z[:-1] + z[1:]) / 2) + + ax.add_collection(segments, autolim=False) + return segments diff --git a/src/solarwindpy/plotting/spiral.py b/src/solarwindpy/plotting/spiral.py index dc16e6450..060773cdd 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 """) @@ -818,14 +818,26 @@ 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): 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 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 @@ -885,9 +897,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 @@ -1016,8 +1029,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 +1047,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 @@ -1045,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()}") @@ -1169,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/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/core/test_plasma_info.py b/tests/core/test_plasma_info.py new file mode 100644 index 000000000..04596339f --- /dev/null +++ b/tests/core/test_plasma_info.py @@ -0,0 +1,71 @@ +# 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 solarwindpy as swp +from solarwindpy.core.plasma import Plasma + +FIELDS = [ + "spacecraft", + "frame", + "start", + "end", + "observations", + "species", + "auxiliary data", +] + + +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" + + +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 + + +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" diff --git a/tests/core/test_quantity_registry.py b/tests/core/test_quantity_registry.py index 5a901cc13..d4b6a1c67 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", @@ -465,3 +466,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" diff --git a/tests/fitfunctions/test_core.py b/tests/fitfunctions/test_core.py index cb3c690e7..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,11 +929,54 @@ 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 +# ============================================================================ + + +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])) + + +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])) + + +@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_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..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() @@ -451,10 +447,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 +475,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 @@ -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() 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..6b4e69c51 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 @@ -11,6 +11,7 @@ import io import logging +import warnings from pathlib import Path import matplotlib.pyplot as plt @@ -72,10 +73,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 +100,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 +108,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 +404,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 +443,25 @@ 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 draws a zero-width window and says so only at DEBUG. 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): + with caplog.at_level(logging.DEBUG): _, (_, window, _) = getattr(plot, f"plot_{kind}")() - assert "No weights" 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() @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 +594,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 +602,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 +645,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. @@ -962,3 +964,23 @@ 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 + + +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 == "" 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_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) 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 289010d31..a6ebb2644 100644 --- a/tests/fitfunctions/test_trend_fits_advanced.py +++ b/tests/fitfunctions/test_trend_fits_advanced.py @@ -285,17 +285,19 @@ def test_make_fit_with_non_interval_index(self): # Verify the trend was created successfully assert isinstance(tf.trend, Line) - 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"): + 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(weights=np.ones(5)), + trend_kwargs=dict(yerr=np.ones(5)), ) 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(): diff --git a/tests/plotting/labels/test_labels_base.py b/tests/plotting/labels/test_labels_base.py index bf2dfa5bb..8cafc917f 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]$" ) @@ -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, ""), ] @@ -124,7 +123,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 +176,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", @@ -197,7 +196,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(): @@ -242,7 +241,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): @@ -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") @@ -348,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]$" + "${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``. - - ``with_units`` is documented as set by ``build_label``, so the label is - rebuilt after ``set_description``. - - ON FAILURE: the code is wrong. - """ - 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 "Total" in result or "Norm" in result - - def test_description_with_ratio_label(self, labels_base): - """Description works with ratio-style labels.""" + def test_name_heads_the_label_in_publication_format(self, labels_base): label = labels_base.TeXlabel( - ("v", "x", "p"), ("n", "", "p"), description="v/n ratio" + ("v", "x", "p"), name="Speed", publication_format=True ) - result = label.with_units - assert result.startswith("v/n ratio\n") - assert "/" in result # Contains ratio + assert str(label) == "Speed\n" + str(labels_base.TeXlabel(("v", "x", "p"))) - 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_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") + + 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 - 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") + def test_description_is_gone(self, labels_base): + label = labels_base.TeXlabel(("v", "x", "p")) + assert not hasattr(label, "description") + assert not hasattr(label, "set_description") @pytest.mark.parametrize( @@ -503,10 +448,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"], @@ -534,11 +479,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. @@ -631,15 +576,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): @@ -658,3 +656,93 @@ 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 + + +@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 + + +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) + + +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__ + + +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") diff --git a/tests/plotting/labels/test_publication_format.py b/tests/plotting/labels/test_publication_format.py new file mode 100644 index 000000000..e9a54d0e7 --- /dev/null +++ b/tests/plotting/labels/test_publication_format.py @@ -0,0 +1,216 @@ +# 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_keyword_is_removed(): + """``description`` was merged into ``name``: one optional first line. + + ON FAILURE: the code is wrong. + """ + with pytest.raises(TypeError): + TeXlabel(("n", "", "p1"), description="Wind") + + +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" + r"$N / N_{\max} \; \left[\#\right]$" + 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, symbol_line", + [ + (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_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) == f"{name}\n{symbol_line}" + + +@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 diff --git a/tests/plotting/labels/test_special.py b/tests/plotting/labels/test_special.py index 2ee17f5fc..0ff2105e0 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): @@ -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.""" @@ -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. @@ -732,11 +755,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 +826,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]$" ) @@ -1001,13 +1020,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. @@ -1022,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 - ), - "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 + "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 ), - "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 + "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 ), - "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_agg_count.py b/tests/plotting/test_agg_count.py new file mode 100644 index 000000000..67677e0e4 --- /dev/null +++ b/tests/plotting/test_agg_count.py @@ -0,0 +1,99 @@ +# 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 + + +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(*args): + 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") 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..9658c5710 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"], ) @@ -242,9 +246,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 @@ -321,6 +324,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_axnorm_by_fcn.py b/tests/plotting/test_axnorm_by_fcn.py new file mode 100644 index 000000000..faf799a86 --- /dev/null +++ b/tests/plotting/test_axnorm_by_fcn.py @@ -0,0 +1,238 @@ +# 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 + +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) + + +@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 + + +@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()) + + +@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) + + +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()) + + +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 = z.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.5 # not the overall median + + +@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)) + + +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) + + +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)) + + +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) + + +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()) + + +@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") + + +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) diff --git a/tests/plotting/test_base.py b/tests/plotting/test_base.py index c4286d033..cb3572c58 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") @@ -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_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_color_scale.py b/tests/plotting/test_color_scale.py new file mode 100644 index 000000000..1e8b72998 --- /dev/null +++ b/tests/plotting/test_color_scale.py @@ -0,0 +1,121 @@ +# 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 + +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) + + +@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" + + +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" + + +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" 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"\#" diff --git a/tests/plotting/test_hist1d.py b/tests/plotting/test_hist1d.py index 7ded072cb..2d5f9cc1c 100644 --- a/tests/plotting/test_hist1d.py +++ b/tests/plotting/test_hist1d.py @@ -611,16 +611,14 @@ 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) 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 @@ -751,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. """ @@ -764,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 @@ -802,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]) @@ -812,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"], ) @@ -825,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) @@ -845,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_alim.py b/tests/plotting/test_hist1d_alim.py new file mode 100644 index 000000000..d6afce7a9 --- /dev/null +++ b/tests/plotting/test_hist1d_alim.py @@ -0,0 +1,86 @@ +# 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 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 + +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) + + +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) + + +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) + + +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] + + +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) + + +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) + + +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() 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 abe55150c..fb6f6ff42 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 @@ -182,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_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_hist2d_plotting.py b/tests/plotting/test_hist2d_plotting.py index 36154ca00..5d53b6969 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,31 @@ 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 _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) @@ -338,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.""" @@ -1472,6 +1447,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.""" @@ -1635,7 +1646,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 +1687,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): @@ -2189,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") 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. 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") 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. diff --git a/tests/plotting/test_plot_invariants.py b/tests/plotting/test_plot_invariants.py index ea72bd066..1267723f0 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,21 +273,9 @@ 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_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_plotted_data(b): + rows = b.h.get_plotted_data() + return [Selection(rows.index, rows, True)] def _select_above_contour(b): @@ -311,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 - - else: - available = h.agg().index - - def y_bounds(at_x): - return at_x.bottom, at_x.top + def y_bounds(at_x, expected_logy): + 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)] @@ -336,7 +315,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 @@ -362,8 +341,7 @@ def _select_projection(b): SELECTIONS = { "data": _select_data, "cut": _select_cut, - "get_plotted_data_boolean_series": _select_plotted, - "get_subset_above_threshold": _select_above_threshold, + "get_plotted_data": _select_plotted_data, "id_data_above_contour": _select_above_contour, "take_data_in_yrange_across_x": _select_in_yrange, "construct_cdf": _select_cdf, @@ -639,13 +617,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))) diff --git a/tests/plotting/test_plotted_data.py b/tests/plotting/test_plotted_data.py new file mode 100644 index 000000000..3b4f0c4ac --- /dev/null +++ b/tests/plotting/test_plotted_data.py @@ -0,0 +1,141 @@ +# 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 + +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]) + + +@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()) + + +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] + + +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] + + +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() + + +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()) diff --git a/tests/plotting/test_repr.py b/tests/plotting/test_repr.py new file mode 100644 index 000000000..5c90a8cac --- /dev/null +++ b/tests/plotting/test_repr.py @@ -0,0 +1,247 @@ +# 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 + +# 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) + + +@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"].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) + assert str(plot) == repr(plot) + + +@pytest.mark.parametrize( + "name, has_z", [("Hist1D", False), ("Hist2D", True), ("Scatter", True)] +) +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"].split(" ")[0] == str(plot.labels.z) + + +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" + + +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" + + +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" + + +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) + + +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)" + + +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") + + +# --------------------------------------------------------------------------- +# Ranges: each axis line shows its bin range and the range of the data binned +# --------------------------------------------------------------------------- + + +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]" + + +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]" + + +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) + + +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]" + + +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]" + + +@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__) diff --git a/tests/plotting/test_return_order.py b/tests/plotting/test_return_order.py index 41daa8007..8eecec8e5 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 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 +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-connect", + lambda: Scatter(X, Y, Z), + "make_plot", + {"connect": 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, segments 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 06bc074f8..aaa18a263 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 @@ -88,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 @@ -106,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) @@ -118,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] @@ -129,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] @@ -142,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 @@ -168,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 @@ -244,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: @@ -289,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 @@ -307,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 @@ -323,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) @@ -378,3 +379,205 @@ def test_scatter_figure_renders_to_png(): finally: plt.close("all") assert buffer.getvalue().startswith(b"\x89PNG\r\n\x1a\n") # PNG signature + + +# --------------------------------------------------------------------------- +# 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)] + + +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) + + +def _mean_z(z, pairs): + return [(z[i] + z[j]) / 2 for i, j in pairs] + + +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. + """ + 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, connect=True) + assert len(out) == 4 + assert isinstance(out[2], LineCollection) + assert out[2] in ax.collections + + +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) + + +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. + """ + 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_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)]) + + +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, connect=True, cmap="plasma" + ) + 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() + 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 + + +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, 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 _nan_y_at_3(): + y = EY.copy() + y[3] = np.nan + return Scatter(EX, y, EZ), EX, y + + +def _alim_hides_2(): + sc = Scatter(EX, EY, EZ) + sc.set_alim(None, 8.0) + return sc, EX, EY + + +def _mask_drops_1(): + mask = pd.Series([True, False, True, True, True]) + return Scatter(EX, EY, EZ, mask=mask), EX, EY + + +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 + + +@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. + """ + 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)) + + +@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. + + A point that is not drawn (here a NaN y) is skipped there too. + ON FAILURE: the code is wrong. + """ + 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, 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_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, 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, 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_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, connect=True) + assert ax.get_xlim() == (EX.min(), EX.max()) + assert ax.get_ylim() == (EY.min(), EY.max()) 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. diff --git a/tests/plotting/test_take_data.py b/tests/plotting/test_take_data.py new file mode 100644 index 000000000..5439d6311 --- /dev/null +++ b/tests/plotting/test_take_data.py @@ -0,0 +1,124 @@ +# 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 + +# 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])]) + + +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 + + +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), + ) 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. diff --git a/tests/test_docs_plot_blocks.py b/tests/test_docs_plot_blocks.py index 34ddeee0b..6b374be2f 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(): @@ -55,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] @@ -70,12 +90,71 @@ 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}") + + +@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 new file mode 100644 index 000000000..87076e787 --- /dev/null +++ b/tests/test_docs_ssn_snapshot.py @@ -0,0 +1,92 @@ +# 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" +) + + +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 + + +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 + + +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] == "#"] + + +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() 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 == [] 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 )