xarray_custom package

Submodules

xarray_custom.accessor module

Module for DataArray accessor classes.

xarray_custom.accessor.add_accessors(cls: type, name: Optional[str] = None) → type[source]

Add unique and common accessors to a DataArray class.

Parameters
  • cls – DataArray class to which accessors are added.

  • name – Name of a common accessor. If not specified, only an unique accessor is added to the class.

Returns

The same DataArray class as the input.

xarray_custom.bases module

Module for providing the base class of DataArray classes.

class xarray_custom.bases.DataArrayClassBase(**kwargs)[source]

Bases: object

Create a custom DataArray from data and coordinates.

(dims=None, dtype=None) No description.

Parameters
  • data – Values of the DataArray. Its shape must match class dims. If class dtype is defined, it will be casted to that type. If it cannot be casted, a ValueError will be raised.

  • name – Name of the DataArray. Default is class name.

  • attrs – Attributes of the DataArray. Default is class attrs.

  • **coords – Coordinates of the DataArray defined by the class.

Returns

Custom DataArray.

accessor: Optional[str] = None
desc: str = 'No description.'
dims: Optional[Union[Sequence[Hashable], Hashable]] = None
dtype: Optional[Union[type, str]] = None
classmethod empty(shape: Union[Tuple[int], int], dtype: Optional[Union[type, str]] = None, order: str = 'C', name: Optional[Hashable] = None, attrs: Optional[Mapping] = None, **coords) → xarray.core.dataarray.DataArray

Create a custom DataArray filled with uninitialized values.

(dims=None, dtype=None) No description.

Parameters
  • shape – Shape of the DataArray. It must match class dims.

  • dtype – Datatype of the DataArray. Default is 64-bit float. It is ignored if class dtype is defined.

  • order – Order of data in memory. Either 'C' (row-major; C-style) or 'F' (column-major; Fortran-style) is accepted.

  • name – Name of the DataArray. Default is class name.

  • attrs – Attributes of the DataArray. Default is class attrs.

  • **coords – Coordinates of the DataArray defined by the class.

Returns

Custom DataArray filled with uninitialized values.

classmethod full(shape: Union[Tuple[int], int], fill_value: Any, dtype: Optional[Union[type, str]] = None, order: str = 'C', name: Optional[Hashable] = None, attrs: Optional[Mapping] = None, **coords) → xarray.core.dataarray.DataArray

Create a custom DataArray filled with fill_value.

(dims=None, dtype=None) No description.

Parameters
  • shape – Shape of the DataArray. It must match class dims.

  • fill_value – Scalar value to fill the custom DataArray.

  • dtype – Datatype of the DataArray. Default is 64-bit float. It is ignored if class dtype is defined.

  • order – Order of data in memory. Either 'C' (row-major; C-style) or 'F' (column-major; Fortran-style) is accepted.

  • name – Name of the DataArray. Default is class name.

  • attrs – Attributes of the DataArray. Default is class attrs.

  • **coords – Coordinates of the DataArray defined by the class.

Returns

Custom DataArray filled with fill_value.

classmethod ones(shape: Union[Tuple[int], int], dtype: Optional[Union[type, str]] = None, order: str = 'C', name: Optional[Hashable] = None, attrs: Optional[Mapping] = None, **coords) → xarray.core.dataarray.DataArray

Create a custom DataArray filled with ones.

(dims=None, dtype=None) No description.

Parameters
  • shape – Shape of the DataArray. It must match class dims.

  • dtype – Datatype of the DataArray. Default is 64-bit float. It is ignored if class dtype is defined.

  • order – Order of data in memory. Either 'C' (row-major; C-style) or 'F' (column-major; Fortran-style) is accepted.

  • name – Name of the DataArray. Default is class name.

  • attrs – Attributes of the DataArray. Default is class attrs.

  • **coords – Coordinates of the DataArray defined by the class.

Returns

Custom DataArray filled with ones.

classmethod zeros(shape: Union[Tuple[int], int], dtype: Optional[Union[type, str]] = None, order: str = 'C', name: Optional[Hashable] = None, attrs: Optional[Mapping] = None, **coords) → xarray.core.dataarray.DataArray

Create a custom DataArray filled with zeros.

(dims=None, dtype=None) No description.

Parameters
  • shape – Shape of the DataArray. It must match class dims.

  • dtype – Datatype of the DataArray. Default is 64-bit float. It is ignored if class dtype is defined.

  • order – Order of data in memory. Either 'C' (row-major; C-style) or 'F' (column-major; Fortran-style) is accepted.

  • name – Name of the DataArray. Default is class name.

  • attrs – Attributes of the DataArray. Default is class attrs.

  • **coords – Coordinates of the DataArray defined by the class.

