Skip to content

Assemble your own PDE from RBF operators

Goal: use RBFLAB for differentiation while owning equation assembly and the sparse solve. Read one stencil and symbolic PDEs first.

1. Choose the mathematical expression

Consider a non-divergence-form equation:

\[-\kappa(x,y)\Delta u+b_xu_x+b_yu_y+\alpha u=f,\qquad u|_\Gamma=g,\]

where \(\kappa=1+0.2x\), \(b_x=0.4\), \(b_y=-0.2\), and \(\alpha=1\). We will write every matrix operation explicitly.

import numpy as np
import scipy.sparse as sparse
from scipy.sparse.linalg import spsolve
import sympy as sp
import rbflab as rbf
from rbflab import geometry, meshgen
    domain = geometry.Ellipse(a=1.2, b=.8, labels=("wall",))
    cloud = meshgen.generate(domain, interior=140, boundary=60, seed=42)
    X = cloud.points
    x, y = X.T
    I, B = cloud.interior_indices, cloud.boundary_indices

I and B select interior and boundary rows of X. Every full matrix below uses the original cloud ordering.

Ellipse nodes and their sparse Laplacian

This is the actual 200-node cloud and 35-node stencil recipe in the script. The sparsity plot identifies which source values contribute at each target.

2. Construct reusable differential maps

local = rbf.PythonBackend()
    space = rbf.ScalarSpace(rbf.PHS(5), polynomial_degree=3)
    source = {"u": rbf.Samples(X, size=35)}
    approximation = rbf.LocalApproximation(
        source=source, trial=space.representers(source), backend=local,
        stencil_policy=rbf.StencilPolicy(scaling="local"),
    )
    ops = approximation.operators(targets=X, operators={"dx": rbf.Derivative(0),
                                  "dy": rbf.Derivative(1), "lap": rbf.Laplacian()})
    # Explicitly export Float64 matrices for the SciPy algorithm below.
    # With Torch this detaches tensors; with MP storage it rounds entries.
    Dx, Dy, Lap = (ops[name]["u"].to_scipy() for name in ("dx", "dy", "lap"))

We explicitly set targets=X, so all three matrices have shape \((N,N)\). Samples describes the supplied values and selects 35 neighbors per target; space.representers(source) makes the trial functions visible. to_scipy() exports each source block for the SciPy algebra below. On Torch this detaches tensors; arbitrary-precision entries would be rounded to Float64. Their rows approximate \(u_x\), \(u_y\), and \(\Delta u\). The recipe uses PHS5 and cubic polynomials. Local scaling normalizes kernel distances while preserving physical derivative units. compute_condition=False skips an optional diagnostic, not part of the equation.

3. Translate the equation into sparse algebra

For nodal samples \(U\),

\[A_h=-\operatorname{diag}(\kappa(X))L+b_xD_x+b_yD_y+\alpha I_N.\]
    kappa = 1 + .2*x
    bx, by, reaction = .4, -.2, 1.
    A = (-sparse.diags(kappa) @ Lap
         + bx*Dx + by*Dy
         + reaction*sparse.eye(len(X))).tocsr()

Left multiplication by the diagonal samples \(\kappa\) at the target of each row. This is \(-\kappa\Delta u\), not \(-\nabla\cdot(\kappa\nabla u)\). The latter also contains \(-\nabla\kappa\cdot\nabla u\) by the product rule. Keep the continuous equation clear when combining matrices.

Boundary rows of A still represent the differential expression. Next we apply the boundary condition separately.

4. Supply the data and eliminate prescribed values

For \(u=\sin x\cos y\), take \(f=(2\kappa+\alpha)u+b_x\cos x\cos y-b_y\sin x\sin y\) and \(g=u|_\Gamma\).

    boundary_data = np.sin(x)*np.cos(y)
    forcing = ((2*kappa+reaction)*boundary_data
               + bx*np.cos(x)*np.cos(y) - by*np.sin(x)*np.sin(y))

The interior equations split into

\[A_{II}U_I+A_{IB}g_B=f_I,\qquad A_{II}U_I=f_I-A_{IB}g_B.\]
    A_ii = A[I, :][:, I]
    A_ib = A[I, :][:, B]
    U = np.empty(len(X))
    U[B] = boundary_data[B]
    U[I] = spsolve(A_ii, forcing[I] - A_ib @ U[B])

U contains nodal values in cloud order, not expansion coefficients. This is your SciPy solve: you can replace its solver, reuse a factorization, or embed it in a larger algorithm. Neumann/Robin conditions do not prescribe \(U_B\) directly; assemble boundary-functional rows instead of reusing this elimination unchanged.

5. Inspect the local construction

    local_row = ops.lap.local(int(I[0]))
    local_system = ops.lap.reconstruct_local(int(I[0]))
    # Work on a copy if experimenting with a matrix; .local() returns copies too.
    experimental_laplacian = Lap.copy()

local_row contains copies of indices, weights and polynomial multipliers. local_system reconstructs the augmented local weight equation on demand. Editing these inspection outputs does not update the operator.

The .matrix attribute retains backend storage (SciPy, Torch, or MP sparse). Here Lap is an explicit SciPy export. Copy matrices before experimenting; changing a matrix does not update cached local inspection records.

For custom neighborhoods, use Samples(points, indices=rows), where each row contains that target's selected group-local indices. Alternatively create an approximation from Samples(selected_points) and call approximation.weights(target=target, operator=operator). The one-stencil lesson shows this complete construction. Choose space.translates(...) or space.representers(...) explicitly when experimenting with the trial basis.

