qewton.config package

Module contents

Config Submodule

Describes the data passed between nodes: its axes, their sizes and its dtype. Graphs match these descriptions when ports are connected, so mismatches are found while building and sizes are inferred from the connected data.

DataConfiguration(BatchAxes(...), GeometryAxes(grid), FeatureAxes(Variable("f", 1)))

describes a batch of fields f on the points of grid.

Configurations and axes

  • DataConfiguration: a sequence of axes plus dtype and element_dtype; at most one FeatureAxes.

  • Axes: BatchAxes (samples), GeometryAxes (points of a Geometry), FeatureAxes (values, named by Variables), EllipsisAxes (any sequence of axes, possibly none).

  • Dims: AxesDim(size) with size an int, None (unknown) or a HyperParameter; EllipsisDim for any sequence of dims.

Matching

Declared configurations never change. A Matching holds what matching finds, e.g. for one graph:

  • matching.place(key, {port: declaration}) instantiates declarations at a place: open objects (unknown dims, ellipses and what contains them) get a stand-in there, every other object is used as it is;

  • config.merge(other) (or matching.merge(a, b) for axes and dims) makes both describe the same data: corresponding axes and dims become one group, an ellipsis is bound to the part it stands for, the dtypes are merged;

  • config.resolve() gives the configuration as known so far: every object replaced by the representative of its group, equal axes as one object.

Configurations of a matching are DynamicDataConfigurations (a DataConfiguration with its matching): only they have merge, merge_dim, resolve and the shape operations, and the results of those belong to the same matching. A contradiction raises DataConfigMismatchError, naming the ports the conflicting values come from. Graphs match along their edges (see qewton.graphs).

Relations of nodes

A node relates its ports in the annotations of forward: one object used in several annotations is the same at every place of the node.

ellipsis = EllipsisAxes()

def forward(self, x: Number[TensorType, DataConfiguration(ellipsis)]
            ) -> Number[TensorType, DataConfiguration(ellipsis)]:

A node that changes dims by their index also implements relate, built from the shape operations of the DynamicDataConfigurations it gets: drop, squeeze, set_size, unsqueeze, permute, flatten, unflatten, reshape, concat, split, broadcast, window.

def relate(self, inp: DataConfiguration) -> DataConfiguration:
    return inp.flatten(self.start_dim, self.end_dim)

They reuse the input’s objects and compute sizes with operation dims (AddedDim, ProductDim, SequenceProductDim, WindowDim, BroadcastDim, …), which solve for an operand where the answer is unique. broadcast makes size 1 and N compatible without merging them.

HyperParameters in configurations

A size that fixes how a node is built is a HyperParameter; the dims of that size are bound to it with AxesDim(hp) and follow its value. HyperParameter.size_from(x, name) takes a given size, or None for one that is inferred from the connected data (HyperParameter.inferred). An inferred size is the same at all places of the node; places that disagree raise at connecting. Arithmetic on HyperParameters (hp * 2) gives a HyperParameterOperation, which is read but not inferred.

Sizes of data sources

The outputs of a DataLoader or PointSampler share one batch axes, bound to its batch_size or n_points. Changing them, or switching a sampler to mesh mode or an active discretization, changes every dim behind it without matching. The size at run time is not checked.

dtypes

dtype is Any, a Python type, TensorType, the tensor class of a backend, or a union of these; element_dtype is open, Number or a marker such as Float32 or Complex64, given in annotations as Complex64[TensorType, config]. Two dtypes match if they have a common member; the more special one is kept.

Saving

Static configurations are saved with their dtypes; matched configurations are rebuilt when the loaded graph is matched.

See REQUIREMENTS.md and DECISIONS.md.

Subpackages

Submodules

qewton.config.axes module

class qewton.config.axes.Axes(*shape: int | AxesDim | None | EllipsisType)[source]

Bases: Serializable

Represents a collection of axes (dimensions) for data, including their sizes and types.

An Axes of this base class is an axes of unknown kind; matching it with a BatchAxes, GeometryAxes or FeatureAxes gives that kind. An axes is a declaration: matching (see Matching) never changes it.

