Skip to content

Your first RBF problem

RBFLAB connects four things: geometry, equations, approximation, and solution. The equation and boundary data define the problem; the RBF method defines how to approximate it. This first example uses the symbolic PDE interface on an ellipse. The local-operator tutorial shows how to build weights and sparse matrices for your own algorithm.

Install and import

python -m pip install rbflab

The calculation below needs only the core package. Plotting is optional: install "rbflab[examples]" for the last step. See installation for virtual environments, C++ and PyTorch.

import numpy as np
import sympy as sp
import rbflab as rbf
from rbflab import geometry, meshgen

1. Describe the domain and its boundary

    domain = geometry.Ellipse(a=1.3, b=.8, labels=("wall",))
    cloud = meshgen.generate(domain, interior=200, boundary=80, seed=42)

The ellipse has semi-axes 1.3 and 0.8. wall labels its perimeter; the result contains 200 interior nodes and 80 boundary nodes. No triangles are needed. Geometry construction does not choose an equation or a numerical method. Learn to compose other shapes in Mesh generation.

2. Write the equation

We solve a Poisson problem with a known answer:

\[ -\Delta u=2\sin x\cos y\quad\text{in }\Omega, \qquad u=\sin x\cos y\quad\text{on }\partial\Omega. \]

Thus \(u_{\mathrm{exact}}=\sin x\cos y\). Using a known solution lets us check the numerical result; ordinary applications supply their own forcing and boundary data.

    model = rbf.SymbolicScalar(2)
    u = model.field
    x, y = model.coordinates
    exact = sp.sin(x)*sp.cos(y)
    problem = model.stationary(
        sp.Eq(-model.laplacian(u), 2*exact),
        boundary=[model.bc("wall", sp.Eq(u, exact))],
    )

SymbolicScalar(2) supplies a scalar field and two spatial coordinates. stationary declares a time-independent equation. The string wall connects the Dirichlet equation to the boundary nodes generated in step 1. Interior rows enforce the Poisson equation; wall rows enforce its prescribed values.

3. Choose RBF-FD and solve

    method = rbf.RBFFD(rbf.PHS(5), stencil_size=35, polynomial_degree=3,
        stencil_policy=rbf.StencilPolicy(scaling="local"))
    system = method.assemble(problem, cloud)
    solution = system.solve()

PHS(5) selects a polyharmonic spline kernel. Each local stencil uses 35 nodes and polynomials through degree three. The global matrix is sparse.

What does scaling="local" do?

It uses each stencil's radius as the distance unit for the kernel. For example, a distance of 0.006 in a stencil of radius 0.02 becomes 0.3. The nodes stay in their physical positions, and RBFLAB automatically converts derivatives back to physical units when computing weights.

This is a numerical scaling choice; it does not select more neighbors or increase precision. With this pure PHS kernel, the exact RBF-FD weights are unchanged, while roundoff can differ. Shape-dependent kernels such as IMQ need more care: local scaling and kernel parameters. Omitting the policy uses scaling="physical".

  • problem describes the PDE and boundary equations.
  • method chooses the approximation and its numerical settings.
  • system holds the sparse equations for the unknown nodal values.
  • solution evaluates the computed field at requested coordinates.

The local stencil size must fit the cloud and be large enough for the polynomial basis. These settings are a small example recipe, not universal accuracy defaults.

4. Check points that were not used in the solve

    query = meshgen.generate(domain, interior=100, boundary=24, seed=17).interior
    reference = np.sin(query[:, 0])*np.cos(query[:, 1])
    error = float(np.max(np.abs(solution.evaluate(query)-reference)))
    print(f"nodes={len(cloud.points)}, sampled maximum error={error:.6e}")

The default run gives about \(1.02\times10^{-4}\) in Float64. This reports a maximum over 100 independently sampled interior points. It is a sampled solution error, not a bound over the whole ellipse and not the residual of the linear solver. See errors and residuals.

Ellipse nodes with their wall label and the computed Poisson solution

5. Plot with one library call

from rbflab import viz
fig, ax = viz.plot_scalar(solution, domain=domain, title="Poisson on an ellipse")
fig.savefig("poisson.png", dpi=160)

domain masks the exterior. The plotting grid only displays the solution; it does not change the numerical nodes.

Complete runnable source
"""A first symbolic Poisson problem on an ellipse; no helper module required."""
import argparse
from pathlib import Path
import numpy as np
import sympy as sp
import rbflab as rbf
from rbflab import geometry, meshgen


def run(plot=None):
    domain = geometry.Ellipse(a=1.3, b=.8, labels=("wall",))
    cloud = meshgen.generate(domain, interior=200, boundary=80, seed=42)

    model = rbf.SymbolicScalar(2)
    u = model.field
    x, y = model.coordinates
    exact = sp.sin(x)*sp.cos(y)
    problem = model.stationary(
        sp.Eq(-model.laplacian(u), 2*exact),
        boundary=[model.bc("wall", sp.Eq(u, exact))],
    )

    method = rbf.RBFFD(rbf.PHS(5), stencil_size=35, polynomial_degree=3,
        stencil_policy=rbf.StencilPolicy(scaling="local"))
    system = method.assemble(problem, cloud)
    solution = system.solve()

    query = meshgen.generate(domain, interior=100, boundary=24, seed=17).interior
    reference = np.sin(query[:, 0])*np.cos(query[:, 1])
    error = float(np.max(np.abs(solution.evaluate(query)-reference)))
    print(f"nodes={len(cloud.points)}, sampled maximum error={error:.6e}")
    if plot:
        from rbflab import viz
        import matplotlib.pyplot as plt
        fig, axes = plt.subplots(1, 2, figsize=(11, 4.5), facecolor="#0b1220",
                                 constrained_layout=True)
        viz.plot_cloud(cloud, ax=axes[0], title="280 nodes / labeled wall")
        viz.plot_scalar(solution, domain=domain, resolution=140, ax=axes[1],
                        title="Computed Poisson solution")
        output = Path(plot)
        output.parent.mkdir(parents=True, exist_ok=True)
        fig.savefig(output, dpi=160)
        plt.close(fig)
    return error


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--plot")
    run(**vars(parser.parse_args()))

Download this self-contained script, or run python -m examples.tutorials.first_problem --plot poisson.png from a source checkout. pip install rbflab installs the library; it does not install the repository's examples directory as a Python package.

Choose the next level of control

You want to… Continue with…
Add holes or label curved boundary pieces Mesh generation
Understand how local derivative weights arise One RBF-FD stencil
Assemble and time-step sparse operators yourself Heat with RBF-FD matrices and LHI from matrices
Compare global collocation, LHI and RBF-FD Compare numerical methods
Build a nonlinear flow algorithm Navier–Stokes cavity

Changing methods or backends is a separate decision from changing the equation. Compare errors whenever you change kernels, stencil rules or precision.