Block-encoding examples

Hide a Hamiltonian inside a larger unitary using a Pauli sum, sparse matrix access, or a structured double-factorized representation. These examples exercise the shared consumers and compare the resulting encodings.

For a body-programmed construction, see Circuit primitive examples: its alias-sampling example composes an LCU with a non-Pauli CZ term and checks Walk/QSVT consumers.

See also

Block encodings — the PauliLCU API and the BlockEncoding protocol these examples exercise.

Walkthrough of the PauliLCU block-encoding API

A Hamiltonian is a weighted sum of simple operations. To use it in quantum algorithms, we need a larger circuit that contains a scaled copy of that sum in the part where its extra qubits are zero. This is a block encoding. This example follows one small Hamiltonian from its coefficients to an executable block encoding, then uses that encoding in a quantum walk and a polynomial transformation.

The comparison asks what changes when the same Hamiltonian uses exact state preparation or finite-precision alias sampling. You should learn how preparation weights, the selected operations, and the normalization determine the encoded matrix; how extra qubits contribute to cost; and how to compare accuracy across implementations. The NumPy checks separate errors caused by rounded coefficients from errors in executing the circuit, so the printed resource savings or costs can be interpreted alongside the approximation.

A guided tour of the PauliLCU block-encoding API: build the encoding from a spin operator, inspect its sizes and normalization, and exercise the device kernels (pauli_lcu.prepare, the select, and the walk) it exposes.

The final sections compare exact and alias PREPARE/SELECT at mu=2, 3 and 4 using the same Hamiltonian and kernel-factory consumers. The output summarizes Hamiltonian approximation error, executed algorithms, and resource cost. On this fixture mu=3 has the same rounded weights as mu=2, while mu=4 reduces the error by about 2.6 times. The resource table accounts for alias workspace and lists every gate family. A separate small fixture prints odd/even measured moments. Independent NumPy checks remain active and are quiet on success; pass --verbose for the detailed diagnostics. See Block encodings for the accuracy/resource tradeoff and the distinction between rounding and circuit error.

"""Walkthrough of the PauliLCU block-encoding API.

A Hamiltonian is a weighted sum of simple operations. To use it in quantum
algorithms, we need a larger circuit that contains a scaled copy of that sum
in the part where its extra qubits are zero. This is a block encoding. This
example follows one small Hamiltonian from its coefficients to an executable
block encoding, then uses that encoding in a quantum walk and a polynomial
transformation.

The comparison asks what changes when the same Hamiltonian uses exact state
preparation or finite-precision alias sampling. You should learn how
preparation weights, the selected operations, and the normalization determine
the encoded matrix; how extra qubits contribute to cost; and how to compare
accuracy across implementations. The NumPy checks separate errors caused by
rounded coefficients from errors in executing the circuit, so the printed
resource savings or costs can be interpreted alongside the approximation.

Run with:  python3 pauli_lcu_demo.py
Add --verbose to show individual numerical checks.
"""

import argparse
import os
import time

import numpy as np

import cudaq
from cudaq import spin

from cudaq_algorithms import sim_utils as sim
from cudaq_algorithms import PauliLCU, PhaseSequence, QSVT, Walk, state_from
from cudaq_algorithms.pauli_lcu import prepare, select, unprepare
from cudaq_algorithms.primitives import AliasSamplingPrepare


def banner(title):
    print(f"\n=== {title} " + "=" * max(0, 60 - len(title)))


def check(label, actual, expected, tolerance=1e-10, *, verbose=False):
    error = float(np.max(np.abs(actual - expected)))
    passed = np.isfinite(error) and error <= tolerance
    if verbose or not passed:
        print(f"CHECK {label}: {error:.3e} <= {tolerance:.3e} -> "
              f"{'PASS' if passed else 'FAIL'}")
    if not passed:
        raise AssertionError(label)


def dense_pauli(word):
    """Explicit little-endian Pauli matrix, preserving idle qubits."""
    matrices = {
        "I": np.eye(2),
        "X": np.array([[0., 1.], [1., 0.]]),
        "Y": np.array([[0., -1j], [1j, 0.]]),
        "Z": np.diag([1., -1.])
    }
    result = np.ones((1, 1), dtype=complex)
    for letter in word:
        result = np.kron(matrices[letter], result)
    return result


def represented_hamiltonian(encoding, *, verbose=False):
    """Use public alias tables, never the PauliLCU's private LCU instance."""
    terms = encoding.terms
    if encoding.backend == "exact":
        return sum(coefficient * dense_pauli(word)
                   for coefficient, word in terms)
    sampler = AliasSamplingPrepare([abs(c) for c, _ in terms],
                                   mu=encoding.mu,
                                   variant="select")
    counts = np.zeros(sampler.num_bins, dtype=int)
    for original in range(sampler.num_bins):
        for reference in range(1 << sampler.mu):
            selected = (original if reference < sampler.keep[original] else
                        sampler.alias[original])
            counts[selected] += 1
    probabilities = counts / (sampler.num_bins * (1 << sampler.mu))
    check("alias branch counts versus public probabilities",
          probabilities,
          sampler.table_probabilities,
          verbose=verbose)
    if len(terms) < sampler.num_bins:
        check("zero-probability padding",
              probabilities[len(terms):],
              np.zeros(sampler.num_bins - len(terms)),
              verbose=verbose)
    check("per-bin alias probability bound",
          float(np.max(np.abs(probabilities - sampler.probabilities))),
          0.,
          tolerance=sampler.discretization_bound + 1e-12,
          verbose=verbose)
    return sum(encoding.alpha * probabilities[k] * np.sign(coefficient) *
               dense_pauli(word)
               for k, (coefficient, word) in enumerate(terms))


def scalar_response(phases, x):
    # Independent all-forward signal model; the step already includes -H/alpha.
    s = np.sqrt(max(0.0, 1 - x * x))
    step = np.array([[-x, -s], [s, -x]], dtype=complex)
    matrix = np.diag([np.exp(1j * phases[0]), 1.0])
    for phase in phases[1:]:
        matrix = np.diag([np.exp(1j * phase), 1.0]) @ step @ matrix
    return matrix[0, 0]


def resource_row(encoding, *, verbose=False):
    """Every gate family of one encoding (apply = PREPARE, SELECT, PREPARE†)."""
    apply = encoding.apply_kernel()
    n_system, n_ancilla = encoding.num_system, encoding.num_ancilla

    @cudaq.kernel
    def harness():
        system = cudaq.qvector(n_system)
        ancilla = cudaq.qvector(n_ancilla)
        apply(ancilla, system)

    resources = cudaq.estimate_resources(harness)
    rotation_gates = ("rx", "ry", "rz", "r1")
    paulis = ("x", "y", "z")
    arities = range(n_ancilla + 2)
    rotations = sum(
        resources.count_controls(gate, 0) for gate in rotation_gates)
    controlled_rotations = sum(
        resources.count_controls(gate, controls) for gate in rotation_gates
        for controls in arities if controls >= 1)
    single_qubit = sum(
        resources.count_controls(gate, 0) for gate in paulis + ("h", "s", "t"))
    one_control = sum(resources.count_controls(gate, 1) for gate in paulis)
    two_control = sum(resources.count_controls(gate, 2) for gate in paulis)
    higher = sum(
        resources.count_controls(gate, controls) for gate in paulis
        for controls in arities if controls >= 3)
    fredkins = resources.count_controls("swap", 1)
    counted = (rotations + controlled_rotations + single_qubit + one_control +
               two_control + higher + fredkins)
    check(f"{encoding.backend} mu={encoding.mu} gate inventory is complete",
          counted,
          resources.count(),
          0,
          verbose=verbose)
    precision = "-" if encoding.mu is None else str(encoding.mu)
    return (f"{encoding.backend:6s} {precision:>4s} "
            f"{n_system:3d} {n_ancilla:3d} {n_system+n_ancilla:5d} "
            f"{rotations:4d} {controlled_rotations:5d} {single_qubit:4d} "
            f"{one_control:4d} {two_control:4d} {higher:4d} {fredkins:7d}")


