On this page

TensorNetwork

symbolica.community.spenso Class

TensorNetwork(expr: Any, library: Optional[TensorLibrary] = None)

A graph of tensor operations that can be simplified and executed.

Named tensor expressions are resolved through a TensorLibrary. Register concrete data before constructing and executing a network; an expression alone supplies structure, not component values.

A network retains the semantic source expression and its public tensor interface separately from the executable graph and its stored values. Value specialization and graph execution therefore do not rewrite the source expression returned by structure() or used by the semantic display methods.

Examples

from symbolica.community.spenso import (
    ExecutionMode,
    Representation,
    Tensor,
    TensorLibrary,
    TensorName,
    TensorNetwork,
)
rep = Representation.euc(2)
A = TensorName("A")
structure = A(rep, rep)
library = TensorLibrary()
library.register(
    Tensor.dense(structure, [1.0, 0.0, 0.0, 1.0])
)
network = TensorNetwork(
    A(rep("i"), rep("j")),
    library=library,
)
network.execute(library=library, mode=ExecutionMode.All)
result = network.result_tensor(library=library)
len(result)

Constructor

#

Create a tensor network by parsing an arithmetic expression.

Parses symbolic expressions containing tensor operations and converts them into an optimizable computational graph representation.

Returns

TensorNetwork

A new TensorNetwork representing the parsed expression

Parameters

NameTypeDefaultDescription
exprAny—

The arithmetic expression or tensor structure to parse

libraryOptional[TensorLibrary]None

Tensor library for resolving named tensor references. Defaults to the built-in four-dimensional HEP and SU(3) library returned by TensorLibrary.hep_lib().

Member details

one

Static method
#
one() -> TensorNetwork

Create a tensor network representing the scalar value 1.

Returns

TensorNetwork

A TensorNetwork containing only the scalar 1

Examples

from symbolica.community.spenso import TensorNetwork
one_net = TensorNetwork.one()
result = one_net.result_scalar()

bracket

Static method
#
bracket() -> Expression

Return the symbolic head used for structured product brackets.

broadcast

Static method
#
broadcast(str: str) -> Expression

Create a Symbolica function symbol tagged for elementwise tensor broadcasting.

Parameters

NameTypeDefaultDescription
strstr——

zero

Static method
#
zero() -> TensorNetwork

Create a tensor network representing the scalar value 0.

Returns

TensorNetwork

A TensorNetwork containing only the scalar 0

Examples

from symbolica.community.spenso import TensorNetwork
zero_net = TensorNetwork.zero()
result = zero_net.result_scalar()

replace

Method
#
replace(pattern: Expression | int | Float | int | float | str | decimal.Decimal | ComplexFloat | Float | int | float | str | decimal.Decimal | complex | tuple[Float | int | float | str | decimal.Decimal, Float | int | float | str | decimal.Decimal], rhs: Expression | int | Float | int | float | str | decimal.Decimal | ComplexFloat | Float | int | float | str | decimal.Decimal | complex | tuple[Float | int | float | str | decimal.Decimal, Float | int | float | str | decimal.Decimal] | HeldExpression | Callable[[dict[Expression, Expression]], Expression] | int | float | complex | Float | ComplexFloat | decimal.Decimal, cond: Optional[PatternRestriction | Condition] = None, non_greedy_wildcards: Optional[Sequence[Expression]] = None, level_range: Optional[tuple[int, Optional[int]]] = None, level_is_tree_depth: Optional[bool] = None, allow_new_wildcards_on_rhs: Optional[bool] = None, rhs_cache_size: Optional[int] = None, repeat: Optional[bool] = None) -> TensorNetwork

Replace patterns in stored symbolic network values.

Rewrites scalar coefficients and symbolic elements of parametric tensors in the execution store. Tensor identities, graph topology, the public interface, and the semantic source expression returned by structure() are unchanged. Rewrite a TensorExpression before constructing the network when the source tensor expression itself should change.

Returns

TensorNetwork

A new TensorNetwork with matching stored values replaced and the same semantic source structure

Parameters

NameTypeDefaultDescription
patternExpression | int | Float | int | float | str | decimal.Decimal | ComplexFloat | Float | int | float | str | decimal.Decimal | complex | tuple[Float | int | float | str | decimal.Decimal, Float | int | float | str | decimal.Decimal]—

