Idenso · latest
On this page

TensorExpression

symbolica.community.tensor Class

TensorExpression(expression: TensorExpression | _ScalarInput, *, structure: Optional[TensorStructure] = None, intern: Optional[Literal['indices', 'flattened']] = None)

A symbolic tensor expression with an ordered set of external axes.

Construct tensors from TensorName and Representation objects, or wrap a Symbolica expression whose tensor structure can be inferred. Scalar tensors have rank zero. Components are obtained separately through to_tensor.

Products contract matching explicit indices and unambiguous compatible unresolved axes. Use outer to keep axes independent, contract_ports to choose a contraction, or compose to choose matrix channels. Arithmetic with Tensor or TensorNetwork operands returns a TensorNetwork.

Reductions preserve this tensor type and keep unrelated sums factorized. Ordinary algebra, including expand_num(), collect_factors(), and factor(), also returns a tensor expression with its ordered interface. This is a Symbolica Expression subclass: inspection, matching, evaluators, and other unoverridden methods are inherited directly. Inherited transformations return ordinary expressions; the tensor-aware overrides retain the interface. Use to_expression() to explicitly drop the tensor interface.

Pass intern="indices" to reversibly encode unknown function-valued index labels, or intern="flattened" to create readable names. Both modes operate only on index payloads and preserve native index forms. An explicit structure retains the declared axis order and can describe the interface of a symbolic zero.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(3)
A = TensorName("A")(space, space)
indexed = A("i", "j")
indexed.rank

Constructor

#

Wrap symbolic algebra as a tensor and check its external axes.

Returns

TensorExpression

A checked tensor expression, preserving existing metadata where possible.

Examples

from symbolica.community.tensor import TensorExpression, TensorStructure, Representation
zero = TensorExpression(0, structure=TensorStructure([Representation.euc(3)]))
zero.rank
from symbolica import S
from symbolica.community.tensor import TensorName
vector = TensorName.vector("v")(Representation.euc(3))
label, payload = S("i"), S("edge")(7, 2)
raw = vector(label).to_expression().replace(label, payload)
TensorExpression(raw, intern="indices").rank

Parameters

NameTypeDefaultDescription
expressionTensorExpression | _ScalarInput—

Existing tensor, Symbolica Expression, or scalar convertible to one. Tensor syntax is inferred; an ordinary scalar has no external axes.

structureOptional[TensorStructure]None

Canonical free-axis signature to check against the expression. It does not reorder arguments or component axes. For zero, it supplies the rank and axes that cannot be inferred from the scalar expression alone.

internOptional[Literal['indices', 'flattened']]None

Encode unknown function-valued index labels before checking the tensor structure. "indices" retains reversible payloads; "flattened" creates readable names. Both preserve index tags and leave scalar arguments and tensor heads intact. Native index forms, including named, scoped, and open indices, remain unchanged. None accepts native index forms without encoding unknown function labels.

Member details

rank

Property · read-only#
rank: int

Number of external tensor axes.

Returns

int

Zero for a scalar.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(3)
A = TensorName("A")(space, space)
A.rank

is_scalar

Property · read-only#
is_scalar: bool

Whether the tensor has no external axes.

Returns

bool

True exactly when rank is zero.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(3)
A = TensorName("A")(space, space)
A.is_scalar

shape

Property · read-only#
shape: tuple[int | Expression, ...]

Dimensions in logical axis order.

Returns

tuple of int or Expression

Concrete dimensions are integers; symbolic dimensions remain expressions.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(3)
A = TensorName("A")(space, space)
A.shape

axes

Property · read-only#
axes: tuple[Slot | Representation, ...]

External axes in the current component and port-position order.

Returns

tuple of Slot or Representation

Indexed or unresolved axes, respectively. Component coordinates and methods taking axis positions use this order. It follows construction and explicit permute_axes() calls; structure.axes instead gives the canonical signature.

Examples

from symbolica.community.tensor import Representation, TensorName
r = Representation.euc(3)
A = TensorName("A")(r("j"), r("i"))
A.axes == (r("j"), r("i"))
A.permute_axes([1, 0]).axes == A.axes[::-1]

structure

Property · read-only#
structure: TensorStructure

Canonical external signature of the whole expression.

Returns

TensorStructure

Immutable signature in canonical order. Inspect this to determine rank, representations, or existing index labels.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(3)
A = TensorName("A")(space, space)
A.structure.shape

name

Property · read-only#
name: Optional[TensorName]

Optional name identifying stored tensor data.

Returns

TensorName or None

Composite expressions may have no name.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(3)
A = TensorName("A")(space, space)
name = A.name

arguments

Property · read-only#
arguments: tuple[Expression, ...]

Scalar arguments identifying the named tensor.

Returns

tuple of Expression

Scalar key arguments in their original order; empty for an unnamed expression. These belong to the expression, not its external signature.

Examples

from symbolica import S
from symbolica.community.tensor import Representation, TensorName
x = S("x")
A = TensorName("A")(x, 7, Representation.euc(3))
A.arguments == (x, 7)

reduction_status

Property · read-only#
reduction_status: ReductionStatus

Report completion under the last reduction settings and budget.

Returns

ReductionStatus

Complete, Deferred, or Capped. Unfinished results remain exact and can be passed to contract() or simplify_algebra() again.

Examples

from symbolica.community.tensor import TensorExpression, ReductionStatus
TensorExpression(3).contract().reduction_status == ReductionStatus.Complete

contraction_complete

Property · read-only#
contraction_complete: bool

Whether symbolic metric/vector contraction is certified complete.

Returns

bool

False also covers a value not yet contracted or stopped before completion.

Examples

from symbolica.community.tensor import TensorExpression
TensorExpression(3).contract().contraction_complete

g

Static method#
g(rep: Representation | Slot, other: Representation | Slot | None = None) -> TensorExpression

Construct the metric pairing, optionally with explicit indices.

Returns

TensorExpression

The metric with supplied indices in argument order. Representations remain unresolved for later indexing. Matching compatible indices contract, just as when indexing an existing metric.

Raises

ValueError

If the two spaces are neither equal nor dual partners, including when their dimensions differ.

TypeError

If an argument is not a Representation or Slot.

Examples

from symbolica.community.tensor import TensorExpression, Representation
r = Representation.mink(4)
metric = TensorExpression.g(r("mu"), r("nu"))
metric == TensorExpression.g(r)("mu", "nu")
partly_indexed = TensorExpression.g(r("mu"), r)
partly_indexed("nu") == metric
f = Representation.cof(3)
identity = TensorExpression.g(f("i"), f.dual()("j"))
identity.rank

Parameters

NameTypeDefaultDescription
repRepresentation | Slot—

First axis. A representation leaves it unresolved; a slot supplies both its representation and its index.

otherRepresentation | Slot | NoneNone

Second axis. Defaults to an unresolved axis in the first axis's representation, even when the first argument is a slot.

flat

Static method#
flat(rep: Representation) -> TensorExpression

Construct the metric map for raising or lowering an index.

Returns

TensorExpression

A rank-2 symbolic tensor with distinct unresolved axes. Call the result with index labels to fill those axes in the order described below.

Notes

This map accounts for the signs in the representation metric.

Examples

from symbolica.community.tensor import TensorExpression, Representation
tensor = TensorExpression.flat(Representation.mink(4))
tensor.rank

Parameters

NameTypeDefaultDescription
repRepresentation—

Space of both axes.

dirac_gamma

Static method#
dirac_gamma(minkowski_dimension: int | Expression | str) -> TensorExpression

Construct the Dirac gamma matrices for Clifford algebra.

Returns

TensorExpression

A rank-3 symbolic tensor with distinct unresolved axes. Call the result with index labels to fill those axes in the order described below.

Notes

The axes are (spinor row, spinor column, Lorentz index), with four components on each spinor axis. The anticommutator obeys {gamma^mu, gamma^nu} = 2 g^{mu,nu} I. This helper is unrelated to the scalar gamma special function. Explicit library matrices are four-dimensional.

Examples

from symbolica.community.tensor import TensorExpression, Representation
tensor = TensorExpression.dirac_gamma(4)
tensor.rank

Parameters

NameTypeDefaultDescription
minkowski_dimensionint | Expression | str—

Dimension of the Minkowski vector index, for example 4 or a symbol D.

gamma0

Static method#
gamma0(spinor_dimension: int | Expression | str) -> TensorExpression

Construct the time-component Dirac matrix gamma^0.

Returns

TensorExpression

A rank-2 symbolic tensor with distinct unresolved axes. Call the result with index labels to fill those axes in the order described below.

Notes

The two axes are spinor row and column. The HEP libraries provide four-component matrices in the Weyl basis.

Examples

from symbolica.community.tensor import TensorExpression, Representation
tensor = TensorExpression.gamma0(4)
tensor.rank

Parameters

NameTypeDefaultDescription
spinor_dimensionint | Expression | str—

Number of spinor components.

charge_conjugation

Static method#
charge_conjugation(spinor_dimension: int | Expression | str) -> TensorExpression

Construct the Dirac charge-conjugation matrix.

Returns

TensorExpression

A rank-2 symbolic tensor with distinct unresolved axes. Call the result with index labels to fill those axes in the order described below.

Notes

The axes are spinor row and column. The head is antisymmetric. The HEP libraries provide the four-component Weyl-basis convention.

Examples

from symbolica.community.tensor import TensorExpression, Representation
tensor = TensorExpression.charge_conjugation(4)
tensor.rank

Parameters

NameTypeDefaultDescription
spinor_dimensionint | Expression | str—

Number of spinor components.

levi_civita

Static method#
levi_civita(rep: Representation, rank: int = 4) -> TensorExpression

Construct the totally antisymmetric Levi-Civita tensor.

Returns

TensorExpression

A symbolic tensor with rank distinct unresolved axes.

Notes

This constructs symbolic epsilon syntax. It does not populate a component library; rank and space dimension need not be equal for symbolic work.

Examples

from symbolica.community.tensor import TensorExpression, Representation
tensor = TensorExpression.levi_civita(Representation.euc(3), rank=3)
tensor.rank

Parameters

NameTypeDefaultDescription
repRepresentation—

Space of every axis.

rankint4

Number of axes, independent of the representation dimension.

expand_projectors

Method#
expand_projectors() -> TensorExpression

Expand normalized factor groups into their permutation sums.

Returns

TensorExpression

Tensor algebra with symmetric, antisymmetric, and cyclic groups expanded. Other sums and products remain factored.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
from symbolica.community.tensor import FactorProjector, trace
expression = trace(space, FactorProjector.symmetric(A, A))
expression.expand_projectors().is_scalar

gamma5

Static method#
gamma5(spinor_dimension: int | Expression | str) -> TensorExpression

Construct the Dirac chirality matrix gamma^5.

Returns

TensorExpression

A rank-2 symbolic tensor with distinct unresolved axes. Call the result with index labels to fill those axes in the order described below.

Notes

The axes are spinor row and column. The HEP libraries provide the four-component Weyl-basis chirality matrix.

Examples

from symbolica.community.tensor import TensorExpression, Representation
tensor = TensorExpression.gamma5(4)
tensor.rank

Parameters

NameTypeDefaultDescription
spinor_dimensionint | Expression | str—

Number of spinor components.

projm

Static method#
projm(spinor_dimension: int | Expression | str) -> TensorExpression

Construct the left-chiral Dirac projector (I - gamma^5)/2.

Returns

TensorExpression

