Skip to main content

xinvert

DOI GitHub Documentation Status PyPI version Workflow pytest status Codacy Badge

animate plot

1. Introduction

Researches on meteorology and oceanography usually encounter inversion problems that need to be solved numerically. One of the classical inversion problem is to solve Poisson equation for a streamfunction $\psi$ given the vertical component of vorticity $\zeta$ and proper boundary conditions.

$$\nabla^2\psi=\zeta$$

Nowadays xarray becomes a popular data structure commonly used in Big Data Geoscience. Since the whole 4D data, as well as the coordinate information, are all combined into xarray, solving the inversion problem become quite straightforward and the only input would be just one xarray.DataArray of vorticity. Inversion on the spherical earth, like some meteorological problems, could utilize the spherical harmonics like windspharm, which would be more efficient using FFT than SOR used here. However, in the case of ocean, xinvert supports irregular land/sea masks directly with SOR.

More importantly, this could be generalized into a numerical solver for elliptic equations using SOR method, with spatially-varying coefficients. Various popular inversion problems in geofluid dynamics will be illustrated as examples.

One problem with SOR is that the speed of iteration using explicit loops in Python will be e-x-t-r-e-m-e-l-y ... s-l-o-w! A very suitable solution here is to use numba. In addition, through using xarray's dask backend for parallel computing, the speed of the inversion could be further improved using multiple CPU cores. Now, we could also make use of CUDA GPU for further acceleration, with a Red-Black SOR kernel achieving up to ~26× speedup over the CPU for 1,000 fixed sweeps in the archived RTX 3090 benchmark (see the benchmark docs). See this notebook for more details of CPU/GPU parallel computing, and this docs for benchmark of the inversion speed.

Classical problems include Gill-Matsuno model, Stommel-Munk model, QG omega model, PV inversion model, Swayer-Eliassen balance model... A complete list of the classical inversion problems can be found at this notebook.

Why xinvert?

  • Thinking and coding in equations: User APIs are very close to the equations: unknowns are on the LHS of =, whereas the known forcings are on its RHS;
  • Generalize steady-state problems: Many steady-state problems in geophysical fluid dynamics can be formulated using the supported elliptic equations;
  • Very short parameter list: Passing a single xarray forcing is enough for the inversion. Coordinates information is already encapsulated.
  • Flexible model parameters: Model parameters can be either a constant, or varying with a specific dimension (like Coriolis $f$), or fully varying with space and time, due to the use of xarray's broadcasting capability;
  • Parallel inverting: The use of xarray, and thus dask allow multi-core CPU parallel inverting, as well as GPU inverting. One only needs to change the setting iParams['architect']='cpu'/'gpu'/'cpu-mc', and the internal implementation is almost transparent to the user;
  • Pure Python code for C-code speed: The use of numba allow pure python code in this package but native speed;

2. How to install

Requirements xinvert supports Python 3.9 and newer and requires xarray, dask, numpy, numba, SciPy, netCDF4, Matplotlib, imageio-ffmpeg, and cloudpickle. The GPU extra installs Numba CUDA, CuPy and CUDA 12 runtime dependencies for both SOR and Li2006; an NVIDIA GPU with a compatible driver is required.

Install via pip

pip install xinvert

Install GPU support

pip install "xinvert[gpu]"

Install via conda

conda install -c conda-forge xinvert

Install from github

git clone https://github.com/miniufo/xinvert.git
cd xinvert
python -m pip install .

3. Examples:

The classic Poisson equation for streamfunction can be inverted by:

from xinvert import invert_Poisson

iParams = {
    'BCs'      : ['fixed', 'periodic'], # fixed north/south,  periodic east/west BCs
    'mxLoop'   : 1000,                  # maximum loop count
    'tolerance': 1e-6,                  # define convergence if error is smaller than this
    'architect': 'GPU',                 # use GPU backend
}

psi = invert_Poisson(vor, dims=['lat','lon'], iParams=iParams)

For vector fields, xinvert.helmholtz provides SOR and Li2006 methods through one interface:

