Skip to content

Signatures

A signature is a many-sorted second-order binding signature: constructors over sorts, each argument with its own binding arity, and, for graph signatures, vertex and edge kinds (Fiore et al., 1999). An expression tree might have a constant constructor and an application constructor with two children. These objects carry the syntax declarations of the DSL at run time.

Variables are de Bruijn indices: a BoundVar(i) term carries an integer index into one index space shared by every sort, and a constructor argument that binds variables pushes a ContextEntry(var_sort=sort, embedding=tensor, type_term=term) per variable onto an implicit context Γ tracked by the encoder and decoder runtime. A bound variable may carry an annotation, an earlier labeled argument of the same constructor, stored alongside its embedding in Γ.

Terms are immutable values with structural equality. Two terms are equal exactly when their operators agree and their arguments agree position by position, recursively through nested subterms, data leaves, annotations, and de Bruijn indices. Hashing agrees with equality, so terms work as dictionary keys and set members. Data leaves compare by type as well as value: make_term("C", 1), make_term("C", 1.0), and make_term("C", True) are three distinct terms. A reconstruction check such as decoded == original thus holds only when the decoder recovered every part of the term. Arguments outside the TermArg union are rejected when the term is constructed.

signature

Signatures: typed multi-sorted second-order algebras.

A Signature is the runtime form of a syntax declaration. It carries the sort table, the constructor table, and, for graph-shaped signatures, the vertex and edge kind tables. Each argument of a constructor has a binding arity: the variables, of declared sorts, that are in scope in that argument and nowhere else. Let : Term, (x : Term).Term -> Term binds one variable in its second argument only.

Terms over a signature are first-class Python values (Term instances): each carries the constructor name and its positional arguments. Variables are de Bruijn indices: BoundVar(i) refers to the i-th enclosing bound variable, counting from the innermost. Bound variable names are display names, so alpha-equivalent terms are equal terms. The generated operations on terms (renaming, substitution, instantiation, free variables, equality, hashing, ordering, printing, and folds) are in quivers.structural.binding.

All structured value types in this module are didactic didactic.api.Model records, matching the quivers convention for schema-bearing data. Recursive term arguments and scope entries use opaque value fields to preserve nested storage. Runtime embeddings use opaque identity fields to preserve tensors and autograd. quivers._values.ValueModel includes these fields in equality, hashing, copying, and pickling.

SortVocabEntry didactic-model

SortVocabEntry(*, kind: Literal['string', 'integer', 'float'], value: DataLeaf)

Bases: Model

One closed-vocabulary entry on a data sort.

Each entry is a tagged Python value: kind is the leaf type ("string" | "integer" | "float"), value is the decoded Python value (str, int, or float).

PARAMETER DESCRIPTION
kind

The leaf type.

TYPE: str

value

The decoded value.

TYPE: DataLeaf

Sort didactic-model

Sort(*, name: str, kind: SortKind, dim: int | None = None, vocab: tuple[SortVocabEntry, ...] = ())

Bases: Model

A sort declaration: name, kind, optional dim, optional closed vocabulary.

A data sort may carry a vocab tuple of SortVocabEntry records. Object / index sorts must have an empty vocab (the framework checks at runtime).

PARAMETER DESCRIPTION
name

The sort's name.

TYPE: str

kind

"object", "index" or "data".

TYPE: SortKind

dim

The embedding dimension, if declared.

TYPE: int or None DEFAULT: None

vocab

The closed vocabulary of a data sort.

TYPE: tuple of SortVocabEntry DEFAULT: ()

vocab_values property

vocab_values: tuple[DataLeaf, ...]

The decoded Python values in declaration order.

RETURNS DESCRIPTION
tuple of DataLeaf

The values.

BoundVariable didactic-model

BoundVariable(*, name: str, sort: str, annotation: int | None = None)

Bases: Model

A variable an argument of a constructor binds.

The variable is in scope in exactly the argument that binds it. Its name is used for display only: terms refer to it by de Bruijn index, so two terms that differ only in the names of their bound variables are the same term.

annotation is the position of an unbound argument of the same constructor, before the binding argument, whose value annotates the variable (a type annotation, for instance). The encoder and decoder initialize the variable from it; substitution and equality ignore it.

PARAMETER DESCRIPTION
name

The display name.

TYPE: str

sort

The variable's sort, an object sort of the signature.

TYPE: str

annotation

The position of the annotating argument, if any.

TYPE: int or None DEFAULT: None

Constructor didactic-model

Constructor(*, name: str, domain: tuple[str, ...] = (), codomain: str = '', scopes: tuple[tuple[BoundVariable, ...], ...] = (), labels: tuple[str, ...] = ())

Bases: Model

