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: object

Block encoding of H / alpha via a linear combination of Pauli strings.

Two backends build the same PREPARE-dagger . SELECT . PREPARE encoding. backend="exact" (the default) is an exact multiplexed-Ry amplitude PREPARE with an address-indexed controlled-Pauli SELECT on max(1, ceil(log2(num_terms))) ancillas; single-term (and identity-only) Hamiltonians get one idle ancilla, so every encoding works uniformly with Walk/QSVT and no flattened kernel argument is ever empty. backend="alias" delegates to LCUBlockEncoding: 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 + 3 qubits for m index bits) and a rounding of the term weights to mu bits (within alpha * discretization_bound each; alpha stays the exact one-norm). Both backends serve every consumer, including Walk.moment odd orders through select_observable; on the alias backend the even orders’ reflection observable has 2^num_ancilla terms, practical only at small mu.

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) for backend="alias"; not accepted with "exact", which has no alias table.

property backend: str

"exact" or "alias" (see the class docstring).

property mu: int | None

Alias-table keep precision in bits; None on the exact backend.

property alpha: float

LCU normalization (1-norm of retained coefficients).

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 from state and the ancilla register (in |0...0>) after it. With state_prep (a (qubits: qview) kernel): a zero-argument kernel that allocates the system register in |0...0>, runs state_prep on 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: a cudaq.State-taking kernel, or a zero-argument kernel when state_prep is 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_i as 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 LCUBlockEncoding index register alone (the first num_index ancillas, 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: object

Block encoding of H / alpha for H = sum_k c_k U_k.

Satisfies the full BlockEncoding protocol. select_observable (the odd-Chebyshev-moment observable Walk.moment uses) is derived from the bodies when every term is a Pauli word ("x", "y", "z" and ("sign",) ops only) and raises NotImplementedError for bodies using the extended vocabulary. Even Walk.moment orders use the geometry-only reflection observable, whose 2^num_ancilla Pauli terms are practical only at small mu; dense Chebyshev data is also available through walk_kernel powers.

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 raises ValueError rather than failing inside a kernel.

Parameters:
  • num_system (int) – System-register width in qubits (the U_k act on system[0:num_system]).

  • weights (Sequence[float]) – The term weights |c_k|: non-negative and finite, with a positive sum. Signs c_k < 0 are 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 involution U_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 num_index: int

Term-index register width (the block ancillas proper).

property num_garbage: int

PREPARE garbage width (entangled between the sandwich halves).

property num_select_work: int

Clean SELECT work scratch (|0> at reflection points).

property weights: tuple

The term weights |c_k|, one per term in term order (the first num_terms PREPARE bins). discretized_weights has one entry per bin; the bins past num_terms are 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_probabilities sum to 1 by construction, so sum(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 from state and the ancilla register (in |0...0>) after it. With state_prep (a (qubits: qview) kernel): a zero-argument kernel that allocates the system register in |0...0>, runs state_prep on it, then applies the encoding.

Parameters:

state_prep (Kernel | None)

Return type:

Kernel

walk_kernel(power=1, state_prep=None)

A kernel applying power qubitization walk steps.

PREPARE, power walk steps, PREPARE-dagger — the same (R U_A)^power that Walk.kernel composes — so the all-zero-ancilla block of the result is T_power(-H/alpha) applied to the input state. Input modes as in encode_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, as PauliLCU’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_k as a cudaq.SpinOperator: the odd-Chebyshev-moment observable.

Measured after prepare_kernel and p walk steps with no UNPREPARE (what Walk.moment does for odd orders), its expectation is <T_{2p+1}(H/alpha)>. It acts on the index register (qubits num_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); raises NotImplementedError for bodies using the extended vocabulary, whose term unitaries have no spin-operator form.

Return type:

Any

class cudaq_algorithms.block_encoding.BlockEncoding(*args, **kwargs)

Bases: Protocol

A zero-flagged block encoding U_A with <0|_anc U_A |0>_anc = H / alpha.

PauliLCU, LCUBlockEncoding and SparseOracleEncoding are the provided implementations; double-factorized or other custom encodings plug in by satisfying the same surface.

property num_system: int

Number of system qubits the encoded operator acts on.

property num_ancilla: int

Number of ancilla (signal) qubits flagging the encoded block.

Consumers (Walk, QSVT, the walk observables) require num_ancilla >= 1: the walk’s -H/alpha sign comes from a reflection about the ancilla zero state, which is a no-op on an empty register. PauliLCU normalizes single-term inputs to one idle ancilla to satisfy this uniformly.

property alpha: float

the encoded block is H / alpha.

Type:

The block-encoding normalization

prepare_kernel()

(ancilla: qview): PREPARE the ancilla superposition.

Return type:

Any

unprepare_kernel()

(ancilla: qview): PREPARE dagger.

Return type:

Any

apply_kernel()

(ancilla: qview, system: qview): the full block encoding U_A.

U_A must be Hermitian, hence an involution (U_A^2 = I), as PREPARE-dagger SELECT PREPARE with an involutory SELECT is. QSVT (which applies U_A for both walk directions) and SumEncoding (whose SELECT is built from its operands’ U_A) rely on it.

Return type:

Any

controlled_apply_kernel()

(control_and_ancilla: qview, system: qview): U_A controlled by qubit 0 of the combined register.

Return type:

Any

walk_step_kernel()

(ancilla: qview, system: qview): one qubitization walk step W (block encodes -H/alpha).

Return type:

Any

adjoint_walk_step_kernel()

(ancilla: qview, system: qview): one adjoint walk step W†.

Return type:

Any

controlled_walk_step_kernel()

(control_and_ancilla: qview, system: qview): controlled W.

Return type:

Any

controlled_adjoint_walk_step_kernel()

(control_and_ancilla: qview, system: qview): controlled W†.

Return type:

Any

select_observable()

The odd-moment observable as a cudaq.SpinOperator.

Measured after PREPARE and p walk 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† SELECT with real prepare_kernel / unprepare_kernel), as the provided encodings do. The construction is encoding-specific (for an LCU it is sum_i sign_i |i><i|_anc x P_i); encodings that cannot supply it raise NotImplementedError, and Walk.moment then serves even orders only. The even-moment reflection observable 2|0..0><0..0| - I needs only the register geometry, so Walk derives it without an encoding hook.

Return type:

Any

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:

SumEncoding

Encodes sum_i c_i H_i from encodings of the H_i with real coefficients c_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.

RotatedEncoding

Encodes V H V^dagger from an encoding of H and a pair of system-side kernels implementing V^dagger (enter) and V (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_rotation builds the kernels from the stateprep orbital-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: object

Block encoding of V H V^dagger from an encoding of H.

Use from_orbital_rotation() for a real orbital rotation in the interleaved spin-orbital layout.

Parameters:
  • inner (BlockEncoding) – A BlockEncoding of H.

  • enter (Kernel) – (system: cudaq.qview) kernels implementing V^dagger and V on the system register. Every (ancilla, system) kernel of inner is wrapped as enter; inner; exit; the ancilla-only PREPARE hooks pass through, and alpha and the ancilla count are unchanged.

  • exit (Kernel) – (system: cudaq.qview) kernels implementing V^dagger and V on the system register. Every (ancilla, system) kernel of inner is wrapped as enter; inner; exit; the ancilla-only PREPARE hooks pass through, and alpha and the ancilla count are unchanged.

classmethod from_orbital_rotation(inner, orthogonal)

Rotate by a real orthogonal one-particle matrix V.

orthogonal is n x n with the target modes as columns and 2 n == inner.num_system (spin orbital 2p is mode p spin up, 2p + 1 spin down). The rotation is compiled with the stateprep orbital-rotation schedule to its adjacent Givens network on both spin sectors (spatial_givens_network). The Givens sweep alone realizes V D for a diagonal of signs D (mode_signs reports it); a Z on both spin orbitals of every mode with sign -1 cancels D (Z_p a_p Z_p = -a_p under Jordan-Wigner), so exit realizes exactly V and enter exactly V^T, for any inner encoding.

Parameters:

inner (BlockEncoding)

Return type:

RotatedEncoding

property num_rotations: int | None

Adjacent Givens rotations per spin sector in a from_orbital_rotation network, applied on entry and again on exit; None for user-supplied kernels.

property mode_signs: tuple[int, ...] | None

The per-mode signs D the Givens sweep of a from_orbital_rotation leaves (its network alone realizes V D); the constructor cancels them with Z gates, so the frame kernels realize V exactly. None for user-supplied kernels.

encode_kernel(state_prep=None)

A kernel applying the full rotated block encoding (PauliLCU shape; see SumEncoding.encode_kernel).

Parameters:

state_prep (Kernel | None)

Return type:

Kernel

class cudaq_algorithms.combinators.SumEncoding(terms)

Bases: object

Block encoding of sum_i c_i H_i from encodings of the H_i.

Ancilla layout is [slot (num_slots qubits)][flag][shared pool] with num_slots = max(1, ceil(log2 K)) and a pool as wide as the widest summand, so num_ancilla = num_slots + 1 + max_i num_ancilla_i. PREPARE puts amplitude sqrt(|c_i| alpha_i / alpha) on slot |i> (the same binary rotation tree PauliLCU uses). For each summand, SELECT toggles flag ^= (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_kernel must be Hermitian on its entire ancilla and system register, hence an involution (U_A^2 = I). Its controlled_apply_kernel must implement exact controlled-U_A for arbitrary incoming ancilla states. Then each signed operand sign(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 and BlockEncoding operands acting on the same number of system qubits. K >= 1.

property num_ancilla: int

num_slots + 1 (flag) + shared pool.

property num_slots: int

Width of the slot register selecting the summand.

property alpha: float

sum_i |c_i| alpha_i.

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 (PauliLCU shape).

Without state_prep: (state: cudaq.State), allocating the system register from state and the ancillas after it. With state_prep (a (qubits: qview) kernel): zero-argument, preparing the system register with state_prep first.

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.sparse matrix, or a (rows, cols, vals) tuple of parallel integer-indexed sequences. Must be symmetric with a non-negative diagonal unless dilate=True.

  • value_bits (int) – Fixed-point angle bits of the value oracle (quantization bound h * (pi/2) * 2^-value_bits per element).

  • dim (int | None) – Matrix dimension — required with triples, optional (checked) otherwise.

  • dilate (bool) – True encodes the Hermitian dilation [[0, A], [A^T, 0]] of a general square A (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 * dim QROM entries); above it this raises pointing at hand-written oracles.

Returns:

  • SparseOracleEncoding with the pricing report attached as

  • encoding.report.

Return type:

SparseOracleEncoding

class cudaq_algorithms.sparse.SparseOracleEncoding(oracles, num_system)

Bases: object

Block encoding of H / (d_padded * h) from sparse-access oracles.

Parameters:
  • oracles (OracleKernels) – The OracleKernels bundle (contract in the module docstring).

  • num_system (int) – System register width n (the encoded matrix is 2^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_block_ancilla: int

Slot + flag pair + dual register (the entangled ancillas).

property num_scratch: int

Value/sign/upper/work qubits, deterministically |0> outside the oracle-load window inside U_A.

property d: int

Requested sparsity (number of structure slots).

property d_padded: int

Slots after power-of-two padding (what alpha honestly pays).

property h: float

Value normalization (h >= max |H_ij|).

property alpha: float

alpha = d_padded * h.

Type:

Honest padded normalization

encode_kernel(state_prep=None)

A kernel applying the full block encoding.

Without state_prep: a @cudaq.kernel(state) allocating the system register from state and the ancilla register (in |0...0>) after it; the state must hold exactly 2^num_system amplitudes (state_from(ket, num_qubits=encoding.num_system) checks that, which the kernel boundary cannot). With state_prep (a (qubits: qview) kernel): a zero-argument kernel that allocates the system register in |0...0>, runs state_prep on it, then applies the encoding.

Parameters:

state_prep (Kernel | None)

Return type:

Kernel

walk_kernel(power=1, state_prep=None)

A kernel applying power qubitization 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 (see prepare_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

select_observable()

Unavailable for this encoding (LCU-specific hook).

Return type:

Any

classmethod from_general_oracles(oracles, num_system)

Encode the Hermitian dilation [[0, A], [A^T, 0]] of A.

oracles describes a general real 2^n x 2^n matrix A (per-slot column permutations c(s, .) with explicit inverses, and the value convention of the module docstring with o_val writing only the angle and sign bits — the dilation supplies the upper bit itself, since row < column reduces to the halves bit). The dilation places the oracle kernels under cudaq.control, so they must be flat (no sub-kernel calls, as banded_oracles builds them); qrom_oracles bundles, which call unary-iteration sub-kernels, are not accepted here. slot_flip is 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 + 1 system qubits (the halves bit is the most significant) and encodes [[0, A], [A^T, 0]] / alpha with the same d, h, value_bits and honest padded alpha as a direct encoding of A would report.

Parameters:
Return type:

SparseOracleEncoding

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: object

The user-supplied oracle bundle (see the module docstring).

Parameters:
o_loc, o_loc_adj, o_val, o_val_adj

@cudaq.kernel device kernels with the documented signatures; every inverse is explicit (cudaq.adjoint is off-limits). o_val loads only the entries assigned to a slot; a mapping that merely completes a slot’s permutation loads zero.

d

Number of structure slots (>= 1); padded to 2^ceil(log2 d).

Type:

int

h

Value normalization, h >= max |H_ij| (> 0).

Type:

float

value_bits

Fixed-point bits of the angle register (>= 1).

Type:

int

num_work

Work qubits the oracles need (entering and returned |0>).

Type:

int

slot_flip

Reverse-slot involution over the padded slot range, or None if unavailable (then only from_general_oracles applies).

Type:

list[int] | None

num_system

System width the kernels were built for, or None if the kernels are width-agnostic; the encoding rejects a mismatch.

Type:

int | None

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); band o holds the elements H[j + o, j] for all in-range j (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.

  • band_values (Sequence[float]) – One real value per offset.

  • num_system (int) – System register width n (the matrix is 2^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 satisfy h >= 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; False produces a dilation-only bundle (slot_flip=None).

Return type:

OracleKernels

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.sparse matrix, 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 satisfy h >= max |H_ij|.

  • dim (int | None) – Matrix dimension — required with triples, optional (checked) otherwise.

Return type:

OracleKernels

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 to 2^value_bits - 1 (the |value| = h edge 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.

Parameters:
Return type:

int

Qubitization and QSVT

class cudaq_algorithms.qubitization.Walk(encoding)

Bases: object

Qubitization walk over a block encoding.

Generic over the BlockEncoding protocol: encoding-specific circuits and the odd-moment observable are delegated to the injected encoding (PauliLCU and LCUBlockEncoding are the provided implementations).

Provides walk/adjoint-walk kernel factories and Chebyshev-moment measurement in the QEL even/odd convention. Requires num_ancilla >= 1 (PauliLCU always 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_prep the returned kernel takes one cudaq.State argument (the input state as data — the simulation-friendly form). With state_prep — a kernel with signature (qubits: cudaq.qview) — the returned kernel takes no arguments: it allocates the system register in |0...0>, runs state_prep on it, and applies the walks. state_prep must act only on that register, whose width is num_system (a documented contract; not verifiable at factory time).

Parameters:
  • power (int)

  • uncompute (bool)

  • state_prep (Kernel | None)

Return type:

Kernel

adjoint_kernel(power=1, uncompute=True, state_prep=None)

PREPARE, (W†)^power, optionally UNPREPARE (see kernel).

Parameters:
  • power (int)

  • uncompute (bool)

  • state_prep (Kernel | None)

Return type:

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: without state_prep the returned kernel takes one cudaq.State argument; with state_prep it 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 to control_state; with control |0> the circuit is the identity up to the (cancelling) PREPARE pair.

Parameters:
  • power (int)

  • control_state (int)

  • uncompute (bool)

  • state_prep (Kernel | None)

Return type:

Kernel

controlled_roundtrip_kernel(power=1, control_state=1, state_prep=None)

Controlled W^power then controlled (W dagger)^power — identity.

Parameters:
  • power (int)

  • control_state (int)

  • state_prep (Kernel | None)

Return type:

Kernel

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-built cudaq.State — the simulation-friendly form) or as state_prep (a (qubits: cudaq.qview) preparation kernel composed into the measured circuit — the hardware-shaped form). Provide exactly one.

Parameters:
  • ket (ArrayLike | None)

  • order (int)

  • state_prep (Kernel | None)

Return type:

float

moments(ket, count, *, state_prep=None)

Measure moments <T_0>, …, <T_{count-1}> (see moment).

Parameters:
  • ket (ArrayLike | None)

  • count (int)

  • state_prep (Kernel | None)

Return type:

list[float]

cudaq_algorithms.qubitization.reflection_observable(encoding)

R = 2|0...0><0...0| - I on the ancilla register.

Parameters:

encoding (BlockEncoding)

Return type:

cudaq.SpinOperator

class cudaq_algorithms.qsvt.QSVT(encoding)

Bases: object

Quantum singular value transformation over a block encoding.

Generic over the BlockEncoding protocol: encoding-specific circuits are delegated to the injected encoding (PauliLCU and LCUBlockEncoding are 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.

sequence may be a PhaseSequence or a plain list of phases (optionally with convention="qsp"). Without state_prep the returned kernel takes one cudaq.State argument; with state_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:
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: a cudaq.State-taking kernel, or a zero-argument kernel when state_prep is 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:
Return type:

Kernel

class cudaq_algorithms.qsvt.PhaseSequence(phases, walk_directions=None, convention='qsvt')

Bases: object

A 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 phases diag(e^{i phi}, e^{-i phi}), the QSPPACK convention). qsp-tagged phases are converted automatically wherever a circuit is built; phases always stays raw.

property projector_phases: list[float]

Phases in the projector convention the circuits implement.

qsp phases are doubled (equivalent up to a global phase of exp(i * sum(phases)); see recover_real_time_evolution).

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_state and sin_state are good-subspace statevectors produced by running qsp-convention sequences through the QSVT circuit (which executes doubled projector phases); the per-sequence global phase exp(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.

Parameters:
  • cos_state (ArrayLike)

  • sin_state (ArrayLike)

  • cos_phases (Sequence[float])

  • sin_phases (Sequence[float])

Return type:

NDArray[np.complex128]

class cudaq_algorithms.phase_estimation.PhaseEstimation(encoding)

Bases: object

Textbook quantum phase estimation over a BlockEncoding.

The phase register holds num_bits qubits; the energy resolution is set by how finely 2π j / 2^num_bits samples the walk eigenphase (about alpha π / 2^num_bits at worst). Composed kernels are cached per (num_bits, state_prep, measure).

Parameters:

encoding (BlockEncoding) – Any object satisfying the BlockEncoding protocol (PauliLCU and the other encodings in this package): it supplies the controlled qubitization walk, the PREPARE hooks that set the walk’s frame, and the one-norm alpha.

phase_to_energy(index, num_bits)

Map an m-bit phase readout j to an energy.

E = −alpha · cos(2π j / 2^m) — the inverse of the walk’s cos θ = −E/alpha eigenphase relation.

Parameters:
Return type:

float

kernel(num_bits, *, state_prep=None, measure=False)

The phase-estimation circuit.

Without state_prep: a @cudaq.kernel(state) allocating the system register from state. With state_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, then num_bits phase qubits (little-endian: phase qubit 0 is the least significant readout bit), then the encoding’s ancillas.

measure=False leaves the phase register ready to read (take its marginal with sim_utils.qpe.phase_probabilities, or measure it yourself). measure=True ends the circuit by measuring the phase register alone, so cudaq.sample returns its bitstrings on any target; decode them with energies_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).

Parameters:
  • num_bits (int)

  • state_prep (Kernel | None)

  • measure (bool)

Return type:

Kernel

phase_probabilities_from_counts(counts, num_bits)

The phase-register distribution behind sampled bitstrings: 2^num_bits relative frequencies, entry j for readout j.

counts is a cudaq.SampleResult or a mapping from bitstring to count. Bitstrings list qubit 0 first. A string of num_bits characters is the phase register (kernel(..., measure=True)); a string over every qubit of the circuit (kernel sampled with no explicit measurement) is sliced at the register layout, system | phase | ancilla.

Parameters:

num_bits (int)

Return type:

ndarray

energies_from_probabilities(probabilities, num_bits, *, top=None)

Rank energies from a phase-register distribution.

Folds the mirror readouts j and 2^m - j (the same energy) into one entry, so the list has 2^(m-1) + 1 distinct energies whose probabilities sum to that of the input, most probable first. top keeps the most probable entries.

Parameters:
  • num_bits (int)

  • top (int | None)

Return type:

list[tuple[float, float]]

energies_from_counts(counts, num_bits, *, top=None)

Ranked energies with probabilities from sampled bitstrings (phase_probabilities_from_counts then energies_from_probabilities).

Parameters:
  • num_bits (int)

  • top (int | None)

Return type:

list[tuple[float, float]]

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.FIRST_ORDER_TROTTER: int = 1

Supported product-formula orders.

cudaq_algorithms.trotter.HamiltonianLike

a cudaq.SpinOperator (or a single cudaq.SpinOperatorTerm product), 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: object

Suzuki-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 parameters time, steps, and order are 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.evolve for statevector-based evolution).

Parameters:
property coefficients: list[float]

Retained non-identity coefficients, in application order.

property words: list[str]

Retained Pauli words, parallel to coefficients.

property identity_coefficient: float

Sum of identity-term coefficients (not realizable in circuit).

property num_qubits: int

Register width the evolution kernels act on.

property num_terms: int

Number of retained non-identity terms.

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.

(Any because CUDA-Q exposes no stable public Python type for compiled kernel objects.)

The kernel allocates num_qubits qubits in |0...0>, optionally runs state_prep (a kernel with signature (qubits: cudaq.qview)) on them, and applies the order-order formula for time over steps steps — with or without state_prep the result takes no arguments and is directly sampleable. state_prep must act only on the register it is handed (width num_qubits, arriving in |0...0>). The identity phase is not included (it cannot be, in a circuit); track identity_coefficient when it matters.

Parameters:
Return type:

Any

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 a cudaq.State argument instead of |0...0> — the input-loading path sim_utils.evolve uses. Both factories share validation and marshaling through _prepared_args.

The supplied state must have dimension 2**num_qubits: sim_utils.evolve checks this; direct callers are responsible for it themselves (the identity-only variant cannot detect a mismatch).

Parameters:
Return type:

Any

resources(steps, order)

Resource estimate for steps steps of the order formula.

Both parameters are required so the estimate can never silently describe a different circuit than the kernel you built.

Parameters:
Return type:

TrotterResourceEstimate

class cudaq_algorithms.trotter.TrotterOrdering(*values)

Bases: Enum

Term-ordering strategies for the product formula.

PRESERVE_INPUT keeps the extraction order; COEFFICIENT_MAGNITUDE_DESCENDING applies 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: object

Lightweight circuit-cost summary for a Trotter sequence.

estimated_cx_count is a decomposition proxy: two CNOTs per additional non-identity Pauli in each rotation.

Parameters:
  • num_terms (int)

  • steps (int)

  • order (int)

  • pauli_rotations (int)

  • estimated_cx_count (int)

  • identity_coefficient (float)

cudaq_algorithms.trotter.estimate_trotter_resources(coefficients, words, steps, order, identity_coefficient=0.0)

Return a lightweight resource estimate for a Trotter sequence.

Parameters:
Return type:

TrotterResourceEstimate

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) where words are padded plain strings: readable, comparable, and accepted directly as list[cudaq.pauli_word] kernel arguments. (Only kernel-captured words need explicit cudaq.pauli_word conversion, which Trotter.kernel performs internally.)

coefficient_tolerance filters 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).

Parameters:
Return type:

tuple[list[float], list[str], float, int]

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: object

Coherent 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 QROM constructor (default "auto": price the variants and mint the cheapest). The chosen variant controls the garbage-register size through qrom.num_ladder (see num_garbage).

  • block_size (int | None) – Keyword-only; forwarded verbatim to the QROM constructor (only meaningful with variant="select_swap"; None lets the QROM pick). Also shapes qrom.num_ladder and hence num_garbage. Invalid combinations raise the QROM’s own ValueError.

  • 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).

property keep: tuple[int, ...]

Per-bin mu-bit keep thresholds (full bins clamped, self-aliased).

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>) between kernel() and adjoint_kernel() — unlike the rest of the garbage — so a SELECT sandwiched between them may reuse garbage[ladder_offset : ladder_offset + qrom.num_ladder] as its own ladder.

property lam: float

The weight one-norm lambda = sum_k w_k.

property num_bins: int

Padded bin count 2^num_index (>= len(weights)).

property num_garbage: int

Garbage register width (layout in the module docstring).

property num_index: int

Index register width (log2 of the padded bin count).

property probabilities: ndarray

The ideal padded distribution w / lambda (zero-padded).

property qrom: QROM

its variant, num_ladder and toffoli_count are the priced lookup facts the PREPARE inherits.

Type:

The minted (alias, keep) lookup

property table_probabilities: ndarray

The exactly realized index marginal (integer-table exact).

class cudaq_algorithms.primitives.QROM(data, address_bits, output_bits, *, variant='auto', block_size=None, controlled=False)

Bases: object

Coherent 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_bits bits.

  • 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 with variant="select_swap"; None there picks the power of two minimizing the documented Toffoli count.

  • controlled (bool) – True mints the externally controlled lookup: the kernel takes a leading one-qubit control view, 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’s num_ladder rather 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 block_size: int | None

SELECT-SWAP block size (None for the select variant).

property controlled: bool

Whether the kernel takes a leading one-qubit control view.

property kernel

The lookup kernel — self-inverse. (address, ladder, output), or (control, address, ladder, output) when controlled.

property num_ladder: int

Clean ancillas the kernel needs (|0> in, |0> out).

address_bits walk lines for "select"; walk lines plus the block_size * output_bits block registers for "select_swap".

property variant: str

‘select’ or ‘select_swap’.

Type:

The construction actually minted

class cudaq_algorithms.primitives.UnaryIterationKernels(kernel, kernel_adj, num_address, num_ladder, num_items, controlled, toffoli_count, num_work=0, ops=None)

Bases: object

The minted walk (see the module docstring for signatures).

Parameters:
  • kernel (Any)

  • kernel_adj (Any)

  • num_address (int)

  • num_ladder (int)

  • num_items (int)

  • controlled (bool)

  • toffoli_count (int)

  • num_work (int)

  • ops (Any)

kernel, kernel_adj

The walk and its hand-written inverse (kernel_adj is None when minted with include_adjoint=False).

num_address, num_ladder, num_items

Register widths (num_ladder == num_address clean ancillas) and the number of iterated addresses.

controlled

Whether kernel takes the leading one-qubit control view.

Type:

bool

num_work

Width of the trailing clean work view (0: no work view in the signature).

Type:

int

toffoli_count

Toffolis in one application (cost accounting).

Type:

int

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 # Toffoli are the gates toffoli_count counts. 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:

str

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); addresses k >= num_items are 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 k to the gate list U_k that the walk applies when the address register holds k — i.e. the minted kernel implements sum_k |k><k| (x) U_k. Each entry is an opcode tuple such as ("x", t) / ("y", t) / ("z", t) (leaf-controlled Pauli on target[t]) or one of the extended gates in the module docstring; an empty list means U_k = I. Called exactly once per address, in address order, during this factory call — the gates are baked into the kernel, so body itself never runs at circuit time.

  • controlled (bool) – Mint the externally controlled walk (leading one-qubit view).

  • include_adjoint (bool) – Mint kernel_adj; pass False when 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 work view. 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 resolved num_work > 0, including a positive explicit width unused by the body; explicit num_work=0 keeps the work-less signatures when the body needs no work.

Return type:

UnaryIterationKernels

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 convention qubit_hamiltonian and 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 l record with all of i,j,k,l nonzero is a two-electron integral, with k == l == 0 a one-electron integral h_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=1 or Psi4’s UHF=.TRUE.) store a spin-resolved integral set with a different index symmetry and are rejected up front by a header guard.

Parameters:

contents (str)

Return type:

tuple[ndarray, ndarray, float]

cudaq_algorithms.chemistry.spin_orbital_tensors(one_body, eri, *, validate_symmetry=True)

Spin-expand chemist-notation spatial integrals.

one_body is the (n, n) core Hamiltonian and eri the (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) over 2n spin orbitals (interleaved spins: 2p up, 2p + 1 down), where two_body_so[p, q, r, s] is the coefficient of a^dag_p a^dag_q a_r a_s as consumed by fermion.jordan_wigner.

eri must 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; pass validate_symmetry=False to skip the check (e.g. for genuinely complex integrals, whose symmetry differs).

Parameters:
  • one_body (ArrayLike)

  • eri (ArrayLike)

  • validate_symmetry (bool)

Return type:

tuple[ndarray, ndarray]

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, whose eri symmetry precondition and validate_symmetry flag apply here too) and applies the Jordan-Wigner transform. scalar_offset is added as an identity term (e.g. the nuclear repulsion energy); tolerance prunes 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
Parameters:
  • one_body (ArrayLike)

  • eri (ArrayLike)

  • scalar_offset (float)

  • tolerance (float)

  • validate_symmetry (bool)

