Performing a Standard FAST-VQE Convergence Study

In this example, we plot the convergence of a FAST Variational Quantum Eigensolver (FAST-VQE) calculation.

Full Script

The script below shows the full script, which is then explained section by section.

  1"""Demonstrate FAST-VQE convergence plotting on LiH molecule."""
  2# ruff: noqa # ruff: ignore[noqa-comments]
  3
  4from pathlib import Path
  5
  6import matplotlib.pyplot as plt
  7import numpy as np
  8
  9import qrunch as qc
 10
 11
 12def plot_energies(
 13    fast_energies: list[float],
 14    reference_energy: float,
 15    *,
 16    outdir: Path = Path("dist"),
 17    show: bool = False,
 18) -> None:
 19    """
 20    Plot VQE energy convergence and log-scale error vs reference energy.
 21
 22    Args:
 23        fast_energies: Sequence of total energies per VQE iteration.
 24        reference_energy: Reference total energy (e.g., FCI) to compare against.
 25        outdir: Output directory where plots are written. Defaults to "dist".
 26        show: Whether to display the figures interactively after saving.
 27    """
 28    # Convert to a NumPy array for safe numeric operations and validation.
 29    energies = np.asarray(list(fast_energies), dtype=float)
 30
 31    # Basic validation to help catch silent failures early.
 32    if energies.size == 0:
 33        msg = "fast_energies must contain at least one value."
 34        raise ValueError(msg)
 35    if not np.isfinite(energies).all():
 36        msg = "fast_energies contains non-finite values."
 37        raise ValueError(msg)
 38    if not np.isfinite(reference_energy):
 39        msg = "reference_energy must be finite."
 40        raise ValueError(msg)
 41
 42    # Prepare x-axis as 1-based iteration indices for readability.
 43    iterations = np.arange(1, energies.size + 1, dtype=int)
 44
 45    # Ensure output directory exists.
 46    outdir.mkdir(parents=True, exist_ok=True)
 47
 48    # -----------------------------
 49    # Figure 1: Energies vs Iteration
 50    # -----------------------------
 51    fig1 = plt.figure()
 52    plt.plot(iterations, energies, "-*", color="darkgreen", label="FAST-VQE")  # points to visualize steps
 53    plt.axhline(reference_energy, linestyle="--", color="black", label="Reference")
 54    plt.xlabel("Iteration number")
 55    plt.ylabel("Total energy [Hartree]")
 56    plt.title("FAST-VQE convergence")
 57    plt.legend()
 58    plt.tight_layout()
 59
 60    convergence_plot = outdir / "vqe_convergence.png"
 61    fig1.savefig(convergence_plot, dpi=200, bbox_inches="tight")
 62
 63    # -----------------------------
 64    # Figure 2: |Energy - Reference| (log scale)
 65    # -----------------------------
 66    # Use absolute error; add a tiny epsilon to avoid log(0) if we hit the reference exactly.
 67    eps = np.finfo(float).eps
 68    abs_error = np.abs(energies - reference_energy) + eps
 69
 70    fig2 = plt.figure()
 71    plt.semilogy(iterations, abs_error, "-*", color="darkgreen", label="|E - E_ref|")
 72    plt.xlabel("Iteration number")
 73    plt.ylabel("Absolute error [Hartree]")
 74    plt.title("FAST-VQE error vs reference")
 75    plt.legend()
 76    plt.tight_layout()
 77
 78    error_convergence_plot = outdir / "vqe_error_semilogy.png"
 79    fig2.savefig(error_convergence_plot, dpi=200, bbox_inches="tight")
 80
 81    if show:
 82        plt.show()
 83    else:
 84        # Close figures to free memory when running in batch contexts.
 85        plt.close(fig1)
 86        plt.close(fig2)
 87
 88
 89
 90
 91def main() -> list[float]:
 92    """Run FAST-VQE on LiH as the first script."""
 93    path_to_molecule_xyz_file = Path().absolute() / "qrunch" / "tests" / "demo_scripts" / "lih.xyz"
 94    # Build Lithium Hydride (LiH) molecular configuration from xyz file.
 95    molecular_configuration = qc.build_molecular_configuration(
 96        molecule=Path(path_to_molecule_xyz_file),
 97        basis_set="sto3g",
 98        spin_difference=0,
 99        charge=0,
100        units="angstrom",
101    )
102
103    # Build the ground state problem.
104    problem_builder = qc.problem_builder_creator().ground_state().standard().create()
105    ground_state_problem = problem_builder.build_unrestricted(molecular_configuration)
106
107    adaptive_vqe_options = qc.options.IterativeVqeOptions(
108        max_iterations=100,  # Increase the maximum number of iterations
109        gates_per_iteration=1,  # Add one gate per iteration (Recommended)
110        force_all_iterations=True,  # Force all iterations to run, independent of convergence.
111    )
112
113    # Build the user-configured VQE calculator instance
114    fast_vqe_calculator = (
115        qc
116        .calculator_creator()  # Start creating a calculator
117        .vqe()  # Narrow: pick Variational quantum eigensolver (VQE)
118        .iterative()  # Narrow: pick the iterative VQE
119        .standard()  # Narrow: pick the standard iterative VQE (FAST-VQE)
120        .with_options(adaptive_vqe_options)  # Use the user-defined iterative VQE options
121        .choose_minimizer()  # Start sub-choice: Choose the gate parameter minimizer
122        .quick_default()  # Perform the sub-choice selection - Here we pick the greedy and quick minimizer
123        .create()  # Create the calculator instance
124    )
125
126    result = fast_vqe_calculator.calculate(ground_state_problem)
127
128    # We can get a nice timings report.
129    print(qc.get_execution_times_report())
130
131    # Extract FAST-VQE energies for plotting
132    fast_energies = result.total_energy_per_macro_iteration_with_initial_energy_and_final_energy.values
133
134    # Build a Full Configuration Interaction (FCI) calculator
135    full_configuration_interaction_calculator = (
136        qc
137        .calculator_creator()  # Start creating a calculator
138        .configuration_interaction()  # Narrow: pick Configuration Interaction (CI)
139        .standard()  # Narrow: pick standard CI (not paired version)
140        .create()  # Create the calculator instance
141    )
142
143    # Calculate the FCI result for reference energy
144    fci_result = full_configuration_interaction_calculator.calculate(ground_state_problem)
145
146    # Plot the convergence and error relative to FCI reference.
147    plot_energies(fast_energies, reference_energy=fci_result.total_energy.value, show=True)
148
149    return fast_energies
150
151
152if __name__ == "__main__":
153    main()