A rank-2 symbolic tensor with distinct unresolved axes. Call the result with index labels to fill those axes in the order described below.

Notes

The two axes are spinor row and column. This is a projector on spinors, not a FactorProjector for permuting tensor factors.

Examples

from symbolica.community.tensor import TensorExpression, Representation
tensor = TensorExpression.projm(4)
tensor.rank

Parameters

NameTypeDefaultDescription
spinor_dimensionint | Expression | str—

Number of spinor components.

projp

Static method#
projp(spinor_dimension: int | Expression | str) -> TensorExpression

Construct the right-chiral Dirac projector (I + gamma^5)/2.

Returns

TensorExpression

A rank-2 symbolic tensor with distinct unresolved axes. Call the result with index labels to fill those axes in the order described below.

Notes

The two axes are spinor row and column. This is a projector on spinors, not a FactorProjector for permuting tensor factors.

Examples

from symbolica.community.tensor import TensorExpression, Representation
tensor = TensorExpression.projp(4)
tensor.rank

Parameters

NameTypeDefaultDescription
spinor_dimensionint | Expression | str—

Number of spinor components.

sigma

Static method#
sigma(minkowski_dimension: int | Expression | str) -> TensorExpression

Construct the antisymmetric Dirac sigma tensor.

Returns

TensorExpression

A rank-4 symbolic tensor with distinct unresolved axes. Call the result with index labels to fill those axes in the order described below.

Notes

The logical axes are (mu, nu, spinor row, spinor column). Both spinor axes have dimension four.

Examples

from symbolica.community.tensor import TensorExpression, Representation
tensor = TensorExpression.sigma(4)
tensor.rank

Parameters

NameTypeDefaultDescription
minkowski_dimensionint | Expression | str—

Dimension of each Minkowski vector index.

color_f

Static method#
color_f(adjoint_dimension: int | Expression | str) -> TensorExpression

Construct the antisymmetric color structure constants f^{abc}.

Returns

TensorExpression

A rank-3 symbolic tensor with distinct unresolved axes. Call the result with index labels to fill those axes in the order described below.

Notes

The axes are three adjoint indices (a, b, c). This dimension is the number of generators, not the dimension of the fundamental representation.

Examples

from symbolica.community.tensor import TensorExpression, Representation
tensor = TensorExpression.color_f(8)
tensor.rank

Parameters

NameTypeDefaultDescription
adjoint_dimensionint | Expression | str—

Dimension of the adjoint representation, for example 8 for SU(3).

color_t

Static method#
color_t(adjoint_dimension: int | Expression | str, fundamental_dimension: int | Expression | str) -> TensorExpression

Construct the fundamental color generators T^a.

Returns

TensorExpression

A rank-3 symbolic tensor with distinct unresolved axes. Call the result with index labels to fill those axes in the order described below.

Notes

The axes are (adjoint, fundamental, antifundamental). The HEP libraries provide SU(3) generators; symbolic color identities retain representation invariants unless their substitution is requested.

Examples

from symbolica.community.tensor import TensorExpression, Representation
tensor = TensorExpression.color_t(8, 3)
tensor.rank

Parameters

NameTypeDefaultDescription
adjoint_dimensionint | Expression | str—

Adjoint dimension, for example 8 for SU(3).

fundamental_dimensionint | Expression | str—

Fundamental dimension, for example 3 for SU(3).

with_name

Method#
with_name(name: TensorName | str | Expression | TensorExpression) -> TensorExpression

Assign a data identity without rewriting the symbolic computation.

Returns

TensorExpression

A new value with the requested identity and the same axes.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
named = A.with_name("named_matrix")
named.rank

Parameters

NameTypeDefaultDescription
nameTensorName | str | Expression | TensorExpression—

New tensor name. A rank-zero atomic TensorExpression may also supply scalar key arguments, for example TensorName("B")(7).

__len__

Method#
__len__() -> int

Count all components in the tensor shape.

Returns

int

Product of the axis dimensions, including implicit zeros; dimensions must be concrete.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
len(A)

to_expression

Method#
to_expression() -> Expression

Return ordinary Symbolica algebra without the tensor interface.

Returns

Expression

The underlying expression. Axis metadata is no longer carried by the result; operations on it are ordinary Symbolica operations.

Notes

TensorExpression already inherits Expression. Convert when deliberately requesting ordinary Symbolica behavior, including replacements that change the tensor interface, rather than its tensor-aware overrides.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
raw = A.to_expression()

is_zero

Method#
is_zero() -> bool

Test whether the expression is exactly zero, including zeros with nonzero tensor rank. This does not perform algebraic simplification.

Returns

bool

True for an exact symbolic zero, irrespective of rank.

Examples

from symbolica.community.tensor import TensorName, Representation
A = TensorName("A")(Representation.euc(3))("i")
assert (0 * A).is_zero()
assert (0 * A).rank == 1

is_one

Method#
is_one() -> bool

Test whether the expression is exactly the scalar one.

Returns

bool

True for scalar one; an identity tensor is not the scalar one.

Examples

from symbolica.community.tensor import TensorExpression
assert TensorExpression(1).is_one()

is_expanded

Method#
is_expanded(var: Optional[_ScalarInput] = None) -> bool

Test whether products and powers are expanded, optionally with respect to var. The expression and its tensor interface are unchanged.

Returns

bool

True if no further arithmetic distribution is needed for the requested scope.

Examples

from symbolica import S
from symbolica.community.tensor import TensorExpression
x = S("x")
value = TensorExpression((x + 1)**2)
assert not value.is_expanded()
assert value.expand().is_expanded(x)

Parameters

NameTypeDefaultDescription
varOptional[_ScalarInput]None

Restrict the expansion check to this indeterminate.

nterms

Method#
nterms() -> int

Count top-level additive terms without expanding the expression. Unlike len(tensor), this counts symbolic terms rather than tensor components.

Returns

int

Number of terms in the outermost sum, or one for a non-sum.

Examples

from symbolica import S
from symbolica.community.tensor import TensorExpression
x = S("x")
value = TensorExpression((x + 1)**2)
assert value.nterms() == 1
assert value.expand().nterms() == 3

replace

Method#
replace(pattern: TensorRule | list[TensorRule] | _ScalarInput, rhs: Optional[_ReplacementInput] = None, cond: Optional[PatternRestriction | Condition] = None, non_greedy_wildcards: Optional[Sequence[Expression]] = None, min_level: int = 0, max_level: Optional[int] = None, level_is_tree_depth: bool = False, partial: bool = True, allow_new_wildcards_on_rhs: bool = False, rhs_cache_size: Optional[int] = None, repeat: bool = False, once: bool = False, bottom_up: bool = False, nested: bool = False) -> TensorExpression

Replace symbolic patterns or apply whole-tensor replacement rules.

Returns

TensorExpression

Rewritten value retaining its checked tensor interface and metadata.

Examples

from symbolica import S
from symbolica.community.tensor import Representation, TensorName, TensorRule
A = TensorName("M")(Representation.euc(2))("i")
x, y = S("x", "y")
assert (x * A).replace(x, y) == y * A
assert A.replace(TensorRule(A, 2 * A)) == 2 * A

Parameters

NameTypeDefaultDescription
patternTensorRule | list[TensorRule] | _ScalarInput—

Symbolica pattern when rhs is supplied. Without rhs, apply prepared TensorRules in priority order, leaving scalar key arguments opaque.

rhsOptional[_ReplacementInput]None

Symbolica replacement, including callbacks. The result must preserve the tensor's ordered interface. Use reindex() to change external labels.

condOptional[PatternRestriction | Condition]None

Restriction on a symbolic match.

non_greedy_wildcardsOptional[Sequence[Expression]]None

Wildcards whose matches should be selected non-greedily.

min_levelint0

Inclusive traversal bounds, starting at zero.

max_levelOptional[int]None

Inclusive traversal bounds, starting at zero.

level_is_tree_depthboolFalse

Count expression-tree levels rather than function nesting.

partialboolTrue

Allow matches inside larger expressions.

allow_new_wildcards_on_rhsboolFalse

Allow wildcard symbols that do not occur in the pattern.

rhs_cache_sizeOptional[int]None

Cache repeated symbolic replacements; zero disables caching.

repeatboolFalse

Symbolica's replacement traversal controls. Prepared TensorRules own their conditions and cache settings and do not accept these options.

onceboolFalse

Symbolica's replacement traversal controls. Prepared TensorRules own their conditions and cache settings and do not accept these options.

bottom_upboolFalse

Symbolica's replacement traversal controls. Prepared TensorRules own their conditions and cache settings and do not accept these options.

nestedboolFalse

Symbolica's replacement traversal controls. Prepared TensorRules own their conditions and cache settings and do not accept these options.

replace_multiple

Method#
replace_multiple(replacements: Sequence[Replacement], repeat: bool = False, once: bool = False, bottom_up: bool = False, nested: bool = False) -> TensorExpression

Apply simultaneous Symbolica replacements and validate the resulting tensor.

Returns

TensorExpression

Rewritten value preserving ordered ports, metadata, and typed zeros.

Examples

from symbolica import S, Replacement
from symbolica.community.tensor import Representation, TensorName
x, y = S("x", "y")
A = TensorName("A")(Representation.euc(3))("i")
assert (x*A).replace_multiple([Replacement(x, y)]) == y*A

Parameters

NameTypeDefaultDescription
replacementsSequence[Replacement]—

Symbolica replacements, including their conditions and callbacks.

repeatboolFalse

Traversal controls with the same meaning as Expression.replace_multiple.

onceboolFalse

Traversal controls with the same meaning as Expression.replace_multiple.

bottom_upboolFalse

Traversal controls with the same meaning as Expression.replace_multiple.

nestedboolFalse

Traversal controls with the same meaning as Expression.replace_multiple.

map

Method#
map(op: Transformer, n_cores: Optional[int] = None, stats_to_file: Optional[str] = None) -> TensorExpression

Apply a Symbolica Transformer and retain the validated tensor interface.

Returns

TensorExpression

Transformed expression with its original ordered tensor interface.

Examples

from symbolica import S, T
from symbolica.community.tensor import Representation, TensorName
x = S("x")
A = TensorName("A")(Representation.euc(3))("i")
result = ((x + 1)**2 * A).map(T().expand())
assert result == ((x + 1)**2 * A).expand()

Parameters

NameTypeDefaultDescription
opTransformer—

Transformations to apply, including user callbacks.

n_coresOptional[int]None

Number of cores for Symbolica's term mapping.

stats_to_fileOptional[str]None

JSON output file for the transformer's statistics.

derivative

Method#
derivative(x: _ScalarInput) -> TensorExpression

Differentiate scalar coefficients, preserving tensor zeros and ports. Formal derivatives of unknown tensor functions are not supported by the network executor. Differentiate their component expressions with Tensor.map_components() instead, or supply a TensorName derivative callback.

Returns

TensorExpression

Derivative with the same ordered external ports, even when zero.

Examples

from symbolica import S
from symbolica.community.tensor import Representation, TensorName
x = S("x")
A = TensorName("A")(Representation.euc(3))("i")
assert (x**2 * A).derivative(x) == 2*x*A
assert A.derivative(x).rank == A.rank

Parameters

NameTypeDefaultDescription
x_ScalarInput—

Scalar differentiation variable.

expand

Method#
expand(var: Optional[_ScalarInput] = None, via_poly: Optional[bool] = None) -> TensorExpression

Distribute scalar products and powers over sums.

Returns

TensorExpression

Expanded algebra with a checked tensor interface.

Notes

