1
$\begingroup$

I would like to know if there is a easy way or native solution to retrieve the number of qubits that is required when using QAOA from qiskit_algorithms package to solve an optimization problem.

I understand that QuantumCircuit.num_qubits can do the work if I have a circuit objects. However, I am using QAOA algorithms from qiskit_algorithms and I couldn't have a circuit object to call even though I think the package construct the circuit under the hood for me.

The only way that I could know the required number of qubit for target problem right now is deliberately setting up a small number of qubit for the local simulator, and then I will get the error message qiskit.transpiler.exceptions.CircuitTooWideForTarget: 'Number of qubits (5) in QAOA is greater than maximum (1) in the coupling_map', and I know the problem require 5 qubits to solve, but I would like to know the number of qubit required before running it.

The code is shown below:

from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_algorithms import QAOA
from qiskit_algorithms.optimizers import COBYLA
from qiskit_optimization.translators import from_docplex_mp
from qiskit.providers.fake_provider import GenericBackendV2

mod = from_docplex_mp(mdl) #the optimization model
backend = GenericBackendV2(num_qubits=1) #fake backend 
sampler = BackendSampler(backend=backend)
qaoa_mes = QAOA(sampler=sampler,reps=1,optimizer=COBYLA(), initial_point=[0.0, 0.0])
qaoa = MinimumEigenOptimizer(qaoa_mes)
exact_result = qaoa.solve(mod) #solve the problem 
$\endgroup$

2 Answers 2

1
$\begingroup$

Qiskit algorithms class QAOA inherits from SamplingVQE. That means, you can access its parameterized QuantumCircuit using the ansatz attribute.

So, you can easily get the number of qubits as follows:

num_qubits = qaoa_mes.ansatz.num_qubits
$\endgroup$
1
  • $\begingroup$ This approach will return Attribute error: 'NoneType' object has no attribute 'num_qubits' because the circuit/model is passed into qaoa_mes in the last line when qaoa.solve(mod) is executed. However, inspired by your approach, I turned the mod into Ising_Hamilton object beforehand and get the qubit number required successfully. So still many thanks! $\endgroup$
    – Chuck
    Commented Jun 25 at 10:08
0
$\begingroup$

After experiments, this code works for me, posting here in case anyone needs it.

mod=from_docplex_mp(mdl)
operator,offset=mod.to_ising()
qubit_needed=operator.num_qubits
print('Needs qubit',qubit_needed)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.