Skip to content

brainhops.datamodel.axes

Axes of coordinate systems, such as spatial and time axes.

The base class

AxisLike module-attribute

AxisLike: TypeAlias = Axis | str

A value that is a Axis or that can be converted to one.

Axis magic

Axis(
    name: str | None = None,
    type: AxisType | str | None = None,
    unit: Unit | None = None,
    discrete: bool | None = None,
    orientation: Orientation | None = None,
)

Bases: DataModelBase

One axis of a coordinate system or of a grid.

An axis records what is known about one dimension of a space: its name, type, unit and orientation, and whether it is discrete. A field that is None is unknown, so Axis() is a placeholder about which nothing is known. Subclasses fix some of the fields. A SpaceAxis, for example, is known to be spatial, although its unit is unknown by default.

Two axes are equal when they have the same class and equal fields. compatible_with tests the looser condition that two axes could describe the same axis.

Parameters:

Name Type Description Default
name str

Name of the axis, such as "x".

None
type AxisType | str

Type of the axis, such as "space" or "time".

None
unit Unit | str

Unit of the coordinates along the axis.

None

Other Parameters:

Name Type Description
discrete bool

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation Orientation | str

Meaningful direction of the axis, such as left to right.

name class-attribute instance-attribute

name: NotKwOnly[str | None] = None

Name of the axis, such as "x".

type class-attribute instance-attribute

type: NotKwOnly[AxisType | str | None] = None

Type of the axis, such as "space" or "time".

unit class-attribute instance-attribute

unit: NotKwOnly[Unit | None] = None

Unit of the coordinates along the axis.

discrete class-attribute instance-attribute

discrete: bool | None = None

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation class-attribute instance-attribute

orientation: Orientation | None = None

Meaningful direction of the axis, such as left to right.

compatible_with

compatible_with(other: Axis) -> bool

Return whether two axes could describe the same axis.

Two axes are compatible when all their fields have either the same value or at least one of them has the value None.

The relation is symmetric but not transitive: Axis() is compatible with Axis(name="x") and Axis(name="y"), but these two are not compatible with each other.

Example

>>> Axis(name="x").compatible_with(Axis(name="x", unit="mm"))
True
>>> Axis(name="x").compatible_with(Axis(name="y"))
False
>>> SpaceAxis(unit="mm").compatible_with(Axis(unit="micrometer"))
False

Parameters:

Name Type Description Default
other Axis

The axis to compare with.

required

Returns:

Type Description
bool

Whether no field is set on both sides to different values.

Raises:

Type Description
TypeError

If other is not an Axis.

merge_with

merge_with(other: Axis) -> Axis

Combine two compatible axes.

The input axes must be compatible in the sense of compatible_with. The resulting axis has all non-None values found on either axis.

When both axes have different Axis subtypes, the resulting axis has the type of the most derived class. For example, an Axis merged with a SpaceAxis results in a SpaceAxis.

Example

>>> Axis(name="x").merge_with(SpaceAxis(unit="micrometer"))
SpaceAxis(name='x', unit='micrometer')
>>> Axis(name="x").merge_with(Axis(name="y"))
Traceback (most recent call last):
  ...
ValueError: Cannot merge axes that disagree on name: 'x' != 'y'.

Parameters:

Name Type Description Default
other Axis

Another description of the same axis.

required

Returns:

Type Description
Axis

A new axis with every field known to either side.

Raises:

Type Description
TypeError

If other is not an Axis.

ValueError

If the axes disagree on a field, or if neither class derives from the other.

from_dict classmethod

from_dict(other: Mapping, *args, **kwargs) -> Self

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

from_instance classmethod

from_instance(other: Any, *args, **kwargs) -> Self

Build an instance from an instance of a related data model.

Two classes are related when:

  • one of them is a parent of the other, or
  • when both belong to the same polymorphic family, or
  • when they represent the same "data model".

In all these cases, attributes that have the same name also have the same meaning, so they can be copied by name.

Note

  • Only attributes that name keyword arguments are used.
  • An attribute that is None leaves the default of the class in place.
  • Extra arguments (*args and **kwargs) are passed to the constructor and take precedence.
  • Unless other is already an instance of this class, an attribute of the instance that that corresponds to a fixed attribute in the target class is checked against its value.
  • In genemost casesral, cls.from_instance(other) is equivalent to other.to(cls, copy=True).

Parameters:

Name Type Description Default
other DataModelBase

The instance to copy.

required
*args Any

Constructor arguments, which take precedence over the fields of other.

()
**kwargs Any

Constructor arguments, which take precedence over the fields of other.

{}

Returns:

Type Description
Self

The new instance.

Raises:

Type Description
TypeError

If other is not an instance of a data model. A file, a mapping and any other value are read by from_any.

ConversionError

If the class of other is not related to this class, so that fields with the same name may mean different things.

ValueError

If a fixed field of other is set to a value other than the value that the class fixes.

from_any classmethod

from_any(other: Any, *args, **kwargs) -> Self

Build an instance from a mapping, a data model or an argument.

This constructors dispatches to from_dict, from_instance or the constructor, depending on the type of other.

Raises:

Type Description
TypeError

If a mapping has a key that names no field. Unlike from_dict, this method catches misspelled keys.

to

to(
    cls: type | None = None, *, copy: bool = False, **kwargs
) -> Any

Convert the object to another class of its data model.

Without a class, the object keeps its own class, and its attributes may be replaced by the keyword arguments.

Otherwise, the object is converted by cls.from_instance, which copies the attributes of a related class by name. Some subclasses override this method so that it triggers a more specific conversion.

Parameters:

Name Type Description Default
cls type

The class to convert to. By default, the class of the object.

None
copy bool

Whether to return a new object even when nothing changes.

False
**kwargs Any

Fields of the result, which take precedence over those of the object.

{}

Returns:

Type Description
DataModelBase

The converted object, an instance of cls.

Raises:

Type Description
ConversionError

If cls is not related to the class of the object.

Axis type polymorphism

SpaceAxis magic

SpaceAxis(name: str | None = None, type: NoRepr[...], unit: Inherit[SpaceUnit | IndexUnit | None], discrete: bool | None = None, orientation: Orientation | None = None)

Bases: Axis

Axis that measures a spatial dimension.

The unit is a space unit, an index unit, or None. Calling Axis builds a SpaceAxis whenever the type is "space", whatever the unit, so Axis(type="space", unit="s") fails rather than building a generic Axis.

Parameters:

Name Type Description Default
name str

Name of the axis, such as "x".

None
type space

Pinned axis type.

"space"
unit SpaceUnit | IndexUnit | str

Unit of the coordinates along the axis.

required

Other Parameters:

Name Type Description
discrete bool

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation Orientation | str

Meaningful direction of the axis, such as left to right.

name class-attribute instance-attribute

name: NotKwOnly[str | None] = None

Name of the axis, such as "x".

discrete class-attribute instance-attribute

discrete: bool | None = None

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation class-attribute instance-attribute

orientation: Orientation | None = None

Meaningful direction of the axis, such as left to right.

from_dict classmethod

from_dict(other: Mapping, *args, **kwargs) -> Self

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

from_instance classmethod

from_instance(other: Any, *args, **kwargs) -> Self

Build an instance from an instance of a related data model.

Two classes are related when:

  • one of them is a parent of the other, or
  • when both belong to the same polymorphic family, or
  • when they represent the same "data model".

In all these cases, attributes that have the same name also have the same meaning, so they can be copied by name.

Note

  • Only attributes that name keyword arguments are used.
  • An attribute that is None leaves the default of the class in place.
  • Extra arguments (*args and **kwargs) are passed to the constructor and take precedence.
  • Unless other is already an instance of this class, an attribute of the instance that that corresponds to a fixed attribute in the target class is checked against its value.
  • In genemost casesral, cls.from_instance(other) is equivalent to other.to(cls, copy=True).

Parameters:

Name Type Description Default
other DataModelBase

The instance to copy.

required
*args Any

Constructor arguments, which take precedence over the fields of other.

()
**kwargs Any

Constructor arguments, which take precedence over the fields of other.

{}

Returns:

Type Description
Self

The new instance.

Raises:

Type Description
TypeError

If other is not an instance of a data model. A file, a mapping and any other value are read by from_any.

ConversionError

If the class of other is not related to this class, so that fields with the same name may mean different things.

ValueError

If a fixed field of other is set to a value other than the value that the class fixes.

from_any classmethod

from_any(other: Any, *args, **kwargs) -> Self

Build an instance from a mapping, a data model or an argument.

This constructors dispatches to from_dict, from_instance or the constructor, depending on the type of other.

Raises:

Type Description
TypeError

If a mapping has a key that names no field. Unlike from_dict, this method catches misspelled keys.

to

to(
    cls: type | None = None, *, copy: bool = False, **kwargs
) -> Any

Convert the object to another class of its data model.

Without a class, the object keeps its own class, and its attributes may be replaced by the keyword arguments.

Otherwise, the object is converted by cls.from_instance, which copies the attributes of a related class by name. Some subclasses override this method so that it triggers a more specific conversion.

Parameters:

Name Type Description Default
cls type

The class to convert to. By default, the class of the object.

None
copy bool

Whether to return a new object even when nothing changes.

False
**kwargs Any

Fields of the result, which take precedence over those of the object.

{}

Returns:

Type Description
DataModelBase

The converted object, an instance of cls.

Raises:

Type Description
ConversionError

If cls is not related to the class of the object.

compatible_with

compatible_with(other: Axis) -> bool

Return whether two axes could describe the same axis.

Two axes are compatible when all their fields have either the same value or at least one of them has the value None.

The relation is symmetric but not transitive: Axis() is compatible with Axis(name="x") and Axis(name="y"), but these two are not compatible with each other.

Example

>>> Axis(name="x").compatible_with(Axis(name="x", unit="mm"))
True
>>> Axis(name="x").compatible_with(Axis(name="y"))
False
>>> SpaceAxis(unit="mm").compatible_with(Axis(unit="micrometer"))
False

Parameters:

Name Type Description Default
other Axis

The axis to compare with.

required

Returns:

Type Description
bool

Whether no field is set on both sides to different values.

Raises:

Type Description
TypeError

If other is not an Axis.

merge_with

merge_with(other: Axis) -> Axis

Combine two compatible axes.

The input axes must be compatible in the sense of compatible_with. The resulting axis has all non-None values found on either axis.

When both axes have different Axis subtypes, the resulting axis has the type of the most derived class. For example, an Axis merged with a SpaceAxis results in a SpaceAxis.

Example

>>> Axis(name="x").merge_with(SpaceAxis(unit="micrometer"))
SpaceAxis(name='x', unit='micrometer')
>>> Axis(name="x").merge_with(Axis(name="y"))
Traceback (most recent call last):
  ...
ValueError: Cannot merge axes that disagree on name: 'x' != 'y'.

Parameters:

Name Type Description Default
other Axis

Another description of the same axis.

required

Returns:

Type Description
Axis

A new axis with every field known to either side.

Raises:

Type Description
TypeError

If other is not an Axis.

ValueError

If the axes disagree on a field, or if neither class derives from the other.

TimeAxis magic

TimeAxis(name: str | None = None, type: NoRepr[...], unit: Inherit[TimeUnit | IndexUnit | None], discrete: bool | None = None, orientation: Orientation | None = None)

Bases: Axis

Axis that measures time, in a time unit or an index unit.

Parameters:

Name Type Description Default
name str

Name of the axis, such as "t".

None
type time

Pinned axis type.

"time"
unit TimeUnit | IndexUnit | str

Unit of the coordinates along the axis.

required

Other Parameters:

Name Type Description
discrete bool

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation Orientation | str

Meaningful direction of the axis, such as left to right.

name class-attribute instance-attribute

name: NotKwOnly[str | None] = None

Name of the axis, such as "x".

discrete class-attribute instance-attribute

discrete: bool | None = None

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation class-attribute instance-attribute

orientation: Orientation | None = None

Meaningful direction of the axis, such as left to right.

from_dict classmethod

from_dict(other: Mapping, *args, **kwargs) -> Self

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

from_instance classmethod

from_instance(other: Any, *args, **kwargs) -> Self

Build an instance from an instance of a related data model.

Two classes are related when:

  • one of them is a parent of the other, or
  • when both belong to the same polymorphic family, or
  • when they represent the same "data model".

In all these cases, attributes that have the same name also have the same meaning, so they can be copied by name.

Note

  • Only attributes that name keyword arguments are used.
  • An attribute that is None leaves the default of the class in place.
  • Extra arguments (*args and **kwargs) are passed to the constructor and take precedence.
  • Unless other is already an instance of this class, an attribute of the instance that that corresponds to a fixed attribute in the target class is checked against its value.
  • In genemost casesral, cls.from_instance(other) is equivalent to other.to(cls, copy=True).

Parameters:

Name Type Description Default
other DataModelBase

The instance to copy.

required
*args Any

Constructor arguments, which take precedence over the fields of other.

()
**kwargs Any

Constructor arguments, which take precedence over the fields of other.

{}

Returns:

Type Description
Self

The new instance.

Raises:

Type Description
TypeError

If other is not an instance of a data model. A file, a mapping and any other value are read by from_any.

ConversionError

If the class of other is not related to this class, so that fields with the same name may mean different things.

ValueError

If a fixed field of other is set to a value other than the value that the class fixes.

from_any classmethod

from_any(other: Any, *args, **kwargs) -> Self

Build an instance from a mapping, a data model or an argument.

This constructors dispatches to from_dict, from_instance or the constructor, depending on the type of other.

Raises:

Type Description
TypeError

If a mapping has a key that names no field. Unlike from_dict, this method catches misspelled keys.

to

to(
    cls: type | None = None, *, copy: bool = False, **kwargs
) -> Any

Convert the object to another class of its data model.

Without a class, the object keeps its own class, and its attributes may be replaced by the keyword arguments.

Otherwise, the object is converted by cls.from_instance, which copies the attributes of a related class by name. Some subclasses override this method so that it triggers a more specific conversion.

Parameters:

Name Type Description Default
cls type

The class to convert to. By default, the class of the object.

None
copy bool

Whether to return a new object even when nothing changes.

False
**kwargs Any

Fields of the result, which take precedence over those of the object.

{}

Returns:

Type Description
DataModelBase

The converted object, an instance of cls.

Raises:

Type Description
ConversionError

If cls is not related to the class of the object.

compatible_with

compatible_with(other: Axis) -> bool

Return whether two axes could describe the same axis.

Two axes are compatible when all their fields have either the same value or at least one of them has the value None.

The relation is symmetric but not transitive: Axis() is compatible with Axis(name="x") and Axis(name="y"), but these two are not compatible with each other.

Example

>>> Axis(name="x").compatible_with(Axis(name="x", unit="mm"))
True
>>> Axis(name="x").compatible_with(Axis(name="y"))
False
>>> SpaceAxis(unit="mm").compatible_with(Axis(unit="micrometer"))
False

Parameters:

Name Type Description Default
other Axis

The axis to compare with.

required

Returns:

Type Description
bool

Whether no field is set on both sides to different values.

Raises:

Type Description
TypeError

If other is not an Axis.

merge_with

merge_with(other: Axis) -> Axis

Combine two compatible axes.

The input axes must be compatible in the sense of compatible_with. The resulting axis has all non-None values found on either axis.

When both axes have different Axis subtypes, the resulting axis has the type of the most derived class. For example, an Axis merged with a SpaceAxis results in a SpaceAxis.

Example

>>> Axis(name="x").merge_with(SpaceAxis(unit="micrometer"))
SpaceAxis(name='x', unit='micrometer')
>>> Axis(name="x").merge_with(Axis(name="y"))
Traceback (most recent call last):
  ...
ValueError: Cannot merge axes that disagree on name: 'x' != 'y'.

Parameters:

Name Type Description Default
other Axis

Another description of the same axis.

required

Returns:

Type Description
Axis

A new axis with every field known to either side.

Raises:

Type Description
TypeError

If other is not an Axis.

ValueError

If the axes disagree on a field, or if neither class derives from the other.

ChannelAxis magic

ChannelAxis(name: str | None = None, type: NoRepr[...], unit: Unit | None = None, discrete: bool | None = None, orientation: Orientation | None = None)

Bases: Axis

Axis that enumerates channels, such as colours or features.

Parameters:

Name Type Description Default
name str

Name of the axis, such as "c".

None
type channel

Pinned axis type.

"channel"
unit Unit | str

Unit of the coordinates along the axis.

None

Other Parameters:

Name Type Description
discrete bool

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation Orientation | str

Meaningful direction of the axis, such as left to right.

name class-attribute instance-attribute

name: NotKwOnly[str | None] = None

Name of the axis, such as "x".

unit class-attribute instance-attribute

unit: NotKwOnly[Unit | None] = None

Unit of the coordinates along the axis.

discrete class-attribute instance-attribute

discrete: bool | None = None

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation class-attribute instance-attribute

orientation: Orientation | None = None

Meaningful direction of the axis, such as left to right.

from_dict classmethod

from_dict(other: Mapping, *args, **kwargs) -> Self

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

from_instance classmethod

from_instance(other: Any, *args, **kwargs) -> Self

Build an instance from an instance of a related data model.

Two classes are related when:

  • one of them is a parent of the other, or
  • when both belong to the same polymorphic family, or
  • when they represent the same "data model".

In all these cases, attributes that have the same name also have the same meaning, so they can be copied by name.

Note

  • Only attributes that name keyword arguments are used.
  • An attribute that is None leaves the default of the class in place.
  • Extra arguments (*args and **kwargs) are passed to the constructor and take precedence.
  • Unless other is already an instance of this class, an attribute of the instance that that corresponds to a fixed attribute in the target class is checked against its value.
  • In genemost casesral, cls.from_instance(other) is equivalent to other.to(cls, copy=True).

Parameters:

Name Type Description Default
other DataModelBase

The instance to copy.

required
*args Any

Constructor arguments, which take precedence over the fields of other.

()
**kwargs Any

Constructor arguments, which take precedence over the fields of other.

{}

Returns:

Type Description
Self

The new instance.

Raises:

Type Description
TypeError

If other is not an instance of a data model. A file, a mapping and any other value are read by from_any.

ConversionError

If the class of other is not related to this class, so that fields with the same name may mean different things.

ValueError

If a fixed field of other is set to a value other than the value that the class fixes.

from_any classmethod

from_any(other: Any, *args, **kwargs) -> Self

Build an instance from a mapping, a data model or an argument.

This constructors dispatches to from_dict, from_instance or the constructor, depending on the type of other.

Raises:

Type Description
TypeError

If a mapping has a key that names no field. Unlike from_dict, this method catches misspelled keys.

to

to(
    cls: type | None = None, *, copy: bool = False, **kwargs
) -> Any

Convert the object to another class of its data model.

Without a class, the object keeps its own class, and its attributes may be replaced by the keyword arguments.

