Skip to content

Commit

Permalink
Add QAOAAnsatz.num_qubits to improve performance (#7203)
Browse files Browse the repository at this point in the history
* Add QAOAAnsatz.num_qubits

* returns 0 if no cost operator is given
  • Loading branch information
t-imamichi authored Nov 1, 2021
1 parent 8267412 commit d352ca3
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
6 changes: 6 additions & 0 deletions qiskit/circuit/library/n_local/qaoa_ansatz.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,12 @@ def mixer_operator(self, mixer_operator) -> None:
self._mixer = mixer_operator
self._invalidate()

@property
def num_qubits(self) -> int:
if self._cost_operator is None:
return 0
return self._cost_operator.num_qubits

def _build(self):
if self._data is not None:
return
Expand Down
19 changes: 18 additions & 1 deletion test/python/circuit/library/test_qaoa_ansatz.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,16 @@
"""Test QAOA ansatz from the library."""

import numpy as np
from ddt import ddt, data

from qiskit.circuit import QuantumCircuit, Parameter
from qiskit.circuit.library.n_local.qaoa_ansatz import QAOAAnsatz
from qiskit.circuit.library import HGate, RXGate, YGate, RYGate, RZGate
from qiskit.circuit.library.n_local.qaoa_ansatz import QAOAAnsatz
from qiskit.opflow import I, Y, Z
from qiskit.test import QiskitTestCase


@ddt
class TestQAOAAnsatz(QiskitTestCase):
"""Test QAOAAnsatz."""

Expand Down Expand Up @@ -141,3 +144,17 @@ def test_circuit_mixer(self):
reps = 4
circuit = QAOAAnsatz(cost_operator=Z ^ Z, mixer_operator=mixer, reps=reps)
self.assertEqual(circuit.num_parameters, 3 * reps)

def test_empty_op(self):
"""Test construction without cost operator"""
circuit = QAOAAnsatz(reps=1)
self.assertEqual(circuit.num_qubits, 0)
with self.assertRaises(ValueError):
circuit.decompose()

@data(1, 2, 3, 4)
def test_num_qubits(self, num_qubits):
"""Test num_qubits with {num_qubits} qubits"""

circuit = QAOAAnsatz(cost_operator=I ^ num_qubits, reps=5)
self.assertEqual(circuit.num_qubits, num_qubits)

0 comments on commit d352ca3

Please sign in to comment.