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/.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/.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 fe46585b2..20688635f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,11 +7,29 @@ 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. +- 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 - `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/CONTRIBUTING.md b/CONTRIBUTING.md index 3ca2ba38d..704e88462 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 @@ -129,50 +128,31 @@ 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 -### 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..6c844f99c 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 ============ @@ -93,7 +94,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 +110,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 Python 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/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)) 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/docs/source/_templates/autosummary/base.rst b/docs/source/_templates/autosummary/base.rst new file mode 100644 index 000000000..2dc4ce8c7 --- /dev/null +++ b/docs/source/_templates/autosummary/base.rst @@ -0,0 +1,11 @@ +{% if fullname in repeated_titles -%} +{{ fullname.split(".", 1)[1] | escape | underline }} +{%- else -%} +{{ objname | escape | underline }} +{%- endif %} + +``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..985ec9a64 100644 --- a/docs/source/_templates/autosummary/class.rst +++ b/docs/source/_templates/autosummary/class.rst @@ -1,4 +1,10 @@ -{{ fullname | escape | underline}} +{% if fullname in repeated_titles -%} +{{ fullname.split(".", 1)[1] | escape | underline }} +{%- else -%} +{{ objname | escape | underline }} +{%- endif %} + +``from {{ module }} import {{ objname }}`` .. currentmodule:: {{ module }} diff --git a/docs/source/_templates/autosummary/module.rst b/docs/source/_templates/autosummary/module.rst index ffc784bb7..1995f9be3 100644 --- a/docs/source/_templates/autosummary/module.rst +++ b/docs/source/_templates/autosummary/module.rst @@ -1,4 +1,10 @@ -{{ fullname | escape | underline}} +{% if fullname in repeated_titles -%} +{{ fullname.split(".", 1)[1] | escape | underline }} +{%- else -%} +{{ name | escape | underline }} +{%- endif %} + +``import {{ fullname }}`` .. automodule:: {{ fullname }} :no-members: @@ -65,7 +71,7 @@ :recursive: {% for item in modules %} - {{ item }} + ~{{ item }} {%- endfor %} {% endif %} 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/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 diff --git a/docs/source/conf.py b/docs/source/conf.py index f34fc9de5..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 @@ -25,7 +26,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 @@ -41,10 +42,42 @@ "sphinx.ext.mathjax", "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 +# 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'] @@ -232,7 +265,7 @@ # -- Options for other output formats ---------------------------------------- -# PDF output configuration (enabled for RTD) +# PDF output configuration latex_engine = 'pdflatex' latex_elements = { 'papersize': 'letterpaper', @@ -245,7 +278,7 @@ ''', } -# EPUB output configuration (enabled for RTD) +# EPUB output configuration epub_show_urls = 'footnote' epub_use_index = True @@ -266,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()} 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..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:: @@ -33,12 +33,6 @@ scientific accuracy. api_reference -.. toctree:: - :maxdepth: 1 - :caption: Development - - documentation_review - .. include:: ../../LICENSE .. include:: ../../CITATION.rst diff --git a/docs/source/installation.rst b/docs/source/installation.rst index df9a40a18..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 @@ -39,19 +41,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 +61,7 @@ package into the environment afterwards: conda env create -f solarwindpy.yml conda activate solarwindpy - pip install -e . + pip install -e ".[dev]" Verification ------------ diff --git a/docs/source/missing_data.rst b/docs/source/missing_data.rst index edcc086fd..21ad7a063 100644 --- a/docs/source/missing_data.rst +++ b/docs/source/missing_data.rst @@ -43,11 +43,25 @@ 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 +Worked example -------------- For temperature (:py:meth:`~solarwindpy.core.plasma.Plasma.T`), @@ -64,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. 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..a16f9888d 100644 --- a/docs/source/tutorial/quickstart.rst +++ b/docs/source/tutorial/quickstart.rst @@ -1,19 +1,304 @@ 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. 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``), 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: + +>>> list(plasma.data.columns.names) +['M', 'C', 'S'] +>>> plasma.data.shape +(3, 31) +>>> 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). +- ``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 +------------------ + +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 +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) +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. A quantity with +components is a DataFrame whose columns are the components, ``C``: + +>>> 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) +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").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 +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 +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: + +>>> 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 the histogram: + +>>> 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`. +Here it fits points scattered about :math:`y = 2x + 1` by noise from a seeded +random number generator: + +>>> import numpy as np +>>> 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), 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``, 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 +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 +>>> 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 ->>> import solarwindpy as sw ->>> sw.__version__ != "unknown" # "unknown" means solarwindpy is not installed -True +Next Steps +---------- +- :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` + (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 ca530176d..7d1eceb90 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: @@ -18,7 +20,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. @@ -27,13 +30,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"], ... ) @@ -66,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 -------------- @@ -103,9 +124,372 @@ 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() + +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 +~~~~~~~~~~~~~~ + +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, and +``use_contourf=True`` fills the contours: + +.. 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( + 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 +: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") +>>> Hist1D(v, nbins=[250, 350, 450, 550]).intervals["x"] +IntervalIndex([(250, 350], (350, 450], (450, 550]], dtype='interval[int64, right]') + +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: @@ -123,11 +507,34 @@ 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 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 ---------- -- 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. diff --git a/pyproject.toml b/pyproject.toml index 12b020eda..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", @@ -170,6 +172,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"] 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 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")