Calculus¶
Finite-difference vector calculus on xarray datasets. Each operator works on cartesian, rectilinear, or spherical geometries by deriving the grid metrics from the coordinates. For a scalar \(\phi\) and vector field \(\mathbf{u}=(u,v)\):
The stencils are geoops's diagnostic difference kernel (geoops.geom.difference, geostack OP-O7), so a field gives the same numbers in xrops.grad and geoops.geom. On a lon/lat grid the metric is a sphere of radius EARTH_RADIUS by default; ellipsoid="WGS84" on partial, gradient, Gradient and Difference uses that ellipsoid's radii, as geoops does on a geographic CRS.
Operators¶
Gradient
¶
Gradient(dims: Sequence[str], *, geometry: Geometry = 'cartesian', accuracy: int = 1, method: str = 'central', periodic: str | Sequence[str] = (), nan_policy: NanPolicy = 'propagate', lon: str = 'lon', lat: str = 'lat', radius: float = EARTH_RADIUS, ellipsoid: str | None = None)
Bases: Operator
The first partial derivatives along dims, stacked on a component dim.
The result has a new leading component dim labelled "d/d<dim>"
in dims order; a Dataset gets one per variable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dims
|
Sequence[str]
|
The dims to differentiate along. |
required |
geometry
|
Geometry
|
As for |
'cartesian'
|
accuracy
|
int
|
The accuracy order of the one-sided stencils. |
1
|
method
|
str
|
|
'central'
|
periodic
|
str | Sequence[str]
|
The dim, or dims, that wrap (a global longitude). |
()
|
nan_policy
|
NanPolicy
|
|
'propagate'
|
lon
|
str
|
Longitude coordinate name (spherical). |
'lon'
|
lat
|
str
|
Latitude coordinate name (spherical). |
'lat'
|
radius
|
float
|
Sphere radius in metres (spherical). |
EARTH_RADIUS
|
ellipsoid
|
str | None
|
A pyproj ellipsoid name for an ellipsoidal metric. |
None
|
Example
import numpy as np import xarray as xr y, x = np.arange(3.0), np.arange(4.0) da = xr.DataArray(3.0 * x + 2.0 * y[:, None], dims=("y", "x"), ... coords={"y": y, "x": x}) g = Gradient(dims=("y", "x"))(da) g.dims, g["component"].values.tolist() (('component', 'y', 'x'), ['d/dy', 'd/dx']) float(g.sel(component="d/dx").mean()), float(g.sel(component="d/dy").mean()) (3.0, 2.0)
Source code in packages/xrtoolz-ops/src/xrops/grad/operators.py
Difference
¶
Difference(dim: str, *, derivative: int = 1, geometry: Geometry = 'cartesian', accuracy: int = 1, method: str = 'central', periodic: bool = False, nan_policy: NanPolicy = 'propagate', lon: str = 'lon', lat: str = 'lat', radius: float = EARTH_RADIUS, ellipsoid: str | None = None)
Bases: Operator
The derivative-th partial derivative along one dim.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dim
|
str
|
The dim to differentiate along. |
required |
derivative
|
int
|
The derivative order. |
1
|
geometry
|
Geometry
|
|
'cartesian'
|
accuracy
|
int
|
The accuracy order of the one-sided stencils. |
1
|
method
|
str
|
|
'central'
|
periodic
|
bool
|
The dim wraps (a global longitude). |
False
|
nan_policy
|
NanPolicy
|
|
'propagate'
|
lon
|
str
|
Longitude coordinate name (spherical). |
'lon'
|
lat
|
str
|
Latitude coordinate name (spherical). |
'lat'
|
radius
|
float
|
Sphere radius in metres (spherical, the default metric). |
EARTH_RADIUS
|
ellipsoid
|
str | None
|
A pyproj ellipsoid name for an ellipsoidal metric (spherical), as geoops's on a geographic CRS. |
None
|
Example
import numpy as np import xarray as xr x = np.linspace(0.0, 3.0, 4) da = xr.DataArray(x**2, dims="x", coords={"x": x}) Difference("x")(da).values array([1., 2., 4., 5.])
Source code in packages/xrtoolz-ops/src/xrops/grad/operators.py
Differential operators¶
These pure functions back the operators above; each takes xr.DataArray/xr.Dataset and a dim: argument.
partial
¶
partial(da: DataArray, dim: str, *, order: int = 1, geometry: Geometry = 'cartesian', accuracy: int = 1, method: str = 'central', periodic: bool = False, nan_policy: NanPolicy = 'propagate', **geom_kw: Any) -> DataArray
Partial derivative ∂ᵒʳᵈᵉʳda/∂<dim>ᵒʳᵈᵉʳ under the given geometry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
DataArray
|
Input field. |
required |
dim
|
str
|
Dimension along which to differentiate. |
required |
order
|
int
|
Derivative order. |
1
|
geometry
|
Geometry
|
One of |
'cartesian'
|
accuracy
|
int
|
Accuracy order forwarded to :func: |
1
|
method
|
str
|
|
'central'
|
periodic
|
bool
|
Treat |
False
|
nan_policy
|
NanPolicy
|
How to treat NaN (typically a land mask).
|
'propagate'
|
**geom_kw
|
Any
|
Geometry-specific keyword arguments (e.g. |
{}
|
Returns:
| Type | Description |
|---|---|
DataArray
|
DataArray with the same dims/coords as |
Raises:
| Type | Description |
|---|---|
ValueError
|
for an unknown |
NotImplementedError
|
for |
Example
d(x²)/dx = 2x — exact on interior points with the central
stencil; the boundary points fall back to one-sided differences
of the requested accuracy:
>>> import numpy as np
>>> import xarray as xr
>>> x = np.linspace(0.0, 3.0, 4)
>>> da = xr.DataArray(x**2, dims="x", coords={"x": x})
>>> partial(da, "x").values
array([1., 2., 4., 5.])
The second derivative d²(x²)/dx² = 2 comes from a single
order-2 stencil rather than two composed passes:
A masked cell costs its neighbour too, because the centred
stencil there reads the NaN. nan_policy="adaptive" gives that
neighbour a one-sided estimate instead, while the masked cell
itself stays NaN:
Source code in packages/xrtoolz-ops/src/xrops/grad/_src/operators.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 | |
gradient
¶
gradient(da: DataArray, *, dims: tuple[str, ...] | None = None, geometry: Geometry = 'cartesian', accuracy: int | tuple[int, ...] = 1, method: str = 'central', periodic: Periodic = None, nan_policy: NanPolicy = 'propagate', **geom_kw: Any) -> Dataset
Gradient ∇da under the given geometry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
DataArray
|
Input scalar field. |
required |
dims
|
tuple[str, ...] | None
|
Dimensions to differentiate against (defaults to |
None
|
geometry
|
Geometry
|
|
'cartesian'
|
accuracy
|
int | tuple[int, ...]
|
Scalar or per-dim tuple. |
1
|
method
|
str
|
Forwarded to :func: |
'central'
|
periodic
|
Periodic
|
Dimension name, or sequence of names, to treat as wrapping. Must be among the differentiated dims. |
None
|
nan_policy
|
NanPolicy
|
|
'propagate'
|
**geom_kw
|
Any
|
Geometry-specific keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
Dataset
|
Dataset with one DataArray per dim in |
Dataset
|
|
Example
Source code in packages/xrtoolz-ops/src/xrops/grad/_src/operators.py
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 | |
divergence
¶
divergence(ds: Dataset, components: tuple[str, str] | tuple[str, str, str], *, dims: tuple[str, ...], geometry: Geometry | Sequence[Geometry] = 'cartesian', accuracy: int | tuple[int, ...] = 1, method: str = 'central', periodic: Periodic = None, nan_policy: NanPolicy = 'propagate', **geom_kw: Any) -> DataArray
Divergence ∇·F of a vector field stored as Dataset variables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ds
|
Dataset
|
Dataset containing the vector components. |
required |
components
|
tuple[str, str] | tuple[str, str, str]
|
Variable names for |
required |
dims
|
tuple[str, ...]
|
Spatial dimensions that pair with each component (e.g.
|
required |
geometry
|
Geometry | Sequence[Geometry]
|
A single geometry applied to every dim, or a per-dim
sequence pairing with |
'cartesian'
|
accuracy
|
int | tuple[int, ...]
|
Scalar (applied to every dim) or per-dim tuple matching
the length of |
1
|
method
|
str
|
|
'central'
|
periodic
|
Periodic
|
Dimension name, or sequence of names, to treat as
wrapping. Must be among |
None
|
nan_policy
|
NanPolicy
|
|
'propagate'
|
**geom_kw
|
Any
|
Geometry-specific kwargs ( |
{}
|
Returns:
| Type | Description |
|---|---|
DataArray
|
Scalar DataArray with the same dims/coords as the components. |
Raises:
| Type | Description |
|---|---|
ValueError
|
if |
Notes
The curvature correction -(v tan φ) / R is added whenever both
the longitude and latitude axes are spherical, so the result
matches :func:metpy.calc.divergence on lon/lat fields:
.. math::
\nabla \cdot \mathbf{F} =
\frac{1}{R\cos\varphi} \frac{\partial F_x}{\partial \lambda}
+ \frac{1}{R} \frac{\partial F_y}{\partial \varphi}
- \frac{F_y \tan\varphi}{R}
Example
The radial field F = (x, y) has constant divergence 2:
>>> import numpy as np
>>> import xarray as xr
>>> x = np.linspace(0.0, 3.0, 4)
>>> X, Y = np.meshgrid(x, x, indexing="xy")
>>> coords = {"y": x, "x": x}
>>> ds = xr.Dataset(
... {
... "u": xr.DataArray(X, dims=("y", "x"), coords=coords),
... "v": xr.DataArray(Y, dims=("y", "x"), coords=coords),
... }
... )
>>> np.unique(divergence(ds, ("u", "v"), dims=("x", "y")).values)
array([2.])
A 3-D ocean budget mixes a spherical horizontal pair with a rectilinear (stretched) vertical axis in one call:
>>> depth = np.array([0.0, 10.0, 30.0, 70.0])
>>> lon, lat = np.array([0.0, 1.0, 2.0]), np.array([10.0, 11.0, 12.0])
>>> shape = (depth.size, lat.size, lon.size)
>>> dims3 = ("depth", "lat", "lon")
>>> coords3 = {"depth": depth, "lat": lat, "lon": lon}
>>> flow = xr.Dataset(
... {
... name: xr.DataArray(np.zeros(shape), dims=dims3, coords=coords3)
... for name in ("u", "v", "w")
... }
... )
>>> div = divergence(
... flow,
... ("u", "v", "w"),
... dims=("lon", "lat", "depth"),
... geometry=("spherical", "spherical", "rectilinear"),
... )
>>> div.dims
('depth', 'lat', 'lon')
Source code in packages/xrtoolz-ops/src/xrops/grad/_src/operators.py
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 | |
curl
¶
curl(ds: Dataset, components: tuple[str, str], *, dims: tuple[str, str], geometry: Geometry = 'cartesian', accuracy: int | tuple[int, ...] = 1, method: str = 'central', periodic: Periodic = None, nan_policy: NanPolicy = 'propagate', **geom_kw: Any) -> DataArray
2-D scalar curl ∂v/∂x − ∂u/∂y (vertical component of ∇×F).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ds
|
Dataset
|
Dataset with the two horizontal components. |
required |
components
|
tuple[str, str]
|
|
required |
dims
|
tuple[str, str]
|
|
required |
geometry
|
Geometry
|
|
'cartesian'
|
accuracy
|
int | tuple[int, ...]
|
Scalar (applied to both dims) or a 2-tuple pairing with
|
1
|
periodic
|
Periodic
|
Dimension name, or sequence of names, to treat as
wrapping. Must be among |
None
|
nan_policy
|
NanPolicy
|
|
'propagate'
|
method
|
str
|
Stencil family (e.g. |
'central'
|
**geom_kw
|
Any
|
Forwarded to :func: |
{}
|
Returns:
| Type | Description |
|---|---|
DataArray
|
Scalar DataArray with the same dims/coords as the components. |
Notes
For spherical geometry the curvature correction
+(u tan φ) / R is added so the result matches
:func:metpy.calc.vorticity on lon/lat fields:
.. math::
\zeta =
\frac{1}{R\cos\varphi} \frac{\partial v}{\partial \lambda}
- \frac{1}{R} \frac{\partial u}{\partial \varphi}
+ \frac{u \tan\varphi}{R}
Example
Rigid rotation F = (-y, x) has constant vorticity 2:
>>> import numpy as np
>>> import xarray as xr
>>> x = np.linspace(0.0, 3.0, 4)
>>> X, Y = np.meshgrid(x, x, indexing="xy")
>>> coords = {"y": x, "x": x}
>>> ds = xr.Dataset(
... {
... "u": xr.DataArray(-Y, dims=("y", "x"), coords=coords),
... "v": xr.DataArray(X, dims=("y", "x"), coords=coords),
... }
... )
>>> np.unique(curl(ds, ("u", "v"), dims=("x", "y")).values)
array([2.])
Source code in packages/xrtoolz-ops/src/xrops/grad/_src/operators.py
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 | |
laplacian
¶
laplacian(da: DataArray, *, dims: tuple[str, ...] | None = None, geometry: Geometry = 'cartesian', accuracy: int | tuple[int, ...] = 1, method: str = 'central', periodic: Periodic = None, nan_policy: NanPolicy = 'propagate', **geom_kw: Any) -> DataArray
Laplacian Δf = ∇·∇f.
For geometry="cartesian" this sums direct second-derivative
stencils (Σ ∂²f/∂dim²), which is exact for quadratic fields at
the default accuracy=1 and contaminates only a single boundary
ring. An axis too short to host a second-derivative stencil falls
back to the composed form below, so short axes keep working.
The other geometries compose gradient followed by divergence so the
spherical curvature correction is inherited automatically. That
applies to all rectilinear grids, including those whose coordinate
is uniform enough to delegate each partial to the cartesian backend.
On those paths the second derivative is two stacked first-derivative
stencils, so pass accuracy=2 (or higher) when you need the
interior to reproduce polynomial fields exactly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
DataArray
|
Input scalar field. |
required |
dims
|
tuple[str, ...] | None
|
Dimensions to differentiate against. Defaults to |
None
|
geometry
|
Geometry
|
|
'cartesian'
|
accuracy
|
int | tuple[int, ...]
|
Scalar (applied to every dim) or per-dim tuple matching
the length of |
1
|
method
|
str
|
Forwarded to :func: |
'central'
|
periodic
|
Periodic
|
Dimension name, or sequence of names, to treat as wrapping. Must be among the differentiated dims. |
None
|
nan_policy
|
NanPolicy
|
|
'propagate'
|
**geom_kw
|
Any
|
Geometry-specific keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
DataArray
|
Unnamed scalar DataArray with the same dims/coords as |
Raises:
| Type | Description |
|---|---|
ValueError
|
if |
Example
Δ(x² + y²) = 4, exact on interior points:
>>> import numpy as np
>>> import xarray as xr
>>> x = np.linspace(0.0, 3.0, 4)
>>> X, Y = np.meshgrid(x, x, indexing="xy")
>>> f = xr.DataArray(
... X**2 + Y**2, dims=("y", "x"), coords={"y": x, "x": x},
... )
>>> lap = laplacian(f, dims=("x", "y"))
>>> np.unique(lap.values[1:-1, 1:-1])
array([4.])
Source code in packages/xrtoolz-ops/src/xrops/grad/_src/operators.py
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 | |
grid_metrics_from_coords
¶
grid_metrics_from_coords(ds: Dataset, *, lat: str = 'lat', lon: str = 'lon', depth: str | None = None, sphere: bool = True, radius: float = EARTH_RADIUS) -> tuple[Dataset, Dataset]
Derive (volume_metrics, face_metrics) from a Dataset's coords.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ds
|
Dataset
|
Dataset whose coordinates define the grid. |
required |
lat
|
str
|
Name of the latitude coordinate. Spherical mode assumes degrees. |
'lat'
|
lon
|
str
|
Name of the longitude coordinate. Spherical mode assumes degrees. |
'lon'
|
depth
|
str | None
|
Optional vertical coordinate name. If |
None
|
sphere
|
bool
|
If |
True
|
radius
|
float
|
Earth radius (m), used in spherical mode. |
EARTH_RADIUS
|
Returns:
| Type | Description |
|---|---|
Dataset
|
|
Dataset
|
keys documented in the module docstring. |
Notes
Edge cells extrapolate the nearest interior spacing; this is adequate for budget closure tests and the demo notebook but will bias real-world budgets near the domain boundary.
Example
A 1°×1° grid near the equator has ≈111 km cell edges:
>>> import xarray as xr
>>> ds = xr.Dataset(coords={"lat": [0.0, 1.0, 2.0], "lon": [10.0, 11.0, 12.0]})
>>> vol, face = grid_metrics_from_coords(ds)
>>> sorted(vol.data_vars)
['cell_area', 'cell_volume', 'dx', 'dy']
>>> sorted(face.data_vars)
['area_e', 'area_n', 'dx_e', 'dy_n']
>>> round(float(vol["dy"].isel(lat=0)) / 1000) # km per degree latitude
111
Source code in packages/xrtoolz-ops/src/xrops/grad/_src/grid_metrics.py
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 | |