def compare_backends(exact, *, verbose=False):
    banner("8. Exact versus alias: accuracy and resources")
    started = time.perf_counter()
    print(
        f"{exact.num_system} system qubits; normalization alpha = {exact.alpha:.3g}"
    )
    print("Alias sampling rounds the term weights; both backends use the same "
          "action, Walk and QSVT interfaces.")
    rng = np.random.default_rng(7)
    ket = rng.normal(size=4) + 1j * rng.normal(size=4)
    ket /= np.linalg.norm(ket)
    ideal = represented_hamiltonian(exact, verbose=verbose)
    encodings = [exact] + [
        PauliLCU(dict((word, coefficient)
                      for coefficient, word in exact.terms),
                 backend="alias",
                 mu=mu) for mu in (2, 3, 4)
    ]
    # Every encoding is priced and its represented operator compared; the
    # walk and QSVT circuits run at mu=2 and mu=3, and the 19-qubit mu=4
    # encoding runs once (its walks and QSVT cost minutes on a CPU).
    circuit_budget = 3
    resource_rows = []
    accuracy_rows = []
    operator_errors = {}
    represented_operators = {}
    phases = [0.3, -0.4, 0.25]
    for encoding in encodings:
        if encoding.terms != exact.terms or encoding.num_system != exact.num_system:
            raise AssertionError(
                "backends did not retain the same intended terms")
        check("one-norm agrees with exact backend",
              encoding.alpha,
              exact.alpha,
              verbose=verbose)
        represented = represented_hamiltonian(encoding, verbose=verbose)
        discretization_error = float(np.linalg.norm(represented - ideal, 2))
        operator_errors[encoding.mu] = discretization_error
        represented_operators[encoding.mu] = represented
        if encoding.backend == "alias":
            # Each Pauli has norm one: sum the per-bin probability bounds
            # over the 2^m bins, which gives alpha * 1.5 / 2^mu.
            bins = 1 << max(1, (encoding.num_terms - 1).bit_length())
            bound = encoding.alpha * bins * (1.5 / (bins * (1 << encoding.mu)))
            check("operator discretization bound",
                  discretization_error,
                  0.,
                  tolerance=bound + 1e-12,
                  verbose=verbose)
        resource_rows.append(resource_row(encoding, verbose=verbose))
        name = f"{encoding.backend}, mu={encoding.mu}"
        normalized = represented / encoding.alpha
        check(f"{name} action",
              sim.action(encoding, ket),
              normalized @ ket,
              verbose=verbose)
        consumers = (encoding.backend == "exact"
                     or encoding.mu <= circuit_budget)
        precision = "-" if encoding.mu is None else str(encoding.mu)
        demonstrations = "Action, Walk, QSVT" if consumers else "Action only"
        accuracy_rows.append(
            f"{encoding.backend:7s} {precision:>2s} "
            f"{discretization_error:18.5f}    {demonstrations}")
        if not consumers:
            continue
        for power, polynomial in ((1, -normalized),
                                  (2,
                                   2 * normalized @ normalized - np.eye(4))):
            output = cudaq.get_state(
                Walk(encoding).kernel(power=power), state_from(ket))
            check(f"{name} Walk {power}",
                  sim.good_subspace(encoding, output),
                  polynomial @ ket,
                  verbose=verbose)
        values, vectors = np.linalg.eigh(normalized)
        responses = np.array(
            [scalar_response(phases, value) for value in values])
        expected = vectors @ (responses * (vectors.conj().T @ ket))
        check(f"{name} QSVT",
              sim.transform(QSVT(encoding), ket, PhaseSequence(phases)),
              expected,
              verbose=verbose)

    print("\nbackend mu  Hamiltonian error    Executed demonstrations")
    for row in accuracy_rows:
        print(row)
    print("Hamiltonian error is the absolute operator norm ||H_encoded-H||_2.")
    if np.allclose(represented_operators[2],
                   represented_operators[3],
                   rtol=0,
                   atol=1e-12):
        print("mu=3 gives the same rounded Hamiltonian as mu=2.")
    if 0 < operator_errors[4] < operator_errors[2]:
        improvement = operator_errors[2] / operator_errors[4]
        print(f"On this Hamiltonian, mu=4 reduces the error by about "
              f"{improvement:.1f}x versus mu=2.")
    print("Each extra bit halves the error bound; the realized rounding error "
          "can plateau.")
    largest = encodings[-1]
    print(
        f"mu=4 uses {largest.num_system + largest.num_ancilla} total qubits; "
        "its Walk/QSVT runs are skipped to keep CPU runtime manageable.")
    print("All executed circuits agree with independent classical references "
          "within 1e-10.")
    print("\nResources count one encoding, without input-state preparation.")
    print("backend   mu sys anc total  rot c-rot   1q  c-P cc-P mc-P Fredkin")
    for row in resource_rows:
        print(row)
    print(
        "Ancillas include alias-preparation garbage and SELECT work. "
        "Gate families are counted separately, without a synthesized T cost.")

    banner("9. Odd/even moments on a separate small fixture")
    print("One-qubit Hamiltonian: H = 0.6 Z - 0.4 X; alias precision mu=2.")
    moment_values = []
    small_ket = np.array([np.sqrt(0.3), 1j * np.sqrt(0.7)])
    for encoding in (PauliLCU({
            "Z": 0.6,
            "X": -0.4
    }), PauliLCU({
            "Z": 0.6,
            "X": -0.4
    }, backend="alias", mu=2)):
        normalized = represented_hamiltonian(encoding,
                                             verbose=verbose) / encoding.alpha
        measured = []
        previous, current = np.eye(2), normalized
        for order in range(4):
            if order == 0:
                polynomial = previous
            elif order == 1:
                polynomial = current
            else:
                polynomial = 2 * normalized @ current - previous
                previous, current = current, polynomial
            expected = np.vdot(small_ket, polynomial @ small_ket).real
            actual = Walk(encoding).moment(small_ket, order)
            check(f"{encoding.backend} measured T_{order}(+H/alpha)",
                  actual,
                  expected,
                  verbose=verbose)
            measured.append(actual)
        moment_values.append(measured)
    print("moment       exact    alias(mu=2)")
    for order in range(4):
        print(f"T_{order}    {moment_values[0][order]:+10.6f} "
              f"{moment_values[1][order]:+14.6f}")
    print("Moments use +H/alpha; walk good blocks use T_k(-H/alpha).")
    print("Both moment columns agree with their represented Hamiltonians "
          "within 1e-10.")
    print("Exact and alias share kernel factories; kernel_args is exact-only.")
    if verbose:
        print(f"Comparison elapsed: {time.perf_counter()-started:.2f}s")


