Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for following VQE minimization in VQESolver #342

Merged
merged 3 commits into from
Sep 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions tangelo/algorithms/variational/tests/test_vqe_solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -655,6 +655,28 @@ def test_rotosolve_unsupported(self):
with self.assertRaises(ValueError):
VQESolver(options).build()

def test_save_energies(self):
"""Performing a deterministic number of optimization steps (calls to
energy_estimation). The energies attributes should have n elements,
where n is the number of optimization steps.
"""

vqe_options = {"molecule": mol_H2_sto3g,
"ansatz": Circuit([Gate("X", 0), Gate("X", 1)], n_qubits=4),
"qubit_mapping": "JW",
"up_then_down": False,
"save_energies": True,
"verbose": False}
vqe_solver = VQESolver(vqe_options)
vqe_solver.build()

n_steps = 3
# Deterministic number of calls to energy_estimation.
for _ in range(n_steps):
vqe_solver.energy_estimation(var_params=[])

self.assertEqual(len(vqe_solver.energies), n_steps)


if __name__ == "__main__":
unittest.main()
10 changes: 9 additions & 1 deletion tangelo/algorithms/variational/vqe_solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
electronic structure calculations.
"""

from contextlib import nullcontext
import warnings
import itertools
from typing import Optional, Union, List
Expand Down Expand Up @@ -91,6 +92,7 @@ class VQESolver:
ref_state (array or Circuit): The reference configuration to use. Replaces HF state
QMF, QCC, ILC require ref_state to be an array. UCC1, UCC3, VSQS can not use a
different ref_state than HF by construction.
save_energies (bool): Flag for saving energy estimation values.
"""

def __init__(self, opt_dict):
Expand All @@ -114,6 +116,7 @@ def __init__(self, opt_dict):
self.verbose: bool = copt_dict.pop("verbose", False)
self.projective_circuit: Circuit = copt_dict.pop("projective_circuit", None)
self.ref_state: Optional[Union[list, Circuit]] = copt_dict.pop("ref_state", None)
self.save_energies: bool = copt_dict.pop("save_energies", False)
ValentinS4t1qbit marked this conversation as resolved.
Show resolved Hide resolved

if len(copt_dict) > 0:
raise KeyError(f"The following keywords are not supported in {self.__class__.__name__}: \n {copt_dict.keys()}")
Expand Down Expand Up @@ -165,6 +168,8 @@ def __init__(self, opt_dict):
self.optimal_var_params = None
self.builtin_ansatze = set(BuiltInAnsatze)

self.energies = list()

def build(self):
"""Build the underlying objects required to run the VQE algorithm
afterwards.
Expand Down Expand Up @@ -311,6 +316,9 @@ def energy_estimation(self, var_params):
if self.verbose:
print(f"\tEnergy = {energy:.7f} ")

if self.save_energies:
self.energies += [energy]

return energy

def operator_expectation(self, operator, var_params=None, n_active_mos=None, n_active_electrons=None, n_active_sos=None, spin=None, ref_state=Circuit()):
Expand Down Expand Up @@ -668,7 +676,7 @@ def _default_optimizer(self, func, var_params):

from scipy.optimize import minimize

with HiddenPrints():
with HiddenPrints() if not self.verbose else nullcontext():
result = minimize(func, var_params, method="SLSQP",
options={"disp": True, "maxiter": 2000, "eps": 1e-5, "ftol": 1e-5})

Expand Down