(obj, to)
| 228 | |
| 229 | |
| 230 | def convert_units(obj, to): |
| 231 | # preprocess |
| 232 | to = { |
| 233 | key: None if not isinstance(value, unit_registry.Unit) else value |
| 234 | for key, value in to.items() |
| 235 | } |
| 236 | if isinstance(obj, xr.Dataset): |
| 237 | data_vars = { |
| 238 | name: convert_units(array.variable, {None: to.get(name)}) |
| 239 | for name, array in obj.data_vars.items() |
| 240 | } |
| 241 | coords = { |
| 242 | name: convert_units(array.variable, {None: to.get(name)}) |
| 243 | for name, array in obj.coords.items() |
| 244 | } |
| 245 | |
| 246 | new_obj = xr.Dataset(data_vars=data_vars, coords=coords, attrs=obj.attrs) |
| 247 | elif isinstance(obj, xr.DataArray): |
| 248 | name = obj.name |
| 249 | |
| 250 | new_units = to.get(name) or to.get("data") or to.get(None) or None |
| 251 | data = convert_units(obj.variable, {None: new_units}) |
| 252 | |
| 253 | coords = { |
| 254 | name: (array.dims, convert_units(array.variable, {None: to.get(name)})) |
| 255 | for name, array in obj.coords.items() |
| 256 | if name != obj.name |
| 257 | } |
| 258 | |
| 259 | new_obj = xr.DataArray( # type: ignore[assignment] |
| 260 | name=name, data=data, coords=coords, attrs=obj.attrs, dims=obj.dims |
| 261 | ) |
| 262 | elif isinstance(obj, xr.Variable): |
| 263 | new_data = convert_units(obj.data, to) |
| 264 | new_obj = obj.copy(data=new_data) # type: ignore[assignment] |
| 265 | elif isinstance(obj, unit_registry.Quantity): |
| 266 | units = to.get(None) |
| 267 | new_obj = obj.to(units) if units is not None else obj |
| 268 | else: |
| 269 | new_obj = obj |
| 270 | |
| 271 | return new_obj |
| 272 | |
| 273 | |
| 274 | def assert_units_equal(a, b): |
no test coverage detected
searching dependent graphs…