def main():
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--verbose",
                        action="store_true",
                        help="show each numerical and gate-accounting check")
    arguments = parser.parse_args()
    cudaq.set_target(os.environ.get("CUDAQ_DEFAULT_SIMULATOR", "qpp-cpu"))

    banner("1. Construct from a plain dict (word -> coefficient)")
    enc = PauliLCU({"ZI": 0.70, "IZ": -0.43, "XX": 0.19, "YZ": 0.11})
    print(enc)
    print(f"terms:         {enc.terms}")
    print(f"alpha:         {enc.alpha}")
    print(f"constant term: {enc.constant_term}")

    banner("2. Or from a cudaq.SpinOperator — same encoding")
    h = (0.70 * spin.z(0) - 0.43 * spin.z(1) + 0.19 * spin.x(0) * spin.x(1) +
         0.11 * spin.y(0) * spin.z(1))
    print(PauliLCU(h, num_qubits=2))

    banner("3. One call: (H/alpha) |psi> via encode + postselect")
    rng = np.random.default_rng(7)
    psi = rng.normal(size=4).astype(np.complex128)
    psi /= np.linalg.norm(psi)
    good = sim.action(enc, psi)
    print(f"|| action(psi) ||           = {np.linalg.norm(good):.6f}")
    print(f"success probability         = {np.linalg.norm(good)**2:.6f}")

    banner("4. Kernel factories for sampling/observing workflows")
    kernel = enc.encode_kernel()
    state = cudaq.get_state(kernel, state_from(psi))
    print(f"full statevector dimension  = {len(np.asarray(state))}")
    print(f"good-subspace dimension     = "
          f"{len(sim.good_subspace(enc, state))}")

    banner("5. Qubitization walks (Chebyshev moments)")
    moment_enc = PauliLCU({"I": 0.2, "X": 0.5, "Z": 0.3})
    ket = np.array([np.cos(0.35), np.sin(0.35)], dtype=np.complex128)
    for k in (1, 2, 3):
        walked = cudaq.get_state(moment_enc.walk_kernel(power=k),
                                 state_from(ket))
        p0 = float(np.sum(np.abs(sim.good_subspace(moment_enc, walked))**2))
        print(f"<T_{2*k}(H/alpha)> from the circuit = {2 * p0 - 1:+.10f}")

    banner("6. Compose the module-level kernels inside your own kernel")
    angles, controls, ops, lengths, signs = enc.kernel_args
    n_anc = enc.num_ancilla

    @cudaq.kernel
    def custom(state: cudaq.State):
        system = cudaq.qvector(state)
        ancilla = cudaq.qvector(n_anc)
        prepare(ancilla, angles)
        select(ancilla, system, controls, ops, lengths, signs)
        unprepare(ancilla, angles)

    manual = sim.good_subspace(enc, cudaq.get_state(custom, state_from(psi)))
    print(f"manual composition matches action(): "
          f"{np.allclose(manual, good, atol=1e-12)}")

    banner("7. Single-term encodings (normalized to one ancilla)")
    negative_single = PauliLCU({"XZ": -0.5})
    positive_single = PauliLCU({"XZ": +0.5})
    print(negative_single)
    opposite = np.allclose(sim.action(negative_single, psi),
                           -sim.action(positive_single, psi),
                           atol=1e-12)
    print(f"-0.5*XZ encodes the opposite state of +0.5*XZ: {opposite}")
    print(f"action norm = "
          f"{np.linalg.norm(sim.action(negative_single, psi)):.6f} "
          f"(single unitary Pauli word: exactly 1)")

    compare_backends(enc, verbose=arguments.verbose)
    print()


if __name__ == "__main__":
    main()

Sparse matrix data and arithmetic oracles

A sparse matrix has only a few nonzero entries in each row. This example asks how to give a quantum algorithm access to those entries without first expressing the entire matrix as a sum of Pauli operations. It constructs the same small matrix from stored matrix data and from arithmetic rules describing its bands, showing two ways to supply the locations and values needed for a sparse block encoding.

You should learn what the matrix-access oracles must return, how a banded pattern handles boundaries, and why the two access methods can have different normalization and workspace costs. Both encodings feed the same Walk and QSVT interfaces. The checks reconstruct the matrix represented by finite-precision value angles and compare the circuit with that matrix, so differences in data access and numerical precision remain visible when assessing the results.

The default output displays the requested and rounded matrices, matrices reconstructed from both circuits, and their results on the same complex input vector. A four-point endpoint input makes clipped band boundaries visible. Circuit errors and a compact resource comparison finish the run. Use --verbose for individual validation checks and constructor/register diagnostics. All checks run in either mode, and failures are always reported.

Construct the same small SPD matrix from SciPy data and clipped banded oracles, inspect slots/normalization/workspace, and compare each encoded block to an independently quantized NumPy reference. Both routes execute Walk and QSVT consumers. A four-point arithmetic case verifies boundary clipping; alternative input forms and dilation are shown through metadata.

Example 07 on Getting-started walkthrough inverts a sparse encoding of this kind with QSVT and separates coefficient, polynomial and circuit error budgets.

"""Matrix data or arithmetic oracles: the same sparse BlockEncoding protocol.

A sparse matrix has only a few nonzero entries in each row. This example asks
how to give a quantum algorithm access to those entries without first
expressing the entire matrix as a sum of Pauli operations. It constructs the
same small matrix from stored matrix data and from arithmetic rules describing
its bands, showing two ways to supply the locations and values needed for a
sparse block encoding.

You should learn what the matrix-access oracles must return, how a banded
pattern handles boundaries, and why the two access methods can have different
normalization and workspace costs. Both encodings feed the same Walk and QSVT
interfaces. The checks reconstruct the matrix represented by finite-precision
value angles and compare the circuit with that matrix, so differences in data
access and numerical precision remain visible when assessing the results.

The default output shows the requested matrix, its four-bit representation,
and matrices reconstructed from both circuits. The same complex input drives
both matrix-vector comparisons. A four-point arithmetic case makes sparsity
and clipped boundaries visible. Every circuit is compared with independently
quantized NumPy matrices; simulator state access supplies the displayed data.
Run: python3 sparse_block_encoding.py
Add --verbose for individual checks and constructor/register diagnostics.
All checks run in either mode; failures are always reported.
"""

import argparse
import os
import time

import cudaq
import numpy as np
from scipy import sparse

from cudaq_algorithms import PhaseSequence, QSVT, Walk, state_from
from cudaq_algorithms import sim_utils as sim
from cudaq_algorithms.sparse import (SparseOracleEncoding, banded_oracles,
                                     encode_sparse)

ATOL = 1e-10


def check(label, actual, expected, tolerance=ATOL, *, verbose=False):
    error = float(np.max(np.abs(np.asarray(actual) - expected)))
    passed = np.isfinite(error) and error <= tolerance
    if verbose or not passed:
        print(f"CHECK {label}: {error:.3e} <= {tolerance:.3e} -> "
              f"{'PASS' if passed else 'FAIL'}")
    if not passed:
        raise AssertionError(label)


def quantized_matrix(matrix, h, bits):
    """Independent nearest-even arcsine/round/clamp/sine-squared reference."""
    result = np.zeros_like(matrix)
    for row, column in zip(*np.nonzero(matrix)):
        value = matrix[row, column]
        theta = np.arcsin(np.sqrt(abs(value) / h))
        code = min((1 << bits) - 1, round((1 << bits) * theta / (np.pi / 2)))
        result[row, column] = np.sign(value) * h * np.sin(np.pi * code /
                                                          (2 * (1 << bits)))**2
    return result


def scalar_response(phases, x):
    """Independent all-forward two-dimensional signal model."""
    step = np.array([[-x, -np.sqrt(max(0., 1 - x * x))],
                     [np.sqrt(max(0., 1 - x * x)), -x]],
                    dtype=complex)
    result = np.diag([np.exp(1j * phases[0]), 1.])
    for phase in phases[1:]:
        result = np.diag([np.exp(1j * phase), 1.]) @ step @ result
    return result[0, 0]


def show_matrix(label, matrix):
    print(label)
    displayed = np.round(np.real_if_close(matrix), 6)
    # Show structural zeros without a minus sign.
    displayed[displayed == 0] = 0.
    print(
        np.array2string(displayed,
                        precision=6,
                        suppress_small=True,
                        floatmode="fixed"))


def show_vectors(columns):
    """Side-by-side amplitudes, with roundoff hidden only for display."""
    print(" index" + "".join(f"{label:>24}" for label in columns))
    for index, values in enumerate(zip(*columns.values())):
        cells = []
        for value in values:
            real = round(float(np.real(value)), 6) + 0.
            imag = round(float(np.imag(value)), 6) + 0.
            text = (f"{real:.6f}" if imag == 0 else f"{real:.6f}{imag:+.6f}j")
            cells.append(f"{text:>24}")
        print(f"{index:6d}" + "".join(cells))