from xinvert.helmholtz import decompose

components = decompose(u, v, dims=['lat', 'lon'], method='li2006')

See Helmholtz decomposition for the method comparison and parameters.

This is a list of the problems that can be solved by xinvert:

Gallery Gallery

invert Poisson equation for
horizontal streamfunction

invert Poisson equation for
overturning streamfunction

invert geostrophic equation for
balanced mass

invert Eliassen model for
overturning streamfunction

invert PV balance equation for
steady reference state

invert Gill-Matsuno model for
wind and mass fields

invert Stommel-Munk model for
wind-driven ocean circulation

invert Fofonoff model for
inviscid/adiabatic steady state

invert Bretherton model for
steady flow over topography

invert Omega equation for
QG vertical velocity

invert geostrophic-adjustment problem
... add more examples ...

4 Record iterations and create animations

The animation at the top was made using record_iteration. Pass one spatial slice; singleton dimensions are removed and spatial dimensions are inferred. Either an inversion function or its name (such as 'Poisson') is accepted:

from xinvert import record_iteration, invert_Poisson

frames = record_iteration(
    invert_Poisson, vor,  # vor is one 2-D spatial slice
    iParams={'BCs': ['fixed', 'periodic'], 'architect': 'cpu'},
    iter_per_frame=1, max_frames=40,
)
# frames is a DataArray with an additional iter dimension.

For file output, add output='iteration.nc' to write frames without keeping all of them in memory. Use create_animation to render the NetCDF frames as GIF or MP4. See Record iteration and create animation for plotting examples and optional convergence diagnostics.

5 Diagnose the error

xinvert uses a normalized, diagonally preconditioned residual for stopping. Its history can optionally be returned for analysis:

iParams = {
    'tolerance': 1e-8,
    'diag_interval': 20,  # diagnose every 20 SOR iterations
}
psi, diags = invert_Poisson(vor, dims=['lat', 'lon'], iParams=iParams)

diags.error.plot(x='iteration', yscale='log')

Through plotting the error, one can observe the convergence rate at regular interation interval. The default diag_interval=0 returns only the solution. See diagnostic analysis documentation for more details.

6 Cite

If you use the package in research, teaching, or other activities, we would be grateful if you mention xinvert and cite our paper in JOSS:

@article{Qian2023,
    doi = {10.21105/joss.05510},
    url = {https://doi.org/10.21105/joss.05510},
    year = {2023},
    publisher = {Journal of Open Source Software},
    volume = {8},
    number = {89},
    pages = {5510},
    author = {Yu-Kun Qian},
    title = {xinvert: A Python package for inversion problems in geophysical fluid dynamics}, journal = {Journal of Open Source Software}
}

Metadata

Release files for xinvert 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for xinvert 0.4.0
File Size Uploaded Provenance Actions
xinvert-0.4.0.tar.gz 237.7 kB Without provenance Details for xinvert-0.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for xinvert 0.4.0
File Interpreter ABI Platform Actions
xinvert-0.4.0-py3-none-any.whl Python 3 none any Details for xinvert-0.4.0-py3-none-any.whl

Total release size: 393.2 kB

Release files / xinvert-0.4.0.tar.gz

Download URL xinvert-0.4.0.tar.gz
Size 237.7 kB
Tags Source
SHA-256 checksum
How to use checksums
d07798b24546986d03879a186f54ce33ebdec8b64f481024cbbf4693b98416b6
BLAKE2b-256 checksum
How to use checksums
1d6eadeca52cbfe21602419670bad9bbd41614de922068fc905cdfaff792967f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.25

Release files / xinvert-0.4.0-py3-none-any.whl

Download URL xinvert-0.4.0-py3-none-any.whl
Size 155.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e6abd3dd795a0c460b8367ffacd99e91669e1b9005d13e87adf9477a81b0face
BLAKE2b-256 checksum
How to use checksums
e4c89e054c235cb245e42f9f350010e941311bb583c74f566a49fa303ede7730
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.25

Security for xinvert 0.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page