Skip to content

Commit

Permalink
Fix multiple appends of '_dg' in name attribute on calling inverse() (#…
Browse files Browse the repository at this point in the history
…6563)

* Fix multiple appends of '_dg' in name attribute.

If inverse() method of Gate is called multiple times, each call appended
'_dg' to the end of the name attribute, i.e. 'gate_name_dg_dg'. This commit
fixes it by checking if the name already contains '_dg'. If so, the '_dg'
is removed from the name. If not, '_dg' is added.

* Add tests and release notes.

* Update bugfix-gate-inverse-name-3401093a18813ace.yaml
  • Loading branch information
jwalaQ committed Jun 12, 2021
1 parent 0a69898 commit 0df56b3
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 4 deletions.
10 changes: 6 additions & 4 deletions qiskit/circuit/instruction.py
Original file line number Diff line number Diff line change
Expand Up @@ -337,18 +337,20 @@ def inverse(self):

from qiskit.circuit import QuantumCircuit, Gate # pylint: disable=cyclic-import

if self.name.endswith("_dg"):
name = self.name[:-3]
else:
name = self.name + "_dg"
if self.num_clbits:
inverse_gate = Instruction(
name=self.name + "_dg",
name=name,
num_qubits=self.num_qubits,
num_clbits=self.num_clbits,
params=self.params.copy(),
)

else:
inverse_gate = Gate(
name=self.name + "_dg", num_qubits=self.num_qubits, params=self.params.copy()
)
inverse_gate = Gate(name=name, num_qubits=self.num_qubits, params=self.params.copy())

inverse_gate.definition = QuantumCircuit(
*self.definition.qregs,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
fixes:
- |
Fixed bug in assigning name attribute to ``inverse()`` function of
:class:`~qiskit.circuit.Gate` (inherited from :class:`~qiskit.circuit.Instruction`).
Earlier, the inverse() function returned a gate with label None. Now
the label of inverse is built using the label calling it.
`#6563 <https://github.com/Qiskit/qiskit-terra/pull/6563>` for more details.
11 changes: 11 additions & 0 deletions test/python/circuit/test_instructions.py
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,17 @@ def test_inverse_with_global_phase(self):
gate_inverse = circ.to_instruction()
self.assertEqual(gate.inverse().definition, gate_inverse.definition)

def test_inverse_with_label(self):
"""test inverting gate initialized with label attribute."""
q = QuantumRegister(2)
qc = QuantumCircuit(q, name="circ")
qc.cx(0, 1)
qc_gate = qc.to_gate()
qc_gate_inverse = qc_gate.inverse()
self.assertEqual(qc_gate.name + "_dg", qc_gate_inverse.name)
qc_gate_inverse_inverse = qc_gate_inverse.inverse()
self.assertEqual(qc_gate_inverse_inverse.name, qc_gate.name)

def test_no_broadcast(self):
"""See https://github.com/Qiskit/qiskit-terra/issues/2777
When creating custom instructions, do not broadcast parameters"""
Expand Down

0 comments on commit 0df56b3

Please sign in to comment.