How to format a qiskit circuit to only have a high level abstraction?

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:

circuit.h(3)
circuit.barrier()
_cccx(circuit, q)
circuit.barrier()
circuit.draw(output="mpl")


The output of the following code is as follows:

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.h(3)
circuit.mcx([0, 1, 2], 3)
circuit.draw(output='mpl')


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

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)
larger.h(4)

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])
larger.draw(output='mpl')


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)

• 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? – IE Irodov May 17 at 2:01
• 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). – Cryoris May 17 at 9:50
• Excellent, thanks! – IE Irodov May 18 at 3:45