Advanced API reference
This page documents the stability-sensitive implementation types that may appear as return values or be needed for specialized workflows. Ordinary user code should prefer the factories, operator compile() methods, and circuit facades documented on the public API reference. Advanced names are public but their signatures and internal-buffer contracts may evolve under API review.
The tencirpauli._native module is private and is not an alternative import path. Advanced plans and engines are factory-created unless their docstring explicitly documents a safe constructor. Arrays owned by plans or engines are generally immutable; arrays returned by apply() and execution terminals follow the ownership and mutability contract stated in their method documentation.
The ordinary circuit facades no longer expose public compile() methods or circuit-plan classes. GateTape, PropagationEngine, and SPPSEngine remain advanced numerical APIs; their explicit parameter slots are low-level runtime buffers and are not the removed symbolic Parameter/ParameterExpr interface.
advanced
Advanced and stability-sensitive TenCirPauli implementation types.
The names in this module are valid public return types, but ordinary user code
should prefer the facade and factory APIs exported from :mod:tencirpauli.
__all__ = ['BackendMVPPlan', 'CanonicalizationArrayResult', 'ChargeLazyMvpPlan', 'ChargeMvpPlan', 'ChargeRestrictedOperator', 'GateTape', 'NativeMVPPlan', 'OperatorBuilder', 'PropagationEngine', 'SPPSEngine', 'U1MvpPlan', 'U1RestrictedOperator', 'Z2TaperingPlan']
module-attribute
ChargeLazyMvpPlan
Bases: _NativeMvpFacade
Explicitly lazy native MVP plan for a finite charge sector.
Unlike :class:ChargeMvpPlan, this plan does not retain the complete
restricted transition graph. The native implementation enumerates source
basis states and aggregates destinations for one source column at a time.
Dense and sparse materialization are intentionally unavailable for this
storage strategy.
ChargeMvpPlan
Bases: _NativeMvpFacade
Reusable matrix-free transition plan in a finite charge-sector basis.
The native handle owns validated destination-major CSR storage and can apply the same restricted operator to many state vectors without materializing a dense matrix. Public COO row indices are derived only when requested.
indptr: np.ndarray[Any, Any]
property
Return a read-only CSR pointer array generated from the native handle.
columns: np.ndarray[Any, Any]
property
Return read-only CSR column indices generated from the native handle.
coefficients: np.ndarray[Any, Any]
property
Return read-only CSR values generated from the native handle.
rows: np.ndarray[Any, Any]
property
Return read-only COO row indices generated from the native handle.
ChargeRestrictedOperator
Exact action of a conserved structured or Pauli operator in one sector.
Construction validates exact charge conservation and retains a compact
lazy plan. Explicit sparse/dense materialization or an eager MVP request
installs one immutable transition-graph cache on this mathematical facade.
The result is a numerical operator on the selected occupation basis, not a
new FermionOperator or PauliOperator. Apply fermion-to-qubit
mapping, Pauli algebra, or Pauli Z2 tapering to the source operator
before restriction; a ChargeRestrictedOperator does not define a
Jordan--Wigner map for its generally non-power-of-two sector dimension.
estimated_bytes: int
property
Return the current best-effort retained-byte estimate.
apply(state: Sequence[complex], *, max_bytes: Optional[int] = DEFAULT_MAX_BYTES) -> np.ndarray[Any, Any]
Apply the restricted operator to one sector-state vector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
Sequence[complex]
|
Complex vector with shape |
required |
max_bytes
|
Optional[int]
|
Best-effort bound for the output allocation. |
DEFAULT_MAX_BYTES
|
Returns:
| Type | Description |
|---|---|
ndarray[Any, Any]
|
A new |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
apply_into(input_state: np.ndarray[Any, Any], output_state: np.ndarray[Any, Any], *, max_bytes: Optional[int] = DEFAULT_MAX_BYTES) -> None
Apply into strict caller-owned buffers using the retained strategy.
mvp_plan(*, storage: ChargeStorage = 'lazy', max_bytes: Optional[int] = DEFAULT_MAX_BYTES) -> Union[ChargeMvpPlan, ChargeLazyMvpPlan]
Return the reusable MVP plan for this restricted operator.
The returned plan is immutable and its storage estimate is checked
against max_bytes before returning. Eager plans retain all
transitions; lazy plans retain only the sector plan and term metadata.
dense(*, max_bytes: Optional[int] = DEFAULT_MAX_BYTES) -> np.ndarray[Any, Any]
Materialize the restricted operator as a bounded dense matrix.
The matrix has shape (dimension, dimension) and follows sector
ordering. Use :meth:mvp_plan or :meth:apply when dense materialization
is not required.
coo(*, max_bytes: Optional[int] = DEFAULT_MAX_BYTES) -> COOMatrix
Materialize deterministic duplicate-aggregated COO arrays.
The returned :class:COOMatrix uses restricted-sector row and column
indices and can be converted to SciPy with to_scipy().
csr(*, max_bytes: Optional[int] = DEFAULT_MAX_BYTES) -> CSRMatrix
Materialize deterministic CSR arrays in sector ordering.
indptr, indices and data are returned in the public
:class:CSRMatrix container. The operation allocates only the CSR
arrays and is guarded by max_bytes.
compile(target: str, *, storage: ChargeStorage = 'lazy', max_bytes: Optional[int] = DEFAULT_MAX_BYTES) -> Union[np.ndarray[Any, Any], COOMatrix, CSRMatrix, ChargeMvpPlan, ChargeLazyMvpPlan]
Compile one supported restricted-operator target.
Restricted operators support dense/COO/CSR materialization and native MVP plans. Backend MVP is intentionally unavailable for this family.
BackendMVPPlan
dataclass
Versioned pure-array MVP plan with an independent NumPy executor.
Pauli plans contain packed X/Z words; direct-Weyl plans contain modular exponent arrays and advertise the factorized backend operations they use.
dimension: int
property
Return the finite basis dimension represented by this plan.
term_count: int
property
Return the number of canonical terms stored in this plan.
apply(state: Sequence[complex], *, max_bytes: Optional[int] = DEFAULT_MAX_BYTES) -> np.ndarray[Any, Any]
Apply the plan using deterministic array operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
Sequence[complex]
|
A flat |
required |
max_bytes
|
Optional[int]
|
Best-effort bound for temporary and output arrays. |
DEFAULT_MAX_BYTES
|
Returns:
| Type | Description |
|---|---|
ndarray[Any, Any]
|
An owned, C-contiguous, writable |
ndarray[Any, Any]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the state shape is incompatible with the plan. |
MemoryError
|
If the estimated workspace exceeds |
NativeMVPPlan
dataclass
Bases: _NativeMvpFacade
Reusable Rust-native matrix-free MVP plan.
The immutable metadata fields describe the target schema, canonical term counts, mapping, finite cutoffs, and local Weyl convention when relevant.
csr(*, max_bytes: Optional[int] = DEFAULT_MAX_BYTES) -> CSRMatrix
Read back CSR from a retained eager Structured graph.
Only eager plans backed by a retained CSR graph support this method; Pauli compact plans and lazy plans must be materialized through their owning operator facade instead.
CanonicalizationArrayResult
dataclass
Contiguous canonicalization arrays for large backend-facing batches.
GateTape
Mutable typed builder for a Schrödinger-order gate tape.
Wires are zero-based and gates execute in append order. Rotation angles are
in radians; a rotation accepts either a static angle or a non-negative
runtime parameter slot. The tape is consumed by
:class:PropagationEngine and :class:SPPSEngine.
nparameters: int
property
Return one plus the largest runtime parameter slot, or zero.
x(wire: int) -> None
Append an X gate on wire.
y(wire: int) -> None
Append a Y gate on wire.
z(wire: int) -> None
Append a Z gate on wire.
h(wire: int) -> None
Append a Hadamard gate on wire.
s(wire: int) -> None
Append an S gate on wire.
sdg(wire: int) -> None
Append an inverse-S gate on wire.
cnot(control: int, target: int) -> None
Append a directed CNOT from control to target.
cz(wire0: int, wire1: int) -> None
Append a controlled-Z gate on two distinct wires.
swap(wire0: int, wire1: int) -> None
Append a SWAP gate on two distinct wires.
rx(wire: int, *, angle: Optional[float] = None, parameter: Optional[int] = None) -> None
Append an X rotation with a static angle or runtime slot.
Exactly one of angle and parameter must be provided. Angles
are measured in radians.
ry(wire: int, *, angle: Optional[float] = None, parameter: Optional[int] = None) -> None
Append a Y rotation with a static angle or runtime slot.
Exactly one of angle and parameter must be provided. Angles
are measured in radians.
rz(wire: int, *, angle: Optional[float] = None, parameter: Optional[int] = None) -> None
Append a Z rotation with a static angle or runtime slot.
Exactly one of angle and parameter must be provided. Angles
are measured in radians.
rxx(wire0: int, wire1: int, *, angle: Optional[float] = None, parameter: Optional[int] = None) -> None
Append a two-qubit X-X rotation with a static angle or runtime slot.
ryy(wire0: int, wire1: int, *, angle: Optional[float] = None, parameter: Optional[int] = None) -> None
Append a two-qubit Y-Y rotation with a static angle or runtime slot.
rzz(wire0: int, wire1: int, *, angle: Optional[float] = None, parameter: Optional[int] = None) -> None
Append a two-qubit Z-Z rotation with a static angle or runtime slot.
ptm(wires: Sequence[int], matrix: np.ndarray[Any, Any], *, name: Optional[str] = None) -> None
Append a real one- or two-qubit Pauli-transfer matrix.
matrix must be a finite float64 array with shape (4, 4) for
one wire or (16, 16) for two wires. The matrix is copied into the
tape, so later mutation of the input does not change the circuit.
depolarizing(wire: int, *, px: Optional[float] = None, py: Optional[float] = None, pz: Optional[float] = None, px_parameter: Optional[int] = None, py_parameter: Optional[int] = None, pz_parameter: Optional[int] = None) -> None
Append TensorCircuit's Pauli-mixture depolarizing channel.
phasedamping(wire: int, *, gamma: Optional[float] = None, gamma_parameter: Optional[int] = None) -> None
Append TensorCircuit-compatible phase damping.
amplitudedamping(wire: int, *, gamma: Optional[float] = None, p: Optional[float] = None, gamma_parameter: Optional[int] = None, p_parameter: Optional[int] = None) -> None
Append TensorCircuit's generalized amplitude damping channel.
PropagationEngine
Reusable Rust-native Heisenberg propagation handle.
The engine propagates a Pauli observable backwards through a fixed gate tape and evaluates it on the selected product initial state. It supports exact dynamic operators and optional Pauli-weight projection; projection is applied after equal Pauli words have been aggregated.
expectation(parameters: Sequence[float] | np.ndarray[Any, Any]) -> float
Return the scalar expectation for a Hermitian observable.
parameters must contain exactly nparameters finite values. The
result is real because the observable is required to be Hermitian.
value_and_grad(parameters: Sequence[float] | np.ndarray[Any, Any], *, checkpoint_interval: Optional[int] = None) -> PropagationValueAndGradient
Return the value and analytic reverse on the executed sparse trace.
Support decisions, exact-zero branches and finite Pauli-weight
projection are frozen to this forward execution. The returned array
is a read-only contiguous float64 vector. The observable must be
Hermitian.
propagate_operator(parameters: Sequence[float] | np.ndarray[Any, Any]) -> PauliOperator
Materialize the canonical propagated Pauli operator.
This exposes the final aggregated operator on the same exact or
weight-projected path used by the engine. It may require substantially
more memory than :meth:expectation.
profile(parameters: Sequence[float] | np.ndarray[Any, Any]) -> ProfiledExpectation
Return an expectation together with propagation diagnostics.
The profile reports gate count, initial/final/peak term counts, a best-effort peak-byte estimate, final weight counts, and kernel time.
SPPSEngine
Reusable Rust-native stochastic Pauli-path estimation handle.
Fixed-budget estimates use independent replicates and report a standard error for the sampled path distribution. Adaptive estimates add samples in cumulative rounds until the requested gradient error proxy is reached or the maximum budget is exhausted.
expectation(parameters: Sequence[float] | np.ndarray[Any, Any], *, samples_per_term: int, seed: int) -> SPPSValueEstimate
Estimate the expectation value without computing a gradient.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
Sequence[float] | ndarray[Any, Any]
|
Finite runtime values for all circuit parameter slots. |
required |
samples_per_term
|
int
|
Fixed path budget per observable term; must be at least two. |
required |
seed
|
int
|
Non-negative unsigned 64-bit random seed. |
required |
Returns:
| Type | Description |
|---|---|
SPPSValueEstimate
|
A value estimate containing the standard error, replicate budgets, |
SPPSValueEstimate
|
total sampled paths, and effective seed. |
value_and_grad(parameters: Sequence[float] | np.ndarray[Any, Any], *, samples_per_term: int, seed: int) -> SPPSEstimate
Estimate the value and all parameter gradients with one fixed budget.
The returned gradient is a read-only float64 vector indexed by runtime parameter slot. The estimate also includes a value standard error and a gradient error proxy when the native estimator provides one.
value_and_grad_adaptive(parameters: Sequence[float] | np.ndarray[Any, Any], *, initial_samples_per_term: int, max_samples_per_term: int, gradient_tolerance: float, seed: int) -> SPPSEstimate
Estimate value and gradients with an adaptive sample budget.
Sampling starts at initial_samples_per_term and grows up to
max_samples_per_term until gradient_tolerance is met. The
returned converged flag distinguishes tolerance convergence from
exhaustion of the maximum budget.
OperatorBuilder
Single-owner batched structured-term builder.
Add raw products incrementally, then call :meth:finish once to perform
native canonicalization and duplicate aggregation in one coarse-grained
operation.
add_product(coefficient: complex = 1.0, *, fermions: Sequence[Tuple[int, str]] = (), bosons: Sequence[Tuple[int, str]] = (), qubits: Sequence[Tuple[int, object]] = (), qudits: Sequence[Tuple[int, int, int]] = ()) -> 'OperatorBuilder'
Append one raw hybrid product to the construction buffer.
The builder accepts sparse factors for each domain and returns itself
so products can be chained. Validation and canonicalization occur in
:meth:finish.
finish(*, max_bytes: Optional[int] = DEFAULT_MAX_BYTES) -> HybridOperator
Canonicalize all buffered products in one native batch call.
Returns a deterministic :class:HybridOperator; repeated equal
products are aggregated and exact zeros are removed.
U1MvpPlan
dataclass
Bases: _NativeMvpFacade
Reusable matrix-free plan over a fixed-particle-number basis.
U1RestrictedOperator
dataclass
A validated Pauli operator restricted to one U(1) sector.
apply(state: Sequence[complex], *, max_bytes: Optional[int] = DEFAULT_MAX_BYTES) -> np.ndarray[Any, Any]
Apply the restricted operator without allocating a full-space state.
apply_into(input_state: np.ndarray[Any, Any], output_state: np.ndarray[Any, Any], *, max_bytes: Optional[int] = DEFAULT_MAX_BYTES) -> None
Apply into strict, non-overlapping caller-owned buffers.
mvp_plan(*, storage: U1Storage = 'lazy', max_bytes: Optional[int] = DEFAULT_MAX_BYTES) -> 'U1MvpPlan'
Build a fixed reusable restricted matrix-free plan.
dense(*, max_bytes: Optional[int] = DEFAULT_MAX_BYTES) -> np.ndarray[Any, Any]
Materialize the bounded dense matrix in restricted-space ordering.
coo(*, max_bytes: Optional[int] = DEFAULT_MAX_BYTES) -> COOMatrix
Materialize deterministic COO arrays in restricted-space ordering.
csr(*, max_bytes: Optional[int] = DEFAULT_MAX_BYTES) -> CSRMatrix
Materialize bounded CSR arrays in restricted-space ordering.
compile(target: str, *, storage: U1Storage = 'lazy', max_bytes: Optional[int] = DEFAULT_MAX_BYTES) -> Union[np.ndarray[Any, Any], COOMatrix, CSRMatrix, 'U1MvpPlan']
Compile one supported U(1)-restricted target.
U(1) restrictions expose dense/COO/CSR materialization and native MVP plans; backend MVP is not a supported representation for this family.
Z2TaperingPlan
dataclass
Reusable Clifford transform and selected Pauli Z2 sector.
transform_operator applies this same transform to compatible Pauli
Hamiltonians or observables. The plan is intentionally Pauli-specific:
it does not automatically transform an :class:AdditiveCharge, combine
with a ChargeSector, or implement occupation-parity restriction.
Such a composition requires checking that both constraints act within the
same selected subspace and is not implied by having the same word
Z2 in their names.
transform_operator(operator: PauliOperator) -> PauliOperator
Transform a compatible operator and substitute the selected sector.