is_ellipsis = False

Whether this stands for a sequence of axes (an ellipsis).

kind_known = False

Whether the kind of this axes (batch, geometry, features) is known.

parameters: tuple = ()

HyperParameters bound to this object; axes have none of their own.

property is_open: bool

Whether this axes can become more concrete at a place of a graph (see Matching): its kind, its content (e.g. a Variable) or one of its dims is not known yet.

property parts: tuple

The dims of this axes.

with_parts(parts: tuple) → Axes[source]

A new axes like this one with the dims parts, e.g. the stand-in of this axes at a place.

depends_on(sizes) → tuple[source]

The items whose sizes this object is computed from; none for an axes.

size_in(sizes) → None[source]

An axes has no size of its own; its dims have.

static new_unknown() → Axes[source]

A new axes of unknown kind with one unknown dim.

kind_compatible(other: Axes) → bool[source]

Whether this axes and other can be of one kind.

contents_agree(other: Axes) → bool[source]

Whether the contents (e.g. Variables) of this axes and other agree; axes of different kinds (one of them unknown) have nothing to compare.

more_concrete_than(other: Axes) → bool[source]

Whether this axes says more than other: a known kind, then a Variable or a geometry.

with_dims(dims) → Axes[source]

New axes of the same kind with dims, e.g. after an operation removed or changed one of them.

property shape

Returns the tuple of AxesDim objects representing the shape.

property is_empty

Checks if the axes collection is empty.

Returns:

True if the shape has no dimensions, False otherwise.

Return type:

bool

add_dim(new_dim, index)[source]

Adds a new dimension to the axes at a specific index.

Parameters:
  • new_dim (AxesDim) – The dimension to add.

  • index (int) – The index at which to add the dimension.

matches(other: Axes) → bool[source]

Checks if these axes exactly match another Axes object in terms of number of dimensions, type, and size.

Parameters:

other (Axes) – The other Axes object to compare with.

Returns:

True if the axes match, False otherwise.

Return type:

bool

class qewton.config.axes.BatchAxes(*shape: int | AxesDim | None | EllipsisType)[source]

Bases: Axes

Represents batch-specific axes, inheriting from Axes.

This class can be used to explicitly denote dimensions that correspond to batch size.

kind_known = True

Whether the kind of this axes (batch, geometry, features) is known.

class qewton.config.axes.GeometryAxes(geometry=None, shape: tuple[int | AxesDim, ...] | None = None)[source]

Bases: Axes

Represents geometry-specific axes, typically used for spatial dimensions.

It encapsulates a Geometry object to manage the underlying geometric shape, which can also be used for plotting etc.

kind_known = True

Whether the kind of this axes (batch, geometry, features) is known.

property geometry

Returns the encapsulated Geometry object.

Returns:

The geometry associated with these axes.

Return type:

Geometry

property variables
with_dims(dims) → GeometryAxes[source]

New axes of the same kind with dims, e.g. after an operation removed or changed one of them.

split(variables: list[Variable]) → list[GeometryAxes][source]

Split the axes of a product geometry into axes of its factors.

Every factor whose variable is in variables gets axes of its own; each run of adjacent other factors stays together as their product. The tensor axes keep their order (the first factor varies slowest), so data described by these axes is reshaped, not reordered.

Parameters:

variables – Variables of factors of the geometry.

Returns:

In the order of the factors; together they

have as many elements as these axes.

Return type:

list of GeometryAxes

Raises:

ValueError – If the geometry is no product, a variable is no factor of it, or the factors do not span these axes.

class qewton.config.axes.FeatureAxes(variable: Variable | None = None, shape: tuple[int | AxesDim, ...] | None = None)[source]

Bases: Axes

Represents feature-specific axes, often associated with a Variable object that defines the features.

kind_known = True

Whether the kind of this axes (batch, geometry, features) is known.

property variables

Returns the encapsulated Variable object, or a new empty Variable if none was set.

with_dims(dims) → FeatureAxes[source]

