Skip to content

Finite axes

Which types index a tensor axis, the canonical order of their elements and of a tensor's axes, the coordinate labels data and targets read, and the erasure of axis names at the first-order boundary. The rules are in Finite axes.

axes

Finite types as the index sets of tensor axes.

A tensor's dimensions are extents. A dimension that is an AxisExtent is also named: it ranges over the elements of a finite type, in the order that type fixes, so a tensor Real[World] is a function from World to Real laid out as an array [@paszke2021getting]. A positional dimension is the Fin n case: it ranges over the positions 0 to n - 1.

This module answers what such an axis is:

  • whether a type is finite, and its elements in canonical order (axis_elements) with their coordinate labels;
  • its cardinality (axis_cardinality) and the extent that names it (axis_extent);
  • the canonical order of a tensor's axes (canonical_dimensions): named axes first, sorted by the axis's rendering, then positional axes in the order written, so a tensor type does not depend on the order its axes are written in;
  • the axis map of a tensor type, which data binding and transpile targets read (tensor_axes);
  • the erasure of names at the first-order boundary (erase_axes), after which every compiled or exported reader sees positional arrays in canonical order.

The canonical order of a finite type's elements:

Type Elements, in order
Bool false, true
Unit unit
an index sort of nullary constructors its constructors, in declaration order
a closed family its constructors in declaration order, each with its fields varying lexicographically, the first field slowest
a product A * B lexicographic, A slowest
a record {a : A, b : B} lexicographic over the fields in label order
a variant <a : A, b : B> the labels in order, each with its payload's elements

Every other type is not finite, and naming an axis by it is refused with the property that fails: an infinite primitive, a recursive family, a family with indices or with a constructor that binds its own statics, a function type, an open row, an abstract type variable.

Declarations

Bases: Protocol

The declarations enumerating a finite type reads.

KernelRegistry and the elaborator's tables both provide them.

families property

families: Mapping[FamilyId, FamilyDecl]

The declared families, by identity.

constructors property

constructors: Mapping[ConstructorId, ConstructorDecl]

The declared constructors, by identity.

FiniteAxisError

FiniteAxisError(message: str, code: str = 'qiec-axis')

Bases: TypeError

A type named as an axis is not finite, or an extent misnames it.

PARAMETER DESCRIPTION
message

What was refused and the property that fails.

TYPE: str

code

The diagnostic code, qiec-axis.

TYPE: str DEFAULT: 'qiec-axis'

Source code in src/quivers/qiec/axes.py
def __init__(self, message: str, code: str = "qiec-axis") -> None:
    super().__init__(message)
    self.message = message
    self.code = code

ElementTree didactic-model