Otherwise, the object is converted by cls.from_instance, which copies the attributes of a related class by name. Some subclasses override this method so that it triggers a more specific conversion.

Parameters:

Name Type Description Default
cls type

The class to convert to. By default, the class of the object.

None
copy bool

Whether to return a new object even when nothing changes.

False
**kwargs Any

Fields of the result, which take precedence over those of the object.

{}

Returns:

Type Description
DataModelBase

The converted object, an instance of cls.

Raises:

Type Description
ConversionError

If cls is not related to the class of the object.

compatible_with

compatible_with(other: Axis) -> bool

Return whether two axes could describe the same axis.

Two axes are compatible when all their fields have either the same value or at least one of them has the value None.

The relation is symmetric but not transitive: Axis() is compatible with Axis(name="x") and Axis(name="y"), but these two are not compatible with each other.

Example

>>> Axis(name="x").compatible_with(Axis(name="x", unit="mm"))
True
>>> Axis(name="x").compatible_with(Axis(name="y"))
False
>>> SpaceAxis(unit="mm").compatible_with(Axis(unit="micrometer"))
False

Parameters:

Name Type Description Default
other Axis

The axis to compare with.

required

Returns:

Type Description
bool

Whether no field is set on both sides to different values.

Raises:

Type Description
TypeError

If other is not an Axis.

merge_with

merge_with(other: Axis) -> Axis

Combine two compatible axes.

The input axes must be compatible in the sense of compatible_with. The resulting axis has all non-None values found on either axis.

When both axes have different Axis subtypes, the resulting axis has the type of the most derived class. For example, an Axis merged with a SpaceAxis results in a SpaceAxis.

Example

>>> Axis(name="x").merge_with(SpaceAxis(unit="micrometer"))
SpaceAxis(name='x', unit='micrometer')
>>> Axis(name="x").merge_with(Axis(name="y"))
Traceback (most recent call last):
  ...
ValueError: Cannot merge axes that disagree on name: 'x' != 'y'.

Parameters:

Name Type Description Default
other Axis

Another description of the same axis.

required

Returns:

Type Description
Axis

A new axis with every field known to either side.

Raises:

Type Description
TypeError

If other is not an Axis.

ValueError

If the axes disagree on a field, or if neither class derives from the other.

OrientedAxis magic

OrientedAxis(
    name: str | None = None,
    type: AxisType | str | None = None,
    unit: Unit | None = None,
    discrete: bool | None = None,
    orientation: Orientation | None = None,
)

Bases: Axis

Axis that carries an orientation.

Parameters:

Name Type Description Default
name str

Name of the axis, such as "x".

None
type AxisType | str

Type of the axis, such as "space" or "time".

None
unit Unit | str

Unit of the coordinates along the axis.

None

Other Parameters:

Name Type Description
discrete bool

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation (Orientation, required)

Meaningful direction of the axis, such as left to right.

name class-attribute instance-attribute

name: NotKwOnly[str | None] = None

Name of the axis, such as "x".

type class-attribute instance-attribute

type: NotKwOnly[AxisType | str | None] = None

Type of the axis, such as "space" or "time".

unit class-attribute instance-attribute

unit: NotKwOnly[Unit | None] = None

Unit of the coordinates along the axis.

discrete class-attribute instance-attribute

discrete: bool | None = None

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation class-attribute instance-attribute

orientation: Orientation | None = None

Meaningful direction of the axis, such as left to right.

from_dict classmethod

from_dict(other: Mapping, *args, **kwargs) -> Self

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

from_instance classmethod

from_instance(other: Any, *args, **kwargs) -> Self

Build an instance from an instance of a related data model.

Two classes are related when:

  • one of them is a parent of the other, or
  • when both belong to the same polymorphic family, or
  • when they represent the same "data model".

In all these cases, attributes that have the same name also have the same meaning, so they can be copied by name.

Note

  • Only attributes that name keyword arguments are used.
  • An attribute that is None leaves the default of the class in place.
  • Extra arguments (*args and **kwargs) are passed to the constructor and take precedence.
  • Unless other is already an instance of this class, an attribute of the instance that that corresponds to a fixed attribute in the target class is checked against its value.
  • In genemost casesral, cls.from_instance(other) is equivalent to other.to(cls, copy=True).

Parameters:

Name Type Description Default
other DataModelBase

The instance to copy.

required
*args Any

Constructor arguments, which take precedence over the fields of other.

()
**kwargs Any

Constructor arguments, which take precedence over the fields of other.

{}

Returns:

Type Description
Self

The new instance.

Raises:

Type Description
TypeError

If other is not an instance of a data model. A file, a mapping and any other value are read by from_any.

ConversionError

If the class of other is not related to this class, so that fields with the same name may mean different things.

ValueError

If a fixed field of other is set to a value other than the value that the class fixes.

from_any classmethod

from_any(other: Any, *args, **kwargs) -> Self

Build an instance from a mapping, a data model or an argument.

This constructors dispatches to from_dict, from_instance or the constructor, depending on the type of other.

Raises:

Type Description
TypeError

If a mapping has a key that names no field. Unlike from_dict, this method catches misspelled keys.

to

to(
    cls: type | None = None, *, copy: bool = False, **kwargs
) -> Any

Convert the object to another class of its data model.

Without a class, the object keeps its own class, and its attributes may be replaced by the keyword arguments.

Otherwise, the object is converted by cls.from_instance, which copies the attributes of a related class by name. Some subclasses override this method so that it triggers a more specific conversion.

Parameters:

Name Type Description Default
cls type

The class to convert to. By default, the class of the object.

None
copy bool

Whether to return a new object even when nothing changes.

False
**kwargs Any

Fields of the result, which take precedence over those of the object.

{}

Returns:

Type Description
DataModelBase

The converted object, an instance of cls.

Raises:

Type Description
ConversionError

If cls is not related to the class of the object.

compatible_with

compatible_with(other: Axis) -> bool

Return whether two axes could describe the same axis.

Two axes are compatible when all their fields have either the same value or at least one of them has the value None.

The relation is symmetric but not transitive: Axis() is compatible with Axis(name="x") and Axis(name="y"), but these two are not compatible with each other.

Example

>>> Axis(name="x").compatible_with(Axis(name="x", unit="mm"))
True
>>> Axis(name="x").compatible_with(Axis(name="y"))
False
>>> SpaceAxis(unit="mm").compatible_with(Axis(unit="micrometer"))
False

Parameters:

Name Type Description Default
other Axis

The axis to compare with.

required

Returns:

Type Description
bool

Whether no field is set on both sides to different values.

Raises:

Type Description
TypeError

If other is not an Axis.

merge_with

merge_with(other: Axis) -> Axis

Combine two compatible axes.

The input axes must be compatible in the sense of compatible_with. The resulting axis has all non-None values found on either axis.

When both axes have different Axis subtypes, the resulting axis has the type of the most derived class. For example, an Axis merged with a SpaceAxis results in a SpaceAxis.

Example

>>> Axis(name="x").merge_with(SpaceAxis(unit="micrometer"))
SpaceAxis(name='x', unit='micrometer')
>>> Axis(name="x").merge_with(Axis(name="y"))
Traceback (most recent call last):
  ...
ValueError: Cannot merge axes that disagree on name: 'x' != 'y'.

Parameters:

Name Type Description Default
other Axis

Another description of the same axis.

required

Returns:

Type Description
Axis

A new axis with every field known to either side.

Raises:

Type Description
TypeError

If other is not an Axis.

ValueError

If the axes disagree on a field, or if neither class derives from the other.

OrientedSpaceAxis magic

OrientedSpaceAxis(name: str | None = None, type: NoRepr[...], unit: Inherit[SpaceUnit | IndexUnit | None], discrete: bool | None = None, orientation: Orientation | None = None)

Bases: SpaceAxis, OrientedAxis

Spatial axis with an orientation.

Parameters:

Name Type Description Default
name str

Name of the axis, such as "x".

None
type space

Pinned axis type.

"space"
unit SpaceUnit | IndexUnit | str

Unit of the coordinates along the axis.

required

Other Parameters:

Name Type Description
discrete bool

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation (Orientation, required)

Meaningful direction of the axis, such as left to right.

name class-attribute instance-attribute

name: NotKwOnly[str | None] = None

Name of the axis, such as "x".

discrete class-attribute instance-attribute

discrete: bool | None = None

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation class-attribute instance-attribute

orientation: Orientation | None = None

Meaningful direction of the axis, such as left to right.

from_dict classmethod

from_dict(other: Mapping, *args, **kwargs) -> Self

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

from_instance classmethod

from_instance(other: Any, *args, **kwargs) -> Self

Build an instance from an instance of a related data model.

Two classes are related when:

  • one of them is a parent of the other, or
  • when both belong to the same polymorphic family, or
  • when they represent the same "data model".

In all these cases, attributes that have the same name also have the same meaning, so they can be copied by name.

Note

  • Only attributes that name keyword arguments are used.
  • An attribute that is None leaves the default of the class in place.
  • Extra arguments (*args and **kwargs) are passed to the constructor and take precedence.
  • Unless other is already an instance of this class, an attribute of the instance that that corresponds to a fixed attribute in the target class is checked against its value.
  • In genemost casesral, cls.from_instance(other) is equivalent to other.to(cls, copy=True).

Parameters:

Name Type Description Default
other DataModelBase

The instance to copy.

required
*args Any

Constructor arguments, which take precedence over the fields of other.

()
**kwargs Any

Constructor arguments, which take precedence over the fields of other.

{}

Returns:

Type Description
Self

The new instance.

Raises:

Type Description
TypeError

If other is not an instance of a data model. A file, a mapping and any other value are read by from_any.

ConversionError

If the class of other is not related to this class, so that fields with the same name may mean different things.

ValueError

If a fixed field of other is set to a value other than the value that the class fixes.

from_any classmethod

from_any(other: Any, *args, **kwargs) -> Self

Build an instance from a mapping, a data model or an argument.

This constructors dispatches to from_dict, from_instance or the constructor, depending on the type of other.

Raises:

Type Description
TypeError

If a mapping has a key that names no field. Unlike from_dict, this method catches misspelled keys.

to

to(
    cls: type | None = None, *, copy: bool = False, **kwargs
) -> Any

Convert the object to another class of its data model.

Without a class, the object keeps its own class, and its attributes may be replaced by the keyword arguments.

Otherwise, the object is converted by cls.from_instance, which copies the attributes of a related class by name. Some subclasses override this method so that it triggers a more specific conversion.

Parameters:

Name Type Description Default
cls type

The class to convert to. By default, the class of the object.

None
copy bool

Whether to return a new object even when nothing changes.

False
**kwargs Any

Fields of the result, which take precedence over those of the object.

{}

Returns:

Type Description
DataModelBase

The converted object, an instance of cls.

Raises:

Type Description
ConversionError

If cls is not related to the class of the object.

compatible_with

compatible_with(other: Axis) -> bool

Return whether two axes could describe the same axis.

Two axes are compatible when all their fields have either the same value or at least one of them has the value None.

The relation is symmetric but not transitive: Axis() is compatible with Axis(name="x") and Axis(name="y"), but these two are not compatible with each other.

Example

>>> Axis(name="x").compatible_with(Axis(name="x", unit="mm"))
True
>>> Axis(name="x").compatible_with(Axis(name="y"))
False
>>> SpaceAxis(unit="mm").compatible_with(Axis(unit="micrometer"))
False

Parameters:

Name Type Description Default
other Axis

The axis to compare with.

required

Returns:

Type Description
bool

Whether no field is set on both sides to different values.

Raises:

Type Description
TypeError

If other is not an Axis.

merge_with

merge_with(other: Axis) -> Axis

Combine two compatible axes.

The input axes must be compatible in the sense of compatible_with. The resulting axis has all non-None values found on either axis.

When both axes have different Axis subtypes, the resulting axis has the type of the most derived class. For example, an Axis merged with a SpaceAxis results in a SpaceAxis.

Example

>>> Axis(name="x").merge_with(SpaceAxis(unit="micrometer"))
SpaceAxis(name='x', unit='micrometer')
>>> Axis(name="x").merge_with(Axis(name="y"))
Traceback (most recent call last):
  ...
ValueError: Cannot merge axes that disagree on name: 'x' != 'y'.

Parameters:

Name Type Description Default
other Axis

Another description of the same axis.

required

Returns:

Type Description
Axis

A new axis with every field known to either side.

Raises:

Type Description
TypeError

If other is not an Axis.

ValueError

If the axes disagree on a field, or if neither class derives from the other.

OrientedTimeAxis magic

OrientedTimeAxis(name: str | None = None, type: NoRepr[...], unit: Inherit[TimeUnit | IndexUnit | None], discrete: bool | None = None, orientation: Orientation | None = None)

Bases: TimeAxis, OrientedAxis

Time axis with an orientation.

Parameters:

Name Type Description Default
name str

Name of the axis, such as "t".

None
type time

Pinned axis type.

"time"
unit TimeUnit | IndexUnit | str

Unit of the coordinates along the axis.

required

Other Parameters:

Name Type Description
discrete bool

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation (Orientation, required)

Meaningful direction of the axis, such as forward.

name class-attribute instance-attribute

name: NotKwOnly[str | None] = None

Name of the axis, such as "x".

discrete class-attribute instance-attribute

discrete: bool | None = None

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation class-attribute instance-attribute

orientation: Orientation | None = None

Meaningful direction of the axis, such as left to right.

from_dict classmethod

from_dict(other: Mapping, *args, **kwargs) -> Self

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

from_instance classmethod

from_instance(other: Any, *args, **kwargs) -> Self

Build an instance from an instance of a related data model.

Two classes are related when:

  • one of them is a parent of the other, or
  • when both belong to the same polymorphic family, or
  • when they represent the same "data model".

In all these cases, attributes that have the same name also have the same meaning, so they can be copied by name.

Note

  • Only attributes that name keyword arguments are used.
  • An attribute that is None leaves the default of the class in place.
  • Extra arguments (*args and **kwargs) are passed to the constructor and take precedence.
  • Unless other is already an instance of this class, an attribute of the instance that that corresponds to a fixed attribute in the target class is checked against its value.
  • In genemost casesral, cls.from_instance(other) is equivalent to other.to(cls, copy=True).

Parameters:

Name Type Description Default
other DataModelBase

The instance to copy.

required
*args Any

Constructor arguments, which take precedence over the fields of other.

()
**kwargs Any

Constructor arguments, which take precedence over the fields of other.

{}

Returns:

Type Description
Self

The new instance.

Raises:

Type Description
TypeError

If other is not an instance of a data model. A file, a mapping and any other value are read by from_any.

ConversionError

If the class of other is not related to this class, so that fields with the same name may mean different things.

ValueError

If a fixed field of other is set to a value other than the value that the class fixes.

from_any classmethod

from_any(other: Any, *args, **kwargs) -> Self

Build an instance from a mapping, a data model or an argument.

This constructors dispatches to from_dict, from_instance or the constructor, depending on the type of other.

Raises:

Type Description
TypeError

If a mapping has a key that names no field. Unlike from_dict, this method catches misspelled keys.

to

to(
    cls: type | None = None, *, copy: bool = False, **kwargs
) -> Any

Convert the object to another class of its data model.

Without a class, the object keeps its own class, and its attributes may be replaced by the keyword arguments.

Otherwise, the object is converted by cls.from_instance, which copies the attributes of a related class by name. Some subclasses override this method so that it triggers a more specific conversion.

Parameters:

Name Type Description Default
cls type

The class to convert to. By default, the class of the object.

None
copy bool

Whether to return a new object even when nothing changes.

False
**kwargs Any

Fields of the result, which take precedence over those of the object.

{}

Returns:

Type Description
DataModelBase

The converted object, an instance of cls.

Raises:

Type Description
ConversionError

If cls is not related to the class of the object.

compatible_with

compatible_with(other: Axis) -> bool

Return whether two axes could describe the same axis.

Two axes are compatible when all their fields have either the same value or at least one of them has the value None.

The relation is symmetric but not transitive: Axis() is compatible with Axis(name="x") and Axis(name="y"), but these two are not compatible with each other.

Example

>>> Axis(name="x").compatible_with(Axis(name="x", unit="mm"))
True
>>> Axis(name="x").compatible_with(Axis(name="y"))
False
>>> SpaceAxis(unit="mm").compatible_with(Axis(unit="micrometer"))
False

Parameters:

Name Type Description Default
other Axis

The axis to compare with.

required

Returns:

Type Description
bool

Whether no field is set on both sides to different values.

Raises:

Type Description
TypeError

If other is not an Axis.

merge_with

merge_with(other: Axis) -> Axis

Combine two compatible axes.

The input axes must be compatible in the sense of compatible_with. The resulting axis has all non-None values found on either axis.

When both axes have different Axis subtypes, the resulting axis has the type of the most derived class. For example, an Axis merged with a SpaceAxis results in a SpaceAxis.

Example

>>> Axis(name="x").merge_with(SpaceAxis(unit="micrometer"))
SpaceAxis(name='x', unit='micrometer')
>>> Axis(name="x").merge_with(Axis(name="y"))
Traceback (most recent call last):
  ...
ValueError: Cannot merge axes that disagree on name: 'x' != 'y'.

Parameters:

Name Type Description Default
other Axis

Another description of the same axis.

required

Returns:

Type Description
Axis

A new axis with every field known to either side.

Raises:

Type Description
TypeError

If other is not an Axis.

ValueError

If the axes disagree on a field, or if neither class derives from the other.

Component axes

Axes whose entries are the components of points, vectors or tensors.

Most axes of an image enumerate independent values, such as the colours of an RGB image. Some axes hold instead the components of a geometric object, such as a displacement, the gradient of an image or a diffusion tensor. These axes are called component axes, and their type says what the object is:

Class type Action of a linear map J
PointAxis "point" none (see below)
CoordinateAxis "coordinate" none, as for "point"
VectorAxis "vector" v ↦ J v, or g ↦ J⁻ᵀ g
DisplacementAxis "displacement" v ↦ J v
TensorAxis "tensor" J or J⁻ᵀ on each index

The valence of a vector or a tensor says, for each of its indices, whether the index is multiplied by J (a "vector" index) or by J⁻ᵀ (a "covector" index). The gradient of an image is a vector whose valence is "covector".

When an image is moved or resampled, the components of vectors and tensors must be re-expressed with the Jacobian of the transformation. The components are expressed in a coordinate system, called the frame of the values, which the image records in SingleScaleImage.frames. The entries of a vector axis follow axes of the system of that frame, in order, and SingleScaleImage.reframe changes the frame. The coordinates of a point change with the map itself rather than with its Jacobian, so they are not re-expressed.

The design is recorded in spec/design/vector-and-tensor-images.md.

COMPONENT_TYPES module-attribute

