← Creating Meshes

fmesher Basics

Interactive guide to understanding how each fm_mesh_2d() parameter affects your mesh.

1. Why Do We Need Meshes?

In SPDE (Stochastic Partial Differential Equations) approaches to spatial modeling, we approximate continuous spatial processes using a finite element representation. The mesh discretizes the spatial domain into triangles.

ConceptDescription
VerticesPoints where triangles meet - the SPDE solution is computed here
TrianglesConnect vertices, define the spatial basis functions
ResolutionSmaller triangles = more accuracy but higher computation cost
ExtensionBuffer zone beyond data reduces boundary artifacts

2. Setup: Sample Data

We'll use 50 random points to demonstrate each parameter:

import numpy as np from fmesher import fm_mesh_2d, fm_segm, fm_nonconvex_hull np.random.seed(42) locs = np.random.randn(50, 2) # 50 random points # Data range: x=[-2.56, 2.53], y=[-2.00, 2.39]

3. Minimal Example: Just the Data Points

The simplest mesh uses only your data point locations:

# Simplest possible mesh - just pass locations mesh_minimal = fm_mesh_2d(loc=locs) print(mesh_minimal.summary()) # FmMesh: # Manifold: R2 # Vertices: 53 # Triangles: 96
What happened? The mesh uses the convex hull of your data points as the boundary. Your data points become mesh vertices. Triangle sizes vary based on point spacing. Problem: No control over triangle quality or boundary extension!

4. Parameter: max_edge (Triangle Size Control)

max_edge sets the maximum allowed edge length for triangles.
  • Single value: Same maximum edge everywhere
  • [inner, outer]: Different limits for inner domain vs. extension zone
  • Smaller values = More triangles, finer resolution, higher computation
  • Larger values = Fewer triangles, coarser resolution, faster computation
# Compare different max_edge values mesh_large = fm_mesh_2d(loc=locs, max_edge=2.0) # Coarse mesh_medium = fm_mesh_2d(loc=locs, max_edge=0.5) # Medium mesh_small = fm_mesh_2d(loc=locs, max_edge=0.2) # Fine # Coarse (max_edge=2.0): 56 vertices, 99 triangles # Medium (max_edge=0.5): 119 vertices, 213 triangles # Fine (max_edge=0.2): 540 vertices, 1026 triangles
Rule of thumb: Set max_edge as a percentage of your domain size:
• Quick exploration: 15-25%
• Standard analysis: 5-15%
• High precision: 2-5%
# Calculate domain size to choose appropriate max_edge domain_width = locs[:, 0].max() - locs[:, 0].min() domain_height = locs[:, 1].max() - locs[:, 1].min() domain_size = max(domain_width, domain_height) print(f"Domain size: {domain_size:.2f}") print(f"Recommended max_edge (10%): {0.1 * domain_size:.2f}") print(f"Recommended max_edge (5%): {0.05 * domain_size:.2f}")

5. Parameter: offset (Boundary Extension)

offset extends the mesh beyond your data points. This creates a buffer zone that reduces boundary artifacts in SPDE models.
  • Positive value: Absolute distance in data units
  • Negative value: Fraction of data diameter (e.g., -0.1 = 10% of extent)
  • [inner, outer]: Two extension layers with different sizes
Why use offset? Without extension, the SPDE model can have artifacts at the boundary. The outer extension "absorbs" these edge effects away from your data.
# Compare different offset values mesh_no_offset = fm_mesh_2d(loc=locs, max_edge=0.5) mesh_small_offset = fm_mesh_2d(loc=locs, max_edge=0.5, offset=0.5) mesh_large_offset = fm_mesh_2d(loc=locs, max_edge=0.5, offset=1.5)
# Negative offset = fraction of data diameter mesh_rel_10 = fm_mesh_2d(loc=locs, max_edge=0.5, offset=-0.1) # 10% extension mesh_rel_30 = fm_mesh_2d(loc=locs, max_edge=0.5, offset=-0.3) # 30% extension

6. Inner vs Outer Zones: [inner, outer] Syntax

Many parameters accept two values [inner, outer] to control different mesh regions:

OUTER ZONE (extension buffer) +----------------------------------+ | | ← controlled by outer values | INNER ZONE (near data) | | +------------------------+ | | | * data points * | | ← controlled by inner values | | * * * | | | +------------------------+ | | | +----------------------------------+
Important: The outer zone only exists when you use offset!
# Using [inner, outer] for max_edge with offset # Fine mesh near data (0.3), coarser in extension (1.0) mesh_uniform = fm_mesh_2d(loc=locs, max_edge=0.5, offset=1.5) mesh_varying = fm_mesh_2d(loc=locs, max_edge=[0.3, 1.0], offset=1.5) # Uniform max_edge: 342 vertices # Varying max_edge: 231 vertices # Savings: 111 fewer vertices with varying resolution!
# Two-layer extension: small inner buffer + larger outer buffer mesh_single_offset = fm_mesh_2d(loc=locs, max_edge=[0.3, 0.8], offset=1.0) mesh_two_layer = fm_mesh_2d(loc=locs, max_edge=[0.3, 0.8], offset=[0.3, 1.0])

7. Parameter: cutoff (Point Merging)

cutoff sets the minimum distance allowed between mesh vertices. Points closer than cutoff are merged together.

Why use cutoff?

  • Prevents degenerate triangles from nearly coincident points
  • Reduces mesh complexity when data has clusters
  • Improves numerical stability
