Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/developer_guide/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ imported directly from `pyremap`.

Remapper.build_map
Remapper.prepare_map
Remapper.finalize_map

Remapper.ncremap
Remapper.remap_numpy
Expand Down
7 changes: 7 additions & 0 deletions docs/remapper/building_mapping.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ tool.
- `prepare_map`: Write the files the mapping tool needs and return the
command that builds the mapping file, without running it. This is for
workflows that launch the tool themselves (see below).
- `finalize_map`: Finish a mapping file made by the command from
`prepare_map()`. `build_map()` calls it itself.

## Attributes
- `map_filename`: The name of the file where the mapping weights will be saved.
Expand Down Expand Up @@ -78,8 +80,13 @@ remapper.src_from_mpas("mesh.nc", mesh_name="oQU240")
remapper.dst_global_lon_lat(dlon=0.5, dlat=0.5)
args = remapper.prepare_map()
subprocess.check_call(["srun", "-n", "64"] + args)
remapper.finalize_map()
```

`finalize_map()` only changes the mapping file when `expand_dist` or
`expand_factor` is set (see [Smoothing](smoothing.md)), but calling it every
time means a workflow keeps working if smoothing is added later.

```{note}
For 1D lat/lon grids, whether a grid is treated as regional or global is
governed by longitude periodicity. Latitude extent does not force a grid to be
Expand Down
4 changes: 2 additions & 2 deletions docs/remapper/smoothing.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ These attributes are particularly useful for producing highly controlled smoothi

The `expand_dist` and `expand_factor` attributes must be used in combination with the `conserve` remapping method. This is because they leverage the area-weighted interpolation mechanism inherent to this method.

## Unstructured Destination Meshes
## Destination Grids

Expanded cells no longer share corners with their neighbors, so with ESMF, smoothing works only when the destination is an unstructured mesh such as an MPAS mesh. `ESMF_RegridWeightGen` fails for expanded logically rectangular grids such as lat-lon and projection grids.
Smoothing works for any destination grid: MPAS meshes, lat-lon grids and projection grids. Expanded cells no longer share corners with their neighbors, so a lat-lon or projection grid is given to the mapping tool as unstructured. Once the mapping file is made, `finalize_map()` puts the true shape, corners and cell areas of the destination grid back in it, so only the weights reflect the expansion and output from `remap_numpy()` and `ncremap()` is on the destination grid as usual. `build_map()` calls `finalize_map()` itself; if you run the command from `prepare_map()`, call `finalize_map()` afterwards.

## Example
```python
Expand Down
14 changes: 14 additions & 0 deletions pyremap/descriptor/utility.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import numpy as np
import pyproj.enums
import xarray as xr
from pyproj import Transformer


Expand Down Expand Up @@ -322,6 +323,9 @@ def expand_scrip(ds, expand_dist, expand_factor):
"""
Expand the vertices of cells outward from the center of the cell

A grid of rank 2 is written as unstructured (rank 1), since expanded
neighboring cells no longer share corners.

Parameters
----------
ds : xarray.Dataset
Expand Down Expand Up @@ -394,6 +398,16 @@ def expand_scrip(ds, expand_dist, expand_factor):
ds['grid_corner_lon'] = (('grid_size', 'grid_corners'), grid_corner_lon)
ds.grid_corner_lon.attrs = attrs

if ds.sizes.get('grid_rank', 1) > 1:
# mapping tools read a grid of rank 2 as logically rectangular, with
# neighboring cells sharing corners, which expanded cells no longer
# do, so describe it as unstructured. Remapper.finalize_map() puts
# the shape of the grid back in the mapping file.
del ds['grid_dims']
ds['grid_dims'] = xr.DataArray(
[grid_size], dims=('grid_rank',)
).astype('int32')


def unwrap_corners(in_field):
"""Turn a 2D array of corners into an array of rectangular mesh elements"""
Expand Down
3 changes: 3 additions & 0 deletions pyremap/remapper/build_map.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import os
from tempfile import TemporaryDirectory

from pyremap.remapper.finalize_map import _finalize_map
from pyremap.remapper.setup import _setup_remapper
from pyremap.utility import check_call

Expand All @@ -24,6 +25,8 @@ def _build_map(remapper, logger=None):
args = _write_files_and_get_args(remapper, '', logger)
_run_map_tool(remapper, args, logger)

_finalize_map(remapper)


def _prepare_map(remapper, logger=None):
"""
Expand Down
132 changes: 132 additions & 0 deletions pyremap/remapper/finalize_map.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import os
from tempfile import TemporaryDirectory

import netCDF4
import numpy as np
import xarray as xr

from pyremap.remapper.setup import _setup_remapper
from pyremap.utility import write_netcdf


def _finalize_map(remapper):
"""
Give a mapping file made with expanded destination cells the true
destination grid

Parameters
----------
remapper : pyremap.Remapper
The remapper whose mapping file to finalize
"""
if remapper.expand_dist is None and remapper.expand_factor is None:
return

_setup_remapper(remapper)

# weights loaded by remap_numpy() are from the file being rewritten
remapper._ds_map = None
remapper._matrix = None

map_filename = remapper.map_filename

with TemporaryDirectory() as tmp_dir:
scrip_filename = os.path.join(tmp_dir, 'dst_mesh.nc')
remapper.dst_descriptor.to_scrip(scrip_filename)
with xr.open_dataset(scrip_filename) as ds_scrip:
ds_scrip = ds_scrip.load()

with netCDF4.Dataset(map_filename) as nc:
file_format = nc.data_model
with xr.open_dataset(map_filename) as ds_map:
ds_map = ds_map.load()

ds_map = _replace_dst_grid(ds_map, ds_scrip)

write_netcdf(ds_map, map_filename, format=file_format)


def _replace_dst_grid(ds_map, ds_scrip):
"""
Replace the destination grid's shape, corners and (for conservative
maps) cell areas in a mapping file with those from a SCRIP file of the
unexpanded destination grid
"""
grid_dims = ds_scrip.grid_dims.values.astype(ds_map.dst_grid_dims.dtype)
corner_lat = _to_units(
ds_scrip.grid_corner_lat, ds_map.yv_b.attrs.get('units', 'degrees')
)
corner_lon = _to_units(
ds_scrip.grid_corner_lon, ds_map.xv_b.attrs.get('units', 'degrees')
)

# the ranks and numbers of corners may differ from the expanded grid,
# so drop the variables (and with them, their dimensions) and add them
# back
replaced = {
'dst_grid_dims': (('dst_grid_rank',), grid_dims, {}),
'yv_b': (('n_b', 'nv_b'), corner_lat, ds_map.yv_b.attrs),
'xv_b': (('n_b', 'nv_b'), corner_lon, ds_map.xv_b.attrs),
}
# area_b is zero for methods that don't compute areas
if np.any(ds_map.area_b.values != 0.0):
area = _spherical_polygon_area(
ds_scrip.grid_corner_lat.values,
ds_scrip.grid_corner_lon.values,
radians='rad' in ds_scrip.grid_corner_lat.attrs['units'],
)
replaced['area_b'] = (('n_b',), area, ds_map.area_b.attrs)

ds_map = ds_map.drop_vars(list(replaced))
for var, (dims, values, attrs) in replaced.items():
ds_map[var] = xr.DataArray(values, dims=dims, attrs=dict(attrs))
return ds_map


def _to_units(da, units):
"""Convert a SCRIP field in degrees or radians to the given units"""
values = da.values
in_radians = 'rad' in da.attrs['units']
out_radians = 'rad' in units
if in_radians and not out_radians:
values = np.rad2deg(values)
elif out_radians and not in_radians:
values = np.deg2rad(values)
return values


def _spherical_polygon_area(corner_lat, corner_lon, radians):
"""
The area of each cell on the unit sphere, for cells whose corners are
joined by great circles, as ESMF computes them

Each cell is split into triangles that fan out from its first corner.
A corner repeated to pad a cell with fewer corners than the array has
gives a triangle of zero area.
"""
if not radians:
corner_lat = np.deg2rad(corner_lat)
corner_lon = np.deg2rad(corner_lon)
xyz = np.stack(
[
np.cos(corner_lat) * np.cos(corner_lon),
np.cos(corner_lat) * np.sin(corner_lon),
np.sin(corner_lat),
],
axis=-1,
)
a = xyz[:, 0, :]
area = np.zeros(xyz.shape[0])
for index in range(1, xyz.shape[1] - 1):
b = xyz[:, index, :]
c = xyz[:, index + 1, :]
# the solid angle of the triangle (Van Oosterom and Strackee, 1983)
triple = np.einsum('ij,ij->i', a, np.cross(b, c))
denom = (
1.0
+ np.einsum('ij,ij->i', a, b)
+ np.einsum('ij,ij->i', b, c)
+ np.einsum('ij,ij->i', c, a)
)
area += 2.0 * np.arctan2(np.abs(triple), denom)
return area
18 changes: 18 additions & 0 deletions pyremap/remapper/remapper.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from pyremap.remapper.build_map import _build_map, _prepare_map
from pyremap.remapper.finalize_map import _finalize_map
from pyremap.remapper.ncremap import _ncremap
from pyremap.remapper.remap_numpy import _remap_numpy
from pyremap.remapper.setup import _setup_remapper
Expand Down Expand Up @@ -447,6 +448,9 @@ def prepare_map(self, logger=None):
``use_tmp`` must be False, because the mapping tool reads the files
after this method returns.

Call :py:meth:`finalize_map()` once the command has made the mapping
file.

Parameters
----------
logger : logging.Logger, optional
Expand All @@ -460,6 +464,20 @@ def prepare_map(self, logger=None):
"""
return _prepare_map(self, logger=logger)

def finalize_map(self):
"""
Finish a mapping file made by the command from
:py:meth:`prepare_map()`. :py:meth:`build_map()` calls this itself.

With ``expand_dist`` or ``expand_factor``, the mapping tool sees
expanded destination cells, and grids of rank 2 (lat-lon and
projection grids) as unstructured. This puts the shape, corners
and (for conservative maps) cell areas of the true destination grid
in the mapping file, so only the weights reflect the expansion.
Without expansion, it does nothing.
"""
_finalize_map(self)

def ncremap(
self,
in_filename,
Expand Down
Loading
Loading