COMPONENT_TYPES: FrozenSet[str] = frozenset(
    {
        AxisType.point,
        AxisType.coordinate,
        AxisType.vector,
        AxisType.displacement,
        AxisType.tensor,
    }
)

The types of the axes whose entries are the components of an object.

ComponentAxis magic

ComponentAxis(
    name: str | None = None,
    type: AxisType | str | None = None,
    unit: Unit | None = None,
    discrete: bool | None = None,
    orientation: Orientation | None = None,
)

Bases: Axis

Axis whose entries are the components of a point, vector or tensor.

This class is the common base of the classes of the component axes, and calling Axis with one of their types builds one of them. It says how many axes of the frame the entries follow, and how the entries change when the frame changes by a linear map.

Parameters:

Name Type Description Default
name str

Name of the axis, such as "c".

None
type AxisType | str

Type of the axis, such as "vector".

None
unit Unit | str

Unit of the coordinates along the axis.

None

Other Parameters:

Name Type Description
discrete bool

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation Orientation | str

Meaningful direction of the axis, such as left to right.

valences property

valences: tuple[Valence, ...] | None

The valence of each index of the object, or None for a point.

A vector has one index, whose valence is its valence, a displacement has one index of valence "vector", and a tensor has one per entry of its valence. A point has no valence, because its coordinates do not change with the Jacobian of a map.

name class-attribute instance-attribute

name: NotKwOnly[str | None] = None

Name of the axis, such as "x".

type class-attribute instance-attribute

type: NotKwOnly[AxisType | str | None] = None

Type of the axis, such as "space" or "time".

unit class-attribute instance-attribute

unit: NotKwOnly[Unit | None] = None

Unit of the coordinates along the axis.

discrete class-attribute instance-attribute

discrete: bool | None = None

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation class-attribute instance-attribute

orientation: Orientation | None = None

Meaningful direction of the axis, such as left to right.

frame_ndim

frame_ndim(size: int, ndim: int | None = None) -> int

Return the number of axes of the frame that the entries follow.

Each entry of a point or a vector follows one axis of the frame, so this number is the number of entries.

Parameters:

Name Type Description Default
size int

The number of entries along the axis.

required
ndim int

The number of axes of the frame, when it is known from elsewhere. It is checked against size.

None

Returns:

Type Description
int

The number of axes of the frame that the entries follow.

Raises:

Type Description
ValueError

If ndim is given and differs from size.

apply

apply(
    values: ArrayProtocol, matrix: ArrayProtocol, axis: int
) -> ArrayProtocol

Apply a linear map of the frame to the entries along an axis.

Each index of the object is multiplied by the map J when it is a vector index and by J⁻ᵀ when it is a covector index, so that a vector becomes J v and a vector of valence "covector" becomes J⁻ᵀ g.

Parameters:

Name Type Description Default
values ArrayProtocol

The values of the image.

required
matrix ArrayProtocol

The linear map J, of shape (*batch, n, n), where batch broadcasts against the shape of values without axis.

required
axis int

The axis of values whose entries are transformed.

required

Returns:

Type Description
ArrayProtocol

The transformed values, with the shape of values.

Raises:

Type Description
NotImplementedError

If the entries are the coordinates of points, which the Jacobian of a map does not re-express.

from_dict classmethod

from_dict(other: Mapping, *args, **kwargs) -> Self

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

from_instance classmethod

from_instance(other: Any, *args, **kwargs) -> Self

Build an instance from an instance of a related data model.

Two classes are related when:

  • one of them is a parent of the other, or
  • when both belong to the same polymorphic family, or
  • when they represent the same "data model".

In all these cases, attributes that have the same name also have the same meaning, so they can be copied by name.

Note

  • Only attributes that name keyword arguments are used.
  • An attribute that is None leaves the default of the class in place.
  • Extra arguments (*args and **kwargs) are passed to the constructor and take precedence.
  • Unless other is already an instance of this class, an attribute of the instance that that corresponds to a fixed attribute in the target class is checked against its value.
  • In genemost casesral, cls.from_instance(other) is equivalent to other.to(cls, copy=True).

Parameters:

Name Type Description Default
other DataModelBase

The instance to copy.

required
*args Any

Constructor arguments, which take precedence over the fields of other.

()
**kwargs Any

Constructor arguments, which take precedence over the fields of other.

{}

Returns:

Type Description
Self

The new instance.

Raises:

Type Description
TypeError

If other is not an instance of a data model. A file, a mapping and any other value are read by from_any.

ConversionError

If the class of other is not related to this class, so that fields with the same name may mean different things.

ValueError

If a fixed field of other is set to a value other than the value that the class fixes.

from_any classmethod

from_any(other: Any, *args, **kwargs) -> Self

Build an instance from a mapping, a data model or an argument.

This constructors dispatches to from_dict, from_instance or the constructor, depending on the type of other.

Raises:

Type Description
TypeError

If a mapping has a key that names no field. Unlike from_dict, this method catches misspelled keys.

to

to(
    cls: type | None = None, *, copy: bool = False, **kwargs
) -> Any

Convert the object to another class of its data model.

Without a class, the object keeps its own class, and its attributes may be replaced by the keyword arguments.

Otherwise, the object is converted by cls.from_instance, which copies the attributes of a related class by name. Some subclasses override this method so that it triggers a more specific conversion.

Parameters:

Name Type Description Default
cls type

The class to convert to. By default, the class of the object.

None
copy bool

Whether to return a new object even when nothing changes.

False
**kwargs Any

Fields of the result, which take precedence over those of the object.

{}

Returns:

Type Description
DataModelBase

The converted object, an instance of cls.

Raises:

Type Description
ConversionError

If cls is not related to the class of the object.

compatible_with

compatible_with(other: Axis) -> bool

Return whether two axes could describe the same axis.

Two axes are compatible when all their fields have either the same value or at least one of them has the value None.

The relation is symmetric but not transitive: Axis() is compatible with Axis(name="x") and Axis(name="y"), but these two are not compatible with each other.

Example

>>> Axis(name="x").compatible_with(Axis(name="x", unit="mm"))
True
>>> Axis(name="x").compatible_with(Axis(name="y"))
False
>>> SpaceAxis(unit="mm").compatible_with(Axis(unit="micrometer"))
False

Parameters:

Name Type Description Default
other Axis

The axis to compare with.

required

Returns:

Type Description
bool

Whether no field is set on both sides to different values.

Raises:

Type Description
TypeError

If other is not an Axis.

merge_with

merge_with(other: Axis) -> Axis

Combine two compatible axes.

The input axes must be compatible in the sense of compatible_with. The resulting axis has all non-None values found on either axis.

When both axes have different Axis subtypes, the resulting axis has the type of the most derived class. For example, an Axis merged with a SpaceAxis results in a SpaceAxis.

Example

>>> Axis(name="x").merge_with(SpaceAxis(unit="micrometer"))
SpaceAxis(name='x', unit='micrometer')
>>> Axis(name="x").merge_with(Axis(name="y"))
Traceback (most recent call last):
  ...
ValueError: Cannot merge axes that disagree on name: 'x' != 'y'.

Parameters:

Name Type Description Default
other Axis

Another description of the same axis.

required

Returns:

Type Description
Axis

A new axis with every field known to either side.

Raises:

Type Description
TypeError

If other is not an Axis.

ValueError

If the axes disagree on a field, or if neither class derives from the other.

PointAxis magic

PointAxis(name: str | None = None, type: NoRepr[...], unit: Unit | None = None, discrete: bool | None = None, orientation: Orientation | None = None)

Bases: ComponentAxis

Axis whose entries are the coordinates of points.

An image of points holds, at each voxel, the position of a point in some space, such as the position that a voxel maps to. Moving these points into another frame needs the map itself rather than its Jacobian, so [apply][brainhops.datamodel.axes.ComponentAxis.apply] and SingleScaleImage.reframe raise NotImplementedError on such an axis. The axis can still have a frame, which records the space of the points.

Parameters:

Name Type Description Default
name str

Name of the axis, such as "c".

None
type point

Pinned axis type.

"point"
unit Unit | str

Unit of the coordinates along the axis.

None

Other Parameters:

Name Type Description
discrete bool

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation Orientation | str

Meaningful direction of the axis, such as left to right.

name class-attribute instance-attribute

name: NotKwOnly[str | None] = None

Name of the axis, such as "x".

unit class-attribute instance-attribute

unit: NotKwOnly[Unit | None] = None

Unit of the coordinates along the axis.

discrete class-attribute instance-attribute

discrete: bool | None = None

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation class-attribute instance-attribute

orientation: Orientation | None = None

Meaningful direction of the axis, such as left to right.

valences property

valences: tuple[Valence, ...] | None

The valence of each index of the object, or None for a point.

A vector has one index, whose valence is its valence, a displacement has one index of valence "vector", and a tensor has one per entry of its valence. A point has no valence, because its coordinates do not change with the Jacobian of a map.

from_dict classmethod

from_dict(other: Mapping, *args, **kwargs) -> Self

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

from_instance classmethod

from_instance(other: Any, *args, **kwargs) -> Self

Build an instance from an instance of a related data model.

Two classes are related when:

  • one of them is a parent of the other, or
  • when both belong to the same polymorphic family, or
  • when they represent the same "data model".

In all these cases, attributes that have the same name also have the same meaning, so they can be copied by name.

Note

  • Only attributes that name keyword arguments are used.
  • An attribute that is None leaves the default of the class in place.
  • Extra arguments (*args and **kwargs) are passed to the constructor and take precedence.
  • Unless other is already an instance of this class, an attribute of the instance that that corresponds to a fixed attribute in the target class is checked against its value.
  • In genemost casesral, cls.from_instance(other) is equivalent to other.to(cls, copy=True).

Parameters:

Name Type Description Default
other DataModelBase

The instance to copy.

required
*args Any

Constructor arguments, which take precedence over the fields of other.

()
**kwargs Any

Constructor arguments, which take precedence over the fields of other.

{}

Returns:

Type Description
Self

The new instance.

Raises:

Type Description
TypeError

If other is not an instance of a data model. A file, a mapping and any other value are read by from_any.

ConversionError

If the class of other is not related to this class, so that fields with the same name may mean different things.

ValueError

If a fixed field of other is set to a value other than the value that the class fixes.

from_any classmethod

from_any(other: Any, *args, **kwargs) -> Self

Build an instance from a mapping, a data model or an argument.

This constructors dispatches to from_dict, from_instance or the constructor, depending on the type of other.

Raises:

Type Description
TypeError

If a mapping has a key that names no field. Unlike from_dict, this method catches misspelled keys.

to

to(
    cls: type | None = None, *, copy: bool = False, **kwargs
) -> Any

Convert the object to another class of its data model.

Without a class, the object keeps its own class, and its attributes may be replaced by the keyword arguments.

Otherwise, the object is converted by cls.from_instance, which copies the attributes of a related class by name. Some subclasses override this method so that it triggers a more specific conversion.

Parameters:

Name Type Description Default
cls type

The class to convert to. By default, the class of the object.

None
copy bool

Whether to return a new object even when nothing changes.

False
**kwargs Any

Fields of the result, which take precedence over those of the object.

{}

Returns:

Type Description
DataModelBase

The converted object, an instance of cls.

Raises:

Type Description
ConversionError

If cls is not related to the class of the object.

compatible_with

compatible_with(other: Axis) -> bool

Return whether two axes could describe the same axis.

Two axes are compatible when all their fields have either the same value or at least one of them has the value None.

The relation is symmetric but not transitive: Axis() is compatible with Axis(name="x") and Axis(name="y"), but these two are not compatible with each other.

Example

>>> Axis(name="x").compatible_with(Axis(name="x", unit="mm"))
True
>>> Axis(name="x").compatible_with(Axis(name="y"))
False
>>> SpaceAxis(unit="mm").compatible_with(Axis(unit="micrometer"))
False

Parameters:

Name Type Description Default
other Axis

The axis to compare with.

required

Returns:

Type Description
bool

Whether no field is set on both sides to different values.

Raises:

Type Description
TypeError

If other is not an Axis.

merge_with

merge_with(other: Axis) -> Axis

Combine two compatible axes.

The input axes must be compatible in the sense of compatible_with. The resulting axis has all non-None values found on either axis.

When both axes have different Axis subtypes, the resulting axis has the type of the most derived class. For example, an Axis merged with a SpaceAxis results in a SpaceAxis.

Example

>>> Axis(name="x").merge_with(SpaceAxis(unit="micrometer"))
SpaceAxis(name='x', unit='micrometer')
>>> Axis(name="x").merge_with(Axis(name="y"))
Traceback (most recent call last):
  ...
ValueError: Cannot merge axes that disagree on name: 'x' != 'y'.

Parameters:

Name Type Description Default
other Axis

Another description of the same axis.

required

Returns:

Type Description
Axis

A new axis with every field known to either side.

Raises:

Type Description
TypeError

If other is not an Axis.

ValueError

If the axes disagree on a field, or if neither class derives from the other.

frame_ndim

frame_ndim(size: int, ndim: int | None = None) -> int

Return the number of axes of the frame that the entries follow.

Each entry of a point or a vector follows one axis of the frame, so this number is the number of entries.

Parameters:

Name Type Description Default
size int

The number of entries along the axis.

required
ndim int

The number of axes of the frame, when it is known from elsewhere. It is checked against size.

None

Returns:

Type Description
int

The number of axes of the frame that the entries follow.

Raises:

Type Description
ValueError

If ndim is given and differs from size.

apply

apply(
    values: ArrayProtocol, matrix: ArrayProtocol, axis: int
) -> ArrayProtocol

Apply a linear map of the frame to the entries along an axis.

Each index of the object is multiplied by the map J when it is a vector index and by J⁻ᵀ when it is a covector index, so that a vector becomes J v and a vector of valence "covector" becomes J⁻ᵀ g.

Parameters:

Name Type Description Default
values ArrayProtocol

The values of the image.

required
matrix ArrayProtocol

The linear map J, of shape (*batch, n, n), where batch broadcasts against the shape of values without axis.

required
axis int

The axis of values whose entries are transformed.

required

Returns:

Type Description
ArrayProtocol

The transformed values, with the shape of values.

Raises:

Type Description
NotImplementedError

If the entries are the coordinates of points, which the Jacobian of a map does not re-express.

CoordinateAxis magic

CoordinateAxis(name: str | None = None, type: NoRepr[...], unit: Unit | None = None, discrete: bool | None = None, orientation: Orientation | None = None)

Bases: ComponentAxis

Axis that enumerates the coordinates of the points of a field.

A coordinate field of OME-NGFF has its spatial axes and one coordinate axis. The axis behaves as a PointAxis, and its type is kept so that the fields of OME-NGFF keep their type.

Parameters:

Name Type Description Default
name str

Name of the axis, such as "c".

None
type coordinate

Pinned axis type.

"coordinate"
unit Unit | str

Unit of the coordinates along the axis.

None

Other Parameters:

Name Type Description
discrete bool

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation Orientation | str

Meaningful direction of the axis, such as left to right.

name class-attribute instance-attribute

name: NotKwOnly[str | None] = None

Name of the axis, such as "x".

unit class-attribute instance-attribute

unit: NotKwOnly[Unit | None] = None

Unit of the coordinates along the axis.

discrete class-attribute instance-attribute

discrete: bool | None = None

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation class-attribute instance-attribute

orientation: Orientation | None = None

Meaningful direction of the axis, such as left to right.

valences property

valences: tuple[Valence, ...] | None

The valence of each index of the object, or None for a point.

A vector has one index, whose valence is its valence, a displacement has one index of valence "vector", and a tensor has one per entry of its valence. A point has no valence, because its coordinates do not change with the Jacobian of a map.

from_dict classmethod

from_dict(other: Mapping, *args, **kwargs) -> Self

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

from_instance classmethod

from_instance(other: Any, *args, **kwargs) -> Self

Build an instance from an instance of a related data model.

Two classes are related when:

  • one of them is a parent of the other, or
  • when both belong to the same polymorphic family, or
  • when they represent the same "data model".

In all these cases, attributes that have the same name also have the same meaning, so they can be copied by name.

Note

  • Only attributes that name keyword arguments are used.
  • An attribute that is None leaves the default of the class in place.
  • Extra arguments (*args and **kwargs) are passed to the constructor and take precedence.
  • Unless other is already an instance of this class, an attribute of the instance that that corresponds to a fixed attribute in the target class is checked against its value.
  • In genemost casesral, cls.from_instance(other) is equivalent to other.to(cls, copy=True).

Parameters:

Name Type Description Default
other DataModelBase

The instance to copy.

required
*args Any

Constructor arguments, which take precedence over the fields of other.

()
**kwargs Any

Constructor arguments, which take precedence over the fields of other.

{}

Returns:

Type Description
Self

The new instance.

Raises:

Type Description
TypeError

If other is not an instance of a data model. A file, a mapping and any other value are read by from_any.

ConversionError

If the class of other is not related to this class, so that fields with the same name may mean different things.

ValueError

If a fixed field of other is set to a value other than the value that the class fixes.

from_any classmethod

from_any(other: Any, *args, **kwargs) -> Self

Build an instance from a mapping, a data model or an argument.

This constructors dispatches to from_dict, from_instance or the constructor, depending on the type of other.

Raises:

Type Description
TypeError

If a mapping has a key that names no field. Unlike from_dict, this method catches misspelled keys.

to

to(
    cls: type | None = None, *, copy: bool = False, **kwargs
) -> Any

Convert the object to another class of its data model.

Without a class, the object keeps its own class, and its attributes may be replaced by the keyword arguments.

Otherwise, the object is converted by cls.from_instance, which copies the attributes of a related class by name. Some subclasses override this method so that it triggers a more specific conversion.

Parameters:

Name Type Description Default
cls type

The class to convert to. By default, the class of the object.

None
copy bool

Whether to return a new object even when nothing changes.

False
**kwargs Any

Fields of the result, which take precedence over those of the object.

{}

Returns:

Type Description
DataModelBase

The converted object, an instance of cls.

Raises:

Type Description
ConversionError

If cls is not related to the class of the object.

compatible_with

compatible_with(other: Axis) -> bool

Return whether two axes could describe the same axis.

Two axes are compatible when all their fields have either the same value or at least one of them has the value None.

The relation is symmetric but not transitive: Axis() is compatible with Axis(name="x") and Axis(name="y"), but these two are not compatible with each other.

Example

>>> Axis(name="x").compatible_with(Axis(name="x", unit="mm"))
True
>>> Axis(name="x").compatible_with(Axis(name="y"))
False
>>> SpaceAxis(unit="mm").compatible_with(Axis(unit="micrometer"))
False

Parameters:

Name Type Description Default
other Axis

The axis to compare with.

required

Returns:

Type Description
bool

Whether no field is set on both sides to different values.

Raises:

Type Description
TypeError

If other is not an Axis.

merge_with

merge_with(other: Axis) -> Axis

