Skip to content

Labeled data

Alignment of labeled arrays and tables to the canonical layout of a tensor type, by axis name and coordinate. The surface is in Programs and data.

axis_data

Binding labeled data to tensors indexed by finite types.

A value for a tensor type with named axes is matched to the axes by label, never by position. It may be given as

  • a labeled array: an xarray DataArray, or its dictionary form {"dims": [...], "coords": {...}, "data": [...]} (what DataArray.to_dict() writes, and what qvr run --data reads as JSON), whose dimension names are the tensor's axis names and whose coordinates along a named axis are that axis's coordinate labels;
  • a columnar table: a data frame (any object with columns whose columns convert with to_numpy()), or {"columns": {name: [...], ...}}, with one column per axis holding each row's coordinate and one more column holding the value. A record axis may instead be given by one column per field.

An axis's name is its type's rendering (World, Bool, {knows : Bool, linguist : Bool}) or Fin n for a positional axis; a name repeated within one tensor type is suffixed #1, #2 (tensor_axes). A coordinate is an element's label: true, Linguist, {knows = true, linguist = false}, or a position for Fin n.

Alignment checks the dimension names and the coordinate set of every axis and refuses a missing, an unknown, or a repeated coordinate with the coordinate named; it reorders labeled data into the canonical order the type fixes, and never reorders positional data. The aligned value is the nested tuple of the entries in canonical order, so two inputs that state the same entries (in any row order, as an array or a table) align to equal values and equal data digests. Positional data (nested lists or a tensor) is accepted for a tensor whose axes are all positional.

Scalar

Scalar = bool | int | float | str

One entry or one coordinate of a labeled value.

Entries

Entries = Scalar | tuple[Entries, ...]

Entries nested by axis, outermost first.

AxisDataError

Bases: ValueError

Data whose labels do not match the axes of its tensor type.

The message names the axis and the coordinate that do not match.

LabeledArray

Bases: Protocol

An array with named dimensions and coordinate labels, as xarray's.

dims property

dims: tuple[str, ...]

The dimension names, in the array's layout order.

coords property

coords: Mapping[str, object]

The coordinate arrays, by dimension name.

values property

values: object

The entries, as an array in layout order.

ColumnarTable

Bases: Protocol

A table of named columns, as a pandas or polars data frame.

columns property

columns: Iterable[str]

The column names.

__getitem__

__getitem__(name: str) -> object

Read one column by name.

PARAMETER DESCRIPTION
name

The column's name.

TYPE: str

RETURNS DESCRIPTION
object

The column in the table's native representation.

Source code in src/quivers/qiec/axis_data.py
def __getitem__(self, name: str, /) -> object:
    """Read one column by name.

    Parameters
    ----------
    name : str
        The column's name.

    Returns
    -------
    object
        The column in the table's native representation.
    """
    ...

ModuleDeclarations

ModuleDeclarations(module: QiecModule)

The family and constructor declarations of a checked module.

PARAMETER DESCRIPTION
module

The module.

TYPE: QiecModule

Source code in src/quivers/qiec/axis_data.py
def __init__(self, module: QiecModule) -> None:
    self._families = {family.id: family for family in module.families}
    self._constructors = {
        constructor.id: constructor for constructor in module.constructors
    }

families property

families: Mapping[FamilyId, FamilyDecl]

The module's families, by identity.

RETURNS DESCRIPTION
Mapping[FamilyId, FamilyDecl]

The families.

constructors property

constructors: Mapping[ConstructorId, ConstructorDecl]

The module's constructors, by identity.

RETURNS DESCRIPTION
Mapping[ConstructorId, ConstructorDecl]

The constructors.

coordinate_label

coordinate_label(item: Scalar) -> str

The label a data coordinate denotes.

PARAMETER DESCRIPTION
item

A coordinate as data holds it.

TYPE: Scalar

RETURNS DESCRIPTION
str

true/false for a Boolean, the decimal text of an integer, the text itself otherwise.

RAISES DESCRIPTION
AxisDataError

If the coordinate is a non-integral number.