6. Express the same problem symbolically

    model = rbf.SymbolicScalar(2)
    u = model.field
    sx, sy = model.coordinates
    truth = sp.sin(sx)*sp.cos(sy)
    lhs = -(1+.2*sx)*model.laplacian(u) + bx*sp.diff(u, sx) + by*sp.diff(u, sy) + reaction*u
    problem = model.stationary(sp.Eq(lhs, lhs.subs(u, truth).doit()),
                               boundary=[model.bc("wall", sp.Eq(u, truth))])
    # Optional equation-to-system convenience route, using the same numerical recipe.
    method = rbf.RBFFD(rbf.PHS(5), stencil_size=35, polynomial_degree=3,
                       stencil_policy=rbf.StencilPolicy(scaling="local"),
                       local_backend=local)
    symbolic = problem.solve(cloud, method)

This optional comparison constructs the supported RBFFD equation-assembly adapter with the same cloud, kernel, polynomial degree, stencil size and scaling. LocalApproximation itself supplies maps, not a problem.solve method. The symbolic route applies the same PDE and boundary equations, although its boundary unknowns need not be eliminated in the same algebraic form. A quick check compares U with symbolic.evaluate(X).

Where to put your own idea

Change Relevant construction
New radial family Kernel supplied before constructing ops
New differential expression Requested operators and matrix combination
New boundary model Boundary rows or elimination
New solver/preconditioner The spsolve call
New time integrator A loop around the spatial matrices
New neighbor rule Memberships in Samples, then approximation.weights

New values on fixed nodes can reuse fixed weights. Changing nodes, kernel or stencil settings requires rebuilding. With backend setup, the script accepts --backend cpp or --backend torch for local assembly. The global solve here remains SciPy Float64.

Complete example

Run python -m examples.tutorials.custom_assembly from a source checkout.

Complete runnable script
"""Use RBF-FD maps to assemble variable-coefficient advection-diffusion-reaction."""
import argparse
import numpy as np
import scipy.sparse as sparse
from scipy.sparse.linalg import spsolve
import sympy as sp
import rbflab as rbf
from rbflab import geometry, meshgen


def run(backend="python"):
    domain = geometry.Ellipse(a=1.2, b=.8, labels=("wall",))
    cloud = meshgen.generate(domain, interior=140, boundary=60, seed=42)
    X = cloud.points
    x, y = X.T
    I, B = cloud.interior_indices, cloud.boundary_indices
    local = {"python": rbf.PythonBackend, "cpp": rbf.CppBackend,
             "torch": rbf.TorchBackend}[backend]()
    space = rbf.ScalarSpace(rbf.PHS(5), polynomial_degree=3)
    source = {"u": rbf.Samples(X, size=35)}
    approximation = rbf.LocalApproximation(
        source=source, trial=space.representers(source), backend=local,
        stencil_policy=rbf.StencilPolicy(scaling="local"),
    )
    ops = approximation.operators(targets=X, operators={"dx": rbf.Derivative(0),
                                  "dy": rbf.Derivative(1), "lap": rbf.Laplacian()})
    # Explicitly export Float64 matrices for the SciPy algorithm below.
    # With Torch this detaches tensors; with MP storage it rounds entries.
    Dx, Dy, Lap = (ops[name]["u"].to_scipy() for name in ("dx", "dy", "lap"))
    kappa = 1 + .2*x
    bx, by, reaction = .4, -.2, 1.
    A = (-sparse.diags(kappa) @ Lap
         + bx*Dx + by*Dy
         + reaction*sparse.eye(len(X))).tocsr()
    boundary_data = np.sin(x)*np.cos(y)
    forcing = ((2*kappa+reaction)*boundary_data
               + bx*np.cos(x)*np.cos(y) - by*np.sin(x)*np.sin(y))
    A_ii = A[I, :][:, I]
    A_ib = A[I, :][:, B]
    U = np.empty(len(X))
    U[B] = boundary_data[B]
    U[I] = spsolve(A_ii, forcing[I] - A_ib @ U[B])
    local_row = ops.lap.local(int(I[0]))
    local_system = ops.lap.reconstruct_local(int(I[0]))
    # Work on a copy if experimenting with a matrix; .local() returns copies too.
    experimental_laplacian = Lap.copy()
    model = rbf.SymbolicScalar(2)
    u = model.field
    sx, sy = model.coordinates
    truth = sp.sin(sx)*sp.cos(sy)
    lhs = -(1+.2*sx)*model.laplacian(u) + bx*sp.diff(u, sx) + by*sp.diff(u, sy) + reaction*u
    problem = model.stationary(sp.Eq(lhs, lhs.subs(u, truth).doit()),
                               boundary=[model.bc("wall", sp.Eq(u, truth))])
    # Optional equation-to-system convenience route, using the same numerical recipe.
    method = rbf.RBFFD(rbf.PHS(5), stencil_size=35, polynomial_degree=3,
                       stencil_policy=rbf.StencilPolicy(scaling="local"),
                       local_backend=local)
    symbolic = problem.solve(cloud, method)
    difference = float(np.max(np.abs(U-symbolic.evaluate(X))))
    error = float(np.max(np.abs(U-boundary_data)))
    print(f"nodal vector={U.shape}, operator={A.shape}, interior solve={A_ii.shape}")
    print(f"symbolic/matrix difference={difference:.3e}, sampled nodal error={error:.3e}")
    return {"route_difference": difference, "error": error}


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--backend", choices=("python", "cpp", "torch"), default="python")
    run(**vars(parser.parse_args()))

Download the script.

Next: Time-step these kinds of matrices, then build a coupled cavity algorithm.