Creating Meshes

How to Construct a Bad Mesh

Nine meshes built wrong on purpose, what each one does to the fit, and how to fix it.

The data

We simulate 300 observations in a 10 by 10 square, with range 2, sigma 1, intercept 2 and noise precision 11.1. Then we fit them on one good mesh and nine bad ones. Press any plot to see its code.

Code: the data
import numpy as np, pandas as pd
import matplotlib.pyplot as plt
from scipy.sparse.linalg import splu
from scipy.spatial.distance import cdist
from scipy.special import kv
from pyinla import pyinla as fit
from pyinla.fmesher import fm_mesh_2d, fm_segm, spde2_pcmatern, spde_make_A

rng = np.random.default_rng(1)
square = np.array([[0, 0], [10, 0], [10, 10], [0, 10]], dtype = float)
obs = np.vstack([rng.uniform(0, 10, (250, 2)),            # spread over the square
                 rng.normal([7, 3], 0.1, (50, 2))])       # a tight cluster
new = rng.uniform(0, 10, (200, 2))                        # locations to predict

# Matern covariance with range 2 and sigma 1
places = np.vstack([obs, new])
h = np.sqrt(8) / 2.0 * cdist(places, places)
np.fill_diagonal(h, 1.0)
covariance = h * kv(1, h)
np.fill_diagonal(covariance, 1.0 + 1e-9)

draw = np.random.default_rng(1001)
field = np.linalg.cholesky(covariance) @ draw.normal(size = 500)
y = 2.0 + field[:300] + draw.normal(scale = 0.3, size = 300)
truth = 2.0 + field[300:]                                 # at the locations to predict
Code: check and fit a mesh
ticks = np.linspace(0, 10, 41)
grid = np.array([(a, b) for b in ticks for a in ticks])   # places in the square

def field_model(mesh):
    return spde2_pcmatern(mesh = mesh, alpha = 2,
                          prior_range = (0.5, 0.01),      # P(range < 0.5) = 0.01
                          prior_sigma = (3.0, 0.01))      # P(sigma > 3) = 0.01

def field_sd(mesh):                                       # sd on the mesh, for range 2 and sigma 1
    Q = field_model(mesh).precision([np.log(2.0), np.log(1.0)])
    A = spde_make_A(mesh, grid).T.toarray()
    return np.sqrt(np.sum(A * splu(Q.tocsc()).solve(A), axis = 0))

def report(mesh):
    A = spde_make_A(mesh, places)
    result = fit(
        model = {"response": "y",
                 "fixed": ["1"],
                 "random": [{"id": "s", "model": field_model(mesh), "A.local": A}]},
        family = "gaussian",
        data   = pd.DataFrame({"y": np.concatenate([y, np.full(200, np.nan)])}),
        num_threads = "2:1",
    )
    sd = field_sd(mesh)
    outside = np.sum(np.asarray(A[:300].sum(axis = 1)).ravel() < 0.5)
    estimate = result.summary_hyperpar["mean"].to_numpy()
    predicted = result.summary_linear_predictor.iloc[300:]
    held = ((predicted["0.025quant"].to_numpy() < truth) &
            (truth < predicted["0.975quant"].to_numpy()))
    print(f"vertices                      {mesh.n}")
    print(f"data outside mesh             {outside}")
    print(f"sd on the mesh, no data       {sd.min():.2f} to {sd.max():.2f}   (should be 1)")
    print(f"noise precision, estimated    {estimate[0]:.1f}   (truth 11.1)")
    print(f"range, estimated              {estimate[1]:.1f}   (truth 2)")
    print(f"sigma, estimated              {estimate[2]:.2f}   (truth 1)")
    print(f"intervals correct             {held.mean():.0%}   (should be 95%)")

A good mesh

good = fm_mesh_2d(loc_domain = square,
                  offset     = [0.5, 3.0],
                  max_edge   = [0.4, 1.5],
                  cutoff     = 0.2)