New axes of the same kind with dims, e.g. after an operation removed or changed one of them.

get_variable_slice(variable)[source]

Retrieves a slice corresponding to a specific variable from the encapsulated Variable object.

Parameters:

variable – The variable for which to get the slice.

Returns:

The slice corresponding to the variable.

Return type:

Any

class qewton.config.axes.EllipsisAxes[source]

Bases: Axes

Represents an ellipsis in axes, indicating a flexible number of dimensions.

An ellipsis stands for a sequence of axes, possibly empty; matching binds it to one at every place (see Matching).

is_ellipsis = True

Whether this stands for a sequence of axes (an ellipsis).

property is_open: bool

Whether this axes can become more concrete at a place of a graph (see Matching): its kind, its content (e.g. a Variable) or one of its dims is not known yet.

class qewton.config.axes.AxesDim(size=None, broadcastable=True)[source]

Bases: Serializable

Represents a single dimension within a set of axes, with an optional size and broadcastability.

A dim is a declaration: matching (see Matching) never changes it. A dim of unknown size is open: at every place of a graph it stands for its own unknown.

A dim may be bound to a HyperParameter, AxesDim(node.in_neurons): its size is the current value of the HyperParameter, also after it changed (e.g. a batch size). It is the same at every place; an open HyperParameter (state INFERRED, value None) is inferred by matching.

parameters

The HyperParameters this dim is bound to.

Type:

tuple[HyperParameter, …]

is_ellipsis = False

Whether this stands for a sequence of dims (an ellipsis).

is_relation = False

Whether the size is computed from other dims (an operation dim).

parameters: tuple = ()
update_size(new_size)[source]

Updates the size of this dimension.

Parameters:

new_size (int | None) – The new size for the dimension.

property size

the value of a bound HyperParameter, else the given number; None if unknown.

Type:

The declared size

property is_open: bool

it has no size and is bound to no HyperParameter.

Type:

Whether this dim can have another size at every place

property parts: tuple

The dims this one is computed from; none for a plain dim.

with_parts(parts: tuple) → AxesDim[source]

A new dim like this one computed from parts, e.g. the stand-in of this dim at a place.

size_in(sizes) → int | None[source]

The size of this dim where the sizes of other dims are given by sizes (DeclaredSizes or a matching): the declared one.

static new_unknown() → AxesDim[source]

A new dim of unknown size.

depends_on(sizes) → tuple[source]

The items whose sizes this dim is computed from, as expanded by sizes; none for a plain dim.

solve(size: int, sizes) → list[tuple[AxesDim, int]][source]

The sizes of unknown dims this one is computed from such that it is size, where the answer is unique: (dim, size) pairs, possibly none.

class qewton.config.axes.DeclaredSizes[source]

Bases: object

Sizes and sequences as declared: what operation dims are computed from outside of a matching. A Matching answers the same questions with what it found.

static size(dim: AxesDim) → int | None[source]

The declared size of dim.

static expand(items) → list[source]

items as declared.

class qewton.config.axes.OperationDim(*args, **kwargs)[source]

Bases: AxesDim

A dimension whose size is computed from other dimensions (its operands), e.g. a sum. It is a relation: compute() and solve() evaluate it with given sizes, as declared or as known to a matching.

is_relation = True

Whether the size is computed from other dims (an operation dim).

property operands: tuple[AxesDim, ...]
property parts: tuple

The dims this one is computed from; none for a plain dim.

with_parts(parts: tuple) → OperationDim[source]

A new dim like this one computed from parts, e.g. the stand-in of this dim at a place.

property is_open: bool

it has no size and is bound to no HyperParameter.

Type:

Whether this dim can have another size at every place

property size

The size computed from the declared sizes of the operands.

size_in(sizes) → int | None[source]

The size of this dim where the sizes of other dims are given by sizes (DeclaredSizes or a matching): the declared one.

depends_on(sizes) → tuple[source]

The items whose sizes this dim is computed from, as expanded by sizes; none for a plain dim.