def check_encoding(name, encoding, ideal, ket, *, verbose=False):
    print(f"Running {name} circuits...", flush=True)
    if verbose:
        print(encoding)
        print(
            f"system={encoding.num_system}, block ancillas={encoding.num_block_ancilla}, "
            f"scratch={encoding.num_scratch}, all ancillas={encoding.num_ancilla}, "
            f"slots={encoding.d}/{encoding.d_padded}, h={encoding.h}, "
            f"alpha={encoding.alpha}, angle bits={encoding.value_bits}")
    realized = quantized_matrix(ideal, encoding.h, encoding.value_bits)
    dimension = len(ideal)
    columns = []
    for index in range(dimension):
        basis = np.zeros(dimension, dtype=complex)
        basis[index] = 1
        columns.append(sim.action(encoding, basis))
    block = np.column_stack(columns)
    check(f"{name} alpha*good-block",
          encoding.alpha * block,
          realized,
          verbose=verbose)
    entry_bound = encoding.h * np.pi / (2 * (1 << encoding.value_bits))
    row_nnz = int(np.count_nonzero(ideal, axis=1).max())
    check(f"{name} ideal-versus-quantized operator",
          np.linalg.norm(realized - ideal, 2),
          0.,
          row_nnz * entry_bound + ATOL,
          verbose=verbose)
    if verbose:
        print(f"Matrix-rounding error bound={row_nnz * entry_bound:.3e}")
        print("The largest angle code is clamped; even the maximal diagonal "
              "is rounded at finite precision.")
    state = np.asarray(
        cudaq.get_state(encoding.encode_kernel(), state_from(ket)))
    action = encoding.alpha * sim.good_subspace(encoding, state)
    check(f"{name} recovered matrix-vector action",
          action,
          realized @ ket,
          verbose=verbose)
    # Scratch is the high register and is zero outside oracle load windows.
    reshaped = state.reshape(
        1 << encoding.num_scratch, 1 <<
        (encoding.num_system + encoding.num_block_ancilla))
    check(f"{name} complete deterministic scratch restoration",
          reshaped[1:],
          np.zeros_like(reshaped[1:]),
          verbose=verbose)
    scaled = realized / encoding.alpha
    walk_errors = []
    for power, polynomial in ((1, -scaled),
                              (2, 2 * scaled @ scaled - np.eye(dimension))):
        output = cudaq.get_state(
            Walk(encoding).kernel(power=power), state_from(ket))
        walked = sim.good_subspace(encoding, output)
        walk_errors.append(float(np.max(np.abs(walked - polynomial @ ket))))
        check(f"{name} Walk power {power}",
              walked,
              polynomial @ ket,
              verbose=verbose)
    phases = [0.3, -0.4, 0.25]
    values, vectors = np.linalg.eigh(scaled)
    response = np.array([scalar_response(phases, value) for value in values])
    expected = vectors @ (response * (vectors.conj().T @ ket))
    transformed = sim.transform(QSVT(encoding), ket, PhaseSequence(phases))
    check(f"{name} QSVT", transformed, expected, verbose=verbose)
    return dict(block=block,
                matrix=encoding.alpha * block,
                action=action,
                represented=realized,
                rounding_error=float(np.linalg.norm(realized - ideal, 2)),
                matrix_error=float(
                    np.max(np.abs(encoding.alpha * block - realized))),
                action_error=float(np.max(np.abs(action - realized @ ket))),
                walk_error=max(walk_errors),
                qsvt_error=float(np.max(np.abs(transformed - expected))))


def main():
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument(
        "--verbose",
        action="store_true",
        help="show individual checks and constructor/register diagnostics")
    verbose = parser.parse_args().verbose
    started = time.perf_counter()
    cudaq.set_target(os.environ.get("CUDAQ_DEFAULT_SIMULATOR", "qpp-cpu"))
    print(
        "Sparse access: turn a banded matrix into quantum matrix-vector multiplication."
    )
    four = (np.diag(np.full(4, 1.5)) + np.diag(np.full(3, -.25), 1) +
            np.diag(np.full(3, -.25), -1))
    show_matrix("A sparse 4x4 example (10 nonzeros; at most three per row):",
                four)
    print("Each row couples a site to itself and its immediate neighbours. "
          "The endpoints stop at the boundary.")
    print(
        "\n1. Compare stored entries with arithmetic rules on a small 2x2 instance."
    )
    ideal = np.array([[1.5, -0.25], [-0.25, 1.5]])
    show_matrix("Requested matrix A:", ideal)
    print(
        "QROM loads stored locations/values; arithmetic computes the three bands."
    )
    print(
        "The selected circuit block contains A~/alpha, where A~ uses four-bit angles. "
        "Multiply that block by alpha to recover the represented matrix.")
    data = encode_sparse(sparse.csr_matrix(ideal), value_bits=4)
    required = ("dim", "nnz", "max_row_nnz", "slots", "alpha", "value_bits",
                "dilated", "qubits")
    report = {field: data.report[field] for field in required}
    if verbose:
        print("SciPy data constructor report:")
        for field, value in report.items():
            print(f"  {field}: {value}")
    check("report total qubits",
          data.report["qubits"],
          data.num_system + data.num_ancilla,
          0,
          verbose=verbose)
    rows, columns = np.nonzero(ideal)
    triples = (rows.tolist(), columns.tolist(), ideal[rows, columns].tolist())
    # Equivalent constructors are shown through metadata; circuit execution
    # below covers the SciPy route, which shares their validated factory.
    for label, source, keywords in (("NumPy", ideal, {}), ("integer triples",
                                                           triples, {
                                                               "dim": 2
                                                           })):
        equivalent = encode_sparse(source, value_bits=4, **keywords)
        if equivalent.report != data.report:
            raise AssertionError(f"{label} constructor metadata differs")
        if verbose:
            print(f"{label} constructor: identical report (metadata only).")
    if verbose:
        print("Assigned matching slots need not equal the maximum row nnz.")
    ket = np.array([1., 1j]) / np.sqrt(2)
    stored = check_encoding("QROM 2x2", data, ideal, ket, verbose=verbose)

    arithmetic = SparseOracleEncoding(banded_oracles([-1, 0, 1],
                                                     [-.25, 1.5, -.25],
                                                     num_system=1,
                                                     value_bits=4),
                                      num_system=1)
    computed = check_encoding("arithmetic 2x2",
                              arithmetic,
                              ideal,
                              ket,
                              verbose=verbose)
    check("both access methods recover the same matrix",
          stored["matrix"],
          computed["matrix"],
          2 * ATOL,
          verbose=verbose)
    check("both access methods agree on the shared input",
          stored["action"],
          computed["action"],
          2 * ATOL,
          verbose=verbose)
    show_matrix("Expected four-bit matrix A~ (NumPy):", stored["represented"])
    show_matrix(
        f"Recovered from QROM: alpha * circuit block (alpha={data.alpha:g}):",
        stored["matrix"])
    show_matrix(
        f"Recovered from arithmetic: alpha * circuit block (alpha={arithmetic.alpha:g}):",
        computed["matrix"])
    print(
        f"Matrix-rounding error ||A~-A||_2 = {stored['rounding_error']:.6f}. "
        "Circuit agreement with A~ is checked separately below.")
    print(
        "\nBoth circuits use b = [1, i]/sqrt(2). Compare their matrix-vector outputs:"
    )
    show_vectors({
        "NumPy A@b": ideal @ ket,
        "NumPy A~@b": stored["represented"] @ ket,
        "QROM alpha*y": stored["action"],
        "Arithmetic alpha*y": computed["action"]
    })
    print(
        "Here y is the unnormalized component in the selected ancilla sector. "
        "Its scale differs between encodings; alpha*y recovers A~@b.")

    print("\n2. Apply the 4x4 banded matrix to an endpoint input.")
    banded = SparseOracleEncoding(banded_oracles([-1, 0, 1], [-.25, 1.5, -.25],
                                                 num_system=2,
                                                 value_bits=4),
                                  num_system=2)
    endpoint = np.array([1., 0., 0., 0.], dtype=complex)
    larger = check_encoding("arithmetic 4x4",
                            banded,
                            four,
                            endpoint,
                            verbose=verbose)
    check("clipped corners do not form a ring",
          larger["block"][[0, 3], [3, 0]],
          np.zeros(2),
          verbose=verbose)
    show_matrix("Matrix recovered from the arithmetic circuit:",
                larger["matrix"])
    print(
        "For b = [1, 0, 0, 0], only the first two output entries are nonzero:")
    show_vectors({
        "NumPy A@b": four @ endpoint,
        "NumPy A~@b": larger["represented"] @ endpoint,
        "Circuit alpha*y": larger["action"]
    })
    print("The far endpoint stays zero: the bands do not wrap into a ring.")
    print(
        f"Four-bit matrix-rounding error ||A~-A||_2 = {larger['rounding_error']:.6f}."
    )

    # This larger geometry is priced classically, without simulating it.
    dilated = encode_sparse(np.array([[0., -.5], [.25, 0.]]),
                            value_bits=4,
                            dilate=True)
    if verbose:
        print("\nGeneral real matrix: Hermitian dilation metadata only:",
              dilated.report)
        print(
            "Direct encoding supports real symmetric matrices, nonnegative "
            "diagonals and signed off-diagonals. Dilation handles general real data."
        )
        print(
            "Factory non-power-of-two padding is zero, unlike example 07's "
            "dense identity padding. Reciprocal examples need a nonzero spectrum."
        )
        print(
            "Sparse encodings lack odd-moment SELECT observables; expanded even "
            "reflection observables are costly. Validate statevector walk blocks here."
        )
    cases = (("QROM 2x2", data, stored), ("Arithmetic 2x2", arithmetic,
                                          computed), ("Arithmetic 4x4", banded,
                                                      larger))
    print("\n3. Compare circuit accuracy and cost.")
    print(
        "Maximum errors against the independent NumPy references (tolerance 1e-10):"
    )
    print(
        f"{'Method':<18} {'Matrix':>11} {'Matvec':>11} {'Walk (1,2)':>12} {'QSVT':>11}"
    )
    for name, _, result in cases:
        print(f"{name:<18} {result['matrix_error']:11.2e} "
              f"{result['action_error']:11.2e} {result['walk_error']:12.2e} "
              f"{result['qsvt_error']:11.2e}")
    print("\nThe same Walk and QSVT APIs consumed each encoding.")
    print(
        f"{'Method':<18} {'System':>7} {'Ancillas':>9} {'Total':>7} {'Padded slots':>13} {'alpha':>7}"
    )
    for name, encoding, _ in cases:
        print(f"{name:<18} {encoding.num_system:7d} {encoding.num_ancilla:9d} "
              f"{encoding.num_system+encoding.num_ancilla:7d} "
              f"{encoding.d_padded:13d} {encoding.alpha:7g}")
    print(
        "Arithmetic uses fewer qubits for this 2x2 fixture but doubles alpha. "
        "A larger alpha moves normalized eigenvalues closer to zero, "
        "which makes inverse polynomials more expensive.")
    print(
        "All checks passed, including workspace restoration and clipped boundaries."
    )
    print(
        "Displayed matrices/vectors are read from the simulator statevector.")
    maximum = max(e.num_system + e.num_ancilla
                  for e in (data, arithmetic, banded))
    print(f"Maximum executed qubits: {maximum}; elapsed: "
          f"{time.perf_counter()-started:.2f}s")