Returns

Custom DataArray filled with zeros.

xarray_custom.dataclasses module

Module for creating custom DataArray classes.

This module provides functions which help to create a custom DataArray class with fixed dimensions, datatype, and coordinates. Two functions are available:

  • dataarrayclass: Class decorator to construct a custom DataArray class.

  • coord: Create a DataArray class for the definition of a coordinate.

Examples

To create a custom DataArray class to represent images:

@dataarrayclass
class Image:
    """DataArray class to represent images."""

    accessor = 'img'
    dims = 'x', 'y'
    dtype = float

    x: coord('x', int) = 0
    y: coord('y', int) = 0

    def normalize(self):
        return self / self.max()

The code style is similar to that of Python’s dataclass. A DataArray is then created using the class:

image = Image([[0, 1], [2, 3]], x=[0, 1], y=[0, 1])
print(image)

# <xarray.DataArray (x: 2, y: 2)>
# array([[0., 1.],
#        [2., 3.]])
# Coordinates:
#   * x        (x) int64 0 1
#   * y        (y) int64 0 1

Because dims, dtype, and coordinates are pre-defined, it is much easier to create a DataArray with given data. Custom methods can be used via an accessor:

normalized = image.img.normalize()
print(normalized)

# <xarray.DataArray (x: 2, y: 2)>
# array([[0.        , 0.33333333],
#        [0.66666667, 1.        ]])
# Coordinates:
#   * x        (x) int64 0 1
#   * y        (y) int64 0 1

Like NumPy, several special class methods are available to create a DataArray filled with some values:

ones = Image.ones((2, 2))
print(ones)

# <xarray.DataArray (x: 2, y: 2)>
# array([[1., 1.],
#        [1., 1.]])
# Coordinates:
#   * x        (x) int64 0 0
#   * y        (y) int64 0 0

Inheriting a custom DataArray class is possible to create a derivative DataArray class:

class WeightedImage(Image):
    accessor = 'wimg'
    w: coord(('x', 'y'), float) = 1.0

zeros = Weightedimage.zeros((2, 2))
print(zeros)

# <xarray.DataArray (x: 2, y: 2)>
# array([[1., 1.],
#        [1., 1.]])
# Coordinates:
#   * x        (x) int64 0 0
#   * y        (y) int64 0 0
#     w        (x, y) float64 1.0 1.0 1.0 1.0
xarray_custom.dataclasses.coord(dims: Optional[Union[Sequence[Hashable], Hashable]] = None, dtype: Optional[Union[type, str]] = None, desc: Optional[str] = None, **_) → type[source]

Create a DataArray class for the definition of a coordinate.

Parameters
  • dims – Dimensions of the coordinate.

  • dtype – Datatype of the coordinate. Default is None, which means that an input of any datatype is accepted.

  • desc – Short description of the coordinate.

Returns

DataArray class for the coordinate.

xarray_custom.dataclasses.dataarrayclass(cls: type) → type[source]

Class decorator to construct a custom DataArray class.

A class can define properties of DataArray to be created. The following class variables are accepted (see examples).

  • dims (str or tuple of str): Name(s) of dimension(s).

  • dtype (str or type): Datatype of DataArray.

  • desc (str): Short description of DataArray. Users can

    alternatively define it by a docstring (__doc__).

  • accessor (str): Name of accessor (if necessary).

The coordinates of DataArray can also be defined as class variables using the coord function (see examples).

Finally users can define custom instance methods which can be used by an accessor whose name is defined by accessor.

Parameters

cls – Class to be decorated.

Returns

Decorated class as a DataArray class.

Examples

To create a custom DataArray class to represent images:

@dataarrayclass
class Image:
    """DataArray class to represent images."""

    accessor = 'img'
    dims = 'x', 'y'
    dtype = float

    x: coord('x', int) = 0
    y: coord('y', int) = 0

    def normalize(self):
        return self / self.max()

xarray_custom.docstring module

Module for making docstrings of functions updatable.

xarray_custom.docstring.updatable_doc(func: Callable) → Callable[source]

Decorator for making the docstring of a function updatable.

A decorated function has the set method, by which an update function for the docstring is registered to the function.

Parameters

func – A function whose docstring should be updatable.

Returns

Decorated function with the copy and set methods.

xarray_custom.docstring.copy()

Copy the decorated function and return a new one.