compute(sizes) → int | None[source]

The size from the sizes of the operands given by sizes (an object with size(dim) and expand(items): DeclaredSizes or a matching); None while one is unknown.

class qewton.config.axes.AddedDim(*args, **kwargs)[source]

Bases: OperationDim

A dimension whose size is the sum of two other dimensions.

solve(size: int, sizes) → list[tuple[AxesDim, int]][source]

The sizes of unknown dims this one is computed from such that it is size, where the answer is unique: (dim, size) pairs, possibly none.

class qewton.config.axes.SubDim(*args, **kwargs)[source]

Bases: OperationDim

A dimension whose size is the difference of two other dimensions.

solve(size: int, sizes) → list[tuple[AxesDim, int]][source]

The sizes of unknown dims this one is computed from such that it is size, where the answer is unique: (dim, size) pairs, possibly none.

class qewton.config.axes.ProductDim(*args, **kwargs)[source]

Bases: OperationDim

A dimension whose size is the product of two other dimensions.

solve(size: int, sizes) → list[tuple[AxesDim, int]][source]

The sizes of unknown dims this one is computed from such that it is size, where the answer is unique: (dim, size) pairs, possibly none.

class qewton.config.axes.DivideDim(*args, **kwargs)[source]

Bases: OperationDim

A dimension whose size is the first of two dimensions divided by the second, rounded down.

class qewton.config.axes.MinimumDim(*args, **kwargs)[source]

Bases: OperationDim

A dimension whose size is the minimum of two other dimensions.

class qewton.config.axes.SequenceProductDim(*args, **kwargs)[source]

Bases: OperationDim

A dimension whose size is the product of the sizes of a sequence of axes and dims, e.g. the dims merged by flattening. The sequence may hold an ellipsis; the size is known once the ellipsis is bound and every size in it is known.

property operands: tuple
with_parts(parts: tuple) → SequenceProductDim[source]

A new dim like this one computed from parts, e.g. the stand-in of this dim at a place.

depends_on(sizes) → tuple[source]

The ellipses and dims of the sequence: its size changes when an ellipsis is bound or a size becomes known.

dims(sizes) → list[AxesDim] | None[source]

The dims of the sequence as expanded by sizes; None while an ellipsis in it is unbound.

compute(sizes) → int | None[source]

The size from the sizes of the operands given by sizes (an object with size(dim) and expand(items): DeclaredSizes or a matching); None while one is unknown.

solve(size: int, sizes) → list[tuple[AxesDim, int]][source]

The sizes of unknown dims this one is computed from such that it is size, where the answer is unique: (dim, size) pairs, possibly none.

class qewton.config.axes.BroadcastDim(*args, **kwargs)[source]

Bases: OperationDim

A dimension that two dims of different inputs broadcast to: the other one where one is 1, else both, which then must agree.

compute(sizes) → int | None[source]

The size from the sizes of the operands given by sizes (an object with size(dim) and expand(items): DeclaredSizes or a matching); None while one is unknown.

class qewton.config.axes.WindowDim(*args, **kwargs)[source]

Bases: OperationDim

The size of a dimension after a sliding window (a convolution or a pooling) with kernel, stride, padding and dilation, rounded down. The kernel size may be a dim itself (e.g. of a weight). Solved backwards only with stride 1, where the input size is unique.

property operands: tuple[AxesDim, ...]
with_parts(parts: tuple) → WindowDim[source]

A new dim like this one computed from parts, e.g. the stand-in of this dim at a place.

compute(sizes) → int | None[source]

The size from the sizes of the operands given by sizes (an object with size(dim) and expand(items): DeclaredSizes or a matching); None while one is unknown.

solve(size: int, sizes) → list[tuple[AxesDim, int]][source]

The sizes of unknown dims this one is computed from such that it is size, where the answer is unique: (dim, size) pairs, possibly none.

class qewton.config.axes.EllipsisDim(size=None, broadcastable=True)[source]

Bases: AxesDim

A special AxesDim representing an ellipsis (…), indicating a flexible number of dimensions.

