Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Finite-difference gradients

Part 5: Coordinate-Aware Gradient Operators

This notebook demonstrates how to compute derivatives with respect to physical coordinates (not just array indices) using finite differences.

5.1 Finite Differences on a Periodic Cartesian Domain

Centered finite differences on a uniform periodic grid.

Temperature field: shape=(64,), dims=('x',)
x range: 0.000 to 9.844 m

Grid spacing from coordinates

dx (from domain): 0.156250 m
dx (from coords): 0.156250 m
Match: True

Periodic centered finite difference

Max absolute error: 1.89e-01
Mean absolute error: 1.09e-01

Reusable helper using cx.field(...)

Helper vs manual diff: 0.00e+00

5.2 Finite Differences with Non-Uniform Spacing

Non-uniform vertical grid (denser near the surface).

Pressure profile: shape=(30,), z range: 0.0 to 20000.0 m

Centered FD for non-uniform grids

Max absolute error: 0.086 Pa/m
Max relative error: 10.34%

5.3 2D Gradients (∇ operator) in Cartesian Coordinates

2D Temperature field: shape=(32, 64), dims=('y', 'x')

Gradient in y (non-periodic) and x (periodic)

y gradient accuracy — max error: 2.538e+00
x gradient accuracy — max error: 5.427e-01
Gradient magnitude range: 1.88 to 37.16 [T]/m

Advanced: Second Derivative (Laplacian)

Second derivative shape: (64,), dims: ('x',)

Key Patterns Summary

  • Periodic uniform grids: (roll(f,-1) - roll(f,+1)) / (2*dx) with dx from coordinates
  • Non-uniform grids: (f[i+1] - f[i-1]) / (x[i+1] - x[i-1]) or jnp.gradient(f, coords, axis=...)
  • Multi-dimensional: compute derivatives in each dimension separately; combine for gradient magnitude
  • cmap pattern: cx.cmap(deriv_fn)(field.untag('dim')).tag(coord_axis)