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 plusdtypeandelement_dtype; at most oneFeatureAxes.Axes:
BatchAxes(samples),GeometryAxes(points of aGeometry),FeatureAxes(values, named byVariables),EllipsisAxes(any sequence of axes, possibly none).Dims:
AxesDim(size)withsizean int, None (unknown) or aHyperParameter;EllipsisDimfor 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)(ormatching.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¶
- qewton.config.data_configurations package
- Module contents
- Submodules
- qewton.config.data_configurations.base module
DataConfigurationDataConfiguration.element_dtypeDataConfiguration.replace()DataConfiguration.empty()DataConfiguration.variablesDataConfiguration.variable_nameDataConfiguration.shapeDataConfiguration.feature_axesDataConfiguration.geometry_axesDataConfiguration.belongs_to()DataConfiguration.set_dtype()DataConfiguration.matches()DataConfiguration.of_value()DataConfiguration.axes_of()DataConfiguration.describe()DataConfiguration.get_variable_slice()DataConfiguration.get_axes_range()DataConfiguration.get_slice()DataConfiguration.save()DataConfiguration.load()DataConfiguration.ready_to_load()
- qewton.config.data_configurations.dynamic module
DynamicDataConfigurationDynamicDataConfiguration.matchingDynamicDataConfiguration.merge()DynamicDataConfiguration.resolve()DynamicDataConfiguration.belongs_to()DynamicDataConfiguration.dim()DynamicDataConfiguration.merge_dim()DynamicDataConfiguration.drop()DynamicDataConfiguration.squeeze()DynamicDataConfiguration.set_size()DynamicDataConfiguration.unsqueeze()DynamicDataConfiguration.permute()DynamicDataConfiguration.flatten()DynamicDataConfiguration.unflatten()DynamicDataConfiguration.reshape()DynamicDataConfiguration.concat()DynamicDataConfiguration.split()DynamicDataConfiguration.broadcast()DynamicDataConfiguration.window()
- qewton.config.data_configurations.grid module
- qewton.config.saving package
- Module contents
- Submodules
- qewton.config.saving.callables module
- qewton.config.saving.loading module
- qewton.config.saving.saving module
- qewton.config.saving.schema_keys module
SavingKeysSavingKeys.KEY_VERSIONSavingKeys.VERSIONSavingKeys.KEY_TYPESavingKeys.KEY_VALUESSavingKeys.KEY_COMPRESSEDSavingKeys.KEY_LISTSavingKeys.KEY_TUPLESavingKeys.KEY_DICTSavingKeys.KEY_SETSavingKeys.KEY_ENUMSavingKeys.KEY_CLASS_OBJSavingKeys.KEY_SERIALIZABLESavingKeys.KEY_CLASSSavingKeys.KEY_SELF_ARGSSavingKeys.KEY_MODULESavingKeys.KEY_ELLIPSISSavingKeys.KEY_BACKEND_PARAMETERSavingKeys.KEY_SLICESavingKeys.NODE_IDSavingKeys.NODE_MODESavingKeys.NODE_STATESavingKeys.FILE_CONFIGSavingKeys.FILE_DATASavingKeys.FILE_PARAMETERS
Submodules¶
qewton.config.axes module¶
- class qewton.config.axes.Axes(*shape: int | AxesDim | None | EllipsisType)[source]¶
Bases:
SerializableRepresents 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.
- 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
- class qewton.config.axes.BatchAxes(*shape: int | AxesDim | None | EllipsisType)[source]¶
Bases:
AxesRepresents 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:
AxesRepresents 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:
- 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:
AxesRepresents 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.
- class qewton.config.axes.EllipsisAxes[source]¶
Bases:
AxesRepresents 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).
- class qewton.config.axes.AxesDim(size=None, broadcastable=True)[source]¶
Bases:
SerializableRepresents 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 (
DeclaredSizesor a matching): the declared one.
- class qewton.config.axes.DeclaredSizes[source]¶
Bases:
objectSizes and sequences as declared: what operation dims are computed from outside of a matching. A
Matchinganswers the same questions with what it found.
- class qewton.config.axes.OperationDim(*args, **kwargs)[source]¶
Bases:
AxesDimA dimension whose size is computed from other dimensions (its operands), e.g. a sum. It is a relation:
compute()andsolve()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 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 (
DeclaredSizesor 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):
DeclaredSizesor a matching); None while one is unknown.
- class qewton.config.axes.AddedDim(*args, **kwargs)[source]¶
Bases:
OperationDimA dimension whose size is the sum of two other dimensions.
- class qewton.config.axes.SubDim(*args, **kwargs)[source]¶
Bases:
OperationDimA dimension whose size is the difference of two other dimensions.
- class qewton.config.axes.ProductDim(*args, **kwargs)[source]¶
Bases:
OperationDimA dimension whose size is the product of two other dimensions.
- class qewton.config.axes.DivideDim(*args, **kwargs)[source]¶
Bases:
OperationDimA dimension whose size is the first of two dimensions divided by the second, rounded down.
- class qewton.config.axes.MinimumDim(*args, **kwargs)[source]¶
Bases:
OperationDimA dimension whose size is the minimum of two other dimensions.
- class qewton.config.axes.SequenceProductDim(*args, **kwargs)[source]¶
Bases:
OperationDimA 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):
DeclaredSizesor a matching); None while one is unknown.
- class qewton.config.axes.BroadcastDim(*args, **kwargs)[source]¶
Bases:
OperationDimA 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):
DeclaredSizesor a matching); None while one is unknown.
- class qewton.config.axes.WindowDim(*args, **kwargs)[source]¶
Bases:
OperationDimThe 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.
- 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):
DeclaredSizesor a matching); None while one is unknown.
- class qewton.config.axes.EllipsisDim(size=None, broadcastable=True)[source]¶
Bases:
AxesDimA 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¶
- class qewton.config.devices.Device[source]¶
Bases:
SerializableA 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.
qewton.config.dtypes module¶
- 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.errors module¶
- exception qewton.config.errors.DataConfigMismatchError[source]¶
Bases:
ValueErrorRaised 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:
ExceptionThe 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:
objectThe 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 areDynamicDataConfigurations 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
- 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.
- 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.
- 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:
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:
SerializableA named quantity, e.g.
uwith 1 orxwith 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.- property is_leaf¶
- property leaves¶
- property quantities: list[Variable]¶
e.g.
[u, p]foru * p. A variable with components of its own (created withdim > 1and 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.
xfor its componentx_3; the variable itself if it is no component of one (seequantities).
- 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.
- 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¶