qiskit-community / qiskit-aqua

Quantum Algorithms & Applications (**DEPRECATED** since April 2021 - see readme for more info)
https://qiskit.org/aqua
Apache License 2.0
572 stars 376 forks source link

portfolio_optimization tutorial QAOA algorithm #504

Closed Del012 closed 5 years ago

Del012 commented 5 years ago

Informations

What is the current behavior?

In the portfolio_optimization tutorial, running the very last cell (QAOA algorithm) results in a AttributeError: 'str' object has no attribute 'construct_circuit'. The only change I made was changing "seed_mapper=seed" to "seed_transpiler=seed".

Here is the resulting error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-11-1210c2490eaa> in <module>
      9 quantum_instance = QuantumInstance(backend=backend, seed=seed, seed_transpiler=seed)
     10 
---> 11 result = qaoa.run(quantum_instance)
     12 
     13 """declarative approach

~/anaconda3/envs/Qiskit09/lib/python3.7/site-packages/qiskit_aqua-0.5.0-py3.7.egg/qiskit/aqua/algorithms/quantum_algorithm.py in run(self, quantum_instance, **kwargs)
     62                 quantum_instance.set_config(**kwargs)
     63             self._quantum_instance = quantum_instance
---> 64         return self._run()
     65 
     66     @abstractmethod

~/anaconda3/envs/Qiskit09/lib/python3.7/site-packages/qiskit_aqua-0.5.0-py3.7.egg/qiskit/aqua/algorithms/adaptive/vqe/vqe.py in _run(self)
    280                                       var_form=self.var_form,
    281                                       cost_fn=self._energy_evaluation,
--> 282                                       optimizer=self.optimizer)
    283 
    284         if self._ret['num_optimizer_evals'] is not None and self._eval_count >= self._ret['num_optimizer_evals']:

~/anaconda3/envs/Qiskit09/lib/python3.7/site-packages/qiskit_aqua-0.5.0-py3.7.egg/qiskit/aqua/algorithms/adaptive/vq_algorithm.py in find_minimum(self, initial_point, var_form, cost_fn, optimizer, gradient_fn)
    116                                                                       variable_bounds=bounds,
    117                                                                       initial_point=initial_point,
--> 118                                                                       gradient_function=gradient_fn)
    119         eval_time = time.time() - start
    120         ret = {}

~/anaconda3/envs/Qiskit09/lib/python3.7/site-packages/qiskit_aqua-0.5.0-py3.7.egg/qiskit/aqua/components/optimizers/cobyla.py in optimize(self, num_vars, objective_function, gradient_function, variable_bounds, initial_point)
     89         super().optimize(num_vars, objective_function, gradient_function, variable_bounds, initial_point)
     90 
---> 91         res = minimize(objective_function, initial_point, tol=self._tol, method="COBYLA", options=self._options)
     92         return res.x, res.fun, res.nfev

~/anaconda3/envs/Qiskit09/lib/python3.7/site-packages/scipy/optimize/_minimize.py in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
    604                              **options)
    605     elif meth == 'cobyla':
--> 606         return _minimize_cobyla(fun, x0, args, constraints, **options)
    607     elif meth == 'slsqp':
    608         return _minimize_slsqp(fun, x0, args, jac, bounds,

~/anaconda3/envs/Qiskit09/lib/python3.7/site-packages/scipy/optimize/cobyla.py in _minimize_cobyla(fun, x0, args, constraints, rhobeg, tol, maxiter, disp, catol, **unknown_options)
    250     xopt, info = _cobyla.minimize(calcfc, m=m, x=np.copy(x0), rhobeg=rhobeg,
    251                                   rhoend=rhoend, iprint=iprint, maxfun=maxfun,
--> 252                                   dinfo=info)
    253 
    254     if info[3] > catol:

~/anaconda3/envs/Qiskit09/lib/python3.7/site-packages/scipy/optimize/cobyla.py in calcfc(x, con)
    240 
    241     def calcfc(x, con):
--> 242         f = fun(x, *args)
    243         i = 0
    244         for size, c in izip(cons_lengths, constraints):

~/anaconda3/envs/Qiskit09/lib/python3.7/site-packages/qiskit_aqua-0.5.0-py3.7.egg/qiskit/aqua/algorithms/adaptive/vqe/vqe.py in _energy_evaluation(self, parameters)
    314         for idx in range(len(parameter_sets)):
    315             parameter = parameter_sets[idx]
--> 316             circuit = self.construct_circuit(parameter, self._quantum_instance.backend, self._use_simulator_operator_mode)
    317             circuits.append(circuit)
    318 

~/anaconda3/envs/Qiskit09/lib/python3.7/site-packages/qiskit_aqua-0.5.0-py3.7.egg/qiskit/aqua/algorithms/adaptive/vqe/vqe.py in construct_circuit(self, parameter, backend, use_simulator_operator_mode)
    198             [QuantumCircuit]: the generated circuits with Hamiltonian.
    199         """
--> 200         input_circuit = self._var_form.construct_circuit(parameter)
    201         if backend is None:
    202             warning_msg = "Circuits used in VQE depends on the backend type, "

~/anaconda3/envs/Qiskit09/lib/python3.7/site-packages/qiskit_aqua-0.5.0-py3.7.egg/qiskit/aqua/algorithms/adaptive/qaoa/var_form.py in construct_circuit(self, angles)
     55         circuit = QuantumCircuit()
     56         if self._initial_state:
---> 57             circuit += self._initial_state.construct_circuit('circuit')
     58         if len(circuit.qregs) == 0:
     59             q = QuantumRegister(self._cost_operator.num_qubits, name='q')

