Package: xarray-dataclasses
xarray-dataclassesxarray data creation made easy by dataclassOverviewxarray-dataclasses is a Python package that makes it easy to createxarray's DataArray and Dataset objects that are "typed" (i.e. fixed dimensions, data type, coordinates, attributes, and name) usingthe Python's dataclass:fromdataclassesimportdataclassfromtypingimportLiteralfromxarray_dataclassesimportAsDataArray,Coord,DataX=Literal["x"]Y=Literal["y"]@dataclassclassImage(AsDataArray):"""2D image as DataArray."""data:Data[tuple[X,Y],float]x:Coord[X,int]=0y:Coord[Y,int]=0FeaturesTyped DataArray or Dataset objects can easily be created:image=Image.new([[0,1],[2,3]],[0,1],[0,1])NumPy-like filled-data creation is also available:image=Image.zeros([2,2],x=[0,1],y=[0,1])Support for features bythe Python's dataclass(field,__post_init__, ...).Support for static type check byPyright.Installationpipinstallxarray-dataclassesBasic usagexarray-dataclasses usesthe Python's dataclass.
Data (or data variables), coordinates, attributes, and a name of DataArray or Dataset objects will be defined as dataclass fields by special type hints (Data,Coord,Attr,Name), respectively.
Note that the following code is supposed in the examples below.fromdataclassesimportdataclassfromtypingimportLiteralfromxarray_dataclassesimportAsDataArray,AsDatasetfromxarray_dataclassesimportAttr,Coord,Data,NameX=Literal["x"]Y=Literal["y"]Data fieldData field is a field whose value will become the data of a DataArray object or a data variable of a Dataset object.
The type hintData[TDims, TDtype]fixes the dimensions and the data type of the object.
Here are some examples of how to specify them.Type hintInferred dimensionsData[tuple[()], ...]()Data[Literal["x"], ...]("x",)Data[tuple[Literal["x"]], ...]("x",)Data[tuple[Literal["x"], Literal["y"]], ...]("x", "y")Type hintInferred data typeData[..., Any]NoneData[..., None]NoneData[..., float]numpy.dtype("float64")Data[..., numpy.float128]numpy.dtype("float128")Data[..., Literal["datetime64[ns]"]]numpy.dtype("<M8[ns]")Coordinate fieldCoordinate field is a field whose value will become a coordinate of a DataArray or a Dataset object.
The type hintCoord[TDims, TDtype]fixes the dimensions and the data type of the object.Attribute fieldAttribute field is a field whose value will become an attribute of a DataArray or a Dataset object.
The type hintAttr[TAttr]specifies the type of the value, which is used only for static type check.Name fieldName field is a field whose value will become the name of a DataArray object.
The type hintName[TName]specifies the type of the value, which is used only for static type check.DataArray classDataArray class is a dataclass that defines typed DataArray specifications.
Exactly one data field is allowed in a DataArray class.
The second and subsequent data fields are just ignored in DataArray creation.@dataclassclassImage(AsDataArray):"""2D image as DataArray."""data:Data[tuple[X,Y],float]x:Coord[X,int]=0y:Coord[Y,int]=0units:Attr[str]="cd / m^2"name:Name[str]="luminance"A DataArray object will be created by a class methodnew():Image.new([[0,1],[2,3]],x=[0,1],y=[0,1])<xarray.DataArray"luminance"(x:2,y:2)>array([[0.,1.],[2.,3.]])Coordinates:*x(x)int6401*y(y)int6401Attributes:units:cd/m^2NumPy-like class methods (zeros(),ones(), ...) are also available:Image.ones((3,3))<xarray.DataArray"luminance"(x:3,y:3)>array([[1.,1.,1.],[1.,1.,1.],[1.,1.,1.]])Coordinates:*x(x)int64000*y(y)int64000Attributes:units:cd/m^2Dataset classDataset class is a dataclass that defines typed Dataset specifications.
Multiple data fields are allowed to define the data variables of the object.@dataclassclassColorImage(AsDataset):"""2D color image as Dataset."""red:Data[tuple[X,Y],float]green:Data[tuple[X,Y],float]blue:Data[tuple[X,Y],float]x:Coord[X,int]=0y:Coord[Y,int]=0units:Attr[str]="cd / m^2"A Dataset object will be created by a class methodnew():ColorImage.new([[0,0],[0,0]],# red[[1,1],[1,1]],# green[[2,2],[2,2]],# blue)<xarray.Dataset>Dimensions:(x:2,y:2)Coordinates:*x(x)int6400*y(y)int6400Datavariables:red(x,y)float640.00.00.00.0green(x,y)float641.01.01.01.0blue(x,y)float642.02.02.02.0Attributes:units:cd/m^2Advanced usageCoordof and Dataof type hintsxarray-dataclasses provides advanced type hints,CoordofandDataof.
UnlikeDataandCoord, they specify a dataclass that defines a DataArray class.
This is useful when users want to add metadata to dimensions forplotting.
For example:fromxarray_dataclassesimportCoordof@dataclassclassXAxis:data:Data[X,int]long_name:Attr[str]="x axis"units:Attr[str]="pixel"@dataclassclassYAxis:data:Data[Y,int]long_name:Attr[str]="y axis"units:Attr[str]="pixel"@dataclassclassImage(AsDataArray):"""2D image as DataArray."""data:Data[tuple[X,Y],float]x:Coordof[XAxis]=0y:Coordof[YAxis]=0General data variable names in Dataset creationDue to the limitation of Python's parameter names, it is not possible to define data variable names that contain white spaces, for example.
In such cases, please define DataArray classes of each data variable so that they have name fields and specify them byDataofin a Dataset class.
Then the values of the name fields will be used as data variable names.
For example:@dataclassclassRed:data:Data[tuple[X,Y],float]name:Name[str]="Red image"@dataclassclassGreen:data:Data[tuple[X,Y],float]name:Name[str]="Green image"@dataclassclassBlue:data:Data[tuple[X,Y],float]name:Name[str]="Blue image"@dataclassclassColorImage(AsDataset):"""2D color image as Dataset."""red:Dataof[Red]green:Dataof[Green]blue:Dataof[Blue]ColorImage.new([[0,0],[0,0]],[[1,1],[1,1]],[[2,2],[2,2]],)<xarray.Dataset>Dimensions:(x:2,y:2)Dimensionswithoutcoordinates:x,yDatavariables:Redimage(x,y)float640.00.00.00.0Greenimage(x,y)float641.01.01.01.0Blueimage(x,y)float642.02.02.02.0Customization of DataArray or Dataset creationFor customization, users can add a special class attribute,__dataoptions__, to a DataArray or Dataset class.
A custom factory for DataArray or Dataset creation is only supported in the current implementation.importxarrayasxrfromxarray_dataclassesimportDataOptionsclassCustom(xr.DataArray):"""Custom DataArray."""__slots__=()defcustom_method(self)->bool:"""Custom method."""returnTrue@dataclassclassImage(AsDataArray):"""2D image as DataArray."""data:Data[tuple[X,Y],float]x:Coord[X,int]=0y:Coord[Y,int]=0__dataoptions__=DataOptions(Custom)image=Image.ones([3,3])isinstance(image,Custom)# Trueimage.custom_method()# TrueDataArray and Dataset creation without shorthandsxarray-dataclasses provides functions,asdataarrayandasdataset.
This is useful when users do not want to inherit the mix-in class (AsDataArrayorAsDataset) in a DataArray or Dataset dataclass.
For example:fromxarray_dataclassesimportasdataarray@dataclassclassImage:"""2D image as DataArray."""data:Data[tuple[X,Y],float]x:Coord[X,int]=0y:Coord[Y,int]=0image=asdataarray(Image([[0,1],[2,3]],[0,1],[0,1]))