if __name__ == "__main__":
    main()

The double-factorized block encoding vs a flat PauliLCU

A molecular Hamiltonian contains many interaction coefficients, and the way those coefficients are organized affects the quantum circuit built from them. This example uses double factorization to express the interactions through simpler contributions in rotated orbital bases. Starting from real molecular integrals, it compares that construction with a Pauli expansion and asks how keeping fewer factors or refining them changes the encoded Hamiltonian and its resource requirements.

You should learn how the choice of orbital basis turns the selected interactions into simple phase operations, and how QROM-loaded angle words let a quantum index choose that basis coherently. The fixed-angle and programmable constructions share the same block-encoding interface, allowing the same Walk and QSVT consumers to use them. Independent references separate factorization and coefficient errors from angle rounding and circuit error, so readers can evaluate accuracy together with normalization, qubit counts, and the cost of loading, using, and clearing the rotation data.

Individual validation checks are shown with --verbose. All checks still run by default, and failures are always reported.

Runs the worked double-factorized encoding (the bring-your-own-encoding example df_encoding.py, next to this script) head to head with a flat PauliLCU on real molecules from PySCF – comparing alpha and term counts, sweeping the truncation dial, re-optimizing kept leaves with RC-DF, and verifying the encoded blocks against a sparse Jordan-Wigner reference.

How the example encoding works, in brief: the factorized Hamiltonian is regrouped so every term is diagonal in some rotated orbital basis – the one-body part in the eigenbasis of the corrected one-body matrix, each factorization leaf in its own eigenbasis. SELECT walks through these frames in its fixed backend with uncontrolled Givens networks (only Z words and sign phases carry ancilla controls, so unselected frames telescope to the identity), and the encoding’s normalization reproduces the published LCU one-norm of double_factorization_one_norm(..., "lcu") exactly, up to the identity term. Compressing the factorization (fewer leaves) shrinks the term count and, typically though not monotonically, the normalization – the knob a flat Pauli expansion does not have. The full construction is documented in the example module’s docstrings.

The default H2 run also selects one real spatial frame coherently with QROM-loaded angle words. It compares fixed and represented operators, clears angle/ladder workspace, and executes Walk and QSVT against NumPy references. Use --rotation-backend {fixed,qrom,both} and --angle-bits 4. A host-only four/six/eight-bit sweep separates angle rounding from circuit error; larger QROM cases are resource-only. See the guide’s real spatial frame section for register conventions and the distinction from the papers’ complete DF algorithms.

"""A user-written block encoding on real molecules, vs the built-in PauliLCU.

A molecular Hamiltonian contains many interaction coefficients, and the way
those coefficients are organized affects the quantum circuit built from them.
This example uses double factorization to express the interactions through
simpler contributions in rotated orbital bases. Starting from real molecular
integrals, it compares that construction with a Pauli expansion and asks how
keeping fewer factors or refining them changes the encoded Hamiltonian and its
resource requirements.

You should learn how the choice of orbital basis turns the selected
interactions into simple phase operations, and how QROM-loaded angle words let
a quantum index choose that basis coherently. The fixed-angle and programmable
constructions share the same block-encoding interface, allowing the same Walk
and QSVT consumers to use them. Independent references separate factorization
and coefficient errors from angle rounding and circuit error, so readers can
evaluate accuracy together with normalization, qubit counts, and the cost of
loading, using, and clearing the rotation data.

The encoding here is user-level code: ``df_encoding.py`` next door
implements ``DoubleFactorizedEncoding`` against the public
``BlockEncoding`` protocol. Because the protocol is structural, the same
``Walk`` consumer drives the user-written encoding and the built-in
``PauliLCU`` identically.

Integrals come from PySCF (``pip install pyscf``) via
``chemistry.from_pyscf``, for a menu of molecular configurations::

    python3 df_block_encoding.py [config] [--circuits]
        [--rotation-backend {fixed,qrom,both}] [--angle-bits 4]

    h2         H2 / STO-3G           2 orbitals ->  4 system qubits  (default)
    h2o-cas44  H2O / STO-3G CAS(4,4) 4 orbitals ->  8 system qubits
    h4         linear H4 / STO-3G    4 orbitals ->  8 system qubits
    lih        LiH / STO-3G          6 orbitals -> 12 system qubits
    h2o        H2O / STO-3G          7 orbitals -> 14 system qubits
    h2o-631g   H2O / 6-31G          13 orbitals -> 26 system qubits

Every configuration tells the classical story: double-factorize the ERI,
compare the DF encoding's normalization ``alpha`` and term count against
the flat Pauli-expansion ``PauliLCU`` baseline, and sweep the truncation
dial (fewer leaves -> fewer terms; alpha typically, though not
monotonically, shrinks -- see the note in the sweep. The flat expansion
has no such knob). All but the largest configuration then re-optimize the
kept leaves with RC-DF at the same budgets
(``compressed_double_factorization`` with a small ridge) -- the second
dial: optimize, don't just truncate. Small configurations also
run the circuits: the encoded block is checked against a sparse
Jordan-Wigner reference Hamiltonian, and the same ``Walk`` consumer
measures Chebyshev moments through both encodings. Larger configurations
skip circuit execution (statevector cost is printed)
-- the classical preprocessing scales; the simulator is what does not.
``lih`` sits on the boundary: pass ``--circuits`` to run it anyway
(hours on a typical CPU).

The H2 default executes both fixed and QROM-programmed spatial frames,
then reports a host-only precision sweep. Larger QROM programs are
resource-only; the size policy above applies to the fixed backend. Tight
circuit checks target the represented operator, with angle rounding
reported separately. No compiled extension is needed.
Add --verbose to show individual validation checks; failures are always reported.
"""
from __future__ import annotations

import argparse
import os
import pathlib
import sys

import numpy as np
import scipy.sparse as sp

import cudaq

