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 |
Native Symbolica evaluator returning tensors |
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 |
Symbolica evaluator returning component tensors in their original logical layout |
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. |
to_typst_project |
Export a customizable Typst project without running a compiler. |
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({})Output
3
as_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_scalarOutput
True
chain
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.rankOutput
2
dot
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_scalarOutput
True
format_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) Unsupported for HTML and notebook output; raises ValueError. Use to_typst_project() or to_svg() for custom Typst 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.
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 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>")Output
True
set_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) Unsupported for HTML and notebook output; raises ValueError. Use to_typst_project() or to_svg() for custom Typst notation.
Returns
strSelf-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 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
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 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)to_typst_project
to_typst_project(
expression: Expression,
show_dimensions: typing.Optional[builtins.bool] = None,
*,
settings: typing.Optional[DisplaySettings] = None,
notation_source: typing.Optional[builtins.str] = None,
) -> dictExport a customizable Typst project without running a compiler.
Parameters
expression(Expression) Symbolica tensor syntax or scalar algebra to display.show_dimensions(bool, optional) Override settings.show_dimensions for this call.settings(DisplaySettings, optional) Tensor notation, layout, and spacing choices.notation_source(str, optional) Replacement notation.typ source. Omit it for the bundled notation.
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
Unlike to_typst(), the project supports all rich layouts and custom notation. The optional Python package typst is needed only to compile the result.
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 import S
from symbolica.community.tensor import to_typst_project
project = to_typst_project(S("x") + 1)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_scalarOutput
True
Constants
AUTO
AUTO: _AutoIndex