Combine two compatible axes.

The input axes must be compatible in the sense of compatible_with. The resulting axis has all non-None values found on either axis.

When both axes have different Axis subtypes, the resulting axis has the type of the most derived class. For example, an Axis merged with a SpaceAxis results in a SpaceAxis.

Example

>>> Axis(name="x").merge_with(SpaceAxis(unit="micrometer"))
SpaceAxis(name='x', unit='micrometer')
>>> Axis(name="x").merge_with(Axis(name="y"))
Traceback (most recent call last):
  ...
ValueError: Cannot merge axes that disagree on name: 'x' != 'y'.

Parameters:

Name Type Description Default
other Axis

Another description of the same axis.

required

Returns:

Type Description
Axis

A new axis with every field known to either side.

Raises:

Type Description
TypeError

If other is not an Axis.

ValueError

If the axes disagree on a field, or if neither class derives from the other.

frame_ndim

frame_ndim(size: int, ndim: int | None = None) -> int

Return the number of axes of the frame that the entries follow.

Each entry of a point or a vector follows one axis of the frame, so this number is the number of entries.

Parameters:

Name Type Description Default
size int

The number of entries along the axis.

required
ndim int

The number of axes of the frame, when it is known from elsewhere. It is checked against size.

None

Returns:

Type Description
int

The number of axes of the frame that the entries follow.

Raises:

Type Description
ValueError

If ndim is given and differs from size.

apply

apply(
    values: ArrayProtocol, matrix: ArrayProtocol, axis: int
) -> ArrayProtocol

Apply a linear map of the frame to the entries along an axis.

Each index of the object is multiplied by the map J when it is a vector index and by J⁻ᵀ when it is a covector index, so that a vector becomes J v and a vector of valence "covector" becomes J⁻ᵀ g.

Parameters:

Name Type Description Default
values ArrayProtocol

The values of the image.

required
matrix ArrayProtocol

The linear map J, of shape (*batch, n, n), where batch broadcasts against the shape of values without axis.

required
axis int

The axis of values whose entries are transformed.

required

Returns:

Type Description
ArrayProtocol

The transformed values, with the shape of values.

Raises:

Type Description
NotImplementedError

If the entries are the coordinates of points, which the Jacobian of a map does not re-express.

VectorAxis magic

VectorAxis(name: str | None = None, type: NoRepr[...], unit: Unit | None = None, discrete: bool | None = None, orientation: Orientation | None = None, valence: Valence = vector)

Bases: ComponentAxis

Axis whose entries are the components of vectors.

A velocity or a fibre direction is a vector of valence "vector". When the frame changes by a linear map J, its components become J v. The gradient of an image and the normal of a surface are vectors of valence "covector", which are also called covectors. Their components become J⁻ᵀ g, so that the pairing of a covector with a vector does not change.

Parameters:

Name Type Description Default
name str

Name of the axis, such as "c".

None
type vector

Pinned axis type.

"vector"
unit Unit | str

Unit of the coordinates along the axis.

None
discrete bool

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

None
orientation Orientation | str

Meaningful direction of the axis, such as left to right.

None
valence Valence | str

Whether the components are multiplied by J or by J⁻ᵀ when the frame changes by J.

"vector"

valence class-attribute instance-attribute

valence: Valence = Valence.vector

Whether the components change with J or with J⁻ᵀ.

valences property

valences: tuple[Valence, ...]

The valence of the single index of the vector, its valence.

name class-attribute instance-attribute

name: NotKwOnly[str | None] = None

Name of the axis, such as "x".

unit class-attribute instance-attribute

unit: NotKwOnly[Unit | None] = None

Unit of the coordinates along the axis.

discrete class-attribute instance-attribute

discrete: bool | None = None

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation class-attribute instance-attribute

orientation: Orientation | None = None

Meaningful direction of the axis, such as left to right.

from_dict classmethod

from_dict(other: Mapping, *args, **kwargs) -> Self

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

from_instance classmethod

from_instance(other: Any, *args, **kwargs) -> Self

Build an instance from an instance of a related data model.

Two classes are related when:

  • one of them is a parent of the other, or
  • when both belong to the same polymorphic family, or
  • when they represent the same "data model".

In all these cases, attributes that have the same name also have the same meaning, so they can be copied by name.

Note

  • Only attributes that name keyword arguments are used.
  • An attribute that is None leaves the default of the class in place.
  • Extra arguments (*args and **kwargs) are passed to the constructor and take precedence.
  • Unless other is already an instance of this class, an attribute of the instance that that corresponds to a fixed attribute in the target class is checked against its value.
  • In genemost casesral, cls.from_instance(other) is equivalent to other.to(cls, copy=True).

Parameters:

Name Type Description Default
other DataModelBase

The instance to copy.

required
*args Any

Constructor arguments, which take precedence over the fields of other.

()
**kwargs Any

Constructor arguments, which take precedence over the fields of other.

{}

Returns:

Type Description
Self

The new instance.

Raises:

Type Description
TypeError

If other is not an instance of a data model. A file, a mapping and any other value are read by from_any.

ConversionError

If the class of other is not related to this class, so that fields with the same name may mean different things.

ValueError

If a fixed field of other is set to a value other than the value that the class fixes.

from_any classmethod

from_any(other: Any, *args, **kwargs) -> Self

Build an instance from a mapping, a data model or an argument.

This constructors dispatches to from_dict, from_instance or the constructor, depending on the type of other.

Raises:

Type Description
TypeError

If a mapping has a key that names no field. Unlike from_dict, this method catches misspelled keys.

to

to(
    cls: type | None = None, *, copy: bool = False, **kwargs
) -> Any

Convert the object to another class of its data model.

Without a class, the object keeps its own class, and its attributes may be replaced by the keyword arguments.

Otherwise, the object is converted by cls.from_instance, which copies the attributes of a related class by name. Some subclasses override this method so that it triggers a more specific conversion.

Parameters:

Name Type Description Default
cls type

The class to convert to. By default, the class of the object.

None
copy bool

Whether to return a new object even when nothing changes.

False
**kwargs Any

Fields of the result, which take precedence over those of the object.

{}

Returns:

Type Description
DataModelBase

The converted object, an instance of cls.

Raises:

Type Description
ConversionError

If cls is not related to the class of the object.

compatible_with

compatible_with(other: Axis) -> bool

Return whether two axes could describe the same axis.

Two axes are compatible when all their fields have either the same value or at least one of them has the value None.

The relation is symmetric but not transitive: Axis() is compatible with Axis(name="x") and Axis(name="y"), but these two are not compatible with each other.

Example

>>> Axis(name="x").compatible_with(Axis(name="x", unit="mm"))
True
>>> Axis(name="x").compatible_with(Axis(name="y"))
False
>>> SpaceAxis(unit="mm").compatible_with(Axis(unit="micrometer"))
False

Parameters:

Name Type Description Default
other Axis

The axis to compare with.

required

Returns:

Type Description
bool

Whether no field is set on both sides to different values.

Raises:

Type Description
TypeError

If other is not an Axis.

merge_with

merge_with(other: Axis) -> Axis

Combine two compatible axes.

The input axes must be compatible in the sense of compatible_with. The resulting axis has all non-None values found on either axis.

When both axes have different Axis subtypes, the resulting axis has the type of the most derived class. For example, an Axis merged with a SpaceAxis results in a SpaceAxis.

Example

>>> Axis(name="x").merge_with(SpaceAxis(unit="micrometer"))
SpaceAxis(name='x', unit='micrometer')
>>> Axis(name="x").merge_with(Axis(name="y"))
Traceback (most recent call last):
  ...
ValueError: Cannot merge axes that disagree on name: 'x' != 'y'.

Parameters:

Name Type Description Default
other Axis

Another description of the same axis.

required

Returns:

Type Description
Axis

A new axis with every field known to either side.

Raises:

Type Description
TypeError

If other is not an Axis.

ValueError

If the axes disagree on a field, or if neither class derives from the other.

frame_ndim

frame_ndim(size: int, ndim: int | None = None) -> int

Return the number of axes of the frame that the entries follow.

Each entry of a point or a vector follows one axis of the frame, so this number is the number of entries.

Parameters:

Name Type Description Default
size int

The number of entries along the axis.

required
ndim int

The number of axes of the frame, when it is known from elsewhere. It is checked against size.

None

Returns:

Type Description
int

The number of axes of the frame that the entries follow.

Raises:

Type Description
ValueError

If ndim is given and differs from size.

apply

apply(
    values: ArrayProtocol, matrix: ArrayProtocol, axis: int
) -> ArrayProtocol

Apply a linear map of the frame to the entries along an axis.

Each index of the object is multiplied by the map J when it is a vector index and by J⁻ᵀ when it is a covector index, so that a vector becomes J v and a vector of valence "covector" becomes J⁻ᵀ g.

Parameters:

Name Type Description Default
values ArrayProtocol

The values of the image.

required
matrix ArrayProtocol

The linear map J, of shape (*batch, n, n), where batch broadcasts against the shape of values without axis.

required
axis int

The axis of values whose entries are transformed.

required

Returns:

Type Description
ArrayProtocol

The transformed values, with the shape of values.

Raises:

Type Description
NotImplementedError

If the entries are the coordinates of points, which the Jacobian of a map does not re-express.

DisplacementAxis magic

DisplacementAxis(name: str | None = None, type: NoRepr[...], unit: Unit | None = None, discrete: bool | None = None, orientation: Orientation | None = None)

Bases: ComponentAxis

Axis that enumerates the components of displacement vectors.

A displacement field has its spatial axes and one displacement axis. The axis behaves as a VectorAxis of valence "vector", which it has no field to change, and its type is kept so that the fields of OME-NGFF keep their type.

Parameters:

Name Type Description Default
name str

Name of the axis, such as "c".

None
type displacement

Pinned axis type.

"displacement"
unit Unit | str

Unit of the coordinates along the axis.

None

Other Parameters:

Name Type Description
discrete bool

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation Orientation | str

Meaningful direction of the axis, such as left to right.

name class-attribute instance-attribute

name: NotKwOnly[str | None] = None

Name of the axis, such as "x".

unit class-attribute instance-attribute

unit: NotKwOnly[Unit | None] = None

Unit of the coordinates along the axis.

discrete class-attribute instance-attribute

discrete: bool | None = None

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation class-attribute instance-attribute

orientation: Orientation | None = None

Meaningful direction of the axis, such as left to right.

valences property

valences: tuple[Valence, ...] | None

The valence of each index of the object, or None for a point.

A vector has one index, whose valence is its valence, a displacement has one index of valence "vector", and a tensor has one per entry of its valence. A point has no valence, because its coordinates do not change with the Jacobian of a map.

from_dict classmethod

from_dict(other: Mapping, *args, **kwargs) -> Self

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

from_instance classmethod

from_instance(other: Any, *args, **kwargs) -> Self

Build an instance from an instance of a related data model.

Two classes are related when:

  • one of them is a parent of the other, or
  • when both belong to the same polymorphic family, or
  • when they represent the same "data model".

In all these cases, attributes that have the same name also have the same meaning, so they can be copied by name.

Note

  • Only attributes that name keyword arguments are used.
  • An attribute that is None leaves the default of the class in place.
  • Extra arguments (*args and **kwargs) are passed to the constructor and take precedence.
  • Unless other is already an instance of this class, an attribute of the instance that that corresponds to a fixed attribute in the target class is checked against its value.
  • In genemost casesral, cls.from_instance(other) is equivalent to other.to(cls, copy=True).

Parameters:

Name Type Description Default
other DataModelBase

The instance to copy.

required
*args Any

Constructor arguments, which take precedence over the fields of other.

()
**kwargs Any

Constructor arguments, which take precedence over the fields of other.

{}

Returns:

Type Description
Self

The new instance.

Raises:

Type Description
TypeError

If other is not an instance of a data model. A file, a mapping and any other value are read by from_any.

ConversionError

If the class of other is not related to this class, so that fields with the same name may mean different things.

ValueError

If a fixed field of other is set to a value other than the value that the class fixes.

from_any classmethod

from_any(other: Any, *args, **kwargs) -> Self

Build an instance from a mapping, a data model or an argument.

This constructors dispatches to from_dict, from_instance or the constructor, depending on the type of other.

Raises:

Type Description
TypeError

If a mapping has a key that names no field. Unlike from_dict, this method catches misspelled keys.

to

to(
    cls: type | None = None, *, copy: bool = False, **kwargs
) -> Any

Convert the object to another class of its data model.

Without a class, the object keeps its own class, and its attributes may be replaced by the keyword arguments.

Otherwise, the object is converted by cls.from_instance, which copies the attributes of a related class by name. Some subclasses override this method so that it triggers a more specific conversion.

Parameters:

Name Type Description Default
cls type

The class to convert to. By default, the class of the object.

None
copy bool

Whether to return a new object even when nothing changes.

False
**kwargs Any

Fields of the result, which take precedence over those of the object.

{}

Returns:

Type Description
DataModelBase

The converted object, an instance of cls.

Raises:

Type Description
ConversionError

If cls is not related to the class of the object.

compatible_with

compatible_with(other: Axis) -> bool

Return whether two axes could describe the same axis.

Two axes are compatible when all their fields have either the same value or at least one of them has the value None.

The relation is symmetric but not transitive: Axis() is compatible with Axis(name="x") and Axis(name="y"), but these two are not compatible with each other.

Example

>>> Axis(name="x").compatible_with(Axis(name="x", unit="mm"))
True
>>> Axis(name="x").compatible_with(Axis(name="y"))
False
>>> SpaceAxis(unit="mm").compatible_with(Axis(unit="micrometer"))
False

Parameters:

Name Type Description Default
other Axis

The axis to compare with.

required

Returns:

Type Description
bool

Whether no field is set on both sides to different values.

Raises:

Type Description
TypeError

If other is not an Axis.

merge_with

merge_with(other: Axis) -> Axis

Combine two compatible axes.

The input axes must be compatible in the sense of compatible_with. The resulting axis has all non-None values found on either axis.

When both axes have different Axis subtypes, the resulting axis has the type of the most derived class. For example, an Axis merged with a SpaceAxis results in a SpaceAxis.

Example

>>> Axis(name="x").merge_with(SpaceAxis(unit="micrometer"))
SpaceAxis(name='x', unit='micrometer')
>>> Axis(name="x").merge_with(Axis(name="y"))
Traceback (most recent call last):
  ...
ValueError: Cannot merge axes that disagree on name: 'x' != 'y'.

Parameters:

Name Type Description Default
other Axis

Another description of the same axis.

required

Returns:

Type Description
Axis

A new axis with every field known to either side.

Raises:

Type Description
TypeError

If other is not an Axis.

ValueError

If the axes disagree on a field, or if neither class derives from the other.

frame_ndim

frame_ndim(size: int, ndim: int | None = None) -> int

Return the number of axes of the frame that the entries follow.

Each entry of a point or a vector follows one axis of the frame, so this number is the number of entries.

Parameters:

Name Type Description Default
size int

The number of entries along the axis.

required
ndim int

The number of axes of the frame, when it is known from elsewhere. It is checked against size.

None

Returns:

Type Description
int

The number of axes of the frame that the entries follow.

Raises:

Type Description
ValueError

If ndim is given and differs from size.

apply

apply(
    values: ArrayProtocol, matrix: ArrayProtocol, axis: int
) -> ArrayProtocol

Apply a linear map of the frame to the entries along an axis.

Each index of the object is multiplied by the map J when it is a vector index and by J⁻ᵀ when it is a covector index, so that a vector becomes J v and a vector of valence "covector" becomes J⁻ᵀ g.

Parameters:

Name Type Description Default
values ArrayProtocol

The values of the image.

required
matrix ArrayProtocol

The linear map J, of shape (*batch, n, n), where batch broadcasts against the shape of values without axis.

required
axis int

The axis of values whose entries are transformed.

required

Returns:

Type Description
ArrayProtocol

The transformed values, with the shape of values.

Raises:

Type Description
NotImplementedError

If the entries are the coordinates of points, which the Jacobian of a map does not re-express.

TensorAxis magic

TensorAxis(name: str | None = None, type: NoRepr[...], unit: Unit | None = None, discrete: bool | None = None, orientation: Orientation | None = None, valence: tuple[Valence, ...] = (vector, vector), layout: TensorLayout | Entries | None = None)

Bases: ComponentAxis

Axis whose entries are the components of tensors.

A diffusion tensor, the Hessian of an image and the Jacobian of a map are tensors with two indices. Each index has a valence, either "vector" or "covector", and valence lists them, so that the number of indices is the rank k of the tensor. When the frame changes by a linear map J, each vector index is multiplied by J and each covector index by J⁻ᵀ:

valence Example New components
("vector", "vector") diffusion tensor J T Jᵀ
("covector", "covector") Hessian J⁻ᵀ H J⁻¹
("vector", "covector") linear map J A J⁻¹

A tensor whose two indices belong to different frames, such as the Jacobian of a warp between two spaces, is stored with two vector axes, one of valence "vector" and one of valence "covector", so that each axis has its own frame.

layout says which components the axis stores, and in which order, for a frame of n axes. It is either a name, a member of TensorLayout or its value, or an explicit tuple that gives, for each entry, the frame axis of each index. The names are listed below with their order for a tensor of rank 2 in a frame of three axes, where ij stands for the entry (i, j):

layout Order for k = 2 and n = 3
"C" 00 01 02 10 11 12 20 21 22
"F" 00 10 20 01 11 21 02 12 22
"symmetric" 00 01 02 11 12 22
"symmetric-lower" 00 10 11 20 21 22
"symmetric-diagonal-first" 00 11 22 01 02 12
"diagonal" 00 11 22

"C" lists all the components with the last index varying fastest, and "F" with the first index varying fastest. "symmetric" lists the indices that do not decrease in lexicographic order, which is the upper triangle row by row for a matrix. "symmetric-lower" lists the indices that do not increase in lexicographic order, which is the lower triangle row by row. "symmetric-diagonal-first" lists the diagonal and then the upper triangle row by row, and it is only defined for tensors of rank 2. "diagonal" stores the components whose indices are all equal, and the other components are zero. The full layouts store n**k entries, the symmetric layouts store C(n + k - 1, k) entries, and the diagonal layout stores n.

Software stores a symmetric matrix in these layouts:

Software layout
FSL, ITK, NRRD, Camino "symmetric"
MRtrix "symmetric-diagonal-first"
DIPY "symmetric-lower"

An explicit tuple lists each stored component once, and each listed component is stored independently, so that a full tensor can be listed in any order. A component that the tuple does not list takes the value of the listed component whose indices are a permutation of its own, if there is one, and it is zero otherwise. A tuple that leaves out a component with several listed permutations is refused, because their values may differ. Taking a value from a permutation makes the tensor symmetric, which needs all its indices to have the same valence, because the symmetry of a tensor whose indices have different valences depends on the frame. The symmetric layouts, and the tuples that take a value from a permutation, are therefore refused for a mixed valence.