A typed constructor symbol with a binding arity per argument.

A first-order constructor declares only domain. A constructor with binding also declares scopes, one tuple of bound variables per argument position, so Let : Term, (x : Term).Term -> Term has the scopes ((), (x,)): its second argument is in the scope of one new variable of sort Term and its first is not. The last variable of a scope is the innermost, de Bruijn index 0, inside the argument. This is the second-order binding signature of Fiore, Plotkin, and Turi.

PARAMETER DESCRIPTION
name

The constructor's name.

TYPE: str

domain

The sort of each argument, in order.

TYPE: tuple of str DEFAULT: ()

codomain

The sort it produces.

TYPE: str DEFAULT: ''

scopes

Empty, or the variables each argument binds, one entry per argument.

TYPE: tuple of tuple of BoundVariable DEFAULT: ()

labels

Empty, or a display label per argument, "" where none is given; an annotation names its argument by label in source.

TYPE: tuple of str DEFAULT: ()

RAISES DESCRIPTION
ValidationError

If scopes or labels do not have one entry per argument, or an annotation does not name an earlier unbound argument.

arity property

arity: int

The number of arguments the constructor takes.

RETURNS DESCRIPTION
int

The arity.

binding_arity property

binding_arity: tuple[int, ...]

How many variables each argument binds.

RETURNS DESCRIPTION
tuple of int

One count per argument, zero for an unbound argument.

binds_variables property

binds_variables: bool

Whether some argument binds a variable.

RETURNS DESCRIPTION
bool

True for a binding constructor.

bound_at

bound_at(position: int) -> tuple[BoundVariable, ...]

The variables an argument binds.

PARAMETER DESCRIPTION
position

The argument position.

TYPE: int

RETURNS DESCRIPTION
tuple of BoundVariable

Its scope, outermost first; empty for an unbound argument.

Source code in src/quivers/structural/signature.py
def bound_at(self, position: int) -> tuple[BoundVariable, ...]:
    """The variables an argument binds.

    Parameters
    ----------
    position : int
        The argument position.

    Returns
    -------
    tuple of BoundVariable
        Its scope, outermost first; empty for an unbound argument.
    """
    return self.scopes[position] if self.scopes else ()

arity_text

arity_text() -> str

The constructor's type as source writes it.

RETURNS DESCRIPTION
str

A, (x : S).B -> C, with a labeled argument as (label : A) and an annotation as x : S : label.

Source code in src/quivers/structural/signature.py
def arity_text(self) -> str:
    """The constructor's type as source writes it.

    Returns
    -------
    str
        ``A, (x : S).B -> C``, with a labeled argument as
        ``(label : A)`` and an annotation as ``x : S : label``.
    """
    parts: list[str] = []
    for position, sort in enumerate(self.domain):
        scope = self.bound_at(position)
        if scope:
            variables = ", ".join(
                f"{v.name} : {v.sort}"
                + (
                    f" : {self.label(v.annotation)}"
                    if v.annotation is not None
                    else ""
                )
                for v in scope
            )
            parts.append(f"({variables}).{sort}")
        elif self.label(position):
            parts.append(f"({self.label(position)} : {sort})")
        else:
            parts.append(sort)
    return f"{', '.join(parts)} -> {self.codomain}".lstrip()

label

label(position: int) -> str

The display label of an argument.

PARAMETER DESCRIPTION
position

The argument position.

TYPE: int

RETURNS DESCRIPTION
str

Its label, or "" when it has none.

Source code in src/quivers/structural/signature.py
def label(self, position: int) -> str:
    """The display label of an argument.

    Parameters
    ----------
    position : int
        The argument position.

    Returns
    -------
    str
        Its label, or ``""`` when it has none.
    """
    return self.labels[position] if self.labels else ""

VertexKind didactic-model

VertexKind(*, name: str, kind: SortKind, dim: int | None = None)

Bases: Model

A vertex kind in a graph-shaped signature.

PARAMETER DESCRIPTION
name

The kind's name.

TYPE: str

kind

The kind of its values.

TYPE: SortKind

dim

The embedding dimension, if declared.

TYPE: int or None DEFAULT: None

EdgeKind didactic-model

EdgeKind(*, name: str, src: str, tgt: str, directed: bool = True)

Bases: Model

An edge kind in a graph-shaped signature.

PARAMETER DESCRIPTION
name

The kind's name.

TYPE: str

src

The vertex kind it leaves.

TYPE: str

tgt

The vertex kind it enters.

TYPE: str

directed

Whether it is directed.

TYPE: bool DEFAULT: True

Signature didactic-model