An ellipsis stands for a sequence of dims, possibly empty; matching binds it to one at every place (see Matching).

is_ellipsis = True

Whether this stands for a sequence of dims (an ellipsis).

property is_open: bool

it has no size and is bound to no HyperParameter.

Type:

Whether this dim can have another size at every place

with_parts(parts: tuple) → EllipsisDim[source]

A new dim like this one computed from parts, e.g. the stand-in of this dim at a place.

qewton.config.devices module

qewton.config.devices.cuda_available()[source]
class qewton.config.devices.Device[source]

Bases: Serializable

A device data and computations live on. Saved by its kind (and index) and loaded as the same canonical object, cpu or cuda(i).

save(serializer: Serializer) → None[source]

The save method is responsible for serializing the object’s state. It collects the object’s attributes and adds them to the serializer.

Parameters:

serializer (Serializer) – The serializer instance that manages the serialization process.

classmethod construct_new_object(serializer: Deserializer, data_config: dict) → Device[source]

Generates a new instance of the class without calling its __init__ method.

Parameters:
  • serializer (Deserializer) – The deserializer instance that manages the loading process.

  • data_config (dict) – A dictionary containing the serialized data for the object.

Returns:

A new instance of the class, without calling its __init__ method.

The attributes will be set later.

Return type:

Any

ready_to_load(serializer: Deserializer, data_config: dict) → bool[source]

Checks if all dependencies of the object are ready to be loaded.

Parameters:
  • serializer (Deserializer) – The deserializer instance that manages the loading process.

  • data_config (dict) – A dictionary containing the serialized data for the object.

Returns:

If the object is ready to be loaded (i.e., all its

dependencies are ready).

Return type:

bool

load(serializer: Deserializer, data_config: dict) → None[source]

Loads the object’s state from the serialized data. It sets the object’s attributes based on the serialized data.

Parameters:
  • serializer (Deserializer) – The deserializer instance that manages the loading process.

  • data_config (dict) – A dictionary containing the serialized data for the object.

class qewton.config.devices.CPU[source]

Bases: Device

class qewton.config.devices.CUDA(index: 'int')[source]

Bases: Device

index: int
qewton.config.devices.cuda(index: int) → CUDA[source]

qewton.config.dtypes module

class qewton.config.dtypes.BFloat16[source]

Bases: _DType

class qewton.config.dtypes.Float16[source]

Bases: _DType

class qewton.config.dtypes.Float32[source]

Bases: _DType

class qewton.config.dtypes.Float64[source]

Bases: _DType

class qewton.config.dtypes.Complex32[source]

Bases: _DType

class qewton.config.dtypes.Complex64[source]

Bases: _DType

class qewton.config.dtypes.Complex128[source]

Bases: _DType

class qewton.config.dtypes.UInt8[source]

Bases: _DType

class qewton.config.dtypes.UInt16[source]

Bases: _DType

class qewton.config.dtypes.UInt32[source]

Bases: _DType

class qewton.config.dtypes.UInt64[source]

Bases: _DType

class qewton.config.dtypes.Int8[source]

Bases: _DType

class qewton.config.dtypes.Int16[source]

Bases: _DType

class qewton.config.dtypes.Int32[source]

Bases: _DType

class qewton.config.dtypes.Int64[source]

Bases: _DType

class qewton.config.dtypes.Number[source]

Bases: _DType

class qewton.config.dtypes.Bool[source]

Bases: _DType

qewton.config.dtypes.merge_dtypes(first: Any, second: Any) → Any[source]

The dtype that data of both first and second has.

From general to special: Any (or None), TensorType, the tensor class of a backend (any class that is no built-in Python type). A union matches where one of its members matches; several matching members give their union.

Parameters:
  • first – A dtype of a configuration.

  • second – Another one.

Returns:

The more special of the two, or the union of the matches.

Return type:

Any

Raises:

DataConfigMismatchError – If no member of first matches one of second.

qewton.config.dtypes.merge_element_dtypes(first: Any, second: Any) → Any[source]