ElementTree(*, kind: str, head: str = '', labels: tuple[str, ...] = (), parts: tuple[ElementTree, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

The structure of one element of a finite type.

PARAMETER DESCRIPTION
kind

"bool", "unit", "index" (an index sort's constructor), "constructor" (a family constructor), "tuple", "record", or "variant".

TYPE: str

head

The Boolean's spelling, the constructor's name, or the variant's label; empty for a tuple, a record, or unit.

TYPE: str DEFAULT: ''

labels

The record's field labels in order, aligned with parts.

TYPE: tuple[str, ...] DEFAULT: ()

parts

The trees of the element's components, in order.

TYPE: tuple[ElementTree, ...] DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

AxisElement didactic-model

AxisElement(*, label: str, tree: ElementTree = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

One element of a finite type, as an axis coordinate.

PARAMETER DESCRIPTION
label

The element's coordinate label: true, Linguist, {knows = true, linguist = false}, (Red, 2).

TYPE: str

tree

The element's structure: a constructor, label, or literal name at the head with the trees of its parts, which the elaborator turns into a value or a static index.

TYPE: ElementTree DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

TensorAxis didactic-model

TensorAxis(*, name: str, extent: int | None, coordinates: tuple[str, ...] = (), named: bool = False)

Bases: QiecModel

One axis of a tensor type, as data and targets see it.

PARAMETER DESCRIPTION
name

The axis's name: the rendering of its finite type, or Fin n for a positional axis, with #k appended to the k-th repeat of a name within one tensor type.

TYPE: str

extent

Its extent, when static.

TYPE: int | None

coordinates

The coordinate labels in canonical order; for a positional axis, the positions 0 to n - 1 as text.

TYPE: tuple[str, ...] DEFAULT: ()

named

Whether the axis is named by a finite type.

TYPE: bool DEFAULT: False

product_components

product_components(type_: TypeExpr) -> tuple[TypeExpr, ...] | None

The components of a builtin product type.

PARAMETER DESCRIPTION
type_

A type.

TYPE: TypeExpr

RETURNS DESCRIPTION
tuple[TypeExpr, ...] or None

The component types, or None when the type is not a product.

Source code in src/quivers/qiec/axes.py
def product_components(type_: TypeExpr) -> tuple[TypeExpr, ...] | None:
    """The components of a builtin product type.

    Parameters
    ----------
    type_ : TypeExpr
        A type.

    Returns
    -------
    tuple[TypeExpr, ...] or None
        The component types, or ``None`` when the type is not a product.
    """
    if not isinstance(type_, TypeApplication):
        return None
    arity = len(type_.arguments)
    if arity < 2 or type_.constructor.id != TypeId.derive(
        "builtin", _PRODUCT_PREFIX, arity
    ):
        return None
    components = tuple(
        argument
        for argument in type_.arguments
        if isinstance(
            argument,
            TypeVariable
            | TypeApplication
            | FunctionType
            | EqualityType
            | RecordType
            | VariantType,
        )
    )
    return components if len(components) == arity else None

family_of

family_of(type_: TypeApplication, registry: Declarations) -> FamilyDecl | None

The declared family a type application applies, if any.

PARAMETER DESCRIPTION
type_

A type application.

TYPE: TypeApplication

registry

The declarations in scope.

TYPE: KernelRegistry

RETURNS DESCRIPTION
FamilyDecl or None

The family, or None for a builtin constructor.

Source code in src/quivers/qiec/axes.py
def family_of(type_: TypeApplication, registry: Declarations) -> FamilyDecl | None:
    """The declared family a type application applies, if any.

    Parameters
    ----------
    type_ : TypeApplication
        A type application.
    registry : KernelRegistry
        The declarations in scope.

    Returns
    -------
    FamilyDecl or None
        The family, or ``None`` for a builtin constructor.
    """
    for family in registry.families.values():
        if family.type_constructor.id == type_.constructor.id:
            return family
    return None

constructor_field_types

constructor_field_types(family: FamilyDecl, constructor: ConstructorDecl, type_: TypeApplication) -> tuple[TypeExpr, ...]

A constructor's field types at the family's static arguments.

PARAMETER DESCRIPTION
family

The family.

TYPE: FamilyDecl

constructor

One of its constructors.

TYPE: ConstructorDecl

type_

The family applied to its parameters.

TYPE: TypeApplication

RETURNS DESCRIPTION
tuple[TypeExpr, ...]

The field types with the parameters substituted.

Source code in src/quivers/qiec/axes.py
def constructor_field_types(
    family: FamilyDecl,
    constructor: ConstructorDecl,
    type_: TypeApplication,
) -> tuple[TypeExpr, ...]:
    """A constructor's field types at the family's static arguments.

    Parameters
    ----------
    family : FamilyDecl
        The family.
    constructor : ConstructorDecl
        One of its constructors.
    type_ : TypeApplication
        The family applied to its parameters.

    Returns
    -------
    tuple[TypeExpr, ...]
        The field types with the parameters substituted.
    """
    types: list[tuple[str, TypeExpr]] = []
    indices: list[tuple[str, IndexTerm]] = []
    for binder, argument in zip(family.parameters, type_.arguments, strict=True):
        if isinstance(binder, TypeBinder):
            types.append((binder.name, cast(TypeExpr, argument)))
        elif isinstance(binder, IndexBinder):
            indices.append((binder.name, cast(IndexTerm, argument)))
    substitution = StaticSubstitution(types=tuple(types), indices=tuple(indices))
    return tuple(
        substitute_type(field.type, substitution) for field in constructor.fields
    )

element_label

element_label(tree: ElementTree) -> str

The coordinate label of one element.

PARAMETER DESCRIPTION
tree

The element.

TYPE: ElementTree

RETURNS DESCRIPTION
str

Its surface spelling: true, Red, Pair(Red, true), (Red, true), {a = Red, b = true}, <a = Red>, <a>.

Source code in src/quivers/qiec/axes.py
def element_label(tree: ElementTree) -> str:
    """The coordinate label of one element.

    Parameters
    ----------
    tree : ElementTree
        The element.

    Returns
    -------
    str
        Its surface spelling: ``true``, ``Red``, ``Pair(Red, true)``,
        ``(Red, true)``, ``{a = Red, b = true}``, ``<a = Red>``, ``<a>``.
    """
    parts = [element_label(part) for part in tree.parts]
    if tree.kind in {"bool", "index"}:
        return tree.head
    if tree.kind == "unit":
        return "unit"
    if tree.kind == "constructor":
        return tree.head if not parts else f"{tree.head}({', '.join(parts)})"
    if tree.kind == "tuple":
        return f"({', '.join(parts)})"
    if tree.kind == "record":
        inner = ", ".join(
            f"{label} = {part}" for label, part in zip(tree.labels, parts, strict=True)
        )
        return "{" + inner + "}"
    payload = tree.parts[0]
    if payload.kind == "unit":
        return f"<{tree.head}>"
    return f"<{tree.head} = {parts[0]}>"

axis_elements

axis_elements(axis: AxisType, registry: Declarations) -> tuple[AxisElement, ...]

The elements of a finite type, in canonical order.

PARAMETER DESCRIPTION
axis

A finite type or index sort.

TYPE: AxisType

registry

The declarations in scope.

TYPE: KernelRegistry

RETURNS DESCRIPTION
tuple[AxisElement, ...]

Each element with its coordinate label.

RAISES DESCRIPTION
FiniteAxisError

If the type is not finite, naming the property that fails.

Source code in src/quivers/qiec/axes.py
def axis_elements(axis: AxisType, registry: Declarations) -> tuple[AxisElement, ...]:
    """The elements of a finite type, in canonical order.

    Parameters
    ----------
    axis : AxisType
        A finite type or index sort.
    registry : KernelRegistry
        The declarations in scope.

    Returns
    -------
    tuple[AxisElement, ...]
        Each element with its coordinate label.

    Raises
    ------
    FiniteAxisError
        If the type is not finite, naming the property that fails.
    """
    return tuple(
        AxisElement(label=element_label(tree), tree=tree)
        for tree in _trees(axis, registry, frozenset())
    )

axis_cardinality

axis_cardinality(axis: AxisType, registry: Declarations) -> int

The number of elements of a finite type.

PARAMETER DESCRIPTION
axis

A finite type or index sort.

TYPE: AxisType

registry

The declarations in scope.

TYPE: KernelRegistry

RETURNS DESCRIPTION
int

Its cardinality.

RAISES DESCRIPTION
FiniteAxisError

If the type is not finite.

Source code in src/quivers/qiec/axes.py
def axis_cardinality(axis: AxisType, registry: Declarations) -> int:
    """The number of elements of a finite type.

    Parameters
    ----------
    axis : AxisType
        A finite type or index sort.
    registry : KernelRegistry
        The declarations in scope.

    Returns
    -------
    int
        Its cardinality.

    Raises
    ------
    FiniteAxisError
        If the type is not finite.
    """
    return _cardinality(axis, registry, frozenset())

element_ordinal

element_ordinal(axis: AxisType, tree: ElementTree, registry: Declarations) -> int

The position of one element in its type's canonical order.

PARAMETER DESCRIPTION
axis

A finite type or index sort.

TYPE: AxisType

tree

An element of it.

TYPE: ElementTree

registry

The declarations in scope.

TYPE: Declarations

RETURNS DESCRIPTION
int

The element's ordinal, computed by mixed radix without listing the type's elements.

RAISES DESCRIPTION
FiniteAxisError

If the type is not finite or the tree is not one of its elements.

Source code in src/quivers/qiec/axes.py
def element_ordinal(axis: AxisType, tree: ElementTree, registry: Declarations) -> int:
    """The position of one element in its type's canonical order.

    Parameters
    ----------
    axis : AxisType
        A finite type or index sort.
    tree : ElementTree
        An element of it.

    registry : Declarations
        The declarations in scope.

    Returns
    -------
    int
        The element's ordinal, computed by mixed radix without listing
        the type's elements.

    Raises
    ------
    FiniteAxisError
        If the type is not finite or the tree is not one of its elements.
    """
    return _ordinal(axis, tree, registry, frozenset())

axis_extent

axis_extent(axis: AxisType, registry: Declarations) -> AxisExtent

The dimension of an axis named by a finite type.

PARAMETER DESCRIPTION
axis

A finite type or index sort.

TYPE: AxisType

registry

The declarations in scope.

TYPE: KernelRegistry

RETURNS DESCRIPTION
AxisExtent

The named extent.

RAISES DESCRIPTION
FiniteAxisError

If the type is not finite.

Source code in src/quivers/qiec/axes.py
def axis_extent(axis: AxisType, registry: Declarations) -> AxisExtent:
    """The dimension of an axis named by a finite type.

    Parameters
    ----------
    axis : AxisType
        A finite type or index sort.
    registry : KernelRegistry
        The declarations in scope.

    Returns
    -------
    AxisExtent
        The named extent.

    Raises
    ------
    FiniteAxisError
        If the type is not finite.
    """
    return AxisExtent(value=axis_cardinality(axis, registry), sort=NAT, axis=axis)

registration_order

registration_order(families: Iterable[FamilyDecl], constructors: Iterable[ConstructorDecl]) -> tuple[ConstructorDecl, ...]

Order constructors so each follows those its fields' axes enumerate.

A constructor field of type Real[T] has an axis whose extent is the number of values of T, which the constructors of the families T reaches determine, so checking the field reads them. Families keep their given order where no axis relates them, and each family's constructors keep theirs; the order depends only on the declarations, not on the order a lowering produced them in.

PARAMETER DESCRIPTION
families

The families the constructors belong to.

TYPE: Iterable[FamilyDecl]

constructors

The constructors, grouped by family in their declared order.

TYPE: Iterable[ConstructorDecl]

RETURNS DESCRIPTION
tuple[ConstructorDecl, ...]

The constructors, each family's after those of every family its fields' axes reach.

RAISES DESCRIPTION
FiniteAxisError

If a field of a family's constructors indexes a tensor by a type that reaches the family itself.

Source code in src/quivers/qiec/axes.py
def registration_order(
    families: Iterable[FamilyDecl], constructors: Iterable[ConstructorDecl]
) -> tuple[ConstructorDecl, ...]:
    """Order constructors so each follows those its fields' axes enumerate.

    A constructor field of type ``Real[T]`` has an axis whose extent is the
    number of values of ``T``, which the constructors of the families ``T``
    reaches determine, so checking the field reads them. Families keep
    their given order where no axis relates them, and each family's
    constructors keep theirs; the order depends only on the declarations,
    not on the order a lowering produced them in.

    Parameters
    ----------
    families : Iterable[FamilyDecl]
        The families the constructors belong to.
    constructors : Iterable[ConstructorDecl]
        The constructors, grouped by family in their declared order.

    Returns
    -------
    tuple[ConstructorDecl, ...]
        The constructors, each family's after those of every family its
        fields' axes reach.

    Raises
    ------
    FiniteAxisError
        If a field of a family's constructors indexes a tensor by a type
        that reaches the family itself.
    """
    declared = tuple(families)
    by_type = {family.type_constructor.id: family for family in declared}
    names = {family.id: family.name for family in declared}
    grouped: dict[FamilyId, list[ConstructorDecl]] = {}
    for constructor in constructors:
        grouped.setdefault(constructor.family, []).append(constructor)

    def reach(type_: AxisType, seen: dict[FamilyId, None]) -> None:
        """Record families reached by the finite type, in discovery order.

        Parameters
        ----------
        type_ : AxisType
            The type or index sort being enumerated.
        seen : dict[FamilyId, None]
            Receives each family once, including those in its fields.
        """
        if isinstance(type_, UserIndexSort):
            return
        components = product_components(type_)
        if components is not None:
            for component in components:
                reach(component, seen)
            return
        if isinstance(type_, (RecordType, VariantType)):
            for field in type_.row.fields:
                reach(field.type, seen)
            return
        if not isinstance(type_, TypeApplication):
            return
        family = by_type.get(type_.constructor.id)
        if family is None or family.id in seen:
            return
        seen[family.id] = None
        for constructor in grouped.get(family.id, ()):
            for field in constructor_field_types(family, constructor, type_):
                reach(field, seen)

    def dependencies(family: FamilyId) -> tuple[FamilyId, ...]:
        """Find the families a constructor's tensor axes enumerate.

        Parameters
        ----------
        family : FamilyId
            The owner of the constructors whose fields are inspected.

        Returns
        -------
        tuple[FamilyId, ...]
            The families reached from the owner's named axes.
        """
        seen: dict[FamilyId, None] = {}
        for constructor in grouped[family]:
            for field in constructor.fields:
                for shape in named_extents(field.type):
                    for dimension in shape.dimensions:
                        if isinstance(dimension, AxisExtent):
                            reach(dimension.axis, seen)
        return tuple(seen)

    ordered: list[ConstructorDecl] = []
    finished: set[FamilyId] = set()
    open_: set[FamilyId] = set()

    def visit(family: FamilyId) -> None:
        """Append a family's constructors after those of its axis dependencies.

        Parameters
        ----------
        family : FamilyId
            The family being ordered.

        Raises
        ------
        FiniteAxisError
            If a tensor axis dependency returns to an open family.
        """
        if family in finished:
            return
        if family in open_:
            raise FiniteAxisError(
                f"{names[family]} cannot index a tensor axis: "
                "a field of its constructors indexes a tensor by a type that "
                "reaches it, so its values are not finitely many"
            )
        open_.add(family)
        for dependency in dependencies(family):
            if dependency in grouped:
                visit(dependency)
        open_.discard(family)
        finished.add(family)
        ordered.extend(grouped[family])

    for family in tuple(grouped):
        visit(family)
    return tuple(ordered)

named_extents

named_extents(root: object) -> Iterator[ShapeIndex]

Every shape under a static term or kernel node that names an axis.

PARAMETER DESCRIPTION
root

A type, a static term, or any kernel node.

TYPE: object

YIELDS DESCRIPTION
ShapeIndex

Each shape with at least one named dimension, once per occurrence.

Source code in src/quivers/qiec/axes.py
def named_extents(root: object) -> Iterator[ShapeIndex]:
    """Every shape under a static term or kernel node that names an axis.

    Parameters
    ----------
    root : object
        A type, a static term, or any kernel node.

    Yields
    ------
    ShapeIndex
        Each shape with at least one named dimension, once per occurrence.
    """
    stack: list[object] = [root]
    while stack:
        node = stack.pop()
        if isinstance(node, tuple):
            stack.extend(node)
        elif isinstance(node, ShapeIndex):
            if named_dimensions(node.dimensions):
                yield node
            stack.extend(node.dimensions)
        elif isinstance(node, AxisExtent):
            stack.append(node.axis)
        elif isinstance(node, QiecModel):
            stack.extend(getattr(node, name) for name in type(node).__field_specs__)

check_axes

check_axes(root: object, registry: Declarations) -> None

Check every named shape under a term.

A named dimension must be the cardinality of a finite type. Axis order is not checked here: a type written in source is put in canonical order by the elaborator, while terms the elaborator builds may lay an intermediate out in another order before permuting it.

PARAMETER DESCRIPTION
root

A type or other static term.

TYPE: object

registry

The declarations in scope.

TYPE: Declarations

RAISES DESCRIPTION
FiniteAxisError

If an axis is not finite or its extent is not its cardinality.

Source code in src/quivers/qiec/axes.py
def check_axes(root: object, registry: Declarations) -> None:
    """Check every named shape under a term.

    A named dimension must be the cardinality of a finite type. Axis order
    is not checked here: a type written in source is put in canonical
    order by the elaborator, while terms the elaborator builds may lay an
    intermediate out in another order before permuting it.

    Parameters
    ----------
    root : object
        A type or other static term.
    registry : Declarations
        The declarations in scope.

    Raises
    ------
    FiniteAxisError
        If an axis is not finite or its extent is not its cardinality.
    """
    for shape in named_extents(root):
        for dimension in shape.dimensions:
            if isinstance(dimension, AxisExtent):
                check_axis_extent(dimension, registry)

check_axis_extent

check_axis_extent(extent: AxisExtent, registry: Declarations) -> None

Check that a named extent is its axis's cardinality.

PARAMETER DESCRIPTION
extent

A named dimension.

TYPE: AxisExtent

registry

The declarations in scope.

TYPE: KernelRegistry

RAISES DESCRIPTION
FiniteAxisError

If the axis is not finite, or the extent is not its cardinality.

Source code in src/quivers/qiec/axes.py
def check_axis_extent(extent: AxisExtent, registry: Declarations) -> None:
    """Check that a named extent is its axis's cardinality.

    Parameters
    ----------
    extent : AxisExtent
        A named dimension.
    registry : KernelRegistry
        The declarations in scope.

    Raises
    ------
    FiniteAxisError
        If the axis is not finite, or the extent is not its cardinality.
    """
    count = axis_cardinality(extent.axis, registry)
    if count != extent.value:
        raise FiniteAxisError(
            f"axis {render_axis(extent.axis)} has {count} elements, not the "
            f"claimed extent {extent.value}"
        )

canonical_dimensions

canonical_dimensions(dimensions: tuple[IndexTerm, ...]) -> tuple[IndexTerm, ...]

A tensor's dimensions in canonical axis order.

PARAMETER DESCRIPTION
dimensions

The dimensions as written.

TYPE: tuple[IndexTerm, ...]

RETURNS DESCRIPTION
tuple[IndexTerm, ...]

Named axes sorted by the rendering of their types (repeats of one type keep their written order), then positional axes in written order.

Source code in src/quivers/qiec/axes.py
def canonical_dimensions(dimensions: tuple[IndexTerm, ...]) -> tuple[IndexTerm, ...]:
    """A tensor's dimensions in canonical axis order.

    Parameters
    ----------
    dimensions : tuple[IndexTerm, ...]
        The dimensions as written.

    Returns
    -------
    tuple[IndexTerm, ...]
        Named axes sorted by the rendering of their types (repeats of one
        type keep their written order), then positional axes in written
        order.
    """
    return tuple(sorted(dimensions, key=_axis_key))

canonical_axis_order

canonical_axis_order(dimensions: tuple[IndexTerm, ...]) -> tuple[int, ...]

The source position of each axis in canonical order.

PARAMETER DESCRIPTION
dimensions

The dimensions as laid out.

TYPE: tuple[IndexTerm, ...]

RETURNS DESCRIPTION
tuple[int, ...]

For each canonical position, the position of the dimension that goes there; the identity when the layout is canonical.

Source code in src/quivers/qiec/axes.py
def canonical_axis_order(dimensions: tuple[IndexTerm, ...]) -> tuple[int, ...]:
    """The source position of each axis in canonical order.

    Parameters
    ----------
    dimensions : tuple[IndexTerm, ...]
        The dimensions as laid out.

    Returns
    -------
    tuple[int, ...]
        For each canonical position, the position of the dimension that
        goes there; the identity when the layout is canonical.
    """
    return tuple(
        sorted(
            range(len(dimensions)), key=lambda position: _axis_key(dimensions[position])
        )
    )

is_canonical

is_canonical(dimensions: tuple[IndexTerm, ...]) -> bool

Whether dimensions are in canonical axis order.

PARAMETER DESCRIPTION
dimensions

A tensor's dimensions.

TYPE: tuple[IndexTerm, ...]

RETURNS DESCRIPTION
bool

True when sorting them canonically leaves them unchanged.

Source code in src/quivers/qiec/axes.py
def is_canonical(dimensions: tuple[IndexTerm, ...]) -> bool:
    """Whether dimensions are in canonical axis order.

    Parameters
    ----------
    dimensions : tuple[IndexTerm, ...]
        A tensor's dimensions.

    Returns
    -------
    bool
        True when sorting them canonically leaves them unchanged.
    """
    return canonical_dimensions(dimensions) == dimensions

axis_name

axis_name(dimension: IndexTerm) -> str

The name of one dimension as data and targets spell it.

PARAMETER DESCRIPTION
dimension

A tensor dimension.

TYPE: IndexTerm

RETURNS DESCRIPTION
str

The name a named axis is written with, else the rendering of its type, or Fin n for a positional one.

Source code in src/quivers/qiec/axes.py
def axis_name(dimension: IndexTerm) -> str:
    """The name of one dimension as data and targets spell it.

    Parameters
    ----------
    dimension : IndexTerm
        A tensor dimension.

    Returns
    -------
    str
        The name a named axis is written with, else the rendering of its
        type, or ``Fin n`` for a positional one.
    """
    if isinstance(dimension, AxisExtent):
        if dimension.label is not None:
            return dimension.label
        return render_axis(dimension.axis)
    return f"Fin {render_static(dimension)}"

tensor_axes

tensor_axes(dimensions: tuple[IndexTerm, ...], registry: Declarations) -> tuple[TensorAxis, ...]

The axes of a tensor, with names and coordinate labels.

PARAMETER DESCRIPTION
dimensions

The tensor's dimensions, in canonical order.

TYPE: tuple[IndexTerm, ...]

registry

The declarations in scope.

TYPE: KernelRegistry

RETURNS DESCRIPTION
tuple[TensorAxis, ...]

One entry per dimension. A name that repeats within the tensor is suffixed #1, #2, ... by occurrence, so every axis has a distinct name.

Source code in src/quivers/qiec/axes.py
def tensor_axes(
    dimensions: tuple[IndexTerm, ...], registry: Declarations
) -> tuple[TensorAxis, ...]:
    """The axes of a tensor, with names and coordinate labels.

    Parameters
    ----------
    dimensions : tuple[IndexTerm, ...]
        The tensor's dimensions, in canonical order.
    registry : KernelRegistry
        The declarations in scope.

    Returns
    -------
    tuple[TensorAxis, ...]
        One entry per dimension. A name that repeats within the tensor is
        suffixed ``#1``, ``#2``, ... by occurrence, so every axis has a
        distinct name.
    """
    names = [axis_name(dimension) for dimension in dimensions]
    counts = {name: names.count(name) for name in names}
    seen: dict[str, int] = {}
    axes: list[TensorAxis] = []
    for name, dimension in zip(names, dimensions, strict=True):
        if counts[name] > 1:
            seen[name] = seen.get(name, 0) + 1
            name = f"{name}#{seen[name]}"
        if isinstance(dimension, AxisExtent):
            axes.append(
                TensorAxis(
                    name=name,
                    extent=int(dimension.value),
                    coordinates=tuple(
                        element.label
                        for element in axis_elements(dimension.axis, registry)
                    ),
                    named=True,
                )
            )
        elif isinstance(dimension, IndexLiteral) and isinstance(dimension.value, int):
            axes.append(
                TensorAxis(
                    name=name,
                    extent=dimension.value,
                    coordinates=tuple(
                        str(position) for position in range(dimension.value)
                    ),
                )
            )
        else:
            axes.append(TensorAxis(name=name, extent=None))
    return tuple(axes)

named_dimensions

named_dimensions(dimensions: tuple[IndexTerm, ...]) -> bool

Whether any dimension is named by a finite type.

PARAMETER DESCRIPTION
dimensions

A tensor's dimensions.

TYPE: tuple[IndexTerm, ...]

RETURNS DESCRIPTION
bool

True when one is an AxisExtent.

Source code in src/quivers/qiec/axes.py
def named_dimensions(dimensions: tuple[IndexTerm, ...]) -> bool:
    """Whether any dimension is named by a finite type.

    Parameters
    ----------
    dimensions : tuple[IndexTerm, ...]
        A tensor's dimensions.

    Returns
    -------
    bool
        True when one is an `AxisExtent`.
    """
    return any(isinstance(dimension, AxisExtent) for dimension in dimensions)

positional_dimension

positional_dimension(dimension: IndexTerm) -> IndexTerm

One dimension with its name forgotten.

PARAMETER DESCRIPTION
dimension

A dimension.

TYPE: IndexTerm

RETURNS DESCRIPTION
IndexTerm

The plain extent of a named dimension; any other dimension itself.

Source code in src/quivers/qiec/axes.py
def positional_dimension(dimension: IndexTerm) -> IndexTerm:
    """One dimension with its name forgotten.

    Parameters
    ----------
    dimension : IndexTerm
        A dimension.

    Returns
    -------
    IndexTerm
        The plain extent of a named dimension; any other dimension itself.
    """
    if isinstance(dimension, AxisExtent):
        return IndexLiteral(value=dimension.value, sort=NAT)
    return dimension

erase_axes

erase_axes(root: T) -> T

Forget every axis name in a kernel graph.

The compiled runtime and every transpile target read arrays in canonical order by position; this is the boundary where names stop.

PARAMETER DESCRIPTION
root

A module, or any kernel node.

TYPE: T

RETURNS DESCRIPTION
T

The graph with every named extent replaced by its plain extent; the root itself when it names no axis.

Source code in src/quivers/qiec/axes.py
def erase_axes[T](root: T) -> T:
    """Forget every axis name in a kernel graph.

    The compiled runtime and every transpile target read arrays in
    canonical order by position; this is the boundary where names stop.

    Parameters
    ----------
    root : T
        A module, or any kernel node.

    Returns
    -------
    T
        The graph with every named extent replaced by its plain extent;
        the root itself when it names no axis.
    """
    if isinstance(root, QiecModel):
        key = id(root)
        entry = _ERASED.get(key)
        if entry is not None and entry[0]() is root:
            return cast(T, entry[1])
        erased = _erase(root, {})

        def forget(
            reference: weakref.ref[QiecModel],
            key: int = key,
            cache: dict[int, tuple[weakref.ref[QiecModel], object]] = _ERASED,
        ) -> None:
            """Drop the entry of a collected root, unless already replaced.

            Parameters
            ----------
            reference : weakref.ref[QiecModel]
                The dead reference.
            key : int
                The identity it was stored under.
            cache : dict[int, tuple[weakref.ref[QiecModel], object]]
                The cache, bound when the entry is made, since module
                globals may already be gone at interpreter shutdown.
            """
            current = cache.get(key)
            if current is not None and current[0] is reference:
                del cache[key]

        _ERASED[key] = (weakref.ref(root, forget), erased)
        return cast(T, erased)
    return cast(T, _erase(root, {}))