"""Interface for Dask arrays"""fromtypingimportAny,OptionalimportnumpyasnpfrompydanticimportSerializationInfofromnumpydantic.interface.interfaceimportInterfacefromnumpydantic.typesimportDtypeType,NDArrayTypetry:fromdask.array.coreimportArrayasDaskArrayexceptImportError:# pragma: no coverDaskArray=None
[docs]classDaskInterface(Interface):""" Interface for Dask :class:`~dask.array.core.Array` """input_types=(DaskArray,)return_type=DaskArray
[docs]@classmethoddefcheck(cls,array:Any)->bool:""" check if array is a dask array """returnDaskArrayisnotNoneandisinstance(array,DaskArray)
[docs]defget_object_dtype(self,array:NDArrayType)->DtypeType:"""Dask arrays require a compute() call to retrieve a single value"""returntype(array.ravel()[0].compute())
[docs]@classmethoddefenabled(cls)->bool:"""check if we successfully imported dask"""returnDaskArrayisnotNone
[docs]@classmethoddefto_json(cls,array:DaskArray,info:Optional[SerializationInfo]=None)->list:""" Convert an array to a JSON serializable array by first converting to a numpy array and then to a list. .. note:: This is likely a very memory intensive operation if you are using dask for large arrays. This can't be avoided, since the creation of the json string happens in-memory with Pydantic, so you are likely looking for a different method of serialization here using the python object itself rather than its JSON representation. """returnnp.array(array).tolist()