None, the default, reads the layout from the number of entries once the size n of the frame is known: n**k entries are "C" and C(n + k - 1, k) entries are "symmetric". These two numbers differ when n and k are both at least 2, and any other number of entries is refused.

A layout with components that are zero by construction, such as "diagonal" or an explicit tuple that leaves components out without a permutation to take their value from, cannot hold the tensor after a general change of frame. apply then returns the tensor in the smallest layout that can, which is "symmetric" when the stored tensor is symmetric with indices of the same valence and "C" otherwise, and reframed gives the axis that describes it. The length of the axis changes.

Parameters:

Name Type Description Default
name str

Name of the axis, such as "c".

None
type tensor

Pinned axis type.

"tensor"
unit Unit | str

Unit of the coordinates along the axis.

None
discrete bool

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

None
orientation Orientation | str

Meaningful direction of the axis, such as left to right.

None
valence tuple of (Valence | str)

The valence of each index of the tensor, one per index.

("vector", "vector")
layout TensorLayout | str | tuple of tuple of int

Which components the axis stores and in which order, as a name of the table above or as an explicit tuple. By default, the layout is read from the number of entries.

None

Raises:

Type Description
ValueError

If the tensor has fewer than two indices, if the layout is an unknown name or a name that is not defined for the rank of the tensor, if a symmetric layout has indices of different valences, or if an explicit layout lists a component twice, has entries of the wrong length, or fills a component from several listed permutations or from a permutation with a mixed valence.

valence class-attribute instance-attribute

valence: tuple[Valence, ...] = (
    Valence.vector,
    Valence.vector,
)

The valence of each index of the tensor, one per index.

layout class-attribute instance-attribute

layout: TensorLayout | Entries | None = None

Which components the axis stores, and in which order.

valences property

valences: tuple[Valence, ...]

The valence of each index of the tensor, as in valence.

name class-attribute instance-attribute

name: NotKwOnly[str | None] = None

Name of the axis, such as "x".

unit class-attribute instance-attribute

unit: NotKwOnly[Unit | None] = None

Unit of the coordinates along the axis.

discrete class-attribute instance-attribute

discrete: bool | None = None

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation class-attribute instance-attribute

orientation: Orientation | None = None

Meaningful direction of the axis, such as left to right.

frame_ndim

frame_ndim(size: int, ndim: int | None = None) -> int

Return the number of axes n of the frame of the tensor.

Parameters:

Name Type Description Default
size int

The number of entries along the axis.

required
ndim int

The number of axes of the frame, when it is known from elsewhere. It is checked against size. An explicit layout accepts any frame that has the axes that it names, and without ndim it gives the smallest such frame.

None

Returns:

Type Description
int

The number of axes of the frame that the indices follow.

Raises:

Type Description
ValueError

If no frame, or more than one, gives size entries.

resolved_layout

resolved_layout(
    ndim: int, size: int | None = None
) -> str | Entries

Return the layout, read from the number of entries if needed.

Parameters:

Name Type Description Default
ndim int

The number of axes of the frame.

required
size int

The number of entries along the axis, which reads a layout that is None.

None

Returns:

Type Description
str or tuple of tuple of int

The layout, never None.

Raises:

Type Description
ValueError

If the layout is None and size is neither n**k nor C(n + k - 1, k).

entries

entries(ndim: int, size: int | None = None) -> Entries

Return the frame axis of each index, for each entry.

Parameters:

Name Type Description Default
ndim int

The number of axes of the frame.

required
size int

The number of entries along the axis, which reads a layout that is None.

None

Returns:

Type Description
tuple of tuple of int

For each entry, the frame axis of each index of the tensor.

Raises:

Type Description
ValueError

If an explicit layout names a frame axis that does not exist.

closed

closed(ndim: int, size: int | None = None) -> bool

Return whether the layout holds the tensor in any frame.

A layout is closed when every component of the tensor is either stored or taken from a stored component, so that no component is zero by construction.

Parameters:

Name Type Description Default
ndim int

The number of axes of the frame.

required
size int

The number of entries along the axis, which reads a layout that is None.

None

Returns:

Type Description
bool

Whether a change of frame keeps the tensor in this layout.

reframed

reframed(ndim: int, size: int | None = None) -> TensorAxis

Return the axis that describes the tensor after apply.

Parameters:

Name Type Description Default
ndim int

The number of axes of the frame.

required
size int

The number of entries along the axis, which reads a layout that is None.

None

Returns:

Type Description
TensorAxis

This axis when its layout is closed, and otherwise a copy in the layout "symmetric" when all the indices have the same valence, and "C" otherwise.

apply

apply(
    values: ArrayProtocol, matrix: ArrayProtocol, axis: int
) -> ArrayProtocol

Return the components of the tensor in the new frame.

The entries are unpacked into a full tensor, each of its indices is multiplied by J or by J⁻ᵀ according to its valence, and the result is packed again in the same layout, or in the layout of reframed when this layout is not closed.

Parameters:

Name Type Description Default
values ArrayProtocol

The values of the image.

required
matrix ArrayProtocol

The linear map J, of shape (*batch, n, n), where batch broadcasts against the shape of values without axis.

required
axis int

The axis of values that holds the components.

required

Returns:

Type Description
ArrayProtocol

The transformed values. The length of axis changes when the layout is not closed.

Raises:

Type Description
ValueError

If the number of entries does not match the layout and the size of matrix.

from_dict classmethod

from_dict(other: Mapping, *args, **kwargs) -> Self

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

from_instance classmethod

from_instance(other: Any, *args, **kwargs) -> Self

Build an instance from an instance of a related data model.

Two classes are related when:

  • one of them is a parent of the other, or
  • when both belong to the same polymorphic family, or
  • when they represent the same "data model".

In all these cases, attributes that have the same name also have the same meaning, so they can be copied by name.

Note

  • Only attributes that name keyword arguments are used.
  • An attribute that is None leaves the default of the class in place.
  • Extra arguments (*args and **kwargs) are passed to the constructor and take precedence.
  • Unless other is already an instance of this class, an attribute of the instance that that corresponds to a fixed attribute in the target class is checked against its value.
  • In genemost casesral, cls.from_instance(other) is equivalent to other.to(cls, copy=True).

Parameters:

Name Type Description Default
other DataModelBase

The instance to copy.

required
*args Any

Constructor arguments, which take precedence over the fields of other.

()
**kwargs Any

Constructor arguments, which take precedence over the fields of other.

{}

Returns:

Type Description
Self

The new instance.

Raises:

Type Description
TypeError

If other is not an instance of a data model. A file, a mapping and any other value are read by from_any.

ConversionError

If the class of other is not related to this class, so that fields with the same name may mean different things.

ValueError

If a fixed field of other is set to a value other than the value that the class fixes.

from_any classmethod

from_any(other: Any, *args, **kwargs) -> Self

Build an instance from a mapping, a data model or an argument.

This constructors dispatches to from_dict, from_instance or the constructor, depending on the type of other.

Raises:

Type Description
TypeError

If a mapping has a key that names no field. Unlike from_dict, this method catches misspelled keys.

to

to(
    cls: type | None = None, *, copy: bool = False, **kwargs
) -> Any

Convert the object to another class of its data model.

Without a class, the object keeps its own class, and its attributes may be replaced by the keyword arguments.

Otherwise, the object is converted by cls.from_instance, which copies the attributes of a related class by name. Some subclasses override this method so that it triggers a more specific conversion.

Parameters:

Name Type Description Default
cls type

The class to convert to. By default, the class of the object.

None
copy bool

Whether to return a new object even when nothing changes.

False
**kwargs Any

Fields of the result, which take precedence over those of the object.

{}

Returns:

Type Description
DataModelBase

The converted object, an instance of cls.

Raises:

Type Description
ConversionError

If cls is not related to the class of the object.

compatible_with

compatible_with(other: Axis) -> bool

Return whether two axes could describe the same axis.

Two axes are compatible when all their fields have either the same value or at least one of them has the value None.

The relation is symmetric but not transitive: Axis() is compatible with Axis(name="x") and Axis(name="y"), but these two are not compatible with each other.

Example

>>> Axis(name="x").compatible_with(Axis(name="x", unit="mm"))
True
>>> Axis(name="x").compatible_with(Axis(name="y"))
False
>>> SpaceAxis(unit="mm").compatible_with(Axis(unit="micrometer"))
False

Parameters:

Name Type Description Default
other Axis

The axis to compare with.

required

Returns:

Type Description
bool

Whether no field is set on both sides to different values.

Raises:

Type Description
TypeError

If other is not an Axis.

merge_with

merge_with(other: Axis) -> Axis

Combine two compatible axes.

The input axes must be compatible in the sense of compatible_with. The resulting axis has all non-None values found on either axis.

When both axes have different Axis subtypes, the resulting axis has the type of the most derived class. For example, an Axis merged with a SpaceAxis results in a SpaceAxis.

Example

>>> Axis(name="x").merge_with(SpaceAxis(unit="micrometer"))
SpaceAxis(name='x', unit='micrometer')
>>> Axis(name="x").merge_with(Axis(name="y"))
Traceback (most recent call last):
  ...
ValueError: Cannot merge axes that disagree on name: 'x' != 'y'.

Parameters:

Name Type Description Default
other Axis

Another description of the same axis.

required

Returns:

Type Description
Axis

A new axis with every field known to either side.

Raises:

Type Description
TypeError

If other is not an Axis.

ValueError

If the axes disagree on a field, or if neither class derives from the other.

is_component_type

is_component_type(value: Any) -> bool

Return whether an axis type describes a component axis.

The readers and the writers of files group these axes with the channels, and only these axes can have a frame.

Parameters:

Name Type Description Default
value AxisType or str or None

The type of an axis, such as "vector". Any other value, such as None, gives False.

required

Returns:

Type Description
bool

Whether the entries along an axis of this type are the components of a point, a vector or a tensor.

Anatomical axes

AnatomicalAxis magic

AnatomicalAxis(name: str | None = None, type: NoRepr[...], unit: Inherit[SpaceUnit | IndexUnit | None], discrete: bool | None = None, orientation: Orientation | None = None)

Bases: OrientedSpaceAxis

Spatial axis with an anatomical orientation.

An anatomical orientation selects this class even without a type. The unit may be an index unit, for a voxel axis along that direction.

Parameters:

Name Type Description Default
name str

Name of the axis, such as "x".

None
type space

Pinned axis type.

"space"
unit SpaceUnit | IndexUnit | str

Unit of the coordinates along the axis.

required

Other Parameters:

Name Type Description
discrete bool

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation (Orientation, required)

Meaningful direction of the axis, such as left to right.

name class-attribute instance-attribute

name: NotKwOnly[str | None] = None

Name of the axis, such as "x".

discrete class-attribute instance-attribute

discrete: bool | None = None

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation class-attribute instance-attribute

orientation: Orientation | None = None

Meaningful direction of the axis, such as left to right.

from_dict classmethod

from_dict(other: Mapping, *args, **kwargs) -> Self

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

from_instance classmethod

from_instance(other: Any, *args, **kwargs) -> Self

Build an instance from an instance of a related data model.

Two classes are related when:

  • one of them is a parent of the other, or
  • when both belong to the same polymorphic family, or
  • when they represent the same "data model".

In all these cases, attributes that have the same name also have the same meaning, so they can be copied by name.

Note

  • Only attributes that name keyword arguments are used.
  • An attribute that is None leaves the default of the class in place.
  • Extra arguments (*args and **kwargs) are passed to the constructor and take precedence.
  • Unless other is already an instance of this class, an attribute of the instance that that corresponds to a fixed attribute in the target class is checked against its value.
  • In genemost casesral, cls.from_instance(other) is equivalent to other.to(cls, copy=True).

Parameters:

Name Type Description Default
other DataModelBase

The instance to copy.

required
*args Any

Constructor arguments, which take precedence over the fields of other.

()
**kwargs Any

Constructor arguments, which take precedence over the fields of other.

{}

Returns:

Type Description
Self

The new instance.

Raises:

Type Description
TypeError

If other is not an instance of a data model. A file, a mapping and any other value are read by from_any.

ConversionError

If the class of other is not related to this class, so that fields with the same name may mean different things.

ValueError

If a fixed field of other is set to a value other than the value that the class fixes.

from_any classmethod

from_any(other: Any, *args, **kwargs) -> Self

Build an instance from a mapping, a data model or an argument.

This constructors dispatches to from_dict, from_instance or the constructor, depending on the type of other.

Raises:

Type Description
TypeError

If a mapping has a key that names no field. Unlike from_dict, this method catches misspelled keys.

to

to(
    cls: type | None = None, *, copy: bool = False, **kwargs
) -> Any

Convert the object to another class of its data model.

Without a class, the object keeps its own class, and its attributes may be replaced by the keyword arguments.

Otherwise, the object is converted by cls.from_instance, which copies the attributes of a related class by name. Some subclasses override this method so that it triggers a more specific conversion.

Parameters:

Name Type Description Default
cls type

The class to convert to. By default, the class of the object.

None
copy bool

Whether to return a new object even when nothing changes.

False
**kwargs Any

Fields of the result, which take precedence over those of the object.

{}

Returns:

Type Description
DataModelBase

The converted object, an instance of cls.

Raises:

Type Description
ConversionError

If cls is not related to the class of the object.

compatible_with

compatible_with(other: Axis) -> bool

Return whether two axes could describe the same axis.

Two axes are compatible when all their fields have either the same value or at least one of them has the value None.

The relation is symmetric but not transitive: Axis() is compatible with Axis(name="x") and Axis(name="y"), but these two are not compatible with each other.

Example

>>> Axis(name="x").compatible_with(Axis(name="x", unit="mm"))
True
>>> Axis(name="x").compatible_with(Axis(name="y"))
False
>>> SpaceAxis(unit="mm").compatible_with(Axis(unit="micrometer"))
False

Parameters:

Name Type Description Default
other Axis

The axis to compare with.

required

Returns:

Type Description
bool

Whether no field is set on both sides to different values.

Raises:

Type Description
TypeError

If other is not an Axis.

merge_with

merge_with(other: Axis) -> Axis

Combine two compatible axes.

The input axes must be compatible in the sense of compatible_with. The resulting axis has all non-None values found on either axis.

When both axes have different Axis subtypes, the resulting axis has the type of the most derived class. For example, an Axis merged with a SpaceAxis results in a SpaceAxis.

Example

>>> Axis(name="x").merge_with(SpaceAxis(unit="micrometer"))
SpaceAxis(name='x', unit='micrometer')
>>> Axis(name="x").merge_with(Axis(name="y"))
Traceback (most recent call last):
  ...
ValueError: Cannot merge axes that disagree on name: 'x' != 'y'.

Parameters:

Name Type Description Default
other Axis

Another description of the same axis.

required

Returns:

Type Description
Axis

A new axis with every field known to either side.

Raises:

Type Description
TypeError

If other is not an Axis.

ValueError

If the axes disagree on a field, or if neither class derives from the other.

LeftToRightAxis magic

LeftToRightAxis(name: ... = 'left-to-right', type: NoRepr[...], unit: Inherit[SpaceUnit | IndexUnit | None], discrete: bool | None = None, orientation: NoRepr[LeftToRight] = LeftToRight())

Bases: AnatomicalAxis

Spatial axis oriented from left to right.

Parameters:

Name Type Description Default
name str

Name of the axis, such as "x".

"left-to-right"
type space

Pinned axis type.

"space"
unit SpaceUnit | IndexUnit | str

Unit of the coordinates along the axis.

required

Other Parameters:

Name Type Description
discrete bool

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation LR

Pinned orientation.

discrete class-attribute instance-attribute

discrete: bool | None = None

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

from_dict classmethod

from_dict(other: Mapping, *args, **kwargs) -> Self

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

from_instance classmethod

from_instance(other: Any, *args, **kwargs) -> Self

Build an instance from an instance of a related data model.

Two classes are related when:

  • one of them is a parent of the other, or
  • when both belong to the same polymorphic family, or
  • when they represent the same "data model".

In all these cases, attributes that have the same name also have the same meaning, so they can be copied by name.

Note

  • Only attributes that name keyword arguments are used.
  • An attribute that is None leaves the default of the class in place.
  • Extra arguments (*args and **kwargs) are passed to the constructor and take precedence.
  • Unless other is already an instance of this class, an attribute of the instance that that corresponds to a fixed attribute in the target class is checked against its value.
  • In genemost casesral, cls.from_instance(other) is equivalent to other.to(cls, copy=True).

Parameters:

Name Type Description Default
other DataModelBase

The instance to copy.

required
*args Any

Constructor arguments, which take precedence over the fields of other.

()
**kwargs Any

Constructor arguments, which take precedence over the fields of other.

{}

Returns:

Type Description
Self

The new instance.

Raises:

Type Description
TypeError

If other is not an instance of a data model. A file, a mapping and any other value are read by from_any.

ConversionError

If the class of other is not related to this class, so that fields with the same name may mean different things.

ValueError

If a fixed field of other is set to a value other than the value that the class fixes.

from_any classmethod

from_any(other: Any, *args, **kwargs) -> Self

Build an instance from a mapping, a data model or an argument.

This constructors dispatches to from_dict, from_instance or the constructor, depending on the type of other.

Raises:

Type Description
TypeError

If a mapping has a key that names no field. Unlike from_dict, this method catches misspelled keys.

to

to(
    cls: type | None = None, *, copy: bool = False, **kwargs
) -> Any

Convert the object to another class of its data model.

Without a class, the object keeps its own class, and its attributes may be replaced by the keyword arguments.

Otherwise, the object is converted by cls.from_instance, which copies the attributes of a related class by name. Some subclasses override this method so that it triggers a more specific conversion.

Parameters:

Name Type Description Default
cls type

The class to convert to. By default, the class of the object.

None
copy bool

Whether to return a new object even when nothing changes.

False
**kwargs Any

Fields of the result, which take precedence over those of the object.

{}

Returns:

Type Description
DataModelBase

The converted object, an instance of cls.

Raises:

Type Description
ConversionError

If cls is not related to the class of the object.

compatible_with

compatible_with(other: Axis) -> bool

Return whether two axes could describe the same axis.

Two axes are compatible when all their fields have either the same value or at least one of them has the value None.

The relation is symmetric but not transitive: Axis() is compatible with Axis(name="x") and Axis(name="y"), but these two are not compatible with each other.

Example

>>> Axis(name="x").compatible_with(Axis(name="x", unit="mm"))
True
>>> Axis(name="x").compatible_with(Axis(name="y"))
False
>>> SpaceAxis(unit="mm").compatible_with(Axis(unit="micrometer"))
False

Parameters:

Name Type Description Default
other Axis

The axis to compare with.

required

Returns:

Type Description
bool

Whether no field is set on both sides to different values.

