From 99047061ce1a4ae6df7d8fddf01121a0bb6cc286 Mon Sep 17 00:00:00 2001 From: David Hassell Date: Wed, 7 Feb 2024 23:25:15 +0000 Subject: [PATCH] xarray in cf.Data --- Changelog.rst | 2 ++ cf/data/creation.py | 10 ++++++++-- cf/data/data.py | 9 ++++++--- 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/Changelog.rst b/Changelog.rst index 907b1a0132..13098a9eb3 100644 --- a/Changelog.rst +++ b/Changelog.rst @@ -3,6 +3,8 @@ version 3.17.0 **2024-??-??** +* Allow `cf.Data` to be initialised with `xarray.DataAarray` + (https://github.com/NCAS-CMS/cf-python/issues/706) * Fix bug that caused `cf.Field.del_file_location` to fail when updating its metdata constructs (https://github.com/NCAS-CMS/cf-python/issues/707) diff --git a/cf/data/creation.py b/cf/data/creation.py index 0f2ebb94e7..980881db80 100644 --- a/cf/data/creation.py +++ b/cf/data/creation.py @@ -15,8 +15,9 @@ def to_dask(array, chunks, **from_array_options): array: array_like The array to be converted to a `dask` array. Examples of - valid types include `numpy` arrays, `dask` arrays, `Array` - subclasses, `list`, `tuple`, scalars. + valid types include anything with a `to_dask_array` + method, `numpy` arrays, `dask` arrays, `xarray` arrays, + `cf.Array` subclasses, `list`, `tuple`, scalars. chunks: `int`, `tuple`, `dict` or `str`, optional Specify the chunking of the returned dask array. Any @@ -68,6 +69,11 @@ def to_dask(array, chunks, **from_array_options): except TypeError: return array.to_dask_array() + if type(array).__module__.split(".")[0] == "xarray": + data = getattr(array, "data", None) + if data is not None: + return da.asanyarray(data) + if not isinstance( array, (np.ndarray, list, tuple, memoryview) + np.ScalarType ) and not hasattr(array, "shape"): diff --git a/cf/data/data.py b/cf/data/data.py index 4746ed0325..a881eefe22 100644 --- a/cf/data/data.py +++ b/cf/data/data.py @@ -189,11 +189,14 @@ def __init__( :Parameters: array: optional - The array of values. May be any scalar or array-like - object, including another `Data` instance. + The array of values. May be a scalar or array-like + object, including another `Data` instance, anything + with a `!to_dask_array` method, `numpy` array, `dask` + array, `xarray` array, `cf.Array` subclass, `list`, + `tuple`, scalar. *Parameter example:* - ``array=[34.6]`` + ``array=34.6`` *Parameter example:* ``array=[[1, 2], [3, 4]]``