def BV_M1(input, count_times): simulator = Aer.get_backend('qasm_simulator') oracle = QuantumRegister(10) register = QuantumRegister(10) c = ClassicalRegister(10) qc = QuantumCircuit(oracle, register, c) input_string = dec2bin(input) for i in range(len(input_string)): if input_string[9 - i] == '1': qc.x(oracle[i]) qc.cnot(oracle[6], oracle[0]) # M4 qc.barrier(oracle) qc.h(register) for i in range(len(input_string)): qc.cz(oracle[i], register[i]) qc.barrier(oracle) qc.h(register) qc.measure(register, c) from qiskit.tools.visualization import circuit_drawer circuit_drawer(qc, filename='./BV_M1_circuit') job = execute(qc, simulator, shots=count_times * 100) result = job.result() counts = result.get_counts(qc) return counts
def letsgo(): l = len(sys.argv[1:]) if (l < 1): sys.exit("error, missing argument (backend r/s/b, [draw 0/1])") qc = create_circuit() if (l > 1 and sys.argv[2] == '1'): circuit_drawer(qc, filename=img_path) if (sys.argv[1] == 's'): print("Running simulation") backend = local_simulate(qc) credits = 10 run_circuit(qc, backend, 4096, credits) elif (sys.argv[1] == 'r'): print("Running for real") backend = online_real(qc) credits = 3 run_circuit(qc, backend, 4096, credits) elif (sys.argv[1] == 'b'): print("Running simulation") backend = local_simulate(qc) credits = 10 run_circuit(qc, backend, 4096, credits) print("Running both") backend = online_real(qc) credits = 3 run_circuit(qc, backend, 4096, credits) else: sys.exit("error, available parameters are 'r' 's' or 'b'")
def display(self, circuit): if self.qiskit_backend != 'local_unitary_simulator': print('drawing circuit...') circuit_drawer(circuit) print('drawing histogram...,') print(' (close graph windows to proceed)') plot_histogram(self.job_exp.result().get_counts(circuit))
def test_teleport(self): """Test draw teleport circuit.""" filename = self._get_resource_path('test_teleport.tex') qr = qiskit.QuantumRegister(3, 'q') cr = qiskit.ClassicalRegister(3, 'c') qc = qiskit.QuantumCircuit(qr, cr) # Prepare an initial state qc.u3(0.3, 0.2, 0.1, qr[0]) # Prepare a Bell pair qc.h(qr[1]) qc.cx(qr[1], qr[2]) # Barrier following state preparation qc.barrier(qr) # Measure in the Bell basis qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) # Apply a correction qc.z(qr[2]).c_if(cr, 1) qc.x(qr[2]).c_if(cr, 2) qc.measure(qr[2], cr[2]) try: circuit_drawer(qc, filename=filename, output='latex_source') self.assertNotEqual(os.path.exists(filename), False) finally: if os.path.exists(filename): os.remove(filename)
def test_wide_circuit(self): """Test draw wide circuit.""" filename = self._get_resource_path('test_wide.tex') qc = self.random_circuit(100, 1, 1) try: circuit_drawer(qc, filename=filename, output='latex_source') self.assertNotEqual(os.path.exists(filename), False) finally: if os.path.exists(filename): os.remove(filename)
def test_cnots(): a = QuantumRegister(3, 'a') b = QuantumRegister(5, 'b') qc = QuantumCircuit(a, b) c = pse.PseudoQuantumRegister('test0') c.add_registers(a, b) qc.ccx(c[0], c[1], c[2]) qc.ccx(c[2], c[3], c[4]) from qiskit.tools.visualization import circuit_drawer circuit_drawer(qc, filename="../img/pseudo_test.png")
def test0(): qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.h(qr) qc.z(qr) qc.h(qr) qc.measure(qr, cr) circuit_drawer(qc, filename="imgs/grover_thru.png") backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend) result = job.result() print(result.get_counts(qc))
def compile_and_run(self, t, vertex_coins, mode="ionq_simulator"): from qiskit_ionq_provider import IonQProvider from qiskit.tools.visualization import circuit_drawer from qiskit.providers.jobstatus import JobStatus provider = IonQProvider(token='UXA0mTBVroG62waNXpn6yCXDyx2iDNH0') backend = provider.get_backend(mode) self.build_evolution_operator(vertex_coins) circuit = self.evolve(t) transpiled = transpile(circuit, backend=backend) print(circuit_drawer(circuit)) job = backend.run(transpiled) #save job_id job_id = job.job_id() if mode == "ionq_simulator": #Fetch the result: result = job.result() elif mode == "ionq_qpu": job=backend.retrieve_job(job_id) while job.status() is not JobStatus.DONE: time.sleep(5) from qiskit.visualization import plot_histogram fig = plot_histogram(result.get_counts()) fig.savefig("hist.png")
def draw(self, scale=0.7, filename=None, style=None, output='text', interactive=False, line_length=None, plot_barriers=True, reverse_bits=False, justify=None): """Draw the quantum circuit Using the output parameter you can specify the format. The choices are: 0. text: ASCII art string 1. latex: high-quality images, but heavy external software dependencies 2. matplotlib: purely in Python with no external dependencies Defaults to an overcomplete basis, in order to not alter gates. Args: scale (float): scale of image to draw (shrink if < 1) filename (str): file path to save image to style (dict or str): dictionary of style or file name of style file. You can refer to the :ref:`Style Dict Doc <style-dict-doc>` for more information on the contents. output (str): Select the output method to use for drawing the circuit. Valid choices are `text`, `latex`, `latex_source`, `mpl`. interactive (bool): when set true show the circuit in a new window (for `mpl` this depends on the matplotlib backend being used supporting this). Note when used with either the `text` or the `latex_source` output type this has no effect and will be silently ignored. line_length (int): sets the length of the lines generated by `text` reverse_bits (bool): When set to True reverse the bit order inside registers for the output visualization. plot_barriers (bool): Enable/disable drawing barriers in the output circuit. Defaults to True. justify (string): Options are `left`, `right` or `none`, if anything else is supplied it defaults to left justified. It refers to where gates should be placed in the output circuit if there is an option. `none` results in each gate being placed in its own column. Currently only supported by text drawer. Returns: PIL.Image or matplotlib.figure or str or TextDrawing: * PIL.Image: (output `latex`) an in-memory representation of the image of the circuit diagram. * matplotlib.figure: (output `mpl`) a matplotlib figure object for the circuit diagram. * str: (output `latex_source`). The LaTeX source code. * TextDrawing: (output `text`). A drawing that can be printed as ascii art Raises: VisualizationError: when an invalid output method is selected """ from qiskit.tools import visualization return visualization.circuit_drawer(self, scale=scale, filename=filename, style=style, output=output, interactive=interactive, line_length=line_length, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify)
def draw(self, scale=0.7, filename=None, style=None, output='text', interactive=False, line_length=None, plot_barriers=True, reverse_bits=False): """Draw the quantum circuit Using the output parameter you can specify the format. The choices are: 0. text: ASCII art string 1. latex: high-quality images, but heavy external software dependencies 2. matplotlib: purely in Python with no external dependencies Defaults to an overcomplete basis, in order to not alter gates. Args: scale (float): scale of image to draw (shrink if < 1) filename (str): file path to save image to style (dict or str): dictionary of style or file name of style file. You can refer to the :ref:`Style Dict Doc <style-dict-doc>` for more information on the contents. output (str): Select the output method to use for drawing the circuit. Valid choices are `text`, `latex`, `latex_source`, `mpl`. interactive (bool): when set true show the circuit in a new window (cannot inline in Jupyter). Note when used with the latex_source output type this has no effect line_length (int): sets the length of the lines generated by `text` reverse_bits (bool): When set to True reverse the bit order inside registers for the output visualization. plot_barriers (bool): Enable/disable drawing barriers in the output circuit. Defaults to True. Returns: PIL.Image: (output `latex`) an in-memory representation of the image of the circuit diagram. matplotlib.figure: (output `mpl`) a matplotlib figure object for the circuit diagram. String: (output `latex_source`). The LaTeX source code. TextDrawing: (output `text`). A drawing that can be printed as ascii art Raises: VisualizationError: when an invalid output method is selected """ from qiskit.tools import visualization return visualization.circuit_drawer(self, scale=scale, filename=filename, style=style, output=output, interactive=interactive, line_length=line_length, plot_barriers=plot_barriers, reverse_bits=reverse_bits)
def test_text_drawer(self): filename = self._get_resource_path('current_textplot.txt') qc = self.sample_circuit() output = circuit_drawer(qc, filename=filename, output="text", line_length=-1) self.assertFilesAreEqual(filename, self.text_reference) os.remove(filename) try: encode(str(output), encoding='cp437') except UnicodeEncodeError: self.fail("_text_circuit_drawer() should only use extended ascii (aka code page 437).")
def main(): n = 8 r = 3 qr, cr, qc = preparing_initial_states(n, r) from os import sys choice = int(sys.argv[1]) if choice == 6: permutation_6(qr, qc, n) elif choice == 7: permutation_7(qr, qc, n) elif choice == 8: permutation_8(qr, qc, n) elif choice == 9: permutation_9(qr, qc, n) else: print("Error choice") return print("Choice", choice) print("Drawing") from qiskit.tools.visualization import circuit_drawer circuit_drawer(qc, filename='img/test_{0}.png'.format(choice)) print("Preparing execution") # from qiskit import Aer # backend = Aer.get_backend('qasm_simulator') from qiskit import IBMQ IBMQ.load_accounts() backend = IBMQ.get_backend('ibmq_qasm_simulator') from qiskit import execute print("Execute") job = execute(qc, backend, shots=4098) print(job.job_id()) result = job.result() print("Results ready") counts = result.get_counts(qc) print(counts) print(len(counts)) from qiskit.tools.visualization import plot_histogram plot_histogram(counts, )
def grover(x_star): qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) ## uniform superpositiom qc.h(qr) ## It suffices to apply the subroutine (oracle + diffusion) just one time oracle(qc, qr, x_star) #grover_diffusion(qc, qr) grover_diffusion2(qc, qr) qc.measure(qr, cr) circuit_drawer(qc, filename="imgs/grover_2.png") backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend) result = job.result() print(result.get_counts(qc))
def construct(self): """construct""" ################################################# """Grover implementation repeating oracle + diffusion """ N = int(sqrt(self.n)) for i in range(N): self.oracle1() self.qc.barrier() self.diffusion_gate() self.qc.barrier() ################################################# """Measurement of quibits """ for i in range(self.n): self.qc.measure(self.q[i], self.c[i]) ################################################# circuit_drawer(self.qc, filename='./Pictures/gidney3_class.png')
def vis_circuit(total_number, file_name="circuit.png"): q = QuantumRegister(total_number) c = ClassicalRegister(total_number) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[1]) qc.x(q[1]) if total_number > 2: for index_limit in range(1, int(math.log(total_number, 2))): index = -1 while index < (2**index_limit) - 1: index = index + 1 index1 = index index2 = index + 2**index_limit print(index1) print(index2) qc.ch(q[index1], q[index2]) qc.cx(q[index2], q[index1]) qc.measure(q, c) circuit_drawer(qc, filename=file_name) return 1
def draw_circuit(qc, img_dir): logger.info("Drawing circuit") img_file = img_dir + qc.name style_mpl = { 'cregbundle': True, 'compress': True, 'usepiformat': True, 'subfontsize': 12, 'fold': 100, 'showindex': True, "displaycolor": { "id": "#ffca64", "u0": "#f69458", "u1": "#f69458", "u2": "#f69458", "u3": "#f69458", "x": "#a6ce38", "y": "#a6ce38", "z": "#a6ce38", "h": "#00bff2", "s": "#00bff2", "sdg": "#00bff2", "t": "#ff6666", "tdg": "#ff6666", "rx": "#ffca64", "ry": "#ffca64", "rz": "#ffca64", "reset": "#d7ddda", "target": "#00bff2", "meas": "#f070aa" } } from qiskit.tools.visualization import circuit_drawer circuit_drawer(qc, filename=img_file + ".png", style=style_mpl, output='mpl')
from math import sqrt n = 4 q = QuantumRegister(n, 'q') c = ClassicalRegister(n, 'c') anc = QuantumRegister(n - 1, 'anc') qc = QuantumCircuit(q, c, anc) # setup initial state qc.x(q[0]) qc.x(q[1]) qc.cx(q[0], anc[0]) qc.ccx(q[1], anc[0], anc[1]) qc.ccx(q[2], anc[1], anc[2]) qc.cx(anc[2], q[3]) qc.measure(q, c) # compile and run the Quantum circuit on a simulator backend backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() # Show the results print("simulation: ", result_sim) print(result_sim.get_counts(qc)) circuit_drawer(qc, filename='phase_flip.png')
def test_matplotlib_drawer(self): filename = self._get_resource_path('current_matplot.png') qc = self.sample_circuit() circuit_drawer(qc, filename=filename, output='mpl') self.assertImagesAreEqual(filename, self.matplotlib_reference) os.remove(filename)
def Grover(index): n = len(index) if not n > 2: raise ValueError # Create a Quantum Register with 2 qubits. # control quibits q = QuantumRegister(n, 'q') # ancillary qubits anc = QuantumRegister(n - 1, 'anc') # control for control z-gate in oracle # target qubits for oracle (for debuggin) tar = QuantumRegister(1, 'tar') # ancillary qubits for diffusion gate ancD = QuantumRegister(n - 2, 'ancD') # target qubits for diffusion gate tarD = QuantumRegister(1, 'tarD') # Create a Classical Register for oracle measurements. # cOracle = ClassicalRegister(1, 'cOracle') # registers for measurement of the qubits c = ClassicalRegister(n, 'c') # Create a Quantum Circuit qc = QuantumCircuit(q, anc, tar, ancD, tarD, c) # # set input for testing # for i in range(n): # v = int(index[i]) # if v != 0: # qc.x(q[i]) # apply hadamard gates for i in range(n): qc.h(q[i]) # qc.x(tar[0]) ################################################# """ORACLE IMPLEMENTATION """ def oracle1(): # applying control-NOT gates forward for i in range(n): v = int(index[i]) # print(v) if i == 0: v2 = int(index[i + 1]) if v2 == 0: qc.x(q[i + 1]) if v == 0: qc.x(q[i]) qc.ccx(q[i], q[i + 1], anc[i]) # qc.x(q[i]) else: qc.ccx(q[i], q[i + 1], anc[i]) # if v2 == 0: # qc.x(q[i + 1]) elif i == 1: pass else: if v == 0: qc.x(q[i]) qc.ccx(q[i], anc[i - 2], anc[i - 1]) # qc.x(q[i]) else: qc.ccx(q[i], anc[i - 2], anc[i - 1]) qc.cx(anc[n - 2], tar[0]) qc.z(tar[0]) # qc.measure(tar, cOracle) qc.cx(anc[n - 2], tar[0]) # applying control-NOT gates backwards -> reset for i in range(n - 1, -1, -1): v = int(index[i]) # print(v) if i == 0: v2 = int(index[i + 1]) # if v2 == 0: # qc.x(q[i + 1]) if v == 0: # qc.x(q[i]) qc.ccx(q[i], q[i + 1], anc[i]) qc.x(q[i]) else: qc.ccx(q[i], q[i + 1], anc[i]) if v2 == 0: qc.x(q[i + 1]) elif i == 1: pass else: if v == 0: # qc.x(q[i]) qc.ccx(q[i], anc[i - 2], anc[i - 1]) qc.x(q[i]) else: qc.ccx(q[i], anc[i - 2], anc[i - 1]) ################################################# """GROVER-DIFFUSION GATE IMPLEMENTAION """ def diffusion_gate(): # apply hadamard gates for i in range(n): qc.h(q[i]) # apply pauli-X gates for i in range(n): qc.x(q[i]) """Apply multi-qubit control-pauli-Z gate """ for i in range(n - 1): if i == 0: qc.ccx(q[i], q[i + 1], ancD[i]) elif i == 1: pass else: qc.ccx(q[i], ancD[i - 2], ancD[i - 1]) qc.cz(ancD[n - 3], q[n - 1]) for i in range(n - 1): if i == 0: qc.ccx(q[i], q[i + 1], ancD[i]) elif i == 1: pass else: qc.ccx(q[i], ancD[i - 2], ancD[i - 1]) # apply pauli-X gates for i in range(n): qc.x(q[i]) # apply hadamard gates for i in range(n): qc.h(q[i]) ################################################# """Grover implementation repeating oracle + diffusion """ N = int(sqrt(n)) for i in range(N): oracle1() diffusion_gate() ################################################# """Measurement of quibits """ for i in range(n): qc.measure(q[i], c[i]) ################################################# circuit_drawer(qc, filename='gidney2.png') # See a list of available local simulators print("Local backends: ", Aer.available_backends()) # compile and run the Quantum circuit on a simulator backend backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() # Show the results print("simulation: ", result_sim) print(result_sim.get_counts(qc))
from qiskit import ClassicalRegister,QuantumRegister,QuantumCircuit,Aer from qiskit.tools.visualization import circuit_drawer import math as m from qiskit import IBMQ IBMQ.load_account() S_simulator=Aer.backends(name='statevector_simulator')[0] M_simulator=Aer.backends(name='qasm_simulator')[0] q=QuantumRegister(1,name='q') c=ClassicalRegister(1,name='c') qc=QuantumCircuit(q,c,name='qc') qc.iden(q[0) qc.u1(m.pi/4,q[0]) print(circuit_drawer(qc))
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.tools.visualization import circuit_drawer def build_bell_circuit(): """IBM: Returns a circuit putting 2 qubits in the Bell state.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) # made changes here qc.h(q[0]) qc.cx(q[0], q[1]) qc.measure(q, c) return qc # create the circuit and display it bell_circuit = build_bell_circuit() diagram = circuit_drawer(bell_circuit, filename='./q2_diagram.png') diagram.show() print( "Ignore the pdflatex warning.\nMore on: https://github.com/Qiskit/qiskit-terra/blob/master/examples/python/hello_quantum.py")
from qiskit import (IBMQ, Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute) from qiskit.backends.ibmq import least_busy from qiskit.tools.visualization import circuit_drawer qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.measure(qr, cr) circuit_drawer(qc, filename="../imgs/pag032.png") backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend) print(job.result().get_counts(qc)) IBMQ.load_accounts() large_enough_devices = IBMQ.backends( filters= lambda x: x.configuration()['n_qubits'] > 2 and not x.configuration()['simulator'] ) backend = least_busy(large_enough_devices) job = execute(qc, backend, max_credits=3) print(job.result().get_counts(qc))
secretnumber = '111011' circuit = QuantumCircuit(len(secretnumber)+1, len(secretnumber)) circuit.h(range(len(secretnumber))) circuit.x(len(secretnumber)) circuit.h(len(secretnumber)) circuit.barrier() for ii, yesno in enumerate(reversed(secretnumber)): if yesno == '1': circuit.cx(ii, len(secretnumber)) circuit.barrier() circuit.h(range(len(secretnumber))) circuit.barrier() circuit.measure(range(len(secretnumber)), range(len(secretnumber))) circuit_drawer(circuit, filename='circuit.png', output='mpl') simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend = simulator, shots=1).result() counts = result.get_counts() print(counts)
best = min([x for x in device_status if x['available'] is True], key=lambda x: x['pending_jobs']) return best['name'] backend = lowest_pending_jobs() print("The best backend is " + backend) q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[1]) qc.measure(q, c) job_exp = execute(qc, backend=backend, shots=1024, max_credits=3) lapse = 0 interval = 10 while not job_exp.done: print('Status @ {} seconds'.format(interval * lapse)) print(job_exp.status) time.sleep(interval) lapse += 1 print(job_exp.status) plot_histogram(job_exp.result().get_counts(qc)) print('You have made entanglement!') circuit_drawer(qc)
expected_valueYY = (countsYY.get('00', 0) - countsYY.get('01', 0) - countsYY.get('10', 0) + countsYY.get('11', 0)) / num_shots expected_valueZZ = (countsZZ.get('00', 0) - countsZZ.get('01', 0) - countsZZ.get('10', 0) + countsZZ.get('11', 0)) / num_shots expected_value = 0.5 - 0.5 * expected_valueXX + 0.5 * expected_valueZZ - 0.5 * expected_valueYY print('The lowest eigenvalue is the expected value, which is : %s' % expected_value) # *** # # Circuit Visualization # In[7]: from qiskit.tools.visualization import circuit_drawer circuit_drawer(vqe_circXX, scale=.4) # In[8]: from qiskit.tools.visualization import circuit_drawer circuit_drawer(vqe_circYY, scale=.4) # In[9]: from qiskit.tools.visualization import circuit_drawer circuit_drawer(vqe_circZZ, scale=.4)
qc.x(anci[0]) qc.x(anci[1]) qc.cz(anci[1], anci[0]) qc.x(anci[0]) qc.x(anci[1]) #W qc.u3(theta, 0, math.pi, anci[0]) qc.ccx(anci[0], anci[1], cont[0]) qc.cy(cont[0], psi[0]) qc.cx(cont[0], psi[0]) qc.ccx(anci[0], anci[1], cont[0]) qc.cx(anci[0], anci[1]) qc.ccx(anci[0], anci[1], cont[0]) qc.cz(cont[0], psi[0]) qc.cy(cont[0], psi[0]) qc.ccx(anci[0], anci[1], cont[0]) qc.u3(theta, 0, math.pi, anci[0]) pic = circuit_drawer(qc) #from PIL import Image pic.save('WRWRW', 'png') #pic.show() #import BackendSetup #BackendSetup.signIn() #backend = BackendSetup.bestBackend()
def test_teleport_image(self): im = circuit_drawer(self.qc) if im: pix = numpy.array(im) self.assertEqual(pix.shape, (260, 701, 3))
qc.x(qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.h(qr[3]) qc.x(qr[0]) qc.x(qr[1]) qc.x(qr[3]) qc.h(qr[3]) qc.ccx(qr[0], qr[1], qr[3]) qc.h(qr[3]) qc.x(qr[0]) qc.x(qr[1]) qc.x(qr[3]) qc.h(qr[0]) qc.h(qr[1]) qc.h(qr[3]) qc.h(qr[4]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) qc.measure(qr[3], cr[3]) qc.measure(qr[4], cr[4]) job_sim = execute(qc, "local_qasm_simulator") sim_result = job_sim.result() circuit_drawer(qc, filename="Yousef.png") # Show the results print("simulation: ", sim_result) print(sim_result.get_counts(qc))
abc.x(ab[bgates[k]]) for k in range(len(agates)): abc.x(ab[agates[k] + n]) QFT(abc, ab, n) R_phis = [0] for i in np.arange(n): R_phis.append(1 / (2**(i)) * m.pi) for k in np.arange(1, n + 1): for j, l in zip(np.arange(k - 1, n), np.arange(1, n - k + 2)): abc.cu1(R_phis[l], ab[int(n + k - 1)], ab[int(j)]) QFT_dgr(abc, ab, n) circuit_drawer(abc) job = execute(abc, S_simulator) result = job.result() result.get_statevector() for i in range(4**n): if result.get_statevector()[i] != 0j: measure_result = str(bin(i))[2:] #print(i) while len(measure_result) < 2 * n: measure_result = '0' + measure_result #Reverse result_a, result_b = int(measure_result[n - 1::-1], 2), int(measure_result[2 * n:n - 1:-1], 2) #result_a,result_b --> QFT(a+b), b --> a+b, b
# the LICENSE.txt file in the root directory of this source tree. """ Example showing how to draw a quantum circuit using Qiskit Terra. """ from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.tools.visualization import circuit_drawer def build_bell_circuit(): """Returns a circuit putting 2 qubits in the Bell state.""" q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[1]) qc.measure(q, c) return qc # Create the circuit bell_circuit = build_bell_circuit() # Provide a name to write the diagram to the filesystem circuit_drawer(bell_circuit, filename='./bell_circuit.png') # Use the return value with show() to display the diagram diagram = circuit_drawer(bell_circuit) diagram.show()