Raises:

Type Description
TypeError

If other is not an Axis.

merge_with

merge_with(other: Axis) -> Axis

Combine two compatible axes.

The input axes must be compatible in the sense of compatible_with. The resulting axis has all non-None values found on either axis.

When both axes have different Axis subtypes, the resulting axis has the type of the most derived class. For example, an Axis merged with a SpaceAxis results in a SpaceAxis.

Example

>>> Axis(name="x").merge_with(SpaceAxis(unit="micrometer"))
SpaceAxis(name='x', unit='micrometer')
>>> Axis(name="x").merge_with(Axis(name="y"))
Traceback (most recent call last):
  ...
ValueError: Cannot merge axes that disagree on name: 'x' != 'y'.

Parameters:

Name Type Description Default
other Axis

Another description of the same axis.

required

Returns:

Type Description
Axis

A new axis with every field known to either side.

Raises:

Type Description
TypeError

If other is not an Axis.

ValueError

If the axes disagree on a field, or if neither class derives from the other.

RightToLeftAxis magic

RightToLeftAxis(name: ... = 'right-to-left', type: NoRepr[...], unit: Inherit[SpaceUnit | IndexUnit | None], discrete: bool | None = None, orientation: NoRepr[RightToLeft] = RightToLeft())

Bases: AnatomicalAxis

Spatial axis oriented from right to left.

Parameters:

Name Type Description Default
name str

Name of the axis, such as "x".

"right-to-left"
type space

Pinned axis type.

"space"
unit SpaceUnit | IndexUnit | str

Unit of the coordinates along the axis.

required

Other Parameters:

Name Type Description
discrete bool

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation RL

Pinned orientation.

discrete class-attribute instance-attribute

discrete: bool | None = None

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

from_dict classmethod

from_dict(other: Mapping, *args, **kwargs) -> Self

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

from_instance classmethod

from_instance(other: Any, *args, **kwargs) -> Self

Build an instance from an instance of a related data model.

Two classes are related when:

  • one of them is a parent of the other, or
  • when both belong to the same polymorphic family, or
  • when they represent the same "data model".

In all these cases, attributes that have the same name also have the same meaning, so they can be copied by name.

Note

  • Only attributes that name keyword arguments are used.
  • An attribute that is None leaves the default of the class in place.
  • Extra arguments (*args and **kwargs) are passed to the constructor and take precedence.
  • Unless other is already an instance of this class, an attribute of the instance that that corresponds to a fixed attribute in the target class is checked against its value.
  • In genemost casesral, cls.from_instance(other) is equivalent to other.to(cls, copy=True).

Parameters:

Name Type Description Default
other DataModelBase

The instance to copy.

required
*args Any

Constructor arguments, which take precedence over the fields of other.

()
**kwargs Any

Constructor arguments, which take precedence over the fields of other.

{}

Returns:

Type Description
Self

The new instance.

Raises:

Type Description
TypeError

If other is not an instance of a data model. A file, a mapping and any other value are read by from_any.

ConversionError

If the class of other is not related to this class, so that fields with the same name may mean different things.

ValueError

If a fixed field of other is set to a value other than the value that the class fixes.

from_any classmethod

from_any(other: Any, *args, **kwargs) -> Self

Build an instance from a mapping, a data model or an argument.

This constructors dispatches to from_dict, from_instance or the constructor, depending on the type of other.

Raises:

Type Description
TypeError

If a mapping has a key that names no field. Unlike from_dict, this method catches misspelled keys.

to

to(
    cls: type | None = None, *, copy: bool = False, **kwargs
) -> Any

Convert the object to another class of its data model.

Without a class, the object keeps its own class, and its attributes may be replaced by the keyword arguments.

Otherwise, the object is converted by cls.from_instance, which copies the attributes of a related class by name. Some subclasses override this method so that it triggers a more specific conversion.

Parameters:

Name Type Description Default
cls type

The class to convert to. By default, the class of the object.

None
copy bool

Whether to return a new object even when nothing changes.

False
**kwargs Any

Fields of the result, which take precedence over those of the object.

{}

Returns:

Type Description
DataModelBase

The converted object, an instance of cls.

Raises:

Type Description
ConversionError

If cls is not related to the class of the object.

compatible_with

compatible_with(other: Axis) -> bool

Return whether two axes could describe the same axis.

Two axes are compatible when all their fields have either the same value or at least one of them has the value None.

The relation is symmetric but not transitive: Axis() is compatible with Axis(name="x") and Axis(name="y"), but these two are not compatible with each other.

Example

>>> Axis(name="x").compatible_with(Axis(name="x", unit="mm"))
True
>>> Axis(name="x").compatible_with(Axis(name="y"))
False
>>> SpaceAxis(unit="mm").compatible_with(Axis(unit="micrometer"))
False

Parameters:

Name Type Description Default
other Axis

The axis to compare with.

required

Returns:

Type Description
bool

Whether no field is set on both sides to different values.

Raises:

Type Description
TypeError

If other is not an Axis.

merge_with

merge_with(other: Axis) -> Axis

Combine two compatible axes.

The input axes must be compatible in the sense of compatible_with. The resulting axis has all non-None values found on either axis.

When both axes have different Axis subtypes, the resulting axis has the type of the most derived class. For example, an Axis merged with a SpaceAxis results in a SpaceAxis.

Example

>>> Axis(name="x").merge_with(SpaceAxis(unit="micrometer"))
SpaceAxis(name='x', unit='micrometer')
>>> Axis(name="x").merge_with(Axis(name="y"))
Traceback (most recent call last):
  ...
ValueError: Cannot merge axes that disagree on name: 'x' != 'y'.

Parameters:

Name Type Description Default
other Axis

Another description of the same axis.

required

Returns:

Type Description
Axis

A new axis with every field known to either side.

Raises:

Type Description
TypeError

If other is not an Axis.

ValueError

If the axes disagree on a field, or if neither class derives from the other.

AnteriorToPosteriorAxis magic

AnteriorToPosteriorAxis(name: ... = 'anterior-to-posterior', type: NoRepr[...], unit: Inherit[SpaceUnit | IndexUnit | None], discrete: bool | None = None, orientation: NoRepr[AnteriorToPosterior] = AnteriorToPosterior())

Bases: AnatomicalAxis

Spatial axis oriented from anterior to posterior.

Parameters:

Name Type Description Default
name str

Name of the axis, such as "y".

"anterior-to-posterior"
type space

Pinned axis type.

"space"
unit SpaceUnit | IndexUnit | str

Unit of the coordinates along the axis.

required

Other Parameters:

Name Type Description
discrete bool

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation AP

Pinned orientation.

discrete class-attribute instance-attribute

discrete: bool | None = None

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

from_dict classmethod

from_dict(other: Mapping, *args, **kwargs) -> Self

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

from_instance classmethod

from_instance(other: Any, *args, **kwargs) -> Self

Build an instance from an instance of a related data model.

Two classes are related when:

  • one of them is a parent of the other, or
  • when both belong to the same polymorphic family, or
  • when they represent the same "data model".

In all these cases, attributes that have the same name also have the same meaning, so they can be copied by name.

Note

  • Only attributes that name keyword arguments are used.
  • An attribute that is None leaves the default of the class in place.
  • Extra arguments (*args and **kwargs) are passed to the constructor and take precedence.
  • Unless other is already an instance of this class, an attribute of the instance that that corresponds to a fixed attribute in the target class is checked against its value.
  • In genemost casesral, cls.from_instance(other) is equivalent to other.to(cls, copy=True).

Parameters:

Name Type Description Default
other DataModelBase

The instance to copy.

required
*args Any

Constructor arguments, which take precedence over the fields of other.

()
**kwargs Any

Constructor arguments, which take precedence over the fields of other.

{}

Returns:

Type Description
Self

The new instance.

Raises:

Type Description
TypeError

If other is not an instance of a data model. A file, a mapping and any other value are read by from_any.

ConversionError

If the class of other is not related to this class, so that fields with the same name may mean different things.

ValueError

If a fixed field of other is set to a value other than the value that the class fixes.

from_any classmethod

from_any(other: Any, *args, **kwargs) -> Self

Build an instance from a mapping, a data model or an argument.

This constructors dispatches to from_dict, from_instance or the constructor, depending on the type of other.

Raises:

Type Description
TypeError

If a mapping has a key that names no field. Unlike from_dict, this method catches misspelled keys.

to

to(
    cls: type | None = None, *, copy: bool = False, **kwargs
) -> Any

Convert the object to another class of its data model.

Without a class, the object keeps its own class, and its attributes may be replaced by the keyword arguments.

Otherwise, the object is converted by cls.from_instance, which copies the attributes of a related class by name. Some subclasses override this method so that it triggers a more specific conversion.

Parameters:

Name Type Description Default
cls type

The class to convert to. By default, the class of the object.

None
copy bool

Whether to return a new object even when nothing changes.

False
**kwargs Any

Fields of the result, which take precedence over those of the object.

{}

Returns:

Type Description
DataModelBase

The converted object, an instance of cls.

Raises:

Type Description
ConversionError

If cls is not related to the class of the object.

compatible_with

compatible_with(other: Axis) -> bool

Return whether two axes could describe the same axis.

Two axes are compatible when all their fields have either the same value or at least one of them has the value None.

The relation is symmetric but not transitive: Axis() is compatible with Axis(name="x") and Axis(name="y"), but these two are not compatible with each other.

Example

>>> Axis(name="x").compatible_with(Axis(name="x", unit="mm"))
True
>>> Axis(name="x").compatible_with(Axis(name="y"))
False
>>> SpaceAxis(unit="mm").compatible_with(Axis(unit="micrometer"))
False

Parameters:

Name Type Description Default
other Axis

The axis to compare with.

required

Returns:

Type Description
bool

Whether no field is set on both sides to different values.

Raises:

Type Description
TypeError

If other is not an Axis.

merge_with

merge_with(other: Axis) -> Axis

Combine two compatible axes.

The input axes must be compatible in the sense of compatible_with. The resulting axis has all non-None values found on either axis.

When both axes have different Axis subtypes, the resulting axis has the type of the most derived class. For example, an Axis merged with a SpaceAxis results in a SpaceAxis.

Example

>>> Axis(name="x").merge_with(SpaceAxis(unit="micrometer"))
SpaceAxis(name='x', unit='micrometer')
>>> Axis(name="x").merge_with(Axis(name="y"))
Traceback (most recent call last):
  ...
ValueError: Cannot merge axes that disagree on name: 'x' != 'y'.

Parameters:

Name Type Description Default
other Axis

Another description of the same axis.

required

Returns:

Type Description
Axis

A new axis with every field known to either side.

Raises:

Type Description
TypeError

If other is not an Axis.

ValueError

If the axes disagree on a field, or if neither class derives from the other.

PosteriorToAnteriorAxis magic

PosteriorToAnteriorAxis(name: ... = 'posterior-to-anterior', type: NoRepr[...], unit: Inherit[SpaceUnit | IndexUnit | None], discrete: bool | None = None, orientation: NoRepr[PosteriorToAnterior] = PosteriorToAnterior())

Bases: AnatomicalAxis

Spatial axis oriented from posterior to anterior.

Parameters:

Name Type Description Default
name str

Name of the axis, such as "y".

"posterior-to-anterior"
type space

Pinned axis type.

"space"
unit SpaceUnit | IndexUnit | str

Unit of the coordinates along the axis.

required

Other Parameters:

Name Type Description
discrete bool

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation PA

Pinned orientation.

discrete class-attribute instance-attribute

discrete: bool | None = None

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

from_dict classmethod

from_dict(other: Mapping, *args, **kwargs) -> Self

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

from_instance classmethod

from_instance(other: Any, *args, **kwargs) -> Self

Build an instance from an instance of a related data model.

Two classes are related when:

  • one of them is a parent of the other, or
  • when both belong to the same polymorphic family, or
  • when they represent the same "data model".

In all these cases, attributes that have the same name also have the same meaning, so they can be copied by name.

Note

  • Only attributes that name keyword arguments are used.
  • An attribute that is None leaves the default of the class in place.
  • Extra arguments (*args and **kwargs) are passed to the constructor and take precedence.
  • Unless other is already an instance of this class, an attribute of the instance that that corresponds to a fixed attribute in the target class is checked against its value.
  • In genemost casesral, cls.from_instance(other) is equivalent to other.to(cls, copy=True).

Parameters:

Name Type Description Default
other DataModelBase

The instance to copy.

required
*args Any

Constructor arguments, which take precedence over the fields of other.

()
**kwargs Any

Constructor arguments, which take precedence over the fields of other.

{}

Returns:

Type Description
Self

The new instance.

Raises:

Type Description
TypeError

If other is not an instance of a data model. A file, a mapping and any other value are read by from_any.

ConversionError

If the class of other is not related to this class, so that fields with the same name may mean different things.

ValueError

If a fixed field of other is set to a value other than the value that the class fixes.

from_any classmethod

from_any(other: Any, *args, **kwargs) -> Self

Build an instance from a mapping, a data model or an argument.

This constructors dispatches to from_dict, from_instance or the constructor, depending on the type of other.

Raises:

Type Description
TypeError

If a mapping has a key that names no field. Unlike from_dict, this method catches misspelled keys.

to

to(
    cls: type | None = None, *, copy: bool = False, **kwargs
) -> Any

Convert the object to another class of its data model.

Without a class, the object keeps its own class, and its attributes may be replaced by the keyword arguments.

Otherwise, the object is converted by cls.from_instance, which copies the attributes of a related class by name. Some subclasses override this method so that it triggers a more specific conversion.

Parameters:

Name Type Description Default
cls type

The class to convert to. By default, the class of the object.

None
copy bool

Whether to return a new object even when nothing changes.

False
**kwargs Any

Fields of the result, which take precedence over those of the object.

{}

Returns:

Type Description
DataModelBase

The converted object, an instance of cls.

Raises:

Type Description
ConversionError

If cls is not related to the class of the object.

compatible_with

compatible_with(other: Axis) -> bool

Return whether two axes could describe the same axis.

Two axes are compatible when all their fields have either the same value or at least one of them has the value None.

The relation is symmetric but not transitive: Axis() is compatible with Axis(name="x") and Axis(name="y"), but these two are not compatible with each other.

Example

>>> Axis(name="x").compatible_with(Axis(name="x", unit="mm"))
True
>>> Axis(name="x").compatible_with(Axis(name="y"))
False
>>> SpaceAxis(unit="mm").compatible_with(Axis(unit="micrometer"))
False

Parameters:

Name Type Description Default
other Axis

The axis to compare with.

required

Returns:

Type Description
bool

Whether no field is set on both sides to different values.

Raises:

Type Description
TypeError

If other is not an Axis.

merge_with

merge_with(other: Axis) -> Axis

Combine two compatible axes.

The input axes must be compatible in the sense of compatible_with. The resulting axis has all non-None values found on either axis.

When both axes have different Axis subtypes, the resulting axis has the type of the most derived class. For example, an Axis merged with a SpaceAxis results in a SpaceAxis.

Example

>>> Axis(name="x").merge_with(SpaceAxis(unit="micrometer"))
SpaceAxis(name='x', unit='micrometer')
>>> Axis(name="x").merge_with(Axis(name="y"))
Traceback (most recent call last):
  ...
ValueError: Cannot merge axes that disagree on name: 'x' != 'y'.

Parameters:

Name Type Description Default
other Axis

Another description of the same axis.

required

Returns:

Type Description
Axis

A new axis with every field known to either side.

Raises:

Type Description
TypeError

If other is not an Axis.

ValueError

If the axes disagree on a field, or if neither class derives from the other.

InferiorToSuperiorAxis magic

InferiorToSuperiorAxis(name: ... = 'inferior-to-superior', type: NoRepr[...], unit: Inherit[SpaceUnit | IndexUnit | None], discrete: bool | None = None, orientation: NoRepr[InferiorToSuperior] = InferiorToSuperior())

Bases: AnatomicalAxis

Spatial axis oriented from inferior to superior.

Parameters:

Name Type Description Default
name str

Name of the axis, such as "z".

"inferior-to-superior"
type space

Pinned axis type.

"space"
unit SpaceUnit | IndexUnit | str

Unit of the coordinates along the axis.

required

Other Parameters:

Name Type Description
discrete bool

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation IS

Pinned orientation.

discrete class-attribute instance-attribute

discrete: bool | None = None

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

from_dict classmethod

from_dict(other: Mapping, *args, **kwargs) -> Self

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

from_instance classmethod

from_instance(other: Any, *args, **kwargs) -> Self

Build an instance from an instance of a related data model.

Two classes are related when:

  • one of them is a parent of the other, or
  • when both belong to the same polymorphic family, or
  • when they represent the same "data model".

In all these cases, attributes that have the same name also have the same meaning, so they can be copied by name.

Note

  • Only attributes that name keyword arguments are used.
  • An attribute that is None leaves the default of the class in place.
  • Extra arguments (*args and **kwargs) are passed to the constructor and take precedence.
  • Unless other is already an instance of this class, an attribute of the instance that that corresponds to a fixed attribute in the target class is checked against its value.
  • In genemost casesral, cls.from_instance(other) is equivalent to other.to(cls, copy=True).

Parameters:

Name Type Description Default
other DataModelBase

The instance to copy.

required
*args Any

Constructor arguments, which take precedence over the fields of other.

()
**kwargs Any

Constructor arguments, which take precedence over the fields of other.

{}

Returns:

Type Description
Self

The new instance.

Raises:

Type Description
TypeError

If other is not an instance of a data model. A file, a mapping and any other value are read by from_any.

ConversionError

If the class of other is not related to this class, so that fields with the same name may mean different things.

ValueError

If a fixed field of other is set to a value other than the value that the class fixes.

from_any classmethod

from_any(other: Any, *args, **kwargs) -> Self

Build an instance from a mapping, a data model or an argument.

This constructors dispatches to from_dict, from_instance or the constructor, depending on the type of other.

Raises:

Type Description
TypeError

If a mapping has a key that names no field. Unlike from_dict, this method catches misspelled keys.

to

to(
    cls: type | None = None, *, copy: bool = False, **kwargs
) -> Any

Convert the object to another class of its data model.

Without a class, the object keeps its own class, and its attributes may be replaced by the keyword arguments.

Otherwise, the object is converted by cls.from_instance, which copies the attributes of a related class by name. Some subclasses override this method so that it triggers a more specific conversion.

Parameters:

Name Type Description Default
cls type

The class to convert to. By default, the class of the object.

None
copy bool

Whether to return a new object even when nothing changes.

False
**kwargs Any

Fields of the result, which take precedence over those of the object.

{}

Returns:

Type Description
DataModelBase

The converted object, an instance of cls.

Raises:

Type Description
ConversionError

If cls is not related to the class of the object.

compatible_with

compatible_with(other: Axis) -> bool

Return whether two axes could describe the same axis.

