from types import EllipsisType
from typing import Annotated, Any
from qewton.backends import DEFAULT_DL_BACKEND, TensorType
from qewton.backends.base import DeepLearningBackend
from qewton.config.data_configurations import DataConfiguration, DynamicDataConfiguration
from qewton.config.axes import EllipsisAxes, FeatureAxes, AxesDim
from qewton.config.errors import StructureUnknown
from qewton.config.variables import Variable
from qewton.graphs.nodes import NO_DEFAULT, Port, InputPort, OutputPort, Node
# region: Slicing and value setting
[docs]
class SetItem(Node[TensorType]):
"""Set item node that assigns values to specific indices of an input tensor.
Has variable input ports for tensor and indices, and one output port.
The value may be a tensor or a Python number, e.g. ``x[:, :1] = 1.0``.
"""
data_axis = EllipsisAxes()
[docs]
def forward(
self,
inp: Annotated[TensorType, DataConfiguration(data_axis)],
key: Annotated[Any, DataConfiguration.empty()],
value: Annotated[TensorType | float, DataConfiguration.empty()],
) -> Annotated[TensorType, DataConfiguration(data_axis)]:
inp[key] = value
return inp
def _track(self, *args, **kwargs):
output_trackers = super()._track(*args, **kwargs)
# Since set item happens in place, we have to update the
# TrackingObject in place as well. Else while tracking this
# operation happens at an arbitrary point.
if "inp" in kwargs:
inp_tacker = kwargs["inp"]
else:
inp_tacker = args[0]
inp_tacker.to_ports = []
inp_tacker.last_output_port = self.output_ports[0]
return output_trackers
[docs]
class Slice(Node[TensorType]):
"""Slice node that extracts a portion of the input tensor based on slice configuration.
Supports integer indices, slices, variables, and ellipsis notation.
Has one input port and one output port.
"""
def __init__(
self,
slice_config: (
int
| slice
| Variable
| tuple[slice | list[int] | EllipsisType | int | Any, ...]
),
name=None,
backend: type[DeepLearningBackend[TensorType]] = DEFAULT_DL_BACKEND,
):
self.slice_obj = slice_config
self.backend: type[DeepLearningBackend[TensorType]] = backend
self.slice_config = slice_config
super().__init__(name if name is not None else "SliceNode", backend=backend)
[docs]
def forward(
self, inp: Annotated[Any, DataConfiguration.empty()]
) -> Annotated[Any, DataConfiguration.empty()]:
if isinstance(inp, self.backend.default_dtype):
return self.backend.math.slice(inp, self.slice_config)
return inp[self.slice_config]
[docs]
def relate(self, inp: DynamicDataConfiguration) -> DataConfiguration | None:
"""Slicing a Variable keeps every axis but the features, which become
the Variable; other slices leave the output open."""
if not isinstance(self.slice_obj, Variable):
return None
if not inp.axes or not isinstance(inp.axes[-1], FeatureAxes):
raise StructureUnknown(f"The features of {inp} are not known yet.")
self.slice_config = inp.get_variable_slice(self.slice_obj)
return DataConfiguration(*inp.axes[:-1], FeatureAxes(variable=self.slice_obj))
@classmethod
def _string_to_slice(cls, slice_str: str):
# Convert a string representation of a slice to an actual slice object
if slice_str == "...":
return Ellipsis
# Slices are saved as "slice(2, None, None)", so we split at commas
# and also need to remove the "slice(" and ")" parts as well as any
# whitespace
elif slice_str.startswith("slice"):
slice_str = slice_str.replace(" ", "")
slice_parts = slice_str[6:-1].split(",")
start = int(slice_parts[0]) if slice_parts[0] != "None" else None
stop = int(slice_parts[1]) if slice_parts[1] != "None" else None
step = int(slice_parts[2]) if slice_parts[2] != "None" else None
return slice(start, stop, step)
else:
return int(slice_str)
[docs]
class SplitVariables(Node[TensorType]):
"""Splits an input tensor's feature axis into one output port per
Variable in `split_into`.
The caller decides the exact pieces upfront - this used to auto-derive
them from whatever named entries its own input happened to have, which
forced always splitting down to the finest granularity available before
anything downstream could ask for less. A caller that knows every
downstream consumer in advance (e.g. PINNPipeline) can instead split
only as finely as actually needed - a variable nothing ever asks to
subdivide can be named whole in `split_into` and passed through with a
single piece.
Args:
split_into (list[Variable]): The pieces to split the input's
feature axis into, in order. Each must be a contiguous run of
the eventual input's own feature Variable - not necessarily a
single leaf, e.g. an auto-expanded 3D variable can be its own
whole piece.
"""
def __init__(
self,
split_into: list[Variable],
name=None,
backend: type[DeepLearningBackend[TensorType]] = DEFAULT_DL_BACKEND,
):
super().__init__(
name if name is not None else "SplitVariablesNode", backend=backend
)
self.backend: type[DeepLearningBackend[TensorType]] = backend
self.split_into = split_into
self.split_sections = [var.dim for var in split_into]
# The pieces keep every axis of the input but the features, which are
# the last axes. The outputs carry their Variables already in their
# static configurations, as PINNPipeline reads them before connecting.
ellipsis_axes = EllipsisAxes()
self._input_ports = [
InputPort(
DataConfiguration(
ellipsis_axes,
FeatureAxes(shape=(AxesDim(sum(self.split_sections)),)),
dtype=backend.default_dtype,
),
node=self,
name="inp",
)
]
self._output_ports = [
OutputPort(
DataConfiguration(
ellipsis_axes, FeatureAxes(variable=var), dtype=backend.default_dtype
),
node=self,
name=var.name,
)
for var in split_into
]
[docs]
def forward(self, inp: Annotated[TensorType, DataConfiguration.empty()]):
return self.backend.math.split(inp, self.split_sections, axis=-1)
[docs]
class ConcatVariables(Node[TensorType]):
"""Concatenate variables node that combines multiple input tensors with different variables along a dimension.
Assumes the feature axes are all the last axes.
Has multiple input ports (one per variable) and one output port.
"""
def __init__(
self,
in_variables,
concat_dim: int = -1,
name=None,
backend: type[DeepLearningBackend[TensorType]] = DEFAULT_DL_BACKEND,
):
super().__init__(
name if name is not None else "ConcatVariablesNode", backend=backend
)
self.backend: type[DeepLearningBackend[TensorType]] = backend
self.in_variables = in_variables
self.check_unique_var_keys()
self.concat_dim = concat_dim
self.concat_sections = None
ellipsis_axes = EllipsisAxes()
self._input_ports = []
for var in self.in_variables:
self._input_ports.append(
InputPort(
DataConfiguration(
ellipsis_axes,
FeatureAxes(variable=var),
dtype=self.backend.default_dtype,
),
node=self,
name=var.name,
)
)
# Fold starting from the first real variable, not an empty
# Variable() placeholder - composing with a genuinely empty
# Variable leaves its dim as None (Variable.__init__ propagates
# "any child's dim is None" outward), which breaks arithmetic like
# Variable.get_slice's running_idx += child.dim on the result.
out_var = Variable.compose(self.in_variables)
self._output_ports = [
OutputPort(
DataConfiguration(
ellipsis_axes,
FeatureAxes(variable=out_var),
dtype=self.backend.default_dtype,
),
node=self,
name=out_var.name,
)
]
[docs]
def check_unique_var_keys(self):
seen_keys = set()
for var in self.in_variables:
if var.name in seen_keys:
raise ValueError(
f"Variable key '{var.name}' is not unique across input variables."
)
seen_keys.add(var.name)
[docs]
def forward(self, *inp):
return self.backend.math.concatenate(inp, axis=self.concat_dim)
[docs]
class AsVariable(Node[TensorType]):
"""Declares that the features of its input are `variable`, e.g. that an
exact solution computed from ``t`` is a value of ``u``, to compare it with
the output of a model of ``u``.
Merging configurations never changes their Variables, so data of ``t``
can not be connected where ``u`` is expected; this node passes the data
on unchanged under the new Variable. The input may have any Variable (or
none) with the same feature size as `variable`.
Args:
variable (Variable): The Variable of the output's features.
"""
def __init__(
self,
variable: Variable,
name=None,
backend: type[DeepLearningBackend[TensorType]] = DEFAULT_DL_BACKEND,
):
super().__init__(
name if name is not None else f"As{variable.name}", backend=backend
)
self.backend: type[DeepLearningBackend[TensorType]] = backend
self.variable = variable
# All axes but the features (the last axes) pass through; the
# Variable is declared statically, as for SplitVariables.
ellipsis_axes = EllipsisAxes()
self._input_ports = [
InputPort(
DataConfiguration(
ellipsis_axes,
FeatureAxes(shape=variable.shape),
dtype=backend.default_dtype,
),
node=self,
name="inp",
)
]
self._output_ports = [
OutputPort(
DataConfiguration(
ellipsis_axes,
FeatureAxes(variable=variable),
dtype=backend.default_dtype,
),
node=self,
name=variable.name,
)
]
[docs]
def forward(self, inp: Annotated[TensorType, DataConfiguration.empty()]):
return inp
[docs]
class ConcatNode(Node[TensorType]):
"""Concatenate node that combines multiple input tensors along a specified dimension.
Has multiple input ports and one output port.
"""
def __init__(
self, concat_dim: int, num_of_input_ports: int = 2, backend=DEFAULT_DL_BACKEND
):
self.concat_dim = concat_dim
self.num_of_input_ports = num_of_input_ports
super().__init__(name=None, backend=backend)
self.backend: type[DeepLearningBackend[TensorType]] = backend
self._input_ports = []
for i in range(num_of_input_ports):
self._input_ports.append(
InputPort(
DataConfiguration.empty(),
node=self,
name=f"Input_{i}",
)
)
[docs]
def forward(self, *inp) -> Annotated[TensorType, DataConfiguration.empty()]:
return self.backend.math.concatenate(inp, axis=self.concat_dim)
# endregion
# region: Reshaping
[docs]
def relate(self, *inputs: DynamicDataConfiguration) -> DataConfiguration:
return inputs[0].concat(list(inputs[1:]), self.concat_dim)
[docs]
class Narrow(Node[TensorType]):
"""Narrow node that returns a narrowed view of the input tensor along a specified dimension.
Has one input port and one output port.
"""
def __init__(self, dim=None, start=0, length=None, backend=DEFAULT_DL_BACKEND):
self.dim = dim if dim is not None else NO_DEFAULT
self.start = start
self.l = length if length is not None else NO_DEFAULT
super().__init__(name=None, backend=backend)
self.backend: type[DeepLearningBackend[TensorType]] = backend
[docs]
def forward(
self,
x: Annotated[TensorType, DataConfiguration.empty()],
) -> Annotated[TensorType, DataConfiguration.empty()]:
o = self.backend.math.narrow(x, self.dim, self.start, self.l) # type: ignore
return o
[docs]
def relate(self, x: DynamicDataConfiguration) -> DataConfiguration | None:
if self.dim is NO_DEFAULT or self.l is NO_DEFAULT:
return None
return x.set_size(self.dim, self.l)
[docs]
class Squeeze(Node[TensorType]):
"""Squeeze node that removes a single dimension of size 1 from the input tensor.
Has one input port and one output port.
"""
def __init__(
self,
dim: int,
name=None,
backend: type[DeepLearningBackend[TensorType]] = DEFAULT_DL_BACKEND,
):
super().__init__(name if name is not None else "SqueezeNode", backend=backend)
self.dim = dim
self.backend: type[DeepLearningBackend[TensorType]] = backend
[docs]
def forward(
self, inp: Annotated[TensorType, DataConfiguration.empty()]
) -> Annotated[TensorType, DataConfiguration.empty()]:
return self.backend.math.squeeze(inp, self.dim)
[docs]
def relate(self, inp: DynamicDataConfiguration) -> DataConfiguration:
return inp.squeeze(self.dim)
[docs]
class Unsqueeze(Node[TensorType]):
"""Unsqueeze node that adds a new dimension of size 1 at the specified position.
Has one input port and one output port.
"""
def __init__(
self,
dim: int,
name=None,
backend: type[DeepLearningBackend[TensorType]] = DEFAULT_DL_BACKEND,
):
super().__init__(name if name is not None else "UnsqueezeNode", backend=backend)
self.dim = dim
self.backend: type[DeepLearningBackend[TensorType]] = backend
[docs]
def forward(
self, inp: Annotated[TensorType, DataConfiguration.empty()]
) -> Annotated[TensorType, DataConfiguration.empty()]:
return self.backend.math.unsqueeze(inp, self.dim)
[docs]
def relate(self, inp: DynamicDataConfiguration) -> DataConfiguration:
return inp.unsqueeze(self.dim)
[docs]
class Reshape(Node[TensorType]):
"""Reshape node that changes the shape of the input tensor to a specified new shape.
Has one input port and one output port.
"""
def __init__(
self,
new_shape: tuple[int, ...],
name=None,
backend: type[DeepLearningBackend[TensorType]] = DEFAULT_DL_BACKEND,
):
self.new_shape = new_shape
super().__init__(name if name is not None else "ReshapeNode", backend=backend)
self.backend: type[DeepLearningBackend[TensorType]] = backend
[docs]
def forward(
self, inp: Annotated[TensorType, DataConfiguration.empty()]
) -> Annotated[TensorType, DataConfiguration.empty()]:
return self.backend.math.reshape(inp, self.new_shape)
[docs]
def relate(self, inp: DynamicDataConfiguration) -> DataConfiguration:
return inp.reshape(tuple(self.new_shape))
[docs]
class ReshapeAtDim(Node[TensorType]):
"""Reshape at dimension node that reshapes a portion of the input tensor at a specified dimension.
Has one input port and one output port.
"""
def __init__(
self,
dim: int,
new_shape: tuple[int, ...],
name=None,
backend: type[DeepLearningBackend[TensorType]] = DEFAULT_DL_BACKEND,
):
self.new_shape = new_shape
self.dim = dim
super().__init__(name if name is not None else "ReshapeNode", backend=backend)
self.backend: type[DeepLearningBackend[TensorType]] = backend
[docs]
def forward(
self, inp: Annotated[TensorType, DataConfiguration.empty()]
) -> Annotated[TensorType, DataConfiguration.empty()]:
if self.dim < 0:
self.dim = len(inp.shape) + self.dim
new_shape = inp.shape[: self.dim] + self.new_shape + inp.shape[self.dim + 1 :]
return self.backend.math.reshape(inp, new_shape)
[docs]
def relate(self, inp: DynamicDataConfiguration) -> DataConfiguration:
return inp.unflatten(self.dim, tuple(self.new_shape))
[docs]
class Flatten(Node[TensorType]):
"""Flatten node that flattens the input tensor between specified dimensions.
Has one input port and one output port.
"""
def __init__(
self,
start_dim: int = 0,
end_dim: int = -1,
name=None,
backend: type[DeepLearningBackend[TensorType]] = DEFAULT_DL_BACKEND,
):
self.start_dim = start_dim
self.end_dim = end_dim
super().__init__(name if name is not None else "FlattenNode", backend=backend)
self.backend: type[DeepLearningBackend[TensorType]] = backend
[docs]
def forward(
self, inp: Annotated[TensorType, DataConfiguration.empty()]
) -> Annotated[TensorType, DataConfiguration.empty()]:
return self.backend.math.flatten(
inp, start_dim=self.start_dim, end_dim=self.end_dim
)
[docs]
def relate(self, inp: DynamicDataConfiguration) -> DataConfiguration:
return inp.flatten(self.start_dim, self.end_dim)
[docs]
class Unflatten(Node[TensorType]):
"""Unflatten node that reshapes a single dimension into multiple dimensions.
Has one input port and one output port.
"""
def __init__(
self,
axis: int,
sizes: tuple[int, ...] | None = None,
name=None,
backend: type[DeepLearningBackend[TensorType]] = DEFAULT_DL_BACKEND,
):
self.axis = axis
self.sizes = sizes
super().__init__(name if name is not None else "UnflattenNode", backend=backend)
self.backend: type[DeepLearningBackend[TensorType]] = backend
[docs]
def forward(
self,
inp: Annotated[TensorType, DataConfiguration.empty()],
size: Annotated[
int | tuple[int, ...] | None,
FeatureAxes(shape=(AxesDim(None),)),
] = None,
) -> Annotated[TensorType, DataConfiguration.empty()]:
if isinstance(size, int):
size = (size,)
elif size is None and self.sizes is not None:
size = self.sizes
return self.backend.math.unflatten(inp, self.axis, size) # type: ignore
[docs]
def relate(
self, inp: DynamicDataConfiguration, size: DynamicDataConfiguration
) -> DataConfiguration | None:
if self.sizes is None:
return None
return inp.unflatten(self.axis, tuple(self.sizes))
[docs]
class Repeat(Node[TensorType]):
def __init__(
self,
repeats: int,
dim: int,
name=None,
backend: type[DeepLearningBackend[TensorType]] = DEFAULT_DL_BACKEND,
):
self.repeats = repeats
self.dim = dim
super().__init__(name if name is not None else "RepeatNode", backend=backend)
self.backend: type[DeepLearningBackend[TensorType]] = backend
[docs]
def forward(
self, inp: Annotated[TensorType, DataConfiguration.empty()]
) -> Annotated[TensorType, DataConfiguration.empty()]:
return self.backend.math.repeat(inp, self.repeats, self.dim)
[docs]
class UnflattenLike(Node[TensorType]):
"""Unflattens an axis of a tensor into a part of the shape of another one.
The axis `axis` of the input is split into the shape
`like.shape[start_dim:end_dim]`. This is the inverse of
`Flatten(start_dim, end_dim)` when the shape to restore is only known at
runtime, taken from the tensor that was flattened.
Args:
start_dim (int): Index of the first axis of `like` whose shape is restored.
end_dim (int | None, optional): Index after the last axis of `like`
whose shape is restored; None for all up to the end. Defaults to None.
axis (int, optional): The axis of the input that is split. Defaults
to -1, the last one.
name (str | None, optional): Name of the node. Defaults to "UnflattenLikeNode".
backend (type[DeepLearningBackend[TensorType]], optional): The backend used for
the computations. Defaults to DEFAULT_DL_BACKEND.
"""
def __init__(
self,
start_dim: int,
end_dim: int | None = None,
axis: int = -1,
name: str | None = None,
backend: type[DeepLearningBackend[TensorType]] = DEFAULT_DL_BACKEND,
) -> None:
self.start_dim = start_dim
self.end_dim = end_dim
self.axis = axis
super().__init__(
name if name is not None else "UnflattenLikeNode", backend=backend
)
self.backend: type[DeepLearningBackend[TensorType]] = backend
[docs]
def forward(
self,
inp: Annotated[TensorType, DataConfiguration.empty()],
like: Annotated[TensorType, DataConfiguration.empty()],
) -> Annotated[TensorType, DataConfiguration.empty()]:
"""Splits the axis `axis` of `inp` into a part of the shape of `like`.
Args:
inp (TensorType): Tensor whose axis is split, e.g. the flattened
spatial axes. Its size must be the product of the restored shape.
like (TensorType): Tensor that provides the shape to restore.
Returns:
TensorType: `inp` with the axis replaced by
`like.shape[start_dim:end_dim]`.
"""
shape = tuple(like.shape[self.start_dim : self.end_dim])
return self.backend.math.unflatten(inp, self.axis, shape)
# endregion
# region: Array info
[docs]
class GetShapeNode(Node[TensorType]):
"""Get shape node that returns the shape tuple of the input tensor.
Has one input port and one output port.
"""
[docs]
def forward(
self, x: Annotated[TensorType, DataConfiguration.empty()]
) -> Annotated[tuple[int, ...], DataConfiguration.empty()]:
return tuple(x.shape)
# endregion