from cudaq_algorithms import (PauliLCU, PhaseSequence, QSVT, Walk, chemistry,
                              state_from)
from cudaq_algorithms import double_factorization as df

# The encoding under demonstration is a sibling example file, not a package
# module (CUDA-Q kernels need real .py files, so a plain import is fine).
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from df_encoding import DoubleFactorizedEncoding

cudaq.set_target(os.environ.get("CUDAQ_DEFAULT_SIMULATOR", "qpp-cpu"))

try:
    from pyscf import ao2mo, gto, mcscf, scf
except ImportError:
    sys.exit("This example builds its molecules with PySCF: pip install pyscf")

# ----------------------------------------------------------------------
# The molecule menu. Each builder returns (one_body, eri, core_energy,
# mean-field energy) with chemist (pq|rs) MO integrals -- exactly what
# chemistry.qubit_hamiltonian and DoubleFactorizedEncoding consume.
# ----------------------------------------------------------------------

_H2O_GEOMETRY = """
O  0.0000  0.0000  0.1173
H  0.0000  0.7572 -0.4692
H  0.0000 -0.7572 -0.4692
"""


def _rhf(atom: str, basis: str):
    molecule = gto.M(atom=atom, basis=basis, symmetry=False, verbose=0)
    return scf.RHF(molecule).run()


def _full_space(atom: str, basis: str):
    mean_field = _rhf(atom, basis)
    one_body, eri, nuclear = chemistry.from_pyscf(mean_field)
    return one_body, eri, nuclear, float(mean_field.e_tot)


def _h2o_cas44():
    """H2O in a (4 electron, 4 orbital) active space.

    PySCF's CASCI effective integrals fold the inactive (core) orbitals
    into a 4-orbital one-body matrix and scalar -- real water at 8 system
    qubits, small enough for the full dense-checked circuit story.
    """
    mean_field = _rhf(_H2O_GEOMETRY, "sto-3g")
    cas = mcscf.CASCI(mean_field, ncas=4, nelecas=4)
    one_body, core_energy = cas.get_h1eff()
    eri = ao2mo.restore(1, cas.get_h2eff(), 4)
    return (np.asarray(one_body), np.asarray(eri), float(core_energy),
            float(mean_field.e_tot))


_H4_CHAIN = "; ".join(f"H 0 0 {i:.1f}" for i in range(4))

CONFIGS = {
    "h2": {
        "label": "H2 / STO-3G",
        "build": lambda: _full_space("H 0 0 0; H 0 0 0.7414", "sto-3g"),
        "mode": "full",
    },
    "h2o-cas44": {
        "label": "H2O / STO-3G, CAS(4e,4o) active space",
        "build": _h2o_cas44,
        "mode": "full",
    },
    "h4": {
        # Smallest system where leaf truncation shows a real alpha-vs-error
        # trade-off; a standard strong-correlation benchmark (stretched
        # chain: 1.0 A spacing vs 0.74 A equilibrium).
        "label": "linear H4 (1.0 A spacing) / STO-3G",
        "build": lambda: _full_space(_H4_CHAIN, "sto-3g"),
        "mode": "full",
    },
    "lih": {
        "label": "LiH / STO-3G",
        "build": lambda: _full_space("Li 0 0 0; H 0 0 1.595", "sto-3g"),
        "mode": "flagged",  # circuits only with --circuits (hours)
    },
    "h2o": {
        "label": "H2O / STO-3G (full space)",
        "build": lambda: _full_space(_H2O_GEOMETRY, "sto-3g"),
        "mode": "classical",
    },
    "h2o-631g": {
        "label": "H2O / 6-31G (full space)",
        "build": lambda: _full_space(_H2O_GEOMETRY, "6-31g"),
        "mode": "classical",
        "cdf": False,  # L-BFGS at 13 orbitals is a coffee break, not a demo
    },
}

# ----------------------------------------------------------------------
# Sparse Jordan-Wigner reference (interleaved spins, qubit 0 least
# significant -- the library's convention). Sparse matrices keep the
# reference cheap out to the 12-qubit LiH configuration.
# ----------------------------------------------------------------------


def _sparse_annihilators(num_qubits: int) -> list[sp.csr_matrix]:
    z2 = sp.csr_matrix(np.diag([1.0, -1.0]))
    identity = sp.identity(2, format="csr")
    lowering = sp.csr_matrix(np.array([[0.0, 1.0], [0.0, 0.0]]))
    out = []
    for mode in range(num_qubits):
        ops = ([z2] * mode + [lowering] + [identity] *
               (num_qubits - mode - 1))[::-1]
        matrix = sp.identity(1, format="csr")
        for op in ops:
            matrix = sp.kron(matrix, op, format="csr")
        out.append(matrix)
    return out


def reference_hamiltonian(one_body: np.ndarray,
                          eri: np.ndarray) -> sp.csr_matrix:
    """H = sum h_pq E_pq + 1/2 sum (pq|rs) (E_pq E_rs - delta_qr E_ps)."""
    n = one_body.shape[0]
    num_qubits = 2 * n
    lower = _sparse_annihilators(num_qubits)
    raise_ = [op.conj().T.tocsr() for op in lower]

    def excite(p, q):
        return (raise_[2 * p] @ lower[2 * q] +
                raise_[2 * p + 1] @ lower[2 * q + 1])

    excitations = [[excite(p, q) for q in range(n)] for p in range(n)]
    dim = 1 << num_qubits
    h = sp.csr_matrix((dim, dim), dtype=complex)
    for p in range(n):
        for q in range(n):
            h = h + one_body[p, q] * excitations[p][q]
            for r in range(n):
                for s in range(n):
                    term = excitations[p][q] @ excitations[r][s]
                    if q == r:
                        term = term - excitations[p][s]
                    h = h + 0.5 * eri[p, q, r, s] * term
    return h.tocsr()


def chebyshev_moment(h_scaled: sp.csr_matrix, ket: np.ndarray,
                     order: int) -> float:
    """<ket| T_k(H/alpha) |ket> by the vector three-term recurrence."""
    t_prev, t_cur = ket, h_scaled @ ket
    if order == 0:
        return float(np.real(ket.conj() @ t_prev))
    for _ in range(order - 1):
        t_prev, t_cur = t_cur, 2.0 * (h_scaled @ t_cur) - t_prev
    return float(np.real(ket.conj() @ t_cur))


def check(label: str, condition: bool, *, verbose=False):
    if verbose or not condition:
        print(f"  [check] {label} ... {'OK' if condition else 'FAILED'}")
    if not condition:
        sys.exit(1)


# ----------------------------------------------------------------------
# The story, per configuration
# ----------------------------------------------------------------------


def fock_matrix(orbital):
    """Independent second quantization by determinant minors."""
    occupied = [[p for p in range(len(orbital)) if bits >> p & 1]
                for bits in range(1 << len(orbital))]
    result = np.zeros((len(occupied), len(occupied)), dtype=complex)
    for s, rows in enumerate(occupied):
        for t, cols in enumerate(occupied):
            if len(rows) == len(cols):
                result[s, t] = np.linalg.det(orbital[np.ix_(rows, cols)])
    return result


def frame_hamiltonian(encoding, *, represented):
    """Retained coefficients/Z words conjugated by independent Fock frames."""
    frames = (encoding.represented_frame_matrices
              if represented else encoding.ideal_frame_matrices)
    lifts = [fock_matrix(np.kron(frame, np.eye(2))) for frame in frames]
    dimension = 1 << encoding.num_system
    result = np.zeros((dimension, dimension), dtype=complex)
    for coefficient, qubits, frame in encoding.terms:
        diagonal = np.array([(-1)**sum((bits >> q) & 1 for q in qubits)
                             for bits in range(dimension)])
        g = lifts[frame]
        result += coefficient * (g * diagonal) @ g.conj().T
    return result


def angle_error_bound(encoding):
    bounds = encoding.rotation_report["frame_error_bounds"]
    return sum(
        abs(c) * min(2., 2 * bounds[frame])
        for c, qubits, frame in encoding.terms if qubits)


