Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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]
Expand All @@ -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
Expand Down
45 changes: 45 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@ __pycache__/
*.egg-info/
.pytest_cache/
.ipynb_checkpoints/
dist/
site/
_site/
34 changes: 34 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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 `<H>` 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`.
44 changes: 32 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 | |
|---|---|---|
Expand Down Expand Up @@ -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
Expand All @@ -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).
84 changes: 84 additions & 0 deletions benchmarks/benchmark.py
Original file line number Diff line number Diff line change
@@ -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()
3 changes: 3 additions & 0 deletions docs/api/analyzers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Analyzers

::: so_schroedinger.analyzers
3 changes: 3 additions & 0 deletions docs/api/animation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Animation

::: so_schroedinger.animation
3 changes: 3 additions & 0 deletions docs/api/eigenstates.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Eigenstates

::: so_schroedinger.eigenstates
3 changes: 3 additions & 0 deletions docs/api/grid.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Grids

::: so_schroedinger.grid
3 changes: 3 additions & 0 deletions docs/api/plotting.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Plotting

::: so_schroedinger.plotting
3 changes: 3 additions & 0 deletions docs/api/potentials.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Potentials

::: so_schroedinger.potentials
3 changes: 3 additions & 0 deletions docs/api/timeprop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Propagation

::: so_schroedinger.timeprop
3 changes: 3 additions & 0 deletions docs/api/wavepackets.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Wavepackets

::: so_schroedinger.wavepackets
1 change: 1 addition & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
--8<-- "README.md"
17 changes: 17 additions & 0 deletions docs/javascripts/mathjax.js
Original file line number Diff line number Diff line change
@@ -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();
});
61 changes: 61 additions & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading