0
$\begingroup$

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: enter image description here

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, enter image description here 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

$\endgroup$

1 Answer 1

1
$\begingroup$

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]

Hope this helps! [1]: https://qiskit.org/documentation/stable/0.19/stubs/qiskit.circuit.QuantumCircuit.to_instruction.html [2]: https://i.stack.imgur.com/PVej7.png

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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