def signal_response(x, phases):
    """Scalar 2x2 projector-phase response; no quantum output calibration."""
    s = np.sqrt(max(0., 1 - x * x))
    w = np.array([[-x, -s], [s, -x]], dtype=complex)
    result = np.diag([np.exp(1j * phases[0]), 1.])
    for phi in phases[1:]:
        result = np.diag([np.exp(1j * phi), 1.]) @ w @ result
    return result[0, 0]


def report_programmed_frames(one_body,
                             eri,
                             factorized,
                             core_energy,
                             angle_bits,
                             circuits,
                             *,
                             verbose=False):
    """Small H2 numerical capstone; larger programs are resource reports."""
    encoding = DoubleFactorizedEncoding(one_body,
                                        factorized.factorization,
                                        rotation_backend="qrom",
                                        angle_bits=angle_bits)
    report = encoding.rotation_report
    total = encoding.num_system + encoding.num_ancilla
    print(f"\n  QROM frames: b={angle_bits}, alpha={encoding.alpha:.12g}, "
          f"{report['mixing_slots']} real spatial mixing slots")
    print(f"  Layout: {encoding.num_system} system + "
          f"{report['term_index_width']} term index + "
          f"{report['program_width']} angle + {report['ladder_width']} ladder "
          f"= {total} qubits; controlled forms add one")
    print(f"  SELECT QROM: variant={report['qrom_variant']}, "
          f"table rows={report['table_size']}; "
          f"{report['lookup_calls']} lookup/unlookup calls per SELECT")
    print(f"  PREPARE: {report['prepare_rotations']} tree rotations; "
          f"SELECT: {report['programmable_spatial_calls']} bit-controlled "
          "spatial rotations (two spin sectors each); external control "
          "acts only on Z words/signs, not on lookup or rotations.")
    print("  Gate counts here are logical operations, without rotation "
          "synthesis or paper-optimized normalization.")
    check("fixed and QROM retain identical coefficients and alpha",
          encoding.terms == factorized.terms
          and encoding.alpha == factorized.alpha,
          verbose=verbose)
    # Dense determinant-minor references grow exponentially. Only the default
    # two-spatial-mode case runs them; larger molecules retain the original
    # classical truncation/compression and fixed-backend demonstrations.
    if len(one_body) > 2:
        print("  QROM circuits and dense angle sweep: resource-only at this "
              f"size ({total} qubits). Angle operator-error bound "
              f"{angle_error_bound(encoding):.6g} Ha.")
        return
    for j, (_, qubits, frame) in enumerate(encoding.terms):
        width = report["term_index_width"]
        address = int(f"{j:0{width}b}"[::-1], 2)
        print(
            f"    term {j:2d} -> physical address {address:2d}, frame {frame}, "
            f"Z{qubits}, packed angle row {report['angle_rows'][address]}")

    input_h = reference_hamiltonian(one_body, eri).toarray()
    df_h = reference_hamiltonian(one_body,
                                 df.reconstruct_eri(
                                     factorized.factorization)).toarray()
    kept = frame_hamiltonian(factorized, represented=False)
    represented = frame_hamiltonian(encoding, represented=True)
    angle_error = np.linalg.norm(represented - kept, 2)
    bound = angle_error_bound(encoding)
    print(
        f"  Operator errors (Ha): factorization={np.linalg.norm(df_h-input_h,2):.3e}, "
        f"threshold={np.linalg.norm(kept-df_h,2):.3e}, "
        f"angle={angle_error:.3e}, bound={bound:.3e} (+1e-10 floating slack)")
    check("angle error satisfies its derived operator bound",
          angle_error <= bound + 1e-10,
          verbose=verbose)
    print(
        f"  NumPy ground energies, including classical core offset: "
        f"fixed={np.linalg.eigvalsh(kept)[0] + core_energy:.12f}, "
        f"represented={np.linalg.eigvalsh(represented)[0] + core_energy:.12f} Ha"
    )
    print(
        "  These are classical diagonalizations; action checks do not measure an energy."
    )
    print("  Host-only precision sweep (no circuit execution):")
    ideal_energy = np.linalg.eigvalsh(kept)[0]
    for bits in (4, 6, 8):
        candidate = DoubleFactorizedEncoding(one_body,
                                             factorized.factorization,
                                             rotation_backend="qrom",
                                             angle_bits=bits)
        h_b = frame_hamiltonian(candidate, represented=True)
        print(
            f"    b={bits}: operator error={np.linalg.norm(h_b-kept,2):.3e}, "
            f"ground-energy error={abs(np.linalg.eigvalsh(h_b)[0]-ideal_energy):.3e} Ha, "
            f"{candidate.num_system + candidate.num_ancilla} qubits")
    if not circuits or total > 20:
        print(
            f"  QROM circuit execution skipped; resource-only ({total} qubits)."
        )
        return
    rng = np.random.default_rng(7)
    ket = rng.normal(size=len(kept)) + 1j * rng.normal(size=len(kept))
    ket = (ket / np.linalg.norm(ket)).astype(np.complex128)

    def verify(label, kernel, expected):
        actual = np.asarray(cudaq.get_state(kernel,
                                            state_from(ket)))[:len(ket)]
        error = float(np.max(np.abs(actual - expected)))
        if verbose or not np.isfinite(error) or error > 1e-10:
            print(f"  {label}: max |diff|={error:.3e}, tolerance=1e-10")
        np.testing.assert_allclose(actual, expected, rtol=0, atol=1e-10)
        check(label, error <= 1e-10, verbose=verbose)

    scaled = represented / encoding.alpha
    verify("QROM <0|U|0> = H_b/alpha", encoding.encode_kernel(), scaled @ ket)
    for order in (1, 2):
        polynomial = -scaled if order == 1 else 2 * scaled @ scaled - np.eye(
            len(kept))
        verify(f"QROM Walk T_{order}(-H_b/alpha)", encoding.walk_kernel(order),
               polynomial @ ket)
    phases = [.3, -.4, .25]
    values, vectors = np.linalg.eigh(scaled)
    expected = (vectors * [signal_response(x, phases)
                           for x in values]) @ (vectors.conj().T @ ket)
    verify("QROM QSVT projector response",
           QSVT(encoding).kernel(PhaseSequence(phases)), expected)
    print(
        "  QROM measured moments omitted: the expanded reflection observable "
        "grows exponentially with workspace.")


