Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

disallow specifying controlled gate with zero controls. #4584

Merged
merged 7 commits into from
Jun 25, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 0 additions & 6 deletions qiskit/circuit/add_control.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,12 +102,6 @@ def control(operation: Union[Gate, ControlledGate],
# pylint: disable=unused-import
import qiskit.circuit.library.standard_gates.multi_control_rotation_gates

# check args
if num_ctrl_qubits == 0:
return operation
elif num_ctrl_qubits < 0:
raise CircuitError('number of control qubits must be positive integer')

q_control = QuantumRegister(num_ctrl_qubits, name='control')
q_target = QuantumRegister(operation.num_qubits, name='target')
q_ancillae = None # TODO: add
Expand Down
31 changes: 27 additions & 4 deletions qiskit/circuit/controlledgate.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,10 +85,8 @@ def __init__(self, name: str, num_qubits: int, params: List,
qc2.draw()
"""
super().__init__(name, num_qubits, params, label=label)
if num_ctrl_qubits < num_qubits:
self.num_ctrl_qubits = num_ctrl_qubits
else:
raise CircuitError('number of control qubits must be less than the number of qubits')
self._num_ctrl_qubits = 1
self.num_ctrl_qubits = num_ctrl_qubits
self.base_gate = None
if definition:
self.definition = definition
Expand Down Expand Up @@ -132,6 +130,31 @@ def definition(self, excited_def: List):
"""Set controlled gate definition with closed controls."""
super(Gate, self.__class__).definition.fset(self, excited_def)

@property
def num_ctrl_qubits(self):
"""Get number of control qubits.

Returns:
int: The number of control qubits for the gate.
"""
return self._num_ctrl_qubits

@num_ctrl_qubits.setter
def num_ctrl_qubits(self, num_ctrl_qubits):
"""Set the number of control qubits.

Args:
num_ctrl_qubits (int): The number of control qubits in [1, num_qubits-1].

Raises:
CircuitError: num_ctrl_qubits is not an integer in [1, num_qubits - 1].
"""
if (num_ctrl_qubits == int(num_ctrl_qubits) and
1 <= num_ctrl_qubits < self.num_qubits):
self._num_ctrl_qubits = num_ctrl_qubits
else:
raise CircuitError('The number of control qubits must be in [1, num_qubits-1]')

@property
def ctrl_state(self) -> int:
"""Return the control state of the gate as a decimal integer."""
Expand Down
4 changes: 1 addition & 3 deletions qiskit/circuit/library/standard_gates/x.py
Original file line number Diff line number Diff line change
Expand Up @@ -739,7 +739,7 @@ class MCXGate(ControlledGate):
def __new__(cls, num_ctrl_qubits=None, label=None, ctrl_state=None):
"""Create a new MCX instance.

Depending on the number of controls, this creates an explicit X, CX, CCX, C3X or C4X
Depending on the number of controls, this creates an explicit CX, CCX, C3X or C4X
instance or a generic MCX gate.
"""
# these gates will always be implemented for all modes of the MCX if the number of control
Expand All @@ -748,8 +748,6 @@ def __new__(cls, num_ctrl_qubits=None, label=None, ctrl_state=None):
1: CXGate,
2: CCXGate
}
if num_ctrl_qubits == 0:
return XGate(label=label)
if num_ctrl_qubits in explicit.keys():
gate_class = explicit[num_ctrl_qubits]
gate = gate_class.__new__(gate_class, label=label, ctrl_state=ctrl_state)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
fixes:
- |
Previously it was possible to set the number of control qubits to zero in which case the
the original, potentially non-controlled, operation would be returned. This could cause
an AttributeError if the caller attempts to access an attribute which only ControlledGates
have. This fix adds a getter/setter for num_ctrl_qubits to handle validation.
16 changes: 13 additions & 3 deletions test/python/circuit/test_controlled_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -541,14 +541,14 @@ def test_multi_controlled_y_rotation_matrix_basic_mode(self, num_controls, use_b
with self.subTest(msg='control state = {}'.format(ctrl_state)):
self.assertTrue(matrix_equal(simulated, expected))

@data(0, 1, 2)
@data(1, 2)
def test_mcx_gates_yield_explicit_gates(self, num_ctrl_qubits):
"""Test the creating a MCX gate yields the explicit definition if we know it."""
cls = MCXGate(num_ctrl_qubits).__class__
explicit = {0: XGate, 1: CXGate, 2: CCXGate}
explicit = {1: CXGate, 2: CCXGate}
self.assertEqual(cls, explicit[num_ctrl_qubits])

@data(0, 3, 4, 5, 8)
@data(3, 4, 5, 8)
def test_mcx_gates(self, num_ctrl_qubits):
"""Test the mcx gates."""
backend = BasicAer.get_backend('statevector_simulator')
Expand Down Expand Up @@ -860,6 +860,16 @@ def test_open_controlled_gate_raises(self):
with self.assertRaises(CircuitError):
base_gate.control(num_ctrl_qubits, ctrl_state='201')

@data(-1, 0, 1.4, '1', 4, 10)
def test_improper_num_ctrl_qubits(self, num_ctrl_qubits):
"""
Test improperly specified num_ctrl_qubits.
"""
num_qubits = 4
with self.assertRaises(CircuitError):
ControlledGate(name='cgate', num_qubits=num_qubits,
params=[], num_ctrl_qubits=num_ctrl_qubits)

def test_open_controlled_equality(self):
"""
Test open controlled gates are equal if their base gates and control states are equal.
Expand Down