Convert an Iris cube into a DataArray
(cube)
| 155 | |
| 156 | |
| 157 | def from_iris(cube): |
| 158 | """Convert an Iris cube into a DataArray""" |
| 159 | import iris.exceptions |
| 160 | |
| 161 | name = _name(cube) |
| 162 | if name == "unknown": |
| 163 | name = None |
| 164 | dims = [] |
| 165 | for i in range(cube.ndim): |
| 166 | try: |
| 167 | dim_coord = cube.coord(dim_coords=True, dimensions=(i,)) |
| 168 | dims.append(_name(dim_coord)) |
| 169 | except iris.exceptions.CoordinateNotFoundError: |
| 170 | dims.append(f"dim_{i}") |
| 171 | |
| 172 | if len(set(dims)) != len(dims): |
| 173 | duplicates = [k for k, v in Counter(dims).items() if v > 1] |
| 174 | raise ValueError(f"Duplicate coordinate name {duplicates}.") |
| 175 | |
| 176 | coords = {} |
| 177 | |
| 178 | for coord in cube.coords(): |
| 179 | coord_attrs = _iris_obj_to_attrs(coord) |
| 180 | coord_dims = [dims[i] for i in cube.coord_dims(coord)] |
| 181 | if coord_dims: |
| 182 | coords[_name(coord)] = (coord_dims, coord.points, coord_attrs) |
| 183 | else: |
| 184 | coords[_name(coord)] = ((), coord.points.item(), coord_attrs) |
| 185 | |
| 186 | array_attrs = _iris_obj_to_attrs(cube) |
| 187 | cell_methods = _iris_cell_methods_to_str(cube.cell_methods) |
| 188 | if cell_methods: |
| 189 | array_attrs["cell_methods"] = cell_methods |
| 190 | |
| 191 | # Deal with iris 1.* and 2.* |
| 192 | cube_data = cube.core_data() if hasattr(cube, "core_data") else cube.data |
| 193 | |
| 194 | # Deal with dask and numpy masked arrays |
| 195 | dask_array_type = array_type("dask") |
| 196 | if isinstance(cube_data, dask_array_type): |
| 197 | from dask.array import ma as dask_ma |
| 198 | |
| 199 | filled_data = dask_ma.filled(cube_data, get_fill_value(cube.dtype)) |
| 200 | elif isinstance(cube_data, np.ma.MaskedArray): |
| 201 | filled_data = np.ma.filled(cube_data, get_fill_value(cube.dtype)) |
| 202 | else: |
| 203 | filled_data = cube_data |
| 204 | |
| 205 | dataarray = DataArray( |
| 206 | filled_data, coords=coords, name=name, attrs=array_attrs, dims=dims |
| 207 | ) |
| 208 | decoded_ds = decode_cf(dataarray._to_temp_dataset()) |
| 209 | return dataarray._from_temp_dataset(decoded_ds) |
no test coverage detected
searching dependent graphs…