|
| 1 | +# Copyright Iris contributors |
| 2 | +# |
| 3 | +# This file is part of Iris and is released under the LGPL license. |
| 4 | +# See COPYING and COPYING.LESSER in the root of the repository for full |
| 5 | +# licensing details. |
| 6 | +""" |
| 7 | +Adds a UGRID extension layer to netCDF file loading. |
| 8 | +
|
| 9 | +""" |
| 10 | +from collections import namedtuple |
| 11 | +import os |
| 12 | + |
| 13 | +import netCDF4 |
| 14 | + |
| 15 | +from gridded.pyugrid.ugrid import UGrid |
| 16 | +from gridded.pyugrid.read_netcdf import ( |
| 17 | + find_mesh_names, |
| 18 | + load_grid_from_nc_dataset, |
| 19 | +) |
| 20 | +from iris.fileformats.cf import CFReader |
| 21 | + |
| 22 | + |
| 23 | +_UGRID_ELEMENT_TYPE_NAMES = ("node", "edge", "face", "volume") |
| 24 | + |
| 25 | +# Generate all possible UGRID structural property names. |
| 26 | +# These are the UGRID mesh properties that contain variable names for linkage, |
| 27 | +# which may appear as recognised properties of the main mesh variable. |
| 28 | + |
| 29 | +# Start with coordinate variables for each element type (aka "mesh_location"). |
| 30 | +_UGRID_LINK_PROPERTIES = [ |
| 31 | + "{}_coordinates".format(elem) for elem in _UGRID_ELEMENT_TYPE_NAMES |
| 32 | +] |
| 33 | + |
| 34 | +# Add in all possible type-to-type_connectivity elements. |
| 35 | +# NOTE: this actually generates extra unused names, such as |
| 36 | +# "node_face_connectivity", because we are not bothering to distinguish |
| 37 | +# between lower- and higher-order elements. |
| 38 | +# For now just don't worry about that, as long as we get all the ones which |
| 39 | +# *are* needed. |
| 40 | +_UGRID_LINK_PROPERTIES += [ |
| 41 | + "{}_{}_connectivity".format(e1, e2) |
| 42 | + for e1 in _UGRID_ELEMENT_TYPE_NAMES |
| 43 | + for e2 in _UGRID_ELEMENT_TYPE_NAMES |
| 44 | +] |
| 45 | + |
| 46 | +# Also allow for boundary information. |
| 47 | +_UGRID_LINK_PROPERTIES += ["boundary_node_connectivity"] |
| 48 | + |
| 49 | + |
| 50 | +class CubeUgrid( |
| 51 | + namedtuple("CubeUgrid", ["cube_dim", "grid", "mesh_location"]) |
| 52 | +): |
| 53 | + """ |
| 54 | + Object recording the unstructured grid dimension of a cube. |
| 55 | +
|
| 56 | + * cube_dim (int): |
| 57 | + The cube dimension which maps the unstructured grid. |
| 58 | + There can be only one. |
| 59 | +
|
| 60 | + * grid (`gridded.pyugrid.UGrid`): |
| 61 | + A 'gridded' description of a UGRID mesh. |
| 62 | +
|
| 63 | + * mesh_location (str): |
| 64 | + Which element of the mesh the cube is mapped to. |
| 65 | + Can be 'face', 'edge' or 'node'. A 'volume' is not supported. |
| 66 | +
|
| 67 | + """ |
| 68 | + |
| 69 | + def __str__(self): |
| 70 | + result = "Cube unstructured-grid dimension:" |
| 71 | + result += "\n cube dimension = {}".format(self.cube_dim) |
| 72 | + result += '\n mesh_location = "{}"'.format(self.mesh_location) |
| 73 | + result += '\n mesh "{}" :\n'.format(self.grid.mesh_name) |
| 74 | + try: |
| 75 | + mesh_str = str(self.grid.info) |
| 76 | + except TypeError: |
| 77 | + mesh_str = "<unprintable mesh>" |
| 78 | + result += "\n".join([" " + line for line in mesh_str.split("\n")]) |
| 79 | + result += "\n" |
| 80 | + return result |
| 81 | + |
| 82 | + |
| 83 | +class UGridCFReader: |
| 84 | + """ |
| 85 | + A CFReader extension to add UGRID information to netcdf cube loading. |
| 86 | +
|
| 87 | + Identifies UGRID-specific parts of a netcdf file, providing: |
| 88 | +
|
| 89 | + * `self.cfreader` : a CFReader object to interpret the CF data from the |
| 90 | + file for cube creation, while ignoring the UGRID mesh data. |
| 91 | +
|
| 92 | + * `self.complete_ugrid_cube(cube)` a call to add the relevant UGRID |
| 93 | + information to a cube created from the cfreader data. |
| 94 | +
|
| 95 | + This allows us to decouple UGRID from CF support with minimal changes to |
| 96 | + the existing `iris.fileformats.netcdf` code, which is intimately coupled to |
| 97 | + both the CFReader class and the netCDF4 file interface. |
| 98 | +
|
| 99 | + """ |
| 100 | + |
| 101 | + def __init__(self, filename, *args, **kwargs): |
| 102 | + self.filename = os.path.expanduser(filename) |
| 103 | + dataset = netCDF4.Dataset(self.filename, mode="r") |
| 104 | + self.dataset = dataset |
| 105 | + meshes = {} |
| 106 | + for meshname in find_mesh_names(self.dataset): |
| 107 | + mesh = UGrid() |
| 108 | + load_grid_from_nc_dataset(dataset, mesh, mesh_name=meshname) |
| 109 | + meshes[meshname] = mesh |
| 110 | + self.meshes = meshes |
| 111 | + |
| 112 | + # Generate list of excluded variable names. |
| 113 | + exclude_vars = list(meshes.keys()) |
| 114 | + |
| 115 | + temp_xios_fix = kwargs.pop("temp_xios_fix", False) |
| 116 | + if not temp_xios_fix: |
| 117 | + # This way *ought* to work, but maybe problems with the test file ? |
| 118 | + for mesh in meshes.values(): |
| 119 | + mesh_var = dataset.variables[mesh.mesh_name] |
| 120 | + for attr in mesh_var.ncattrs(): |
| 121 | + if attr in _UGRID_LINK_PROPERTIES: |
| 122 | + exclude_vars.extend(mesh_var.getncattr(attr).split()) |
| 123 | + else: |
| 124 | + # A crude and XIOS-specific alternative .. |
| 125 | + exclude_vars += [ |
| 126 | + name |
| 127 | + for name in dataset.variables.keys() |
| 128 | + if any(name.startswith(meshname) for meshname in meshes.keys()) |
| 129 | + ] |
| 130 | + |
| 131 | + # Identify possible mesh dimensions and make a map of them. |
| 132 | + meshdims_map = {} # Maps {dimension-name: (mesh, mesh-location)} |
| 133 | + for mesh in meshes.values(): |
| 134 | + mesh_var = dataset.variables[mesh.mesh_name] |
| 135 | + if mesh.faces is not None: |
| 136 | + # Work out name of faces dimension and record it. |
| 137 | + if "face_dimension" in mesh_var.ncattrs(): |
| 138 | + faces_dim_name = mesh_var.getncattr("face_dimension") |
| 139 | + else: |
| 140 | + # Assume default dimension ordering, and get the dim name |
| 141 | + # from dims of a non-optional connectivity variable. |
| 142 | + faces_varname = mesh_var.face_node_connectivity |
| 143 | + faces_var = dataset.variables[faces_varname] |
| 144 | + faces_dim_name = faces_var.dimensions[0] |
| 145 | + meshdims_map[faces_dim_name] = (mesh, "face") |
| 146 | + if mesh.edges is not None: |
| 147 | + # Work out name of edges dimension and record it. |
| 148 | + if "edge_dimension" in mesh_var.ncattrs(): |
| 149 | + edges_dim_name = mesh_var.getncattr("edge_dimension") |
| 150 | + else: |
| 151 | + # Assume default dimension ordering, and get the dim name |
| 152 | + # from dims of a non-optional connectivity variable. |
| 153 | + edges_varname = mesh_var.edge_node_connectivity |
| 154 | + edges_var = dataset.variables[edges_varname] |
| 155 | + edges_dim_name = edges_var.dimensions[0] |
| 156 | + meshdims_map[edges_dim_name] = (mesh, "edge") |
| 157 | + if mesh.nodes is not None: |
| 158 | + # Work out name of nodes dimension and record it. |
| 159 | + # Get it from a non-optional coordinate variable. |
| 160 | + nodes_varname = mesh_var.node_coordinates.split()[0] |
| 161 | + nodes_var = dataset.variables[nodes_varname] |
| 162 | + nodes_dim_name = nodes_var.dimensions[0] |
| 163 | + meshdims_map[nodes_dim_name] = (mesh, "node") |
| 164 | + self.meshdims_map = meshdims_map |
| 165 | + |
| 166 | + # Create a CFReader object which skips the UGRID-related variables. |
| 167 | + kwargs["exclude_var_names"] = exclude_vars |
| 168 | + self.cfreader = CFReader(self.dataset, *args, **kwargs) |
| 169 | + |
| 170 | + def complete_ugrid_cube(self, cube): |
| 171 | + """ |
| 172 | + Add the ".ugrid" property to a cube loaded with the `self.cfreader`. |
| 173 | +
|
| 174 | + We identify the unstructured-grid dimension of the cube (if any), and |
| 175 | + attach a suitable CubeUgrid object, linking the cube mesh dimension to |
| 176 | + an element-type (aka "mesh_location") of a mesh. |
| 177 | +
|
| 178 | + """ |
| 179 | + # Set a 'cube.ugrid' property. |
| 180 | + data_var = self.dataset.variables[cube.var_name] |
| 181 | + meshes_info = [ |
| 182 | + (i_dim, self.meshdims_map.get(dim_name)) |
| 183 | + for i_dim, dim_name in enumerate(data_var.dimensions) |
| 184 | + if dim_name in self.meshdims_map |
| 185 | + ] |
| 186 | + if len(meshes_info) > 1: |
| 187 | + msg = "Cube maps more than one mesh dimension: {}" |
| 188 | + raise ValueError(msg.format(meshes_info)) |
| 189 | + if meshes_info: |
| 190 | + i_dim, (mesh, mesh_location) = meshes_info[0] |
| 191 | + cube.ugrid = CubeUgrid( |
| 192 | + cube_dim=i_dim, grid=mesh, mesh_location=mesh_location |
| 193 | + ) |
| 194 | + else: |
| 195 | + # Add an empty 'cube.ugrid' to all cubes otherwise. |
| 196 | + cube.ugrid = None |
| 197 | + return |
| 198 | + |
| 199 | + def __del__(self): |
| 200 | + # Explicitly close dataset to prevent file remaining open. |
| 201 | + self.dataset.close() |
0 commit comments