Label unresolved axes before expansion when their identities cannot be tracked through a rewritten sum. Expansion can enlarge expressions. Tensor simplifiers do not generally require expanding the whole expression first.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
from symbolica import S
x = S("x")
expanded = ((x + 1)**2 * A("i", "j")).expand()
expanded.rank

Parameters

NameTypeDefaultDescription
varOptional[_ScalarInput]None

Restrict expansion to terms involving this expression. None expands throughout the expression.

via_polyOptional[bool]None

Use Symbolica's polynomial-based expansion when True. Defaults to False. With a selector, a result that would divide by a non-numeric factor is recomputed by ordinary expansion instead, which can group the terms in the selector differently.

factor

Method#
factor(complex: bool = False, extension: Optional[Sequence[_ScalarInput]] = None) -> TensorExpression

Factor scalar algebra while retaining ordered tensor ports and data metadata. Tensor leaves are treated as symbolic indeterminates; no tensor identity is applied.

Returns

TensorExpression

Factored expression with the original tensor interface, including typed zeros.

Examples

from symbolica import S
from symbolica.community.tensor import TensorName, Representation
x = S("x")
A = TensorName("A")(Representation.euc(3))("i")
factored = ((x**2 + 2*x + 1) * A).factor()
assert factored == (x + 1)**2 * A

Parameters

NameTypeDefaultDescription
complexboolFalse

Factor over the complex rationals rather than the rationals.

extensionOptional[Sequence[_ScalarInput]]None

Algebraic numbers defining the coefficient field, as in Expression.factor.

expand_num

Method#
expand_num() -> TensorExpression

Distribute numerical coefficients over sums without expanding symbolic products. The result remains a TensorExpression with the same ordered ports and metadata.

Returns

TensorExpression

Rewritten scalar algebra with the original tensor interface and metadata.

Examples

from symbolica import S
from symbolica.community.tensor import TensorName, Representation
x, y = S("x", "y")
A = TensorName("A")(Representation.euc(3))("i")
result = (2 * (x + y) * A).expand_num()
assert result == (2*x + 2*y) * A

collect

Method#
collect(*x: symbolica.core.Expression, key_map: Optional[Callable[[symbolica.core.Expression], symbolica.core.Expression]] = None, coeff_map: Optional[Callable[[symbolica.core.Expression], symbolica.core.Expression]] = None) -> TensorExpression

Collect terms in variables or functions, retaining the tensor interface.

Returns

TensorExpression

Collected expression with the original interface and metadata.

Examples

from symbolica import S
from symbolica.community.tensor import TensorName, Representation
x, y = S("x", "y")
A = TensorName("A")(Representation.euc(3))("i")
result = (x*A + x*y*A).collect(x)
assert result.expand() == (x*(1+y)*A).expand()

Parameters

NameTypeDefaultDescription
xsymbolica.core.Expression——
key_mapOptional[Callable[[symbolica.core.Expression], symbolica.core.Expression]]None

Map each collected key or coefficient. Callbacks receive and return ordinary Expressions. Their results must preserve this tensor's ordered external ports; otherwise the operation raises ValueError. Zero retains the original interface.

coeff_mapOptional[Callable[[symbolica.core.Expression], symbolica.core.Expression]]None

Map each collected key or coefficient. Callbacks receive and return ordinary Expressions. Their results must preserve this tensor's ordered external ports; otherwise the operation raises ValueError. Zero retains the original interface.

collect_num

Method#
collect_num() -> TensorExpression

Extract common numerical coefficients from sums, retaining ordered ports and metadata. This reverses numerical distribution performed by expand_num().

Returns

TensorExpression

Expression with common numerical coefficients extracted.

Examples

from symbolica import S
from symbolica.community.tensor import TensorName, Representation
x, y = S("x", "y")
A = TensorName("A")(Representation.euc(3))("i")
assert ((2*x + 4*y)*A).collect_num() == 2*(x + 2*y)*A

collect_factors

Method#
collect_factors() -> TensorExpression

Collect common factors from nested sums without applying tensor identities. Ordered ports, unresolved axes, tensor zeros, and data metadata are retained.

Returns

TensorExpression

Rewritten scalar algebra with the original tensor interface and metadata.

Examples

from symbolica import S
from symbolica.community.tensor import TensorName, Representation
x, y = S("x", "y")
A = TensorName("A")(Representation.euc(3))("i")
result = (x*A + y*A).collect_factors()
assert result == (x+y)*A

collect_by_coefficient

Method#
collect_by_coefficient() -> TensorExpression

Group terms with equal numerical coefficients, retaining ordered ports and metadata.

Returns

TensorExpression

Expression grouped by numerical coefficient with the original tensor interface.

Examples

from symbolica import S
from symbolica.community.tensor import TensorExpression
x, y = S("x", "y")
result = TensorExpression(2*x + 2*y).collect_by_coefficient()
assert result.to_expression() == 2*(x + y)

collect_symbol

Method#
collect_symbol(x: Expression, key_map: Optional[Callable[[symbolica.core.Expression], symbolica.core.Expression]] = None, coeff_map: Optional[Callable[[symbolica.core.Expression], symbolica.core.Expression]] = None) -> TensorExpression

Collect terms by powers of a variable or calls with the same function head.

Returns

TensorExpression

Collected expression with the original interface and metadata.

Examples

from symbolica import S
from symbolica.community.tensor import TensorName, Representation
x, f = S("x", "f")
A = TensorName("A")(Representation.euc(3))("i")
result = (f(x)*A + 2*f(x)*A).collect_symbol(f)
assert result.expand() == (3*f(x)*A).expand()

Parameters

NameTypeDefaultDescription
xExpression—

Variable or function symbol to collect in.

key_mapOptional[Callable[[symbolica.core.Expression], symbolica.core.Expression]]None

Map ordinary Expressions. As with collect(), the result is checked for preservation of the tensor's ordered external ports.

coeff_mapOptional[Callable[[symbolica.core.Expression], symbolica.core.Expression]]None

Map ordinary Expressions. As with collect(), the result is checked for preservation of the tensor's ordered external ports.

collect_horner

Method#
collect_horner(vars: Optional[Sequence[Expression]] = None) -> TensorExpression

Rewrite polynomial algebra in Horner form, retaining ordered ports and metadata.

Returns

TensorExpression

Horner-form expression with the original tensor interface.

Examples

from symbolica import S
from symbolica.community.tensor import TensorExpression
x, y = S("x", "y")
result = TensorExpression(x**2 + x*y).collect_horner([x, y])
assert result.to_expression() == x*(x + y)

Parameters

NameTypeDefaultDescription
varsOptional[Sequence[Expression]]None

Variable order. Omit it to use Symbolica's heuristic ordering.

together

Method#
together() -> TensorExpression

Combine scalar denominators into one fraction, retaining ordered ports and metadata. This is ordinary rational algebra and performs no tensor contractions.

Returns

TensorExpression

Single rational expression with the original tensor interface.

Examples

from symbolica import S
from symbolica.community.tensor import TensorExpression
x, y = S("x", "y")
assert TensorExpression(1/x + 1/y).together().to_expression() == (x + y)/(x*y)

cancel

Method#
cancel() -> TensorExpression

Cancel common numerator and denominator factors, retaining ordered ports and metadata. This is ordinary rational algebra and performs no tensor contractions.

Returns

TensorExpression

Rational expression with common factors cancelled and the original tensor interface.

Examples

from symbolica import S
from symbolica.community.tensor import TensorName, Representation
x = S("x")
A = TensorName("A")(Representation.euc(3))("i")
assert ((x**2 - 1)/(x - 1)*A).cancel() == (x + 1)*A

apart

Method#
apart(*variables: symbolica.core.Expression) -> TensorExpression

Decompose scalar denominators into partial fractions, retaining the tensor interface.

Returns

TensorExpression

Partial fractions with the original ordered ports and metadata.

Examples

from symbolica import S
from symbolica.community.tensor import TensorName, Representation
x = S("x")
A = TensorName("A")(Representation.euc(3))("i")
assert (A/(x*(x + 1))).apart(x) == A/x - A/(x + 1)

Parameters

NameTypeDefaultDescription
variablessymbolica.core.Expression——

__copy__

Method#
__copy__() -> TensorExpression

Copy the expression and its tensor metadata.

Returns

TensorExpression

A copy with the same ordered axes and optional data name.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
import copy
copy.copy(A).shape

__deepcopy__

Method#
__deepcopy__(memo: dict) -> TensorExpression

Copy the tensor's immutable expression, ordered axes, and data metadata.

Returns

TensorExpression

Independent Python wrapper sharing the immutable tensor value.

Examples

import copy
from symbolica.community.tensor import Representation, TensorName
A = TensorName("A")(Representation.euc(3))
zero = 0 * A
assert copy.deepcopy(zero).structure == zero.structure

Parameters

NameTypeDefaultDescription
memodict—

Copy bookkeeping maintained by Python's copy module.

__reduce__

Method#
__reduce__() -> NoReturn

Reject pickling that would silently discard the ordered tensor interface. Use to_expression() when explicitly serializing only the symbolic algebra.

Raises

TypeError

Tensor metadata serialization is not supported.

with_lorentz_dimension

Method#
with_lorentz_dimension(dimension: int | Expression | str) -> TensorExpression

Replace four-dimensional Minkowski index spaces by a supplied dimension.

Returns

TensorExpression

Updated explicit slots and compact representation arguments.

Notes

Spinor and color dimensions, scalar coefficients, and Minkowski spaces with dimensions other than four are unchanged. Apply this before performing contractions that have already replaced four-dimensional traces by numbers.

Examples

from symbolica import S
from symbolica.community.tensor import TensorExpression
gamma = TensorExpression.dirac_gamma(4).with_lorentz_dimension(S("D"))
gamma.shape[:2]

Parameters

NameTypeDefaultDescription
dimensionint | Expression | str—

New Lorentz dimension, such as a symbol D. An Expression must be a single symbol.

simplify_algebra

Method#
simplify_algebra(*, gamma: bool = True, color: bool = True, epsilon: bool = False, contract: Literal['fully', 'minimal', 'dots', 'selected', 'none'] = "fully", representations: Optional[Sequence[Representation | RepresentationName]] = None, collect_coefficients: bool = True, gamma_output: Optional[Literal['reduced', 'chains']] = None, gamma_ordering: Optional[Literal['repeated_pairs', 'canonical']] = None, gamma_evaluate_traces: Optional[bool] = None, gamma0: Optional[bool] = None, gamma_conjugate: Optional[bool] = None, gamma_expand_three_gamma_epsilon: Optional[bool] = None, color_evaluate_traces: Optional[bool] = None, color_expand_fierz: Optional[bool] = None, color_substitute_cof_dimension_invariants: Optional[bool] = None, max_steps_per_domain: Optional[int] = None) -> TensorExpression

Reduce enabled tensor identities and their required index contractions.

Gamma and color identities are enabled by default; epsilon identities are opt-in. The default also completes supported structural contractions, so a second contract() call is normally unnecessary. The input is unchanged.

Returns

TensorExpression

A typed result carrying its checked interface and reduction_status. No alias wrapper or separate materialization step is required.

Raises

ValueError

An option value is invalid, representations is missing or used with the wrong mode, a family-specific option is supplied for a disabled family, or a rewrite cannot produce a valid tensor interface.

Notes

Select the families together; the shared planner schedules identities and contractions until no further permitted work is found. Under "fully" and "dots", a closed color delta produces its dimension even with color=False. Under "none", an unrelated Lorentz numerator can remain indexed and factored after its color sector is reduced. Use contract() for structural work alone.

