Metadata-Version: 2.4
Name: Divergence_Free_Interpolant
Version: 0.2.0
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Rust
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: MacOS
Classifier: Operating System :: POSIX :: Linux
Classifier: Topic :: Scientific/Engineering :: Mathematics
Classifier: Topic :: Scientific/Engineering :: Physics
Requires-Dist: numpy>=1.23
Requires-Dist: scipy>=1.12
Requires-Dist: sympy>=1.12.1 ; extra == 'symbolic'
Provides-Extra: symbolic
License-File: LICENSE
Summary: Divergence-free and curl-free interpolation of scattered vector data with matrix-valued RBFs
Keywords: Interpolation,Vector-Field,Radial-Basis-Functions,Divergence-Free,Curl-Free
Author-email: Peteris Zvejnieks <peterf610@gmail.com>
License-Expression: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Homepage, https://github.com/Peteris-Zvejnieks/DivergenceFreeInterpolation
Project-URL: Repository, https://github.com/Peteris-Zvejnieks/DivergenceFreeInterpolation


# Divergence Free Interpolation

Interpolation of scattered vector data with fields that are **exactly divergence-free** or
**exactly curl-free**, in 2D, 3D and higher dimensions. It uses the matrix-valued radial basis
functions of Fuselier [[1]](#1), built from Wendland's compactly supported functions [[2]](#2),
so the linear systems are sparse. Multilevel variants [[3]](#3) handle large and multi-scale
data sets accurately.

> **About the name:** the package started out divergence-free only. The curl-free interpolant
> comes from the same paper and shares all of the machinery, so it lives here too, despite the
> name.

| Divergence-free (`DivergenceFreeInterpolant`) | Curl-free (`CurlFreeInterpolant`) |
|---|---|
| Incompressible flow, magnetic fields: anything with zero divergence | Gradients, electrostatic fields, slopes: anything with zero curl |
| 2D: `stream_function()`, whose contour lines are the streamlines | `potential()`: the scalar potential whose gradient is the field |

### Divergence-free

A 2D flow reconstructed from 200 scattered velocity measurements, including its stream
function, and a 3D flow of swirling vortices:

![Divergence-free 2D](https://raw.githubusercontent.com/Peteris-Zvejnieks/DivergenceFreeInterpolation/main/graphics/2D_divergence_free.png)

![Divergence-free 3D](https://raw.githubusercontent.com/Peteris-Zvejnieks/DivergenceFreeInterpolation/main/graphics/3D_divergence_free.png)

### Curl-free

A landscape reconstructed from 200 scattered slope measurements (the height map is the recovered
potential), and an electric field with its equipotential surfaces recovered from field
measurements:

![Curl-free 2D](https://raw.githubusercontent.com/Peteris-Zvejnieks/DivergenceFreeInterpolation/main/graphics/2D_curl_free.png)

![Curl-free 3D](https://raw.githubusercontent.com/Peteris-Zvejnieks/DivergenceFreeInterpolation/main/graphics/3D_curl_free.png)

### Multilevel

A multi-scale flow reconstructed from 20 000 scattered velocity measurements, refined level by
level from coarse to fine (flow speed shown):

![Multilevel 2D](https://raw.githubusercontent.com/Peteris-Zvejnieks/DivergenceFreeInterpolation/main/graphics/2D_multilevel.png)

### Boundary conditions

Flow past a cylinder from scattered measurements, none close to the wall. With a no-penetration
condition on the cylinder, the streamlines go around it instead of through it. As a boundary
condition (`NormalComponent`), the wall is imposed in the mean over short segments; as a wall
built into the kernel (`walls=`), exactly, everywhere along it:

![Boundary conditions 2D](https://raw.githubusercontent.com/Peteris-Zvejnieks/DivergenceFreeInterpolation/main/graphics/2D_boundary_conditions.png)

## Installation

```bash
uv add Divergence-Free-Interpolant
# or
pip install Divergence-Free-Interpolant
```

The compute-heavy parts are written in Rust. Installing from source (a git checkout, or a
platform without a pre-built wheel) therefore needs a Rust toolchain; [rustup](https://rustup.rs)
is the easiest way to get one.

The kernels for the usual parameters ship with the package, so sympy is optional. Install the
`symbolic` extra for kernel parameters beyond those (see `k` and `nu` below), or to define
boundaries with sympy expressions:

```bash
pip install "Divergence-Free-Interpolant[symbolic]"
```

## Quick start

```python
import numpy as np
import divergence_free_interpolant as dfi

rng = np.random.default_rng(0)

# Sample positions and vectors, both of shape (N, dim): here a rotation, which is divergence-free
points = rng.random((200, 2))
values = np.column_stack([-points[:, 1], points[:, 0]])

interp = dfi.DivergenceFreeInterpolant(support_radius=0.3).fit(points, values)

# Evaluate at points of shape (..., dim) to get vectors of shape (..., dim)
interp(np.array([0.5, 0.5]))  # shape (2,)
interp(rng.random((1000, 2)))  # shape (1000, 2)
grid = np.stack(np.mgrid[0:1:50j, 0:1:50j], axis=-1)
interp(grid)  # shape (50, 50, 2)

# 2D only: the stream function, whose contour lines are the streamlines
interp.stream_function(grid)  # shape (50, 50)
```

The curl-free interpolant works the same way:

```python
# The gradient of |x|^2, which is curl-free
gradients = 2 * points

interp = dfi.CurlFreeInterpolant(support_radius=0.3).fit(points, gradients)
interp(points)  # the interpolated gradient field
interp.potential(points)  # its potential, up to a constant
```

For large or multi-scale data sets, the multilevel interpolants choose their support radii
from the data:

```python
interp = dfi.MultilevelDivergenceFreeInterpolant().fit(points, values)
interp(grid)

# Number of points and support radius per level, coarse to fine
[(level.n_points, level.support_radius) for level in interp.levels]
```

## API

### `DivergenceFreeInterpolant(support_radius, *, k=3, nu=None, solver='auto', tol=1e-10, walls=())`
### `CurlFreeInterpolant(support_radius, *, k=3, nu=None, solver='auto', tol=1e-10)`

- **`support_radius`** (required): radius of the compactly supported kernel. Each sample only
  influences the field within this distance. Larger values give smoother and usually more
  accurate fields, but denser, worse-conditioned systems. Start at a few times the typical
  spacing between samples. Far from all samples, the field and its potentials are exactly zero.
- **`k`**: smoothness of the Wendland function ψ<sub>ν,k</sub>, which is C<sup>2k</sup>. Must be
  ≥ 1. The default of 3 rarely needs changing.
- **`nu`**: Wendland parameter. It defaults to the smallest value that keeps the kernel positive
  definite, `dim // 2 + k + 1`. Smaller values raise a `ValueError` when you fit.
- **Shipped kernels:** k = 1–4, each with ν = k + 2 to k + 5. That covers the default ν in up to
  9 dimensions. Other combinations are derived with sympy, which needs the `symbolic` extra.
- **`solver`**:
  - `'direct'`: sparse factorisation.
  - `'cg'`: conjugate gradients, with relative tolerance `tol` (between 0 and 1).
  - `'lstsq'`: dense least squares. For small problems only; it tolerates duplicate points.
  - `'auto'`: uses `'direct'` in 2D (up to 250k unknowns) and for 3D systems up to 15k
    unknowns (5000 points), `'cg'` otherwise. If CG fails, for example on nearly coincident
    points, systems up to 50k unknowns are retried with `'direct'`.
- **`walls`** (divergence-free only): walls the field satisfies exactly; see [Walls](#walls).

### Methods

- **`fit(points, values)`**: `points` and `values` are arrays of shape `(N, dim)` with
  `dim >= 2`. The dimension is inferred from the data. Returns the interpolant, so calls can be
  chained. Duplicate points raise a `ValueError`, since they make the system singular. A failed
  fit leaves the previous fit untouched.
- **`interp(points)`**: evaluates at `points` of shape `(..., dim)` and returns vectors of shape
  `(..., dim)`.
- **`DivergenceFreeInterpolant.stream_function(points)`** (2D only): the stream function ψ, with
  the field equal to `(∂ψ/∂y, -∂ψ/∂x)`. Returns shape `(...)`.
- **`CurlFreeInterpolant.potential(points)`**: the potential P, with the field equal to `∇P`.
  Returns shape `(...)`.

Both scalar potentials are determined up to an additive constant. The ones returned here vanish
farther than `support_radius` from all samples and boundary conditions.

### Multilevel interpolation

### `MultilevelDivergenceFreeInterpolant(*, support_factor=6.0, refinement=0.5, k=3, nu=None, solver='auto', tol=1e-10, walls=())`
### `MultilevelCurlFreeInterpolant(...)` (same parameters, without `walls`)

A single support radius has to compromise. Small supports are cheap, but they cannot bridge the
gaps between samples, so accuracy stays poor, and larger data sets with proportionally smaller
supports don't help. Large supports are accurate, but the systems become dense and
ill-conditioned. The multilevel interpolants of Farrell, Gillow & Wendland [[3]](#3) avoid this:

- The data is split into nested levels, from a few dozen well-spread points up to all of them,
  by greedy farthest-point sampling. Each level is quasi-uniform: its points are at least its
  spacing apart and cover all the data within that spacing.
- Each level interpolates what the coarser levels left over, with a support radius of
  `support_factor` × its spacing, and the spacing halves (`refinement`) from level to level. The
  finest level uses all the points, so the data is still interpolated exactly, and the result is
  still exactly divergence-free or curl-free.
- Every level's system stays sparse, and the quasi-uniform levels are well-conditioned
  (conjugate gradients converges in a few hundred iterations at any size).

They have the same `fit`, call, `stream_function`/`potential` methods as the single-level
interpolants. Two additions:

- `levels`: a per-level summary (number of points, spacing, support radius, solver and CG
  iterations).
- `levels=j`, an optional argument when evaluating, which sums only the j coarsest levels, to
  inspect the refinement.

`support_factor` controls the accuracy. Around 6 the levels reliably reduce the error. Below 5
the refinement can stall. Larger values are more accurate (8 is a good choice in 2D), but the
number of neighbours per point grows like `support_factor`<sup>dim</sup>.

### Boundary conditions

Besides the data, `fit(points, values, conditions=[...])` takes conditions on curves and
surfaces. All interpolants accept them, single-level and multilevel:

```python
import numpy as np
import divergence_free_interpolant as dfi

# A parametric boundary: a callable of the parameter, or sympy expressions
wall = dfi.Curve(
    lambda t: np.stack([0.3 * np.cos(t), 0.3 * np.sin(t)], axis=-1),
    interval=(0, 2 * np.pi),
)
rng = np.random.default_rng(0)
points = rng.uniform(-1, 1, size=(300, 2))
points = points[np.linalg.norm(points, axis=1) > 0.35]
values = np.tile([1.0, 0.0], (len(points), 1))

interp = dfi.DivergenceFreeInterpolant(1.0).fit(
    points, values, conditions=[dfi.NormalComponent(wall)]
)
```

- **Geometry:**
  - `Curve(function, interval)`: `function(t)` maps parameters of shape `(n,)` to points
    `(n, dim)`.
  - `Surface(function, s_interval, t_interval)`: `function(s, t)` maps to points `(..., 3)`.

  Either can be given as sympy expressions instead of a callable, which gives exact
  derivatives (this needs the `symbolic` extra); callables get numerical ones. A curve's normal
  points to the right of its direction of travel, i.e. outwards for a counter-clockwise closed
  curve. A surface's normal is `∂σ/∂s × ∂σ/∂t`.
- **Conditions:**
  - `NormalComponent(boundary, value=0)`: prescribes n·u. For flows, 0 is a no-penetration
    (slip) wall, and a non-zero value is an inflow or outflow. For curl-free fields it
    prescribes the normal derivative of the potential. It needs a curve in 2D or a surface in
    3D.
  - `VectorValue(boundary, value=0)`: prescribes the whole vector u. For flows, 0 is a no-slip
    wall, and a non-zero value is a moving wall. It works for curves in any dimension and for
    surfaces.

  `value` is a constant, or a function of the boundary points.
- **How it is imposed:** the boundary is cut into segments (patches for surfaces) about one
  point spacing long, and each condition holds for the mean over each segment. The default
  resolves every boundary with at least 32 segments or about 128 patches; set
  `segment_length` to change that. Between segment centres the condition holds approximately,
  but closely in practice: in the cylinder example the largest normal velocity on the wall
  drops from 0.34 to 10⁻⁵. Multilevel interpolants impose the conditions on every level, with
  segments matched to that level's spacing.
- **Exactness:** the field stays exactly divergence-free or curl-free; the boundary condition
  is what is approximated.
- **Closed boundaries:** a divergence-free field has zero net flux through any closed curve or
  surface (divergence theorem). So for divergence-free interpolants, the values prescribed on a
  closed boundary must have zero net flux, otherwise `fit` raises a `ValueError`. The flux
  through one segment then follows from the others, so that constraint is dropped to keep the
  system well-conditioned. Closed boundaries are detected automatically (coinciding ends of a
  curve, coinciding or collapsing edges of a surface), or set with `closed=`. A closed wall must
  be a single `Curve` or `Surface`: one split into several open pieces is not recognised as
  closed, so neither the check nor the dropped constraint applies to it.

### Walls

For walls of simple shape, divergence-free interpolants can satisfy no penetration (u·n = 0) or
no slip (u = 0) **exactly, at every point of the wall**, instead of in the mean over segments.
The wall is built into the kernel rather than added to the system, so it costs no unknowns:

```python
from divergence_free_interpolant import walls

interp = dfi.DivergenceFreeInterpolant(
    1.0, walls=[walls.Circle((0, 0), 0.3, band=0.5)]
).fit(points, values)
```

- **Shapes** (module `divergence_free_interpolant.walls`):
  - `Circle(center, radius)` (2D) and `Sphere(center, radius)` (3D): an obstacle, or with
    `inside=True` a container.
  - `Line(point, normal)` (2D) and `Plane(point, normal)` (3D): the flow is on the side the
    normal points to.
  - `Cylinder(point, axis, radius)` (3D): an infinite cylinder, or with `inside=True` a pipe.

  Several walls can be combined, e.g. a channel with an obstacle. Every wall takes `band` and
  `condition`.
- **`condition`**: `'no_penetration'` (the default) makes the field tangent to the wall;
  `'no_slip'` makes it vanish there.
- **`band`** (required): the width of the layer along the wall in which the kernel changes,
  i.e. how far the wall's influence reaches into the flow. Away from all walls the interpolant
  is the usual one. A band of a few point spacings up to the obstacle's size works well (for a
  container it must be smaller than the radius); there is no automatic choice yet.
- **How it works:** the field is the curl of a vector potential, and the potential is
  multiplied by a smooth function g that vanishes on the walls. On a wall that leaves only
  components tangent to it, or none at all with g² (no slip). The field is still exactly
  divergence-free; see [docs/tier2_boundary_conditions.md](docs/tier2_boundary_conditions.md).
- **Data on a wall** (closer than 0.001 × band) keeps only the components the wall leaves free:
  its tangential velocity for no penetration, nothing for no slip. Data on the far side of a
  wall (inside an obstacle) raises a `ValueError`. The interpolant has no meaning there.
- **Stream function:** in 2D, the wall is a streamline: the stream function is zero along it.
- Walls work with the multilevel interpolants (shared by all levels) and alongside
  `conditions` on other boundaries.

In the cylinder example, the exact wall gives the smallest error (RMS 0.081 outside the
cylinder, against 0.097 with `NormalComponent` and 0.14 without a wall). Evaluation costs about
twice as much as without walls; fitting is barely slower. General curved boundaries (`Curve`,
`Surface`) still need `conditions`, and curl-free fields have no walls yet.

### Performance

The kernels have compact support, so fitting builds a sparse system via kd-tree neighbour search,
and evaluation only visits nearby samples. Assembly, evaluation, the farthest-point thinning
and conjugate gradients run in parallel in a Rust core. Conjugate gradients uses a block-Jacobi
preconditioner over clusters of unusually close points, which random data always has. Direct
solves of large 3D systems use a sparse Cholesky factorisation in the Rust core (faer), and
scipy's SuperLU otherwise: in 2D its fill-reducing ordering is the better one.

Timings on one desktop machine (12 cores), random points in the unit square/cube, `'auto'`
solver. A single level with about 30 (2D) or 50 (3D) neighbours per point
(`benchmarks/bench_scaling.py`):

| single level | 1 000 points | 10 000 points | 100 000 points | evaluation |
|---|---|---|---|---|
| 2D fit | 0.05 s | 0.25 s | 7.5 s | 0.1–0.5 µs / point |
| 3D fit | 0.07 s | 0.12 s | 1.4 s | 0.2–0.8 µs / point |

The 2D fits are dominated by the direct sparse factorisation; in 3D, `'auto'` uses conjugate
gradients from 15k unknowns.

Such small supports are fast but inaccurate. The multilevel interpolant (default settings) is
far more accurate for a few times the cost. Here is the RMS error against a smooth analytic
field (`benchmarks/bench_multilevel.py`):

| | 10 000 points | 100 000 points |
|---|---|---|
| 2D single level | 0.26 s, error 1.1 | 7.1 s, error 1.1 |
| 2D multilevel | 0.34 s, error 7.5 · 10⁻⁴ | 6.3 s, error 6.1 · 10⁻⁵ |
| 3D single level | 0.11 s, error 0.70 | 1.3 s, error 0.70 |
| 3D multilevel | 1.0 s, error 1.9 · 10⁻³ | 13 s, error 1.8 · 10⁻⁴ |

## Examples

Install the example dependencies with `uv sync --group examples`, then run e.g.
`uv run python examples/curl_free_2D.py`.

- [`examples/divergence_free_2D.py`](examples/divergence_free_2D.py): reconstructs a 2D
  incompressible flow of vortices from scattered velocity measurements, including its stream
  function, compared with the true one.
- [`examples/divergence_free_3D.py`](examples/divergence_free_3D.py): a 3D incompressible flow
  of swirling vortex blobs, shown as streamlines in pyvista.
- [`examples/curl_free_2D.py`](examples/curl_free_2D.py): reconstructs a landscape from
  scattered slope measurements, compared with the true height map.
- [`examples/curl_free_3D.py`](examples/curl_free_3D.py): electrostatics. Interpolates an
  electric field from scattered measurements and recovers the electric potential, shown as
  field lines and equipotential surfaces.
- [`examples/multilevel_2D.py`](examples/multilevel_2D.py): a multi-scale flow from 20 000
  scattered measurements. Shows the reconstruction after the first, the first three and all
  levels, compared with a single level.
- [`examples/boundary_conditions_2D.py`](examples/boundary_conditions_2D.py): flow past a
  cylinder, without and with a no-penetration wall condition.

## Migrating from 0.1

- The import name is now lowercase: `import divergence_free_interpolant as dfi`.
- `dfi.interpolant(nu, k, dim)` with `.condition(XY, UV, support_radii, method)` and
  `interp(x, y, z)` (positional or keyword coordinates) still works, but emits a
  `DeprecationWarning`. Its attributes (`XY`, `sol`, `N`, `support_radii`, `method`, `kernel`,
  `zero_kernel`) are still available, read-only. Two things deliberately behave differently,
  because the 0.1 behaviour was incorrect:
  - Duplicate points raise a `ValueError`, instead of producing a singular system and a
    meaningless result. `method='lstsq'` (or `'SVD'`/`'penrose'`) still accepts them.
  - Non-finite coordinates (NaN, inf) raise a `ValueError`, instead of quietly evaluating to NaN.
    To evaluate a masked grid, pass only the finite points.

  The replacement is:

  ```python
  # 0.1
  interp = dfi.interpolant(nu=5, k=3, dim=3)
  interp.condition(XY, UV, support_radii=0.5)
  interp(x, y, z)
  # 0.2
  interp = dfi.DivergenceFreeInterpolant(0.5, k=3).fit(XY, UV)
  interp(np.stack([x, y, z], axis=-1))
  ```

## How it works

For a radial function ψ(r), with A(r) = ψ′(r)/r and H(r) = ψ″(r) − ψ′(r)/r, the Hessian is
∇∇ᵀψ = A·I + H·x̂x̂ᵀ. The two matrix kernels are

- divergence-free: Φ = (∇∇ᵀ − Δ·I)ψ = (−(d−1)A − H)·I + H·x̂x̂ᵀ
- curl-free: Φ = −∇∇ᵀψ = −A·I − H·x̂x̂ᵀ

Every column of the first is divergence-free and every column of the second is curl-free. An
interpolant s(x) = Σⱼ Φ(x − xⱼ) cⱼ therefore inherits that property exactly. The coefficients cⱼ
are found by solving the sparse, symmetric positive definite system that makes s match the
data. For Wendland's functions, A and H are polynomials in r, and the same code works in any
dimension. Their exact coefficients are derived with sympy: for the usual parameters ahead of
time (the table in `_wendland_table.py`, written by `tools/gen_kernels.py`), for others when
first needed.

With walls, the divergence-free kernel is K(x, y) = tr(M)·I − Mᵀ with
M = ∇ₓ∇ᵧᵀ[g(x) g(y) ψ(|x − y|)], for a wall function g that vanishes on the walls. It is no
longer a function of x − y alone, but its columns are still divergence-free, and on a wall they
are tangent to it.

## Development

The project is managed with [uv](https://docs.astral.sh/uv/), and needs a Rust toolchain
(1.87 or newer, e.g. via [rustup](https://rustup.rs)) for the core in `rust/`. That core is
built by [maturin](https://www.maturin.rs) as `divergence_free_interpolant._core`.

```bash
uv sync                    # build the Rust core, create .venv with the package (editable) + dev tools
uv run pytest              # run the tests
uv run ruff check          # lint (enforced in CI)
uv run ruff format         # format (enforced in CI)
uv sync --group examples   # also install matplotlib, PyQt6 and pyvista for the examples
```

After changing Rust code, `uv sync` rebuilds the extension. The table of shipped kernels is
generated: regenerate it with `uv run python tools/gen_kernels.py` (a test fails when it is out of
date). In `rust/`, `cargo test` tests the
core without Python, and `cargo fmt` and `cargo clippy --all-targets -- -D warnings` (with and
without `--features python`) are enforced in CI.

The numpy implementations of assembly, evaluation, thinning and conjugate gradients stay as the
reference the Rust core is tested against. Run with `DFI_BACKEND=numpy` to use them, e.g.
`DFI_BACKEND=numpy uv run pytest`.

`benchmarks/` holds timing scripts. `benchmarks/track.py` runs a fixed suite in about a
minute and compares it with the last run on the same machine, recorded in
`benchmarks/history.jsonl`; record a run when committing performance-relevant changes.
`research/` holds exploratory spikes, such as
`research/boundary_weighted_kernel.py`, the prototype of the walls; its findings are in
[docs/tier2_boundary_conditions.md](docs/tier2_boundary_conditions.md).

### Releasing

`.github/workflows/release.yml` builds one abi3 wheel per platform (Linux x86_64 and aarch64,
macOS arm64 and x86_64, Windows x64), each for every Python ≥ 3.10, plus the sdist, and runs the
tests against every wheel it can run. Pushing a tag `vX.Y.Z` that matches the version in
`pyproject.toml` also publishes to PyPI. It uses trusted publishing, so no token is stored. Set
it up once on PyPI:

1. In the project's settings, add a trusted publisher for GitHub Actions: this repository,
   workflow `release.yml`, environment `pypi`.
2. In the GitHub repository settings, create the environment `pypi` (optionally with required
   reviewers).

Running the workflow by hand builds and tests the wheels without publishing.

## References

<a id="1">[1]</a> Fuselier, Edward J.
“Sobolev-Type Approximation Rates for Divergence-Free and Curl-Free RBF Interpolants.”
Mathematics of Computation, vol. 77, no. 263, 2008, pp. 1407–23.
http://www.jstor.org/stable/40234564

<a id="2">[2]</a> Wendland, H.
Piecewise polynomial, positive definite and compactly supported radial functions of minimal degree.
Adv Comput Math 4, 389–396 (1995).
https://doi.org/10.1007/BF02123482

<a id="3">[3]</a> Patricio Farrell, Kathryn Gillow, Holger Wendland,
Multilevel interpolation of divergence-free vector fields,
IMA Journal of Numerical Analysis, Volume 37, Issue 1, January 2017, Pages 332–353,
https://doi.org/10.1093/imanum/drw006

<a id="4">[4]</a> Floater M. S. Iske A.
Thinning algorithms for scattered data interpolation.
BIT, 38, 705–720 (1998)

