Python API Reference
The object surface (PauliLCU, Walk, QSVT, Trotter, …)
is re-exported from the package root
(cudaq_algorithms.PauliLCU); the composable device kernels stay in their
module namespaces. Symbols are documented below at their defining module.
Block encodings
- class cudaq_algorithms.pauli_lcu.PauliLCU(hamiltonian, num_qubits=None, *, include_identity=True, coefficient_threshold=1e-12, backend='exact', mu=None)
Bases:
objectBlock encoding of H / alpha via a linear combination of Pauli strings.
Two backends build the same
PREPARE-dagger . SELECT . PREPAREencoding.backend="exact"(the default) is an exact multiplexed-Ry amplitude PREPARE with an address-indexed controlled-Pauli SELECT onmax(1, ceil(log2(num_terms)))ancillas; single-term (and identity-only) Hamiltonians get one idle ancilla, so every encoding works uniformly withWalk/QSVTand no flattened kernel argument is ever empty.backend="alias"delegates toLCUBlockEncoding: the alias-sampled PREPARE and unary-iteration (QROM) SELECT primitives, with each Pauli word as a SELECT body and a("sign",)op carrying a negative coefficient. That replaces the rotations with Toffoli-style gates at the cost of extra ancillas (index + alias garbage + SELECT work:3 m + 2 mu + 3qubits formindex bits) and a rounding of the term weights tomubits (withinalpha * discretization_boundeach;alphastays the exact one-norm). Both backends serve every consumer, includingWalk.momentodd orders throughselect_observable; on the alias backend the even orders’ reflection observable has2^num_ancillaterms, practical only at smallmu.- Parameters:
hamiltonian (HamiltonianLike) – A
cudaq.SpinOperator, a mapping{"XZI...": coefficient}, or an iterable of(coefficient, word)pairs. Words use one I/X/Y/Z character per qubit, position = qubit index.num_qubits (int | None) – Optional; inferred from the input when omitted, validated against it when given.
include_identity (bool) – Whether identity words are retained inside the encoded operator (their sum is always reported as
constant_term).coefficient_threshold (float) – Terms with
|coefficient|below this are dropped.backend (str) –
"exact"(default) or"alias"; see above.mu (int | None) – Alias-table keep precision in bits (
>= 1, default 8) forbackend="alias"; not accepted with"exact", which has no alias table.
- property kernel_args: tuple[list[float], list[int], list[int], list[int], list[int]]
(angles, term_controls, term_ops, term_lengths, term_signs).
Escape hatch for composing the module-level kernels inside your own
@cudaq.kernel; the factory methods below capture these for you. Returns defensive copies. Available for the exact backend only (the alias backend has no such flattened arrays).
- encode_kernel(state_prep=None)
A kernel applying the full block encoding.
Without
state_prep: a@cudaq.kernel(state)allocating the system register fromstateand the ancilla register (in|0...0>) after it. Withstate_prep(a(qubits: qview)kernel): a zero-argument kernel that allocates the system register in|0...0>, runsstate_prepon it, then applies the encoding.- Parameters:
state_prep (Kernel | None)
- Return type:
Kernel
- walk_kernel(power=1, state_prep=None)
A kernel running PREPARE, walk^power, UNPREPARE.
The all-zero-ancilla block of the result is T_power(-H/alpha) applied to the input state (Chebyshev polynomial of the walk block -H/alpha). Input modes as in
encode_kernel: acudaq.State-taking kernel, or a zero-argument kernel whenstate_prepis given.- Parameters:
power (int)
state_prep (Kernel | None)
- Return type:
Kernel
- prepare_kernel()
(ancilla: qview): PREPARE with this encoding’s angles.- Return type:
Kernel
- unprepare_kernel()
(ancilla: qview): PREPARE dagger with this encoding’s angles.- Return type:
Kernel
- apply_kernel()
(ancilla, system): the full block encoding U_A.- Return type:
Kernel
- controlled_apply_kernel()
(control_and_ancilla, system): U_A controlled by qubit 0.Uncontrolled PREPARE pairs wrap the controlled SELECT, so the circuit is the identity at control
|0>.- Return type:
Kernel
- walk_step_kernel()
(ancilla, system): one qubitization walk step W.- Return type:
Kernel
- adjoint_walk_step_kernel()
(ancilla, system): one adjoint walk step W†.- Return type:
Kernel
- controlled_walk_step_kernel()
(control_and_ancilla, system): controlled walk step.- Return type:
Kernel
- controlled_adjoint_walk_step_kernel()
(control_and_ancilla, system): controlled adjoint walk step.- Return type:
Kernel
- select_observable()
The odd-moment SELECT observable for this encoding.
BlockEncoding protocol hook; delegates to the module-level
select_observable, which serves both backends.- Return type:
SpinOperator
- cudaq_algorithms.pauli_lcu.select_observable(encoding)
The SELECT operator
sum_i sign_i |i><i|_anc x P_ias an observable.LCU-specific: built from the encoding’s signed Pauli terms. Its expectation after PREPARE and p walk steps is the odd Chebyshev moment <T_{2p+1}(H/alpha)> (the BlockEncoding.select_observable hook). On the alias backend the projectors act on the
LCUBlockEncodingindex register alone (the firstnum_indexancillas, little-endian), so the operator is taken from there.- Parameters:
encoding (PauliLCU)
- Return type:
SpinOperator
- class cudaq_algorithms.lcu.LCUBlockEncoding(num_system, weights, bodies, *, mu=8, num_select_work=None)
Bases:
objectBlock encoding of
H / alphaforH = sum_k c_k U_k.Satisfies the full
BlockEncodingprotocol.select_observable(the odd-Chebyshev-moment observableWalk.momentuses) is derived from the bodies when every term is a Pauli word ("x","y","z"and("sign",)ops only) and raisesNotImplementedErrorfor bodies using the extended vocabulary. EvenWalk.momentorders use the geometry-only reflection observable, whose2^num_ancillaPauli terms are practical only at smallmu; dense Chebyshev data is also available throughwalk_kernelpowers.Every body op is validated at construction (known op, operand count, system targets
< num_system, and a Hermitian product for Pauli-word bodies); the encoding raisesValueErrorrather than failing inside a kernel.- Parameters:
num_system (int) – System-register width in qubits (the
U_kact onsystem[0:num_system]).weights (Sequence[float]) – The term weights
|c_k|: non-negative and finite, with a positive sum. Signsc_k < 0are carried on the SELECT branch (a("sign",)op in the body), never on the weights.bodies (Sequence[Sequence[tuple]]) – One SELECT body per term (same length as
weights), each a list of unary-iteration gate ops realizing the Hermitian involutionU_k.mu (int) – Alias-table keep precision in bits (>= 1); the per-term probability rounding is bounded by
discretization_bound.num_select_work (int | None) – SELECT work-scratch width. Defaults to the minimum the bodies require; a larger value is accepted, a smaller one is rejected.
- property num_ancilla: int
index + PREPARE garbage + SELECT work scratch.
The block is the all-ancilla-
|0...0>subspace, so consumers reflect about the full register, not the index alone: after SELECT the garbage is entangled with the system, so the index-|0>sector still carries nonzero garbage and an index-only reflection would misidentify the block. The SELECT work scratch is|0>at reflection points but is still counted here because CUDA-Q cannot deallocate it mid-circuit.- Type:
All ancillas
- property weights: tuple
The term weights
|c_k|, one per term in term order (the firstnum_termsPREPARE bins).discretized_weightshas one entry per bin; the bins pastnum_termsare zero-weight padding that acts as the identity.
- property alpha: float
The term one-norm
sum_k |c_k|.Exact for the discretized weights too:
table_probabilitiessum to 1 by construction, sosum(discretized_weights)equals this ideal one-norm identically.
- property discretized_weights: ndarray
The exactly realized per-bin weights
alpha * table_probabilities(the dense-reference anchor).
- property discretization_bound: float
Per-bin probability rounding bound (see
cudaq_algorithms.primitives._alias_sampling).
- property preparation: AliasSamplingPrepare
The underlying alias-sampling PREPARE (tables and bounds).
- encode_kernel(state_prep=None)
A kernel applying the full block encoding.
Without
state_prep: a@cudaq.kernel(state)allocating the system register fromstateand the ancilla register (in|0...0>) after it. Withstate_prep(a(qubits: qview)kernel): a zero-argument kernel that allocates the system register in|0...0>, runsstate_prepon it, then applies the encoding.- Parameters:
state_prep (Kernel | None)
- Return type:
Kernel
- walk_kernel(power=1, state_prep=None)
A kernel applying
powerqubitization walk steps.PREPARE,
powerwalk steps, PREPARE-dagger — the same(R U_A)^powerthatWalk.kernelcomposes — so the all-zero-ancilla block of the result is T_power(-H/alpha) applied to the input state. Input modes as inencode_kernel.- Parameters:
power (int)
state_prep (Kernel | None)
- Return type:
Kernel
- prepare_kernel()
(ancilla: qview): the alias PREPARE on[index | garbage]— the walk runs in the PREPARE frame, asPauliLCU’s does.- Return type:
Kernel
- unprepare_kernel()
(ancilla: qview): PREPARE-dagger.- Return type:
Kernel
- apply_kernel()
(ancilla, system): the full block encoding U_A.- Return type:
Kernel
- controlled_apply_kernel()
(control_and_ancilla, system): U_A controlled by qubit 0.- Return type:
Kernel
- walk_step_kernel()
(ancilla, system): one qubitization walk step W = R U_A.- Return type:
Kernel
- adjoint_walk_step_kernel()
(ancilla, system): one adjoint walk step W-dagger.- Return type:
Kernel
- controlled_walk_step_kernel()
(control_and_ancilla, system): controlled walk step.- Return type:
Kernel
- controlled_adjoint_walk_step_kernel()
(control_and_ancilla, system): controlled adjoint step.- Return type:
Kernel
- select_observable()
The SELECT operator
sum_k sign_k |k><k|_index (x) P_kas acudaq.SpinOperator: the odd-Chebyshev-moment observable.Measured after
prepare_kernelandpwalk steps with no UNPREPARE (whatWalk.momentdoes for odd orders), its expectation is<T_{2p+1}(H/alpha)>. It acts on the index register (qubitsnum_system .. num_system + num_index - 1, little-endian) and the system, and is the identity on the garbage and work. Available when every body is a Pauli word ("x"/"y"/"z"and("sign",)ops only); raisesNotImplementedErrorfor bodies using the extended vocabulary, whose term unitaries have no spin-operator form.- Return type:
- class cudaq_algorithms.block_encoding.BlockEncoding(*args, **kwargs)
Bases:
ProtocolA zero-flagged block encoding
U_Awith<0|_anc U_A |0>_anc = H / alpha.PauliLCU,LCUBlockEncodingandSparseOracleEncodingare the provided implementations; double-factorized or other custom encodings plug in by satisfying the same surface.- property num_ancilla: int
Number of ancilla (signal) qubits flagging the encoded block.
Consumers (
Walk,QSVT, the walk observables) requirenum_ancilla >= 1: the walk’s-H/alphasign comes from a reflection about the ancilla zero state, which is a no-op on an empty register.PauliLCUnormalizes single-term inputs to one idle ancilla to satisfy this uniformly.
- apply_kernel()
(ancilla: qview, system: qview): the full block encoding U_A.U_Amust be Hermitian, hence an involution (U_A^2 = I), asPREPARE-dagger SELECT PREPAREwith an involutory SELECT is.QSVT(which appliesU_Afor both walk directions) andSumEncoding(whose SELECT is built from its operands’U_A) rely on it.- Return type:
- controlled_apply_kernel()
(control_and_ancilla: qview, system: qview): U_A controlled by qubit 0 of the combined register.- Return type:
- walk_step_kernel()
(ancilla: qview, system: qview): one qubitization walk step W (block encodes-H/alpha).- Return type:
- adjoint_walk_step_kernel()
(ancilla: qview, system: qview): one adjoint walk step W†.- Return type:
- controlled_walk_step_kernel()
(control_and_ancilla: qview, system: qview): controlled W.- Return type:
- controlled_adjoint_walk_step_kernel()
(control_and_ancilla: qview, system: qview): controlled W†.- Return type:
- select_observable()
The odd-moment observable as a
cudaq.SpinOperator.Measured after PREPARE and
pwalk steps (no UNPREPARE), its expectation is the odd Chebyshev moment<T_{2p+1}(H/alpha)>. This presumes the walk step is defined in the PREPARE frame (W = PREPARE R PREPARE† SELECTwith realprepare_kernel/unprepare_kernel), as the provided encodings do. The construction is encoding-specific (for an LCU it issum_i sign_i |i><i|_anc x P_i); encodings that cannot supply it raiseNotImplementedError, andWalk.momentthen serves even orders only. The even-moment reflection observable2|0..0><0..0| - Ineeds only the register geometry, soWalkderives it without an encoding hook.- Return type:
Combinators that build new BlockEncoding objects out of existing ones.
Two constructions, both generic over the BlockEncoding protocol (any
conforming encoding can be an operand) and both producing an object that
satisfies the protocol again, so Walk and QSVT consume the result
unchanged and the combinators nest:
SumEncodingEncodes
sum_i c_i H_ifrom encodings of theH_iwith real coefficientsc_i;alpha = sum_i |c_i| alpha_i. One extra slot register selects the summand, one flag qubit drives the selected summand’s own controlled block encoding, and the summands’ ancillas share one pool: SELECT is block-diagonal over the slot register, each block a unitary on the whole pool, and the encoded block is the all-zero subspace of the entire ancilla register. A single summand is the “scale by a constant” case.RotatedEncodingEncodes
V H V^daggerfrom an encoding ofHand a pair of system-side kernels implementingV^dagger(enter) andV(exit). Because the rotation touches only the system register it commutes with every ancilla-side operation, so each protocol kernel of the inner encoding is simply sandwiched between the two rotations; the controlled variants come for free.from_orbital_rotationbuilds the kernels from thestatepreporbital-rotation schedule and its spin-lifted Givens network.
The payoff is choosing where each piece is cheap to encode: a hopping
term is diagonal in momentum space (alpha_T = sum_k |eps_k|) while the
interaction is diagonal in real space, and the sum of the two encodings
has a smaller alpha than one flat Pauli LCU of the whole Hamiltonian
(see docs/sphinx/examples/python/09_hubbard_combined_encoding.py).
What is not provided: odd-moment select_observable hooks. The sum’s
SELECT drives each summand’s full block encoding, PREPARE trees included,
so it has no compact cudaq.SpinOperator form; a rotated encoding’s
terms are not computational-frame Pauli words. Even moments
(Walk.moment with even order), Walk.kernel statevectors at any
power, and QSVT sequences are all available; Walk.moments, which
alternates even and odd orders, is not.
Every operand’s apply_kernel must be Hermitian (hence an involution),
as the protocol requires and every encoding in this package satisfies;
SumEncoding builds its SELECT from the operands’ U_A and relies on
it for walk powers >= 2.
- class cudaq_algorithms.combinators.RotatedEncoding(inner, enter, exit)
Bases:
objectBlock encoding of
V H V^daggerfrom an encoding ofH.Use
from_orbital_rotation()for a real orbital rotation in the interleaved spin-orbital layout.- Parameters:
inner (BlockEncoding) – A
BlockEncodingofH.enter (Kernel) –
(system: cudaq.qview)kernels implementingV^daggerandVon the system register. Every(ancilla, system)kernel ofinneris wrapped asenter; inner; exit; the ancilla-only PREPARE hooks pass through, andalphaand the ancilla count are unchanged.exit (Kernel) –
(system: cudaq.qview)kernels implementingV^daggerandVon the system register. Every(ancilla, system)kernel ofinneris wrapped asenter; inner; exit; the ancilla-only PREPARE hooks pass through, andalphaand the ancilla count are unchanged.
- classmethod from_orbital_rotation(inner, orthogonal)
Rotate by a real orthogonal one-particle matrix
V.orthogonalisn x nwith the target modes as columns and2 n == inner.num_system(spin orbital2pis modepspin up,2p + 1spin down). The rotation is compiled with thestatepreporbital-rotation schedule to its adjacent Givens network on both spin sectors (spatial_givens_network). The Givens sweep alone realizesV Dfor a diagonal of signsD(mode_signsreports it); aZon both spin orbitals of every mode with sign-1cancelsD(Z_p a_p Z_p = -a_punder Jordan-Wigner), soexitrealizes exactlyVandenterexactlyV^T, for any inner encoding.- Parameters:
inner (BlockEncoding)
- Return type:
- property num_rotations: int | None
Adjacent Givens rotations per spin sector in a
from_orbital_rotationnetwork, applied on entry and again on exit;Nonefor user-supplied kernels.
- property mode_signs: tuple[int, ...] | None
The per-mode signs
Dthe Givens sweep of afrom_orbital_rotationleaves (its network alone realizesV D); the constructor cancels them withZgates, so the frame kernels realizeVexactly.Nonefor user-supplied kernels.
- encode_kernel(state_prep=None)
A kernel applying the full rotated block encoding (
PauliLCUshape; seeSumEncoding.encode_kernel).- Parameters:
state_prep (Kernel | None)
- Return type:
Kernel
- class cudaq_algorithms.combinators.SumEncoding(terms)
Bases:
objectBlock encoding of
sum_i c_i H_ifrom encodings of theH_i.Ancilla layout is
[slot (num_slots qubits)][flag][shared pool]withnum_slots = max(1, ceil(log2 K))and a pool as wide as the widest summand, sonum_ancilla = num_slots + 1 + max_i num_ancilla_i. PREPARE puts amplitudesqrt(|c_i| alpha_i / alpha)on slot|i>(the same binary rotation treePauliLCUuses). For each summand, SELECT togglesflag ^= (slot == i), applies the signed operand controlled by the flag, restores the flag, and repeats the signed controlled operand on the contiguous[flag | pool]view. Since the signed operand is an involution, the two calls cancel off the selected slot and apply it once on the selected slot, independently of the incoming flag state. SELECT is block-diagonal over the slot register, each block a unitary on the whole pool, so summands of different widths share the pool and the encoded block is the all-zero subspace of the entire ancilla register, which the walk’s reflection covers.Each summand’s
apply_kernelmust be Hermitian on its entire ancilla and system register, hence an involution (U_A^2 = I). Itscontrolled_apply_kernelmust implement exact controlled-U_Afor arbitrary incoming ancilla states. Then each signed operandsign(c_i) U_A, each slot factor and SELECT itself are involutions, and the standard walk construction applies. An encoding that merely provides the protocol’s API members can still violate these properties; verify both for a foreign encoding before summing it.- Parameters:
terms (Iterable[tuple[float, 'BlockEncoding']]) –
[(c_1, encoding_1), ..., (c_K, encoding_K)]with real, nonzero, finite coefficients andBlockEncodingoperands acting on the same number of system qubits.K >= 1.
- prepare_kernel()
(ancilla: qview): PREPARE the slot register.- Return type:
Kernel
- unprepare_kernel()
(ancilla: qview): PREPARE dagger on the slot register.- Return type:
Kernel
- apply_kernel()
(ancilla, system): PREPARE, SELECT, PREPARE dagger.- Return type:
Kernel
- controlled_apply_kernel()
(control_and_ancilla, system): the block encoding controlled by qubit 0. The PREPARE pair stays uncontrolled: it cancels when the control is|0>because the controlled SELECT is the identity.- Return type:
Kernel
- walk_step_kernel()
(ancilla, system): SELECT, then reflect about PREPARE.- Return type:
Kernel
- adjoint_walk_step_kernel()
(ancilla, system): reflect about PREPARE, then SELECT.- Return type:
Kernel
- encode_kernel(state_prep=None)
A kernel applying the full block encoding (
PauliLCUshape).Without
state_prep:(state: cudaq.State), allocating the system register fromstateand the ancillas after it. Withstate_prep(a(qubits: qview)kernel): zero-argument, preparing the system register withstate_prepfirst.- Parameters:
state_prep (Kernel | None)
- Return type:
Kernel
Sparse-access block encodings
- cudaq_algorithms.sparse.encode_sparse(matrix, *, value_bits=8, dim=None, dilate=False, max_entries=4096)
Encode a sparse real matrix on the sparse-access oracle construction.
- Parameters:
matrix – A dense 2-D array, a
scipy.sparsematrix, or a(rows, cols, vals)tuple of parallel integer-indexed sequences. Must be symmetric with a non-negative diagonal unlessdilate=True.value_bits (int) – Fixed-point angle bits of the value oracle (quantization bound
h * (pi/2) * 2^-value_bitsper element).dim (int | None) – Matrix dimension — required with triples, optional (checked) otherwise.
dilate (bool) –
Trueencodes the Hermitian dilation[[0, A], [A^T, 0]]of a general squareA(one extra system qubit; module docstring).False(default) raises on non-symmetric input, including a symmetric matrix supplied as one triangle, and on negative diagonal entries.max_entries (int) – Budget for the from-data oracles’ classical table (
slots * dimQROM entries); above it this raises pointing at hand-written oracles.
- Returns:
SparseOracleEncodingwith the pricing report attached asencoding.report.
- Return type:
- class cudaq_algorithms.sparse.SparseOracleEncoding(oracles, num_system)
Bases:
objectBlock encoding of
H / (d_padded * h)from sparse-access oracles.- Parameters:
oracles (OracleKernels) – The
OracleKernelsbundle (contract in the module docstring).num_system (int) – System register width
n(the encoded matrix is2^n x 2^n).select_observable (Satisfies the BlockEncoding protocol except)
hook) ((LCU-specific odd-moment)
NotImplementedError. (which raises)
through (Every kernel factory works unchanged; measure Chebyshev data)
the (Walk(...).walk_kernel powers rather than Walk.moment —)
Pauli (even-moment reflection observable expands to 2^num_ancilla)
terms
(Walk (astronomical at this encoding's ancilla widths)
hanging). (refuses fast rather than)
- property num_ancilla: int
block ancillas plus deterministic scratch.
See the module docstring for why the scratch is folded in (CUDA-Q cannot deallocate mid-circuit) and why reflecting over it is exactly equivalent to a block-only reflection.
- Type:
All ancillas
- property num_scratch: int
Value/sign/upper/work qubits, deterministically
|0>outside the oracle-load window inside U_A.
- encode_kernel(state_prep=None)
A kernel applying the full block encoding.
Without
state_prep: a@cudaq.kernel(state)allocating the system register fromstateand the ancilla register (in|0...0>) after it; the state must hold exactly2^num_systemamplitudes (state_from(ket, num_qubits=encoding.num_system)checks that, which the kernel boundary cannot). Withstate_prep(a(qubits: qview)kernel): a zero-argument kernel that allocates the system register in|0...0>, runsstate_prepon it, then applies the encoding.- Parameters:
state_prep (Kernel | None)
- Return type:
Kernel
- walk_kernel(power=1, state_prep=None)
A kernel applying
powerqubitization walk steps.The all-zero-ancilla block of the result is T_power(-H/alpha) applied to the input state (this encoding’s PREPARE is trivial, so no PREPARE/UNPREPARE sandwich is needed). Input modes as in
encode_kernel.- Parameters:
power (int)
state_prep (Kernel | None)
- Return type:
Kernel
- prepare_kernel()
(ancilla: qview): trivial (the diffusion lives inside U_A).- Return type:
Kernel
- unprepare_kernel()
(ancilla: qview): trivial (seeprepare_kernel).- Return type:
Kernel
- apply_kernel()
(ancilla, system): the full block encoding U_A.- Return type:
Kernel
- controlled_apply_kernel()
(control_and_ancilla, system): U_A controlled by qubit 0.- Return type:
Kernel
- walk_step_kernel()
(ancilla, system): one qubitization walk step W = R U_A.- Return type:
Kernel
- adjoint_walk_step_kernel()
(ancilla, system): one adjoint walk step W-dagger.- Return type:
Kernel
- controlled_walk_step_kernel()
(control_and_ancilla, system): controlled walk step.- Return type:
Kernel
- controlled_adjoint_walk_step_kernel()
(control_and_ancilla, system): controlled adjoint step.- Return type:
Kernel
- classmethod from_general_oracles(oracles, num_system)
Encode the Hermitian dilation
[[0, A], [A^T, 0]]ofA.oraclesdescribes a general real2^n x 2^nmatrixA(per-slot column permutationsc(s, .)with explicit inverses, and the value convention of the module docstring witho_valwriting only the angle and sign bits — the dilation supplies theupperbit itself, since row < column reduces to the halves bit). The dilation places the oracle kernels undercudaq.control, so they must be flat (no sub-kernel calls, asbanded_oraclesbuilds them);qrom_oraclesbundles, which call unary-iteration sub-kernels, are not accepted here.slot_flipis ignored: every dilated slot is its own reverse (c_H(s, .)is an involution by construction), so the flip is the identity.The result acts on
num_system + 1system qubits (the halves bit is the most significant) and encodes[[0, A], [A^T, 0]] / alphawith the samed,h,value_bitsand honest paddedalphaas a direct encoding ofAwould report.- Parameters:
oracles (OracleKernels)
num_system (int)
- Return type:
- class cudaq_algorithms.sparse.OracleKernels(o_loc, o_loc_adj, o_val, o_val_adj, d, h, value_bits, num_work=0, slot_flip=None, num_system=None)
Bases:
objectThe user-supplied oracle bundle (see the module docstring).
- Parameters:
- o_loc, o_loc_adj, o_val, o_val_adj
@cudaq.kerneldevice kernels with the documented signatures; every inverse is explicit (cudaq.adjointis off-limits).o_valloads only the entries assigned to a slot; a mapping that merely completes a slot’s permutation loads zero.
- slot_flip
Reverse-slot involution over the padded slot range, or
Noneif unavailable (then onlyfrom_general_oraclesapplies).
- cudaq_algorithms.sparse.banded_oracles(offsets, band_values, num_system, value_bits, *, h=None, hermitian=True)
Oracles for the banded matrix
H[j + o, j] = band_values[o].- Parameters:
offsets (Sequence[int]) – Distinct integer band offsets
o(|o| < 2^num_system); bandoholds the elementsH[j + o, j]for all in-rangej(no periodic wrap-around). Offsets of any magnitude are applied exactly: the adder and comparator rotations take each constant reduced per bit as an integer.num_system (int) – System register width
n(the matrix is2^n x 2^n).value_bits (int) – Fixed-point bits for the angle register.
h (float | None) – Value normalization (defaults to
max |band_values|); must satisfyh >= max |band_values|.hermitian (bool) – Validate and lay out for direct encoding (see the module docstring): offsets closed under negation, band values symmetric to
1e-12 * max |band_values|, non-negative diagonal;Falseproduces a dilation-only bundle (slot_flip=None).
- Return type:
- cudaq_algorithms.sparse.qrom_oracles(matrix, value_bits, *, h=None, dim=None)
QROM-backed oracles for a real symmetric sparse matrix.
- Parameters:
matrix – A dense 2-D array, a
scipy.sparsematrix, or a(rows, cols, vals)tuple of parallel sequences. Must be symmetric with a non-negative diagonal (see the module docstring for the escape hatches).value_bits (int) – Fixed-point bits for the angle register.
h (float | None) – Value normalization (defaults to
max |H_ij|); must satisfyh >= max |H_ij|.dim (int | None) – Matrix dimension — required with triples, optional (checked) otherwise.
- Return type:
- cudaq_algorithms.sparse.quantized_angle(value, h, value_bits)
Fixed-point angle for
|value|:round(theta / (pi/2) * 2^vb).theta = arcsin(sqrt(|value| / h)); the result is clamped to2^value_bits - 1(the|value| = hedge loses one ulp). Shared by the oracle factory and the dense-reference tests, so the tests pin the exact encoded (quantized) operator at simulator precision.
Qubitization and QSVT
- class cudaq_algorithms.qubitization.Walk(encoding)
Bases:
objectQubitization walk over a block encoding.
Generic over the
BlockEncodingprotocol: encoding-specific circuits and the odd-moment observable are delegated to the injected encoding (PauliLCUandLCUBlockEncodingare the provided implementations).Provides walk/adjoint-walk kernel factories and Chebyshev-moment measurement in the QEL even/odd convention. Requires
num_ancilla >= 1(PauliLCUalways satisfies this; the guard defends against degenerate foreign encodings). The encoding is fixed at construction — kernels and observables are cached per instance.- Parameters:
encoding (BlockEncoding)
- property encoding
kernels and observables are cached against it, so swapping it would serve stale circuits).
- Type:
The injected block encoding (read-only
- kernel(power=1, uncompute=True, state_prep=None)
PREPARE, W^power, optionally UNPREPARE.
Without
state_prepthe returned kernel takes onecudaq.Stateargument (the input state as data — the simulation-friendly form). Withstate_prep— a kernel with signature(qubits: cudaq.qview)— the returned kernel takes no arguments: it allocates the system register in|0...0>, runsstate_prepon it, and applies the walks.state_prepmust act only on that register, whose width isnum_system(a documented contract; not verifiable at factory time).
- adjoint_kernel(power=1, uncompute=True, state_prep=None)
PREPARE, (W†)^power, optionally UNPREPARE (see
kernel).
- roundtrip_kernel(power=1, state_prep=None)
PREPARE, W^power, (W†)^power, UNPREPARE — the identity, for tests.
- Parameters:
power (int)
state_prep (Kernel | None)
- Return type:
Kernel
- controlled_kernel(power=1, control_state=1, uncompute=True, state_prep=None)
Controlled walks over the system register.
Input modes as in
kernel: withoutstate_prepthe returned kernel takes onecudaq.Stateargument; withstate_prepit takes no arguments and prepares the system register itself (the injected prep runs once, uncontrolled, as in QPE). Either way the system register is followed by one register holding [control, ancillas] (the control cannot share a control set with a separate register in CUDA-Q Python). The control qubit is initialized tocontrol_state; with control|0>the circuit is the identity up to the (cancelling) PREPARE pair.
- controlled_roundtrip_kernel(power=1, control_state=1, state_prep=None)
Controlled W^power then controlled (W dagger)^power — identity.
- moment(ket, order, *, state_prep=None)
Measure the Chebyshev moment <T_order(H/alpha)>.
The input state is given either as
ket(array-like or an already-builtcudaq.State— the simulation-friendly form) or asstate_prep(a(qubits: cudaq.qview)preparation kernel composed into the measured circuit — the hardware-shaped form). Provide exactly one.
- cudaq_algorithms.qubitization.reflection_observable(encoding)
R =
2|0...0><0...0| - Ion the ancilla register.- Parameters:
encoding (BlockEncoding)
- Return type:
cudaq.SpinOperator
- class cudaq_algorithms.qsvt.QSVT(encoding)
Bases:
objectQuantum singular value transformation over a block encoding.
Generic over the
BlockEncodingprotocol: encoding-specific circuits are delegated to the injected encoding (PauliLCUandLCUBlockEncodingare the provided implementations).- Parameters:
encoding (BlockEncoding)
- property encoding
kernels are cached against it, so swapping it would serve stale circuits).
- Type:
The injected block encoding (read-only
- kernel(sequence, convention=None, state_prep=None)
A kernel applying the phase/walk sequence.
sequencemay be a PhaseSequence or a plain list of phases (optionally withconvention="qsp"). Withoutstate_prepthe returned kernel takes onecudaq.Stateargument; withstate_prep— a(qubits: cudaq.qview)kernel — it takes no arguments and prepares the system register itself. The signal register is allocated in|0...0>after the system register.- Parameters:
sequence (PhaseSequence | Iterable[float])
convention (str | None)
state_prep (Kernel | None)
- Return type:
Kernel
- controlled_kernel(sequence, convention=None, control_state=1, state_prep=None)
A kernel applying the sequence controlled.
Input modes as in
kernel: acudaq.State-taking kernel, or a zero-argument kernel whenstate_prepis given (the injected prep runs on the system register only, uncontrolled). Either way the system register is followed by one register holding [control, signal] (a CUDA-Q Python control set cannot mix a bare qubit with a separate register). With control|0>the sequence is the identity.- Parameters:
sequence (PhaseSequence | Iterable[float])
convention (str | None)
control_state (int)
state_prep (Kernel | None)
- Return type:
Kernel
- class cudaq_algorithms.qsvt.PhaseSequence(phases, walk_directions=None, convention='qsvt')
Bases:
objectA validated QSVT/QSP phase sequence.
- Parameters:
phases (tuple[float, ...]) – d + 1 phase angles for a degree-d polynomial.
walk_directions (tuple[int, ...]) – Optional; one direction (‘forward’/’adjoint’ or 0/1) per walk, length d. Defaults to all forward.
convention (str) – “qsvt” (projector phases
diag(e^{i phi}, 1), the default) or “qsp” (Z-rotation phasesdiag(e^{i phi}, e^{-i phi}), the QSPPACK convention). qsp-tagged phases are converted automatically wherever a circuit is built;phasesalways stays raw.
- cudaq_algorithms.qsvt.recover_real_time_evolution(cos_state, sin_state, cos_phases, sin_phases)
Combine cosine/sine QSP components into
exp(-i H t)|psi>.cos_stateandsin_stateare good-subspace statevectors produced by running qsp-convention sequences through the QSVT circuit (which executes doubled projector phases); the per-sequence global phaseexp(i * sum(phases))is removed here. Valid for real Hamiltonians and real input states, where the cosine/sine parts live in the real/imaginary components.
- class cudaq_algorithms.phase_estimation.PhaseEstimation(encoding)
Bases:
objectTextbook quantum phase estimation over a
BlockEncoding.The phase register holds
num_bitsqubits; the energy resolution is set by how finely2π j / 2^num_bitssamples the walk eigenphase (aboutalpha π / 2^num_bitsat worst). Composed kernels are cached per(num_bits, state_prep, measure).- Parameters:
encoding (BlockEncoding) – Any object satisfying the
BlockEncodingprotocol (PauliLCUand the other encodings in this package): it supplies the controlled qubitization walk, the PREPARE hooks that set the walk’s frame, and the one-normalpha.
- phase_to_energy(index, num_bits)
Map an
m-bit phase readoutjto an energy.E = −alpha · cos(2π j / 2^m)— the inverse of the walk’scos θ = −E/alphaeigenphase relation.
- kernel(num_bits, *, state_prep=None, measure=False)
The phase-estimation circuit.
Without
state_prep: a@cudaq.kernel(state)allocating the system register fromstate. Withstate_prep(a(qubits: qview)kernel): a zero-argument kernel that prepares the system register itself. In both the phase + ancilla registers start in|0...0>. Register layout: system, thennum_bitsphase qubits (little-endian: phase qubit 0 is the least significant readout bit), then the encoding’s ancillas.measure=Falseleaves the phase register ready to read (take its marginal withsim_utils.qpe.phase_probabilities, or measure it yourself).measure=Trueends the circuit by measuring the phase register alone, socudaq.samplereturns its bitstrings on any target; decode them withenergies_from_counts. On a simulator, a long ladder needs a large thread stack, about 1 kB per walk step (sim_utils.run_on_large_stack(cudaq.sample, circuit, ...); module docstring).
- phase_probabilities_from_counts(counts, num_bits)
The phase-register distribution behind sampled bitstrings:
2^num_bitsrelative frequencies, entryjfor readoutj.countsis acudaq.SampleResultor a mapping from bitstring to count. Bitstrings list qubit 0 first. A string ofnum_bitscharacters is the phase register (kernel(..., measure=True)); a string over every qubit of the circuit (kernelsampled with no explicit measurement) is sliced at the register layout, system | phase | ancilla.
- energies_from_probabilities(probabilities, num_bits, *, top=None)
Rank energies from a phase-register distribution.
Folds the mirror readouts
jand2^m - j(the same energy) into one entry, so the list has2^(m-1) + 1distinct energies whose probabilities sum to that of the input, most probable first.topkeeps the most probable entries.
- cudaq_algorithms.qsvt.FORWARD = 0
int([x]) -> integer int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating-point numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100’, base=0) 4
- cudaq_algorithms.qsvt.ADJOINT = 1
int([x]) -> integer int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating-point numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100’, base=0) 4
Trotter
Suzuki-Trotter Hamiltonian simulation.
Product-formula time evolution for Hamiltonians expressed as sums of Pauli strings: term extraction, host-side planning and ordering, resource estimation, and the circuit primitive itself.
The typical workflow constructs a Trotter object (term extraction,
validation, and ordering happen once) and either uses its kernel
factories or composes the apply_trotter primitive inside a custom
kernel:
from cudaq_algorithms import trotter
evolution = trotter.Trotter(hamiltonian)
kernel = evolution.kernel(time=0.8, steps=4, order=2) # @cudaq.kernel()
resources = evolution.resources(steps=4, order=2)
Identity terms: for H = c I + H', apply_trotter implements the
product formula for H' only. The omitted exp(-i c t) is an
unobservable global phase for one unconditioned evolution but a real
relative phase for controlled or interference-based algorithms;
identity_coefficient is reported on the Trotter object so callers
can account for it (the simulation helper sim_utils.evolve
reintroduces it host-side).
- cudaq_algorithms.trotter.HamiltonianLike
a
cudaq.SpinOperator(or a singlecudaq.SpinOperatorTermproduct), a{"XZI...": coefficient}mapping, or an iterable of(coefficient, word)pairs.- Type:
Accepted Hamiltonian input forms
alias of
SpinOperator|SpinOperatorTerm|Mapping[str,complex] |Iterable[tuple[complex,str]]
- class cudaq_algorithms.trotter.Trotter(hamiltonian, ordering=TrotterOrdering.PRESERVE_INPUT, *, coefficient_tolerance=1e-12)
Bases:
objectSuzuki-Trotter product formulas for a Pauli-sum Hamiltonian.
Term extraction, validation, and ordering happen once at construction (identity terms are split off into
identity_coefficient); the evolution parameterstime,steps, andorderare supplied per kernel request, mirroring the other primitives (Walk.kernel(power=...),QSVT.kernel(sequence)).The object is hardware-shaped: nothing here executes a simulator-only API (see
sim_utils.evolvefor statevector-based evolution).- Parameters:
hamiltonian (HamiltonianLike)
ordering (TrotterOrdering | str)
coefficient_tolerance (float)
- property identity_coefficient: float
Sum of identity-term coefficients (not realizable in circuit).
- property ordering: TrotterOrdering
Term-ordering strategy fixed at construction.
- kernel(time, steps=1, order=2, state_prep=None)
Return a
@cudaq.kernel()applying the product formula.(
Anybecause CUDA-Q exposes no stable public Python type for compiled kernel objects.)The kernel allocates
num_qubitsqubits in|0...0>, optionally runsstate_prep(a kernel with signature(qubits: cudaq.qview)) on them, and applies theorder-order formula fortimeoverstepssteps — with or withoutstate_prepthe result takes no arguments and is directly sampleable.state_prepmust act only on the register it is handed (widthnum_qubits, arriving in|0...0>). The identity phase is not included (it cannot be, in a circuit); trackidentity_coefficientwhen it matters.
- state_kernel(time, steps=1, order=2)
Return a
@cudaq.kernel(state)evolving an arbitrary state.Same validated product formula as
kernel(), but the register is allocated from acudaq.Stateargument instead of|0...0>— the input-loading pathsim_utils.evolveuses. Both factories share validation and marshaling through_prepared_args.The supplied state must have dimension
2**num_qubits:sim_utils.evolvechecks this; direct callers are responsible for it themselves (the identity-only variant cannot detect a mismatch).
- resources(steps, order)
Resource estimate for
stepssteps of theorderformula.Both parameters are required so the estimate can never silently describe a different circuit than the kernel you built.
- Parameters:
- Return type:
- class cudaq_algorithms.trotter.TrotterOrdering(*values)
Bases:
EnumTerm-ordering strategies for the product formula.
PRESERVE_INPUTkeeps the extraction order;COEFFICIENT_MAGNITUDE_DESCENDINGapplies the largest-magnitude terms first, a common heuristic for reducing Trotter error.
- class cudaq_algorithms.trotter.TrotterResourceEstimate(num_terms, steps, order, pauli_rotations, estimated_cx_count, identity_coefficient)
Bases:
objectLightweight circuit-cost summary for a Trotter sequence.
estimated_cx_countis a decomposition proxy: two CNOTs per additional non-identity Pauli in each rotation.
- cudaq_algorithms.trotter.estimate_trotter_resources(coefficients, words, steps, order, identity_coefficient=0.0)
Return a lightweight resource estimate for a Trotter sequence.
- cudaq_algorithms.trotter.make_trotter_terms(hamiltonian, coefficient_tolerance=1e-12)
Return flattened terms for the Suzuki-Trotter circuit primitive.
Returns
(coefficients, words, identity_coefficient, num_qubits)wherewordsare padded plain strings: readable, comparable, and accepted directly aslist[cudaq.pauli_word]kernel arguments. (Only kernel-captured words need explicitcudaq.pauli_wordconversion, whichTrotter.kernelperforms internally.)coefficient_tolerancefilters term magnitudes only: terms with|coefficient|below it (and exactly-zero terms regardless of it) are dropped — they would emit zero-angle rotations and inflate resource estimates. It does not affect complex-coefficient validation, which is fixed package-wide (see_real_coefficient).
Circuit primitives
Fault-tolerant circuit primitives: unary iteration, QROM, arithmetic.
unary_iteration_kernels mints unary iteration (Babbush et al.,
arXiv:1805.03662, Fig. 7) in its strictly unitary form — no
measurement-based uncomputation, i.e. the fused select(V) walk of
Childs et al. (arXiv:1711.10980, Appendix G.4) — applying a
per-address body exactly when the address register equals k.
QROM builds coherent
classical-table lookups on top of it, either as the plain
unary-iteration SELECT or as the SELECT-SWAP / QROAM construction of
Low, Kliuchnikov and Schaeffer (arXiv:1812.00954), either one
optionally under an external control (controlled=True).
Everything here is strictly unitary: the papers’ headline Toffoli counts assume measurement-based ancilla uncomputation, which this library does not use (primitives must stay statevector-testable and inverse-composable); the module docstrings state the coherent costs the minted kernels actually have, and the resource tests pin them against the compiler.
The reversible integer arithmetic device kernels (_arithmetic)
are the in-place little-endian adders and comparators the lookup-based
constructions compose with: the CDKM/Cuccaro ripple-carry family
(add_register / subtract_register, add_constant /
subtract_constant, cmp_ge_constant, and the register-register
comparators cmp_ge_register / cmp_gt_register) and the ancilla-free Draper
QFT family (qft / iqft, the Fourier-basis adder phase_add_constant,
add_constant_qft / subtract_constant_qft, and the
cmp_ge_constant_qft_shift / cmp_ge_constant_qft_shift_adj pair). Every
inverse is hand-written and the gate prices are compiler-pinned by the resource
tests. Autodoc does not render @cudaq.kernel objects; the indexed
arithmetic API reference provides explicit signatures
and register contracts. Each kernel’s own docstring also carries its contract.
AliasSamplingPrepare composes both: the coherent alias-sampling
PREPARE-with-garbage of Babbush et al. (arXiv:1805.03662, Sec. III.D)
— integer Vose preprocessing, a QROM lookup of the (alias, keep) table
priced by variant="auto", and the CDKM comparator — realizing a
weighted index-register marginal exactly, up to a derived mu-bit
discretization bound.
Composition: minted kernels are building blocks — call them from your
own kernels, and wrap the whole composition in cudaq.control to
obtain the controlled operation. This is the intended consumption model
for SELECT-style constructions (the select_swap QROM is itself a parent
kernel composing a walk, a routing network and a copy), and it is pinned
by tests/python/test_primitives_composition.py. Where a controlled
walk is what you need, the factory’s controlled=True variants are
the cheaper route by a wide margin: cudaq.control over a composition
adds a control to every gate, so each of the walk’s Toffolis becomes a
3-controlled X and each root or ladder CNOT becomes a Toffoli, while the
factory folds the control into the root gadgets. Measured with
cudaq.estimate_resources on CUDA-Q 0.16.0 (one-gate bodies): a 4-bit,
16-item walk costs 44 Toffolis plus 19 3-controlled X under
cudaq.control against 23 Toffolis from the factory; a 5-bit, 32-item
walk 87 Toffolis plus 43 3-controlled X against 47.
Import the subpackage directly (from cudaq_algorithms.primitives
import QROM); nothing here is re-exported from the package root.
- class cudaq_algorithms.primitives.AliasSamplingPrepare(weights, mu, *, variant='auto', block_size=None)
Bases:
objectCoherent alias-sampling PREPARE (see the module docstring).
- Parameters:
weights (Sequence[float]) – Non-negative, finite weights with a positive sum; zero entries are allowed (their bins get exactly zero probability). Padded with zero-weight bins to the next power of two.
mu (int) – Keep-threshold precision in bits (>= 1); the per-bin discretization error is bounded by
discretization_bound.variant (str) – Keyword-only; forwarded verbatim to the
QROMconstructor (default"auto": price the variants and mint the cheapest). The chosen variant controls the garbage-register size throughqrom.num_ladder(seenum_garbage).block_size (int | None) – Keyword-only; forwarded verbatim to the
QROMconstructor (only meaningful withvariant="select_swap";Nonelets the QROM pick). Also shapesqrom.num_ladderand hencenum_garbage. Invalid combinations raise the QROM’s ownValueError.caveat (Garbage)
orthogonal (mutually)
is (so the reduced state on the index register)
index (not diag(p_k); only the amplitude magnitudes on the)
guaranteed. (register are)
PREP|0> (That is exactly what qubitization's <0|PREP^dagger SELECT)
but (contract needs — index orthogonality kills the cross terms —)
garbage. (consumers must not assume orthonormal)
- adjoint_kernel()
PREPARE^dagger
(index, garbage)— the exact inverse.
- property discretization_bound: float
Per-bin bound on
|table - ideal|probability (see module doc).
- kernel()
PREPARE
(index, garbage)— both|0...0>on entry.
- property ladder_offset: int
Offset of the
qrom.num_ladder-wide QROM ladder inside garbage.The ladder qubits are clean (
|0>) betweenkernel()andadjoint_kernel()— unlike the rest of the garbage — so a SELECT sandwiched between them may reusegarbage[ladder_offset : ladder_offset + qrom.num_ladder]as its own ladder.
- class cudaq_algorithms.primitives.QROM(data, address_bits, output_bits, *, variant='auto', block_size=None, controlled=False)
Bases:
objectCoherent lookup of a classical integer table (see module docstring).
- Parameters:
data (Sequence[int]) – The table: non-negative integers, one per address, each fitting in
output_bitsbits.address_bits (int) – Address register width (
len(data) <= 2^address_bits).output_bits (int) – Output register width.
variant (str) –
"auto"(default),"select"or"select_swap"— see the module docstring for the constructions and their exact prices.block_size (int | None) – SELECT-SWAP block size: a power of two in
[2, 2^(address_bits - 1)]. Only valid withvariant="select_swap";Nonethere picks the power of two minimizing the documented Toffoli count.controlled (bool) –
Truemints the externally controlled lookup: the kernel takes a leading one-qubitcontrolview, is the identity at control|0>and the plain lookup at|1>(module docstring). The identity at|0>holds on the clean ladder the kernel requires anyway; a dirty ladder is outside the contract either way.variant="auto"prices the controlled candidates against each other on Toffolis alone, and the optimum can sit at a larger block than the plain lookup’s, with more block registers: size the ladder from this instance’snum_ladderrather than assume the plain and controlled lookups share a layout (seven one-bit entries over three address bits take 5 ladder qubits controlled, 4 plain).contiguity (The views of the minted kernel may live anywhere (no)
them) (requirement between)
QROM (which is what lets callers weave the)
variant
is (the kernel)
uncompute. (exactly self-inverse — apply it again to)
- property kernel
The lookup kernel — self-inverse.
(address, ladder, output), or(control, address, ladder, output)whencontrolled.
- class cudaq_algorithms.primitives.UnaryIterationKernels(kernel, kernel_adj, num_address, num_ladder, num_items, controlled, toffoli_count, num_work=0, ops=None)
Bases:
objectThe minted walk (see the module docstring for signatures).
- Parameters:
- kernel, kernel_adj
The walk and its hand-written inverse (
kernel_adjisNonewhen minted withinclude_adjoint=False).
- num_address, num_ladder, num_items
Register widths (
num_ladder == num_addressclean ancillas) and the number of iterated addresses.
- describe()
Decode the instruction tape into a human-readable gate listing.
One line per gate, in execution order — exactly what the interpreter kernel replays. Lines tagged
# Toffoliare the gatestoffoli_countcounts. This is the intended way to read a minted walk; the kernel source itself is a generic interpreter and shows nothing about any particular circuit.- Return type:
- cudaq_algorithms.primitives.unary_iteration_kernels(num_address_bits, num_items, body, *, controlled=False, include_adjoint=True, num_work=None)
Mint the unary-iteration walk for a factory-time body callback.
- Parameters:
num_address_bits (int) – Address register width (>= 1).
num_items (int) – Number of iterated addresses (
1 <= num_items <= 2^num_address_bits); addressesk >= num_itemsare never entered and the walk acts as the identity on them.body (Callable[[int], Sequence[tuple]]) – The payload table of the SELECT: a factory-time callback mapping each address
kto the gate listU_kthat the walk applies when the address register holdsk— i.e. the minted kernel implementssum_k |k><k| (x) U_k. Each entry is an opcode tuple such as("x", t)/("y", t)/("z", t)(leaf-controlled Pauli ontarget[t]) or one of the extended gates in the module docstring; an empty list meansU_k = I. Called exactly once per address, in address order, during this factory call — the gates are baked into the kernel, sobodyitself never runs at circuit time.controlled (bool) – Mint the externally controlled walk (leading one-qubit view).
include_adjoint (bool) – Mint
kernel_adj; passFalsewhen the walk is known to be an involution (commuting self-inverse body, e.g. X-only QROM).num_work (int | None) – Width of the trailing clean
workview.None(default) infers the width from the body’s work usage. An explicit value must cover that usage. The work view is present only when the resolvednum_work > 0, including a positive explicit width unused by the body; explicitnum_work=0keeps the work-less signatures when the body needs no work.
- Return type:
The arithmetic kernels have explicit, indexed signatures and register contracts on the following reference page:
Preprocessing
Chemistry-input bridges between classical tensors and qubit Hamiltonians.
Connects the double-factorization preprocessing to the quantum primitives:
chemist-notation spatial integrals (the form the DF module consumes and
reconstructs) are spin-expanded and passed through the fermion
subpackage’s Jordan-Wigner transform, yielding a cudaq.SpinOperator
ready for PauliLCU/Walk/QSVT.
spin_orbital_tensors is pure NumPy and always importable and usable.
qubit_hamiltonian additionally uses fermion.jordan_wigner (imported
lazily); importing this module never raises, and if fermion is
unavailable the ImportError surfaces when qubit_hamiltonian is
called, not at import.
- cudaq_algorithms.chemistry.from_fcidump(contents)
Parse FCIDUMP contents into chemist-notation spatial integrals.
Takes the integral data as a string – the text of the file, already read – not a path; the caller does the file I/O:
one_body, eri, core = from_fcidump(Path("mol.fcidump").read_text())
Keeping the parse pure (no file access) lets callers and tests inject the integrals directly. Returns
(one_body, eri, core_energy): the(n, n)core Hamiltonian, the dense(n, n, n, n)chemist-notation(pq|rs)two-electron tensor (all eight symmetry partners of each stored record populated), and the scalar core/constant energy – the(one_body, eri, core_energy)triple, in the exact conventionqubit_hamiltonianand the block encodings consume:one_body, eri, core = from_fcidump(text) hamiltonian = qubit_hamiltonian(one_body, eri, scalar_offset=core)
FCIDUMP indices are Fortran 1-based; a
value i j k lrecord with all ofi,j,k,lnonzero is a two-electron integral, withk == l == 0a one-electron integralh_ij(its transpose is filled too), and with all indices zero the core energy.Only real (RHF/ROHF-style) FCIDUMP files are supported; unrestricted variants (Molpro’s
IUHF=1or Psi4’sUHF=.TRUE.) store a spin-resolved integral set with a different index symmetry and are rejected up front by a header guard.
- cudaq_algorithms.chemistry.spin_orbital_tensors(one_body, eri, *, validate_symmetry=True)
Spin-expand chemist-notation spatial integrals.
one_bodyis the(n, n)core Hamiltonian anderithe(n, n, n, n)chemist-notation(pq|rs)two-electron tensor over real spatial orbitals — the exact convention the double-factorization module documents. Returns(one_body_so, two_body_so)over2nspin orbitals (interleaved spins:2pup,2p + 1down), wheretwo_body_so[p, q, r, s]is the coefficient ofa^dag_p a^dag_q a_r a_sas consumed byfermion.jordan_wigner.erimust obey the real-orbital chemist permutation symmetry ((pq|rs) = (qp|rs) = (pq|sr) = (rs|pq)and their compositions) — this is what makes the resulting qubit Hamiltonian Hermitian, and it holds for reconstructed DF integrals and mean-field integrals. It is checked by default; passvalidate_symmetry=Falseto skip the check (e.g. for genuinely complex integrals, whose symmetry differs).
- cudaq_algorithms.chemistry.qubit_hamiltonian(one_body, eri, *, scalar_offset=0.0, tolerance=1e-12, validate_symmetry=True)
Qubit Hamiltonian (
cudaq.SpinOperator) from chemist integrals.Spin-expands the spatial integrals (see
spin_orbital_tensors, whoseerisymmetry precondition andvalidate_symmetryflag apply here too) and applies the Jordan-Wigner transform.scalar_offsetis added as an identity term (e.g. the nuclear repulsion energy);toleranceprunes negligible terms inside the transform.Combined with the double-factorization module this closes the classical-to-quantum loop:
factorization = compressed_double_factorization(eri, num_leaves=T) h_truncated = qubit_hamiltonian(one_body, reconstruct_eri(factorization)) encoding = PauliLCU(h_truncated) # -> Walk / QSVT
- cudaq_algorithms.chemistry.from_pyscf(mean_field)
Chemist
(pq|rs)MO integrals + nuclear repulsion from PySCF.mean_fieldis a converged restricted mean field (e.g. the result ofpyscf.scf.RHF(mol).run()). Returns(one_body, eri, nuclear_repulsion)in the molecular-orbital basis and chemist notation – exactly the argumentsqubit_hamiltonian()expects (passnuclear_repulsionas itsscalar_offset).Restricted (single
mo_coeffmatrix) references only; the spin expansion downstream assumes one spatial set shared by both spins.
- cudaq_algorithms.chemistry.from_psi4(wavefunction)
Chemist
(pq|rs)MO integrals + nuclear repulsion from Psi4.wavefunctionis a converged restricted wavefunction, e.g. the second return value ofpsi4.energy("scf", return_wfn=True). Returns(one_body, eri, nuclear_repulsion)in the molecular-orbital basis and chemist notation – identical in meaning and convention tofrom_pyscf(), so either drivesqubit_hamiltonian()unchanged.Restricted references only (uses
Ca);mo_erialready returns the chemist(pq|rs)ordering, matching the PySCF path.The wavefunction must be computed in C1 symmetry (
symmetry c1in the Psi4 geometry). The extraction readsCaas a single dense block, so an irrep-blocked (higher-symmetry) wavefunction is rejected.
Fermion-to-qubit transforms (pure Python, no compiled extension).
- cudaq_algorithms.fermion.jordan_wigner(one_body_or_two_body, two_body=None, scalar_offset=0.0, tolerance=1e-15, *, num_modes=None)
Jordan-Wigner transform of fermionic integrals to a qubit operator.
The integrals are the coefficients of
adag_i a_j(one-body) andadag_i adag_j a_k a_l(two-body) overnspin orbitals,- H = scalar_offset * I + sum_ij h[i, j] adag_i a_j
sum_ijkl V[i, j, k, l] adag_i adag_j a_k a_l
compiled exactly as given: index order is preserved and no conjugate terms, tensor symmetries or prefactors are inserted (Hermiticity is the caller’s responsibility). Each tensor may be dense – an
(n, n)one-body array, optionally followed by an(n, n, n, n)two-body array, or a two-body array alone – or sparse, a mapping from index tuples to coefficients whose missing entries are zero:h = {(0, 1): -1.0, (1, 0): -1.0} # hopping 0 <-> 1 V = {(0, 1, 1, 0): 0.5} # 0.5 * n_0 n_1 op = jordan_wigner(h, V, num_modes=4)
Dense and sparse forms may be mixed. The mode count is read from any dense tensor; when both inputs are mappings it must be given as
num_modes, because it is part of the operator’s definition rather than something to infer from the largest index (it sets the qubit width, and for Bravyi-Kitaev the shape of the Fenwick tree). Declared modes that carry no term are allowed, as an all-zero dense row/column always was.scalar_offsetis added as an identity term; input entries (explicit zeros included) and compiled terms with magnitude belowtoleranceare dropped. Returns acudaq.SpinOperator.
- cudaq_algorithms.fermion.bravyi_kitaev(one_body_or_two_body, two_body=None, scalar_offset=0.0, tolerance=1e-15, *, num_modes=None)
Bravyi-Kitaev transform of fermionic integrals to a qubit operator.
Same input conventions as
jordan_wigner(dense tensors or sparse mappings,num_modeswhen both inputs are mappings); the qubits store Fenwick-tree partial sums of the occupations, giving O(log n)-weight Pauli words. Returns acudaq.SpinOperator.Migration note: the two-body tensor is compiled literally, entry by entry as
V[i,j,k,l] adag_i adag_j a_k a_l— identical tojordan_wigner. The retired compiled binding instead antisymmetrized the tensor internally before transforming; matchingjordan_wignerhere repairs a prior JW/BK inconsistency. A caller who passed a raw, non-antisymmetrized (e.g. chemist-ordered) two-body tensor and relied on that internal antisymmetrization must now antisymmetrize the input themselves, or they will silently get a different operator.
- cudaq_algorithms.fermion.bravyi_kitaev_superfast(one_body_or_two_body, two_body=None, scalar_offset=0.0, tolerance=1e-15, interaction_graph=None, local_modes='binary_tree', parity=0, *, num_modes=None)
Bravyi-Kitaev Superfast transform of fermionic integrals.
A locality-preserving fermion-to-qubit mapping that places the qubits by the Hamiltonian’s interaction graph: local terms compile to bounded-weight Pauli operators (set by the graph degree), the payoff over Jordan-Wigner’s O(N) strings when the graph is sparse. The qubit count is the number of graph edges (
> Nfor dense Hamiltonians – this mapping is for sparse ones).The integrals are the coefficients of
adag_i a_jandadag_i adag_j a_k a_l(the convention ofjordan_wigner(), compiled exactly as given), either dense – an(n, n)one-body tensor, optionally with an(n, n, n, n)two-body tensor, or a two-body tensor alone – or sparse, mappings from index tuples to coefficients whose missing entries are zero. Sparse is the natural form for the lattice models this encoding is for, where a dense two-body tensor isO(n^4)storage forO(n)couplings:L = 10 # Hubbard chain, 2p up / 2p+1 down h = {} for site in range(L - 1): for spin in (0, 1): a, b = 2 * site + spin, 2 * site + 2 + spin h[(a, b)] = h[(b, a)] = -1.0 V = {(2 * s, 2 * s + 1, 2 * s + 1, 2 * s): 4.0 for s in range(L)} op = bravyi_kitaev_superfast(h, V, num_modes=2 * L)
Dense and sparse forms may be mixed; the mode count is read from any dense tensor and must be given as
num_modeswhen both inputs are mappings. Declared modes that carry no term are not part of the interaction graph and get no qubits (as an all-zero dense row/column never did). Arbitrary (complex, non-symmetric) one-body and arbitrary two-body integrals are supported.scalar_offsetis added as an identity term; input entries (explicit zeros included) and compiled terms belowtoleranceare dropped. Returns acudaq.SpinOperator.local_modesselects the construction (Setia, Bravyi, Mezzacapo, Whitfield, Phys. Rev. Research 1, 033033, generalizing Bravyi-Kitaev, Annals of Physics 298):"binary_tree"(default): the generalized encoding with Fenwick-tree local Majorana modes –O(log d)Pauli weight in the graph degreed(vertex operators of weight 1). Requires even vertex degree; the graph is padded with zero-coefficient dummy edges when needed."error_correcting": generalized encoding whose code corrects any single-qubit error on a 3-connected graph of even degree>= 6(the graph is validated / padded accordingly)."standard": the original edge encoding (one qubit per edge; one Z-string vertex operator, dressed-X edge operator), ofO(d)weight.a custom provider (callable
degree -> modesor mapping): the caller’s own local Majorana modes, each a Pauli string or(coeff, (x, z))word ondegree/2qubits, validated to obey the Majorana algebra.
interaction_graphoptionally pins the edge set (an iterable of(i, j)mode pairs) instead of inferring it from the nonzero terms – to control the qubit layout or to add extra edges. It must be a superset of the edges the Hamiltonian requires; the edge ordering fixes the qubit indexing.The interaction graph over the modes that carry a term must be connected (fermion parity is fixed per connected component, so a disconnected graph would not map to a single global-parity sector); a disconnected graph or an isolated number-only mode raises, pointing at
interaction_graphto add connecting edges. Hermiticity of the input is the caller’s responsibility, as forjordan_wigner().parityselects the fermion-parity sector the code subspace represents:0(default) for an even number of particles,1for an odd number. The encoding maps the even operator algebra only, so the encoded parityprod_i (-1)^{n_i} = prod_i B_iis a constant on the code subspace rather than an operator with both eigenvalues;parity=1negates the vertex operator of one designated mode (the lowest active one), which flips that constant and leaves the edge operators, their orientation and the loop stabilizers unchanged. Restricting the mapped Hamiltonian to the stabilizers’ joint+1eigenspace then recovers the spectrum of the selected Jordan-Wigner parity sector. The mapping of a state with the other parity is not defined; pass the parity of the particle number of the states you intend to prepare.Dense two-body couplings densify the interaction graph and emit a
UserWarning(no locality advantage there). Usebravyi_kitaev_superfast_stabilizers()for the loop stabilizers that fix the code subspace.
- cudaq_algorithms.fermion.bravyi_kitaev_superfast_stabilizers(one_body_or_two_body, two_body=None, tolerance=1e-15, interaction_graph=None, local_modes='binary_tree', parity=0, *, num_modes=None)
Loop stabilizers of the Superfast code subspace for the given integrals.
Returns one
cudaq.SpinOperatorper independent cycle of the interaction graph (empty for a tree graph). Each is a Hermitian involution, commutes with the mapped Hamiltonian, and is sign-fixed so that the code subspace is their joint +1 eigenspace – the fermion-parity sector selected byparity(even by default), matching that sector under Jordan-Wigner. Restricting the mapped Hamiltonian to that eigenspace recovers the fermionic spectrum of the sector.The integrals,
local_modes,interaction_graph,parityandnum_modesare as inbravyi_kitaev_superfast()(use the same values for both so the stabilizers act on the matching qubits). The stabilizer words themselves do not depend onparity: the sector is selected by the vertex operators the Hamiltonian compiles to.
Double factorization of two-electron integrals (X-DF and C-DF).
Explicit (X-DF) and compressed (C-DF) double factorization following Cohn, Motta, and Parrish, PRX Quantum 2, 040352 (2021) (arXiv:2104.08957). Heavy linear algebra runs on the NVIDIA math libraries (cuSOLVER / cuBLAS via CuPy) when a GPU is available, with a NumPy/SciPy fallback selected automatically.
- class cudaq_algorithms.double_factorization.DoubleFactorization(num_orbitals, leaf_rotations, leaf_cores, method, first_factorization=None, leaf_weights=None, optimizer_success=None, optimizer_nit=None, optimizer_grad_norm=None)
Bases:
objectResult of a double factorization of the two-electron integrals.
leaf_rotations[t]is the orthogonal matrixU^t(shape(num_orbitals, num_orbitals)) andleaf_cores[t]is the symmetric coreZ^tfor leaft.methodis"X-DF"or"C-DF".C-DF fills
optimizer_success,optimizer_nit, andoptimizer_grad_normfrom the L-BFGS-B result (Noneon X-DF). Whenn == 1, no optimization runs, so those fields areTrue,0, and0.0.- Parameters:
- cudaq_algorithms.double_factorization.explicit_double_factorization(eri, threshold=1e-08, max_num_leaves=None, second_factor_threshold=0.0, first_factorization='cholesky', backend='auto')
Explicit double factorization (X-DF).
First factorization of the ERI supermatrix
(pq|rs) = sum_t L^t_pq L^t_rsinto symmetric leavesL^t:first_factorization="cholesky"(default) – pivoted Cholesky of the positive-semidefinite ERI matrix. Rank-revealing: it keeps leaves while the residual-diagonal pivot exceedsthreshold(the numerical null space terminates it), so it stops at the true factorization rank.first_factorization="eigendecomposition"– symmetric eigendecomposition(pq|rs) = sum_t lambda_t V^t_pq V^t_rskeeping|lambda_t| > threshold. Required for indefinite inputs; the ERI is PSD so Cholesky is preferred.
max_num_leavescaps the leaf count. Second factorization: each symmetric leaf is eigendecomposed,L^t = U^t diag(gamma^t) (U^t)^T, giving the rank-one coreZ^t = outer(gamma^t, gamma^t)(scaled bylambda_tin the eigendecomposition case).second_factor_thresholdoptionally zeros smallgamma^t_k(importance-weighted, matching OpenFermion’s convention). On the eigendecomposition path the importance includes|lambda_t|, so both paths compare the same absolute quantity – the mode’s contribution to the core one-norm; on the Cholesky path the pivot scale is already carried by the leaf vector’s norm.Returns a
DoubleFactorizationwith NumPy arrays.
- cudaq_algorithms.double_factorization.compressed_double_factorization(eri, num_leaves, max_iterations=2000, tolerance=1e-10, regularization=0.0, inner_solver='lstsq', cg_tolerance=1e-10, cg_max_iterations=None, cg_warm_start=True, cg_optimization_tolerance=None, initial_generators=None, backend='auto')
Compressed double factorization (C-DF) by least-squares optimization.
Minimizes
O = 1/2 || eri - sum_t U^t Z^t (U^t)^T (congruence) ||_F^2over a fixed number of leaves. Uses the two-step scheme of arXiv:2104.08957: the leaf rotations are parameterized asU^t = exp(X^t)with antisymmetricX^tand optimized with L-BFGS (warm-started from X-DF), while the symmetric coresZ^tare solved exactly in closed form at each step.regularization(rho) enables RC-DF (arXiv:2212.07957, Eq. 17): the L2 penaltyrho * sum_{t,k,l} (Z^t_kl)^2is added to the objective and, crucially, folded into the inner core solve as a ridge term. It shrinks the cores – lowering the Hamiltonian one-normlambdaand the measurement variance – and conditions the inner system.rhois an absolute coefficient (its useful scale depends on the integral magnitude; the paper uses ~1e-6 to 1e-3).rho = 0reproduces plain C-DF.inner_solverselects how the cores are solved each step:"lstsq"(default) forms an explicit design matrix, while"cg"is the matrix-free conjugate-gradient solve (RC-DF Eqs. 25-30) that avoids then^4-row design matrix and scales to large orbital counts.cg_toleranceandcg_max_iterationscontrol the CG solve.cg_toleranceis relative to the projected right-hand-side norm||R||_F;cg_optimization_toleranceinherits the same meaning.For
inner_solver="cg"two accelerators cut the per-step CG cost without changing the final accuracy:cg_warm_start(defaultTrue) seeds each new L-BFGS evaluation’s CG from the previous evaluation’s cores – which move slowly between steps – while a re-evaluation of the same parameters (a rejected line-search point) reuses cores from a short LRU of recent solves so(f, g)stays a function ofx.cg_optimization_tolerance(defaultmax(cg_tolerance, 1e-6)) solves the in-loop systems only loosely (an inexact inner solve; the gradient need only be approximate by the envelope theorem) while the single final solve is tightened tocg_tolerance.L-BFGS-B status is stored on the returned
DoubleFactorization(optimizer_success,optimizer_nit,optimizer_grad_norm). ARuntimeWarningis issued if the optimizer does not converge, including when it hitsmax_iterations; the best factorization found is still returned. Whenn == 1, there are no free antisymmetric parameters, so each leaf rotation is the identity, the cores are the closed-form solution, andoptimizer_nitis 0.Returns a
DoubleFactorizationwith NumPy arrays.- Parameters:
- Return type:
- cudaq_algorithms.double_factorization.reconstruct_eri(factorization)
Reconstruct the chemist-notation ERI tensor from a factorization.
- Parameters:
factorization (DoubleFactorization)
- Return type:
- cudaq_algorithms.double_factorization.factorization_error(eri, factorization)
Frobenius norm of the ERI reconstruction residual.
- Parameters:
eri (ArrayLike)
factorization (DoubleFactorization)
- Return type:
- cudaq_algorithms.double_factorization.modified_one_body_integrals(one_body, eri)
Return the DF-corrected one-body matrix
kappa_pq = h_pq - 1/2 sum_r (pr|qr)(Eq. 3 of arXiv:2104.08957), used when assembling the full double-factorized Hamiltonian from the two-body factorization.- Parameters:
one_body (ArrayLike)
eri (ArrayLike)
- Return type:
- cudaq_algorithms.double_factorization.double_factorization_one_norm(factorization, one_body_eigenvalues, convention='lcu')
One-norm
lambdaof the double-factorized Hamiltonian (RC-DF, arXiv:2212.07957), used to assess factorization quality.convention="lcu"(Eq. 13) – the LCU / Pauli-rotation normsum_k |F_k| + sum_t (sum_{k<l} |Z^t_kl| + 1/4 sum_k |Z^t_kk|).convention="burg"– the qubitization norm in the standard von Burg/Lee form: with each core eigendecomposed asZ^t = sum_i lambda^t_i v^t_i (v^t_i)^T,sum_k |F_k| + 1/4 sum_t sum_i |lambda^t_i| (sum_k |v^t_ki|)^2. (A factorizationZ = W W^TleavesWfree up to a right orthogonal gauge, and the column-norm formula is not gauge invariant; the eigenfactor is the standard, gauge-fixed choice and reduces to RC-DF Eq. 15 / von Burg’s(1/4)(sum_k |gamma_k|)^2for rank-one cores.)one_body_eigenvaluesare the diagonal one-body (Fock-like) eigenvalues.- Parameters:
factorization (DoubleFactorization)
one_body_eigenvalues (ArrayLike)
convention (str)
- Return type:
- cudaq_algorithms.double_factorization.cupy_gpu_available()
Return True when CuPy can run a kernel on a visible GPU.
getDeviceCountonly talks to the driver, so a driver-only install (no NVRTC / CUDA toolkit) would otherwise look usable and then fail on the first compiled kernel. The tinyarangeforces that compile, and.sum()into a hostfloatwaits for the device so a fault that only appears at synchronization is not missed.- Return type:
- cudaq_algorithms.double_factorization.resolve_backend(backend='auto', problem_size=None, gpu_min_size=0)
Return
(array_module, name)for the requested backend."auto"selects CuPy when the problem is large enough to amortize GPU launch/sync overhead – i.e.problem_size(the orbital countn) is at leastgpu_min_size– and a GPU is available; otherwise NumPy. The size check is evaluated first so a below-threshold problem does not create a CUDA context. With noproblem_sizehint it keeps the legacy behavior: CuPy whenever a GPU is present."cupy"/"numpy"force the backend regardless of size.
State preparation
State-preparation kernels and operator pools (pure Python).
Same API as the former compiled bindings: the uccsd, uccgsd,
upccgsd, and ceo device kernels are @cudaq.kernel functions
composable from user kernels, and the excitation/pool helpers run on the
host with cudaq.spin algebra. hartree_fock /
hartree_fock_occupation prepare the reference determinant (closed
shell, or open shell via make_hartree_fock_occupation), and
fixed_parameter_ucc / hartree_fock_ucc_kernel apply an arbitrary
operator pool at fixed, non-variational amplitudes on top of it. The
Givens-rotation Slater-determinant kernels and schedule helpers
(_givens) follow the same split: composable device kernels plus
host-side planning; the same module holds the orbital-rotation schedule
and the spin-lifted Givens network that RotatedEncoding and the
double-factorized example conjugate encodings with.
Error-type convention: every input guard raises ValueError, and
get_uccsd_excitations and make_hartree_fock_occupation apply the
same (num_qubits, num_electrons, spin) checks with the same messages
(spin is 2*S_z, so num_electrons - spin must be even). Note
also that the CEO helpers take num_orbitals in spatial orbitals
(the pool acts on 2 * num_orbitals qubits), matching the compiled
API.
- cudaq_algorithms.stateprep.get_uccsd_excitations(num_qubits, num_electrons, spin=0)
Enumerate UCCSD excitations for the interleaved spin-orbital layout.
Returns
(singles_alpha, singles_beta, doubles_mixed, doubles_alpha, doubles_beta)as lists of index lists, in the C++ enumeration order (which fixes the parameter order of theuccsdkernel).
- cudaq_algorithms.stateprep.get_num_uccsd_parameters(num_qubits, num_electrons, spin=0)
Number of UCCSD ansatz parameters (one per excitation).
- cudaq_algorithms.stateprep.get_uccgsd_pauli_lists(num_qubits, only_singles=False, only_doubles=False)
UCCGSD pool as (pauli word groups, coefficient groups).
- cudaq_algorithms.stateprep.get_upccgsd_pauli_lists(num_qubits, only_doubles=False)
UpCCGSD pool as (pauli word groups, coefficient groups).
- cudaq_algorithms.stateprep.get_ceo_pauli_lists(num_orbitals)
CEO pool as (pauli word groups, coefficient groups).
- cudaq_algorithms.stateprep.get_fixed_parameter_ucc_pauli_lists(operator_pool, num_qubits, coefficient_tolerance=1e-12)
Any operator pool as (Pauli word groups, coefficient groups).
Like the pool-specific
get_*_pauli_listshelpers, but for an arbitrary pool (e.g.make_uccsd_operator_pool): one group per pool operator, in pool order, ready for thefixed_parameter_ucckernel. Terms with|coefficient| <= coefficient_toleranceare dropped (they would waste identity rotations); coefficients with an imaginary part above the tolerance are rejected —exp_pauliangles are real.
- cudaq_algorithms.stateprep.make_uccsd_operator_pool(num_qubits, num_electrons, spin=0)
One spin operator per UCCSD excitation, in excitation order.
- cudaq_algorithms.stateprep.make_uccgsd_operator_pool(num_qubits, only_singles=False, only_doubles=False)
Generalized singles and doubles over all qubit pairs/quadruples.
- cudaq_algorithms.stateprep.make_upccgsd_operator_pool(num_qubits, only_doubles=False)
Spin-preserving singles plus paired (same-spatial-orbital) doubles.
- cudaq_algorithms.stateprep.make_ceo_operator_pool(num_orbitals)
Coupled-exchange-operator pool (arXiv:2407.08696 conventions).
- cudaq_algorithms.stateprep.make_hartree_fock_occupation(num_qubits, num_electrons, spin=0)
Occupied spin-orbital indices of the Hartree-Fock reference.
spin == 0(closed shell): the contiguous set{0, ..., num_electrons - 1}.spin > 0(open shell): alpha electrons on even spin orbitals and beta on odd, matchingget_uccsd_excitationsso the determinant lines up with a fixed-parameter UCCSD pool built at the same spin (e.g. 4 electrons at spin 2 occupy{0, 1, 2, 4}, not{0, 1, 2, 3}).
- cudaq_algorithms.stateprep.validate_hartree_fock_occupation(num_qubits, occupied_orbitals)
Reject out-of-range, duplicate, or non-integral orbital indices.
- cudaq_algorithms.stateprep.validate_fixed_parameter_ucc(num_qubits, parameters, pauli_words, coefficients)
Validate grouped fixed-parameter UCC data against
num_qubits.Pauli words given as strings are checked for length and alphabet;
cudaq.pauli_wordobjects expose no accessor and are trusted (theget_*_pauli_listshelpers build them at the right width).
- cudaq_algorithms.stateprep.estimate_hartree_fock_resources(num_qubits, num_electrons, spin=0)
Resource estimate for the canonical Hartree-Fock reference.
- Return type:
- cudaq_algorithms.stateprep.estimate_hartree_fock_occupation_resources(num_qubits, occupied_orbitals)
Resource estimate for an explicit-occupation reference.
- Return type:
- cudaq_algorithms.stateprep.estimate_fixed_parameter_ucc_resources(num_qubits, pauli_words)
Resource estimate for a fixed-parameter UCC product.
- Return type:
- cudaq_algorithms.stateprep.hartree_fock_ucc_kernel(num_qubits, parameters, pauli_words, coefficients, *, num_electrons=None, spin=0, occupied_orbitals=None)
A
(qubits: qview)kernel: Hartree-Fock reference + UCC product.Provide exactly one of
num_electrons(with optionalspinfor an open-shell reference) or explicitoccupied_orbitals. The returned kernel expects anum_qubits-wide register in|0...0>and is directly injectable as astate_prepkernel (e.g. intoPauliLCU.encode_kernel). The grouped data is flattened into per-rotation angles before capture — nested lists cannot be captured by Python kernels.
- class cudaq_algorithms.stateprep.HartreeFockResourceEstimate(num_qubits, num_electrons, num_x_gates)
Bases:
objectCircuit cost of a Hartree-Fock reference preparation.
- class cudaq_algorithms.stateprep.FixedParameterUccResourceEstimate(num_qubits, num_excitations, num_pauli_rotations, max_pauli_rotations_per_excitation)
Bases:
objectCircuit cost of a fixed-parameter UCC product (Pauli rotations).
- class cudaq_algorithms.stateprep.GivensRotation(first_orbital, second_orbital, theta, phase=0.0)
Bases:
objectOne adjacent Givens rotation between two orbitals.
phaseis the relative phase applied after the rotation (exp(i * phase * n_second)); it is 0 for real schedules.
- class cudaq_algorithms.stateprep.GivensRotationSchedule(num_spin_orbitals, num_electrons, is_complex=False, rotations=<factory>, final_phases=<factory>)
Bases:
objectA Givens rotation sequence preparing a Slater determinant.
rotationsare in application order (the reverse of the elimination order).final_phasesholds one phase per electron, applied to the occupied qubits before the rotations; it is all-zero for real schedules.
- class cudaq_algorithms.stateprep.GivensResourceEstimate(num_spin_orbitals, num_electrons, num_givens_rotations, num_exp_pauli_calls, num_phase_rotations, two_qubit_gate_count_proxy, depth_proxy)
Bases:
objectLightweight circuit-cost summary for a Givens schedule.
num_spin_orbitalsandnum_electronsecho the schedule.num_exp_pauli_callscounts the two-qubitexp_paulirotations (two per Givens rotation);num_phase_rotationscounts the single-qubitrzgates of a complex preparation (one per rotation plus one per electron). The proxies are decomposition-independent upper bounds, not transpiled gate counts.
- cudaq_algorithms.stateprep.slater_determinant_kernel(schedule)
A
(qubits: qview)kernel preparing the schedule’s determinant.The returned kernel expects a
schedule.num_spin_orbitals-wide register in|0...0>and is directly injectable as astate_prepkernel (e.g. intoPauliLCU.encode_kernel). It dispatches onschedule.is_complexto theslater_determinant/complex_slater_determinantkernel path. The schedule is flattened into plain index/angle/phase arrays before capture — nested structures marshal as kernel arguments but cannot be closure-captured by Python kernels.- Parameters:
schedule (GivensRotationSchedule)
- cudaq_algorithms.stateprep.make_givens_rotation_schedule(orbital_coefficients, tolerance=1e-12)
Build the Givens rotation schedule preparing a Slater determinant.
orbital_coefficientsis a (num_spin_orbitals x num_electrons) matrix (numpy array or nested lists) whose orthonormal columns are the occupied orbitals. Real and complex inputs dispatch automatically (a complex dtype routes complex even when all values are real). For interleaved-spin systems the matrix rows must follow the package’s alpha (even) / beta (odd) spin-orbital ordering, so the prepared determinant composes withhartree_fock_occupationreferences and the UCCSD excitation conventions built at the same spin.- Return type:
- cudaq_algorithms.stateprep.validate_givens_rotation_schedule(schedule)
Validate a schedule against the state-preparation kernel contract.
make_givens_rotation_scheduleoutput always passes; this guards hand-built schedules (the kernels themselves cannot raise).- Parameters:
schedule (GivensRotationSchedule)
- cudaq_algorithms.stateprep.get_givens_rotation_indices(schedule)
Flattened (first, second) orbital pairs, two entries per rotation.
- Parameters:
schedule (GivensRotationSchedule)
- Return type:
- cudaq_algorithms.stateprep.get_givens_rotation_angles(schedule)
Rotation angles in application order.
- Parameters:
schedule (GivensRotationSchedule)
- Return type:
- cudaq_algorithms.stateprep.get_givens_rotation_phases(schedule)
Relative phases in application order (all zero for real schedules).
- Parameters:
schedule (GivensRotationSchedule)
- Return type:
- cudaq_algorithms.stateprep.estimate_givens_resources(schedule)
Resource estimate for preparing a schedule’s Slater determinant.
- Parameters:
schedule (GivensRotationSchedule)
- Return type:
- class cudaq_algorithms.stateprep.OrbitalRotationSchedule(num_modes, rotations, signs)
Bases:
objectAn adjacent Givens sweep of a real orthogonal matrix
V.rotationsare(mode, theta)plane rotations on modes(mode, mode + 1)in elimination order: applied to the rows ofVin turn they reduce it to a diagonal of signs,R_m ... R_1 V = diag(signs).signsis that residual, one+-1per mode: the networks built from the schedule reproduceV diag(signs), i.e.Vup to a sign per mode. That is immaterial for operators diagonal in the rotated modes (number operators);RotatedEncoding.from_orbital_rotationcancels it with aZon both spin orbitals of each mode with sign-1(Z_p a_p Z_p = -a_punder Jordan-Wigner), so its frame kernels realizeVexactly.
- cudaq_algorithms.stateprep.make_orbital_rotation_schedule(orthogonal, tolerance=1e-12)
Decompose a real orthogonal
n x nmatrix (target modes as columns) into adjacent plane rotations.Column by column, bottom-up, each rotation on rows
(p, p + 1)zeroes the lower entry — the orthogonal-matrix analogue ofmake_givens_rotation_schedule, acting on spatial modes rather than spin orbitals. RaisesValueErrorfor a complex, non-square or non-orthonormal input.- Parameters:
tolerance (float)
- Return type:
- cudaq_algorithms.stateprep.orbital_rotation_program(schedule, *, inverse)
Flattened
(modes, angles)lists forspatial_givens_network.With
inverse=Falsethe network realizesV diag(signs)on the one-particle space of each spin: fromR_m ... R_1 V = DfollowsV D = R_1^T ... R_m^T, so the sweep is applied reversed with negated angles (the last elimination first in circuit time). Withinverse=Trueit realizes the transpose,D V^T: the sweep in elimination order. A diagonalVhas no rotations; the lists are then the single zero-angle rotation[0], [0.0]— an identity on any register, including a single spatial mode — so that they are never empty when they cross the kernel boundary (cuda-quantum#4847).
Chemistry primitives
Fermionic basis changes
The factory and plan class are also available from the package root.
See Fermionic basis changes for phase conventions, encoding,
register placement, and explicit QROM composition.
GivensOperation, GivensStructure and GivensBasisChangeSchedule
here describe basis changes over spin-orbital modes, one per qubit. The
similarly named stateprep symbols above differ: GivensRotation and
GivensRotationSchedule (from make_givens_rotation_schedule)
prepare Slater determinants, and OrbitalRotationSchedule (from
make_orbital_rotation_schedule) rotates spatial modes in both spin
sectors.
Fermionic basis changes with classical or coherently supplied angles.
- class cudaq_algorithms.basis_change.AngleEncoding(width)
Bases:
objectUnsigned little-endian full-turn fixed point with nearest-even rounding.
word[k]has radian weight2*pi * 2**(k-width). Widths from one through 52 are supported for the double-valued host parameters; rounding is evaluated in double precision (seeencode()). This encoding applies to complete Givens gates and number phases; it does not authorize wrapping a standalone Pauli rotation at 2*pi. Encoded values are Python integers and do not allocate quantum words.- Parameters:
width (int)
- property bit_order
Word bit order, always
"little"(bit zero is least significant).
- decode(code)
Return the represented angle in [0, 2*pi), without measurement.
The result is
code * steprounded to a double.
- encode(angle)
Round a finite real radian angle to an unsigned full-turn code.
The angle is first converted to an IEEE double, so exact integers beyond
2**53,Fractionand extended-precision values are rounded before reduction. The quotient bystepis also rounded to a double before nearest-even rounding: from about 43 bits, and for some floating-point near-ties at smaller widths, a code can be one step from the exact nearest code, less than about 1e-15 rad beyond half a step. Exact half-step ties within one signed turn resolve to even; beyond one turn, ties follow the trigonometric argument reduction.
- property step
Radians per code unit,
2*pi / 2**width.
- property weights
Radian weight of each word bit, least significant first.
- class cudaq_algorithms.basis_change.FermionBasisChange(schedule, angle_encoding=None, parameter_registers=None)
Bases:
objectImmutable plan acting on an existing system and optional angle words.
Construct plans with
fermion_basis_change(). Kernels accept one qview spanning at leastnum_qubitsqubits (num_qubits + 1forcontrolled_kernel()). CUDA-Q does not bounds-check views, so a narrower view silently addresses the following qubits of the parent allocation. System modes followstructure.mode_map; optional words followparameter_registers. The caller owns their preparation and uncomputation. No QROM or workspace is allocated here.controlled_kernel()puts the enable only on the Rz and R1 rotations;cudaq.controlofkernel()puts it on every emitted gate, including the Clifford and parity scaffold. Theadjointflag ofcontrolled_kernel()must be a Pythonbool.- Parameters:
schedule (GivensBasisChangeSchedule)
angle_encoding (AngleEncoding | None)
- adjoint_kernel()
Return the inverse, including all exact mode phases.
- property angle_bits
Bits per parameter word, or None for a classical plan.
- angle_encoding: AngleEncoding | None = None
Word encoding of a programmable plan, or None for a classical plan.
- controlled_kernel(*, adjoint=False)
Return a kernel with enable at index zero and the base register after it.
Allocate
num_qubits + 1qubits. Every base index shifts by one; the inactive enable branch is exact identity on all operands. The enable controls only the Rz and R1 rotations, since each Clifford and parity scaffold cancels around its rotation.adjointmust be a Pythonbool.
- property encoded_words
Host integer codes in parameter order, or None without a reference.
- property is_programmable
True when caller-owned quantum words supply the executed angles.
- kernel()
Return a kernel applying the transformation to a combined qview.
- property num_qubits
Combined register span, excluding lookup and external controls.
- parameter_registers: tuple[tuple[int, ...], ...] | None = None
Qubit indices of each parameter word in slot order; empty if classical.
- property quantization_error
Circular parameter-error report; excludes host and synthesis error.
Bounds hold in exact arithmetic for the supplied values; they are evaluated in double precision from rounded decodes, so they are not certified below about 1e-15 rad per tape occurrence.
- property quantization_error_bound
Conservative Fock-space bound from
quantization_error, or None.
- property represented_parameters
Decoded radian values of encoded_words, or None when unavailable.
- property structure
Static Givens structure of the schedule, including
mode_map.
- schedule: GivensBasisChangeSchedule
Compiled host schedule with its structure and optional angle values.
- cudaq_algorithms.basis_change.fermion_basis_change(basis=None, *, structure=None, programmable=False, angle_bits=None, parameter_registers=None, tolerance=1e-12)
Plan a full or selected-column fermionic transformation.
basisis a unitary square matrix or normalized vector/column of at least two modes, or aGivensBasisChangeSchedule. Columns are transformed modes; the operation preserves vacuum and all required determinant phases. It acts on an existing state and does not initialize occupations. Each index labels one fermionic mode on its own qubit, so a2**nby2**nqubit unitary is interpreted as2**nmodes on2**nqubits; this is not arbitrary qubit-unitary synthesis.programmablemust be a Pythonbool. Withprogrammable=True, requireangle_bitsfrom 1 through 52. Every slot consumes an unsigned little-endian quantum word encoding a full-turn angle. Supplied numerical values provide host reference data and encoded table entries; the loaded words determine execution. Structure-only programmable plans have no host numerical reference.Words default to disjoint contiguous slices after the physical system span, including spectators. Explicit words are any distinct qubit indices outside the system span, listed least-significant bit first, that do not overlap other words. Plan kernels need a view spanning at least
num_qubitsqubits (num_qubits + 1forcontrolled_kernel); CUDA-Q does not bounds-check views, so a narrower view silently addresses the following qubits of the parent allocation.controlled_kernelcontrols only the Rz and R1 rotations;cudaq.controlofkernel()controls every emitted gate. The caller composes QROM or arithmetic explicitly.tolerance(0 < tolerance < 1) validates input unitarity or normalization; it is not a quantization or synthesis budget. Inexact input within tolerance compiles to the unitary its angles define, so checkschedule.reconstruction_errorwhen loosening it. Reconstruction and quantization diagnostics are exposed separately by the returned plan.
- class cudaq_algorithms.basis_change.GivensStructure(num_modes, kind, mode_map=None, reference_mode=None)
Bases:
objectStatic topology and parameter schema, independent of numerical values.
Full schemas start with
mdiagonal phases, followed by atheta, phipair per chronological mixing slot. Partial schemas containm-1mixing angles followed bymoutput number phases. All slots remain present for zero angles and real input data.num_modesmust be at least two: a single mode has no mixing and admits only a number phase, which callers apply directly withr1.mode_mapis an ordered sequence (list, tuple, range or one-dimensional array) of distinct physical qubit indices, one per logical mode, each from 0 to2**31 - 1.- Parameters:
- classmethod full(num_modes, *, mode_map=None)
Construct the fixed adjacent QR topology for a square unitary.
- property mode_pairs
Logical mixing pairs in chronological application order.
- property num_parameters
m**2full,2*m - 1partial.- Type:
Real parameter slot count
- property num_system_qubits
Minimum physical register width containing every mapped mode.
- property operations
Exact number phases and real mixing gates in chronological order.
- property parameter_names
Stable names in the numerical parameter-vector order.
- property parameter_schema
Immutable ordered parameter names; every parameter is a real angle.
- classmethod partial(num_modes, *, mode_map=None, reference_mode=0)
Construct a magnitude-distribution chain rooted at reference_mode.
- class cudaq_algorithms.basis_change.GivensOperation(kind, first, second, parameter_index, scale=1.0)
Bases:
objectOne chronological logical operation with an indexed real parameter.
kindis"phase", the number phaseexp(i*angle*n)on modefirst, or"givens", the real rotation[[c, -s], [s, c]]on the mode pair(first, second)withc, s = cos(angle), sin(angle).firstandsecondare logical mode indices; the physical qubit of modefirstisstructure.mode_map[first].secondisNonefor a phase.parameter_indexindexes the schedule parameters, and the applied angle isscale * parameters[parameter_index]:scale = -1marks the leadingP_b(-phi)of a complex mixing block.
- class cudaq_algorithms.basis_change.GivensBasisChangeSchedule(structure, parameters=None, reconstruction_error=None)
Bases:
objectImmutable static tape with optional numerical angle values.
reconstruction_erroris the maximum absolute orbital-matrix entry error (the specified column only for partial input), a finite nonnegative diagnostic. It isNonefor structure-only plans and takes no part in equality or hashing, which depend only onstructureandparameters. No input or output ndarray is retained.GivensBasisChangeSchedule(schedule.structure)is the structure-only form of any schedule.dataclasses.replace(schedule, parameters=None)raises for a schedule with areconstruction_errorunlessreconstruction_error=Noneis also passed, and replacing the parameters keeps the old residual, so recompile instead when the angles change.- Parameters:
structure (GivensStructure)
reconstruction_error (float | None)
- property num_parameters
Number of real parameter slots in the schedule.
- property operations
Chronological
GivensOperationtape of the structure.
- orbital_matrix(parameters=None)
Reconstruct the complete orbital unitary using optional overrides.
A partial plan specifies only its reference column; the other columns are a deterministic unitary completion. The returned array is fresh. Structure-only plans require an explicit parameter vector.
- property parameter_names
Stable names in the numerical parameter-vector order.
- parameters: tuple[float, ...] | None = None
Host angles in radians in parameter order, or None if structure-only.
- reconstruction_error: float | None = None
Maximum orbital-matrix entry residual, or None if structure-only.
- structure: GivensStructure
Static topology and parameter schema of the tape.
- cudaq_algorithms.basis_change.compile_givens_basis_change(basis=None, *, structure=None, tolerance=1e-12)
Compile a square unitary or a normalized orbital column on the host.
basismay have shape(m,m),(m,)or(m,1)withm >= 2.basis=Nonerequires a structure and allocates the same tape and parameter schema without numerical values. Validation uses the absolutetolerance, with0 < tolerance < 1, for the column norm or maximum entry of U†U-I, and rejects inputs outside it. Accepted input is compiled from its elimination angles, so an inexact input is replaced by the unitary (or unit column) those angles define.reconstruction_errorreports the maximum entry discrepancy; check it when looseningtolerance.
- class cudaq_algorithms.basis_change.FermionBasisChangeErrorEstimate(parameter_deltas, parameter_error_sum, synthesis_error_bound, basis_change_error_bound, reflection_error_bound)
Bases:
objectSpectral-norm bounds for a represented basis change and reflection.
parameter_error_sumincludes every tape occurrence, so a full-plan relative phase contributes twice.synthesis_error_boundis a supplied bound for the complete represented basis-change circuit, not per gate.basis_change_error_boundclips their sum at two. The reflection bound clips twice their sum at two, for conjugation of any norm-one reflection. No assumption about how represented angles were encoded is required. The bounds hold in exact arithmetic for the supplied values. They are evaluated in double precision, and represented parameters decoded from words are rounded, so they are not certified below about 1e-15 rad per tape occurrence.
- class cudaq_algorithms.basis_change.FermionBasisChangeResourceEstimate(num_modes, num_parameters, num_system_qubits, num_program_qubits, num_workspace_qubits, num_givens_rotations, num_number_phases, num_elementary_rotations, num_bit_controlled_rotations, num_parity_cnots, num_hadamards, num_s_phase_gates, num_clifford_basis_changes)
Bases:
objectStatic resources for the complete tape, including zero-valued slots.
Number phases and real mixing gates are abstract algorithm operations. Each mixing operation uses two elementary Pauli rotations, with four parity CNOTs per physical mode separation and twelve Clifford basis changes (eight H and four S/S-dagger). Number phases are one elementary rotation each and require no parity ladder.
Counts describe the uncontrolled tape.
FermionBasisChange.controlled_kernelkeeps every Clifford and parity CNOT and adds the enable to each rotation only: each Rz becomes a controlled Rz and each R1 a controlled R1 (bit-controlled rotations become doubly controlled).cudaq.controlofkernel()instead puts the enable on every emitted gate: each H becomes a controlled H, each S or S-dagger a controlled S or S-dagger and each parity CNOT a Toffoli as well.An optional angle width counts bit-controlled rotations and defaults to keeping every parameter word resident. A caller-supplied program width overrides that reported qubit count only; the kernels keep every word resident. Address, QROM lookup/unlookup, and synthesis resources are excluded.
- Parameters:
num_modes (int)
num_parameters (int)
num_system_qubits (int)
num_program_qubits (int)
num_workspace_qubits (int)
num_givens_rotations (int)
num_number_phases (int)
num_elementary_rotations (int)
num_bit_controlled_rotations (int)
num_parity_cnots (int)
num_hadamards (int)
num_s_phase_gates (int)
num_clifford_basis_changes (int)
- cudaq_algorithms.basis_change.estimate_fermion_basis_change_error(schedule, represented_parameters, *, synthesis_error_bound=0.0)
Bound spectral error from supplied represented real angle values.
A real Givens generator and an exact number-phase generator each have spectral norm one, hence a gate perturbation is bounded by the absolute angle difference. Telescoping unitary products sums those differences. This remains valid on the full fermionic Fock space and under arbitrary physical mode embeddings. The optional synthesis bound is added once for the complete basis-change implementation; when each Rz and R1 is synthesized to spectral error
epsincluding global phase, passnum_elementary_rotations * epsfromestimate_fermion_basis_change_resources()(num_bit_controlled_rotations * epsfor a programmable plan). Conjugating a reflection incurs at most twice that total error.Original numerical schedule values are required. Parameter differences are shortest signed circular deltas modulo 2*pi for the complete Givens gates and number phases. No binary encoding convention is assumed. Host reconstruction discrepancies are excluded. The bounds hold in exact arithmetic for the supplied values; they are evaluated in double precision, and represented parameters decoded from words are rounded, so they are not certified below about 1e-15 rad per tape occurrence.
- cudaq_algorithms.basis_change.estimate_fermion_basis_change_resources(schedule, *, angle_bits=None, num_program_qubits=None)
Count static algorithm operations and physical parity-ladder costs.
scheduleis aGivensBasisChangeScheduleor aFermionBasisChangeplan. A plan supplies its own angle width and program-qubit count,num_qubits - num_system_qubits, which includes gaps in explicitparameter_registers;angle_bitsandnum_program_qubitsmust then be omitted.For physical endpoint separation
d, each of the two mixing Pauli strings has weightd+1. A compute/uncompute parity ladder therefore has2*dCNOTs per string, or4*dfor the mixing operation. Every zero angle remains present, matching a programmable consumer’s tape. The algorithm needs no workspace beyond the system and caller-owned program register; internal synthesis ancillas are not estimated.angle_bitsis an integer from 1 through 52. If given, each elementary rotation uses that many bit-controlled rotations; without it, their count is zero.num_program_qubitsdefaults to all parameter words resident (num_parameters * angle_bits), or zero without a width. An explicit count overrides that default; with a width it must be at leastangle_bits(one word). The override changes only this report; the kernels keep every word resident. QROM address, lookup and unlookup are excluded.Counts describe the uncontrolled tape; see
FermionBasisChangeResourceEstimatefor the controlled costs.
Simulation utilities
Simulation-only helpers.
Everything here depends on statevector access (cudaq.get_state /
postselection slicing), which only exists on simulators. The module ships
with the package as a clearly-labeled companion, but it is not part of the
hardware-shaped API: the library classes (encodings, kernel factories,
observables, Walk.moment via cudaq.observe) never execute
get_state. Per-algorithm shortcuts live in sub-namespaces: qpe
for PhaseEstimation.
- cudaq_algorithms.sim_utils.state_from(ket, num_qubits=None)
Build a cudaq.State from array data at the current target’s precision.
fp32 simulators (e.g. the default
nvidiatarget) reject complex128 input (“[sim-state] invalid data precision”); cudaq.complex() reports the dtype the active target expects.num_qubitspins the register the state is meant for: a kernel that allocatescudaq.qvector(state)takes whatever width the data implies, so an oversized ket silently widens the system register and an undersized one fails inside the simulator with an opaque error. Withnum_qubitsgiven, a ket of any other length raisesValueErrorhere instead. The kernel factories’ state-taking circuits (encode_kernel,walk_kernel,Walk.kernel, …) expect exactly2^num_systemamplitudes.- Parameters:
num_qubits (int | None)
- Return type:
State
- cudaq_algorithms.sim_utils.good_subspace(encoding, state)
Postselect the all-zero-ancilla block of a simulated statevector.
The kernel factories allocate the system register first, so with CUDA-Q’s little-endian statevector order (q[0] = least-significant bit) the good subspace is the first contiguous block of 2**num_system amplitudes.
- Parameters:
encoding (PauliLCU)
state (ArrayLike)
- Return type:
NDArray[np.complex128]
- cudaq_algorithms.sim_utils.action(encoding, ket)
Return (H/alpha)|ket> by simulating the encoding and postselecting.
Multiply by
encoding.alphato recover H|ket>.- Parameters:
encoding (PauliLCU)
ket (ArrayLike)
- Return type:
NDArray[np.complex128]
- cudaq_algorithms.sim_utils.transform(transformer, ket, sequence, convention=None)
Return the good-subspace state after a QSVT sequence.
For an eigenstate of H with eigenvalue lambda the result is
p(lambda / alpha)times the input, wherepis the polynomial the phase sequence implements.- Parameters:
transformer (QSVT)
ket (ArrayLike)
sequence (PhaseSequence | Iterable[float])
convention (str | None)
- Return type:
NDArray[np.complex128]
- cudaq_algorithms.sim_utils.evolve(evolution, ket, time, steps=1, order=2, include_identity_phase=True)
Simulate a Trotter evolution on
ket; return the evolved statevector.Unlike the circuit primitive, this can reintroduce the identity phase
exp(-i * identity_coefficient * time)(on by default), so the result approximates the fullexp(-i H t)|ket>.Delegates to
Trotter.state_kernel— the same validation (finite time, positive integral steps, order in {1, 2, 4}) and marshaling asTrotter.kernel, raisingValueErrorfor invalid parameters instead of silently returning an unevolved state.
- cudaq_algorithms.sim_utils.run_on_large_stack(function, /, *args, stack_bytes=536870912, **kwargs)
Call
function(*args, **kwargs)on a worker thread with astack_bytesstack and return its result (exceptions propagate).A simulated kernel runs on the calling thread’s stack. When a kernel applies a sub-kernel that captures Python lists inside a loop, the compiler re-materializes those lists on the stack on every iteration and releases them only when the kernel returns, so the stack in use grows with the trip count: about 1 kB per controlled walk step for a
PauliLCU, which exceeds the default 8 MiB thread stack after a few thousand steps and ends the process with a segmentation fault. Running the executor on a thread with a large stack keeps such circuits within bounds;phase_probabilitiesdoes this for the2^num_bits - 1walk steps of a phase-estimation circuit, and a circuit fromPhaseEstimation.kernelthat you sample on a simulator needs the same:counts = sim_utils.run_on_large_stack(cudaq.sample, circuit, shots_count=1000)
If the platform refuses the requested stack size the call runs on the current thread.
Statevector shortcuts for PhaseEstimation (simulators only).
The class builds circuits and decodes readouts; these helpers execute
its measurement-free circuit with cudaq.get_state on a large-stack
worker and hand the exact phase-register marginal to its decoders.
- cudaq_algorithms.sim_utils.qpe.phase_probabilities(estimator, num_bits, *, ket=None, state_prep=None)
The exact phase-register marginal of a phase-estimation circuit:
2^num_bitsprobabilities, entryjfor readoutj, summing to 1 (no shot noise).Simulates
estimator.kernel(num_bits, state_prep=...)withcudaq.get_stateon a large-stack worker (sim_utils.run_on_large_stack) and traces out the system and ancilla registers. Provide exactly one ofket(array-like /cudaq.State) orstate_prep. Decode withPhaseEstimation.energies_from_probabilities, or callenergies.- Parameters:
estimator (PhaseEstimation)
num_bits (int)
- Return type:
NDArray[np.float64]
- cudaq_algorithms.sim_utils.qpe.energies(estimator, num_bits, *, ket=None, state_prep=None, top=None)
Ranked
(energy, probability)pairs from the simulated phase-estimation circuit:phase_probabilitiesdecoded byPhaseEstimation.energies_from_probabilities(mirror readouts folded, most probable first,topkeeps the leading entries).
- cudaq_algorithms.common_kernels.state_from(ket, num_qubits=None)
Build a cudaq.State from array data at the current target’s precision.
fp32 simulators (e.g. the default
nvidiatarget) reject complex128 input (“[sim-state] invalid data precision”); cudaq.complex() reports the dtype the active target expects.num_qubitspins the register the state is meant for: a kernel that allocatescudaq.qvector(state)takes whatever width the data implies, so an oversized ket silently widens the system register and an undersized one fails inside the simulator with an opaque error. Withnum_qubitsgiven, a ket of any other length raisesValueErrorhere instead. The kernel factories’ state-taking circuits (encode_kernel,walk_kernel,Walk.kernel, …) expect exactly2^num_systemamplitudes.- Parameters:
num_qubits (int | None)
- Return type:
State