diff --git a/.github/workflows/jupyterlite.yml b/.github/workflows/pages.yml similarity index 68% rename from .github/workflows/jupyterlite.yml rename to .github/workflows/pages.yml index 740e0d9..5446ee4 100644 --- a/.github/workflows/jupyterlite.yml +++ b/.github/workflows/pages.yml @@ -1,7 +1,8 @@ -name: jupyterlite +name: pages -# Builds a JupyterLite site with the notebooks and the package, so they run -# fully in the browser (Pyodide kernel), and deploys it to GitHub Pages. +# Builds the documentation (MkDocs, at the site root) and a JupyterLite site +# with the notebooks and the package under lite/, so the notebooks run fully +# in the browser (Pyodide kernel), and deploys both to GitHub Pages. on: push: branches: [main] @@ -19,9 +20,10 @@ jobs: - uses: actions/setup-python@v5 with: python-version: "3.12" - - run: pip install build jupyterlite-core jupyterlite-pyodide-kernel jupyter-server jupyterlab_widgets + - run: pip install build jupyterlite-core jupyterlite-pyodide-kernel jupyter-server jupyterlab_widgets ".[docs]" + - run: mkdocs build --strict --site-dir _site - run: python -m build --wheel - - run: jupyter lite build --contents notebooks --piplite-wheels dist/*.whl --output-dir _site + - run: jupyter lite build --contents notebooks --piplite-wheels dist/*.whl --output-dir _site/lite - uses: actions/upload-pages-artifact@v3 with: path: _site diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..658cf1a --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,45 @@ +name: release + +# Builds the sdist and wheel on every pull request (as a check) and uploads +# them to PyPI when a GitHub release is published. The upload uses PyPI's +# trusted publishing, so no token is stored in the repository. +on: + pull_request: + release: + types: [published] + workflow_dispatch: + +permissions: + contents: read + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.13" + - run: pip install build twine + - run: python -m build + - run: twine check --strict dist/* + - uses: actions/upload-artifact@v4 + with: + name: dist + path: dist/ + + publish: + if: github.event_name == 'release' + needs: build + runs-on: ubuntu-latest + environment: + name: pypi + url: https://pypi.org/project/so_schroedinger/ + permissions: + id-token: write + steps: + - uses: actions/download-artifact@v4 + with: + name: dist + path: dist/ + - uses: pypa/gh-action-pypi-publish@release/v1 diff --git a/.gitignore b/.gitignore index 345eb36..59bddf6 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,6 @@ __pycache__/ *.egg-info/ .pytest_cache/ .ipynb_checkpoints/ +dist/ +site/ +_site/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..8527ab6 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,34 @@ +# Changelog + +## 0.5.0 + +First release on PyPI. + +- Speed: FFTs through `scipy.fft` on all cores (pluggable, e.g. pyFFTW), and + merged potential half steps in `propagate()`; about 3× faster in 2d. +- `SplitOperator(order=4)` and `order=6`: higher-order splittings by + composing Strang steps (Yoshida's triple jump). +- `dtype=np.complex64` for grids: single precision, half the memory. +- Time-dependent potentials are propagated to second order (V(t) and + V(t+dt) in the two half steps). +- Energy `` on grids and in `Observables`; `ground_state()` and + `lowest_eigenstates()` from imaginary time evolution. +- `so.plotting`: one-line plots of wavefunctions, potentials, momentum + distributions and eigenstates. +- Live mode for the animations (`live=True`), which steps while drawing. +- New notebooks: Talbot carpet, Anderson localization; sliders in the + tunneling notebook; splitting orders in the harmonic oscillator notebook. +- Notebooks run on Binder, Colab and in the browser with JupyterLite. +- API documentation with MkDocs, a benchmark script, and a PyPI release + workflow. + +## 0.4.0 + +The analyzers take the grid instead of `(psi, V, t)`, no longer plot, and +return arrays. + +## 0.3.0 + +The former camelCase API was renamed to PEP 8 names, e.g. `psiNorm` → +`psi_norm`, `expectationX()` → `expectation_x()`, `nSteps` → `n_steps`, +`nFrames`/`stepsPerFrame` → `n_frames`/`steps_per_frame`. diff --git a/README.md b/README.md index c3f770a..2d9cf17 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,8 @@ # so_schroedinger [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/aeberspaecher/splitoperator/main?urlpath=lab/tree/notebooks) -[![JupyterLite](https://jupyterlite.rtfd.io/en/latest/_static/badge.svg)](https://aeberspaecher.github.io/splitoperator/lab/index.html) +[![JupyterLite](https://jupyterlite.rtfd.io/en/latest/_static/badge.svg)](https://aeberspaecher.github.io/splitoperator/lite/lab/index.html) +[![Docs](https://img.shields.io/badge/docs-API-blue)](https://aeberspaecher.github.io/splitoperator/) Split operator time propagation for the time-dependent Schrödinger equation, written in pure Python on top of NumPy's FFT. @@ -21,10 +22,12 @@ All quantities are in atomic units (ħ = m = 1). ## Installation ```bash -pip install . # or: pip install -e ".[test]" for development +pip install so_schroedinger ``` -Requires Python ≥ 3.10, NumPy, SciPy and Matplotlib. +or from a checkout, `pip install .` (`pip install -e ".[test]"` for +development). Requires Python ≥ 3.10, NumPy, SciPy and Matplotlib. The API +documentation is at https://aeberspaecher.github.io/splitoperator/. ## Example @@ -72,6 +75,10 @@ double precision. grid = so.Grid2d(((-20, 20), (-20, 20)), 1024, pot, psi0, dtype=np.complex64) ``` +`python benchmarks/benchmark.py` times steps for 1d and 2d grids in both +precisions and at orders 2 and 4 (`--quick` for the smaller grids only, +`--pyfftw` to use pyFFTW, `--help` for the rest). + ## Two dimensions `Grid2d` works like `Grid1d`; potentials and wavepackets are evaluated with @@ -175,7 +182,7 @@ starts in seconds and needs no server, but it is slower than native Python and the animation cells take a while. [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/aeberspaecher/splitoperator/main?urlpath=lab/tree/notebooks) -[![JupyterLite](https://jupyterlite.rtfd.io/en/latest/_static/badge.svg)](https://aeberspaecher.github.io/splitoperator/lab/index.html) +[![JupyterLite](https://jupyterlite.rtfd.io/en/latest/_static/badge.svg)](https://aeberspaecher.github.io/splitoperator/lite/lab/index.html) | Notebook | Content | | |---|---|---| @@ -214,6 +221,26 @@ The tests check the propagator against analytic results: norm conservation, spreading of a free Gaussian, a coherent state in a harmonic oscillator and the oscillator ground state energy from imaginary time evolution. +## Documentation + +The API documentation is built with MkDocs from the docstrings: + +```bash +pip install -e ".[docs]" +mkdocs serve +``` + +On every push to `main`, the `pages` workflow publishes it on GitHub Pages +together with the JupyterLite notebooks (under `lite/`). + +## Releases + +The changes are listed in [CHANGELOG.md](https://github.com/aeberspaecher/splitoperator/blob/main/CHANGELOG.md). +To release, bump the version in `pyproject.toml` and +`so_schroedinger/__init__.py`, add the changelog entry, and publish a GitHub +release with a tag `vX.Y.Z`; the `release` workflow then uploads the sdist +and wheel to PyPI with trusted publishing. + ## Code style The code follows PEP 8: `snake_case` for functions, methods, arguments and @@ -226,13 +253,6 @@ ruff check . ruff format . ``` -Version 0.4.0 reworked the analyzers: they take the grid instead of -`(psi, V, t)`, no longer plot, and return arrays instead. - -Version 0.3.0 renamed the former camelCase API, e.g. `psiNorm` → -`psi_norm`, `expectationX()` → `expectation_x()`, `nSteps` → `n_steps`, -`nFrames`/`stepsPerFrame` → `n_frames`/`steps_per_frame`. - ## License -BSD 2-Clause, see [LICENSE](LICENSE). +BSD 2-Clause, see [LICENSE](https://github.com/aeberspaecher/splitoperator/blob/main/LICENSE). diff --git a/benchmarks/benchmark.py b/benchmarks/benchmark.py new file mode 100644 index 0000000..d2014df --- /dev/null +++ b/benchmarks/benchmark.py @@ -0,0 +1,84 @@ +"""Time split operator steps for typical grid sizes, precisions and orders. + +Run as ``python benchmarks/benchmark.py``; ``--help`` lists the options. The +time per step is the best of several runs of ``--steps`` steps, so it shows +what the machine can do rather than the noise of other processes. +""" + +import argparse +import os +import platform +import time + +import numpy as np +import scipy.fft + +import so_schroedinger as so + + +def make_grid(samples, dtype): + """A harmonic oscillator with a moving Gaussian; ``samples`` is an int for + 1d and a tuple ``(n, n)`` for 2d.""" + + if np.ndim(samples) == 0: + return so.Grid1d((-40.0, 40.0), samples, so.HarmOscPot(1.0), so.Gaussian1d(0.0, 1.0, 1.0), dtype=dtype) + psi0 = so.Gaussian2d(3.0, 0.0, 1.0, 1.0, 0.0, 1.0) + return so.Grid2d(((-20.0, 20.0), (-20.0, 20.0)), samples, so.HarmOscPot2d(1.0), psi0, dtype=dtype) + + +def grid_sizes(quick): + return [2**11, (256, 256), (512, 512)] if quick else [2**11, 2**14, (512, 512), (1024, 1024)] + + +def time_step(samples, dtype, order, workers, steps, repeat): + """Best time per step in seconds.""" + + grid = make_grid(samples, dtype) + prop = so.SplitOperator(order=order, workers=workers) + prop.propagate(grid, 0.001, 2) # warm up the caches and FFT plans + best = np.inf + for _ in range(repeat): + t0 = time.perf_counter() + prop.propagate(grid, 0.001, steps) + best = min(best, (time.perf_counter() - t0) / steps) + return best + + +def format_time(seconds): + return f"{seconds * 1e3:8.3f} ms" if seconds >= 1e-3 else f"{seconds * 1e6:8.1f} µs" + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--steps", type=int, default=20, help="steps per timing run (default 20)") + parser.add_argument("--repeat", type=int, default=5, help="timing runs, the best counts (default 5)") + parser.add_argument("--workers", type=int, default=-1, help="FFT threads, -1 for all cores (default)") + parser.add_argument("--quick", action="store_true", help="smaller grids only") + parser.add_argument("--pyfftw", action="store_true", help="use pyFFTW as the scipy.fft backend") + args = parser.parse_args() + + backend = "scipy.fft" + if args.pyfftw: + import pyfftw.interfaces.cache + import pyfftw.interfaces.scipy_fft + + pyfftw.interfaces.cache.enable() + scipy.fft.set_global_backend(pyfftw.interfaces.scipy_fft) + backend = "pyFFTW" + + print(f"so_schroedinger {so.__version__}, NumPy {np.__version__}, SciPy {scipy.__version__}, {backend}") + print(f"{platform.processor() or platform.machine()}, {os.cpu_count()} cores, workers={args.workers}\n") + columns = [(np.complex128, 2), (np.complex64, 2), (np.complex128, 4)] + header = ["grid".ljust(12)] + [f"{np.dtype(d).name}, order {o}".rjust(22) for d, o in columns] + print("".join(header)) + for samples in grid_sizes(args.quick): + label = f"1d {samples}" if np.ndim(samples) == 0 else f"2d {samples[0]}x{samples[1]}" + row = [label.ljust(12)] + for dtype, order in columns: + t = time_step(samples, dtype, order, args.workers, args.steps, args.repeat) + row.append(format_time(t).rjust(22)) + print("".join(row), flush=True) + + +if __name__ == "__main__": + main() diff --git a/docs/api/analyzers.md b/docs/api/analyzers.md new file mode 100644 index 0000000..4744b09 --- /dev/null +++ b/docs/api/analyzers.md @@ -0,0 +1,3 @@ +# Analyzers + +::: so_schroedinger.analyzers diff --git a/docs/api/animation.md b/docs/api/animation.md new file mode 100644 index 0000000..67981f6 --- /dev/null +++ b/docs/api/animation.md @@ -0,0 +1,3 @@ +# Animation + +::: so_schroedinger.animation diff --git a/docs/api/eigenstates.md b/docs/api/eigenstates.md new file mode 100644 index 0000000..a7328f3 --- /dev/null +++ b/docs/api/eigenstates.md @@ -0,0 +1,3 @@ +# Eigenstates + +::: so_schroedinger.eigenstates diff --git a/docs/api/grid.md b/docs/api/grid.md new file mode 100644 index 0000000..5c1baa5 --- /dev/null +++ b/docs/api/grid.md @@ -0,0 +1,3 @@ +# Grids + +::: so_schroedinger.grid diff --git a/docs/api/plotting.md b/docs/api/plotting.md new file mode 100644 index 0000000..40b19c4 --- /dev/null +++ b/docs/api/plotting.md @@ -0,0 +1,3 @@ +# Plotting + +::: so_schroedinger.plotting diff --git a/docs/api/potentials.md b/docs/api/potentials.md new file mode 100644 index 0000000..aaf25c6 --- /dev/null +++ b/docs/api/potentials.md @@ -0,0 +1,3 @@ +# Potentials + +::: so_schroedinger.potentials diff --git a/docs/api/timeprop.md b/docs/api/timeprop.md new file mode 100644 index 0000000..e23c82e --- /dev/null +++ b/docs/api/timeprop.md @@ -0,0 +1,3 @@ +# Propagation + +::: so_schroedinger.timeprop diff --git a/docs/api/wavepackets.md b/docs/api/wavepackets.md new file mode 100644 index 0000000..d7bc6fc --- /dev/null +++ b/docs/api/wavepackets.md @@ -0,0 +1,3 @@ +# Wavepackets + +::: so_schroedinger.wavepackets diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000..612c7a5 --- /dev/null +++ b/docs/index.md @@ -0,0 +1 @@ +--8<-- "README.md" diff --git a/docs/javascripts/mathjax.js b/docs/javascripts/mathjax.js new file mode 100644 index 0000000..3764a76 --- /dev/null +++ b/docs/javascripts/mathjax.js @@ -0,0 +1,17 @@ +// render the $...$ math in docstrings (pymdownx.arithmatex, generic mode) +window.MathJax = { + tex: { + inlineMath: [["\\(", "\\)"]], + displayMath: [["\\[", "\\]"]], + processEscapes: true, + processEnvironments: true, + }, + options: { + ignoreHtmlClass: ".*|", + processHtmlClass: "arithmatex", + }, +}; + +document$.subscribe(() => { + MathJax.typesetPromise(); +}); diff --git a/mkdocs.yml b/mkdocs.yml new file mode 100644 index 0000000..4fae971 --- /dev/null +++ b/mkdocs.yml @@ -0,0 +1,61 @@ +site_name: so_schroedinger +site_description: Split operator time propagation for the time-dependent Schrödinger equation +repo_url: https://github.com/aeberspaecher/splitoperator +edit_uri: "" + +theme: + name: material + features: + - content.code.copy + palette: + - media: "(prefers-color-scheme: light)" + scheme: default + toggle: + icon: material/brightness-7 + name: Dark mode + - media: "(prefers-color-scheme: dark)" + scheme: slate + toggle: + icon: material/brightness-4 + name: Light mode + +nav: + - Home: index.md + - Notebooks in the browser: https://aeberspaecher.github.io/splitoperator/lite/lab/index.html + - API: + - Grids: api/grid.md + - Propagation: api/timeprop.md + - Eigenstates: api/eigenstates.md + - Potentials: api/potentials.md + - Wavepackets: api/wavepackets.md + - Analyzers: api/analyzers.md + - Plotting: api/plotting.md + - Animation: api/animation.md + +plugins: + - search + - mkdocstrings: + handlers: + python: + options: + docstring_style: numpy + members_order: source + show_source: false + show_root_heading: false + show_symbol_type_heading: true + heading_level: 2 + filters: ["!^_"] + merge_init_into_class: true + +markdown_extensions: + - admonition + - pymdownx.arithmatex: + generic: true + - pymdownx.highlight + - pymdownx.superfences + - pymdownx.snippets: + check_paths: true + +extra_javascript: + - javascripts/mathjax.js + - https://cdn.jsdelivr.net/npm/mathjax@3.2.2/es5/tex-mml-chtml.js diff --git a/pyproject.toml b/pyproject.toml index 9d9618e..688a5ee 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,18 +4,32 @@ build-backend = "setuptools.build_meta" [project] name = "so_schroedinger" -version = "0.4.0" +version = "0.5.0" description = "Split operator time propagation for the time-dependent Schroedinger equation" readme = "README.md" license = "BSD-2-Clause" license-files = ["LICENSE"] +keywords = ["quantum mechanics", "Schroedinger equation", "split operator", "wavepacket", "physics"] +classifiers = [ + "Development Status :: 4 - Beta", + "Intended Audience :: Science/Research", + "Intended Audience :: Education", + "Programming Language :: Python :: 3", + "Topic :: Scientific/Engineering :: Physics", +] authors = [{ name = "Alexander Eberspächer" }] requires-python = ">=3.10" dependencies = ["numpy>=1.23", "scipy>=1.10", "matplotlib>=3.6"] +[project.urls] +Documentation = "https://aeberspaecher.github.io/splitoperator/" +Source = "https://github.com/aeberspaecher/splitoperator" +Notebooks = "https://aeberspaecher.github.io/splitoperator/lite/lab/index.html" + [project.optional-dependencies] test = ["pytest", "nbformat", "nbclient", "ipykernel"] notebooks = ["jupyterlab", "ipykernel", "ipywidgets"] +docs = ["mkdocs-material", "mkdocstrings[python]"] [tool.setuptools] packages = ["so_schroedinger"] diff --git a/so_schroedinger/__init__.py b/so_schroedinger/__init__.py index e733cd5..4995386 100644 --- a/so_schroedinger/__init__.py +++ b/so_schroedinger/__init__.py @@ -12,4 +12,4 @@ from .timeprop import * from .wavepackets import * -__version__ = "0.4.0" +__version__ = "0.5.0"