The element dtype that data of both first and second has.

From general to special: None (open), Number, a concrete marker such as Float32.

Raises:

DataConfigMismatchError – If both are concrete and differ.

qewton.config.dtypes.saved_dtype(dtype: Any) → Any[source]

The form a dtype is saved in, without classes to import: a marker (“Any”, “TensorType”, “None”), a built-in type or the tensor class of a backend by name, a class of qewton (e.g. Float32) as it is, and a union, Literal or generic type (e.g. tuple[int, …]) as its origin and arguments. See loaded_dtype().

qewton.config.dtypes.loaded_dtype(saved: Any) → Any[source]

The dtype saved as saved (see saved_dtype()).

qewton.config.dtypes.element_dtype_in(metadata) → Any[source]

The element dtype marker (e.g. Float32) among the metadata of a type annotation such as Float32[TensorType, ...]; None if there is none.

qewton.config.errors module

exception qewton.config.errors.DataConfigMismatchError[source]

Bases: ValueError

Raised when two data configurations that are expected to match do not match or when they are tried to be unified.

exception qewton.config.errors.StructureUnknown[source]

Bases: Exception

The structure of a configuration is not known far enough for a shape operation yet, e.g. the position of a dim behind an ellipsis.

Raised by the shape operations of a configuration while a graph is connected; the graph tries the operation again once more is known.

qewton.config.matching module

Matching of data configurations: Matching.

class qewton.config.matching.Matching[source]

Bases: object

The state of matching data configurations, e.g. of one graph.

Declared configurations never change. At a place (e.g. a node in a graph) a declaration is instantiated: every object that can become more concrete there (an unknown dim, an ellipsis, axes of unknown kind or content, and what contains them) gets a stand-in of its own, every other object is used as it is (place()). Merging makes objects one group with a representative, binds ellipses to sequences and relates sizes through operation dims; all of it is kept here, in tables over the objects.

Configurations of a matching (its places, resolve()) and the results of their shape operations are DynamicDataConfigurations of it: what those operations fix (e.g. that a dim is 1) goes through it.

refining

Whether shape operations may refine unknown structure by binding ellipses to new unknowns; else they raise StructureUnknown.

Type:

bool

place(key: Hashable, declarations: dict) → dict[source]

Instantiate declarations at the place key; ports the place has already are kept.

Parameters:
  • key – The place, e.g. a node at a path of GraphNodes.

  • declarations – The declared configuration of each port.

Returns:

The configuration of every port at the place; an open

object shared by declarations is one stand-in there.

Return type:

dict

has_place(key: Hashable) → bool[source]

Whether key was instantiated.

configs(key: Hashable) → dict[source]

The configuration of every port at the place key.

places() → dict[source]

The configurations of the ports of every place, by place.

representative(item)[source]

The object that stands for item and everything merged with it.

size(item) → int | None[source]

The size of item (a dim; None for axes) as far as known: its own (declared, or computed from its operands), else the one found for its group.

expand(items: Sequence) → list[source]

The representatives of items, with every bound ellipsis replaced by the sequence it is bound to.

origin(dim) → Any[source]

What brought in the size of dim, e.g. a port; None if unknown.

merge(first, second)[source]

Make two axes or two dims one group.

Returns:

The representative of both.

Raises:

DataConfigMismatchError – If they contradict.

merge_configurations(first, second) → None[source]

Make two configurations describe the same data: their dtypes and their sequences of axes. Only configurations of this matching are written to; a declaration is read only.

Raises:

DataConfigMismatchError – If they contradict.

compatible(first, second) → bool[source]

Whether two axes or two dims could be merged.

merge_sequences(first: Sequence, second: Sequence) → None[source]

Merge two sequences of axes or dims item by item; ellipses take the rest. Of the consistent alignments, those that merge the most are preferred (no new ellipsis between the sides); a single remaining one is applied, several wait until an ellipsis is bound, so the result does not depend on the order of merges.

Raises:

DataConfigMismatchError – If no alignment of the sequences is consistent.