Source code in src/quivers/qiec/axis_data.py
def coordinate_label(item: Scalar) -> str:
    """The label a data coordinate denotes.

    Parameters
    ----------
    item : Scalar
        A coordinate as data holds it.

    Returns
    -------
    str
        ``true``/``false`` for a Boolean, the decimal text of an integer,
        the text itself otherwise.

    Raises
    ------
    AxisDataError
        If the coordinate is a non-integral number.
    """
    if isinstance(item, bool):
        return "true" if item else "false"
    if isinstance(item, int):
        return str(item)
    if isinstance(item, float):
        if not item.is_integer():
            raise AxisDataError(f"coordinate {item!r} is not a label or a position")
        return str(int(item))
    return item

labeled

labeled(value: object) -> bool

Whether a value carries axis labels.

PARAMETER DESCRIPTION
value

A datum.

TYPE: object

RETURNS DESCRIPTION
bool

True for a labeled array or table, or their dictionary forms.

Source code in src/quivers/qiec/axis_data.py
def labeled(value: object) -> bool:
    """Whether a value carries axis labels.

    Parameters
    ----------
    value : object
        A datum.

    Returns
    -------
    bool
        True for a labeled array or table, or their dictionary forms.
    """
    if isinstance(value, Mapping):
        keys = set(value)
        return keys == {"columns"} or {"dims", "data"} <= keys <= {
            "dims",
            "coords",
            "data",
            "attrs",
            "name",
        }
    return isinstance(value, LabeledArray | ColumnarTable)

align_value

align_value(value: object, type_: TypeExpr, declarations: Declarations, *, name: str) -> object

Align one datum to the canonical layout of its tensor type.

PARAMETER DESCRIPTION
value

The datum: labeled (an array, a table, or their dictionary forms), or positional.

TYPE: object

type_

The parameter's type.

TYPE: TypeExpr

declarations

The declarations its axis types refer to.

TYPE: Declarations

name

The parameter's name, for the diagnostics.

TYPE: str

RETURNS DESCRIPTION
object

The entries in canonical order as nested tuples, for labeled data; the datum itself for positional data of a tensor with positional axes only, or of a type that is not a tensor.

RAISES DESCRIPTION
AxisDataError

If labeled data does not match the axes, or positional data is given for a tensor with a named axis.

Source code in src/quivers/qiec/axis_data.py
def align_value(
    value: object, type_: TypeExpr, declarations: Declarations, *, name: str
) -> object:
    """Align one datum to the canonical layout of its tensor type.

    Parameters
    ----------
    value : object
        The datum: labeled (an array, a table, or their dictionary forms),
        or positional.
    type_ : TypeExpr
        The parameter's type.
    declarations : Declarations
        The declarations its axis types refer to.
    name : str
        The parameter's name, for the diagnostics.

    Returns
    -------
    object
        The entries in canonical order as nested tuples, for labeled data;
        the datum itself for positional data of a tensor with positional
        axes only, or of a type that is not a tensor.

    Raises
    ------
    AxisDataError
        If labeled data does not match the axes, or positional data is
        given for a tensor with a named axis.
    """
    split = tensor_shape(type_)
    if split is None:
        if labeled(value):
            raise AxisDataError(
                f"{name}: labeled data for a value that is not a tensor"
            )
        return value
    dimensions = tuple(split[1])
    if not labeled(value):
        if named_dimensions(dimensions):
            raise AxisDataError(
                f"{name}: a tensor with axes named by types is bound to labeled "
                'data (an xarray DataArray, a table, or {"dims", "coords", '
                '"data"}), never by position'
            )
        return value
    axes = tensor_axes(dimensions, declarations)
    if any(axis.extent is None for axis in axes):
        raise AxisDataError(
            f"{name}: labeled data needs every axis's extent fixed by the type"
        )
    return align_axes(value, axes, name=name, dimensions=dimensions)

align_axes

align_axes(value: object, axes: tuple[TensorAxis, ...], *, name: str, dimensions: tuple[IndexTerm, ...] | None = None) -> Entries