Signature(*, name: str, params: tuple[str, ...] = (), sorts_t: tuple[Sort, ...] = (), constructors_t: tuple[Constructor, ...] = (), vertex_kinds_t: tuple[VertexKind, ...] = (), edge_kinds_t: tuple[EdgeKind, ...] = ())

Bases: Model

A multi-sorted second-order signature, or a graph signature.

Sort, constructor, vertex_kind and edge_kind tables are represented as tuples of records (rather than dicts) so the enclosing dx.Model keeps a schema-bearing layout. The runtime exposes name-keyed tables (sorts, constructors, ...) on top of those tuples, each built once per signature, and every lookup through them takes constant time. A constructor's arguments may bind variables (see Constructor), so one table holds both first-order and binding constructors.

PARAMETER DESCRIPTION
name

The signature's name.

TYPE: str

params

Its parameters.

TYPE: tuple of str DEFAULT: ()

sorts_t

Its sorts.

TYPE: tuple of Sort DEFAULT: ()

constructors_t

Its constructors.

TYPE: tuple of Constructor DEFAULT: ()

vertex_kinds_t

Its vertex kinds, for a graph signature.

TYPE: tuple of VertexKind DEFAULT: ()

edge_kinds_t

Its edge kinds, for a graph signature.

TYPE: tuple of EdgeKind DEFAULT: ()

sorts cached property

sorts: Mapping[str, Sort]

The sort declarations keyed by sort name.

RETURNS DESCRIPTION
Mapping[str, Sort]

A read-only table, built once.

constructors cached property

constructors: Mapping[str, Constructor]

The constructor declarations keyed by constructor name.

RETURNS DESCRIPTION
Mapping[str, Constructor]

A read-only table, built once.

vertex_kinds cached property

vertex_kinds: Mapping[str, VertexKind]

The graph vertex kinds keyed by kind name.

RETURNS DESCRIPTION
Mapping[str, VertexKind]

A read-only table, built once.

edge_kinds cached property

edge_kinds: Mapping[str, EdgeKind]

The graph edge kinds keyed by kind name.

RETURNS DESCRIPTION
Mapping[str, EdgeKind]

A read-only table, built once.

variable_sorts cached property

variable_sorts: tuple[str, ...]

The sorts some argument binds a variable of, in sort order.

RETURNS DESCRIPTION
tuple of str

The sorts that have variables; a term of any other sort is never a variable.

is_inductive

is_inductive() -> bool

Whether the signature declares any constructor.

RETURNS DESCRIPTION
bool

True when terms over the signature are inductive.

Source code in src/quivers/structural/signature.py
def is_inductive(self) -> bool:
    """Whether the signature declares any constructor.

    Returns
    -------
    bool
        ``True`` when terms over the signature are inductive.
    """
    return bool(self.constructors_t)

is_graph

is_graph() -> bool

Whether the signature declares both vertex and edge kinds.

RETURNS DESCRIPTION
bool

True when the signature is graph-shaped.

Source code in src/quivers/structural/signature.py
def is_graph(self) -> bool:
    """Whether the signature declares both vertex and edge kinds.

    Returns
    -------
    bool
        ``True`` when the signature is graph-shaped.
    """
    return bool(self.vertex_kinds_t) and bool(self.edge_kinds_t)

is_first_order

is_first_order() -> bool

Whether no constructor binds a variable.

RETURNS DESCRIPTION
bool

True when every argument of every constructor is unbound.

Source code in src/quivers/structural/signature.py
def is_first_order(self) -> bool:
    """Whether no constructor binds a variable.

    Returns
    -------
    bool
        ``True`` when every argument of every constructor is unbound.
    """
    return not any(c.binds_variables for c in self.constructors_t)

all_ops

all_ops() -> Iterable[str]

Iterate over every operation name of the signature.

YIELDS DESCRIPTION
str

Each constructor name in declaration order.

Source code in src/quivers/structural/signature.py
def all_ops(self) -> Iterable[str]:
    """Iterate over every operation name of the signature.

    Yields
    ------
    str
        Each constructor name in declaration order.
    """
    for c in self.constructors_t:
        yield c.name

constructor

constructor(op: str) -> Constructor

Return a constructor by name.

PARAMETER DESCRIPTION
op

The constructor name.

TYPE: str

RETURNS DESCRIPTION
Constructor

Its declaration.

RAISES DESCRIPTION
KeyError

If no constructor of that name is declared.

Source code in src/quivers/structural/signature.py
def constructor(self, op: str) -> Constructor:
    """Return a constructor by name.

    Parameters
    ----------
    op : str
        The constructor name.

    Returns
    -------
    Constructor
        Its declaration.

    Raises
    ------
    KeyError
        If no constructor of that name is declared.
    """
    constructor = self.constructors.get(op)
    if constructor is None:
        raise KeyError(f"signature {self.name!r}: op {op!r} is not a constructor")
    return constructor

