From 3ab39f7fe54671ea846ff2637ea7973d309943a9 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 02:06:49 -0500 Subject: [PATCH 01/21] docs: correct the development setup instructions - Development installs use `pip install -e ".[dev]"` in README.rst, installation.rst and CONTRIBUTING.md, including after the conda environment: solarwindpy.yml's own header says the same, and the plain editable install lacks the test and docs tools the next steps run. - README states what the pre-commit hooks run, per their `files` filters, instead of only ruff. - README's docs build uses the flags CI uses: -W --keep-going -n. - CONTRIBUTING drops the nonexistent `--targeted` flag and the hand-kept example and line counts that had drifted. - RELEASING's conda check uses Python 3.12, and its expected PyPI metadata matches requires-python >=3.12 and the classifiers. Co-Authored-By: Claude Opus 5.5 --- .claude/docs/RELEASING.md | 6 +++--- CONTRIBUTING.md | 28 ++++++++++------------------ README.rst | 11 ++++++++--- docs/source/installation.rst | 12 +++--------- 4 files changed, 24 insertions(+), 33 deletions(-) diff --git a/.claude/docs/RELEASING.md b/.claude/docs/RELEASING.md index 0ce4c1158..123b9bbfd 100644 --- a/.claude/docs/RELEASING.md +++ b/.claude/docs/RELEASING.md @@ -198,8 +198,8 @@ print(f\"Classifiers: {', '.join([c for c in data['info']['classifiers'] if 'Pro **Expected Output**: ``` Version: X.Y.Z -Python: <4,>=3.11 -Classifiers: Python :: 3.11, Python :: 3.12, Python :: 3.13 +Python: <4,>=3.12 +Classifiers: Programming Language :: Python :: 3, Programming Language :: Python :: 3.12, Programming Language :: Python :: 3.13, Programming Language :: Python :: 3.14 ``` ### 8. Enhance GitHub Release Notes (Optional) @@ -385,7 +385,7 @@ After PR merge (2-4 hours for package build): ```bash # Create test environment -conda create -n test-solarwindpy-release python=3.11 -y +conda create -n test-solarwindpy-release python=3.12 -y conda activate test-solarwindpy-release # Install from conda-forge diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3ca2ba38d..de067cbc5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -17,7 +17,7 @@ Thank you for considering contributing to SolarWindPy. ```bash conda env create -f solarwindpy.yml conda activate solarwindpy - pip install -e . + pip install -e ".[dev]" ``` 2. Format code with `ruff format` and lint with `ruff check` (includes the pydocstyle rules). @@ -80,7 +80,7 @@ pytest --doctest-glob='*.rst' docs/source -q ``` **Troubleshooting Common Issues:** -- **Import errors**: Ensure `pip install -e .` was run in development environment +- **Import errors**: Ensure `pip install -e ".[dev]"` was run in the development environment - **Physics calculation failures**: Check units and verify against known results - **Timeout issues**: Simplify examples or split into smaller components - **Package import issues**: Use relative imports within solarwindpy modules @@ -88,14 +88,13 @@ pytest --doctest-glob='*.rst' docs/source -q ### Validation Framework Usage **Framework Design Philosophy:** -- **Proportional complexity**: Tools match package scope (47 examples, not enterprise-scale) +- **Proportional complexity**: Tools match the package's scope - **Essential focus**: Physics correctness over comprehensive metrics - **Sustainable maintenance**: Appropriate for research package team capacity - **User-friendly**: Simple workflow for researchers and contributors -**Full vs. Minimal Validation:** -- **Targeted validation** (`--targeted`): Focuses on core physics modules - use for most contributions -- **Full validation**: Tests all modules - use when making extensive changes +**Local vs. CI Validation:** +- **Local validation**: The two commands under "Local Testing Commands" above - **CI validation**: Automated essential checks - runs on all pull requests ## Dependency Management @@ -143,36 +142,29 @@ review. ## Validation Framework Maintenance -### Framework Sustainability Metrics -The validation framework has been right-sized for SolarWindPy's scope: -- **Framework size**: 570 lines (83% reduction from over-engineered 3,349 lines) -- **Execution time**: <5 minutes for full validation -- **Maintenance complexity**: Low (appropriate for research package team) -- **Example coverage**: 47 documentation examples (proportional tooling) - ### Annual Framework Assessment Review framework appropriateness annually: -1. **Scope verification**: Are we still at ~47 examples? +1. **Scope verification**: Is the tooling still proportional to the number of examples? 2. **Performance check**: Is validation completing in <5 minutes? 3. **Maintenance burden**: Can current team sustain framework complexity? 4. **Enhancement justification**: Are proposed additions necessary for current scope? ### Troubleshooting Validation Issues **Common issues and solutions:** -- **Import errors**: Ensure `pip install -e .` in development environment +- **Import errors**: Ensure `pip install -e ".[dev]"` was run in the development environment - **Physics calculation failures**: Check units and verify against known results -- **Timeout issues**: Use `--targeted` flag for faster critical module validation +- **Timeout issues**: Simplify examples or split into smaller components - **Matplotlib compatibility**: Some doctest failures may be due to version differences (acceptable) ### Framework Enhancement Guidelines Before adding complexity to validation framework: -1. **Justification**: Document why enhancement is needed for 47 examples +1. **Justification**: Document why the enhancement is needed for the current examples 2. **Proportionality**: Will enhancement maintain appropriate complexity level? 3. **Sustainability**: Can research team maintain enhanced framework? 4. **Alternative**: Could issue be addressed through simpler means? **Enhancement approval criteria:** -- Addresses actual problem with current 47 examples +- Addresses an actual problem with the current examples - Maintains <5 minute execution time - Complexity remains appropriate for research package - Team can sustain maintenance burden diff --git a/README.rst b/README.rst index f9228ed20..5c8ed9714 100644 --- a/README.rst +++ b/README.rst @@ -93,7 +93,7 @@ Development conda env create -f solarwindpy.yml conda activate solarwindpy - pip install -e . + pip install -e ".[dev]" 3. Run the test suite with ``pytest``: @@ -109,14 +109,19 @@ Development pre-commit install - This will run ``ruff check`` and ``ruff format`` automatically when committing. + Each commit then runs ``ruff check``, ``ruff format`` and whitespace, + merge-conflict and large-file checks on staged Python files, ``doc8`` on + staged ``.rst``, ``.md`` and ``.py`` files, and the conventional-commit check + on the message. A commit that stages a ``.py`` file also runs the full test + suite with a coverage floor (``.claude/hooks/pre-commit-tests.sh``), and one + that stages a file under ``src/solarwindpy`` runs an import test. 5. Build the documentation and fail on warnings: .. code-block:: bash cd docs - make html SPHINXOPTS=-W + make html SPHINXOPTS="-W --keep-going -n" License diff --git a/docs/source/installation.rst b/docs/source/installation.rst index df9a40a18..b08ea718f 100644 --- a/docs/source/installation.rst +++ b/docs/source/installation.rst @@ -39,19 +39,13 @@ Development Installation ------------------------ To work with the development version, clone the repository and install it in -editable mode: +editable mode with the testing, documentation, and linting tools declared in +the ``dev`` extra: .. code-block:: bash git clone https://github.com/blalterman/SolarWindPy.git cd SolarWindPy - pip install -e . - -Contributors can install the testing, documentation, and linting tools -declared in the ``dev`` extra instead: - -.. code-block:: bash - pip install -e ".[dev]" Conda Environment Setup @@ -65,7 +59,7 @@ package into the environment afterwards: conda env create -f solarwindpy.yml conda activate solarwindpy - pip install -e . + pip install -e ".[dev]" Verification ------------ From 23115cd5c2bd164e77634d4e75fcfedcc2edecaa Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 02:07:56 -0500 Subject: [PATCH 02/21] docs(missing_data): name every quantity that takes a species total "Only temperatures and pressures form totals" was false. n, rho, pth, T and Wk sum over the species present, and beta, R, cs and ca are built from those totals; each accepts "a+p1". Checked against the code: with the alphas masked at one time, every "a+p1" value there equals the p1 value, and with no species present it is NaN. Also documents the strict total `n(..., skipna=False)`, which Plasma.n's comment already points to this page for. Co-Authored-By: Claude Opus 5.5 --- docs/source/missing_data.rst | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/docs/source/missing_data.rst b/docs/source/missing_data.rst index edcc086fd..4cde57a1e 100644 --- a/docs/source/missing_data.rst +++ b/docs/source/missing_data.rst @@ -43,9 +43,23 @@ and the mass-density ratio in :py:meth:`~solarwindpy.core.plasma.Plasma.nuc`, and the reduced mass in :py:meth:`~solarwindpy.core.plasma.Plasma.pdv`, are NaN at a time when either species is missing. -Thermal speeds do not add across species, so -:py:meth:`~solarwindpy.core.plasma.Plasma.w` raises for a total such -as ``"a+p1"``. Only temperatures and pressures form totals. +Quantities that sum over species take a total: number density +(:py:meth:`~solarwindpy.core.plasma.Plasma.n`), mass density +(:py:meth:`~solarwindpy.core.plasma.Plasma.rho`), thermal pressure +(:py:meth:`~solarwindpy.core.plasma.Plasma.pth`), temperature +(:py:meth:`~solarwindpy.core.plasma.Plasma.T`) and kinetic energy flux +(:py:meth:`~solarwindpy.core.plasma.Plasma.Wk`). So do the quantities built +from those totals, such as the plasma beta +(:py:meth:`~solarwindpy.core.plasma.Plasma.beta`), the anisotropy +(:py:meth:`~solarwindpy.core.plasma.Plasma.R`), the sound speed +(:py:meth:`~solarwindpy.core.plasma.Plasma.cs`) and the Alfvén speed +(:py:meth:`~solarwindpy.core.plasma.Plasma.ca`). Thermal speeds do not add +across species, so :py:meth:`~solarwindpy.core.plasma.Plasma.w` raises for a +total such as ``"a+p1"``. + +A total density can also be strict: +``plasma.n("a+p1", skipna=False)`` is NaN at a time when any of its species is +missing. The two levels -------------- From 5cd02dea04b88d3f92573045ca8627f586059351 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 02:08:23 -0500 Subject: [PATCH 03/21] docs: remove the documentation review plan page The page promised a quarterly review that never ran. CI already lints the docs with doc8 and builds them with warnings as errors on every push, which is the check the page described. The "Development" toctree held only this page, so it goes too. Co-Authored-By: Claude Opus 5.5 --- docs/source/documentation_review.rst | 8 -------- docs/source/index.rst | 6 ------ 2 files changed, 14 deletions(-) delete mode 100644 docs/source/documentation_review.rst diff --git a/docs/source/documentation_review.rst b/docs/source/documentation_review.rst deleted file mode 100644 index f39706011..000000000 --- a/docs/source/documentation_review.rst +++ /dev/null @@ -1,8 +0,0 @@ -========================= -Documentation Review Plan -========================= - -The project documentation is reviewed every quarter to ensure accuracy and -relevance. Reviews should use the `Documentation Review` issue template and -include running `doc8` and rebuilding the Sphinx documentation. - diff --git a/docs/source/index.rst b/docs/source/index.rst index 773516220..842352bd6 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -33,12 +33,6 @@ scientific accuracy. api_reference -.. toctree:: - :maxdepth: 1 - :caption: Development - - documentation_review - .. include:: ../../LICENSE .. include:: ../../CITATION.rst From 023bd140f737f2363233cf93f5c510d6f3db577e Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 02:08:46 -0500 Subject: [PATCH 04/21] docs(conf): require the Sphinx the docs extra declares needs_sphinx said 1.8 while pyproject's docs and dev extras require sphinx>=7.0, so the configured floor guarded nothing. The PDF and EPUB settings were marked "enabled for RTD", but .readthedocs.yaml lists no formats, so Read the Docs builds HTML only; the markers go, the settings stay for local latex and epub builds. Co-Authored-By: Claude Opus 5.5 --- docs/source/conf.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/source/conf.py b/docs/source/conf.py index f34fc9de5..2af0b693d 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -25,7 +25,7 @@ # -- General configuration --------------------------------------------------- -needs_sphinx = "1.8" +needs_sphinx = "7.0" # the docs extra's floor, sphinx>=7.0 in pyproject.toml # numpydoc is the only docstring processor. Running napoleon beside it made # both rewrite every docstring; napoleon's ``Attributes`` sections then emitted @@ -232,7 +232,7 @@ # -- Options for other output formats ---------------------------------------- -# PDF output configuration (enabled for RTD) +# PDF output configuration latex_engine = 'pdflatex' latex_elements = { 'papersize': 'letterpaper', @@ -245,7 +245,7 @@ ''', } -# EPUB output configuration (enabled for RTD) +# EPUB output configuration epub_show_urls = 'footnote' epub_use_index = True From 6cade845c62e930b9d4e9370b50d26bf7209172f Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 02:12:52 -0500 Subject: [PATCH 05/21] docs(quickstart): walk the example plasma from load to fit The quickstart was a version check. It now runs end to end on swp.examples.load_plasma(): the M/C/S column frame, density, speed, thermal speed, temperature in kelvin via plasma.units, beta, R, an "a+p1" total, a Hist2D (agg, path and make_plot, with the caveat that three rows are only a demonstration) and a Line fit's popt and results. Values are rounded or hand-checkable (700 km/s, R = 7^2/10^2). Every example is a doctest, which the Sybil rst-examples job and --doctest-glob already run. tutorial.rst was a stub whose only content was a toctree pointing at the quickstart, so the quickstart takes its place in the User Guide toctree, after installation. usage.rst and the sidebar template no longer link the stub. README links the documentation on Read the Docs. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 ++ README.rst | 3 +- docs/source/_templates/sidebar.html | 2 +- docs/source/index.rst | 2 +- docs/source/tutorial.rst | 9 -- docs/source/tutorial/quickstart.rst | 162 ++++++++++++++++++++++++++-- docs/source/usage.rst | 2 +- 7 files changed, 165 insertions(+), 21 deletions(-) delete mode 100644 docs/source/tutorial.rst diff --git a/CHANGELOG.md b/CHANGELOG.md index fe46585b2..3d58e1e9f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- A quickstart page that runs end to end on `solarwindpy.examples.load_plasma`: the + `M`/`C`/`S` columns, derived quantities with their units, an `"a+p1"` total, a `Hist2D` + and a `Line` fit's `results`. It replaces the tutorial stub. + ### Changed - `pre-commit install` now installs the commit-message hook as well as the pre-commit hook diff --git a/README.rst b/README.rst index 5c8ed9714..3b109bd54 100644 --- a/README.rst +++ b/README.rst @@ -48,7 +48,8 @@ After installation, import the package and create a plasma object with sample da >>> print(f"Proton density: {plasma.p1.n.mean():.1f} cm⁻³") Proton density: 6.7 cm⁻³ -See the documentation for detailed usage examples and API reference. +See the `documentation `_ for the +quickstart, usage examples and the API reference. Installation ============ diff --git a/docs/source/_templates/sidebar.html b/docs/source/_templates/sidebar.html index 7f3e29b73..689e0f920 100644 --- a/docs/source/_templates/sidebar.html +++ b/docs/source/_templates/sidebar.html @@ -6,7 +6,7 @@