xarray_custom.docstring.set()

Set an update function to the decorated function.

Examples:

@updatable_doc
def func():
    """Docstring."""
    pass

# set an updater function
func.set(lambda doc: doc.replace(".", "!"))

# show the help of the decorated function
help(func) # -> Docstring!

xarray_custom.special module

Module for special class methods of DataArray classes.

xarray_custom.special.add_classmethods(cls: type, updater: Optional[Callable] = None) → type[source]

Add special class methods to a DataArray class.

Parameters

updater – Function to update docstrings of the class methods. Its input must be a docstring (str) and its output must be the updated docstring (str). If not specified (by default), any docstrings will not be updated.

Returns

The same DataArray class as the input.

xarray_custom.typing module

Module for type hints of xarray DataArray.

This module provides type hints of xarray DataArray which are intended to be used other modules of the package.

xarray_custom.typing.Attrs

The central part of internal API.

This represents a generic version of type ‘origin’ with type arguments ‘params’. There are two kind of these aliases: user defined and special. The special ones are wrappers around builtin collections and ABCs in collections.abc. These must have ‘name’ always set. If ‘inst’ is False, then the alias can’t be instantiated, this is used by e.g. typing.List and typing.Dict.

alias of Mapping

xarray_custom.typing.Dims

The central part of internal API.

This represents a generic version of type ‘origin’ with type arguments ‘params’. There are two kind of these aliases: user defined and special. The special ones are wrappers around builtin collections and ABCs in collections.abc. These must have ‘name’ always set. If ‘inst’ is False, then the alias can’t be instantiated, this is used by e.g. typing.List and typing.Dict.

alias of Union[Sequence[Hashable], Hashable]

xarray_custom.typing.Dtype

The central part of internal API.

This represents a generic version of type ‘origin’ with type arguments ‘params’. There are two kind of these aliases: user defined and special. The special ones are wrappers around builtin collections and ABCs in collections.abc. These must have ‘name’ always set. If ‘inst’ is False, then the alias can’t be instantiated, this is used by e.g. typing.List and typing.Dict.

alias of Union[type, str]

xarray_custom.typing.Name

The central part of internal API.

This represents a generic version of type ‘origin’ with type arguments ‘params’. There are two kind of these aliases: user defined and special. The special ones are wrappers around builtin collections and ABCs in collections.abc. These must have ‘name’ always set. If ‘inst’ is False, then the alias can’t be instantiated, this is used by e.g. typing.List and typing.Dict.

alias of Hashable

xarray_custom.typing.Shape

The central part of internal API.

This represents a generic version of type ‘origin’ with type arguments ‘params’. There are two kind of these aliases: user defined and special. The special ones are wrappers around builtin collections and ABCs in collections.abc. These must have ‘name’ always set. If ‘inst’ is False, then the alias can’t be instantiated, this is used by e.g. typing.List and typing.Dict.

alias of Union[Tuple[int], int]

xarray_custom.utils module

Module for utilities which help to create custom DataArray classes.

Currently this module only provides include class decorator which can include a custom DataArray definition written in a file.

  • include: Class decorator to include a custom DataArray definition in a file.

xarray_custom.utils.include(path: Union[pathlib.Path, str]) → Callable[source]

Class decorator to include a custom DataArray definition in a file.

File format of either JSON, TOML, or YAML is accepted. The following key=value pairs can be included if available.

  • dims=<array of string>: Dimensions of the DataArray.

  • dtype=<string>: Datatype of the DataArray.

  • desc=<string>: Short description of the DataArray.

  • coords=<map of coord>: Definition of coordinates (coords). Each coord is a map which can have the following key=value pairs.

    • dims=<array of string>: Dimensions of a coordinate.

    • dtype=<string>: Datatype of a coordinate.

    • desc=<string>: Short description of a coordinate.

    • default=<any>: Default value of a coordinate.

Parameters

path – Path or filename of the file.

Returns

Decorator to include the definition.

Examples

If a definition is written in dataarray.toml:

# dataarray.toml

dims = [ "x", "y" ]
dtype = "float"
desc = "DataArray class to represent images."

[coords.x]
dims = "x"
dtype = "int"
default = 0

[coords.y]
dims = "y"
dtype = "int"
default = 0

then the following two class definitions are equivalent:

@include('dataarray.toml')
@dataarrayclass
class Image:
    pass
@dataarrayclass
class Image:
    """DataArray class to represent images."""

    dims = 'x', 'y'
    dtype = float
    x: coord('x', int) = 0
    y: coord('y', int) = 0

Module contents