> ## Documentation Index
> Fetch the complete documentation index at: https://docs.classiq.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Sample-Based Krylov Quantum Diagonalization (SKQD)

> [card] [View on GitHub](https://github.com/Classiq/classiq-library/blob/main/algorithms/quantum_phase_estimation/SKQD/skqd.ipynb)
>
> Open this notebook in GitHub to run it yourself

SKQD \[[1](#skqd)] estimates the **ground-state energy** of a Hamiltonian $H$. It is an alternative to Quantum Phase Estimation (QPE), designed for
pre-fault-tolerant hardware.

QPE, the textbook quantum algorithm for eigenvalue estimation, is for now out of reach: it
requires circuits far too deep for current, noisy hardware.

This has motivated a search for
shallower, near-term alternatives.

One promising family is the **subspace diagonalization**
algorithms, in which a quantum module identifies a low-dimensional subspace of the Hilbert space
expected to contain most of the ground state's weight, and a classical module then diagonalizes
$H$ restricted to that subspace.

These methods differ in how the quantum module builds the
subspace. In **Krylov quantum diagonalization (KQD)** \[[2](#kqd)], it is spanned by time-evolving a
reference state over a range of time intervals. In **sample-based quantum diagonalization (SQD)**, it is spanned by
sampling a reference state in the computational basis (see \[[3](#sqd)] for example).

**Sample-based Krylov quantum diagonalization (SKQD)** \[[1](#skqd)], which we implement in this notebook, draws
on both: a well-chosen reference state is time-evolved over several time intervals, and each evolved
state is then sampled in the computational basis.

The sampled bitstrings define the subspace in
which we classically diagonalize $H$.

Like KQD, SKQD comes with a **polynomial-time convergence guarantee** (under certain assumptions we mention below), but it
uses shallower circuits than KQD, and the sampling makes it more robust to noise.

In this notebook we implement SKQD, using the **single-impurity Anderson model (SIAM)** \[[4](#anderson)] as a worked
example.

## The idea

Starting from a reference state $|\psi_0\rangle$, real-time evolution generates the
**Krylov states**

$$
|\psi_k\rangle = e^{-iH\,k\,\Delta t}\,|\psi_0\rangle, \qquad k = 0, 1, \dots, D-1 .
$$

Their span is a Krylov subspace that, provided $|\psi_0\rangle$ has sufficient overlap
with the true ground state,  captures the low-energy physics, so diagonalizing $H$
restricted to that subspace gives a good ground-energy estimate.

The **sample-based** twist avoids measuring overlaps with Hadamard tests.

Instead we
sample each $|\psi_k\rangle$ in the computational basis, collect the set
$\mathcal{S}$ of observed bitstrings,
and diagonalize $H$ projected onto $\mathrm{span}(\mathcal{S})$.

Informally, the main assumptions are (the full convergence analysis is considerably more intricate;
see Theorem 1 of \[[1](#skqd)]):

1. **Ground-state overlap.** The reference $|\psi_0\rangle$ needs appreciable overlap with the
   true ground state; the smaller the overlap, the more Krylov vectors and shots are needed.
2. **Ground-state sparsity.** The ground state must be reasonably sparse in the computational
   basis, so that sampling actually collects the few configurations that carry its weight.

**Complexity.** Made quantitative (inverse-polynomial overlap and a polynomially sparse ground state), these assumptions yield a polynomial-time ground-energy estimate \[[1](#skqd)].

The notebook first builds a generic time-evolution core, then instantiates it on the SIAM
example — constructing the Hamiltonian, mapping it to qubits, and preparing a Hartree–Fock
reference — and finally samples the Krylov states and diagonalizes $H$ in the sampled subspace.

```python theme={null}
!pip install -qq "classiq[chemistry]"
```

```python theme={null}

import numpy as np

from classiq import *
```

## Time evolution: building the Krylov states

The quantum heart of SKQD is building the Krylov states
$|\psi_k\rangle = e^{-iH\,(k\,\Delta t)}\,|\psi_0\rangle$. We approximate the evolution $e^{-iHt}$ by a **Suzuki–Trotter** product, using
Classiq's built-in [`suzuki_trotter`](https://docs.classiq.io/qmod-reference/library-reference/core-library-functions/hamiltonian_evolution/suzuki_trotter/suzuki_trotter).

The reference state enters through a pluggable `state_prep` argument so it can be swapped later; the
concrete `main` is assembled further down.

```python theme={null}
@qfunc
def krylov_evolve(
    hamiltonian: SparsePauliOp,
    evolution_time: CReal,
    order: CInt,
    repetitions: CInt,
    qba: QArray,
) -> None:
    """Apply e^{-i H t} to `qba`, approximated by a Suzuki-Trotter product."""
    suzuki_trotter(
        hamiltonian,
        evolution_coefficient=evolution_time,
        order=order,
        repetitions=repetitions,
        qbv=qba,
    )


@qfunc
def krylov_state(
    state_prep: QCallable[QArray],
    hamiltonian: SparsePauliOp,
    evolution_time: CReal,
    order: CInt,
    repetitions: CInt,
    qba: QArray,
) -> None:
    """Prepare |psi_0> via the supplied `state_prep`, then evolve to time t."""
    state_prep(qba)
    krylov_evolve(hamiltonian, evolution_time, order, repetitions, qba)
```

## The single-impurity Anderson model

The worked example is the **single-impurity Anderson model** \[[4](#anderson)]: one impurity orbital
$d$ coupled to $L$ bath sites $k = 1, \dots, L$.

With spin $\sigma \in \{\uparrow, \downarrow\}$,

$$
H = \epsilon_d \sum_\sigma n_{d\sigma}
  \;+\; U\, n_{d\uparrow} n_{d\downarrow}
  \;+\; \sum_{k=1}^{L}\sum_\sigma \epsilon_k\, n_{k\sigma}
  \;+\; \sum_{k=1}^{L}\sum_\sigma V_k \left(c_{d\sigma}^\dagger c_{k\sigma} + c_{k\sigma}^\dagger c_{d\sigma}\right),
$$

where $c^\dagger$ and $c$ are the fermionic creation and annihilation operators, $n = c^\dagger c$ is the number operator, $\epsilon_d$ the impurity level, $U$ the
on-site Coulomb interaction felt when the impurity is doubly occupied (repulsive for $U>0$, the regime we use), $\epsilon_k$ the bath
energies, and $V_k$ the impurity–bath hybridization (hopping).

There are $2(L+1)$ spin-orbitals, hence a register of $N = 2(L+1)$ qubits (one qubit per spin-orbital). We index modes in a spin-blocked layout,

$$
\text{mode}(o, \sigma) = \sigma\,(L+1) + o,
$$

with orbital $o = 0$ the impurity and $o = 1, \dots, L$ the bath; spin $\sigma = 0$ (up),
$1$ (down).

We build $H$ as an `openfermion` `FermionOperator`.

Any other
second-quantized Hamiltonian can be swapped in and fed to the time-evolution core above.

```python theme={null}
from openfermion import FermionOperator

from classiq.applications.chemistry.mapping import FermionToQubitMapper
from classiq.applications.chemistry.op_utils import qubit_op_to_qmod
from classiq.applications.chemistry.problems import FermionHamiltonianProblem


def siam_fermion_hamiltonian(eps_d, U, eps_bath, V):
    """Single-impurity Anderson model as an openfermion FermionOperator.

    Args:
        eps_d:    impurity on-site energy
        U:        on-site Coulomb interaction on the impurity
        eps_bath: list of L bath on-site energies
        V:        list of L impurity-bath hybridizations

    Modes (spin-blocked): mode(orbital, spin) = spin*(L+1) + orbital,
    with orbital 0 = impurity and 1..L = bath; spin 0 = up, 1 = down.
    """
    L = len(eps_bath)
    assert len(V) == L, "need one hybridization V per bath site"

    def mode(orbital, spin):
        return spin * (L + 1) + orbital

    H = FermionOperator()  # zero operator
    for spin in (0, 1):
        d = mode(0, spin)
        H += FermionOperator(f"{d}^ {d}", eps_d)  # impurity level
        for k in range(1, L + 1):
            b = mode(k, spin)
            H += FermionOperator(f"{b}^ {b}", eps_bath[k - 1])  # bath level
            H += FermionOperator(f"{d}^ {b}", V[k - 1])  # hybridization d <- k
            H += FermionOperator(f"{b}^ {d}", V[k - 1])  # hybridization k <- d
    du, dd = mode(0, 0), mode(0, 1)
    H += FermionOperator(f"{du}^ {du} {dd}^ {dd}", U)  # Coulomb repulsion
    return H
```

#

## Mapping to a qubit Hamiltonian (Jordan–Wigner)

As the test case we take $L = 5$ bath sites with a **symmetric bath** (energies symmetric about
zero) at the **particle–hole symmetric point** ($\epsilon_d = -U/2$), at half filling (three spin-up
and three spin-down electrons).

This is a 12-qubit model whose $(3,3)$ sector is 400-dimensional.

The Anderson Hamiltonian conserves the number of electrons of each spin, so it is block-diagonal in the $(n_\uparrow, n_\downarrow)$ sectors.

Our reference has definite occupation numbers (the Hartree–Fock state, defined below). Real-time evolution then keeps every Krylov state in that one sector, and every sampled bitstring has exactly $n_\uparrow$ ($n_\downarrow$) occupied up- (down-) orbitals. SKQD therefore targets the ground state *within that sector*.

For our half-filled $(3,3)$ choice at the particle–hole-symmetric point, this sector ground state **coincides with the global ground state**.

We map this fermionic Hamiltonian to qubits with the **Jordan–Wigner** transformation, which assigns one qubit per spin-orbital (qubit $i$ is $|1\rangle$ exactly when spin-orbital $i$ is occupied).

The code below builds $H$, applies the mapping, and converts the result to the Qmod operator the time-evolution core expects.

```python theme={null}
# test case: L = 5 bath sites, symmetric bath, particle-hole symmetric point (eps_d = -U/2),
# half filling (three spin-up + three spin-down electrons)
L = 5
EPS_D, U = -2.0, 4.0
EPS_BATH, V = [-2.0, -1.0, 0.0, 1.0, 2.0], [0.4, 0.6, 0.7, 0.6, 0.4]
N_PARTICLES = (3, 3)

H_fermion = siam_fermion_hamiltonian(EPS_D, U, EPS_BATH, V)

problem = FermionHamiltonianProblem(
    fermion_hamiltonian=H_fermion, n_particles=N_PARTICLES
)
mapper = FermionToQubitMapper()  # Jordan-Wigner
qubit_op = mapper.map(problem.fermion_hamiltonian)  # openfermion qubit operator
hamiltonian = qubit_op_to_qmod(qubit_op)  # -> Qmod SparsePauliOp (for krylov_evolve)

num_qubits = mapper.get_num_qubits(problem)
print(
    f"SIAM with L = {L} bath site(s): {num_qubits} qubits, {len(qubit_op.terms)} Pauli terms"
)
```

> [!NOTE]
>
> **Output:**
>
> ```
>
> SIAM with L = 5 bath site(s): 12 qubits, 30 Pauli terms
>
>
> ```

## The initial state (Hartree–Fock reference)

SKQD needs a reference state $|\psi_0\rangle$ with appreciable overlap with the ground state
(assumption 1 in the intro). A standard, cheap choice is the **Hartree–Fock (HF) state**.

```python theme={null}
from classiq.applications.chemistry.hartree_fock import get_hf_state

hf_state = get_hf_state(problem, mapper)  # list[bool]: which spin-orbitals are occupied
print("Hartree-Fock occupation:", hf_state)
hf_bits = [int(occ) for occ in hf_state]  # 0/1 per spin-orbital, for the in-place XOR


@qfunc
def prepare_hf(state: CArray[CInt], qba: QArray[QBit]) -> None:
    """Prepare the Hartree-Fock state in place via element-wise XOR: qba[i] ^= state[i]."""
    qba ^= state
```

> [!NOTE]
>
> **Output:**
>
> ```
>
> Hartree-Fock occupation: [True, True, True, False, False, False, True, True, True, False, False, False]
>
>
> ```

For this test case the overlap between the HF state and the true ground state is $|\langle \mathrm{HF}\,|\,\mathrm{ground}\rangle|^2 \approx 0.10$, which we now confirm by exact diagonalization. We also compute the exact ground-state energy — the benchmark we compare against later — and check how concentrated the ground state's weight is in the computational basis (assumption 2, the sparsity that lets sampling work).

All three are possible only at this small scale, and are not part of SKQD itself.

```python theme={null}
from math import comb

# --- classical reference values (small systems only): exact ground energy, HF overlap, sparsity ---
import numpy as np

# Dense 2^N Hamiltonian from the qubit (Pauli) operator, then a classical eigensolve.
evals, evecs = np.linalg.eigh(
    hamiltonian_to_matrix(hamiltonian)
)  # full 2^N solve (does NOT scale)
E_exact, ground = float(evals[0]), evecs[:, 0]

# Hartree-Fock as a single computational-basis state: its index is the occupation bitstring read
# as an integer. hf_bits is in qubit order, so reverse it to match hamiltonian_to_matrix's ordering.
hf_index = int("".join(str(b) for b in hf_bits)[::-1], 2)
hf_vec = np.zeros(2**num_qubits, dtype=complex)
hf_vec[hf_index] = 1.0
overlap = abs(np.vdot(hf_vec, ground)) ** 2

print(f"exact ground energy = {E_exact:.6f}")
print(f"|<HF|ground>|^2     = {overlap:.4f}")

# how concentrated is the ground state? count configurations carrying 90% / 99% of its weight
weights = np.sort(np.abs(ground) ** 2)[::-1]
cumulative = np.cumsum(weights)
n90 = int(np.searchsorted(cumulative, 0.90) + 1)
n99 = int(np.searchsorted(cumulative, 0.99) + 1)
sector_dim = comb(L + 1, N_PARTICLES[0]) * comb(L + 1, N_PARTICLES[1])
print(
    f"{n90} configurations carry 90% of the weight; {n99} carry 99% "
    f"(of the {sector_dim}-dimensional sector)"
)
```

> [!NOTE]
>
> **Output:**
>
> ```
> exact ground energy = -9.142690
>   |<HF|ground>|^2     = 0.1009
>   8 configurations carry 90% of the weight; 24 carry 99% (of the 400-dimensional sector)
>
>
> ```

## Assembling and synthesizing the circuit

We assemble the entry point `main`, in which we prepare the Hartree–Fock reference and evolve under $H$, and
synthesize it.

The evolution time `t` is left as a classical parameter, so a single synthesis
yields a circuit we reuse at $t = k\,\Delta t$ for each Krylov index $k$.

**How large should `DELTA_T` be?** As a rule of thumb, the step should be small enough to resolve the spectrum: on the order of $\pi/\Delta E$, where $\Delta E = E_{\max}-E_{\min}$ is the Hamiltonian's spectral width (with too large a step, distinct eigenvalues may become indistinguishable).

**How does the Trotter accuracy influence the accuracy of the output?** The goal of the time-evolution in SKQD is only to generate configurations.

The energy itself comes
from diagonalizing the exact Hamiltonian in the sampled subspace, so we don't need precise dynamics, only enough
accuracy to reach the ground-state-relevant configurations.

For this reason a few Trotter repetitions suffice.

```python theme={null}
# Krylov / Trotter settings
DELTA_T = 0.3  # Krylov time step; |psi_k> uses t = k * DELTA_T
TROTTER_ORDER = 1
TROTTER_REPS = 6  # Trotter repetitions per evaluation (accuracy knob)


@qfunc
def main(t: CReal, qba: Output[QArray[QBit, num_qubits]]) -> None:
    allocate(num_qubits, qba)
    krylov_state(
        lambda q: prepare_hf(hf_bits, q),
        hamiltonian,
        t,
        TROTTER_ORDER,
        TROTTER_REPS,
        qba,
    )


qprog = synthesize(main)
show(qprog)
```

> [!NOTE]
>
> **Output:**
>
> ```
>
> Quantum program link: https://platform.classiq.io/circuit/3MKPSKmzZ6xVueASfCDMOFS9pY4
>
>
> ```

## Sampling the Krylov states

Now we run the quantum part.

For each Krylov index $k = 0, 1, \dots, D-1$ we evaluate the circuit
at $t = k\,\Delta t$ and sample it in the computational basis.

Each shot returns an electron
configuration — a bitstring over the spin-orbitals.

The union of all configurations observed across the $D$
Krylov states is the set $\mathcal{S}$ that defines the subspace we diagonalize in the final diagonalization step.

How many Krylov states $D$, and how many shots per state, are enough? There is no simple
rule: $D$, the shot budget, the reference overlap $|\langle\psi_0|\mathrm{ground}\rangle|^2$, the
ground-state sparsity, and the target energy error are all tied together by SKQD's convergence
analysis — see Theorem 1 of \[[1](#skqd)]. Qualitatively, smaller overlap or a tighter target error
demands more Krylov states and more shots.

For this small model we simply pick values that
converge comfortably.

Although our model is small, we want it to behave like the real, at-scale regime, where the sector
is far too large to enumerate. We therefore use a modest shot budget, keeping the collected set
$\mathcal{S}$ a genuine subset of the 400-dimensional sector rather than all of it (with many
more shots we would simply collect all 400 configurations and recover exact-sector diagonalization).

We also apply an explicit **particle-number post-selection**: we keep only bitstrings in the
$(n_\uparrow, n_\downarrow)$ sector. It discards nothing here since the simulator conserves particle
number exactly, but on noisy hardware it removes samples that a bit-flip has knocked out of the
correct sector.

```python theme={null}
from collections import Counter
from math import comb

NUM_KRYLOV = 10  # number of Krylov states D (times t = 0, DELTA_T, ..., (D-1)*DELTA_T)
NUM_SHOTS = 300  # modest budget: keeps the collected set a genuine subset of the sector

krylov_times = [k * DELTA_T for k in range(NUM_KRYLOV)]

# batched execution: one DataFrame per Krylov time
results = sample(
    qprog,
    parameters=[{"t": t} for t in krylov_times],
    num_shots=NUM_SHOTS,
    random_seed=0,
)

# collect configurations from the structured `qba` column (list of 0/1 per spin-orbital),
# summing how often each was sampled.
config_counts = Counter()
for df in results:
    for occ, c in zip(df["qba"], df["counts"]):
        occ = tuple(occ)
        # symmetry post-selection: keep only configs in the (n_up, n_down) sector (no-op on a
        # noiseless simulator; on noisy hardware it drops bitstrings knocked out of the sector).
        if sum(occ[: L + 1]) != N_PARTICLES[0] or sum(occ[L + 1 :]) != N_PARTICLES[1]:
            continue
        config_counts[occ] += int(c)

configs = sorted(config_counts)

sector_dim = comb(L + 1, N_PARTICLES[0]) * comb(L + 1, N_PARTICLES[1])
print(
    f"Sampled {NUM_KRYLOV} Krylov states ({NUM_SHOTS} shots each); "
    f"collected {len(configs)} unique configurations (sector dimension = {sector_dim})."
)
```

> [!NOTE]
>
> **Output:**
>
> ```
>
> Submitting job to simulator
>   Job: https://platform.classiq.io/jobs/84e14f5b-d5e8-4149-a0b9-4f67750a8537
>
>
> ```

> [!NOTE]
>
> **Output:**
>
> ```
>
> Sampled 10 Krylov states (300 shots each); collected 139 unique configurations (sector dimension = 400).
>
>
> ```

## Sample-based diagonalization

Finally we turn the sampled configurations into a ground-energy estimate.

The set $\mathcal{S}$ of
collected configurations spans a subspace; we build the Hamiltonian projected onto it,
$H_{\mathcal{S}}$, and take its lowest eigenvalue.

We compare our estimate against the exact ground-state energy $E_0$ computed earlier (by
diagonalizing the full $2^N$ matrix).

```python theme={null}
import numpy as np


def _apply_pauli(term, occ):
    """Apply one Pauli string (a tuple of (qubit, 'X'|'Y'|'Z')) to a computational-basis state.

Returns (phase, new_occ).
    """
    phase, s = 1 + 0j, set(occ)
    for q, p in term:
        bit = q in s
        if p == "Z":  # Z|1> = -|1>,  Z|0> = |0>
            if bit:
                phase = -phase
        else:  # X or Y both flip qubit q
            if p == "Y":  # Y|0> = i|1>,  Y|1> = -i|0>
                phase *= -1j if bit else 1j
            s.symmetric_difference_update({q})
    return phase, frozenset(s)


def sample_based_ground_energy(qubit_op, configs):
    """Lowest eigenvalue of H projected onto the subspace spanned by `configs`.

Builds H_sub[i, j] = <config_i|H|config_j> directly from the qubit (Pauli) Hamiltonian.
    """
    index = {
        frozenset(i for i, b in enumerate(c) if b): j for j, c in enumerate(configs)
    }
    H_sub = np.zeros((len(configs), len(configs)), dtype=complex)
    for j, c in enumerate(configs):
        ket = frozenset(i for i, b in enumerate(c) if b)
        for term, coeff in qubit_op.terms.items():
            phase, bra = _apply_pauli(term, ket)
            i = index.get(bra)
            if i is not None:
                H_sub[i, j] += coeff * phase
    return float(
        np.linalg.eigvalsh(H_sub)[0].real
    )  # the small-subspace diagonalization


E_skqd = sample_based_ground_energy(qubit_op, configs)

# E_exact (our benchmark) was computed earlier, with the other classical reference values.

# variational sanity check: diagonalizing in a subspace can never go below the true
# ground energy, so E_skqd >= E_exact always (the 1e-9 absorbs floating-point slack).
# Holds regardless of noise, since H_sub uses the exact Hamiltonian's matrix elements.
assert E_skqd >= E_exact - 1e-9, (
    "SKQD energy below exact ground energy — variational bound violated (bug in projection/diagonalization)"
)

# regression guard (for the default configuration above): on a healthy run this error is ~1.2e-

3.
assert abs(E_skqd 

- E_exact) < 5e-2, (
    f"SKQD error {E_skqd 

- E_exact:+.2e} far exceeds the ~1.2e-3 expected for the default "
    f"configuration. If you intentionally changed the setup (model, "
    f"sampling, or Trotter parameters), delete this assert."
)

print(f"subspace dimension |S| = {len(configs)}   (full sector = {sector_dim})")
print(f"SKQD energy   = {E_skqd:.6f}")
print(f"exact energy  = {E_exact:.6f}")
print(f"error         = {E_skqd 

- E_exact:+.2e}")
```

> [!NOTE]
>
> **Output:**
>
> ```
> subspace dimension |S| = 139   (full sector = 400)
>   SKQD energy   = -9.141487
>   exact energy  = -9.142690
>   error         = +1.20e-03
>
>
> ```

## Alternative: keep the top-k most-sampled configurations

The core SKQD algorithm above keeps all unique sampled configurations. A variant that can be used for noise robustness, as well as for reducing the cost of the classical diagonalization, is to keep
only the configurations that were **sampled most often**.

With good probability estimates from many shots, the
top-ranked configurations are reliably the important ones.

Here we keep the top $k = 30$ and compare to
the Hartree–Fock baseline and the exact energy.

In this noiseless run, keeping fewer configurations can only raise the estimate (i.e. move it further above the true ground energy), since a larger subspace is always variationally lower. So keeping only the top-ranked configurations trades a little accuracy for a cheaper classical diagonalization; the real payoff comes on noisy hardware, where the rarely-sampled configurations that get discarded are largely noise-induced ones.

```python theme={null}
TOP_K = 30
top_configs = [cfg for cfg, _ in config_counts.most_common(TOP_K)]

E_hf = sample_based_ground_energy(qubit_op, [hf_state])  # <HF|H|HF> baseline
E_topk = sample_based_ground_energy(qubit_op, top_configs)
corr = E_exact 

- E_hf

print(
    f"kept top {TOP_K} of {len(config_counts)} collected configurations (sector dimension = {sector_dim})"
)
print(f"Hartree-Fock energy         = {E_hf:.4f}")
print(
    f"SKQD (top {TOP_K})             = {E_topk:.4f}   (error {E_topk 

- E_exact:+.2e})"
)
print(f"exact energy                = {E_exact:.4f}")
print(f"correlation recovered vs HF = {100 * (E_topk 

- E_hf) / corr:.0f}%")
```

> [!NOTE]
>
> **Output:**
>
> ```
> kept top 30 of 139 collected configurations (sector dimension = 400)
>   Hartree-Fock energy         = -6.0000
>   SKQD (top 30)             = -9.0610   (error +8.16e-02)
>   exact energy                = -9.1427
>   correlation recovered vs HF = 97%
>
>
> ```

## Convergence vs. subspace size

How many configurations do we actually need, and how does a small subspace compare to the cheap
classical baseline — the Hartree–Fock energy $\langle \mathrm{HF}|H|\mathrm{HF}\rangle$? We
rank the collected configurations by how often they were sampled, keep the top $m$, and
diagonalize in that $m$-dimensional subspace.

The left panel shows the absolute energy, bracketed
between the HF baseline and the exact energy: SKQD starts at the HF level and, with only a handful
of configurations, recovers most of the correlation energy HF misses.

The right panel shows the
error to the exact energy on a log scale, which exposes the continued convergence that the left
panel hides once the curve visually merges with the exact line.

```python theme={null}
import matplotlib.pyplot as plt

# rank the collected configurations by how often they were sampled, then grow the subspace
ranked = [cfg for cfg, _ in config_counts.most_common()]
ms = list(range(1, len(ranked) + 1))
energies = [sample_based_ground_energy(qubit_op, ranked[:m]) for m in ms]

E_hf = sample_based_ground_energy(
    qubit_op, [hf_state]
)  # Hartree-Fock baseline <HF|H|HF>
errors = [abs(E_exact - e) for e in energies]
errors = [
    e if e > 0 else np.nan for e in errors
]  # a zero error cannot be shown on a log axis

fig, (ax_energy, ax_error) = plt.subplots(1, 2, figsize=(12, 4.2))

# left: absolute energy, bracketed by the HF baseline and the exact energy
ax_energy.plot(ms, energies, "o-", label="SKQD (top-$m$)")
ax_energy.axhline(E_hf, color="C1", ls=":", label=f"Hartree-Fock = {E_hf:.3f}")
ax_energy.axhline(E_exact, color="k", ls="--", label=f"exact = {E_exact:.3f}")
ax_energy.set_xlabel("subspace size $m$ (configurations included)")
ax_energy.set_ylabel("ground-energy estimate")
ax_energy.legend()

# right: error to exact on a log scale
ax_error.semilogy(ms, errors, "o-", color="C3")
ax_error.set_xlabel("subspace size $m$ (configurations included)")
ax_error.set_ylabel(r"$|E_{\mathrm{exact}} - E_{\mathrm{SKQD}}|$ (log scale)")
ax_error.grid(True, which="both", ls=":", alpha=0.4)

fig.suptitle(f"SKQD convergence vs. subspace size (full sector = {sector_dim})")
fig.tight_layout()
plt.show()
```

![output](https://mintcdn.com/classiq/84HPmCWufF3YAEav/explore/algorithms/quantum_phase_estimation/SKQD/skqd_files/skqd_1.png?fit=max\&auto=format\&n=84HPmCWufF3YAEav\&q=85\&s=57627321b473914c8ad6ce44f7fb2eda)

## References

\[1] J. Yu, J.

Robledo Moreno, J. T. Iosue, L. Bertels, D. Claudino, B. Fuller, P. Groszkowski,
T. S. Humble, P. Jurcevic, W. Kirby, T. A. Maier, M. Motta, B. Pokharel, A. Seif, A. Shehata,
K. J. Sung, M. C. Tran, V. Tripathi, A. Mezzacapo, and K. Sharma,
*"Quantum-Centric Algorithm for Sample-Based Krylov Diagonalization"*,
[arXiv:2501.09702](https://arxiv.org/abs/2501.09702) (2025).

\[2] N. Yoshioka, M. Amico, W. Kirby, P. Jurcevic, A. Dutt, B. Fuller, S. Garion, H. Haas, I. Hamamura, A. Ivrii, R. Majumdar, Z. Minev, M. Motta, B. Pokharel, P. Rivero, K. Sharma, C. J. Wood, A. Javadi-Abhari, and A. Mezzacapo, *"Diagonalization of Large Many-Body Hamiltonians on a Quantum Processor"*, [arXiv:2407.14431](https://arxiv.org/abs/2407.14431) (2024).

\[3] J. Robledo-Moreno, M. Motta, H. Haas, A. Javadi-Abhari, P. Jurcevic, W. Kirby, S. Martiel, K. Sharma, S. Sharma, T. Shirakawa, I. Sitdikov, R.-Y. Sun, K. J. Sung, M. Takita, M. C. Tran, S. Yunoki, and A. Mezzacapo, *"Chemistry Beyond the Scale of Exact Diagonalization on a Quantum-Centric Supercomputer"*, Science Advances **11**, eadu9991 (2025); [arXiv:2405.05068](https://arxiv.org/abs/2405.05068).

\[4] P. W. Anderson, *"Localized Magnetic States in Metals"*, [Phys. Rev. **124**, 41 (1961)](https://doi.org/10.1103/PhysRev.124.41).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.