Consider the following situation, we import a 3-bit Toffoli gate as follows:

from qiskit.aqua.circuits.gates.multi_control_toffoli_gate import _cccx

I further define a Quantum Register of size 4 and a circuit containing it:

qr = QuantumRegister(4, 'q')
circuit = QuantumCircuit(qr)

I form a small circuit by applying Hadamard on the last qubit followed by _cccx:

_cccx(circuit, q)

The output of the following code is as follows:

enter image description here

As we can see that the underlying logic of _cccx is shown which makes the circuit too big, is there any way to display a higher-level abstraction which would consume less space and simply conceal the underlying gate logic?

Edit: This question is not limited to $n$-bit Toffoli gate but to any circuit which may even be defined by user.


You should use the mcx method of the circuit instead (methods with a leading underscore are usually for internal usage and not developed for users), then you can do

from qiskit import QuantumCircuit
circuit = QuantumCircuit(4)
circuit.mcx([0, 1, 2], 3)

Which outputs


If you decompose or transpile the circuit you'll get down to the implementation of the multi-controlled X

from qiskit import transpile
basis_gates = ['h', 'cx', 'cu1', 'u1', 'u3']
transpiled = transpile(circuit, basis_gates=basis_gates)
transpiled.draw(output='mpl', filename='c3x_decomp.png')

to get enter image description here

General logic wrapping into Instructions

To wrap any circuit logic into an abstract block you can use the Instruction object. First you define a subcircuit and then append it onto the larger circuit as Instruction. Here's a short example:

larger = QuantumCircuit(5)

sub = QuantumCircuit(4, name='My subcircuit')
sub.ccx(0, 1, 2)
sub.h([0, 1, 2, 3])
sub.crx(0.2, 3, 0)

larger.append(sub.to_instruction(), [1, 2, 3, 4])

enter image description here

If you decompose the larger circuit you'll see the components. If you don't want to wrap it into a block you can just directly append sub to the circuit using the compose method:

composed = larger.compose(sub, qubits=[1, 2, 3, 4)
  • $\begingroup$ Thanks for your answer that does solve this problem of mine but are there any methods in qiskit library that does this universally? Your answer is applicable to toffoli-gates but what if I wanted to abstract any logic in general? $\endgroup$ – Übermensch May 17 '20 at 2:01
  • $\begingroup$ Ah, yes that's also possible if you wrap your logic inside an Instruction object. I'll update my answer to explain that (since it contains some more code). $\endgroup$ – Cryoris May 17 '20 at 9:50
  • $\begingroup$ Excellent, thanks! $\endgroup$ – Übermensch May 18 '20 at 3:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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