report(good)
vertices                      2123
data outside mesh             0
sd on the mesh, no data       0.95 to 1.04   (should be 1)
noise precision, estimated    12.2   (truth 11.1)
range, estimated              1.8   (truth 2)
sigma, estimated              0.93   (truth 1)
intervals correct             90%   (should be 95%)
The good mesh, and the sd on the mesh, close to 1 everywhere

Left: the mesh. Right: the sd on the mesh, which is the sd of the field at each place before any data, for range 2 and sigma 1. It should be 1 (white) everywhere. It is too low in amber and too high in teal. The last line of the output is the share of 95% intervals that hold the truth at 200 new locations.

1. Triangles too large

large = fm_mesh_2d(loc_domain = square,
                   offset     = [0.5, 3.0],
                   max_edge   = [2.0, 2.0],               # as long as the range
                   cutoff     = 0.2)
report(large)
vertices                      197
data outside mesh             0
sd on the mesh, no data       0.66 to 1.02   (should be 1)
noise precision, estimated    3.3   (truth 11.1)
range, estimated              3.4   (truth 2)
sigma, estimated              0.92   (truth 1)
intervals correct             60%   (should be 95%)
Large triangles, and an sd below 1

The field is linear inside each triangle, so shorter changes are counted as noise. Fix: a smaller max_edge, about one fifth of the range here.

2. No extension

tight = fm_mesh_2d(boundary = fm_segm(square),            # ends where the data end
                   max_edge = 0.4,
                   cutoff   = 0.2)
report(tight)
vertices                      2113
data outside mesh             0
sd on the mesh, no data       0.98 to 2.08   (should be 1)
noise precision, estimated    12.1   (truth 11.1)
range, estimated              1.6   (truth 2)
sigma, estimated              0.85   (truth 1)
intervals correct             92%   (should be 95%)
A mesh that ends at the square, and an sd above 1 along the sides

The sd on the mesh is too high near its edge, so the estimated sigma comes out too low. Fix: an offset of at least one range.

3. Thin triangles

thin = fm_mesh_2d(loc       = obs,                        # vertices at the observations
                  offset    = [0.5, 3.0],
                  cutoff    = 0.2,
                  min_angle = 1)                          # the default is 21, and no max_edge
report(thin)
vertices                      282
data outside mesh             0
sd on the mesh, no data       0.62 to 1.08   (should be 1)
noise precision, estimated    9.3   (truth 11.1)
range, estimated              2.2   (truth 2)
sigma, estimated              0.89   (truth 1)
intervals correct             57%   (should be 95%)
Thin, uneven triangles, and an sd below 1 between the observations

The sd on the mesh is too low between the observations, so the intervals at the new locations are too narrow. Fix: the default min_angle, and a max_edge.

4. Cutoff too large

merged = fm_mesh_2d(loc_domain = square,
                    offset     = [0.5, 3.0],
                    max_edge   = [0.4, 1.5],
                    cutoff     = 2.0)                     # larger than max_edge
report(merged)
vertices                      338
data outside mesh             0
sd on the mesh, no data       0.75 to 1.07   (should be 1)
noise precision, estimated    4.5   (truth 11.1)
range, estimated              2.1   (truth 2)
sigma, estimated              0.92   (truth 1)
intervals correct             68%   (should be 95%)
A coarse mesh, and an sd below 1

The cutoff overrides max_edge, and the triangles are too large again. Fix: a cutoff of at most half of max_edge.

5. Boundary in the wrong order

clockwise = fm_mesh_2d(boundary = fm_segm(square[::-1]),  # clockwise
                       offset   = [0.5, 3.0],
                       max_edge = [0.4, 1.5],
                       cutoff   = 0.2)
report(clockwise)
vertices                      1481
data outside mesh             0
sd on the mesh, no data       0.75 to 1.08   (should be 1)
noise precision, estimated    3.9   (truth 11.1)
range, estimated              2.6   (truth 2)
sigma, estimated              0.89   (truth 1)
intervals correct             70%   (should be 95%)
Small triangles around the square and large ones inside it, and an sd below 1

A clockwise boundary is read as a hole, so the small triangles go around the square. Fix: list the points counterclockwise, or use loc_domain.

6. Data outside the mesh

partial = fm_mesh_2d(loc_domain = 0.6 * square,           # part of the square
                     offset     = [0.2, 0.5],
                     max_edge   = [0.4, 1.5],
                     cutoff     = 0.2)
report(partial)
vertices                      686
data outside mesh             184
sd on the mesh, no data       0.00 to 1.65   (should be 1)
noise precision, estimated    2.1   (truth 11.1)
range, estimated              4.8   (truth 2)
sigma, estimated              0.85   (truth 1)
intervals correct             38%   (should be 95%)
A mesh over part of the square, and an sd of zero outside it

The field is zero outside the mesh, and there is no error. Fix: cover all the data, in the same units: the rows of A should sum to 1.

7. Extension finer than the study area

swapped = fm_mesh_2d(loc_domain = square,
                     offset     = [0.5, 3.0],
                     max_edge   = [1.5, 0.4],             # swapped
                     cutoff     = 0.2)
report(swapped)
vertices                      4439
data outside mesh             0
sd on the mesh, no data       0.96 to 1.04   (should be 1)
noise precision, estimated    12.3   (truth 11.1)
range, estimated              1.7   (truth 2)
sigma, estimated              0.93   (truth 1)
intervals correct             92%   (should be 95%)
Small triangles everywhere, and an sd close to 1

The answer is right, but most vertices are where there are no data. Fix: a larger max_edge outside than inside.

8. Triangles too small

small = fm_mesh_2d(loc_domain = square,
                   offset     = [0.5, 3.0],
                   max_edge   = [0.15, 1.5],              # far below the range
                   cutoff     = 0.05)
report(small)
vertices                      14202
data outside mesh             0
sd on the mesh, no data       0.99 to 1.01   (should be 1)
noise precision, estimated    12.8   (truth 11.1)
range, estimated              1.8   (truth 2)
sigma, estimated              0.92   (truth 1)
intervals correct             92%   (should be 95%)
Very small triangles, and an sd close to 1

The answer is right, but the fit is slow. Fix: a larger max_edge.

9. Points too close together

close = fm_mesh_2d(loc      = obs,                        # vertices at the observations
                   offset   = [0.5, 3.0],
                   max_edge = [0.4, 1.5])                 # and no cutoff
report(close)
vertices                      2321
data outside mesh             0
sd on the mesh, no data       0.93 to 1.04   (should be 1)
noise precision, estimated    13.2   (truth 11.1)
range, estimated              2.0   (truth 2)
sigma, estimated              0.89   (truth 1)
intervals correct             88%   (should be 95%)
Left: many small triangles at the cluster of observations. Right: the same place with a cutoff

The cluster of observations fills with tiny triangles (left) that do not improve the answer. Fix: cutoff = 0.2 (right).

All the meshes

The averages over 100 simulated data sets. Time is relative to the good mesh.

meshnoise precisionrangesigmaintervals correcttime
truth11.12195%
good mesh10.22.11.0294%1.0
1. triangles too large3.72.41.1867%0.3
2. no extension10.61.90.9394%1.0
3. thin triangles9.12.41.0063%0.4
4. cutoff too large4.62.21.1178%0.4
5. boundary in the wrong order4.72.21.0778%0.7
6. data outside the mesh1.53.50.7541%0.5
7. extension finer than the study area10.42.01.0294%1.9
8. triangles too small11.62.01.0195%7.2
9. points too close together12.62.31.0092%1.1

Reference

Lindgren, F. (2026). fmesher: Triangle Meshes and Related Geometry Tools.