# Create data with some clustered points np.random.seed(123) locs_clustered = np.vstack([ np.random.randn(30, 2), # Spread points np.random.randn(20, 2) * 0.1 + [0.5, 0.5] # Tight cluster ]) mesh_no_cutoff = fm_mesh_2d(loc=locs_clustered, max_edge=0.5) mesh_small_cutoff = fm_mesh_2d(loc=locs_clustered, max_edge=0.5, cutoff=0.1) mesh_large_cutoff = fm_mesh_2d(loc=locs_clustered, max_edge=0.5, cutoff=0.3)
Data TypeRecommended cutoff
Well-spaced observationsNot needed
Some clustering3-5% of domain
Heavy clustering5-10% of domain
Warning: Setting cutoff too large will lose spatial detail!

8. Parameter: min_angle (Triangle Quality)

min_angle sets the minimum interior angle for triangles (in degrees).
  • Well-shaped triangles (closer to equilateral) improve numerical accuracy
  • Skinny triangles can cause numerical instability
  • Typical range: 21-30 degrees
  • Maximum practical value: ~33 degrees (theoretical limit for guaranteed convergence)
# Compare different min_angle values mesh_low_angle = fm_mesh_2d(loc=locs, max_edge=0.5, min_angle=10) # Allows skinny mesh_default_angle = fm_mesh_2d(loc=locs, max_edge=0.5, min_angle=21) # Default mesh_high_angle = fm_mesh_2d(loc=locs, max_edge=0.5, min_angle=30) # High quality

9. Parameter: boundary (Custom Boundaries)

Instead of the convex hull, you can specify a custom boundary polygon.

Use cases:

  • Irregular study regions (countries, watersheds)
  • Excluding certain areas
  • Matching administrative boundaries
from fmesher import fm_segm # Create a custom square boundary square_corners = np.array([ [-3, -3], [3, -3], [3, 3], [-3, 3] ]) square_boundary = fm_segm(square_corners, is_bnd=True) # Create a custom L-shaped boundary L_shape = np.array([ [-3, -3], [3, -3], [3, 0], [0, 0], [0, 3], [-3, 3] ]) L_boundary = fm_segm(L_shape, is_bnd=True) mesh_square = fm_mesh_2d(loc=locs, boundary=square_boundary, max_edge=0.5) mesh_L = fm_mesh_2d(loc=locs, boundary=L_boundary, max_edge=0.5)

10. Non-Convex Hull: Following Data Shape

Use fm_nonconvex_hull() to create a boundary that follows your data more closely:

from fmesher import fm_nonconvex_hull # Create non-convex hull with different tightness hull_loose = fm_nonconvex_hull(locs, convex=-0.3) # Looser fit hull_tight = fm_nonconvex_hull(locs, convex=-0.1) # Tighter fit mesh_loose = fm_mesh_2d(loc=locs, boundary=hull_loose, max_edge=0.4) mesh_tight = fm_mesh_2d(loc=locs, boundary=hull_tight, max_edge=0.4)

11. Complete Example: Putting It All Together

Here's a well-configured mesh combining all the parameters:

# Calculate domain-relative values domain_size = max( locs[:, 0].max() - locs[:, 0].min(), locs[:, 1].max() - locs[:, 1].min() ) # Well-configured mesh for SPDE modeling mesh_optimal = fm_mesh_2d( loc=locs, offset=[0.1 * domain_size, 0.3 * domain_size], # Inner and outer extension max_edge=[0.08 * domain_size, 0.25 * domain_size], # Fine inner, coarse outer cutoff=0.03 * domain_size, # Prevent tiny triangles min_angle=21 # Good triangle quality ) print(mesh_optimal.summary())

12. Quick Reference Card

ParameterTypeDescriptionTypical Values
loc array (n, 2) Data point locations Required
max_edge float or [inner, outer] Maximum triangle edge length 5-15% of domain
offset float or [inner, outer] Extension beyond data 10-30% of domain
cutoff float Minimum point spacing 3-10% of domain
min_angle float Minimum triangle angle (degrees) 21-30
boundary FmSegment or array Custom boundary polygon Optional

13. Best Practices

  1. Always use offset for SPDE models to reduce boundary artifacts
  2. Use [inner, outer] syntax to save computation - fine mesh near data, coarse in extension
  3. Set cutoff when data has clusters to prevent degenerate triangles
  4. Start coarse, refine as needed - begin with larger max_edge and decrease until results stabilize
  5. Match parameters to data scale - always calculate domain size first

14. Helper Function: Suggest Mesh Parameters

Use this helper function to get suggested parameters based on your data:

def suggest_mesh_params(locs, quality='standard'): """Suggest mesh parameters based on data locations. Parameters ---------- locs : array (n, 2) Data point locations quality : str 'quick', 'standard', or 'high' Returns ------- dict : Suggested parameters for fm_mesh_2d() """ locs = np.asarray(locs) domain_size = max( locs[:, 0].max() - locs[:, 0].min(), locs[:, 1].max() - locs[:, 1].min() ) configs = { 'quick': {'max_edge': [0.15, 0.35], 'offset': [0.1, 0.25], 'cutoff': 0.08}, 'standard': {'max_edge': [0.08, 0.25], 'offset': [0.1, 0.3], 'cutoff': 0.05}, 'high': {'max_edge': [0.04, 0.15], 'offset': [0.1, 0.35], 'cutoff': 0.03} } cfg = configs[quality] return { 'max_edge': [cfg['max_edge'][0] * domain_size, cfg['max_edge'][1] * domain_size], 'offset': [cfg['offset'][0] * domain_size, cfg['offset'][1] * domain_size], 'cutoff': cfg['cutoff'] * domain_size, 'min_angle': 21 } # Example usage params = suggest_mesh_params(locs, quality='standard') print("Suggested parameters for your data:") for key, value in params.items(): print(f" {key}: {value}")