qrunch.quantum.internal
Unified Python module that contains all Rust-backed quantum classes. This consolidates all #[pyclass] definitions into a single .so file, which solves PyO3’s type identity issues across module boundaries.
Functions
Combined excitation index generation + metric computation + top-k selection (BigUint measurements). |
|
Combined excitation index generation + metric computation + top-k selection (u64 measurements). |
|
Combined pair-excitation index generation + metric computation + top-k selection (BigUint measurements). |
|
Combined pair-excitation index generation + metric computation + top-k selection (u64 measurements). |
|
|
|
Find the best contraction path using the adaptive strategy. |
|
Set |
|
|
Generate the operators needed for the 1-particle reduced density matrix. |
|
Generate the operators needed for the 2-particle reduced density matrix. |
|
Generate the operators needed for the 3-particle reduced density matrix. |
|
Generate the operators needed for the 4-particle reduced density matrix. |
Generate all excitation gate pool indices for a molecular electron configuration. |
|
|
Generate the operators needed for the restricted 1-particle reduced density matrix. |
|
Generate the operators needed for the restricted 2-particle reduced density matrix. |
Generate a batch of restricted 2-RDM operators for a slice of canonical indices. |
|
Generate the operators needed for the unrestricted 1-particle reduced density matrix for a single spin component. |
|
Generate the operators needed for the unrestricted mixed-spin 2-particle RDM. |
|
Generate a batch of mixed-spin 2-RDM operators for a slice of canonical indices. |
|
Generate the operators needed for the unrestricted same-spin 2-particle RDM. |
|
|
Generate a batch of same-spin 2-RDM operators for a slice of canonical indices. |
|
Generate all C(dimension, 2) HermitianPauliSums, each containing a single X⊗X Pauli string over every unique 2-qubit combination. |
|
Generate all |
|
Generate (X[x]*X[y]+Y[x]*Y[y]) * Z[p] operators. |
|
Generate (X[x]*X[y]+Y[x]*Y[y]) * Z[p]*Z[q] operators. |
|
Generate X[x]*X[y]*Z[p] operators in the order of [generate_xx_plus_yy_with_z_operators]. |
|
Generate X[x]*X[y]*Z[p]*Z[q] operators in the order of [generate_xx_plus_yy_with_zz_operators]. |
Generate the operators of [generate_xx_with_zz_operators] of the pairs (x, y) with lexicographic rank in |
|
|
Generate all C(dimension, 4) HermitianPauliSums, each containing two terms: X⊗X⊗X⊗X + Y⊗Y⊗Y⊗Y over every unique 4-qubit combination. |
|
Generate XXYY operators for pair-of-pairs iteration. |
|
Generate the three pairings |
Generate the three pairings of [generate_xxyy_pairing_operators] of the quadruples with lexicographic rank in |
|
|
Generate all |
|
Generate all C(dimension, 2) HermitianPauliSums, each containing a single Z⊗Z Pauli string over every unique 2-qubit combination. |
|
Generate all C(dimension, 3) HermitianPauliSums, each containing a single Z⊗Z⊗Z Pauli string over every unique 3-qubit combination. |
|
Generate all C(dimension, 4) HermitianPauliSums, each containing a single Z⊗Z⊗Z⊗Z Pauli string over every unique 4-qubit combination. |
Generate the operators of [generate_zzzz_operators] with index in |
|
|
Generate all C(dimension, 5) HermitianPauliSums, each containing a single Z⊗Z⊗Z⊗Z⊗Z Pauli string over every unique 5-qubit combination. |
Generate Z⊗Z⊗Z⊗Z⊗Z operators for a subset of qubit quintuples determined by active pair-breaking terms. |
|
|
Return the number of canonical 2-fold symmetric index tuples for the restricted 2-RDM. |
Return the number of canonical 2-fold symmetric index tuples for mixed-spin 2-RDM. |
|
Return the number of canonical 8-fold symmetric index tuples for same-spin 2-RDM, after filtering out p==q or r==s cases. |
|
|
|
|
|
|
Return the lexicographic ranks in |
Reduce the observables for a state in which the fixed_mask qubits are in the computational basis state given by occupied_mask and unentangled with the rest. |
|
|
|
|
|
Compute the top-k double-excitation heuristic gradient metrics directly from the molecular electron-repulsion integrals (ERIs) using the Slater–Condon rules, without building the qubit Hamiltonian. |
|
Compute the top-k pair-excitation metrics for the BEAST Hamiltonian directly from the reduced one-body integrals |
|
Compute the top-k first-order single-excitation metrics (Fock matrix off-diagonal elements) directly from one-body and two-body integrals, without building the qubit Hamiltonian. |
|
|
Compute the top-k second-order single-excitation metrics from the BCH expansion directly from one-body and two-body integrals, without building the qubit Hamiltonian. |
Compute |
Classes
Stabilizer of Pauli strings, represented by dynamically sized Z and X bitmasks. |
- class AntiHermitianPauliSum
Bases:
object- classmethod __new__(*args, **kwargs)
- constant()
Returns the constant as a complex number (re=0)
- indices()
- len()
- number_of_qubits
- prune(tolerance)
- string_coefficient_pairs()
Usage of the string_coefficient_pairs method is discouraged. Use proper rust code for efficient data handling. This is only provided for Python compatibility.
- terms_as_int
Usage of the terms_as_int method is discouraged. Use proper rust code for efficient data handling. This is only provided for Python compatibility. Note: This now reconstructs the int_terms on each call since we no longer store it.
- class CuQuantumStatevectorGateCompiler
Bases:
objectHigh-level compiler engine for quantum circuits and gates targeting cuStateVec.
# Pre-cached Python Modules and Gate Types: Pre-importing and retaining references to Python gate types allows fast pointer-equality checks (gate.get_type().is(self.rx_gate_type)) during circuit parsing loops without repeatedly paying module import or attribute lookup overhead.
- classmethod __new__(*args, **kwargs)
- apply_instructions_to_state_vector(handle, state_vector_ptr, num_qubits, instructions, cuda_data_type, compute_type, workspace=None)
Executes a sequence of compiled DeviceGateInstruction objects on a GPU state vector.
- clear()
Clears all internal caches (unitary matrix cache and workspace size cache) and resets the active qubit count.
- compile_circuit(circuit)
Compiles an entire quantum circuit into a list of DeviceGateInstruction objects.
# Parameters - circuit: Python QuantumCircuit object.
- compile_gate(gate, num_qubits)
Compiles an individual quantum gate into a list of DeviceGateInstruction objects.
Recursively decomposes composite or controlled gates, builds target/control layout arrays, evaluates/caches the unitary matrices on the GPU, and returns the device instruction list.
# Parameters - gate: Python quantum gate object. - num_qubits: Total number of qubits in the circuit.
- fuse_instructions(instructions, max_targets=4)
Greedily fuses consecutive compatible DeviceGateInstruction objects into multi-qubit matrices (up to max_targets qubits), memoizing intermediate pair contractions and instruction objects across repeated sub-circuits (e.g. repeated Trotter steps).
- class DeviceGateInstruction
Bases:
objectDevice-ready instruction representing a single gate execution on the GPU.
Combines the unitary matrix (as a CuPy GPU array and its raw device memory pointer) with the target/control qubit arrays and their raw memory pointers.
Python code (or Rust apply_instructions_to_state_vector) can consume these instructions to execute custatevecApplyMatrix directly on CUDA state vectors with zero parsing overhead.
- classmethod __new__(*args, **kwargs)
- control_bit_values
1D NumPy array of control bit values (0 or 1), or None.
- control_bit_values_ptr
Host memory pointer to the contiguous control bit values array data, or 0.
- controls
1D NumPy array of control qubit indices, or None.
- controls_ptr
Host memory pointer to the contiguous control qubit array data, or 0.
- matrix
CuPy 2D complex unitary matrix array resident in GPU memory.
- matrix_ptr
GPU device memory pointer (matrix.data.ptr) to the unitary matrix elements.
- n_controls
Number of control qubits.
- n_targets
Number of target qubits.
- targets
1D NumPy array of target qubit indices.
- targets_ptr
Host memory pointer to the contiguous target qubit array data.
- class ExcitationGate
Bases:
object- static new_double_excitation_gate(number_of_qubits, creation_index1, creation_index2, annihilation_index1, annihilation_index2, theta, float_type=Ellipsis, particle_conservation=Ellipsis, gate_zs=Ellipsis)
- static new_single_excitation_gate(number_of_qubits, creation_index, annihilation_index, theta, float_type=Ellipsis, particle_conservation=Ellipsis, gate_zs=Ellipsis)
- class ExcitationGateCircuit
Bases:
object- classmethod __new__(*args, **kwargs)
- add_gate(gate)
- get_energy(shots=None, hamiltonian=None, eps=None)
- get_parameters()
- get_samples(shots, eps=None)
- get_state_vector()
- run_circuit()
- set_gates(gates)
- set_grouping(grouping)
- set_hamiltonian(hamiltonian)
- update_parameter_at_index(parameter, index)
- update_parameters(parameters)
- class Hamiltonian
Bases:
object- classmethod __new__(*args, **kwargs)
- static from_hermitian_pauli_sum(pauli_sum, float_type=Ellipsis)
- class HermitianPauliSum
Bases:
object- classmethod __new__(*args, **kwargs)
- constant()
Expose the constant_value
- filter_untouched_qubits(untouched_mask)
Filters the sum based on a bitmask of untouched qubits. Any term acting with X or Y on an untouched qubit is removed.
- format_complex_str(suffix)
- indices()
Returns a sorted list of unique qubit indices acted upon by this sum.
- len()
- number_of_qubits
- partition_by_double_excitation_commutation(p, q, r, s)
Partitions the sum into (commuting, non-commuting) relative to a DoubleExcitationGate acting on qubits p, q, r, s.
A Pauli string commutes with the gate when the local Pauli pattern on (p, q, r, s) is one of: IIII, even-Z patterns (IIZZ, IZIZ, IZZI, ZIIZ, ZIZI, ZZII, ZZZZ), or X/Y-dominant patterns (XXXY, XXYX, XYXX, YXXX, XYYY, YXYY, YYXY, YYYX). The identity/constant term always goes into the commuting partition.
- partition_by_double_fermionic_evolution_commutation(p, q, r, s)
Partitions the sum into (commuting, non-commuting) relative to a DoubleFermionicEvolutionGate acting on qubits p, q, r, s.
A Pauli string commutes with the gate when the local Pauli pattern on (p, q, r, s) is one of the 16 patterns obtained from the double-excitation commuting patterns by swapping X and Y on p. The identity/constant term always goes into the commuting partition.
- partition_by_double_fermionic_excitation_commutation(p, q, r, s)
Partitions the sum into (commuting, non-commuting) relative to a DoubleFermionicExcitationGate acting on qubits p, q, r, s.
The gate is a DoubleExcitationGate whose generator carries a Z string on the qubits strictly between the two smallest and strictly between the two largest indices, handled as in [Self::partition_by_single_fermionic_excitation_commutation]. The identity/constant term always goes into the commuting partition.
- partition_by_single_excitation_commutation(p, q)
Partitions the sum into (commuting, non-commuting) relative to a SingleExcitationGate acting on qubits p and q.
A Pauli string commutes with the gate when the local Pauli pattern on (p, q) is one of: II, XY, YX, ZZ. The identity/constant term always goes into the commuting partition.
- partition_by_single_fermionic_evolution_commutation(p, q)
Partitions the sum into (commuting, non-commuting) relative to a SingleFermionicEvolutionGate acting on qubits p and q.
A Pauli string commutes with the gate when the local Pauli pattern on (p, q) is one of: II, XX, YY, ZZ. The identity/constant term always goes into the commuting partition.
- partition_by_single_fermionic_excitation_commutation(p, q)
Partitions the sum into (commuting, non-commuting) relative to a SingleFermionicExcitationGate acting on qubits p and q.
The gate is a SingleExcitationGate whose generator carries a Z string on the qubits strictly between p and q, so a Pauli string with an odd number of X/Y there commutes with the gate exactly when its pattern on (p, q), with Z toggled on p, commutes with the SingleExcitationGate. The identity/constant term always goes into the commuting partition.
- prune(tolerance)
- string_coefficient_pairs()
Usage of the string_coefficient_pairs method is discouraged. Use proper rust code for efficient data handling. This is only provided for Python compatibility.
- terms_as_int
Usage of the terms_as_int method is discouraged. Use proper rust code for efficient data handling. This is only provided for Python compatibility. Note: This now reconstructs the int_terms on each call since we no longer store it.
- class ParallelSetting
Bases:
object- Parallel = ParallelSetting.Parallel
- Serial = ParallelSetting.Serial
- class ParticleConservation
Bases:
object- Spin = ParticleConservation.Spin
- Total = ParticleConservation.Total
- class PauliString
Bases:
object- classmethod __new__(*args, **kwargs)
- as_ints()
Returns bitmasks (x, y, z) as Python ints (via BigUint).
- commutative_sign(other)
Returns the sign when commuting with another PauliString (-1 or 1).
- classmethod from_sorted_and_disjoint_sets(x_indices=None, y_indices=None, z_indices=None)
- classmethod from_stabilizer(stabilizer)
- classmethod from_z_indices(z_indices)
- is_commuting(other)
Check if the Pauli string commutes with another.
- is_diagonal()
Check if the Pauli string only contains diagonal (I and Z) operators.
- is_identity()
- max_index
- min_index
- multiply(other)
Multiply with another PauliString.
- shift_by_one()
Return a new PauliString with all qubit indices shifted by one (+1).
- to_stabilizer(num_qubits=None)
Convert this Pauli string to a stabilizer.
- Parameters:
num_qubits (-) – Optional circuit width used to validate the Pauli indices. The sparse bitmask representation does not otherwise need the circuit width.
- x_indices
- y_indices
- z_indices
- class ReducedPauliSums
Bases:
objectObservables reduced on fixed qubits: the unique reduced Pauli strings and, per observable, a constant plus a sparse row (CSR indptr, indices, coefficients) into those strings.
- coefficients
Coefficient of each term.
- constants
Constant part of each observable.
- indices
Index into strings of each term.
- indptr
the terms of observable i are indptr[i]..indptr[i + 1].
- Type:
CSR row pointers
- strings
The unique reduced Pauli strings to estimate.
- class RustCircuit
Bases:
object- classmethod __new__(*args, **kwargs)
- controlled(control_qubit_index)
Mark the next appended gate as controlled by the given qubit.
- cx(control_qubit_index, target_qubit_index)
Append a gate corresponding to the CXGate in Kvantify Qrunch.
- decay(random_threshold, index)
Append a gate corresponding to the Decay.
- dephasing(random_threshold, index)
Append a gate corresponding to the Dephasing.
- diagonal_pauli(parameter, z_indices)
Append a gate corresponding to the DiagonalPauliGate (Z-only Pauli).
- double_excitation(parameter, creation_qubit_index_1, creation_qubit_index_2, annihilation_qubit_index_1, annihilation_qubit_index_2)
Append a gate corresponding to the DoubleExcitationGate in Kvantify Qrunch.
- double_fermionic_evolution(parameter, creation_qubit_index_1, creation_qubit_index_2, annihilation_qubit_index_1, annihilation_qubit_index_2)
Append a gate corresponding to the DoubleFermionicEvolutionGate in Kvantify Qrunch.
- double_fermionic_excitation(parameter, creation_qubit_index_1, creation_qubit_index_2, annihilation_qubit_index_1, annihilation_qubit_index_2)
Append a gate corresponding to the DoubleFermionicExcitationGate in Kvantify Qrunch.
- num_qubits()
- pauli(parameter, x_indices, y_indices, z_indices)
Append a gate corresponding to the PauliGate.
- requires_complex_numbers()
- rx(parameter, qubit_index)
Append a gate corresponding to the RXGate in Kvantify Qrunch.
- ry(parameter, qubit_index)
Append a gate corresponding to the RYGate in Kvantify Qrunch.
- rz(parameter, qubit_index)
Append a gate corresponding to the RZGate in Kvantify Qrunch.
- single_excitation(parameter, creation_qubit_index, annihilation_qubit_index)
Append a gate corresponding to the SingleExcitationGate in Kvantify Qrunch.
- single_fermionic_evolution(parameter, creation_qubit_index, annihilation_qubit_index)
Append a gate corresponding to the SingleFermionicEvolutionGate in Kvantify Qrunch.
- single_fermionic_excitation(parameter, creation_qubit_index, annihilation_qubit_index)
Append a gate corresponding to the SingleFermionicExcitationGate in Kvantify Qrunch.
- x(qubit_index)
Append a gate corresponding to the XGate in Kvantify Qrunch.
- xx_plus_yy(parameter, qubit_index_1, qubit_index_2)
Append a gate corresponding to the XXplusYYGate.
- class RustEstimatingResult
Bases:
object- expectation_values
- number_of_amplitudes_used
- state_vector_error
- class RustMemoryRestrictedSimulator
Bases:
object- classmethod __new__(*args, **kwargs)
- estimate(observables, circuit)
- get_cached_effective_max_number_of_amplitudes()
- get_state_vector(circuit)
- sample(circuit, shots)
- class RustStateVectorResult
Bases:
object- amplitudes
- number_of_amplitudes_used
- state_vector_error
- class Stabilizer
Bases:
objectStabilizer of Pauli strings, represented by dynamically sized Z and X bitmasks. Trailing identity qubits are implicit and do not affect equality or multiplication.
- classmethod __new__(*args, **kwargs)
- apply_cx_gate(control_index, target_index)
Conjugate the stabilizer by a controlled-X gate.
- Parameters:
control_index (-) – Control qubit of the gate.
target_index (-) – Target qubit of the gate.
- apply_h_gate(index)
Conjugate the stabilizer by a Hadamard gate.
- Parameters:
index (-) – Qubit on which the gate acts.
- apply_s_gate(index)
Conjugate the stabilizer by an S gate.
- Parameters:
index (-) – Qubit on which the gate acts.
- apply_sdg_gate(index)
Conjugate the stabilizer by an inverse S gate.
- Parameters:
index (-) – Qubit on which the gate acts.
- apply_x_gate(index)
Conjugate the stabilizer by an X gate on index.
- apply_y_gate(index)
Conjugate the stabilizer by a Y gate on index.
- apply_z_gate(index)
Conjugate the stabilizer by a Z gate on index.
- multiply(other)
Multiplies with another stabilizer. Returns (Resulting Stabilizer, Complex Phase)
- x
- z
- compute_excitation_metrics_topk_biguint(observable, measurements_integer_dict, num_alpha_electrons, num_beta_electrons, num_spatial_orbitals, include_single, include_double, excluded_indices, metric_type, expectation_value, top_k, single_scaling_factor)
Combined excitation index generation + metric computation + top-k selection (BigUint measurements).
Same as compute_excitation_metrics_topk_u64 but for systems with >= 65 qubits. Excitations are processed in batches to limit peak memory.
- compute_excitation_metrics_topk_u64(observable, measurements_integer_dict, num_alpha_electrons, num_beta_electrons, num_spatial_orbitals, include_single, include_double, excluded_indices, metric_type, expectation_value, top_k, single_scaling_factor)
Combined excitation index generation + metric computation + top-k selection (u64 measurements).
This function combines three steps in a single Rust call, avoiding repeated Python↔Rust boundary crossings and the overhead of creating millions of Python GatePoolOperator objects:
Generate excitation indices in batches (filtering excluded ones)
Compute importance metrics for each batch
Stream results into a top-k accumulator
Excitations are processed in batches of EXCITATION_BATCH_SIZE to limit peak memory usage when the total count scales as O(N⁴).
- Parameters:
observable – The Hamiltonian / observable
measurements_integer_dict – Sparse measurement map {bitstring_int: probability}
num_alpha_electrons – Number of alpha (spin-up) electrons
num_beta_electrons – Number of beta (spin-down) electrons
num_spatial_orbitals – Number of spatial orbitals
include_single – Whether to include single excitations
include_double – Whether to include double excitations
excluded_indices – Indices to exclude (already selected/excluded gates)
metric_type – 0 = heuristic_gradient, 1 = full_heuristic_gradient, 2 = selected_ci
expectation_value – Current expectation value (only used for selected_ci)
top_k – Number of top entries to return
single_scaling_factor – Scaling factor applied to single excitation metrics
- Returns:
Tuple of (top_k_results, total_metric_sum) where top_k_results is a list of (indices, metric) tuples sorted by metric descending.
- compute_pair_excitation_metrics_topk_biguint(observable, measurements_integer_dict, num_electron_pairs, num_spatial_orbitals, include_single, include_double, excluded_indices, metric_type, expectation_value, top_k, single_scaling_factor)
Combined pair-excitation index generation + metric computation + top-k selection (BigUint measurements).
Same as compute_pair_excitation_metrics_topk_u64 but for systems with >= 65 qubits.
- compute_pair_excitation_metrics_topk_u64(observable, measurements_integer_dict, num_electron_pairs, num_spatial_orbitals, include_single, include_double, excluded_indices, metric_type, expectation_value, top_k, single_scaling_factor)
Combined pair-excitation index generation + metric computation + top-k selection (u64 measurements).
This is the BEAST analogue of compute_excitation_metrics_topk_u64. Instead of alpha/beta spin sectors, pair excitations operate on a single set of spatial orbitals with occupied pairs in [0, num_electron_pairs) and virtual orbitals in [num_electron_pairs, num_spatial_orbitals).
- Parameters:
observable – The Hamiltonian / observable
measurements_integer_dict – Sparse measurement map {bitstring_int: probability}
num_electron_pairs – Number of occupied electron pairs
num_spatial_orbitals – Number of spatial orbitals
include_single – Whether to include single pair excitations
include_double – Whether to include double pair excitations
excluded_indices – Indices to exclude (already selected/excluded gates)
metric_type – 0 = heuristic_gradient, 1 = full_heuristic_gradient, 2 = selected_ci
expectation_value – Current expectation value (only used for selected_ci)
top_k – Number of top entries to return
single_scaling_factor – Scaling factor applied to single pair excitation metrics
- create_hermitian_pauli_sum_from_fermionic_hamiltonian(one_body_alpha_alpha, one_body_beta_beta, two_body_alpha_alpha, two_body_beta_beta, two_body_beta_alpha, number_of_qubits, tolerance=1e-10)
- create_hermitian_pauli_sum_from_hardcore_bosonic_hamiltonian(one_body_matrix, two_body_matrix, number_of_qubits, tolerance=1e-10)
- find_greedy_boltzmann_bisection_contraction_path(einsum_string, shapes, seed, boltzmann_pool, boltzmann_rounds, greedy_threshold, coarsen_target, initial_partition_restarts, bisection_trials, bisection_cut_model, hyper_greedy_boltzmann_rounds, hyper_greedy_boltzmann_pool, cost_revalidation_tolerance, int_cost_revalidation_tolerance, sa_num_iters_per_seed, sa_initial_temp, sa_seeds_per_thread, sa_nominal_threads, sa_max_warm_starts, sa_rotation_fraction, lookahead, memory_limit_elements, max_slices, slice_min_benefit, slice_candidate_paths, slice_reconf_rounds, slice_probe_candidates, slice_reconf_subtree_leaves, subtree_reconfigure_leaves, subtree_reconfigure_rounds, slicing_aware_rounds, slice_memory_penalty, slice_max_flops_overhead, slice_max_flops_per_memory_bit, slice_peak_reduction_factor, search_restarts, dense_geometry_restarts, greedy_return_flops, int_trials_return_flops)
Find the best contraction path using the adaptive strategy.
Combines integer-space greedy (correct for high-dimensional networks), log-space exploration (good diversity for low-dimensional networks), and multi-level bisection.
- Parameters:
einsum_string (-) – Einstein summation notation (e.g. “ab,bc->ac”).
shapes (-) – Dimension shapes for each operand, matching einsum order.
seed (-) – PRNG seed for reproducible Boltzmann sampling.
boltzmann_pool (-) – Top-K candidates for int-space Boltzmann sampling.
boltzmann_rounds (-) – Number of int-space Boltzmann trial rounds.
greedy_threshold (-) – Subproblem size at which bisection falls back to greedy.
coarsen_target (-) – Target node count for the coarsened hypergraph.
initial_partition_restarts (-) – Random restarts for initial partition.
bisection_trials (-) – Number of independent bisection trials with different seeds.
bisection_cut_model (-) – How a bipartition charges an index spanning both sides. “hyperedge” charges it once, which is what the resulting intermediate costs; “clique” charges it once per straddling pair.
hyper_greedy_boltzmann_rounds (-) – Boltzmann rounds in the log-space hyper-greedy phase.
hyper_greedy_boltzmann_pool (-) – Pool size for hyper-greedy Boltzmann sampling.
cost_revalidation_tolerance (-) – Tolerance for lazy cost revalidation in deterministic greedy phases.
sa_num_iters_per_seed (-) – SA iterations per seed (0 = disabled).
sa_initial_temp (-) – Initial temperature for SA Metropolis criterion.
sa_seeds_per_thread (-) – Number of SA seeds per thread (total = this x threads).
sa_max_warm_starts (-) – Maximum warm-start paths from each phase for SA.
sa_rotation_fraction (-) – Fraction of SA mutations that are tree rotations (0.0-1.0). The remainder are subtree swaps.
memory_limit_elements (-) – Peak live memory budget in tensor elements; indices are sliced until one slice fits. <= 0 disables slicing.
max_slices (-) – Hard cap on the number of sliced indices.
slice_candidate_paths (-) – Number of warm-start paths sliced alongside the winner so the post-slicing best can win.
slice_reconf_rounds (-) – Rounds of alternating tree re-annealing against the sliced dimensions and re-slicing.
slice_probe_candidates (-) – How many warm starts are probe-sliced before slice reconfiguration picks its repair pool (0 keeps dense order).
slice_reconf_subtree_leaves (-) – Largest frontier the exact subtree DP re-derives during slice reconfiguration; below 3 disables it.
subtree_reconfigure_leaves (-) – Largest subtree frontier re-derived exactly; the subset DP costs 3^k. Below 3 disables it.
subtree_reconfigure_rounds (-) – Sweeps of subtree reconfiguration.
slicing_aware_rounds (-) – How many times the whole tree search is re-run against the cuts the previous round found. 1 is a single pass.
slice_memory_penalty (-) – Bits of FLOPs one bit of peak memory is worth when ranking sliced candidates. Charged on the whole peak, since every candidate already fits the ceiling; 0 ranks on FLOPs alone.
slice_max_flops_overhead (-) – Largest total-FLOP increase slicing may cause, as a factor of the path’s dense FLOP count. <= 1 cuts until the memory budget is met regardless of cost.
slice_max_flops_per_memory_bit (-) – Most bits of extra total FLOPs one bit of peak-memory reduction may cost, judged per cut and applied only once memory_limit_elements is met. 0 stops at the budget unless a cut is free.
slice_peak_reduction_factor (-) – Smallest factor by which slicing must reduce the path’s own dense peak; the effective ceiling is the lower of this and memory_limit_elements. <= 1 disables it.
search_restarts (-) – Number of independent searches with different seeds; the best result wins.
dense_geometry_restarts (-) – How many of those restarts search the dense index dimensions instead of the pre-sliced ones.
greedy_return_flops (-) – Return the cheapest deterministic greedy path, before any other search, when it needs no slicing and costs at most this many FLOPs. <= 0 disables it.
int_trials_return_flops (-) – End each search after its integer-space greedy trials when their best path costs at most this many FLOPs. <= 0 disables it.
Returns (path, sliced_positions) where path is a list of (i, j) index pairs in linear (positional) form and sliced_positions gives one (operand, axis, slice_size) triple per sliced index, empty when nothing was sliced.
- fock_weighted_zzzz_from_diagonal_weighted_values(quadruples, diagonal_weighted_values, zzz_values, fock_diagonal, fock_weighted_zzzz, dimension)
Set
fock_weighted_zzzz[rank(Q)] = <Z_Q W> - sum_{e in Q} f_ee <Z_{Q \ {e}}>for every sorted qubit quadrupleQ, whereW = sum_p f_pp Z_p. This issum_{p not in Q} f_pp <Z_Q Z_p>.zzz_values are indexed like
combinations(range(dimension), 3).
- full_heuristic_gradient_metrics_biguint(observable, measurements_integer_dict, gate_pool_as_generator_indices)
- full_heuristic_gradient_metrics_for_custom_operators(observable, measurements_integer_dict, gate_pool_as_generator_dict_list)
- full_heuristic_gradient_metrics_u64(observable, measurements_integer_dict, gate_pool_as_generator_indices)
- generate_1_rdm_operators(num_qubits)
Generate the operators needed for the 1-particle reduced density matrix.
Returns two lists: 1. diagonal_operators – n operators of the form 0.5*Z(p) + 0.5*Z(p+n). 2. off_diagonal_operators – C(n,2) operators for p < q with alpha+beta XX+YY terms.
The Python side uses them as: gamma[p,p] = 1 - <diagonal_op_p> and gamma[p,q] = gamma[q,p] = <off_diagonal_op_{p,q}>.
- generate_2_rdm_operators(num_qubits)
Generate the operators needed for the 2-particle reduced density matrix.
Returns a tuple of: 1. operators – the list of HermitianPauliSum to estimate. 2. skip_indexes – the set of (p, r, s, q) tuples that produced zero operators. 3. canonical_indices – the canonical (p, r, s, q) tuples from the iteration.
- generate_3_rdm_operators(num_qubits)
Generate the operators needed for the 3-particle reduced density matrix.
- generate_4_rdm_operators(num_qubits)
Generate the operators needed for the 4-particle reduced density matrix.
- generate_excitation_indices(num_alpha_electrons, num_beta_electrons, num_spatial_orbitals, include_single, include_double)
Generate all excitation gate pool indices for a molecular electron configuration.
This is a fast Rust implementation that generates all valid single and/or double excitation operators, returning them as index lists that can be directly used by the metric calculators.
- Parameters:
num_alpha_electrons – Number of alpha (spin-up) electrons
num_beta_electrons – Number of beta (spin-down) electrons
num_spatial_orbitals – Number of spatial orbitals
include_single – Whether to include single excitations
include_double – Whether to include double excitations
- Returns:
A list of index lists. Single excitations have 2 indices, double excitations have 4.
- generate_restricted_1_rdm_operators(num_qubits)
Generate the operators needed for the restricted 1-particle reduced density matrix.
Returns operators whose expectation values directly give gamma[p,q]. Order: combinations_with_replacement(0..n, 2) where n = num_qubits / 2.
Diagonal (p == q): I - 0.5*Z(p) - 0.5*Z(p+n) → <op> = n_p_alpha + n_p_beta = gamma[p,p]
Off-diagonal (p < q): JW-mapped 0.5*(a†_p a_q + a†_q a_p)_alpha + 0.5*(…)_beta
- generate_restricted_2_rdm_operators(num_qubits)
Generate the operators needed for the restricted 2-particle reduced density matrix.
Uses 2-fold symmetry: {(p,q,r,s), (s,r,q,p)}. For each canonical (p,q,r,s), generates the combined operator summing over all spin combos (alpha-alpha, beta-beta, and mixed with factor 2).
Returns (operators, indices).
- generate_restricted_2_rdm_operators_batched(num_qubits, batch_start, batch_end)
Generate a batch of restricted 2-RDM operators for a slice of canonical indices.
batch_start and batch_end refer to the range of canonical 2-fold symmetric indices to process. This allows the Python side to iterate in memory-friendly chunks.
Returns (operators, indices) for the batch.
- generate_unrestricted_1_rdm_operators(num_qubits, spin_component)
Generate the operators needed for the unrestricted 1-particle reduced density matrix for a single spin component.
spin_component: 0 for alpha, 1 for beta.
Returns operators in the order of combinations_with_replacement(0..n, 2) where n = num_qubits / 2. - Diagonal (p == q): (I - Z_{p + spin*n}) / 2 - Off-diagonal (p < q): 0.25 * (X_{p+s*n} * Z_chain * X_{q+s*n} + Y_{p+s*n} * Z_chain * Y_{q+s*n})
Expectation values directly give gamma[p,q].
- generate_unrestricted_2_rdm_operators_mixed(num_qubits)
Generate the operators needed for the unrestricted mixed-spin 2-particle RDM.
This generates operators for the beta-alpha-beta-alpha (physics ordering) component: a†_{p+n} a†_q a_r a_{s+n}
Uses 2-fold symmetry: {(p,q,r,s), (s,r,q,p)}. For each valid (p,q,r,s): - If p==s and q==r: coefficient 1.0 - Otherwise: 0.5 * (operator + Hermitian conjugate)
Returns (operators, indices).
- generate_unrestricted_2_rdm_operators_mixed_batched(num_qubits, batch_start, batch_end)
Generate a batch of mixed-spin 2-RDM operators for a slice of canonical indices.
batch_start and batch_end refer to the range of canonical indices to process. This allows the Python side to iterate in memory-friendly chunks.
Returns (operators, indices) for the batch.
- generate_unrestricted_2_rdm_operators_same_spin(num_qubits, spin_component)
Generate the operators needed for the unrestricted same-spin 2-particle RDM.
spin_component: 0 for alpha-alpha, 1 for beta-beta.
Uses 8-fold symmetry. Skips indices where p==q or r==s. For each valid (p,q,r,s), generates the Hermitian combination: - If p==s and q==r: coefficient 1.0 for a†_p a†_q a_r a_s - Otherwise: 0.5 * (a†_p a†_q a_r a_s + a†_s a†_r a_q a_p)
Returns (operators, indices).
- generate_unrestricted_2_rdm_operators_same_spin_batched(num_qubits, spin_component, batch_start, batch_end)
Generate a batch of same-spin 2-RDM operators for a slice of canonical indices.
batch_start and batch_end refer to the range of valid (non-filtered) indices to process. This allows the Python side to iterate in memory-friendly chunks.
Returns (operators, indices) for the batch.
- generate_xx_operators(dimension)
Generate all C(dimension, 2) HermitianPauliSums, each containing a single X⊗X Pauli string over every unique 2-qubit combination.
- generate_xx_plus_yy_operators(dimension)
Generate all
C(dimension, 2)two-term HermitianPauliSumsX[x]*X[y] + Y[x]*Y[y]for each unique pair(x, y).
- generate_xx_plus_yy_with_z_operators(dimension)
Generate (X[x]*X[y]+Y[x]*Y[y]) * Z[p] operators.
For each (x, y) with x < y, and each p ∉ {x, y}, produce a two-term sum.
- generate_xx_plus_yy_with_zz_operators(dimension)
Generate (X[x]*X[y]+Y[x]*Y[y]) * Z[p]*Z[q] operators.
For each (x, y) with x < y, and each (p, q) with p < q and {p,q} ∩ {x,y} = ∅, produce a two-term sum.
- generate_xx_with_z_operators(dimension)
Generate X[x]*X[y]*Z[p] operators in the order of [generate_xx_plus_yy_with_z_operators].
- generate_xx_with_zz_operators(dimension)
Generate X[x]*X[y]*Z[p]*Z[q] operators in the order of [generate_xx_plus_yy_with_zz_operators].
- generate_xx_with_zz_operators_for_pair_rank_range(dimension, start, stop)
Generate the operators of [generate_xx_with_zz_operators] of the pairs (x, y) with lexicographic rank in
start..stop, soC(dimension - 2, 2)operators per pair.
- generate_xxxx_plus_yyyy_operators(dimension)
Generate all C(dimension, 4) HermitianPauliSums, each containing two terms: X⊗X⊗X⊗X + Y⊗Y⊗Y⊗Y over every unique 4-qubit combination.
- generate_xxyy_operators(dimension)
Generate XXYY operators for pair-of-pairs iteration.
For each (x, y) with x < y, and each (p, q) with p < q and {p,q} ∩ {x,y} = ∅, produce a single-term sum: X[x]*X[y]*Y[p]*Y[q].
- generate_xxyy_pairing_operators(dimension)
Generate the three pairings
X[a]*X[b]*Y[c]*Y[d],X[a]*X[c]*Y[b]*Y[d]andX[a]*X[d]*Y[b]*Y[c]of every quadruplea < b < c < d, quadruples in lexicographic order.For particle-number conserving states
X[x]X[y]Y[p]Y[q]andX[p]X[q]Y[x]Y[y]have the same expectation value, so these3 * C(n, 4)operators determine all operators of [generate_xxyy_operators].
- generate_xxyy_pairing_operators_for_rank_range(dimension, start, stop)
Generate the three pairings of [generate_xxyy_pairing_operators] of the quadruples with lexicographic rank in
start..stop, so3 * (stop - start)operators.
- generate_z_operators(dimension)
Generate all
dimensionHermitianPauliSums, each containing a single Z Pauli string on one qubit.
- generate_zz_operators(dimension)
Generate all C(dimension, 2) HermitianPauliSums, each containing a single Z⊗Z Pauli string over every unique 2-qubit combination.
- generate_zzz_operators(dimension)
Generate all C(dimension, 3) HermitianPauliSums, each containing a single Z⊗Z⊗Z Pauli string over every unique 3-qubit combination.
- generate_zzzz_operators(dimension)
Generate all C(dimension, 4) HermitianPauliSums, each containing a single Z⊗Z⊗Z⊗Z Pauli string over every unique 4-qubit combination.
- generate_zzzz_operators_for_rank_range(dimension, start, stop)
Generate the operators of [generate_zzzz_operators] with index in
start..stop, which is the lexicographic rank of the quadruple.
- generate_zzzzz_operators(dimension)
Generate all C(dimension, 5) HermitianPauliSums, each containing a single Z⊗Z⊗Z⊗Z⊗Z Pauli string over every unique 5-qubit combination.
- generate_zzzzz_operators_for_active_terms(active_terms, dimension)
Generate Z⊗Z⊗Z⊗Z⊗Z operators for a subset of qubit quintuples determined by active pair-breaking terms.
For each active term
(y, x, v, u)and each qubitein0..dimensionthat is not in{y, x, v, u}, produce a single-termHermitianPauliSumcontainingZ(y)*Z(x)*Z(v)*Z(u)*Z(e).The ordering exactly matches the Python loop:
for active_term in active_terms: for e in range(n): if e in {y, x, v, u}: continue ...
Identical sorted 5-tuples arising from different active terms are deduplicated. Returns (unique_operators, scatter_indices) where scatter_indices[i] maps position i in the original flat layout to the index into unique_operators.
- get_restricted_2_rdm_num_indices(num_qubits)
Return the number of canonical 2-fold symmetric index tuples for the restricted 2-RDM.
This is used by the Python side to determine batch boundaries without generating operators.
- get_unrestricted_2_rdm_num_indices_mixed(num_qubits)
Return the number of canonical 2-fold symmetric index tuples for mixed-spin 2-RDM.
This is used by the Python side to determine batch boundaries without generating operators.
- get_unrestricted_2_rdm_num_indices_same_spin(num_qubits)
Return the number of canonical 8-fold symmetric index tuples for same-spin 2-RDM, after filtering out p==q or r==s cases.
This is used by the Python side to determine batch boundaries without generating operators.
- heuristic_gradient_metrics_biguint(observable, measurements_integer_dict, gate_pool_as_generator_indices)
- heuristic_gradient_metrics_for_custom_operators(observable, measurements_integer_dict, gate_pool_as_generator_dict_list)
- heuristic_gradient_metrics_u64(observable, measurements_integer_dict, gate_pool_as_generator_indices)
- multiply_paulis(paulis)
- needed_quadruples_for_rank_range(start, stop, needed_quadruples, dimension)
Return the lexicographic ranks in
start..stopof the quadruples marked in needed_quadruples, which is indexed likecombinations(range(dimension), 4), together with the sorted qubit quadruples.
- reduce_pauli_sums_on_fixed_qubits(observables, fixed_mask, occupied_mask)
Reduce the observables for a state in which the fixed_mask qubits are in the computational basis state given by occupied_mask and unentangled with the rest.
Terms with X or Y on a fixed qubit have zero expectation value and are dropped, Z on a fixed qubit is replaced by its eigenvalue, and the remaining Pauli strings are deduplicated. The expectation value of observable i is constants[i] + sum(coefficients[k] * <strings[indices[k]]>) for k in indptr[i]..indptr[i + 1].
- selected_ci_metrics_biguint(observable, measurements_integer_dict, gate_pool_as_generator_indices, expectation_value)
- selected_ci_metrics_for_custom_operators(observable, measurements_integer_dict, gate_pool_as_generator_dict_list, expectation_value)
- selected_ci_metrics_u64(observable, measurements_integer_dict, gate_pool_as_generator_indices, expectation_value)
- top_k_double_excitation_metrics_from_integrals(eri_aa, eri_bb, eri_ba, n_alpha_occ, n_beta_occ, n_spatial, top_k)
Compute the top-k double-excitation heuristic gradient metrics directly from the molecular electron-repulsion integrals (ERIs) using the Slater–Condon rules, without building the qubit Hamiltonian.
For a double excitation i_ρ → a_ρ , j_ν → b_ν the first-order metric is:
- Same-spin (ρ = ν):
M = abs(⟨a b || i j⟩) = abs(g[a,j,b,i] − g[a,i,b,j])
- Mixed-spin (ρ ≠ ν):
M = abs(eri_ba[b,j,a,i])(or transposed, depending on which spin is alpha)
The function enumerates all spin-conserving double excitations, keeps only the top_k largest, and returns them sorted descending.
Generator-indices convention:
[c1, c2, a1, a2]where c1 < c2 are creation (virtual) qubit indices, a1 < a2 are annihilation (occupied) qubit indices. Alpha qubits are[0, n_spatial), beta are[n_spatial, 2·n_spatial).- Parameters:
eri_aa – Alpha-alpha 4-index ERI tensor, shape (n_sp, n_sp, n_sp, n_sp).
eri_bb – Beta-beta 4-index ERI tensor.
eri_ba – Beta-alpha 4-index ERI tensor.
n_alpha_occ – Number of occupied alpha orbitals.
n_beta_occ – Number of occupied beta orbitals.
n_spatial – Number of spatial orbitals.
top_k – Maximum number of results to return.
- top_k_pair_excitation_metrics_from_integrals(single_excitation_array, n_occ, n_spatial, top_k)
Compute the top-k pair-excitation metrics for the BEAST Hamiltonian directly from the reduced one-body integrals
h^{(r1)}.For a pair excitation i → a (moving a pair from occupied spatial orbital i to virtual spatial orbital a) the first-order metric derived from the BEAST Hamiltonian is:
M_{ai} = |h^{(r1)}_{a,i}|where
h^{(r1)}_{p,q} = h_{p,q} δ_{pq} + (pq|pq). For a ≠ i this simplifies to(ai|ai)– the pair-transfer integral.The function enumerates all pair excitations from occupied orbitals
[0, n_occ)to virtual orbitals[n_occ, n_spatial), keeps only the top_k largest by absolute value, and returns them sorted descending.Generator-indices convention:
[creation_qubit, annihilation_qubit]where qubit indices are in[0, n_spatial).- Parameters:
single_excitation_array – The
h^{(r1)}matrix, shape(n_spatial, n_spatial).n_occ – Number of occupied (pair-occupied) spatial orbitals.
n_spatial – Total number of spatial orbitals.
top_k – Maximum number of results to return.
- top_k_single_excitation_metrics_from_integrals(h_alpha, h_beta, eri_aa, eri_bb, eri_ba, n_alpha_occ, n_beta_occ, n_spatial, top_k)
Compute the top-k first-order single-excitation metrics (Fock matrix off-diagonal elements) directly from one-body and two-body integrals, without building the qubit Hamiltonian.
For a single excitation i_ρ → a_ρ the first-order metric is the absolute value of the Fock matrix element:
- Alpha excitation (a, i both in alpha sector):
F_{ai} = h_α[a,i] + Σ_j∈occ_α (g_αα[a,i,j,j] − g_αα[a,j,j,i]) + Σ_j∈occ_β g_βα[j,j,a,i]
- Beta excitation (a, i both in beta sector):
F_{ai} = h_β[a,i] + Σ_j∈occ_β (g_ββ[a,i,j,j] − g_ββ[a,j,j,i]) + Σ_j∈occ_α g_βα[a,i,j,j]
M =
abs(F_{ai})Generator-indices convention: [creation_qubit, annihilation_qubit]. Alpha qubits are [0, n_spatial), beta are [n_spatial, 2·n_spatial).
- Parameters:
h_alpha – Alpha one-body integrals, shape (n_spatial, n_spatial).
h_beta – Beta one-body integrals, shape (n_spatial, n_spatial).
eri_aa – Alpha-alpha 4-index ERI tensor, shape (n_sp, n_sp, n_sp, n_sp).
eri_bb – Beta-beta 4-index ERI tensor.
eri_ba – Beta-alpha 4-index ERI tensor.
n_alpha_occ – Number of occupied alpha orbitals.
n_beta_occ – Number of occupied beta orbitals.
n_spatial – Number of spatial orbitals.
top_k – Maximum number of results to return.
- top_k_single_excitation_metrics_second_order_from_integrals(h_alpha, h_beta, eri_aa, eri_bb, eri_ba, n_alpha_occ, n_beta_occ, n_spatial, top_k)
Compute the top-k second-order single-excitation metrics from the BCH expansion directly from one-body and two-body integrals, without building the qubit Hamiltonian.
For a single excitation i_ρ → a_ρ the second-order metric is:
M_{ai}^{(2)} = abs(2 * (ε_a − ε_i − J_{ai} + K_{ai}))where ε_p is the Fock diagonal (orbital energy), and J_{ai}, K_{ai} are Coulomb and exchange integrals between orbitals a and i.
- Alpha (a, i in alpha sector):
ε_p = h_α[p,p] + Σ_k∈occ_α (g_αα[p,p,k,k] − g_αα[p,k,k,p]) + Σ_k∈occ_β g_βα[k,k,p,p]J_{ai} = g_αα[a,a,i,i]K_{ai} = g_αα[a,i,a,i]
- Beta (a, i in beta sector):
ε_p = h_β[p,p] + Σ_k∈occ_β (g_ββ[p,p,k,k] − g_ββ[p,k,k,p]) + Σ_k∈occ_α g_βα[p,p,k,k]J_{ai} = g_ββ[a,a,i,i]K_{ai} = g_ββ[a,i,a,i]
Generator-indices convention: [creation_qubit, annihilation_qubit]. Alpha qubits are [0, n_spatial), beta are [n_spatial, 2·n_spatial).
- Parameters:
h_alpha – Alpha one-body integrals, shape (n_spatial, n_spatial).
h_beta – Beta one-body integrals, shape (n_spatial, n_spatial).
eri_aa – Alpha-alpha 4-index ERI tensor, shape (n_sp, n_sp, n_sp, n_sp).
eri_bb – Beta-beta 4-index ERI tensor.
eri_ba – Beta-alpha 4-index ERI tensor.
n_alpha_occ – Number of occupied alpha orbitals.
n_beta_occ – Number of occupied beta orbitals.
n_spatial – Number of spatial orbitals.
top_k – Maximum number of results to return.
- z_strings_with_diagonal_weight_from_distribution(bitstrings, probabilities, weights, z_strings)
Compute
<Z_Q W>withW = sum_p weights[p] Z_pfor every rowQof z_strings.- Parameters:
bitstrings (-) – One row per basis state of little-endian 64-bit words; qubit
qis bitq % 64of wordq / 64.probabilities (-) – Probability (or sampled frequency) of each basis state.
weights (-) – Weight
w_pofZ_pfor every qubitp.z_strings (-) – Qubit indices of each Z string, one string per row, padded with
-1.