"""Interface to zarr arrays"""importcontextlibfromdataclassesimportdataclassfrompathlibimportPathfromtypingimportAny,Optional,Sequence,UnionfrompydanticimportSerializationInfofromnumpydantic.interface.interfaceimportInterfacetry:importzarrfromzarr.coreimportArrayasZarrArrayfromzarr.storageimportStoreLikeexceptImportError:# pragma: no coverZarrArray=NoneStoreLike=Nonestorage=None
[docs]@dataclassclassZarrArrayPath:""" Map to an array within a zarr store. See :func:`zarr.open` """file:Union[Path,str]"""Location of Zarr store file or directory"""path:Optional[str]=None"""Path to array within hierarchical zarr store"""
[docs]defopen(self,**kwargs:dict)->ZarrArray:"""Open the zarr array at the provided path"""returnzarr.open(str(self.file),path=self.path,**kwargs)
[docs]@classmethoddeffrom_iterable(cls,spec:Sequence)->"ZarrArrayPath":""" Construct a :class:`.ZarrArrayPath` specifier from an iterable, rather than kwargs """iflen(spec)==1:returnZarrArrayPath(file=spec[0])eliflen(spec)==2:returnZarrArrayPath(file=spec[0],path=spec[1])else:raiseValueError("Only len 1-2 iterables can be used for a ZarrArrayPath")
[docs]classZarrInterface(Interface):""" Interface to in-memory or on-disk zarr arrays """input_types=(Path,ZarrArray,ZarrArrayPath)return_type=ZarrArray
[docs]@classmethoddefenabled(cls)->bool:"""True if zarr is installed"""returnZarrArrayisnotNone
[docs]@classmethoddefcheck(cls,array:Any)->bool:""" Check if array is in-memory zarr array, a path to a zarr array, or a :class:`.ZarrArrayPath` """ifisinstance(array,ZarrArray):returnTrue# See if can be coerced to ZarrArrayPathifisinstance(array,(Path,str)):array=ZarrArrayPath(file=array)ifisinstance(array,(tuple,list)):# something that can be coerced to ZarrArrayPathwithcontextlib.suppress(ValueError):array=ZarrArrayPath.from_iterable(array)ifisinstance(array,ZarrArrayPath):withcontextlib.suppress(Exception):arr=array.open(mode="r")ifisinstance(arr,ZarrArray):returnTruereturnFalse
[docs]defbefore_validation(self,array:Union[ZarrArray,str,Path,ZarrArrayPath,Sequence])->ZarrArray:""" Ensure that the zarr array is opened """returnself._get_array(array)
[docs]@classmethoddefto_json(cls,array:Union[ZarrArray,str,Path,ZarrArrayPath,Sequence],info:Optional[SerializationInfo]=None,)->dict:""" Dump just the metadata for an array from :meth:`zarr.core.Array.info_items` plus the :meth:`zarr.core.Array.hexdigest`. The full array can be returned by passing ``'zarr_dump_array': True`` to the serialization ``context`` :: model.model_dump_json(context={'zarr_dump_array': True}) """dump_array=FalseifinfoisnotNoneandinfo.contextisnotNone:dump_array=info.context.get("zarr_dump_array",False)array=cls._get_array(array)info=array.info_items()info_dict={i[0]:i[1]foriininfo}info_dict["hexdigest"]=array.hexdigest()ifdump_array:info_dict["array"]=array[:].tolist()returninfo_dict