codomain_of

codomain_of(op: str) -> str

Return the codomain sort of a constructor.

PARAMETER DESCRIPTION
op

The constructor name.

TYPE: str

RETURNS DESCRIPTION
str

The name of the sort the operation produces.

RAISES DESCRIPTION
KeyError

If op is not a constructor.

Source code in src/quivers/structural/signature.py
def codomain_of(self, op: str) -> str:
    """Return the codomain sort of a constructor.

    Parameters
    ----------
    op : str
        The constructor name.

    Returns
    -------
    str
        The name of the sort the operation produces.

    Raises
    ------
    KeyError
        If ``op`` is not a constructor.
    """
    return self.constructor(op).codomain

domain_of

domain_of(op: str) -> tuple[str, ...]

Return the positional argument sorts of a constructor.

PARAMETER DESCRIPTION
op

The constructor name.

TYPE: str

RETURNS DESCRIPTION
tuple[str, ...]

The sort of each positional argument.

RAISES DESCRIPTION
KeyError

If op is not a constructor.

Source code in src/quivers/structural/signature.py
def domain_of(self, op: str) -> tuple[str, ...]:
    """Return the positional argument sorts of a constructor.

    Parameters
    ----------
    op : str
        The constructor name.

    Returns
    -------
    tuple[str, ...]
        The sort of each positional argument.

    Raises
    ------
    KeyError
        If ``op`` is not a constructor.
    """
    return self.constructor(op).domain

binds_variables

binds_variables(op: str) -> bool

Whether some argument of a constructor binds a variable.

PARAMETER DESCRIPTION
op

The operation name.

TYPE: str

RETURNS DESCRIPTION
bool

True for a declared binding constructor.

Source code in src/quivers/structural/signature.py
def binds_variables(self, op: str) -> bool:
    """Whether some argument of a constructor binds a variable.

    Parameters
    ----------
    op : str
        The operation name.

    Returns
    -------
    bool
        ``True`` for a declared binding constructor.
    """
    constructor = self.constructors.get(op)
    return constructor is not None and constructor.binds_variables

sort_dim

sort_dim(sort: str) -> int | None

Return the declared embedding dimension of a sort or vertex kind.

PARAMETER DESCRIPTION
sort

The sort or vertex-kind name.

TYPE: str

RETURNS DESCRIPTION
int or None

The declared dimension, or None when the name is not declared or declares no dimension.

Source code in src/quivers/structural/signature.py
def sort_dim(self, sort: str) -> int | None:
    """Return the declared embedding dimension of a sort or vertex kind.

    Parameters
    ----------
    sort : str
        The sort or vertex-kind name.

    Returns
    -------
    int or None
        The declared dimension, or ``None`` when the name is not
        declared or declares no dimension.
    """
    declared = self.sorts.get(sort)
    if declared is not None:
        return declared.dim
    vertex = self.vertex_kinds.get(sort)
    if vertex is not None:
        return vertex.dim
    return None

Term didactic-model