The symbolic pattern to match within stored values

rhsExpression | int | Float | int | float | str | decimal.Decimal | ComplexFloat | Float | int | float | str | decimal.Decimal | complex | tuple[Float | int | float | str | decimal.Decimal, Float | int | float | str | decimal.Decimal] | HeldExpression | Callable[[dict[Expression, Expression]], Expression] | int | float | complex | Float | ComplexFloat | decimal.Decimal—

The replacement expression or pattern

condOptional[PatternRestriction | Condition]None

Additional restriction that each match must satisfy

non_greedy_wildcardsOptional[Sequence[Expression]]None

List of wildcard symbols to match non-greedily

level_rangeOptional[tuple[int, Optional[int]]]None

Tuple specifying depth range for pattern matching

level_is_tree_depthOptional[bool]None

Whether level refers to tree depth or expression depth

allow_new_wildcards_on_rhsOptional[bool]None

Allow new wildcards in replacement pattern

rhs_cache_sizeOptional[int]None

Size of cache for replacement pattern compilation

repeatOptional[bool]None

Whether to repeatedly apply the replacement until no more matches

evaluate

Method
#
evaluate(constants: Mapping[Expression, float], functions: Mapping[Expression, Any]) -> TensorNetwork

Evaluate symbolic tensor values in the execution store.

Substitutes symbolic constants and functions in stored parametric tensor elements, converting them to concrete numerical tensors. Tensor identities, graph topology, the public interface, and the semantic source expression are retained.

Returns

TensorNetwork

A new TensorNetwork with stored tensor values evaluated and the same semantic source structure

Parameters

NameTypeDefaultDescription
constantsMapping[Expression, float]—

Dict mapping symbolic expressions to their numerical values

functionsMapping[Expression, Any]—

Dict mapping function symbols to Python callable objects

execute

Method
#
execute(library: Optional[TensorLibrary] = None, function_library: Optional[TensorFunctionLibrary] = None, n_steps: Optional[int] = None, mode: ExecutionMode = ExecutionMode.All) -> None

Execute the tensor network to perform tensor contractions and simplifications.

Processes the computational graph by executing tensor operations such as contractions, additions, and multiplications. The execution can be controlled by mode and step limits.

Examples

from symbolica.community.spenso import TensorNetwork, ExecutionMode, TensorLibrary
network = TensorNetwork(some_expression)
network.execute()
network.execute(n_steps=5)
network.execute(mode=ExecutionMode.Scalar)
lib = TensorLibrary.hep_lib()
network.execute(library=lib)

Parameters

NameTypeDefaultDescription
libraryOptional[TensorLibrary]None

Optional tensor library for resolving tensor operations

function_libraryOptional[TensorFunctionLibrary]None

Tensor function callbacks; None uses the built-in function library

n_stepsOptional[int]None

Maximum number of execution steps (None for complete execution)

modeExecutionModeExecutionMode.All

Execution strategy. ExecutionMode.Single selects one smallest-degree rewrite per step; use n_steps to bound how many steps run.

result_tensor

Method
#
result_tensor(library: Optional[TensorLibrary] = None) -> Tensor

Extract the final tensor result from the executed network.

After network execution, retrieves the computed tensor result. The network should be executed before calling this method.

Returns

Tensor

The computed tensor result

Raises

RuntimeError

If the network execution resulted in an error

Examples

from symbolica.community.spenso import TensorNetwork, TensorLibrary
network = TensorNetwork(tensor_expression)
network.execute()
result = network.result_tensor()
lib = TensorLibrary.hep_lib()
result_with_lib = network.result_tensor(library=lib)

Parameters

NameTypeDefaultDescription
libraryOptional[TensorLibrary]None

Optional tensor library for resolving tensor structures

result_scalar

Method
#
result_scalar() -> Expression

Extract the final scalar result from the executed network.

For networks that evaluate to scalar expressions, retrieves the computed scalar value. The network should be executed before calling this method.

Returns

Expression

The computed scalar expression

Raises

RuntimeError

If the network execution resulted in an error

Examples

from symbolica.community.spenso import TensorNetwork
network = TensorNetwork(scalar_expression)
network.execute()
scalar_result = network.result_scalar()

__str__