Align labeled data to axes given by name and coordinates.

PARAMETER DESCRIPTION
value

A labeled array or table, or their dictionary forms.

TYPE: object

axes

The axes in layout order, each with its name and coordinates.

TYPE: tuple[TensorAxis, ...]

name

The datum's name, for the diagnostics.

TYPE: str

dimensions

The axes' dimensions, which let a record axis be read from one column per field; None when the axes are not named by types.

TYPE: tuple[IndexTerm, ...] or None DEFAULT: None

RETURNS DESCRIPTION
Entries

The entries in the axes' order, nested as tuples.

RAISES DESCRIPTION
AxisDataError

If the data's dimensions are not the axes, or an axis's coordinates do not match.

Source code in src/quivers/qiec/axis_data.py
def align_axes(
    value: object,
    axes: tuple[TensorAxis, ...],
    *,
    name: str,
    dimensions: tuple[IndexTerm, ...] | None = None,
) -> Entries:
    """Align labeled data to axes given by name and coordinates.

    Parameters
    ----------
    value : object
        A labeled array or table, or their dictionary forms.
    axes : tuple[TensorAxis, ...]
        The axes in layout order, each with its name and coordinates.
    name : str
        The datum's name, for the diagnostics.
    dimensions : tuple[IndexTerm, ...] or None
        The axes' dimensions, which let a record axis be read from one
        column per field; None when the axes are not named by types.

    Returns
    -------
    Entries
        The entries in the axes' order, nested as tuples.

    Raises
    ------
    AxisDataError
        If the data's dimensions are not the axes, or an axis's
        coordinates do not match.
    """
    if dimensions is None:
        dimensions = tuple(
            IndexLiteral(value=axis.extent or 0, sort=NAT) for axis in axes
        )
    if isinstance(value, Mapping) and set(value) == {"columns"}:
        raw = cast(Mapping[str, object], value["columns"])
        return _align_columns(
            name, axes, dimensions, {key: _items(column) for key, column in raw.items()}
        )
    if isinstance(value, Mapping):
        dims = [str(dim) for dim in cast(Sequence[object], value["dims"])]
        raw_coords = cast(Mapping[str, object], value.get("coords") or {})
        coords = {
            key: _items(
                coordinate["data"] if isinstance(coordinate, Mapping) else coordinate
            )
            for key, coordinate in raw_coords.items()
        }
        return _align_array(name, axes, dims, coords, _nested(value["data"]))
    if isinstance(value, LabeledArray):
        coords = {
            str(key): _items(coordinate)
            for key, coordinate in value.coords.items()
            if str(key) in value.dims
        }
        return _align_array(
            name, axes, [str(dim) for dim in value.dims], coords, _nested(value.values)
        )
    table = cast(ColumnarTable, value)
    return _align_columns(
        name,
        axes,
        dimensions,
        {str(column): _items(table[str(column)]) for column in table.columns},
    )

axis_coordinates

axis_coordinates(type_: TypeExpr, declarations: Declarations) -> tuple[TensorAxis, ...]

The axes a datum of a tensor type is labeled with.

PARAMETER DESCRIPTION
type_

A tensor type.

TYPE: TypeExpr

declarations

The declarations its axis types refer to.

TYPE: Declarations

RETURNS DESCRIPTION
tuple[TensorAxis, ...]

Its axes in canonical order, with names and coordinates; empty for a type that is not a tensor.

Source code in src/quivers/qiec/axis_data.py
def axis_coordinates(
    type_: TypeExpr, declarations: Declarations
) -> tuple[TensorAxis, ...]:
    """The axes a datum of a tensor type is labeled with.

    Parameters
    ----------
    type_ : TypeExpr
        A tensor type.
    declarations : Declarations
        The declarations its axis types refer to.

    Returns
    -------
    tuple[TensorAxis, ...]
        Its axes in canonical order, with names and coordinates; empty for
        a type that is not a tensor.
    """
    split = tensor_shape(type_)
    return () if split is None else tensor_axes(tuple(split[1]), declarations)