Term(*, op: str, args: tuple = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

A closed term over a signature.

op is the constructor name, the binder name, or the framework-reserved "BoundVar" for a de-Bruijn variable reference.

args are positional children. Object positions carry a Term; data positions carry a DataLeaf raw value; index positions carry a non-negative int. args is held opaque (its element type is the open union TermArg, which didactic cannot encode because one of its arms is Term itself); construction checks that args is a tuple whose elements are Term or DataLeaf values, and the encoder / decoder enforce sort agreement at use time.

args compares by value, so equality and hashing are structural (see quivers._values.ValueModel): two terms are equal exactly when their operators agree and their arguments agree position by position, recursively, so terms that differ in a data leaf, a nested subterm, a binder, or a de-Bruijn index are distinct. Data leaves compare by type as well as value, so 1, 1.0, and True at the same position are three different terms. Both operations walk the term with an explicit stack, so deep terms (long Cons lists) do not exhaust the interpreter's recursion limit; a term's hash is computed once and cached, and copies and pickles keep args.

No wrapping such as Term("Data", …) is used at any position; raw values appear directly at data positions.

PARAMETER DESCRIPTION
op

The constructor, binder, or "BoundVar".

TYPE: str

args

The positional children.

TYPE: tuple of TermArg DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

to_tuple

to_tuple() -> tuple

A serialisable form matching the agenda's item-tuple convention: (op, *args_serialised). Children that are Terms are recursively serialised; data leaves and indices pass through.

RETURNS DESCRIPTION
tuple

The nested tuple (op, *args_serialised).

Source code in src/quivers/structural/signature.py
def to_tuple(self) -> tuple:
    """A serialisable form matching the agenda's item-tuple
    convention: ``(op, *args_serialised)``. Children that are
    `Term`s are recursively serialised; data leaves and
    indices pass through.

    Returns
    -------
    tuple
        The nested tuple ``(op, *args_serialised)``.
    """
    out: list = [self.op]
    for a in self.args:
        if isinstance(a, Term):
            out.append(a.to_tuple())
        else:
            out.append(a)
    return tuple(out)

ContextEntry didactic-model

ContextEntry(*, var_sort: str, embedding: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), type_term: Term | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

One scope entry on the binder stack.

embedding is a runtime tensor; type_term is the binder's annotation term captured at scope-extension time. Tensor identity participates in equality and hashing, preserving live autograd state.

PARAMETER DESCRIPTION
var_sort

The sort of the bound variable.

TYPE: str

embedding

Its embedding.

TYPE: Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

type_term

The binder's annotation of it, if any.

TYPE: Term or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

Context didactic-model

Context(*, entries: tuple[ContextEntry, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

The de-Bruijn scope context threaded through encoder and decoder runtimes.

Position 0 is the most recently bound variable; lookup var(i) returns the i-th entry from the top.

PARAMETER DESCRIPTION
entries

The entries, innermost first.

TYPE: tuple of ContextEntry DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

push

push(var_sort: str, embedding: Tensor, type_term: Term | None = None) -> 'Context'

Return the context extended by one innermost bound variable.

PARAMETER DESCRIPTION
var_sort

The sort of the new variable.

TYPE: str

embedding

The variable's embedding.

TYPE: Tensor

type_term

The binder's annotation term for the variable, if any.

TYPE: Term or None DEFAULT: None

RETURNS DESCRIPTION
Context

A new context whose index 0 is the new variable; self is unchanged.

Source code in src/quivers/structural/signature.py
def push(
    self,
    var_sort: str,
    embedding: torch.Tensor,
    type_term: Term | None = None,
) -> "Context":
    """Return the context extended by one innermost bound variable.

    Parameters
    ----------
    var_sort : str
        The sort of the new variable.
    embedding : torch.Tensor
        The variable's embedding.
    type_term : Term or None
        The binder's annotation term for the variable, if any.

    Returns
    -------
    Context
        A new context whose index 0 is the new variable; ``self``
        is unchanged.
    """
    return Context(
        entries=(
            ContextEntry(
                var_sort=var_sort,
                embedding=embedding,
                type_term=type_term,
            ),
        )
        + self.entries,
    )

var

var(index: int) -> Tensor

Return the embedding of a bound variable.

PARAMETER DESCRIPTION
index

The de-Bruijn index, counted from the innermost variable.

TYPE: int

RETURNS DESCRIPTION
Tensor

The variable's embedding.

RAISES DESCRIPTION
IndexError

If index is negative or not below the context depth.

Source code in src/quivers/structural/signature.py
def var(self, index: int) -> torch.Tensor:
    """Return the embedding of a bound variable.

    Parameters
    ----------
    index : int
        The de-Bruijn index, counted from the innermost variable.

    Returns
    -------
    torch.Tensor
        The variable's embedding.

    Raises
    ------
    IndexError
        If ``index`` is negative or not below the context depth.
    """
    if index < 0 or index >= len(self.entries):
        raise IndexError(
            f"Context.var({index}): out of range "
            f"(context depth {len(self.entries)})"
        )
    return self.entries[index].embedding

type_of

type_of(index: int) -> Term | None

Return the annotation term of a bound variable.

PARAMETER DESCRIPTION
index

The de-Bruijn index, counted from the innermost variable.

TYPE: int

RETURNS DESCRIPTION
Term or None

The annotation captured when the variable was bound, or None when it carries none.

Source code in src/quivers/structural/signature.py
def type_of(self, index: int) -> Term | None:
    """Return the annotation term of a bound variable.

    Parameters
    ----------
    index : int
        The de-Bruijn index, counted from the innermost variable.

    Returns
    -------
    Term or None
        The annotation captured when the variable was bound, or
        ``None`` when it carries none.
    """
    return self.entries[index].type_term

depth

depth() -> int

Return the number of variables in scope.

RETURNS DESCRIPTION
int

The context depth.

Source code in src/quivers/structural/signature.py
def depth(self) -> int:
    """Return the number of variables in scope.

    Returns
    -------
    int
        The context depth.
    """
    return len(self.entries)

by_sort

by_sort(sort: str) -> list[tuple[int, ContextEntry]]

All entries whose var_sort matches; returned as (depth-index, entry) pairs for the decoder's categorical-over-in-scope-variables.

PARAMETER DESCRIPTION
sort

The variable sort to select.

TYPE: str

RETURNS DESCRIPTION
list[tuple[int, ContextEntry]]

The matching entries with their de-Bruijn indices, innermost first.

Source code in src/quivers/structural/signature.py
def by_sort(self, sort: str) -> list[tuple[int, ContextEntry]]:
    """All entries whose ``var_sort`` matches; returned as
    ``(depth-index, entry)`` pairs for the decoder's
    categorical-over-in-scope-variables.

    Parameters
    ----------
    sort : str
        The variable sort to select.

    Returns
    -------
    list[tuple[int, ContextEntry]]
        The matching entries with their de-Bruijn indices, innermost
        first.
    """
    return [(i, e) for i, e in enumerate(self.entries) if e.var_sort == sort]

SubstitutionError

Bases: ValueError

A substitution cannot be applied to a term.

Substitution didactic-model

Substitution(*, replacements: tuple[Term, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), shift: int = 0)

Bases: ValueModel

A simultaneous substitution of the free variables of de-Bruijn terms.

The variable with index i becomes replacements[i] when i is below their number n, and the variable i - n + shift otherwise. Every substitution of terms in a context of n + k variables by terms in a context of shift + k variables has this form. A renaming is a substitution whose replacements are variables.

PARAMETER DESCRIPTION
replacements

The replacements of the innermost variables.

TYPE: tuple of Term DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

shift

Where the remaining variables go; at least zero.

TYPE: int DEFAULT: 0

RAISES DESCRIPTION
ValidationError

If the shift is negative.

weakening classmethod

weakening(amount: int) -> Substitution

The renaming that makes room for new innermost variables.

PARAMETER DESCRIPTION
amount

How many variables are added.

TYPE: int

RETURNS DESCRIPTION
Substitution

The variable i goes to i + amount.

Source code in src/quivers/structural/signature.py
@classmethod
def weakening(cls, amount: int) -> Substitution:
    """The renaming that makes room for new innermost variables.

    Parameters
    ----------
    amount : int
        How many variables are added.

    Returns
    -------
    Substitution
        The variable ``i`` goes to ``i + amount``.
    """
    return cls(shift=amount)

renaming classmethod

renaming(targets: tuple[int, ...], shift: int) -> Substitution

The renaming that sends variable i to targets[i].

PARAMETER DESCRIPTION
targets

The new index of each of the innermost variables.

TYPE: tuple of int

shift

Where the remaining variables go.

TYPE: int

RETURNS DESCRIPTION
Substitution

The renaming.

Source code in src/quivers/structural/signature.py
@classmethod
def renaming(cls, targets: tuple[int, ...], shift: int) -> Substitution:
    """The renaming that sends variable ``i`` to ``targets[i]``.

    Parameters
    ----------
    targets : tuple of int
        The new index of each of the innermost variables.
    shift : int
        Where the remaining variables go.

    Returns
    -------
    Substitution
        The renaming.
    """
    return cls(replacements=tuple(bound_var(i) for i in targets), shift=shift)

image

image(index: int) -> Term

The replacement of one variable.

PARAMETER DESCRIPTION
index

The variable.

TYPE: int

RETURNS DESCRIPTION
Term

Its replacement.

Source code in src/quivers/structural/signature.py
def image(self, index: int) -> Term:
    """The replacement of one variable.

    Parameters
    ----------
    index : int
        The variable.

    Returns
    -------
    Term
        Its replacement.
    """
    if index < len(self.replacements):
        return self.replacements[index]
    return bound_var(index - len(self.replacements) + self.shift)

lift

lift(count: int, signature: Signature) -> Substitution

The substitution under count new innermost variables.

PARAMETER DESCRIPTION
count

The variables a binder introduces.

TYPE: int

signature

The signature of the terms.

TYPE: Signature

RETURNS DESCRIPTION
Substitution

The new variables go to themselves, and the replacements are weakened past them.

Source code in src/quivers/structural/signature.py
def lift(self, count: int, signature: Signature) -> Substitution:
    """The substitution under ``count`` new innermost variables.

    Parameters
    ----------
    count : int
        The variables a binder introduces.
    signature : Signature
        The signature of the terms.

    Returns
    -------
    Substitution
        The new variables go to themselves, and the replacements are
        weakened past them.
    """
    if count == 0:
        return self
    weaken = Substitution.weakening(count)
    return Substitution(
        replacements=(
            *(bound_var(i) for i in range(count)),
            *(substitute(item, weaken, signature) for item in self.replacements),
        ),
        shift=self.shift + count,
    )

then

then(other: Substitution, signature: Signature) -> Substitution

The substitution that applies this one and then another.

PARAMETER DESCRIPTION
other

The substitution applied second.

TYPE: Substitution

signature

The signature of the terms.

TYPE: Signature

RETURNS DESCRIPTION
Substitution

substitute(t, self.then(other)) == substitute(substitute(t, self), other) for every term t.

Source code in src/quivers/structural/signature.py
def then(self, other: Substitution, signature: Signature) -> Substitution:
    """The substitution that applies this one and then another.

    Parameters
    ----------
    other : Substitution
        The substitution applied second.
    signature : Signature
        The signature of the terms.

    Returns
    -------
    Substitution
        ``substitute(t, self.then(other)) == substitute(substitute(t,
        self), other)`` for every term ``t``.
    """
    first = tuple(substitute(item, other, signature) for item in self.replacements)
    count = len(other.replacements)
    extra = other.replacements[self.shift :] if self.shift < count else ()
    return Substitution(
        replacements=(*first, *extra),
        shift=other.shift + max(0, self.shift - count),
    )

bound_var

bound_var(index: int) -> Term

A de-Bruijn variable reference.

PARAMETER DESCRIPTION
index

The de-Bruijn index: 0 refers to the innermost bound variable.

TYPE: int

RETURNS DESCRIPTION
Term

The term BoundVar(index).

RAISES DESCRIPTION
TypeError

If index is not a non-negative int.

Source code in src/quivers/structural/signature.py
def bound_var(index: int) -> Term:
    """A de-Bruijn variable reference.

    Parameters
    ----------
    index : int
        The de-Bruijn index: 0 refers to the innermost bound variable.

    Returns
    -------
    Term
        The term ``BoundVar(index)``.

    Raises
    ------
    TypeError
        If ``index`` is not a non-negative ``int``.
    """
    if not isinstance(index, int) or index < 0:
        raise TypeError(f"bound_var requires a non-negative int, got {index!r}")
    return Term(op="BoundVar", args=(index,))

make_term

make_term(op: str, *args) -> Term

Construct a term over a signature.

Each arg must be a Term, a DataLeaf raw value, or a non-negative int (for index-sorted positions). The encoder / decoder runtime validate sort agreement at use time.

PARAMETER DESCRIPTION
op

The constructor or binder name.

TYPE: str

*args

The positional children.

TYPE: TermArg DEFAULT: ()

RETURNS DESCRIPTION
Term

The term op(*args).

RAISES DESCRIPTION
TypeError

If op is not a string.

ValidationError

If an argument is neither a Term nor a DataLeaf.

Source code in src/quivers/structural/signature.py
def make_term(op: str, *args) -> Term:
    """Construct a term over a signature.

    Each ``arg`` must be a `Term`, a `DataLeaf` raw
    value, or a non-negative int (for index-sorted positions). The
    encoder / decoder runtime validate sort agreement at use
    time.

    Parameters
    ----------
    op : str
        The constructor or binder name.
    *args : TermArg
        The positional children.

    Returns
    -------
    Term
        The term ``op(*args)``.

    Raises
    ------
    TypeError
        If ``op`` is not a string.
    didactic.api.ValidationError
        If an argument is neither a `Term` nor a `DataLeaf`.
    """
    if not isinstance(op, str):
        raise TypeError(f"make_term requires a string op, got {type(op).__name__}")
    return Term(op=op, args=tuple(args))

substitute

substitute(term: Term, substitution: Substitution, signature: Signature) -> Term

Apply a substitution to the free variables of a term.

It goes under binders by lifting the substitution, so a replacement is never captured. An argument at an index-sorted position names a variable and may only be renamed. The cost is the size of the term times the cost of weakening each replacement used under binders; the traversal uses an explicit stack.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

substitution

The substitution.

TYPE: Substitution

signature

The signature of the term.

TYPE: Signature

RETURNS DESCRIPTION
Term

The substituted term.

RAISES DESCRIPTION
SubstitutionError

If an operation is undeclared, an index position would receive a term that is not a variable, or an argument's kind does not match its position.

Source code in src/quivers/structural/signature.py
def substitute(term: Term, substitution: Substitution, signature: Signature) -> Term:
    """Apply a substitution to the free variables of a term.

    It goes under binders by lifting the substitution, so a replacement is
    never captured. An argument at an index-sorted position names a
    variable and may only be renamed. The cost is the size of the term
    times the cost of weakening each replacement used under binders; the
    traversal uses an explicit stack.

    Parameters
    ----------
    term : Term
        The term.
    substitution : Substitution
        The substitution.
    signature : Signature
        The signature of the term.

    Returns
    -------
    Term
        The substituted term.

    Raises
    ------
    SubstitutionError
        If an operation is undeclared, an index position would receive a
        term that is not a variable, or an argument's kind does not match
        its position.
    """
    frames: list[tuple[Term, Substitution, tuple[tuple[str, int], ...]]] = []
    built: list[list[TermArg]] = []
    result: Term | None = None

    def deliver(value: Term) -> Term | None:
        """Hand a finished subterm to its parent, or return it at the root.

        Parameters
        ----------
        value : Term
            The finished subterm.

        Returns
        -------
        Term or None
            The value when it is the root, else ``None``.
        """
        if built:
            built[-1].append(value)
            return None
        return value

    def enter(node: Term, sigma: Substitution) -> Term | None:
        """Start a subterm, or finish it at once when it is a variable.

        Parameters
        ----------
        node : Term
            The subterm.
        sigma : Substitution
            The substitution in its scope.

        Returns
        -------
        Term or None
            The root's result when the root is a variable.

        Raises
        ------
        SubstitutionError
            If the operation is undeclared or has the wrong arity.
        """
        if node.op == "BoundVar":
            index = node.args[0]
            assert isinstance(index, int)
            return deliver(sigma.image(index))
        scopes = _scopes(signature, node.op)
        if len(scopes) != len(node.args):
            raise SubstitutionError(
                f"{node.op!r} takes {len(scopes)} arguments, got {len(node.args)}"
            )
        frames.append((node, sigma, scopes))
        built.append([])
        return None

    result = enter(term, substitution)
    while frames:
        node, sigma, scopes = frames[-1]
        position = len(built[-1])
        if position == len(node.args):
            frames.pop()
            arguments = tuple(built.pop())
            result = deliver(Term(op=node.op, args=arguments))
            continue
        sort, count = scopes[position]
        argument = node.args[position]
        inner = sigma.lift(count, signature)
        if isinstance(argument, Term):
            result = enter(argument, inner)
            continue
        declared = signature.sorts.get(sort)
        if declared is not None and declared.kind == "index":
            assert isinstance(argument, int)
            image = inner.image(argument)
            if image.op != "BoundVar":
                raise SubstitutionError(
                    f"index position of {node.op!r} would receive a term that "
                    "is not a variable"
                )
            built[-1].append(image.args[0])
        else:
            built[-1].append(argument)
    assert result is not None
    return result

free_indices

free_indices(term: Term, signature: Signature) -> frozenset[int]

The free variables of a term.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

signature

Its signature.

TYPE: Signature

RETURNS DESCRIPTION
frozenset of int

The indices of its free variables in its context.

RAISES DESCRIPTION
SubstitutionError

If an operation is undeclared.

Source code in src/quivers/structural/signature.py
def free_indices(term: Term, signature: Signature) -> frozenset[int]:
    """The free variables of a term.

    Parameters
    ----------
    term : Term
        The term.
    signature : Signature
        Its signature.

    Returns
    -------
    frozenset of int
        The indices of its free variables in its context.

    Raises
    ------
    SubstitutionError
        If an operation is undeclared.
    """
    found: set[int] = set()
    stack: list[tuple[Term, int]] = [(term, 0)]
    while stack:
        node, depth = stack.pop()
        if node.op == "BoundVar":
            index = node.args[0]
            assert isinstance(index, int)
            if index >= depth:
                found.add(index - depth)
            continue
        for (sort, count), argument in zip(
            _scopes(signature, node.op), node.args, strict=True
        ):
            if isinstance(argument, Term):
                stack.append((argument, depth + count))
            elif (
                signature.sorts.get(sort) is not None
                and signature.sorts[sort].kind == "index"
            ):
                assert isinstance(argument, int)
                if argument >= depth + count:
                    found.add(argument - depth - count)
    return frozenset(found)

Type aliases and constants

Structural compression: signatures, encoders, decoders, losses.

Runtime substrate for QVR signatures, encoders, decoders, and attached losses: second-order binding signatures with their generated term operations, and a uniform algebraic interface for compressing structured objects to fixed-length vectors and decoding them under a learned distribution.

EMPTY_CONTEXT module-attribute

EMPTY_CONTEXT = Context()

The context with no bound variables.

DataLeaf

DataLeaf = str | int | float | bytes | bool

A raw value at a data-sorted argument position of a Term.

Values outside this union are rejected at runtime with a typed error rather than coerced.

TermArg

TermArg = Term | DataLeaf | int

A positional argument of a Term: a subterm at an object position, a DataLeaf at a data position, or an int at an index position.

SortKind

SortKind = Literal['object', 'index', 'data']

The kinds of sort a Signature can declare.

Cited sources

Marcelo Fiore, Gordon Plotkin, and Daniele Turi. Abstract Syntax and Variable Binding. In Proceedings of the 14th Symposium on Logic in Computer Science (LICS), 193–202. IEEE Computer Society, 1999. doi:10.1109/LICS.1999.782615.