sequences_compatible(first: Sequence, second: Sequence) → bool[source]

Whether two sequences could be merged; with an ellipsis, only their items outside of it are checked.

bind(ellipsis, sequence: Sequence) → None[source]

Bind ellipsis to sequence and merge again the equations that wait for it.

Raises:

DataConfigMismatchError – If the ellipsis is bound to another sequence already that sequence contradicts.

open_up(ellipsis, at_start: bool) → None[source]

Bind ellipsis to one new unknown and a new ellipsis for the rest, the unknown at the start or the end.

Raises:

StructureUnknown – Unless refining.

resolve(config)[source]

config as known so far: every object replaced by the representative of its group, every bound ellipsis by what it stands for. Where the representative does not show what is known (other dims of an axes, a size only this matching found), a new object is built once per group, so equal axes stay one object; an operation dim is built over its resolved operands, so it follows HyperParameters (e.g. a changed batch size).

Returns:

A configuration of this matching.

Return type:

DynamicDataConfiguration

qewton.config.variables module

class qewton.config.variables.Variable(name: str | None = None, dim: int | tuple[int, ...] | None = None, children: list[Variable] | None = None, parent: Variable | None = None)[source]

Bases: Serializable

A named quantity, e.g. u with 1 or x with 2 components.

Variables are values: two are equal if their names, dims and children are (==), and copies are equal to the original. Composing them (u * p) builds a new Variable and leaves its parts unchanged; the order of the children matters.

classmethod empty()[source]
property is_leaf
property leaves
property quantities: list[Variable]

e.g. [u, p] for u * p. A variable with components of its own (created with dim > 1 and no children) is one quantity.

Returns:

The quantities, in order.

Return type:

list[Variable]

Type:

The distinct quantities this variable bundles

property quantity: Variable

The quantity this variable is part of, e.g. x for its component x_3; the variable itself if it is no component of one (see quantities).

property leaf_names: set[str]

The names of every leaf in this Variable’s tree.

property math_name: str

.name, wrapped for TeX math-mode rendering (Plotly’s MathJax support) - every Variable is a plotted quantity, so every Variable renders as a math symbol wherever a name is shown as a title/label. The single place this wrapping is defined, so callers throughout visualization (e.g. the titles in qewton.visualization.references) stay consistent by deferring to it instead of re-wrapping their own $…$ in different places.

Anything that ends up named but isn’t actually a Variable - a plain Axes, or a TablePlot column key - is deliberately not a Variable in the first place and has no equivalent here; it renders as plain text unless the caller wraps it themselves.

static compose(variables: list[Variable]) → Variable[source]

Folds variables into one Variable via *, left to right.

Returns the single variable itself, unchanged, when only one is given - *-ing a lone variable would otherwise wrap it in a pointless composite.

classmethod from_dict(data: dict[str, int | tuple[int, ...]]) → Variable[source]
get_slice(variable: Variable) → slice[source]

Computes a slice index for the variable provided in this main variable. The provided variable has to be included in this variable

Parameters:

variable (Variable) – The variable for which to compute the slice.

Raises:

KeyError – If the provided variable contains keys that are not present in this variable.

Returns:

The slice indices.

Return type:

tuple[slice, …] | list[int]

property is_empty: bool

Check if the variable has no children and dim is 0.

Returns:

True if the variable is empty, False otherwise.

Return type:

bool

prune(keep_names: set[str]) → Variable | None[source]

Removes every leaf whose name isn’t in keep_names, preserving as much of the original grouping as possible.

Returns this Variable itself, unchanged, if none of its leaves needed dropping - so an auto-expanded multi-component variable used whole stays whole instead of being flattened into its individual components just because some other, unrelated variable needed pruning. Returns None if every leaf was dropped.

unify(other: Variable) → Variable[source]

Unifies two variables, i.e. checks if they are compatible and returns a new variable containing the information from both original variables.

Parameters:

other (Variable) – The other variable to unify with.

Raises:
  • ValueError – If the variables have multiple axes.

  • ValueError – If the variable names do not agree for unification.

property shape