cudaq_algorithms.chemistry.from_pyscf(mean_field)

Chemist (pq|rs) MO integrals + nuclear repulsion from PySCF.

mean_field is a converged restricted mean field (e.g. the result of pyscf.scf.RHF(mol).run()). Returns (one_body, eri, nuclear_repulsion) in the molecular-orbital basis and chemist notation – exactly the arguments qubit_hamiltonian() expects (pass nuclear_repulsion as its scalar_offset).

Restricted (single mo_coeff matrix) references only; the spin expansion downstream assumes one spatial set shared by both spins.

Return type:

tuple[ndarray, ndarray, float]

cudaq_algorithms.chemistry.from_psi4(wavefunction)

Chemist (pq|rs) MO integrals + nuclear repulsion from Psi4.

wavefunction is a converged restricted wavefunction, e.g. the second return value of psi4.energy("scf", return_wfn=True). Returns (one_body, eri, nuclear_repulsion) in the molecular-orbital basis and chemist notation – identical in meaning and convention to from_pyscf(), so either drives qubit_hamiltonian() unchanged.

Restricted references only (uses Ca); mo_eri already returns the chemist (pq|rs) ordering, matching the PySCF path.

The wavefunction must be computed in C1 symmetry (symmetry c1 in the Psi4 geometry). The extraction reads Ca as a single dense block, so an irrep-blocked (higher-symmetry) wavefunction is rejected.

