Skip to content

Differentiate a field

Goal: compute gradients and Laplacians, then reuse local derivative matrices with new data. Start with scattered-data interpolation.

1. Construct a function from samples

import numpy as np
import rbflab as rbf
    rng = np.random.default_rng(7)
    centers = rng.uniform(-1., 1., (64, 2))
    values = np.sin(centers[:, 0]) + np.cos(centers[:, 1])
    query = np.array([[.1, .2], [-.3, .4], [.5, -.2]])
    interpolant = rbf.interpolate(rbf.PHS(5), centers, values, polynomial_degree=2)

interpolant is the global function \(s\) fitted to these 64 values. query contains three evaluation points. We will differentiate that function, not finite-difference the three query values.

2. Apply a differential functional

For \(s(x)=\sum_j a_j\phi(\|x-x_j\|)+\sum_m b_mp_m(x)\),

\[\partial_x s(x)=\sum_j a_j\partial_x\phi(\|x-x_j\|) +\sum_m b_m\partial_xp_m(x).\]

The fitted coefficients stay fixed; the evaluation basis is differentiated.

    dx = rbf.Derivative(0, dimension=2)
    dy = rbf.Derivative(1, dimension=2)
    gradient = np.column_stack((interpolant.evaluate(query, dx),
                               interpolant.evaluate(query, dy)))
    laplacian = interpolant.evaluate(query, rbf.Laplacian(2))

Axis 0 means \(x\), axis 1 means \(y\). Each evaluate(query, operator) returns one scalar per query. Stacking the two first derivatives gives an (M, 2) gradient; the Laplacian is an (M,) array. In 3D, use dimension=3, include axis 2, and use Laplacian(3).

A second derivative can be expressed as dx @ dx: here @ composes differential operators. Later, ops.dx @ values is matrix application. The objects on its two sides determine its meaning.

The sample values, reconstructed field and computed derivative

3. Build matrices when the sampled data will change

Suppose you need the same derivatives of many fields on the same source nodes. Construct RBF-FD weights once:

\[D_x d\approx (\partial_x u(q_k))_{k=1}^M,\qquad D_x\in\mathbb R^{M\times N}.\]
    space = rbf.ScalarSpace(rbf.PHS(5), polynomial_degree=2)
    source = {"u": rbf.Samples(centers, size=20)}
    local = rbf.LocalApproximation(source=source, trial=space.representers(source))
    ops = local.operators(targets=query,
                           operators={"dx": dx, "dy": dy, "lap": rbf.Laplacian(2)})
    local_gradient = np.column_stack((ops.dx @ values, ops["dy"] @ values))
    local_laplacian = ops.lap @ values

Samples(centers, size=20) declares value data and the per-target neighbor count. space.representers(source) forms ordinary kernel translates because these source functionals are point evaluations. targets gives locations where derivatives are requested. With one source block, ops.dx @ values and ops.dx["u"] @ values are equivalent. Here each matrix has shape (3, 64). Every target uses 20 neighboring samples and quadratic polynomial augmentation. The names dx, dy, and lap are keys you choose; attribute and dictionary access refer to the same operators.

The global interpolant and these local maps are different approximations. One uses all 64 samples in a single fit; the other fits a neighborhood for each target. Their derivatives need not agree exactly.

4. Reuse and combine the operators

new_values = centers[:, 0]**2 + centers[:, 1]**2
new_laplacian = ops.lap @ new_values
A = 2*ops.dx.matrix - ops.dy.matrix
advective_derivative = A @ new_values

A is an ordinary SciPy sparse matrix for \(2\partial_x-\partial_y\) at these three targets. Changing only the sampled data does not require rebuilding the weights. Changing source/target locations, kernel, or stencil policy does.

A quick check

For \(x^2+y^2\), the Laplacian is 4. Quadratic reproduction makes this a convenient check of the operator and array ordering.

Complete example

Run python -m examples.tutorials.differentiation from a source checkout. The short API fragments above also work with an installed package when combined with their imports and preceding steps.

Complete runnable script
"""Differentiate an interpolant, then construct reusable local derivative maps."""
import numpy as np
import rbflab as rbf


def run():
    rng = np.random.default_rng(7)
    centers = rng.uniform(-1., 1., (64, 2))
    values = np.sin(centers[:, 0]) + np.cos(centers[:, 1])
    query = np.array([[.1, .2], [-.3, .4], [.5, -.2]])
    interpolant = rbf.interpolate(rbf.PHS(5), centers, values, polynomial_degree=2)
    dx = rbf.Derivative(0, dimension=2)
    dy = rbf.Derivative(1, dimension=2)
    gradient = np.column_stack((interpolant.evaluate(query, dx),
                               interpolant.evaluate(query, dy)))
    laplacian = interpolant.evaluate(query, rbf.Laplacian(2))
    space = rbf.ScalarSpace(rbf.PHS(5), polynomial_degree=2)
    source = {"u": rbf.Samples(centers, size=20)}
    local = rbf.LocalApproximation(source=source, trial=space.representers(source))
    ops = local.operators(targets=query,
                           operators={"dx": dx, "dy": dy, "lap": rbf.Laplacian(2)})
    local_gradient = np.column_stack((ops.dx @ values, ops["dy"] @ values))
    local_laplacian = ops.lap @ values
    truth = np.column_stack((np.cos(query[:, 0]), -np.sin(query[:, 1])))
    polynomial = 1+centers[:, 0]+centers[:, 1]**2
    reproduction = float(np.max(np.abs(ops.lap @ polynomial-2)))
    result = {"gradient_error": float(np.max(np.abs(gradient-truth))),
              "local_gradient_error": float(np.max(np.abs(local_gradient-truth))),
              "polynomial_laplacian_error": reproduction}
    print(f"gradient={gradient.shape}, laplacian={laplacian.shape}, local matrix={ops.lap.shape}")
    print(result)
    return result


if __name__ == "__main__":
    run()

Download the script.

Next: Build one stencil, then assemble your own PDE.