This is not a global arithmetic expansion. Planning starts with a shallow view of factor interfaces and opens selected regions when needed. Necessary local distribution and identity-generated sums are allowed; unrelated sums and scalar coefficients stay factored. Request expand() explicitly when the final output must be a fully expanded polynomial.

Dimensions belong to the tensor representations. Set them before reduction, for example with with_lorentz_dimension(D). Ordinary Clifford contractions support compatible symbolic Lorentz dimensions. Four-dimensional gamma5, axial-trace and epsilon-basis rules are not a general D-dimensional gamma5 prescription; changing D after evaluation cannot recover lost dimension factors.

Family-specific None values use the defaults documented above. Even an explicitly supplied False option requires its family to be enabled. Reusable configurations are ordinary dictionaries passed with **options.

Inspect reduction_status on the returned reduction result. Complete means no eligible work remains under these settings, not under disabled families or other output requirements. Deferred retains exact work the current implementation could not finish. Capped means an explicit limit stopped it. Rerunning a Complete result with the same settings is stable. Capped or Deferred results can be passed back for further work, without a guarantee that an unsupported Deferred case will progress. contraction_complete is a separate structural certificate and can be False for a Complete "none" result.

See Also

contract : Structural contractions without enabling identities. to_dots : Change surviving scalar-product notation without contracting indices. expand : Explicit arithmetic distribution. undo_trace : Unfold an existing trace without evaluating it.

Examples

A closed Dirac word evaluates to 4*D even with no additional structural pass. The spinor dimension remains four while the Lorentz dimension is D.

from symbolica import E, S
from symbolica.community import tensor as sp
D = S("algebra_docs::D")
gamma = sp.TensorExpression.dirac_gamma(4).with_lorentz_dimension(D)
word = gamma("a", "b", "mu") * gamma("b", "a", "mu")
result = word.simplify_algebra(color=False, contract="none")
assert result.to_expression() == 4 * D
assert result.reduction_status == sp.ReductionStatus.Complete

Retain nested identity output when that form is preferable. Both requests represent the same tensor and leave unrelated scalar prefactors factored.

nested = word.simplify_algebra(color=False, collect_coefficients=False)
assert (nested - result).expand().to_expression() == 0

Color-only reduction with explicit SU(3) invariants gives T^a T^a = 4/3 I. Omit the invariant-substitution option to retain symbolic Casimirs.

fundamental = sp.Representation.cof(3)
identity = sp.TensorExpression.g(fundamental, fundamental.dual())
T = sp.TensorExpression.color_t(8, 3)
pair = T("a", "i", "j") * T("a", "j", "k")
color_only = dict(gamma=False, color=True, contract="none",
                  color_substitute_cof_dimension_invariants=True)
assert pair.simplify_algebra(**color_only) == E("4/3") * identity("i", "k")

Structural color-delta contraction is independent of color identities. With both identity families disabled, "none" preserves this product; "fully" and a matching "selected" filter produce its dimension.

cycle = identity("i", "j") * identity("j", "i")
structural = dict(gamma=False, color=False)
assert cycle.simplify_algebra(**structural, contract="none") == cycle
assert cycle.simplify_algebra(**structural).to_expression() == 3
selected = cycle.simplify_algebra(**structural, contract="selected",
                                   representations=[fundamental.name])
assert selected.to_expression() == 3
assert cycle.simplify_algebra(**structural, contract="selected",
                              representations=[]) == cycle

"dots" includes scalar-product notation conversion. Epsilon reduction is separately enabled; here the Euclidean identity epsilon_ijk epsilon_ijk = 6 is evaluated without gamma or color identities.

lorentz = sp.Representation.mink(4)
p = sp.TensorName.vector("algebra_docs::p")(lorentz)
q = sp.TensorName.vector("algebra_docs::q")(lorentz)
dotted = (p("mu") * q("mu")).simplify_algebra(**structural, contract="dots")
assert dotted == sp.dot(p, q)
epsilon = sp.TensorExpression.levi_civita(sp.Representation.euc(3), rank=3)
product = epsilon("i", "j", "k") * epsilon("i", "j", "k")
assert product.simplify_algebra(**structural, epsilon=True).to_expression() == 6

Minimal contraction leaves a product of tensor sums exact and factorized. It can report Complete even though full contraction would do more work. The equivalent structural-only request is contract(expand=False).

metric = sp.TensorExpression.g(lorentz)
A = sp.TensorName("algebra_docs::A")(lorentz, lorentz)
factored = (metric("mu", "nu") + A("mu", "nu")) * (p("mu") + q("mu"))
minimal = factored.simplify_algebra(**structural, contract="minimal")
assert minimal == factored
assert minimal.reduction_status == sp.ReductionStatus.Complete
assert minimal == factored.contract(expand=False)
assert minimal != factored.contract()

An explicit limit preserves the exact remaining expression. Continue by calling the same operation without a limit; no manual expansion is needed.

pending = cycle.simplify_algebra(**structural, max_steps_per_domain=0)
assert pending.reduction_status == sp.ReductionStatus.Capped
assert pending == cycle
assert pending.simplify_algebra(**structural).to_expression() == 3

Parameters

NameTypeDefaultDescription
gammaboolTrue

Enable Dirac/Clifford and color identities, respectively. Each family authorizes the structural contractions required to apply its identities. Set the other families to False when requesting only one family.

colorboolTrue

Enable Dirac/Clifford and color identities, respectively. Each family authorizes the structural contractions required to apply its identities. Set the other families to False when requesting only one family.

epsilonboolFalse

Enable supported Levi-Civita pair contractions and their prerequisites. These can generate determinant sums. Epsilon tensors emitted by gamma reduction do not implicitly enable this option. Intrinsic antisymmetry normalization during construction is independent of this setting.

contractLiteral['fully', 'minimal', 'dots', 'selected', 'none']"fully"

Structural work in addition to enabled identities and their prerequisites: - "fully": contract compatible metrics/identities and vectors, collect matrix chains, and close compatible chains into trace notation. - "dots": the same work, plus canonical dot notation for scalar products. - "minimal": perform structural contractions that do not multiply out independent sum alternatives. Boundary substitutions through existing sums and contractions within their branches are allowed. Products of sums stay factored when contracting them would require distribution. - "selected": the same structural operations, restricted to connections in representations. This does not restrict identity prerequisites. - "none": no additional structural pass. Enabled identities still get their prerequisite contractions; this does not disable all contraction. These modes do not enable identity families. In particular, collecting a trace does not evaluate it, and contracting a color delta does not apply a generator or Fierz identity. "minimal" restricts additional structural work; enabled algebra identities retain their prerequisites and can still introduce sums. It is not a global ban on expansion.

representationsOptional[Sequence[Representation | RepresentationName]]None

Required with contract="selected" and rejected with the other modes. Select connecting representation families, including their duals, rather than whole tensor factors. For example, Representation.mink(4) selects the Minkowski family, including symbolic-D instances; it does not change dimensions. Each connection must still have compatible dimensions and orientation. [] permits no additional index contractions or trace closure. Identity prerequisites and existing constructor normalization are unaffected.

collect_coefficientsboolTrue

Collect generated exact coefficients in contracted Dirac traces and their bound vector factors so equal terms combine and cancel. Includes Symbolica's expand_num() distribution of numerical factors over sums inside those generated coefficients. False retains their nested, factored output. Other family kernels retain their existing coefficient normalization. This is not global expansion: unrelated input sums and scalar prefactors remain factorized. It neither expands free Dirac traces nor reverses simplification already performed.

gamma_outputOptional[Literal['reduced', 'chains']]None

Defaults to "reduced": apply supported Clifford and trace identities. "chains" collects Dirac chains/traces without Clifford reduction or trace evaluation, even if gamma_evaluate_traces=True. Explicit gamma0 and gamma_conjugate preparation still applies when requested.

gamma_orderingOptional[Literal['repeated_pairs', 'canonical']]None

Ordering for reduced open Dirac chains. The default "repeated_pairs" brings repeated indices together without fully sorting unrelated matrices. "canonical" orders the chain and can introduce metric-term sums through anticommutation. It is inactive for gamma_output="chains".

gamma_evaluate_tracesOptional[bool]None

Evaluate supported closed Dirac traces with reduced output; defaults to True. False retains trace notation while other enabled identities remain available. Trace normalization follows the spinor representation dimension.

gamma0Optional[bool]None

Apply gamma-zero factoring before chain collection; defaults to False. This controls the preparation pass, not every gamma-zero identity already included in reduced Dirac algebra.

gamma_conjugateOptional[bool]None

Rewrite explicitly complex-conjugated Dirac matrices before collection; defaults to False. This does not conjugate the input tensor.

gamma_expand_three_gamma_epsilonOptional[bool]None

With reduced output, expand three compatible four-dimensional gammas in a gamma5/epsilon basis; defaults to False. This can introduce sums and epsilon tensors, but does not enable epsilon identities.

color_evaluate_tracesOptional[bool]None

Evaluate supported closed color traces; defaults to True. False retains unevaluated traces, but enabled Fierz identities may still join or change them. It does not disable the rest of color algebra.

color_expand_fierzOptional[bool]None

Apply fundamental Fierz identities between different open chains or traces; defaults to True. This may introduce sums. False disables these cross-chain expansions, not every color identity or source of sums.

color_substitute_cof_dimension_invariantsOptional[bool]None

Write supported color invariants in terms of the fundamental SU(N) dimension, with T_F=1/2; defaults to False, retaining symbolic invariants. In the supported fundamental/adjoint spaces this gives C_F=(N**2-1)/(2*N) and C_A=N. The dimension comes from the representation: this does not set every color space to SU(3) or reduce arbitrary groups.

max_steps_per_domainOptional[int]None

Optional nonnegative limit on successful planner transformations in each active expression domain. None imposes no automatic work limit. This is not a bound on time, memory, terms, or work inside one kernel. Zero leaves eligible work untouched and reports Capped; an already completed request can still report Complete. Unfinished results remain exact.

wrap_indices

Method#
wrap_indices(header: Expression, *, dummies_only: bool = False) -> TensorExpression

Give explicit indices a scope that separates them from other copies.

Returns

TensorExpression

Scoped indices with the same internal contraction relationships.

Notes

Applying the same outer scope twice is idempotent; different scopes nest. Alphabet display uses primed labels for scoped copies. This is useful when multiplying independently summed expressions or an amplitude and its adjoint.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
from symbolica import S
scoped = A("i", "j").wrap_indices(S("bra"))
scoped.rank

Parameters

NameTypeDefaultDescription
headerExpression—

A single Symbolica symbol naming the scope.

dummies_onlyboolFalse

Scope only contracted indices, leaving external labels unchanged.

list_dangling

Method#
list_dangling() -> list[Expression]

List the external indices that are not summed over.

Returns

list of Expression

Representation-aware index expressions, in logical order when all axes are labeled. Dual indices retain their dual wrapper.

Notes

For unresolved axes, prefer structure.axes to inspect the interface.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
len(A("i", "j").list_dangling())

canonize

Method#
canonize() -> TensorExpression

Canonicalize tensor factors and dummy-index labels.

Returns

TensorExpression

An equivalent expression with deterministically named contracted indices.

Raises

CanonicalizationError

The tensor expression cannot be canonicalized.

Notes