Quick Navigation

diff --git a/docs/source/index.rst b/docs/source/index.rst index 842352bd6..5b2477190 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -23,8 +23,8 @@ scientific accuracy. :caption: User Guide installation + tutorial/quickstart usage - tutorial missing_data .. toctree:: diff --git a/docs/source/tutorial.rst b/docs/source/tutorial.rst deleted file mode 100644 index 9c4fc83ca..000000000 --- a/docs/source/tutorial.rst +++ /dev/null @@ -1,9 +0,0 @@ -Tutorial -======== - -This section walks through a short example using SolarWindPy. - -.. toctree:: - :maxdepth: 1 - - tutorial/quickstart diff --git a/docs/source/tutorial/quickstart.rst b/docs/source/tutorial/quickstart.rst index 4c07ac551..486f53de4 100644 --- a/docs/source/tutorial/quickstart.rst +++ b/docs/source/tutorial/quickstart.rst @@ -1,19 +1,165 @@ Quickstart ========== -Get up and running with SolarWindPy. +This page goes from installation to derived quantities, a histogram and a fit. +Every example runs as a test, so each output shown is the one you get. -Installation ------------- +.. contents:: + :local: + :depth: 1 + +Install +------- .. code-block:: bash pip install solarwindpy -Basic Usage ------------ +:doc:`/installation` covers conda-forge and development installs. + +Load the Example Plasma +----------------------- + +SolarWindPy ships a small example: three rows of synthetic solar wind +measurements, chosen for illustration rather than taken from a mission. +:py:func:`~solarwindpy.examples.load_plasma` builds a +:py:class:`~solarwindpy.core.plasma.Plasma` from them: + +>>> import solarwindpy as swp +>>> plasma = swp.examples.load_plasma() +>>> plasma.species +('a', 'e', 'p1', 'p2') + +The species are alphas (``a``), electrons (``e``), protons (``p1``) and a +proton beam (``p2``). + +The measurements live in one pandas DataFrame, ``plasma.data``. Its columns are +a three-level MultiIndex: + +>>> list(plasma.data.columns.names) +['M', 'C', 'S'] +>>> plasma.data.shape +(3, 31) +>>> plasma.data.columns.get_level_values("M").unique().tolist() +['b', 'n', 'v', 'w'] + +- ``M``, the measurement: ``n`` (number density), ``v`` (velocity), ``w`` + (thermal speed), ``b`` (magnetic field). +- ``C``, the component: ``x``, ``y``, ``z`` for vectors; ``par``, ``per`` and + ``scalar`` for thermal speeds, relative to the magnetic field; empty for + scalars such as density. +- ``S``, the species; empty for the magnetic field. + +Derived Quantities +------------------ + +Each species is an attribute of the plasma. Densities are in +cm\ :sup:`-3` and speeds in km/s. The second proton speed is +:math:`\sqrt{200^2 + 300^2 + 600^2} = 700` km/s: + +>>> plasma.p1.n.tolist() +[1.0, 2.0, 3.0] +>>> plasma.p1.v.mag.round(1).tolist() +[458.3, 700.0, 1044.0] + +Thermal speeds, in km/s, have parallel, perpendicular and scalar components: + +>>> w = plasma.w("p1") +>>> w.columns.tolist() +['par', 'per', 'scalar'] +>>> w["par"].tolist() +[10.0, 20.0, 30.0] + +Temperatures are stored in units of :math:`10^5` K, under the convention +:math:`m w^2 = 2 k_B T`. ``plasma.units`` holds each quantity's factor to SI, +so multiplying by ``plasma.units.T`` gives kelvin: + +>>> T = plasma.T("p1")["scalar"] * plasma.units.T +>>> T.round(-2).tolist() +[4000.0, 35400.0, 49800.0] + +The plasma beta and the anisotropy ``R`` are dimensionless. ``R`` is the +perpendicular over the parallel pressure; for one species it is +:math:`(w_\perp / w_\parallel)^2`, so :math:`7^2 / 10^2 = 0.49` at the first +time: + +>>> plasma.beta("p1")["scalar"].round(2).tolist() +[0.34, 4.18, 4.93] +>>> plasma.R("p1").round(2).tolist() +[0.49, 1.69, 0.87] + +A species string joined with ``+`` asks for a total over those species. The +alpha and proton densities add: + +>>> plasma.a.n.tolist() +[0.5, 1.0, 1.5] +>>> plasma.n("a+p1").tolist() +[1.5, 3.0, 4.5] + +:doc:`/missing_data` lists the quantities that take a total and how a total +treats a species missing at some times. + +A 2D Histogram +-------------- + +:py:class:`~solarwindpy.plotting.hist2d.Hist2D` bins pairs of values. Three +rows make only a demonstration, so this histogram uses three bins per axis: + +>>> h = swp.plotting.hist2d.Hist2D(plasma.p1.n, plasma.p1.v.mag, nbins=3) +>>> int(h.agg().sum()) +3 + +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 for saving the figure: + +>>> TeXlabel = swp.plotting.labels.base.TeXlabel +>>> h.set_labels(x=TeXlabel(("n", "", "p1")), y=TeXlabel(("v", "", "p1"))) +>>> h.path.as_posix() +'Hist2D/n_p1/v_p1/count/linX-linY' + +:py:meth:`~solarwindpy.plotting.hist2d.Hist2D.make_plot` draws it. The +``Agg`` backend renders without a display: + +>>> import matplotlib +>>> matplotlib.use("Agg") +>>> import matplotlib.pyplot as plt +>>> ax, mesh, cbar = h.make_plot() +>>> ax.get_xlabel() +'$n_{p_1} \\; \\left[\\mathrm{cm}^{-3}\\right]$' +>>> plt.close(ax.figure) + +A Fit +----- + +Every fit function takes observed ``x`` and ``y`` arrays. +:py:class:`~solarwindpy.fitfunctions.lines.Line` fits :math:`y = m x + b`; on +points that lie on :math:`y = 2x + 1` it recovers the slope and intercept: + +>>> import numpy as np +>>> x = np.linspace(0, 10, 11) +>>> y = 2.0 * x + 1.0 +>>> fit = swp.fitfunctions.lines.Line(x, y) +>>> fit.make_fit() +>>> {name: round(float(value), 3) for name, value in fit.popt.items()} +{'m': 2.0, 'b': 1.0} + +:py:attr:`~solarwindpy.fitfunctions.core.FitFunction.results` is the fit's +outcome as a one-row table: each parameter's value and uncertainty, then the +fit quality, the number of observations, the degrees of freedom and the +status: + +>>> results = fit.results +>>> results.columns.get_level_values("P").unique().tolist() +['m', 'b', 'chisq_dof', 'rsq', 'nobs', 'dof', 'status'] +>>> round(float(results.loc[0, ("m", "value")]), 3) +2.0 +>>> results.loc[0, ("status", "")] +'ok' ->>> import solarwindpy as sw ->>> sw.__version__ != "unknown" # "unknown" means solarwindpy is not installed -True +Next Steps +---------- +- :doc:`/usage` builds a plasma from your own DataFrame and saves a fit's plot. +- :doc:`/missing_data` explains how missing measurements propagate. +- :doc:`/api_reference` documents every public class and function. diff --git a/docs/source/usage.rst b/docs/source/usage.rst index ca530176d..002e3e96f 100644 --- a/docs/source/usage.rst +++ b/docs/source/usage.rst @@ -129,5 +129,5 @@ component, and species that the plot labels know. Next Steps ---------- -- The :doc:`tutorial` covers more of the library. +- :doc:`missing_data` explains how missing measurements propagate. - The :doc:`api_reference` documents every public class and function. From 93cf14a59078173737275d817bce3aac354a8d49 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 02:14:30 -0500 Subject: [PATCH 06/21] ci(docs): publish the documentation on Read the Docs only The docs were published twice: by Read the Docs, which the README badge and the new quickstart link point to, and by the docs workflow's deploy job to GitHub Pages with a cname of solarwindpy.github.io, a domain this repository does not serve. The deploy job goes; the build job keeps checking every push with -W --keep-going -n. pyproject.toml lists Read the Docs as the Documentation URL, and docs/README.md says where the docs are hosted. The gh-pages branch is left for the branch cleanup. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/docs.yml | 31 ------------------------------- CHANGELOG.md | 8 ++++++++ docs/README.md | 4 +++- pyproject.toml | 1 + 4 files changed, 12 insertions(+), 32 deletions(-) diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 84de36441..1b37b9012 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -66,34 +66,3 @@ jobs: docs/build/coverage/ docs/build/linkcheck/ retention-days: 90 - - deploy: - needs: build - if: github.ref == 'refs/heads/master' && github.event_name == 'push' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - - - uses: actions/setup-python@v7 - with: - python-version: "3.12" - - - name: Install dependencies - run: | - python -m pip install --upgrade pip wheel - # Install pytables separately if needed by the package - pip install --verbose tables - pip install -e ".[docs]" - - - name: Build documentation for deployment - working-directory: docs - run: | - make clean - make html - - - name: Deploy to GitHub Pages - uses: peaceiris/actions-gh-pages@v4 - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - publish_dir: docs/build/html - cname: solarwindpy.github.io # If you have a custom domain \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d58e1e9f..55ee9a030 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `pre-commit install` now installs the commit-message hook as well as the pre-commit hook (`default_install_hook_types` in `.pre-commit-config.yaml`), so the conventional-commit check runs without a separate `pre-commit install --hook-type commit-msg`. +- Read the Docs (https://solarwindpy.readthedocs.io) is the only documentation host. The + package metadata lists it as the `Documentation` URL. + +### Removed + +- The GitHub Pages deployment of the documentation (the `deploy` job in + `.github/workflows/docs.yml`). The workflow still builds the docs with warnings as errors on + every push and pull request. ## [0.4.0] - 2026-11-05 diff --git a/docs/README.md b/docs/README.md index 0427264c3..c02c8ea20 100644 --- a/docs/README.md +++ b/docs/README.md @@ -30,4 +30,6 @@ gitignored, and `make clean` removes it. ## Deployment -Documentation is automatically built and deployed to GitHub Pages via the `.github/workflows/docs.yml` workflow when changes are pushed to the `master` branch. +Read the Docs builds and hosts the documentation at https://solarwindpy.readthedocs.io, +configured by `.readthedocs.yaml`. The `.github/workflows/docs.yml` workflow builds the docs +with warnings as errors on every push and pull request; it does not deploy them. diff --git a/pyproject.toml b/pyproject.toml index 12b020eda..b003a87ca 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -170,6 +170,7 @@ analysis = [ [project.urls] "Bug Tracker" = "https://github.com/blalterman/SolarWindPy/issues" "Source" = "https://github.com/blalterman/SolarWindPy" +"Documentation" = "https://solarwindpy.readthedocs.io" [tool.setuptools.package-data] solarwindpy = ["core/data/*.csv"] From 10ab52c72999be33dcfc3ac8efa5457fa7d91a07 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 02:27:06 -0500 Subject: [PATCH 07/21] docs: scope the species-total and import-test wording The quickstart said any species string joined with "+" asks for a total, but w raises for one and v returns the center-of-mass velocity; it now says quantities that add over species take one, and points to missing_data for which. README's import test runs on staged Python files under src/solarwindpy, not on any file there. Co-Authored-By: Claude Opus 5.5 --- README.rst | 2 +- docs/source/tutorial/quickstart.rst | 9 +++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/README.rst b/README.rst index 3b109bd54..6c844f99c 100644 --- a/README.rst +++ b/README.rst @@ -115,7 +115,7 @@ Development staged ``.rst``, ``.md`` and ``.py`` files, and the conventional-commit check on the message. A commit that stages a ``.py`` file also runs the full test suite with a coverage floor (``.claude/hooks/pre-commit-tests.sh``), and one - that stages a file under ``src/solarwindpy`` runs an import test. + that stages a Python file under ``src/solarwindpy`` runs an import test. 5. Build the documentation and fail on warnings: diff --git a/docs/source/tutorial/quickstart.rst b/docs/source/tutorial/quickstart.rst index 486f53de4..d0d95b392 100644 --- a/docs/source/tutorial/quickstart.rst +++ b/docs/source/tutorial/quickstart.rst @@ -88,16 +88,17 @@ time: >>> plasma.R("p1").round(2).tolist() [0.49, 1.69, 0.87] -A species string joined with ``+`` asks for a total over those species. The -alpha and proton densities add: +Quantities that add over species, such as density, take a species string +joined with ``+`` and return the total. The alpha and proton densities add: >>> plasma.a.n.tolist() [0.5, 1.0, 1.5] >>> plasma.n("a+p1").tolist() [1.5, 3.0, 4.5] -:doc:`/missing_data` lists the quantities that take a total and how a total -treats a species missing at some times. +:doc:`/missing_data` lists the quantities that take a total, notes that +thermal speeds do not, and explains how a total treats a species missing at some +times. A 2D Histogram -------------- From cd2ac644f832a653faf939f563546ca58e2e05bb Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 02:30:32 -0500 Subject: [PATCH 08/21] docs: remove the quarterly documentation review process The review plan page is gone; CONTRIBUTING's "Documentation reviews" section and the Documentation Review issue template described the same quarterly review, which never ran. CI lints and builds the docs with warnings as errors on every push instead. Co-Authored-By: Claude Opus 5.5 --- .github/ISSUE_TEMPLATE/documentation_review.md | 15 --------------- CONTRIBUTING.md | 12 ------------ 2 files changed, 27 deletions(-) delete mode 100644 .github/ISSUE_TEMPLATE/documentation_review.md diff --git a/.github/ISSUE_TEMPLATE/documentation_review.md b/.github/ISSUE_TEMPLATE/documentation_review.md deleted file mode 100644 index cc36807cf..000000000 --- a/.github/ISSUE_TEMPLATE/documentation_review.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -name: Documentation Review -about: Track periodic reviews of project documentation ---- - -## Summary - -Describe the scope of the documentation review. - -## Checklist - -- [ ] Verify docstrings follow NumPy conventions. -- [ ] Run `doc8` and fix issues. -- [ ] Build docs and resolve warnings. -- [ ] Update outdated content and links. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index de067cbc5..704e88462 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -128,18 +128,6 @@ run the suite. - **Version constraints**: Use lower bounds for compatibility, upper bounds for breaking changes - **NumPy 2.0**: Ensure all dependencies support NumPy >=1.26,<3.0 -## Documentation reviews - -Documentation should be reviewed quarterly. Open an issue using the -"Documentation Review" template under `.github/ISSUE_TEMPLATE` to track the -review. - -**Sustainable Review Process:** -- Focus on scientific accuracy of physics examples -- Verify core functionality examples still work -- Update validation approach if package scope changes significantly -- Annual assessment of validation framework appropriateness for current needs - ## Validation Framework Maintenance ### Annual Framework Assessment From 2a9b008a42bc0cecafa5036133ccabef2f91b5e1 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 02:34:20 -0500 Subject: [PATCH 09/21] docs(quickstart): answer a fresh reader's open questions From a fresh-reader review of the quickstart: - The fit uses noisy data from a seeded RNG and reads the slope's uncertainty from psigma and from results[("m", "uncertainty")]; it says the uncertainty is the square root of pcov's diagonal, scaled by the reduced chi-squared as curve_fit does by default. - The histogram is saved: h.path is relative, joined to a figure directory with an extension added, as its docstring says. - The scalar thermal speed is defined, sqrt((w_par^2 + 2 w_per^2) / 3), and stated to be computed by Plasma rather than input; usage.rst says the same. The field magnitude is shown in nT. - e and p2 are named; Agg is selected before solarwindpy is imported. - Next Steps links Plasma, Hist2D and FitFunction.results and names pth, ca, cs, afsq and estimate_electrons. Co-Authored-By: Claude Opus 5.5 --- docs/source/tutorial/quickstart.rst | 103 +++++++++++++++++++++------- docs/source/usage.rst | 3 +- 2 files changed, 79 insertions(+), 27 deletions(-) diff --git a/docs/source/tutorial/quickstart.rst b/docs/source/tutorial/quickstart.rst index d0d95b392..926156995 100644 --- a/docs/source/tutorial/quickstart.rst +++ b/docs/source/tutorial/quickstart.rst @@ -23,15 +23,19 @@ Load the Example Plasma SolarWindPy ships a small example: three rows of synthetic solar wind measurements, chosen for illustration rather than taken from a mission. :py:func:`~solarwindpy.examples.load_plasma` builds a -:py:class:`~solarwindpy.core.plasma.Plasma` from them: +:py:class:`~solarwindpy.core.plasma.Plasma` from them. The session selects +matplotlib's ``Agg`` backend first, so the plot further down renders without a +display: +>>> import matplotlib +>>> matplotlib.use("Agg") >>> import solarwindpy as swp >>> plasma = swp.examples.load_plasma() >>> plasma.species ('a', 'e', 'p1', 'p2') -The species are alphas (``a``), electrons (``e``), protons (``p1``) and a -proton beam (``p2``). +The species are alphas (``a``), electrons (``e``), the proton core (``p1``) +and a proton beam (``p2``), a second proton population. The measurements live in one pandas DataFrame, ``plasma.data``. Its columns are a three-level MultiIndex: @@ -45,11 +49,16 @@ a three-level MultiIndex: - ``M``, the measurement: ``n`` (number density), ``v`` (velocity), ``w`` (thermal speed), ``b`` (magnetic field). -- ``C``, the component: ``x``, ``y``, ``z`` for vectors; ``par``, ``per`` and - ``scalar`` for thermal speeds, relative to the magnetic field; empty for - scalars such as density. +- ``C``, the component: ``x``, ``y``, ``z`` for vectors; ``par`` and ``per`` + for thermal speeds, parallel and perpendicular to the magnetic field; empty + for scalars such as density. - ``S``, the species; empty for the magnetic field. +The data you give a plasma carry ``par`` and ``per`` thermal speeds. The plasma +computes a ``scalar`` thermal speed for each species from those two (see below) +and adds it to ``plasma.data`` as a ``("w", "scalar", species)`` column; it is +not an input. + Derived Quantities ------------------ @@ -62,13 +71,24 @@ cm\ :sup:`-3` and speeds in km/s. The second proton speed is >>> plasma.p1.v.mag.round(1).tolist() [458.3, 700.0, 1044.0] -Thermal speeds, in km/s, have parallel, perpendicular and scalar components: +The magnetic field is in nT: + +>>> plasma.b.mag.round(2).tolist() +[0.63, 0.77, 1.03] + +Thermal speeds, in km/s, have parallel, perpendicular and scalar components. +The scalar thermal speed is +:math:`w = \sqrt{(w_\parallel^2 + 2 w_\perp^2) / 3}`, the combination of a +temperature :math:`T = (T_\parallel + 2 T_\perp) / 3`; at the first time it is +:math:`\sqrt{(10^2 + 2 \cdot 7^2) / 3} \approx 8.12` km/s: >>> w = plasma.w("p1") >>> w.columns.tolist() ['par', 'per', 'scalar'] >>> w["par"].tolist() [10.0, 20.0, 30.0] +>>> w["scalar"].round(2).tolist() +[8.12, 24.17, 28.68] Temperatures are stored in units of :math:`10^5` K, under the convention :math:`m w^2 = 2 k_B T`. ``plasma.units`` holds each quantity's factor to SI, @@ -111,50 +131,70 @@ rows make only a demonstration, so this histogram uses three bins per axis: 3 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 for saving the figure: +counts the points in each bin. Axis labels name the quantities, and the plot's +``path`` is built from them: >>> TeXlabel = swp.plotting.labels.base.TeXlabel >>> h.set_labels(x=TeXlabel(("n", "", "p1")), y=TeXlabel(("v", "", "p1"))) >>> h.path.as_posix() 'Hist2D/n_p1/v_p1/count/linX-linY' -:py:meth:`~solarwindpy.plotting.hist2d.Hist2D.make_plot` draws it. The -``Agg`` backend renders without a display: +:py:meth:`~solarwindpy.plotting.hist2d.Hist2D.make_plot` draws the histogram: ->>> import matplotlib ->>> matplotlib.use("Agg") >>> import matplotlib.pyplot as plt >>> ax, mesh, cbar = h.make_plot() >>> ax.get_xlabel() '$n_{p_1} \\; \\left[\\mathrm{cm}^{-3}\\right]$' + +``path`` is relative: join it to the directory you save figures under and add +a file extension. Nothing is saved for you. Here the directory is a temporary +one: + +>>> import tempfile +>>> from pathlib import Path +>>> with tempfile.TemporaryDirectory() as figures: +... target = (Path(figures) / h.path).with_suffix(".png") +... target.parent.mkdir(parents=True) +... ax.figure.savefig(target) +... print(target.relative_to(figures).as_posix(), target.exists()) +Hist2D/n_p1/v_p1/count/linX-linY.png True >>> plt.close(ax.figure) A Fit ----- Every fit function takes observed ``x`` and ``y`` arrays. -:py:class:`~solarwindpy.fitfunctions.lines.Line` fits :math:`y = m x + b`; on -points that lie on :math:`y = 2x + 1` it recovers the slope and intercept: +:py:class:`~solarwindpy.fitfunctions.lines.Line` fits :math:`y = m x + b`. +Here it fits points scattered about :math:`y = 2x + 1` by noise from a seeded +random number generator: >>> import numpy as np ->>> x = np.linspace(0, 10, 11) ->>> y = 2.0 * x + 1.0 +>>> rng = np.random.default_rng(42) +>>> x = np.linspace(0, 10, 21) +>>> y = 2.0 * x + 1.0 + rng.normal(0.0, 0.5, x.size) >>> fit = swp.fitfunctions.lines.Line(x, y) >>> fit.make_fit() ->>> {name: round(float(value), 3) for name, value in fit.popt.items()} -{'m': 2.0, 'b': 1.0} - -:py:attr:`~solarwindpy.fitfunctions.core.FitFunction.results` is the fit's -outcome as a one-row table: each parameter's value and uncertainty, then the -fit quality, the number of observations, the degrees of freedom and the -status: +>>> {name: round(float(value), 2) for name, value in fit.popt.items()} +{'m': 1.99, 'b': 1.08} +>>> {name: round(float(value), 2) for name, value in fit.psigma.items()} +{'m': 0.03, 'b': 0.19} + +``popt`` holds the fitted parameters and ``psigma`` their uncertainties. Each +uncertainty is the square root of a diagonal element of the parameter +covariance ``pcov``, which is scaled by the fit's reduced chi-squared, as +:py:func:`scipy.optimize.curve_fit` does by default. + +:py:attr:`~solarwindpy.fitfunctions.core.FitFunction.results` is the same +outcome as a one-row table. Its columns are a MultiIndex of the parameter or +quality name (``P``) and the kind (``K``): each parameter's ``value`` and +``uncertainty``, then the fit quality, the number of observations, the degrees +of freedom and the status: >>> results = fit.results >>> results.columns.get_level_values("P").unique().tolist() ['m', 'b', 'chisq_dof', 'rsq', 'nobs', 'dof', 'status'] ->>> round(float(results.loc[0, ("m", "value")]), 3) -2.0 +>>> round(float(results.loc[0, ("m", "uncertainty")]), 2) +0.03 >>> results.loc[0, ("status", "")] 'ok' @@ -163,4 +203,15 @@ Next Steps - :doc:`/usage` builds a plasma from your own DataFrame and saves a fit's plot. - :doc:`/missing_data` explains how missing measurements propagate. +- :py:class:`~solarwindpy.core.plasma.Plasma` documents every derived quantity. + Methods worth knowing next: :py:meth:`~solarwindpy.core.plasma.Plasma.pth` + (thermal pressure), :py:meth:`~solarwindpy.core.plasma.Plasma.ca` (Alfvén + speed), :py:meth:`~solarwindpy.core.plasma.Plasma.cs` (sound speed), + :py:meth:`~solarwindpy.core.plasma.Plasma.afsq` (firehose anisotropy factor) + and :py:meth:`~solarwindpy.core.plasma.Plasma.estimate_electrons` (electrons + from quasi-neutrality and zero current). +- :py:class:`~solarwindpy.plotting.hist2d.Hist2D` documents the histogram's + binning, normalization and contour options. +- :py:attr:`~solarwindpy.fitfunctions.core.FitFunction.results` documents every + column of a fit's table. - :doc:`/api_reference` documents every public class and function. diff --git a/docs/source/usage.rst b/docs/source/usage.rst index 002e3e96f..9bd7df1d6 100644 --- a/docs/source/usage.rst +++ b/docs/source/usage.rst @@ -18,7 +18,8 @@ three-level MultiIndex named ``M``, ``C``, ``S``: - ``M``, the measurement: ``n`` (number density, cm\ :sup:`-3`), ``v`` (velocity, km/s), ``w`` (thermal speed, km/s), ``b`` (magnetic field, nT). - ``C``, the component: ``x``, ``y``, ``z`` for vectors, ``par`` and ``per`` - for thermal speeds, empty for scalars. + for thermal speeds, empty for scalars. The plasma computes a ``scalar`` + thermal speed from ``par`` and ``per``; it is not an input. - ``S``, the species: ``p1`` (protons), ``a`` (alphas), empty for the magnetic field. From d42e15d12c1beec8c474b3330a7d27b3459fcfcb Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 02:42:41 -0500 Subject: [PATCH 10/21] docs: state the fit uncertainty rule and the supported Python range From the hands-on quickstart test: - The quickstart said psigma is rescaled by the reduced chi-squared "as curve_fit does by default", implying the rescaling can be switched off. It cannot: make_fit(absolute_sigma=True) raises NotImplementedError. The page now says pcov is always rescaled by the robust reduced chi-squared, that weights are the 1-sigma uncertainties of y, and what chisq_dof's linear and robust kinds are (the robust one follows the Huber loss make_fit uses by default). - installation.rst states the supported Python range, 3.12 and newer, instead of only pointing at pyproject.toml. - Next Steps says usage.rst shows the input DataFrame layout for bringing your own data. Co-Authored-By: Claude Opus 5.5 --- docs/source/installation.rst | 2 ++ docs/source/tutorial/quickstart.rst | 18 +++++++++++++++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/docs/source/installation.rst b/docs/source/installation.rst index b08ea718f..7174e002b 100644 --- a/docs/source/installation.rst +++ b/docs/source/installation.rst @@ -8,6 +8,8 @@ Installation Requirements ------------ +SolarWindPy supports Python 3.12 and newer (``requires-python = ">=3.12,<4"``). + ``pyproject.toml`` is the single declaration of what SolarWindPy needs: ``requires-python`` gives the supported Python versions and ``dependencies`` gives the supported range of each required package. The diff --git a/docs/source/tutorial/quickstart.rst b/docs/source/tutorial/quickstart.rst index 926156995..ae77f7227 100644 --- a/docs/source/tutorial/quickstart.rst +++ b/docs/source/tutorial/quickstart.rst @@ -181,8 +181,18 @@ random number generator: ``popt`` holds the fitted parameters and ``psigma`` their uncertainties. Each uncertainty is the square root of a diagonal element of the parameter -covariance ``pcov``, which is scaled by the fit's reduced chi-squared, as -:py:func:`scipy.optimize.curve_fit` does by default. +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. + +``chisq_dof`` has two kinds. ``linear`` is the sum of squared residuals, +divided by ``weights`` 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``: + +>>> [round(float(value), 3) for value in fit.chisq_dof] +[0.197, 0.064] :py:attr:`~solarwindpy.fitfunctions.core.FitFunction.results` is the same outcome as a one-row table. Its columns are a MultiIndex of the parameter or @@ -201,7 +211,9 @@ of freedom and the status: Next Steps ---------- -- :doc:`/usage` builds a plasma from your own DataFrame and saves a fit's plot. +- :doc:`/usage` shows the input DataFrame layout for bringing your own data: + the ``M``, ``C``, ``S`` columns a plasma needs. It builds a plasma from that + DataFrame and saves a fit's plot. - :doc:`/missing_data` explains how missing measurements propagate. - :py:class:`~solarwindpy.core.plasma.Plasma` documents every derived quantity. Methods worth knowing next: :py:meth:`~solarwindpy.core.plasma.Plasma.pth` From 219ce1b3f7550553b30427511f9360204d4e0fbf Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 02:57:06 -0500 Subject: [PATCH 11/21] docs(missing-data): keep one worked table and name the section for it Rename "The two levels" to "Worked example" and replace the pressure table, which repeated the temperature one, with a sentence. Co-Authored-By: Claude Opus 5.5 --- docs/source/missing_data.rst | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/docs/source/missing_data.rst b/docs/source/missing_data.rst index 4cde57a1e..21ad7a063 100644 --- a/docs/source/missing_data.rst +++ b/docs/source/missing_data.rst @@ -61,7 +61,7 @@ A total density can also be strict: ``plasma.n("a+p1", skipna=False)`` is NaN at a time when any of its species is missing. -The two levels +Worked example -------------- For temperature (:py:meth:`~solarwindpy.core.plasma.Plasma.T`), @@ -78,16 +78,8 @@ either component is masked as a whole at that time, so its result there is NaN: t3 NaN ok -> NaN NaN ok -> NaN -> NaN Pressure (:py:meth:`~solarwindpy.core.plasma.Plasma.pth`) follows the same -pattern: - -.. code-block:: text - - protons (p1) alphas (a) total "a+p1" - time p_par p_perp -> p_p1 p_par p_perp -> p_a - t0 ok ok -> ok ok ok -> ok -> p1 + a - t1 ok NaN -> NaN ok ok -> ok -> a only - t2 ok ok -> ok NaN NaN -> NaN -> p1 only - t3 NaN ok -> NaN NaN ok -> NaN -> NaN +pattern, with the parallel and perpendicular pressures in place of the +temperatures. The per-species result at each time is the within-species rule; the total is the across-species rule applied to those results. From ed9ae995a96f168f537c8afb522c879e08f8303b Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 02:57:21 -0500 Subject: [PATCH 12/21] docs(usage): list the Plasma columns one tuple per line Co-Authored-By: Claude Opus 5.5 --- docs/source/usage.rst | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/docs/source/usage.rst b/docs/source/usage.rst index 9bd7df1d6..4b8441fab 100644 --- a/docs/source/usage.rst +++ b/docs/source/usage.rst @@ -28,13 +28,21 @@ three-level MultiIndex named ``M``, ``C``, ``S``: >>> epoch = pd.date_range("2023-01-01", periods=3, freq="1h") >>> columns = pd.MultiIndex.from_tuples( ... [ -... ("n", "", "p1"), ("n", "", "a"), -... ("v", "x", "p1"), ("v", "x", "a"), -... ("v", "y", "p1"), ("v", "y", "a"), -... ("v", "z", "p1"), ("v", "z", "a"), -... ("w", "par", "p1"), ("w", "par", "a"), -... ("w", "per", "p1"), ("w", "per", "a"), -... ("b", "x", ""), ("b", "y", ""), ("b", "z", ""), +... ("n", "", "p1"), # density +... ("n", "", "a"), +... ("v", "x", "p1"), # velocity +... ("v", "x", "a"), +... ("v", "y", "p1"), +... ("v", "y", "a"), +... ("v", "z", "p1"), +... ("v", "z", "a"), +... ("w", "par", "p1"), # thermal speed +... ("w", "par", "a"), +... ("w", "per", "p1"), +... ("w", "per", "a"), +... ("b", "x", ""), # magnetic field +... ("b", "y", ""), +... ("b", "z", ""), ... ], ... names=["M", "C", "S"], ... ) From 02178eca2d42bb4d7e66ae2aa871a2b995513ff7 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 03:00:20 -0500 Subject: [PATCH 13/21] docs(quickstart): print the fit results tables and say how to read them Show the Line fit's results on its side, explain each row, and add a seeded Gaussian fit whose table shows the same layout with three parameters. Co-Authored-By: Claude Opus 5.5 --- docs/source/tutorial/quickstart.rst | 46 +++++++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 2 deletions(-) diff --git a/docs/source/tutorial/quickstart.rst b/docs/source/tutorial/quickstart.rst index ae77f7227..312f0b033 100644 --- a/docs/source/tutorial/quickstart.rst +++ b/docs/source/tutorial/quickstart.rst @@ -201,13 +201,55 @@ quality name (``P``) and the kind (``K``): each parameter's ``value`` and of freedom and the status: >>> results = fit.results ->>> results.columns.get_level_values("P").unique().tolist() -['m', 'b', 'chisq_dof', 'rsq', 'nobs', 'dof', 'status'] +>>> print(results.round(3).T.to_string(header=False, index_names=False)) +m value 1.992 + uncertainty 0.029 +b value 1.078 + uncertainty 0.189 +chisq_dof linear 0.197 + robust 0.064 +rsq 0.995 +nobs 21 +dof 19 +status ok + +Printed on its side, the table reads as a checklist. Each parameter's +``value`` is the fit and its ``uncertainty`` the 1-sigma error from ``pcov``. +``chisq_dof`` gives the ``linear`` and ``robust`` reduced chi-squared, ``rsq`` +the coefficient of determination, ``nobs`` the observations used and ``dof`` +the degrees of freedom, ``nobs`` less the number of parameters. ``status`` is +``"ok"`` for a fit that converged; a failed fit holds NaN values and names the +exception instead. A cell reads by its column pair: + >>> round(float(results.loc[0, ("m", "uncertainty")]), 2) 0.03 >>> results.loc[0, ("status", "")] 'ok' +Every fit function's table has this layout, with one pair of columns per +parameter. A :py:class:`~solarwindpy.fitfunctions.gaussians.Gaussian` fit to a +seeded, noisy peak of height 10 at :math:`\mu = 0.5` with width +:math:`\sigma = 1.2` recovers all three within their uncertainties: + +>>> 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) +>>> gaussian = swp.fitfunctions.gaussians.Gaussian(x, y) +>>> gaussian.make_fit() +>>> print(gaussian.results.round(3).T.to_string(header=False, index_names=False)) +mu value 0.502 + uncertainty 0.015 +sigma value 1.201 + uncertainty 0.018 +A value 9.93 + uncertainty 0.131 +chisq_dof linear 0.084 + robust 0.035 +rsq 0.993 +nobs 41 +dof 38 +status ok + Next Steps ---------- From 8703b4cbf94046736704d76118b7e7eab0605abf Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 03:10:29 -0500 Subject: [PATCH 14/21] docs(usage): add a Make a Plot section with build-time figures Document the four plot classes, their bins, axnorm normalizations, contour smoothing, distribution edges and TeXlabel labels, and add the fit-with-residuals figure. Figures come from the matplotlib plot directive with the code shown and no hidden setup (plot_pre_code is empty), so each block runs alone; tests/test_docs_plot_blocks.py runs every block in its own namespace. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 + docs/source/conf.py | 24 +++ docs/source/usage.rst | 352 ++++++++++++++++++++++++++++++++- tests/test_docs_plot_blocks.py | 72 +++++++ 4 files changed, 447 insertions(+), 5 deletions(-) create mode 100644 tests/test_docs_plot_blocks.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 55ee9a030..20688635f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - A quickstart page that runs end to end on `solarwindpy.examples.load_plasma`: the `M`/`C`/`S` columns, derived quantities with their units, an `"a+p1"` total, a `Hist2D` and a `Line` fit's `results`. It replaces the tutorial stub. +- A "Make a Plot" section in the Usage guide: when to use `Hist1D`, `Hist2D`, `SpiralPlot2D` + and `Scatter`, their bins, `axnorm` normalizations, contour smoothing, distribution edges and + `TeXlabel` labels, with figures drawn at build time by the code shown beside them. A test + runs each of those code blocks on its own. ### Changed diff --git a/docs/source/conf.py b/docs/source/conf.py index 2af0b693d..b2c86693f 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -41,10 +41,34 @@ "sphinx.ext.mathjax", "numpydoc", "sphinxcontrib.bibtex", + "matplotlib.sphinxext.plot_directive", ] bibtex_bibfiles = ['solarwindpy.bib'] +# -- Plot directive configuration ------------------------------------------- + +# Every figure in the guide is drawn by the code shown with it, and that code +# must run on its own when pasted into a fresh session: no hidden setup code +# (the default would import numpy and pyplot), one PNG per figure, and the +# package's style, which the directive's per-figure reset would otherwise +# discard after the first import of solarwindpy.plotting. +import matplotlib # noqa: E402 + +plot_include_source = True +plot_pre_code = "" +plot_formats = [("png", 100)] +plot_html_show_formats = False +plot_html_show_source_link = False +plot_rcparams = dict( + matplotlib.rc_params_from_file( + os.path.join( + os.path.dirname(solarwindpy.__file__), "plotting", "solarwindpy.mplstyle" + ), + use_default_template=False, + ) +) + # -- Templates configuration ------------------------------------------------ templates_path = ['_templates'] diff --git a/docs/source/usage.rst b/docs/source/usage.rst index 4b8441fab..349e152e7 100644 --- a/docs/source/usage.rst +++ b/docs/source/usage.rst @@ -2,8 +2,10 @@ Usage Guide =========== This page walks through a first session: build a plasma from a DataFrame, read -a species' quantities, fit a function, and save a plot. Every example on this -page runs as a doctest (``pytest --doctest-glob='*.rst' docs/source``). +a species' quantities, fit a function, and make and save plots. Every ``>>>`` +example on this page runs as a doctest +(``pytest --doctest-glob='*.rst' docs/source``), and every figure is drawn by +the code shown above it when the documentation is built. .. contents:: :local: @@ -112,9 +114,331 @@ Fit function Module LaTeX Gaussian gaussians f(x)=A \cdot e^{-\frac{1}{2} \left(\frac{x-\mu}{\sigma}\right)^2} ... -Save a Plot +Make a Plot ----------- +:py:mod:`solarwindpy.plotting` has four plot classes. Each takes pandas +Series, so a plasma's quantities pass straight in: + +- :py:class:`~solarwindpy.plotting.hist1d.Hist1D` bins one quantity: the + distribution of ``x``, or the mean of a ``y`` in each bin of ``x``. +- :py:class:`~solarwindpy.plotting.hist2d.Hist2D` bins two quantities on a + fixed grid: their joint distribution, or the mean of a ``z`` in each cell. +- :py:class:`~solarwindpy.plotting.spiral.SpiralPlot2D` bins two quantities on + an adaptive mesh, which splits a cell into four while it holds more than + ``min_per_bin`` points. Use it when the data are dense in some places and + sparse in others, so one grid is either too coarse for the core or too noisy + in the tails. +- :py:class:`~solarwindpy.plotting.scatter.Scatter` draws every point, + optionally colored by ``z``. Use it for few points; past a few thousand they + overlap and a histogram shows more. + +The figures below use synthetic, seeded data that look like solar wind: a slow +population near 380 km/s and a fast one near 650 km/s, with a log-normal +density that falls as speed rises. Each block is complete: paste it into a +fresh Python session and it draws the figure shown under it. + +One quantity +~~~~~~~~~~~~ + +``make_plot`` draws the histogram. ``set_labels`` takes a +:py:class:`~solarwindpy.plotting.labels.base.TeXlabel` per axis; `Labels`_ +explains them. + +.. plot:: + + import numpy as np + import pandas as pd + from solarwindpy.plotting.hist1d import Hist1D + 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") + + h1 = Hist1D(v, nbins=60) + h1.set_labels(x=TeXlabel(("v", "", "p1"))) + h1.make_plot() + +Two quantities +~~~~~~~~~~~~~~ + +Density spans a decade, so ``logy=True`` bins it in :math:`\log_{10}` and +draws a log axis. ``make_plot`` colors each cell by its count: + +.. plot:: + + import numpy as np + import pandas as pd + 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") + + h2 = Hist2D(v, n, logy=True, nbins=50) + h2.set_labels(x=TeXlabel(("v", "", "p1")), y=TeXlabel(("n", "", "p1"))) + h2.make_plot() + +: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 +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 +``axnorm="t"``, explained in `Normalizations`_, scales the peak to 1: + +.. plot:: + + import numpy as np + import pandas as pd + 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") + + h2 = Hist2D(v, n, logy=True, nbins=50, axnorm="t") + h2.set_labels(x=TeXlabel(("v", "", "p1")), y=TeXlabel(("n", "", "p1"))) + h2.plot_contours(gaussian_filter_std=2, nan_aware_filter=True, plot_edges=True) + +:py:meth:`~solarwindpy.plotting.hist2d.Hist2D.make_joint_h2_h1_plot` draws the +histogram with its projections on the top and right margins. Each margin is a +:py:class:`~solarwindpy.plotting.hist1d.Hist1D` from +:py:meth:`~solarwindpy.plotting.hist2d.Hist2D.project_1d`, on the histogram's +own bins; the right one is drawn with ``make_plot(transpose_axes=True)``, so +its counts run along ``x``. Call those two methods yourself to lay out the +margins differently. + +.. plot:: + + import numpy as np + import pandas as pd + 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") + + h2 = Hist2D(v, n, logy=True, nbins=50) + h2.set_labels(x=TeXlabel(("v", "", "p1")), y=TeXlabel(("n", "", "p1"))) + h2.make_joint_h2_h1_plot() + +An adaptive mesh +~~~~~~~~~~~~~~~~ + +:py:class:`~solarwindpy.plotting.spiral.SpiralPlot2D` takes the same data. Its +cells are small in the two cores and large in the sparse region between them, +so each cell holds enough points to be trusted. Because the cells differ in +size, plot it with ``axnorm="d"``: a raw count would make a large, sparse cell +look as full as a small, dense one. The mesh is its smoothing: it has no +Gaussian filter, by design. + +.. plot:: + + import numpy as np + import pandas as pd + from solarwindpy.plotting.spiral import SpiralPlot2D + 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") + + sp = SpiralPlot2D(v, n, logy=True, axnorm="d", min_per_bin=50) + sp.set_labels(x=TeXlabel(("v", "", "p1")), y=TeXlabel(("n", "", "p1"))) + sp.make_plot() + +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. + +.. 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(0) + N = 300 + 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") + w = pd.Series(0.1 * v + rng.normal(0, 5, v.size), name="w") + + sc = Scatter(v, w, n) + sc.set_labels( + x=TeXlabel(("v", "", "p1")), + y=TeXlabel(("w", "", "p1")), + z=TeXlabel(("n", "", "p1")), + ) + sc.make_plot(s=8) + +Bins +~~~~ + +``nbins`` chooses the bins of a :py:class:`~solarwindpy.plotting.hist1d.Hist1D` +or :py:class:`~solarwindpy.plotting.hist2d.Hist2D`: + +- an integer, that many equal bins between the data's extremes + (:func:`numpy.histogram_bin_edges`); +- a rule name such as ``"fd"`` or ``"auto"``, passed to the same function, or + ``"knuth"`` for astropy's ``knuth_bin_width``; +- an array of edges, or another histogram's ``intervals``; +- in 2-D, a pair giving each axis its own specification. + +``logx`` and ``logy`` bin :math:`\log_{10}|x|` instead of ``x``, so the bins +are equal in ratio. ``clip=True`` drops the points outside the 0.01st and +99.99th percentiles when the points are placed in bins (``"l"`` or ``"u"`` +clips one tail); the bin edges still come from all the data. +:py:class:`~solarwindpy.plotting.spiral.SpiralPlot2D` instead takes +``initial_bins`` and ``min_per_bin``. + +Edges given as an array are used as given: + +>>> import pandas as pd +>>> from solarwindpy.plotting.hist1d import Hist1D +>>> rng = np.random.default_rng(0) +>>> v = pd.Series(rng.normal(400, 50, 1000), name="v") +>>> bins = Hist1D(v, nbins=[250, 350, 450, 550]).intervals["x"] +>>> bins.left.tolist(), bins.right.tolist() +([250, 350, 450], [350, 450, 550]) + +Normalizations +~~~~~~~~~~~~~~ + +``axnorm`` normalizes the aggregated values: + +- ``None``: no normalization; counts, or the aggregated ``y`` or ``z``. +- ``"t"``: divide by the maximum, so the peak is 1. +- ``"d"``: divide by the total and by each bin's width (1-D) or area (2-D), a + probability density. On a log axis the width is measured in + :math:`\log_{10}`. +- ``"c"`` and ``"r"``: divide each column (``x`` bin) or row (``y`` bin) by its + own maximum, so every column or row peaks at 1. Use them to compare shapes + across ``x`` when the counts vary greatly with ``x``. +- ``"cd"`` and ``"rd"``: make each column or row a probability density along + the other axis: divide by its total and by the bin width along that axis. + +The binning decides which keys a plot accepts. +:py:class:`~solarwindpy.plotting.hist2d.Hist2D` accepts all six; +: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.scatter.Scatter` has no bins and no +``axnorm``. Any other key raises: + +>>> Hist1D(v).binning.allowed_axnorm +('d', 't') +>>> Hist1D(v, axnorm="c") +Traceback (most recent call last): +... +ValueError: Unrecognized axnorm 'c'; expected one of: d, t + +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: + +.. 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") + + fig, axes = plt.subplots(2, 2, figsize=(9, 7), sharex=True, sharey=True) + for ax, axnorm in zip(axes.flat, [None, "d", "c", "cd"]): + h2 = Hist2D(v, n, logy=True, nbins=40, axnorm=axnorm) + h2.set_labels(x=TeXlabel(("v", "", "p1")), y=TeXlabel(("n", "", "p1"))) + h2.make_plot(ax=ax) + ax.set_title(f"axnorm={axnorm!r}") + ax.label_outer() + fig.tight_layout() + +Labels +~~~~~~ + +A :py:class:`~solarwindpy.plotting.labels.base.TeXlabel` builds an axis label +from the same ``(M, C, S)`` key that names a column of the plasma's data: the +measurement's symbol, subscripted by the component and the species, and its +display units. The symbols and units come from the quantity registry, +:py:mod:`solarwindpy.core.quantities`. Leave the component or species empty +when there is none: + +>>> from solarwindpy.plotting.labels.base import TeXlabel +>>> print(TeXlabel(("n", "", "p1"))) +$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]$ + +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: + +>>> 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]$ + +A dimensionless quantity, such as :math:`\beta`, has the units +:math:`[\#]`. A second key makes a ratio: + +>>> print(TeXlabel(("n", "", "a"), ("n", "", "p1"))) +$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``: + +>>> from solarwindpy.plotting.hist2d import Hist2D +>>> h2 = Hist2D(v, (2 * v).rename("y"), axnorm="cd") +>>> print(h2.labels.z) +$\mathrm{1D \, Probability \, Density} \; \left[\#\right]$ + +``solarwindpy.plotting.labels.available()`` prints every measurement, +component and species ``TeXlabel`` knows, and the special labels. + +Plot a Fit +---------- + A fit carries a plotter that draws the observations and the fitted curve. The ``Agg`` backend renders without a display. The figure is written to a temporary directory: @@ -132,8 +456,26 @@ temporary directory: True >>> plt.close(ax.figure) -``solarwindpy.plotting.labels.available()`` prints every measurement, -component, and species that the plot labels know. +:py:meth:`~solarwindpy.fitfunctions.plots.FFPlot.plot_raw_used_fit_resid` +adds the residuals. The top panel shows the observations, the fitted curve and +an annotation with the fit function, its parameters and their uncertainties, +and the reduced chi-squared of each kind. The bottom panel shows the residuals, +observed minus fitted, against ``x``; the default ``resid_pct=True`` shows them +in percent of the fit instead, which is large wherever the fit nears zero. +The Gaussian is the seeded, noisy one whose results table +:doc:`tutorial/quickstart` prints: + +.. plot:: + + import numpy as np + from solarwindpy.fitfunctions.gaussians import Gaussian + + 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.make_fit() + fit.plotter.plot_raw_used_fit_resid(resid_kwargs=dict(resid_pct=False)) Next Steps ---------- diff --git a/tests/test_docs_plot_blocks.py b/tests/test_docs_plot_blocks.py new file mode 100644 index 000000000..8ce3f9158 --- /dev/null +++ b/tests/test_docs_plot_blocks.py @@ -0,0 +1,72 @@ +# Spent-When: PERMANENT(the documentation stops drawing figures with the plot directive) +# Supersedes: none +"""Every ``.. plot::`` block in the documentation runs on its own. + +The guide shows the code that draws each figure, and a reader should be able +to paste one block into a fresh session and get that figure. ``conf.py`` sets +``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. +""" + +import re +from pathlib import Path + +import matplotlib +import pytest + +matplotlib.use("Agg") +from matplotlib import pyplot as plt # noqa: E402 + +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, + ) + +_DIRECTIVE = re.compile(r"^(\s*)\.\. plot::\s*$") + + +def _plot_blocks(path): + """Yield ``(line, code)`` for each inline ``.. plot::`` block in ``path``.""" + lines = path.read_text().splitlines() + for i, line in enumerate(lines): + match = _DIRECTIVE.match(line) + if match is None: + continue + indent = len(match.group(1)) + body = [] + for following in lines[i + 1 :]: + if following.strip() and len(following) - len(following.lstrip()) <= indent: + break + body.append(following) + # Drop the directive's options, then the blank line after them. + while body and (not body[0].strip() or body[0].strip().startswith(":")): + body.pop(0) + width = min(len(b) - len(b.lstrip()) for b in body if b.strip()) + yield i + 1, "\n".join(b[width:] for b in body).strip() + "\n" + + +BLOCKS = [ + pytest.param(code, id=f"{path.relative_to(DOCS)}:{line}") + for path in sorted(DOCS.rglob("*.rst")) + for line, code in _plot_blocks(path) +] + + +def test_the_guide_has_plot_blocks(): + """The collector finds blocks, so an empty parametrization cannot pass.""" + assert BLOCKS + + +@pytest.mark.parametrize("code", BLOCKS) +def test_plot_block_runs_alone(code): + """A block runs with nothing defined beforehand and draws a figure.""" + try: + exec(compile(code, "", "exec"), {"__name__": "__main__"}) + assert plt.get_fignums(), "the block drew no figure" + finally: + plt.close("all") From 86f6dac2b60f41168a40a3b7e03ad3b45133b1fd Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 03:13:44 -0500 Subject: [PATCH 15/21] docs: copy examples without their prompts Add sphinx-copybutton, configured to strip the ">>> " and "... " prompts, to conf.py, the docs and dev extras and solarwindpy.yml. Co-Authored-By: Claude Opus 5.5 --- docs/source/conf.py | 8 ++++++++ pyproject.toml | 2 ++ solarwindpy.yml | 1 + 3 files changed, 11 insertions(+) diff --git a/docs/source/conf.py b/docs/source/conf.py index b2c86693f..793e3ed2b 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -42,10 +42,18 @@ "numpydoc", "sphinxcontrib.bibtex", "matplotlib.sphinxext.plot_directive", + "sphinx_copybutton", ] bibtex_bibfiles = ['solarwindpy.bib'] +# -- Copy button configuration --------------------------------------------- + +# Copy doctest examples without their ``>>> `` and ``... `` prompts, so a +# reader can paste them into a session. +copybutton_prompt_text = r">>> |\.\.\. " +copybutton_prompt_is_regexp = True + # -- Plot directive configuration ------------------------------------------- # Every figure in the guide is drawn by the code shown with it, and that code diff --git a/pyproject.toml b/pyproject.toml index b003a87ca..84524d19b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -132,6 +132,7 @@ docs = [ "sphinx_rtd_theme>=2.0", "sphinxcontrib-spelling>=8.0", "sphinxcontrib-bibtex>=2.6", + "sphinx-copybutton>=0.5", "numpydoc>=1.6", "docstring-inheritance>=3.0,<4", "doc8>=1.1", @@ -146,6 +147,7 @@ dev = [ "sphinx_rtd_theme>=2.0", "sphinxcontrib-spelling>=8.0", "sphinxcontrib-bibtex>=2.6", + "sphinx-copybutton>=0.5", "numpydoc>=1.6", "docstring-inheritance>=3.0,<4", "doc8>=1.1", diff --git a/solarwindpy.yml b/solarwindpy.yml index 379f6dde3..f8f555356 100644 --- a/solarwindpy.yml +++ b/solarwindpy.yml @@ -87,6 +87,7 @@ dependencies: - six - snowballstemmer - sphinx +- sphinx-copybutton - sphinx-rtd-theme - sphinxcontrib-applehelp - sphinxcontrib-bibtex From 127a7222da0f8b2317fc9483cfae08b0c2104b54 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 03:26:58 -0500 Subject: [PATCH 16/21] test(docs): run rst examples under fixed pandas display options Doctests and Sybil examples now run under pandas' non-terminal display defaults, set in one place in conftest.py, so a printed Series or DataFrame does not follow the width of the terminal running pytest. rst examples compare output with whitespace normalized under both runners; docstring examples keep exact whitespace. Co-Authored-By: Claude Opus 5.5 --- conftest.py | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) diff --git a/conftest.py b/conftest.py index c78b0d5db..f5ccd298b 100644 --- a/conftest.py +++ b/conftest.py @@ -27,10 +27,19 @@ Docstring examples that need a ``Plasma`` build one with ``solarwindpy.examples.load_plasma()``; no fixture injects one. + +Every example, doctest or Sybil, runs under pandas' display defaults for a +session without a terminal (``PANDAS_DISPLAY``), so a printed Series or +DataFrame does not depend on the width of the terminal running pytest, and a +reader who copies an example sees the output it shows. Whitespace in an +expected output of an rst example is normalized, under Sybil and under the +doctest plugin alike; docstring examples keep exact whitespace. """ +import doctest from pathlib import Path +import pandas as pd import pytest # Doctest node id -> reason. Each entry names the defect that retires it. @@ -42,6 +51,30 @@ "docs/source/tutorial/quickstart.rst", "docs/source/installation.rst", ] + +# pandas' own defaults when output is not a terminal, set explicitly so an +# example's printed table never follows the terminal pytest runs in. +PANDAS_DISPLAY = { + "display.width": 80, + "display.max_columns": 20, + "display.max_rows": 60, + "display.precision": 6, +} +_pandas_display_contexts = [] + + +def _enter_pandas_display(): + """Apply ``PANDAS_DISPLAY`` until the matching ``_exit_pandas_display``.""" + context = pd.option_context(*(x for item in PANDAS_DISPLAY.items() for x in item)) + context.__enter__() + _pandas_display_contexts.append(context) + + +def _exit_pandas_display(): + """Restore the pandas options ``_enter_pandas_display`` replaced.""" + _pandas_display_contexts.pop().__exit__(None, None, None) + + _SYBIL_PATHS = { Path(__file__).resolve().parent / document for document in SYBIL_DOCUMENTS } @@ -57,11 +90,30 @@ from sybil.parsers.rest import DocTestParser, PythonCodeBlockParser, SkipParser pytest_collect_file = Sybil( - parsers=[DocTestParser(), PythonCodeBlockParser(), SkipParser()], + parsers=[ + DocTestParser(optionflags=doctest.NORMALIZE_WHITESPACE), + PythonCodeBlockParser(), + SkipParser(), + ], patterns=SYBIL_DOCUMENTS, + setup=lambda namespace: _enter_pandas_display(), + teardown=lambda namespace: _exit_pandas_display(), ).pytest() +@pytest.fixture(autouse=True) +def _pandas_display_defaults(request): + """Run each doctest under ``PANDAS_DISPLAY``; Sybil sets it per document.""" + if not isinstance(request.node, pytest.DoctestItem): + yield + return + _enter_pandas_display() + try: + yield + finally: + _exit_pandas_display() + + def _restore_document_order(items): """Put Sybil examples back in document line order, in their own slots.""" # Sorts the Sybil items by (path, line), so within each document the @@ -93,6 +145,9 @@ def _deselect_doctest_duplicates(config, items): def pytest_collection_modifyitems(config, items): for item in items: + if isinstance(item, pytest.DoctestItem) and item.path.suffix == ".rst": + # One runner serves a file's examples, so this sets the file's flag. + item.runner.optionflags |= doctest.NORMALIZE_WHITESPACE reason = DOCTEST_XFAIL.get(item.nodeid) if reason is not None: item.add_marker(pytest.mark.xfail(strict=True, reason=reason)) From 9685ed01445b34303caaaf1229a107ca67539320 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 03:32:51 -0500 Subject: [PATCH 17/21] docs: show pandas output instead of lists in the examples A quantity prints as the Series or DataFrame it is, with its epoch index, name and component columns, rather than as a bare list. The unique-measurement Index keeps .tolist(): its repr prints the dtype, which pandas has changed between versions. Co-Authored-By: Claude Opus 5.5 --- docs/source/tutorial/quickstart.rst | 83 ++++++++++++++++++++--------- docs/source/usage.rst | 29 ++++++---- 2 files changed, 77 insertions(+), 35 deletions(-) diff --git a/docs/source/tutorial/quickstart.rst b/docs/source/tutorial/quickstart.rst index 312f0b033..56aced23a 100644 --- a/docs/source/tutorial/quickstart.rst +++ b/docs/source/tutorial/quickstart.rst @@ -62,59 +62,92 @@ not an input. Derived Quantities ------------------ -Each species is an attribute of the plasma. Densities are in +Each species is an attribute of the plasma, and each of its quantities is a +pandas Series indexed by the measurement time, ``epoch``. Densities are in cm\ :sup:`-3` and speeds in km/s. The second proton speed is :math:`\sqrt{200^2 + 300^2 + 600^2} = 700` km/s: ->>> plasma.p1.n.tolist() -[1.0, 2.0, 3.0] ->>> plasma.p1.v.mag.round(1).tolist() -[458.3, 700.0, 1044.0] +>>> plasma.p1.n +epoch +1995-01-01 12:35:00.000000 1.0 +2022-03-23 19:29:09.000000 2.0 +2022-10-09 01:47:01.234560 3.0 +Name: n, dtype: float64 +>>> plasma.p1.v.mag.round(1) +epoch +1995-01-01 12:35:00.000000 458.3 +2022-03-23 19:29:09.000000 700.0 +2022-10-09 01:47:01.234560 1044.0 +Name: mag, dtype: float64 The magnetic field is in nT: ->>> plasma.b.mag.round(2).tolist() -[0.63, 0.77, 1.03] +>>> plasma.b.mag.round(2) +epoch +1995-01-01 12:35:00.000000 0.63 +2022-03-23 19:29:09.000000 0.77 +2022-10-09 01:47:01.234560 1.03 +Name: mag, dtype: float64 Thermal speeds, in km/s, have parallel, perpendicular and scalar components. The scalar thermal speed is :math:`w = \sqrt{(w_\parallel^2 + 2 w_\perp^2) / 3}`, the combination of a temperature :math:`T = (T_\parallel + 2 T_\perp) / 3`; at the first time it is -:math:`\sqrt{(10^2 + 2 \cdot 7^2) / 3} \approx 8.12` km/s: +:math:`\sqrt{(10^2 + 2 \cdot 7^2) / 3} \approx 8.12` km/s. A quantity with +components is a DataFrame whose columns are the components, ``C``: ->>> w = plasma.w("p1") ->>> w.columns.tolist() -['par', 'per', 'scalar'] ->>> w["par"].tolist() -[10.0, 20.0, 30.0] ->>> w["scalar"].round(2).tolist() -[8.12, 24.17, 28.68] +>>> plasma.w("p1").round(2) +C par per scalar +epoch +1995-01-01 12:35:00.000000 10.0 7.0 8.12 +2022-03-23 19:29:09.000000 20.0 26.0 24.17 +2022-10-09 01:47:01.234560 30.0 28.0 28.68 Temperatures are stored in units of :math:`10^5` K, under the convention :math:`m w^2 = 2 k_B T`. ``plasma.units`` holds each quantity's factor to SI, so multiplying by ``plasma.units.T`` gives kelvin: >>> T = plasma.T("p1")["scalar"] * plasma.units.T ->>> T.round(-2).tolist() -[4000.0, 35400.0, 49800.0] +>>> T.round(-2) +epoch +1995-01-01 12:35:00.000000 4000.0 +2022-03-23 19:29:09.000000 35400.0 +2022-10-09 01:47:01.234560 49800.0 +Name: scalar, dtype: float64 The plasma beta and the anisotropy ``R`` are dimensionless. ``R`` is the perpendicular over the parallel pressure; for one species it is :math:`(w_\perp / w_\parallel)^2`, so :math:`7^2 / 10^2 = 0.49` at the first time: ->>> plasma.beta("p1")["scalar"].round(2).tolist() -[0.34, 4.18, 4.93] ->>> plasma.R("p1").round(2).tolist() -[0.49, 1.69, 0.87] +>>> plasma.beta("p1").round(2) +C par per scalar +epoch +1995-01-01 12:35:00.000000 0.52 0.26 0.34 +2022-03-23 19:29:09.000000 2.86 4.84 4.18 +2022-10-09 01:47:01.234560 5.39 4.70 4.93 +>>> plasma.R("p1").round(2) +epoch +1995-01-01 12:35:00.000000 0.49 +2022-03-23 19:29:09.000000 1.69 +2022-10-09 01:47:01.234560 0.87 +Name: p1, dtype: float64 Quantities that add over species, such as density, take a species string joined with ``+`` and return the total. The alpha and proton densities add: ->>> plasma.a.n.tolist() -[0.5, 1.0, 1.5] ->>> plasma.n("a+p1").tolist() -[1.5, 3.0, 4.5] +>>> plasma.a.n +epoch +1995-01-01 12:35:00.000000 0.5 +2022-03-23 19:29:09.000000 1.0 +2022-10-09 01:47:01.234560 1.5 +Name: n, dtype: float64 +>>> plasma.n("a+p1") +epoch +1995-01-01 12:35:00.000000 1.5 +2022-03-23 19:29:09.000000 3.0 +2022-10-09 01:47:01.234560 4.5 +Name: a+p1, dtype: float64 :doc:`/missing_data` lists the quantities that take a total, notes that thermal speeds do not, and explains how a total treats a species missing at some diff --git a/docs/source/usage.rst b/docs/source/usage.rst index 349e152e7..3007a8086 100644 --- a/docs/source/usage.rst +++ b/docs/source/usage.rst @@ -77,17 +77,27 @@ Vectors carry their magnitude. The first proton speed is :math:`\sqrt{400^2 + 10^2 + 20^2} \approx 400.62` km/s, and the first field magnitude is :math:`\sqrt{3.5^2 + 1.2^2 + 0.8^2} \approx 3.79` nT: ->>> plasma.p1.v.mag.round(2).tolist() -[400.62, 450.94, 420.75] ->>> plasma.b.mag.round(2).tolist() -[3.79, 4.53, 4.12] +>>> plasma.p1.v.mag.round(2) +2023-01-01 00:00:00 400.62 +2023-01-01 01:00:00 450.94 +2023-01-01 02:00:00 420.75 +Freq: h, Name: mag, dtype: float64 +>>> plasma.b.mag.round(2) +2023-01-01 00:00:00 3.79 +2023-01-01 01:00:00 4.53 +2023-01-01 02:00:00 4.12 +Freq: h, Name: mag, dtype: float64 The plasma combines species and field. Proton beta is :math:`\beta = 2 \mu_0 p / B^2`, with thermal pressure :math:`p = n m w^2 / 2` -under the :math:`m w^2 = 2 k_B T` convention: +under the :math:`m w^2 = 2 k_B T` convention. Like temperature and thermal +speed, it has ``par``, ``per`` and ``scalar`` columns: ->>> plasma.beta("p1")["par"].round(2).tolist() -[0.66, 1.0, 0.83] +>>> plasma.beta("p1").round(2) +C par per scalar +2023-01-01 00:00:00 0.66 0.46 0.53 +2023-01-01 01:00:00 1.00 0.64 0.76 +2023-01-01 02:00:00 0.83 0.55 0.64 Fit a Function -------------- @@ -322,9 +332,8 @@ Edges given as an array are used as given: >>> from solarwindpy.plotting.hist1d import Hist1D >>> rng = np.random.default_rng(0) >>> v = pd.Series(rng.normal(400, 50, 1000), name="v") ->>> bins = Hist1D(v, nbins=[250, 350, 450, 550]).intervals["x"] ->>> bins.left.tolist(), bins.right.tolist() -([250, 350, 450], [350, 450, 550]) +>>> Hist1D(v, nbins=[250, 350, 450, 550]).intervals["x"] +IntervalIndex([(250, 350], (350, 450], (450, 550]], dtype='interval[int64, right]') Normalizations ~~~~~~~~~~~~~~ From 2c31186fb0ca93c7ffc8081a233fc981f3603943 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 03:34:12 -0500 Subject: [PATCH 18/21] docs(api): title API pages and sections by their short names Class, function and module pages take the object's own name as their title (Plasma, hist1d), so the sidebar no longer repeats the package path; each page states its import line instead. Submodule tables list short names, and the API sections drop the word "Module". Co-Authored-By: Claude Opus 5.5 --- docs/source/_templates/autosummary/base.rst | 7 +++++ docs/source/_templates/autosummary/class.rst | 4 ++- docs/source/_templates/autosummary/module.rst | 6 ++-- docs/source/api_reference.rst | 28 +++++++++---------- 4 files changed, 28 insertions(+), 17 deletions(-) create mode 100644 docs/source/_templates/autosummary/base.rst diff --git a/docs/source/_templates/autosummary/base.rst b/docs/source/_templates/autosummary/base.rst new file mode 100644 index 000000000..e04fd17f1 --- /dev/null +++ b/docs/source/_templates/autosummary/base.rst @@ -0,0 +1,7 @@ +{{ objname | escape | underline}} + +``from {{ module }} import {{ objname }}`` + +.. currentmodule:: {{ module }} + +.. auto{{ objtype }}:: {{ objname }} diff --git a/docs/source/_templates/autosummary/class.rst b/docs/source/_templates/autosummary/class.rst index 7585d7cb5..ce1f0235b 100644 --- a/docs/source/_templates/autosummary/class.rst +++ b/docs/source/_templates/autosummary/class.rst @@ -1,4 +1,6 @@ -{{ fullname | escape | underline}} +{{ objname | escape | underline}} + +``from {{ module }} import {{ objname }}`` .. currentmodule:: {{ module }} diff --git a/docs/source/_templates/autosummary/module.rst b/docs/source/_templates/autosummary/module.rst index ffc784bb7..be6b4ed33 100644 --- a/docs/source/_templates/autosummary/module.rst +++ b/docs/source/_templates/autosummary/module.rst @@ -1,4 +1,6 @@ -{{ fullname | escape | underline}} +{{ name | escape | underline}} + +``import {{ fullname }}`` .. automodule:: {{ fullname }} :no-members: @@ -65,7 +67,7 @@ :recursive: {% for item in modules %} - {{ item }} + ~{{ item }} {%- endfor %} {% endif %} diff --git a/docs/source/api_reference.rst b/docs/source/api_reference.rst index 2e1f766c6..2a8142853 100644 --- a/docs/source/api_reference.rst +++ b/docs/source/api_reference.rst @@ -27,8 +27,8 @@ the module that defines it, and is documented at that path. ~solarwindpy.plotting.hist2d.Hist2D ~solarwindpy.plotting.labels.base.TeXlabel -Core Module ------------ +Core +---- .. autosummary:: :toctree: _autosummary @@ -36,8 +36,8 @@ Core Module solarwindpy.core -Plotting Module ---------------- +Plotting +-------- .. autosummary:: :toctree: _autosummary @@ -45,8 +45,8 @@ Plotting Module solarwindpy.plotting -Fit Functions Module --------------------- +Fit Functions +------------- .. autosummary:: :toctree: _autosummary @@ -54,8 +54,8 @@ Fit Functions Module solarwindpy.fitfunctions -Solar Activity Module ---------------------- +Solar Activity +-------------- .. autosummary:: :toctree: _autosummary @@ -63,8 +63,8 @@ Solar Activity Module solarwindpy.solar_activity -Instabilities Module --------------------- +Instabilities +------------- .. autosummary:: :toctree: _autosummary @@ -72,8 +72,8 @@ Instabilities Module solarwindpy.instabilities -Tools Module ------------- +Tools +----- .. autosummary:: :toctree: _autosummary @@ -81,8 +81,8 @@ Tools Module solarwindpy.tools -Examples Module ---------------- +Examples +-------- .. autosummary:: :toctree: _autosummary From a89338cc4dc45ed93522edb67d0af843f5b9d694 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 03:41:27 -0500 Subject: [PATCH 19/21] docs(quickstart): show the measurement level as its Index The Index repr names the level, M. Its dtype, str, holds across the supported pandas 3.x range, so the list form kept by the previous commit was not needed. Co-Authored-By: Claude Opus 5.5 --- docs/source/tutorial/quickstart.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/source/tutorial/quickstart.rst b/docs/source/tutorial/quickstart.rst index 56aced23a..a16f9888d 100644 --- a/docs/source/tutorial/quickstart.rst +++ b/docs/source/tutorial/quickstart.rst @@ -44,8 +44,8 @@ a three-level MultiIndex: ['M', 'C', 'S'] >>> plasma.data.shape (3, 31) ->>> plasma.data.columns.get_level_values("M").unique().tolist() -['b', 'n', 'v', 'w'] +>>> plasma.data.columns.get_level_values("M").unique() +Index(['b', 'n', 'v', 'w'], dtype='str', name='M') - ``M``, the measurement: ``n`` (number density), ``v`` (velocity), ``w`` (thermal speed), ``b`` (magnetic field). From a42c52a65776376467da0c626657a1b2f9b606d8 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 03:55:28 -0500 Subject: [PATCH 20/21] docs(api): qualify repeated API page titles by their package path Where two API pages share a short name (the base modules of core and plotting, the two tools modules, the two Ion classes), each is titled by its path below solarwindpy (core.base, plotting.base); unique names stay short. conf.py lists the repeated names in autosummary_context, from the public modules and the classes and functions each defines, and the templates read it; no event hook changes what autosummary generates. Co-Authored-By: Claude Opus 5.5 --- docs/source/_templates/autosummary/base.rst | 6 +++- docs/source/_templates/autosummary/class.rst | 6 +++- docs/source/_templates/autosummary/module.rst | 6 +++- docs/source/conf.py | 35 ++++++++++++++++++- 4 files changed, 49 insertions(+), 4 deletions(-) diff --git a/docs/source/_templates/autosummary/base.rst b/docs/source/_templates/autosummary/base.rst index e04fd17f1..2dc4ce8c7 100644 --- a/docs/source/_templates/autosummary/base.rst +++ b/docs/source/_templates/autosummary/base.rst @@ -1,4 +1,8 @@ -{{ objname | escape | underline}} +{% if fullname in repeated_titles -%} +{{ fullname.split(".", 1)[1] | escape | underline }} +{%- else -%} +{{ objname | escape | underline }} +{%- endif %} ``from {{ module }} import {{ objname }}`` diff --git a/docs/source/_templates/autosummary/class.rst b/docs/source/_templates/autosummary/class.rst index ce1f0235b..985ec9a64 100644 --- a/docs/source/_templates/autosummary/class.rst +++ b/docs/source/_templates/autosummary/class.rst @@ -1,4 +1,8 @@ -{{ objname | escape | underline}} +{% if fullname in repeated_titles -%} +{{ fullname.split(".", 1)[1] | escape | underline }} +{%- else -%} +{{ objname | escape | underline }} +{%- endif %} ``from {{ module }} import {{ objname }}`` diff --git a/docs/source/_templates/autosummary/module.rst b/docs/source/_templates/autosummary/module.rst index be6b4ed33..1995f9be3 100644 --- a/docs/source/_templates/autosummary/module.rst +++ b/docs/source/_templates/autosummary/module.rst @@ -1,4 +1,8 @@ -{{ name | escape | underline}} +{% if fullname in repeated_titles -%} +{{ fullname.split(".", 1)[1] | escape | underline }} +{%- else -%} +{{ name | escape | underline }} +{%- endif %} ``import {{ fullname }}`` diff --git a/docs/source/conf.py b/docs/source/conf.py index 793e3ed2b..222fd2bc2 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -7,6 +7,7 @@ import os import sys +from collections import Counter sys.path.insert(0, os.path.abspath("../../src")) import solarwindpy @@ -298,4 +299,36 @@ epub_title = project epub_author = author epub_publisher = author -epub_copyright = copyright \ No newline at end of file +epub_copyright = copyright + + +# -- API page titles --------------------------------------------------------- + +# The autosummary templates title each API page by its short name (``Plasma``, +# ``hist1d``). Where two pages would share a title, such as the ``base`` +# modules of ``core`` and ``plotting``, each of them is titled by its path +# below the package instead (``core.base``, ``plotting.base``), so a title +# alone names one object. The pages are the public modules and the public +# objects each defines; ``repeated_titles`` holds the full names of those whose +# short name another shares, and the templates read it. +def _repeated_api_titles(): + import importlib + import inspect + import pkgutil + + full_names = [] + for info in pkgutil.walk_packages(solarwindpy.__path__, "solarwindpy."): + if any(part.startswith("_") for part in info.name.split(".")): + continue + module = importlib.import_module(info.name) + full_names.append(info.name) + for name, obj in vars(module).items(): + public = not name.startswith("_") + documented = inspect.isclass(obj) or inspect.isfunction(obj) + if public and documented and obj.__module__ == info.name: + full_names.append(f"{info.name}.{name}") + counts = Counter(name.rsplit(".", 1)[-1] for name in full_names) + return sorted(name for name in full_names if counts[name.rsplit(".", 1)[-1]] > 1) + + +autosummary_context = {"repeated_titles": _repeated_api_titles()} From 793259ca56fb113f93371baab2f098e91f042a23 Mon Sep 17 00:00:00 2001 From: blalterman Date: Thu, 5 Nov 2026 04:01:31 -0500 Subject: [PATCH 21/21] docs(usage): show plot paths, filled and overlaid contours, fit labels The Hist1D example shows the plot's path and what it is for. The contour example fills its contours, and a new figure overlays black contour lines on the histogram with plot_hist_with_contours and one colorbar. The fit plot labels its axes with set_labels. Co-Authored-By: Claude Opus 5.5 --- docs/source/usage.rst | 53 ++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 50 insertions(+), 3 deletions(-) diff --git a/docs/source/usage.rst b/docs/source/usage.rst index 3007a8086..7d1eceb90 100644 --- a/docs/source/usage.rst +++ b/docs/source/usage.rst @@ -171,6 +171,18 @@ explains them. h1.set_labels(x=TeXlabel(("v", "", "p1"))) h1.make_plot() +Every plot also has a ``path``, built from its class, its labels and its axis +scales, to file the figure under when you save it: join it to your figure +directory and add an extension, as :doc:`tutorial/quickstart` does. + +>>> import pandas as pd +>>> from solarwindpy.plotting.hist1d import Hist1D +>>> from solarwindpy.plotting.labels.base import TeXlabel +>>> h1 = Hist1D(pd.Series([380.0, 650.0], name="v")) +>>> h1.set_labels(x=TeXlabel(("v", "", "p1"))) +>>> h1.path.as_posix() +'Hist1D/v_p1/count/linX-linY' + Two quantities ~~~~~~~~~~~~~~ @@ -206,7 +218,8 @@ edges of the occupied distribution 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 -``axnorm="t"``, explained in `Normalizations`_, scales the peak to 1: +``axnorm="t"``, explained in `Normalizations`_, scales the peak to 1, and +``use_contourf=True`` fills the contours: .. plot:: @@ -223,7 +236,36 @@ than 50 bins set ``window_length`` in ``edges_kwargs=dict(sg_kwargs=...)``. Here h2 = Hist2D(v, n, logy=True, nbins=50, axnorm="t") h2.set_labels(x=TeXlabel(("v", "", "p1")), y=TeXlabel(("n", "", "p1"))) - h2.plot_contours(gaussian_filter_std=2, nan_aware_filter=True, plot_edges=True) + h2.plot_contours( + use_contourf=True, gaussian_filter_std=2, nan_aware_filter=True, 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, +the histogram's. Black contour lines (``contour_kwargs=dict(colors="k")``) +stand out over the colored cells; the line style changes with the level: + +.. plot:: + + import numpy as np + import pandas as pd + 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") + + h2 = Hist2D(v, n, logy=True, nbins=50, axnorm="t") + h2.set_labels(x=TeXlabel(("v", "", "p1")), y=TeXlabel(("n", "", "p1"))) + h2.plot_hist_with_contours( + 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 histogram with its projections on the top and right margins. Each margin is a @@ -471,19 +513,24 @@ an annotation with the fit function, its parameters and their uncertainties, and the reduced chi-squared of each kind. The bottom panel shows the residuals, observed minus fitted, against ``x``; the default ``resid_pct=True`` shows them in percent of the fit instead, which is large wherever the fit nears zero. -The Gaussian is the seeded, noisy one whose results table +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: .. plot:: import numpy as np from solarwindpy.fitfunctions.gaussians import Gaussian + from solarwindpy.plotting.labels.base import TeXlabel + from solarwindpy.plotting.labels.special import Count 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.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)) Next Steps