Calculate the Ground State Energy Using QPE and BEAST-VQE

Goal

Run quantum phase estimation (QPE) and Bayesian quantum phase estimation (BQPE) for LiH in the STO-3G basis, with and without a BEAST-VQE state as input. Compare their total energies with the BEAST-VQE convergence curve.

QPE is generally very resource demanding. This guide uses the paired-electron approximation and a hardcore-boson Hamiltonian encoder to reduce the cost. This can make useful hardware experiments accessible earlier than a full fermionic QPE approach. The paired-electron approximation changes the physical model: the target is the paired full configuration interaction (pFCI) ground-state energy, which is not equal the full configuration interaction (FCI) energy.

Prerequisites

  • A ground-state problem (see Construct a Ground State Energy Problem)

  • An NVIDIA GPU with a compatible CUDA and cuQuantum installation for the statevector sampler and estimator used in this example.

  • A Qrunch Pro license

Steps

  1. Import the modules and prepare the molecular problem

    from pathlib import Path
    
    import matplotlib.pyplot as plt
    from matplotlib.ticker import MaxNLocator
    
    import qrunch as qc
    
    

    Build a restricted ground-state problem with paired alpha and beta electrons:

        molecular_configuration = qc.build_molecular_configuration(
            molecule=[
                ("H", 0.0, 0.0, 0.0),
                ("Li", 1.5474, 0.0, 0.0),
            ],
            basis_set="sto3g",
        )
        problem_builder = qc.problem_builder_creator().ground_state().standard().create()
        problem = problem_builder.build_restricted(molecular_configuration)
    

    See Construct a Ground State Energy Problem for other ways to specify a problem.

  2. Create the sampler and estimator

    Basic QPE uses a sampler to read the phase register. BQPE uses an estimator for successive Hadamard tests. Both use cuQuantum statevector simulation here:

        sampler = (
            qc
            .sampler_creator()
            .cuquantum_statevector()
            .with_options(qc.options.CuQuantumStatevectorSamplerOptions(float_type="f32"))
            .create()
        )
        estimator = (
            qc
            .estimator_creator()
            .cuquantum_statevector()
            .with_options(qc.options.CuQuantumStatevectorEstimatorOptions(float_type="f32"))
            .create()
        )
    

    float_type="f32" selects single-precision arithmetic. For accuracy studies, repeat with "f64" to check for single-precision effects. GPU simulation is not an execution on quantum hardware. See Create a Sampler and Create an Estimator for alternative execution components.

  3. Prepare an approximate eigenstate with BEAST-VQE

        beast_calculator = (
            qc
            .calculator_creator()
            .vqe()
            .iterative()
            .beast()
            .with_estimator(estimator)
            .with_options(qc.options.IterativeVqeOptions(max_iterations=20))
            .choose_minimizer()
            .quick_default()
            .create()
        )
        beast_result = beast_calculator.calculate(problem)
    

    BEAST-VQE already uses paired electrons and bosonic encoding. Its optimized circuit can improve overlap with the paired ground state, making it a useful input to phase estimation. Without a supplied VQE result, these calculators start from the problem’s Hartree-Fock reference circuit. See Calculate the Ground State Energy Using the BEAST-VQE for BEAST-VQE configuration options.

  4. Choose a paired-electron Hamiltonian encoder

    Basic QPE uses the fixed-step encoder:

        max_trotter_steps = 300
        hamiltonian_encoder = (
            qc
            .hamiltonian_encoder_creator()
            .trotterization()
            .suzuki_trotter()
            .with_expansion_order(2)
            .with_options(
                qc.options.TrotterizationHamiltonianEncoderOptions(mode="fixed_steps", trotter_steps=max_trotter_steps)
            )
            .create()
        )
    

    The encoder approximates Hamiltonian evolution using second-order Suzuki-Trotter decomposition with 300 fixed steps. The QPE calculator selects the hard-core boson decomposer by default when .paired_electron_approximation() is enabled, and Pauli otherwise. An explicit choice overrides the default: for example, .choose_trotterization_decomposer().locality_hardcore_boson(5) uses locality-aware decomposition with a maximum block size of five. Explicit hard-core boson decomposers require the paired-electron approximation.

    The script sets max_trotter_steps = 300 before constructing the encoders. This variable specifies the fixed number of steps for each basic QPE evolution. With Hamiltonian bound \(\Lambda = \sum_j |c_j|\) and precision qubit index \(k\), basic QPE requests evolution time

    \[t_k = \frac{\pi 2^k}{\Lambda}.\]

    Using \(number_of_precision_qubits=12\) all twelve controlled evolutions use 300 steps, so the step duration \(t_k/300\) increases with \(k\). For this LiH problem, \(\Lambda \approx 13.58\) and the longest time is approximately 474. The longest evolutions are therefore especially sensitive to Trotter error. Adding precision qubits without increasing the step count can sharpen the phase grid while leaving the energy estimate inaccurate.

    The choice of 300 steps is a practical demo setting, not a certified accuracy threshold. Repeat with larger fixed steps while keeping the precision register unchanged, and compare the resulting energies. Increase the precision only after checking this evolution convergence. Fourth-order Suzuki-Trotter decomposition is another option, with additional circuit cost per step.

    Warning

    More precision qubits (QPE) or a tighter tolerance (BQPE) do not guarantee a more accurate energy. QPE’s precision register controls phase resolution; BQPE’s tolerance controls its posterior stopping criterion. Neither controls the error in the Trotterized Hamiltonian evolution. Both can report a finely resolved but inaccurate energy if the evolution is not sufficiently accurate.

    Each additional QPE precision qubit doubles the longest requested evolution time. With a fixed number of Trotter steps per evolution, the steps therefore become longer, making the last precision qubits especially susceptible to Trotter error. Increasing the register size without increasing the step count can make the phase grid finer without improving the energy accuracy.

    In BQPE, narrowing the posterior generally calls for longer evolution times. A tighter tolerance can therefore require more iterations and more Trotter steps per iteration. More iterations alone cannot correct inaccurate evolution, and a small posterior uncertainty need not mean a small energy error.

    Converge the evolution accuracy as well as the phase estimation settings. Dynamic Trotter stepping specifies a reference step count, here at \(t=1\), and increases the count with evolution time to keep a leading-order Trotter error estimate roughly constant. This is not a rigorous error bound: check convergence by increasing the reference count. A maximum step count limits the per-evolution resource cost, not the energy error or the total cost of the calculation.

    In this demo, basic QPE uses a fixed step count; only BQPE uses dynamic stepping with a cap. BQPE stops before a measurement whose requested evolution would exceed its step cap and returns the last posterior, which may not have reached the requested tolerance. Check the resource-limit warning and independently converge the step counts before interpreting agreement or reported uncertainty as evidence of accuracy.

    For both BQPE runs, the demo creates a separate encoder that increases the step count with evolution time:

        hamiltonian_encoder = (
            qc
            .hamiltonian_encoder_creator()
            .trotterization()
            .suzuki_trotter()
            .with_expansion_order(2)
            .with_options(
                qc.options.TrotterizationHamiltonianEncoderOptions(
                    mode="dynamic_steps", trotter_steps=20, reference_time=1.0, max_trotter_steps=max_trotter_steps
                )
            )
            .create()
        )
    

    The specified step count is now the minimum and the count at the reference time: options with mode="dynamic_steps", trotter_steps=20, reference_time=1.0 mean 20 steps for \(|t| \leq 1\). For a product formula of order \(p\), the uncapped requested step count is

    \[n(t) = \left\lceil n_{\mathrm{ref}} \max\left(1, (|t|/t_{\mathrm{ref}})^{1+1/p}\right) \right\rceil.\]

    This keeps the leading error estimate \(O(|t|^{p+1}/n^p)\) roughly constant above the reference time, rather than only keeping the step size constant. The builder uses the selected expansion order automatically. Select mode="fixed_steps" for fixed-step behavior.

    At second order the exponent is \(3/2\): time 2 needs 57 steps, time 4 needs 160, and time 6 needs 294. This grows faster than a fixed step-duration rule, which would only scale linearly with time. Calibrate the reference count independently by increasing it and comparing results; the scaling controls only a leading-order error estimate, not a rigorous error bound, and does not guarantee equal accuracy to the fixed-step QPE run.

    The demo passes the shared variable as max_trotter_steps=300 for BQPE. Here it really is a per-evolution resource cap, not a total budget across iterations. With 20 reference steps at time 1, the largest allowed time is

    \[|t|_{\max} = \left(\frac{300}{20}\right)^{2/3} \approx 6.08.\]

    Before each BQPE measurement, the algorithm asks the encoder whether the requested time would require more steps than this cap. If so, it stops with a warning and returns the last posterior without submitting that measurement. A request exactly at the cap is allowed. If the first request already exceeds the cap, the returned estimate is the unupdated prior. This is a resource-limit stop, not successful convergence to the requested tolerance. The warning includes the number of completed iterations and the final posterior estimate, even when INFO-level iteration logs are hidden:

    BQPE stopped: Maximum number of trotter steps have been reached. Performed 11 iterations for a final estimate of -8.90443134±0.06863386
    

    This is an illustrative electronic-energy estimate; the plot uses total energies, including nuclear repulsion. The iteration count and estimate can differ between runs and initial states.

    Increase the cap to permit longer evolution times. Increasing the reference step count improves the evolution approximation but, at a fixed cap, reduces the maximum allowed time. Omitting the cap permits unlimited step growth. Changing the shared max_trotter_steps variable also changes basic QPE’s fixed count; edit the two encoder arguments independently when studying their convergence separately.

    Note that the basic QPE encoder in this demo has no dynamic reference time or separate cap.

  5. Run basic QPE with and without BEAST-VQE input

        qpe_calculator = (
            qc
            .calculator_creator()
            .quantum_phase_estimation()
            .basic()
            .paired_electron_approximation()
            .with_sampler(sampler)
            .with_options(qc.options.BasicQuantumPhaseEstimationOptions(number_of_precision_qubits=12))
            .with_hamiltonian_encoder(hamiltonian_encoder)
            .create()
        )
    

    Select .paired_electron_approximation() on the QPE calculator to match the BEAST-VQE state and select the hard-core boson decomposer. In this basis LiH has six spatial orbitals: the paired state register uses six qubits rather than twelve spin-orbital qubits. Basic QPE additionally uses the twelve precision qubits specified above, for eighteen qubits in total.

        qpe_result = qpe_calculator.calculate(problem)
        qpe_from_beast_result = qpe_calculator.calculate(problem, beast_result)
    

    Pass the complete beast_result as the second argument, not just its energy. It supplies the optimized state-preparation circuit. Use a result from the same molecular problem and compatible encoding.

    More number_of_precision_qubits gives finer phase resolution but also increases qubit use and the largest controlled evolution time exponentially. Twelve precision qubits do not imply a total-energy accuracy of \(10^{-4}\) Hartree: the energy resolution also depends on the Hamiltonian scaling.

  6. Run Bayesian QPE with and without BEAST-VQE input

        bqpe_calculator = (
            qc
            .calculator_creator()
            .quantum_phase_estimation()
            .bayesian()
            .paired_electron_approximation()
            .with_estimator(estimator)
            .with_options(
                qc.options.BayesianQuantumPhaseEstimationOptions(
                    convergence_rate=5.0,
                    tolerance=1.0e-3,
                    max_number_of_iterations=100,
                )
            )
            .with_hamiltonian_encoder(hamiltonian_encoder)
            .create()
        )
    

    BQPE replaces the multi-qubit phase register with successive Hadamard tests and a classical Bayesian update. It needs one ancillary qubit in addition to the state register, but can still require long evolution circuits.

    tolerance sets the posterior standard deviation at which iteration can stop early. max_number_of_iterations caps the number of Hadamard-test submissions; reaching the cap does not imply that the tolerance was met. convergence_rate controls the strength of the likelihood updates. number_of_candidate_values controls the classical candidate-energy grid.

    This demo requests tolerance=1.0e-3 Hartree, at most 100 iterations, and convergence_rate=5.0. The tolerance is a target, but in this case the 300-step resource cap stops the BQPE much earlier.

        bqpe_result = bqpe_calculator.calculate(problem)
        bqpe_from_beast_result = bqpe_calculator.calculate(problem, beast_result)
    

    For hardware, supply a compatible estimator and a positive shot budget, for example .with_total_estimator_shots(1000). For basic QPE, configure sampling with .with_sampler_shots(1000) and a compatible sampler.

  7. Compare the four results

    Each phase estimation calculation returns a GroundStateProblemCalculatorResult. Use result.total_energy.value for the total molecular energy and result.total_energy.error for the reported uncertainty.

        beast_energies = beast_result.total_energy_per_macro_iteration_with_initial_energy_and_final_energy.values
        phase_estimation_energies = {
            "QPE from Hartree-Fock": qpe_result.total_energy.value,
            "QPE from BEAST-VQE": qpe_from_beast_result.total_energy.value,
            "BQPE from Hartree-Fock": bqpe_result.total_energy.value,
            "BQPE from BEAST-VQE": bqpe_from_beast_result.total_energy.value,
        }
        plot_energies(
            beast_energies,
            phase_estimation_energies,
            outdir=outdir,
            show=show,
        )
    

    The plot uses the following helper:

    def plot_energies(
        beast_energies: list[float],
        phase_estimation_energies: dict[str, float],
        *,
        outdir: Path = Path("dist"),
        show: bool = False,
    ) -> None:
        """
        Plot BEAST-VQE convergence alongside the four phase estimation results.
    
        Args:
            beast_energies: Total energies including the initial and final BEAST-VQE energies.
            phase_estimation_energies: Labels and total energies of the QPE and BQPE runs.
            outdir: Directory in which to save the comparison plot.
            show: Whether to display the plot interactively.
    
        """
        outdir.mkdir(parents=True, exist_ok=True)
        figure, axes = plt.subplots()
        axes.plot(range(len(beast_energies)), beast_energies, "-*", color="darkgreen", label="BEAST-VQE")
        for (label, energy), color, linestyle in zip(
            phase_estimation_energies.items(),
            ("royalblue", "orange", "firebrick", "purple"),
            ("-", "--", "-.", ":"),
            strict=True,
        ):
            axes.axhline(energy, color=color, linestyle=linestyle, label=label)
    
        axes.set_xlabel("BEAST-VQE iteration (including initial and final energies)")
        axes.set_ylabel("Total energy [Hartree]")
        axes.set_title("LiH: paired-electron phase estimation")
        # Display only integer x-axis ticks.
        axes.xaxis.set_major_locator(MaxNLocator(integer=True))
        axes.legend()
        figure.tight_layout()
        figure.savefig(outdir / "qpe_from_beast.png", dpi=200, bbox_inches="tight")
        if show:
            plt.show()
        plt.close(figure)
    
    
    

    Run the complete example from the repository root: Download qpe_from_beast.py

    python qpe_from_beast.py
    

    The script displays the figure and writes dist/qpe_from_beast.png. The BEAST-VQE convergence curve and four horizontal energy estimates are plotted without error bars.

Expected Result

The following figure is the expected output from the demo:

LiH BEAST-VQE convergence compared with QPE and BQPE energies from Hartree-Fock and BEAST-VQE states.

Total LiH energies in the paired-electron approximation. The green curve shows BEAST-VQE convergence; horizontal lines show the four phase estimation estimates, some of which may overlap.

Use this as a qualitative comparison, not a guarantee of identical numerical values or iteration counts. BEAST preparation improves ground-state overlap; it need not change the most probable QPE energy bin.

Verify the Result

  • Compare against a CI calculator built with .configuration_interaction().paired_electron_approximation().create() on the same problem, rather than expecting agreement with full FCI.

  • Repeat with more Trotter steps and finer QPE precision, or more BQPE iterations and candidate values, to distinguish the sources of numerical error.

  • A better input state improves ground-state overlap; it does not guarantee a lower reported energy. Basic QPE selects the most probable measured phase, and BQPE relies on its likelihood model. Excited-state weight can affect both.

  • The reported uncertainty is not a bound on all error sources. It does not include the paired-electron approximation or all Trotter, floating-point, state-preparation, and hardware errors. BQPE’s requested tolerance is not a guarantee of absolute energy accuracy.

See Also