This identifies different spellings of the same dummy-index contractions; it is not a general polynomial simplifier.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
canonical = A("i", "j").canonize()
canonical.rank

dirac_adjoint

Method#
dirac_adjoint(*, preserve_indices: bool = False) -> TensorExpression

Construct the Dirac adjoint of a spinor tensor expression.

Returns

TensorExpression

The complex conjugate with reversed spinor chains and the gamma^0 boundary factors required by a Dirac adjoint.

Raises

DiracAdjointError

The index structure does not admit a consistent Dirac adjoint.

Notes

The expression must use the registered Dirac representation and tensor forms. This operation is specialized to Dirac spinors; it is not an ordinary transpose of arbitrary tensor components.

Examples

from symbolica.community.tensor import TensorName, Representation
spinor = TensorName("psi")(Representation.bis(4)("a"))
spinor.dirac_adjoint().rank

Parameters

NameTypeDefaultDescription
preserve_indicesboolFalse

Keep external labels on their original physical legs. False uses matrix-adjoint ordering and exchanges open-chain endpoints.

to_dots

Method#
to_dots() -> TensorExpression

Write compact metric products using dot notation.

Returns

TensorExpression

An equivalent value in the requested notation.

Notes

This changes notation; it does not itself contract explicit vector indices. Use contract() first when those contractions are needed.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
converted = A.to_dots()

undo_dots

Method#
undo_dots() -> TensorExpression

Write dot products as explicit indexed contractions.

Returns

TensorExpression

An equivalent value in the requested notation.

Notes

Other compact forms and factored sums are retained. This does not evaluate component data or expand a polynomial.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
converted = A.undo_dots()

undo_chain

Method#
undo_chain() -> TensorExpression

Expose collected chain factors with fresh compatible dummy indices.

Returns

TensorExpression

Equivalent algebra in the requested notation.

Notes

This changes notation without distributing polynomial sums or requesting Dirac/color identities. Use undo_trace().undo_chain() to expose indexed trace factors.

Examples

from symbolica.community.tensor import Representation, TensorName, chain, trace
space = Representation.euc(2)
A = TensorName("M")(space, space)
expression = chain(space("i"), space("j"), A, A)
opened = expression.undo_chain()

undo_trace

Method#
undo_trace() -> TensorExpression

Open compact traces as closed chains without evaluating them.

Returns

TensorExpression

Equivalent algebra in the requested notation.

Notes

This changes notation without distributing polynomial sums or requesting Dirac/color identities. Use undo_trace().undo_chain() to expose indexed trace factors.

Examples

from symbolica.community.tensor import Representation, TensorName, chain, trace
space = Representation.euc(2)
A = TensorName("M")(space, space)
expression = trace(space, A, A)
opened = expression.undo_trace()

to_network

Method#
to_network(library: Optional[TensorLibrary] = None) -> TensorNetwork

Build an executable network for this symbolic tensor.

Returns

TensorNetwork

A new network with the same external axes. Construction does not execute its contractions.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
network = A.to_network()
network.rank

Parameters

NameTypeDefaultDescription
libraryOptional[TensorLibrary]None

Component definitions. Defaults to the built-in four-dimensional Dirac and SU(3) library. Unregistered tensors receive symbolic components.

to_tensor

Method#
to_tensor(library: Optional[TensorLibrary] = None, *, function_library: Optional[TensorFunctionLibrary] = None) -> Tensor

Evaluate this expression and return its components.

Returns

Tensor

Resulting components in logical axis order. Dimensions must be concrete.

Notes

The original expression and the supplied libraries are unchanged.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
A.to_tensor().shape

Parameters

NameTypeDefaultDescription
libraryOptional[TensorLibrary]None

Component definitions. Defaults to the built-in four-dimensional Dirac and SU(3) library. Unregistered tensors receive symbolic components.

function_libraryOptional[TensorFunctionLibrary]None

Numerical implementations of broadcast functions. Defaults to the built-in function library.

components

Method#
components(library: Optional[TensorLibrary] = None) -> list[Expression | complex | float]

Evaluate this tensor and return its flat component list.

Returns

list of Expression, float, or complex

Components in logical row-major order; one element for a scalar. Dimensions must be concrete.

Notes

Unregistered tensors receive symbolic components. Relabeling abstract indices does not change those component identities.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
len(A.components())

Parameters

NameTypeDefaultDescription
libraryOptional[TensorLibrary]None

Component definitions. Defaults to the built-in four-dimensional Dirac and SU(3) library. Unregistered tensors receive symbolic components.

index

Method#
index(*indices: _IndexInput, intern: Optional[Literal['indices', 'flattened']] = None) -> TensorExpression

Assign labels to the unresolved external axes.

Returns

TensorExpression

An indexed expression.

Notes

Existing explicit labels are left in place. Use reindex to replace them.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
indexed = A.index("i", "j")
indexed.rank

Parameters

NameTypeDefaultDescription
indices_IndexInput——
internOptional[Literal['indices', 'flattened']]None

Encode unknown function-valued index labels before checking the tensor structure. "indices" retains reversible payloads; "flattened" creates readable names. Both preserve index tags and leave scalar arguments and tensor heads intact. Native index forms, including named, scoped, and open indices, remain unchanged. None accepts native index forms without encoding unknown function labels.

reindex

Method#
reindex(*indices: _IndexInput, intern: Optional[Literal['indices', 'flattened']] = None) -> TensorExpression

Assign labels to all external axes.

Returns

TensorExpression

An indexed expression.

Notes

Existing labels are replaced as well as unresolved axes.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
indexed = A.reindex("i", "j")
indexed.rank

Parameters

NameTypeDefaultDescription
indices_IndexInput——
internOptional[Literal['indices', 'flattened']]None

Encode unknown function-valued index labels before checking the tensor structure. "indices" retains reversible payloads; "flattened" creates readable names. Both preserve index tags and leave scalar arguments and tensor heads intact. Native index forms, including named, scoped, and open indices, remain unchanged. None accepts native index forms without encoding unknown function labels.

rename_indices

Method#
rename_indices(mapping: dict[int | str | Expression | Slot, _IndexInput], *, intern: Optional[Literal['indices', 'flattened']] = None) -> TensorExpression

Rename selected external labels without changing the tensor rank.

Returns

TensorExpression

A new value with renamed axes; the original is unchanged.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
indexed = A.index("i", "j")
renamed = indexed.rename_indices({"i": "k"})
renamed.rank

Parameters

NameTypeDefaultDescription
mappingdict[int | str | Expression | Slot, _IndexInput]—

Old label to new label. A Slot key also restricts the representation. Keys must identify existing external axes. Each axis may be renamed once; renaming must preserve the external interface.

internOptional[Literal['indices', 'flattened']]None

Encode unknown function-valued index labels before checking the tensor structure. "indices" retains reversible payloads; "flattened" creates readable names. Both preserve index tags and leave scalar arguments and tensor heads intact. Native index forms, including named, scoped, and open indices, remain unchanged. None accepts native index forms without encoding unknown function labels.

permute_axes

Method#
permute_axes(axes: Sequence[int]) -> TensorExpression

Reorder the external axes in logical component order.

Returns

TensorExpression

A new tensor view with the reordered interface.

Notes

This permutes axes; it does not conjugate component values.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
transposed = A.permute_axes([1, 0])
transposed.shape

Parameters

NameTypeDefaultDescription
axesSequence[int]—

Each current axis position exactly once, in the desired new order. For a matrix, [1, 0] exchanges the two axes.

__call__

Method#
__call__(*indices: _IndexInput, intern: Optional[Literal['indices', 'flattened']] = None) -> TensorExpression:  # type: ignore[override]  # ty: ignore[invalid-method-override]

Assign labels to the unresolved external axes.

Returns

TensorExpression

An indexed expression.

Notes

Equivalent to index(*indices).

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
indexed = A("i", "j")
indexed.rank

Parameters

NameTypeDefaultDescription
indices_IndexInput——
internOptional[Literal['indices', 'flattened']]None

Encode unknown function-valued index labels before checking the tensor structure. "indices" retains reversible payloads; "flattened" creates readable names. Both preserve index tags and leave scalar arguments and tensor heads intact. Native index forms, including named, scoped, and open indices, remain unchanged. None accepts native index forms without encoding unknown function labels.

__neg__

Method#
__neg__() -> TensorExpression

Negate every tensor component.

Returns

TensorExpression

Negated symbolic algebra with the same external axes.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
negated = -A

__pow__

Method#
__pow__(exponent: TensorExpression | _ScalarInput, modulo: Optional[Any] = None) -> TensorExpression:  # type: ignore[override]  # ty: ignore[invalid-method-override]

Raise tensor algebra to a scalar power.

Returns

TensorExpression

Powered tensor expression. A non-scalar base requires a nonnegative integer exponent and uses repeated tensor multiplication, including its contraction and ambiguity rules. This is not an elementwise power.

Examples

from symbolica.community.tensor import TensorExpression
squared = TensorExpression(3)**2
squared.to_expression() == 9

Parameters

NameTypeDefaultDescription
exponentTensorExpression | _ScalarInput—

Scalar exponent.

moduloOptional[Any]None

Must be None; modular tensor powers are not supported.

__rpow__

Method#
__rpow__(base: TensorExpression | _ScalarInput, modulo: Optional[Any] = None) -> TensorExpression

Use a scalar tensor expression as an exponent.

Returns

TensorExpression

Scalar power with a checked tensor interface.

Examples

from symbolica.community.tensor import TensorExpression
result = 2**TensorExpression(3)
result.to_expression() == 8

Parameters

NameTypeDefaultDescription
baseTensorExpression | _ScalarInput—

Scalar base.

moduloOptional[Any]None

Must be None; modular powers are not supported.

__eq__

Method#
__eq__(other: Any) -> bool

Compare normalized expressions and their ordered tensor interfaces for equality. For a comparison to a plain Symbolica expression, first use .to_expression().

Examples

from symbolica.community import tensor as sp
r = sp.Representation.euc(2)
A = sp.TensorName("docs::A")(r, r)
assert A == sp.TensorExpression(A)

Parameters

NameTypeDefaultDescription
otherAny—

TensorExpression to compare. Values without an ordered tensor interface are unequal.

__ne__

Method#
__ne__(other: Any) -> bool

Test whether normalized expressions or their ordered tensor interfaces differ.

Examples

from symbolica.community import tensor as sp
r = sp.Representation.euc(2)
A = sp.TensorName("docs::A")(r, r)
assert A != 2 * A

Parameters

NameTypeDefaultDescription
otherAny—

TensorExpression to compare. Values without an ordered tensor interface are unequal.

__hash__

Method#
__hash__() -> int

Hash the immutable tensor value for use in dictionaries and sets. Equal tensor expressions have equal hashes, including their ordered interfaces.

Examples

from symbolica.community import tensor as sp
r = sp.Representation.euc(2)
A = sp.TensorName("docs::A")(r, r)
labels = {A: "matrix A"}
assert labels[sp.TensorExpression(A)] == "matrix A"

__bool__

Method#
__bool__() -> bool

Test whether the symbolic tensor expression is nonzero.

Examples

from symbolica.community import tensor as sp
r = sp.Representation.euc(2)
A = sp.TensorName("docs::A")(r, r)
nonzero = bool(A)

contract

Method#
contract(*, representations: Optional[Sequence[Representation | RepresentationName]] = None, metrics: bool = True, rank_one: bool = True, collect_chains: bool = True, collect_traces: bool = True, expand: bool = True, order: Optional[Sequence[int]] = None, max_steps_per_domain: Optional[int] = None) -> TensorExpression