Method
#
__str__() -> str

Return a DOT representation of the executable network graph.

Generates a DOT format representation of the computational graph that can be visualized using graphviz or similar tools.

to_dot

Method
#
to_dot() -> str

Return the computational graph in Graphviz DOT format.

format_tensor

Method
#
format_tensor(show_dimensions: Optional[bool] = None, *, settings: Optional[DisplaySettings] = None) -> str

Format the exact semantic structure using compact Spenso notation.

Parameters

NameTypeDefaultDescription
show_dimensionsOptional[bool]None—
settingsOptional[DisplaySettings]None—

to_typst

Method
#
to_typst(show_dimensions: Optional[bool] = None, *, settings: Optional[DisplaySettings] = None) -> str

Format the semantic source structure as Typst math source.

Parameters

NameTypeDefaultDescription
show_dimensionsOptional[bool]None—
settingsOptional[DisplaySettings]None—

formatted

Method
#
formatted(show_dimensions: Optional[bool] = None, *, settings: Optional[DisplaySettings] = None, notation_source: Optional[str] = None) -> FormattedOutput

Build Symbolica's rich display wrapper for the semantic source structure.

Parameters

NameTypeDefaultDescription
show_dimensionsOptional[bool]None—
settingsOptional[DisplaySettings]None—
notation_sourceOptional[str]None—

to_html

Method
#
to_html(show_dimensions: Optional[bool] = None, *, settings: Optional[DisplaySettings] = None, notation_source: Optional[str] = None) -> str

No description is available for this member.

Parameters

NameTypeDefaultDescription
show_dimensionsOptional[bool]None—
settingsOptional[DisplaySettings]None—
notation_sourceOptional[str]None—

to_svg

Method
#
to_svg(show_dimensions: Optional[bool] = None, *, settings: Optional[DisplaySettings] = None, notation_source: Optional[str] = None) -> str

No description is available for this member.

Parameters

NameTypeDefaultDescription
show_dimensionsOptional[bool]None—
settingsOptional[DisplaySettings]None—
notation_sourceOptional[str]None—

_repr_html_

Method
#
_repr_html_() -> Optional[str]

No description is available for this member.

structure

Method
#
structure() -> TensorExpression

Return the semantic source expression and its public tensor interface.

This expression records the tensor-aware structure used for composition and provenance. It is not reconstructed from the current execution store, so replace(), evaluate(), and execute() leave it unchanged. Use result_scalar() or result_tensor() to inspect the current computed value.

index

Method
#
index(*indices: Any, cook_indices: bool = False) -> TensorNetwork

Fill the unresolved external ports with indices in interface order.

Pass AUTO to leave a port unresolved. Set cook_indices=True to flatten nested symbolic index payloads before insertion.

Parameters

NameTypeDefaultDescription
indicesAny——
cook_indicesboolFalse—

__call__

Method
#
__call__(*indices: Any, cook_indices: bool = False) -> TensorNetwork

Fill the unresolved external ports with indices in interface order.

Parameters

NameTypeDefaultDescription
indicesAny——
cook_indicesboolFalse—

__neg__

Method
#
__neg__() -> TensorNetwork

No description is available for this member.

__add__

Method
#
__add__(rhs: Expression | int | Float | ComplexFloat | TensorExpression | TensorNetwork | Tensor) -> TensorNetwork

Add two tensor networks element-wise.

Returns

TensorNetwork

A new TensorNetwork representing the sum

Examples

net1 = TensorNetwork(expr1)
net2 = TensorNetwork(expr2)
sum_net = net1 + net2

Parameters

NameTypeDefaultDescription
rhsExpression | int | Float | ComplexFloat | TensorExpression | TensorNetwork | Tensor—

The tensor network to add (right-hand side)

__radd__

Method
#
__radd__(rhs: Expression | int | Float | ComplexFloat | TensorExpression | TensorNetwork | Tensor) -> TensorNetwork

Add two tensor networks element-wise (right-hand addition).

Parameters

NameTypeDefaultDescription
rhsExpression | int | Float | ComplexFloat | TensorExpression | TensorNetwork | Tensor——

__sub__

Method
#
__sub__(rhs: Expression | int | Float | ComplexFloat | TensorExpression | TensorNetwork | Tensor) -> TensorNetwork

