# How to build a QAOA Ansatz

I saw there is a qiskit package called "QAOAAnsatz" https://qiskit.org/documentation/stubs/qiskit.circuit.library.QAOAAnsatz.html. But I didn't find out any tutorial related, so I have no idea how to use it. Can anyone help me please? e.g. how to build parameter "cost_operator" etc. .

You can have a look at how the QAOAAnsatz class is used in the tests here.

Note that the link given @KAJ226 in the question comments does not use QAOAAnsatz directly but use the QAOA class that forward the given operator to the QAOAAnsatz class. So when the line

result = qaoa.compute_minimum_eigenvalue(qubit_op)


in cell 6 of KAJ226 link is executed, it will call the _check_operator_ansatz with the exact same operator. To summarise, the QAOAAnsatz class takes as parameter a cost_operator that can be constructed exactly like in cell n°5 of KAJ226 link.

The way you construct your operator depends on your particular cost function, so you will have to construct the operator by yourself, but you have a working example to start.

The QAOAAnsatz was built for the QAOA algorithm, which if you look at the qaoa code in Qiskit you will see it builds a QAOAAnsatz instance internally. Hopefully looking at that helps you use it https://github.com/Qiskit/qiskit-terra/blob/5ca967557b21828c0760763b7f0c5870e5f032d9/qiskit/algorithms/minimum_eigen_solvers/qaoa.py#L131-L132

• I tried to use it and got this result. 'QAOA' object has no attribute '_check_operator_ansatz' Jul 13 at 3:31
• That method is not intended to be called directly. I linked it to show you how the QAOAAnsatz was built in the context of QAOA so you could see what the cost operator etc was. The method is not found since it was changed from 0.17 to 0.18, and 0.18 is the version I linked to in main. (Actually 0.18 was released yesterday). For 0.17 its this github.com/Qiskit/qiskit-terra/blob/… Jul 13 at 14:09