MCPcopy
hub / github.com/pydata/xarray / convert_units

Function convert_units

xarray/tests/test_units.py:230–271  ·  view source on GitHub ↗
(obj, to)

Source from the content-addressed store, hash-verified

228
229
230def 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
274def assert_units_equal(a, b):

Callers 15

test_align_dataarrayFunction · 0.85
test_align_datasetFunction · 0.85
test_broadcast_dataarrayFunction · 0.85
test_combine_by_coordsFunction · 0.85
test_combine_nestedFunction · 0.85
test_concat_dataarrayFunction · 0.85
test_concat_datasetFunction · 0.85
test_merge_dataarrayFunction · 0.85
test_merge_datasetFunction · 0.85
test_where_dataarrayFunction · 0.85
test_where_datasetFunction · 0.85
test_numpy_methodsMethod · 0.85

Calls 3

itemsMethod · 0.80
getMethod · 0.45
copyMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…