Contract compatible indices without applying tensor-algebra identities.

Eliminate metrics and identity tensors, including closed dimension factors; substitute vectors into compatible ports; form scalar products; and collect ordered matrix chains and unevaluated traces. Matrix order and orientation are preserved. The input is unchanged.

Returns

TensorExpression

A typed result with its checked external interface and reduction_status. Unrelated scalar coefficients and sums remain factored. No alias wrapper or separate materialization step is required.

Raises

ValueError

order is not a permutation of all normalized top-level factors, or a substitution cannot produce a valid tensor interface.

Notes

Contracting a color delta does not enable generator or Fierz identities. Collecting a Dirac or color trace does not evaluate it. Use simplify_algebra() for identities, contract_ports(rhs, left=..., right=...) for an explicit binary port contraction, and to_tensor() for component-library evaluation. With rank_one=False, collect_chains=False and collect_traces=False, only metric/identity contraction is requested.

Planning starts with a depth-one view of factor interfaces. It opens a selected region only when the contraction needs its interior, reusing unchanged leaves and known interfaces. With expand=True, necessary local distribution is allowed; an unrelated scalar sum is not routinely expanded. Internal dummy contractions can be processed even inside a scalar-interface leaf. This is distinct from expanding the whole expression with expand().

Settings do not undo intrinsic normalization performed during construction. A metric with identical compatible ports can already be its dimension, typed vector multiplication can already form a scalar product, and symmetric dot arguments are already ordered. representations=[] and disabled flags preserve these existing normalizations. Assign explicit compatible indices before requesting a particular Einstein contraction; unresolved axes are distinct port identities, not dummy indices to pair by guesswork.

Scalar products can remain in compact metric notation g(p(R), q(R)). to_dots() converts that surviving notation to dot(p(R), q(R)) without searching for repeated indices. undo_dots(), undo_chain() and undo_trace() unfold existing notation with fresh compatible dummy indices, preserving matrix order. They do not recover expressions already changed by identities.

Complete means no eligible work remains under the requested settings; disabled contractions and unevaluated traces may remain. Deferred retains exact work the current implementation could not finish. Capped means an explicit work limit stopped the operation. Completed reruns with the same settings are stable. Unfinished results can be passed back to contract(), possibly with different settings; unsupported cases need not make progress. Inspect this operation's reduction_status before other transformations. contraction_complete is a separate structural certificate, not a substitute for completion under a restricted representation filter or expand=False.

See Also

simplify_algebra : Gamma, color and epsilon identities plus their contractions. contract_ports : Explicit binary contraction of selected logical ports. to_dots : Scalar-product notation conversion without index contraction. undo_trace : Turn trace notation into a closed indexed chain. expand : Explicit arithmetic distribution.

Examples

A metric relabels a vector. A Lorentz-only filter also permits a metric to enter a gamma matrix without touching its two spinor ports.

from symbolica import S
from symbolica.community import tensor as sp
lorentz = sp.Representation.mink(4)
metric = sp.TensorExpression.g(lorentz)
p = sp.TensorName.vector("contract_docs::p")(lorentz)
source = metric("mu", "nu") * p("nu")
assert source.contract() == p("mu")
gamma = sp.TensorExpression.dirac_gamma(4)
mixed = gamma("a", "b", "nu") * metric("mu", "nu")
assert mixed.contract(representations=[lorentz]) == gamma("a", "b", "mu")

Trace collection and trace evaluation are separate operations. The collected trace represents the same tensor as 4*g(mu,nu), but contract() leaves it unevaluated. Unfolding and contracting it recovers the collected notation.

word = gamma("a", "b", "mu") * gamma("b", "a", "nu")
collected = word.contract()
assert collected.simplify_algebra(color=False) == 4 * metric("mu", "nu")
assert collected.undo_trace().undo_chain().contract() == collected
uncollected = word.contract(collect_traces=False)
assert uncollected.contract() == collected

A supplied spinor remains attached when collecting an open gamma word. Only the unresolved spinor slot remains an external axis.

spinor = sp.Representation.bis(4)
psi = sp.TensorName.vector("contract_docs::psi")(spinor)
word = psi("a") * gamma("a", "b", "mu") * p("mu") * gamma("b", sp.AUTO, "nu") * p("nu")
collected = word.contract()
assert collected.rank == 1
assert collected.contract() == collected

A closed color delta gives N_c without any color-algebra identity. An empty filter retains this product, and an unrelated scalar power remains factored.

Nc = S("contract_docs::Nc")
fundamental = sp.Representation.cof(Nc)
delta = sp.TensorExpression.g(fundamental, fundamental.dual())
cycle = delta("i", "j") * delta("j", "i")
assert cycle.contract().to_expression() == Nc
assert cycle.contract(representations=[]) == cycle
x, y = S("contract_docs::x", "contract_docs::y")
assert ((x + y)**8 * cycle).contract().to_expression() == (x + y)**8 * Nc

Minimal contraction still relabels ports through a sum. It leaves products of independent tensor sums factorized instead of enumerating their pairings.

q = sp.TensorName.vector("contract_docs::q")(lorentz)
A = sp.TensorName("contract_docs::A")(lorentz, lorentz)
relabel = metric("mu", "nu") * (p("nu") + q("nu"))
assert relabel != p("mu") + q("mu")
assert relabel.contract(expand=False) == p("mu") + q("mu")
product = (metric("mu", "nu") + A("mu", "nu")) * (p("mu") + q("mu"))
minimal = product.contract(expand=False)
assert minimal == product
assert minimal.reduction_status == sp.ReductionStatus.Complete
full = product.contract()
assert minimal != full
assert minimal.contract() == full

An explicit zero limit retains eligible work exactly. Continuing without that limit completes it, while the original input remains available.

pending = cycle.contract(max_steps_per_domain=0)
assert pending.reduction_status == sp.ReductionStatus.Capped
assert pending == cycle
assert pending.contract().to_expression() == Nc

Parameters

NameTypeDefaultDescription
representationsOptional[Sequence[Representation | RepresentationName]]None

Filter connections by representation family: None permits all, [] none. Families include dual representations. For example, Representation.mink(4) permits the Minkowski family, including symbolic-D slots; the 4 is not a dimension filter. Each connection must still satisfy dimension and orientation compatibility. Matching representation names alone is insufficient. The filter acts on connecting ports, not whole tensor factors: a Lorentz connection can enter a gamma matrix while its spinor ports survive. Chain assembly and trace closure also require a permitted connection.

metricsboolTrue

Eliminate compatible metric/identity tensors by index substitution and evaluate closed metric loops to their representation dimension.

rank_oneboolTrue

Substitute vectors into compatible tensor ports (Schoonschip notation) and contract vector pairs into scalar products. This can enter a gamma matrix without applying a gamma identity. False retains those connections.

collect_chainsboolTrue

Represent connected matrix products as ordered chains without evaluating their matrices, including words with supplied rank-one endpoints. Supplied endpoints do not add external axes. False retains the indexed factors for open products.

collect_tracesboolTrue

Represent compatible closed matrix products as unevaluated traces. False retains indexed closure, including when collect_chains=True. It does not unfold trace notation already present in the input.

expandboolTrue

Permit local arithmetic distribution required by a selected contraction. False performs the minimal structural work: substitute at boundaries and contract within existing sum branches, but do not multiply out independent sum alternatives. A product of tensor sums can therefore remain indexed and still be Complete under expand=False. Neither value requests global polynomial expansion; expand() is a separate operation.

orderOptional[Sequence[int]]None

Optional zero-based permutation of every normalized top-level factor, used for the initial contraction round. Factors follow Symbolica's normalized order, not necessarily the order in the Python source. None lets the planner choose. This affects scheduling, never matrix order; omit it unless you need to prescribe a factor order explicitly.

max_steps_per_domainOptional[int]None

Optional nonnegative limit on successful planner transformations in each active expression domain. None imposes no automatic work limit. This is not a limit on time, memory, generated terms, or work inside one kernel. Zero preserves eligible work and reports Capped; a request with no eligible work can still report Complete. All unfinished results remain exact.

trace

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

Close a pair of matrix axes on this tensor.

Returns

TensorExpression

The traced tensor; spectator axes remain external.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
A.trace(channel=(0, 1)).is_scalar

Parameters

NameTypeDefaultDescription
channelOptional[tuple[int, int]]None

(input_axis, output_axis) to contract. If omitted, the matrix channel must be uniquely determined by the representations. Specify it when more than one pairing is possible.

format_tensor

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

Produce compact plain-text tensor notation.

Returns

str

Readable tensor text, suitable for logs or terminal output.

Notes

Only ports layout and default spacing are supported in this source format. Use to_html() or to_svg() for other layouts and custom gaps.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
output = A.format_tensor()

Parameters

NameTypeDefaultDescription
show_dimensionsOptional[bool]None

Override settings.show_dimensions for this call. None retains the selected settings, whose default omits dimensions.

settingsOptional[DisplaySettings]None

Tensor notation and display choices. Defaults to DisplaySettings().

to_latex

Method#
to_latex(max_line_length: Optional[int] = None, *, settings: Optional[DisplaySettings] = None) -> str

Produce LaTeX for the symbolic tensor expression.

Returns

str

LaTeX tensor notation, including the enclosing math delimiters.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
source = A.to_latex()

Parameters

NameTypeDefaultDescription
max_line_lengthOptional[int]None

Requested line-length bound for the printer. None leaves it unbounded.

settingsOptional[DisplaySettings]None

Index labels, dimensions and invariant notation. Defaults to DisplaySettings(). Only ports layout and default spacing are supported.

to_typst

Method#
to_typst(show_dimensions: Optional[bool] = None, *, settings: Optional[DisplaySettings] = None) -> str:  # type: ignore[override]  # ty: ignore[invalid-method-override]

Produce static Typst math source.

Returns

str

Typst source without an enclosing document; no compilation is performed.

Notes

Only ports layout and default spacing are supported in this source format. Use to_html() or to_svg() for other layouts and custom gaps.

Static Typst output remains available independently of the HTML explorer.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
output = A.to_typst()

Parameters

NameTypeDefaultDescription
show_dimensionsOptional[bool]None

Override settings.show_dimensions for this call. None retains the selected settings, whose default omits dimensions.

settingsOptional[DisplaySettings]None

Tensor notation and display choices. Defaults to DisplaySettings().

to_typst_project

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

Export a customizable Typst project without running a compiler.

Returns

dict[str, bytes]

main.typ, render.typ, notation.typ, and the portable tree.cbor payload. Write each file's bytes beneath one project directory. Compile main.typ with that directory as the compiler root, for example using typst.compile(project_dir / "main.typ", root=project_dir).

Notes

All rich layouts are supported. The optional Python package typst is needed only to compile the returned project.

# Errors

Returns a Python exception if payload export fails. Registered Python printer exceptions are logged and decline the override, allowing native fallback.

Examples

from symbolica.community.tensor import TensorExpression
project = TensorExpression(1).to_typst_project()

Parameters

NameTypeDefaultDescription
show_dimensionsOptional[bool]None

Override settings.show_dimensions for this call.

settingsOptional[DisplaySettings]None

Tensor notation, layout, and spacing choices.

notation_sourceOptional[str]None

Replacement notation.typ source; defaults to the bundled notation.

formatted

Method#
formatted(show_dimensions: Optional[bool] = None, *, settings: Optional[DisplaySettings] = None, notation_source: Optional[str] = None) -> FormattedOutput:  # type: ignore[override]  # ty: ignore[invalid-method-override]

