Skip to content

ugrid

Working with UGRID standard for unstrctured grids.

Functions:

as_ugrid

as_ugrid(ds: Dataset | DataArray) -> ux.UxDataset

Convert dataset DYNAMICO icosahedral grid to UGRID standard.

The conversion assumes several variable, dimension, and coordinate names are present. The result is an uxarray dataset holding the orginal data with the UGRID grid.

Example:

from ipsl_common.ugrid import as_ugrid
import xarray as xa
import cartopy.crs as ccrs
import matplotlib.pyplot as plt

ds = xa.open_dataset("start0.nc")
uxds = as_ugrid(ds)
fig, ax = plt.subplots(
    subplot_kw={"projection": ccrs.EqualEarth()},
    figsize=(9, 6),
    constrained_layout=True,
)
ax.set_global()
raster = uxds["tracer001"][0].to_raster(ax=ax)
img = ax.imshow(
    raster, cmap="viridis", origin="lower", extent=ax.get_xlim() + ax.get_ylim()
)
ax.coastlines()
cbar = fig.colorbar(img, ax=ax, fraction=0.03)
plt.show()

Parameters:

  • ds

    (Dataset | DataArray) –

    input xarray dataset

Returns:

  • UxDataset –

    ux.UxDataset: dataset with original data redefined on the UGRID grid

Source code in ipsl_common/ugrid.py
 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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
def as_ugrid(ds: xa.Dataset | xa.DataArray) -> ux.UxDataset:
    """Convert dataset DYNAMICO icosahedral grid to UGRID standard.

    The conversion assumes several variable, dimension, and coordinate names are present.
    The result is an uxarray dataset holding the orginal data with the UGRID grid.

    Example:

        from ipsl_common.ugrid import as_ugrid
        import xarray as xa
        import cartopy.crs as ccrs
        import matplotlib.pyplot as plt

        ds = xa.open_dataset("start0.nc")
        uxds = as_ugrid(ds)
        fig, ax = plt.subplots(
            subplot_kw={"projection": ccrs.EqualEarth()},
            figsize=(9, 6),
            constrained_layout=True,
        )
        ax.set_global()
        raster = uxds["tracer001"][0].to_raster(ax=ax)
        img = ax.imshow(
            raster, cmap="viridis", origin="lower", extent=ax.get_xlim() + ax.get_ylim()
        )
        ax.coastlines()
        cbar = fig.colorbar(img, ax=ax, fraction=0.03)
        plt.show()

    Args:
        ds: input xarray dataset

    Returns:
        ux.UxDataset: dataset with original data redefined on the UGRID grid
    """
    ico = match_dynamico_icosahedral_grid(ds)
    if ico is None:
        raise ValueError(
            "Not a DYNAMICO icosahedral grid. Couldn't match variables, dimensions and coordinates."
        )
    # Rename dimensions and coordinates to match the UGRID convention
    ds = ds.rename(
        {
            ico["n_face"]: "n_face",
            ico["face_lat"]: "face_lat",
            ico["face_lon"]: "face_lon",
            ico["n_max_face_nodes"]: "n_max_face_nodes",
        }
    )
    # Retrieve lat-lon coordinates of all nodes from face bounds
    lats = ds[ico["node_lat"]].values.ravel()
    lons = ds[ico["node_lon"]].values.ravel()
    # Find only unique node lat-lon coordinates
    uniqe_node_coords = np.unique(
        np.column_stack((lats, lons)),
        axis=0,
    )
    # Create UGRID standarized variables for node lat-lon coordinates
    ds["node_lat"] = (("n_node",), uniqe_node_coords[:, 0])
    ds["node_lon"] = (("n_node",), uniqe_node_coords[:, 1])
    # Assign numerical ID [0..(n_node-1)] to each node lat-lon coordinate
    node_coords_to_id = {tuple(c): i for i, c in enumerate(uniqe_node_coords, start=0)}
    # Convert all face node coordinates (up to x6 par face) into node IDs as required by the UGRID
    face_node_connectivity = np.array(
        [
            node_coords_to_id[(x, y)]
            for x, y in zip(
                lats,
                lons,
            )
        ]
    ).reshape(ds[ico["node_lat"]].shape)
    # Create variable holding entries with nodes forming particular faces (penta-/hexagons)
    ds["face_node_connectivity"] = (
        ("n_face", "n_max_face_nodes"),
        face_node_connectivity,
        {
            "cf_role": "face_node_connectivity",
            "start_index": 0,
        },
    )
    # Create meta variable for storing UGRID-required attributes
    ds["mesh"] = xa.DataArray(
        0,
        attrs={
            "cf_role": "mesh_topology",
            "topology_dimension": 2,
            "node_coordinates": "node_lon node_lat",
            "face_node_connectivity": "face_node_connectivity",
        },
    )
    # Open grid from the modified dataset
    grid = ux.open_grid(ds)
    # Return uxarray dataset combining the classical xarray dataset with uxgrid
    return ux.UxDataset(ds, uxgrid=grid)

match_dynamico_icosahedral_grid

match_dynamico_icosahedral_grid(
    ds: Dataset | DataArray,
) -> dict | None

Match dataset variables, dimensions and coordinates to a specific DYNAMICO icosahedral grid.

The same DYNAMICO grid might be expressed by different variables, dimensions and coordinates. This function tries to match the grid to known, predefined names.

Parameters:

  • ds

    (Dataset | DataArray) –

    input xarray dataset

Returns:

  • dict | None –

    dict | None: mapping of element names to UGRID names, or None if not a DYNAMICO grid

Source code in ipsl_common/ugrid.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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
def match_dynamico_icosahedral_grid(ds: xa.Dataset | xa.DataArray) -> dict | None:
    """Match dataset variables, dimensions and coordinates to a specific DYNAMICO icosahedral grid.

    The same DYNAMICO grid might be expressed by different variables, dimensions and coordinates.
    This function tries to match the grid to known, predefined names.

    Args:
        ds: input xarray dataset

    Returns:
        dict | None: mapping of element names to UGRID names, or None if not a DYNAMICO grid
    """
    grid_types = {
        # Created by XIOS, observed in some standard DYNAMICO tests and coupled
        # configurations.
        "v1": {
            "node_lat": "bounds_lat_mesh",
            "node_lon": "bounds_lon_mesh",
            "face_lat": "lat_mesh",
            "face_lon": "lon_mesh",
            "n_face": "cell_mesh",
            "n_max_face_nodes": "nvertex_mesh",
        },
        # Created by XIOS in coupled MODIPSL configurations, like ICOLMDZISO
        # used in e.g. histmth, histday files.
        "v2": {
            "node_lat": "bounds_lat",
            "node_lon": "bounds_lon",
            "face_lat": "lat",
            "face_lon": "lon",
            "n_face": "cell",
            "n_max_face_nodes": "nvertex",
        },
    }
    for mapping in grid_types.values():
        if _contains_elements(
            ds,
            required_vars=select_values_by_keys(mapping, "node_lat", "node_lon"),
            required_dims=select_values_by_keys(mapping, "n_face", "n_max_face_nodes"),
            required_coords=select_values_by_keys(mapping, "face_lat", "face_lon"),
        ):
            return mapping
    return None