The script requires an XYZ file specifying the molecule: Download lih.xyz

Explanation

  1. Import Kvantify Qrunch

    from pathlib import Path
    
    import matplotlib.pyplot as plt
    import numpy as np
    
    import qrunch as qc
    

    This code snippet loads the python packages we need. The public and stable Kvantify Qrunch API is loaded as import qrunch as qc. This is the only import you need for most tasks, and the only one that is guaranteed to be supported across versions. In addition, we use matplotlib, numpy, and Path (from pathlib).

  2. The plotting method

    def plot_energies(
        fast_energies: list[float],
        reference_energy: float,
        *,
        outdir: Path = Path("dist"),
        show: bool = False,
    ) -> None:
        """
        Plot VQE energy convergence and log-scale error vs reference energy.
    
        Args:
            fast_energies: Sequence of total energies per VQE iteration.
            reference_energy: Reference total energy (e.g., FCI) to compare against.
            outdir: Output directory where plots are written. Defaults to "dist".
            show: Whether to display the figures interactively after saving.
        """
        # Convert to a NumPy array for safe numeric operations and validation.
        energies = np.asarray(list(fast_energies), dtype=float)
    
        # Basic validation to help catch silent failures early.
        if energies.size == 0:
            msg = "fast_energies must contain at least one value."
            raise ValueError(msg)
        if not np.isfinite(energies).all():
            msg = "fast_energies contains non-finite values."
            raise ValueError(msg)
        if not np.isfinite(reference_energy):
            msg = "reference_energy must be finite."
            raise ValueError(msg)
    
        # Prepare x-axis as 1-based iteration indices for readability.
        iterations = np.arange(1, energies.size + 1, dtype=int)
    
        # Ensure output directory exists.
        outdir.mkdir(parents=True, exist_ok=True)
    
        # -----------------------------
        # Figure 1: Energies vs Iteration
        # -----------------------------
        fig1 = plt.figure()
        plt.plot(iterations, energies, "-*", color="darkgreen", label="FAST-VQE")  # points to visualize steps
        plt.axhline(reference_energy, linestyle="--", color="black", label="Reference")
        plt.xlabel("Iteration number")
        plt.ylabel("Total energy [Hartree]")
        plt.title("FAST-VQE convergence")
        plt.legend()
        plt.tight_layout()
    
        convergence_plot = outdir / "vqe_convergence.png"
        fig1.savefig(convergence_plot, dpi=200, bbox_inches="tight")
    
        # -----------------------------
        # Figure 2: |Energy - Reference| (log scale)
        # -----------------------------
        # Use absolute error; add a tiny epsilon to avoid log(0) if we hit the reference exactly.
        eps = np.finfo(float).eps
        abs_error = np.abs(energies - reference_energy) + eps
    
        fig2 = plt.figure()
        plt.semilogy(iterations, abs_error, "-*", color="darkgreen", label="|E - E_ref|")
        plt.xlabel("Iteration number")
        plt.ylabel("Absolute error [Hartree]")
        plt.title("FAST-VQE error vs reference")
        plt.legend()
        plt.tight_layout()
    
        error_convergence_plot = outdir / "vqe_error_semilogy.png"
        fig2.savefig(error_convergence_plot, dpi=200, bbox_inches="tight")
    
        if show:
            plt.show()
        else:
            # Close figures to free memory when running in batch contexts.
            plt.close(fig1)
            plt.close(fig2)
    
    
    

    This code plot the convergence of the VQE energy and the error relative to the reference full configuration interaction (FCI) energy.

    The code generates two PNG files under dist/:

    • vqe_convergence.png

    • vqe_error_semilogy.png

  3. Molecule from XYZ file

        # Build Lithium Hydride (LiH) molecular configuration from xyz file.
        molecular_configuration = qc.build_molecular_configuration(
            molecule=Path(path_to_molecule_xyz_file),
            basis_set="sto3g",
            spin_difference=0,
            charge=0,
            units="angstrom",
        )
    

    We load LiH from an XYZ file, set the STO-3G basis, neutral charge, zero spin difference, and specify that the unit is ångström.

  4. Build the ground-state problem

        # Build the ground state problem.
        problem_builder = qc.problem_builder_creator().ground_state().standard().create()
        ground_state_problem = problem_builder.build_unrestricted(molecular_configuration)
    

    We create a standard ground-state problem using the problem builder. Here we use the unrestricted variant for LiH (spin up and spin down electrons are allowed to occupy different spatial orbitals).

  5. Configure and create the FAST-VQE calculator

        adaptive_vqe_options = qc.options.IterativeVqeOptions(
            max_iterations=100,  # Increase the maximum number of iterations
            gates_per_iteration=1,  # Add one gate per iteration (Recommended)
            force_all_iterations=True,  # Force all iterations to run, independent of convergence.
        )
    
        # Build the user-configured VQE calculator instance
        fast_vqe_calculator = (
            qc
            .calculator_creator()  # Start creating a calculator
            .vqe()  # Narrow: pick Variational quantum eigensolver (VQE)
            .iterative()  # Narrow: pick the iterative VQE
            .standard()  # Narrow: pick the standard iterative VQE (FAST-VQE)
            .with_options(adaptive_vqe_options)  # Use the user-defined iterative VQE options
            .choose_minimizer()  # Start sub-choice: Choose the gate parameter minimizer
            .quick_default()  # Perform the sub-choice selection - Here we pick the greedy and quick minimizer
            .create()  # Create the calculator instance
        )
    

    We specify that we want a maximum of 100 iterations, one gate per iteration, and we force all iterations to be executed, independent of any stopping criteria.

    We then build the adaptive VQE calculator with the specified options, where we choose a quick default gate parameter optimization method, optimizing only the parameter of the last gate in every iteration.

  6. Run and extract energies

        result = fast_vqe_calculator.calculate(ground_state_problem)
    

    We run the VQE calculation, and here we also print a timing report for profiling:

        # We can get a nice timings report.
        print(qc.get_execution_times_report())
    
  7. Compute a high-accuracy FCI reference

        # Build a Full Configuration Interaction (FCI) calculator
        full_configuration_interaction_calculator = (
            qc
            .calculator_creator()  # Start creating a calculator
            .configuration_interaction()  # Narrow: pick Configuration Interaction (CI)
            .standard()  # Narrow: pick standard CI (not paired version)
            .create()  # Create the calculator instance
        )
    
        # Calculate the FCI result for reference energy
        fci_result = full_configuration_interaction_calculator.calculate(ground_state_problem)
    

    We build a FCI calculator and calculate the FCI energy for the same problem.

  8. Make the plots

        # Plot the convergence and error relative to FCI reference.
        plot_energies(fast_energies, reference_energy=fci_result.total_energy.value, show=True)
    

    We plot the VQE convergence and the error relative to the FCI reference, by calling the plotting function defined above.

Running the Example

After saving the script as run_vqe_convergence.py, you can run it directly from the command line:

$ python run_vqe_convergence.py

You should see 2 plots:

FAST-VQE convergence plot FAST-VQE convergence plot, as the error relative to FCI