Create a lazy rich display value for a notebook.

Returns

FormattedOutput

Small expressions render once per backend; large notebook displays use bounded pages.

Notes

Automatic representations of large expressions are bounded previews. Paging retains factorization and ordered ports; explicit exports remain complete. Settings are captured here; custom printers run on the first request for each backend. Create a new formatted value after changing printers.

# Errors

Returns ValueError for Typst notation or incomplete MathML. Registered Python printer exceptions are logged and decline the override, allowing native fallback.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
output = A.formatted()

Parameters

NameTypeDefaultDescription
show_dimensionsOptional[bool]None

Override settings.show_dimensions for this call. None retains the selected settings, whose default omits dimensions.

settingsOptional[DisplaySettings]None

Tensor notation and display choices. Defaults to DisplaySettings().

notation_sourceOptional[str]None

Unsupported for HTML and notebook output; raises ValueError. Use to_typst_project() or to_svg() for custom Typst notation.

paged

Method#
paged(page_size: Optional[int] = None, *, settings: Optional[DisplaySettings] = None, notation_source: Optional[str] = None) -> Any

Create a bounded, interactive MathML viewer in marimo or Jupyter.

Only the current page is rendered. Nested expressions retain their factorization, and omitted subexpressions can be opened independently. Requires the optional notebook-display dependencies for live navigation.

Returns

object

Notebook viewer retaining the expression and rendering pages on demand. Display it in marimo or Jupyter to navigate its widget. # Errors Returns ValueError for Typst notation or an invalid page size; viewer failures propagate. Registered Python printer exceptions are logged and decline the override, allowing native fallback.

Examples

from symbolica.community.tensor import TensorExpression
viewer = TensorExpression(1).paged()

Parameters

NameTypeDefaultDescription
page_sizeOptional[int]None

None uses automatic previews: compact products may be shown completely, with 25 entries per page otherwise. An explicit size sets the maximum entries per page, between 1 and 500. Rendering budgets may show fewer.

settingsOptional[DisplaySettings]None

Tensor notation, index labels, and other presentation preferences.

notation_sourceOptional[str]None

Unsupported by the direct MathML pager. Use to_typst_project() or to_svg() for custom Typst notation; paging raises ValueError when supplied.

_display_

Method#
_display_() -> Any

Return marimo's notebook presentation with bounded pages for large expressions.

Returns

object

Rich notebook output or an interactive viewer, using default settings.

_repr_mimebundle_

Method#
_repr_mimebundle_(include: Optional[Sequence[str]] = None, exclude: Optional[Sequence[str]] = None) -> Any

Return the rich representations requested by a Jupyter frontend.

Returns

object

MIME bundle for the complete small expression or paged large expression.

Parameters

NameTypeDefaultDescription
includeOptional[Sequence[str]]None

MIME types to include or exclude from the returned representations.

excludeOptional[Sequence[str]]None

MIME types to include or exclude from the returned representations.

to_html

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

Render the tensor as an HTML fragment.

Returns

str

Self-contained output fragment for an HTML-capable notebook or page.

Notes

Mathematical rendering uses direct MathML and requires no Typst compiler. The complete expression is exported; oversized output raises an error. Pass the returned string to the notebook's HTML display facility.

# Errors

Returns ValueError for Typst notation or incomplete MathML. Registered Python printer exceptions are logged and decline the override, allowing native fallback.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
output = A.to_html()

Parameters

NameTypeDefaultDescription
show_dimensionsOptional[bool]None

Override settings.show_dimensions for this call. None retains the selected settings, whose default omits dimensions.

settingsOptional[DisplaySettings]None

Tensor notation and display choices. Defaults to DisplaySettings().

notation_sourceOptional[str]None

Unsupported for HTML and notebook output; raises ValueError. Use to_typst_project() or to_svg() for custom Typst notation.

to_svg

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

Render static mathematical tensor notation to SVG.

Returns

str

SVG markup suitable for embedding or saving to a file.

Notes

SVG export uses the optional Python package typst (typst-py). Pass the returned markup to the notebook's SVG display facility.

# Errors

Returns ImportError if optional typst-py is unavailable, or RuntimeError if compilation fails. Registered Python printer exceptions are logged and decline the override, allowing native fallback.

Examples

from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
output = A.to_svg()

Parameters

NameTypeDefaultDescription
show_dimensionsOptional[bool]None

Override settings.show_dimensions for this call. None retains the selected settings, whose default omits dimensions.

settingsOptional[DisplaySettings]None

Tensor notation and display choices. Defaults to DisplaySettings().

notation_sourceOptional[str]None

Custom Typst notation source used by the rich renderer. This is Typst code, not a filename; omit it for the supplied tensor notation.

__repr__

Method#
__repr__() -> str

Return a readable object description for inspection.

Examples

from symbolica.community import tensor as sp
r = sp.Representation.euc(2)
A = sp.TensorName("docs::A")(r, r)
text = repr(A)

__str__

Method#
__str__() -> str

Return a readable text representation.

Examples

from symbolica.community import tensor as sp
r = sp.Representation.euc(2)
A = sp.TensorName("docs::A")(r, r)
text = str(A)

_repr_pretty_

Method#
_repr_pretty_(pretty: Any, cycle: bool) -> None

No description is available for this member.

Parameters

NameTypeDefaultDescription
prettyAny——
cyclebool——

_repr_html_

Method#
_repr_html_() -> Optional[str]: ...  # type: ignore[override]  # ty: ignore[invalid-method-override]

No description is available for this member.

_repr_latex_

Method#
_repr_latex_() -> str

No description is available for this member.

__add__

Method#

Overloads

Overload 1 #
__add__(rhs: TensorExpression | _ScalarInput) -> TensorExpression

Add tensors with compatible external interfaces.

Returns

TensorExpression or TensorNetwork

Symbolic operands return TensorExpression; component-bearing operands return TensorNetwork.

Notes

Scalar zero acts as the additive identity. Other scalars can be added only to rank-zero tensors.

Examples
from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
result = A + A
Parameters
NameTypeDefaultDescription
rhsTensorExpression | _ScalarInput—

Other operand. Component data are retained in a lazy network.

Overload 2 #
__add__(rhs: Union[Tensor, TensorNetwork]) -> TensorNetwork

Add tensors with compatible external interfaces.

Returns

TensorExpression or TensorNetwork

Symbolic operands return TensorExpression; component-bearing operands return TensorNetwork.

Notes

Scalar zero acts as the additive identity. Other scalars can be added only to rank-zero tensors.

Examples
from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
result = A + A
Parameters
NameTypeDefaultDescription
rhsUnion[Tensor, TensorNetwork]—

Other operand. Component data are retained in a lazy network.

__radd__

Method#

Overloads

Overload 1 #
__radd__(lhs: TensorExpression | _ScalarInput) -> TensorExpression

Implement reflected addition.

Returns

TensorExpression or TensorNetwork

Symbolic operands return TensorExpression; component-bearing operands return TensorNetwork.

Notes

Scalar zero acts as the additive identity. Other scalars can be added only to rank-zero tensors.

Examples
from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
result = A + A
Parameters
NameTypeDefaultDescription
lhsTensorExpression | _ScalarInput—

Other operand. Component data are retained in a lazy network.

Overload 2 #
__radd__(lhs: Union[Tensor, TensorNetwork]) -> TensorNetwork

Implement reflected addition.

Returns

TensorExpression or TensorNetwork

Symbolic operands return TensorExpression; component-bearing operands return TensorNetwork.

Notes

Scalar zero acts as the additive identity. Other scalars can be added only to rank-zero tensors.

Examples
from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
result = A + A
Parameters
NameTypeDefaultDescription
lhsUnion[Tensor, TensorNetwork]—

Other operand. Component data are retained in a lazy network.

__sub__

Method#

Overloads

Overload 1 #
__sub__(rhs: TensorExpression | _ScalarInput) -> TensorExpression

Subtract tensors with compatible external interfaces.

Returns

TensorExpression or TensorNetwork

Symbolic operands return TensorExpression; component-bearing operands return TensorNetwork.

Notes

Subtraction requires matching tensor axes; a nonzero scalar cannot be subtracted from a tensor with external axes.

Examples
from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
result = A - A
Parameters
NameTypeDefaultDescription
rhsTensorExpression | _ScalarInput—

Other operand. Component data are retained in a lazy network.

Overload 2 #
__sub__(rhs: Union[Tensor, TensorNetwork]) -> TensorNetwork

Subtract tensors with compatible external interfaces.

Returns

TensorExpression or TensorNetwork

Symbolic operands return TensorExpression; component-bearing operands return TensorNetwork.

Notes

Subtraction requires matching tensor axes; a nonzero scalar cannot be subtracted from a tensor with external axes.

Examples
from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
result = A - A
Parameters
NameTypeDefaultDescription
rhsUnion[Tensor, TensorNetwork]—

Other operand. Component data are retained in a lazy network.

__rsub__

Method#

Overloads

Overload 1 #
__rsub__(lhs: TensorExpression | _ScalarInput) -> TensorExpression

Implement reflected subtraction.

Returns

TensorExpression or TensorNetwork

Symbolic operands return TensorExpression; component-bearing operands return TensorNetwork.

Notes

Subtraction requires matching tensor axes; a nonzero scalar cannot be subtracted from a tensor with external axes.

Examples
from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
result = A - A
Parameters
NameTypeDefaultDescription
lhsTensorExpression | _ScalarInput—

Other operand. Component data are retained in a lazy network.

Overload 2 #
__rsub__(lhs: Union[Tensor, TensorNetwork]) -> TensorNetwork

Implement reflected subtraction.

Returns

TensorExpression or TensorNetwork

Symbolic operands return TensorExpression; component-bearing operands return TensorNetwork.

Notes

Subtraction requires matching tensor axes; a nonzero scalar cannot be subtracted from a tensor with external axes.

Examples
from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
result = A - A
Parameters
NameTypeDefaultDescription
lhsUnion[Tensor, TensorNetwork]—

Other operand. Component data are retained in a lazy network.

__mul__

Method#

Overloads

Overload 1 #
__mul__(rhs: TensorExpression | _ScalarInput) -> TensorExpression

Multiply tensors, contracting unambiguous compatible axes.

Returns

TensorExpression or TensorNetwork

Symbolic operands return TensorExpression; component-bearing operands return TensorNetwork.

Notes

Matching explicit labels contract. Compatible unresolved axes are paired to maximize the number of contractions. Among equally complete pairings, unresolved-unresolved pairs take precedence over unresolved-named pairs; equally preferred alternatives raise an ambiguity error. Established matrix channels retain their composition order. Use outer(), contract_ports(), or compose() to make the intended pairing explicit.

Automatic dot notation requires both operands to be calls to rank-one-tagged heads, created with TensorName.vector(). Rank alone does not select a dot: generic rank-one tensors and composite expressions retain their indexed contractions. Use contract() to pack them into Schoonschip notation, or dot() to request a scalar-product notation explicitly.

Examples
from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
result = A * 2
from symbolica.community.tensor import dot
p = TensorName.vector("product_p")(space)
q = TensorName.vector("product_q")(space)
assert p * q == dot(p, q)
Parameters
NameTypeDefaultDescription
rhsTensorExpression | _ScalarInput—

Other operand. Component data are retained in a lazy network.

Overload 2 #
__mul__(rhs: Union[Tensor, TensorNetwork]) -> TensorNetwork

