# This file is automatically generated by pyo3_stub_gen
# ruff: noqa: E501, F401
r"""
Symbolic and component-based tensor manipulation.

Use Representation and TensorName to construct TensorExpression objects;
Tensor stores component data and TensorNetwork executes tensor calculations.
TensorLibrary supplies reusable components, and TensorPattern/TensorRule
provide interface-aware rewriting. Dirac matrices, color tensors, and their
simplifiers are specialized helpers built on these generic tensor operations.

AUTO (also exported as _) leaves a tensor axis unresolved during indexing.
Nc() returns the registered real Symbolica color-count symbol: its built-in numerical
value is 3. Use your own dimension symbol for formal SU(N) calculations
when that default numerical value is not appropriate.

Examples
--------
>>> from symbolica.community.tensor import Representation, TensorName, AUTO
>>> matrix = TensorName("A")(Representation.euc(3), Representation.euc(3))
>>> matrix(AUTO, "j").rank
2
"""

import builtins
import decimal
import numpy
import numpy.typing
import symbolica.core
import typing
from symbolica import ComplexFloat, Float
from symbolica.community.graph import DiagramView, RenderSettings
from symbolica.core import Condition, Evaluator, Expression, FormattedOutput, FunctionDefinition, HeldExpression, PatternRestriction, Replacement, Transformer

AUTO: _AutoIndex
_: _AutoIndex
_Components: typing.TypeAlias = "Expression | float | complex | list[_Components]"
_IndexInput: typing.TypeAlias = "int | str | Expression | Slot | _AutoIndex"
_LibraryDefault = typing.TypeVar("_LibraryDefault")
_Projected = typing.TypeVar("_Projected", "TensorExpression", "TensorNetwork", covariant=True)
_RealInput: typing.TypeAlias = "Float | int | float | str | decimal.Decimal"
_ReplacementInput: typing.TypeAlias = "_ScalarInput | HeldExpression | typing.Callable[[dict[Expression, Expression]], Expression]"
_ScalarInput: typing.TypeAlias = "Expression | int | float | complex | str | decimal.Decimal | Float | ComplexFloat | tuple[_RealInput, _RealInput]"
@typing.final
class BroadcastFunction:
    r"""
    A unary function applied independently to each tensor component.

    Calling it on a TensorExpression preserves the tensor interface. Calling it
    on Tensor or TensorNetwork creates a lazy network. Scalar inputs produce
    ordinary Symbolica Expressions. Register numerical behavior separately in
    a TensorFunctionLibrary.

    Examples
    --------
    >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
    >>> space = Representation.euc(2)
    >>> A = TensorName("M")(space, space)
    >>> from symbolica.community.tensor import Tensor
    >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
    >>> from symbolica.community.tensor import BroadcastFunction
    >>> conjugated = BroadcastFunction.conj()(tensor)
    >>> conjugated.shape
    (2, 2)
    """
    def __new__(cls, name: builtins.str, *, is_symmetric: typing.Optional[builtins.bool] = None, is_antisymmetric: typing.Optional[builtins.bool] = None, is_cyclesymmetric: typing.Optional[builtins.bool] = None, is_linear: typing.Optional[builtins.bool] = None, is_flat: typing.Optional[builtins.bool] = None, is_scalar: typing.Optional[builtins.bool] = None, is_real: typing.Optional[builtins.bool] = None, is_integer: typing.Optional[builtins.bool] = None, is_positive: typing.Optional[builtins.bool] = None, tags: typing.Optional[typing.Sequence[builtins.str]] = None, aliases: typing.Optional[typing.Sequence[builtins.str]] = None, normalization: typing.Optional[symbolica.core.Transformer | typing.Callable[[symbolica.core.Expression], symbolica.core.Expression]] = None, print: typing.Optional[typing.Any] = None, derivative: typing.Optional[typing.Any] = None, series: typing.Optional[typing.Any] = None, eval: typing.Optional[typing.Any] = None, data: typing.Optional[_ScalarInput | str | dict | list | bytes] = None) -> BroadcastFunction:
        r"""
        Register a Symbolica function for elementwise tensor application.

        Parameters
        ----------
        name : str
            Registered unary function name. It receives the broadcast tag and
            cannot also be a tensor head.
        is_symmetric, is_antisymmetric, is_cyclesymmetric : bool, optional
            Symmetry of the function arguments under all permutations, signed
            permutations, or cyclic rotations. These affect scalar arguments as
            well as index arguments. Repeated arguments in an antisymmetric call
            make that call zero.
        is_linear : bool, optional
            Distribute the function over sums in its arguments.
        is_flat : bool, optional
            Flatten nested calls with the same head.
        is_scalar : bool, optional
            Declare calls scalar for Symbolica's algebra. The broadcast acts on scalar component values.
        is_real, is_integer, is_positive : bool, optional
            Assumptions used by Symbolica for the registered symbol.
        tags : sequence of str, optional
            Additional Symbolica tags; Spenso's required tags are included automatically.
        aliases : sequence of str, optional
            Additional names for the same Symbolica symbol.
        normalization : Transformer or callable, optional
            Normalize a newly constructed call. A callable receives an Expression
            and returns its normalized Expression; tensor interfaces must remain valid.
        print : callable, optional
            Symbolica custom-print callback for the complete function call.
            Returning None selects standard printing.
        derivative, series, eval : callable, optional
            Symbolica callbacks for differentiation, series expansion, and numerical
            evaluation. Their arguments and results follow ``symbolica.S``.
        data : object, optional
            Symbolica user data attached to the symbol, such as a dict, list, or bytes.

        Returns
        -------
        BroadcastFunction
            Callable wrapper with tensor-aware result types.

        Examples
        --------
        >>> from symbolica.community.tensor import BroadcastFunction, TensorExpression
        >>> function = BroadcastFunction("elementwise")
        >>> applied = function(TensorExpression(2))
        >>> applied.is_scalar
        True
        """
    @staticmethod
    def conj() -> BroadcastFunction:
        r"""
        Return the built-in elementwise complex-conjugation function.

        Returns
        -------
        BroadcastFunction
            Registered conjugation, with a built-in numerical implementation.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import BroadcastFunction
        >>> BroadcastFunction.conj()(tensor).to_tensor()[0, 1]
        2.0
        """
    def __repr__(self) -> builtins.str:
        r"""
        Return a readable object description for inspection.

        Examples
        --------
        >>> from symbolica.community import tensor as sp
        >>> conjugate = sp.BroadcastFunction.conj()
        >>> text = repr(conjugate)
        """
    def __str__(self) -> builtins.str:
        r"""
        Return a readable text representation.

        Examples
        --------
        >>> from symbolica.community import tensor as sp
        >>> conjugate = sp.BroadcastFunction.conj()
        >>> text = str(conjugate)
        """
    def to_expression(self) -> Expression:
        r"""
        Return this function name as a Symbolica symbol.

        Returns
        -------
        Expression
            The bare function head, without arguments or tensor structure.

        Examples
        --------
        >>> from symbolica.community.tensor import BroadcastFunction
        >>> name = BroadcastFunction("tagged_BroadcastFunction", tags=["example::example"])
        >>> head = name.to_expression()
        """
    def has_tag(self, tag: builtins.str) -> builtins.bool:
        r"""
        Check whether the registered function carries a tag.

        Parameters
        ----------
        tag : str
            Exact tag name. An unqualified name also matches its "python::" form.

        Returns
        -------
        bool
            Whether the tag is present.

        Examples
        --------
        >>> from symbolica.community.tensor import BroadcastFunction
        >>> name = BroadcastFunction("tagged_BroadcastFunction", tags=["example::example"])
        >>> name.has_tag("example::example")
        True
        """
    def get_tags(self) -> builtins.list[builtins.str]:
        r"""
        List the tags attached to the registered function.

        Returns
        -------
        list of str
            Fully qualified tags, including the tags required by Spenso.

        Examples
        --------
        >>> from symbolica.community.tensor import BroadcastFunction
        >>> name = BroadcastFunction("tagged_BroadcastFunction", tags=["example::example"])
        >>> "example::example" in name.get_tags()
        True
        """
    @typing.overload
    def __call__(self, arg: Tensor | TensorNetwork) -> TensorNetwork:
        r"""
        Apply this unary function to a scalar or to every tensor component.

        Parameters
        ----------
        arg : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Value to transform independently at each component.

        Returns
        -------
        Expression, TensorExpression, or TensorNetwork
            Scalar inputs return Expression; symbolic tensors retain
            TensorExpression; component-bearing inputs return TensorNetwork.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import BroadcastFunction
        >>> result = BroadcastFunction.conj()(tensor).to_tensor()
        >>> result.shape
        (2, 2)
        """
    @typing.overload
    def __call__(self, arg: TensorExpression) -> TensorExpression:
        r"""
        Apply this unary function to a scalar or to every tensor component.

        Parameters
        ----------
        arg : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Value to transform independently at each component.

        Returns
        -------
        Expression, TensorExpression, or TensorNetwork
            Scalar inputs return Expression; symbolic tensors retain
            TensorExpression; component-bearing inputs return TensorNetwork.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import BroadcastFunction
        >>> result = BroadcastFunction.conj()(tensor).to_tensor()
        >>> result.shape
        (2, 2)
        """
    @typing.overload
    def __call__(self, arg: _ScalarInput) -> Expression:
        r"""
        Apply this unary function to a scalar or to every tensor component.

        Parameters
        ----------
        arg : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Value to transform independently at each component.

        Returns
        -------
        Expression, TensorExpression, or TensorNetwork
            Scalar inputs return Expression; symbolic tensors retain
            TensorExpression; component-bearing inputs return TensorNetwork.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import BroadcastFunction
        >>> result = BroadcastFunction.conj()(tensor).to_tensor()
        >>> result.shape
        (2, 2)
        """

class CanonicalizationError(builtins.ValueError):
    r"""
    Raised when dummy-index or tensor-factor canonicalization cannot be completed.

    Notes
    -----
    Subclass of ValueError. Catch it around the corresponding tensor operation
    to handle invalid input or an unsupported symbolic form.

    Examples
    --------
    >>> from symbolica.community.tensor import CanonicalizationError
    >>> issubclass(CanonicalizationError, ValueError)
    True
    """
    ...

@typing.final
class CompiledTensorEvaluator:
    r"""
    Native Symbolica evaluator returning tensors. Construct with TensorEvaluator.compile.

    evaluate uses the number_type selected at compilation, as in Symbolica's compiled
    evaluators. scalar_evaluator exposes the underlying native evaluator.
    """
    @property
    def parameters(self) -> builtins.list[Expression]:
        r"""
        Symbolic inputs in evaluation order.
        """
    @property
    def input_size(self) -> builtins.int:
        r"""
        Number of entries in each input row.
        """
    @property
    def output_shape(self) -> tuple[int, ...]:
        r"""
        Logical shape of each result tensor.
        """
    @property
    def supports_real(self) -> builtins.bool:
        r"""
        Whether compilation selected a real number type.
        """
    @property
    def scalar_evaluator(self) -> typing.Any:
        r"""
        Underlying Symbolica compiled evaluator.
        """
    def evaluate(self, inputs: numpy.typing.ArrayLike) -> builtins.list[Tensor]:
        r"""
        Evaluate real or complex inputs, according to the compiled number type.
        """
    def __repr__(self) -> builtins.str:
        r"""
        Describe the compiled output tensor layout and numeric domain.
        """

class CookingError(builtins.TypeError):
    r"""
    Raised when a compound index label cannot be encoded by the selected interning mode.

    Notes
    -----
    Subclass of TypeError. Catch it around the corresponding tensor operation
    to handle invalid input or an unsupported symbolic form.

    Examples
    --------
    >>> from symbolica.community.tensor import CookingError
    >>> issubclass(CookingError, TypeError)
    True
    """
    ...

class DiracAdjointError(builtins.ValueError):
    r"""
    Raised when spinor index structure does not define a consistent Dirac adjoint.

    Notes
    -----
    Subclass of ValueError. Catch it around the corresponding tensor operation
    to handle invalid input or an unsupported symbolic form.

    Examples
    --------
    >>> from symbolica.community.tensor import DiracAdjointError
    >>> issubclass(DiracAdjointError, ValueError)
    True
    """
    ...

@typing.final
class DisplaySettings:
    r"""
    Immutable presentation options for tensor notation and component displays.

    Formatting does not change indices, tensor algebra, or component order.
    The defaults use representation-specific index alphabets and an interactive
    component explorer. The direct MathML pager supports rich layouts and gaps;
    static Typst/plain source supports ports layout. HTML uses direct MathML;
    customizable Typst projects and SVG exports retain the Typst notation backend.

    Examples
    --------
    >>> from symbolica.community.tensor import DisplaySettings
    >>> settings = DisplaySettings(component_style="array", index_style="alphabet")
    """
    @property
    def tensor_layout(self) -> typing.Literal['ports', 'schoonschip', 'call']:
        r"""
        Rich layout: "ports" places indices by tensor axes; "schoonschip"

        Returns
        -------
        str
            Rich layout: "ports" places indices by tensor axes; "schoonschip"
            uses compact contracted-vector notation; "call" uses function-call notation.

        Examples
        --------
        >>> from symbolica.community.tensor import DisplaySettings
        >>> value = DisplaySettings().tensor_layout
        """
    @property
    def index_style(self) -> typing.Literal['alphabet', 'graph', 'raw']:
        r"""
        "alphabet" assigns representation-specific letters to generated indices;

        Returns
        -------
        str
            "alphabet" assigns representation-specific letters to generated indices;
            "graph" shows graph identities; "raw" retains the original labels.

        Examples
        --------
        >>> from symbolica.community.tensor import DisplaySettings
        >>> value = DisplaySettings().index_style
        """
    @property
    def component_style(self) -> typing.Literal['superscript', 'array']:
        r"""
        Concrete component labels: "superscript" for A(x,7)^{0,1},

        Returns
        -------
        str
            Concrete component labels: "superscript" for A(x,7)^{0,1},
            or "array" for A(x,7)[0,1]. Scalar arguments stay in parentheses.

        Examples
        --------
        >>> from symbolica.community.tensor import DisplaySettings
        >>> value = DisplaySettings().component_style
        """
    @property
    def tensor_view(self) -> typing.Literal['interactive', 'matrix']:
        r"""
        Concrete-tensor HTML: "interactive" provides a component explorer with

        Returns
        -------
        str
            Concrete-tensor HTML: "interactive" provides a component explorer with
            a Memory grid / Matrix toggle; "matrix" selects static mathematical output.

        Examples
        --------
        >>> from symbolica.community.tensor import DisplaySettings
        >>> value = DisplaySettings().tensor_view
        """
    @property
    def invariant_style(self) -> typing.Literal['compact', 'explicit']:
        r"""
        Choose compact or degree-explicit scalar invariant notation.

        Returns
        -------
        str
            "compact" uses C_F, C_A and T_R for the quadratic color invariants;
            "explicit" uses C_2(F), C_2(A) and I_2(F). Higher degrees use
            C_k(R), I_k(R) and G_k(R, S) in either style.

        Examples
        --------
        >>> from symbolica.community.tensor import DisplaySettings
        >>> DisplaySettings(invariant_style="explicit").invariant_style
        'explicit'
        """
    @property
    def show_dimensions(self) -> builtins.bool:
        r"""
        Include representation dimensions in index notation.

        Returns
        -------
        bool
            Include representation dimensions in index notation and scalar invariants.
            Invariants then show their degree and representation, such as C_2(F_3).

        Examples
        --------
        >>> from symbolica.community.tensor import DisplaySettings
        >>> value = DisplaySettings().show_dimensions
        """
    @property
    def parentheses(self) -> builtins.bool:
        r"""
        Include the optional grouping parentheses used by tensor notation.

        Returns
        -------
        bool
            Include the optional grouping parentheses used by tensor notation.

        Examples
        --------
        >>> from symbolica.community.tensor import DisplaySettings
        >>> value = DisplaySettings().parentheses
        """
    @property
    def commas(self) -> typing.Optional[builtins.bool]:
        r"""
        Show comma separators. None follows the layout: enabled for "call",

        Returns
        -------
        bool or None
            Show comma separators. None follows the layout: enabled for "call",
            disabled otherwise.

        Examples
        --------
        >>> from symbolica.community.tensor import DisplaySettings
        >>> value = DisplaySettings().commas
        """
    @property
    def symbol_scripts(self) -> builtins.bool:
        r"""
        Render index and component information using symbol scripts where supported.

        Returns
        -------
        bool
            Render index and component information using symbol scripts where supported.

        Examples
        --------
        >>> from symbolica.community.tensor import DisplaySettings
        >>> value = DisplaySettings().symbol_scripts
        """
    @property
    def index_gap(self) -> builtins.str:
        r"""
        Spacing between rendered indices, as a finite length using

        Returns
        -------
        str
            Spacing between rendered indices, as a finite length using
            pt, mm, cm, in, em, or %.

        Examples
        --------
        >>> from symbolica.community.tensor import DisplaySettings
        >>> value = DisplaySettings().index_gap
        """
    @property
    def factor_gap(self) -> builtins.str:
        r"""
        Spacing between rendered factors, using the same length units as index_gap.

        Returns
        -------
        str
            Spacing between rendered factors, using the same length units as index_gap.

        Examples
        --------
        >>> from symbolica.community.tensor import DisplaySettings
        >>> value = DisplaySettings().factor_gap
        """
    def __new__(cls, tensor_layout: typing.Literal['ports', 'schoonschip', 'call'] = 'ports', show_dimensions: builtins.bool = False, parentheses: builtins.bool = True, commas: typing.Optional[builtins.bool] = None, symbol_scripts: builtins.bool = True, index_gap: builtins.str = '0.08em', factor_gap: builtins.str = '0.12em', index_style: typing.Literal['alphabet', 'graph', 'raw'] = 'alphabet', component_style: typing.Literal['superscript', 'array'] = 'superscript', tensor_view: typing.Literal['interactive', 'matrix'] = 'interactive', invariant_style: typing.Literal['compact', 'explicit'] = 'compact') -> DisplaySettings:
        r"""
        Choose tensor notation, index labels, and component presentation.

        Parameters
        ----------
        tensor_layout : str, default "ports"
            Rich layout: "ports" places indices by tensor axes; "schoonschip"
            uses compact contracted-vector notation; "call" uses function-call notation.
        show_dimensions : bool, default False
            Include representation dimensions in index notation and scalar invariants.
            Invariants then show their degree and representation, such as C_2(F_3).
        parentheses : bool, default True
            Include the optional grouping parentheses used by tensor notation.
        commas : bool or None, default None
            Show comma separators. None follows the layout: enabled for "call",
            disabled otherwise.
        symbol_scripts : bool, default True
            Render index and component information using symbol scripts where supported.
        index_gap : str, default "0.08em"
            Spacing between rendered indices, as a finite length using
            pt, mm, cm, in, em, or %.
        factor_gap : str, default "0.12em"
            Spacing between rendered factors, using the same length units as index_gap.
        index_style : str, default "alphabet"
            "alphabet" assigns representation-specific letters to generated indices;
            "graph" shows graph identities; "raw" retains the original labels.
        component_style : str, default "superscript"
            Concrete component labels: "superscript" for A(x,7)^{0,1},
            or "array" for A(x,7)[0,1]. Scalar arguments stay in parentheses.
        tensor_view : str, default "interactive"
            Concrete-tensor HTML: "interactive" provides a component explorer with
            a Memory grid / Matrix toggle; "matrix" selects static mathematical output.

        invariant_style : {"compact", "explicit"}, default "compact"
            Compact quadratic color notation uses C_F, C_A and T_R. Explicit
            notation uses C_2(F), C_2(A) and I_2(F). Both use C_k(R), I_k(R)
            and G_k(R, S) for higher invariants. show_dimensions adds the
            dimension to each representation label and disables quadratic aliases.
            Older scalar symbols have no representation dimension to display.

        Returns
        -------
        DisplaySettings
            Immutable settings to pass to formatting methods.

        Notes
        -----
        The tensor_view option affects concrete tensor HTML, not symbolic
        TensorExpression algebra or TensorNetwork graph rendering.

        Examples
        --------
        >>> from symbolica.community.tensor import DisplaySettings
        >>> settings = DisplaySettings(component_style="array", tensor_view="matrix")
        """
    @staticmethod
    def ports() -> DisplaySettings:
        r"""
        Select the ports tensor layout with default options.

        Returns
        -------
        DisplaySettings
            Default presentation with this layout.

        Examples
        --------
        >>> from symbolica.community.tensor import DisplaySettings
        >>> DisplaySettings.ports().tensor_layout
        'ports'
        """
    @staticmethod
    def schoonschip() -> DisplaySettings:
        r"""
        Select the schoonschip tensor layout with default options.

        Returns
        -------
        DisplaySettings
            Default presentation with this layout.

        Notes
        -----
        Use with rich HTML or SVG rendering. Plain and Typst source methods
        require ports layout.

        Examples
        --------
        >>> from symbolica.community.tensor import DisplaySettings
        >>> DisplaySettings.schoonschip().tensor_layout
        'schoonschip'
        """
    @staticmethod
    def call() -> DisplaySettings:
        r"""
        Select the call tensor layout with default options.

        Returns
        -------
        DisplaySettings
            Default presentation with this layout; comma separators are enabled.

        Notes
        -----
        Use with rich HTML or SVG rendering. Plain and Typst source methods
        require ports layout.

        Examples
        --------
        >>> from symbolica.community.tensor import DisplaySettings
        >>> DisplaySettings.call().tensor_layout
        'call'
        """
    def __repr__(self) -> builtins.str:
        r"""
        Return a readable object description for inspection.

        Examples
        --------
        >>> from symbolica.community import tensor as sp
        >>> settings = sp.DisplaySettings()
        >>> text = repr(settings)
        """

@typing.final
class ExecutionMode:
    r"""
    Choose how network execution schedules contractions.

    ``All`` uses the default contraction schedule. ``Single`` selects one
    contraction at a time. ``Scalar`` restricts contraction to scalar work.
    Use ``execute(n_steps=...)`` to bound the number of execution rounds;
    the mode by itself does not bound the total number of rounds.

    Examples
    --------
    >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
    >>> space = Representation.euc(2)
    >>> A = TensorName("M")(space, space)
    >>> from symbolica.community.tensor import Tensor
    >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
    >>> from symbolica.community.tensor import TensorNetwork
    >>> network = TensorNetwork(tensor)
    >>> from symbolica.community.tensor import ExecutionMode
    >>> network.execute(n_steps=1, mode=ExecutionMode.Single)
    """
    Single: typing.ClassVar[ExecutionMode]
    r"""
    Select one smallest-degree rewrite per step; without `n_steps`, continue until no work remains
    """
    Scalar: typing.ClassVar[ExecutionMode]
    r"""
    Restrict each execution step to scalar work.
    """
    All: typing.ClassVar[ExecutionMode]
    r"""
    Use the default contraction schedule.
    """
    def __int__(self) -> builtins.int:
        r"""
        Return the underlying integer discriminant.
        """

@typing.final
class ExecutionStatus:
    r"""
    Read-only snapshot of a TensorNetwork's remaining work.

    Obtain this object from ``network.status``. Counts refer to graph structure,
    not estimated arithmetic cost or memory use; a previously obtained snapshot
    does not change when the network executes.

    Examples
    --------
    >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
    >>> space = Representation.euc(2)
    >>> A = TensorName("M")(space, space)
    >>> from symbolica.community.tensor import Tensor
    >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
    >>> from symbolica.community.tensor import TensorNetwork
    >>> network = TensorNetwork(tensor)
    >>> progress = network.status
    >>> progress.complete
    True
    """
    @property
    def nodes(self) -> builtins.int:
        r"""
        Number of remaining nodes, including values and operations.

        Returns
        -------
        int
            Current graph node count.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> snapshot_value = network.status.nodes
        """
    @property
    def operations(self) -> builtins.int:
        r"""
        Number of remaining operation nodes.

        Returns
        -------
        int
            Pending sums, products, broadcasts, and other operation nodes.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> snapshot_value = network.status.operations
        """
    @property
    def contractions(self) -> builtins.int:
        r"""
        Number of remaining internal index connections.

        Returns
        -------
        int
            Includes self-traces.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> snapshot_value = network.status.contractions
        """
    @property
    def complete(self) -> builtins.bool:
        r"""
        Whether one result value remains with no pending work.

        Returns
        -------
        bool
            True when no operations or index contractions remain.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> snapshot_value = network.status.complete
        """
    @property
    def ready_operations(self) -> tuple[str, ...]:
        r"""
        Operations whose inputs are currently available values.

        Returns
        -------
        tuple of str
            Operation descriptions in the scheduler's current traversal order.
            Preprocessing, including self-traces, can run before these operations.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> snapshot_value = network.status.ready_operations
        """
    def __repr__(self) -> builtins.str:
        r"""
        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)
        >>> tensor = sp.Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> network = tensor("i", "j") * tensor("j", "k")
        >>> status = network.status
        >>> text = repr(status)
        """

@typing.final
class FactorProjector(typing.Generic[_Projected]):
    r"""
    A normalized permutation group of matrix factors for a chain or trace.

    Symmetric and antisymmetric groups average all permutations with weight
    1/n!, with signs for the antisymmetric case. Cyclic groups average n cyclic
    rotations with weight 1/n. Groups may be nested and remain compact until
    expanded. They are factor groups, not standalone tensor expressions.

    Symbolic factors stay symbolic. A group containing Tensor or TensorNetwork
    data produces a TensorNetwork when inserted in a chain or trace. Supply
    individual factors rather than a precomposed multi-factor chain.

    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
    >>> group = FactorProjector.symmetric(A, A)
    >>> trace(space, group).is_scalar
    True
    """
    @typing.overload
    @staticmethod
    def symmetric(*factors: TensorExpression | Expression | FactorProjector[TensorExpression]) -> FactorProjector[TensorExpression]:
        r"""
        Average all permutations with weight 1/n!.

        Parameters
        ----------
        *factors : TensorExpression, Tensor, TensorNetwork, or FactorProjector
            Individual matrix factors with compatible channels, or nested groups.
            Their order defines the starting permutation.

        Returns
        -------
        FactorProjector
            Compact normalized group, retaining any supplied component data.
            Insert it with chain() or trace().

        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
        >>> group = FactorProjector.symmetric(A, A)
        >>> result = trace(space, group)
        """
    @typing.overload
    @staticmethod
    def symmetric(*factors: typing.Unpack[tuple[Tensor | TensorNetwork | FactorProjector[TensorNetwork], *tuple[TensorExpression | _ScalarInput | Tensor | TensorNetwork | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork], ...]]]) -> FactorProjector[TensorNetwork]:
        r"""
        Average all permutations with weight 1/n!.

        Parameters
        ----------
        *factors : TensorExpression, Tensor, TensorNetwork, or FactorProjector
            Individual matrix factors with compatible channels, or nested groups.
            Their order defines the starting permutation.

        Returns
        -------
        FactorProjector
            Compact normalized group, retaining any supplied component data.
            Insert it with chain() or trace().

        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
        >>> group = FactorProjector.symmetric(A, A)
        >>> result = trace(space, group)
        """
    @typing.overload
    @staticmethod
    def symmetric(*factors: typing.Unpack[tuple[TensorExpression | _ScalarInput | Tensor | TensorNetwork | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork], Tensor | TensorNetwork | FactorProjector[TensorNetwork], *tuple[TensorExpression | _ScalarInput | Tensor | TensorNetwork | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork], ...]]]) -> FactorProjector[TensorNetwork]:
        r"""
        Average all permutations with weight 1/n!.

        Parameters
        ----------
        *factors : TensorExpression, Tensor, TensorNetwork, or FactorProjector
            Individual matrix factors with compatible channels, or nested groups.
            Their order defines the starting permutation.

        Returns
        -------
        FactorProjector
            Compact normalized group, retaining any supplied component data.
            Insert it with chain() or trace().

        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
        >>> group = FactorProjector.symmetric(A, A)
        >>> result = trace(space, group)
        """
    @typing.overload
    @staticmethod
    def symmetric(*factors: TensorExpression | _ScalarInput | Tensor | TensorNetwork | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]:
        r"""
        Average all permutations with weight 1/n!.

        Parameters
        ----------
        *factors : TensorExpression, Tensor, TensorNetwork, or FactorProjector
            Individual matrix factors with compatible channels, or nested groups.
            Their order defines the starting permutation.

        Returns
        -------
        FactorProjector
            Compact normalized group, retaining any supplied component data.
            Insert it with chain() or trace().

        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
        >>> group = FactorProjector.symmetric(A, A)
        >>> result = trace(space, group)
        """
    @typing.overload
    @staticmethod
    def antisymmetric(*factors: TensorExpression | Expression | FactorProjector[TensorExpression]) -> FactorProjector[TensorExpression]:
        r"""
        Average all signed permutations with weight 1/n!.

        Parameters
        ----------
        *factors : TensorExpression, Tensor, TensorNetwork, or FactorProjector
            Individual matrix factors with compatible channels, or nested groups.
            Their order defines the starting permutation.

        Returns
        -------
        FactorProjector
            Compact normalized group, retaining any supplied component data.
            Insert it with chain() or trace().

        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
        >>> group = FactorProjector.antisymmetric(A, A)
        >>> result = trace(space, group)
        """
    @typing.overload
    @staticmethod
    def antisymmetric(*factors: typing.Unpack[tuple[Tensor | TensorNetwork | FactorProjector[TensorNetwork], *tuple[TensorExpression | _ScalarInput | Tensor | TensorNetwork | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork], ...]]]) -> FactorProjector[TensorNetwork]:
        r"""
        Average all signed permutations with weight 1/n!.

        Parameters
        ----------
        *factors : TensorExpression, Tensor, TensorNetwork, or FactorProjector
            Individual matrix factors with compatible channels, or nested groups.
            Their order defines the starting permutation.

        Returns
        -------
        FactorProjector
            Compact normalized group, retaining any supplied component data.
            Insert it with chain() or trace().

        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
        >>> group = FactorProjector.antisymmetric(A, A)
        >>> result = trace(space, group)
        """
    @typing.overload
    @staticmethod
    def antisymmetric(*factors: typing.Unpack[tuple[TensorExpression | _ScalarInput | Tensor | TensorNetwork | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork], Tensor | TensorNetwork | FactorProjector[TensorNetwork], *tuple[TensorExpression | _ScalarInput | Tensor | TensorNetwork | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork], ...]]]) -> FactorProjector[TensorNetwork]:
        r"""
        Average all signed permutations with weight 1/n!.

        Parameters
        ----------
        *factors : TensorExpression, Tensor, TensorNetwork, or FactorProjector
            Individual matrix factors with compatible channels, or nested groups.
            Their order defines the starting permutation.

        Returns
        -------
        FactorProjector
            Compact normalized group, retaining any supplied component data.
            Insert it with chain() or trace().

        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
        >>> group = FactorProjector.antisymmetric(A, A)
        >>> result = trace(space, group)
        """
    @typing.overload
    @staticmethod
    def antisymmetric(*factors: TensorExpression | _ScalarInput | Tensor | TensorNetwork | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]:
        r"""
        Average all signed permutations with weight 1/n!.

        Parameters
        ----------
        *factors : TensorExpression, Tensor, TensorNetwork, or FactorProjector
            Individual matrix factors with compatible channels, or nested groups.
            Their order defines the starting permutation.

        Returns
        -------
        FactorProjector
            Compact normalized group, retaining any supplied component data.
            Insert it with chain() or trace().

        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
        >>> group = FactorProjector.antisymmetric(A, A)
        >>> result = trace(space, group)
        """
    @typing.overload
    @staticmethod
    def cyclic(*factors: TensorExpression | Expression | FactorProjector[TensorExpression]) -> FactorProjector[TensorExpression]:
        r"""
        Average cyclic rotations with weight 1/n.

        Parameters
        ----------
        *factors : TensorExpression, Tensor, TensorNetwork, or FactorProjector
            Individual matrix factors with compatible channels, or nested groups.
            Their order defines the starting permutation.

        Returns
        -------
        FactorProjector
            Compact normalized group, retaining any supplied component data.
            Insert it with chain() or trace().

        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
        >>> group = FactorProjector.cyclic(A, A)
        >>> result = trace(space, group)
        """
    @typing.overload
    @staticmethod
    def cyclic(*factors: typing.Unpack[tuple[Tensor | TensorNetwork | FactorProjector[TensorNetwork], *tuple[TensorExpression | _ScalarInput | Tensor | TensorNetwork | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork], ...]]]) -> FactorProjector[TensorNetwork]:
        r"""
        Average cyclic rotations with weight 1/n.

        Parameters
        ----------
        *factors : TensorExpression, Tensor, TensorNetwork, or FactorProjector
            Individual matrix factors with compatible channels, or nested groups.
            Their order defines the starting permutation.

        Returns
        -------
        FactorProjector
            Compact normalized group, retaining any supplied component data.
            Insert it with chain() or trace().

        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
        >>> group = FactorProjector.cyclic(A, A)
        >>> result = trace(space, group)
        """
    @typing.overload
    @staticmethod
    def cyclic(*factors: typing.Unpack[tuple[TensorExpression | _ScalarInput | Tensor | TensorNetwork | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork], Tensor | TensorNetwork | FactorProjector[TensorNetwork], *tuple[TensorExpression | _ScalarInput | Tensor | TensorNetwork | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork], ...]]]) -> FactorProjector[TensorNetwork]:
        r"""
        Average cyclic rotations with weight 1/n.

        Parameters
        ----------
        *factors : TensorExpression, Tensor, TensorNetwork, or FactorProjector
            Individual matrix factors with compatible channels, or nested groups.
            Their order defines the starting permutation.

        Returns
        -------
        FactorProjector
            Compact normalized group, retaining any supplied component data.
            Insert it with chain() or trace().

        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
        >>> group = FactorProjector.cyclic(A, A)
        >>> result = trace(space, group)
        """
    @typing.overload
    @staticmethod
    def cyclic(*factors: TensorExpression | _ScalarInput | Tensor | TensorNetwork | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]:
        r"""
        Average cyclic rotations with weight 1/n.

        Parameters
        ----------
        *factors : TensorExpression, Tensor, TensorNetwork, or FactorProjector
            Individual matrix factors with compatible channels, or nested groups.
            Their order defines the starting permutation.

        Returns
        -------
        FactorProjector
            Compact normalized group, retaining any supplied component data.
            Insert it with chain() or trace().

        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
        >>> group = FactorProjector.cyclic(A, A)
        >>> result = trace(space, group)
        """
    def __repr__(self) -> builtins.str:
        r"""
        Describe the permutation group and the number of retained factors.
        """
    def _repr_html_(self) -> builtins.str:
        r"""
        Show the checked factor group using the tensor index printer.
        """

class NetworkToolingError(builtins.ValueError):
    r"""
    Raised when tensor syntax cannot be interpreted as a supported symbolic network.

    Notes
    -----
    Subclass of ValueError. Catch it around the corresponding tensor operation
    to handle invalid input or an unsupported symbolic form.

    Examples
    --------
    >>> from symbolica.community.tensor import NetworkToolingError
    >>> issubclass(NetworkToolingError, ValueError)
    True
    """
    ...

@typing.final
class PortPattern(Expression):
    r"""
    A Symbolica pattern for a tensor index or its representation.

    Use an exact representation or a wildcard constrained by representation
    tags. Omitting the index produces representation-only syntax for compact
    vectors and traces. These are Expression objects for matching, not actual
    tensor axes with an inferred dimension.

    Examples
    --------
    >>> from symbolica import S
    >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
    >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
    >>> port = PortPattern.self_dual("SelfDual_", D_, i_)
    """
    @staticmethod
    def chain_in() -> PortPattern:
        r"""
        Refer to a factor's input endpoint inside a chain or trace pattern.

        Returns
        -------
        PortPattern
            Contextual endpoint marker, interpreted relative to the surrounding
            factor sequence rather than as an explicit index label.

        Notes
        -----
        Exchange chain_in() and chain_out() in a factor pattern to match its
        transposed orientation.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> gamma = TensorPattern.dirac_gamma(D_, PortPattern.chain_in(), PortPattern.chain_out(), mu_)
        """
    @staticmethod
    def chain_out() -> PortPattern:
        r"""
        Refer to a factor's output endpoint inside a chain or trace pattern.

        Returns
        -------
        PortPattern
            Contextual endpoint marker, interpreted relative to the surrounding
            factor sequence rather than as an explicit index label.

        Notes
        -----
        Exchange chain_in() and chain_out() in a factor pattern to match its
        transposed orientation.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> gamma = TensorPattern.dirac_gamma(D_, PortPattern.chain_in(), PortPattern.chain_out(), mu_)
        """
    @staticmethod
    def exact(rep: Representation, index: typing.Optional[_ScalarInput] = None) -> PortPattern:
        r"""
        Match one specific representation and optionally an index.

        Parameters
        ----------
        rep : Representation
            Representation, including its dimension and duality. Its dimension
            may be a wildcard symbol.
        index : scalar expression, optional
            Exact index or wildcard. Omit it to match representation-only syntax.

        Returns
        -------
        PortPattern
            Symbolica expression for a typed port or a stripped representation.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> port = PortPattern.exact(Representation.euc(3), i_)
        """
    @staticmethod
    def any(name: builtins.str, dimension: _ScalarInput, index: typing.Optional[_ScalarInput] = None) -> PortPattern:
        r"""
        Match any registered representation head.

        Parameters
        ----------
        name : str
            Wildcard name ending in exactly one underscore. Reuse this name
            to constrain multiple occurrences to the same representation.
        dimension : scalar expression
            Dimension value or wildcard.
        index : scalar expression, optional
            Index value or wildcard. Omit for representation-only syntax.

        Returns
        -------
        PortPattern
            Tagged Symbolica pattern, without constructing a concrete index space.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> port = PortPattern.any("R_", D_, i_)
        """
    @staticmethod
    def self_dual(name: builtins.str, dimension: _ScalarInput, index: typing.Optional[_ScalarInput] = None) -> PortPattern:
        r"""
        Match a self-dual representation head.

        Parameters
        ----------
        name : str
            Wildcard name ending in exactly one underscore. Reuse this name
            to constrain multiple occurrences to the same representation.
        dimension : scalar expression
            Dimension value or wildcard.
        index : scalar expression, optional
            Index value or wildcard. Omit for representation-only syntax.

        Returns
        -------
        PortPattern
            Tagged Symbolica pattern, without constructing a concrete index space.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> port = PortPattern.self_dual("SelfDual_", D_, i_)
        """
    @staticmethod
    def dualizable(name: builtins.str, dimension: _ScalarInput, index: typing.Optional[_ScalarInput] = None, *, dual: builtins.bool = False) -> PortPattern:
        r"""
        Match a dualizable representation head.

        Parameters
        ----------
        name : str
            Wildcard name ending in exactly one underscore. Reuse this name
            to constrain multiple occurrences to the same representation.
        dimension : scalar expression
            Dimension value or wildcard.
        index : scalar expression, optional
            Index value or wildcard. Omit for representation-only syntax.
        dual : bool, default False
            Match the dual partner rather than the base orientation.

        Returns
        -------
        PortPattern
            Tagged Symbolica pattern, without constructing a concrete index space.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> port = PortPattern.dualizable("Dual_", D_, i_)
        """

@typing.final
class ReductionStatus:
    r"""
    Completion of a tensor reduction under its selected settings.

    Complete means no eligible work remains. Deferred means exact eligible work
    remains for another operation. Capped means an explicitly requested work limit
    stopped processing. A partial result still represents the exact original tensor;
    completion is relative to the requested operations, not every possible identity.

    Examples
    --------
    >>> from symbolica.community.tensor import TensorExpression, ReductionStatus
    >>> result = TensorExpression(3).contract()
    >>> result.reduction_status == ReductionStatus.Complete
    True
    """
    Complete: typing.ClassVar[ReductionStatus]
    r"""
    No eligible work remains under the requested settings.
    """
    Deferred: typing.ClassVar[ReductionStatus]
    r"""
    Exact eligible work remains for a subsequent operation.
    """
    Capped: typing.ClassVar[ReductionStatus]
    r"""
    An explicit work limit stopped processing; the remaining expression is exact.
    """
    def __int__(self) -> builtins.int:
        r"""
        Return the underlying integer discriminant.
        """

@typing.final
class Representation:
    r"""
    An index space with a dimension and a rule for pairing indices.

    Use representations to distinguish axes that have the same size but different
    mathematical meanings. A self-dual space pairs with itself; a dualizable space
    pairs with its ``dual()``. Calling a representation assigns an index label.
    Built-in spaces include Euclidean and Minkowski vectors, Dirac spinors, and
    color representations; custom spaces work with the same tensor operations.

    Examples
    --------
    >>> from symbolica.community.tensor import Representation, TensorName
    >>> space = Representation.euc(3)
    >>> vector = TensorName.vector("v")(space)
    >>> vector("i").rank
    1
    """
    @property
    def name(self) -> RepresentationName:
        r"""
        The registered space identity and duality, without its dimension.

        Returns
        -------
        RepresentationName
            Metadata shared by this representation at different dimensions.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> Representation.euc(3).name == Representation.euc(5).name
        True
        """
    @property
    def dimension(self) -> Expression:
        r"""
        The dimension of this index space as a Symbolica expression.

        Returns
        -------
        Expression
            An integer-valued expression or a dimension symbol.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> Representation.euc(3).dimension == 3
        True
        """
    def __eq__(self, other: builtins.object) -> builtins.bool: ...
    @typing.overload
    def __call__(self, aind: builtins.int | builtins.str) -> Slot:
        r"""
        Attach an abstract index label to this space.

        Parameters
        ----------
        aind : int, str, or Expression
            An index label, not a component coordinate. A string, Python integer, or
            single symbol creates a Slot. Other Expressions retain raw representation
            syntax: supported numeric, tagged named, and scoped labels can be admitted
            directly; other compound payloads require ``intern="indices"`` when
            constructing a tensor.

        Returns
        -------
        Slot or Expression
            A typed index, or symbolic syntax for a compound index payload.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import Representation, Slot
        >>> space = Representation.euc(3)
        >>> isinstance(space(S("i")), Slot)
        True
        """
    @typing.overload
    def __call__(self, aind: Expression) -> Expression | Slot:
        r"""
        Attach an abstract index label to this space.

        Parameters
        ----------
        aind : int, str, or Expression
            An index label, not a component coordinate. A string, Python integer, or
            single symbol creates a Slot. Other Expressions retain raw representation
            syntax: supported numeric, tagged named, and scoped labels can be admitted
            directly; other compound payloads require ``intern="indices"`` when
            constructing a tensor.

        Returns
        -------
        Slot or Expression
            A typed index, or symbolic syntax for a compound index payload.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import Representation, Slot
        >>> space = Representation.euc(3)
        >>> isinstance(space(S("i")), Slot)
        True
        """
    def _repr_html_(self) -> builtins.str: ...
    def to_html(self) -> builtins.str:
        r"""
        Render a compact HTML view of this tensor metadata.

        Returns
        -------
        str
            HTML fragment for display in a notebook or page.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> value = Representation.euc(3)
        >>> html = value.to_html()
        """
    def _repr_latex_(self) -> builtins.str: ...
    def __new__(cls, name: builtins.str, dimension: builtins.int | Expression | str, is_self_dual: builtins.bool = True) -> Representation:
        r"""
        Create or reuse a named index space.

        Parameters
        ----------
        name : str
            Registered name distinguishing this space from other representations.
        dimension : int, Expression, or str
            Number of components in this index space, or a symbol naming that number.
            An Expression must be a single symbol, not a sum or product.
        is_self_dual : bool, default True
            Whether indices pair with the same space. False creates a space with
            a distinct dual; use ``dual()`` to obtain it.

        Returns
        -------
        Representation
            The requested space, ready to use as an unresolved tensor axis.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> space = Representation("Flavor", 5, is_self_dual=False)
        >>> space.dual().dual() == space
        True
        """
    def dual(self) -> Representation:
        r"""
        Return the space that pairs with this one under contraction.

        Returns
        -------
        Representation
            The same space for a self-dual representation; its partner otherwise.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> Representation.euc(3).dual() == Representation.euc(3)
        True
        >>> Representation.cof(3).dual().dual() == Representation.cof(3)
        True
        """
    def casimir(self, degree: _ScalarInput = 2) -> Expression:
        r"""
        Construct the degree-dependent Casimir eigenvalue.

        Parameters
        ----------
        degree : scalar expression, default 2
            Degree of the invariant. The default is the quadratic invariant.

        Returns
        -------
        Expression
            A symbolic scalar invariant; constructing it does not evaluate a
            group-specific formula.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> invariant = Representation.cof(3).casimir()
        """
    def dynkin_index(self, degree: _ScalarInput = 2) -> Expression:
        r"""
        Construct the degree-dependent Dynkin index.

        Parameters
        ----------
        degree : scalar expression, default 2
            Degree of the invariant. The default is the quadratic invariant.

        Returns
        -------
        Expression
            A symbolic scalar invariant; constructing it does not evaluate a
            group-specific formula.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> invariant = Representation.cof(3).dynkin_index()
        """
    def gram(self, degree: _ScalarInput, other: typing.Optional[Representation] = None) -> Expression:
        r"""
        Construct a Gram invariant for two representations.

        Parameters
        ----------
        degree : scalar expression
            Degree of the invariant.
        other : Representation, optional
            Second representation. Defaults to this representation.

        Returns
        -------
        Expression
            A symbolic Gram invariant, without evaluating a group-specific formula.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> invariant = Representation.cof(3).gram(2)
        """
    def g(self, i: builtins.int | Expression | str, j: builtins.int | Expression | str) -> TensorExpression:
        r"""
        Create the metric with two explicit index labels.

        Parameters
        ----------
        i, j : int, str, or Expression
            Abstract index labels accepted by the shared tensor-structure parser,
            including numeric, symbolic, tagged named, and scoped indices.

        Returns
        -------
        TensorExpression
            The indexed rank-two tensor, or its contraction when the labels pair.

        Notes
        -----
        Both ports belong to this representation. For a pairing between a space
        and its dual, use ``id`` or ``TensorExpression.g(rep, rep.dual())``.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> tensor = Representation.euc(3).g("i", "j")
        >>> tensor.rank
        2
        """
    def flat(self, i: builtins.int | Expression | str, j: builtins.int | Expression | str) -> TensorExpression:
        r"""
        Create the metric map used to lower or raise an index.

        Parameters
        ----------
        i, j : int, str, or Expression
            Abstract index labels accepted by the shared tensor-structure parser,
            including numeric, symbolic, tagged named, and scoped indices.

        Returns
        -------
        TensorExpression
            The indexed rank-two tensor, or its contraction when the labels pair.

        Notes
        -----
        Both ports belong to this representation. The flat map accounts for the
        metric signs when identifying vectors and covectors.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> tensor = Representation.euc(3).flat("i", "j")
        >>> tensor.rank
        2
        """
    def id(self, i: builtins.int | Expression | str, j: builtins.int | Expression | str) -> TensorExpression:
        r"""
        Create the identity pairing between this space and its dual.

        Parameters
        ----------
        i, j : int, str, or Expression
            Abstract index labels accepted by the shared tensor-structure parser,
            including numeric, symbolic, tagged named, and scoped indices.

        Returns
        -------
        TensorExpression
            The indexed rank-two tensor, or its contraction when the labels pair.

        Notes
        -----
        The first port is in ``self.dual()`` and the second in ``self``.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> tensor = Representation.euc(3).id("i", "j")
        >>> tensor.rank
        2
        """
    def __repr__(self) -> builtins.str:
        r"""
        Return a readable object description for inspection.

        Examples
        --------
        >>> from symbolica.community import tensor as sp
        >>> r = sp.Representation.mink(4)
        >>> text = repr(r)
        """
    def __str__(self) -> builtins.str:
        r"""
        Return a readable text representation.

        Examples
        --------
        >>> from symbolica.community import tensor as sp
        >>> r = sp.Representation.mink(4)
        >>> text = str(r)
        """
    def to_expression(self) -> Expression:
        r"""
        Return the symbolic encoding of the space and its dimension.

        Returns
        -------
        Expression
            Representation syntax without an index label. Use the Representation
            itself when constructing tensor axes.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> encoded = Representation.euc(3).to_expression()
        """
    @staticmethod
    def bis(dimension: builtins.int | Expression | str) -> Representation:
        r"""
        Create the Dirac bispinor space.

        Parameters
        ----------
        dimension : int, Expression, or str
            Number of components in this index space, or a symbol naming that number.
            An Expression must be a single symbol, not a sum or product.

        Returns
        -------
        Representation
            The built-in index space with the supplied dimension.

        Notes
        -----
        This is the self-dual spinor index space used by the Dirac-matrix helpers.
        Its dimension counts spinor components, not space-time coordinates.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> space = Representation.bis(4)
        >>> space.dimension == 4
        True
        """
    @staticmethod
    def euc(dimension: builtins.int | Expression | str) -> Representation:
        r"""
        Create the Euclidean vector space.

        Parameters
        ----------
        dimension : int, Expression, or str
            Number of components in this index space, or a symbol naming that number.
            An Expression must be a single symbol, not a sum or product.

        Returns
        -------
        Representation
            The built-in index space with the supplied dimension.

        Notes
        -----
        The space is self-dual, with positive metric signs on every component.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> space = Representation.euc(3)
        >>> space.dimension == 3
        True
        """
    @staticmethod
    def mink(dimension: builtins.int | Expression | str) -> Representation:
        r"""
        Create the Minkowski vector space.

        Parameters
        ----------
        dimension : int, Expression, or str
            Number of components in this index space, or a symbol naming that number.
            An Expression must be a single symbol, not a sum or product.

        Returns
        -------
        Representation
            The built-in index space with the supplied dimension.

        Notes
        -----
        The space is self-dual, with metric signature (+, -, ..., -).
        Component zero is the time coordinate.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> space = Representation.mink(4)
        >>> space.dimension == 4
        True
        """
    @staticmethod
    def cof(dimension: builtins.int | Expression | str) -> Representation:
        r"""
        Create the fundamental color representation.

        Parameters
        ----------
        dimension : int, Expression, or str
            Number of components in this index space, or a symbol naming that number.
            An Expression must be a single symbol, not a sum or product.

        Returns
        -------
        Representation
            The built-in index space with the supplied dimension.

        Notes
        -----
        For SU(N), the dimension is N. This space pairs with its distinct dual,
        the antifundamental representation.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> space = Representation.cof(3)
        >>> space.dimension == 3
        True
        """
    @staticmethod
    def coad(dimension: builtins.int | Expression | str) -> Representation:
        r"""
        Create the adjoint color representation.

        Parameters
        ----------
        dimension : int, Expression, or str
            Number of components in this index space, or a symbol naming that number.
            An Expression must be a single symbol, not a sum or product.

        Returns
        -------
        Representation
            The built-in index space with the supplied dimension.

        Notes
        -----
        For SU(N), pass N**2 - 1 (for example 8 for SU(3)). This space is self-dual.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> space = Representation.coad(8)
        >>> space.dimension == 8
        True
        """
    @staticmethod
    def cos(dimension: builtins.int | Expression | str) -> Representation:
        r"""
        Create the sextet color representation.

        Parameters
        ----------
        dimension : int, Expression, or str
            Number of components in this index space, or a symbol naming that number.
            An Expression must be a single symbol, not a sum or product.

        Returns
        -------
        Representation
            The built-in index space with the supplied dimension.

        Notes
        -----
        The SU(3) sextet has dimension 6 and a distinct dual representation.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> space = Representation.cos(6)
        >>> space.dimension == 6
        True
        """

@typing.final
class RepresentationName:
    r"""
    A representation identity independent of its dimension.

    Obtain this read-only metadata through ``Representation.name``. It distinguishes
    self-dual spaces from the two partners of a dualizable space.

    Examples
    --------
    >>> from symbolica.community.tensor import Representation
    >>> identity = Representation.mink(4).name
    >>> identity.duality
    'self-dual'
    """
    @property
    def name(self) -> builtins.str:
        r"""
        The exact registered name of the representation.

        Returns
        -------
        str
            Name without dimension or index arguments.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> identity = Representation.mink(4).name
        >>> name = identity.name
        """
    @property
    def duality(self) -> builtins.str:
        r"""
        How this representation pairs with another space.

        Returns
        -------
        str
            One of "self-dual", "base", or "dual".

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> identity = Representation.mink(4).name
        >>> identity.duality
        'self-dual'
        """
    def __eq__(self, other: builtins.object) -> builtins.bool: ...
    def dual(self) -> RepresentationName:
        r"""
        Return the dimension-independent identity of the paired space.

        Returns
        -------
        RepresentationName
            The same identity for a self-dual space; the dual partner otherwise.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> identity = Representation.cof(3).name
        >>> identity.dual().dual() == identity
        True
        """
    def metric_sign(self, index: builtins.int) -> builtins.int:
        r"""
        Return the sign of the canonical pairing at a component coordinate.

        Parameters
        ----------
        index : int
            Nonnegative component coordinate. This identity has no dimension, so
            the coordinate is not checked against a particular tensor shape.

        Returns
        -------
        int
            +1 or -1. In Minkowski space, zero gives +1 and spatial coordinates -1.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> metric = Representation.mink(4).name
        >>> [metric.metric_sign(i) for i in range(4)]
        [1, -1, -1, -1]
        """
    def __str__(self) -> builtins.str:
        r"""
        Return a readable text representation.

        Examples
        --------
        >>> from symbolica.community import tensor as sp
        >>> name = sp.Representation.mink(4).name
        >>> text = str(name)
        """
    def __repr__(self) -> builtins.str:
        r"""
        Return a readable object description for inspection.

        Examples
        --------
        >>> from symbolica.community import tensor as sp
        >>> name = sp.Representation.mink(4).name
        >>> text = repr(name)
        """
    def to_html(self) -> builtins.str:
        r"""
        Render a compact HTML view of this tensor metadata.

        Returns
        -------
        str
            HTML fragment for display in a notebook or page.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> value = Representation.mink(4).name
        >>> html = value.to_html()
        """
    def _repr_html_(self) -> builtins.str: ...

@typing.final
class Slot:
    r"""
    One abstract tensor index together with its representation.

    An index label identifies a possible contraction; it is not a component
    coordinate. Prefer ``space("i")`` to construct a slot for an existing space.

    Examples
    --------
    >>> from symbolica.community.tensor import Representation
    >>> slot = Representation.euc(3)("i")
    >>> slot.representation == Representation.euc(3)
    True
    """
    @property
    def index(self) -> Expression:
        r"""
        The abstract label carried by this slot.

        Returns
        -------
        Expression
            Symbolic label or integer; not a component coordinate.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> slot = Representation.euc(3)("i")
        >>> label = slot.index
        """
    @property
    def representation(self) -> Representation:
        r"""
        The dimensioned space to which this index belongs.

        Returns
        -------
        Representation
            Includes the duality of the slot.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> slot = Representation.euc(3)("i")
        >>> space = slot.representation
        """
    def __eq__(self, other: builtins.object) -> builtins.bool: ...
    def __hash__(self) -> builtins.int:
        r"""
        Hash the immutable representation and index label for dictionaries and sets.

        Examples
        --------
        >>> from symbolica.community import tensor as sp
        >>> r = sp.Representation.euc(2)
        >>> labels = {r("i"): "free index"}
        >>> assert labels[r("i")] == "free index"
        """
    def _repr_html_(self) -> builtins.str: ...
    def to_html(self, *, settings: typing.Optional[DisplaySettings] = None) -> builtins.str:
        r"""
        Render a compact HTML view of this tensor metadata.

        Parameters
        ----------
        settings : DisplaySettings, optional
            Index and tensor presentation choices; defaults to DisplaySettings().

        Returns
        -------
        str
            HTML fragment for display in a notebook or page.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> value = Representation.euc(3)("i")
        >>> html = value.to_html()
        """
    def _repr_latex_(self) -> builtins.str: ...
    def __repr__(self) -> builtins.str:
        r"""
        Return a readable object description for inspection.

        Examples
        --------
        >>> from symbolica.community import tensor as sp
        >>> slot = sp.Representation.mink(4)("mu")
        >>> text = repr(slot)
        """
    def __str__(self) -> builtins.str:
        r"""
        Return a readable text representation.

        Examples
        --------
        >>> from symbolica.community import tensor as sp
        >>> slot = sp.Representation.mink(4)("mu")
        >>> text = str(slot)
        """
    def dual(self) -> Slot:
        r"""
        Pair this index label with the dual representation.

        Returns
        -------
        Slot
            A new slot with the same label.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> slot = Representation.euc(3)("i")
        >>> paired = slot.dual()
        """
    def __new__(cls, name: builtins.str, dimension: builtins.int, aind: builtins.int | Expression | str, dual: builtins.bool = False) -> Slot:
        r"""
        Create a labeled index in a registered representation.

        Parameters
        ----------
        name : str
            Registered representation name.
        dimension : int
            Dimension of the index space.
        aind : int, str, or Expression
            Abstract index label accepted by the shared tensor-structure parser,
            including numeric, symbolic, tagged named, and scoped indices.
        dual : bool, default False
            Whether to use the dual of the named representation.

        Returns
        -------
        Slot
            The representation and index label together.

        Notes
        -----
        Use ``Representation.euc(3)("i")`` when working with representation objects.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, Slot
        >>> space = Representation.euc(3)
        >>> slot = Slot(space.name.name, 3, "i")
        >>> slot == space("i")
        True
        """
    def to_expression(self) -> Expression:
        r"""
        Return symbolic syntax for the representation and index.

        Returns
        -------
        Expression
            The encoded slot, for use in raw Symbolica expressions.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation
        >>> slot = Representation.euc(3)("i")
        >>> encoded = slot.to_expression()
        """

@typing.final
class SymbolicParallelism:
    r"""
    Threading policy for operations on symbolic component expressions.

    ``Auto`` permits parallel work when the Symbolica license supports it,
    with workload-size heuristics. ``Serial`` keeps symbolic work on the calling
    thread. ``Parallel`` requests parallel work without Auto's license check.
    This does not set the number of threads or force every operation to parallelize.

    Examples
    --------
    >>> from symbolica.community.tensor import SymbolicParallelism, set_symbolica_rayon_enabled
    >>> allowed = set_symbolica_rayon_enabled(SymbolicParallelism.Auto)
    """
    Auto: typing.ClassVar[SymbolicParallelism]
    r"""
    Permit Rayon when licensed and use workload heuristics where available.
    """
    Serial: typing.ClassVar[SymbolicParallelism]
    r"""
    Keep symbolic operations on the calling thread.
    """
    Parallel: typing.ClassVar[SymbolicParallelism]
    r"""
    Force Rayon without `Auto`'s Symbolica license safety check.
    """
    def __int__(self) -> builtins.int:
        r"""
        Return the underlying integer discriminant.
        """

@typing.final
class Tensor:
    r"""
    Tensor components together with their symbolic identity and ordered axes.

    Use dense(), sparse(), or from_numpy() to construct one. Components can be
    real floats, complex floats, or Symbolica expressions. Square brackets access
    components; calling the tensor assigns abstract index labels and returns a
    lazy TensorNetwork. Arithmetic also builds networks, retaining component data.

    The default notebook view is an interactive component explorer with a matrix
    toggle. ``to_typst()`` provides static mathematical source.

    Examples
    --------
    >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
    >>> space = Representation.euc(2)
    >>> A = TensorName("M")(space, space)
    >>> from symbolica.community.tensor import Tensor
    >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
    >>> tensor[1, 0]
    3.0
    """
    @property
    def dtype(self) -> type[float] | type[complex] | type[Expression]:
        r"""
        Python type used for the stored components.

        Returns
        -------
        type
            One of float, complex, or Expression.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> tensor.dtype is float
        True
        """
    @property
    def storage(self) -> typing.Literal['dense', 'sparse']:
        r"""
        How components are stored.

        Returns
        -------
        str
            "dense" for all entries, or "sparse" for populated entries.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> tensor.storage
        'dense'
        """
    @property
    def rank(self) -> builtins.int:
        r"""
        Number of external tensor axes.

        Returns
        -------
        int
            Zero for a scalar.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> tensor.rank
        2
        """
    @property
    def is_scalar(self) -> builtins.bool:
        r"""
        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(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> tensor.is_scalar
        False
        """
    @property
    def shape(self) -> tuple[int, ...]:
        r"""
        Dimensions in logical axis order.

        Returns
        -------
        tuple of int
            Axis sizes in the order of axes, the current component view.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> tensor.shape
        (2, 2)
        """
    @property
    def axes(self) -> tuple[Slot | Representation, ...]:
        r"""
        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"))
        True
        >>> A.permute_axes([1, 0]).axes == A.axes[::-1]
        True
        """
    @property
    def structure(self) -> TensorStructure:
        r"""
        Canonical external signature of the whole tensor.

        Returns
        -------
        TensorStructure
            Free axes in canonical order, independent of names and component layout.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> tensor.structure.rank
        2
        """
    def copy(self) -> Tensor:
        r"""
        Copy this tensor's components and metadata.

        Returns
        -------
        Tensor
            An independent copy. Changes to it do not alter the original.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> copied = tensor.copy()
        >>> copied.shape == tensor.shape
        True
        """
    def map_components(self, callback: typing.Callable[[Expression | float | complex], Expression | float | complex], *, dtype: type[float] | type[complex] | type[Expression] | None = None) -> Tensor:
        r"""
        Apply a scalar function to component values.

        Parameters
        ----------
        callback : callable
            Function receiving one component and returning its replacement.
            The traversal order is unspecified.
        dtype : type, optional
            Output component type: float, complex, or Expression. Defaults to
            the current type; callback results must convert to the selected type.

        Returns
        -------
        Tensor
            An independent tensor with the same axes and mapped components.

        Notes
        -----
        Sparse storage remains sparse when the implicit zero maps to zero.
        If it maps to a nonzero value, the result becomes dense. The implicit
        zero is mapped once; avoid relying on callback invocation counts.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> tensor.map_components(lambda value: value * 2)[1, 0]
        6.0
        """
    def to_numpy(self) -> numpy.typing.NDArray[numpy.float64] | numpy.typing.NDArray[numpy.complex128]:
        r"""
        Copy numerical components into a NumPy array.

        Numeric Expression literals, such as exact results of a contraction,
        are rounded to float64. The array uses complex128 if a converted
        value has a nonzero imaginary part.

        Returns
        -------
        numpy.ndarray
            Array with the tensor's logical shape and dtype float64 or complex128.

        Raises
        ------
        TypeError
            An Expression component is not a numeric literal. Evaluate it first.
        ValueError
            An Expression component converts to a nonfinite value.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> tensor.to_numpy().tolist()
        [[1.0, 2.0], [3.0, 4.0]]
        """
    @staticmethod
    def from_numpy(structure: TensorExpression, array: numpy.typing.ArrayLike) -> Tensor:
        r"""
        Copy a numerical array into a named tensor.

        Parameters
        ----------
        structure : TensorExpression
            Named descriptor with concrete dimensions matching the array shape.
        array : numpy.typing.ArrayLike
            Real or complex array-like data. Axes follow the descriptor's current axes.

        Returns
        -------
        Tensor
            Dense tensor with float or complex components.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.from_numpy(A, [[1.0, 2.0], [3.0, 4.0]])
        >>> tensor[1, 0]
        3.0
        """
    def evaluator(self, params: typing.Sequence[Expression], functions: typing.Sequence[FunctionDefinition] = [], iterations: builtins.int = 1, cpe_iterations: typing.Optional[builtins.int] = None, n_cores: builtins.int = 4, verbose: builtins.bool = False, jit_compile: builtins.bool = True, direct_translation: builtins.bool = True, jit_direct_translation: builtins.bool = False, jit_optimization_level: builtins.int = 3, jit_options: typing.Mapping[builtins.str, builtins.str] = {}, max_horner_scheme_variables: builtins.int = 500, max_common_pair_cache_entries: builtins.int = 1000000, max_common_pair_distance: builtins.int = 100, horner_use_cpe: builtins.bool = False) -> TensorEvaluator:
        r"""
        Optimise all components together using Symbolica's evaluator.

        Accepts the same parameters, FunctionDefinitions, optimisation controls,
        and JIT settings as Expression.evaluator. Fixed values can be substituted
        before construction. Evaluation returns one Tensor per input row, retaining
        the logical axes and data identity. JIT compilation occurs on first use.
        Set `horner_use_cpe=True` to include common-pair elimination when scoring
        Horner candidates. Final common-pair elimination remains enabled in both
        modes and is bounded by `cpe_iterations`.

        >>> from symbolica import S
        >>> from symbolica.community.tensor import Tensor, TensorName, Representation
        >>> x = S("x")
        >>> values = Tensor.dense(TensorName.vector("eval_v")(Representation.euc(2)), [x, x**2])
        >>> values.evaluator([x]).evaluate([[2.0]])[0][1]
        4.0
        """
    def expression(self) -> TensorExpression:
        r"""
        Return the symbolic descriptor for these components.

        Returns
        -------
        TensorExpression
            A symbolic tensor with the same external axes.

        Notes
        -----
        The descriptor identifies the data but does not embed its components.
        Register the tensor in a TensorLibrary to evaluate that symbolic reference.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> tensor.expression().rank
        2
        """
    def with_name(self, name: TensorName | builtins.str | Expression | TensorExpression) -> Tensor:
        r"""
        Assign a data identity without rewriting the symbolic computation.

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

        Returns
        -------
        Tensor
            A new value with the requested identity and the same axes and components.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> named = tensor.with_name("named_matrix")
        >>> named.rank
        2
        """
    @staticmethod
    def sparse(structure: TensorExpression, type_info: type) -> Tensor:
        r"""
        Create an initially zero tensor using sparse component storage.

        Parameters
        ----------
        structure : TensorExpression
            Named descriptor with concrete dimensions in logical axis order.
        type_info : type
            Component type: float or Expression. Expression storage preserves
            exact symbolic values and accepts integer assignments without rounding.
            Floating-point storage requires numerical assignments.

        Returns
        -------
        Tensor
            A zero tensor storing only explicitly populated entries.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.sparse(A, float)
        >>> tensor[1, 0] = 3.0
        >>> tensor[0, 0]
        0.0
        """
    @staticmethod
    def dense(structure: TensorExpression, data: typing.Sequence[Expression | int | builtins.complex | float]) -> Tensor:
        r"""
        Store every component of a named tensor.

        Parameters
        ----------
        structure : TensorExpression
            Named descriptor with concrete dimensions and the desired logical
            axis order. Use with_name() to give a composite expression a name.
        data : sequence of int, float, complex, or Expression
            Flat component data in logical row-major order. The length must equal
            the product of the dimensions. An explicit Expression selects symbolic
            storage for the sequence, preserving exact rational and algebraic
            values. Integer-only input is exact too. Float or complex sequences
            without Expressions retain numerical storage.

        Returns
        -------
        Tensor
            A dense component tensor; the input descriptor remains symbolic.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> tensor.shape
        (2, 2)
        """
    def to_dense(self) -> Tensor:
        r"""
        Copy the components into dense storage.

        Returns
        -------
        Tensor
            Independent dense tensor with the same values and logical axes.

        Notes
        -----
        Dense storage allocates space for every component.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> tensor.to_dense().storage
        'dense'
        """
    def to_sparse(self) -> Tensor:
        r"""
        Copy the components into sparse storage.

        Returns
        -------
        Tensor
            Independent sparse tensor with the same values and logical axes.

        Notes
        -----
        Sparse storage retains nonzero entries and represents other entries by zero.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> tensor.to_sparse().storage
        'sparse'
        """
    def __repr__(self) -> builtins.str:
        r"""
        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)
        >>> tensor = sp.Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> text = repr(tensor)
        """
    def __str__(self) -> builtins.str:
        r"""
        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)
        >>> tensor = sp.Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> text = str(tensor)
        """
    def format_tensor(self, show_dimensions: typing.Optional[builtins.bool] = None, *, settings: typing.Optional[DisplaySettings] = None) -> builtins.str:
        r"""
        Produce compact plain-text tensor notation.

        Parameters
        ----------
        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
        -------
        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.

        Components follow the current view's logical interface order (the order
        of axes), independently of the canonical structure signature. Large
        static displays show a bounded preview rather than every component.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> output = tensor.format_tensor()
        """
    def to_typst(self, show_dimensions: typing.Optional[builtins.bool] = None, *, settings: typing.Optional[DisplaySettings] = None) -> builtins.str:
        r"""
        Produce static Typst math source.

        Parameters
        ----------
        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
        -------
        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.

        Components follow the current view's logical interface order (the order
        of axes), independently of the canonical structure signature. Large
        static displays show a bounded preview rather than every component.

        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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> output = tensor.to_typst()
        """
    def to_typst_project(self, show_dimensions: typing.Optional[builtins.bool] = None, *, settings: typing.Optional[DisplaySettings] = None, notation_source: typing.Optional[builtins.str] = None) -> dict:
        r"""
        Return the source files of a complete Typst project without compiling it.
        Custom notation is source code for `notation.typ` in the returned mapping.

        # Errors

        Returns a Python exception if the tensor cannot be serialized. Registered
        Python printer exceptions are logged and decline the override, allowing
        native fallback. Exporting does not import or invoke a compiler.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, Tensor, TensorName
        >>> tensor = Tensor.dense(TensorName("A")(Representation.euc(2)), [1., 2.])
        >>> project = tensor.to_typst_project()
        >>> sorted(project)
        ['main.typ', 'notation.typ', 'render.typ', 'tree.cbor']
        """
    def formatted(self, show_dimensions: typing.Optional[builtins.bool] = None, *, settings: typing.Optional[DisplaySettings] = None, notation_source: typing.Optional[builtins.str] = None) -> FormattedOutput:
        r"""
        Create a rich display value for a notebook.

        Parameters
        ----------
        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 formatted output; raises ValueError.
            Use to_typst_project() or to_svg() for custom Typst notation.

        Returns
        -------
        FormattedOutput
            Symbolica display wrapper with text and available rich representations.

        Notes
        -----
        Components follow logical axis order. Large static displays show a
        bounded preview rather than every component.

        # 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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> output = tensor.formatted()
        """
    def to_html(self, show_dimensions: typing.Optional[builtins.bool] = None, *, settings: typing.Optional[DisplaySettings] = None, notation_source: typing.Optional[builtins.str] = None) -> builtins.str:
        r"""
        Render the tensor as an HTML fragment.

        Parameters
        ----------
        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 formatted output; raises ValueError.
            Use to_typst_project() or to_svg() for custom Typst notation.

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

        Notes
        -----
        Mathematical rendering uses direct MathML without a Typst compiler.
        Pass the returned fragment to the notebook's HTML display facility.

        Components follow logical axis order. Large static displays show a
        bounded preview rather than every component.

        The default is a responsive component explorer with a Memory grid /
        Matrix toggle. Dark mode follows the surrounding page. The color scale
        measures stored component payload bytes, not total process memory. Use
        DisplaySettings(tensor_view="matrix") for static mathematical HTML.

        # 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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> output = tensor.to_html()
        """
    def to_svg(self, show_dimensions: typing.Optional[builtins.bool] = None, *, settings: typing.Optional[DisplaySettings] = None, notation_source: typing.Optional[builtins.str] = None) -> builtins.str:
        r"""
        Render static mathematical tensor notation to SVG.

        Parameters
        ----------
        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
        -------
        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.

        Components follow logical axis order. Large static displays show a
        bounded preview rather than every component.

        # 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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> output = tensor.to_svg()
        """
    def _repr_html_(self) -> typing.Optional[builtins.str]: ...
    def _repr_latex_(self) -> typing.Optional[builtins.str]: ...
    def _repr_pretty_(self, pretty: typing.Any, cycle: builtins.bool) -> None: ...
    def __len__(self) -> builtins.int:
        r"""
        Count all components in the tensor shape.

        Returns
        -------
        int
            Product of the axis dimensions, including implicit zeros.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> len(tensor)
        4
        """
    def scalar(self) -> Expression:
        r"""
        Extract the only component of a rank-zero tensor.

        Examples
        --------
        >>> from symbolica.community import tensor as sp
        >>> scalar = sp.Tensor.dense(sp.TensorName("docs::scalar")(), [2.0])
        >>> value = scalar.scalar()

        Returns
        -------
        Expression
            Scalar value converted to a Symbolica expression, including numeric data.

        Raises
        ------
        RuntimeError
            The tensor has external axes.

        Examples
        --------
        >>> from symbolica.community.tensor import TensorExpression
        >>> TensorExpression(3).to_tensor().scalar() == 3
        True
        """
    def index(self, *indices: _IndexInput, intern: typing.Optional[typing.Literal['indices', 'flattened']] = None) -> TensorNetwork:
        r"""
        Assign labels to the unresolved external axes.

        Parameters
        ----------
        *indices : int, str, Expression, Slot, or AUTO
            One label per unresolved axis, in logical order. AUTO leaves the
            corresponding axis unchanged. A Slot must have the matching
            representation. Repeated compatible labels cause contraction.
        intern : {"indices", "flattened"} or None, optional
            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.

        Returns
        -------
        TensorNetwork
            An indexed network retaining the component data; the original is unchanged.

        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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> indexed = tensor.index("i", "j")
        >>> indexed.rank
        2
        """
    def reindex(self, *indices: _IndexInput, intern: typing.Optional[typing.Literal['indices', 'flattened']] = None) -> TensorNetwork:
        r"""
        Assign labels to all external axes.

        Parameters
        ----------
        *indices : int, str, Expression, Slot, or AUTO
            One label per external axis, in logical order. AUTO leaves the
            corresponding axis unchanged. A Slot must have the matching
            representation. Repeated compatible labels cause contraction.
        intern : {"indices", "flattened"} or None, optional
            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.

        Returns
        -------
        TensorNetwork
            An indexed network retaining the component data; the original is unchanged.

        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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> indexed = tensor.reindex("i", "j")
        >>> indexed.rank
        2
        """
    def rename_indices(self, mapping: dict[int | str | Expression | Slot, _IndexInput], *, intern: typing.Optional[typing.Literal['indices', 'flattened']] = None) -> Tensor:
        r"""
        Rename selected external labels without changing the tensor rank.

        Parameters
        ----------
        mapping : dict
            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.
        intern : {"indices", "flattened"} or None, optional
            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.

        Returns
        -------
        Tensor
            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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> indexed = Tensor.dense(A("i", "j"), [1.0, 2.0, 3.0, 4.0])
        >>> indexed.rename_indices({"i": "k"}).rank
        2
        """
    def permute_axes(self, axes: typing.Sequence[builtins.int]) -> Tensor:
        r"""
        Reorder the external axes in logical component order.

        Parameters
        ----------
        axes : sequence of int
            Each current axis position exactly once, in the desired new order.
            For a matrix, [1, 0] exchanges the two axes.

        Returns
        -------
        Tensor
            A new tensor view with the reordered interface and correspondingly
            reordered component access.

        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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> transposed = tensor.permute_axes([1, 0])
        >>> transposed.shape
        (2, 2)
        """
    def __copy__(self) -> Tensor:
        r"""
        Implement ``copy.copy`` using an independent Tensor copy.

        Returns
        -------
        Tensor
            Copy of the component data and metadata.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> import copy
        >>> copied = copy.copy(tensor)
        """
    def __call__(self, *indices: _IndexInput, intern: typing.Optional[typing.Literal['indices', 'flattened']] = None) -> TensorNetwork:
        r"""
        Assign labels to the unresolved external axes.

        Parameters
        ----------
        *indices : int, str, Expression, Slot, or AUTO
            One label per unresolved axis, in logical order. AUTO leaves the
            corresponding axis unchanged. A Slot must have the matching
            representation. Repeated compatible labels cause contraction.
        intern : {"indices", "flattened"} or None, optional
            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.

        Returns
        -------
        TensorNetwork
            An indexed network retaining the component data; the original is unchanged.

        Notes
        -----
        Equivalent to ``index(*indices)``.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> indexed = tensor("i", "j")
        >>> indexed.rank
        2
        """
    def __neg__(self) -> TensorNetwork:
        r"""
        Negate every tensor component.

        Returns
        -------
        TensorNetwork
            Negated symbolic algebra retaining component data lazily.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> negated = -tensor
        """
    def __add__(self, rhs: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> TensorNetwork:
        r"""
        Add tensors with compatible external interfaces.

        Parameters
        ----------
        rhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        Returns
        -------
        TensorNetwork
            New lazy calculation; operands are unchanged.

        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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> result = tensor + tensor
        """
    def __radd__(self, lhs: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> TensorNetwork:
        r"""
        Implement reflected addition.

        Parameters
        ----------
        lhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        Returns
        -------
        TensorNetwork
            New lazy calculation; operands are unchanged.

        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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> result = tensor + tensor
        """
    def __sub__(self, rhs: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> TensorNetwork:
        r"""
        Subtract tensors with compatible external interfaces.

        Parameters
        ----------
        rhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        Returns
        -------
        TensorNetwork
            New lazy calculation; operands are unchanged.

        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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> result = tensor - tensor
        """
    def __rsub__(self, lhs: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> TensorNetwork:
        r"""
        Implement reflected subtraction.

        Parameters
        ----------
        lhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        Returns
        -------
        TensorNetwork
            New lazy calculation; operands are unchanged.

        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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> result = tensor - tensor
        """
    def __mul__(self, rhs: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> TensorNetwork:
        r"""
        Multiply tensors, contracting unambiguous compatible axes.

        Parameters
        ----------
        rhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        Returns
        -------
        TensorNetwork
            New lazy calculation; operands are unchanged.

        Notes
        -----
        Matching explicit labels contract. Compatible unresolved axes are
        paired only when the choice is unambiguous. Use outer(), contract(),
        or compose() to make the intended pairing explicit.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> result = tensor * 2
        """
    def __rmul__(self, lhs: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> TensorNetwork:
        r"""
        Implement reflected multiplication.

        Parameters
        ----------
        lhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        Returns
        -------
        TensorNetwork
            New lazy calculation; operands are unchanged.

        Notes
        -----
        Matching explicit labels contract. Compatible unresolved axes are
        paired only when the choice is unambiguous. Use outer(), contract(),
        or compose() to make the intended pairing explicit.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> result = 2 * tensor
        """
    def __truediv__(self, rhs: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> TensorNetwork:
        r"""
        Divide tensor components by a scalar expression.

        Parameters
        ----------
        rhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        Returns
        -------
        TensorNetwork
            New lazy calculation; operands are unchanged.

        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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> result = tensor / 2
        """
    def __rtruediv__(self, lhs: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> TensorNetwork:
        r"""
        Implement reflected division.

        Parameters
        ----------
        lhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        Returns
        -------
        TensorNetwork
            New lazy calculation; operands are unchanged.

        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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> result = 2 / TensorExpression(3).to_tensor()
        """
    def outer(self, rhs: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> TensorNetwork:
        r"""
        Form an outer product without implicit contractions between the operands.

        Parameters
        ----------
        rhs : TensorExpression, Tensor, or TensorNetwork
            Tensor whose axes follow this tensor's axes.

        Returns
        -------
        TensorNetwork
            A lazy outer product retaining the operands' component data.

        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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> product = tensor.outer(tensor)
        >>> product.rank
        4
        """
    def contract_ports(self, rhs: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork], *, left: builtins.int, right: builtins.int) -> TensorNetwork:
        r"""
        Contract one chosen pair of axes between two tensors.

        Parameters
        ----------
        rhs : TensorExpression, Tensor, or TensorNetwork
            Tensor to contract with this tensor.
        left, right : int
            Zero-based axis positions in this tensor and rhs, respectively.
            The representations must be compatible under contraction.

        Returns
        -------
        TensorNetwork
            A lazy contraction retaining component data.

        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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> contracted = tensor.contract_ports(tensor, left=1, right=0)
        >>> contracted.rank
        2
        """
    def compose(self, rhs: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork], *, left: tuple[builtins.int, builtins.int], right: tuple[builtins.int, builtins.int]) -> TensorNetwork:
        r"""
        Multiply two tensors along explicitly selected matrix channels.

        Parameters
        ----------
        rhs : TensorExpression, Tensor, or TensorNetwork
            Next factor in the ordered matrix product.
        left, right : tuple of int and 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.

        Returns
        -------
        TensorNetwork
            A lazy ordered matrix product retaining 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 Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> product = tensor.compose(tensor, left=(0, 1), right=(0, 1))
        >>> product.rank
        2
        """
    def dot(self, rhs: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> TensorNetwork:
        r"""
        Contract two rank-one tensors using their representation pairing.

        Parameters
        ----------
        rhs : TensorExpression, Tensor, or TensorNetwork
            Rank-one tensor in a compatible space.

        Returns
        -------
        TensorNetwork
            A lazy scalar contraction, including the metric signs of the space.

        Examples
        --------
        >>> from symbolica.community.tensor import TensorName, Tensor, TensorNetwork, Representation
        >>> vector = Tensor.dense(TensorName.vector("dot_v")(Representation.euc(2)), [1.0, 2.0])
        >>> vector.dot(vector).to_tensor().scalar() == 5
        True
        """
    def trace(self, *, channel: typing.Optional[tuple[builtins.int, builtins.int]] = None) -> TensorNetwork:
        r"""
        Close a pair of matrix axes on this tensor.

        Parameters
        ----------
        channel : tuple of int and int, optional
            (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.

        Returns
        -------
        TensorNetwork
            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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> tensor.trace(channel=(0, 1)).is_scalar
        True
        """
    def __iter__(self) -> typing.Iterator[Expression | float | complex]:
        r"""
        Iterate over all components in logical row-major order.

        Returns
        -------
        iterator of Expression, float, or complex
            Includes implicit zeros from sparse storage.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> list(tensor)
        [1.0, 2.0, 3.0, 4.0]
        """
    @typing.overload
    def __getitem__(self, item: builtins.slice) -> builtins.list[Expression | builtins.complex | float]:
        r"""
        Read components in logical row-major order.

        Parameters
        ----------
        item : int, slice, or tuple of int or slice
            An integer is a flat position. A tuple gives one selector per axis.
            A flat slice returns a list; coordinate slices return nested lists.
            Negative indices count from the end.

        Returns
        -------
        Expression, float, complex, or list
            A scalar component, or lists for the sliced axes.

        Notes
        -----
        Coordinates follow axes, the current component view; structure.axes is a canonical signature.
        The canonical storage-axis order is not exposed by component indexing.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> tensor[:, 1]
        [2.0, 4.0]
        >>> tensor[-1]
        4.0
        """
    @typing.overload
    def __getitem__(self, item: typing.Sequence[builtins.int] | builtins.int) -> Expression | builtins.complex | float:
        r"""
        Read components in logical row-major order.

        Parameters
        ----------
        item : int, slice, or tuple of int or slice
            An integer is a flat position. A tuple gives one selector per axis.
            A flat slice returns a list; coordinate slices return nested lists.
            Negative indices count from the end.

        Returns
        -------
        Expression, float, complex, or list
            A scalar component, or lists for the sliced axes.

        Notes
        -----
        Coordinates follow axes, the current component view; structure.axes is a canonical signature.
        The canonical storage-axis order is not exposed by component indexing.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> tensor[:, 1]
        [2.0, 4.0]
        >>> tensor[-1]
        4.0
        """
    @typing.overload
    def __getitem__(self, item: tuple[int | slice, ...]) -> _Components:
        r"""
        Read components in logical row-major order.

        Parameters
        ----------
        item : int, slice, or tuple of int or slice
            An integer is a flat position. A tuple gives one selector per axis.
            A flat slice returns a list; coordinate slices return nested lists.
            Negative indices count from the end.

        Returns
        -------
        Expression, float, complex, or list
            A scalar component, or lists for the sliced axes.

        Notes
        -----
        Coordinates follow axes, the current component view; structure.axes is a canonical signature.
        The canonical storage-axis order is not exposed by component indexing.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> tensor[:, 1]
        [2.0, 4.0]
        >>> tensor[-1]
        4.0
        """
    def __setitem__(self, item: builtins.int | typing.Sequence[builtins.int], value: Expression | int | builtins.complex | float) -> None:
        r"""
        Change one stored component in place.

        Parameters
        ----------
        item : int or sequence of int
            Flat logical row-major position or one coordinate per logical axis.
            Negative indices count from the end.
        value : float, complex, or Expression
            Replacement matching the tensor's component type: float for real
            storage, complex for complex storage, or Expression for symbolic storage.

        Returns
        -------
        None
            The tensor is modified in place.

        Notes
        -----
        Coordinates follow axes, the current component view; structure.axes is a canonical signature.
        The canonical storage-axis order is not exposed by component indexing.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> tensor[1, 0] = 7.0
        >>> tensor[1, 0]
        7.0
        """

@typing.final
class TensorEvaluator:
    r"""
    Symbolica evaluator returning component tensors in their original logical layout.

    Construct with Tensor.evaluator. The scalar_evaluator property exposes the
    underlying Symbolica Evaluator for precision evaluation, export and inspection.
    """
    @property
    def parameters(self) -> builtins.list[Expression]:
        r"""
        Symbolic inputs in evaluation order.
        """
    @property
    def input_size(self) -> builtins.int:
        r"""
        Number of entries in an input row.
        """
    @property
    def output_shape(self) -> tuple[int, ...]:
        r"""
        Logical shape of each output tensor, excluding the batch dimension.
        """
    @property
    def supports_real(self) -> builtins.bool:
        r"""
        Whether all exact coefficients are real.
        """
    @property
    def scalar_evaluator(self) -> Evaluator:
        r"""
        Underlying Symbolica Evaluator, with outputs in logical component order.

        Use for arbitrary-precision evaluation, export, or instruction inspection.
        These operations return scalar components; they do not wrap tensor metadata.
        """
    def __repr__(self) -> builtins.str:
        r"""
        Describe the output tensor layout and supported numeric domains.
        """
    def evaluate(self, inputs: numpy.typing.ArrayLike) -> builtins.list[Tensor]:
        r"""
        Evaluate real inputs using Symbolica's ArrayLike input conventions.

        Returns one Tensor per row. A flat input array is also accepted, with
        the same reshaping and validation as Evaluator.evaluate.
        """
    def evaluate_complex(self, inputs: numpy.typing.ArrayLike) -> builtins.list[Tensor]:
        r"""
        Evaluate complex inputs; returns one Tensor per input row.
        """
    def jit_compile(self, jit_compile: builtins.bool, direct_translation: typing.Optional[builtins.bool] = None, optimization_level: typing.Optional[builtins.int] = None, options: typing.Optional[typing.Mapping[builtins.str, builtins.str]] = None) -> None:
        r"""
        Enable or disable JIT compilation with Symbolica's settings.
        """
    def set_real_params(self, real_params: typing.Sequence[builtins.int], sqrt_real: builtins.bool = False, log_real: builtins.bool = False, powf_real: builtins.bool = False, real_if_args_real: builtins.bool = False, verbose: builtins.bool = False) -> None:
        r"""
        Mark real parameters using the same assumptions as Evaluator.set_real_params.
        """
    def compile(self, function_name: builtins.str, filename: builtins.str, library_name: builtins.str, number_type: builtins.str, inline_asm: builtins.str = 'default', optimization_level: builtins.int = 3, native: builtins.bool = True, compiler_path: typing.Optional[builtins.str] = None, compiler_flags: typing.Optional[typing.Sequence[builtins.str]] = None, custom_header: typing.Optional[builtins.str] = None, cuda_number_of_evaluations: builtins.int = 1, cuda_block_size: builtins.int = 512) -> CompiledTensorEvaluator:
        r"""
        Compile a native evaluator with the same options as Evaluator.compile.

        number_type selects real, complex, real_4x, complex_4x, cuda_real or
        cuda_complex. The returned object's evaluate method uses that number type
        and returns tensors. Source and library files are written to the given paths.
        """

@typing.final
class TensorExpression(Expression):
    r"""
    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
    2
    """
    @property
    def rank(self) -> builtins.int:
        r"""
        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
        2
        """
    @property
    def is_scalar(self) -> builtins.bool:
        r"""
        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
        False
        """
    @property
    def shape(self) -> tuple[int | Expression, ...]:
        r"""
        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
        (3, 3)
        """
    @property
    def axes(self) -> tuple[Slot | Representation, ...]:
        r"""
        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"))
        True
        >>> A.permute_axes([1, 0]).axes == A.axes[::-1]
        True
        """
    @property
    def structure(self) -> TensorStructure:
        r"""
        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
        (3, 3)
        """
    @property
    def name(self) -> typing.Optional[TensorName]:
        r"""
        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
        """
    @property
    def arguments(self) -> tuple[Expression, ...]:
        r"""
        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)
        True
        """
    @property
    def reduction_status(self) -> ReductionStatus:
        r"""
        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
        True
        """
    @property
    def contraction_complete(self) -> builtins.bool:
        r"""
        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
        True
        """
    def __new__(cls, expression: TensorExpression | _ScalarInput, *, structure: typing.Optional[TensorStructure] = None, intern: typing.Optional[typing.Literal['indices', 'flattened']] = None) -> TensorExpression:
        r"""
        Wrap symbolic algebra as a tensor and check its external axes.

        Parameters
        ----------
        expression : TensorExpression or scalar expression
            Existing tensor, Symbolica Expression, or scalar convertible to one.
            Tensor syntax is inferred; an ordinary scalar has no external axes.
        structure : TensorStructure, optional
            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.
        intern : {"indices", "flattened"} or None, optional
            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.

        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
        1
        >>> 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
        1
        """
    @staticmethod
    def g(rep: Representation | Slot, other: Representation | Slot | None = None) -> TensorExpression:
        r"""
        Construct the metric pairing, optionally with explicit indices.

        Parameters
        ----------
        rep : Representation or Slot
            First axis. A representation leaves it unresolved; a slot supplies
            both its representation and its index.
        other : Representation or Slot, optional
            Second axis. Defaults to an unresolved axis in the first axis's
            representation, even when the first argument is a slot.

        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")
        True
        >>> partly_indexed = TensorExpression.g(r("mu"), r)
        >>> partly_indexed("nu") == metric
        True
        >>> f = Representation.cof(3)
        >>> identity = TensorExpression.g(f("i"), f.dual()("j"))
        >>> identity.rank
        2
        """
    @staticmethod
    def flat(rep: Representation) -> TensorExpression:
        r"""
        Construct the metric map for raising or lowering an index.

        Parameters
        ----------
        rep : Representation
            Space of both axes.

        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
        2
        """
    @staticmethod
    def dirac_gamma(minkowski_dimension: builtins.int | Expression | str) -> TensorExpression:
        r"""
        Construct the Dirac gamma matrices for Clifford algebra.

        Parameters
        ----------
        minkowski_dimension : int, Expression, or str
            Dimension of the Minkowski vector index, for example 4 or a symbol D.

        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
        3
        """
    @staticmethod
    def gamma0(spinor_dimension: builtins.int | Expression | str) -> TensorExpression:
        r"""
        Construct the time-component Dirac matrix gamma^0.

        Parameters
        ----------
        spinor_dimension : int, Expression, or str
            Number of spinor components.

        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
        2
        """
    @staticmethod
    def charge_conjugation(spinor_dimension: builtins.int | Expression | str) -> TensorExpression:
        r"""
        Construct the Dirac charge-conjugation matrix.

        Parameters
        ----------
        spinor_dimension : int, Expression, or str
            Number of spinor components.

        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
        2
        """
    @staticmethod
    def levi_civita(rep: Representation, rank: builtins.int = 4) -> TensorExpression:
        r"""
        Construct the totally antisymmetric Levi-Civita tensor.

        Parameters
        ----------
        rep : Representation
            Space of every axis.
        rank : int, default 4
            Number of axes, independent of the representation dimension.

        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
        3
        """
    def expand_projectors(self) -> TensorExpression:
        r"""
        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
        True
        """
    @staticmethod
    def gamma5(spinor_dimension: builtins.int | Expression | str) -> TensorExpression:
        r"""
        Construct the Dirac chirality matrix gamma^5.

        Parameters
        ----------
        spinor_dimension : int, Expression, or str
            Number of spinor components.

        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
        2
        """
    @staticmethod
    def projm(spinor_dimension: builtins.int | Expression | str) -> TensorExpression:
        r"""
        Construct the left-chiral Dirac projector (I - gamma^5)/2.

        Parameters
        ----------
        spinor_dimension : int, Expression, or str
            Number of spinor components.

        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
        2
        """
    @staticmethod
    def projp(spinor_dimension: builtins.int | Expression | str) -> TensorExpression:
        r"""
        Construct the right-chiral Dirac projector (I + gamma^5)/2.

        Parameters
        ----------
        spinor_dimension : int, Expression, or str
            Number of spinor components.

        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
        2
        """
    @staticmethod
    def sigma(minkowski_dimension: builtins.int | Expression | str) -> TensorExpression:
        r"""
        Construct the antisymmetric Dirac sigma tensor.

        Parameters
        ----------
        minkowski_dimension : int, Expression, or str
            Dimension of each Minkowski vector index.

        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
        4
        """
    @staticmethod
    def color_f(adjoint_dimension: builtins.int | Expression | str) -> TensorExpression:
        r"""
        Construct the antisymmetric color structure constants f^{abc}.

        Parameters
        ----------
        adjoint_dimension : int, Expression, or str
            Dimension of the adjoint representation, for example 8 for SU(3).

        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
        3
        """
    @staticmethod
    def color_t(adjoint_dimension: builtins.int | Expression | str, fundamental_dimension: builtins.int | Expression | str) -> TensorExpression:
        r"""
        Construct the fundamental color generators T^a.

        Parameters
        ----------
        adjoint_dimension : int, Expression, or str
            Adjoint dimension, for example 8 for SU(3).
        fundamental_dimension : int, Expression, or str
            Fundamental dimension, for example 3 for SU(3).

        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
        3
        """
    def with_name(self, name: TensorName | builtins.str | Expression | TensorExpression) -> TensorExpression:
        r"""
        Assign a data identity without rewriting the symbolic computation.

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

        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
        2
        """
    def __len__(self) -> builtins.int:
        r"""
        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)
        4
        """
    def to_expression(self) -> Expression:
        r"""
        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()
        """
    def is_zero(self) -> builtins.bool:
        r"""
        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
        """
    def is_one(self) -> builtins.bool:
        r"""
        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()
        """
    def is_expanded(self, var: typing.Optional[_ScalarInput] = None) -> builtins.bool:
        r"""
        Test whether products and powers are expanded, optionally with respect to var.
        The expression and its tensor interface are unchanged.

        Parameters
        ----------
        var : Expression, optional
            Restrict the expansion check to this indeterminate.

        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)
        """
    def nterms(self) -> builtins.int:
        r"""
        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
        """
    def replace(self, pattern: TensorRule | list[TensorRule] | _ScalarInput, rhs: typing.Optional[_ReplacementInput] = None, cond: typing.Optional[PatternRestriction | Condition] = None, non_greedy_wildcards: typing.Optional[typing.Sequence[Expression]] = None, min_level: builtins.int = 0, max_level: typing.Optional[builtins.int] = None, level_is_tree_depth: builtins.bool = False, partial: builtins.bool = True, allow_new_wildcards_on_rhs: builtins.bool = False, rhs_cache_size: typing.Optional[builtins.int] = None, repeat: builtins.bool = False, once: builtins.bool = False, bottom_up: builtins.bool = False, nested: builtins.bool = False) -> TensorExpression:
        r"""
        Replace symbolic patterns or apply whole-tensor replacement rules.

        Parameters
        ----------
        pattern : Expression, TensorRule, or list of TensorRule
            Symbolica pattern when rhs is supplied. Without rhs, apply prepared
            TensorRules in priority order, leaving scalar key arguments opaque.
        rhs : Expression, HeldExpression, or callable, optional
            Symbolica replacement, including callbacks. The result must preserve
            the tensor's ordered interface. Use reindex() to change external labels.
        cond : PatternRestriction or Condition, optional
            Restriction on a symbolic match.
        non_greedy_wildcards : list of Expression, optional
            Wildcards whose matches should be selected non-greedily.
        min_level, max_level : int, optional
            Inclusive traversal bounds, starting at zero.
        level_is_tree_depth : bool, default False
            Count expression-tree levels rather than function nesting.
        partial : bool, default True
            Allow matches inside larger expressions.
        allow_new_wildcards_on_rhs : bool, default False
            Allow wildcard symbols that do not occur in the pattern.
        rhs_cache_size : int, optional
            Cache repeated symbolic replacements; zero disables caching.
        repeat, once, bottom_up, nested : bool, default False
            Symbolica's replacement traversal controls. Prepared TensorRules own
            their conditions and cache settings and do not accept these options.

        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
        """
    def replace_multiple(self, replacements: typing.Sequence[Replacement], repeat: builtins.bool = False, once: builtins.bool = False, bottom_up: builtins.bool = False, nested: builtins.bool = False) -> TensorExpression:
        r"""
        Apply simultaneous Symbolica replacements and validate the resulting tensor.

        Parameters
        ----------
        replacements : list of Replacement
            Symbolica replacements, including their conditions and callbacks.
        repeat, once, bottom_up, nested : bool, default False
            Traversal controls with the same meaning as Expression.replace_multiple.

        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
        """
    def map(self, op: Transformer, n_cores: typing.Optional[builtins.int] = None, stats_to_file: typing.Optional[builtins.str] = None) -> TensorExpression:
        r"""
        Apply a Symbolica Transformer and retain the validated tensor interface.

        Parameters
        ----------
        op : Transformer
            Transformations to apply, including user callbacks.
        n_cores : int, optional
            Number of cores for Symbolica's term mapping.
        stats_to_file : str, optional
            JSON output file for the transformer's statistics.

        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()
        """
    def derivative(self, x: _ScalarInput) -> TensorExpression:
        r"""
        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.

        Parameters
        ----------
        x : Expression
            Scalar differentiation variable.

        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
        """
    def expand(self, var: typing.Optional[_ScalarInput] = None, via_poly: typing.Optional[builtins.bool] = None) -> TensorExpression:
        r"""
        Distribute scalar products and powers over sums.

        Parameters
        ----------
        var : scalar expression, optional
            Restrict expansion to terms involving this expression. None expands
            throughout the expression.
        via_poly : bool, optional
            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.

        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
        2
        """
    def factor(self, complex: builtins.bool = False, extension: typing.Optional[typing.Sequence[_ScalarInput]] = None) -> TensorExpression:
        r"""
        Factor scalar algebra while retaining ordered tensor ports and data metadata.
        Tensor leaves are treated as symbolic indeterminates; no tensor identity is applied.

        Parameters
        ----------
        complex : bool, default False
            Factor over the complex rationals rather than the rationals.
        extension : list of Expression, optional
            Algebraic numbers defining the coefficient field, as in Expression.factor.

        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
        """
    def expand_num(self) -> TensorExpression:
        r"""
        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
        """
    def collect(self, *x: symbolica.core.Expression, key_map: typing.Optional[typing.Callable[[symbolica.core.Expression], symbolica.core.Expression]] = None, coeff_map: typing.Optional[typing.Callable[[symbolica.core.Expression], symbolica.core.Expression]] = None) -> TensorExpression:
        r"""
        Collect terms in variables or functions, retaining the tensor interface.

        Parameters
        ----------
        *x : Expression
            Variables or functions to collect in, with Expression.collect semantics.
        key_map, coeff_map : callable, optional
            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.

        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()
        """
    def collect_num(self) -> TensorExpression:
        r"""
        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
        """
    def collect_factors(self) -> TensorExpression:
        r"""
        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
        """
    def collect_by_coefficient(self) -> TensorExpression:
        r"""
        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)
        """
    def collect_symbol(self, x: Expression, key_map: typing.Optional[typing.Callable[[symbolica.core.Expression], symbolica.core.Expression]] = None, coeff_map: typing.Optional[typing.Callable[[symbolica.core.Expression], symbolica.core.Expression]] = None) -> TensorExpression:
        r"""
        Collect terms by powers of a variable or calls with the same function head.

        Parameters
        ----------
        x : Expression
            Variable or function symbol to collect in.
        key_map, coeff_map : callable, optional
            Map ordinary Expressions. As with collect(), the result is checked for
            preservation of the tensor's ordered external ports.

        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()
        """
    def collect_horner(self, vars: typing.Optional[typing.Sequence[Expression]] = None) -> TensorExpression:
        r"""
        Rewrite polynomial algebra in Horner form, retaining ordered ports and metadata.

        Parameters
        ----------
        vars : list of Expression, optional
            Variable order. Omit it to use Symbolica's heuristic ordering.

        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)
        """
    def together(self) -> TensorExpression:
        r"""
        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)
        """
    def cancel(self) -> TensorExpression:
        r"""
        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
        """
    def apart(self, *variables: symbolica.core.Expression) -> TensorExpression:
        r"""
        Decompose scalar denominators into partial fractions, retaining the tensor interface.

        Parameters
        ----------
        *variables : Expression
            Variables for partial fractioning. Omit them to use all indeterminates,
            as in Expression.apart().

        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)
        """
    def __copy__(self) -> TensorExpression:
        r"""
        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
        (2, 2)
        """
    def __deepcopy__(self, memo: dict) -> TensorExpression:
        r"""
        Copy the tensor's immutable expression, ordered axes, and data metadata.

        Parameters
        ----------
        memo : dict
            Copy bookkeeping maintained by Python's copy module.

        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
        """
    def __reduce__(self) -> typing.NoReturn:
        r"""
        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.
        """
    def with_lorentz_dimension(self, dimension: builtins.int | Expression | str) -> TensorExpression:
        r"""
        Replace four-dimensional Minkowski index spaces by a supplied dimension.

        Parameters
        ----------
        dimension : int, Expression, or str
            New Lorentz dimension, such as a symbol D. An Expression must be
            a single symbol.

        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]
        (4, 4)
        """
    def simplify_algebra(self, *, gamma: builtins.bool = True, color: builtins.bool = True, epsilon: builtins.bool = False, contract: typing.Literal['fully', 'minimal', 'dots', 'selected', 'none'] = "fully", representations: typing.Optional[typing.Sequence[Representation | RepresentationName]] = None, collect_coefficients: builtins.bool = True, gamma_output: typing.Optional[typing.Literal['reduced', 'chains']] = None, gamma_ordering: typing.Optional[typing.Literal['repeated_pairs', 'canonical']] = None, gamma_evaluate_traces: typing.Optional[builtins.bool] = None, gamma0: typing.Optional[builtins.bool] = None, gamma_conjugate: typing.Optional[builtins.bool] = None, gamma_expand_three_gamma_epsilon: typing.Optional[builtins.bool] = None, color_evaluate_traces: typing.Optional[builtins.bool] = None, color_expand_fierz: typing.Optional[builtins.bool] = None, color_substitute_cof_dimension_invariants: typing.Optional[builtins.bool] = None, max_steps_per_domain: typing.Optional[builtins.int] = None) -> TensorExpression:
        r"""
        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.

        Parameters
        ----------
        gamma, color : bool, default True
            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.
        epsilon : bool, default False
            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.
        contract : {"fully", "dots", "minimal", "selected", "none"}, default "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.
        representations : sequence of Representation or RepresentationName, optional
            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_coefficients : bool, default True
            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_output : {"reduced", "chains"}, optional
            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_ordering : {"repeated_pairs", "canonical"}, optional
            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_traces : bool, optional
            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.
        gamma0 : bool, optional
            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_conjugate : bool, optional
            Rewrite explicitly complex-conjugated Dirac matrices before collection;
            defaults to False. This does not conjugate the input tensor.
        gamma_expand_three_gamma_epsilon : bool, optional
            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_traces : bool, optional
            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_fierz : bool, optional
            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_invariants : bool, optional
            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_domain : int or None, default 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.

        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
        """
    def wrap_indices(self, header: Expression, *, dummies_only: builtins.bool = False) -> TensorExpression:
        r"""
        Give explicit indices a scope that separates them from other copies.

        Parameters
        ----------
        header : Expression
            A single Symbolica symbol naming the scope.
        dummies_only : bool, default False
            Scope only contracted indices, leaving external labels unchanged.

        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
        2
        """
    def list_dangling(self) -> builtins.list[Expression]:
        r"""
        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())
        2
        """
    def canonize(self) -> TensorExpression:
        r"""
        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
        2
        """
    def dirac_adjoint(self, *, preserve_indices: builtins.bool = False) -> TensorExpression:
        r"""
        Construct the Dirac adjoint of a spinor tensor expression.

        Parameters
        ----------
        preserve_indices : bool, default False
            Keep external labels on their original physical legs. False uses
            matrix-adjoint ordering and exchanges open-chain endpoints.

        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
        1
        """
    def to_dots(self) -> TensorExpression:
        r"""
        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()
        """
    def undo_dots(self) -> TensorExpression:
        r"""
        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()
        """
    def undo_chain(self) -> TensorExpression:
        r"""
        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()
        """
    def undo_trace(self) -> TensorExpression:
        r"""
        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()
        """
    def to_network(self, library: typing.Optional[TensorLibrary] = None) -> TensorNetwork:
        r"""
        Build an executable network for this symbolic tensor.

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

        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
        2
        """
    def to_tensor(self, library: typing.Optional[TensorLibrary] = None, *, function_library: typing.Optional[TensorFunctionLibrary] = None) -> Tensor:
        r"""
        Evaluate this expression and return its components.

        Parameters
        ----------
        library : TensorLibrary, optional
            Component definitions. Defaults to the built-in four-dimensional Dirac
            and SU(3) library. Unregistered tensors receive symbolic components.
        function_library : TensorFunctionLibrary, optional
            Numerical implementations of broadcast functions. Defaults to the
            built-in function library.

        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
        (2, 2)
        """
    def components(self, library: typing.Optional[TensorLibrary] = None) -> builtins.list[Expression | builtins.complex | builtins.float]:
        r"""
        Evaluate this tensor and return its flat component list.

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

        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())
        4
        """
    def index(self, *indices: _IndexInput, intern: typing.Optional[typing.Literal['indices', 'flattened']] = None) -> TensorExpression:
        r"""
        Assign labels to the unresolved external axes.

        Parameters
        ----------
        *indices : int, str, Expression, Slot, or AUTO
            One label per unresolved axis, in logical order. AUTO leaves the
            corresponding axis unchanged. A Slot must have the matching
            representation. Repeated compatible labels cause contraction.
        intern : {"indices", "flattened"} or None, optional
            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.

        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
        2
        """
    def reindex(self, *indices: _IndexInput, intern: typing.Optional[typing.Literal['indices', 'flattened']] = None) -> TensorExpression:
        r"""
        Assign labels to all external axes.

        Parameters
        ----------
        *indices : int, str, Expression, Slot, or AUTO
            One label per external axis, in logical order. AUTO leaves the
            corresponding axis unchanged. A Slot must have the matching
            representation. Repeated compatible labels cause contraction.
        intern : {"indices", "flattened"} or None, optional
            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.

        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
        2
        """
    def rename_indices(self, mapping: dict[int | str | Expression | Slot, _IndexInput], *, intern: typing.Optional[typing.Literal['indices', 'flattened']] = None) -> TensorExpression:
        r"""
        Rename selected external labels without changing the tensor rank.

        Parameters
        ----------
        mapping : dict
            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.
        intern : {"indices", "flattened"} or None, optional
            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.

        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
        2
        """
    def permute_axes(self, axes: typing.Sequence[builtins.int]) -> TensorExpression:
        r"""
        Reorder the external axes in logical component order.

        Parameters
        ----------
        axes : sequence of int
            Each current axis position exactly once, in the desired new order.
            For a matrix, [1, 0] exchanges the two axes.

        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
        (2, 2)
        """
    def __call__(self, *indices: _IndexInput, intern: typing.Optional[typing.Literal['indices', 'flattened']] = None) -> TensorExpression:  # type: ignore[override]  # ty: ignore[invalid-method-override]
        r"""
        Assign labels to the unresolved external axes.

        Parameters
        ----------
        *indices : int, str, Expression, Slot, or AUTO
            One label per unresolved axis, in logical order. AUTO leaves the
            corresponding axis unchanged. A Slot must have the matching
            representation. Repeated compatible labels cause contraction.
        intern : {"indices", "flattened"} or None, optional
            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.

        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
        2
        """
    def __neg__(self) -> TensorExpression:
        r"""
        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
        """
    def __pow__(self, exponent: TensorExpression | _ScalarInput, modulo: typing.Optional[typing.Any] = None) -> TensorExpression:  # type: ignore[override]  # ty: ignore[invalid-method-override]
        r"""
        Raise tensor algebra to a scalar power.

        Parameters
        ----------
        exponent : TensorExpression or scalar expression
            Scalar exponent.
        modulo : object, optional
            Must be None; modular tensor powers are not supported.

        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
        True
        """
    def __rpow__(self, base: TensorExpression | _ScalarInput, modulo: typing.Optional[typing.Any] = None) -> TensorExpression:
        r"""
        Use a scalar tensor expression as an exponent.

        Parameters
        ----------
        base : TensorExpression or scalar expression
            Scalar base.
        modulo : None, optional
            Must be None; modular powers are not supported.

        Returns
        -------
        TensorExpression
            Scalar power with a checked tensor interface.

        Examples
        --------
        >>> from symbolica.community.tensor import TensorExpression
        >>> result = 2**TensorExpression(3)
        >>> result.to_expression() == 8
        True
        """
    def __eq__(self, other: typing.Any) -> builtins.bool:
        r"""
        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
        ----------
        other : object
            TensorExpression to compare. Values without an ordered tensor interface are unequal.
        """
    def __ne__(self, other: typing.Any) -> builtins.bool:
        r"""
        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
        ----------
        other : object
            TensorExpression to compare. Values without an ordered tensor interface are unequal.
        """
    def __hash__(self) -> builtins.int:
        r"""
        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"
        """
    def __bool__(self) -> builtins.bool:
        r"""
        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)
        """
    def contract(self, *, representations: typing.Optional[typing.Sequence[Representation | RepresentationName]] = None, metrics: builtins.bool = True, rank_one: builtins.bool = True, collect_chains: builtins.bool = True, collect_traces: builtins.bool = True, expand: builtins.bool = True, order: typing.Optional[typing.Sequence[builtins.int]] = None, max_steps_per_domain: typing.Optional[builtins.int] = None) -> TensorExpression:
        r"""
        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.

        Parameters
        ----------
        representations : sequence of Representation or RepresentationName, optional
            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.
        metrics : bool, default True
            Eliminate compatible metric/identity tensors by index substitution and
            evaluate closed metric loops to their representation dimension.
        rank_one : bool, default True
            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_chains : bool, default True
            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_traces : bool, default True
            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.
        expand : bool, default True
            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.
        order : sequence of int, optional
            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_domain : int or None, default 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.

        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
        """
    def trace(self, *, channel: typing.Optional[tuple[builtins.int, builtins.int]] = None) -> TensorExpression:
        r"""
        Close a pair of matrix axes on this tensor.

        Parameters
        ----------
        channel : tuple of int and int, optional
            (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.

        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
        True
        """
    def format_tensor(self, show_dimensions: typing.Optional[builtins.bool] = None, *, settings: typing.Optional[DisplaySettings] = None) -> builtins.str:
        r"""
        Produce compact plain-text tensor notation.

        Parameters
        ----------
        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
        -------
        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()
        """
    def to_latex(self, max_line_length: typing.Optional[builtins.int] = None, *, settings: typing.Optional[DisplaySettings] = None) -> builtins.str:
        r"""
        Produce LaTeX for the symbolic tensor expression.

        Parameters
        ----------
        max_line_length : int, optional
            Requested line-length bound for the printer. None leaves it unbounded.
        settings : DisplaySettings, optional
            Index labels, dimensions and invariant notation. Defaults to
            DisplaySettings(). Only ports layout and default spacing are supported.

        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()
        """
    def to_typst(self, show_dimensions: typing.Optional[builtins.bool] = None, *, settings: typing.Optional[DisplaySettings] = None) -> builtins.str:  # type: ignore[override]  # ty: ignore[invalid-method-override]
        r"""
        Produce static Typst math source.

        Parameters
        ----------
        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
        -------
        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()
        """
    def to_typst_project(self, show_dimensions: typing.Optional[builtins.bool] = None, *, settings: typing.Optional[DisplaySettings] = None, notation_source: typing.Optional[builtins.str] = None) -> dict:
        r"""
        Export a customizable Typst project without running a compiler.

        Parameters
        ----------
        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; defaults to 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
        -----
        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()
        """
    def formatted(self, show_dimensions: typing.Optional[builtins.bool] = None, *, settings: typing.Optional[DisplaySettings] = None, notation_source: typing.Optional[builtins.str] = None) -> FormattedOutput:  # type: ignore[override]  # ty: ignore[invalid-method-override]
        r"""
        Create a lazy rich display value for a notebook.

        Parameters
        ----------
        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
        -------
        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()
        """
    def paged(self, page_size: typing.Optional[builtins.int] = None, *, settings: typing.Optional[DisplaySettings] = None, notation_source: typing.Optional[builtins.str] = None) -> typing.Any:
        r"""
        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.

        Parameters
        ----------
        page_size : int, optional
            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.
        settings : DisplaySettings, optional
            Tensor notation, index labels, and other presentation preferences.
        notation_source : str, optional
            Unsupported by the direct MathML pager. Use to_typst_project() or to_svg()
            for custom Typst notation; paging raises ValueError when supplied.

        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()
        """
    def _display_(self) -> typing.Any:
        r"""
        Return marimo's notebook presentation with bounded pages for large expressions.

        Returns
        -------
        object
            Rich notebook output or an interactive viewer, using default settings.
        """
    def _repr_mimebundle_(self, include: typing.Optional[typing.Sequence[builtins.str]] = None, exclude: typing.Optional[typing.Sequence[builtins.str]] = None) -> typing.Any:
        r"""
        Return the rich representations requested by a Jupyter frontend.

        Parameters
        ----------
        include, exclude : list of str, optional
            MIME types to include or exclude from the returned representations.

        Returns
        -------
        object
            MIME bundle for the complete small expression or paged large expression.
        """
    def to_html(self, show_dimensions: typing.Optional[builtins.bool] = None, *, settings: typing.Optional[DisplaySettings] = None, notation_source: typing.Optional[builtins.str] = None) -> builtins.str:
        r"""
        Render the tensor as an HTML fragment.

        Parameters
        ----------
        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
        -------
        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()
        """
    def to_svg(self, show_dimensions: typing.Optional[builtins.bool] = None, *, settings: typing.Optional[DisplaySettings] = None, notation_source: typing.Optional[builtins.str] = None) -> builtins.str:
        r"""
        Render static mathematical tensor notation to SVG.

        Parameters
        ----------
        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
        -------
        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()
        """
    def __repr__(self) -> builtins.str:
        r"""
        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)
        """
    def __str__(self) -> builtins.str:
        r"""
        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)
        """
    def _repr_pretty_(self, pretty: typing.Any, cycle: builtins.bool) -> None: ...
    def _repr_html_(self) -> typing.Optional[builtins.str]: ...  # type: ignore[override]  # ty: ignore[invalid-method-override]
    def _repr_latex_(self) -> builtins.str: ...
    @typing.overload
    def __add__(self, rhs: TensorExpression | _ScalarInput) -> TensorExpression:
        r"""
        Add tensors with compatible external interfaces.

        Parameters
        ----------
        rhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        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
        """
    @typing.overload
    def __add__(self, rhs: typing.Union[Tensor, TensorNetwork]) -> TensorNetwork:
        r"""
        Add tensors with compatible external interfaces.

        Parameters
        ----------
        rhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        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
        """
    @typing.overload
    def __radd__(self, lhs: TensorExpression | _ScalarInput) -> TensorExpression:
        r"""
        Implement reflected addition.

        Parameters
        ----------
        lhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        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
        """
    @typing.overload
    def __radd__(self, lhs: typing.Union[Tensor, TensorNetwork]) -> TensorNetwork:
        r"""
        Implement reflected addition.

        Parameters
        ----------
        lhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        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
        """
    @typing.overload
    def __sub__(self, rhs: TensorExpression | _ScalarInput) -> TensorExpression:
        r"""
        Subtract tensors with compatible external interfaces.

        Parameters
        ----------
        rhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        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
        """
    @typing.overload
    def __sub__(self, rhs: typing.Union[Tensor, TensorNetwork]) -> TensorNetwork:
        r"""
        Subtract tensors with compatible external interfaces.

        Parameters
        ----------
        rhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        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
        """
    @typing.overload
    def __rsub__(self, lhs: TensorExpression | _ScalarInput) -> TensorExpression:
        r"""
        Implement reflected subtraction.

        Parameters
        ----------
        lhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        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
        """
    @typing.overload
    def __rsub__(self, lhs: typing.Union[Tensor, TensorNetwork]) -> TensorNetwork:
        r"""
        Implement reflected subtraction.

        Parameters
        ----------
        lhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        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
        """
    @typing.overload
    def __mul__(self, rhs: TensorExpression | _ScalarInput) -> TensorExpression:
        r"""
        Multiply tensors, contracting unambiguous compatible axes.

        Parameters
        ----------
        rhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        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)
        """
    @typing.overload
    def __mul__(self, rhs: typing.Union[Tensor, TensorNetwork]) -> TensorNetwork:
        r"""
        Multiply tensors, contracting unambiguous compatible axes.

        Parameters
        ----------
        rhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        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)
        """
    @typing.overload
    def __rmul__(self, lhs: TensorExpression | _ScalarInput) -> TensorExpression:
        r"""
        Implement reflected multiplication.

        Parameters
        ----------
        lhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        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
        """
    @typing.overload
    def __rmul__(self, lhs: typing.Union[Tensor, TensorNetwork]) -> TensorNetwork:
        r"""
        Implement reflected multiplication.

        Parameters
        ----------
        lhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        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
        """
    @typing.overload
    def __truediv__(self, rhs: TensorExpression | _ScalarInput) -> TensorExpression:
        r"""
        Divide tensor components by a scalar expression.

        Parameters
        ----------
        rhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        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
        """
    @typing.overload
    def __truediv__(self, rhs: typing.Union[Tensor, TensorNetwork]) -> TensorNetwork:
        r"""
        Divide tensor components by a scalar expression.

        Parameters
        ----------
        rhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        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
        """
    @typing.overload
    def __rtruediv__(self, lhs: TensorExpression | _ScalarInput) -> TensorExpression:
        r"""
        Implement reflected division.

        Parameters
        ----------
        lhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        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)
        """
    @typing.overload
    def __rtruediv__(self, lhs: typing.Union[Tensor, TensorNetwork]) -> TensorNetwork:
        r"""
        Implement reflected division.

        Parameters
        ----------
        lhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        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)
        """
    @typing.overload
    def outer(self, rhs: TensorExpression | Expression) -> TensorExpression:
        r"""
        Form an outer product without implicit contractions between the operands.

        Parameters
        ----------
        rhs : TensorExpression, Tensor, or TensorNetwork
            Tensor whose axes follow this tensor's axes.

        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
        4
        """
    @typing.overload
    def outer(self, rhs: typing.Union[Tensor, TensorNetwork]) -> TensorNetwork:
        r"""
        Form an outer product without implicit contractions between the operands.

        Parameters
        ----------
        rhs : TensorExpression, Tensor, or TensorNetwork
            Tensor whose axes follow this tensor's axes.

        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
        4
        """
    @typing.overload
    def contract_ports(self, rhs: TensorExpression | Expression, *, left: builtins.int, right: builtins.int) -> TensorExpression:
        r"""
        Contract one chosen pair of axes between two tensors.

        Parameters
        ----------
        rhs : TensorExpression, Tensor, or TensorNetwork
            Tensor to contract with this tensor.
        left, right : int
            Zero-based axis positions in this tensor and rhs, respectively.
            The representations must be compatible under contraction.

        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
        2
        """
    @typing.overload
    def contract_ports(self, rhs: typing.Union[Tensor, TensorNetwork], *, left: int, right: int) -> TensorNetwork:
        r"""
        Contract one chosen pair of axes between two tensors.

        Parameters
        ----------
        rhs : TensorExpression, Tensor, or TensorNetwork
            Tensor to contract with this tensor.
        left, right : int
            Zero-based axis positions in this tensor and rhs, respectively.
            The representations must be compatible under contraction.

        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
        2
        """
    @typing.overload
    def compose(self, rhs: TensorExpression | Expression, *, left: tuple[builtins.int, builtins.int], right: tuple[builtins.int, builtins.int]) -> TensorExpression:
        r"""
        Multiply two tensors along explicitly selected matrix channels.

        Parameters
        ----------
        rhs : TensorExpression, Tensor, or TensorNetwork
            Next factor in the ordered matrix product.
        left, right : tuple of int and 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.

        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
        2
        """
    @typing.overload
    def compose(self, rhs: typing.Union[Tensor, TensorNetwork], *, left: tuple[int, int], right: tuple[int, int]) -> TensorNetwork:
        r"""
        Multiply two tensors along explicitly selected matrix channels.

        Parameters
        ----------
        rhs : TensorExpression, Tensor, or TensorNetwork
            Next factor in the ordered matrix product.
        left, right : tuple of int and 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.

        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
        2
        """
    @typing.overload
    def __getitem__(self, item: builtins.int) -> builtins.list[builtins.int]:  # type: ignore[override]
        r"""
        Convert between flat component positions and coordinates.

        Parameters
        ----------
        item : int, sequence of int, or slice
            A nonnegative flat position, coordinates in logical axis order, or
            a slice of flat positions. All axis dimensions must be concrete.

        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]
        [1, 0]
        >>> A[1, 0]
        2
        """
    @typing.overload
    def __getitem__(self, item: typing.Sequence[builtins.int]) -> builtins.int:  # type: ignore[override]
        r"""
        Convert between flat component positions and coordinates.

        Parameters
        ----------
        item : int, sequence of int, or slice
            A nonnegative flat position, coordinates in logical axis order, or
            a slice of flat positions. All axis dimensions must be concrete.

        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]
        [1, 0]
        >>> A[1, 0]
        2
        """
    @typing.overload
    def __getitem__(self, item: builtins.slice) -> builtins.list[builtins.list[builtins.int]]:  # type: ignore[override]  # ty: ignore[invalid-method-override]
        r"""
        Convert between flat component positions and coordinates.

        Parameters
        ----------
        item : int, sequence of int, or slice
            A nonnegative flat position, coordinates in logical axis order, or
            a slice of flat positions. All axis dimensions must be concrete.

        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]
        [1, 0]
        >>> A[1, 0]
        2
        """

@typing.final
class TensorFunctionLibrary:
    r"""
    Numerical implementations of unary elementwise tensor functions.

    Use with network execution to evaluate BroadcastFunction calls on numeric
    components. Complex conjugation is included by default. Symbolic function
    calls whose arguments are not numeric can remain symbolic.

    Examples
    --------
    >>> from symbolica.community.tensor import TensorFunctionLibrary, BroadcastFunction
    >>> functions = TensorFunctionLibrary()
    >>> functions.register(BroadcastFunction("square"), lambda x: x * x)
    """
    def __repr__(self) -> builtins.str:
        r"""
        Return a summary of the registered elementwise tensor functions.

        Examples
        --------
        >>> from symbolica.community import tensor as sp
        >>> functions = sp.TensorFunctionLibrary()
        >>> text = repr(functions)
        """
    def __new__(cls) -> TensorFunctionLibrary:
        r"""
        Create a numerical function library with built-in conjugation.

        Returns
        -------
        TensorFunctionLibrary
            Mutable library for BroadcastFunction implementations.

        Examples
        --------
        >>> from symbolica.community.tensor import TensorFunctionLibrary
        >>> functions = TensorFunctionLibrary()
        """
    def register(self, function: BroadcastFunction, callback: typing.Callable[[float | complex], float | complex]) -> None:
        r"""
        Register a numerical implementation for an elementwise function.

        Parameters
        ----------
        function : BroadcastFunction
            Function to implement; an existing implementation is replaced.
        callback : callable
            Receives one float or complex value and returns a float or complex
            value. Results determine the numerical output type.

        Returns
        -------
        None
            Updates this function library.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorFunctionLibrary, BroadcastFunction
        >>> square = BroadcastFunction("numeric_square")
        >>> functions = TensorFunctionLibrary()
        >>> functions.register(square, lambda value: value * value)
        >>> square(tensor).to_tensor(function_library=functions)[0, 1]
        4.0
        """

@typing.final
class TensorLibrary:
    r"""
    Reusable component definitions indexed by tensor name and signature.

    Register a named Tensor, then use its symbolic expression in calculations
    with this library. A full signature includes the name, scalar arguments, and
    representations. A name alone is a shortcut when it identifies one entry.

    Lookup returns independent component data. Enumeration lists stored entries;
    dimension-dependent factories, such as metrics, are resolved on demand.

    Examples
    --------
    >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
    >>> space = Representation.euc(2)
    >>> A = TensorName("M")(space, space)
    >>> from symbolica.community.tensor import Tensor
    >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
    >>> from symbolica.community.tensor import TensorLibrary
    >>> library = TensorLibrary()
    >>> library.register(tensor)
    >>> library[A.name][1, 0]
    3.0
    """
    def __repr__(self) -> builtins.str:
        r"""
        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)
        >>> tensor = sp.Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> library = sp.TensorLibrary()
        >>> library.register(tensor)
        >>> text = repr(library)
        """
    def to_html(self, *, settings: typing.Optional[DisplaySettings] = None) -> builtins.str:
        r"""
        Display stored tensors with on-demand component and construction details.

        Parameters
        ----------
        settings : DisplaySettings, optional
            Index and tensor presentation choices; defaults to DisplaySettings().

        Returns
        -------
        str
            HTML fragment for display in a notebook or page.

        Notes
        -----
        Stored entries can be selected to inspect the same component explorer
        as a standalone Tensor. On-demand factories are listed separately.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorLibrary
        >>> library = TensorLibrary()
        >>> library.register(tensor)
        >>> value = library
        >>> html = value.to_html()
        """
    def _repr_html_(self) -> typing.Optional[builtins.str]: ...
    def __new__(cls) -> TensorLibrary:
        r"""
        Create an empty tensor component library.

        Examples
        --------
        >>> from symbolica.community import tensor as sp
        >>> library = sp.TensorLibrary()

        Returns
        -------
        TensorLibrary
            Library ready to accept named tensors through register().

        Examples
        --------
        >>> from symbolica.community.tensor import TensorLibrary
        >>> library = TensorLibrary()
        >>> len(library)
        0
        """
    @staticmethod
    def construct() -> TensorLibrary:
        r"""
        Create an empty tensor component library.

        Examples
        --------
        >>> from symbolica.community import tensor as sp
        >>> library = sp.TensorLibrary.construct()

        Returns
        -------
        TensorLibrary
            Library ready to accept named tensors through register().

        Examples
        --------
        >>> from symbolica.community.tensor import TensorLibrary
        >>> library = TensorLibrary.construct()
        >>> len(library)
        0
        """
    def register(self, tensor: Tensor) -> None:
        r"""
        Store an independent copy of a named tensor's components.

        Examples
        --------
        >>> from symbolica.community import tensor as sp
        >>> r = sp.Representation.euc(2)
        >>> A = sp.TensorName("docs::A")(r, r)
        >>> tensor = sp.Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> library = sp.TensorLibrary()
        >>> library.register(tensor)
        >>> stored = library[A]

        Parameters
        ----------
        tensor : Tensor
            Tensor with a name, scalar key arguments, concrete dimensions, and
            fully unresolved external axes (no explicit index labels).
            Use tensor.with_name(...) if the tensor is unnamed.

        Returns
        -------
        None
            Adds or replaces the entry for this exact signature.

        Notes
        -----
        Changing the original tensor afterward does not change this library.
        Register a modified tensor again to update its stored definition.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorLibrary
        >>> library = TensorLibrary()
        >>> library.register(tensor)
        >>> len(library)
        1
        """
    def __getitem__(self, key: TensorExpression | TensorName | Expression | builtins.str) -> Tensor:
        r"""
        Retrieve a tensor by exact signature or unambiguous name.

        Parameters
        ----------
        key : TensorExpression, TensorName, Expression, or str
            A fully unresolved tensor expression selects an exact signature.
            A TensorName, symbol, or string selects a name only when exactly one
            stored signature has that name. Exact signatures also select factories.
            Strings without a namespace use "spenso_python"; prefer TensorName
            or a fully qualified string when the symbol uses another namespace.

        Returns
        -------
        Tensor
            An independent copy in the requested logical axis order. Call its
            expression() method for a symbolic reference.

        Raises
        ------
        KeyError
            The key is missing or the name matches more than one stored signature.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorLibrary
        >>> library = TensorLibrary()
        >>> library.register(tensor)
        >>> stored = library[A]
        >>> stored[0, 1]
        2.0
        """
    def __contains__(self, key: TensorExpression | TensorName | Expression | builtins.str) -> builtins.bool:
        r"""
        Check whether a stored signature or factory can resolve a key.

        Parameters
        ----------
        key : TensorExpression, TensorName, Expression, or str
            A fully unresolved tensor expression selects an exact signature.
            A TensorName, symbol, or string selects a name only when exactly one
            stored signature has that name. Exact signatures also select factories.
            Strings without a namespace use "spenso_python"; prefer TensorName
            or a fully qualified string when the symbol uses another namespace.

        Returns
        -------
        bool
            False for a missing key. Factories are checked without constructing
            their component data.

        Notes
        -----
        An ambiguous name or invalid key raises the same error as lookup.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorLibrary
        >>> library = TensorLibrary()
        >>> library.register(tensor)
        >>> A in library
        True
        """
    @typing.overload
    def get(self, key: TensorExpression | TensorName | Expression | builtins.str, default: None = None) -> Tensor | None:
        r"""
        Retrieve a tensor, returning a default when its signature is absent.

        Parameters
        ----------
        key : TensorExpression, TensorName, Expression, or str
            A fully unresolved tensor expression selects an exact signature.
            A TensorName, symbol, or string selects a name only when exactly one
            stored signature has that name. Exact signatures also select factories.
            Strings without a namespace use "spenso_python"; prefer TensorName
            or a fully qualified string when the symbol uses another namespace.
        default : object, default None
            Value returned only when the signature is missing.

        Returns
        -------
        Tensor or object
            Independent tensor snapshot, or the supplied default.

        Notes
        -----
        Ambiguous names and invalid keys still raise; they do not select the default.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorLibrary
        >>> library = TensorLibrary()
        >>> library.register(tensor)
        >>> library.get("missing_tensor") is None
        True
        """
    @typing.overload
    def get(self, key: TensorExpression | TensorName | Expression | builtins.str, default: _LibraryDefault) -> Tensor | _LibraryDefault:
        r"""
        Retrieve a tensor, returning a default when its signature is absent.

        Parameters
        ----------
        key : TensorExpression, TensorName, Expression, or str
            A fully unresolved tensor expression selects an exact signature.
            A TensorName, symbol, or string selects a name only when exactly one
            stored signature has that name. Exact signatures also select factories.
            Strings without a namespace use "spenso_python"; prefer TensorName
            or a fully qualified string when the symbol uses another namespace.
        default : object, default None
            Value returned only when the signature is missing.

        Returns
        -------
        Tensor or object
            Independent tensor snapshot, or the supplied default.

        Notes
        -----
        Ambiguous names and invalid keys still raise; they do not select the default.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorLibrary
        >>> library = TensorLibrary()
        >>> library.register(tensor)
        >>> library.get("missing_tensor") is None
        True
        """
    def __len__(self) -> builtins.int:
        r"""
        Count stored tensor definitions.

        Returns
        -------
        int
            Number of stored entries; excludes on-demand factories.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorLibrary
        >>> library = TensorLibrary()
        >>> library.register(tensor)
        >>> len(library)
        1
        """
    def keys(self) -> builtins.list[TensorExpression]:
        r"""
        List the full unresolved signatures of stored tensors.

        Returns
        -------
        list of TensorExpression
            Snapshot in name/signature order, excluding on-demand factories.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorLibrary
        >>> library = TensorLibrary()
        >>> library.register(tensor)
        >>> len(library.keys())
        1
        """
    def values(self) -> builtins.list[Tensor]:
        r"""
        List independent copies of the stored tensors.

        Returns
        -------
        list of Tensor
            Snapshot in the same order as keys(), excluding on-demand factories.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorLibrary
        >>> library = TensorLibrary()
        >>> library.register(tensor)
        >>> len(library.values())
        1
        """
    def items(self) -> builtins.list[tuple[TensorExpression, Tensor]]:
        r"""
        List stored tensor signatures together with their component data.

        Returns
        -------
        list of (TensorExpression, Tensor)
            Independent snapshots in the same order as keys().

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorLibrary
        >>> library = TensorLibrary()
        >>> library.register(tensor)
        >>> len(library.items())
        1
        """
    def __iter__(self) -> typing.Iterator[TensorExpression]:
        r"""
        Iterate over a snapshot of stored tensor signatures.

        Returns
        -------
        iterator of TensorExpression
            Same entries and ordering as keys().

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorLibrary
        >>> library = TensorLibrary()
        >>> library.register(tensor)
        >>> len(list(library))
        1
        """
    @staticmethod
    def hep_lib() -> TensorLibrary:
        r"""
        Load standard Dirac and SU(3) tensors with floating-point components.

        Examples
        --------
        >>> from symbolica.community import tensor as sp
        >>> library = sp.TensorLibrary.hep_lib()
        >>> gamma = sp.TensorExpression.dirac_gamma(4)
        >>> components = gamma.to_tensor(library)

        Returns
        -------
        TensorLibrary
            Independent library with four-dimensional Dirac matrices in the Weyl
            basis, SU(3) color tensors, and dimension-dependent metric factories.

        Notes
        -----
        Values use double-precision real or complex numbers. This explicitly
        selects numerical components; omitted HEP libraries and hep_lib_atom()
        use exact Symbolica expressions.

        Examples
        --------
        >>> from symbolica.community.tensor import TensorLibrary, TensorExpression
        >>> library = TensorLibrary.hep_lib()
        >>> library[TensorExpression.dirac_gamma(4)].shape
        (4, 4, 4)
        """
    @staticmethod
    def hep_lib_atom() -> TensorLibrary:
        r"""
        Load standard Dirac and SU(3) tensors with exact symbolic components.

        Examples
        --------
        >>> from symbolica.community import tensor as sp
        >>> library = sp.TensorLibrary.hep_lib_atom()
        >>> gamma = sp.TensorExpression.dirac_gamma(4)
        >>> components = gamma.to_tensor(library)

        Returns
        -------
        TensorLibrary
            Independent library with four-dimensional Dirac matrices in the Weyl
            basis, SU(3) color tensors, and dimension-dependent metric factories.

        Notes
        -----
        Components are Symbolica Expressions, retaining exact rational and
        algebraic constants for symbolic component calculations. This is the
        same component convention used when tensor-network evaluation omits a
        library. Use hep_lib() to request floating-point HEP data explicitly.

        Examples
        --------
        >>> from symbolica.community.tensor import TensorLibrary, TensorExpression
        >>> library = TensorLibrary.hep_lib_atom()
        >>> library[TensorExpression.dirac_gamma(4)].shape
        (4, 4, 4)
        """

@typing.final
class TensorName:
    r"""
    A registered function name for symbolic tensors of arbitrary index spaces.

    Call a name with scalar arguments followed by Slots or Representations to
    create a TensorExpression. The latter leave axes unresolved for later indexing.
    Use ``vector`` for a rank-one name that also supports compact dot notation.
    Predefined accessors identify standard tensors; use TensorExpression factories
    to construct their correctly ordered axes and TensorPattern for matching.

    Examples
    --------
    >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
    >>> space = Representation.euc(3)
    >>> A = TensorName("A")(space, space)
    >>> A("i", "j").rank
    2
    """
    def _repr_html_(self) -> typing.Optional[builtins.str]: ...
    def _repr_latex_(self) -> builtins.str: ...
    def __new__(cls, name: builtins.str, *, rank: typing.Optional[builtins.int] = None, is_symmetric: typing.Optional[builtins.bool] = None, is_antisymmetric: typing.Optional[builtins.bool] = None, is_cyclesymmetric: typing.Optional[builtins.bool] = None, is_linear: typing.Optional[builtins.bool] = None, is_flat: typing.Optional[builtins.bool] = None, is_scalar: typing.Optional[builtins.bool] = None, is_real: typing.Optional[builtins.bool] = None, is_integer: typing.Optional[builtins.bool] = None, is_positive: typing.Optional[builtins.bool] = None, tags: typing.Optional[typing.Sequence[builtins.str]] = None, aliases: typing.Optional[typing.Sequence[builtins.str]] = None, normalization: typing.Optional[symbolica.core.Transformer | typing.Callable[[symbolica.core.Expression], symbolica.core.Expression]] = None, print: typing.Optional[dict[str, str] | typing.Callable[..., str | None]] = None, derivative: typing.Optional[typing.Any] = None, series: typing.Optional[typing.Any] = None, eval: typing.Optional[typing.Any] = None, data: typing.Optional[_ScalarInput | str | dict | list | bytes] = None) -> TensorName:
        r"""
        Register a tensor function name.

        Parameters
        ----------
        name : str
            Symbolica function name. Passing only a previously registered name
            reuses its attributes and printers.
        rank : int, optional
            None permits arbitrary rank. Only rank=1 is supported as a fixed rank;
            it requires exactly one structural axis in each call.
        is_symmetric, is_antisymmetric, is_cyclesymmetric : bool, optional
            Symmetry of the function arguments under all permutations, signed
            permutations, or cyclic rotations. These affect scalar arguments as
            well as index arguments. Repeated arguments in an antisymmetric call
            make that call zero.
        is_linear : bool, optional
            Distribute the function over sums in its arguments.
        is_flat : bool, optional
            Flatten nested calls with the same head.
        is_scalar : bool, optional
            Declare calls scalar for Symbolica's algebra. Do not use True for a
            tensor head with free indices.
        is_real, is_integer, is_positive : bool, optional
            Assumptions used by Symbolica for the registered symbol.
        tags : sequence of str, optional
            Additional Symbolica tags; Spenso's required tags are included automatically.
        aliases : sequence of str, optional
            Additional names for the same Symbolica symbol.
        normalization : Transformer or callable, optional
            Normalize a newly constructed call. A callable receives an Expression
            and returns its normalized Expression; tensor interfaces must remain valid.
        print : dict of str to str or callable, optional
            A mapping with keys "plain", "latex", "typst", or "mathml" changes just the
            displayed tensor name. Plain, LaTeX and Typst values are bounded display
            text without math delimiters, for example {"typst": "overline(J)"}.
            MathML accepts a bounded presentation subset with validated attributes;
            executable markup, namespaces and unknown entities raise ValueError.
            Notation is process-local and is not saved with expressions. Equal
            re-registration succeeds; conflicting notation raises ValueError.
            Spenso adds arguments and indices.
            A callable uses Symbolica's print callback convention and replaces
            the complete display; returning None selects the standard display.
        derivative, series, eval : callable, optional
            Symbolica callbacks for differentiation, series expansion, and numerical
            evaluation. Their arguments and results follow ``symbolica.S``.
        data : object, optional
            Symbolica user data attached to the symbol, such as a dict, list, or bytes.

        Returns
        -------
        TensorName
            A callable name for constructing symbolic tensors.

        Examples
        --------
        >>> from symbolica.community.tensor import TensorName, Representation
        >>> J = TensorName("Jbar", print={"typst": "overline(J)"})
        >>> vector = J(Representation.euc(3))
        >>> vector.rank
        1
        """
    @staticmethod
    def vector(name: builtins.str, *, is_symmetric: typing.Optional[builtins.bool] = None, is_antisymmetric: typing.Optional[builtins.bool] = None, is_cyclesymmetric: typing.Optional[builtins.bool] = None, is_linear: typing.Optional[builtins.bool] = None, is_flat: typing.Optional[builtins.bool] = None, is_scalar: typing.Optional[builtins.bool] = None, is_real: typing.Optional[builtins.bool] = None, is_integer: typing.Optional[builtins.bool] = None, is_positive: typing.Optional[builtins.bool] = None, tags: typing.Optional[typing.Sequence[builtins.str]] = None, aliases: typing.Optional[typing.Sequence[builtins.str]] = None, normalization: typing.Optional[symbolica.core.Transformer | typing.Callable[[symbolica.core.Expression], symbolica.core.Expression]] = None, print: typing.Optional[dict[str, str] | typing.Callable[..., str | None]] = None, derivative: typing.Optional[typing.Any] = None, series: typing.Optional[typing.Any] = None, eval: typing.Optional[typing.Any] = None, data: typing.Optional[_ScalarInput | str | dict | list | bytes] = None) -> TensorName:
        r"""
        Register a tensor function with exactly one axis.

        Parameters
        ----------
        name : str
            Symbolica function name. Passing only a previously registered name
            reuses its attributes and printers.
        is_symmetric, is_antisymmetric, is_cyclesymmetric : bool, optional
            Symmetry of the function arguments under all permutations, signed
            permutations, or cyclic rotations. These affect scalar arguments as
            well as index arguments. Repeated arguments in an antisymmetric call
            make that call zero.
        is_linear : bool, optional
            Distribute the function over sums in its arguments.
        is_flat : bool, optional
            Flatten nested calls with the same head.
        is_scalar : bool, optional
            Declare calls scalar for Symbolica's algebra. Do not use True for a
            tensor head with free indices.
        is_real, is_integer, is_positive : bool, optional
            Assumptions used by Symbolica for the registered symbol.
        tags : sequence of str, optional
            Additional Symbolica tags; Spenso's required tags are included automatically.
        aliases : sequence of str, optional
            Additional names for the same Symbolica symbol.
        normalization : Transformer or callable, optional
            Normalize a newly constructed call. A callable receives an Expression
            and returns its normalized Expression; tensor interfaces must remain valid.
        print : dict of str to str or callable, optional
            A mapping with keys "plain", "latex", "typst", or "mathml" changes just the
            displayed tensor name. Plain, LaTeX and Typst values are bounded display
            text without math delimiters, for example {"typst": "overline(J)"}.
            MathML accepts a bounded presentation subset with validated attributes;
            executable markup, namespaces and unknown entities raise ValueError.
            Notation is process-local and is not saved with expressions. Equal
            re-registration succeeds; conflicting notation raises ValueError.
            Spenso adds arguments and indices.
            A callable uses Symbolica's print callback convention and replaces
            the complete display; returning None selects the standard display.
        derivative, series, eval : callable, optional
            Symbolica callbacks for differentiation, series expansion, and numerical
            evaluation. Their arguments and results follow ``symbolica.S``.
        data : object, optional
            Symbolica user data attached to the symbol, such as a dict, list, or bytes.

        Returns
        -------
        TensorName
            A callable name for constructing symbolic tensors.

        Examples
        --------
        >>> from symbolica.community.tensor import TensorName, Representation
        >>> J = TensorName.vector("Jbar_vector", print={"typst": "overline(J)"})
        >>> vector = J(Representation.euc(3))
        >>> vector.rank
        1
        """
    def __repr__(self) -> builtins.str:
        r"""
        Return a readable object description for inspection.

        Examples
        --------
        >>> from symbolica.community import tensor as sp
        >>> name = sp.TensorName("docs::A")
        >>> text = repr(name)
        """
    def __str__(self) -> builtins.str:
        r"""
        Return a readable text representation.

        Examples
        --------
        >>> from symbolica.community import tensor as sp
        >>> name = sp.TensorName("docs::A")
        >>> text = str(name)
        """
    def to_expression(self) -> Expression:
        r"""
        Return this function name as a Symbolica symbol.

        Examples
        --------
        >>> from symbolica.community import tensor as sp
        >>> name = sp.TensorName("docs::A")
        >>> symbolic_head = name.to_expression()

        Returns
        -------
        Expression
            The bare function head, without arguments or tensor structure.

        Examples
        --------
        >>> from symbolica.community.tensor import TensorName
        >>> name = TensorName("tagged_TensorName", tags=["example::example"])
        >>> head = name.to_expression()
        """
    def has_tag(self, tag: builtins.str) -> builtins.bool:
        r"""
        Check whether the registered function carries a tag.

        Parameters
        ----------
        tag : str
            Exact tag name. An unqualified name also matches its "python::" form.

        Returns
        -------
        bool
            Whether the tag is present.

        Examples
        --------
        >>> from symbolica.community.tensor import TensorName
        >>> name = TensorName("tagged_TensorName", tags=["example::example"])
        >>> name.has_tag("example::example")
        True
        """
    def get_tags(self) -> builtins.list[builtins.str]:
        r"""
        List the tags attached to the registered function.

        Returns
        -------
        list of str
            Fully qualified tags, including the tags required by Spenso.

        Examples
        --------
        >>> from symbolica.community.tensor import TensorName
        >>> name = TensorName("tagged_TensorName", tags=["example::example"])
        >>> "example::example" in name.get_tags()
        True
        """
    @staticmethod
    def g() -> TensorName:
        r"""
        Return the registered name of the metric pairing.

        Returns
        -------
        TensorName
            The existing symbolic function head, including its tags and symmetries.

        Notes
        -----
        Use ``TensorExpression.g`` to construct a tensor with distinct unresolved
        axes, or ``TensorPattern.g`` to construct a rewrite pattern. The Python
        accessor name does not change the underlying Symbolica symbol.

        Examples
        --------
        >>> from symbolica.community.tensor import TensorName
        >>> head = TensorName.g().to_expression()
        """
    @staticmethod
    def flat() -> TensorName:
        r"""
        Return the registered name of the metric map for raising or lowering an index.

        Returns
        -------
        TensorName
            The existing symbolic function head, including its tags and symmetries.

        Notes
        -----
        Use ``TensorExpression.flat`` to construct a tensor with distinct unresolved
        axes, or ``TensorPattern.flat`` to construct a rewrite pattern. The Python
        accessor name does not change the underlying Symbolica symbol.

        Examples
        --------
        >>> from symbolica.community.tensor import TensorName
        >>> head = TensorName.flat().to_expression()
        """
    @staticmethod
    def dirac_gamma() -> TensorName:
        r"""
        Return the registered name of the Dirac gamma matrices for Clifford algebra.

        Returns
        -------
        TensorName
            The existing symbolic function head, including its tags and symmetries.

        Notes
        -----
        Use ``TensorExpression.dirac_gamma`` to construct a tensor with distinct unresolved
        axes, or ``TensorPattern.dirac_gamma`` to construct a rewrite pattern. The Python
        accessor name does not change the underlying Symbolica symbol.

        Examples
        --------
        >>> from symbolica.community.tensor import TensorName
        >>> head = TensorName.dirac_gamma().to_expression()
        """
    @staticmethod
    def gamma0() -> TensorName:
        r"""
        Return the registered name of the time-component Dirac matrix gamma^0.

        Returns
        -------
        TensorName
            The existing symbolic function head, including its tags and symmetries.

        Notes
        -----
        Use ``TensorExpression.gamma0`` to construct a tensor with distinct unresolved
        axes, or ``TensorPattern.gamma0`` to construct a rewrite pattern. The Python
        accessor name does not change the underlying Symbolica symbol.

        Examples
        --------
        >>> from symbolica.community.tensor import TensorName
        >>> head = TensorName.gamma0().to_expression()
        """
    @staticmethod
    def charge_conjugation() -> TensorName:
        r"""
        Return the registered name of the Dirac charge-conjugation matrix.

        Returns
        -------
        TensorName
            The existing symbolic function head, including its tags and symmetries.

        Notes
        -----
        Use ``TensorExpression.charge_conjugation`` to construct a tensor with distinct unresolved
        axes, or ``TensorPattern.charge_conjugation`` to construct a rewrite pattern. The Python
        accessor name does not change the underlying Symbolica symbol.

        Examples
        --------
        >>> from symbolica.community.tensor import TensorName
        >>> head = TensorName.charge_conjugation().to_expression()
        """
    @staticmethod
    def levi_civita() -> TensorName:
        r"""
        Return the registered name of the totally antisymmetric Levi-Civita tensor.

        Returns
        -------
        TensorName
            The existing symbolic function head, including its tags and symmetries.

        Notes
        -----
        Use ``TensorExpression.levi_civita`` to construct a tensor with distinct unresolved
        axes, or ``TensorPattern.levi_civita`` to construct a rewrite pattern. The Python
        accessor name does not change the underlying Symbolica symbol.

        Examples
        --------
        >>> from symbolica.community.tensor import TensorName
        >>> head = TensorName.levi_civita().to_expression()
        """
    @staticmethod
    def gamma5() -> TensorName:
        r"""
        Return the registered name of the Dirac chirality matrix gamma^5.

        Returns
        -------
        TensorName
            The existing symbolic function head, including its tags and symmetries.

        Notes
        -----
        Use ``TensorExpression.gamma5`` to construct a tensor with distinct unresolved
        axes, or ``TensorPattern.gamma5`` to construct a rewrite pattern. The Python
        accessor name does not change the underlying Symbolica symbol.

        Examples
        --------
        >>> from symbolica.community.tensor import TensorName
        >>> head = TensorName.gamma5().to_expression()
        """
    @staticmethod
    def projm() -> TensorName:
        r"""
        Return the registered name of the left-chiral Dirac projector (I - gamma^5)/2.

        Returns
        -------
        TensorName
            The existing symbolic function head, including its tags and symmetries.

        Notes
        -----
        Use ``TensorExpression.projm`` to construct a tensor with distinct unresolved
        axes, or ``TensorPattern.projm`` to construct a rewrite pattern. The Python
        accessor name does not change the underlying Symbolica symbol.

        Examples
        --------
        >>> from symbolica.community.tensor import TensorName
        >>> head = TensorName.projm().to_expression()
        """
    @staticmethod
    def projp() -> TensorName:
        r"""
        Return the registered name of the right-chiral Dirac projector (I + gamma^5)/2.

        Returns
        -------
        TensorName
            The existing symbolic function head, including its tags and symmetries.

        Notes
        -----
        Use ``TensorExpression.projp`` to construct a tensor with distinct unresolved
        axes, or ``TensorPattern.projp`` to construct a rewrite pattern. The Python
        accessor name does not change the underlying Symbolica symbol.

        Examples
        --------
        >>> from symbolica.community.tensor import TensorName
        >>> head = TensorName.projp().to_expression()
        """
    @staticmethod
    def sigma() -> TensorName:
        r"""
        Return the registered name of the antisymmetric Dirac sigma tensor.

        Returns
        -------
        TensorName
            The existing symbolic function head, including its tags and symmetries.

        Notes
        -----
        Use ``TensorExpression.sigma`` to construct a tensor with distinct unresolved
        axes, or ``TensorPattern.sigma`` to construct a rewrite pattern. The Python
        accessor name does not change the underlying Symbolica symbol.

        Examples
        --------
        >>> from symbolica.community.tensor import TensorName
        >>> head = TensorName.sigma().to_expression()
        """
    @staticmethod
    def color_f() -> TensorName:
        r"""
        Return the registered name of the antisymmetric color structure constants f^{abc}.

        Returns
        -------
        TensorName
            The existing symbolic function head, including its tags and symmetries.

        Notes
        -----
        Use ``TensorExpression.color_f`` to construct a tensor with distinct unresolved
        axes, or ``TensorPattern.color_f`` to construct a rewrite pattern. The Python
        accessor name does not change the underlying Symbolica symbol.

        Examples
        --------
        >>> from symbolica.community.tensor import TensorName
        >>> head = TensorName.color_f().to_expression()
        """
    @staticmethod
    def color_t() -> TensorName:
        r"""
        Return the registered name of the fundamental color generators T^a.

        Returns
        -------
        TensorName
            The existing symbolic function head, including its tags and symmetries.

        Notes
        -----
        Use ``TensorExpression.color_t`` to construct a tensor with distinct unresolved
        axes, or ``TensorPattern.color_t`` to construct a rewrite pattern. The Python
        accessor name does not change the underlying Symbolica symbol.

        Examples
        --------
        >>> from symbolica.community.tensor import TensorName
        >>> head = TensorName.color_t().to_expression()
        """
    def __call__(self, *args: Slot | Representation | _ScalarInput) -> TensorExpression:
        r"""
        Construct a tensor with scalar arguments and ordered axes.

        Parameters
        ----------
        *args : scalar expression, Slot, or Representation
            Scalar arguments first, then labeled Slots or unresolved Representations.
            A compact vector may bind an axis of a generic tensor, producing a
            contraction instead of a stored-data descriptor.

        Returns
        -------
        TensorExpression
            The tensor call, including a scalar tensor when there are no axes.
            Repeated compatible explicit labels are contracted.

        Notes
        -----
        For predefined metrics, Dirac matrices, and color tensors, prefer the
        corresponding TensorExpression factory. Fixed-structure names reject direct
        calls. Symmetries act on the full argument list; an antisymmetric name
        called twice with exactly the same representation argument is zero.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorName, Representation
        >>> space = Representation.euc(3)
        >>> tensor = TensorName("B")(S("x"), 7, space("i"), space)
        >>> tensor.rank
        2
        """

@typing.final
class TensorNetwork:
    r"""
    An executable tensor calculation that retains component data.

    Networks combine tensor contractions, sums, products, and elementwise
    functions. Arithmetic creates new networks. ``execute()`` advances a network
    in place; ``step()`` and ``to_tensor()`` work on copies. ``expression()``
    returns the symbolic source, while ``status`` reports remaining work.

    Examples
    --------
    >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
    >>> space = Representation.euc(2)
    >>> A = TensorName("M")(space, space)
    >>> from symbolica.community.tensor import Tensor
    >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
    >>> from symbolica.community.tensor import TensorNetwork
    >>> network = TensorNetwork(tensor)
    >>> result = network.to_tensor()
    >>> result[0, 1]
    2.0
    """
    @property
    def axes(self) -> tuple[Slot | Representation, ...]:
        r"""
        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"))
        True
        >>> A.permute_axes([1, 0]).axes == A.axes[::-1]
        True
        """
    @property
    def structure(self) -> TensorStructure:
        r"""
        Canonical external signature of the whole tensor.

        Returns
        -------
        TensorStructure
            Free axes in canonical order, independent of names and component layout.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> network.structure.rank
        2
        """
    @property
    def rank(self) -> builtins.int:
        r"""
        Number of external tensor axes.

        Returns
        -------
        int
            Zero for a scalar.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> network.rank
        2
        """
    @property
    def is_scalar(self) -> builtins.bool:
        r"""
        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(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> network.is_scalar
        False
        """
    @property
    def shape(self) -> tuple[int | Expression, ...]:
        r"""
        Dimensions in logical axis order.

        Returns
        -------
        tuple of int or Expression
            Axis sizes in the order of axes, the current component view.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> network.shape
        (2, 2)
        """
    @property
    def status(self) -> ExecutionStatus:
        r"""
        Read a snapshot of the remaining graph work without executing it.

        Returns
        -------
        ExecutionStatus
            Counts and ready operations at the moment of inspection.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> network.status.complete
        True
        """
    def __new__(cls, expr: typing.Any, library: typing.Optional[TensorLibrary] = None) -> TensorNetwork:
        r"""
        Create a network from tensor components or symbolic algebra.

        Parameters
        ----------
        expr : Tensor, TensorNetwork, TensorExpression, or scalar expression
            Computation to represent. A Tensor retains its data; a TensorNetwork
            is copied with its execution progress.
        library : TensorLibrary, optional
            Component definitions. Defaults to the built-in four-dimensional Dirac
            and SU(3) library. Unregistered tensors receive symbolic components.

        Returns
        -------
        TensorNetwork
            A new network with the corresponding external tensor interface.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> network.shape
        (2, 2)
        """
    @staticmethod
    def one() -> TensorNetwork:
        r"""
        Construct the scalar 1 network.

        Examples
        --------
        >>> from symbolica.community import tensor as sp
        >>> network = sp.TensorNetwork.one()
        >>> value = network.to_tensor().scalar()

        Returns
        -------
        TensorNetwork
            A rank-zero multiplicative identity.

        Examples
        --------
        >>> from symbolica.community.tensor import TensorNetwork
        >>> TensorNetwork.one().result_scalar() == 1
        True
        """
    @staticmethod
    def bracket() -> Expression:
        r"""
        Return the symbolic function used to group a tensor subexpression.

        Returns
        -------
        Expression
            A callable Symbolica head. Its argument is kept as a grouped tensor
            subexpression when parsed as a network.

        Notes
        -----
        This is useful when constructing raw Symbolica tensor syntax. Tensor-aware
        operations and simplifiers already understand this grouping.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorNetwork
        >>> grouped = TensorNetwork.bracket()(S("x") + 1)
        """
    @staticmethod
    def broadcast(str: builtins.str) -> Expression:
        r"""
        Register a raw Symbolica function for elementwise tensor application.

        Parameters
        ----------
        str : str
            Function name to register with the broadcast tag.

        Returns
        -------
        Expression
            A callable Symbolica function head.

        Notes
        -----
        Prefer BroadcastFunction when applying the function to TensorExpression,
        Tensor, or TensorNetwork objects so the return type follows the operand.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorNetwork
        >>> applied = TensorNetwork.broadcast("raw_function")(S("x"))
        """
    @staticmethod
    def zero() -> TensorNetwork:
        r"""
        Construct the scalar 0 network.

        Examples
        --------
        >>> from symbolica.community import tensor as sp
        >>> network = sp.TensorNetwork.zero()
        >>> value = network.to_tensor().scalar()

        Returns
        -------
        TensorNetwork
            A rank-zero additive zero.

        Examples
        --------
        >>> from symbolica.community.tensor import TensorNetwork
        >>> TensorNetwork.zero().result_scalar() == 0
        True
        """
    def replace(self, pattern: _ScalarInput, rhs: _ReplacementInput, cond: typing.Optional[PatternRestriction | Condition] = None, non_greedy_wildcards: typing.Optional[typing.Sequence[Expression]] = None, level_range: typing.Optional[tuple[builtins.int, typing.Optional[builtins.int]]] = None, level_is_tree_depth: typing.Optional[builtins.bool] = None, allow_new_wildcards_on_rhs: typing.Optional[builtins.bool] = None, rhs_cache_size: typing.Optional[builtins.int] = None, repeat: typing.Optional[builtins.bool] = None) -> TensorNetwork:
        r"""
        Replace scalar expressions and symbolic component values in a copy.

        Examples
        --------
        >>> from symbolica.community import tensor as sp
        >>> from symbolica import E, S
        >>> x = S("docs::x")
        >>> network = sp.TensorNetwork(sp.TensorExpression(x + 1))
        >>> replaced = network.replace(x, E("2"))

        Parameters
        ----------
        pattern : scalar expression
            Symbolica pattern to find in scalar algebra and component expressions.
        rhs : scalar expression or HeldExpression
            Replacement expression. Python replacement callbacks are not supported
            by this network method; use TensorRule with TensorExpression for
            whole-tensor replacement.
        cond : PatternRestriction or Condition, optional
            Restriction applied to candidate matches.
        non_greedy_wildcards : sequence of Expression, optional
            Wildcards that should prefer shorter matches.
        level_range : (int, int or None), optional
            Minimum and maximum matching level; defaults to (0, None).
        level_is_tree_depth : bool, optional
            Count tree depth rather than function nesting. Defaults to False.
        allow_new_wildcards_on_rhs : bool, optional
            Permit unbound wildcard symbols in the replacement. Defaults to False.
        rhs_cache_size : int, optional
            Maximum cached right-hand-side substitutions. Defaults to 100.
        repeat : bool, optional
            Repeat replacements until unchanged. Defaults to False.

        Returns
        -------
        TensorNetwork
            A copy with updated scalar/component expressions. Its external axes
            and symbolic source descriptor are unchanged.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import Tensor, TensorName, Representation
        >>> x = S("x")
        >>> values = Tensor.dense(TensorName.vector("eval_v")(Representation.euc(2)), [x, x**2])
        >>> evaluator = values.evaluator([x], iterations=1, n_cores=1)
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(values).replace(x, 2)
        >>> network.to_tensor()[0] == 2
        True
        """
    def evaluate(self, constants: typing.Mapping[Expression, builtins.float], functions: typing.Mapping[Expression, typing.Any]) -> TensorNetwork:
        r"""
        Numerically evaluate symbolic component values in a network copy.

        Parameters
        ----------
        constants : mapping of Expression to float
            Real values for symbolic parameters.
        functions : mapping of Expression to callable
            Symbolica function heads and real-valued Python implementations.
            A callback receives one list of evaluated argument values and
            returns a float; for example, lambda args: args[0] ** 2.

        Returns
        -------
        TensorNetwork
            Network with evaluated component values; contractions are not executed.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import Tensor, TensorName, Representation
        >>> x = S("x")
        >>> values = Tensor.dense(TensorName.vector("eval_v")(Representation.euc(2)), [x, x**2])
        >>> evaluator = values.evaluator([x], iterations=1, n_cores=1)
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(values).evaluate({x: 2.0}, {})
        >>> network.to_tensor()[1]
        4.0
        >>> f = S("f_network")
        >>> data = Tensor.dense(values.expression(), [f(x), x])
        >>> network = TensorNetwork(data).evaluate({x: 2.0}, {f: lambda args: args[0] + 1})
        >>> network.to_tensor()[0]
        3.0
        """
    def execute(self, library: typing.Optional[TensorLibrary] = None, function_library: typing.Optional[TensorFunctionLibrary] = None, n_steps: typing.Optional[builtins.int] = None, mode: ExecutionMode = ExecutionMode.All) -> None:
        r"""
        Advance this network's computation in place.

        Parameters
        ----------
        library : TensorLibrary, optional
            Component definitions. Defaults to the built-in four-dimensional Dirac
            and SU(3) library. Unregistered tensors receive symbolic components.
        function_library : TensorFunctionLibrary, optional
            Numerical implementations of broadcast functions. Defaults to the
            built-in function library.
        n_steps : int, optional
            Number of execution rounds. None runs the selected strategy to completion.
        mode : ExecutionMode, default ExecutionMode.All
            All uses MinIntermediateCost, which estimates sparse overlap and
            symbolic intermediate cost when choosing each contraction. Single
            selects one minimum-degree contraction at a time. Scalar restricts
            contraction to scalar work.
            Preprocessing and ready operations may also run in an execution round.

        Returns
        -------
        None
            This network's execution progress and stored intermediate values change.

        Notes
        -----
        Use ``to_tensor()`` to evaluate a copy, or ``step()`` for an intermediate
        copy. ``result_tensor()`` extracts the result after execution.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> network.execute()
        >>> network.result_tensor()[1, 0]
        3.0
        """
    def result_tensor(self, library: typing.Optional[TensorLibrary] = None) -> Tensor:
        r"""
        Read the component tensor from a completed network.

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

        Returns
        -------
        Tensor
            Result components with the source computation's logical axis order.

        Raises
        ------
        RuntimeError
            Work remains that prevents extracting one result tensor.

        Notes
        -----
        This does not run pending operations. Call execute() first, or use
        to_tensor() to execute a copy and extract the result in one operation.
        Existing component storage is preserved: exact Symbolica expressions
        are not converted to floating-point values.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> network.execute()
        >>> network.result_tensor().shape
        (2, 2)
        """
    def result_scalar(self) -> Expression:
        r"""
        Read the scalar value of a completed rank-zero network.

        Returns
        -------
        Expression
            Scalar result as Symbolica algebra.

        Raises
        ------
        RuntimeError
            The network has not reduced to a scalar result.

        Examples
        --------
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(3)
        >>> network.execute()
        >>> network.result_scalar() == 3
        True
        """
    def __repr__(self) -> builtins.str:
        r"""
        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)
        >>> tensor = sp.Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> network = tensor("i", "j") * tensor("j", "k")
        >>> text = repr(network)
        """
    def __str__(self) -> builtins.str:
        r"""
        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)
        >>> tensor = sp.Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> network = tensor("i", "j") * tensor("j", "k")
        >>> text = str(network)
        """
    def _repr_latex_(self) -> builtins.str: ...
    def _repr_pretty_(self, pretty: typing.Any, cycle: builtins.bool) -> None: ...
    def to_dot(self) -> builtins.str:
        r"""
        Export the current network graph in Graphviz DOT syntax.

        Returns
        -------
        str
            Graph description containing the current tensor nodes and connections.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> source = network.to_dot()
        """
    def to_linnest(self, *, config: typing.Optional[RenderSettings] = None) -> builtins.str:
        r"""
        Export a self-contained Typst document embedding the native SVG graph.

        Parameters
        ----------
        config : RenderSettings, optional
            Graph layout and rendering options. Omit for the standard network view.

        Returns
        -------
        str
            Typst source containing the complete SVG and its typeset labels.

        Notes
        -----
        This depicts the current graph, including execution progress. For the
        symbolic computation in tensor notation, use formatted() or to_svg().
        Graph geometry is drawn in Rust. Static exports reuse completed measurements,
        otherwise use optional Typst or estimated MathML label sizes.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> output = network.to_linnest()
        """
    def render(self, *, config: typing.Optional[RenderSettings] = None) -> DiagramView:
        r"""
        Render a displayable snapshot of the current network graph.

        Parameters
        ----------
        config : RenderSettings, optional
            Graph layout and rendering options. Omit for the standard network view.

        Returns
        -------
        DiagramRender
            Interactive graph snapshot with SVG/HTML exports and notebook display.

        Notes
        -----
        This depicts the current graph, including execution progress. For the
        symbolic computation in tensor notation, use formatted() or to_svg().
        Graph geometry is drawn in Rust. Static exports reuse completed measurements,
        otherwise use optional Typst or estimated MathML label sizes.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> output = network.render()
        """
    def format_tensor(self, show_dimensions: typing.Optional[builtins.bool] = None, *, settings: typing.Optional[DisplaySettings] = None) -> builtins.str:
        r"""
        Produce compact plain-text tensor notation.

        Parameters
        ----------
        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
        -------
        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.

        This formats the symbolic source expression, independent of execution
        progress. Use render() or to_html() for the network graph.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> output = network.format_tensor()
        """
    def to_typst(self, show_dimensions: typing.Optional[builtins.bool] = None, *, settings: typing.Optional[DisplaySettings] = None) -> builtins.str:
        r"""
        Produce static Typst math source.

        Parameters
        ----------
        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
        -------
        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.

        This formats the symbolic source expression, independent of execution
        progress. Use render() or to_html() for the network graph.

        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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> output = network.to_typst()
        """
    def formatted(self, show_dimensions: typing.Optional[builtins.bool] = None, *, settings: typing.Optional[DisplaySettings] = None, notation_source: typing.Optional[builtins.str] = None) -> FormattedOutput:
        r"""
        Create a lazy rich display value for a notebook.

        Parameters
        ----------
        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
        -------
        FormattedOutput
            Each requested backend renders the complete source expression once
            and caches it.

        Notes
        -----
        This formats the symbolic source expression, independent of execution
        progress, retaining a snapshot of that source. Use render() or to_html()
        for the network graph.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> output = network.formatted()
        """
    def to_html(self, *, config: typing.Optional[RenderSettings] = None, browser: typing.Optional[builtins.str] = None) -> builtins.str:
        r"""
        Display the current network graph and execution status.

        Parameters
        ----------
        config : RenderSettings, optional
            Graph layout and rendering options. Omit for the standard network view.

        Returns
        -------
        str
            Interactive HTML graph with its progress summary.

        Notes
        -----
        This depicts the current graph, including execution progress. For the
        symbolic computation in tensor notation, use formatted() or to_svg().
        Graph geometry is drawn in Rust. Static exports reuse completed measurements,
        otherwise use optional Typst or estimated MathML label sizes.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> output = network.to_html()
        """
    def to_svg(self, show_dimensions: typing.Optional[builtins.bool] = None, *, settings: typing.Optional[DisplaySettings] = None, notation_source: typing.Optional[builtins.str] = None) -> builtins.str:
        r"""
        Render static mathematical tensor notation to SVG.
        Requires the optional `typst` Python package. For the network diagram
        without that compiler, use `network.render().to_svg()` instead.

        Parameters
        ----------
        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
        -------
        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.
        Raises ImportError if the optional typst-py package is unavailable, or RuntimeError
        if compilation fails.

        This formats the symbolic source expression, independent of execution
        progress. Use render() or to_html() for the network graph.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> output = network.to_svg()
        """
    def _mime_(self) -> typing.Any: ...
    def _repr_mimebundle_(self, include: typing.Optional[typing.Sequence[builtins.str]] = None, exclude: typing.Optional[typing.Sequence[builtins.str]] = None) -> typing.Any: ...
    def expression(self) -> TensorExpression:
        r"""
        Return the symbolic source computation of this network.

        Returns
        -------
        TensorExpression
            A symbolic tensor with the same external axes.

        Notes
        -----
        Execution progress and replacement of component values do not rewrite
        this source expression. Use result_tensor after execution to inspect values.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> network.expression().rank
        2
        """
    def index(self, *indices: _IndexInput, intern: typing.Optional[typing.Literal['indices', 'flattened']] = None) -> TensorNetwork:
        r"""
        Assign labels to the unresolved external axes.

        Parameters
        ----------
        *indices : int, str, Expression, Slot, or AUTO
            One label per unresolved axis, in logical order. AUTO leaves the
            corresponding axis unchanged. A Slot must have the matching
            representation. Repeated compatible labels cause contraction.
        intern : {"indices", "flattened"} or None, optional
            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.

        Returns
        -------
        TensorNetwork
            An indexed network retaining the component data; the original is unchanged.

        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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> indexed = network.index("i", "j")
        >>> indexed.rank
        2
        """
    def reindex(self, *indices: _IndexInput, intern: typing.Optional[typing.Literal['indices', 'flattened']] = None) -> TensorNetwork:
        r"""
        Assign labels to all external axes.

        Parameters
        ----------
        *indices : int, str, Expression, Slot, or AUTO
            One label per external axis, in logical order. AUTO leaves the
            corresponding axis unchanged. A Slot must have the matching
            representation. Repeated compatible labels cause contraction.
        intern : {"indices", "flattened"} or None, optional
            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.

        Returns
        -------
        TensorNetwork
            An indexed network retaining the component data; the original is unchanged.

        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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> indexed = network.reindex("i", "j")
        >>> indexed.rank
        2
        """
    def rename_indices(self, mapping: dict[int | str | Expression | Slot, _IndexInput], *, intern: typing.Optional[typing.Literal['indices', 'flattened']] = None) -> TensorNetwork:
        r"""
        Rename selected external labels without changing the tensor rank.

        Parameters
        ----------
        mapping : dict
            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.
        intern : {"indices", "flattened"} or None, optional
            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.

        Returns
        -------
        TensorNetwork
            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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> indexed = network.index("i", "j")
        >>> renamed = indexed.rename_indices({"i": "k"})
        >>> renamed.rank
        2
        """
    def permute_axes(self, axes: typing.Sequence[builtins.int]) -> TensorNetwork:
        r"""
        Reorder the external axes in logical component order.

        Parameters
        ----------
        axes : sequence of int
            Each current axis position exactly once, in the desired new order.
            For a matrix, [1, 0] exchanges the two axes.

        Returns
        -------
        TensorNetwork
            A new tensor view with the reordered interface and correspondingly
            reordered component access.

        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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> transposed = network.permute_axes([1, 0])
        >>> transposed.shape
        (2, 2)
        """
    def __copy__(self) -> TensorNetwork:
        r"""
        Implement ``copy.copy`` using an independent TensorNetwork copy.

        Returns
        -------
        TensorNetwork
            Copy of the component data and execution progress.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> import copy
        >>> copied = copy.copy(network)
        """
    def __call__(self, *indices: _IndexInput, intern: typing.Optional[typing.Literal['indices', 'flattened']] = None) -> TensorNetwork:
        r"""
        Assign labels to the unresolved external axes.

        Parameters
        ----------
        *indices : int, str, Expression, Slot, or AUTO
            One label per unresolved axis, in logical order. AUTO leaves the
            corresponding axis unchanged. A Slot must have the matching
            representation. Repeated compatible labels cause contraction.
        intern : {"indices", "flattened"} or None, optional
            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.

        Returns
        -------
        TensorNetwork
            An indexed network retaining the component data; the original is unchanged.

        Notes
        -----
        Equivalent to ``index(*indices)``.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> indexed = network("i", "j")
        >>> indexed.rank
        2
        """
    def __neg__(self) -> TensorNetwork:
        r"""
        Negate every tensor component.

        Returns
        -------
        TensorNetwork
            Negated symbolic algebra retaining component data lazily.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> negated = -network
        """
    def __add__(self, rhs: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> TensorNetwork:
        r"""
        Add tensors with compatible external interfaces.

        Parameters
        ----------
        rhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        Returns
        -------
        TensorNetwork
            New lazy calculation; operands are unchanged.

        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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> result = network + network
        """
    def __radd__(self, rhs: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> TensorNetwork:
        r"""
        Implement reflected addition.

        Parameters
        ----------
        rhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        Returns
        -------
        TensorNetwork
            New lazy calculation; operands are unchanged.

        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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> result = network + network
        """
    def __sub__(self, rhs: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> TensorNetwork:
        r"""
        Subtract tensors with compatible external interfaces.

        Parameters
        ----------
        rhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        Returns
        -------
        TensorNetwork
            New lazy calculation; operands are unchanged.

        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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> result = network - network
        """
    def __rsub__(self, rhs: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> TensorNetwork:
        r"""
        Implement reflected subtraction.

        Parameters
        ----------
        rhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        Returns
        -------
        TensorNetwork
            New lazy calculation; operands are unchanged.

        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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> result = network - network
        """
    def __mul__(self, rhs: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> TensorNetwork:
        r"""
        Multiply tensors, contracting unambiguous compatible axes.

        Parameters
        ----------
        rhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        Returns
        -------
        TensorNetwork
            New lazy calculation; operands are unchanged.

        Notes
        -----
        Matching explicit labels contract. Compatible unresolved axes are
        paired only when the choice is unambiguous. Use outer(), contract_ports(),
        or compose() to make the intended pairing explicit.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> result = network * 2
        """
    def __rmul__(self, rhs: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> TensorNetwork:
        r"""
        Implement reflected multiplication.

        Parameters
        ----------
        rhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        Returns
        -------
        TensorNetwork
            New lazy calculation; operands are unchanged.

        Notes
        -----
        Matching explicit labels contract. Compatible unresolved axes are
        paired only when the choice is unambiguous. Use outer(), contract_ports(),
        or compose() to make the intended pairing explicit.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> result = 2 * network
        """
    def __truediv__(self, rhs: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> TensorNetwork:
        r"""
        Divide tensor components by a scalar expression.

        Parameters
        ----------
        rhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        Returns
        -------
        TensorNetwork
            New lazy calculation; operands are unchanged.

        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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> result = network / 2
        """
    def __rtruediv__(self, lhs: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> TensorNetwork:
        r"""
        Implement reflected division.

        Parameters
        ----------
        lhs : scalar expression, TensorExpression, Tensor, or TensorNetwork
            Other operand. Component data are retained in a lazy network.

        Returns
        -------
        TensorNetwork
            New lazy calculation; operands are unchanged.

        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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> result = 2 / TensorNetwork(3)
        """
    def outer(self, rhs: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> TensorNetwork:
        r"""
        Form an outer product without implicit contractions between the operands.

        Parameters
        ----------
        rhs : TensorExpression, Tensor, or TensorNetwork
            Tensor whose axes follow this tensor's axes.

        Returns
        -------
        TensorNetwork
            A lazy outer product retaining the operands' component data.

        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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> product = network.outer(network)
        >>> product.rank
        4
        """
    def contract_ports(self, rhs: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork], *, left: builtins.int, right: builtins.int) -> TensorNetwork:
        r"""
        Contract one chosen pair of axes between two tensors.

        Parameters
        ----------
        rhs : TensorExpression, Tensor, or TensorNetwork
            Tensor to contract with this tensor.
        left, right : int
            Zero-based axis positions in this tensor and rhs, respectively.
            The representations must be compatible under contraction.

        Returns
        -------
        TensorNetwork
            A lazy contraction retaining component data.

        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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> contracted = network.contract_ports(network, left=1, right=0)
        >>> contracted.rank
        2
        """
    def compose(self, rhs: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork], *, left: tuple[builtins.int, builtins.int], right: tuple[builtins.int, builtins.int]) -> TensorNetwork:
        r"""
        Multiply two tensors along explicitly selected matrix channels.

        Parameters
        ----------
        rhs : TensorExpression, Tensor, or TensorNetwork
            Next factor in the ordered matrix product.
        left, right : tuple of int and 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.

        Returns
        -------
        TensorNetwork
            A lazy ordered matrix product retaining 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 Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> product = network.compose(network, left=(0, 1), right=(0, 1))
        >>> product.rank
        2
        """
    def dot(self, rhs: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> TensorNetwork:
        r"""
        Contract two rank-one tensors using their representation pairing.

        Parameters
        ----------
        rhs : TensorExpression, Tensor, or TensorNetwork
            Rank-one tensor in a compatible space.

        Returns
        -------
        TensorNetwork
            A lazy scalar contraction, including the metric signs of the space.

        Examples
        --------
        >>> from symbolica.community.tensor import TensorName, Tensor, TensorNetwork, Representation
        >>> vector = Tensor.dense(TensorName.vector("dot_v")(Representation.euc(2)), [1.0, 2.0])
        >>> TensorNetwork(vector).dot(vector).to_tensor().scalar() == 5
        True
        """
    def trace(self, *, channel: typing.Optional[tuple[builtins.int, builtins.int]] = None) -> TensorNetwork:
        r"""
        Close a pair of matrix axes on this tensor.

        Parameters
        ----------
        channel : tuple of int and int, optional
            (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.

        Returns
        -------
        TensorNetwork
            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)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> network.trace(channel=(0, 1)).is_scalar
        True
        """
    def copy(self) -> TensorNetwork:
        r"""
        Copy this network and its current execution progress.

        Returns
        -------
        TensorNetwork
            An independent copy. Changes to it do not alter the original.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> copied = network.copy()
        >>> copied.shape == network.shape
        True
        """
    def step(self, library: typing.Optional[TensorLibrary] = None, *, function_library: typing.Optional[TensorFunctionLibrary] = None) -> TensorNetwork:
        r"""
        Run one execution round on a copy of this network.

        Parameters
        ----------
        library : TensorLibrary, optional
            Component definitions. Defaults to the built-in four-dimensional Dirac
            and SU(3) library. Unregistered tensors receive symbolic components.
        function_library : TensorFunctionLibrary, optional
            Numerical implementations of broadcast functions. Defaults to the
            built-in function library.

        Returns
        -------
        TensorNetwork
            Next intermediate computation; this network remains unchanged.

        Notes
        -----
        The round uses ExecutionMode.Single and includes the usual preprocessing;
        it is not a promise to remove exactly one graph node.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> intermediate = network.step()
        >>> intermediate.shape
        (2, 2)
        """
    def to_tensor(self, library: typing.Optional[TensorLibrary] = None, *, function_library: typing.Optional[TensorFunctionLibrary] = None) -> Tensor:
        r"""
        Evaluate an independent copy of this network and return its components.

        Parameters
        ----------
        library : TensorLibrary, optional
            Component definitions. Defaults to the built-in four-dimensional Dirac
            and SU(3) library. Unregistered tensors receive symbolic components.
        function_library : TensorFunctionLibrary, optional
            Numerical implementations of broadcast functions. Defaults to the
            built-in function library.

        Returns
        -------
        Tensor
            Resulting components in logical axis order. Dimensions must be concrete.

        Notes
        -----
        The original network and its execution progress and the supplied libraries are unchanged.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import Tensor
        >>> tensor = Tensor.dense(A, [1.0, 2.0, 3.0, 4.0])
        >>> from symbolica.community.tensor import TensorNetwork
        >>> network = TensorNetwork(tensor)
        >>> network.to_tensor().shape
        (2, 2)
        """

@typing.final
class TensorPattern(Expression):
    r"""
    Representation-aware Symbolica patterns for matching tensor expressions.

    Scalar arguments and structural ports are specified separately. Either
    section can contain Symbolica wildcards, including sequence wildcards.
    Unlike TensorExpression, a pattern does not require a concrete rank or
    compatible external tensor axes. Use patterns with TensorRule for checked
    whole-tensor replacements, or with ordinary Expression matching.

    Examples
    --------
    >>> from symbolica import S
    >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
    >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
    >>> pattern = TensorPattern.dirac_gamma(D_, i_, j_, mu_)
    """
    def __new__(cls, head: TensorName, *, args: typing.Sequence[_ScalarInput] = [], ports: typing.Sequence[Slot | Representation | _ScalarInput] = []) -> TensorPattern:
        r"""
        Match a fixed tensor function with separately specified arguments and ports.

        Parameters
        ----------
        head : TensorName
            Exact tensor function head to match.
        args : sequence of scalar expressions, default []
            Non-index tensor arguments, including ordinary or sequence wildcards.
        ports : sequence of Slot, Representation, or Expression, default []
            Structural port patterns, placed after args. PortPattern and sequence
            wildcards can describe representations, indices, or variable arity.

        Returns
        -------
        TensorPattern
            Pattern expression with args before ports.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> pattern = TensorPattern(TensorName("B"), ports=[PortPattern.exact(Representation.euc(3), i_)])
        """
    @staticmethod
    def any(name: builtins.str, *, args: typing.Sequence[_ScalarInput] = [], ports: typing.Sequence[Slot | Representation | _ScalarInput] = []) -> TensorPattern:
        r"""
        Match any tensor-tagged function.

        Parameters
        ----------
        name : str
            Wildcard function name ending in exactly one underscore.
        args : sequence of scalar expressions, default []
            Non-index tensor arguments, including ordinary or sequence wildcards.
        ports : sequence of Slot, Representation, or Expression, default []
            Structural port patterns, placed after args. PortPattern and sequence
            wildcards can describe representations, indices, or variable arity.

        Returns
        -------
        TensorPattern
            Tagged pattern. Concrete arity is not imposed, so sequence wildcards
            can match the argument and port lists.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> rest = S("ports___")
        >>> pattern = TensorPattern.any("T_", ports=[rest])
        """
    @staticmethod
    def vector(name: builtins.str, *, args: typing.Sequence[_ScalarInput] = [], ports: typing.Sequence[Slot | Representation | _ScalarInput] = []) -> TensorPattern:
        r"""
        Match a function tagged as a rank-one tensor.

        Parameters
        ----------
        name : str
            Wildcard function name ending in exactly one underscore.
        args : sequence of scalar expressions, default []
            Non-index tensor arguments, including ordinary or sequence wildcards.
        ports : sequence of Slot, Representation, or Expression, default []
            Structural port patterns, placed after args. PortPattern and sequence
            wildcards can describe representations, indices, or variable arity.

        Returns
        -------
        TensorPattern
            Tagged pattern. Concrete arity is not imposed, so sequence wildcards
            can match the argument and port lists.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> rest = S("ports___")
        >>> pattern = TensorPattern.vector("V_", ports=[rest])
        """
    @staticmethod
    def dot(left: _ScalarInput, right: _ScalarInput) -> TensorPattern:
        r"""
        Match a compact tensor dot product.

        Parameters
        ----------
        left, right : scalar expression
            Operand patterns, including unrestricted wildcards.

        Returns
        -------
        TensorPattern
            Pattern for the compact dot notation, not explicit indexed products.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> pattern = TensorPattern.dot(S("left_"), S("right_"))
        """
    @staticmethod
    def chain(start: Slot | Representation | _ScalarInput, end: Slot | Representation | _ScalarInput, *factors: _ScalarInput) -> TensorPattern:
        r"""
        Match an ordered tensor chain with endpoints and factor patterns.

        Parameters
        ----------
        start, end : Slot, Representation, or Expression
            Endpoint patterns.
        *factors : scalar expression
            Ordered factor patterns, optionally including sequence wildcards.
            Contextual PortPattern.chain_in() and chain_out() can select a
            factor's orientation.

        Returns
        -------
        TensorPattern
            A chain pattern that does not infer a concrete matrix interface.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> pattern = TensorPattern.chain(i_, j_, S("factors___"))
        """
    @staticmethod
    def trace(representation: Representation | Expression, *factors: _ScalarInput) -> TensorPattern:
        r"""
        Match a compact cyclic trace.

        Parameters
        ----------
        representation : Representation or Expression
            Exact traced space, representation pattern, or wildcard.
        *factors : scalar expression
            Factor patterns, optionally including sequence wildcards.

        Returns
        -------
        TensorPattern
            Trace pattern with the cyclic factor wrapper used by tensor notation.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> pattern = TensorPattern.trace(Representation.euc(3), S("factors___"))
        """
    @staticmethod
    def casimir(degree: _ScalarInput, representation: Representation | Expression) -> TensorPattern:
        r"""
        Match a symbolic Casimir invariant.

        Parameters
        ----------
        degree : scalar expression
            Invariant degree or wildcard.
        representation : Representation or Expression
            Exact representation, representation pattern, or wildcard.

        Returns
        -------
        TensorPattern
            Pattern for a scalar representation invariant.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> pattern = TensorPattern.casimir(S("degree_"), S("rep_"))
        """
    @staticmethod
    def dynkin_index(degree: _ScalarInput, representation: Representation | Expression) -> TensorPattern:
        r"""
        Match a symbolic Dynkin index.

        Parameters
        ----------
        degree : scalar expression
            Invariant degree or wildcard.
        representation : Representation or Expression
            Exact representation, representation pattern, or wildcard.

        Returns
        -------
        TensorPattern
            Pattern for a scalar representation invariant.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> pattern = TensorPattern.dynkin_index(S("degree_"), S("rep_"))
        """
    @staticmethod
    def symmetric(*factors: _ScalarInput) -> TensorPattern:
        r"""
        Match a normalized symmetric group of matrix factors.

        Parameters
        ----------
        *factors : scalar expression
            Patterns for the grouped factors, including sequence wildcards.

        Returns
        -------
        TensorPattern
            Pattern for the compact FactorProjector syntax inside a chain or trace.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> pattern = TensorPattern.symmetric(S("factors___"))
        """
    @staticmethod
    def antisymmetric(*factors: _ScalarInput) -> TensorPattern:
        r"""
        Match a normalized antisymmetric group of matrix factors.

        Parameters
        ----------
        *factors : scalar expression
            Patterns for the grouped factors, including sequence wildcards.

        Returns
        -------
        TensorPattern
            Pattern for the compact FactorProjector syntax inside a chain or trace.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> pattern = TensorPattern.antisymmetric(S("factors___"))
        """
    @staticmethod
    def cyclic(*factors: _ScalarInput) -> TensorPattern:
        r"""
        Match a normalized cyclic group of matrix factors.

        Parameters
        ----------
        *factors : scalar expression
            Patterns for the grouped factors, including sequence wildcards.

        Returns
        -------
        TensorPattern
            Pattern for the compact FactorProjector syntax inside a chain or trace.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> pattern = TensorPattern.cyclic(S("factors___"))
        """
    @staticmethod
    def gamma0(spinor_dimension: _ScalarInput, i: _ScalarInput, j: _ScalarInput) -> TensorPattern:
        r"""
        Match the time-component Dirac matrix gamma^0.

        Parameters
        ----------
        spinor_dimension : scalar expression
            Spinor dimension or wildcard.
        i, j : scalar expression
            Spinor-index patterns or contextual chain endpoints.

        Returns
        -------
        TensorPattern
            Registered tensor syntax with representation-aware port patterns.
            Wildcards are retained rather than checked as a concrete tensor.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> pattern = TensorPattern.gamma0(D_, i_, j_)
        """
    @staticmethod
    def charge_conjugation(spinor_dimension: _ScalarInput, i: _ScalarInput, j: _ScalarInput) -> TensorPattern:
        r"""
        Match the Dirac charge-conjugation matrix.

        Parameters
        ----------
        spinor_dimension : scalar expression
            Spinor dimension or wildcard.
        i, j : scalar expression
            Spinor-index patterns or contextual chain endpoints.

        Returns
        -------
        TensorPattern
            Registered tensor syntax with representation-aware port patterns.
            Wildcards are retained rather than checked as a concrete tensor.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> pattern = TensorPattern.charge_conjugation(D_, i_, j_)
        """
    @staticmethod
    def levi_civita(rep_pattern: Representation | Expression, *indices: _ScalarInput) -> TensorPattern:
        r"""
        Match the totally antisymmetric Levi-Civita tensor.

        Parameters
        ----------
        rep_pattern : Representation or Expression
            Exact space or a representation-only PortPattern.
        *indices : scalar expression
            One index pattern per axis; their number fixes the rank.

        Returns
        -------
        TensorPattern
            Registered tensor syntax with representation-aware port patterns.
            Wildcards are retained rather than checked as a concrete tensor.

        Notes
        -----
        For an unrestricted number of epsilon axes, use
        TensorPattern(TensorName.levi_civita(), ports=[ports___]).

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> pattern = TensorPattern.levi_civita(Representation.euc(D_), i_, j_, a_)
        """
    @staticmethod
    def g(rep_pattern: Representation | Expression, i: _ScalarInput, j: _ScalarInput) -> TensorPattern:
        r"""
        Match the metric pairing.

        Parameters
        ----------
        rep_pattern : Representation or Expression
            Exact space or a representation-only PortPattern.
        i, j : scalar expression
            Index values, wildcards, or contextual chain endpoints.

        Returns
        -------
        TensorPattern
            Registered tensor syntax with representation-aware port patterns.
            Wildcards are retained rather than checked as a concrete tensor.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> pattern = TensorPattern.g(Representation.euc(D_), i_, j_)
        """
    @staticmethod
    def flat(rep_pattern: Representation | Expression, i: _ScalarInput, j: _ScalarInput) -> TensorPattern:
        r"""
        Match the metric map for raising or lowering an index.

        Parameters
        ----------
        rep_pattern : Representation or Expression
            Exact space or a representation-only PortPattern.
        i, j : scalar expression
            Index values, wildcards, or contextual chain endpoints.

        Returns
        -------
        TensorPattern
            Registered tensor syntax with representation-aware port patterns.
            Wildcards are retained rather than checked as a concrete tensor.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> pattern = TensorPattern.flat(Representation.euc(D_), i_, j_)
        """
    @staticmethod
    def dirac_gamma(minkowski_dimension: _ScalarInput, i: _ScalarInput, j: _ScalarInput, mu: _ScalarInput) -> TensorPattern:
        r"""
        Match the Dirac gamma matrices for Clifford algebra.

        Parameters
        ----------
        minkowski_dimension : scalar expression
            Minkowski dimension or wildcard. Spinor dimensions are fixed at four.
        i, j : scalar expression
            Spinor-index patterns or contextual chain endpoints.
        mu : scalar expression
            Lorentz-index pattern.

        Returns
        -------
        TensorPattern
            Registered tensor syntax with representation-aware port patterns.
            Wildcards are retained rather than checked as a concrete tensor.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> pattern = TensorPattern.dirac_gamma(D_, i_, j_, mu_)
        """
    @staticmethod
    def gamma5(spinor_dimension: _ScalarInput, i: _ScalarInput, j: _ScalarInput) -> TensorPattern:
        r"""
        Match the Dirac chirality matrix gamma^5.

        Parameters
        ----------
        spinor_dimension : scalar expression
            Spinor dimension or wildcard.
        i, j : scalar expression
            Spinor-index patterns or contextual chain endpoints.

        Returns
        -------
        TensorPattern
            Registered tensor syntax with representation-aware port patterns.
            Wildcards are retained rather than checked as a concrete tensor.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> pattern = TensorPattern.gamma5(D_, i_, j_)
        """
    @staticmethod
    def projm(spinor_dimension: _ScalarInput, i: _ScalarInput, j: _ScalarInput) -> TensorPattern:
        r"""
        Match the left-chiral Dirac projector (I - gamma^5)/2.

        Parameters
        ----------
        spinor_dimension : scalar expression
            Spinor dimension or wildcard.
        i, j : scalar expression
            Spinor-index patterns or contextual chain endpoints.

        Returns
        -------
        TensorPattern
            Registered tensor syntax with representation-aware port patterns.
            Wildcards are retained rather than checked as a concrete tensor.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> pattern = TensorPattern.projm(D_, i_, j_)
        """
    @staticmethod
    def projp(spinor_dimension: _ScalarInput, i: _ScalarInput, j: _ScalarInput) -> TensorPattern:
        r"""
        Match the right-chiral Dirac projector (I + gamma^5)/2.

        Parameters
        ----------
        spinor_dimension : scalar expression
            Spinor dimension or wildcard.
        i, j : scalar expression
            Spinor-index patterns or contextual chain endpoints.

        Returns
        -------
        TensorPattern
            Registered tensor syntax with representation-aware port patterns.
            Wildcards are retained rather than checked as a concrete tensor.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> pattern = TensorPattern.projp(D_, i_, j_)
        """
    @staticmethod
    def sigma(minkowski_dimension: _ScalarInput, mu: _ScalarInput, nu: _ScalarInput, i: _ScalarInput, j: _ScalarInput) -> TensorPattern:
        r"""
        Match the antisymmetric Dirac sigma tensor.

        Parameters
        ----------
        minkowski_dimension : scalar expression
            Minkowski dimension or wildcard. Spinor dimensions are fixed at four.
        i, j : scalar expression
            Spinor-index patterns or contextual chain endpoints.
        mu, nu : scalar expression
            Lorentz-index patterns.

        Returns
        -------
        TensorPattern
            Registered tensor syntax with representation-aware port patterns.
            Wildcards are retained rather than checked as a concrete tensor.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> pattern = TensorPattern.sigma(D_, mu_, nu_, i_, j_)
        """
    @staticmethod
    def color_f(adjoint_dimension: _ScalarInput, a: _ScalarInput, b: _ScalarInput, c: _ScalarInput) -> TensorPattern:
        r"""
        Match the antisymmetric color structure constants f^{abc}.

        Parameters
        ----------
        adjoint_dimension : scalar expression
            Adjoint dimension or wildcard, e.g. 8 for SU(3).
        a, b, c : scalar expression
            Patterns for the three adjoint indices.

        Returns
        -------
        TensorPattern
            Registered tensor syntax with representation-aware port patterns.
            Wildcards are retained rather than checked as a concrete tensor.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> pattern = TensorPattern.color_f(D_, a_, b_, c_)
        """
    @staticmethod
    def color_t(adjoint_dimension: _ScalarInput, fundamental_dimension: _ScalarInput, a: _ScalarInput, i: _ScalarInput, j: _ScalarInput) -> TensorPattern:
        r"""
        Match the fundamental color generators T^a.

        Parameters
        ----------
        adjoint_dimension : scalar expression
            Adjoint dimension or wildcard, e.g. 8 for SU(3).
        fundamental_dimension : scalar expression
            Fundamental dimension or wildcard, e.g. 3 for SU(3).
        a : scalar expression
            Adjoint-index pattern.
        i, j : scalar expression
            Fundamental and antifundamental index patterns, or contextual endpoints.

        Returns
        -------
        TensorPattern
            Registered tensor syntax with representation-aware port patterns.
            Wildcards are retained rather than checked as a concrete tensor.

        Examples
        --------
        >>> from symbolica import S
        >>> from symbolica.community.tensor import TensorPattern, PortPattern, Representation, TensorName
        >>> D_, i_, j_, mu_, nu_, a_, b_, c_ = S("D_", "i_", "j_", "mu_", "nu_", "a_", "b_", "c_")
        >>> pattern = TensorPattern.color_t(D_, S("N_"), a_, i_, j_)
        """

@typing.final
class TensorRule:
    r"""
    A reusable replacement rule that preserves tensor interfaces.

    Use with TensorExpression.replace.
    A replacement must preserve the matched tensor's external indices, including
    their representations. Literal replacements are checked where possible at
    construction; wildcard-dependent replacements are checked when matched.

    Examples
    --------
    >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
    >>> space = Representation.euc(2)
    >>> A = TensorName("M")(space, space)
    >>> from symbolica.community.tensor import TensorRule
    >>> indexed = A("i", "j")
    >>> rule = TensorRule(indexed, 2 * indexed)
    >>> indexed.replace(rule).rank
    2
    """
    def __repr__(self) -> builtins.str:
        r"""
        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)
        >>> rule = sp.TensorRule(A("i", "j"), 2 * A("i", "j"))
        >>> text = repr(rule)
        """
    def __new__(cls, pattern: TensorExpression | _ScalarInput | HeldExpression, rhs: TensorExpression | _ScalarInput | HeldExpression | typing.Callable[[dict[Expression, Expression]], TensorExpression | _ScalarInput], *, cond: typing.Optional[PatternRestriction | Condition] = None, rhs_cache_size: builtins.int = 100) -> TensorRule:
        r"""
        Construct a checked whole-tensor replacement rule.

        Parameters
        ----------
        pattern : TensorExpression, scalar expression, or HeldExpression
            Tensor to match. TensorPattern can describe wildcard tensor syntax.
        rhs : TensorExpression, scalar expression, HeldExpression, or callable
            Replacement with the same external interface. A callable receives
            a dict from wildcard Expressions to matched Expressions and returns
            the replacement. Zero retains the matched tensor's interface.
        cond : PatternRestriction or Condition, optional
            Condition evaluated for each candidate match.
        rhs_cache_size : int, default 100
            Maximum number of cached replacement results per application. Use
            zero for a callback whose side effects must run at every match.

        Returns
        -------
        TensorRule
            Reusable replacement, without applying it yet.

        Notes
        -----
        Right-hand-side wildcards must be bound by the pattern. Index multiplicity
        and external representations must remain valid after substitution.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> from symbolica.community.tensor import TensorRule
        >>> indexed = A("i", "j")
        >>> rule = TensorRule(indexed, 2 * indexed)
        >>> result = indexed.replace(rule)
        """

@typing.final
class TensorStructure:
    r"""
    The canonical external signature of an opaque tensor.

    A Slot denotes a labeled axis; a Representation denotes an unresolved axis.
    This immutable signature contains only free axes: no tensor name, scalar
    arguments, expression, component data, or layout permutation. Axes follow
    Spenso's canonical representation/index ordering. A(i,j), A(j,i), and their
    sum have the same structure. The expression retains argument order; tensor
    and network component views retain their own axis order.

    Examples
    --------
    >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
    >>> space = Representation.euc(3)
    >>> A = TensorName("A")(space, space)
    >>> metadata = A.structure
    >>> metadata.rank
    2
    """
    @property
    def axes(self) -> tuple[Slot | Representation, ...]:
        r"""
        Free axes in canonical representation/index order.

        The signature is independent of argument order, factor order, and summand
        order. It describes the whole expression as an opaque tensor. Component
        coordinates belong to the tensor's current view, not to this signature.

        Returns
        -------
        tuple of Slot or Representation
            Labeled and unresolved axes, respectively.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(3)
        >>> A = TensorName("A")(space, space)
        >>> A.structure.axes == (space, space)
        True
        """
    @property
    def rank(self) -> builtins.int:
        r"""
        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 = A.structure
        >>> A.rank
        2
        """
    @property
    def shape(self) -> tuple[int | Expression, ...]:
        r"""
        Dimensions in canonical signature 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 = A.structure
        >>> A.shape
        (3, 3)
        """
    @property
    def is_scalar(self) -> builtins.bool:
        r"""
        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 = A.structure
        >>> A.is_scalar
        False
        """
    def __eq__(self, other: builtins.object) -> builtins.bool: ...
    def __new__(cls, slots: typing.Sequence[Slot | Representation]) -> TensorStructure:
        r"""
        Describe an opaque tensor by its canonical free axes.

        Parameters
        ----------
        slots : sequence of Slot or Representation
            Free axes, sorted into canonical order. Repeated unresolved spaces
            remain distinct axes. This describes a signature without contracting it.

        Returns
        -------
        TensorStructure
            Canonical signature, independent of the supplied sequence order.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorStructure
        >>> metadata = TensorStructure([Representation.euc(2), Representation.euc(3)])
        >>> metadata.shape
        (2, 3)
        """
    def slots(self) -> builtins.list[Slot]:
        r"""
        Return every external axis as an explicitly indexed slot.

        Returns
        -------
        list of Slot
            Slots in canonical order; an empty list for a scalar. Representations
            and dimensions may differ between axes.

        Raises
        ------
        ValueError
            If any axis is unresolved. No indices are invented or axes omitted.
            Use ``axes`` to inspect a mixed structure.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorStructure
        >>> space = Representation.euc(3)
        >>> metadata = TensorStructure([space("j"), space("i")])
        >>> metadata.slots() == TensorStructure([space("i"), space("j")]).slots()
        True
        """
    def representations(self) -> builtins.list[Representation]:
        r"""
        Return every external axis as an unresolved representation.

        Returns
        -------
        list of Representation
            Representations in canonical order; an empty list for a scalar.
            Different spaces, dimensions, and dualities are allowed.

        Raises
        ------
        ValueError
            If any axis has an explicit index. Labels are never discarded.
            Use ``axes`` to inspect a mixed structure.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorStructure
        >>> spaces = [Representation.mink(4), Representation.euc(3)]
        >>> TensorStructure(spaces) == TensorStructure(spaces[::-1])
        True
        """
    def __repr__(self) -> builtins.str:
        r"""
        Return a readable object description for inspection.

        Examples
        --------
        >>> from symbolica.community import tensor as sp
        >>> r = sp.Representation.euc(2)
        >>> structure = sp.TensorStructure([r("i"), r("j")])
        >>> text = repr(structure)
        """
    def to_html(self, *, settings: typing.Optional[DisplaySettings] = None) -> builtins.str:
        r"""
        Render a compact HTML view of this tensor metadata.

        Parameters
        ----------
        settings : DisplaySettings, optional
            Index and tensor presentation choices; defaults to DisplaySettings().

        Returns
        -------
        str
            HTML fragment for display in a notebook or page.

        Examples
        --------
        >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
        >>> space = Representation.euc(2)
        >>> A = TensorName("M")(space, space)
        >>> value = A.structure
        >>> html = value.to_html()
        """
    def _repr_html_(self) -> builtins.str: ...

@typing.final
class _AutoIndex:
    r"""
    Sentinel type for an unresolved tensor axis.

    Use the exported singleton ``AUTO`` (also available as ``_``), rather than
    constructing this type. During index() or reindex(), AUTO leaves that axis
    unchanged. It is not a wildcard and not a component coordinate.
    Unresolved axes display as hollow squares. When several axes of a tensor
    are unresolved, their squares carry zero-based axis numbers, excluding
    scalar parameters. These local numbers do not imply contractions. Hover
    over a square in HTML output to see its axis and representation.

    Examples
    --------
    >>> from symbolica.community.tensor import Representation, TensorName, TensorExpression
    >>> space = Representation.euc(2)
    >>> A = TensorName("M")(space, space)
    >>> from symbolica.community.tensor import AUTO
    >>> partly_indexed = A(AUTO, "j")
    >>> partly_indexed.rank
    2
    """
    ...

def Nc() -> Expression:
    r"""
    Return 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({})
    3
    """

def as_tensor(expression: typing.Any) -> TensorExpression:
    r"""
    Convert 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
    -------
    TensorExpression
        Tensor-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
    True
    """

@typing.overload
def chain(start_slot: Slot, end_slot: Slot, *factors: TensorExpression | Expression | FactorProjector[TensorExpression]) -> TensorExpression:
    r"""
    Compose 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 TensorNetwork
        A 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
    2
    """

@typing.overload
def chain(start_slot: Slot, end_slot: Slot, factor: Tensor | TensorNetwork | FactorProjector[TensorNetwork], /, *factors: TensorExpression | _ScalarInput | Tensor | TensorNetwork | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> TensorNetwork:
    r"""
    Compose 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 TensorNetwork
        A 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
    2
    """

@typing.overload
def 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:
    r"""
    Compose 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 TensorNetwork
        A 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
    2
    """

@typing.overload
def chain(start_slot: Slot, end_slot: Slot, *factors: TensorExpression | _ScalarInput | Tensor | TensorNetwork | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> TensorExpression | TensorNetwork:
    r"""
    Compose 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 TensorNetwork
        A 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
    2
    """

@typing.overload
def dot(left: TensorExpression | Expression, right: TensorExpression | Expression) -> TensorExpression:
    r"""
    Contract 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 TensorNetwork
        Symbolic 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
    True
    """

@typing.overload
def dot(left: typing.Union[Tensor, TensorNetwork], right: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> TensorNetwork:
    r"""
    Contract 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 TensorNetwork
        Symbolic 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
    True
    """

@typing.overload
def dot(left: _ScalarInput | TensorExpression | TensorNetwork | Tensor | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork], right: typing.Union[Tensor, TensorNetwork]) -> TensorNetwork:
    r"""
    Contract 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 TensorNetwork
        Symbolic 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
    True
    """

def format_tensor(expression: Expression, show_dimensions: typing.Optional[builtins.bool] = None, *, settings: typing.Optional[DisplaySettings] = None) -> builtins.str:
    r"""
    Produce 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
    -------
    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 import S
    >>> expression = S("x") + 1
    >>> from symbolica.community.tensor import format_tensor
    >>> output = format_tensor(expression)
    """

def formatted(expression: Expression, show_dimensions: typing.Optional[builtins.bool] = None, *, settings: typing.Optional[DisplaySettings] = None, notation_source: typing.Optional[builtins.str] = None) -> FormattedOutput:
    r"""
    Create 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
    -------
    FormattedOutput
        Each 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)
    """

def load_math_font() -> builtins.str:
    r"""
    Embed the bundled math font in an HTML notebook or document.

    Returns
    -------
    str
        A 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>")
    True
    """

def set_symbolica_rayon_enabled(policy: SymbolicParallelism) -> builtins.bool:
    r"""
    Set 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
    -------
    bool
        Whether 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)
    """

def to_html(expression: Expression, show_dimensions: typing.Optional[builtins.bool] = None, *, settings: typing.Optional[DisplaySettings] = None, notation_source: typing.Optional[builtins.str] = None) -> builtins.str:
    r"""
    Render 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
    -------
    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 import S
    >>> expression = S("x") + 1
    >>> from symbolica.community.tensor import to_html
    >>> output = to_html(expression)
    """

def to_svg(expression: Expression, show_dimensions: typing.Optional[builtins.bool] = None, *, settings: typing.Optional[DisplaySettings] = None, notation_source: typing.Optional[builtins.str] = None) -> builtins.str:
    r"""
    Render 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
    -------
    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 import S
    >>> expression = S("x") + 1
    >>> from symbolica.community.tensor import to_svg
    >>> output = to_svg(expression)
    """

def to_typst(expression: Expression, show_dimensions: typing.Optional[builtins.bool] = None, *, settings: typing.Optional[DisplaySettings] = None) -> builtins.str:
    r"""
    Produce 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
    -------
    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 import S
    >>> expression = S("x") + 1
    >>> from symbolica.community.tensor import to_typst
    >>> output = to_typst(expression)
    """

def to_typst_project(expression: Expression, show_dimensions: typing.Optional[builtins.bool] = None, *, settings: typing.Optional[DisplaySettings] = None, notation_source: typing.Optional[builtins.str] = None) -> dict:
    r"""
    Export 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)
    """

@typing.overload
def trace(representation: Representation, *factors: TensorExpression | Expression | FactorProjector[TensorExpression]) -> TensorExpression:
    r"""
    Close 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 TensorNetwork
        Symbolic 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
    True
    """

@typing.overload
def trace(representation: Representation, factor: Tensor | TensorNetwork | FactorProjector[TensorNetwork], /, *factors: TensorExpression | _ScalarInput | Tensor | TensorNetwork | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> TensorNetwork:
    r"""
    Close 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 TensorNetwork
        Symbolic 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
    True
    """

@typing.overload
def 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:
    r"""
    Close 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 TensorNetwork
        Symbolic 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
    True
    """

@typing.overload
def trace(representation: Representation, *factors: TensorExpression | _ScalarInput | Tensor | TensorNetwork | FactorProjector[TensorExpression] | FactorProjector[TensorNetwork]) -> TensorExpression | TensorNetwork:
    r"""
    Close 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 TensorNetwork
        Symbolic 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
    True
    """