Subtract one tensor network from another element-wise.

Returns

TensorNetwork

A new TensorNetwork representing the difference

Examples

net1 = TensorNetwork(expr1)
net2 = TensorNetwork(expr2)
diff_net = net1 - net2

Parameters

NameTypeDefaultDescription
rhsExpression | int | Float | ComplexFloat | TensorExpression | TensorNetwork | Tensor—

The tensor network to subtract (right-hand side)

__rsub__

Method
#
__rsub__(rhs: Expression | int | Float | ComplexFloat | TensorExpression | TensorNetwork | Tensor) -> TensorNetwork

Subtract one tensor network from another (right-hand subtraction).

Parameters

NameTypeDefaultDescription
rhsExpression | int | Float | ComplexFloat | TensorExpression | TensorNetwork | Tensor——

__mul__

Method
#
__mul__(rhs: Expression | int | Float | ComplexFloat | TensorExpression | TensorNetwork | Tensor) -> TensorNetwork

Multiply two tensor networks.

Returns

TensorNetwork

A new TensorNetwork representing the product

Examples

net1 = TensorNetwork(expr1)
net2 = TensorNetwork(expr2)
product_net = net1 * net2

Parameters

NameTypeDefaultDescription
rhsExpression | int | Float | ComplexFloat | TensorExpression | TensorNetwork | Tensor—

The tensor network to multiply with (right-hand side)

__rmul__

Method
#
__rmul__(rhs: Expression | int | Float | ComplexFloat | TensorExpression | TensorNetwork | Tensor) -> TensorNetwork

Multiply two tensor networks (right-hand multiplication).

Parameters

NameTypeDefaultDescription
rhsExpression | int | Float | ComplexFloat | TensorExpression | TensorNetwork | Tensor——

__truediv__

Method
#
__truediv__(rhs: Expression | int | Float | ComplexFloat | TensorExpression | TensorNetwork | Tensor) -> TensorNetwork

No description is available for this member.

Parameters

NameTypeDefaultDescription
rhsExpression | int | Float | ComplexFloat | TensorExpression | TensorNetwork | Tensor——

__rtruediv__

Method
#
__rtruediv__(lhs: Expression | int | Float | ComplexFloat | TensorExpression | TensorNetwork | Tensor) -> TensorNetwork

No description is available for this member.

Parameters

NameTypeDefaultDescription
lhsExpression | int | Float | ComplexFloat | TensorExpression | TensorNetwork | Tensor——

outer

Method
#
outer(rhs: Expression | int | Float | ComplexFloat | TensorExpression | TensorNetwork | Tensor) -> TensorNetwork

Form an outer tensor product without contracting compatible ports.

Parameters

NameTypeDefaultDescription
rhsExpression | int | Float | ComplexFloat | TensorExpression | TensorNetwork | Tensor——

contract

Method
#
contract(rhs: Expression | int | Float | ComplexFloat | TensorExpression | TensorNetwork | Tensor, *, left: int, right: int) -> TensorNetwork

Contract one selected pair of public interface positions.

Parameters

NameTypeDefaultDescription
rhsExpression | int | Float | ComplexFloat | TensorExpression | TensorNetwork | Tensor——
leftint——
rightint——

compose

Method
#
compose(rhs: Expression | int | Float | ComplexFloat | TensorExpression | TensorNetwork | Tensor, *, left: tuple[int, int], right: tuple[int, int]) -> TensorNetwork

Compose two explicitly selected matrix channels.

Parameters

NameTypeDefaultDescription
rhsExpression | int | Float | ComplexFloat | TensorExpression | TensorNetwork | Tensor——
lefttuple[int, int]——
righttuple[int, int]——

dot

Method
#
dot(rhs: Expression | int | Float | ComplexFloat | TensorExpression | TensorNetwork | Tensor) -> TensorNetwork

Contract two rank-one operands into the canonical dot form.

Parameters

NameTypeDefaultDescription
rhsExpression | int | Float | ComplexFloat | TensorExpression | TensorNetwork | Tensor——

trace

Method
#
trace(*, channel: Optional[tuple[int, int]] = None) -> TensorNetwork

Close a selected or uniquely inferred propagation channel.

Parameters

NameTypeDefaultDescription
channelOptional[tuple[int, int]]None—