Two axes are compatible when all their fields have either the same value or at least one of them has the value None.

The relation is symmetric but not transitive: Axis() is compatible with Axis(name="x") and Axis(name="y"), but these two are not compatible with each other.

Example

>>> Axis(name="x").compatible_with(Axis(name="x", unit="mm"))
True
>>> Axis(name="x").compatible_with(Axis(name="y"))
False
>>> SpaceAxis(unit="mm").compatible_with(Axis(unit="micrometer"))
False

Parameters:

Name Type Description Default
other Axis

The axis to compare with.

required

Returns:

Type Description
bool

Whether no field is set on both sides to different values.

Raises:

Type Description
TypeError

If other is not an Axis.

merge_with

merge_with(other: Axis) -> Axis

Combine two compatible axes.

The input axes must be compatible in the sense of compatible_with. The resulting axis has all non-None values found on either axis.

When both axes have different Axis subtypes, the resulting axis has the type of the most derived class. For example, an Axis merged with a SpaceAxis results in a SpaceAxis.

Example

>>> Axis(name="x").merge_with(SpaceAxis(unit="micrometer"))
SpaceAxis(name='x', unit='micrometer')
>>> Axis(name="x").merge_with(Axis(name="y"))
Traceback (most recent call last):
  ...
ValueError: Cannot merge axes that disagree on name: 'x' != 'y'.

Parameters:

Name Type Description Default
other Axis

Another description of the same axis.

required

Returns:

Type Description
Axis

A new axis with every field known to either side.

Raises:

Type Description
TypeError

If other is not an Axis.

ValueError

If the axes disagree on a field, or if neither class derives from the other.

SuperiorToInferiorAxis magic

SuperiorToInferiorAxis(name: ... = 'superior-to-inferior', type: NoRepr[...], unit: Inherit[SpaceUnit | IndexUnit | None], discrete: bool | None = None, orientation: NoRepr[SuperiorToInferior] = SuperiorToInferior())

Bases: AnatomicalAxis

Spatial axis oriented from superior to inferior.

Parameters:

Name Type Description Default
name str

Name of the axis, such as "z".

"superior-to-inferior"
type space

Pinned axis type.

"space"
unit SpaceUnit | IndexUnit | str

Unit of the coordinates along the axis.

required

Other Parameters:

Name Type Description
discrete bool

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

orientation SI

Pinned orientation.

discrete class-attribute instance-attribute

discrete: bool | None = None

Whether the axis is discrete, meaning that its elements have no specific order and should not be interpolated.

from_dict classmethod

from_dict(other: Mapping, *args, **kwargs) -> Self

Build an instance from a mapping.

Only keys that can be passed to the constructor are used. Other keys are ignored, unlike in from_any

A key that corresponds to a fixed attribute (that is, an attribute that cannot be set by the constructor) is checked against its value.

Extra arguments (*args and **kwargs) are passed to the constructor and take precedence over the mapping.

Raises:

Type Description
ValueError

If a fixed attribute is given a value other than None or the value that the class fixes.

from_instance classmethod

from_instance(other: Any, *args, **kwargs) -> Self

Build an instance from an instance of a related data model.

Two classes are related when:

  • one of them is a parent of the other, or
  • when both belong to the same polymorphic family, or
  • when they represent the same "data model".

In all these cases, attributes that have the same name also have the same meaning, so they can be copied by name.

Note

  • Only attributes that name keyword arguments are used.
  • An attribute that is None leaves the default of the class in place.
  • Extra arguments (*args and **kwargs) are passed to the constructor and take precedence.
  • Unless other is already an instance of this class, an attribute of the instance that that corresponds to a fixed attribute in the target class is checked against its value.
  • In genemost casesral, cls.from_instance(other) is equivalent to other.to(cls, copy=True).

Parameters:

Name Type Description Default
other DataModelBase

The instance to copy.

required
*args Any

Constructor arguments, which take precedence over the fields of other.

()
**kwargs Any

Constructor arguments, which take precedence over the fields of other.

{}

Returns:

Type Description
Self

The new instance.

Raises:

Type Description
TypeError

If other is not an instance of a data model. A file, a mapping and any other value are read by from_any.

ConversionError

If the class of other is not related to this class, so that fields with the same name may mean different things.

ValueError

If a fixed field of other is set to a value other than the value that the class fixes.

from_any classmethod

from_any(other: Any, *args, **kwargs) -> Self

Build an instance from a mapping, a data model or an argument.

This constructors dispatches to from_dict, from_instance or the constructor, depending on the type of other.

Raises:

Type Description
TypeError

If a mapping has a key that names no field. Unlike from_dict, this method catches misspelled keys.

to

to(
    cls: type | None = None, *, copy: bool = False, **kwargs
) -> Any

Convert the object to another class of its data model.

Without a class, the object keeps its own class, and its attributes may be replaced by the keyword arguments.

Otherwise, the object is converted by cls.from_instance, which copies the attributes of a related class by name. Some subclasses override this method so that it triggers a more specific conversion.

Parameters:

Name Type Description Default
cls type

The class to convert to. By default, the class of the object.

None
copy bool

Whether to return a new object even when nothing changes.

False
**kwargs Any

Fields of the result, which take precedence over those of the object.

{}

Returns:

Type Description
DataModelBase

The converted object, an instance of cls.

Raises:

Type Description
ConversionError

If cls is not related to the class of the object.

compatible_with

compatible_with(other: Axis) -> bool

Return whether two axes could describe the same axis.

Two axes are compatible when all their fields have either the same value or at least one of them has the value None.

The relation is symmetric but not transitive: Axis() is compatible with Axis(name="x") and Axis(name="y"), but these two are not compatible with each other.

Example

>>> Axis(name="x").compatible_with(Axis(name="x", unit="mm"))
True
>>> Axis(name="x").compatible_with(Axis(name="y"))
False
>>> SpaceAxis(unit="mm").compatible_with(Axis(unit="micrometer"))
False

Parameters:

Name Type Description Default
other Axis

The axis to compare with.

required

Returns:

Type Description
bool

Whether no field is set on both sides to different values.

Raises:

Type Description
TypeError

If other is not an Axis.

merge_with

merge_with(other: Axis) -> Axis

Combine two compatible axes.

The input axes must be compatible in the sense of compatible_with. The resulting axis has all non-None values found on either axis.

When both axes have different Axis subtypes, the resulting axis has the type of the most derived class. For example, an Axis merged with a SpaceAxis results in a SpaceAxis.

Example

>>> Axis(name="x").merge_with(SpaceAxis(unit="micrometer"))
SpaceAxis(name='x', unit='micrometer')
>>> Axis(name="x").merge_with(Axis(name="y"))
Traceback (most recent call last):
  ...
ValueError: Cannot merge axes that disagree on name: 'x' != 'y'.

Parameters:

Name Type Description Default
other Axis

Another description of the same axis.

required

Returns:

Type Description
Axis

A new axis with every field known to either side.

Raises:

Type Description
TypeError

If other is not an Axis.

ValueError

If the axes disagree on a field, or if neither class derives from the other.

Short aliases

LR module-attribute

Aliases of LeftToRightAxis.

Coordinates along this axis increase toward the right.

RL module-attribute

Aliases of RightToLeftAxis.

Coordinates along this axis increase toward the left.

PA module-attribute

Aliases of PosteriorToAnteriorAxis.

Coordinates along this axis increase toward the front.

AP module-attribute

Aliases of AnteriorToPosteriorAxis.

Coordinates along this axis increase toward the back.

IS module-attribute

Aliases of InferiorToSuperiorAxis.

Coordinates along this axis increase toward the top.

SI module-attribute

Aliases of SuperiorToInferiorAxis.

Coordinates along this axis increase toward the bottom.

Lists of axes

AxisQuery module-attribute

AxisQuery: TypeAlias = (
    Axis
    | str
    | Type[Axis]
    | Mapping[str, Any]
    | Callable[[Axis], bool]
)

A description of the axes to find in an AxisSequence.

A query is one of the following:

  • a name, which stands for Axis(name=...);
  • an axis used as a template, which matches the axes that are instances of its class and have the same value for every field that it sets;
  • an axis class, which matches its instances, so that ComponentAxis matches every point, vector, displacement and tensor axis;
  • a dictionary of axis fields, which stands for Axis(**fields), so that {"type": "space"} is the template SpaceAxis();
  • a function that receives an axis and returns whether it matches.

The ... of a variadic sequence matches no query.

AxisSequenceLike module-attribute

AxisSequenceLike: TypeAlias = (
    AxisSequence[AXIS] | Sequence[AXIS_LIKE]
)

A value that is a AxisSequence or that can be converted to one.

AxisSequence

Bases: Sequence[AXIS]

Axes of a coordinate system, some of which may be unknown.

An axis sequence holds Axis objects and at most one ..., which stands for zero or more unknown axes. A sequence that holds ... is variadic, because its number of axes is unknown; otherwise it is finite and lists every axis. The ... is an entry but never counts as an axis. A sequence with more than one ... describes no axes: the methods that read axes raise ValueError, and coordinate systems refuse it. For example, [..., TimeAxis()] says that the last axis is a time axis, and [...] says nothing.

This class is the read-only base of AxisList, which is mutable, and AxisTuple, which is immutable. Slicing and the methods that build new sequences return the type of the original sequence. The type parameter is the type of the items, so an AxisSequence[Axis], whose items are all axes, is finite.

Entries and axes

Length, iteration, equality and axes[i] work on entries, including .... ndim counts axes, and at, expand, restrict, embed and compatible_with work on positions in the space, where ... stands for as many axes as needed. Non-negative positions count from the first axis and negative positions from the last. In a finite sequence, entries and axes coincide. In [x, ..., t], however, axes[2] is t while axes.at(2) is one of the axes that ... stands for.

Finding an axis

index finds the first axis that matches a query, and indices finds every axis that matches it. A query is a name, a template axis, an axis class, a dictionary of axis fields or a function, as AxisQuery describes. Thus axes.index(TimeAxis()) finds the first time axis whatever its unit, and axes.indices(SpaceAxis) finds every spatial axis. Both methods return numbers that are entries and positions at once: an axis before ... is counted from the start and an axis after ... from the end, so that axes[i] and axes.at(i) give the same axis. The ... matches nothing, and an unknown Axis() matches no query that sets a field.

Names

axes["t"] returns the explicit axis named "t", "t" in axes tests for one, and names lists the names. A name that several axes share is refused. There is no mapping interface, because axes may be unnamed or share names.

Example

>>> x, t = Axis(name="x"), TimeAxis(name="t")
>>> axes = AxisList([x, ..., t])
>>> axes.ndim is None, axes.is_variadic
(True, True)
>>> axes.index("t"), axes.index(TimeAxis()), axes["t"] is t
(-1, -1, True)
>>> "x" in axes, axes.names
(True, ('x', Ellipsis, 't'))
>>> axes[2] is t, axes.at(2), axes.at(-1) is t
(True, Axis(), True)
>>> axes.expand(4)[1:]
[Axis(), Axis(), TimeAxis(name='t')]
>>> axes.restrict([-1, 0, 1])[1:]
[Axis(name='x'), Axis()]

names property

names: tuple[str | None | EllipsisType, ...]

Name of each entry, or None for an unnamed axis.

Example

>>> AxisList([Axis(name="x"), Axis(), ...]).names
('x', None, Ellipsis)

ndim property

ndim: int | None

Number of axes, or None when the sequence is variadic.

Example

>>> AxisList([Axis(), Axis()]).ndim
2
>>> AxisList([Axis(), ...]).ndim is None
True

is_variadic property

is_variadic: bool

Whether the sequence holds ..., so its number of axes is unknown.

AxisList([...]) is variadic, and an empty list is finite.

__getitem__

__getitem__(key: SupportsIndex) -> AXIS
__getitem__(key: slice) -> Self
__getitem__(key: str) -> Axis

Return an entry, a slice, or the explicit axis with a name.

Integers and slices index entries, as they do for a list, whereas at reads the axis at a position in the space.

Example

>>> x, t = Axis(name="x"), TimeAxis(name="t")
>>> AxisList([x, ..., t])["t"] is t
True
>>> AxisList([x, ..., t])[2] is t
True

Raises:

Type Description
KeyError

If no axis has the name.

ValueError

If several axes have the name.

__contains__

__contains__(item: object) -> bool

Return whether an item is an entry, or a string names an axis.

index

index(
    query: AxisQuery,
    start: SupportsIndex = 0,
    stop: SupportsIndex = maxsize,
) -> int

Return the index of the first axis that matches a query.

The test is looser than equality: unset fields of a template are not compared, as described in the class documentation. The index of an axis after ... counts from the end, so that it is both an entry and a position in the space.

Example

>>> x, t = SpaceAxis(name="x"), TimeAxis(name="t", unit="s")
>>> axes = AxisList([x, ..., t])
>>> axes.index("t"), axes.index(SpaceAxis())
(-1, 0)
>>> axes.index(Axis(unit="second")), axes.index(Axis())
(-1, 0)
>>> axes.index({"type": "time"}), axes.index(TimeAxis)
(-1, -1)
>>> axes.index("y")
Traceback (most recent call last):
  ...
ValueError: Axis(name='y') is not in list

Parameters:

Name Type Description Default
query AxisQuery

A name, a template axis, an axis class, a dictionary of axis fields or a function, as AxisQuery describes.

required
start int

Start of the search window among the entries, as for list.index.

0
stop int

End of the search window among the entries, as for list.index.

sys.maxsize

Returns:

Type Description
int

Index of the axis. It is non-negative for an axis before ... or in a finite sequence, and negative for an axis after ....

Raises:

Type Description
ValueError

If no axis matches.

TypeError

If the query is not one of the forms of AxisQuery.

indices

indices(query: AxisQuery) -> list[int]

Return the indices of every axis that matches a query.

The axes are found as by index, and their indices follow the order of the sequence. An index is both an entry and a position in the space: it counts from the start for an axis before ..., or in a finite sequence, and from the end for an axis after .... The indices can therefore be passed to restrict and at.

Example

>>> x, y = SpaceAxis(name="x"), SpaceAxis(name="y")
>>> t = TimeAxis(name="t")
>>> AxisList([x, y, t]).indices(SpaceAxis)
[0, 1]
>>> AxisList([x, ..., y, t]).indices({"type": "space"})
[0, -2]
>>> AxisList([x, y, t]).indices(lambda axis: axis.name != "y")
[0, 2]

Parameters:

Name Type Description Default
query AxisQuery

A name, a template axis, an axis class, a dictionary of axis fields or a function, as AxisQuery describes.

required

Returns:

Type Description
list of int

The indices of the matching axes, which is empty when no axis matches.

Raises:

Type Description
TypeError

If the query is not one of the forms of AxisQuery.

expand

expand(ndim: int) -> Self

Return a finite sequence of ndim axes.

In a variadic sequence, ... is replaced by as many unknown axes as needed. A finite sequence is returned as a copy.

Example

>>> AxisList([Axis(name="x"), ...]).expand(3)
[Axis(name='x'), Axis(), Axis()]
>>> AxisList([...]).expand(2)
[Axis(), Axis()]

Raises:

Type Description
ValueError

If ndim is smaller than the number of explicit axes of a variadic sequence, or differs from the length of a finite sequence.

TypeError

If ndim is not an integer.

restrict

restrict(
    refs: AxisQuery | Iterable[int | AxisQuery],
) -> Self

Return the axes that some references designate, in that order.

This is how a subspace is described, for example the spatial axes of an image. A reference is a position in the space, the name of an explicit axis as in axes[name], or any other query of AxisQuery, which designates every axis that it matches, in the order of the sequence. A single query may be given instead of a list. In a finite sequence of n axes, positions lie in [-n, n). In a variadic sequence, every position is valid, and the positions that fall among the axes of ... give unknown axes.

Example

>>> x, y = SpaceAxis(name="x"), SpaceAxis(name="y")
>>> t = TimeAxis(name="t")
>>> AxisList([x, y, t]).restrict(["t", 0])
[TimeAxis(name='t'), SpaceAxis(name='x')]
>>> AxisList([x, y, t]).restrict(SpaceAxis)
[SpaceAxis(name='x'), SpaceAxis(name='y')]
>>> AxisList([x, ...]).restrict([0, 1])
[SpaceAxis(name='x'), Axis()]

Parameters:

Name Type Description Default
refs AxisQuery or iterable of (int or AxisQuery)

The positions, names and other queries that designate the axes to keep.

required

Returns:

Type Description
AxisSequence

A new finite sequence with the designated axes.

Raises:

Type Description
IndexError

If a position lies outside a finite sequence.

KeyError

If no explicit axis has a name.

ValueError

If a name is shared, or two references designate the same axis.

TypeError

If a reference is neither an integer nor a query.

positions

positions(
    refs: AxisQuery | Iterable[int | AxisQuery],
) -> list[int]

Return the positions of the axes that references designate.

The references are read as restrict reads them, and the result lists the position of each designated axis, in the order of refs, instead of the axes themselves. A position in a finite sequence is made non-negative. A position in a variadic sequence is returned as it is given, and the position of an axis after ... counts from the end, as in indices.

Example

>>> x, y = SpaceAxis(name="x"), SpaceAxis(name="y")
>>> t = TimeAxis(name="t")
>>> AxisList([x, y, t]).positions(["t", -3])
[2, 0]
>>> AxisList([x, ..., t]).positions([SpaceAxis, "t", 1])
[0, -1, 1]

Parameters:

Name Type Description Default
refs AxisQuery or iterable of (int or AxisQuery)

The positions, names and other queries that designate the axes.

required

Returns:

Type Description
list of int

The position of each designated axis.

Raises:

Type Description
IndexError

If a position lies outside a finite sequence.

KeyError

If no explicit axis has a name.

ValueError

If a name is shared, or two references designate the same axis.

TypeError

If a reference is neither an integer nor a query.

embed

embed(
    positions: Iterable[int], ndim: int | None = None
) -> Self

Return the axes of a larger space in which these axes sit.

This method is the inverse of restrict. Axis j of this sequence sits at positions[j] in the larger space, and the other axes of the larger space are unknown. A variadic sequence is first broadcast to len(positions) axes, as by expand. Positions refer to a space that does not exist yet, so names are not accepted.

Example

>>> x = Axis(name="x")
>>> AxisList([x]).embed([1])
[Axis(), Axis(name='x'), Ellipsis]
>>> AxisList([x]).embed([1], ndim=3)
[Axis(), Axis(name='x'), Axis()]

Parameters:

Name Type Description Default
positions iterable of int

Non-negative position of each axis.

required
ndim int

Number of axes of the larger space. When it is omitted, the result is open-ended and ends with ....

None

Raises:

Type Description
ValueError

If a position is negative or repeated, if ndim does not exceed every position, or if the sequence cannot be restricted to len(positions) axes.

TypeError

If a position or ndim is not an integer.

compatible_with

