sectionate 0.3.4__tar.gz → 0.3.5__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {sectionate-0.3.4 → sectionate-0.3.5}/.github/workflows/ci.yml +5 -2
- {sectionate-0.3.4 → sectionate-0.3.5}/PKG-INFO +2 -2
- {sectionate-0.3.4 → sectionate-0.3.5}/ci/environment.yml +1 -1
- {sectionate-0.3.4 → sectionate-0.3.5}/sectionate/_version.py +2 -2
- {sectionate-0.3.4 → sectionate-0.3.5}/sectionate/section.py +66 -2
- sectionate-0.3.5/sectionate/tests/test_tripolar_fold.py +304 -0
- sectionate-0.3.5/sectionate/tracers.py +104 -0
- {sectionate-0.3.4 → sectionate-0.3.5}/sectionate/transports.py +84 -15
- sectionate-0.3.4/sectionate/tracers.py +0 -76
- {sectionate-0.3.4 → sectionate-0.3.5}/.github/workflows/publish-to-pypi.yml +0 -0
- {sectionate-0.3.4 → sectionate-0.3.5}/.gitignore +0 -0
- {sectionate-0.3.4 → sectionate-0.3.5}/.readthedocs.yaml +0 -0
- {sectionate-0.3.4 → sectionate-0.3.5}/LICENSE +0 -0
- {sectionate-0.3.4 → sectionate-0.3.5}/README.md +0 -0
- {sectionate-0.3.4 → sectionate-0.3.5}/binder/environment.yml +0 -0
- {sectionate-0.3.4 → sectionate-0.3.5}/conda/meta.yaml +0 -0
- {sectionate-0.3.4 → sectionate-0.3.5}/docs/Makefile +0 -0
- {sectionate-0.3.4 → sectionate-0.3.5}/docs/environment.yml +0 -0
- {sectionate-0.3.4 → sectionate-0.3.5}/docs/make.bat +0 -0
- {sectionate-0.3.4 → sectionate-0.3.5}/docs/source/_static/.gitkeep +0 -0
- {sectionate-0.3.4 → sectionate-0.3.5}/docs/source/_static/custom.css +0 -0
- {sectionate-0.3.4 → sectionate-0.3.5}/docs/source/_templates/.gitkeep +0 -0
- {sectionate-0.3.4 → sectionate-0.3.5}/docs/source/conf.py +0 -0
- {sectionate-0.3.4 → sectionate-0.3.5}/docs/source/index.rst +0 -0
- {sectionate-0.3.4 → sectionate-0.3.5}/docs/source/installation.rst +0 -0
- {sectionate-0.3.4 → sectionate-0.3.5}/pyproject.toml +0 -0
- {sectionate-0.3.4 → sectionate-0.3.5}/sectionate/__init__.py +0 -0
- {sectionate-0.3.4 → sectionate-0.3.5}/sectionate/catalog/Atlantic_transport_arrays.json +0 -0
- {sectionate-0.3.4 → sectionate-0.3.5}/sectionate/gridutils.py +0 -0
- {sectionate-0.3.4 → sectionate-0.3.5}/sectionate/tests/test_convergent_transport.py +0 -0
- {sectionate-0.3.4 → sectionate-0.3.5}/sectionate/tests/test_section.py +0 -0
- {sectionate-0.3.4 → sectionate-0.3.5}/sectionate/tests/test_section_class.py +0 -0
- {sectionate-0.3.4 → sectionate-0.3.5}/sectionate/tests/test_section_cornercases.py +0 -0
- {sectionate-0.3.4 → sectionate-0.3.5}/sectionate/tests/test_utils.py +0 -0
- {sectionate-0.3.4 → sectionate-0.3.5}/sectionate/utils.py +0 -0
- {sectionate-0.3.4 → sectionate-0.3.5}/sectionate/version.py +0 -0
|
@@ -34,13 +34,16 @@ jobs:
|
|
|
34
34
|
fetch-depth: 0
|
|
35
35
|
|
|
36
36
|
- name: Conda setup
|
|
37
|
-
uses: conda-incubator/setup-miniconda@
|
|
37
|
+
uses: conda-incubator/setup-miniconda@v4
|
|
38
38
|
with:
|
|
39
|
+
# Install conda explicitly: ubuntu-latest (26.04 and later) no longer
|
|
40
|
+
# bundles Miniconda.
|
|
41
|
+
miniforge-version: latest
|
|
39
42
|
channels: conda-forge
|
|
40
43
|
mamba-version: '*'
|
|
41
44
|
python-version: ${{ matrix.python-version }}
|
|
42
45
|
activate-environment: test_env_sectionate
|
|
43
|
-
auto-activate
|
|
46
|
+
auto-activate: false
|
|
44
47
|
|
|
45
48
|
- name: Set up conda environment
|
|
46
49
|
run: |
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
2
|
Name: sectionate
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.5
|
|
4
4
|
Summary: A package to sample grid-consistent sections from ocean model outputs
|
|
5
5
|
Project-URL: Homepage, https://github.com/MOM6-community/sectionate
|
|
6
6
|
Project-URL: Bugs/Issues/Features, https://github.com/MOM6-community/sectionate/issues
|
|
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
|
|
|
18
18
|
commit_id: str | None
|
|
19
19
|
__commit_id__: str | None
|
|
20
20
|
|
|
21
|
-
__version__ = version = '0.3.
|
|
22
|
-
__version_tuple__ = version_tuple = (0, 3,
|
|
21
|
+
__version__ = version = '0.3.5'
|
|
22
|
+
__version_tuple__ = version_tuple = (0, 3, 5)
|
|
23
23
|
|
|
24
24
|
__commit_id__ = commit_id = None
|
|
@@ -458,12 +458,15 @@ def infer_grid_path(i1, j1, i2, j2, gridlon, gridlat, boundary={"X":"periodic",
|
|
|
458
458
|
Default: {"X":"periodic", "Y":"extend"}. Set to {"X":"extend", "Y":"extend"} if using a non-periodic regional domain.
|
|
459
459
|
topology: str
|
|
460
460
|
Default: "latlon". Currently only supports the following options: ["latlon", "cartesian", "MOM-tripolar"].
|
|
461
|
+
For "MOM-tripolar", the top row of (gridlon, gridlat) is the tripolar fold; which point on the other side
|
|
462
|
+
of the fold each top-row point coincides with is read from the coordinates (see `fold_partner_offset`).
|
|
461
463
|
|
|
462
464
|
RETURNS:
|
|
463
465
|
-------
|
|
464
466
|
|
|
465
467
|
i_c_seg, j_c_seg: list of int
|
|
466
|
-
list of (i,j) pairs bounded by (i1, j1) and (i2, j2)
|
|
468
|
+
list of (i,j) pairs bounded by (i1, j1) and (i2, j2). Where the path crosses the tripolar fold, the
|
|
469
|
+
crossing point appears twice in a row, once with its index on each side of the fold.
|
|
467
470
|
lons_c_seg, lats_c_seg: list of float
|
|
468
471
|
corresponding longitude and latitude for i_c_seg, j_c_seg
|
|
469
472
|
"""
|
|
@@ -474,6 +477,13 @@ def infer_grid_path(i1, j1, i2, j2, gridlon, gridlat, boundary={"X":"periodic",
|
|
|
474
477
|
if isinstance(gridlat, xr.core.dataarray.DataArray):
|
|
475
478
|
gridlat = gridlat.values
|
|
476
479
|
|
|
480
|
+
fold = (topology == "MOM-tripolar")
|
|
481
|
+
if fold:
|
|
482
|
+
# top-row point (ny-1, i) is the same point as (ny-1, (s - i) % nx), its twin across the fold
|
|
483
|
+
s = fold_partner_offset(gridlon, gridlat)
|
|
484
|
+
def twin(i):
|
|
485
|
+
return (s - i) % nx
|
|
486
|
+
|
|
477
487
|
# target coordinates
|
|
478
488
|
lon1, lat1 = gridlon[j1, i1], gridlat[j1, i1]
|
|
479
489
|
lon2, lat2 = gridlon[j2, i2], gridlat[j2, i2]
|
|
@@ -496,6 +506,13 @@ def infer_grid_path(i1, j1, i2, j2, gridlon, gridlat, boundary={"X":"periodic",
|
|
|
496
506
|
j_prev, i_prev = j,i
|
|
497
507
|
while (i%nx != i2) or (j != j2):
|
|
498
508
|
|
|
509
|
+
# On the fold, the end point may have been reached from the other side of the fold, i.e. at its twin.
|
|
510
|
+
# Finish on the end point's own index so that consecutive segments join up.
|
|
511
|
+
if fold and (j == ny-1) and (j2 == ny-1) and (twin(i) == i2):
|
|
512
|
+
i_c_seg.append(i2)
|
|
513
|
+
j_c_seg.append(j2)
|
|
514
|
+
break
|
|
515
|
+
|
|
499
516
|
# safety precaution: exit after taking enough steps to have crossed the entire model grid
|
|
500
517
|
if ct > (nx+ny+1):
|
|
501
518
|
raise RuntimeError(f"Should have reached the endpoint by now.")
|
|
@@ -522,7 +539,8 @@ def infer_grid_path(i1, j1, i2, j2, gridlon, gridlat, boundary={"X":"periodic",
|
|
|
522
539
|
if j!=ny-1:
|
|
523
540
|
up = (j+1, i%nx)
|
|
524
541
|
else:
|
|
525
|
-
|
|
542
|
+
# across the fold: one row down from this point's twin on the other side
|
|
543
|
+
up = (j-1, twin(i))
|
|
526
544
|
|
|
527
545
|
elif topology=="cartesian" or topology=="latlon":
|
|
528
546
|
up = (np.clip(j+1, 0, ny-1), i)
|
|
@@ -590,6 +608,13 @@ def infer_grid_path(i1, j1, i2, j2, gridlon, gridlat, boundary={"X":"periodic",
|
|
|
590
608
|
|
|
591
609
|
j_prev, i_prev = j,i
|
|
592
610
|
|
|
611
|
+
# Crossing the fold: the next point is adjacent to this point's twin on the other side of the fold,
|
|
612
|
+
# not to (j, i) itself. Record the twin first, so that every step of the path joins adjacent indices.
|
|
613
|
+
if fold and (j == ny-1) and ((j_next, i_next) == up) and (twin(i) != i):
|
|
614
|
+
i_c_seg.append(twin(i))
|
|
615
|
+
j_c_seg.append(j)
|
|
616
|
+
j_prev, i_prev = j, twin(i)
|
|
617
|
+
|
|
593
618
|
j = j_next
|
|
594
619
|
i = i_next
|
|
595
620
|
|
|
@@ -607,6 +632,45 @@ def infer_grid_path(i1, j1, i2, j2, gridlon, gridlat, boundary={"X":"periodic",
|
|
|
607
632
|
return np.array(i_c_seg), np.array(j_c_seg), np.array(lons_c_seg), np.array(lats_c_seg)
|
|
608
633
|
|
|
609
634
|
|
|
635
|
+
def fold_partner_offset(gridlon, gridlat):
|
|
636
|
+
"""
|
|
637
|
+
Find how the top row of a tripolar grid folds onto itself: the offset `s` such that the top-row point
|
|
638
|
+
(ny-1, i) is the same geographic point as (ny-1, (s - i) % nx).
|
|
639
|
+
|
|
640
|
+
The offset depends on where the vorticity points sit relative to the fold, so it is read from the
|
|
641
|
+
coordinates rather than assumed. With poles on vorticity points 0 and nx/2 (MOM6), `s = 0` for a
|
|
642
|
+
symmetric grid (as passed here, without its repeated periodic column) and `s = -2` for a non-symmetric
|
|
643
|
+
grid (MOM6 non-symmetric, MOM5).
|
|
644
|
+
|
|
645
|
+
PARAMETERS:
|
|
646
|
+
-----------
|
|
647
|
+
gridlon: np.ndarray
|
|
648
|
+
2d array of vorticity-point longitude, in degrees
|
|
649
|
+
gridlat: np.ndarray
|
|
650
|
+
2d array of vorticity-point latitude, in degrees
|
|
651
|
+
|
|
652
|
+
RETURNS:
|
|
653
|
+
--------
|
|
654
|
+
s : int
|
|
655
|
+
"""
|
|
656
|
+
lon, lat = np.asarray(gridlon)[-1], np.asarray(gridlat)[-1]
|
|
657
|
+
nx = lon.size
|
|
658
|
+
i = np.arange(nx)
|
|
659
|
+
spacing = np.median(distance_on_unit_sphere(lon, lat, np.roll(lon, -1), np.roll(lat, -1)))
|
|
660
|
+
for s in (0, -2, -1):
|
|
661
|
+
twin = (s - i) % nx
|
|
662
|
+
if np.max(distance_on_unit_sphere(lon, lat, lon[twin], lat[twin])) < 1.e-3 * spacing:
|
|
663
|
+
return s
|
|
664
|
+
raise ValueError(
|
|
665
|
+
"topology='MOM-tripolar', but the top row of vorticity points does not fold onto itself "
|
|
666
|
+
"((ny-1, i) coincides with none of (ny-1, (s - i) % nx) for s in (0, -1, -2)). "
|
|
667
|
+
"Grids without a tripolar fold should use topology='latlon' or topology='cartesian'. "
|
|
668
|
+
"Note that regionate passes topology='MOM-tripolar' by default: if this error was reached "
|
|
669
|
+
"through regionate, pass topology='latlon' (or 'cartesian') to GriddedRegion, which needs "
|
|
670
|
+
"regionate >= 0.5.8 (regionate <= 0.5.7 always uses 'MOM-tripolar')."
|
|
671
|
+
)
|
|
672
|
+
|
|
673
|
+
|
|
610
674
|
def find_closest_grid_point(lon, lat, gridlon, gridlat):
|
|
611
675
|
"""
|
|
612
676
|
Find integer indices of closest grid point in grid of coordinates
|
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
"""Sections across the fold of a MOM-style tripolar grid.
|
|
2
|
+
|
|
3
|
+
The test grid is regular in latitude and longitude south of LAT0. North of it is a bipolar cap, built from
|
|
4
|
+
bipolar coordinates in the north-polar stereographic plane, whose two poles sit on vorticity points i = 0
|
|
5
|
+
and i = NX/2 of the cap's southern edge, as in MOM5/MOM6. The top row of vorticity points is the fold:
|
|
6
|
+
(top, i) and (top, NX - i) are the same point.
|
|
7
|
+
|
|
8
|
+
Transports are made divergence-free by deriving them from a streamfunction on vorticity points,
|
|
9
|
+
u = psi[j+1, i] - psi[j, i] and v = -(psi[j, i+1] - psi[j, i]). The transport across any section is then
|
|
10
|
+
psi(end) - psi(start), whatever path the section takes: exactly zero around a closed section. That checks
|
|
11
|
+
both that the section is a connected chain of velocity faces and that each face is the right one with the
|
|
12
|
+
right sign, including where the section crosses the fold.
|
|
13
|
+
"""
|
|
14
|
+
import numpy as np
|
|
15
|
+
import pytest
|
|
16
|
+
import xarray as xr
|
|
17
|
+
import xgcm
|
|
18
|
+
|
|
19
|
+
from sectionate.section import grid_section
|
|
20
|
+
from sectionate.transports import convergent_transport
|
|
21
|
+
|
|
22
|
+
NX = 72 # vorticity points around a latitude circle
|
|
23
|
+
NYC = 12 # rows of cells in the bipolar cap
|
|
24
|
+
LAT_SOUTH = 30.
|
|
25
|
+
LAT0 = 60. # southern edge of the bipolar cap
|
|
26
|
+
DLAT = 2.
|
|
27
|
+
LON0 = 80. # longitude of the first pole
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def tripolar_supergrid():
|
|
31
|
+
"""Longitude and latitude on a supergrid with twice the resolution of the model grid."""
|
|
32
|
+
m = 2*NX
|
|
33
|
+
lam = 2*np.pi*np.arange(m+1)/m # angle from the first pole, including the periodic repeat
|
|
34
|
+
lam_deg = np.rad2deg(lam)
|
|
35
|
+
|
|
36
|
+
# regular latitude-longitude grid up to and including the edge of the cap
|
|
37
|
+
lat_s = np.arange(LAT_SOUTH, LAT0 + DLAT/4, DLAT/2)
|
|
38
|
+
x_s = np.broadcast_to(LON0 + lam_deg, (lat_s.size, m+1))
|
|
39
|
+
y_s = np.broadcast_to(lat_s[:, None], (lat_s.size, m+1))
|
|
40
|
+
|
|
41
|
+
# bipolar cap: z = tan(colatitude/2) exp(i longitude) in the north-polar stereographic plane, with the
|
|
42
|
+
# poles at z = +a and -a on the cap's edge |z| = a. In bipolar coordinates zeta = tau + i sigma,
|
|
43
|
+
# (z + a)/(z - a) = exp(zeta): grid rows are arcs of constant sigma through both poles, from |sigma| = pi/2
|
|
44
|
+
# on the cap's edge to |sigma| = pi on the segment between the poles, which is the fold; columns are
|
|
45
|
+
# curves of constant tau, matching the cap's edge at the longitude of each column.
|
|
46
|
+
a = np.tan(np.deg2rad(90. - LAT0)/2)
|
|
47
|
+
upper = lam < np.pi # columns 0 < i < NX/2 (and the pole at i = 0)
|
|
48
|
+
with np.errstate(divide="ignore"):
|
|
49
|
+
tau = np.log(np.abs(1/np.tan(lam/2)))
|
|
50
|
+
frac = np.arange(1, 2*NYC+1)[:, None]/(2*NYC)
|
|
51
|
+
sigma = np.where(upper, -1., 1.)[None, :]*(np.pi/2)*(1. + frac)
|
|
52
|
+
with np.errstate(over="ignore", invalid="ignore"):
|
|
53
|
+
e = np.exp(tau[None, :] + 1j*sigma)
|
|
54
|
+
z = a*(e + 1)/(e - 1)
|
|
55
|
+
z[-1] = a*np.tanh(tau/2) # the fold row, exactly: the same point on both sides
|
|
56
|
+
poles = np.isinf(tau)
|
|
57
|
+
z[:, poles & (tau > 0)] = a # columns through the poles collapse onto the poles
|
|
58
|
+
z[:, poles & (tau < 0)] = -a
|
|
59
|
+
x_c = LON0 + np.rad2deg(np.angle(z))
|
|
60
|
+
y_c = 90. - 2*np.rad2deg(np.arctan(np.abs(z)))
|
|
61
|
+
|
|
62
|
+
x = np.concatenate([x_s, x_c], axis=0)
|
|
63
|
+
y = np.concatenate([y_s, y_c], axis=0)
|
|
64
|
+
return x, y
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def streamfunction(shape, seed=0):
|
|
68
|
+
"""Random streamfunction on the vorticity points of the symmetric grid, single-valued across the fold."""
|
|
69
|
+
psi = np.random.default_rng(seed).standard_normal(shape)
|
|
70
|
+
psi[:, -1] = psi[:, 0]
|
|
71
|
+
twin = (NX - np.arange(NX+1)) % NX
|
|
72
|
+
psi[-1] = 0.5*(psi[-1] + psi[-1, twin])
|
|
73
|
+
return psi
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def tripolar_grid(symmetric):
|
|
77
|
+
x, y = tripolar_supergrid()
|
|
78
|
+
psi = streamfunction(x[::2, ::2].shape)
|
|
79
|
+
u = psi[1:, :] - psi[:-1, :] # (yh, xq)
|
|
80
|
+
v = -(psi[:, 1:] - psi[:, :-1]) # (yq, xh)
|
|
81
|
+
ny = u.shape[0]
|
|
82
|
+
ds = xr.Dataset(
|
|
83
|
+
{"u": (("yh", "xq"), u), "v": (("yq", "xh"), v), "psi": (("yq", "xq"), psi)},
|
|
84
|
+
coords={
|
|
85
|
+
"xh": np.arange(NX) + 0.5, "xq": np.arange(NX+1) + 0.,
|
|
86
|
+
"yh": np.arange(ny) + 0.5, "yq": np.arange(ny+1) + 0.,
|
|
87
|
+
"geolon_c": (("yq", "xq"), x[::2, ::2]), "geolat_c": (("yq", "xq"), y[::2, ::2]),
|
|
88
|
+
"geolon": (("yh", "xh"), x[1::2, 1::2]), "geolat": (("yh", "xh"), y[1::2, 1::2]),
|
|
89
|
+
"geolon_u": (("yh", "xq"), x[1::2, ::2]), "geolat_u": (("yh", "xq"), y[1::2, ::2]),
|
|
90
|
+
"geolon_v": (("yq", "xh"), x[::2, 1::2]), "geolat_v": (("yq", "xh"), y[::2, 1::2]),
|
|
91
|
+
},
|
|
92
|
+
)
|
|
93
|
+
position = "outer"
|
|
94
|
+
if not symmetric:
|
|
95
|
+
# vorticity points to the north-east of tracer points only
|
|
96
|
+
ds = ds.isel(xq=slice(1, None), yq=slice(1, None))
|
|
97
|
+
position = "right"
|
|
98
|
+
return xgcm.Grid(
|
|
99
|
+
ds,
|
|
100
|
+
coords={"X": {"center": "xh", position: "xq"}, "Y": {"center": "yh", position: "yq"}},
|
|
101
|
+
boundary={"X": "periodic", "Y": "extend"},
|
|
102
|
+
autoparse_metadata=False,
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def section_transport(grid, lons, lats):
|
|
107
|
+
i_c, j_c, _, _ = grid_section(grid, lons, lats, topology="MOM-tripolar")
|
|
108
|
+
conv = convergent_transport(grid, i_c, j_c, utr="u", vtr="v", layer=None)
|
|
109
|
+
return float(conv["conv_mass_transport"].sum()), i_c, j_c
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def test_test_grid_is_a_tripolar_grid():
|
|
113
|
+
grid = tripolar_grid(symmetric=True)
|
|
114
|
+
lon, lat = grid._ds.geolon_c.values, grid._ds.geolat_c.values
|
|
115
|
+
top = lat[-1, :NX]
|
|
116
|
+
assert np.allclose(top, top[(NX - np.arange(NX)) % NX]) # the top row folds onto itself
|
|
117
|
+
assert np.argmax(top) in (NX//4, 3*NX//4) and np.isclose(top.max(), 90.)
|
|
118
|
+
assert np.allclose(lat[:, 0][lat[:, 0] >= LAT0], LAT0) # column 0 collapses onto a pole
|
|
119
|
+
v = grid._ds.v.values[-1]
|
|
120
|
+
assert np.allclose(v, -v[::-1]) # flow across the fold is consistent
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@pytest.mark.parametrize("symmetric, offset", [(True, 0), (False, -2)])
|
|
124
|
+
def test_fold_partner_offset(symmetric, offset):
|
|
125
|
+
from sectionate.section import fold_partner_offset
|
|
126
|
+
grid = tripolar_grid(symmetric)
|
|
127
|
+
lon, lat = grid._ds.geolon_c.values, grid._ds.geolat_c.values
|
|
128
|
+
if symmetric:
|
|
129
|
+
lon, lat = lon[:, :-1], lat[:, :-1] # as passed to the path finder: no repeated periodic column
|
|
130
|
+
assert fold_partner_offset(lon, lat) == offset
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@pytest.mark.parametrize("symmetric", [True, False])
|
|
134
|
+
@pytest.mark.parametrize("lat", [61., 65., 70., 75., 80., 85., 88.])
|
|
135
|
+
def test_latitude_circle_across_fold_is_closed(symmetric, lat):
|
|
136
|
+
"""A latitude circle north of the cap's edge crosses the fold twice; zero net transport."""
|
|
137
|
+
grid = tripolar_grid(symmetric)
|
|
138
|
+
lons = np.linspace(3., 363., 37)
|
|
139
|
+
transport, _, _ = section_transport(grid, lons, np.full(lons.size, lat))
|
|
140
|
+
assert abs(transport) < 1.e-10
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
@pytest.mark.parametrize("symmetric", [True, False])
|
|
144
|
+
def test_closed_section_through_fold_points(symmetric):
|
|
145
|
+
"""Waypoints exactly on the fold, reached from both sides of it."""
|
|
146
|
+
grid = tripolar_grid(symmetric)
|
|
147
|
+
lon_c, lat_c = grid._ds.geolon_c.values, grid._ds.geolat_c.values
|
|
148
|
+
lons = [lon_c[-1, 6], LON0 + 150., lon_c[-1, 30], LON0 + 250., lon_c[-1, 6]]
|
|
149
|
+
lats = [lat_c[-1, 6], 72., lat_c[-1, 30], 70., lat_c[-1, 6]]
|
|
150
|
+
transport, _, _ = section_transport(grid, lons, lats)
|
|
151
|
+
assert abs(transport) < 1.e-10
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
@pytest.mark.parametrize("symmetric", [True, False])
|
|
155
|
+
def test_open_section_across_fold(symmetric):
|
|
156
|
+
"""Across the fold and the pole: the transport is the streamfunction difference between the ends."""
|
|
157
|
+
grid = tripolar_grid(symmetric)
|
|
158
|
+
lons, lats = [LON0 + 40., LON0 + 220.], [70., 70.]
|
|
159
|
+
with pytest.warns(UserWarning, match="orientation of open sections"):
|
|
160
|
+
transport, i_c, j_c = section_transport(grid, lons, lats)
|
|
161
|
+
psi = grid._ds.psi.values
|
|
162
|
+
dpsi = psi[j_c[-1], i_c[-1]] - psi[j_c[0], i_c[0]]
|
|
163
|
+
assert abs(dpsi) > 0.1
|
|
164
|
+
assert np.isclose(abs(transport), abs(dpsi), rtol=0., atol=1.e-10)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def test_tripolar_topology_on_grid_without_fold_raises():
|
|
168
|
+
"""A regular latitude-longitude grid has no fold: say so, and say what to use instead."""
|
|
169
|
+
nx, ny = 36, 10
|
|
170
|
+
lon_c, lat_c = np.meshgrid(10.*np.arange(nx+1), -45. + 10.*np.arange(ny+1))
|
|
171
|
+
ds = xr.Dataset(coords={
|
|
172
|
+
"xh": np.arange(nx) + 0.5, "xq": np.arange(nx+1) + 0.,
|
|
173
|
+
"yh": np.arange(ny) + 0.5, "yq": np.arange(ny+1) + 0.,
|
|
174
|
+
"geolon_c": (("yq", "xq"), lon_c), "geolat_c": (("yq", "xq"), lat_c),
|
|
175
|
+
})
|
|
176
|
+
grid = xgcm.Grid(
|
|
177
|
+
ds,
|
|
178
|
+
coords={"X": {"center": "xh", "outer": "xq"}, "Y": {"center": "yh", "outer": "yq"}},
|
|
179
|
+
boundary={"X": "periodic", "Y": "extend"},
|
|
180
|
+
autoparse_metadata=False,
|
|
181
|
+
)
|
|
182
|
+
lons, lats = [20., 120.], [0., 20.]
|
|
183
|
+
with pytest.raises(ValueError, match=r"topology='latlon'.*regionate >= 0\.5\.8.*regionate <= 0\.5\.7"):
|
|
184
|
+
grid_section(grid, lons, lats, topology="MOM-tripolar")
|
|
185
|
+
i_c, _, _, _ = grid_section(grid, lons, lats, topology="latlon")
|
|
186
|
+
assert len(i_c) > 1
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def test_periodic_seam_without_velocity_point_coordinates():
|
|
190
|
+
"""
|
|
191
|
+
Without `geolon_u/v` and `geolat_u/v`, velocity-point coordinates come from the tracer and vorticity
|
|
192
|
+
points. On a non-symmetric grid, the V point at the periodic seam then has to wrap its "X" index.
|
|
193
|
+
"""
|
|
194
|
+
grid = tripolar_grid(symmetric=False)
|
|
195
|
+
ds = grid._ds.drop_vars(["geolon_u", "geolat_u", "geolon_v", "geolat_v"])
|
|
196
|
+
grid = xgcm.Grid(
|
|
197
|
+
ds,
|
|
198
|
+
coords={"X": {"center": "xh", "right": "xq"}, "Y": {"center": "yh", "right": "yq"}},
|
|
199
|
+
boundary={"X": "periodic", "Y": "extend"},
|
|
200
|
+
autoparse_metadata=False,
|
|
201
|
+
)
|
|
202
|
+
lons = np.linspace(3., 363., 37)
|
|
203
|
+
transport, i_c, _ = section_transport(grid, lons, np.full(lons.size, 45.))
|
|
204
|
+
assert {0, NX-1} <= set(i_c.tolist()) # the section does cross the seam
|
|
205
|
+
assert abs(transport) < 1.e-10
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def tripolar_grid_offset_m1():
|
|
209
|
+
"""
|
|
210
|
+
Non-symmetric tripolar grid whose poles sit on tracer-point columns rather than on vorticity points:
|
|
211
|
+
the vorticity points are on the odd columns of the supergrid, so the top-row point i folds onto
|
|
212
|
+
NX - 1 - i and no vorticity point is its own twin.
|
|
213
|
+
"""
|
|
214
|
+
x, y = tripolar_supergrid()
|
|
215
|
+
x, y = x[:, :-1], y[:, :-1] # without the periodic repeat
|
|
216
|
+
lon_c, lat_c = x[::2, 1::2], y[::2, 1::2]
|
|
217
|
+
psi = np.random.default_rng(1).standard_normal(lon_c.shape)
|
|
218
|
+
psi[-1] = 0.5*(psi[-1] + psi[-1, ::-1]) # single-valued across the fold
|
|
219
|
+
u = psi[1:, :] - psi[:-1, :] # (yh, xq): between vorticity points j-1 and j
|
|
220
|
+
v = -(psi - np.roll(psi, 1, axis=1))[1:] # (yq, xh): between vorticity points i-1 and i
|
|
221
|
+
ny = u.shape[0]
|
|
222
|
+
ds = xr.Dataset(
|
|
223
|
+
{"u": (("yh", "xq"), u), "v": (("yq", "xh"), v), "psi": (("yq", "xq"), psi[1:])},
|
|
224
|
+
coords={
|
|
225
|
+
"xh": np.arange(NX) + 0.5, "xq": np.arange(NX) + 1.,
|
|
226
|
+
"yh": np.arange(ny) + 0.5, "yq": np.arange(ny) + 1.,
|
|
227
|
+
"geolon_c": (("yq", "xq"), lon_c[1:]), "geolat_c": (("yq", "xq"), lat_c[1:]),
|
|
228
|
+
"geolon": (("yh", "xh"), x[1::2, ::2]), "geolat": (("yh", "xh"), y[1::2, ::2]),
|
|
229
|
+
"geolon_u": (("yh", "xq"), x[1::2, 1::2]), "geolat_u": (("yh", "xq"), y[1::2, 1::2]),
|
|
230
|
+
"geolon_v": (("yq", "xh"), x[2::2, ::2]), "geolat_v": (("yq", "xh"), y[2::2, ::2]),
|
|
231
|
+
},
|
|
232
|
+
)
|
|
233
|
+
return xgcm.Grid(
|
|
234
|
+
ds,
|
|
235
|
+
coords={"X": {"center": "xh", "right": "xq"}, "Y": {"center": "yh", "right": "yq"}},
|
|
236
|
+
boundary={"X": "periodic", "Y": "extend"},
|
|
237
|
+
autoparse_metadata=False,
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def test_fold_partner_offset_between_vorticity_points():
|
|
242
|
+
from sectionate.section import fold_partner_offset
|
|
243
|
+
grid = tripolar_grid_offset_m1()
|
|
244
|
+
assert fold_partner_offset(grid._ds.geolon_c.values, grid._ds.geolat_c.values) == -1
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
@pytest.mark.parametrize("lat", [65., 75., 85.])
|
|
248
|
+
def test_latitude_circle_across_fold_with_offset_m1(lat):
|
|
249
|
+
grid = tripolar_grid_offset_m1()
|
|
250
|
+
lons = np.linspace(3., 363., 37)
|
|
251
|
+
transport, _, j_c = section_transport(grid, lons, np.full(lons.size, lat))
|
|
252
|
+
assert j_c.max() == grid._ds.yq.size - 1 # the section does reach the fold
|
|
253
|
+
assert abs(transport) < 1.e-10
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def fold_row_section(grid):
|
|
257
|
+
"""A section between two points on opposite sides of the cap, which runs along the fold."""
|
|
258
|
+
i_c, j_c, _, _ = grid_section(grid, [LON0 + 40., LON0 + 220.], [70., 70.], topology="MOM-tripolar")
|
|
259
|
+
return i_c, j_c
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
@pytest.mark.parametrize("make_grid", [
|
|
263
|
+
lambda: tripolar_grid(True), lambda: tripolar_grid(False), lambda: tripolar_grid_offset_m1(),
|
|
264
|
+
], ids=["symmetric", "non-symmetric", "offset -1"])
|
|
265
|
+
def test_tracer_on_fold_row_uses_cell_across_fold(make_grid):
|
|
266
|
+
"""A V point on the fold lies between a top-row cell and the cell across the fold -- not the cell at
|
|
267
|
+
the opposite (southern) edge of the grid."""
|
|
268
|
+
from sectionate.tracers import extract_tracer
|
|
269
|
+
from sectionate.transports import uvindices_from_qindices, uvcoords_from_uvindices
|
|
270
|
+
grid = make_grid()
|
|
271
|
+
grid._ds["tracer"] = (("yh", "xh"), grid._ds.geolat.values) # tracer = latitude
|
|
272
|
+
i_c, j_c = fold_row_section(grid)
|
|
273
|
+
uv = uvindices_from_qindices(grid, i_c, j_c)
|
|
274
|
+
_, lats_uv = uvcoords_from_uvindices(grid, uv)
|
|
275
|
+
on_fold = (uv["var"] == "V") & (lats_uv > grid._ds.geolat.values.max())
|
|
276
|
+
assert on_fold.any() # the section runs along the fold
|
|
277
|
+
tracer = extract_tracer("tracer", grid, i_c, j_c, topology="MOM-tripolar").values
|
|
278
|
+
assert tracer.size == lats_uv.size
|
|
279
|
+
assert np.all(np.abs(tracer - lats_uv) < 1.5) # within a cell of the velocity point
|
|
280
|
+
# without the topology, the top row is an edge of the grid: the one cell below the fold
|
|
281
|
+
edge = extract_tracer("tracer", grid, i_c, j_c).values
|
|
282
|
+
assert np.all(np.abs(edge - lats_uv) < 1.5)
|
|
283
|
+
|
|
284
|
+
# ... and it is the right cell across the fold: the two cells either side of a velocity point on
|
|
285
|
+
# the fold are the two top-row cells whose centres are nearest to it
|
|
286
|
+
from sectionate.section import distance_on_unit_sphere
|
|
287
|
+
values = np.random.default_rng(2).standard_normal(grid._ds.geolat.shape)
|
|
288
|
+
grid._ds["random"] = (("yh", "xh"), values)
|
|
289
|
+
random = extract_tracer("random", grid, i_c, j_c, topology="MOM-tripolar").values
|
|
290
|
+
lons_uv, _ = uvcoords_from_uvindices(grid, uv)
|
|
291
|
+
for k in np.flatnonzero(on_fold):
|
|
292
|
+
d = distance_on_unit_sphere(lons_uv[k], lats_uv[k], grid._ds.geolon.values[-1], grid._ds.geolat.values[-1])
|
|
293
|
+
nearest = np.argsort(d)[:2]
|
|
294
|
+
assert np.isclose(random[k], values[-1, nearest].mean())
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def test_tracer_at_edge_of_grid_uses_interior_cell():
|
|
298
|
+
"""A V point on the southern edge of the grid has one cell next to it; the tracer is that cell's."""
|
|
299
|
+
from sectionate.tracers import extract_tracer
|
|
300
|
+
grid = tripolar_grid(True)
|
|
301
|
+
grid._ds["tracer"] = (("yh", "xh"), grid._ds.geolat.values)
|
|
302
|
+
i_c, j_c = np.array([10, 11, 12]), np.array([0, 0, 0])
|
|
303
|
+
tracer = extract_tracer("tracer", grid, i_c, j_c).values
|
|
304
|
+
assert np.allclose(tracer, grid._ds.geolat.values[0, 10:12])
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import xarray as xr
|
|
3
|
+
from .transports import (
|
|
4
|
+
uvindices_from_qindices
|
|
5
|
+
)
|
|
6
|
+
|
|
7
|
+
from .gridutils import (
|
|
8
|
+
check_symmetric,
|
|
9
|
+
coord_dict,
|
|
10
|
+
get_geo_corners
|
|
11
|
+
)
|
|
12
|
+
from .section import fold_partner_offset
|
|
13
|
+
|
|
14
|
+
def extract_tracer(
|
|
15
|
+
name,
|
|
16
|
+
grid,
|
|
17
|
+
i_c,
|
|
18
|
+
j_c,
|
|
19
|
+
sect_coord="sect",
|
|
20
|
+
topology="latlon"
|
|
21
|
+
):
|
|
22
|
+
"""
|
|
23
|
+
Extract tracer data on cell thickness grid along the grid path
|
|
24
|
+
of (i_c, j_c) for plotting.
|
|
25
|
+
|
|
26
|
+
PARAMETERS:
|
|
27
|
+
-----------
|
|
28
|
+
name:
|
|
29
|
+
name of variable in `grid._ds`
|
|
30
|
+
grid: xgcm.Grid
|
|
31
|
+
grid describing model and containing data
|
|
32
|
+
i_c: int
|
|
33
|
+
vorticity point indices along 'X' dimension
|
|
34
|
+
j_c: int
|
|
35
|
+
vorticity point indices along 'Y' dimension
|
|
36
|
+
sect_coord: str
|
|
37
|
+
Name of the dimension describing along-section data in the output. Default: 'sect'.
|
|
38
|
+
topology: str
|
|
39
|
+
Default: "latlon". Grid topology, as passed to `sectionate.grid_section` when the section was
|
|
40
|
+
created. For "MOM-tripolar", the cell on the far side of a velocity point on the top row of
|
|
41
|
+
vorticity points is the cell across the tripolar fold.
|
|
42
|
+
|
|
43
|
+
RETURNS:
|
|
44
|
+
--------
|
|
45
|
+
|
|
46
|
+
xarray.DataArray with data interpolated to the U and V points along the section: the mean of the
|
|
47
|
+
two tracer cells either side of each velocity point, or the value of the one cell there is if the
|
|
48
|
+
other is missing (NaN) or would lie beyond a non-periodic edge of the grid.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
da=grid._ds[name]
|
|
52
|
+
coords = coord_dict(grid)
|
|
53
|
+
symmetric = check_symmetric(grid)
|
|
54
|
+
|
|
55
|
+
# get indices of UV points from broken line
|
|
56
|
+
uvindices = uvindices_from_qindices(grid, i_c, j_c)
|
|
57
|
+
|
|
58
|
+
section = xr.Dataset()
|
|
59
|
+
section["i"] = xr.DataArray(uvindices["i"], dims=sect_coord)
|
|
60
|
+
section["j"] = xr.DataArray(uvindices["j"], dims=sect_coord)
|
|
61
|
+
section["Umask"] = xr.DataArray(uvindices["var"]=="U", dims=sect_coord)
|
|
62
|
+
section["Vmask"] = xr.DataArray(uvindices["var"]=="V", dims=sect_coord)
|
|
63
|
+
|
|
64
|
+
Xc, Yc = coords["X"]["center"], coords["Y"]["center"]
|
|
65
|
+
nx, ny = da[Xc].size, da[Yc].size
|
|
66
|
+
periodic = {axis: grid.axes[axis]._boundary == "periodic" for axis in ["X", "Y"]}
|
|
67
|
+
|
|
68
|
+
fold_offset = None
|
|
69
|
+
if topology == "MOM-tripolar":
|
|
70
|
+
# Top-row vorticity point i is the same point as (s - i) % nx across the fold. Vorticity points
|
|
71
|
+
# i and i+1 (symmetric) or i-1 and i (non-symmetric) bound tracer cell i, so the cell across
|
|
72
|
+
# the fold from top-row cell i is cell (s - 1 - i) % nx or (s + 1 - i) % nx, respectively.
|
|
73
|
+
geo_corners = get_geo_corners(grid)
|
|
74
|
+
gridlon, gridlat = geo_corners["X"].values, geo_corners["Y"].values
|
|
75
|
+
if symmetric and periodic["X"]:
|
|
76
|
+
gridlon, gridlat = gridlon[:, :-1], gridlat[:, :-1]
|
|
77
|
+
fold_offset = fold_partner_offset(gridlon, gridlat) + (-1 if symmetric else 1)
|
|
78
|
+
|
|
79
|
+
def cell(i, j):
|
|
80
|
+
"""Selector of the tracer cell (j, i), which may lie one cell beyond an edge of the grid."""
|
|
81
|
+
if fold_offset is not None:
|
|
82
|
+
across = j > ny-1
|
|
83
|
+
i = xr.where(across, fold_offset - i, i)
|
|
84
|
+
i = np.mod(i, nx) if periodic["X"] else np.clip(i, 0, nx-1)
|
|
85
|
+
j = np.mod(j, ny) if periodic["Y"] else np.clip(j, 0, ny-1)
|
|
86
|
+
return {Xc: i, Yc: j}
|
|
87
|
+
|
|
88
|
+
increment = 1 if symmetric else 0
|
|
89
|
+
usel_left = cell(section["i"]-increment , section["j"])
|
|
90
|
+
usel_right = cell(section["i"]-increment+1, section["j"])
|
|
91
|
+
vsel_left = cell(section["i"], section["j"]-increment )
|
|
92
|
+
vsel_right = cell(section["i"], section["j"]-increment+1)
|
|
93
|
+
|
|
94
|
+
tracer = sum([
|
|
95
|
+
xr.where(~np.isnan(da.isel(usel_right)), 0.5*da.isel(usel_left), da.isel(usel_left) ).fillna(0.) * section["Umask"],
|
|
96
|
+
xr.where(~np.isnan(da.isel(usel_left )), 0.5*da.isel(usel_right), da.isel(usel_right)).fillna(0.) * section["Umask"],
|
|
97
|
+
xr.where(~np.isnan(da.isel(vsel_right)), 0.5*da.isel(vsel_left), da.isel(vsel_left) ).fillna(0.) * section["Vmask"],
|
|
98
|
+
xr.where(~np.isnan(da.isel(vsel_left )), 0.5*da.isel(vsel_right), da.isel(vsel_right)).fillna(0.) * section["Vmask"],
|
|
99
|
+
])
|
|
100
|
+
tracer = tracer.where(tracer!=0., np.nan)
|
|
101
|
+
tracer.name = da.name
|
|
102
|
+
tracer.attrs = da.attrs
|
|
103
|
+
|
|
104
|
+
return tracer
|
|
@@ -6,12 +6,53 @@ import dask
|
|
|
6
6
|
from .gridutils import check_symmetric, coord_dict, get_geo_corners
|
|
7
7
|
from .section import distance_on_unit_sphere
|
|
8
8
|
|
|
9
|
+
def _face_steps(grid, i_c, j_c, symmetric):
|
|
10
|
+
"""
|
|
11
|
+
Indices k of the steps (i_c[k], j_c[k]) -> (i_c[k+1], j_c[k+1]) that cross a velocity face.
|
|
12
|
+
|
|
13
|
+
A step between adjacent vorticity points crosses one face. A step between two indices of the same
|
|
14
|
+
geographic point (the two sides of a tripolar fold, see `sectionate.section.infer_grid_path`) crosses
|
|
15
|
+
none and is skipped. Any other step does not correspond to a velocity face, and raises an error rather
|
|
16
|
+
than silently picking one.
|
|
17
|
+
"""
|
|
18
|
+
coords = coord_dict(grid)
|
|
19
|
+
periodic = grid.axes["X"]._boundary == "periodic"
|
|
20
|
+
nx = grid._ds[coords["X"]["corner"]].size - (1 if symmetric else 0)
|
|
21
|
+
geo_corners = None
|
|
22
|
+
steps = []
|
|
23
|
+
for k in range(0, len(i_c)-1):
|
|
24
|
+
di = abs(int(i_c[k+1]) - int(i_c[k]))
|
|
25
|
+
if periodic:
|
|
26
|
+
di = min(di % nx, (-di) % nx)
|
|
27
|
+
dj = abs(int(j_c[k+1]) - int(j_c[k]))
|
|
28
|
+
if di + dj == 1:
|
|
29
|
+
steps.append(k)
|
|
30
|
+
continue
|
|
31
|
+
if geo_corners is None:
|
|
32
|
+
geo_corners = {ax: np.asarray(c) for (ax, c) in get_geo_corners(grid).items()}
|
|
33
|
+
lon, lat = geo_corners["X"], geo_corners["Y"]
|
|
34
|
+
d = distance_on_unit_sphere(
|
|
35
|
+
lon[j_c[k], i_c[k]], lat[j_c[k], i_c[k]],
|
|
36
|
+
lon[j_c[k+1], i_c[k+1]], lat[j_c[k+1], i_c[k+1]],
|
|
37
|
+
R=1.
|
|
38
|
+
)
|
|
39
|
+
if d > 1.e-6:
|
|
40
|
+
raise ValueError(
|
|
41
|
+
f"Consecutive section points (j, i) = ({j_c[k]}, {i_c[k]}) and ({j_c[k+1]}, {i_c[k+1]}) "
|
|
42
|
+
"are neither adjacent grid points nor the same point, so they do not define a velocity face."
|
|
43
|
+
)
|
|
44
|
+
return steps
|
|
45
|
+
|
|
9
46
|
def uvindices_from_qindices(grid, i_c, j_c):
|
|
10
47
|
"""
|
|
11
|
-
Find the `grid` indices of the
|
|
48
|
+
Find the `grid` indices of the velocity points defined by the consecutive indices of
|
|
12
49
|
N vorticity points. Follows MOM6 conventions (https://mom6.readthedocs.io/en/main/api/generated/pages/Horizontal_Indexing.html),
|
|
13
50
|
automatically checking `grid` metadata to determine whether the grid is symmetric or non-symmetric.
|
|
14
51
|
|
|
52
|
+
Each step between adjacent vorticity points gives one velocity point. A step between two indices of the
|
|
53
|
+
same point (where a section crosses a tripolar fold) gives none, so for a section that crosses the fold
|
|
54
|
+
there are fewer than N-1 velocity points.
|
|
55
|
+
|
|
15
56
|
PARAMETERS:
|
|
16
57
|
-----------
|
|
17
58
|
grid: xgcm.Grid
|
|
@@ -31,16 +72,16 @@ def uvindices_from_qindices(grid, i_c, j_c):
|
|
|
31
72
|
- "nward" : True if point was passed through while going in positive "j"-index direction
|
|
32
73
|
- "eward" : True if point was passed through while going in positive "i"-index direction
|
|
33
74
|
"""
|
|
34
|
-
|
|
75
|
+
symmetric = check_symmetric(grid)
|
|
76
|
+
steps = _face_steps(grid, i_c, j_c, symmetric)
|
|
35
77
|
uvindices = {
|
|
36
|
-
"var":np.zeros(
|
|
37
|
-
"i":np.zeros(
|
|
38
|
-
"j":np.zeros(
|
|
39
|
-
"nward":np.zeros(
|
|
40
|
-
"eward":np.zeros(
|
|
78
|
+
"var":np.zeros(len(steps), dtype="<U2"),
|
|
79
|
+
"i":np.zeros(len(steps), dtype=np.int64),
|
|
80
|
+
"j":np.zeros(len(steps), dtype=np.int64),
|
|
81
|
+
"nward":np.zeros(len(steps), dtype=bool),
|
|
82
|
+
"eward":np.zeros(len(steps), dtype=bool)
|
|
41
83
|
}
|
|
42
|
-
|
|
43
|
-
for k in range(0, nsec-1):
|
|
84
|
+
for n, k in enumerate(steps):
|
|
44
85
|
zonal = not(j_c[k+1] != j_c[k])
|
|
45
86
|
eward = i_c[k+1] > i_c[k]
|
|
46
87
|
nward = j_c[k+1] > j_c[k]
|
|
@@ -57,12 +98,13 @@ def uvindices_from_qindices(grid, i_c, j_c):
|
|
|
57
98
|
uvindex["i"] += (1 if not(symmetric) and zonal else 0)
|
|
58
99
|
uvindex["j"] += (1 if not(symmetric) and not(zonal) else 0)
|
|
59
100
|
for (key, v) in uvindices.items():
|
|
60
|
-
v[
|
|
101
|
+
v[n] = uvindex[key]
|
|
61
102
|
return uvindices
|
|
62
103
|
|
|
63
104
|
def uvcoords_from_uvindices(grid, uvindices):
|
|
64
105
|
"""
|
|
65
|
-
Find the (lons,lats) coordinates of the
|
|
106
|
+
Find the (lons,lats) coordinates of the velocity points defined by `uvindices` (returned by `uvindices_from_qindices`):
|
|
107
|
+
one for each of them, which is fewer than N-1 for a section of N vorticity points that crosses a tripolar fold.
|
|
66
108
|
Assumes the names of longitude and latitude coordinates in `grid` contain the sub-strings "lon" and "lat", respectively,
|
|
67
109
|
but otherwise finds the names using `grid` metadata.
|
|
68
110
|
|
|
@@ -124,7 +166,7 @@ def uvcoords_from_uvindices(grid, uvindices):
|
|
|
124
166
|
elif (f"geolon_corner" in corner_names) and (f"geolat_center" in center_names):
|
|
125
167
|
lon = ds[corner_names[f"geolon_corner"]].isel({
|
|
126
168
|
coords["X"]["corner"]:i,
|
|
127
|
-
coords["Y"]["corner"]:j
|
|
169
|
+
coords["Y"]["corner"]:wrap_corner_idx(j, grid, "Y")
|
|
128
170
|
}).values
|
|
129
171
|
lat = ds[center_names[f"geolat_center"]].isel({
|
|
130
172
|
coords["X"]["center"]:wrap_idx(i, grid, "X"),
|
|
@@ -148,8 +190,10 @@ def uvcoords_from_uvindices(grid, uvindices):
|
|
|
148
190
|
coords["X"]["center"]:wrap_idx(i, grid, "X"),
|
|
149
191
|
coords["Y"]["center"]:wrap_idx(j, grid, "Y")
|
|
150
192
|
}).values
|
|
193
|
+
# On a non-symmetric grid, the "X" index of a V point at the periodic seam is one past
|
|
194
|
+
# the last vorticity point, so it has to be wrapped before indexing a corner variable.
|
|
151
195
|
lat = ds[corner_names[f"geolat_corner"]].isel({
|
|
152
|
-
coords["X"]["corner"]:i,
|
|
196
|
+
coords["X"]["corner"]:wrap_corner_idx(i, grid, "X"),
|
|
153
197
|
coords["Y"]["corner"]:j
|
|
154
198
|
}).values
|
|
155
199
|
else:
|
|
@@ -176,6 +220,9 @@ def uvcoords_from_qindices(grid, i_c, j_c):
|
|
|
176
220
|
--------
|
|
177
221
|
lons : np.ndarray(float)
|
|
178
222
|
lats : np.ndarray(float)
|
|
223
|
+
One per velocity point, as returned by `uvindices_from_qindices`: N-1 for N vorticity points, or fewer
|
|
224
|
+
if the section crosses a tripolar fold (the crossing point is listed twice and has no velocity point
|
|
225
|
+
between its two indices).
|
|
179
226
|
"""
|
|
180
227
|
return uvcoords_from_uvindices(
|
|
181
228
|
grid,
|
|
@@ -291,8 +338,11 @@ def convergent_transport(
|
|
|
291
338
|
orient_fact = 1 if positive_in else -1
|
|
292
339
|
|
|
293
340
|
coords = coord_dict(grid)
|
|
341
|
+
# `usel` is applied to every point of the section and the V points are masked out afterwards. On a
|
|
342
|
+
# non-symmetric grid, the "X" index of a V point at the periodic seam is one past the last U point,
|
|
343
|
+
# so clip it to a valid index; this never changes the index of a U point.
|
|
294
344
|
usel = {
|
|
295
|
-
coords["X"]["corner"]: sect["i"],
|
|
345
|
+
coords["X"]["corner"]: np.minimum(sect["i"], grid._ds[coords["X"]["corner"]].size-1),
|
|
296
346
|
coords["Y"]["center"]: wrap_idx(sect["j"], grid, "Y")
|
|
297
347
|
}
|
|
298
348
|
vsel = {
|
|
@@ -502,4 +552,23 @@ def wrap_idx(idx, grid, axis):
|
|
|
502
552
|
idx = np.mod(idx, grid._ds[coords[axis]["center"]].size)
|
|
503
553
|
else:
|
|
504
554
|
idx = np.minimum(idx, grid._ds[coords[axis]["center"]].size-1)
|
|
505
|
-
return idx
|
|
555
|
+
return idx
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
def wrap_corner_idx(idx, grid, axis):
|
|
559
|
+
"""
|
|
560
|
+
As `wrap_idx`, but for an index into the corner (vorticity-point) dimension of `axis`, whose size
|
|
561
|
+
differs from that of the center dimension on a symmetric grid.
|
|
562
|
+
|
|
563
|
+
On a periodic non-symmetric grid the index wraps around. On a symmetric grid the corner dimension
|
|
564
|
+
includes the repeated periodic point, so every index that can arise is already valid and is only
|
|
565
|
+
clipped, as on a non-periodic grid.
|
|
566
|
+
"""
|
|
567
|
+
coords = coord_dict(grid)
|
|
568
|
+
n_corner = grid._ds[coords[axis]["corner"]].size
|
|
569
|
+
n_center = grid._ds[coords[axis]["center"]].size
|
|
570
|
+
if (grid.axes[axis]._boundary == "periodic") and (n_corner == n_center):
|
|
571
|
+
idx = np.mod(idx, n_corner)
|
|
572
|
+
else:
|
|
573
|
+
idx = np.minimum(idx, n_corner-1)
|
|
574
|
+
return idx
|
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
import numpy as np
|
|
2
|
-
import xarray as xr
|
|
3
|
-
from .transports import (
|
|
4
|
-
uvindices_from_qindices
|
|
5
|
-
)
|
|
6
|
-
|
|
7
|
-
from .gridutils import (
|
|
8
|
-
check_symmetric,
|
|
9
|
-
coord_dict
|
|
10
|
-
)
|
|
11
|
-
|
|
12
|
-
def extract_tracer(
|
|
13
|
-
name,
|
|
14
|
-
grid,
|
|
15
|
-
i_c,
|
|
16
|
-
j_c,
|
|
17
|
-
sect_coord="sect"
|
|
18
|
-
):
|
|
19
|
-
"""
|
|
20
|
-
Extract tracer data on cell thickness grid along the grid path
|
|
21
|
-
of (i_c, j_c) for plotting.
|
|
22
|
-
|
|
23
|
-
PARAMETERS:
|
|
24
|
-
-----------
|
|
25
|
-
name:
|
|
26
|
-
name of variable in `grid._ds`
|
|
27
|
-
grid: xgcm.Grid
|
|
28
|
-
grid describing model and containing data
|
|
29
|
-
i_c: int
|
|
30
|
-
vorticity point indices along 'X' dimension
|
|
31
|
-
j_c: int
|
|
32
|
-
vorticity point indices along 'Y' dimension
|
|
33
|
-
sect_coord: str
|
|
34
|
-
Name of the dimension describing along-section data in the output. Default: 'sect'.
|
|
35
|
-
|
|
36
|
-
RETURNS:
|
|
37
|
-
--------
|
|
38
|
-
|
|
39
|
-
xarray.DataArray with data interpolated to the U and V points along the section.
|
|
40
|
-
"""
|
|
41
|
-
|
|
42
|
-
da=grid._ds[name]
|
|
43
|
-
coords = coord_dict(grid)
|
|
44
|
-
symmetric = check_symmetric(grid)
|
|
45
|
-
|
|
46
|
-
# get indices of UV points from broken line
|
|
47
|
-
uvindices = uvindices_from_qindices(grid, i_c, j_c)
|
|
48
|
-
|
|
49
|
-
section = xr.Dataset()
|
|
50
|
-
section["i"] = xr.DataArray(uvindices["i"], dims=sect_coord)
|
|
51
|
-
section["j"] = xr.DataArray(uvindices["j"], dims=sect_coord)
|
|
52
|
-
section["Umask"] = xr.DataArray(uvindices["var"]=="U", dims=sect_coord)
|
|
53
|
-
section["Vmask"] = xr.DataArray(uvindices["var"]=="V", dims=sect_coord)
|
|
54
|
-
|
|
55
|
-
increment = 1 if symmetric else 0
|
|
56
|
-
usel_left = {coords["X"]["center"]: np.mod(section["i"]-increment , da[coords["X"]["center"]].size),
|
|
57
|
-
coords["Y"]["center"]: np.mod(section["j"] , da[coords["Y"]["center"]].size)}
|
|
58
|
-
usel_right = {coords["X"]["center"]: np.mod(section["i"]-increment+1, da[coords["X"]["center"]].size),
|
|
59
|
-
coords["Y"]["center"]: np.mod(section["j"] , da[coords["Y"]["center"]].size)}
|
|
60
|
-
|
|
61
|
-
vsel_left = {coords["X"]["center"]: np.mod(section["i"] , da[coords["X"]["center"]].size),
|
|
62
|
-
coords["Y"]["center"]: np.mod(section["j"]-increment , da[coords["Y"]["center"]].size)}
|
|
63
|
-
vsel_right = {coords["X"]["center"]: np.mod(section["i"] , da[coords["X"]["center"]].size),
|
|
64
|
-
coords["Y"]["center"]: np.mod(section["j"]-increment+1, da[coords["Y"]["center"]].size)}
|
|
65
|
-
|
|
66
|
-
tracer = sum([
|
|
67
|
-
xr.where(~np.isnan(da.isel(usel_right)), 0.5*da.isel(usel_left), da.isel(usel_left) ).fillna(0.) * section["Umask"],
|
|
68
|
-
xr.where(~np.isnan(da.isel(usel_left )), 0.5*da.isel(usel_right), da.isel(usel_right)).fillna(0.) * section["Umask"],
|
|
69
|
-
xr.where(~np.isnan(da.isel(vsel_right)), 0.5*da.isel(vsel_left), da.isel(vsel_left) ).fillna(0.) * section["Vmask"],
|
|
70
|
-
xr.where(~np.isnan(da.isel(vsel_left )), 0.5*da.isel(vsel_right), da.isel(vsel_right)).fillna(0.) * section["Vmask"],
|
|
71
|
-
])
|
|
72
|
-
tracer = tracer.where(tracer!=0., np.nan)
|
|
73
|
-
tracer.name = da.name
|
|
74
|
-
tracer.attrs = da.attrs
|
|
75
|
-
|
|
76
|
-
return tracer
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|