How to encapsulate the set of quantum gates qiskit circuit display? (abstraction)

So I have successfully make simple input of n-bit classical register with just using 1-qubit register.

Here is my program / cell code:

from qiskit import QuantumCircuit
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram

def toBin(val,size=8): return bin(val)[2:].rjust(size,'0') # return binary string of val with fixed size 8 (default)

def indexOf(s, ch): return [i for i, ltr in enumerate(s[::-1]) if ltr == ch] # return all index of ch in reversed s string.

# the value must be unsigned integer.
value = 123 #@param {"type":"integer"}

# the 'bitSize' of classical register. (must be unsigned integer)
bitSize = 8 #@param {"type":"integer"}

while value > (2**bitSize)-1: bitSize +=1 # if value is overflow, keep increment bitSize

qc =  QuantumCircuit(1, bitSize) # 1-bit quantum register, 8-bit classical register

binString = toBin(value, bitSize) # will convert 123 to 01111011 (binary string)

# auto circuit
qc.reset(0)
for i in indexOf(binString,'0'): qc.measure(0,i)
qc.x(0)
for i in indexOf(binString,'1'): qc.measure(0,i)
qc.reset(0)

display(qc.draw(output='mpl'))
display(plot_histogram(AerSimulator().run(qc).result().get_counts()))


Output:

So basically my program will set value of the n-bit classical register from 1-qubit register only. The problem is as you see, the circuit is too crowd. I expect I can abstract/encapsulate it with black box. This is not the problem if the classical register bit size is 8, how about 64-bit classical register? I can't imagine the crowd of quantum logic gates.

I expect the circuit display will looks like this, where myCustomGate contain #auto circuit that I commented in my code. So now the circuit will not crowd anymore.

Btw, I draw the circuit with mpl aka matplotlib.

So, can qiskit do it?

You can run the code in Google Colab: enter link description here

Inorder to Encapsulate set of gate operations and Measurements we generally use [qiskit.circuit.QuantumCircuit.to_instruction][1] .

my_inst = qc.to_instruction()
new_circ = QuantumCircuit(1,8)
new_circ.append(my_inst,[0],range(8))

# display(qc.draw(output='mpl'))
display(new_circ.draw(output='mpl'))


Encapsulated Output using to_instruction: [![enter image description here][2]][2]

• This is okay, but why the circuit drawing tells explicitly the bus of classical register with 8 lines? Why not just one line bus? Oct 17, 2022 at 3:50