Return type:

tuple[ndarray, ndarray, float]

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) and adag_i adag_j a_k a_l (two-body) over n spin 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_offset is added as an identity term; input entries (explicit zeros included) and compiled terms with magnitude below tolerance are dropped. Returns a cudaq.SpinOperator.

Parameters:
  • one_body_or_two_body (ArrayLike | Mapping)

  • two_body (ArrayLike | Mapping | None)

  • scalar_offset (float)

  • tolerance (float)

  • num_modes (int | None)

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_modes when both inputs are mappings); the qubits store Fenwick-tree partial sums of the occupations, giving O(log n)-weight Pauli words. Returns a cudaq.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 to jordan_wigner. The retired compiled binding instead antisymmetrized the tensor internally before transforming; matching jordan_wigner here 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.

Parameters:
  • one_body_or_two_body (ArrayLike | Mapping)

  • two_body (ArrayLike | Mapping | None)

  • scalar_offset (float)

  • tolerance (float)

  • num_modes (int | None)

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 (> N for dense Hamiltonians – this mapping is for sparse ones).

The integrals are the coefficients of adag_i a_j and adag_i adag_j a_k a_l (the convention of jordan_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 is O(n^4) storage for O(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_modes when 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_offset is added as an identity term; input entries (explicit zeros included) and compiled terms below tolerance are dropped. Returns a cudaq.SpinOperator.

local_modes selects 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 degree d (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), of O(d) weight.

  • a custom provider (callable degree -> modes or mapping): the caller’s own local Majorana modes, each a Pauli string or (coeff, (x, z)) word on degree/2 qubits, validated to obey the Majorana algebra.

interaction_graph optionally 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_graph to add connecting edges. Hermiticity of the input is the caller’s responsibility, as for jordan_wigner().

parity selects the fermion-parity sector the code subspace represents: 0 (default) for an even number of particles, 1 for an odd number. The encoding maps the even operator algebra only, so the encoded parity prod_i (-1)^{n_i} = prod_i B_i is a constant on the code subspace rather than an operator with both eigenvalues; parity=1 negates 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 +1 eigenspace 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). Use bravyi_kitaev_superfast_stabilizers() for the loop stabilizers that fix the code subspace.

Parameters:
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.SpinOperator per 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 by parity (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, parity and num_modes are as in bravyi_kitaev_superfast() (use the same values for both so the stabilizers act on the matching qubits). The stabilizer words themselves do not depend on parity: the sector is selected by the vertex operators the Hamiltonian compiles to.

Parameters:
  • tolerance (float)

  • parity (int)

  • num_modes (int | None)

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: object

Result of a double factorization of the two-electron integrals.

leaf_rotations[t] is the orthogonal matrix U^t (shape (num_orbitals, num_orbitals)) and leaf_cores[t] is the symmetric core Z^t for leaf t. method is "X-DF" or "C-DF".

C-DF fills optimizer_success, optimizer_nit, and optimizer_grad_norm from the L-BFGS-B result (None on X-DF). When n == 1, no optimization runs, so those fields are True, 0, and 0.0.

Parameters:
reconstruct_eri()

Reconstruct the (n, n, n, n) chemist-notation ERI tensor.

Return type:

ndarray

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_rs into symmetric leaves L^t:

  • first_factorization="cholesky" (default) – pivoted Cholesky of the positive-semidefinite ERI matrix. Rank-revealing: it keeps leaves while the residual-diagonal pivot exceeds threshold (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_rs keeping |lambda_t| > threshold. Required for indefinite inputs; the ERI is PSD so Cholesky is preferred.

max_num_leaves caps the leaf count. Second factorization: each symmetric leaf is eigendecomposed, L^t = U^t diag(gamma^t) (U^t)^T, giving the rank-one core Z^t = outer(gamma^t, gamma^t) (scaled by lambda_t in the eigendecomposition case). second_factor_threshold optionally zeros small gamma^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 DoubleFactorization with NumPy arrays.

Parameters:
  • eri (ArrayLike)

  • threshold (float)

  • max_num_leaves (int | None)

  • second_factor_threshold (float)

  • first_factorization (str)

  • backend (str)

Return type:

DoubleFactorization

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^2 over a fixed number of leaves. Uses the two-step scheme of arXiv:2104.08957: the leaf rotations are parameterized as U^t = exp(X^t) with antisymmetric X^t and optimized with L-BFGS (warm-started from X-DF), while the symmetric cores Z^t are solved exactly in closed form at each step.

regularization (rho) enables RC-DF (arXiv:2212.07957, Eq. 17): the L2 penalty rho * sum_{t,k,l} (Z^t_kl)^2 is added to the objective and, crucially, folded into the inner core solve as a ridge term. It shrinks the cores – lowering the Hamiltonian one-norm lambda and the measurement variance – and conditions the inner system. rho is an absolute coefficient (its useful scale depends on the integral magnitude; the paper uses ~1e-6 to 1e-3). rho = 0 reproduces plain C-DF.

inner_solver selects 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 the n^4-row design matrix and scales to large orbital counts. cg_tolerance and cg_max_iterations control the CG solve. cg_tolerance is relative to the projected right-hand-side norm ||R||_F; cg_optimization_tolerance inherits the same meaning.

For inner_solver="cg" two accelerators cut the per-step CG cost without changing the final accuracy: cg_warm_start (default True) 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 of x. cg_optimization_tolerance (default max(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 to cg_tolerance.

L-BFGS-B status is stored on the returned DoubleFactorization (optimizer_success, optimizer_nit, optimizer_grad_norm). A RuntimeWarning is issued if the optimizer does not converge, including when it hits max_iterations; the best factorization found is still returned. When n == 1, there are no free antisymmetric parameters, so each leaf rotation is the identity, the cores are the closed-form solution, and optimizer_nit is 0.

Returns a DoubleFactorization with NumPy arrays.

Parameters:
  • eri (ArrayLike)

  • num_leaves (int)

  • max_iterations (int)

  • tolerance (float)

  • regularization (float)

  • inner_solver (str)

  • cg_tolerance (float)

  • cg_max_iterations (int | None)

  • cg_warm_start (bool)

  • cg_optimization_tolerance (float | None)

  • initial_generators (List[ndarray] | None)

  • backend (str)

Return type:

DoubleFactorization

cudaq_algorithms.double_factorization.reconstruct_eri(factorization)

Reconstruct the chemist-notation ERI tensor from a factorization.

Parameters:

factorization (DoubleFactorization)

Return type:

ndarray

cudaq_algorithms.double_factorization.factorization_error(eri, factorization)

Frobenius norm of the ERI reconstruction residual.

Parameters:
Return type:

float

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:

ndarray

cudaq_algorithms.double_factorization.double_factorization_one_norm(factorization, one_body_eigenvalues, convention='lcu')

One-norm lambda of the double-factorized Hamiltonian (RC-DF, arXiv:2212.07957), used to assess factorization quality.

convention="lcu" (Eq. 13) – the LCU / Pauli-rotation norm sum_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 as Z^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 factorization Z = W W^T leaves W free 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|)^2 for rank-one cores.)

one_body_eigenvalues are the diagonal one-body (Fock-like) eigenvalues.

Parameters:
Return type:

float

cudaq_algorithms.double_factorization.cupy_gpu_available()

Return True when CuPy can run a kernel on a visible GPU.

getDeviceCount only 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 tiny arange forces that compile, and .sum() into a host float waits for the device so a fault that only appears at synchronization is not missed.

Return type:

bool

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 count n) is at least gpu_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 no problem_size hint it keeps the legacy behavior: CuPy whenever a GPU is present. "cupy" / "numpy" force the backend regardless of size.

Parameters:
  • backend (str)

  • problem_size (int | None)

  • gpu_min_size (int)

Return type:

tuple[Any, str]

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 the uccsd kernel).

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_lists helpers, but for an arbitrary pool (e.g. make_uccsd_operator_pool): one group per pool operator, in pool order, ready for the fixed_parameter_ucc kernel. Terms with |coefficient| <= coefficient_tolerance are dropped (they would waste identity rotations); coefficients with an imaginary part above the tolerance are rejected — exp_pauli angles 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, matching get_uccsd_excitations so 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_word objects expose no accessor and are trusted (the get_*_pauli_lists helpers 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:

HartreeFockResourceEstimate

cudaq_algorithms.stateprep.estimate_hartree_fock_occupation_resources(num_qubits, occupied_orbitals)

Resource estimate for an explicit-occupation reference.

Return type:

HartreeFockResourceEstimate

cudaq_algorithms.stateprep.estimate_fixed_parameter_ucc_resources(num_qubits, pauli_words)

Resource estimate for a fixed-parameter UCC product.

Return type:

FixedParameterUccResourceEstimate

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 optional spin for an open-shell reference) or explicit occupied_orbitals. The returned kernel expects a num_qubits-wide register in |0...0> and is directly injectable as a state_prep kernel (e.g. into PauliLCU.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: object

Circuit cost of a Hartree-Fock reference preparation.

Parameters:
  • num_qubits (int)

  • num_electrons (int)

  • num_x_gates (int)

class cudaq_algorithms.stateprep.FixedParameterUccResourceEstimate(num_qubits, num_excitations, num_pauli_rotations, max_pauli_rotations_per_excitation)

Bases: object

Circuit cost of a fixed-parameter UCC product (Pauli rotations).

Parameters:
  • num_qubits (int)

  • num_excitations (int)

  • num_pauli_rotations (int)

  • max_pauli_rotations_per_excitation (int)

class cudaq_algorithms.stateprep.GivensRotation(first_orbital, second_orbital, theta, phase=0.0)

Bases: object

One adjacent Givens rotation between two orbitals.

phase is the relative phase applied after the rotation (exp(i * phase * n_second)); it is 0 for real schedules.

Parameters:
class cudaq_algorithms.stateprep.GivensRotationSchedule(num_spin_orbitals, num_electrons, is_complex=False, rotations=<factory>, final_phases=<factory>)

Bases: object

A Givens rotation sequence preparing a Slater determinant.

rotations are in application order (the reverse of the elimination order). final_phases holds one phase per electron, applied to the occupied qubits before the rotations; it is all-zero for real schedules.

Parameters:
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: object

Lightweight circuit-cost summary for a Givens schedule.

num_spin_orbitals and num_electrons echo the schedule. num_exp_pauli_calls counts the two-qubit exp_pauli rotations (two per Givens rotation); num_phase_rotations counts the single-qubit rz gates of a complex preparation (one per rotation plus one per electron). The proxies are decomposition-independent upper bounds, not transpiled gate counts.

Parameters:
  • num_spin_orbitals (int)

  • num_electrons (int)

  • num_givens_rotations (int)

  • num_exp_pauli_calls (int)

  • num_phase_rotations (int)

  • two_qubit_gate_count_proxy (int)

  • depth_proxy (int)

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 a state_prep kernel (e.g. into PauliLCU.encode_kernel). It dispatches on schedule.is_complex to the slater_determinant / complex_slater_determinant kernel 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_coefficients is 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 with hartree_fock_occupation references and the UCCSD excitation conventions built at the same spin.

Return type:

GivensRotationSchedule

cudaq_algorithms.stateprep.validate_givens_rotation_schedule(schedule)

Validate a schedule against the state-preparation kernel contract.

make_givens_rotation_schedule output 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:

list[int]

cudaq_algorithms.stateprep.get_givens_rotation_angles(schedule)

Rotation angles in application order.

Parameters:

schedule (GivensRotationSchedule)

Return type:

list[float]

cudaq_algorithms.stateprep.get_givens_rotation_phases(schedule)

Relative phases in application order (all zero for real schedules).

Parameters:

schedule (GivensRotationSchedule)

Return type:

list[float]

cudaq_algorithms.stateprep.estimate_givens_resources(schedule)

Resource estimate for preparing a schedule’s Slater determinant.

Parameters:

schedule (GivensRotationSchedule)

Return type:

GivensResourceEstimate

class cudaq_algorithms.stateprep.OrbitalRotationSchedule(num_modes, rotations, signs)

Bases: object

An adjacent Givens sweep of a real orthogonal matrix V.

rotations are (mode, theta) plane rotations on modes (mode, mode + 1) in elimination order: applied to the rows of V in turn they reduce it to a diagonal of signs, R_m ... R_1 V = diag(signs). signs is that residual, one +-1 per mode: the networks built from the schedule reproduce V diag(signs), i.e. V up to a sign per mode. That is immaterial for operators diagonal in the rotated modes (number operators); RotatedEncoding.from_orbital_rotation cancels it with a Z on both spin orbitals of each mode with sign -1 (Z_p a_p Z_p = -a_p under Jordan-Wigner), so its frame kernels realize V exactly.

Parameters:
cudaq_algorithms.stateprep.make_orbital_rotation_schedule(orthogonal, tolerance=1e-12)

Decompose a real orthogonal n x n matrix (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 of make_givens_rotation_schedule, acting on spatial modes rather than spin orbitals. Raises ValueError for a complex, non-square or non-orthonormal input.

Parameters:

tolerance (float)

Return type:

OrbitalRotationSchedule

cudaq_algorithms.stateprep.orbital_rotation_program(schedule, *, inverse)

Flattened (modes, angles) lists for spatial_givens_network.

With inverse=False the network realizes V diag(signs) on the one-particle space of each spin: from R_m ... R_1 V = D follows V D = R_1^T ... R_m^T, so the sweep is applied reversed with negated angles (the last elimination first in circuit time). With inverse=True it realizes the transpose, D V^T: the sweep in elimination order. A diagonal V has 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).

Parameters:
Return type:

tuple[list[int], list[float]]

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: object

Unsigned little-endian full-turn fixed point with nearest-even rounding.

word[k] has radian weight 2*pi * 2**(k-width). Widths from one through 52 are supported for the double-valued host parameters; rounding is evaluated in double precision (see encode()). 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 * step rounded 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, Fraction and extended-precision values are rounded before reduction. The quotient by step is 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.

width: int

Number of word bits, an integer from 1 through 52.

class cudaq_algorithms.basis_change.FermionBasisChange(schedule, angle_encoding=None, parameter_registers=None)

Bases: object

Immutable plan acting on an existing system and optional angle words.

Construct plans with fermion_basis_change(). Kernels accept one qview spanning at least num_qubits qubits (num_qubits + 1 for controlled_kernel()). CUDA-Q does not bounds-check views, so a narrower view silently addresses the following qubits of the parent allocation. System modes follow structure.mode_map; optional words follow parameter_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.control of kernel() puts it on every emitted gate, including the Clifford and parity scaffold. The adjoint flag of controlled_kernel() must be a Python bool.

Parameters:
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 + 1 qubits. 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. adjoint must be a Python bool.

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.

basis is a unitary square matrix or normalized vector/column of at least two modes, or a GivensBasisChangeSchedule. 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 a 2**n by 2**n qubit unitary is interpreted as 2**n modes on 2**n qubits; this is not arbitrary qubit-unitary synthesis.

programmable must be a Python bool. With programmable=True, require angle_bits from 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_qubits qubits (num_qubits + 1 for controlled_kernel); CUDA-Q does not bounds-check views, so a narrower view silently addresses the following qubits of the parent allocation. controlled_kernel controls only the Rz and R1 rotations; cudaq.control of kernel() 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 check schedule.reconstruction_error when 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: object

Static topology and parameter schema, independent of numerical values.

Full schemas start with m diagonal phases, followed by a theta, phi pair per chronological mixing slot. Partial schemas contain m-1 mixing angles followed by m output number phases. All slots remain present for zero angles and real input data. num_modes must be at least two: a single mode has no mixing and admits only a number phase, which callers apply directly with r1. mode_map is an ordered sequence (list, tuple, range or one-dimensional array) of distinct physical qubit indices, one per logical mode, each from 0 to 2**31 - 1.

Parameters:
  • num_modes (int)

  • kind (str)

  • mode_map (tuple[int, ...] | None)

  • reference_mode (int | None)

classmethod full(num_modes, *, mode_map=None)

Construct the fixed adjacent QR topology for a square unitary.

mode_map: tuple[int, ...] | None = None

Physical qubit of each logical mode; defaults to 0 .. m-1.

property mode_pairs

Logical mixing pairs in chronological application order.

property num_parameters

m**2 full, 2*m - 1 partial.

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.

reference_mode: int | None = None

Logical reference mode of a partial schedule, otherwise None.

num_modes: int

Number of logical fermionic modes, at least two.

kind: str

Schedule kind, either "full" or "partial".

class cudaq_algorithms.basis_change.GivensOperation(kind, first, second, parameter_index, scale=1.0)

Bases: object

One chronological logical operation with an indexed real parameter.

kind is "phase", the number phase exp(i*angle*n) on mode first, or "givens", the real rotation [[c, -s], [s, c]] on the mode pair (first, second) with c, s = cos(angle), sin(angle). first and second are logical mode indices; the physical qubit of mode first is structure.mode_map[first]. second is None for a phase. parameter_index indexes the schedule parameters, and the applied angle is scale * parameters[parameter_index]: scale = -1 marks the leading P_b(-phi) of a complex mixing block.

Parameters:
class cudaq_algorithms.basis_change.GivensBasisChangeSchedule(structure, parameters=None, reconstruction_error=None)

Bases: object

Immutable static tape with optional numerical angle values.

reconstruction_error is the maximum absolute orbital-matrix entry error (the specified column only for partial input), a finite nonnegative diagnostic. It is None for structure-only plans and takes no part in equality or hashing, which depend only on structure and parameters. 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 a reconstruction_error unless reconstruction_error=None is also passed, and replacing the parameters keeps the old residual, so recompile instead when the angles change.

Parameters:
property num_parameters

Number of real parameter slots in the schedule.

property operations

Chronological GivensOperation tape 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.

basis may have shape (m,m), (m,) or (m,1) with m >= 2. basis=None requires a structure and allocates the same tape and parameter schema without numerical values. Validation uses the absolute tolerance, with 0 < 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_error reports the maximum entry discrepancy; check it when loosening tolerance.

class cudaq_algorithms.basis_change.FermionBasisChangeErrorEstimate(parameter_deltas, parameter_error_sum, synthesis_error_bound, basis_change_error_bound, reflection_error_bound)

Bases: object

Spectral-norm bounds for a represented basis change and reflection.

parameter_error_sum includes every tape occurrence, so a full-plan relative phase contributes twice. synthesis_error_bound is a supplied bound for the complete represented basis-change circuit, not per gate. basis_change_error_bound clips 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.

Parameters:
  • parameter_deltas (tuple[float, ...])

  • parameter_error_sum (float)

  • synthesis_error_bound (float)

  • basis_change_error_bound (float)

  • reflection_error_bound (float)

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: object

Static 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_kernel keeps 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.control of kernel() 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 eps including global phase, pass num_elementary_rotations * eps from estimate_fermion_basis_change_resources() (num_bit_controlled_rotations * eps for 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.

schedule is a GivensBasisChangeSchedule or a FermionBasisChange plan. A plan supplies its own angle width and program-qubit count, num_qubits - num_system_qubits, which includes gaps in explicit parameter_registers; angle_bits and num_program_qubits must then be omitted.

For physical endpoint separation d, each of the two mixing Pauli strings has weight d+1. A compute/uncompute parity ladder therefore has 2*d CNOTs per string, or 4*d for 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_bits is 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_qubits defaults 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 least angle_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 FermionBasisChangeResourceEstimate for 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 nvidia target) reject complex128 input (“[sim-state] invalid data precision”); cudaq.complex() reports the dtype the active target expects.

num_qubits pins the register the state is meant for: a kernel that allocates cudaq.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. With num_qubits given, a ket of any other length raises ValueError here instead. The kernel factories’ state-taking circuits (encode_kernel, walk_kernel, Walk.kernel, …) expect exactly 2^num_system amplitudes.

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:
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.alpha to recover H|ket>.

Parameters:
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, where p is the polynomial the phase sequence implements.

Parameters:
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 full exp(-i H t)|ket>.

Delegates to Trotter.state_kernel — the same validation (finite time, positive integral steps, order in {1, 2, 4}) and marshaling as Trotter.kernel, raising ValueError for invalid parameters instead of silently returning an unevolved state.

Parameters:
Return type:

NDArray[np.complex128]

cudaq_algorithms.sim_utils.run_on_large_stack(function, /, *args, stack_bytes=536870912, **kwargs)

Call function(*args, **kwargs) on a worker thread with a stack_bytes stack 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_probabilities does this for the 2^num_bits - 1 walk steps of a phase-estimation circuit, and a circuit from PhaseEstimation.kernel that 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_bits probabilities, entry j for readout j, summing to 1 (no shot noise).

Simulates estimator.kernel(num_bits, state_prep=...) with cudaq.get_state on a large-stack worker (sim_utils.run_on_large_stack) and traces out the system and ancilla registers. Provide exactly one of ket (array-like / cudaq.State) or state_prep. Decode with PhaseEstimation.energies_from_probabilities, or call energies.

Parameters:
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_probabilities decoded by PhaseEstimation.energies_from_probabilities (mirror readouts folded, most probable first, top keeps the leading entries).

Parameters:
Return type:

list[tuple[float, float]]

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 nvidia target) reject complex128 input (“[sim-state] invalid data precision”); cudaq.complex() reports the dtype the active target expects.

num_qubits pins the register the state is meant for: a kernel that allocates cudaq.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. With num_qubits given, a ket of any other length raises ValueError here instead. The kernel factories’ state-taking circuits (encode_kernel, walk_kernel, Walk.kernel, …) expect exactly 2^num_system amplitudes.

Parameters:

num_qubits (int | None)

Return type:

State