compatible_with(other: Sequence[Any]) -> bool

Return whether two sequences could describe the same axes.

The sequences are compatible when some choice of what each ... stands for makes them match axis by axis, with each pair compatible in the sense of Axis.compatible_with. Unlike equality, an unknown axis matches any axis and [...] matches every sequence. The relation is symmetric but not transitive.

Example

>>> x, t = SpaceAxis(name="x"), TimeAxis()
>>> AxisList([x, ...]).compatible_with([x, Axis(), t])
True
>>> AxisList([..., t]).compatible_with([x])
False

Raises:

Type Description
TypeError

If other is not a list or a tuple.

at

at(position: int) -> Axis

Return the axis at a position in the space.

Non-negative positions count from the first axis and negative positions from the last. In a finite sequence, axes.at(i) equals axes[i] and the position lies in [-ndim, ndim). In a variadic sequence, every position is valid, and a position that falls among the axes of ... gives a new unknown axis.

Example

>>> x, t = Axis(name="x"), TimeAxis(name="t")
>>> axes = AxisList([x, ..., t])
>>> axes.at(0) is x, axes.at(-1) is t, axes.at(1)
(True, True, Axis())
>>> axes[2] is t, axes.at(2)
(True, Axis())

Raises:

Type Description
IndexError

If the position lies outside a finite sequence.

TypeError

If the position is not an integer.

AxisTuple

Bases: tuple, AxisSequence, Generic[Unpack[AXES]]

Immutable AxisSequence for systems with a fixed number of axes.

The type parameters fix the item type at each position, and thereby the number of items. A field typed AxisTuple[SpaceAxis, SpaceAxis] converts each item to the type of its position and refuses a wrong count, None and .... A bare AxisTuple holds any items.

Example

>>> axes = RASCoordinateSystem().axes
>>> type(axes).__name__, axes.ndim, axes.names[0]
('AxisTuple', 3, 'left-to-right')
>>> axes["left-to-right"] is axes[0] is axes.at(-3)
True

names property

names: tuple[str | None | EllipsisType, ...]

Name of each entry, or None for an unnamed axis.

Example

>>> AxisList([Axis(name="x"), Axis(), ...]).names
('x', None, Ellipsis)

ndim property

ndim: int | None

Number of axes, or None when the sequence is variadic.

Example

>>> AxisList([Axis(), Axis()]).ndim
2
>>> AxisList([Axis(), ...]).ndim is None
True

is_variadic property

is_variadic: bool

Whether the sequence holds ..., so its number of axes is unknown.

AxisList([...]) is variadic, and an empty list is finite.

indices

indices(query: AxisQuery) -> list[int]

Return the indices of every axis that matches a query.

The axes are found as by index, and their indices follow the order of the sequence. An index is both an entry and a position in the space: it counts from the start for an axis before ..., or in a finite sequence, and from the end for an axis after .... The indices can therefore be passed to restrict and at.

Example

>>> x, y = SpaceAxis(name="x"), SpaceAxis(name="y")
>>> t = TimeAxis(name="t")
>>> AxisList([x, y, t]).indices(SpaceAxis)
[0, 1]
>>> AxisList([x, ..., y, t]).indices({"type": "space"})
[0, -2]
>>> AxisList([x, y, t]).indices(lambda axis: axis.name != "y")
[0, 2]

Parameters:

Name Type Description Default
query AxisQuery

A name, a template axis, an axis class, a dictionary of axis fields or a function, as AxisQuery describes.

required

Returns:

Type Description
list of int

The indices of the matching axes, which is empty when no axis matches.

Raises:

Type Description
TypeError

If the query is not one of the forms of AxisQuery.

expand

expand(ndim: int) -> Self

Return a finite sequence of ndim axes.

In a variadic sequence, ... is replaced by as many unknown axes as needed. A finite sequence is returned as a copy.

Example

>>> AxisList([Axis(name="x"), ...]).expand(3)
[Axis(name='x'), Axis(), Axis()]
>>> AxisList([...]).expand(2)
[Axis(), Axis()]

Raises:

Type Description
ValueError

If ndim is smaller than the number of explicit axes of a variadic sequence, or differs from the length of a finite sequence.

TypeError

If ndim is not an integer.

restrict

restrict(
    refs: AxisQuery | Iterable[int | AxisQuery],
) -> Self

Return the axes that some references designate, in that order.

This is how a subspace is described, for example the spatial axes of an image. A reference is a position in the space, the name of an explicit axis as in axes[name], or any other query of AxisQuery, which designates every axis that it matches, in the order of the sequence. A single query may be given instead of a list. In a finite sequence of n axes, positions lie in [-n, n). In a variadic sequence, every position is valid, and the positions that fall among the axes of ... give unknown axes.

Example

>>> x, y = SpaceAxis(name="x"), SpaceAxis(name="y")
>>> t = TimeAxis(name="t")
>>> AxisList([x, y, t]).restrict(["t", 0])
[TimeAxis(name='t'), SpaceAxis(name='x')]
>>> AxisList([x, y, t]).restrict(SpaceAxis)
[SpaceAxis(name='x'), SpaceAxis(name='y')]
>>> AxisList([x, ...]).restrict([0, 1])
[SpaceAxis(name='x'), Axis()]

Parameters:

Name Type Description Default
refs AxisQuery or iterable of (int or AxisQuery)

The positions, names and other queries that designate the axes to keep.

required

Returns:

Type Description
AxisSequence

A new finite sequence with the designated axes.

Raises:

Type Description
IndexError

If a position lies outside a finite sequence.

KeyError

If no explicit axis has a name.

ValueError

If a name is shared, or two references designate the same axis.

TypeError

If a reference is neither an integer nor a query.

positions

positions(
    refs: AxisQuery | Iterable[int | AxisQuery],
) -> list[int]

Return the positions of the axes that references designate.

The references are read as restrict reads them, and the result lists the position of each designated axis, in the order of refs, instead of the axes themselves. A position in a finite sequence is made non-negative. A position in a variadic sequence is returned as it is given, and the position of an axis after ... counts from the end, as in indices.

Example

>>> x, y = SpaceAxis(name="x"), SpaceAxis(name="y")
>>> t = TimeAxis(name="t")
>>> AxisList([x, y, t]).positions(["t", -3])
[2, 0]
>>> AxisList([x, ..., t]).positions([SpaceAxis, "t", 1])
[0, -1, 1]

Parameters:

Name Type Description Default
refs AxisQuery or iterable of (int or AxisQuery)

The positions, names and other queries that designate the axes.

required

Returns:

Type Description
list of int

The position of each designated axis.

Raises:

Type Description
IndexError

If a position lies outside a finite sequence.

KeyError

If no explicit axis has a name.

ValueError

If a name is shared, or two references designate the same axis.

TypeError

If a reference is neither an integer nor a query.

embed

embed(
    positions: Iterable[int], ndim: int | None = None
) -> Self

Return the axes of a larger space in which these axes sit.

This method is the inverse of restrict. Axis j of this sequence sits at positions[j] in the larger space, and the other axes of the larger space are unknown. A variadic sequence is first broadcast to len(positions) axes, as by expand. Positions refer to a space that does not exist yet, so names are not accepted.

Example

>>> x = Axis(name="x")
>>> AxisList([x]).embed([1])
[Axis(), Axis(name='x'), Ellipsis]
>>> AxisList([x]).embed([1], ndim=3)
[Axis(), Axis(name='x'), Axis()]

Parameters:

Name Type Description Default
positions iterable of int

Non-negative position of each axis.

required
ndim int

Number of axes of the larger space. When it is omitted, the result is open-ended and ends with ....

None

Raises:

Type Description
ValueError

If a position is negative or repeated, if ndim does not exceed every position, or if the sequence cannot be restricted to len(positions) axes.

TypeError

If a position or ndim is not an integer.

compatible_with

compatible_with(other: Sequence[Any]) -> bool

Return whether two sequences could describe the same axes.

The sequences are compatible when some choice of what each ... stands for makes them match axis by axis, with each pair compatible in the sense of Axis.compatible_with. Unlike equality, an unknown axis matches any axis and [...] matches every sequence. The relation is symmetric but not transitive.

Example

>>> x, t = SpaceAxis(name="x"), TimeAxis()
>>> AxisList([x, ...]).compatible_with([x, Axis(), t])
True
>>> AxisList([..., t]).compatible_with([x])
False

Raises:

Type Description
TypeError

If other is not a list or a tuple.

at

at(position: int) -> Axis

Return the axis at a position in the space.

Non-negative positions count from the first axis and negative positions from the last. In a finite sequence, axes.at(i) equals axes[i] and the position lies in [-ndim, ndim). In a variadic sequence, every position is valid, and a position that falls among the axes of ... gives a new unknown axis.

Example

>>> x, t = Axis(name="x"), TimeAxis(name="t")
>>> axes = AxisList([x, ..., t])
>>> axes.at(0) is x, axes.at(-1) is t, axes.at(1)
(True, True, Axis())
>>> axes[2] is t, axes.at(2)
(True, Axis())

Raises:

Type Description
IndexError

If the position lies outside a finite sequence.

TypeError

If the position is not an integer.

AxisList

Bases: AxisSequence[AXIS], list

Mutable AxisSequence for systems with any number of axes.

A list or tuple given to such a system is converted item by item to the axis type of the system. The sequence [...] says nothing about the axes. A coordinate system may instead store None for unknown axes, which [get_axes][brainhops.datamodel._sugar.get_axes] reads as [...]. An AxisList[Axis] is finite.

Example

>>> axes = CoordinateSystem(axes=[Axis(name="x"), ...]).axes
>>> type(axes).__name__, axes.is_variadic, axes["x"]
('AxisList', True, Axis(name='x'))
>>> axes.append(TimeAxis(name="t"))
>>> axes.at(-1)
TimeAxis(name='t')

names property

names: tuple[str | None | EllipsisType, ...]

Name of each entry, or None for an unnamed axis.

Example

>>> AxisList([Axis(name="x"), Axis(), ...]).names
('x', None, Ellipsis)

ndim property

ndim: int | None

Number of axes, or None when the sequence is variadic.

Example

>>> AxisList([Axis(), Axis()]).ndim
2
>>> AxisList([Axis(), ...]).ndim is None
True

is_variadic property

is_variadic: bool

Whether the sequence holds ..., so its number of axes is unknown.

AxisList([...]) is variadic, and an empty list is finite.

__getitem__

__getitem__(key: SupportsIndex) -> AXIS
__getitem__(key: slice) -> Self
__getitem__(key: str) -> Axis

Return an entry, a slice, or the explicit axis with a name.

Integers and slices index entries, as they do for a list, whereas at reads the axis at a position in the space.

Example

>>> x, t = Axis(name="x"), TimeAxis(name="t")
>>> AxisList([x, ..., t])["t"] is t
True
>>> AxisList([x, ..., t])[2] is t
True

Raises:

Type Description
KeyError

If no axis has the name.

ValueError

If several axes have the name.

__contains__

__contains__(item: object) -> bool

Return whether an item is an entry, or a string names an axis.

index

index(
    query: AxisQuery,
    start: SupportsIndex = 0,
    stop: SupportsIndex = maxsize,
) -> int

Return the index of the first axis that matches a query.

The test is looser than equality: unset fields of a template are not compared, as described in the class documentation. The index of an axis after ... counts from the end, so that it is both an entry and a position in the space.

Example

>>> x, t = SpaceAxis(name="x"), TimeAxis(name="t", unit="s")
>>> axes = AxisList([x, ..., t])
>>> axes.index("t"), axes.index(SpaceAxis())
(-1, 0)
>>> axes.index(Axis(unit="second")), axes.index(Axis())
(-1, 0)
>>> axes.index({"type": "time"}), axes.index(TimeAxis)
(-1, -1)
>>> axes.index("y")
Traceback (most recent call last):
  ...
ValueError: Axis(name='y') is not in list

Parameters:

Name Type Description Default
query AxisQuery

A name, a template axis, an axis class, a dictionary of axis fields or a function, as AxisQuery describes.

required
start int

Start of the search window among the entries, as for list.index.

0
stop int

End of the search window among the entries, as for list.index.

sys.maxsize

Returns:

Type Description
int

Index of the axis. It is non-negative for an axis before ... or in a finite sequence, and negative for an axis after ....

Raises:

Type Description
ValueError

If no axis matches.

TypeError

If the query is not one of the forms of AxisQuery.

indices

indices(query: AxisQuery) -> list[int]

Return the indices of every axis that matches a query.

The axes are found as by index, and their indices follow the order of the sequence. An index is both an entry and a position in the space: it counts from the start for an axis before ..., or in a finite sequence, and from the end for an axis after .... The indices can therefore be passed to restrict and at.

Example

>>> x, y = SpaceAxis(name="x"), SpaceAxis(name="y")
>>> t = TimeAxis(name="t")
>>> AxisList([x, y, t]).indices(SpaceAxis)
[0, 1]
>>> AxisList([x, ..., y, t]).indices({"type": "space"})
[0, -2]
>>> AxisList([x, y, t]).indices(lambda axis: axis.name != "y")
[0, 2]

Parameters:

Name Type Description Default
query AxisQuery

A name, a template axis, an axis class, a dictionary of axis fields or a function, as AxisQuery describes.

required

Returns:

Type Description
list of int

The indices of the matching axes, which is empty when no axis matches.

Raises:

Type Description
TypeError

If the query is not one of the forms of AxisQuery.

expand

expand(ndim: int) -> Self

Return a finite sequence of ndim axes.

In a variadic sequence, ... is replaced by as many unknown axes as needed. A finite sequence is returned as a copy.

Example

>>> AxisList([Axis(name="x"), ...]).expand(3)
[Axis(name='x'), Axis(), Axis()]
>>> AxisList([...]).expand(2)
[Axis(), Axis()]

Raises:

Type Description
ValueError

If ndim is smaller than the number of explicit axes of a variadic sequence, or differs from the length of a finite sequence.

TypeError

If ndim is not an integer.

restrict

restrict(
    refs: AxisQuery | Iterable[int | AxisQuery],
) -> Self

Return the axes that some references designate, in that order.

This is how a subspace is described, for example the spatial axes of an image. A reference is a position in the space, the name of an explicit axis as in axes[name], or any other query of AxisQuery, which designates every axis that it matches, in the order of the sequence. A single query may be given instead of a list. In a finite sequence of n axes, positions lie in [-n, n). In a variadic sequence, every position is valid, and the positions that fall among the axes of ... give unknown axes.

Example

>>> x, y = SpaceAxis(name="x"), SpaceAxis(name="y")
>>> t = TimeAxis(name="t")
>>> AxisList([x, y, t]).restrict(["t", 0])
[TimeAxis(name='t'), SpaceAxis(name='x')]
>>> AxisList([x, y, t]).restrict(SpaceAxis)
[SpaceAxis(name='x'), SpaceAxis(name='y')]
>>> AxisList([x, ...]).restrict([0, 1])
[SpaceAxis(name='x'), Axis()]

Parameters:

Name Type Description Default
refs AxisQuery or iterable of (int or AxisQuery)

The positions, names and other queries that designate the axes to keep.

required

Returns:

Type Description
AxisSequence

A new finite sequence with the designated axes.

Raises:

Type Description
IndexError

If a position lies outside a finite sequence.

KeyError

If no explicit axis has a name.

ValueError

If a name is shared, or two references designate the same axis.

TypeError

If a reference is neither an integer nor a query.

positions

positions(
    refs: AxisQuery | Iterable[int | AxisQuery],
) -> list[int]

Return the positions of the axes that references designate.

The references are read as restrict reads them, and the result lists the position of each designated axis, in the order of refs, instead of the axes themselves. A position in a finite sequence is made non-negative. A position in a variadic sequence is returned as it is given, and the position of an axis after ... counts from the end, as in indices.

Example

>>> x, y = SpaceAxis(name="x"), SpaceAxis(name="y")
>>> t = TimeAxis(name="t")
>>> AxisList([x, y, t]).positions(["t", -3])
[2, 0]
>>> AxisList([x, ..., t]).positions([SpaceAxis, "t", 1])
[0, -1, 1]

Parameters:

Name Type Description Default
refs AxisQuery or iterable of (int or AxisQuery)

The positions, names and other queries that designate the axes.

required

Returns:

Type Description
list of int

The position of each designated axis.

Raises:

Type Description
IndexError

If a position lies outside a finite sequence.

KeyError

If no explicit axis has a name.

ValueError

If a name is shared, or two references designate the same axis.

TypeError

If a reference is neither an integer nor a query.

embed

embed(
    positions: Iterable[int], ndim: int | None = None
) -> Self

Return the axes of a larger space in which these axes sit.

This method is the inverse of restrict. Axis j of this sequence sits at positions[j] in the larger space, and the other axes of the larger space are unknown. A variadic sequence is first broadcast to len(positions) axes, as by expand. Positions refer to a space that does not exist yet, so names are not accepted.

Example

>>> x = Axis(name="x")
>>> AxisList([x]).embed([1])
[Axis(), Axis(name='x'), Ellipsis]
>>> AxisList([x]).embed([1], ndim=3)
[Axis(), Axis(name='x'), Axis()]

Parameters:

Name Type Description Default
positions iterable of int

Non-negative position of each axis.

required
ndim int

Number of axes of the larger space. When it is omitted, the result is open-ended and ends with ....

None

Raises:

Type Description
ValueError

If a position is negative or repeated, if ndim does not exceed every position, or if the sequence cannot be restricted to len(positions) axes.

TypeError

If a position or ndim is not an integer.

compatible_with

compatible_with(other: Sequence[Any]) -> bool

Return whether two sequences could describe the same axes.

The sequences are compatible when some choice of what each ... stands for makes them match axis by axis, with each pair compatible in the sense of Axis.compatible_with. Unlike equality, an unknown axis matches any axis and [...] matches every sequence. The relation is symmetric but not transitive.

Example

>>> x, t = SpaceAxis(name="x"), TimeAxis()
>>> AxisList([x, ...]).compatible_with([x, Axis(), t])
True
>>> AxisList([..., t]).compatible_with([x])
False

Raises:

Type Description
TypeError

If other is not a list or a tuple.

at

at(position: int) -> Axis

Return the axis at a position in the space.

Non-negative positions count from the first axis and negative positions from the last. In a finite sequence, axes.at(i) equals axes[i] and the position lies in [-ndim, ndim). In a variadic sequence, every position is valid, and a position that falls among the axes of ... gives a new unknown axis.

Example

>>> x, t = Axis(name="x"), TimeAxis(name="t")
>>> axes = AxisList([x, ..., t])
>>> axes.at(0) is x, axes.at(-1) is t, axes.at(1)
(True, True, Axis())
>>> axes[2] is t, axes.at(2)
(True, Axis())

Raises:

Type Description
IndexError

If the position lies outside a finite sequence.

TypeError

If the position is not an integer.