def run(key: str,
        force_circuits: bool,
        rotation_backend="both",
        angle_bits=4,
        *,
        verbose=False):
    config = CONFIGS[key]
    one_body, eri, core_energy, scf_energy = config["build"]()
    n = one_body.shape[0]
    num_system = 2 * n

    print(f"=== {key}: {config['label']} ===")
    print(f"RHF energy {scf_energy:.6f} Ha; core/nuclear constant "
          f"{core_energy:.6f} Ha (added classically, not encoded)")
    print(f"{n} spatial orbitals -> {num_system} system qubits")

    # --- classical story: both encodings, and the truncation dial --------
    flat = PauliLCU(chemistry.qubit_hamiltonian(one_body, eri))
    factorization = df.explicit_double_factorization(eri, threshold=0.0)
    factorized = DoubleFactorizedEncoding(one_body, factorization)

    print(f"\n  flat PauliLCU:            alpha = {flat.alpha:10.4f}, "
          f"{flat.num_terms} Pauli terms, {flat.num_ancilla} ancillas")
    print(f"  DoubleFactorizedEncoding: alpha = {factorized.alpha:10.4f}, "
          f"{factorized.num_terms} Z-word terms in {factorized.num_frames} "
          f"frames ({factorization.num_leaves} leaves), "
          f"{factorized.num_givens_rotations} Givens rotations, "
          f"{factorized.num_ancilla} ancillas")

    print("\n  Truncating the factorization (the knob PauliLCU lacks):")
    total = factorization.num_leaves
    if total <= 12:
        leaf_counts = list(range(1, total + 1))
    else:
        leaf_counts = sorted(
            set(np.linspace(1, total, 10).astype(int).tolist()))
    errors = []
    for leaves in leaf_counts:
        truncated = df.explicit_double_factorization(eri,
                                                     threshold=0.0,
                                                     max_num_leaves=leaves)
        encoding = DoubleFactorizedEncoding(one_body, truncated)
        error = df.factorization_error(eri, truncated)
        errors.append(error)
        print(f"    {leaves:3d} leaves: alpha = {encoding.alpha:10.4f}, "
              f"{encoding.num_terms:5d} terms, tensor error {error:.2e}")
    # Note: alpha is NOT guaranteed monotone in the leaf count -- dropping a
    # leaf also reshapes the one-body singles absorbed into kappa, so alpha
    # can overshoot at intermediate truncations. The tensor error IS
    # monotone (nested pivoted-Cholesky truncation).
    check("truncation error is non-increasing in leaves",
          all(a >= b - 1e-9 for a, b in zip(errors, errors[1:])),
          verbose=verbose)
    check("full-rank X-DF reconstructs the ERI exactly",
          errors[-1] < 1e-8,
          verbose=verbose)

    # RC-DF: the other dial. X-DF truncation keeps the FIRST leaves of an
    # exact factorization; C-DF re-optimizes the leaves you keep (L-BFGS
    # over the rotations, closed-form cores) for the same budget. The small
    # ridge (regularization=1e-4, i.e. RC-DF) matters: unregularized C-DF
    # can exploit gauge freedom to fit better with ENORMOUS core entries --
    # alpha blows up by orders of magnitude -- the pathology the
    # regularized variant exists to prevent.
    if config.get("cdf", True):
        if n <= 4:
            budgets = sorted(
                {max(1, round(total * f))
                 for f in (0.25, 0.5, 0.75)} - {total})
        else:
            budgets = [max(1, round(total / 3))]  # L-BFGS gets expensive
        budgets = [b for b in budgets if b < total]  # rank-1: nothing to do
        print("\n  RC-DF at the same leaf budgets (optimize the kept "
              "leaves, don't just truncate):")
        eri_norm = float(np.linalg.norm(eri))  # scale-invariant gate
        wins = []
        for leaves in budgets:
            truncated = df.explicit_double_factorization(eri,
                                                         threshold=0.0,
                                                         max_num_leaves=leaves)
            xdf_error = df.factorization_error(eri, truncated)
            compressed = df.compressed_double_factorization(
                eri, num_leaves=leaves, regularization=1e-4)
            cdf_error = df.factorization_error(eri, compressed)
            cdf_alpha = DoubleFactorizedEncoding(one_body, compressed).alpha
            ratio = xdf_error / max(cdf_error, 1e-16)
            if cdf_error < 1e-10:
                better = "exact fit"
            elif ratio >= 1.0:
                better = f"{ratio:.1f}x better"
            else:
                # Near full rank the truncation error is already ~ the
                # ridge scale, so the regularization bias dominates: the
                # ridge trades a small fit penalty for bounded cores
                # (sane alpha). The win to assert is at AGGRESSIVE budgets.
                better = f"{1.0 / ratio:.1f}x worse (ridge bias; X-DF "\
                         "already near-exact here)"
            if xdf_error > 1e-2 * eri_norm:
                wins.append(cdf_error <= xdf_error * 1.001 + 1e-12)
            print(f"    {leaves:3d} leaves: X-DF error {xdf_error:.2e}  "
                  f"RC-DF error {cdf_error:.2e}  ({better}), "
                  f"RC-DF alpha = {cdf_alpha:.4f}")
        # Reported, not asserted: L-BFGS guarantees descent of the
        # REGULARIZED objective, not of the raw fit error, so the win is
        # empirical (robust in practice at significant truncation error,
        # but a hard exit here could misfire on someone else's molecule).
        if wins and all(wins):
            if verbose:
                print("  [check] RC-DF fits at least as well wherever "
                      "truncation error is still significant ... OK")
        elif wins:
            print("  [note] RC-DF trailed truncated X-DF at a "
                  "significant-error budget -- the ridge trades fit for "
                  "bounded cores; try a smaller regularization.")
        else:
            print("  (no budget in the significant-error regime; "
                  "RC-DF win not reported)")
    else:
        print("\n  RC-DF comparison skipped at this size (the L-BFGS "
              "optimization is the expensive path; see "
              "examples/double_factorization/).")

    # --- circuit story (size-gated) ---------------------------------------
    mode = config["mode"]
    circuits = mode == "full" or (mode == "flagged" and force_circuits)
    if rotation_backend in ("qrom", "both"):
        report_programmed_frames(one_body,
                                 eri,
                                 factorized,
                                 core_energy,
                                 angle_bits,
                                 circuits,
                                 verbose=verbose)
    if rotation_backend == "qrom":
        return
    total_qubits = num_system + factorized.num_ancilla
    if mode == "classical" or (mode == "flagged" and not force_circuits):
        amplitudes = f"2^{total_qubits}"
        print(f"\n  Circuit execution skipped: {num_system} system + "
              f"{factorized.num_ancilla} ancilla = {total_qubits} qubits "
              f"({amplitudes} amplitudes per state).")
        if mode == "flagged":
            print("  Rerun with --circuits to run them anyway "
                  "(hours on a typical CPU).")
        print("  The classical preprocessing above is the part that scales;"
              " the statevector simulator is the part that does not.")
        return

    print(
        f"\n  Fixed circuits: {num_system} system + {factorized.num_ancilla} "
        f"index + 0 angle + 0 ladder = {total_qubits} qubits; "
        "controlled forms add one")
    dim = 1 << num_system
    hamiltonian = reference_hamiltonian(one_body, eri)
    rng = np.random.default_rng(7)
    ket = rng.normal(size=dim) + 1.0j * rng.normal(size=dim)
    ket = (ket / np.linalg.norm(ket)).astype(np.complex128)

    # The encoded block <0|U|0> must equal H/alpha, on a random state,
    # against the independent sparse Jordan-Wigner reference.
    state = np.array(
        cudaq.get_state(factorized.encode_kernel(), state_from(ket)))
    block = state[:dim]
    expected = (hamiltonian @ ket) / factorized.alpha
    block_error = float(np.max(np.abs(block - expected)))
    if verbose or not np.isfinite(block_error) or block_error >= 1e-10:
        print(f"  encoded block vs sparse JW reference: max |diff| = "
              f"{block_error:.2e}")
    check("<0|U|0> == H/alpha", block_error < 1e-10, verbose=verbose)

    print("\n  Even Chebyshev moments <T_k(H/alpha)> through Walk (same"
          "\n  consumer, either encoding; alphas differ, H is the same):")
    for order in (0, 2, 4):
        measured_flat = Walk(flat).moment(ket, order)
        measured_df = Walk(factorized).moment(ket, order)
        exact_flat = chebyshev_moment(hamiltonian / flat.alpha, ket, order)
        exact_df = chebyshev_moment(hamiltonian / factorized.alpha, ket, order)
        print(f"    T_{order}:  PauliLCU {measured_flat:+.8f} "
              f"(exact {exact_flat:+.8f})   DF {measured_df:+.8f} "
              f"(exact {exact_df:+.8f})")
        check(f"T_{order} moments match the reference",
              abs(measured_flat - exact_flat) < 1e-8
              and abs(measured_df - exact_df) < 1e-8,
              verbose=verbose)


def main():
    parser = argparse.ArgumentParser(
        description=__doc__.splitlines()[0],
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="configurations:\n" +
        "\n".join(f"  {key:10s} {config['label']}"
                  for key, config in CONFIGS.items()))
    parser.add_argument("config",
                        nargs="?",
                        default="h2",
                        choices=sorted(CONFIGS),
                        help="molecular configuration (default: h2)")
    parser.add_argument("--circuits",
                        action="store_true",
                        help="run circuits on boundary-size configurations "
                        "(lih; hours on a typical CPU)")
    parser.add_argument("--rotation-backend",
                        choices=("fixed", "qrom", "both"),
                        default="both",
                        help="DF rotation backend (default: both)")
    parser.add_argument("--angle-bits",
                        type=int,
                        default=4,
                        help="QROM full-turn angle bits (default: 4)")
    parser.add_argument(
        "--verbose",
        action="store_true",
        help="show each validation check (failures are always reported)")
    arguments = parser.parse_args()
    run(arguments.config,
        arguments.circuits,
        arguments.rotation_backend,
        arguments.angle_bits,
        verbose=arguments.verbose)


if __name__ == "__main__":
    main()