Overview
Tensor algebra
A comprehensive Python tensor library for symbolic and numerical tensor computations, with a focus on physics applications.
Overview
The Spenso Python API provides powerful tools for:
- Tensor Algebra: Dense and sparse tensors with flexible data types
- Symbolic Computation: Integration with Symbolica for tensors with symbolic expressions
- Network Operations: Tensor networks for optimized computation graphs
- Tensor Simplification: Idenso algebra operations using Spenso tensor notation, exposed as TensorExpression methods
- Physics Applications: Built-in support for HEP tensors (gamma matrices, color structures, etc.)
- Performance: Compiled evaluators for high-speed numerical computation
Contributors
- Lucien Huber mail@lucien.ch
Use from symbolica.community import tensor. symbolica.community.spenso remains a compatibility import. Idenso simplifications are exposed as TensorExpression methods.
AUTO (also exported as _) requests an automatically assigned tensor index.
Classes
BroadcastFunction |
A unary function applied independently to each tensor component |
CanonicalizationError |
Raised when dummy-index or tensor-factor canonicalization cannot be completed. |
CompiledTensorEvaluator |
A tensor evaluator compiled into a loaded native library |
CookingError |
Raised when a compound index label cannot be encoded by the selected interning mode. |
DiracAdjointError |
Raised when spinor index structure does not define a consistent Dirac adjoint. |
DisplaySettings |
Immutable presentation options for tensor notation and component displays |
ExecutionMode |
Choose how network execution schedules contractions |
ExecutionStatus |
Read-only snapshot of a TensorNetwork’s remaining work |
FactorProjector |
A normalized permutation group of matrix factors for a chain or trace |
NetworkToolingError |
Raised when tensor syntax cannot be interpreted as a supported symbolic network. |
PortPattern |
A Symbolica pattern for a tensor index or its representation |
ReductionStatus |
Completion of a tensor reduction under its selected settings |
Representation |
An index space with a dimension and a rule for pairing indices |
RepresentationName |
A representation identity independent of its dimension |
Slot |
One abstract tensor index together with its representation |
SymbolicParallelism |
Threading policy for operations on symbolic component expressions |
Tensor |
Tensor components together with their symbolic identity and ordered axes |
TensorEvaluator |
Optimized numerical evaluation of a tensor’s component formulas |
TensorExpression |
A symbolic tensor expression with an ordered set of external axes |
TensorFunctionLibrary |
Numerical implementations of unary elementwise tensor functions |
TensorLibrary |
Reusable component definitions indexed by tensor name and signature |
TensorName |
A registered function name for symbolic tensors of arbitrary index spaces |
TensorNetwork |
An executable tensor calculation that retains component data |
TensorPattern |
Representation-aware Symbolica patterns for matching tensor expressions |
TensorRule |
A reusable replacement rule that preserves tensor interfaces |
TensorStructure |
The canonical external signature of an opaque tensor |
Functions
Nc |
Return the canonical real color-count symbol, whose default numerical value is 3 |
as_tensor |
Convert a symbolic expression to a TensorExpression. |
chain |
Compose an ordered product with explicitly labeled endpoints. |
dot |
Contract two rank-one tensors into a scalar product. |
format_tensor |
Produce compact plain-text tensor notation. |
formatted |
Create a lazy rich display value for a notebook. |
load_math_font |
Embed the bundled math font in an HTML notebook or document. |
set_symbolica_rayon_enabled |
Set the threading policy for Spenso’s Symbolica operations. |
to_html |
Render the tensor as an HTML fragment. |
to_svg |
Render static mathematical tensor notation to SVG. |
to_typst |
Produce static Typst math source. |
trace |
Close an ordered product along a representation channel. |
Nc
Nc() -> ExpressionReturn the canonical real color-count symbol, whose default numerical value is 3.
Construct it on demand so importing Symbolica leaves time to set a license key. Use a separate dimension symbol for formal SU(N) calculations when the default numerical value is not appropriate.
Examples
from symbolica.community.tensor import Nc
Nc().evaluate({})
3as_tensor
as_tensor(expression: typing.Any) -> TensorExpressionConvert a symbolic expression to a TensorExpression.
Parameters
expression(TensorExpression or scalar expression) Tensor syntax to infer, or an ordinary scalar. An existing TensorExpression retains its tensor metadata.
Returns
TensorExpressionTensor-aware algebra, including rank-zero scalars.
Notes
Equivalent to TensorExpression(expression) without its optional structure and index-cooking settings.
Examples
from symbolica.community.tensor import as_tensor
as_tensor(2).is_scalar
Truechain
chain(
start_slot: Slot,
end_slot: Slot,
*factors: TensorExpression | Expression | FactorProjector[TensorExpression],
) -> TensorExpression
chain(
start_slot: Slot,
end_slot: Slot,
factor: Tensor | TensorNetwork | FactorProjector[TensorNetwork],
/,
*factors: TensorExpression | _ScalarInput | Tensor | TensorNetwork | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork],
) -> TensorNetwork
chain(
start_slot: Slot,
end_slot: Slot,
first: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork],
second: Tensor | TensorNetwork | FactorProjector[TensorNetwork],
/,
*factors: TensorExpression | _ScalarInput | Tensor | TensorNetwork | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork],
) -> TensorNetwork
chain(
start_slot: Slot,
end_slot: Slot,
*factors: TensorExpression | _ScalarInput | Tensor | TensorNetwork | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork],
) -> TensorExpression | TensorNetworkCompose an ordered product with explicitly labeled endpoints.
Parameters
start_slot, end_slot(Slot) External input and output indices, compatible with the factors’ matrix channel. Matching endpoint labels close a trace.*factors(TensorExpression, scalar expression, Tensor, TensorNetwork, or FactorProjector) Ordered matrix factors, each with a unique compatible channel. Spectator axes remain external. Supply constituent factors separately when using a factor projector. Scalar factors multiply the whole chain. In the overloads, factor, first, and second name leading entries in this same sequence of positional factors.
Returns
TensorExpression or TensorNetworkA symbolic chain when all factors are symbolic; a lazy TensorNetwork if any factor or projector contains component data.
Examples
from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
from symbolica.community.tensor import chain
product = chain(space("i"), space("j"), A, A)
product.rank
2dot
dot(left: TensorExpression | Expression, right: TensorExpression | Expression) -> TensorExpression
dot(
left: typing.Union[Tensor, TensorNetwork],
right: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork],
) -> TensorNetwork
dot(
left: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork],
right: typing.Union[Tensor, TensorNetwork],
) -> TensorNetworkContract two rank-one tensors into a scalar product.
Parameters
left, right(TensorExpression, Tensor, or TensorNetwork) Rank-one operands in compatible representation spaces.
Returns
TensorExpression or TensorNetworkSymbolic operands return TensorExpression. If either operand carries component data, the result is a lazy TensorNetwork.
Notes
The pairing includes the representation metric, for example Minkowski signs. This is a bilinear product; it does not conjugate either operand.
Examples
from symbolica.community.tensor import Representation, TensorName, dot
space = Representation.euc(3)
p = TensorName.vector("dot_p")(space)
q = TensorName.vector("dot_q")(space)
dot(p, q).is_scalar
Trueformat_tensor
format_tensor(
expression: Expression,
show_dimensions: typing.Optional[builtins.bool] = None,
*,
settings: typing.Optional[DisplaySettings] = None,
) -> builtins.strProduce compact plain-text tensor notation.
Parameters
expression(Expression) Symbolica tensor syntax or scalar algebra to display. For a TensorExpression or component Tensor, prefer its formatting methods.show_dimensions(bool, optional) Override settings.show_dimensions for this call. None retains the selected settings, whose default omits dimensions.settings(DisplaySettings, optional) Tensor notation and display choices. Defaults to DisplaySettings().
Returns
strReadable 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 import S
expression = S("x") + 1
from symbolica.community.tensor import format_tensor
output = format_tensor(expression)formatted
formatted(
expression: Expression,
show_dimensions: typing.Optional[builtins.bool] = None,
*,
settings: typing.Optional[DisplaySettings] = None,
notation_source: typing.Optional[builtins.str] = None,
) -> FormattedOutputCreate a lazy rich display value for a notebook.
Parameters
expression(Expression) Symbolica tensor syntax or scalar algebra to display. For a TensorExpression or component Tensor, prefer its formatting methods.show_dimensions(bool, optional) Override settings.show_dimensions for this call. None retains the selected settings, whose default omits dimensions.settings(DisplaySettings, optional) Tensor notation and display choices. Defaults to DisplaySettings().notation_source(str, optional) Custom Typst notation source used by the rich renderer. This is Typst code, not a filename; omit it for the supplied tensor notation.
Returns
FormattedOutputEach requested backend renders the complete expression once and caches it.
Notes
Settings are captured here; custom printers run on the first request for each backend. Create a new formatted value after changing printers.
Examples
from symbolica import S
expression = S("x") + 1
from symbolica.community.tensor import formatted
output = formatted(expression)load_math_font
load_math_font() -> builtins.strEmbed the bundled math font in an HTML notebook or document.
Returns
strA style element with the font data and redistribution license.
Notes
Display this HTML once before tensor outputs, or include it in an exported document’s head. It avoids the normal font download and applies to the same HTML document; isolated output frames need their own copy. In Marimo, use mo.Html(load_math_font()); in IPython, use HTML(load_math_font()).
Examples
from symbolica.community.tensor import load_math_font
html = load_math_font()
html.startswith("<style>")
Trueset_symbolica_rayon_enabled
set_symbolica_rayon_enabled(policy: SymbolicParallelism) -> builtins.boolSet the threading policy for Spenso’s Symbolica operations.
Parameters
policy(SymbolicParallelism) Auto checks the license at this call; Serial disables symbolic parallelism; Parallel enables it without that automatic check.
Returns
boolWhether the resolved policy permits parallel execution. Individual operations may still choose serial execution for small workloads.
Notes
This changes the process-wide policy, not just one tensor or network.
Examples
from symbolica.community.tensor import SymbolicParallelism, set_symbolica_rayon_enabled
allowed = set_symbolica_rayon_enabled(SymbolicParallelism.Auto)to_html
to_html(
expression: Expression,
show_dimensions: typing.Optional[builtins.bool] = None,
*,
settings: typing.Optional[DisplaySettings] = None,
notation_source: typing.Optional[builtins.str] = None,
) -> builtins.strRender the tensor as an HTML fragment.
Parameters
expression(Expression) Symbolica tensor syntax or scalar algebra to display. For a TensorExpression or component Tensor, prefer its formatting methods.show_dimensions(bool, optional) Override settings.show_dimensions for this call. None retains the selected settings, whose default omits dimensions.settings(DisplaySettings, optional) Tensor notation and display choices. Defaults to DisplaySettings().notation_source(str, optional) Custom Typst notation source used by the rich renderer. This is Typst code, not a filename; omit it for the supplied tensor notation.
Returns
strSelf-contained output fragment for an HTML-capable notebook or page.
Notes
Mathematical rendering uses the embedded Typst compiler. The returned string is not automatically displayed; pass it to the notebook’s HTML or SVG display facility.
Examples
from symbolica import S
expression = S("x") + 1
from symbolica.community.tensor import to_html
output = to_html(expression)to_svg
to_svg(
expression: Expression,
show_dimensions: typing.Optional[builtins.bool] = None,
*,
settings: typing.Optional[DisplaySettings] = None,
notation_source: typing.Optional[builtins.str] = None,
) -> builtins.strRender static mathematical tensor notation to SVG.
Parameters
expression(Expression) Symbolica tensor syntax or scalar algebra to display. For a TensorExpression or component Tensor, prefer its formatting methods.show_dimensions(bool, optional) Override settings.show_dimensions for this call. None retains the selected settings, whose default omits dimensions.settings(DisplaySettings, optional) Tensor notation and display choices. Defaults to DisplaySettings().notation_source(str, optional) Custom Typst notation source used by the rich renderer. This is Typst code, not a filename; omit it for the supplied tensor notation.
Returns
strSVG markup suitable for embedding or saving to a file.
Notes
Mathematical rendering uses the embedded Typst compiler. The returned string is not automatically displayed; pass it to the notebook’s HTML or SVG display facility.
Examples
from symbolica import S
expression = S("x") + 1
from symbolica.community.tensor import to_svg
output = to_svg(expression)to_typst
to_typst(
expression: Expression,
show_dimensions: typing.Optional[builtins.bool] = None,
*,
settings: typing.Optional[DisplaySettings] = None,
) -> builtins.strProduce static Typst math source.
Parameters
expression(Expression) Symbolica tensor syntax or scalar algebra to display. For a TensorExpression or component Tensor, prefer its formatting methods.show_dimensions(bool, optional) Override settings.show_dimensions for this call. None retains the selected settings, whose default omits dimensions.settings(DisplaySettings, optional) Tensor notation and display choices. Defaults to DisplaySettings().
Returns
strTypst 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 import S
expression = S("x") + 1
from symbolica.community.tensor import to_typst
output = to_typst(expression)trace
trace(
representation: Representation,
*factors: TensorExpression | Expression | FactorProjector[TensorExpression],
) -> TensorExpression
trace(
representation: Representation,
factor: Tensor | TensorNetwork | FactorProjector[TensorNetwork],
/,
*factors: TensorExpression | _ScalarInput | Tensor | TensorNetwork | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork],
) -> TensorNetwork
trace(
representation: Representation,
first: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork],
second: Tensor | TensorNetwork | FactorProjector[TensorNetwork],
/,
*factors: TensorExpression | _ScalarInput | Tensor | TensorNetwork | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork],
) -> TensorNetwork
trace(
representation: Representation,
*factors: TensorExpression | _ScalarInput | Tensor | TensorNetwork | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork],
) -> TensorExpression | TensorNetworkClose an ordered product along a representation channel.
Parameters
representation(Representation) Space over which the matrix indices are traced.*factors(TensorExpression, scalar expression, Tensor, TensorNetwork, or FactorProjector) Ordered factors with compatible matrix channels. Additional axes are retained as spectator axes. Scalar factors multiply the whole trace. In the overloads, factor, first, and second name leading entries in this same sequence of positional factors.
Returns
TensorExpression or TensorNetworkSymbolic operands produce a symbolic trace. Any component-bearing factor produces a lazy TensorNetwork.
Examples
from symbolica.community.tensor import Representation, TensorName, TensorExpression
space = Representation.euc(2)
A = TensorName("M")(space, space)
from symbolica.community.tensor import trace
trace(space, A, A).is_scalar
TrueConstants
AUTO
AUTO: _AutoIndex