-
Notifications
You must be signed in to change notification settings - Fork 0
/
vvqe.py
582 lines (468 loc) · 25.9 KB
/
vvqe.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
# -*- coding: utf-8 -*-
#
# This is a derivative work of the code at
# https://qiskit.org/documentation/_modules/qiskit/aqua/algorithms/minimum_eigen_solvers/vqe.html#VQE
# The original copyright notice for that code is:
#
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2020.
# Changes by Eli Chertkov, Ryan Levy 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
"""The Variational Variance Quantum Eigensolver algorithm.
"""
from typing import Optional, List, Callable, Union, Dict
import logging
import warnings
from time import time
import numpy as np
import copy
from hamiltonian import square
from qiskit import ClassicalRegister, QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.circuit.library import RealAmplitudes
from qiskit.providers import BaseBackend
from qiskit.aqua import QuantumInstance, AquaError
from qiskit.aqua.algorithms import QuantumAlgorithm
from qiskit.aqua.operators import (OperatorBase, ExpectationBase, ExpectationFactory, StateFn,
CircuitStateFn, LegacyBaseOperator, ListOp, I, CircuitSampler)
from qiskit.aqua.components.optimizers import Optimizer, SLSQP
from qiskit.aqua.components.variational_forms import VariationalForm
from qiskit.aqua.utils.validation import validate_min
from qiskit.aqua.algorithms.vq_algorithm import VQAlgorithm, VQResult
from qiskit.aqua.algorithms.minimum_eigen_solvers import MinimumEigensolver, MinimumEigensolverResult
logger = logging.getLogger(__name__)
# disable check for var_forms, optimizer setter because of pylint bug
# pylint: disable=no-member
class VVQE(VQAlgorithm, MinimumEigensolver):
r"""The Variational (Variance) Quantum Eigensolver algorithm.
`VVQE is a hybrid algorithm that uses a
variational technique and interleaves quantum and classical computations in order to find
states that minimize the variance of the Hamiltonian :math:`H` of a given system.
An instance of VVQE requires defining two algorithmic sub-components:
a trial state (ansatz) from Aqua's :mod:`~qiskit.aqua.components.variational_forms`, and one
of the classical :mod:`~qiskit.aqua.components.optimizers`. The ansatz is varied, via its set
of parameters, by the optimizer, such that it works towards a state, as determined by the
parameters applied to the variational form, that will result in the minimum expectation value
being measured of the input operator (Hamiltonian).
An optional array of parameter values, via the *initial_point*, may be provided as the
starting point for the search of the minimum eigenvalue. This feature is particularly useful
such as when there are reasons to believe that the solution point is close to a particular
point. As an example, when building the dissociation profile of a molecule,
it is likely that using the previous computed optimal solution as the starting
initial point for the next interatomic distance is going to reduce the number of iterations
necessary for the variational algorithm to converge. Aqua provides an
`initial point tutorial <https://github.com/Qiskit/qiskit-tutorials-community/blob/master
/chemistry/h2_vqe_initial_point.ipynb>`__ detailing this use case.
The length of the *initial_point* list value must match the number of the parameters
expected by the variational form being used. If the *initial_point* is left at the default
of ``None``, then VVQE will look to the variational form for a preferred value, based on its
given initial state. If the variational form returns ``None``,
then a random point will be generated within the parameter bounds set, as per above.
If the variational form provides ``None`` as the lower bound, then VVQE
will default it to :math:`-2\pi`; similarly, if the variational form returns ``None``
as the upper bound, the default value will be :math:`2\pi`.
.. note::
The VVQE stores the parameters of ``var_form`` sorted by name to map the values
provided by the optimizer to the circuit. This is done to ensure reproducible results,
for example such that running the optimization twice with same random seeds yields the
same result. Also, the ``optimal_point`` of the result object can be used as initial
point of another VVQE run by passing it as ``initial_point`` to the initializer.
"""
def __init__(self,
operator: Optional[Union[OperatorBase, LegacyBaseOperator]] = None,
var_form: Optional[Union[QuantumCircuit, VariationalForm]] = None,
optimizer: Optional[Optimizer] = None,
initial_point: Optional[np.ndarray] = None,
expectation: Optional[ExpectationBase] = None,
include_custom: bool = False,
max_evals_grouped: int = 1,
aux_operators: Optional[List[Optional[Union[OperatorBase,
LegacyBaseOperator]]]] = None,
callback: Optional[Callable[[int, np.ndarray, float, float], None]] = None,
quantum_instance: Optional[Union[QuantumInstance, BaseBackend]] = None) -> None:
"""
Args:
operator: Qubit operator of the Observable
var_form: A parameterized circuit used as Ansatz for the wave function.
optimizer: A classical optimizer.
initial_point: An optional initial point (i.e. initial parameter values)
for the optimizer. If ``None`` then VVQE will look to the variational form for a
preferred point and if not will simply compute a random one.
expectation: The Expectation converter for taking the average value of the
Observable over the var_form state function. When ``None`` (the default) an
:class:`~qiskit.aqua.operators.expectations.ExpectationFactory` is used to select
an appropriate expectation based on the operator and backend. When using Aer
qasm_simulator backend, with paulis, it is however much faster to leverage custom
Aer function for the computation but, although VVQE performs much faster
with it, the outcome is ideal, with no shot noise, like using a state vector
simulator. If you are just looking for the quickest performance when choosing Aer
qasm_simulator and the lack of shot noise is not an issue then set `include_custom`
parameter here to ``True`` (defaults to ``False``).
include_custom: When `expectation` parameter here is None setting this to ``True`` will
allow the factory to include the custom Aer pauli expectation.
max_evals_grouped: Max number of evaluations performed simultaneously. Signals the
given optimizer that more than one set of parameters can be supplied so that
potentially the expectation values can be computed in parallel. Typically this is
possible when a finite difference gradient is used by the optimizer such that
multiple points to compute the gradient can be passed and if computed in parallel
improve overall execution time.
aux_operators: Optional list of auxiliary operators to be evaluated with the
eigenstate of the minimum eigenvalue main result and their expectation values
returned. For instance in chemistry these can be dipole operators, total particle
count operators so we can get values for these at the ground state.
callback: a callback that can access the intermediate data during the optimization.
Four parameter values are passed to the callback as follows during each evaluation
by the optimizer for its current set of parameters as it works towards the minimum.
These are: the evaluation count, the optimizer parameters for the
variational form, the evaluated mean and the evaluated standard deviation.`
quantum_instance: Quantum Instance or Backend
"""
if operator is not None:
operator2 = square(operator)
else:
operator2 = None
validate_min('max_evals_grouped', max_evals_grouped, 1)
if var_form is None:
var_form = RealAmplitudes()
if optimizer is None:
optimizer = SLSQP()
# set the initial point to the preferred parameters of the variational form
if initial_point is None and hasattr(var_form, 'preferred_init_points'):
initial_point = var_form.preferred_init_points
self._max_evals_grouped = max_evals_grouped
self._circuit_sampler = None
self._expectation = expectation
self._include_custom = include_custom
self._expect_op = None
self._operator = None
super().__init__(var_form=var_form,
optimizer=optimizer,
cost_fn=self._variance_evaluation,
initial_point=initial_point,
quantum_instance=quantum_instance)
self._ret = None
self._eval_time = None
self._optimizer.set_max_evals_grouped(max_evals_grouped)
self._callback = callback
if operator is not None:
self.operator = operator
#print('H = \n{}\nH^2 = \n{}'.format(self.operator, self.operator2))
self.aux_operators = aux_operators
self._eval_count = 0
logger.info(self.print_settings())
# we can get two operators to be contracted at once using ListOp
# operator is overwritten with [operator, operator^2]
self.operator = ListOp([self.operator,operator2])
@property
def operator(self) -> Optional[OperatorBase]:
""" Returns operator """
return self._operator
@property
def operator2(self) -> Optional[OperatorBase]:
""" Returns operator squared """
return self._operator2
@operator.setter
def operator(self, operator: Union[OperatorBase, LegacyBaseOperator]) -> None:
""" set operator """
if isinstance(operator, LegacyBaseOperator):
operator = operator.to_opflow()
self._operator = operator
self._expect_op = None
self._check_operator_varform()
if self._expectation is None:
self._try_set_expectation_value_from_factory()
def _try_set_expectation_value_from_factory(self):
if self.operator and self.quantum_instance:
self.expectation = ExpectationFactory.build(operator=self.operator,
backend=self.quantum_instance,
include_custom=self._include_custom)
@QuantumAlgorithm.quantum_instance.setter
def quantum_instance(self, quantum_instance: Union[QuantumInstance, BaseBackend]) -> None:
""" set quantum_instance """
super(VVQE, self.__class__).quantum_instance.__set__(self, quantum_instance)
if self._circuit_sampler is None:
self._circuit_sampler = CircuitSampler(self._quantum_instance)
else:
self._circuit_sampler.quantum_instance = self._quantum_instance
if self._expectation is None:
self._try_set_expectation_value_from_factory()
@property
def expectation(self) -> ExpectationBase:
""" The expectation value algorithm used to construct the expectation measurement from
the observable. """
return self._expectation
@expectation.setter
def expectation(self, exp: ExpectationBase) -> None:
self._expectation = exp
self._expect_op = None
@property
def aux_operators(self) -> Optional[List[Optional[OperatorBase]]]:
""" Returns aux operators """
return self._aux_operators
@aux_operators.setter
def aux_operators(self,
aux_operators: Optional[List[Optional[Union[OperatorBase,
LegacyBaseOperator]]]]) -> None:
""" Set aux operators """
# We need to handle the array entries being Optional i.e. having value None
self._aux_op_nones = None
if isinstance(aux_operators, list):
self._aux_op_nones = [op is None for op in aux_operators]
zero_op = I.tensorpower(self.operator.num_qubits) * 0.0
converted = [op.to_opflow() if op else zero_op for op in aux_operators]
# For some reason Chemistry passes aux_ops with 0 qubits and paulis sometimes.
converted = [zero_op if op == 0 else op for op in converted]
aux_operators = ListOp(converted)
elif isinstance(aux_operators, LegacyBaseOperator):
aux_operators = [aux_operators.to_opflow()]
self._aux_operators = aux_operators
def _check_operator_varform(self):
"""Check that the number of qubits of operator and variational form match."""
if self.operator is not None and self.var_form is not None:
if self.operator.num_qubits != self.var_form.num_qubits:
# try to set the number of qubits on the variational form, if possible
try:
self.var_form.num_qubits = self.operator.num_qubits
self._var_form_params = sorted(self.var_form.parameters, key=lambda p: p.name)
except AttributeError:
raise AquaError("The number of qubits of the variational form does not match "
"the operator, and the variational form does not allow setting "
"the number of qubits using `num_qubits`.")
@VQAlgorithm.optimizer.setter
def optimizer(self, optimizer: Optimizer):
""" Sets optimizer """
super(VVQE, self.__class__).optimizer.__set__(self, optimizer)
if optimizer is not None:
optimizer.set_max_evals_grouped(self._max_evals_grouped)
@property
def setting(self):
"""Prepare the setting of VVQE as a string."""
ret = "Algorithm: {}\n".format(self.__class__.__name__)
params = ""
for key, value in self.__dict__.items():
if key[0] == "_":
if "initial_point" in key and value is None:
params += "-- {}: {}\n".format(key[1:], "Random seed")
else:
params += "-- {}: {}\n".format(key[1:], value)
ret += "{}".format(params)
return ret
def print_settings(self):
"""
Preparing the setting of VVQE into a string.
Returns:
str: the formatted setting of VVQE
"""
ret = "\n"
ret += "==================== Setting of {} ============================\n".format(
self.__class__.__name__)
ret += "{}".format(self.setting)
ret += "===============================================================\n"
if hasattr(self._var_form, 'setting'):
ret += "{}".format(self._var_form.setting)
elif hasattr(self._var_form, 'print_settings'):
ret += "{}".format(self._var_form.print_settings())
elif isinstance(self._var_form, QuantumCircuit):
ret += "var_form is a custom circuit"
else:
ret += "var_form has not been set"
ret += "===============================================================\n"
ret += "{}".format(self._optimizer.setting)
ret += "===============================================================\n"
return ret
def construct_circuit(self,
parameter: Union[List[float], List[Parameter], np.ndarray]
) -> OperatorBase:
r"""
Generate the ansatz circuit and expectation value measurement, and return their
runnable composition.
Args:
parameter: Parameters for the ansatz circuit.
Returns:
The Operator equalling the measurement of the ansatz :class:`StateFn` by the
Observable's expectation :class:`StateFn`.
Raises:
AquaError: If no operator has been provided.
"""
if self.operator is None:
raise AquaError("The operator was never provided.")
# ensure operator and varform are compatible
self._check_operator_varform()
if isinstance(self.var_form, QuantumCircuit):
param_dict = dict(zip(self._var_form_params, parameter))
wave_function = self.var_form.assign_parameters(param_dict)
else:
wave_function = self.var_form.construct_circuit(parameter)
# If ExpectationValue was never created, create one now.
if not self.expectation:
self._try_set_expectation_value_from_factory()
observable_meas = self.expectation.convert(StateFn(self.operator, is_measurement=True))
ansatz_circuit_op = CircuitStateFn(wave_function)
return observable_meas.compose(ansatz_circuit_op).reduce()
def supports_aux_operators(self) -> bool:
return True
def _run(self) -> 'VVQEResult':
"""Run the algorithm to compute the minimum eigenvalue.
Returns:
The result of the VVQE algorithm as ``VVQEResult``.
Raises:
AquaError: Wrong setting of operator and backend.
"""
if self.operator is None:
raise AquaError("The operator was never provided.")
self._check_operator_varform()
self._quantum_instance.circuit_summary = True
self._eval_count = 0
vqresult = self.find_minimum(initial_point=self.initial_point,
var_form=self.var_form,
cost_fn=self._variance_evaluation,
optimizer=self.optimizer)
# TODO remove all former dictionary logic
self._ret = {}
self._ret['num_optimizer_evals'] = vqresult.optimizer_evals
self._ret['min_val'] = vqresult.optimal_value
self._ret['opt_params'] = vqresult.optimal_point
self._ret['eval_time'] = vqresult.optimizer_time
self._ret['opt_params_dict'] = vqresult.optimal_parameters
if self._ret['num_optimizer_evals'] is not None and \
self._eval_count >= self._ret['num_optimizer_evals']:
self._eval_count = self._ret['num_optimizer_evals']
self._eval_time = self._ret['eval_time']
logger.info('Optimization complete in %s seconds.\nFound opt_params %s in %s evals',
self._eval_time, self._ret['opt_params'], self._eval_count)
self._ret['eval_count'] = self._eval_count
self._ret['variance'] = self.get_optimal_cost()
self._ret['eigvals'] = np.asarray([self._ret['variance']])
self._ret['eigvecs'] = np.asarray([self.get_optimal_vector()])
result = VVQEResult()
result.combine(vqresult)
result.eigenvalue = vqresult.optimal_value + 0j
result.eigenstate = self.get_optimal_vector()
if self.aux_operators:
self._eval_aux_ops()
# TODO remove when ._ret is deprecated
result.aux_operator_eigenvalues = self._ret['aux_ops'][0]
result.cost_function_evals = self._eval_count
return result
def _eval_aux_ops(self, threshold=1e-12):
# Create new CircuitSampler to avoid breaking existing one's caches.
sampler = CircuitSampler(self.quantum_instance)
aux_op_meas = self.expectation.convert(StateFn(self.aux_operators, is_measurement=True))
aux_op_expect = aux_op_meas.compose(CircuitStateFn(self.get_optimal_circuit()))
values = np.real(sampler.convert(aux_op_expect).eval())
# Discard values below threshold
aux_op_results = (values * (np.abs(values) > threshold))
# Deal with the aux_op behavior where there can be Nones or Zero qubit Paulis in the list
self._ret['aux_ops'] = [None if is_none else [result]
for (is_none, result) in zip(self._aux_op_nones, aux_op_results)]
self._ret['aux_ops'] = np.array([self._ret['aux_ops']])
def compute_minimum_eigenvalue(
self,
operator: Optional[Union[OperatorBase, LegacyBaseOperator]] = None,
aux_operators: Optional[List[Optional[Union[OperatorBase,
LegacyBaseOperator]]]] = None
) -> MinimumEigensolverResult:
super().compute_minimum_eigenvalue(operator, aux_operators)
return self._run()
def _variance_evaluation(self, parameters: Union[List[float], np.ndarray]
) -> Union[float, List[float]]:
"""Evaluate energy at given parameters for the variational form.
This is the objective function to be passed to the optimizer that is used for evaluation.
Args:
parameters: The parameters for the variational form.
Returns:
Energy of the hamiltonian of each parameter.
Raises:
RuntimeError: If the variational form has no parameters.
"""
if not self._expect_op:
self._expect_op = self.construct_circuit(self._var_form_params)
num_parameters = self.var_form.num_parameters
if self._var_form.num_parameters == 0:
raise RuntimeError('The var_form cannot have 0 parameters.')
parameter_sets = np.reshape(parameters, (-1, num_parameters))
# Create dict associating each parameter with the lists of parameterization values for it
param_bindings = dict(zip(self._var_form_params, parameter_sets.transpose().tolist()))
start_time = time()
sampled_expect_op = self._circuit_sampler.convert(self._expect_op, params=param_bindings)
# TODO: assumes only one operator is being passed to VVQE
E,Var = np.real(sampled_expect_op.eval())[0]
means,means2 = [E], [Var]
if self._callback is not None:
variance = np.real(self._expectation.compute_variance(sampled_expect_op))
estimator_error = np.sqrt(variance / self.quantum_instance.run_config.shots)
for i, param_set in enumerate(parameter_sets):
self._eval_count += 1
self._callback(self._eval_count, param_set, means[i], estimator_error[i])
else:
self._eval_count += len(means)
mean_results = [means2[i] - means[i]**2.0 for i in range(len(means))]
#print('means2 = {}\nmeans = {}\nmean_results = {}'.format(means2, means, mean_results))
assert means[0]!=means2[0] or means2[0]!=0
end_time = time()
logger.info('Variance evaluation returned %s - %.5f (ms), eval count: %s',
mean_results, (end_time - start_time) * 1000, self._eval_count)
return mean_results if len(mean_results) > 1 else mean_results[0]
def get_optimal_cost(self) -> float:
"""Get the minimal cost or energy found by the VVQE."""
if 'opt_params' not in self._ret:
raise AquaError("Cannot return optimal cost before running the "
"algorithm to find optimal params.")
return self._ret['min_val']
def get_optimal_circuit(self) -> QuantumCircuit:
"""Get the circuit with the optimal parameters."""
if 'opt_params' not in self._ret:
raise AquaError("Cannot find optimal circuit before running the "
"algorithm to find optimal params.")
if isinstance(self.var_form, VariationalForm):
return self._var_form.construct_circuit(self._ret['opt_params'])
return self.var_form.assign_parameters(self._ret['opt_params_dict'])
def get_optimal_vector(self) -> Union[List[float], Dict[str, int]]:
"""Get the simulation outcome of the optimal circuit. """
# pylint: disable=import-outside-toplevel
from qiskit.aqua.utils.run_circuits import find_regs_by_name
if 'opt_params' not in self._ret:
raise AquaError("Cannot find optimal vector before running the "
"algorithm to find optimal params.")
qc = self.get_optimal_circuit()
if self._quantum_instance.is_statevector:
ret = self._quantum_instance.execute(qc)
self._ret['min_vector'] = ret.get_statevector(qc)
else:
c = ClassicalRegister(qc.width(), name='c')
q = find_regs_by_name(qc, 'q')
qc.add_register(c)
qc.barrier(q)
qc.measure(q, c)
ret = self._quantum_instance.execute(qc)
self._ret['min_vector'] = ret.get_counts(qc)
return self._ret['min_vector']
@property
def optimal_params(self) -> List[float]:
"""The optimal parameters for the variational form."""
if 'opt_params' not in self._ret:
raise AquaError("Cannot find optimal params before running the algorithm.")
return self._ret['opt_params']
class VVQEResult(VQResult, MinimumEigensolverResult):
""" VVQE Result."""
@property
def cost_function_evals(self) -> int:
""" Returns number of cost optimizer evaluations """
return self.get('cost_function_evals')
@cost_function_evals.setter
def cost_function_evals(self, value: int) -> None:
""" Sets number of cost function evaluations """
self.data['cost_function_evals'] = value
def __getitem__(self, key: object) -> object:
if key == 'eval_count':
warnings.warn('eval_count deprecated, use cost_function_evals property.',
DeprecationWarning)
return super().__getitem__('cost_function_evals')
try:
return VQResult.__getitem__(self, key)
except KeyError:
return MinimumEigensolverResult.__getitem__(self, key)