Multiply tensors, contracting unambiguous compatible axes.

Returns

TensorExpression or TensorNetwork

Symbolic operands return TensorExpression; component-bearing operands return TensorNetwork.

Notes

Matching explicit labels contract. Compatible unresolved axes are paired to maximize the number of contractions. Among equally complete pairings, unresolved-unresolved pairs take precedence over unresolved-named pairs; equally preferred alternatives raise an ambiguity error. Established matrix channels retain their composition order. Use outer(), contract_ports(), or compose() to make the intended pairing explicit.

Automatic dot notation requires both operands to be calls to rank-one-tagged heads, created with TensorName.vector(). Rank alone does not select a dot: generic rank-one tensors and composite expressions retain their indexed contractions. Use contract() to pack them into Schoonschip notation, or dot() to request a scalar-product notation explicitly.

Examples
from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
result = A * 2
from symbolica.community.tensor import dot
p = TensorName.vector("product_p")(space)
q = TensorName.vector("product_q")(space)
assert p * q == dot(p, q)
Parameters
NameTypeDefaultDescription
rhsUnion[Tensor, TensorNetwork]—

Other operand. Component data are retained in a lazy network.

__rmul__

Method#

Overloads

Overload 1 #
__rmul__(lhs: TensorExpression | _ScalarInput) -> TensorExpression

Implement reflected multiplication.

Returns

TensorExpression or TensorNetwork

Symbolic operands return TensorExpression; component-bearing operands return TensorNetwork.

Notes

Matching explicit labels contract. Compatible unresolved axes are paired to maximize the number of contractions. Among equally complete pairings, unresolved-unresolved pairs take precedence over unresolved-named pairs; equally preferred alternatives raise an ambiguity error. Established matrix channels retain their composition order. Use outer(), contract_ports(), or compose() to make the intended pairing explicit.

Automatic dot notation follows __mul__(): both operands must be calls to rank-one-tagged heads created with TensorName.vector().

Examples
from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
result = 2 * A
Parameters
NameTypeDefaultDescription
lhsTensorExpression | _ScalarInput—

Other operand. Component data are retained in a lazy network.

Overload 2 #
__rmul__(lhs: Union[Tensor, TensorNetwork]) -> TensorNetwork

Implement reflected multiplication.

Returns

TensorExpression or TensorNetwork

Symbolic operands return TensorExpression; component-bearing operands return TensorNetwork.

Notes

Matching explicit labels contract. Compatible unresolved axes are paired to maximize the number of contractions. Among equally complete pairings, unresolved-unresolved pairs take precedence over unresolved-named pairs; equally preferred alternatives raise an ambiguity error. Established matrix channels retain their composition order. Use outer(), contract_ports(), or compose() to make the intended pairing explicit.

Automatic dot notation follows __mul__(): both operands must be calls to rank-one-tagged heads created with TensorName.vector().

Examples
from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
result = 2 * A
Parameters
NameTypeDefaultDescription
lhsUnion[Tensor, TensorNetwork]—

Other operand. Component data are retained in a lazy network.

__truediv__

Method#

Overloads

Overload 1 #
__truediv__(rhs: TensorExpression | _ScalarInput) -> TensorExpression

Divide tensor components by a scalar expression.

Returns

TensorExpression or TensorNetwork

Symbolic operands return TensorExpression; component-bearing operands return TensorNetwork.

Notes

The denominator must be scalar. For scalar divided by tensor, the tensor must also have rank zero.

Examples
from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
result = A / 2
Parameters
NameTypeDefaultDescription
rhsTensorExpression | _ScalarInput—

Other operand. Component data are retained in a lazy network.

Overload 2 #
__truediv__(rhs: Union[Tensor, TensorNetwork]) -> TensorNetwork

Divide tensor components by a scalar expression.

Returns

TensorExpression or TensorNetwork

Symbolic operands return TensorExpression; component-bearing operands return TensorNetwork.

Notes

The denominator must be scalar. For scalar divided by tensor, the tensor must also have rank zero.

Examples
from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
result = A / 2
Parameters
NameTypeDefaultDescription
rhsUnion[Tensor, TensorNetwork]—

Other operand. Component data are retained in a lazy network.

__rtruediv__

Method#

Overloads

Overload 1 #
__rtruediv__(lhs: TensorExpression | _ScalarInput) -> TensorExpression

Implement reflected division.

Returns

TensorExpression or TensorNetwork

Symbolic operands return TensorExpression; component-bearing operands return TensorNetwork.

Notes

The denominator must be scalar. For scalar divided by tensor, the tensor must also have rank zero.

Examples
from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
result = 2 / TensorExpression(3)
Parameters
NameTypeDefaultDescription
lhsTensorExpression | _ScalarInput—

Other operand. Component data are retained in a lazy network.

Overload 2 #
__rtruediv__(lhs: Union[Tensor, TensorNetwork]) -> TensorNetwork

Implement reflected division.

Returns

TensorExpression or TensorNetwork

Symbolic operands return TensorExpression; component-bearing operands return TensorNetwork.

Notes

The denominator must be scalar. For scalar divided by tensor, the tensor must also have rank zero.

Examples
from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
result = 2 / TensorExpression(3)
Parameters
NameTypeDefaultDescription
lhsUnion[Tensor, TensorNetwork]—

Other operand. Component data are retained in a lazy network.

outer

Method#

Overloads

Overload 1 #
outer(rhs: TensorExpression | Expression) -> TensorExpression

Form an outer product without implicit contractions between the operands.

Returns

TensorExpression or TensorNetwork

Symbolic operands return TensorExpression. If rhs carries component data, the result is a TensorNetwork.

Notes

Use this when compatible unresolved axes should remain independent. Choose explicit distinct labels if you need to refer to them separately.

Examples
from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
product = A.outer(A)
product.rank
Parameters
NameTypeDefaultDescription
rhsTensorExpression | Expression—

Tensor whose axes follow this tensor's axes.

Overload 2 #
outer(rhs: Union[Tensor, TensorNetwork]) -> TensorNetwork

Form an outer product without implicit contractions between the operands.

Returns

TensorExpression or TensorNetwork

Symbolic operands return TensorExpression. If rhs carries component data, the result is a TensorNetwork.

Notes

Use this when compatible unresolved axes should remain independent. Choose explicit distinct labels if you need to refer to them separately.

Examples
from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
product = A.outer(A)
product.rank
Parameters
NameTypeDefaultDescription
rhsUnion[Tensor, TensorNetwork]—

Tensor whose axes follow this tensor's axes.

contract_ports

Method#

Overloads

Overload 1 #
contract_ports(rhs: TensorExpression | Expression, *, left: int, right: int) -> TensorExpression

Contract one chosen pair of axes between two tensors.

Returns

TensorExpression or TensorNetwork

A symbolic tensor unless rhs carries component data, in which case a lazy TensorNetwork is returned.

Notes

Other axes remain external. Axis numbers refer to axes.

Examples
from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
contracted = A.contract_ports(A, left=1, right=0)
contracted.rank
Parameters
NameTypeDefaultDescription
rhsTensorExpression | Expression—

Tensor to contract with this tensor.

leftint—

Zero-based axis positions in this tensor and rhs, respectively. The representations must be compatible under contraction.

rightint—

Zero-based axis positions in this tensor and rhs, respectively. The representations must be compatible under contraction.

Overload 2 #
contract_ports(rhs: Union[Tensor, TensorNetwork], *, left: int, right: int) -> TensorNetwork

Contract one chosen pair of axes between two tensors.

Returns

TensorExpression or TensorNetwork

A symbolic tensor unless rhs carries component data, in which case a lazy TensorNetwork is returned.

Notes

Other axes remain external. Axis numbers refer to axes.

Examples
from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
contracted = A.contract_ports(A, left=1, right=0)
contracted.rank
Parameters
NameTypeDefaultDescription
rhsUnion[Tensor, TensorNetwork]—

Tensor to contract with this tensor.

leftint—

Zero-based axis positions in this tensor and rhs, respectively. The representations must be compatible under contraction.

rightint—

Zero-based axis positions in this tensor and rhs, respectively. The representations must be compatible under contraction.

compose

Method#

Overloads

Overload 1 #
compose(rhs: TensorExpression | Expression, *, left: tuple[int, int], right: tuple[int, int]) -> TensorExpression

Multiply two tensors along explicitly selected matrix channels.

Returns

TensorExpression or TensorNetwork

Symbolic operands return TensorExpression. A concrete rhs produces a TensorNetwork that retains its data.

Examples
from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
product = A.compose(A, left=(0, 1), right=(0, 1))
product.rank
Parameters
NameTypeDefaultDescription
rhsTensorExpression | Expression—

Next factor in the ordered matrix product.

lefttuple[int, int]—

(input_axis, output_axis) in this tensor and rhs, respectively. The left output contracts with the right input. Other axes are retained as spectator axes.

righttuple[int, int]—

(input_axis, output_axis) in this tensor and rhs, respectively. The left output contracts with the right input. Other axes are retained as spectator axes.

Overload 2 #
compose(rhs: Union[Tensor, TensorNetwork], *, left: tuple[int, int], right: tuple[int, int]) -> TensorNetwork

Multiply two tensors along explicitly selected matrix channels.

Returns

TensorExpression or TensorNetwork

Symbolic operands return TensorExpression. A concrete rhs produces a TensorNetwork that retains its data.

Examples
from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
product = A.compose(A, left=(0, 1), right=(0, 1))
product.rank
Parameters
NameTypeDefaultDescription
rhsUnion[Tensor, TensorNetwork]—

Next factor in the ordered matrix product.

lefttuple[int, int]—

(input_axis, output_axis) in this tensor and rhs, respectively. The left output contracts with the right input. Other axes are retained as spectator axes.

righttuple[int, int]—

(input_axis, output_axis) in this tensor and rhs, respectively. The left output contracts with the right input. Other axes are retained as spectator axes.

__getitem__

Method#

Overloads

Overload 1 #
__getitem__(item: int) -> list[int]:  # type: ignore[override]

Convert between flat component positions and coordinates.

Returns

int, list of int, or list of lists of int

Coordinates for a flat position, a flat position for coordinates, or a coordinate list for a slice. No component values are evaluated.

Examples
from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
A[2]
A[1, 0]
Parameters
NameTypeDefaultDescription
itemint—

A nonnegative flat position, coordinates in logical axis order, or a slice of flat positions. All axis dimensions must be concrete.

Overload 2 #
__getitem__(item: Sequence[int]) -> int:  # type: ignore[override]

Convert between flat component positions and coordinates.

Returns

int, list of int, or list of lists of int

Coordinates for a flat position, a flat position for coordinates, or a coordinate list for a slice. No component values are evaluated.

Examples
from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
A[2]
A[1, 0]
Parameters
NameTypeDefaultDescription
itemSequence[int]—

A nonnegative flat position, coordinates in logical axis order, or a slice of flat positions. All axis dimensions must be concrete.

Overload 3 #
__getitem__(item: slice) -> list[list[int]]:  # type: ignore[override]  # ty: ignore[invalid-method-override]

Convert between flat component positions and coordinates.

Returns

int, list of int, or list of lists of int

Coordinates for a flat position, a flat position for coordinates, or a coordinate list for a slice. No component values are evaluated.

Examples
from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
A[2]
A[1, 0]
Parameters
NameTypeDefaultDescription
itemslice—

A nonnegative flat position, coordinates in logical axis order, or a slice of flat positions. All axis dimensions must be concrete.