diff --git a/docs/developer_guide/api.md b/docs/developer_guide/api.md index f03a900b..88c61196 100644 --- a/docs/developer_guide/api.md +++ b/docs/developer_guide/api.md @@ -76,6 +76,7 @@ imported directly from `pyremap`. Remapper.build_map Remapper.prepare_map + Remapper.finalize_map Remapper.ncremap Remapper.remap_numpy diff --git a/docs/remapper/building_mapping.md b/docs/remapper/building_mapping.md index 0a8bb16e..da14686a 100644 --- a/docs/remapper/building_mapping.md +++ b/docs/remapper/building_mapping.md @@ -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. @@ -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 diff --git a/docs/remapper/smoothing.md b/docs/remapper/smoothing.md index cd2051ad..f6a62aee 100644 --- a/docs/remapper/smoothing.md +++ b/docs/remapper/smoothing.md @@ -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 diff --git a/pyremap/descriptor/utility.py b/pyremap/descriptor/utility.py index 7018a553..1cc93699 100644 --- a/pyremap/descriptor/utility.py +++ b/pyremap/descriptor/utility.py @@ -14,6 +14,7 @@ import numpy as np import pyproj.enums +import xarray as xr from pyproj import Transformer @@ -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 @@ -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""" diff --git a/pyremap/remapper/build_map.py b/pyremap/remapper/build_map.py index c32ce82f..8397d7d0 100644 --- a/pyremap/remapper/build_map.py +++ b/pyremap/remapper/build_map.py @@ -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 @@ -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): """ diff --git a/pyremap/remapper/finalize_map.py b/pyremap/remapper/finalize_map.py new file mode 100644 index 00000000..0ec80430 --- /dev/null +++ b/pyremap/remapper/finalize_map.py @@ -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 diff --git a/pyremap/remapper/remapper.py b/pyremap/remapper/remapper.py index e73e92ce..3130cc26 100644 --- a/pyremap/remapper/remapper.py +++ b/pyremap/remapper/remapper.py @@ -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 @@ -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 @@ -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, diff --git a/tests/test_remapper_expand.py b/tests/test_remapper_expand.py new file mode 100644 index 00000000..2b2052af --- /dev/null +++ b/tests/test_remapper_expand.py @@ -0,0 +1,157 @@ +# This software is open source software available under the BSD-3 license. +# +# Copyright (c) 2025 Triad National Security, LLC. All rights reserved. +# Copyright (c) 2025 Lawrence Livermore National Security, LLC. All rights +# reserved. +# Copyright (c) 2025 UT-Battelle, LLC. All rights reserved. +# +# Additional copyright and license information can be found in the LICENSE file +# distributed with this code, or at +# https://raw.githubusercontent.com/MPAS-Dev/pyremap/main/LICENSE +""" +Tests of mapping files made with expanded destination cells +(``expand_dist``), for lat-lon, projection and MPAS destinations +""" + +import os + +import numpy as np +import pytest +import xarray as xr + +from pyremap import ( + MpasCellMeshDescriptor, + Remapper, + get_lat_lon_descriptor, + get_polar_descriptor, +) +from pyremap.utility import check_call + +MPAS_MESH = os.path.join( + os.path.dirname(__file__), 'test_interpolate', 'mpasMesh.nc' +) + +EXPAND_DIST = 100e3 + + +def _get_dst_descriptor(dst_type): + if dst_type == 'lat_lon': + return get_lat_lon_descriptor(dlon=10.0, dlat=10.0) + if dst_type == 'polar': + return get_polar_descriptor( + lx=6000.0, ly=5000.0, dx=500.0, dy=500.0, projection='antarctic' + ) + return MpasCellMeshDescriptor(MPAS_MESH, mesh_name='oQU240') + + +def _get_remapper(dst_type, map_filename, expand_dist): + remapper = Remapper( + ntasks=1, + method='conserve', + map_filename=map_filename, + src_descriptor=get_lat_lon_descriptor(dlon=2.0, dlat=2.0), + dst_descriptor=_get_dst_descriptor(dst_type), + use_tmp=False, + ) + remapper.expand_dist = expand_dist + return remapper + + +@pytest.mark.parametrize('dst_type', ['lat_lon', 'polar', 'mpas']) +def test_expanded_map_has_true_dst_grid(tmp_path, monkeypatch, dst_type): + """ + A map with expanded destination cells can be built, and describes the + true destination grid, with only its weights differing from a map + without expansion + """ + monkeypatch.chdir(tmp_path) + + plain = _get_remapper(dst_type, 'map_plain.nc', expand_dist=None) + plain.build_map() + expanded = _get_remapper(dst_type, 'map_expanded.nc', EXPAND_DIST) + expanded.build_map() + + with ( + xr.open_dataset('map_plain.nc') as ds_plain, + xr.open_dataset('map_expanded.nc') as ds_expanded, + ): + np.testing.assert_array_equal( + ds_expanded.dst_grid_dims.values, ds_plain.dst_grid_dims.values + ) + for var in ['xc_b', 'yc_b', 'xv_b', 'yv_b']: + np.testing.assert_allclose( + ds_expanded[var].values, ds_plain[var].values, atol=1e-10 + ) + np.testing.assert_allclose( + ds_expanded.area_b.values, ds_plain.area_b.values, rtol=1e-6 + ) + # the expansion is in the weights + assert ds_expanded.sizes['n_s'] > ds_plain.sizes['n_s'] + + ds = xr.Dataset() + src_descriptor = expanded.src_descriptor + ds['field'] = (src_descriptor.dims, np.ones(src_descriptor.dim_sizes)) + for dim, coord in src_descriptor.coords.items(): + ds.coords[dim] = (coord['dims'], coord['data']) + remapped = expanded.remap_numpy(ds) + assert list(remapped.field.dims) == expanded.dst_descriptor.dims + valid = remapped.field.notnull() + assert valid.any() + np.testing.assert_allclose(remapped.field.values[valid.values], 1.0) + + +def test_expanded_lat_lon_ncremap(tmp_path, monkeypatch): + """ + ncremap with a map with expanded lat-lon destination cells writes the + same grid as without expansion + """ + monkeypatch.chdir(tmp_path) + + for name, expand_dist in [('plain', None), ('expanded', EXPAND_DIST)]: + remapper = _get_remapper('lat_lon', f'map_{name}.nc', expand_dist) + remapper.build_map() + if name == 'plain': + src_descriptor = remapper.src_descriptor + ds = xr.Dataset() + ds['field'] = ( + src_descriptor.dims, + np.ones(src_descriptor.dim_sizes), + ) + for dim, coord in src_descriptor.coords.items(): + ds.coords[dim] = (coord['dims'], coord['data'], coord['attrs']) + ds.to_netcdf('in.nc') + remapper.ncremap('in.nc', f'out_{name}.nc') + + with ( + xr.open_dataset('out_plain.nc') as ds_plain, + xr.open_dataset('out_expanded.nc') as ds_expanded, + ): + assert ds_expanded.field.dims == ds_plain.field.dims + for var in ['lat', 'lon', 'lat_bnds', 'lon_bnds', 'area']: + np.testing.assert_allclose( + ds_expanded[var].values, ds_plain[var].values, rtol=1e-6 + ) + + +def test_prepare_then_finalize_matches_build(tmp_path, monkeypatch): + """ + Running the command from prepare_map() and then finalize_map() gives + the same mapping file as build_map() + """ + monkeypatch.chdir(tmp_path) + + built = _get_remapper('lat_lon', 'map_built.nc', EXPAND_DIST) + built.build_map() + + prepared = _get_remapper('lat_lon', 'map_prepared.nc', EXPAND_DIST) + check_call(prepared.prepare_map()) + prepared.finalize_map() + + with ( + xr.open_dataset('map_built.nc') as ds_built, + xr.open_dataset('map_prepared.nc') as ds_prepared, + ): + for var in ['dst_grid_dims', 'xv_b', 'yv_b', 'area_b', 'S']: + np.testing.assert_array_equal( + ds_prepared[var].values, ds_built[var].values + )