AttributeError: 'str' object has no attribute 'construct_circuit'

Steps to reproduce the problem

Run the tutorial (making some minor fixes in imports as well), this is the very last cell

What is the expected behavior?

Having a functional cell

Suggested solutions

hushaohan commented 5 years ago

@Del012 could you provide the link to the notebook you used?

Del012 commented 5 years ago

https://github.com/Qiskit/qiskit-tutorials/blob/master/qiskit/aqua/finance/portfolio_optimization.ipynb

hushaohan commented 5 years ago

That branch of the tutorials repo isn't kept in sync with the latest development version of Aqua

could you try https://github.com/manoelmarques/qiskit-tutorials/tree/aqua0.5/qiskit/finance

Del012 commented 5 years ago

Yeah I tried it and that one works. My apologies, I wasn't aware that there were updated versions of the tutorials.

woodsp-ibm commented 5 years ago

The main qiskit tutorials repository works with the official release from PyPI. It can be hard to keep these up to date with the development of the code hence the choice to have them work with the official release. If you are using our latest master code then changes there may mean they not longer work, as you saw. We had the Work In Progress PR, as you can see on qiskit tutorials to update notebooks for Aqua 0.5 ie the next version that will be released. The fork where we are doing this is was what you were pointed at. When the code is released, as the next official version, then the PR will be merged and the tutorials repo updated. Hope that helps explain things a little

adityaabothra commented 4 years ago

set classical optimizer

maxiter = 100 optimizer = COBYLA(maxiter=maxiter)

set variational ansatz

var_form = RY(n, depth=1) #remove this line and run the line below it for QAOA var form

var_form = QAOAVarForm(H, 1) # use this ansatz for CVaR-QAOA

m = var_form.num_parameters

set backend

backend = Aer.get_backend('statevector_simulator')

backend = Aer.get_backend('qasm_simulator') # use this for QASM simulator

this was the code from a repository:https://github.com/stefan-woerner/cvar_quantum_optimization.git

and while running the QAOA Var Form i am getting this error(after i comment Ry and use just QAOA.var_form or QAOA.Var_Form)

error::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::>

TypeError Traceback (most recent call last)

in () 5 # set variational ansatz 6 #var_form = RY(n, depth=1) ----> 7 var_form = QAOA.var_form(H, 1) # use this ansatz for CVaR-QAOA 8 m = var_form.num_parameters 9 TypeError: 'property' object is not callable how to solve this?
woodsp-ibm commented 4 years ago

That code was done a few months ago. You could find a release of Qiskit from around that time and install that. If you are trying this on the latest code you will need to change the import since algorithms were re-organized into different categories since then

from qiskit.aqua.algorithms.adaptive.qaoa.var_form import QAOAVarForm

# var_form = QAOAVarForm(H, 1)  # use this ansatz for CVaR-QAOA

to

from qiskit.aqua.algorithms.minimum_eigen_solvers.qaoa.var_form import QAOAVarForm

# var_form = QAOAVarForm(H, 1)  # use this ansatz for CVaR-QAOA

The QAOA varform line does not need changing other than to remove the comment to use it. Your change to QAOA.var_form(H, 1) seems to try to access a setter (property), which exists on QAOA to set in a given var_form directly, hence var_form(H,1) is seen as trying to pass (call) it parameters which is why you see the error you do.

adityaabothra commented 4 years ago

The earlier code error was resolved but Now I received this new error; weighted Pauli operator -attribute error

Code:

run variational optimization for different values of alpha

alphas = [1.0, 0.25, 0.10] # confidence levels to be evaluated initial_point = np.random.rand(m) # same random initial set of parameters for all experiments objectives = {} # set of tested objective functions w.r.t. alpha for alpha in alphas: objectives[alpha] = Objective(var_form, H, offset, alpha, backend, optimal=optimal_value) optimizer.optimize(m, objectives[alpha].evaluate, initial_point=initial_point)

error is =========================>

AttributeError Traceback (most recent call last)

in () 5 for alpha in alphas: 6 objectives[alpha] = Objective(var_form, H, offset, alpha, backend, optimal=optimal_value) ----> 7 optimizer.optimize(m, objectives[alpha].evaluate, initial_point=initial_point) 5 frames /usr/local/lib/python3.6/dist-packages/qiskit/aqua/algorithms/minimum_eigen_solvers/qaoa/var_form.py in construct_circuit(self, parameters, q) 92 93 for idx in range(self._p): ---> 94 circuit = (self._cost_operator * parameters[idx]).exp_i().compose(circuit) 95 circuit = (self._mixer_operator * parameters[idx + self._p]).exp_i().compose(circuit) 96 AttributeError: 'WeightedPauliOperator' object has no attribute 'exp_i' also, sir, if I put a pull request to correct these errors if I manage to make a new version of it for the same dataset? Like updating it for the most recent qiskit and other librarires version?
woodsp-ibm commented 4 years ago

Try this

var_form = QAOAVarForm(H.to_opflow(), 1)

The operator logic was updated - this should update it to make it work.

I put a pull request to correct these errors if I manage to make a new version of it for the same dataset?

If the persons repository allows you to raise and issue or do a PR you can try and let them know. Clearly it would have worked against the code of the time when it was done. But things change over time and the operator form it now generates, the WeightedPauliOperator, is now a legacy function and it is expected to be deprecated and removed over time. Hence the fix above which converts it to the new form of operator.

adityaabothra commented 4 years ago

thanks for the prompt response, this solution worked