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%)

from matplotlib.colors import LinearSegmentedColormap, TwoSlopeNorm
colours = LinearSegmentedColormap.from_list("sd", ["#f59e0b", "#ffffff", "#0b7f82"])
def show(mesh):
fig, (left, right) = plt.subplots(1, 2, figsize = (9.2, 4.0))
left.triplot(mesh.loc[:, 0], mesh.loc[:, 1], mesh.tv, color = "#4fb3b6", linewidth = 0.5)
left.plot(*square[[0, 1, 2, 3, 0]].T, color = "#1a1a1a", linewidth = 1.0)
left.scatter(*obs.T, s = 2, color = "#3d434c", zorder = 3)
left.set(xlim = (-5.6, 15.6), ylim = (-5.6, 15.6), aspect = "equal")
left.axis("off")
image = right.imshow(field_sd(mesh).reshape(41, 41), origin = "lower",
extent = (0, 10, 0, 10), cmap = colours,
norm = TwoSlopeNorm(1.0, vmin = 0.5, vmax = 2.0))
right.set(xticks = [0, 5, 10], yticks = [0, 5, 10])
right.spines[:].set_visible(False)
fig.colorbar(image, ax = right, extend = "both", shrink = 0.8,
ticks = [0.5, 0.75, 1.0, 1.5, 2.0])
plt.tight_layout()
plt.show()
show(good)
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%)

show(large)
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%)

show(tight)
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%)

show(thin)
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%)

show(merged)
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%)

show(clockwise)
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%)

show(partial)
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%)

show(swapped)
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%)

show(small)
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%)

merged_points = fm_mesh_2d(loc = obs, offset = [0.5, 3.0],
max_edge = [0.4, 1.5], cutoff = 0.2)
fig, axes = plt.subplots(1, 2, figsize = (9.2, 4.0))
for ax, mesh in zip(axes, [close, merged_points]):
ax.triplot(mesh.loc[:, 0], mesh.loc[:, 1], mesh.tv, color = "#4fb3b6", linewidth = 0.6)
ax.scatter(*obs.T, s = 4, color = "#3d434c", zorder = 3)
ax.set(xlim = (6.2, 7.8), ylim = (2.2, 3.8), aspect = "equal")
ax.axis("off")
plt.tight_layout()
plt.show()
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.
| mesh | noise precision | range | sigma | intervals correct | time |
|---|---|---|---|---|---|
| truth | 11.1 | 2 | 1 | 95% | |
| good mesh | 10.2 | 2.1 | 1.02 | 94% | 1.0 |
| 1. triangles too large | 3.7 | 2.4 | 1.18 | 67% | 0.3 |
| 2. no extension | 10.6 | 1.9 | 0.93 | 94% | 1.0 |
| 3. thin triangles | 9.1 | 2.4 | 1.00 | 63% | 0.4 |
| 4. cutoff too large | 4.6 | 2.2 | 1.11 | 78% | 0.4 |
| 5. boundary in the wrong order | 4.7 | 2.2 | 1.07 | 78% | 0.7 |
| 6. data outside the mesh | 1.5 | 3.5 | 0.75 | 41% | 0.5 |
| 7. extension finer than the study area | 10.4 | 2.0 | 1.02 | 94% | 1.9 |
| 8. triangles too small | 11.6 | 2.0 | 1.01 | 95% | 7.2 |
| 9. points too close together | 12.6 | 2.3 | 1.00 | 92% | 1.1 |
Reference
Lindgren, F. (2026). fmesher: Triangle Meshes and Related Geometry Tools.