Performing a Standard BEAST-VQE Convergence Study
In this example, we plot the convergence of a BEAST Variational Quantum Eigensolver (BEAST-VQE) calculation.
Full Script
The script below shows the full script, which are then explained section by section.
1"""Demonstrate BEAST-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 beast_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 beast_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 """
29 # Convert to a NumPy array for safe numeric operations and validation.
30 energies = np.asarray(list(beast_energies), dtype=float)
31
32 # Basic validation to help catch silent failures early.
33 if energies.size == 0:
34 msg = "beast_energies must contain at least one value."
35 raise ValueError(msg)
36 if not np.isfinite(energies).all():
37 msg = "beast_energies contains non-finite values."
38 raise ValueError(msg)
39 if not np.isfinite(reference_energy):
40 msg = "reference_energy must be finite."
41 raise ValueError(msg)
42
43 # Prepare x-axis as 1-based iteration indices for readability.
44 iterations = np.arange(1, energies.size + 1, dtype=int)
45
46 # Ensure output directory exists.
47 outdir.mkdir(parents=True, exist_ok=True)
48
49 # -----------------------------
50 # Figure 1: Energies vs Iteration
51 # -----------------------------
52 fig1 = plt.figure()
53 plt.plot(iterations, energies, "-*", color="darkgreen", label="BEAST-VQE") # points to visualize steps
54 plt.axhline(reference_energy, linestyle="--", color="black", label="Reference")
55 plt.xlabel("Iteration number")
56 plt.ylabel("Total energy [Hartree]")
57 plt.title("BEAST-VQE convergence")
58 plt.legend()
59 plt.tight_layout()
60
61 convergence_plot = outdir / "vqe_convergence.png"
62 fig1.savefig(convergence_plot, dpi=200, bbox_inches="tight")
63
64 # -----------------------------
65 # Figure 2: |Energy - Reference| (log scale)
66 # -----------------------------
67 # Use absolute error; add a tiny epsilon to avoid log(0) if we hit the reference exactly.
68 eps = np.finfo(float).eps
69 abs_error = np.abs(energies - reference_energy) + eps
70
71 fig2 = plt.figure()
72 plt.semilogy(iterations, abs_error, "-*", color="darkgreen", label="|E - E_ref|")
73 plt.xlabel("Iteration number")
74 plt.ylabel("Absolute error [Hartree]")
75 plt.title("BEAST-VQE error vs reference")
76 plt.legend()
77 plt.tight_layout()
78
79 error_convergence_plot = outdir / "vqe_error_semilogy.png"
80 fig2.savefig(error_convergence_plot, dpi=200, bbox_inches="tight")
81
82 if show:
83 plt.show()
84 else:
85 # Close figures to free memory when running in batch contexts.
86 plt.close(fig1)
87 plt.close(fig2)
88
89
90
91
92def main() -> list[float]:
93 """Run BEAST-VQE on LiH as the first script."""
94 path_to_molecule_xyz_file = Path().absolute() / "qrunch" / "tests" / "demo_scripts" / "lih.xyz"
95 # Build Lithium Hydride (LiH) molecular configuration from xyz file.
96 molecular_configuration = qc.build_molecular_configuration(
97 molecule=Path(path_to_molecule_xyz_file),
98 basis_set="sto3g",
99 spin_difference=0,
100 charge=0,
101 units="angstrom",
102 )
103
104 # Build the ground state problem.
105 problem_builder = qc.problem_builder_creator().ground_state().standard().create()
106 ground_state_problem = problem_builder.build_restricted(molecular_configuration)
107
108 adaptive_vqe_options = qc.options.IterativeVqeOptions(
109 max_iterations=100, # Increase the maximum number of iterations
110 force_all_iterations=True, # Force all iterations to run, independent of convergence.
111 )
112
113 # Build the BEAST-VQE calculator using the user-configured VQE instance
114 beast_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 .beast() # Narrow: pick the iterative 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 = beast_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 BEAST-VQE energies for plotting
132 beast_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 .paired_electron_approximation() # Narrow: pick paired CI
140 .create() # Create the calculator instance
141 )
142
143 # Calculate the paired-FCI result for reference energy
144 pfci_result = full_configuration_interaction_calculator.calculate(ground_state_problem)
145
146 # Plot the convergence and error relative to FCI reference.
147 plot_energies(beast_energies, reference_energy=pfci_result.total_energy.value, show=True)
148
149 return beast_energies
150
151
152if __name__ == "__main__":
153 main()
The script requires an XYZ file specifying the molecule: Download lih.xyz
Explanation
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 minor versions. In addition, we usematplotlib,numpy, andPath(frompathlib).The plotting method
def plot_energies( beast_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: beast_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(beast_energies), dtype=float) # Basic validation to help catch silent failures early. if energies.size == 0: msg = "beast_energies must contain at least one value." raise ValueError(msg) if not np.isfinite(energies).all(): msg = "beast_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="BEAST-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("BEAST-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("BEAST-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 plots the convergence of the VQE energy and the error relative to the reference. The paired Full Configuration Interaction (pFCI) energy.
The code generates two PNG files under
dist/:vqe_convergence.pngvqe_error_semilogy.png
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 the unit as ångström.
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_restricted(molecular_configuration)
We create a standard ground-state problem using the problem builder. Here we use the restricted variant for LiH This is required for the BEAST-VQE algorithm, and the Paired-FCI reference calculation.
Configure and create the BEAST-VQE calculator
adaptive_vqe_options = qc.options.IterativeVqeOptions( max_iterations=100, # Increase the maximum number of iterations force_all_iterations=True, # Force all iterations to run, independent of convergence. ) # Build the BEAST-VQE calculator using the user-configured VQE instance beast_vqe_calculator = ( qc .calculator_creator() # Start creating a calculator .vqe() # Narrow: pick Variational quantum eigensolver (VQE) .iterative() # Narrow: pick the iterative VQE .beast() # Narrow: pick the iterative 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 with the specified options and wrap it in the BEAST-VQE calculator, where we choose a quick default gate parameter optimization method, optimizing only the parameter of the last gate in every iteration.
Run and extract energies
result = beast_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())
Compute a high-accuracy paired-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) .paired_electron_approximation() # Narrow: pick paired CI .create() # Create the calculator instance ) # Calculate the paired-FCI result for reference energy pfci_result = full_configuration_interaction_calculator.calculate(ground_state_problem)
We build a paired-FCI calculator and calculate the paired-FCI energy for the same problem to use as a reference.
Make the plots
# Plot the convergence and error relative to FCI reference. plot_energies(beast_energies, reference_energy=pfci_result.total_energy.value, show=True)
We plot the VQE convergence and the error relative to the paired-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: