I am carrying out a ground state estimation of a molecule via qiskit-nature workflows. As explained in qiskit documentation I define a VQE solver by means of a backend estimator that runs on a specific backend. Normally I use different backends (mainly the IBMQ backends, the local Aer backends and other remote simulators available for the scientific community), this time I would like to address the backends included in the qiskit_braket_provider module for the sake of comparison among different qubit modalities.
Once I defined the problem as in the above mentioned qiskit documentation, I carry out the usual workflow that worked in other backends.
from qiskit_braket_provider import AWSBraketProvider
provider = AWSBraketProvider()
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit_nature.second_q.mappers import JordanWignerMapper
from qiskit.algorithms.optimizers import SPSA
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit_nature.second_q.circuit.library import UCCSD, HartreeFock
from qiskit.primitives import BackendEstimator as BEstimator
my_optimizer=SPSA(maxiter=30)
mybackend = provider.get_backend("SV1")
my_est=BEstimator(backend=mybackend)
mapper=JordanWignerMapper()
ansatz = UCCSD(
problem.num_spatial_orbitals,
problem.num_particles,
mapper,
initial_state=HartreeFock(
problem.num_spatial_orbitals,
problem.num_particles,
mapper,
),
)
vqe_solver = VQE(my_est, ansatz, my_optimizer)
vqe_solver.initial_point=np.zeros(ansatz.num_parameters)
calc = GroundStateEigensolver(mapper, vqe_solver)
res = calc.solve(problem)
This time I got the error
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
File [...]/python3.9/site-packages/qiskit/algorithms/minimum_eigensolvers/vqe.py:254, in VQE._get_evaluate_energy.<locals>.evaluate_energy(parameters)
253 job = self.estimator.run(batch_size * [ansatz], batch_size * [operator], parameters)
--> 254 estimator_result = job.result()
255 except Exception as exc:
File [...]/python3.9/site-packages/qiskit/primitives/primitive_job.py:55, in PrimitiveJob.result(self)
54 self._check_submitted()
---> 55 return self._future.result()
File /opt/conda/lib/python3.9/concurrent/futures/_base.py:446, in Future.result(self, timeout)
445 elif self._state == FINISHED:
--> 446 return self.__get_result()
447 else:
File /opt/conda/lib/python3.9/concurrent/futures/_base.py:391, in Future.__get_result(self)
390 try:
--> 391 raise self._exception
392 finally:
393 # Break a reference cycle with the exception in self._exception
File /opt/conda/lib/python3.9/concurrent/futures/thread.py:58, in _WorkItem.run(self)
57 try:
---> 58 result = self.fn(*self.args, **self.kwargs)
59 except BaseException as exc:
File [...]/python3.9/site-packages/qiskit/primitives/backend_estimator.py:255, in BackendEstimator._call(self, circuits, observables, parameter_values, **run_options)
254 # Run
--> 255 result, metadata = _run_circuits(bound_circuits, self._backend, **run_options)
257 return self._postprocessing(result, accum, metadata)
File [...]/python3.9/site-packages/qiskit/primitives/backend_estimator.py:72, in _run_circuits(circuits, backend, **run_options)
71 else:
---> 72 result = [backend.run(circuits, **run_options).result()]
73 return result, metadata
File [...]/python3.9/site-packages/qiskit_braket_provider/providers/braket_backend.py:247, in AWSBraketBackend.run(self, run_input, **options)
245 raise QiskitBraketException(f"Unsupported input type: {type(run_input)}")
--> 247 braket_circuits = list(convert_qiskit_to_braket_circuits(circuits))
249 if options.pop("verbatim", False):
File ~/.qbraid/environments/qiskit_i5o7if/pyenv/lib/python3.9/site-packages/qiskit_braket_provider/providers/adapter.py:412, in convert_qiskit_to_braket_circuits(circuits)
411 for circuit in circuits:
--> 412 yield convert_qiskit_to_braket_circuit(circuit)
File [...]/python3.9/site-packages/qiskit_braket_provider/providers/adapter.py:371, in convert_qiskit_to_braket_circuit(circuit)
366 if name == "measure":
367 # TODO: change Probability result type for Sample for proper functioning # pylint:disable=fixme
368 # Getting the index from the bit mapping
369 quantum_circuit.add_result_type(
370 # pylint:disable=fixme
--> 371 result_types.Sample(
372 observable=observables.Z(),
373 target=[
374 circuit.find_bit(qiskit_gates[1][0]).index,
375 circuit.find_bit(qiskit_gates[2][0]).index,
376 ],
377 )
378 )
379 elif name == "barrier":
380 # This does not exist
File [...]/python3.9/site-packages/braket/circuits/result_types.py:547, in Sample.__init__(self, observable, target)
530 """
531 Args:
532 observable (Observable): the observable for the result type
(...)
545 >>> ResultType.Sample(observable=tensor_product, target=[0, 1])
546 """
--> 547 super().__init__(
548 ascii_symbols=[f"Sample({obs_ascii})" for obs_ascii in observable.ascii_symbols],
549 observable=observable,
550 target=target,
551 )
File [...]/python3.9/site-packages/braket/circuits/result_type.py:231, in ObservableResultType.__init__(self, ascii_symbols, observable, target)
230 elif self._observable.qubit_count != len(self._target):
--> 231 raise ValueError(
232 f"Observable's qubit count {self._observable.qubit_count} and "
233 f"the size of the target qubit set {self._target} must be equal"
234 )
235 elif self._observable.qubit_count != len(self.ascii_symbols):
ValueError: Observable's qubit count 1 and the size of the target qubit set QubitSet([Qubit(4), Qubit(3)]) must be equal
The above exception was the direct cause of the following exception:
AlgorithmError Traceback (most recent call last)
Cell In[9], line 64
62 vqe_solver.initial_point=np.zeros(ansatz.num_parameters)
63 calc = GroundStateEigensolver(mapper, vqe_solver)
---> 64 res = calc.solve(problem)
65 print(res)
66 t.write(str(res))
File [...]/python3.9/site-packages/qiskit_nature/second_q/algorithms/ground_state_solvers/ground_state_eigensolver.py:96, in GroundStateEigensolver.solve(self, problem, aux_operators)
85 """Compute Ground State properties.
86
87 Args:
(...)
93 :meth:`~.BaseProblem.interpret`.
94 """
95 main_operator, aux_ops = self.get_qubit_operators(problem, aux_operators)
---> 96 raw_mes_result = self.solver.compute_minimum_eigenvalue( # type: ignore
97 main_operator, aux_ops
98 )
100 eigenstate_result = EigenstateResult.from_result(raw_mes_result)
101 result = problem.interpret(eigenstate_result)
File [...]/python3.9/site-packages/qiskit/algorithms/minimum_eigensolvers/vqe.py:191, in VQE.compute_minimum_eigenvalue(self, operator, aux_operators)
186 else:
187 # we always want to submit as many estimations per job as possible for minimal
188 # overhead on the hardware
189 was_updated = _set_default_batchsize(self.optimizer)
--> 191 optimizer_result = self.optimizer.minimize(
192 fun=evaluate_energy, x0=initial_point, jac=evaluate_gradient, bounds=bounds
193 )
195 # reset to original value
196 if was_updated:
File [...]/python3.9/site-packages/qiskit/algorithms/optimizers/spsa.py:514, in SPSA.minimize(self, fun, x0, jac, bounds)
504 def minimize(
505 self,
506 fun: Callable[[POINT], float],
(...)
511 # ensure learning rate and perturbation are correctly set: either none or both
512 # this happens only here because for the calibration the loss function is required
513 if self.learning_rate is None and self.perturbation is None:
--> 514 get_eta, get_eps = self.calibrate(fun, x0, max_evals_grouped=self._max_evals_grouped)
515 else:
516 get_eta, get_eps = _validate_pert_and_learningrate(
517 self.perturbation, self.learning_rate
518 )
File [...]/python3.9/site-packages/qiskit/algorithms/optimizers/spsa.py:335, in SPSA.calibrate(loss, initial_point, c, stability_constant, target_magnitude, alpha, gamma, modelspace, max_evals_grouped)
332 pert = bernoulli_perturbation(dim)
333 points += [initial_point + c * pert, initial_point - c * pert]
--> 335 losses = _batch_evaluate(loss, points, max_evals_grouped)
337 avg_magnitudes = 0.0
338 for i in range(steps):
File [...]/python3.9/site-packages/qiskit/algorithms/optimizers/spsa.py:748, in _batch_evaluate(function, points, max_evals_grouped, unpack_points)
746 results += _as_list(function(*batch))
747 else:
--> 748 results += _as_list(function(batch))
750 return results
File [...]/python3.9/site-packages/qiskit/algorithms/minimum_eigensolvers/vqe.py:256, in VQE._get_evaluate_energy.<locals>.evaluate_energy(parameters)
254 estimator_result = job.result()
255 except Exception as exc:
--> 256 raise AlgorithmError("The primitive job to evaluate the energy failed!") from exc
258 values = estimator_result.values
260 if self.callback is not None:
AlgorithmError: 'The primitive job to evaluate the energy failed!'
I tried to upgrade the packages of the qiskit sdk (now I am using qiskit 0.44.0 . I tried to use different optimizers, the error message changes a little but I don't succeed in running a proper vqe workflow. I am using python 3.9. Do I need to specify any methods in the BackendEstimator call or to encapsulate the backend in a different way to make it work?
Thank you in advance for your help.