repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# Checking the version of PYTHON; we only support 3 at the moment import sys if sys.version_info < (3,0): raise Exception('Please use Python version 3 or greater.') # useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np import time from pprint import pprint # importing the QISKit from qiskit import QuantumCircuit, QuantumProgram #import Qconfig # import basic plot tools from qiskit.tools.visualization import plot_histogram QPS_SPECS = { 'circuits': [{ 'name': 'W_states', 'quantum_registers': [{ 'name':'q', 'size':5 }], 'classical_registers': [{ 'name':'c', 'size':5 }]}], } "Choice of the backend" # The flag_qx2 must be "True" for using the ibmqx2. # "True" is also better when using the simulator #backend = 'ibmqx2' # not advisable if other pending jobs! #backend = 'ibmqx4' # not advisable if other pending jobs! backend = 'local_qasm_simulator' #OK #backend = 'ibmqx_hpc_qasm_simulator' #OK flag_qx2 = True if backend == 'ibmqx4': flag_qx2 = False print("Your choice for the backend is: ", backend, "flag_qx2 is: ", flag_qx2) # Here, two useful routine # Define a F_gate def F_gate(circ,q,i,j,n,k) : theta = np.arccos(np.sqrt(1/(n-k+1))) circ.ry(-theta,q[j]) circ.cz(q[i],q[j]) circ.ry(theta,q[j]) circ.barrier(q[i]) # Define the cxrv gate which uses reverse CNOT instead of CNOT def cxrv(circ,q,i,j) : circ.h(q[i]) circ.h(q[j]) circ.cx(q[j],q[i]) circ.h(q[i]) circ.h(q[j]) circ.barrier(q[i],q[j]) # 3-qubit W state Q_program = QuantumProgram(specs=QPS_SPECS) #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) W_states = Q_program.get_circuit('W_states') q = Q_program.get_quantum_register('q') c = Q_program.get_classical_register('c') W_states.x(q[2]) #start is |100> F_gate(W_states,q,2,1,3,1) # Applying F12 F_gate(W_states,q,1,0,3,2) # Applying F23 if flag_qx2 : # option ibmqx2 W_states.cx(q[1],q[2]) # cNOT 21 W_states.cx(q[0],q[1]) # cNOT 32 else : # option ibmqx4 cxrv(W_states,q,1,2) cxrv(W_states,q,0,1) # Coin tossing W_states.h(q[3]) W_states.h(q[4]) for i in range(5) : W_states.measure(q[i] , c[i]) circuits = ['W_states'] "Dotted alphabet" top_bottom = "███████████████" blank = "█ █" chosen = [] chosen = chosen + ["███████████████"] chosen = chosen + ["███████████ ██"] chosen = chosen + ["██████████ ███"] chosen = chosen + ["█████████ ████"] chosen = chosen + ["████████ █████"] chosen = chosen + ["█ ████ ██████"] chosen = chosen + ["██ ██ ███████"] chosen = chosen + ["███ ████████"] chosen = chosen + ["████ █████████"] chosen = chosen + ["███████████████"] here_left = [] here_left = here_left + ["███████████████"] here_left = here_left + ["███████████████"] here_left = here_left + ["███ █████████"] here_left = here_left + ["███ █████████"] here_left = here_left + ["███ █████████"] here_left = here_left + ["███ █████████"] here_left = here_left + ["███ █████████"] here_left = here_left + ["███ ████"] here_left = here_left + ["███████████████"] here_left = here_left + ["███████████████"] here_center = [] here_center = here_center + ["███████████████"] here_center = here_center + ["███████████████"] here_center = here_center + ["█████ ████"] here_center = here_center + ["███ █████████"] here_center = here_center + ["███ █████████"] here_center = here_center + ["███ █████████"] here_center = here_center + ["███ █████████"] here_center = here_center + ["█████ ████"] here_center = here_center + ["███████████████"] here_center = here_center + ["███████████████"] here_right = [] here_right = here_right + ["███████████████"] here_right = here_right + ["███████████████"] here_right = here_right + ["███ █████"] here_right = here_right + ["███ ███ ███"] here_right = here_right + ["███ ███ ███"] here_right = here_right + ["███ █████"] here_right = here_right + ["███ ██ ████"] here_right = here_right + ["███ ███ ███"] here_right = here_right + ["███████████████"] here_right = here_right + ["███████████████"] goa=["█ █","█ ( ) █","█ ( ) █","█ / O O \ █","█ )|( █","█ @ █","█ = █","█ Y █","█ █"] car=["█ █","█ _______ █","█ / \ █","█ ° _______ ° █","█ / \ █","█ (O) ### (O) █","█ =+=====+= █","█ || || █","█ █"] "(RE)INITIATES STATISTICS" nb_randomnb = 0 nb_left = 0 nb_center = 0 nb_right = 0 nb_switches = 0 nb_stays = 0 nb_won_switching = 0 nb_won_sticking = 0 nb_games = 0 n_won = 0 "HERE START THE GAME" "Hiding the car and the two goats behind the three doors" Label = ["left", "central", "right"] shots = 1 repeat = "Y" while repeat == "Y": nb_of_cars = 4 while nb_of_cars != 1: result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=5, wait=5, timeout=600) c5str = str(result.get_counts('W_states')) nb_of_cars = int(c5str[4]) + int(c5str[5]) + int(c5str[6]) #this is for checking results from the real computer: if nb_of_cars == 0: print("They managed to hide three goats and no car behind the doors! Restarting the hiding process...") if nb_of_cars >= 2: print("They managed to hide", nb_of_cars, "cars behind the doors! Restarting the hiding process...") print(top_bottom," ",top_bottom," ",top_bottom) for i in range(9): print(here_left[i]," ",here_center[i]," ",here_right[i]) print(top_bottom," ",top_bottom," ",top_bottom,"\n") door = input("Game master: Your choice? letter l: left door, c: central door, r: right door + enter\n").upper() picl = here_left picc = here_center picr = here_right if (door == "L"): Doorchosen = 1 nb_left = nb_left + 1 picl = chosen else: if (door == "C"): Doorchosen = 2 nb_center = nb_center + 1 picc=chosen else: Doorchosen = 3 nb_right = nb_right + 1 picr = chosen print('Game master: Your choice was the',Label[Doorchosen-1], "door") "AN OPPORTUNITY TO CHANGE YOUR MIND" c5str = str(result.get_counts('W_states')) randomnb = (int(c5str[2]) + int(c5str[3])) %2 if c5str[4] == "1": #car behind left door Doorwinning = 1 if Doorchosen == 1: Dooropen = 2 + randomnb Doorswitch = 3 - randomnb if Doorchosen == 2: Dooropen = 3 Doorswitch = 1 if Doorchosen == 3: Dooropen = 2 Doorswitch = 1 if c5str[5] == "1": #car behind central door Doorwinning = 2 if Doorchosen == 2: Dooropen = 1 + 2*randomnb Doorswitch = 3 - 2*randomnb if Doorchosen == 1: Dooropen = 3 Doorswitch = 2 if Doorchosen == 3: Dooropen = 1 Doorswitch = 2 if c5str[6] == "1": #car behind right door Doorwinning = 3 if Doorchosen == 3: Dooropen = randomnb + 1 Doorswitch = 2 - randomnb if Doorchosen == 1: Dooropen = 2 Doorswitch = 3 if Doorchosen == 2: Dooropen = 1 Doorswitch = 3 if Dooropen == 1: picl = goa if Dooropen == 2: picc = goa if Dooropen == 3: picr = goa print(top_bottom," ",top_bottom," ",top_bottom) for i in range(9): print(picl[i]," ",picc[i]," ",picr[i]) print(top_bottom," ",top_bottom," ",top_bottom,"\n") print('I opened the', Label[Dooropen-1], 'door and you see a goat') print('You get now an opportunity to change your choice!') print("Do you want to switch for the ",Label[Doorswitch-1], " door?") I_switch = input(" Answer by (y/n) + enter\n").upper() if (I_switch == "Y"): Doorfinal = Doorswitch else: Doorfinal = Doorchosen "FINAL ANNOUNCE" if Doorfinal == Doorwinning: if Doorfinal == 1: picl = car if Doorfinal == 2: picc = car if Doorfinal == 3: picr = car endmessage = 'won the car! Congratulations!' else: if Doorfinal == 1: picl = goa if Doorfinal == 2: picc = goa if Doorfinal == 3: picr = goa endmessage = 'won a goat! Sorry!' print(top_bottom," ",top_bottom," ",top_bottom) for i in range(9): print(picl[i]," ",picc[i]," ",picr[i]) print(top_bottom," ",top_bottom," ",top_bottom,"\n") print('Game master: You opened the',Label[Doorfinal-1],'door and', endmessage) "STATISTICS" nb_games = nb_games + 1 nb_randomnb = nb_randomnb + randomnb if Doorfinal == Doorswitch: nb_switches = nb_switches +1 if c5str[Doorfinal+3] == "1": nb_won_switching = nb_won_switching + 1 else: nb_stays = nb_stays+1 if c5str[Doorfinal+3] == "1": nb_won_sticking = nb_won_sticking + 1 n_won = nb_won_switching + nb_won_sticking print() print("YOUR STATS") print("nb of games: ", nb_games," total nb won:", n_won, " first choice: left",nb_left," center", nb_center,"right", nb_right) print("nb sticking: ",nb_stays," nb won when sticking: ",nb_won_sticking,"nb switching:",nb_switches," nb won when switching:",nb_won_switching) repeat = input("Another game? Answer by (y/n) + enter\n").upper() print("Game over") %run "../version.ipynb"
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# Checking the version of PYTHON; we only support 3 at the moment import sys if sys.version_info < (3,0): raise Exception('Please use Python version 3 or greater.') # useful additional packages import matplotlib.pyplot as plt %matplotlib inline import numpy as np import time from pprint import pprint # importing the QISKit from qiskit import QuantumCircuit, QuantumProgram #import Qconfig # import basic plot tools from qiskit.tools.visualization import plot_histogram Q_program = QuantumProgram() #Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) "Choice of the backend" backend = 'local_qasm_simulator' #can be very slow when number of shoots increases #backend = 'ibmqx_hpc_qasm_simulator' print("Your choice for the backend is: ", backend) # Define a F_gate def F_gate(circ,q,i,j,n,k) : theta = np.arccos(np.sqrt(1/(n-k+1))) circ.ry(-theta,q[j]) circ.cz(q[i],q[j]) circ.ry(theta,q[j]) circ.barrier(q[i]) # Define the cxrv gate which uses reverse CNOT instead of CNOT def cxrv(circ,q,i,j) : circ.h(q[i]) circ.h(q[j]) circ.cx(q[j],q[i]) circ.h(q[i]) circ.h(q[j]) circ.barrier(q[i],q[j]) #"CIRCUITS" q = Q_program.create_quantum_register("q", 16) c = Q_program.create_classical_register("c", 16) twin = Q_program.create_circuit("twin", [q], [c]) # First W state twin.x(q[14]) F_gate(twin,q,14,3,3,1) F_gate(twin,q,3,2,3,2) twin.cx(q[3],q[14]) twin.cx(q[2],q[3]) #Second W state twin.x(q[12]) F_gate(twin,q,12,5,3,1) F_gate(twin,q,5,6,3,2) cxrv(twin,q,5,12) twin.cx(q[6],q[5]) #Coin tossing twin.h(q[0]) twin.h(q[1]) switch1 = Q_program.create_circuit('switch1',[q],[c]) #Stick or switch switch1.h(q[13]) for i in range (4) : switch1.measure(q[i] , c[i]); for i in range (5,7) : switch1.measure(q[i] , c[i]); for i in range (12,15) : switch1.measure(q[i] , c[i]); Q_program.add_circuit("AliceBob", twin+switch1) Label = ["left", "central", "right"] wstates = 0 while wstates != 1: time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print("Alice vs Bob", "backend=", backend, "starting time", time_exp) result = Q_program.execute("AliceBob", backend=backend, shots=1, max_credits=5, wait=5, timeout=120) time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print("Alice vs Bob", "backend=", backend, " end time", time_exp) cstr = str(result.get_counts("AliceBob")) nb_of_cars = int(cstr[3]) + int(cstr[14]) + int(cstr[15]) nb_of_doors = int(cstr[12]) + int(cstr[11]) + int(cstr[5]) wstates = nb_of_cars * nb_of_doors print(" ") print('Alice: One car and two goats are now hidden behind these doors.') print(' Which door do you choose?') print(" ") "Chosing the left door" if int(cstr[5]) == 1: Doorchosen = 1 "Chosing the center door" if int(cstr[11]) == 1: Doorchosen = 2 "Chosing the right door" if int(cstr[12]) == 1: Doorchosen = 3 time.sleep(2) print('Bob: My choice is the',Label[Doorchosen-1], "door") print(" ") randomnb = int(cstr[16]) + int(cstr[17]) %2 if cstr[3] == "1": #car behind left door Doorwinning = 1 if Doorchosen == 1: Dooropen = 2 + randomnb Doorswitch = 3 - randomnb if Doorchosen == 2: Dooropen = 3 Doorswitch = 1 if Doorchosen == 3: Dooropen = 2 Doorswitch = 1 if cstr[14] == "1": #car behind central door Doorwinning = 2 if Doorchosen == 2: Dooropen = 1 + 2*randomnb Doorswitch = 3 - 2*randomnb if Doorchosen == 1: Dooropen = 3 Doorswitch = 2 if Doorchosen == 3: Dooropen = 1 Doorswitch = 2 if cstr[15] == "1": #car behind right door Doorwinning = 3 if Doorchosen == 3: Dooropen = randomnb + 1 Doorswitch = 2 - randomnb if Doorchosen == 1: Dooropen = 2 Doorswitch = 3 if Doorchosen == 2: Dooropen = 1 Doorswitch = 3 time.sleep(2) print('Alice: Now I open the', Label[Dooropen-1], 'door and you see a goat') time.sleep(2) print(' You get an opportunity to change your choice!') time.sleep(2) print(' Do you want to switch for the',Label[Doorswitch-1], "door?") print(" ") time.sleep(2) switch_flag = int(cstr[4]) "BOB STICKS WITH HIS FIRST CHOICE!" if switch_flag == 0: Doorfinal = Doorchosen print('Bob: I stick with my first choice, the',Label[Doorfinal-1], "door") "BOB CHANGES HIS MIND!" if switch_flag == 1: Doorfinal = Doorswitch print('Bob: I change my mind and choose the',Label[Doorfinal-1], "door") "FINAL ANNOUNCE" if Doorfinal == Doorwinning: endmessage = 'won the car! Congratulations!' else: endmessage = 'won a goat! Sorry!' time.sleep(2) print() print('Alice: You opened the',Label[Doorfinal-1],'door and', endmessage) print("Game over") #Toffoli gates Toffoli = Q_program.create_circuit('Toffoli',[q],[c]) Toffoli.ccx(q[3], q[5], q[4]) Toffoli.swap(q[2],q[3]) Toffoli.swap(q[6],q[5]) Toffoli.ccx(q[3], q[5], q[4]) Toffoli.swap(q[3],q[14]) Toffoli.swap(q[12],q[5]) Toffoli.ccx(q[3], q[5], q[4]) # A general solution with 50% switching strategy switch_fifty_percent = Q_program.create_circuit('switch_fifty_percent',[q],[c]) #switch flag switch_fifty_percent.h(q[13]) switch_fifty_percent.cx(q[13],q[4]) switch_fifty_percent.measure(q[4] , c[4]); switch_fifty_percent.measure(q[13] , c[13]); Q_program.add_circuit("general_solution", twin+Toffoli+switch_fifty_percent) circuits = ['general_solution'] shots = 1024 time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print(backend, "shots", shots, "starting time", time_exp) result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=5, wait=30, timeout=600) time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print(backend, "shots", shots, "end time", time_exp) plot_histogram(result.get_counts("general_solution")) print(result.get_counts("general_solution")) observable_stickwon = {'0000000000010000': 1, '0010000000010000': 0, '0010000000000000': 0, '0000000000000000': 0} observable_switchwon = {'0000000000010000': 0, '0010000000010000': 1, '0010000000000000': 0, '0000000000000000': 0} observable_stickall = {'0000000000010000': 1, '0010000000010000': 0, '0010000000000000': 0, '0000000000000000': 1} observable_switchall = {'0000000000010000': 0, '0010000000010000': 1, '0010000000000000': 1, '0000000000000000': 0} stickwon = result.average_data("general_solution",observable_stickwon) switchwon = result.average_data("general_solution",observable_switchwon) stickall = result.average_data("general_solution",observable_stickall) switchall = result.average_data("general_solution",observable_switchall) print("Proportion sticking: %6.2f " % stickall) print("Proportion switching: %6.2f " % switchall) stickwon_stickall = stickwon/stickall switchwon_switchall = switchwon/switchall print("Proportion winning when sticking: %6.2f " % stickwon_stickall) print("Proportion winning when switching: %6.2f " % switchwon_switchall) # Illustrating different strategies xdat = [] ydat = [] observable = {'0000000000000000': 0, '0000000000010000': 1} shots = 1024 time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print(backend, "shots", shots, "starting time", time_exp) for i in range(9) : strategies = Q_program.create_circuit('strategies',[q],[c]) Prob = i/8 lambda_s = 2*np.arcsin(np.sqrt(Prob)) strategies.rx(lambda_s,q[13]) strategies.cx(q[13],q[4]) strategies.measure(q[4] , c[4]); statploti = "statplot"+str(i) Q_program.create_circuit("statploti",[q],[c]) Q_program.add_circuit("statploti",twin+Toffoli+strategies) result = Q_program.execute("statploti", backend=backend, shots=shots, max_credits=5, wait=30, timeout=600) loop_average=(result.average_data("statploti",observable)) print(statploti," Proportion switching: %6.3f" % Prob, " Proportion winning: %6.2f" % loop_average) ydat.append(loop_average) xdat.append(Prob) time_exp = time.strftime('%d/%m/%Y %H:%M:%S') print(backend, "shots", shots, "end time", time_exp) plt.plot(xdat, ydat, 'ro') plt.grid() plt.ylabel('Probability of Winning', fontsize=12) plt.xlabel(r'Probability of Switching', fontsize=12) plt.show() print("Our Advice: \n") y_aver = [] for j in range(0,7,3) : y_aver.append((ydat[j] + ydat[j+1] +ydat[j+2])/3) if y_aver[0] == max(y_aver) : print(" Thou Shalt Not Switch") elif y_aver[2] == max(y_aver) : print(" Thou Shalt Not Stick") else: print(" Just follow the intuition of the moment") %run "../version.ipynb"
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
pip install qiskit # Useful packages for the next gates experiments import numpy as np from qiskit import QuantumCircuit, QuantumRegister from qiskit import execute from qiskit.tools.visualization import circuit_drawer from qiskit import Aer backend = Aer.get_backend('unitary_simulator') # Pauli X : bit-flip gate q = QuantumRegister(1) qc = QuantumCircuit(q) qc.x(q) im = circuit_drawer(qc) im.save("GateX.png", "PNG") job = execute(qc, backend) print(np.round(job.result().get_data(qc)['unitary'], 3)) # Pauli Y : bit and phase-flip gate q = QuantumRegister(1) qc = QuantumCircuit(q) qc.y(q) im = circuit_drawer(qc) im.save("GateY.png", "PNG") job = execute(qc, backend) print(np.round(job.result().get_data(qc)['unitary'], 3)) # Pauli Z : phase-flip gate q = QuantumRegister(1) qc = QuantumCircuit(q) qc.z(q) im = circuit_drawer(qc) im.save("GateZ.png", "PNG") job = execute(qc, backend) print(np.round(job.result().get_data(qc)['unitary'], 3)) # Clifford Hadamard gate q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) im = circuit_drawer(qc) im.save("GateH.png", "PNG") job = execute(qc, backend) print(np.round(job.result().get_data(qc)['unitary'], 3)) # Clifford S gate q = QuantumRegister(1) qc = QuantumCircuit(q) qc.s(q) im = circuit_drawer(qc) im.save("GateS.png", "PNG") job = execute(qc, backend) print(np.round(job.result().get_data(qc)['unitary'], 3)) # Clifford T gate q = QuantumRegister(1) qc = QuantumCircuit(q) qc.t(q) im = circuit_drawer(qc) im.save("GateT.png", "PNG") job = execute(qc, backend) print(np.round(job.result().get_data(qc)['unitary'], 3)) # Pauli Controlled-X (or, controlled-NOT) gate q = QuantumRegister(2) qc = QuantumCircuit(q) qc.cx(q) im = circuit_drawer(qc) im.save("GateCX.png", "PNG") job = execute(qc, backend) print(np.round(job.result().get_data(qc)['unitary'], 3)) # Pauli Controlled Z (or, controlled Phase) gate q = QuantumRegister(2) qc = QuantumCircuit(q) qc.cz(q) im = circuit_drawer(qc) im.save("GateCZ.png", "PNG") job = execute(qc, backend) print(np.round(job.result().get_data(qc)['unitary'], 3)) # SWAP gate q = QuantumRegister(2) qc = QuantumCircuit(q) qc.swap(q) im = circuit_drawer(qc) im.save("GateSWAP.png", "PNG") job = execute(qc, backend) print(np.round(job.result().get_data(qc)['unitary'], 3)) # Toffoli gate (ccx gate) q = QuantumRegister(3) qc = QuantumCircuit(q) qc.ccx(q) im = circuit_drawer(qc) im.save("GateCCX.png", "PNG") job = execute(qc, backend) print(np.round(job.result().get_data(qc)['unitary'], 3)) from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit, execute from qiskit.tools.visualization import plot_histogram, circuit_drawer # Create a Quantum Register called "qr" with 2 qubits. qr = QuantumRegister(2) # Create a Classical Register called "cr" with 2 bits. cr = ClassicalRegister(2) # Create a Quantum Circuit called "qc" with qr and cr. qc = QuantumCircuit(qr, cr) # Add the H gate in the Qubit 1, putting this qubit in superposition. qc.h(qr[1]) # Add the CX gate on control qubit 1 and target qubit 0, putting the qubits in a Bell state i.e entanglement. qc.cx(qr[1], qr[0]) # Add a Measure gate to see the state. qc.measure(qr, cr) # Compile and execute the quantum program in the local simulator. job_sim = execute(qc, "qasm_simulator") stats_sim = job_sim.result().get_counts() # Plot and print results. plot_histogram(stats_sim) print(stats_sim) im = circuit_drawer(qc) im.save("circuit.png", "PNG") from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit, execute from qiskit.tools.visualization import plot_histogram import matplotlib.pyplot as plt # 3 bitStrings, one for each symbol : )( #":" 00111010 "(" 00101000 ")" 00101001 # Create a Quantum Register called "qr" with 16 qubits. qr = QuantumRegister(16) # Create a Classical Register called "cr" with 16 bits. cr = ClassicalRegister(16) # Create a Quantum Circuit called "qc" with qr and cr. qc = QuantumCircuit(qr, cr) # Add the H gate in the 0 Qubit, putting the qubit in superposition. qc.h(qr[0]) qc.x(qr[3]) qc.x(qr[5]) qc.x(qr[9]) qc.x(qr[11]) qc.x(qr[12]) qc.x(qr[13]) for j in range(16): qc.measure(qr[j], cr[j]) # Compile and execute the quantum program in the local simulator. shots_sim = 128 job_sim = execute(qc, "qasm_simulator", shots=shots_sim) stats_sim = job_sim.result().get_counts() # Plot and print results. plot_histogram(stats_sim) print(stats_sim) def plotSmiley (stats, shots): for bitString in stats: char = chr(int(bitString[0:8],2)) # 8 bits (left), convert to an ASCII character. char += chr(int(bitString[8:16],2)) # 8 bits (right), add it to the previous character. prob = stats[bitString]/shots # Fraction of shots the result occurred plt.annotate(char, (0.5,0.5), va="center", ha="center", color = (0,0,0,prob), size = 300) # Create plot. plt.axis("off") plt.show() plotSmiley(stats_sim, shots_sim) from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit, execute # E.g. number 21 in binary. number = "10101" # Initializing the registers. # Create a Quantum Register called "qr" with length number qubits. qr = QuantumRegister(len(str(number))) # Create a Classical Register called "cr" with length number bits. cr = ClassicalRegister(len(str(number))) # Create a Quantum Circuit called "qc" with qr and cr. qc = QuantumCircuit(qr, cr) # Setting up the registers using the value inputted. for i in range(len(str(number))): if number[i] == "1": qc.x(qr[len(str(number)) - (i+1)]) #Flip the qubit from 0 to 1. #Measure qubits and store results in classical register cr. for i in range(len(str(number))): qc.measure(qr[i], cr[i]) # Compile and execute the quantum program in the local simulator. job_sim = execute(qc, "qasm_simulator") stats_sim = job_sim.result().get_counts() # Print number. print(stats_sim) # Boolean binary string adder. def rjust_lenght(s1, s2, fill='0'): l1, l2 = len(s1), len(s2) if l1 > l2: s2 = s2.rjust(l1, fill) elif l2 > l1: s1 = s1.rjust(l2, fill) return (s1, s2) def get_input(): bits_a = input('input your first binary string ') bits_b = input('input your second binary string ') return rjust_lenght(bits_a, bits_b) def xor(bit_a, bit_b): A1 = bit_a and (not bit_b) A2 = (not bit_a) and bit_b return int(A1 or A2) def half_adder(bit_a, bit_b): return (xor(bit_a, bit_b), bit_a and bit_b) def full_adder(bit_a, bit_b, carry=0): sum1, carry1 = half_adder(bit_a, bit_b) sum2, carry2 = half_adder(sum1, carry) return (sum2, carry1 or carry2) def binary_string_adder(bits_a, bits_b): carry = 0 result = '' for i in range(len(bits_a)-1 , -1, -1): summ, carry = full_adder(int(bits_a[i]), int(bits_b[i]), carry) result += str(summ) result += str(carry) return result[::-1] def main(): bits_a, bits_b = get_input() print('1st string of bits is : {}, ({})'.format(bits_a, int(bits_a, 2))) print('2nd string of bits is : {}, ({})'.format(bits_b, int(bits_b, 2))) result = binary_string_adder(bits_a, bits_b) print('summarized is : {}, ({})'.format(result, int(result, 2))) if __name__ == '__main__': main() from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit, execute from qiskit.tools.visualization import circuit_drawer # Initializing the registers. # Create a Quantum Registers. cin = QuantumRegister(1) a = QuantumRegister(4) b = QuantumRegister(4) cout = QuantumRegister(1) # Create a Classical Registers. ans = ClassicalRegister(5) # Create a Quantum Circuit called "qc". qc = QuantumCircuit(cin, a, b, cout, ans) # Set input states. x = "0001" #1 y = "1111" #15 # Setting up the registers using the value inputted. for i in range(len(str(x))): if x[i] == "1": qc.x(a[len(str(x)) - (i+1)]) #Flip the qubit from 0 to 1. for i in range(len(str(y))): if y[i] == "1": qc.x(b[len(str(y)) - (i+1)]) #Flip the qubit from 0 to 1. def majority(circ, a, b, c): circ.cx(c,b) circ.cx(c,a) circ.ccx(a,b,c) def unmaj(circ, a, b, c): circ.ccx(a,b,c) circ.cx(c,a) circ.cx(a,b) # Add a to b, storing result in b majority(qc,cin[0],b[0],a[0]) majority(qc,a[0],b[1],a[1]) majority(qc,a[1],b[2],a[2]) majority(qc,a[2],b[3],a[3]) qc.cx(a[3],cout[0]) unmaj(qc,a[2],b[3],a[3]) unmaj(qc,a[1],b[2],a[2]) unmaj(qc,a[0],b[1],a[1]) unmaj(qc,cin[0],b[0],a[0]) # Measure qubits and store results. for i in range(0, 4): qc.measure(b[i], ans[i]) qc.measure(cout[0], ans[4]) # Compile and execute the quantum program in the local simulator. num_shots = 2 # Number of times to repeat measurement. job = execute(qc, "qasm_simulator", shots=num_shots) job_stats = job.result().get_counts() # Print result number and circuit. print(job_stats) im = circuit_drawer(qc) im.save("circuitSum.png", "PNG") from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit, execute from qiskit.tools.visualization import circuit_drawer import numpy as np n1 = '10011' # E.g. number 19 n2 = '0011101' # E.g. number 29 if len(str(n1)) > len(str(n2)): n = len(str(n1)) else: n = len(str(n2)) # Initializing the registers. # Create a Quantum Registers called "qr1" and "qr2". qr1 = QuantumRegister(n+1) qr2 = QuantumRegister(n+1) # The classical register. cr = ClassicalRegister(n+1) # Create a Quantum Circuit called "qc". qc = QuantumCircuit(qr1, qr2, cr) length1 = len(n1) length2 = len(n2) # Set same length. if length2 > length1: n1,n2 = n2, n1 length2, length1 = length1, length2 n2 = ("0")*(length1-length2) + n2 # Set registers qr1 and qr2 to hold the two numbers. for i in range(len(str(n1))): if n1[i] == "1": qc.x(qr1[len(str(n1)) - (i+1)]) for i in range(len(str(n2))): if n2[i] == "1": qc.x(qr2[len(str(n2)) - (i+1)]) def qft(circ, q1, q2, n): # n-qubit QFT on q in circ. for i in range(0, n+1): qc.cu1(np.math.pi/float(2**(i)), q2[n-i], q1[n]) def invqft(circ, q, n): # Performs the inverse quantum Fourier transform. for i in range(0, n): qc.cu1(-np.math.pi/float(2**(n-i)), q[i], q[n]) qc.h(q[n]) def input_state(circ, q, n): # n-qubit input state for QFT. qc.h(q[n]) for i in range(0, n): qc.cu1(np.math.pi/float(2**(i+1)), q[n-(i+1)], q[n]) for i in range(0, n+1): input_state(qc, qr1, n-i) qc.barrier() for i in range(0, n+1): qft(qc, qr1, qr2, n-i) qc.barrier() for i in range(0, n+1): invqft(qc, qr1, i) qc.barrier() for i in range(0, n+1): qc.cx(qr1[i],qr2[i]) for i in range(0, n+1): qc.measure(qr1[i], cr[i]) # Compile and execute the quantum program in the local simulator. num_shots = 2 # Number of times to repeat measurement. job = execute(qc, "qasm_simulator", shots=num_shots) job_stats = job.result().get_counts() print(job_stats) im = circuit_drawer(qc) im.save("circuitAdderQFT.png", "PNG") from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit, execute from qiskit.tools.visualization import circuit_drawer # Initializing the registers. # Create a Quantum Registers. cin = QuantumRegister(1) a = QuantumRegister(2) b = QuantumRegister(2) cout = QuantumRegister(1) # Create a Classical Registers. ans = ClassicalRegister(3) # Create a Quantum Circuit called "qc". qc = QuantumCircuit(cin, a, b, cout, ans) # Set input states. x = "00" #0 y = "11" #3 # Setting up the registers using the value inputted. for i in range(len(str(x))): if x[i] == "1": qc.x(a[len(str(x)) - (i+1)]) #Flip the qubit from 0 to 1. for i in range(len(str(y))): if y[i] == "1": qc.x(b[len(str(y)) - (i+1)]) #Flip the qubit from 0 to 1. # Add a to b, storing result in b majority(qc,cin[0],b[0],a[0]) majority(qc,a[0],b[1],a[1]) qc.cx(a[1],cout[0]) unmaj(qc,a[0],b[1],a[1]) unmaj(qc,cin[0],b[0],a[0]) qc.cx(b[1],b[0]) qc.x(b[1]) # Measure qubits and store results. for i in range(0, 1): qc.measure(b[i], ans[i]) qc.measure(cout[0], ans[1]) # Compile and execute the quantum program in the local simulator. num_shots = 2 # Number of times to repeat measurement. job = execute(qc, "qasm_simulator", shots=num_shots) job_stats = job.result().get_counts() # Print result number and circuit. print(job_stats) im = circuit_drawer(qc) im.save("circuitAverage.png", "PNG") import matplotlib.pyplot as plt import numpy as np from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit, execute from qiskit.tools.visualization import plot_histogram, circuit_drawer n = 3 sat_formula = [[1,2,-3],[-1,-2,-3],[1,-2,3]] f_in = QuantumRegister(n) f_out = QuantumRegister(1) aux = QuantumRegister(len(sat_formula)+1) ans = ClassicalRegister(n) qc = QuantumCircuit(f_in, f_out, aux, ans) # Initializes all of the qbits. def input_state(circuit, f_in, f_out, n): for j in range(n): circuit.h(f_in[j]) circuit.x(f_out) circuit.h(f_out) # The back box U function (Oracle). def black_box_u_f(circuit, f_in, f_out, aux, n, sat_formula): num_claus = len(sat_formula) for(k,claus) in enumerate(sat_formula): for literal in claus: if literal > 0: circuit.cx(f_in[literal-1],aux[k]) else: circuit.x(f_in[-literal-1]) circuit.cx(f_in[-literal-1],aux[k]) circuit.ccx(f_in[0],f_in[1],aux[num_claus]) circuit.ccx(f_in[2],aux[num_claus],aux[k]) circuit.ccx(f_in[0],f_in[1],aux[num_claus]) for literal in claus: if literal < 0: circuit.x(f_in[-literal-1]) if(num_claus == 1): circuit.cx(aux[0], f_out[0]) elif(num_claus == 2): circuit.ccx(aux[0],aux[1],f_out[0]) elif(num_claus == 3): circuit.ccx(aux[0], aux[1], aux[num_claus]) circuit.ccx(aux[2], aux[num_claus], f_out[0]) circuit.ccx(aux[0], aux[1], aux[num_claus]) else: raise ValueError('Apenas 3 clausulas pf :)') for(k,claus) in enumerate(sat_formula): for literal in claus: if literal > 0: circuit.cx(f_in[literal-1],aux[k]) else: circuit.x(f_in[-literal-1]) circuit.cx(f_in[-literal-1],aux[k]) circuit.ccx(f_in[0], f_in[1], aux[num_claus]) circuit.ccx(f_in[2], aux[num_claus], aux[k]) circuit.ccx(f_in[0], f_in[1], aux[num_claus]) for literal in claus: if literal < 0: circuit.x(f_in[-literal-1]) # iInverts the qbit that was affected by the Oracle function. def inversion_about_average(circuit,f_in,n): for j in range(n): circuit.h(f_in[j]) for j in range(n): circuit.x(f_in[j]) n_controlled_z(circuit, [f_in[j] for j in range(n-1)], f_in[n-1]) for j in range(n): circuit.x(f_in[j]) for j in range(n): circuit.h(f_in[j]) def n_controlled_z(circuit,controls,target): if(len(controls) > 2): raise ValueError('erro de control') elif(len(controls) == 1): circuit.h(target) circuit.cx(controls[0],target) circuit.h(target) elif(len(controls) == 2): circuit.h(target) circuit.ccx(controls[0],controls[1],target) circuit.h(target) input_state(qc,f_in,f_out,n) black_box_u_f(qc,f_in,f_out,aux,n,sat_formula) inversion_about_average(qc,f_in,n) black_box_u_f(qc,f_in,f_out,aux,n,sat_formula) inversion_about_average(qc,f_in,n) for j in range(n): qc.measure(f_out[0],ans[j]) # Compile and execute the quantum program in the local simulator. job_sim = execute(qc, "qasm_simulator") stats_sim = job_sim.result().get_counts() # Plot and print results. print(stats_sim) plot_histogram(stats_sim) im = circuit_drawer(qc) im.save("circuitGrover.pdf", "PDF")
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from os import listdir as ld files = [ff for ff in ld('bronze') if ff[:1] == 'B'] sols = [ff for ff in ld('bronze-solutions') if ff[:1] == 'B'] files.sort() sols.sort() for ss in files: print('- ['+ss+'](bronze/'+ss+')') tt = [ff for ff in sols if ff[:3]==ss[:3]] if len(tt) > 0: print('<br> *solutions:* [`'+tt[0]+'`](bronze-solutions/'+tt[0]+')')
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# A jupyter notebook is composed by one or more cells. # A cell is used to write and execute your codes. # A cell is also used to write descriptions, notes, formulas, etc. # You can format your descriptions by using HTML or LaTex codes. # During this tutorial, you are expected to write only python codes. # Interested readers may also use HTML and LaTex, but it is not necesary to complete this tutorial. # # We explain basic usage of cells in Jupyter notebooks here # # This is the first cell in this notebook. # You can write Python code here, # and then EXECUTE/RUN it by # 1) pressing SHIFT+ENTER # 2) clicking "Run" on the menu # here is a few lines of python codes print("hello world") str="*" for i in range(5): print(str) str+="*" # after executing this cell, you will see the outcomes immedeately after this cell # you may change the range above and re-run this cell # after executing this cell, you can continue with the next cell # This is the second cell. # # When you double click after the last cell, a new cell appears automatically. # It automatically happens when you execute the last cell as well. # # By using menu item "Insert", you may also add a new cell before or after the selected cell. # When a cell is selected, you may delete it by using menu item "Edit". # # As you may notice, there are other editing options under "Edit", # for example, copy/cut-paste cells and split-merge cells.
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# I am a comment in python print("Hello From Quantum World :-)") # please run me from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from random import randrange # Create my circuit and register objects qreg = QuantumRegister(2) # my quantum register creg = ClassicalRegister(2) # my classical register circuit = QuantumCircuit(qreg,creg) # my quantum circuit # let's apply a Hadamard gate to the first qubit circuit.h(qreg[0]) # let's set the second qubit to |1> circuit.x(qreg[1]) # let's apply CNOT(first_qubit,second_qubit) circuit.cx(qreg[0],qreg[1]) # let's measure the both qubits circuit.measure(qreg,creg) print("The execution was completed, and the circuit was created :)") ## execute the circuit 100 times job = execute(circuit,Aer.get_backend('qasm_simulator'),shots=1024) # get the result counts = job.result().get_counts(circuit) print(counts) from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # draw the overall circuit drawer(circuit) # re-execute me if you DO NOT see the circuit diagram from qiskit import IBMQ IBMQ.save_account('write YOUR IBM API TOKEN here') # Then, execute this cell IBMQ.stored_accounts() IBMQ.load_accounts() IBMQ.active_accounts() IBMQ.backends() IBMQ.backends(operational=True, simulator=False) from qiskit.backends.ibmq import least_busy least_busy(IBMQ.backends(simulator=False)) backend = least_busy(IBMQ.backends(simulator=True)) backend.name() from qiskit import compile qobj = compile(circuit, backend=backend, shots=1024) job = backend.run(qobj) result = job.result() counts = result.get_counts() print(counts) backend_real = least_busy(IBMQ.backends(simulator=False)) backend_real.name() backend_real.status() qobj_real = compile(circuit, backend=backend_real, shots=1024) job_real = backend_real.run(qobj_real) job_real.queue_position() result_real = job_real.result() counts_real = result_real.get_counts() print(counts_real)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
number = 5 # integer real = -3.4 # float name = 'Asja' # string surname = "Sarkana" # string boolean1 = True # Boolean boolean1 = False # Boolean a = 13 b = 5 print("a =",a) print("b =",b) print() # basics operators print("a + b =",a+b) print("a - b =",a-b) print("a * b =",a*b) print("a / b =",a/b) a = 13 b = 5 print("a =",a) print("b =",b) print() # integer division print("a//b =",a//b) # modulus operator print("a mod b =",a % b) b = 5 print("b =",b) print() print("b*b =",b**2) print("b*b*b =",b**3) print("sqrt(b)=",b**0.5) # list mylist = [10,8,6,4,2] print(mylist) # tuple mytuple=(1,4,5,'Asja') print(mytuple) # dictionary mydictionary = { 'name' : "Asja", 'surname':'Sarkane', 'age': 23 } print(mydictionary) print(mydictionary['surname']) # list of the other objects or variables list_of_other_objects =[ mylist, mytuple, 3, "Asja", mydictionary ] print(list_of_other_objects) # length of a string print(len("Asja Sarkane")) # size of a list print(len([1,2,3,4])) # size of a dictionary mydictionary = { 'name' : "Asja", 'surname':'Sarkane', 'age': 23} print(len(mydictionary)) i = 10 while i>0: # while condition(s): print(i) i = i - 1 for i in range(10): # i is in [0,1,...,9] print(i) for i in range(-5,6): # i is in [-5,-4,...,0,...,4,5] print(i) for i in range(0,23,4): # i is in [0,4,8,12,16,20] print(i) for i in [3,8,-5,11]: print(i) for i in "Sarkane": print(i) # dictionary mydictionary = { 'name' : "Asja", 'surname':'Sarkane', 'age': 23, } for key in mydictionary: print("key is",key,"and its value is",mydictionary[key]) for a in range(4,7): # if condition(s) if a<5: print(a,"is less than 5") # elif conditions(s) elif a==5: print(a,"is equal to 5") # else else: print(a,"is greater than 5") # Logical operator "and" i = -3 j = 4 if i<0 and j > 0: print(i,"is negative AND",j,"is positive") # Logical operator "or" i = -2 j = 2 if i==2 or j == 2: print("i OR j is 2: (",i,",",j,")") # Logical operator "not" i = 3 if not (i==2): print(i,"is NOT equal to 2") # Operator "equal to" i = -1 if i == -1: print(i,"is EQUAL TO -1") # Operator "not equal to" i = 4 if i != 3: print(i,"is NOT EQUAL TO 3") # Operator "not equal to" i = 2 if i <= 5: print(i,"is LESS THAN OR EQUAL TO 5") # Operator "not equal to" i = 5 if i >= 1: print(i,"is GREATER THAN OR EQUAL TO 3") A =[ [1,2,3], [-2,-4,-6], [3,6,9] ] # print all print(A) print() # print list by list for list in A: print(list) list1 = [1,2,3] list2 = [4,5,6] #concatenation of two lists list3 = list1 + list2 print(list3) list4 = list2 + list1 print(list4) list = [0,1,2] list.append(3) print(list) list = list + [4] print(list) def summation_of_integers(n): summation = 0 for integer in range(n+1): summation = summation + integer return summation print(summation_of_integers(10)) print(summation_of_integers(20)) from random import randrange print(randrange(10),"is picked randomly between 0 and 9") print(randrange(-9,10),"is picked randomly between -9 and 9") print(randrange(0,20,3),"is picked randomly from the list [0,3,6,9,12,15,18]")
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# This is a comment # A comment is used for explanations/descriptions/etc. # Comments do not affect the programs # let's define an integer variable named a a = 5 # let's print its value print(a) # let's define three integer variables named a, b, and c a = 2 b = 4 c = a + b # summation of a and b # let's print their values together print(a,b,c) # a single space will automatically appears in between # let's print their values in reverse order print(c,b,a) # let's print their summation and multiplication print(a+b+c,a*b*c) # let's define variables with string/text values hw = "hello world" # we can use double quotes hqw = 'hello quantum world' # we can use single quotes # let's print them print(hw) print(hqw) # let's print them together by inserting another string in between print(hw,"and",hqw) # let's concatenate a few strings d = "Hello " + 'World' + " but " + 'Quantum' + "World" # let's print the result print(d) # let's print numeric and string values together print("a =",a,", b =",b,", a+b =",a+b) # let's subtract two numbers d = a-b print(a,b,d) # let's divide two numbers d = a/b print(a,b,d) # let's divide two integers over integers # the result is always an integer with possible integer remainder d = 33 // 6 print(d) # reminder/mod operator r = 33 % 6 # 33 mod 6 = 3 # or when 33 is divided by 6 over integers, the reminder is 3 # 33 = 5 * 6 + 3 # let's print the result print(r) # Booleen variables t = True f = False # let's print their values print(t,f) # print their negations print(not t) print("the negation of",t,"is",not t) print(not f) print("the negation of",f,"is",not f) # define a float variable d = -3.4444 # let's print its value and its square print(d, d * d) e = (23*13) - (11 * 15) print(e) # we can use more than one variable # left is the variable for the left part of the expression # we start with the multiplication inside the parathesis left = 34*11 # we continue with the substruction inside the parathesis # we reuse the variable named left left = 123 - left # we reuse left again for the multiplication with -3 left = -3 * left # right is the variable for the right part of the expression # we use the same idea here right = 23 * 15 right = 5 + right right = 4 * right # at the end, we use left for the result left = left + right # let's print the result print(left) # # your solution is here # # # your solution is here # # # your solution is here #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# let's print all numbers between 0 and 9 for i in range(10): print(i) # range(n) represents the list of all numbers from 0 to n-1 # i is the variable to take the values in the range(n) iteratively: 0, 1, ..., 9 in our example # let's write the same code in two lines for i in range(10): # do not forget to use colon print(i) # the second line is indented # that means the command in the second line will be executed inside the for-loop # any other code executed inside the for-loop must be intented in the same way #my_code_inside_for-loop_2 #my_code_inside_for-loop_3 #my_code_inside_for-loop_4 # now I am out of the scope of for-loop #my_code_outside_for-loop_1 #my_code_outside_for-loop_2 # let's calculate the summation 1+2+...+10 by using a for-loop # we use variable total for the total summation total = 0 for i in range(11): # do not forget to use colon total = total + i # total is updated by i in each iteration # alternatively the same assignment can shortly be written as total =+ i similar to languages C, C++, Java, etc. # now I am out of the scope of for-loop # let's print the latest value of total print(total) # let's calculate the summation 10+12+14+...+44 # we create a list having all numbers in the summation # for this purpose, this time we will use three parameters in range total = 0 for j in range(10,45,2): # the range is defined between 10 and 44, and the value of j will be increased by 2 after each iteration total += j # let's use the shorten version of total = total + j print(total) # let's calculate the summation 1+2+4+8+16+...+256 # remark that 256 = 2*2*...*2 (8 times) total = 0 current_number = 1 # this value will be multiplied by 2 after each iteration for k in range(9): total = total + current_number # current_number is 1 at the beginning, and its value will be doubled after each iteration current_number = 2 * current_number # let's double the value of the current_number for the next iteration # short version of the same assignment: current_number *= 2 as in the languages C, C++, Java, etc. # now I am out of the scope of for-loop # let's print the latest value of total print(total) # instead of a range, we can directly use a list for i in [1,10,100,1000,10000]: print(i) # instead of [...], we can also use (...) # but this time it is a tuple, not a list (keep in your mind that the values in a tuple cannot be changed) for i in (1,10,100,1000,10000): print(i) # let's create a range containing the multiples of 7 and between 10 and 91 for j in range(14,92,7): # 14 is the first multiple of 7 greater or equal to 10 # 91 should be in the range, and so we write 92 print(j) # let's create a range between 11 and 22 for i in range(11,23): print(i) # we can also use variables in range n = 5 for j in range(n,2*n): print(j) # we will print all numbers in {n,n+1,n+2,...,2n-1} # we can use a list of strings for name in ("Asja","Balvis","Fyodor"): print("Hello",name,":-)") # any range can be converted to a list L1 = list(range(10)) print(L1) L2 = list(range(55,200,11)) print(L2) # # your solution is here # # # your solution is here # # let's calculate the summation 1+2+4+8+...+256 by using a while-loop total = 0 i = 1 #while condition(s): # your_code1 # your_code2 # your_code3 while i < 257: # this loop iterates as long as i is less than 257 total = total + i i = i * 2 # i is doubled in each iteration, and so soon it will be greater than 256 print(total) # remember that we calculated this summation as 511 before L = [0,1,2,3,4,5,11] # this is a list containing 7 integer values i = 0 while i in L: # this loop will be iterated as long as i is in L print(i) i = i + 1 # the value of i iteratively increased, and so soon it will hit a value not in the list L # the loop is terminated after i is set to 6, because 6 is not in L # let's use negation in the condition of while-loop L = [10] # this list has a single element i = 0 while i not in L: # this loop will be iterated as long as i is not equal to 10 print(i) i = i+1 # the value of i will hit to 10 after ten iterations # let's rewrite the same loop by using a direct inequality i = 0 while i != 10: # "!=" is used for "not equal to" operator print(i) i=i+1 # let's rewrite the same loop by using negation of equality i = 0 while not (i == 10): # "==" is used for "equal to" operator print(i) i=i+1 # while-loop seems having more fun :-) # but we should be more careful when writing the condition(s)! # summation and n is zero at the beginning S = 0 n = 0 while S < 1000: # this loop will stop after S exceeds 999 (S = 1000 or S > 1000) n = n +1 S = S + n # let's print n and S print(n,S) # three examples for the operator "less than or equal to" #print (4 <= 5) #print (5 <= 5) #print (6 <= 5) # you may comment out the above three lines for executing and seeing the results # # your solution is here # # this is the code for including function randrange to our program from random import randrange # randrange(n) picks a number from the list [0,1,2,...,n-1] randomly #r = randrange(100) #print(r) # # your solution is here # # here is a schematic example for double nested loops #for i in range(10): # your_code1 # your_code2 # while j != 7: # your_code_3 # your_code_4 # # your solution is here #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# let's randomly pick a number between 0 and 9, and print its value if it is greater than 5 from random import randrange r = randrange(10) if r > 5: print(r) # when the condition (r > 5) is valid/true, the code (print(r)) will be executed # you may need to execute your code more than once to observe an outcome # repeat the same task four times, and also print the value of iteration variable (i) for i in range(4): r = randrange(10) # this code belongs to for-loop, and so it is indented if r > 5: # this code also belongs to for-loop, and so it is indented as well print("i=",i,"r=",r) # this code belongs to if-statement, and so it is indented with respect to if-statement # if you are unlucky (with probabability less than 13/100), you may still do not see any outcome in a single run # do the same task 100 times, and find the percentage of successful iteration (attempt) # an iteration (attempt) is successful if the randomly picked number is greater than 5 # the expected percentage is 40, because, out of 10 numbers, there are 4 numbers greater than 5 # but the experimental results differ success = 0 for i in range(100): r = randrange(10) if r > 5: success = success + 1 print(success,"%") # each run most probabily will give different percentage value # let's randomly pick a number between 0 and 9, and says whether it less than 6 or not # we use two conditionals here r = randrange(10) print("the picked number is ",r) if r < 6: print("it is less than 6") if r >= 6: print("it is greater than or equal to 6") # let's write the same code by using if-else r = randrange(10) print("the picked number is ",r) if r < 6: print("it is less than 6") else: # if the above condition (r<6) is False print("it is greater than or equal to 6") # # your solution is here # # # when there are many conditionals, we can use if-elif-else # # let's randomly pick an even number between 1 and 99 # then determine whether it is less than 25, between 25 and 50, between 51 and 75, or greater than 75. r = randrange(2,100,2) # randonmly pick a number in range {2,4,6,...,98}, which satisfies our condition # let's print this range to verify our claim print(list(range(2,100,2))) print() # print an empty line print("the picked number is",r) if r < 25: print("it is less than 25") elif r<=50: # if the above condition is False and my condition is True print("it is between 25 and 50") elif r<=75: # if both conditions above are False and my condition is True print("it is between 51 and 75") else: # if all conditions above are False print("it is greater than 75") # # your solution is here # # let's determine whether a randomly picked number between -10 and 100 is prime or not. # this is a good example for using more than one conditionals in different parts of the program # this is also an example for "break" command, which terminates any loop immediately r = randrange(-10,101) # pick a number between -10 and 100 print(r) # print is value if r < 2: print("it is NOT a prime number") # this is by definition elif r == 2: print("it is a PRIME number") # we already know this else: prime=True # we assume that r is prime, and try to falsify this assumption by looking for a divisor in the following loop for i in range(2,r): # check all integers between 2 and r-1 if r % i ==0: # if i divides r without any reminder (or reminder is zero), then r is not be a prime number print("it is NOT a prime number") prime=False # our assumption is falsifed break # TERMINATE the iteration immediately # we are out of if-scope # we are out of for-loop-scope if prime == True: # if our assumption is still True (if it was not falsied inside for-loop) print("it is a PRIME number") # this is an example to write a function # our function will return a Boolean value True or False def prime(number): # our function has one parameter if number < 2: return False # once return command is executed, we exit the function if number == 2: return True # because of return command, we can use "if" instead of "elif" if number % 2 == 0: return False # any even number greater than 2 is not prime, because it is divisible by 2 for i in range(3,number,2): # we can skip even integers if number % i == 0: return False # once we find a divisor of the number, we return False and exit the function return True # the number has passed all checks until now # because of return command, the program can be shorten # remark that this might not be a good choice everytime for readibility of codes # let's test our program by printing all prime numbers between -10 and 30 for i in range(-10,30): # we pass i to the function prime if prime(i): # the function prime(i) returns True or False print(i) # this code will be executed if i is prime, i.e., prime(i) returns True
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# here is a list holding all even numbers between 10 and 20 L = [10, 12, 14, 16, 18, 20] # let's print the list print(L) # let's print each element by using its index but in reverse order print(L[5],L[4],L[3],L[2],L[1],L[0]) # let's print the length (size) of list print(len(L)) # let's print each element and its index in the list # we use a for-loop and the number of iteration is determined by the length of the list # everthing is automatic :-) L = [10, 12, 14, 16, 18, 20] for i in range(len(L)): print(L[i],"is the element in our list with the index",i) # let's replace each number in the list with its double value L = [10, 12, 14, 16, 18, 20] # let's print the list before doubling print("the list before doubling",L) for i in range(len(L)): current_element=L[i] # get the value of the i-th element L[i] = 2 * current_element # update the value of the i-th element # let's shorten the replacing code #L[i] = 2 * L[i] # or #L[i] *= 2 # let's print the list after doubling print("the list after doubling",L) # after each exceution of this cell, the latest values will be doubled # so the values in the list will be exponentially increased # let's define two lists L1 = [1,2,3,4] L2 = [-5,-6,-7,-8] # two lists can be concatenated # the results is a new list print("the concatenation of L1 and L2 is",L1+L2) # the order of terms is important print("the concatenation of L2 and L1 is",L2+L1) # this is a different list than L1+L2 # we can add a new element to a list, which increases its length/size by 1 L = [10, 12, 14, 16, 18, 20] print(L,"the current length is",len(L)) # we add two values by showing two different methods # L.append(value) directly adds the value as a new element to the list L.append(-4) # we can also use concatenation operator + L = L + [-8] # here [-8] is a list with single element print(L,"the new length is",len(L)) # a list can be multiplied with an integer L = [1,2] # we can consider the multiplication of L by an integer # as a repeated summation (concatenation) of L by itself # L * 1 is the list itself # L * 2 is L + L (concatenation of L with itself) # L * 3 is L + L + L (concatenation of L with itself twice) # L * m is L + ... + L (concatenation of L with itself m-1 times) # L * 0 is the empty list # L * i is the same as i * L # let's print the different cases for i in range(6): print(i,"* L is",i*L) # this can be useful when initializing a list with the same value(s) # let's create a list of prime numbers less than 100 # here is a function determining whether a given number is prime or not def prime(number): if number < 2: return False if number == 2: return True if number % 2 == 0: return False for i in range(3,number,2): if number % i == 0: return False return True # end of function # let's start with an empty list L=[] # what can the length of this list be? print("my initial length is",len(L)) for i in range(2,100): if prime(i): L.append(i) # alternative methods: #L = L + [i] #L += [i] # print the final list print(L) print("my final length is",len(L)) # let's define the list with S(0) L = [0] # let's iteratively define n and S # initial values n = 0 S = 0 # the number of iteration N = 20 while n <= N: # we iterate all values from 1 to 20 n = n + 1 S = S + n L.append(S) # print the final list print(L) # # your solution is here # F = [1,1] # the following list stores certain information about Asja # name, surname, age, profession, height, weight, partner(s) if any, kid(s) if any, date ASJA = ['Asja','Sarkane',34,'musician',180,65.5,[],['Eleni','Fyodor'],"October 24, 2018"] print(ASJA) # Remark that an element of a list can be another list as well. # # your solution is here # # let's define a dictionary pairing a person with her/his age ages = { 'Asja':32, 'Balvis':28, 'Fyodor':43 } # let print all keys for person in ages: print(person) # let's print the values for person in ages: print(ages[person])
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# consider the following list with 4 elements L = [1,-2,0,5] print(L) # 3 * v v = [1,-2,0,5] print("v is",v) # we use the same list for the result for i in range(len(v)): v[i] = 3 * v[i] print("3v is",v) # -0.6 * u # reinitialize the list v v = [1,-2,0,5] for i in range(len(v)): v[i] = -0.6 * v[i] print("0.6v is",v) u = [-3,-2,0,-1,4] v = [-1,-1,2,-3,5] result=[] for i in range(len(u)): result.append(u[i]+v[i]) print("u+v is",result) # let's also print the result vector similar to a column vector print() # print an empty line print("the elements of u+v are") for j in range(len(result)): print(result[j]) from random import randrange # # your solution is here # #r=randrange(-10,11) # randomly pick a number from the list {-10,-9,...,-1,0,1,...,9,10} # # your solution is here # v = [-1,-3,5,3,1,2] length_square=0 for i in range(len(v)): print(v[i],":square ->",v[i]**2) # let's print each entry and its square value length_square = length_square + v[i]**2 # let's sum up the square of each entry length = length_square ** 0.5 # let's take the square root of the summation of the squares of all entries print("the summation is",length_square) print("then the length is",length) # for square root, we can also use built-in function math.sqrt print() # print an empty line from math import sqrt print("the sqaure root of",length_square,"is",sqrt(length_square)) # # your solution is here # # # your solution is here #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# let's define both vectors u = [-3,-2,0,-1,4] v = [-1,-1,2,-3,5] uv = 0; # summation is initially zero for i in range(len(u)): # iteratively access every pair with the same indices print("pairwise multiplication of the entries with index",i,"is",u[i]*v[i]) uv = uv + u[i]*v[i] # i-th entries are multiplied and then added to summation print() # print an empty line print("The inner product of",u,'and',v,'is',uv) # # your solution is here # # # your solution is here # # let's find the inner product of v and u v = [-4,0] u = [0,-5] result = 0; for i in range(2): result = result + v[i]*u[i] print("the inner product of u and v is",result) # we can use the same code v = [-4,3] u = [-3,-4] result = 0; for i in range(2): result = result + v[i]*u[i] print("the inner product of u and v is",result) # you may consider to write a function in python for innner product # # your solution is here # # # your solution is here #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# we can break lines when defining our list M = [ [8 , 0 , -1 , 0 , 2], [-2 , -3 , 1 , 1 , 4], [0 , 0 , 1 , -7 , 1], [1 , 4 , -2 , 5 , 9] ] # let's print matrix M print(M) # let's print M in matrix form, row by row for i in range(4): # there are 4 rows print(M[i]) M = [ [8 , 0 , -1 , 0 , 2], [-2 , -3 , 1 , 1 , 4], [0 , 0 , 1 , -7 , 1], [1 , 4 , -2 , 5 , 9] ] #let's print the element of M in the 1st row and the 1st column. print(M[0][0]) #let's print the element of M in the 3rd row and the 4th column. print(M[2][3]) #let's print the element of M in the 4th row and the 5th column. print(M[3][4]) # we use double nested for-loops N =[] # the result matrix for i in range(4): # for each row N.append([]) # create an empty sub-list for each row in the result matrix for j in range(5): # in row (i+1), for each column N[i].append(M[i][j]*-2) # we add new elements into the i-th sub-list # let's print M and N, and see the results print("I am M:") for i in range(4): print(M[i]) print() print("I am N:") for i in range(4): print(N[i]) # create an empty list for the result matrix K=[] for i in range(len(M)): # len(M) return the number of rows in M K.append([]) # we create a new row for K for j in range(len(M[0])): # len(M[0]) returns the number of columns in M K[i].append(M[i][j]+N[i][j]) # we add new elements into the i-th sublist/rows # print each matrix in a single line print("M=",M) print("N=",N) print("K=",K) from random import randrange # # your solution is here # M = [ [-2,3,0,4], [-1,1,5,9] ] N =[ [1,2,3], [4,5,6], [7,8,9] ] # # your solution is here # # matrix M M = [ [-1,0,1], [-2,-3,4], [1,5,6] ] # vector v v = [1,-3,2] # the result vector u u = [] # for each row, we do an inner product for i in range(3): # inner product for one row is initiated inner_result = 0 # this variable keeps the summation of the pairwise multiplications for j in range(3): # the elements in the i-th row inner_result = inner_result + M[i][j] * v[j] # inner product for one row is completed u.append(inner_result) print("M is") for i in range(len(M)): print(M[i]) print() print("v=",v) print() print("u=",u) # # your solution is here # # matrix M M = [ [-1,0,1], [-2,-1,2], [1,2,-2] ] # matrix N M = [ [0,2,1], [3,-1,-2], [-1,1,0] ] # matrix K K = [] # # your solution is here # # # your solution is here #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# vector v v = [1,2,3] # vector u u=[-2,3] vu = [] for i in range(len(v)): # Each element of v will be replaced for j in range(len(u)): # the vector u will come to the replaced place after multiplying with the entry there vu.append( v[i] * u[j] ) print("v=",v) print("u=",u) print("vu=",vu) # # your solution is here # # matrix M M = [ [-1,0,1], [-2,-1,2], [1,2,-2] ] # matrix N N = [ [0,2,1], [3,-1,-2], [-1,1,0] ] # MN will be (9x9)-dimensional matrix # let's prepare it as a zero matrix # this helps us to easily fill it MN=[] for i in range(9): MN.append([]) for j in range(9): MN[i].append(0) for i in range(3): # row of M for j in range(3): # column of M for k in range(3): # row of N for l in range(3): # column of N MN[i*3+k][3*j+l] = M[i][j] * N[k][l] print("M-tensor-N is") for i in range(9): print(MN[i]) # matrix M and N were defined above # matrix NM will be prepared as a (9x9)-dimensional zero matrix NM=[] for i in range(9): NM.append([]) for j in range(9): NM[i].append(0) for i in range(3): # row of N for j in range(3): # column of N for k in range(3): # row of M for l in range(3): # column of M NM[i*3+k][3*j+l] = N[i][j] * M[k][l] print("N-tensor-M is") for i in range(9): print(NM[i]) # # your solution is here # # # your solution is here #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# # A quantum circuit is composed by quantum and classical bits. # # here are the objects that we use to create a quantum circuit from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit # we use a quantum register to keep our quantum bits. qreg = QuantumRegister(1) # in this example we will use a single quantum bit # To get an information from a quantum bit, it must be measured. (More details will appear.) # The measurement result is stored classically. # Therefore, we also use a classical regiser with classical bits creg = ClassicalRegister(1) # in this example we will use a single classical bit # now we can define our quantum circuit # it is composed by a quantum and a classical register mycircuit = QuantumCircuit(qreg,creg) # we apply operators on quantum bits # operators are also called as gates # we apply NOT operator represented as "x" # operator is a part of the circuit, and we should specify the quantum bit as the parameter mycircuit.x(qreg[0]) # (quantum) bits are enumerated starting from 0 # NOT operator or x-gate is applied to the first qubit of the quantum register # let's run our codes until now, and then draw our circuit print("Everything looks fine, let's continue ...") # we use matplotlib_circuit_drawer # we shortly refer it as "drawer" in our codes from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # let's draw our circuit now drawer(mycircuit) # re-execute me if you DO NOT see the circuit diagram # measurement is defined by associating a quantum bit to a classical bit mycircuit.measure(qreg[0],creg[0]) # the result will be stored in the classical bit print("Everything looks fine, let's continue ...") # let's draw the circuit again to see how the measurement is defined drawer(mycircuit) # reexecute me if you DO NOT see the circuit diagram # we are done with design of our circuit # now we can execute it # we execute quantum circuits many times (WHY?) # we use method "execute" and object "Aer" from qiskit library from qiskit import execute, Aer # we create a job object for execution of the circuit # there are three parameters # 1. mycircuit # 2. beckend on which it will be executed: we will use local simulator # 3. how_many_times will it be executed, let's pick it as 1024 job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1024) # we can get the result of the outcome as follows counts = job.result().get_counts(mycircuit) print(counts) # usually quantum programs produce probabilistic outcomes # # My second quantum circuit # # we import all at once from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # we will use 4 quantum bits and 4 classical bits qreg2 = QuantumRegister(4) creg2 = ClassicalRegister(4) mycircuit2 = QuantumCircuit(qreg2,creg2) # I will apply x-gate to the first quantum bit twice mycircuit2.x(qreg2[0]) mycircuit2.x(qreg2[0]) # I will apply x-gate to the fourth quantum bit once mycircuit2.x(qreg2[3]) # I will apply x-gate to the third quantum bit three times mycircuit2.x(qreg2[2]) mycircuit2.x(qreg2[2]) mycircuit2.x(qreg2[2]) # I will apply x-gate to the second quantum bit four times mycircuit2.x(qreg2[1]) mycircuit2.x(qreg2[1]) mycircuit2.x(qreg2[1]) mycircuit2.x(qreg2[1]) # if the size of quantum and classical registers are the same, we can define measurements with a single line code mycircuit2.measure(qreg2,creg2) # then each quantum bit and classical bit is associated with respect to their indices # let's run our codes until now, and then draw our circuit print("Everything looks fine, let's continue ...") drawer(mycircuit2) # re-execute me if you DO NOT see the circuit diagram job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=500) counts = job.result().get_counts(mycircuit2) print(counts) def print_outcomes(counts): # takes a dictionary variable for outcome in counts: # for each key-value in dictionary reverse_outcome = '' for i in outcome: # each string can be considered as a list of characters reverse_outcome = i + reverse_outcome # each new symbol comes before the old symbol(s) print(reverse_outcome,"is observed",counts[outcome],"times") job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=1024) counts = job.result().get_counts(mycircuit2) # counts is a dictionary object in python print_outcomes(counts) from random import randrange n = 20 r=randrange(n) # pick a number from the list {0,1,...,n-1} print(r) # test this method by using a loop for i in range(10): print(randrange(n)) # # your solution is here #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# first we import a procedure for picking a random number from random import randrange # randrange(m) returns a number randomly from the list {0,1,...,m-1} # randrange(10) returns a number randomly from the list {0,1,...,9} # here is an example r=randrange(5) print("I picked a random number between 0 and 4, which is ",r) # # your solution is here # # first we import a procedure for picking a random number from random import randrange # # your solution is here #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# # OUR SOLUTION # # initial case # We assume that the probability of getting head is 1 at the beginning, # because Asja will start with one euro. prob_head = 1 prob_tail = 0 # # first coin-flip # # if the last result was head new_prob_head_from_head = prob_head * 0.6 new_prob_tail_from_head = prob_head * 0.4 # if the last result was tail # we know that prob_tail is 0 at the beginning # but we still keep these two lines to have the same code for each iteration new_prob_head_from_tail = prob_tail * 0.3 new_prob_tail_from_tail = prob_tail * 0.7 # update the probabilities at the end of coin toss prob_head = new_prob_head_from_head + new_prob_head_from_tail prob_tail = new_prob_tail_from_head + new_prob_tail_from_tail # # second coin-flip # # we do the same calculations new_prob_head_from_head = prob_head * 0.6 new_prob_tail_from_head = prob_head * 0.4 new_prob_head_from_tail = prob_tail * 0.3 new_prob_tail_from_tail = prob_tail * 0.7 prob_head = new_prob_head_from_head + new_prob_head_from_tail prob_tail = new_prob_tail_from_head + new_prob_tail_from_tail # # third coin-flip # # we do the same calculations new_prob_head_from_head = prob_head * 0.6 new_prob_tail_from_head = prob_head * 0.4 new_prob_head_from_tail = prob_tail * 0.3 new_prob_tail_from_tail = prob_tail * 0.7 prob_head = new_prob_head_from_head + new_prob_head_from_tail prob_tail = new_prob_tail_from_head + new_prob_tail_from_tail # print prob_head and prob_tail print("the probability of getting head",prob_head) print("the probability of getting tail",prob_tail) # # your solution is here #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# # You may use python for your calculations. # all_portions = [7,5,4,2,6,1]; from random import randrange # # your solution is here #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# # your solution is here # # # your solution is here # # operator for the test A = [ [0.4,0.6,0], [0.2,0.1,0.7], [0.4,0.3,0.3] ] # state for test v = [0.1,0.3,0.6] # # your solution is here # # the initial state initial = [0.5, 0, 0.5, 0] # probabilistic operator for symbol a A = [ [0.5, 0, 0, 0], [0.25, 1, 0, 0], [0, 0, 1, 0], [0.25, 0, 0, 1] ] # probabilistic operator for symbol b B = [ [1, 0, 0, 0], [0, 1, 0.25, 0], [0, 0, 0.5, 0], [0, 0, 0.25, 1] ] # # your solution is here #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # define a quantum register with one qubit qreg1 = QuantumRegister(1) # define a classical register with one bit # it stores the measurement result of the quantum part creg1 = ClassicalRegister(1) # define our quantum circuit mycircuit1 = QuantumCircuit(qreg1,creg1) # apply h-gate (Hadamard: quantum coin-flipping) to the first qubit mycircuit1.h(qreg1[0]) # measure the first qubit, and store the result in the first classical bit mycircuit1.measure(qreg1,creg1) print("Everything looks fine, let's continue ...") # draw the circuit drawer(mycircuit1) # reexecute me if you DO NOT see the circuit diagram # execute the circuit 10000 times in the local simulator job = execute(mycircuit1,Aer.get_backend('qasm_simulator'),shots=10000) counts1 = job.result().get_counts(mycircuit1) print(counts1) # print the outcomes # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # define a quantum register with one qubit qreg2 = QuantumRegister(1) # define a classical register with one bit # it stores the measurement result of the quantum part creg2 = ClassicalRegister(1) # define our quantum circuit mycircuit2 = QuantumCircuit(qreg2,creg2) # apply h-gate (Hadamard: quantum coin-flipping) to the first qubit mycircuit2.h(qreg2[0]) # apply h-gate (Hadamard: quantum coin-flipping) to the first qubit once more mycircuit2.h(qreg2[0]) # measure the first qubit, and store the result in the first classical bit mycircuit2.measure(qreg2,creg2) print("Everyhing looks fine, let's continue ...") # draw the circuit drawer(mycircuit2) # reexecute me if you DO NOT see the circuit diagram # execute the circuit 10000 times in the local simulator job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=10000) counts2 = job.result().get_counts(mycircuit2) print(counts2) # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # # your code is here #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# # you may use python #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# # your code is here or you may find the values by hand (in mind) # # # your solution is here #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# # your solution is here # # let's import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # let's import randrange for random choices from random import randrange # # your code is here #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # we use four pairs of two qubits in order to see all results at once # the first pair -> qubits with indices 0 and 1 # the second pair -> qubits with indices 2 and 3 # the third pair -> qubits with indices 4 and 5 # the fourth pair -> qubits with indices 6 and 7 qreg = QuantumRegister(8) creg = ClassicalRegister(8) mycircuit = QuantumCircuit(qreg,creg) # the first pair is already in |00> # the second pair is set to be in |01> mycircuit.x(qreg[3]) # the third pair is set to be in |10> mycircuit.x(qreg[4]) # the fourth pair is set to be in |11> mycircuit.x(qreg[6]) mycircuit.x(qreg[7]) # apply cx to each pair for i in range(0,8,2): # i = 0,2,4,6 mycircuit.cx(qreg[i],qreg[i+1]) # measure the quantum register mycircuit.measure(qreg,creg) print("Everything looks fine, let's continue ...") # draw the circuit drawer(mycircuit) # re-run this cell if you DO NOT see the circuit diagram # execute the circuit 1000 times in the local simulator job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1000) counts = job.result().get_counts(mycircuit) # print the reverse of the output for outcome in counts: reverse_outcome = '' for i in outcome: reverse_outcome = i + reverse_outcome print(reverse_outcome,"is observed",counts[outcome],"times") print() print("let's also split into the pairs") for i in range(0,8,2): print(reverse_outcome[i:i+2]) # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # import randrange for random choices from random import randrange # # your code is here # # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # # your code is here # # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # # your code is here #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer all_pairs = ['00','01','10','11'] for pair in all_pairs: # # your code is here #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # # your code is here # # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # # your code is here #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from random import randrange # randomly create a 2-dimensional quantum state def random_quantum_state(): first_entry = randrange(100) first_entry = first_entry/100 first_entry = first_entry**0.5 # we found the first value before determining its sign if randrange(2) == 0: first_entry = -1 * first_entry second_entry = 1 - (first_entry**2) second_entry = second_entry**0.5 if randrange(2) == 0: second_entry = -1 * second_entry return [first_entry,second_entry] from matplotlib.pyplot import plot, show, figure # import the useful tool for drawing figures in python figure(figsize=(6,6), dpi=60) # size of the figure plot(0,0,'bo') # point the origin (0,0) for i in range(100): quantum_state = random_quantum_state(); # random quantum state plot(quantum_state[0],quantum_state[1],'bo') # put a point for the quantum state show() # show the diagram # import the useful tool for drawing figures in python from matplotlib.pyplot import plot, show, figure, Circle, axis, gca, annotate, arrow, text figure(figsize=(6,6), dpi=80) # size of the figure gca().add_patch( Circle((0,0),1,color='black',fill=False) ) # define a circle plot(-1.3,0) plot(1.3,0) plot(0,1.3) plot(0,-1.3) # axes arrow(0,0,1.1,0,head_width=0.04, head_length=0.08) arrow(0,0,-1.1,0,head_width=0.04, head_length=0.08) arrow(0,0,0,-1.1,head_width=0.04, head_length=0.08) arrow(0,0,0,1.1,head_width=0.04, head_length=0.08) show() # show the diagram def rotations(rotation_angle,number_of_rotations): # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # import the useful tool for drawing figures in python from matplotlib.pyplot import plot, show, figure, Circle, axis, gca, annotate, arrow, text # import the constant pi from math import pi # we define a quantum circuit with one qubit and one bit qreg1 = QuantumRegister(1) # quantum register with a single qubit creg1 = ClassicalRegister(1) # classical register with a single bit mycircuit1 = QuantumCircuit(qreg1,creg1) # quantum circuit with quantum and classical registers # create the plane figure(figsize=(6,6), dpi=80) # size of the figure gca().add_patch( Circle((0,0),1,color='black',fill=False) ) # draw the circle # auxiliary points plot(-1.3,0) plot(1.3,0) plot(0,1.3) plot(0,-1.3) # axes arrow(0,0,1.1,0,head_width=0.04, head_length=0.08) arrow(0,0,-1.1,0,head_width=0.04, head_length=0.08) arrow(0,0,0,-1.1,head_width=0.04, head_length=0.08) arrow(0,0,0,1.1,head_width=0.04, head_length=0.08) # end of create the plane for i in range(number_of_rotations): # iteratively apply the rotation mycircuit1.ry(2*rotation_angle,qreg1[0]) # the following code is used to get the quantum state of the quantum register job = execute(mycircuit1,Aer.get_backend('statevector_simulator')) current_quantum_state=job.result().get_statevector(mycircuit1) x_value = current_quantum_state[0].real # get the amplitude of |0> y_value = current_quantum_state[1].real # get the amplitude of |1> # show the quantum state as an arrow on the diagram arrow(0,0,x_value,y_value,head_width=0.04, head_length=0.08,color='blue') # the following code is used to indicate the rotation number if x_value<0: text_x_value=x_value-0.1 else: text_x_value=x_value+0.1 if y_value<0: text_y_value=y_value-0.1 else: text_y_value=y_value+0.1 text(text_x_value,text_y_value,'r='+str(i+1)) # end of for-loop show() # show the diagram #end of function print("function 'rotations' is defined now, and so it can be used in the following part") # call function rotations 8 times with angle pi/4 # import the constant pi from math import pi rotations(pi/4,8) # # your code is here # # # your code is here # # # your code is here # # # your code is here # # # your code is here # # # your code is here #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from math import acos # acos is the inverse of function cosine from math import pi def angle_between_two_quantum_states(quantum_state1,quantum_state2): inner_product = quantum_state1[0] * quantum_state2[0] + quantum_state1[1] * quantum_state2[1] return acos(inner_product) print("function 'angle_between_two_quantum_states' is defined now, and so it can be used in the following part") print("the angle between |0> and |1> is pi/2 (90 degree)") print(angle_between_two_quantum_states([1,0],[0,1]),"is the angle between |0> and |1>") print(pi/2,"is the value of pi/2") print() print("the angle between |0> and the quantum state [3/5,4/5] is around 0.295*pi") print(angle_between_two_quantum_states([3/5,4/5],[1,0]),"is the angle between |0> and the quantum state [3/5,4/5]") print(0.295*pi,"is the value of 0.295*pi") print() print("the angle between |0> and quantum state [-1/(2**0.5),-1/(2**0.5)] is 3pi/4 (135 degree)") print(angle_between_two_quantum_states([-1/(2**0.5),-1/(2**0.5)],[1,0]),"is the angle between |0> and quantum state [-1/(2**0.5),-1/(2**0.5)]") print(3*pi/4,"is the value of 3*pi/4",) print() # # OPTIONAL # # you may also test the function angle_between_two_quantum_states # from random import randrange # randomly create a quantum state of a qubit def random_quantum_state(): first_entry = randrange(100) first_entry = first_entry/100 first_entry = first_entry**0.5 if randrange(2) == 0: # determine the sign of the first entry first_entry = -1 * first_entry second_entry = 1 - (first_entry**2) second_entry = second_entry**0.5 # the second entry cannot be nonnegative if randrange(2) == 0: # determine the sign second_entry = -1 * second_entry return [first_entry,second_entry] print("function 'random_quantum_state' is defined now, and so it can be used in the following part") from math import pi def find_angle_of_a_quantum_state(quantum_state): # find the angle between quantum_state and [1,0] angle = angle_between_two_quantum_states(quantum_state,[1,0]) if quantum_state[1] < 0: # the angle is greater than pi angle = 2 * pi - angle return angle print("function 'find_angle_of_a_quantum_state' is defined now, and so it can be used in the following part") # find the angles of |0>, |1>, -|0>, and -|1> print(find_angle_of_a_quantum_state([1,0]),"is the angle of |0>, which should be 0*pi=",0*pi) print(find_angle_of_a_quantum_state([0,1]),"is the angle of |1>, which should be pi/2=",pi/2) print(find_angle_of_a_quantum_state([-1,0]),"is the angle of -|0>, which should be pi=",pi) print(find_angle_of_a_quantum_state([0,-1]),"is the angle of -|1>, which should be 3*pi/2=",3*pi/2) print() # find the angle of H|0> = [1/2**0.5,1/2**0.5] print(find_angle_of_a_quantum_state([1/2**0.5,1/2**0.5]),"is the angle of H|0>, which should be pi/4=",pi/4) # find the angle of [-1/2**0.5,1/2**0.5], which is pi/2 more than the previous angle print(find_angle_of_a_quantum_state([-1/2**0.5,1/2**0.5]),"is pi/2 more than the previous angle, which should be 3*pi/4=",3*pi/4) # find the angle of [-1/2**0.5,-1/2**0.5], which is pi/2 more than the previous angle print(find_angle_of_a_quantum_state([-1/2**0.5,-1/2**0.5]),"is pi/2 more than the previous angle, which should be 5*pi/4=",5*pi/4) # find the angle of [-1/2**0.5,1/2**0.5], which is pi/2 more than the previous angle print(find_angle_of_a_quantum_state([1/2**0.5,-1/2**0.5]),"is pi/2 more than the previous angle, which should be 7*pi/4=",7*pi/4) def visualize_quantum_states(quantum_states): # import the useful tool for drawing figures in pythpn from matplotlib.pyplot import plot, show, figure, Circle, axis, gca, annotate, arrow, text # import the constant pi from math import pi figure(figsize=(6,6), dpi=80) # size of the figure gca().add_patch( Circle((0,0),1,color='black',fill=False) ) # draw the circle # auxiliary points plot(-1.3,0) plot(1.3,0) plot(0,1.3) plot(0,-1.3) # axes arrow(0,0,1.1,0,head_width=0.04, head_length=0.08) arrow(0,0,-1.1,0,head_width=0.04, head_length=0.08) arrow(0,0,0,-1.1,head_width=0.04, head_length=0.08) arrow(0,0,0,1.1,head_width=0.04, head_length=0.08) # draw all quantum states for quantum_state in quantum_states: # show the quantum state as an arrow on the diagram state_name = quantum_state[0] # label of the quantum state x_value = quantum_state[1] # amplitude of |0> y_value = quantum_state[2] # amplitude of |1> # draw the arrow arrow(0,0,x_value,y_value,head_width=0.04, head_length=0.04,color='blue') # the following code is used to write the name of quantum states if x_value<0: text_x_value=x_value-0.1 else: text_x_value=x_value+0.05 if y_value<0: text_y_value=y_value-0.1 else: text_y_value=y_value+0.05 text(text_x_value,text_y_value,state_name) show() # show the diagram # end of function print("function 'visualize_quantum_states' is defined now, and so it can be used in the following part") # define a list of three quantum states with their labels all_quantum_states =[ ['u',-1/2**0.5,-1/2**0.5], ['v',3/5,4/5], ['|1>',0,1] ] # visualize all quantum states visualize_quantum_states(all_quantum_states) def amplitudes_of_a_quantum_state(quantum_circuit): # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # the following code is used to get the quantum state of a quantum circuit job = execute(quantum_circuit,Aer.get_backend('statevector_simulator')) current_quantum_state=job.result().get_statevector(quantum_circuit) # now we read the real parts of the amplitudes the_first_amplitude = current_quantum_state[0].real # amplitude of |0> the_second_amplitude = current_quantum_state[1].real # amplitude of |1> return[the_first_amplitude,the_second_amplitude] # end of function def reflection_game(): # randomly construct u u = random_quantum_state() print("u is",u) # randomly construct v v = random_quantum_state() print("v is",v) print() # the angle representing u uniquely angle_of_u = find_angle_of_a_quantum_state(u) print("the angle uniquely representing u is",angle_of_u,"=",angle_of_u/pi*180,"degrees") # the angle representing v uniquely angle_of_v = find_angle_of_a_quantum_state(v) print("the angle uniquely representing v is",angle_of_v,"=",angle_of_v/pi*180,"degrees") # the angle between u and v angle_between_u_and_v = angle_of_u-angle_of_v print("the angle between u and v is",angle_between_u_and_v,"=",angle_between_u_and_v/pi*180,"degrees") # # # we find |u>, |v>, and |uv> by writing a quantum program # # # start in |0> # rotate with u_angle to find |u> # rotate with -angle_between_u_and_v to find |v> # rotate with -angle_between_u_and_v once more to find the reflection of |u> over the axis |v> # we use ry-gatefor the rotations # COPY-PASTE from the previous programs # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # we define a quantum circuit with one qubit and one bit qreg1 = QuantumRegister(1) # quantum register with a single qubit creg1 = ClassicalRegister(1) # classical register with a single bit mycircuit1 = QuantumCircuit(qreg1,creg1) # quantum circuits with quantum and classical registers # store all quantum states with their labels all_quantum_states = [ ['0',1,0] # start with |0> ] print()# print an empty line # 1) # already started in |0> # rotate with angle_of_u to find |u> mycircuit1.ry(2*angle_of_u,qreg1[0]) # get the amplitudes of the current quantum state [x_value,y_value] = amplitudes_of_a_quantum_state(mycircuit1) all_quantum_states.append(['u',x_value,y_value]) # add the quantum state u # 2) # rotate with -angle_between_u_and_v to find |v> mycircuit1.ry(-2*angle_between_u_and_v,qreg1[0]) # get the amplitudes of the current quantum state [x_value,y_value] = amplitudes_of_a_quantum_state(mycircuit1) all_quantum_states.append(['v',x_value,y_value]) # add the quantum state v # 3) # rotate with -angle_between_u_and_v once more to find the reflection of |u> over the axis |v> mycircuit1.ry(-2*angle_between_u_and_v,qreg1[0]) # get the amplitudes of the current quantum state [x_value,y_value] = amplitudes_of_a_quantum_state(mycircuit1) all_quantum_states.append(['uv',x_value,y_value]) # add the quantum state uv print("all quantum states:") print(all_quantum_states) # visualize all quantum states visualize_quantum_states(all_quantum_states) # end of function print("function 'reflection game' is defined now, and so it can be used in the following part") # game 1 reflection_game() # game 2 reflection_game() # game 3 reflection_game() # game 4 reflection_game() # game 5 reflection_game() # games 6 - 20 for i in range(6,21): reflection_game()
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # # your solution is here # # # your solution # # # your code is here #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# A jupyter notebook is composed by one or more cells. # A cell is used to write and execute your codes. # A cell is also used to write descriptions, notes, formulas, etc. # You can format your descriptions by using HTML or LaTex codes. # During this tutorial, you are expected to write only python codes. # Interested readers may also use HTML and LaTex, but it is not necesary to complete this tutorial. # # We explain basic usage of cells in Jupyter notebooks here # # This is the first cell in this notebook. # You can write Python code here, # and then EXECUTE/RUN it by # 1) pressing SHIFT+ENTER # 2) clicking "Run" on the menu # here is a few lines of python codes print("hello world") str="*" for i in range(5): print(str) str+="*" # after executing this cell, you will see the outcomes immedeately after this cell # you may change the range above and re-run this cell # after executing this cell, you can continue with the next cell # This is the second cell. # # When you double click after the last cell, a new cell appears automatically. # It automatically happens when you execute the last cell as well. # # By using menu item "Insert", you may also add a new cell before or after the selected cell. # When a cell is selected, you may delete it by using menu item "Edit". # # As you may notice, there are other editing options under "Edit", # for example, copy/cut-paste cells and split-merge cells.
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# I am a comment in python print("Hello From Quantum World :-)") # please run me from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from random import randrange # Create my circuit and register objects qreg = QuantumRegister(2) # my quantum register creg = ClassicalRegister(2) # my classical register circuit = QuantumCircuit(qreg,creg) # my quantum circuit # let's apply a Hadamard gate to the first qubit circuit.h(qreg[0]) # let's set the second qubit to |1> circuit.x(qreg[1]) # let's apply CNOT(first_qubit,second_qubit) circuit.cx(qreg[0],qreg[1]) # let's measure the both qubits circuit.measure(qreg,creg) print("The execution was completed, and the circuit was created :)") ## execute the circuit 100 times job = execute(circuit,Aer.get_backend('qasm_simulator'),shots=1024) # get the result counts = job.result().get_counts(circuit) print(counts) from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # draw the overall circuit drawer(circuit) # re-execute me if you DO NOT see the circuit diagram from qiskit import IBMQ IBMQ.save_account('write YOUR IBM API TOKEN here') # Then, execute this cell IBMQ.stored_accounts() IBMQ.load_accounts() IBMQ.active_accounts() IBMQ.backends() IBMQ.backends(operational=True, simulator=False) from qiskit.backends.ibmq import least_busy least_busy(IBMQ.backends(simulator=False)) backend = least_busy(IBMQ.backends(simulator=True)) backend.name() from qiskit import compile qobj = compile(circuit, backend=backend, shots=1024) job = backend.run(qobj) result = job.result() counts = result.get_counts() print(counts) backend_real = least_busy(IBMQ.backends(simulator=False)) backend_real.name() backend_real.status() qobj_real = compile(circuit, backend=backend_real, shots=1024) job_real = backend_real.run(qobj_real) job_real.queue_position() result_real = job_real.result() counts_real = result_real.get_counts() print(counts_real)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
number = 5 # integer real = -3.4 # float name = 'Asja' # string surname = "Sarkana" # string boolean1 = True # Boolean boolean1 = False # Boolean a = 13 b = 5 print("a =",a) print("b =",b) print() # basics operators print("a + b =",a+b) print("a - b =",a-b) print("a * b =",a*b) print("a / b =",a/b) a = 13 b = 5 print("a =",a) print("b =",b) print() # integer division print("a//b =",a//b) # modulus operator print("a mod b =",a % b) b = 5 print("b =",b) print() print("b*b =",b**2) print("b*b*b =",b**3) print("sqrt(b)=",b**0.5) # list mylist = [10,8,6,4,2] print(mylist) # tuple mytuple=(1,4,5,'Asja') print(mytuple) # dictionary mydictionary = { 'name' : "Asja", 'surname':'Sarkane', 'age': 23 } print(mydictionary) print(mydictionary['surname']) # list of the other objects or variables list_of_other_objects =[ mylist, mytuple, 3, "Asja", mydictionary ] print(list_of_other_objects) # length of a string print(len("Asja Sarkane")) # size of a list print(len([1,2,3,4])) # size of a dictionary mydictionary = { 'name' : "Asja", 'surname':'Sarkane', 'age': 23} print(len(mydictionary)) i = 10 while i>0: # while condition(s): print(i) i = i - 1 for i in range(10): # i is in [0,1,...,9] print(i) for i in range(-5,6): # i is in [-5,-4,...,0,...,4,5] print(i) for i in range(0,23,4): # i is in [0,4,8,12,16,20] print(i) for i in [3,8,-5,11]: print(i) for i in "Sarkane": print(i) # dictionary mydictionary = { 'name' : "Asja", 'surname':'Sarkane', 'age': 23, } for key in mydictionary: print("key is",key,"and its value is",mydictionary[key]) for a in range(4,7): # if condition(s) if a<5: print(a,"is less than 5") # elif conditions(s) elif a==5: print(a,"is equal to 5") # else else: print(a,"is greater than 5") # Logical operator "and" i = -3 j = 4 if i<0 and j > 0: print(i,"is negative AND",j,"is positive") # Logical operator "or" i = -2 j = 2 if i==2 or j == 2: print("i OR j is 2: (",i,",",j,")") # Logical operator "not" i = 3 if not (i==2): print(i,"is NOT equal to 2") # Operator "equal to" i = -1 if i == -1: print(i,"is EQUAL TO -1") # Operator "not equal to" i = 4 if i != 3: print(i,"is NOT EQUAL TO 3") # Operator "not equal to" i = 2 if i <= 5: print(i,"is LESS THAN OR EQUAL TO 5") # Operator "not equal to" i = 5 if i >= 1: print(i,"is GREATER THAN OR EQUAL TO 3") A =[ [1,2,3], [-2,-4,-6], [3,6,9] ] # print all print(A) print() # print list by list for list in A: print(list) list1 = [1,2,3] list2 = [4,5,6] #concatenation of two lists list3 = list1 + list2 print(list3) list4 = list2 + list1 print(list4) list = [0,1,2] list.append(3) print(list) list = list + [4] print(list) def summation_of_integers(n): summation = 0 for integer in range(n+1): summation = summation + integer return summation print(summation_of_integers(10)) print(summation_of_integers(20)) from random import randrange print(randrange(10),"is picked randomly between 0 and 9") print(randrange(-9,10),"is picked randomly between -9 and 9") print(randrange(0,20,3),"is picked randomly from the list [0,3,6,9,12,15,18]")
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# # A quantum circuit is composed by quantum and classical bits. # # here are the objects that we use to create a quantum circuit from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit # we use a quantum register to keep our quantum bits. qreg = QuantumRegister(1) # in this example we will use a single quantum bit # To get an information from a quantum bit, it must be measured. (More details will appear.) # The measurement result is stored classically. # Therefore, we also use a classical regiser with classical bits creg = ClassicalRegister(1) # in this example we will use a single classical bit # now we can define our quantum circuit # it is composed by a quantum and a classical register mycircuit = QuantumCircuit(qreg,creg) # we apply operators on quantum bits # operators are also called as gates # we apply NOT operator represented as "x" # operator is a part of the circuit, and we should specify the quantum bit as the parameter mycircuit.x(qreg[0]) # (quantum) bits are enumerated starting from 0 # NOT operator or x-gate is applied to the first qubit of the quantum register # let's run our codes until now, and then draw our circuit print("Everything looks fine, let's continue ...") # we use matplotlib_circuit_drawer # we shortly refer it as "drawer" in our codes from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # let's draw our circuit now drawer(mycircuit) # re-execute me if you DO NOT see the circuit diagram # measurement is defined by associating a quantum bit to a classical bit mycircuit.measure(qreg[0],creg[0]) # the result will be stored in the classical bit print("Everything looks fine, let's continue ...") # let's draw the circuit again to see how the measurement is defined drawer(mycircuit) # reexecute me if you DO NOT see the circuit diagram # we are done with design of our circuit # now we can execute it # we execute quantum circuits many times (WHY?) # we use method "execute" and object "Aer" from qiskit library from qiskit import execute, Aer # we create a job object for execution of the circuit # there are three parameters # 1. mycircuit # 2. beckend on which it will be executed: we will use local simulator # 3. how_many_times will it be executed, let's pick it as 1024 job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1024) # we can get the result of the outcome as follows counts = job.result().get_counts(mycircuit) print(counts) # usually quantum programs produce probabilistic outcomes # # My second quantum circuit # # we import all at once from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # we will use 4 quantum bits and 4 classical bits qreg2 = QuantumRegister(4) creg2 = ClassicalRegister(4) mycircuit2 = QuantumCircuit(qreg2,creg2) # I will apply x-gate to the first quantum bit twice mycircuit2.x(qreg2[0]) mycircuit2.x(qreg2[0]) # I will apply x-gate to the fourth quantum bit once mycircuit2.x(qreg2[3]) # I will apply x-gate to the third quantum bit three times mycircuit2.x(qreg2[2]) mycircuit2.x(qreg2[2]) mycircuit2.x(qreg2[2]) # I will apply x-gate to the second quantum bit four times mycircuit2.x(qreg2[1]) mycircuit2.x(qreg2[1]) mycircuit2.x(qreg2[1]) mycircuit2.x(qreg2[1]) # if the size of quantum and classical registers are the same, we can define measurements with a single line code mycircuit2.measure(qreg2,creg2) # then each quantum bit and classical bit is associated with respect to their indices # let's run our codes until now, and then draw our circuit print("Everything looks fine, let's continue ...") drawer(mycircuit2) # re-execute me if you DO NOT see the circuit diagram job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=500) counts = job.result().get_counts(mycircuit2) print(counts) def print_outcomes(counts): # takes a dictionary variable for outcome in counts: # for each key-value in dictionary reverse_outcome = '' for i in outcome: # each string can be considered as a list of characters reverse_outcome = i + reverse_outcome # each new symbol comes before the old symbol(s) print(reverse_outcome,"is observed",counts[outcome],"times") job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=1024) counts = job.result().get_counts(mycircuit2) # counts is a dictionary object in python print_outcomes(counts) from random import randrange n = 20 r=randrange(n) # pick a number from the list {0,1,...,n-1} print(r) # test this method by using a loop for i in range(10): print(randrange(n)) # # your solution is here #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# first we import a procedure for picking a random number from random import randrange # randrange(m) returns a number randomly from the list {0,1,...,m-1} # randrange(10) returns a number randomly from the list {0,1,...,9} # here is an example r=randrange(5) print("I picked a random number between 0 and 4, which is ",r) # # your solution is here # # first we import a procedure for picking a random number from random import randrange # # your solution is here #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# # OUR SOLUTION # # initial case # We assume that the probability of getting head is 1 at the beginning, # because Asja will start with one euro. prob_head = 1 prob_tail = 0 # # first coin-flip # # if the last result was head new_prob_head_from_head = prob_head * 0.6 new_prob_tail_from_head = prob_head * 0.4 # if the last result was tail # we know that prob_tail is 0 at the beginning # but we still keep these two lines to have the same code for each iteration new_prob_head_from_tail = prob_tail * 0.3 new_prob_tail_from_tail = prob_tail * 0.7 # update the probabilities at the end of coin toss prob_head = new_prob_head_from_head + new_prob_head_from_tail prob_tail = new_prob_tail_from_head + new_prob_tail_from_tail # # second coin-flip # # we do the same calculations new_prob_head_from_head = prob_head * 0.6 new_prob_tail_from_head = prob_head * 0.4 new_prob_head_from_tail = prob_tail * 0.3 new_prob_tail_from_tail = prob_tail * 0.7 prob_head = new_prob_head_from_head + new_prob_head_from_tail prob_tail = new_prob_tail_from_head + new_prob_tail_from_tail # # third coin-flip # # we do the same calculations new_prob_head_from_head = prob_head * 0.6 new_prob_tail_from_head = prob_head * 0.4 new_prob_head_from_tail = prob_tail * 0.3 new_prob_tail_from_tail = prob_tail * 0.7 prob_head = new_prob_head_from_head + new_prob_head_from_tail prob_tail = new_prob_tail_from_head + new_prob_tail_from_tail # print prob_head and prob_tail print("the probability of getting head",prob_head) print("the probability of getting tail",prob_tail) # # your solution is here #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# # You may use python for your calculations. # all_portions = [7,5,4,2,6,1]; from random import randrange # # your solution is here #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# # your code is here or you may find the values by hand (in mind) # # # your solution is here #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# # your solution is here # # let's import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # let's import randrange for random choices from random import randrange # # your code is here #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer all_pairs = ['00','01','10','11'] for pair in all_pairs: # # your code is here #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # # your solution is here # # # your solution # # # your code is here #
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
n1,n2,n3 = 3,-4,6 print(n1,n2,n3) r1 = (2 * n1 + 3 * n2)*2 - 5 *n3 print(r1) n1,n2,n3 = 3,-4,6 up = (n1-n2) * (n2-n3) down = (n3-n1) * (n3 +1) result = up/down print (result) N = "Abuzer" S = "Yakaryilmaz" print("hello from the quantum world to",N,S)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
total1 = 0 total2 = 0 for i in range(3,52,3): total1 = total1 + i total2 += i # shorter form print("The summation is",total1) print("the summation is",total2) T = 0 current_number = 1 for i in range(9): T = T + current_number print("3 to",i,"is",current_number) current_number = 3 * current_number print("summation is",T) # python has also exponent operator: ** # we may directly use it T = 0 for i in range(9): print("3 to",i,"is",3**i) T = T + 3 ** i print("summation is",T) T = 0 n = 2 # this value will be first halved and then added to the summation how_many_terms = 0 while T<=1.99: n = n/2 # half the value of n T = T + n # update the value of T how_many_terms = how_many_terms + 1 print(n,T) print("how many terms in the summation is",how_many_terms) # our result says that there should be 8 terms in our summation # let's calculate the summation of the first seven and the first eight terms, and verify our results T7 = 0 n = 2 # this value will be first halved and then added to the summation for i in range(7): n = n/2 print(n) T7 = T7 + n print("the summation of the first seven terms is",T7) T8 = 0 n = 2 # this value will be first halved and then added to the summation for i in range(8): n = n/2 print(n) T8 = T8 + n print("the summation of the first eight terms is",T8) print("(the summation of the first seven terms is",T7,")") from random import randrange r = 0 attempt = 0 while r != 3: # the loop iterates as long as r is not equal to 3 r = randrange(10) # randomly pick a number attempt = attempt + 1 # increase the number of attempts by 1 print (attempt,"->",r) # print the number of attmept and the randomly picked number at this moment print("total number of attempt(s) is",attempt) # be aware of single and double indentions number_of_execution = 2000 # change this with 200, 2000, 20000, 200000 and reexecute this cell total_attempts = 0 from random import randrange for i in range(number_of_execution): # the outer loops iterates number_of_execution times r = 0 attempt = 0 while r != 3: # the while-loop iterates as long as r is not equal to 3 r = randrange(10) # randomly pick a number attempt = attempt + 1 # increase the number of attempts by 1 # I am out of scope of while-loop total_attempts = total_attempts + attempt # update the total number of attempts # I am out of scope of for-loop print(number_of_execution,"->",total_attempts/number_of_execution) # let's use triple nested loops for number_of_execution in [20,200,2000,20000,200000]: # we will use the same code by indenting all lines one more level :-) total_attempts = 0 for i in range(number_of_execution): # the middle loops iterates number_of_execution times r = 0 attempt = 0 while r != 3: # the while-loop iterates as long as r is not equal to 3 r = randrange(10) # randomly pick a number attempt = attempt + 1 # increase the number of attempts by 1 # I am out of scope of while-loop total_attempts = total_attempts + attempt # update the total number of attempts # I am out of scope of for-loop print(number_of_execution,"->",total_attempts/number_of_execution) # you can include 2 million to the list, but you should WAIT for a while to see the result # can your computer compete with exponential growth? # if you think "yes", please try 20 million, 200 million, and so on
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from random import randrange r = randrange(10,51) if r % 2 ==0: print(r,"is even") else: print(r,"is odd") from random import randrange for N in [100,1000,10000,100000]: first_half=second_half=0 for i in range(N): r = randrange(100) if r<50: first_half = first_half + 1 else: second_half=second_half + 1 print(N,"->",first_half/N,second_half/N)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# the first and second elements are 1 and 1 F = [1,1] for i in range(2,30): F.append(F[i-1] + F[i-2]) # print the final list print(F) # define an empty list N = [] for i in range(11): N.append([ i , i*i , i*i*i , i*i + i*i*i ]) # a list having four elements is added to the list N # Alternatively: #N.append([i , i**2 , i**3 , i**2 + i**3]) # ** is the exponent operator #N = N + [ [i , i*i , i*i*i , i*i + i*i*i] ] # Why using double brakets? #N = N + [ [i , i**2 , i**3 , i**2 + i**3] ] # Why using double brakets? # In the last two alternative solutions, you may try with a single braket, # and then see why double brakets are needed for the exact solution. # print the final list print(N) # let's print the list element by element for i in range(len(N)): print(N[i]) # let's print the list element by element by using an alternative method for el in N: # el will iteratively takes the values of elements in N print(el)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from random import randrange dimension = 7 # create u and v as empty list u = [] v = [] for i in range(dimension): u.append(randrange(-10,11)) # add a randomly picked number to the list u v.append(randrange(-10,11)) # add a randomly picked number to the list v # print both lists print("u is",u) print("v is",v) # let's create a result list # the first method result=[] # fill it with zeros for i in range(dimension): result.append(0) print("result is initialized by the first method to ",result) # the second method # alternative and shorter solution for creating a list with zeros result = [0] * 7 print("result is initialized by the second method to",result) # let's calculate 3u-2v for i in range(dimension): result[i] = 3 * u[i] - 2 * v[i] # print all lists print("u is",u) print("v is",v) print("3u-2v is",result) u = [1,-2,-4,2] fouru=[4,-8,-16,8] len_u = 0 len_fouru = 0 for i in range(len(u)): len_u = len_u + u[i]**2 # adding square of each value len_fouru = len_fouru + fouru[i]**2 # adding sqaure of each value len_u = len_u ** 0.5 # taking square root of the summation len_fouru = len_fouru ** 0.5 # taking square root of the summation # print the lengths print("length of u is",len_u) print("4 * length of u is",4 * len_u) print("length of 4u is",len_fouru) from random import randrange u = [1,-2,-4,2] print("u is",u) r = randrange(9) # r is a number in {0,...,8} r = r + 1 # r is a number in {1,...,9} r = r/10 # r is a number in {1/10,...,9/10} print() print("r is",r) newu=[] for i in range(len(u)): newu.append(-1*r*u[i]) print() print("-ru is",newu) print() length = 0 for i in range(len(newu)): length = length + newu[i]**2 # adding square of each number print(newu[i],"->[square]->",newu[i]**2) print() print("the summation of squares is",length) length = length**0.5 # taking square root print("the length of",newu,"is",length)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# let's define the vectors v=[-3,4,-5,6] u=[4,3,6,5] vu = 0 for i in range(len(v)): vu = vu + v[i]*u[i] print(v,u,vu) u = [-3,-4] uu = u[0]*u[0] + u[1]*u[1] print(u,u,uu) u = [-3,-4] neg_u=[3,4] v=[-4,3] neg_v=[4,-3] # let's define a function for inner product def inner(v_one,v_two): summation = 0 for i in range(len(v_one)): summation = summation + v_one[i]*v_two[i] # adding up pairwise multiplications return summation # return the inner product print("inner product of u and -v (",u," and ",neg_v,") is",inner(u,neg_v)) print("inner product of -u and v (",neg_u," and ",v,") is",inner(neg_u,v)) print("inner product of -u and -v (",neg_u," and ",neg_v,") is",inner(neg_u,neg_v)) # let's define a function for inner product def inner(v_one,v_two): summation = 0 for i in range(len(v_one)): summation = summation + v_one[i]*v_two[i] # adding up pairwise multiplications return summation # return the inner product v = [-1,2,-3,4] v_neg_two=[2,-4,6,-8] u=[-2,-1,5,2] u_three=[-6,-3,15,6] print("inner product of v and u is",inner(v,u)) print("inner product of -2v and 3u is",inner(v_neg_two,u_three))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from random import randrange A = [] B = [] for i in range(3): A.append([]) B.append([]) for j in range(4): A[i].append(randrange(-5,6)) B[i].append(randrange(-5,6)) print("A is",A) print("B is",B) C = [] for i in range(3): C.append([]) for j in range(4): C[i].append( 3*A[i][j]-2*B[i][j]) print("C is 3A - 2B") print("C is",C) M = [ [-2,3,0,4], [-1,1,5,9] ] N =[ [1,2,3], [4,5,6], [7,8,9] ] # create the transpose of M as a zero matrix # its dimension is (4x2) MT = [] for i in range(4): MT.append([]) for j in range(2): MT[i].append(0) # create the transpose of N as a zero matrix # its dimension is (3x3) NT = [] for i in range(3): NT.append([]) for j in range(3): NT[i].append(0) # calculate the MT for i in range(2): for j in range(4): MT[j][i]=M[i][j] # check the indices print("M is") for i in range(len(M)): print(M[i]) print() print("Transpose of M is") for i in range(len(MT)): print(MT[i]) print() # calculate the NT for i in range(3): for j in range(3): NT[j][i]=N[i][j] # check the indices print("N is") for i in range(len(N)): print(N[i]) print() print("Transpose of N is") for i in range(len(NT)): print(NT[i]) N = [ [-1,1,2], [0,-2,-3], [3,2,5], [0,2,-2] ] u = [2,-1,3] uprime =[] print("N is") for i in range(len(N)): print(N[i]) print() print("u is",u) for i in range(len(N)): # the number of rows of N S = 0 # summation of pairwise multiplications for j in range(len(u)): # the dimension of u S = S + N[i][j] * u[j] uprime.append(S) print() print("u' is",uprime) # matrix M M = [ [-1,0,1], [-2,-1,2], [1,2,-2] ] # matrix N N = [ [0,2,1], [3,-1,-2], [-1,1,0] ] # matrix K K = [] for i in range(3): K.append([]) for j in range(3): # here we calculate K[i][j] # inner product of i-th row of M with j-th row of N S = 0 for k in range(3): S = S + M[i][k] * N[k][j] K[i].append(S) print("M is") for i in range(len(M)): print(M[i]) print() print("N is") for i in range(len(N)): print(N[i]) print() print("K is") for i in range(len(K)): print(K[i]) from random import randrange A = [] B = [] AB = [] BA = [] DIFF = [] # create A, B, AB, BA, DIFF together for i in range(2): A.append([]) B.append([]) AB.append([]) BA.append([]) DIFF.append([]) for j in range(2): A[i].append(randrange(-10,10)) # the elements of A are random B[i].append(randrange(-10,10)) # the elements of B are random AB[i].append(0) # the elements of AB are initially set to zeros BA[i].append(0) # the elements of BA are initially set to zeros DIFF[i].append(0) # the elements of DIFF are initially set to zeros print("A =",A) print("B =",B) print() # print a line print("AB, BA, and DIFF are initially zero matrices") print("AB =",AB) print("BA =",BA) print("DIFF =",BA) # let's find AB for i in range(2): for j in range(2): # remark that AB[i][j] is already 0, and so we can directly add all pairwise multiplications for k in range(2): AB[i][j] = AB[i][j] + A[i][k] * B[k][j] # each multiplication is added print() # print a line print("AB =",AB) # let's find BA for i in range(2): for j in range(2): # remark that BA[i][j] is already 0, and so we can directly add all pairwise multiplications for k in range(2): BA[i][j] = BA[i][j] + B[i][k] * A[k][j] # each multiplication is added print("BA =",BA) # let's calculate DIFF = AB- BA for i in range(2): for j in range(2): DIFF[i][j] = AB[i][j] - BA[i][j] print() # print a line print("DIFF = AB - BA =",DIFF)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
u = [-2,-1,0,1] v = [1,2,3] uv = [] vu = [] for i in range(len(u)): # one element of u is picked for j in range(len(v)): # now we iteratively select every element of v uv.append(u[i]*v[j]) # this one element of u is iteratively multiplied with every element of v print("u-tensor-v is",uv) for i in range(len(v)): # one element of v is picked for j in range(len(u)): # now we iteratively select every element of u vu.append(v[i]*u[j]) # this one element of v is iteratively multiplied with every element of u print("v-tensor-u is",vu) A = [ [-1,0,1], [-2,-1,2] ] B = [ [0,2], [3,-1], [-1,1] ] print("A =") for i in range(len(A)): print(A[i]) print() # print a line print("B =") for i in range(len(B)): print(B[i]) # let's define A-tensor-B as a (6x6)-dimensional zero matrix AB = [] for i in range(6): AB.append([]) for j in range(6): AB[i].append(0) # let's find A-tensor-B for i in range(2): for j in range(3): # for each A(i,j) we execute the following codes a = A[i][j] # we access each element of B for m in range(3): for n in range(2): b = B[m][n] # now we put (a*b) in the appropriate index of AB AB[3*i+m][2*j+n] = a * b print() # print a line print("A-tensor-B =") print() # print a line for i in range(6): print(AB[i]) A = [ [-1,0,1], [-2,-1,2] ] B = [ [0,2], [3,-1], [-1,1] ] print() # print a line print("B =") for i in range(len(B)): print(B[i]) print("A =") for i in range(len(A)): print(A[i]) # let's define B-tensor-A as a (6x6)-dimensional zero matrix BA = [] for i in range(6): BA.append([]) for j in range(6): BA[i].append(0) # let's find B-tensor-A for i in range(3): for j in range(2): # for each B(i,j) we execute the following codes b = B[i][j] # we access each element of A for m in range(2): for n in range(3): a = A[m][n] # now we put (a*b) in the appropriate index of AB BA[2*i+m][3*j+n] = b * a print() # print a line print("B-tensor-A =") print() # print a line for i in range(6): print(BA[i])
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# we import all necessary methods and objects from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer from random import randrange # we will use 10 quantum bits and 10 classical bits qreg3 = QuantumRegister(10) creg3 = ClassicalRegister(10) mycircuit3 = QuantumCircuit(qreg3,creg3) # we will store the index of each qubit to which x-gate is applied picked_qubits=[] for i in range(10): if randrange(2) == 0: # Assume that 0 is Head and 1 is Tail mycircuit3.x(qreg3[i]) # apply x-gate print("x-gate is applied to the qubit with index",i) picked_qubits.append(i) # i is picked # measurement mycircuit3.measure(qreg3,creg3) print("Everything looks fine, let's continue ...") # draw the circuit drawer(mycircuit3) # reexecute me if you DO NOT see the circuit diagram def print_outcomes(counts): # takes a dictionary variable for outcome in counts: # for each key-value in dictionary reverse_outcome = '' for i in outcome: # each string can be considered as a list of characters reverse_outcome = i + reverse_outcome # each new symbol comes before the old symbol(s) print(reverse_outcome,"is observed",counts[outcome],"times") # execute the circuit and read the results job = execute(mycircuit3,Aer.get_backend('qasm_simulator'),shots=128) counts = job.result().get_counts(mycircuit3) print_outcomes(counts)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from random import randrange for experiment in [100,1000,10000,100000]: heads = tails = 0 for i in range(experiment): if randrange(2) == 0: heads = heads + 1 else: tails = tails + 1 print("experiment:",experiment) print("the ratio of #heads/#tails is",(heads/tails),"heads =",heads,"tails = ",tails) print() # empty line from random import randrange # let's pick a random number between {0,1,...,99} # it is expected to be less than 60 with probability 0.6 # and greater than or equal to 60 with probability 0.4 for experiment in [100,1000,10000,100000]: heads = tails = 0 for i in range(experiment): if randrange(100) <60: heads = heads + 1 # probability with 0.6 else: tails = tails + 1 # probability with 0.4 print("experiment:",experiment) print("the ratio of #heads/#tails is",(heads/tails),"heads =",heads,"tails = ",tails) print() # empty line
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# # We copy and paste the previous code # # initial case # We assume that the probability of getting head is 1 at the beginning, # becasue Asja will start with one euro. prob_head = 1 prob_tail = 0 number_of_iteration = 10 for i in range(number_of_iteration): # if the last result was head new_prob_head_from_head = prob_head * 0.6 new_prob_tail_from_head = prob_head * 0.4 # if the last result was tail # we know that prob_tail is 0 at the begining # but we still keep these two lines to have the same code for each iteration new_prob_head_from_tail = prob_tail * 0.3 new_prob_tail_from_tail = prob_tail * 0.7 # update the probabilities at the end of coin toss prob_head = new_prob_head_from_head + new_prob_head_from_tail prob_tail = new_prob_tail_from_head + new_prob_tail_from_tail # print prob_head and prob_tail print("the probability of getting head",prob_head) print("the probability of getting tail",prob_tail)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# all portions are stored in a list all_portions = [7,5,4,2,6,1]; # let's calculate the total portion total_portion = 0 for i in range(6): total_portion = total_portion + all_portions[i] print("total portion is",total_portion) # find the weight of one portion one_portion = 1/total_portion print("the weight of one portion is",one_portion) print() # print an empty line # now we can calculate the probabilities of rolling 1,2,3,4,5, and 6 for i in range(6): print("the probability of rolling",(i+1),"is",(one_portion*all_portions[i])) # we will randomly create a probabilistic state # # we should be careful about two things: # 1. a probability value must be between 0 and 1 # 2. the total probability must be 1 # # therefore, we can randomly pick three probability values. # once we have three probability values, the fourth one is determined automatically # the fourth one cannot be arbitrary, because the summation of the four values must be 1 # let's use a list of size 4 # initial values are zeros my_state = [0,0,0,0] # we pick three random probabilistic values from random import randrange # I assume that I have the following total value to distribute to four parts total = 1000 # I will randomly pick a value, and then continue with the remaining value for i in range(3): # let's find the three values pick_a_value = randrange(total) print("I picked",pick_a_value) my_state[i] = pick_a_value total = total - pick_a_value # remaining value for the others my_state[3] = total # this is the remaining value after three iterations print("The remaining value is",total) # let's verify the summation of the elements in my_state sum = 0 print() # print an empty line for i in range(len(my_state)): sum = sum + my_state[i] print("the summation of the elements in my_state is",sum) # let's convert the selected values to the probabilities # we can also call this procedure as **NORMALIZATION** for i in range(len(my_state)): my_state[i] = my_state[i]/1000 print() # print an empty line print("the entries of my probabilistic state:") # let's print all probabilities for i in range(len(my_state)): print(my_state[i])
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# let's start with a zero matrix A = [ [0,0,0], [0,0,0], [0,0,0] ] # we will randomly construct 3 columns from random import randrange for j in range(3): # each column is iteratively constructed total = 100 # we will start with 100 and randomly distribute it into three parties for i in range(2): # we will determine the first two entries randomly picked_probability = randrange(total) A[i][j] = picked_probability # the value of the i-th row in j-th column total = total - picked_probability # remaining part to distribute in the next iteration A[2][j] = total # the last row (in the j-th column) takes the remaining part after two iterations # let's print matrix A before the normalization # the entries are between 0 and 100 print("matrix A before normalization:") for i in range(3): print(A[i]) print("the column summations must be 100") # let's normalize the entries by dividing every element with 100 for i in range(3): for j in range(3): A[i][j] /=100 # shorter form of A[i][j] = A[i][j] / 100 # let's print matrix A after the normalization print() # print an empty line print("matrix A after normalization:") for i in range(3): print(A[i]) print("the column summations must be 1") # Asja's probabilistic operator (coin flip protocol) A = [ [0.6,0.3], [0.4,0.7] ] # one-step evolution of Asja's probabilistic operator on a given probabilistic state def asja(prelist): newlist=[0,0] for i in range(2): # for each row for j in range(2): # for each column newlist[i] = newlist[i] + prelist[j] * A[i][j] # summation of pairwise multiplication return newlist # return the new state # initial state state = [1,0] # after one step state = asja(state) print("after one step, the state is",state) # the new state is correct # let's check one more step state = asja(state) print("after two steps, the state is",state) # this is also correct # # then, let's evolve the system for more steps for i in [3,6,9,12,24,48,96]: # start from the initial state state = [1,0] for t in range(i): # apply asja t times state = asja(state) # print the result print(state,"after",(t+1),"steps") def evolve(Op,state): newstate=[] for i in range(len(Op)): # for each row # we calculate the corresponding entry of the new state newstate.append(0) # we set this value to 0 for the initialization for j in range(len(state)): # for each element in state newstate[i] = newstate[i] + Op[i][j] * state[j] # summation of pairwise multiplications return newstate # return the new probabilistic state # test the function # operator for the test A = [ [0.4,0.6,0], [0.2,0.1,0.7], [0.4,0.3,0.3] ] # state for test v = [0.1,0.3,0.6] newstate = evolve(A,v) print(newstate) for step in [5,10,20,40]: new_state = [0.1,0.3,0.6] # initial state for i in range(step): new_state = evolve(A,new_state) print(new_state) # change the initial state for step in [5,10,20,40]: new_state = [1,0,0] # initial state for i in range(step): new_state = evolve(A,new_state) print(new_state) # for random number generation from random import randrange # we will use evolve function def evolve(Op,state): newstate=[] for i in range(len(Op)): # for each row newstate.append(0) for j in range(len(state)): # for each element in state newstate[i] = newstate[i] + Op[i][j] * state[j] # summation of pairwise multiplications return newstate # return the new probabilistic state # the initial state state = [0.5, 0, 0.5, 0] # probabilistic operator for symbol a A = [ [0.5, 0, 0, 0], [0.25, 1, 0, 0], [0, 0, 1, 0], [0.25, 0, 0, 1] ] # probabilistic operator for symbol b B = [ [1, 0, 0, 0], [0, 1, 0.25, 0], [0, 0, 0.5, 0], [0, 0, 0.25, 1] ] # # your solution is here # length = 40 total = 50 # total = 1000 # we will also test our code for 1000 strings # we will check 5 cases # let's use a list cases = [0,0,0,0,0] for i in range(total): # total number of strings Na = 0 Nb = 0 string = "" state = [0.5, 0, 0.5, 0] for j in range(length): # generate random string if randrange(2) == 0: Na = Na + 1 # new symbol is a string = string + "a" state = evolve(A,state) # update the probabilistic state by A else: Nb = Nb + 1 # new symbol is b string = string + "b" state = evolve(B,state) # update the probabilistic state by B # now we have the final state p0 = state[0] + state [1] # the probabilities of being in 00 and 01 p1 = state[2] + state[3] # the probabilities of being in 10 and 11 #print() # print an empty line print("(Na-Nb) is",Na-Nb,"and","(p0-p1) is",p0-p1) # let's check possible different cases # start with the case in which both are nonzero # then their multiplication is nonzero # let's check the sign of their multiplication if (Na-Nb) * (p0-p1) < 0: print("they have opposite sign") cases[0] = cases[0] + 1 elif (Na-Nb) * (p0-p1) > 0: print("they have the same sign") cases[1] = cases[1] + 1 # one of them should be zero elif (Na-Nb) == 0: if (p0-p1) == 0: print("both are zero") cases[2] = cases[2] + 1 else: print("(Na-Nb) is zero, but (p0-p1) is nonzero") cases[3] = cases[3] + 1 elif (p0-p1) == 0: print("(Na-Nb) is nonzero, but (p0-p1) is zero") cases[4] = cases[4] + 1 # check the case(s) observed and the case(s) not observed print() # print an empty line print(cases)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # define a quantum register with one qubit qreg3 = QuantumRegister(1) # define a classical register with one bit # it stores the measurement result of the quantum part creg3 = ClassicalRegister(1) # define our quantum circuit mycircuit3 = QuantumCircuit(qreg3,creg3) # apply x-gate to the first qubit mycircuit3.x(qreg3[0]) # apply h-gate (Hadamard: quantum coin-flipping) to the first qubit mycircuit3.h(qreg3[0]) # measure the first qubit, and store the result in the first classical bit mycircuit3.measure(qreg3,creg3) print("Everything looks fine, let's continue ...") # draw the circuit drawer(mycircuit3) # reexecute me if you DO NOT see the circuit diagram # execute the circuit and read the results job = execute(mycircuit3,Aer.get_backend('qasm_simulator'),shots=10000) counts3 = job.result().get_counts(mycircuit3) print(counts3) # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # define a quantum register with one qubit qreg4 = QuantumRegister(1) # define a classical register with one bit # it stores the measurement result of the quantum part creg4 = ClassicalRegister(1) # define our quantum circuit mycircuit4 = QuantumCircuit(qreg4,creg4) # apply x-gate to the first qubit mycircuit4.x(qreg4[0]) # apply h-gate (Hadamard: quantum coin-flipping) to the first qubit twice mycircuit4.h(qreg4[0]) mycircuit4.h(qreg4[0]) # measure the first qubit, and store the result in the first classical bit mycircuit4.measure(qreg4,creg4) print("Everyhing looks fine, let's continue ...") # draw the circuit drawer(mycircuit4) # reexecute me if you DO NOT see the circuit diagram # execute the circuit and read the results job = execute(mycircuit4,Aer.get_backend('qasm_simulator'),shots=10000) counts4 = job.result().get_counts(mycircuit4) print(counts4)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# vector |v> print("vector |v>") values = [-0.1, -0.3, 0.4, 0.5] total = 0 # summation of squares for i in range(len(values)): total += values[i]**2; # add the square of each value print("total is ",total) print("the missing part is",1-total) print("so, the value a should be",(1-total)**0.5) # sqaure root of the missing part print() print("vector |u>") values = [1/(2**0.5), -1/(3**0.5)] total = 0 # summation of squares for i in range(len(values)): total += values[i]**2; # add the square of each value print("total is ",total) print("the missing part is",1-total) # the missing part is 1/b, square of 1/sqrt(b) # thus b is 1/missing-part print("so, the value b should be",1/(1-total)) from random import randrange # randomly create a 2-dimensional quantum state def random_quantum_state(): first_entry = randrange(100) first_entry = first_entry/100 first_entry = first_entry**0.5 # we found the first value before determining its sign if randrange(2) == 0: # determine the sign first_entry = -1 * first_entry second_entry = 1 - (first_entry**2) second_entry = second_entry**0.5 if randrange(2) == 0: # determine the sign second_entry = -1 * second_entry return [first_entry,second_entry] def is_quantum_state(quantum_state): length_square = 0 for i in range(len(quantum_state)): length_square += quantum_state[i]**2 print("summation of entry squares is",length_square) # there might be precision problem # the length may be very close to 1 but not exactly 1 # so we use the following trick if (length_square - 1)**2 < 0.00000001: return True return False # else # define a function for Hadamard multiplication def hadamard(quantum_state): result_quantum_state = [0,0] # define with zero entries result_quantum_state[0] = (1/(2**0.5)) * quantum_state[0] + (1/(2**0.5)) * quantum_state[1] result_quantum_state[1] = (1/(2**0.5)) * quantum_state[0] - (1/(2**0.5)) * quantum_state[1] return result_quantum_state # we are ready for i in range(10): picked_quantum_state=random_quantum_state() print(picked_quantum_state,"this is randomly picked quantum state") new_quantum_state = hadamard(picked_quantum_state) print(new_quantum_state,"this is new quantum state") print("Is it valid?",is_quantum_state(new_quantum_state)) print() # print an empty line
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
def square_roots(a,b,c): # we iteratively calculate the expression with many square roots # we start with c and continue with b and a result = c**0.5 # square root of c result = 2 * result # 2*sqrt(c) result = result + b # b + 2*sqrt(c) result = result**0.5 # square root result = a**0.5 - result return result quantum_state =[ square_roots(3,5,6)**(-1), square_roots(3,7,12)**(-1), square_roots(5,13,40)**(-1), square_roots(7,15,56)**(-1), ] # this is our quantum state # print the quantum state print(quantum_state) print() print("The probability of observing the states 00, 01, 10, 11:") total_probability = 0 for i in range(len(quantum_state)): current_probability = quantum_state[i]**2 # square of the amplitude print(current_probability) total_probability = total_probability + current_probability print() print("total probability is",total_probability) # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # import randrange for random choices from random import randrange number_of_qubit = 5 # define a quantum register with 5 qubits qreg = QuantumRegister(number_of_qubit) # define a classical register with 5 bits creg = ClassicalRegister(number_of_qubit) # define our quantum circuit mycircuit = QuantumCircuit(qreg,creg) # apply h-gate to all qubits for i in range(number_of_qubit): mycircuit.h(qreg[i]) # apply z-gate randomly picked qubits for i in range(number_of_qubit): if randrange(2) == 0: # the qubit with index i is picked to apply z-gate mycircuit.z(qreg[i]) # apply h-gate to all qubits for i in range(number_of_qubit): mycircuit.h(qreg[i]) # measure all qubits mycircuit.measure(qreg,creg) print("Everything looks fine, let's continue ...") # draw the circuit drawer(mycircuit) # reexecute me if you DO NOT see the circuit diagram # execute the circuit 1000 times in the local simulator job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1000) counts = job.result().get_counts(mycircuit) for outcome in counts: # print the reverse of the outcome reverse_outcome = '' for i in outcome: reverse_outcome = i + reverse_outcome print(reverse_outcome,"is observed",counts[outcome],"times")
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # import randrange for random choices from random import randrange n = 5 m = 4 values_of_qubits = [] # we keep a record of the qubits also in a list qreg1 = QuantumRegister(n) # quantum register with n qubits creg1 = ClassicalRegister(n) # classical register with n bits mycircuit1 = QuantumCircuit(qreg1,creg1) # quantum circuit with quantum and classical registers # set each qubit to |1> for i in range(n): mycircuit1.x(qreg1[i]) # apply x-gate (NOT operator) values_of_qubits.append(1) # the value of each qubit is set to 1 # randomly pick m pairs of qubits for i in range(m): controller_qubit = randrange(n) target_qubit = randrange(n) # controller and target qubits should be different while controller_qubit == target_qubit: # if they are the same, we pick the target_qubit again target_qubit = randrange(n) # print our picked qubits print("the indices of the controller and target qubits are",controller_qubit,target_qubit) # apply cx-gate (CNOT operator) mycircuit1.cx(qreg1[controller_qubit],qreg1[target_qubit]) # we also trace the results if values_of_qubits[controller_qubit] == 1: # if the value of the controller qubit is 1, values_of_qubits[target_qubit] = 1 - values_of_qubits[target_qubit] # then flips the value of the target qubit # remark that 1-x gives the negation of x # measure the quantum register mycircuit1.measure(qreg1,creg1) print("Everything looks fine, let's continue ...") # draw the circuit drawer(mycircuit1) # re-execute this cell if you DO NOT see the circuit diagram # execute the circuit 100 times in the local simulator job = execute(mycircuit1,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(mycircuit1) # print the reverse of the outcome for outcome in counts: reverse_outcome = '' for i in outcome: reverse_outcome = i + reverse_outcome print(reverse_outcome,"is observed",counts[outcome],"times") # the value of the qubits should be as follows based on our own calculation print(values_of_qubits) # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer all_inputs=['00','01','10','11'] for input in all_inputs: qreg2 = QuantumRegister(2) # quantum register with 2 qubits creg2 = ClassicalRegister(2) # classical register with 2 bits mycircuit2 = QuantumCircuit(qreg2,creg2) # quantum circuit with quantum and classical registers #initialize the inputs if input[0]=='1': mycircuit2.x(qreg2[0]) # set the state of the first qubit to |1> if input[1]=='1': mycircuit2.x(qreg2[1]) # set the state of the second qubit to |1> # apply h-gate to both qubits mycircuit2.h(qreg2[0]) mycircuit2.h(qreg2[1]) # apply cx(first-qubit,second-qubit) mycircuit2.cx(qreg2[0],qreg2[1]) # apply h-gate to both qubits mycircuit2.h(qreg2[0]) mycircuit2.h(qreg2[1]) # measure both qubits mycircuit2.measure(qreg2,creg2) # execute the circuit 100 times in the local simulator job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(mycircuit2) for outcome in counts: # print the reverse of the outcomes reverse_outcome = '' for i in outcome: reverse_outcome = i + reverse_outcome print("our input is",input,"and",reverse_outcome,"is observed",counts[outcome],"times") # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer all_inputs=['00','01','10','11'] for input in all_inputs: qreg3 = QuantumRegister(2) # quantum register with 2 qubits creg3 = ClassicalRegister(2) # classical register with 2 bits mycircuit3 = QuantumCircuit(qreg3,creg3) # quantum circuit with quantum and classical registers #initialize the inputs if input[0]=='1': mycircuit3.x(qreg3[0]) # set the value of the first qubit to |1> if input[1]=='1': mycircuit3.x(qreg3[1]) # set the value of the second qubit to |1> # apply cx(first-qubit,second-qubit) mycircuit3.cx(qreg3[0],qreg3[1]) # apply cx(second-qubit,first-qubit) mycircuit3.cx(qreg3[1],qreg3[0]) # apply cx(first-qubit,second-qubit) mycircuit3.cx(qreg3[0],qreg3[1]) mycircuit3.measure(qreg3,creg3) # execute the circuit 100 times in the local simulator job = execute(mycircuit3,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(mycircuit3) for outcome in counts: # print the reverse of the outcomes reverse_outcome = '' for i in outcome: reverse_outcome = i + reverse_outcome print("our input is",input,"and",reverse_outcome,"is observed",counts[outcome],"times")
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer all_pairs = ['00','01','10','11'] for pair in all_pairs: # create a quantum curcuit with two qubits: Asja's and Balvis' qubits. # both are initially set to |0>. qreg = QuantumRegister(2) # quantum register with 2 qubits creg = ClassicalRegister(2) # classical register with 2 bits mycircuit = QuantumCircuit(qreg,creg) # quantum circuit with quantum and classical registers # apply h-gate (Hadamard) to the first qubit. mycircuit.h(qreg[0]) # apply cx-gate (CNOT) with parameters first-qubit and second-qubit. mycircuit.cx(qreg[0],qreg[1]) # they are separated now. # if a is 1, then apply z-gate to the first qubit. if pair[0]=='1': mycircuit.z(qreg[0]) # if b is 1, then apply x-gate (NOT) to the first qubit. if pair[1]=='1': mycircuit.x(qreg[0]) # Asja sends her qubit to Balvis. # apply cx-gate (CNOT) with parameters first-qubit and second-qubit. mycircuit.cx(qreg[0],qreg[1]) # apply h-gate (Hadamard) to the first qubit. mycircuit.h(qreg[0]) # measure both qubits mycircuit.measure(qreg,creg) # compare the results with pair (a,b) job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(mycircuit) for outcome in counts: reverse_outcome = '' for i in outcome: reverse_outcome = i + reverse_outcome print("(a,b) is",pair,"and",reverse_outcome,"is observed",counts[outcome],"times")
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer qreg1 = QuantumRegister(2) # quantum register with 2 qubits creg1 = ClassicalRegister(2) # classical register with 2 bits mycircuit1 = QuantumCircuit(qreg1,creg1) # quantum circuit with quantum and classical registers # the first qubit is in |0> # set the second qubit to |1> mycircuit1.x(qreg1[1]) # apply x-gate (NOT operator) # apply Hadamard to both qubits. mycircuit1.h(qreg1[0]) mycircuit1.h(qreg1[1]) # apply CNOT operator, where the controller qubit is the first qubit and the target qubit is the second qubit. mycircuit1.cx(qreg1[0],qreg1[1]) # apply Hadamard to both qubits. mycircuit1.h(qreg1[0]) mycircuit1.h(qreg1[1]) # measure both qubits mycircuit1.measure(qreg1,creg1) # execute the circuit 100 times in the local simulator job = execute(mycircuit1,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(mycircuit1) # print the reverse of the outcome for outcome in counts: reverse_outcome = '' for i in outcome: reverse_outcome = i + reverse_outcome print("We start in quantum state 01 and",reverse_outcome,"is observed",counts[outcome],"times") # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer # Create a curcuit with 7 qubits. n = 7 qreg2 = QuantumRegister(n) # quantum register with 7 qubits creg2 = ClassicalRegister(n) # classical register with 7 bits mycircuit2 = QuantumCircuit(qreg2,creg2) # quantum circuit with quantum and classical registers # the first six qubits are already in |0> # set the last qubit to |1> mycircuit2.x(qreg2[n-1]) # apply x-gate (NOT operator) # apply Hadamard to all qubits. for i in range(n): mycircuit2.h(qreg2[i]) # apply CNOT operator (first-qubit,last-qubit) # apply CNOT operator (fourth-qubit,last-qubit) # apply CNOT operator (fifth-qubit,last-qubit) mycircuit2.cx(qreg2[0],qreg2[n-1]) mycircuit2.cx(qreg2[3],qreg2[n-1]) mycircuit2.cx(qreg2[4],qreg2[n-1]) # apply Hadamard to all qubits. for i in range(n): mycircuit2.h(qreg2[i]) # measure all qubits mycircuit2.measure(qreg2,creg2) # execute the circuit 100 times in the local simulator job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(mycircuit2) # print the reverse of the outcome for outcome in counts: reverse_outcome = '' for i in outcome: reverse_outcome = i + reverse_outcome print(reverse_outcome,"is observed",counts[outcome],"times") for i in range(len(reverse_outcome)-1): print("the final value of the",(i+1),". qubit is",reverse_outcome[i])
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer qreg = QuantumRegister(4) # quantum register with 4 qubits creg = ClassicalRegister(4) # classical register with 4 bits mycircuit = QuantumCircuit(qreg,creg) # quantum circuit with quantum and classical registers # apply h-gate (Hadamard) to each qubit for i in range(4): mycircuit.h(qreg[i]) # measure both qubits mycircuit.measure(qreg,creg) # execute the circuit 1600 times, and print the outcomes job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1600) counts = job.result().get_counts(mycircuit) for outcome in counts: reverse_outcome = '' for i in outcome: reverse_outcome = i + reverse_outcome print(reverse_outcome,"is observed",counts[outcome],"times") # find the angle theta u2 = [(13/16)**0.5,(3/16)**0.5] print(u2) from math import acos # acos is the inverse of function cosine from math import pi def angle_between_two_quantum_states(quantum_state1,quantum_state2): inner_product = quantum_state1[0] * quantum_state2[0] + quantum_state1[1] * quantum_state2[1] return acos(inner_product) # angle between |u> and |0> theta2 = angle_between_two_quantum_states(u2,[1,0]) print(theta2) # COPY-PASTE the functions from the notebook "B80_Reflections" def amplitudes_of_a_quantum_state(quantum_circuit): # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # the following code is used to get the quantum state of a quantum circuit job = execute(quantum_circuit,Aer.get_backend('statevector_simulator')) current_quantum_state=job.result().get_statevector(quantum_circuit) # now we read the real parts of the amplitudes the_first_amplitude = current_quantum_state[0].real # amplitude of |0> the_second_amplitude = current_quantum_state[1].real # amplitude of |1> return[the_first_amplitude,the_second_amplitude] # end of function def visualize_quantum_states(quantum_states): # import the useful tool for drawing figures in pythpn from matplotlib.pyplot import plot, show, figure, Circle, axis, gca, annotate, arrow, text # import the constant pi from math import pi figure(figsize=(6,6), dpi=80) # size of the figure gca().add_patch( Circle((0,0),1,color='black',fill=False) ) # draw the circle # auxiliary points plot(-1.3,0) plot(1.3,0) plot(0,1.3) plot(0,-1.3) # axes arrow(0,0,1.1,0,head_width=0.04, head_length=0.08) arrow(0,0,-1.1,0,head_width=0.04, head_length=0.08) arrow(0,0,0,-1.1,head_width=0.04, head_length=0.08) arrow(0,0,0,1.1,head_width=0.04, head_length=0.08) # draw all quantum states for quantum_state in quantum_states: # show the quantum state as an arrow on the diagram state_name = quantum_state[0] # label of the quantum state x_value = quantum_state[1] # amplitude of |0> y_value = quantum_state[2] # amplitude of |1> # draw the arrow arrow(0,0,x_value,y_value,head_width=0.04, head_length=0.04,color='blue') # the following code is used to write the name of quantum states if x_value<0: text_x_value=x_value-0.1 else: text_x_value=x_value+0.05 if y_value<0: text_y_value=y_value-0.1 else: text_y_value=y_value+0.05 text(text_x_value,text_y_value,state_name) show() # show the diagram # end of function # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer all_visited_quantum_states2 =[] qreg2 = QuantumRegister(1) # quantum register with 1 qubit creg2 = ClassicalRegister(1) # classical register with 1 bit mycircuit2 = QuantumCircuit(qreg2,creg2) # quantum circuit with quantum and classical registers # set the qubit to |u> # rotate by theta2 # do not forget to multiply it by 2 mycircuit2.ry(2*theta2,qreg2[0]) # read and store the current quantum state [x,y] = amplitudes_of_a_quantum_state(mycircuit2) all_visited_quantum_states2.append(['u',x,y]) # this is (-2*theta2) in the first iteration rotation_angle_for_the_first_reflection2 = -2 * theta2 # this is always (2*theta2) more than (-1*rotation_angle_for_the_first_reflection2) rotation_angle_for_the_second_reflection2 = (2*theta2) + (-1*rotation_angle_for_the_first_reflection2) # the first reflection: rotate by rotation_angle_for_the_first_reflection2 mycircuit2.ry(2*rotation_angle_for_the_first_reflection2,qreg2[0]) # read and store the current quantum state [x,y] = amplitudes_of_a_quantum_state(mycircuit2) all_visited_quantum_states2.append(['r',x,y]) # the label is r (reflected state) # the second reflection: rotate by rotation_angle_for_the_second_reflection2 mycircuit2.ry(2*rotation_angle_for_the_second_reflection2,qreg2[0]) # read and store the current quantum state [x,y] = amplitudes_of_a_quantum_state(mycircuit2) all_visited_quantum_states2.append(['n',x,y]) # the label is n (new state) visualize_quantum_states(all_visited_quantum_states2) # measure both qubits mycircuit2.measure(qreg2,creg2) # execute the circuit 100 times, and print the outcomes job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=100) counts2 = job.result().get_counts(mycircuit2) for outcome in counts2: reverse_outcome = '' for i in outcome: reverse_outcome = i + reverse_outcome print(reverse_outcome,"is observed",counts2[outcome],"times") print(all_visited_quantum_states2) # find the angle theta u3 = [(63/64)**0.5,(1/64)**0.5] print(u3) from math import acos # acos is the inverse of function cosine from math import pi def angle_between_two_quantum_states(quantum_state1,quantum_state2): inner_product = quantum_state1[0] * quantum_state2[0] + quantum_state1[1] * quantum_state2[1] return acos(inner_product) # angle between |u> and |0> theta3 = angle_between_two_quantum_states(u3,[1,0]) print(theta3) # COPY-PASTE the functions from the notebook "B80_Reflections" def amplitudes_of_a_quantum_state(quantum_circuit): # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # the following code is used to get the quantum state of a quantum circuit job = execute(quantum_circuit,Aer.get_backend('statevector_simulator')) current_quantum_state=job.result().get_statevector(quantum_circuit) # now we read the real parts of the amplitudes the_first_amplitude = current_quantum_state[0].real # amplitude of |0> the_second_amplitude = current_quantum_state[1].real # amplitude of |1> return[the_first_amplitude,the_second_amplitude] # end of function def visualize_quantum_states(quantum_states): # import the useful tool for drawing figures in pythpn from matplotlib.pyplot import plot, show, figure, Circle, axis, gca, annotate, arrow, text # import the constant pi from math import pi figure(figsize=(6,6), dpi=80) # size of the figure gca().add_patch( Circle((0,0),1,color='black',fill=False) ) # draw the circle # auxiliary points plot(-1.3,0) plot(1.3,0) plot(0,1.3) plot(0,-1.3) # axes arrow(0,0,1.1,0,head_width=0.04, head_length=0.08) arrow(0,0,-1.1,0,head_width=0.04, head_length=0.08) arrow(0,0,0,-1.1,head_width=0.04, head_length=0.08) arrow(0,0,0,1.1,head_width=0.04, head_length=0.08) # draw all quantum states for quantum_state in quantum_states: # show the quantum state as an arrow on the diagram state_name = quantum_state[0] # label of the quantum state x_value = quantum_state[1] # amplitude of |0> y_value = quantum_state[2] # amplitude of |1> # draw the arrow arrow(0,0,x_value,y_value,head_width=0.04, head_length=0.04,color='blue') # the following code is used to write the name of quantum states if x_value<0: text_x_value=x_value-0.1 else: text_x_value=x_value+0.05 if y_value<0: text_y_value=y_value-0.1 else: text_y_value=y_value+0.05 text(text_x_value,text_y_value,state_name) show() # show the diagram # end of function # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer all_visited_quantum_states3 =[] qreg3 = QuantumRegister(1) # quantum register with 1 qubit creg3 = ClassicalRegister(1) # classical register with 1 bit mycircuit3 = QuantumCircuit(qreg3,creg3) # quantum circuit with quantum and classical registers # set the qubit to |u> # rotate by theta3 # do not forget to multiply it by 2 mycircuit3.ry(2*theta3,qreg3[0]) # read and store the current quantum state [x,y] = amplitudes_of_a_quantum_state(mycircuit3) all_visited_quantum_states3.append(['u',x,y]) # this is -2 * theta3 in the first iteration rotation_angle_for_the_first_reflection3 = -2 * theta3 # this is always (2*theta3) more than (-1*rotation_angle_for_the_first_reflection3) rotation_angle_for_the_second_reflection3 = (2*theta3) + (-1*rotation_angle_for_the_first_reflection3) for i in range(3): # three iterations # later check 4, 5, 6, 7, 8, 9, and 10 # the first reflection: rotate by rotation_angle_for_the_first_reflection3 mycircuit3.ry(2*rotation_angle_for_the_first_reflection3,qreg3[0]) # read and store the current quantum state [x,y] = amplitudes_of_a_quantum_state(mycircuit3) all_visited_quantum_states3.append(['r'+str(i+1),x,y]) # the labels are r1, r2, ... (reflected states) # the second reflection: rotate by rotation_angle_for_the_second_reflection3 mycircuit3.ry(2*rotation_angle_for_the_second_reflection3,qreg3[0]) # read and store the current quantum state [x,y] = amplitudes_of_a_quantum_state(mycircuit3) all_visited_quantum_states3.append(['n'+str(i+1),x,y]) # the labels are n1, n2, ... (new states) # this will be increased by (-4*theta2) after each iteration rotation_angle_for_the_first_reflection3 = rotation_angle_for_the_first_reflection3 -4* theta3 # this is always (2*theta2) more than (-1*rotation_angle_for_the_first_reflection3) rotation_angle_for_the_second_reflection3 = (2*theta3) + (-1*rotation_angle_for_the_first_reflection3) # end of iterations visualize_quantum_states(all_visited_quantum_states3) # measure both qubits mycircuit3.measure(qreg3,creg3) # execute the circuit 100 times, and print the outcomes job = execute(mycircuit3,Aer.get_backend('qasm_simulator'),shots=100) counts3 = job.result().get_counts(mycircuit3) for outcome in counts3: reverse_outcome = '' for i in outcome: reverse_outcome = i + reverse_outcome print(reverse_outcome,"is observed",counts3[outcome],"times") print(all_visited_quantum_states3) # find the angle theta # k=8, 2^k = 256 u4 = [(255/256)**0.5,(1/256)**0.5] print(u4) from math import acos # acos is the inverse of function cosine from math import pi def angle_between_two_quantum_states(quantum_state1,quantum_state2): inner_product = quantum_state1[0] * quantum_state2[0] + quantum_state1[1] * quantum_state2[1] return acos(inner_product) # angle between |u> and |0> theta4 = angle_between_two_quantum_states(u4,[1,0]) print(theta4) # COPY-PASTE the functions from the notebook "B80_Reflections" def amplitudes_of_a_quantum_state(quantum_circuit): # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # the following code is used to get the quantum state of a quantum circuit job = execute(quantum_circuit,Aer.get_backend('statevector_simulator')) current_quantum_state=job.result().get_statevector(quantum_circuit) # now we read the real parts of the amplitudes the_first_amplitude = current_quantum_state[0].real # amplitude of |0> the_second_amplitude = current_quantum_state[1].real # amplitude of |1> return[the_first_amplitude,the_second_amplitude] # end of function def visualize_quantum_states(quantum_states): # import the useful tool for drawing figures in pythpn from matplotlib.pyplot import plot, show, figure, Circle, axis, gca, annotate, arrow, text # import the constant pi from math import pi figure(figsize=(6,6), dpi=80) # size of the figure gca().add_patch( Circle((0,0),1,color='black',fill=False) ) # draw the circle # auxiliary points plot(-1.3,0) plot(1.3,0) plot(0,1.3) plot(0,-1.3) # axes arrow(0,0,1.1,0,head_width=0.04, head_length=0.08) arrow(0,0,-1.1,0,head_width=0.04, head_length=0.08) arrow(0,0,0,-1.1,head_width=0.04, head_length=0.08) arrow(0,0,0,1.1,head_width=0.04, head_length=0.08) # draw all quantum states for quantum_state in quantum_states: # show the quantum state as an arrow on the diagram state_name = quantum_state[0] # label of the quantum state x_value = quantum_state[1] # amplitude of |0> y_value = quantum_state[2] # amplitude of |1> # draw the arrow arrow(0,0,x_value,y_value,head_width=0.04, head_length=0.04,color='blue') # the following code is used to write the name of quantum states if x_value<0: text_x_value=x_value-0.1 else: text_x_value=x_value+0.05 if y_value<0: text_y_value=y_value-0.1 else: text_y_value=y_value+0.05 text(text_x_value,text_y_value,state_name) show() # show the diagram # end of function # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer how_many_times_state_one_observed = 0 decrease = False number_of_iteration = 1 while decrease == False: qreg4 = QuantumRegister(1) # quantum register with 1 qubit creg4 = ClassicalRegister(1) # classical register with 1 bit mycircuit4 = QuantumCircuit(qreg4,creg4) # quantum circuit with quantum and classical registers # set the qubit to |u> # rotate by theta4 # do not forget to multiply it by 2 mycircuit4.ry(2*theta4,qreg4[0]) # this is -2 * theta4 in the first iteration rotation_angle_for_the_first_reflection4 = -2 * theta4 # this is always (2*theta4) more than (-1*rotation_angle_for_the_first_reflection4) rotation_angle_for_the_second_reflection4 = (2*theta4) + (-1*rotation_angle_for_the_first_reflection4) for i in range(number_of_iteration): # the first reflection: rotate by rotation_angle_for_the_first_reflection4 mycircuit4.ry(2*rotation_angle_for_the_first_reflection4,qreg4[0]) # the second reflection: rotate by rotation_angle_for_the_second_reflcetion4 mycircuit4.ry(2*rotation_angle_for_the_second_reflection4,qreg4[0]) # this will be increased by (-4*theta4) after each iteration rotation_angle_for_the_first_reflection4 = rotation_angle_for_the_first_reflection4 -4* theta4 # this is always (2*theta4) more than (-1*rotation_angle_for_the_first_reflection4) rotation_angle_for_the_second_reflection4 = (2*theta4) + (-1*rotation_angle_for_the_first_reflection4) # end of iterations # measure both qubits mycircuit4.measure(qreg4,creg4) # execute the circuit 1000 times, and print the outcomes job = execute(mycircuit4,Aer.get_backend('qasm_simulator'),shots=1000) counts4 = job.result().get_counts(mycircuit4) print(number_of_iteration,counts4) # print the outcomes for outcome in counts4: if outcome == '1': # how_many_times_state_one_observed is more than 500 and has a less value than the previous one # then it is time to STOP if how_many_times_state_one_observed> 500 and how_many_times_state_one_observed > counts4[outcome]: print("B is",number_of_iteration-1) decrease = True else: # we should continue how_many_times_state_one_observed = counts4[outcome] # update how_many_times_state_one_observed number_of_iteration = number_of_iteration + 1 # increase number_of_iteration
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer qreg = QuantumRegister(4) # quantum register with 4 qubits creg = ClassicalRegister(4) # classical register with 4 bits mycircuit = QuantumCircuit(qreg,creg) # quantum circuit with quantum and classical registers # apply h-gate (Hadamard) to each qubit for i in range(4): mycircuit.h(qreg[i]) # measure both qubits mycircuit.measure(qreg,creg) # execute the circuit 1600 times, and print the outcomes job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1600) counts = job.result().get_counts(mycircuit) for outcome in counts: reverse_outcome = '' for i in outcome: reverse_outcome = i + reverse_outcome print(reverse_outcome,"is observed",counts[outcome],"times") # find the angle theta u2 = [(13/16)**0.5,(3/16)**0.5] print(u2) from math import acos # acos is the inverse of function cosine from math import pi def angle_between_two_quantum_states(quantum_state1,quantum_state2): inner_product = quantum_state1[0] * quantum_state2[0] + quantum_state1[1] * quantum_state2[1] return acos(inner_product) # angle between |u> and |0> theta2 = angle_between_two_quantum_states(u2,[1,0]) print(theta2) # COPY-PASTE the functions from the notebook "B80_Reflections" def amplitudes_of_a_quantum_state(quantum_circuit): # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # the following code is used to get the quantum state of a quantum circuit job = execute(quantum_circuit,Aer.get_backend('statevector_simulator')) current_quantum_state=job.result().get_statevector(quantum_circuit) # now we read the real parts of the amplitudes the_first_amplitude = current_quantum_state[0].real # amplitude of |0> the_second_amplitude = current_quantum_state[1].real # amplitude of |1> return[the_first_amplitude,the_second_amplitude] # end of function def visualize_quantum_states(quantum_states): # import the useful tool for drawing figures in pythpn from matplotlib.pyplot import plot, show, figure, Circle, axis, gca, annotate, arrow, text # import the constant pi from math import pi figure(figsize=(6,6), dpi=80) # size of the figure gca().add_patch( Circle((0,0),1,color='black',fill=False) ) # draw the circle # auxiliary points plot(-1.3,0) plot(1.3,0) plot(0,1.3) plot(0,-1.3) # axes arrow(0,0,1.1,0,head_width=0.04, head_length=0.08) arrow(0,0,-1.1,0,head_width=0.04, head_length=0.08) arrow(0,0,0,-1.1,head_width=0.04, head_length=0.08) arrow(0,0,0,1.1,head_width=0.04, head_length=0.08) # draw all quantum states for quantum_state in quantum_states: # show the quantum state as an arrow on the diagram state_name = quantum_state[0] # label of the quantum state x_value = quantum_state[1] # amplitude of |0> y_value = quantum_state[2] # amplitude of |1> # draw the arrow arrow(0,0,x_value,y_value,head_width=0.04, head_length=0.04,color='blue') # the following code is used to write the name of quantum states if x_value<0: text_x_value=x_value-0.1 else: text_x_value=x_value+0.05 if y_value<0: text_y_value=y_value-0.1 else: text_y_value=y_value+0.05 text(text_x_value,text_y_value,state_name) show() # show the diagram # end of function # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer all_visited_quantum_states2 =[] qreg2 = QuantumRegister(1) # quantum register with 1 qubit creg2 = ClassicalRegister(1) # classical register with 1 bit mycircuit2 = QuantumCircuit(qreg2,creg2) # quantum circuit with quantum and classical registers # set the qubit to |u> # rotate by theta2 # do not forget to multiply it by 2 mycircuit2.ry(2*theta2,qreg2[0]) # read and store the current quantum state [x,y] = amplitudes_of_a_quantum_state(mycircuit2) all_visited_quantum_states2.append(['u',x,y]) # this is (-2*theta2) in the first iteration rotation_angle_for_the_first_reflection2 = -2 * theta2 # this is always (2*theta2) more than (-1*rotation_angle_for_the_first_reflection2) rotation_angle_for_the_second_reflection2 = (2*theta2) + (-1*rotation_angle_for_the_first_reflection2) # the first reflection: rotate by rotation_angle_for_the_first_reflection2 mycircuit2.ry(2*rotation_angle_for_the_first_reflection2,qreg2[0]) # read and store the current quantum state [x,y] = amplitudes_of_a_quantum_state(mycircuit2) all_visited_quantum_states2.append(['r',x,y]) # the label is r (reflected state) # the second reflection: rotate by rotation_angle_for_the_second_reflection2 mycircuit2.ry(2*rotation_angle_for_the_second_reflection2,qreg2[0]) # read and store the current quantum state [x,y] = amplitudes_of_a_quantum_state(mycircuit2) all_visited_quantum_states2.append(['n',x,y]) # the label is n (new state) visualize_quantum_states(all_visited_quantum_states2) # measure both qubits mycircuit2.measure(qreg2,creg2) # execute the circuit 100 times, and print the outcomes job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=100) counts2 = job.result().get_counts(mycircuit2) for outcome in counts2: reverse_outcome = '' for i in outcome: reverse_outcome = i + reverse_outcome print(reverse_outcome,"is observed",counts2[outcome],"times") print(all_visited_quantum_states2) # find the angle theta u3 = [(63/64)**0.5,(1/64)**0.5] print(u3) from math import acos # acos is the inverse of function cosine from math import pi def angle_between_two_quantum_states(quantum_state1,quantum_state2): inner_product = quantum_state1[0] * quantum_state2[0] + quantum_state1[1] * quantum_state2[1] return acos(inner_product) # angle between |u> and |0> theta3 = angle_between_two_quantum_states(u3,[1,0]) print(theta3) # COPY-PASTE the functions from the notebook "B80_Reflections" def amplitudes_of_a_quantum_state(quantum_circuit): # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # the following code is used to get the quantum state of a quantum circuit job = execute(quantum_circuit,Aer.get_backend('statevector_simulator')) current_quantum_state=job.result().get_statevector(quantum_circuit) # now we read the real parts of the amplitudes the_first_amplitude = current_quantum_state[0].real # amplitude of |0> the_second_amplitude = current_quantum_state[1].real # amplitude of |1> return[the_first_amplitude,the_second_amplitude] # end of function def visualize_quantum_states(quantum_states): # import the useful tool for drawing figures in pythpn from matplotlib.pyplot import plot, show, figure, Circle, axis, gca, annotate, arrow, text # import the constant pi from math import pi figure(figsize=(6,6), dpi=80) # size of the figure gca().add_patch( Circle((0,0),1,color='black',fill=False) ) # draw the circle # auxiliary points plot(-1.3,0) plot(1.3,0) plot(0,1.3) plot(0,-1.3) # axes arrow(0,0,1.1,0,head_width=0.04, head_length=0.08) arrow(0,0,-1.1,0,head_width=0.04, head_length=0.08) arrow(0,0,0,-1.1,head_width=0.04, head_length=0.08) arrow(0,0,0,1.1,head_width=0.04, head_length=0.08) # draw all quantum states for quantum_state in quantum_states: # show the quantum state as an arrow on the diagram state_name = quantum_state[0] # label of the quantum state x_value = quantum_state[1] # amplitude of |0> y_value = quantum_state[2] # amplitude of |1> # draw the arrow arrow(0,0,x_value,y_value,head_width=0.04, head_length=0.04,color='blue') # the following code is used to write the name of quantum states if x_value<0: text_x_value=x_value-0.1 else: text_x_value=x_value+0.05 if y_value<0: text_y_value=y_value-0.1 else: text_y_value=y_value+0.05 text(text_x_value,text_y_value,state_name) show() # show the diagram # end of function # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer all_visited_quantum_states3 =[] qreg3 = QuantumRegister(1) # quantum register with 1 qubit creg3 = ClassicalRegister(1) # classical register with 1 bit mycircuit3 = QuantumCircuit(qreg3,creg3) # quantum circuit with quantum and classical registers # set the qubit to |u> # rotate by theta3 # do not forget to multiply it by 2 mycircuit3.ry(2*theta3,qreg3[0]) # read and store the current quantum state [x,y] = amplitudes_of_a_quantum_state(mycircuit3) all_visited_quantum_states3.append(['u',x,y]) # this is -2 * theta3 in the first iteration rotation_angle_for_the_first_reflection3 = -2 * theta3 # this is always (2*theta3) more than (-1*rotation_angle_for_the_first_reflection3) rotation_angle_for_the_second_reflection3 = (2*theta3) + (-1*rotation_angle_for_the_first_reflection3) for i in range(3): # three iterations # later check 4, 5, 6, 7, 8, 9, and 10 # the first reflection: rotate by rotation_angle_for_the_first_reflection3 mycircuit3.ry(2*rotation_angle_for_the_first_reflection3,qreg3[0]) # read and store the current quantum state [x,y] = amplitudes_of_a_quantum_state(mycircuit3) all_visited_quantum_states3.append(['r'+str(i+1),x,y]) # the labels are r1, r2, ... (reflected states) # the second reflection: rotate by rotation_angle_for_the_second_reflection3 mycircuit3.ry(2*rotation_angle_for_the_second_reflection3,qreg3[0]) # read and store the current quantum state [x,y] = amplitudes_of_a_quantum_state(mycircuit3) all_visited_quantum_states3.append(['n'+str(i+1),x,y]) # the labels are n1, n2, ... (new states) # this will be increased by (-4*theta2) after each iteration rotation_angle_for_the_first_reflection3 = rotation_angle_for_the_first_reflection3 -4* theta3 # this is always (2*theta2) more than (-1*rotation_angle_for_the_first_reflection3) rotation_angle_for_the_second_reflection3 = (2*theta3) + (-1*rotation_angle_for_the_first_reflection3) # end of iterations visualize_quantum_states(all_visited_quantum_states3) # measure both qubits mycircuit3.measure(qreg3,creg3) # execute the circuit 100 times, and print the outcomes job = execute(mycircuit3,Aer.get_backend('qasm_simulator'),shots=100) counts3 = job.result().get_counts(mycircuit3) for outcome in counts3: reverse_outcome = '' for i in outcome: reverse_outcome = i + reverse_outcome print(reverse_outcome,"is observed",counts3[outcome],"times") print(all_visited_quantum_states3) # find the angle theta # k=8, 2^k = 256 u4 = [(255/256)**0.5,(1/256)**0.5] print(u4) from math import acos # acos is the inverse of function cosine from math import pi def angle_between_two_quantum_states(quantum_state1,quantum_state2): inner_product = quantum_state1[0] * quantum_state2[0] + quantum_state1[1] * quantum_state2[1] return acos(inner_product) # angle between |u> and |0> theta4 = angle_between_two_quantum_states(u4,[1,0]) print(theta4) # COPY-PASTE the functions from the notebook "B80_Reflections" def amplitudes_of_a_quantum_state(quantum_circuit): # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # the following code is used to get the quantum state of a quantum circuit job = execute(quantum_circuit,Aer.get_backend('statevector_simulator')) current_quantum_state=job.result().get_statevector(quantum_circuit) # now we read the real parts of the amplitudes the_first_amplitude = current_quantum_state[0].real # amplitude of |0> the_second_amplitude = current_quantum_state[1].real # amplitude of |1> return[the_first_amplitude,the_second_amplitude] # end of function def visualize_quantum_states(quantum_states): # import the useful tool for drawing figures in pythpn from matplotlib.pyplot import plot, show, figure, Circle, axis, gca, annotate, arrow, text # import the constant pi from math import pi figure(figsize=(6,6), dpi=80) # size of the figure gca().add_patch( Circle((0,0),1,color='black',fill=False) ) # draw the circle # auxiliary points plot(-1.3,0) plot(1.3,0) plot(0,1.3) plot(0,-1.3) # axes arrow(0,0,1.1,0,head_width=0.04, head_length=0.08) arrow(0,0,-1.1,0,head_width=0.04, head_length=0.08) arrow(0,0,0,-1.1,head_width=0.04, head_length=0.08) arrow(0,0,0,1.1,head_width=0.04, head_length=0.08) # draw all quantum states for quantum_state in quantum_states: # show the quantum state as an arrow on the diagram state_name = quantum_state[0] # label of the quantum state x_value = quantum_state[1] # amplitude of |0> y_value = quantum_state[2] # amplitude of |1> # draw the arrow arrow(0,0,x_value,y_value,head_width=0.04, head_length=0.04,color='blue') # the following code is used to write the name of quantum states if x_value<0: text_x_value=x_value-0.1 else: text_x_value=x_value+0.05 if y_value<0: text_y_value=y_value-0.1 else: text_y_value=y_value+0.05 text(text_x_value,text_y_value,state_name) show() # show the diagram # end of function # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer how_many_times_state_one_observed = 0 decrease = False number_of_iteration = 1 while decrease == False: qreg4 = QuantumRegister(1) # quantum register with 1 qubit creg4 = ClassicalRegister(1) # classical register with 1 bit mycircuit4 = QuantumCircuit(qreg4,creg4) # quantum circuit with quantum and classical registers # set the qubit to |u> # rotate by theta4 # do not forget to multiply it by 2 mycircuit4.ry(2*theta4,qreg4[0]) # this is -2 * theta4 in the first iteration rotation_angle_for_the_first_reflection4 = -2 * theta4 # this is always (2*theta4) more than (-1*rotation_angle_for_the_first_reflection4) rotation_angle_for_the_second_reflection4 = (2*theta4) + (-1*rotation_angle_for_the_first_reflection4) for i in range(number_of_iteration): # the first reflection: rotate by rotation_angle_for_the_first_reflection4 mycircuit4.ry(2*rotation_angle_for_the_first_reflection4,qreg4[0]) # the second reflection: rotate by rotation_angle_for_the_second_reflcetion4 mycircuit4.ry(2*rotation_angle_for_the_second_reflection4,qreg4[0]) # this will be increased by (-4*theta4) after each iteration rotation_angle_for_the_first_reflection4 = rotation_angle_for_the_first_reflection4 -4* theta4 # this is always (2*theta4) more than (-1*rotation_angle_for_the_first_reflection4) rotation_angle_for_the_second_reflection4 = (2*theta4) + (-1*rotation_angle_for_the_first_reflection4) # end of iterations # measure both qubits mycircuit4.measure(qreg4,creg4) # execute the circuit 1000 times, and print the outcomes job = execute(mycircuit4,Aer.get_backend('qasm_simulator'),shots=1000) counts4 = job.result().get_counts(mycircuit4) print(number_of_iteration,counts4) # print the outcomes for outcome in counts4: if outcome == '1': # how_many_times_state_one_observed is more than 500 and has a less value than the previous one # then it is time to STOP if how_many_times_state_one_observed> 500 and how_many_times_state_one_observed > counts4[outcome]: print("B is",number_of_iteration-1) decrease = True else: # we should continue how_many_times_state_one_observed = counts4[outcome] # update how_many_times_state_one_observed number_of_iteration = number_of_iteration + 1 # increase number_of_iteration
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from IPython.display import HTML HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide(); } else { $('div.input').show(); } code_show = !code_show } $( document ).ready(code_toggle); </script> <form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code for QISKit exercises."></form>''') from qiskit import * # Quantum program setup Q_program = QuantumProgram() # Creating registers q = Q_program.create_quantum_register('q', 5) c0 = Q_program.create_classical_register('c0', 1) c1 = Q_program.create_classical_register('c1', 1) c2 = Q_program.create_classical_register('c2', 1) # Creates the quantum circuit bit_flip = Q_program.create_circuit('bit_flip', [q], [c0,c1,c2]) # Prepares qubit in the desired initial state bit_flip.h(q[0]) # Encodes the qubit in a three-qubit entangled state bit_flip.cx(q[0], q[1]) bit_flip.cx(q[0], q[2]) # Bit-flip error on the second qubit bit_flip.x(q[1]) # Adds additional two qubits for error-correction bit_flip.cx(q[0], q[3]) bit_flip.cx(q[1], q[3]) bit_flip.cx(q[0], q[4]) bit_flip.cx(q[2], q[4]) # Measure the two additional qubits bit_flip.measure(q[3], c0[0]) bit_flip.measure(q[4], c1[0]) # Do error correction bit_flip.x(q[1]).c_if(c0, 1) bit_flip.x(q[2]).c_if(c1, 1) # Decodes the qubit from the three-qubit entangled state bit_flip.cx(q[0], q[1]) bit_flip.cx(q[0], q[2]) # Check the state of the initial qubit bit_flip.measure(q[0], c2[0]) # Shows gates of the circuit circuits = ['bit_flip'] print(Q_program.get_qasms(circuits)[0]) # Parameters for execution on simulator backend = 'local_qasm_simulator' shots = 1024 # the number of shots in the experiment # Run the algorithm result = Q_program.execute(circuits, backend=backend, shots=shots) #Shows the results obtained from the quantum algorithm counts = result.get_counts('bit_flip') print('\nThe measured outcomes of the circuits are:', counts) from qiskit import * # Quantum program setup Q_program = QuantumProgram() # Creating registers q = Q_program.create_quantum_register('q', 5) c0 = Q_program.create_classical_register('c0', 1) c1 = Q_program.create_classical_register('c1', 1) c2 = Q_program.create_classical_register('c2', 1) # Creates the quantum circuit bit_flip = Q_program.create_circuit('bit_flip', [q], [c0,c1,c2]) # Prepares qubit in the desired initial state bit_flip.h(q[0]) # Encodes the qubit in a three-qubit entangled state bit_flip.cx(q[0], q[1]) bit_flip.cx(q[0], q[2]) # Go to Hadamard basis bit_flip.h(q[0]) bit_flip.h(q[1]) bit_flip.h(q[2]) # Phase error on the second qubit bit_flip.z(q[1]) # Converts phase error in bit-flip error bit_flip.h(q[0]) bit_flip.h(q[1]) bit_flip.h(q[2]) # Adds additional two qubits for error-correction bit_flip.cx(q[0], q[3]) bit_flip.cx(q[1], q[3]) bit_flip.cx(q[0], q[4]) bit_flip.cx(q[2], q[4]) # Measure the two additional qubits bit_flip.measure(q[3], c0[0]) bit_flip.measure(q[4], c1[0]) # Do error correction bit_flip.x(q[1]).c_if(c0, 1) bit_flip.x(q[2]).c_if(c1, 1) # Decodes the qubit from the three-qubit entangled state bit_flip.cx(q[0], q[1]) bit_flip.cx(q[0], q[2]) # Check the state of the initial qubit bit_flip.measure(q[0], c2[0]) # Shows gates of the circuit circuits = ['bit_flip'] print(Q_program.get_qasms(circuits)[0]) # Parameters for execution on simulator backend = 'local_qasm_simulator' shots = 1024 # the number of shots in the experiment # Run the algorithm result = Q_program.execute(circuits, backend=backend, shots=shots) #Shows the results obtained from the quantum algorithm counts = result.get_counts('bit_flip') print('\nThe measured outcomes of the circuits are:', counts)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from initialize import * my_algorithm = initialize(circuit_name = 'demo', qubit_number=2, bit_number=2, backend = 'local_qasm_simulator', shots = 1024) #Append sequence of gates to the quantum circuit. #For each gate, the qubits on which it is acting must be specified along with other gate-dependent parameters my_algorithm.q_circuit.x(my_algorithm.q_reg[0]) # apply the X gate to the first qubit my_algorithm.q_circuit.x(my_algorithm.q_reg[1]) # apply the X gate to the second qubit my_algorithm.q_circuit.h(my_algorithm.q_reg[0]) # apply the Hadamard gate to the first qubit my_algorithm.q_circuit.cx(my_algorithm.q_reg[0],my_algorithm.q_reg[1]) # apply the CNOT gate using the first qubit as control and second qubit as target my_algorithm.q_circuit.measure(my_algorithm.q_reg[0], my_algorithm.c_reg[0]) # measures the first qubit and store the result in the first bit my_algorithm.q_circuit.measure(my_algorithm.q_reg[1], my_algorithm.c_reg[1]) # measures the second qubit and store the result in the second bit print('List of gates:') for circuit in my_algorithm.q_circuit: print(circuit.name) #Execute the quantum algorithm result = my_algorithm.Q_program.execute(my_algorithm.circ_name, backend=my_algorithm.backend, shots= my_algorithm.shots) #Show the results obtained from the quantum algorithm counts = result.get_counts(my_algorithm.circ_name) ## you can declare/initiate q_name first at the time you initialize circuit, print('\nThe measured outcomes of the circuits are:',counts) from initialize import * #initialize quantum program my_alg = initialize(circuit_name = 'multi', qubit_number=7, bit_number=7, backend = 'local_qasm_simulator', shots = 1024) #add gates to the circuit my_alg.q_circuit.x(my_alg.q_reg[1]) # applies X gate to second qubit my_alg.q_circuit.x(my_alg.q_reg[3]) # applies X gate to fourth qubit my_alg.q_circuit.x(my_alg.q_reg[5]) # applies X gate to sixth qubit my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit and store the result in the first bit my_alg.q_circuit.measure(my_alg.q_reg[1], my_alg.c_reg[1]) # measures the second qubit and store the result in the second bit my_alg.q_circuit.measure(my_alg.q_reg[2], my_alg.c_reg[2]) # measures the third qubit and store the result in the third bit my_alg.q_circuit.measure(my_alg.q_reg[3], my_alg.c_reg[3]) # measures the fourth qubit and store the result in the fourth bit my_alg.q_circuit.measure(my_alg.q_reg[4], my_alg.c_reg[4]) # measures the fifth qubit and store the result in the fifth bit my_alg.q_circuit.measure(my_alg.q_reg[5], my_alg.c_reg[5]) # measures the sixth qubit and store the result in the sixth bit my_alg.q_circuit.measure(my_alg.q_reg[6], my_alg.c_reg[6]) # measures the seventh qubit and store the result in the seventh bit print('List of gates:') for circuit in my_alg.q_circuit: print(circuit.name) #Execute the quantum algorithm result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots) #Show the results obtained from the quantum algorithm counts = result.get_counts(my_alg.circ_name) print('\nThe measured outcomes of the circuits are:',counts) from initialize import * #initialize quantum program my_alg = initialize(circuit_name = 'multi_super', qubit_number=2, bit_number=2, backend = 'local_qasm_simulator', shots = 1024) #add gates to the circuit my_alg.q_circuit.h(my_alg.q_reg[0]) # applies H gate to first qubit my_alg.q_circuit.h(my_alg.q_reg[1]) # applies X gate to second qubit my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit and store the result in the first bit my_alg.q_circuit.measure(my_alg.q_reg[1], my_alg.c_reg[1]) # measures the second qubit and store the result in the second bit print('List of gates:') for circuit in my_alg.q_circuit: print(circuit.name) #Execute the quantum algorithm result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots) #Show the results obtained from the quantum algorithm counts = result.get_counts(my_alg.circ_name) print('\nThe measured outcomes of the circuits are:',counts) from initialize import * #initialize quantum program my_alg = initialize(circuit_name = 'bell', qubit_number=2, bit_number=2, backend = 'local_qasm_simulator', shots = 1024) #add gates to the circuit my_alg.q_circuit.h(my_alg.q_reg[0]) # applies H gate to first qubit my_alg.q_circuit.cx(my_alg.q_reg[0],my_alg.q_reg[1]) # applies CX gate using the first qubit as control and the second qubit as target my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit and store the result in the first bit my_alg.q_circuit.measure(my_alg.q_reg[1], my_alg.c_reg[1]) # measures the second qubit and store the result in the second bit print('List of gates:') for circuit in my_alg.q_circuit: print(circuit.name) #Execute the quantum algorithm result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots) #Show the results obtained from the quantum algorithm counts = result.get_counts(my_alg.circ_name) print('\nThe measured outcomes of the circuits are:',counts) from initialize import * #initialize quantum program my_alg = initialize(circuit_name = 'x_gate', qubit_number=1, bit_number=1, backend = 'local_qasm_simulator', shots = 1024) #add gates to the circuit my_alg.q_circuit.x(my_alg.q_reg[0]) # applies X gate to first qubit my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit and store the result in the first bit print('List of gates:') for circuit in my_alg.q_circuit: print(circuit.name) #Execute the quantum algorithm result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots) #Show the results obtained from the quantum algorithm counts = result.get_counts(my_alg.circ_name) print('\nThe measured outcomes of the circuits are:',counts) from initialize import * #initialize quantum program my_alg = initialize(circuit_name = 'y_gate', qubit_number=1, bit_number=1, backend = 'local_qasm_simulator', shots = 1024) #add gates to the circuit my_alg.q_circuit.y(my_alg.q_reg[0]) # applies Y gate to first qubit my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit and store the result in the first bit print('List of gates:') for circuit in my_alg.q_circuit: print(circuit.name) #Execute the quantum algorithm result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots) #Show the results obtained from the quantum algorithm counts = result.get_counts(my_alg.circ_name) print('\nThe measured outcomes of the circuits are:',counts) from initialize import * #initialize quantum program my_alg = initialize(circuit_name = 'h_gate', qubit_number=1, bit_number=1, backend = 'local_qasm_simulator', shots = 1024) #add gates to the circuit my_alg.q_circuit.h(my_alg.q_reg[0]) # applies H gate to first qubit my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit and store the result in the first bit print('List of gates:') for circuit in my_alg.q_circuit: print(circuit.name) #Execute the quantum algorithm result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots) #Show the results obtained from the quantum algorithm counts = result.get_counts(my_alg.circ_name) print('\nThe measured outcomes of the circuits are:',counts) from initialize import * #initialize quantum program my_alg = initialize(circuit_name = 'rx_gate', qubit_number=1, bit_number=1, backend = 'local_qasm_simulator', shots = 1024) theta = 0.79 # angle of rotation pi/4 #add gates to the circuit my_alg.q_circuit.rx(theta, my_alg.q_reg[0]) # applies x-rotation of angle theta to first qubit my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit and store the result in the first bit print('List of gates:') for circuit in my_alg.q_circuit: print(circuit.name) #Execute the quantum algorithm result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots) #Show the results obtained from the quantum algorithm counts = result.get_counts(my_alg.circ_name) print('\nThe measured outcomes of the circuits are:',counts) from initialize import * for _ in range(4): # run over all possible initial states of two qubits #initialize quantum program my_alg = initialize(circuit_name = 'cx_gate', qubit_number=2, bit_number=2, backend = 'local_qasm_simulator', shots = 1024) #add gates to the circuit if _ == 1: my_alg.q_circuit.x(my_alg.q_reg[0]) # applies X gate to first qubit (prepares state 10) if _ == 2: my_alg.q_circuit.x(my_alg.q_reg[1]) # applies X gate to second qubit (prepares state 01) if _ == 3: my_alg.q_circuit.x(my_alg.q_reg[0]) # applies X gate to first qubit my_alg.q_circuit.x(my_alg.q_reg[1]) # applies X gate to second qubit (prepares state 11) my_alg.q_circuit.cx(my_alg.q_reg[0],my_alg.q_reg[1]) ## applies CX gate using the first qubit as control and the second qubit as target my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit and store the result in the first bit my_alg.q_circuit.measure(my_alg.q_reg[1], my_alg.c_reg[1]) # measures the second qubit and store the result in the second bit print('List of gates:') for circuit in my_alg.q_circuit: print(circuit.name) #Execute the quantum algorithm result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots) #Show the results obtained from the quantum algorithm counts = result.get_counts(my_alg.circ_name) print('\nThe measured outcomes of the circuits are:',counts) from initialize import * #initialize quantum program my_alg = initialize(circuit_name = 'evo_1', qubit_number=1, bit_number=1, backend = 'local_qasm_simulator', shots = 1024) #add gates to the circuit my_alg.q_circuit.iden(my_alg.q_reg[0]) # applies U1 my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit and store the result in the first bit print('List of gates:') for circuit in my_alg.q_circuit: print(circuit.name) #Execute the quantum algorithm result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots) #Show the results obtained from the quantum algorithm counts = result.get_counts(my_alg.circ_name) print('\nThe measured outcomes of the circuits are:',counts) from initialize import * #initialize quantum program my_alg = initialize(circuit_name = 'evo_2', qubit_number=1, bit_number=1, backend = 'local_qasm_simulator', shots = 1024) #add gates to the circuit my_alg.q_circuit.iden(my_alg.q_reg[0]) my_alg.q_circuit.x(my_alg.q_reg[0]) # applies U2 my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit and store the result in the first bit print('List of gates:') for circuit in my_alg.q_circuit: print(circuit.name) #Execute the quantum algorithm result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots) #Show the results obtained from the quantum algorithm counts = result.get_counts(my_alg.circ_name) print('\nThe measured outcomes of the circuits are:',counts) from initialize import * #initialize quantum program my_alg = initialize(circuit_name = 'evo_3', qubit_number=1, bit_number=1, backend = 'local_qasm_simulator', shots = 1024) #add gates to the circuit my_alg.q_circuit.iden(my_alg.q_reg[0]) my_alg.q_circuit.x(my_alg.q_reg[0]) my_alg.q_circuit.x(my_alg.q_reg[0]) # applies U3 my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit and store the result in the first bit print('List of gates:') for circuit in my_alg.q_circuit: print(circuit.name) #Execute the quantum algorithm result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots) #Show the results obtained from the quantum algorithm counts = result.get_counts(my_alg.circ_name) print('\nThe measured outcomes of the circuits are:',counts)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from IPython.display import HTML HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide(); } else { $('div.input').show(); } code_show = !code_show } $( document ).ready(code_toggle); </script> <form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code for QISKit exercises."></form>''') from initialize import * #initialize quantum program my_alg = initialize(circuit_name = 'deutsch', qubit_number=2, bit_number=1, backend = 'local_qasm_simulator', shots = 1024) #add gates to the circuit my_alg.q_circuit.x(my_alg.q_reg[1]) # initializes ancilla qubit my_alg.q_circuit.h(my_alg.q_reg[0]) # applies H gate to first qubit my_alg.q_circuit.h(my_alg.q_reg[1]) # applies H gate to second qubit my_alg.q_circuit.cx(my_alg.q_reg[0],my_alg.q_reg[1]) ## applies CX gate as the query function my_alg.q_circuit.h(my_alg.q_reg[0]) # applies H gate to first qubit my_alg.q_circuit.h(my_alg.q_reg[1]) # applies H gate to second qubit my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit and store the result in the first bit print('List of gates:') for circuit in my_alg.q_circuit: print(circuit.name) #Execute the quantum algorithm result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots) #Show the results obtained from the quantum algorithm counts = result.get_counts(my_alg.circ_name) print('\nThe measured outcomes of the circuits are:',counts) from initialize import * #initialize quantum program my_alg = initialize(circuit_name = 'ber_vaz', qubit_number=3, bit_number=2, backend = 'local_qasm_simulator', shots = 1024) #add gates to the circuit my_alg.q_circuit.x(my_alg.q_reg[2]) # initializes ancilla qubit my_alg.q_circuit.h(my_alg.q_reg[0]) # applies H gate to first qubit my_alg.q_circuit.h(my_alg.q_reg[1]) # applies H gate to second qubit my_alg.q_circuit.h(my_alg.q_reg[2]) # applies H gate to third qubit my_alg.q_circuit.cx(my_alg.q_reg[1],my_alg.q_reg[2]) ## applies CX gate as the query function my_alg.q_circuit.cx(my_alg.q_reg[0],my_alg.q_reg[2]) ## applies CX gate as the query function my_alg.q_circuit.h(my_alg.q_reg[0]) # applies H gate to first qubit my_alg.q_circuit.h(my_alg.q_reg[1]) # applies H gate to second qubit my_alg.q_circuit.h(my_alg.q_reg[2]) # applies H gate to third qubit my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit and store the result in the first bit my_alg.q_circuit.measure(my_alg.q_reg[1], my_alg.c_reg[1]) # measures the second qubit and store the result in the second bit print('List of gates:') for circuit in my_alg.q_circuit: print(circuit.name) #Execute the quantum algorithm result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots) #Show the results obtained from the quantum algorithm counts = result.get_counts(my_alg.circ_name) print('\nThe measured outcomes of the circuits are:',counts) from initialize import * #initialize quantum program my_alg = initialize(circuit_name = 'simon', qubit_number=4, bit_number=4, backend = 'local_qasm_simulator', shots = 1024) #add gates to the circuit my_alg.q_circuit.h(my_alg.q_reg[0]) # applies H gate to first qubit my_alg.q_circuit.h(my_alg.q_reg[1]) # applies H gate to second qubit my_alg.q_circuit.cx(my_alg.q_reg[0],my_alg.q_reg[2]) ## applies CX gate as the query function my_alg.q_circuit.cx(my_alg.q_reg[0],my_alg.q_reg[3]) ## applies CX gate as the query function my_alg.q_circuit.cx(my_alg.q_reg[1],my_alg.q_reg[2]) ## applies CX gate as the query function my_alg.q_circuit.cx(my_alg.q_reg[1],my_alg.q_reg[3]) ## applies CX gate as the query function my_alg.q_circuit.measure(my_alg.q_reg[2], my_alg.c_reg[2]) # measures the third qubit my_alg.q_circuit.measure(my_alg.q_reg[3], my_alg.c_reg[3]) # measures the fourth qubit my_alg.q_circuit.h(my_alg.q_reg[0]) # applies H gate to first qubit my_alg.q_circuit.h(my_alg.q_reg[1]) # applies H gate to second qubit my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit my_alg.q_circuit.measure(my_alg.q_reg[1], my_alg.c_reg[1]) # measures the second qubit print('List of gates:') for circuit in my_alg.q_circuit: print(circuit.name) #Execute the quantum algorithm result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots) #Show the results obtained from the quantum algorithm counts = result.get_counts(my_alg.circ_name) print('\nThe measured outcomes of the circuits are:',counts)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from IPython.display import HTML HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide(); } else { $('div.input').show(); } code_show = !code_show } $( document ).ready(code_toggle); </script> <form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code for QISKit exercises."></form>''') from qiskit import * # Quantum program setup Q_program = QuantumProgram() # Creating registers q = Q_program.create_quantum_register('q', 3) c0 = Q_program.create_classical_register('c0', 1) c1 = Q_program.create_classical_register('c1', 1) c2 = Q_program.create_classical_register('c2', 1) # Creates the quantum circuit teleport = Q_program.create_circuit('teleport', [q], [c0,c1,c2]) # Make the shared entangled state teleport.h(q[1]) teleport.cx(q[1], q[2]) # Prepare Alice's qubit teleport.h(q[0]) # Alice applies teleportation gates (or projects to Bell basis) teleport.cx(q[0], q[1]) teleport.h(q[0]) # Alice measures her qubits teleport.measure(q[0], c0[0]) teleport.measure(q[1], c1[0]) # Bob applies certain gates based on the outcome of Alice's measurements teleport.z(q[2]).c_if(c0, 1) teleport.x(q[2]).c_if(c1, 1) # Bob checks the state of the teleported qubit teleport.measure(q[2], c2[0]) # Shows gates of the circuit circuits = ['teleport'] print(Q_program.get_qasms(circuits)[0]) # Parameters for execution on simulator backend = 'local_qasm_simulator' shots = 1024 # the number of shots in the experiment # Run the algorithm result = Q_program.execute(circuits, backend=backend, shots=shots) #Shows the results obtained from the quantum algorithm counts = result.get_counts('teleport') print('\nThe measured outcomes of the circuits are:', counts) # credits to: https://github.com/QISKit/qiskit-tutorial from initialize import * from qiskit import * #initialize quantum program my_alg = initialize(circuit_name = 'superdense', qubit_number=2, bit_number=2, backend = 'local_qasm_simulator', shots = 1024) #add gates to the circuit #creates a bell pair my_alg.q_circuit.h(my_alg.q_reg[0]) # applies H gate to first qubit my_alg.q_circuit.cx(my_alg.q_reg[0],my_alg.q_reg[1]) ## applies CX gate #Alice encodes 01 my_alg.q_circuit.x(my_alg.q_reg[0]) #to measure in the Bell basis, Bob does the following operations before measuring in the standard basis my_alg.q_circuit.cx(my_alg.q_reg[0],my_alg.q_reg[1]) ## applies CX gate my_alg.q_circuit.h(my_alg.q_reg[0]) # applies H gate to first qubit my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures the first qubit my_alg.q_circuit.measure(my_alg.q_reg[1], my_alg.c_reg[1]) # measures the second qubit print('List of gates:') for circuit in my_alg.q_circuit: print(circuit.name) #Execute the quantum algorithm result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots) #Show the results obtained from the quantum algorithm counts = result.get_counts(my_alg.circ_name) print('\nThe measured outcomes of the circuits are:',counts) # credits to: https://github.com/QISKit/qiskit-tutorial
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from IPython.display import HTML HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide(); } else { $('div.input').show(); } code_show = !code_show } $( document ).ready(code_toggle); </script> <form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code for QISKit exercises."></form>''') # QISKIT: QFT code # calculate qft of two qubit as the example above from initialize import * def qft(circ, q, n): """n-qubit QFT on q in circ.""" for j in range(n): for k in range(j): circ.cu1(3.14/float(2**(j-k)), q[j], q[k]) circ.h(q[j]) #initialize quantum program my_alg = initialize(circuit_name = 'fourier', qubit_number=2, bit_number=2, backend = 'local_qasm_simulator', shots = 1024) #add gates to the circuit qft(my_alg.q_circuit, my_alg.q_reg, 2) # qft of input state my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures first qubit my_alg.q_circuit.measure(my_alg.q_reg[1], my_alg.c_reg[1]) # measures second qubit # print list of gates in the circuit print('List of gates:') for circuit in my_alg.q_circuit: print(circuit.name) #Execute the quantum algorithm result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots) #Show the results obtained from the quantum algorithm counts = result.get_counts(my_alg.circ_name) print('\nThe measured outcomes of the circuits are:',counts) # credits to: https://github.com/QISKit/qiskit-tutorial
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from IPython.display import HTML HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide(); } else { $('div.input').show(); } code_show = !code_show } $( document ).ready(code_toggle); </script> <form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code for QISKit exercises."></form>''') from initialize import * import random #initialize quantum program my_alg = initialize(circuit_name = 'bb84', qubit_number=1, bit_number=1, backend = 'local_qasm_simulator', shots = 1) #add gates to the circuit # Alice encodes the bit 1 into a qubit my_alg.q_circuit.x(my_alg.q_reg[0]) # Alice randomly applies the Hadamard gate to go to the Hadamard basis a = random.randint(0,1) if a==1: my_alg.q_circuit.h(my_alg.q_reg[0]) # Bob randomly applies the Hadamard gate to go to the Hadamard basis b = random.randint(0,1) if b==1: my_alg.q_circuit.h(my_alg.q_reg[0]) my_alg.q_circuit.measure(my_alg.q_reg[0], my_alg.c_reg[0]) # measures first qubit # print list of gates in the circuit print('List of gates:') for circuit in my_alg.q_circuit: print(circuit.name) #Execute the quantum algorithm result = my_alg.Q_program.execute(my_alg.circ_name, backend=my_alg.backend, shots= my_alg.shots) #Show the results obtained from the quantum algorithm counts = result.get_counts(my_alg.circ_name) print('\nThe measured outcomes of the circuits are:',counts) if a == b: print('Alice and Bob agree on the basis, thus they keep the bit') else: print("Alice and Bob don't agree the same basis, thus they discard the bit") ### <span style="color:blue"> QISKit: EPR protocol </span> #### <span style="color:blue"> 3) Show the communication of one bit </span>
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Example use of the initialize gate to prepare arbitrary pure states. """ import math from qiskit import QuantumCircuit, execute, BasicAer ############################################################### # Make a quantum circuit for state initialization. ############################################################### circuit = QuantumCircuit(4, 4, name="initializer_circ") desired_vector = [ 1 / math.sqrt(4) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(8) * complex(0, 1), 0, 0, 0, 0, 1 / math.sqrt(4) * complex(1, 0), 1 / math.sqrt(8) * complex(1, 0), ] circuit.initialize(desired_vector, [0, 1, 2, 3]) circuit.measure([0, 1, 2, 3], [0, 1, 2, 3]) print(circuit) ############################################################### # Execute on a simulator backend. ############################################################### shots = 10000 # Desired vector print("Desired probabilities: ") print([format(abs(x * x), ".3f") for x in desired_vector]) # Initialize on local simulator sim_backend = BasicAer.get_backend("qasm_simulator") job = execute(circuit, sim_backend, shots=shots) result = job.result() counts = result.get_counts(circuit) qubit_strings = [format(i, "04b") for i in range(2**4)] print("Probabilities from simulator: ") print([format(counts.get(s, 0) / shots, ".3f") for s in qubit_strings])
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import matplotlib import networkx import numpy import sklearn import scipy import dwave_networkx import dimod import minorminer import qiskit import qiskit_aqua
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit import execute from qiskit import BasicAer import numpy as np np.set_printoptions(precision=3, suppress=True) backend = BasicAer.get_backend('qasm_simulator') q = QuantumRegister(1) c = ClassicalRegister(1) circuit = QuantumCircuit(q, c) circuit.measure(q[0], c[0]) job = execute(circuit, backend, shots=100) result = job.result() result.get_counts(circuit) backend = BasicAer.get_backend('statevector_simulator') circuit = QuantumCircuit(q, c) circuit.iden(q[0]) job = execute(circuit, backend) state = job.result().get_statevector(circuit) print(state) from qiskit.tools.visualization import circuit_drawer q = QuantumRegister(1) c = ClassicalRegister(1) circuit = QuantumCircuit(q, c) circuit.measure(q[0], c[0]) circuit_drawer(circuit) from qiskit.tools.visualization import plot_bloch_multivector backend = BasicAer.get_backend('statevector_simulator') circuit = QuantumCircuit(q, c) circuit.iden(q[0]) job = execute(circuit, backend) state = job.result().get_statevector(circuit) print("Initial state") plot_bloch_multivector(state) circuit.h(q[0]) job = execute(circuit, backend) state = job.result().get_statevector(circuit) print("After a Hadamard gate") plot_bloch_multivector(state) from qiskit.tools.visualization import plot_histogram backend = BasicAer.get_backend('qasm_simulator') q = QuantumRegister(1) c = ClassicalRegister(1) circuit = QuantumCircuit(q, c) circuit.measure(q[0], c[0]) job = execute(circuit, backend, shots=1000) print("Initial state statistics") plot_histogram(job.result().get_counts(circuit)) circuit = QuantumCircuit(q, c) circuit.h(q[0]) circuit.measure(q[0], c[0]) job = execute(circuit, backend, shots=1000) print("Statistics if we apply a Hadamard gate") plot_histogram(job.result().get_counts(circuit))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np n_samples = 100 p_1 = 0.2 x_data = np.random.binomial(1, p_1, (n_samples,)) print(x_data) frequency_of_zeros, frequency_of_ones = 0, 0 for x in x_data: if x: frequency_of_ones += 1/n_samples else: frequency_of_zeros += 1/n_samples print(frequency_of_ones+frequency_of_zeros) import matplotlib.pyplot as plt %matplotlib inline p_0 = np.linspace(0, 1, 100) p_1 = 1-p_0 fig, ax = plt.subplots() ax.set_xlim(-1.2, 1.2) ax.set_ylim(-1.2, 1.2) ax.spines['left'].set_position('center') ax.spines['bottom'].set_position('center') ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.set_xlabel("$p_0$") ax.xaxis.set_label_coords(1.0, 0.5) ax.set_ylabel("$p_1$") ax.yaxis.set_label_coords(0.5, 1.0) plt.plot(p_0, p_1) p = np.array([[0.8], [0.2]]) np.linalg.norm(p, ord=1) Π_0 = np.array([[1, 0], [0, 0]]) np.linalg.norm(Π_0.dot(p), ord=1) Π_1 = np.array([[0, 0], [0, 1]]) np.linalg.norm(Π_1.dot(p), ord=1) p = np.array([[.5], [.5]]) M = np.array([[0.7, 0.6], [0.3, 0.4]]) np.linalg.norm(M.dot(p), ord=1) ϵ = 10e-10 p_0 = np.linspace(ϵ, 1-ϵ, 100) p_1 = 1-p_0 H = -(p_0*np.log(p_0) + p_1*np.log(p_1)) fig, ax = plt.subplots() ax.set_xlim(0, 1) ax.set_ylim(0, -np.log(0.5)) ax.set_xlabel("$p_0$") ax.set_ylabel("$H$") plt.plot(p_0, H) plt.axvline(x=0.5, color='k', linestyle='--') from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute from qiskit import BasicAer from qiskit.tools.visualization import plot_histogram, plot_bloch_multivector import numpy as np π = np.pi backend = BasicAer.get_backend('qasm_simulator') q = QuantumRegister(1) c = ClassicalRegister(1) circuit = QuantumCircuit(q, c) circuit.measure(q, c) job = execute(circuit, backend, shots=100) result = job.result() result.get_counts(circuit) backend_statevector = BasicAer.get_backend('statevector_simulator') circuit = QuantumCircuit(q, c) circuit.iden(q[0]) job = execute(circuit, backend_statevector) plot_bloch_multivector(job.result().get_statevector(circuit)) circuit = QuantumCircuit(q, c) circuit.ry(π/2, q[0]) circuit.measure(q, c) job = execute(circuit, backend, shots=100) plot_histogram(job.result().get_counts(circuit)) circuit = QuantumCircuit(q, c) circuit.ry(π/2, q[0]) job = execute(circuit, backend_statevector) plot_bloch_multivector(job.result().get_statevector(circuit)) circuit = QuantumCircuit(q, c) circuit.x(q[0]) circuit.ry(π/2, q[0]) job = execute(circuit, backend_statevector) plot_bloch_multivector(job.result().get_statevector(circuit)) circuit.measure(q, c) job = execute(circuit, backend, shots=100) plot_histogram(job.result().get_counts(circuit)) circuit = QuantumCircuit(q, c) circuit.ry(π/2, q[0]) circuit.ry(π/2, q[0]) circuit.measure(q, c) job = execute(circuit, backend, shots=100) plot_histogram(job.result().get_counts(circuit)) q0 = np.array([[1], [0]]) q1 = np.array([[1], [0]]) np.kron(q0, q1) q = QuantumRegister(2) c = ClassicalRegister(2) circuit = QuantumCircuit(q, c) circuit.h(q[0]) circuit.cx(q[0], q[1]) circuit.measure(q, c) job = execute(circuit, backend, shots=100) plot_histogram(job.result().get_counts(circuit))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np zero_ket = np.array([[1], [0]]) print("|0> ket:\n", zero_ket) print("<0| bra:\n", zero_ket.T.conj()) zero_ket.T.conj().dot(zero_ket) one_ket = np.array([[0], [1]]) zero_ket.T.conj().dot(one_ket) zero_ket.dot(zero_ket.T.conj()) ψ = np.array([[1], [1]])/np.sqrt(2) Π_0 = zero_ket.dot(zero_ket.T.conj()) ψ.T.conj().dot(Π_0.dot(ψ)) from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute from qiskit import BasicAer from qiskit.tools.visualization import plot_histogram backend = BasicAer.get_backend('qasm_simulator') q = QuantumRegister(1) c = ClassicalRegister(1) circuit = QuantumCircuit(q, c) circuit.h(q[0]) circuit.measure(q, c) job = execute(circuit, backend, shots=100) plot_histogram(job.result().get_counts(circuit)) ψ = np.array([[np.sqrt(2)/2], [np.sqrt(2)/2]]) Π_0 = zero_ket.dot(zero_ket.T.conj()) probability_0 = ψ.T.conj().dot(Π_0.dot(ψ)) Π_0.dot(ψ)/np.sqrt(probability_0) c = ClassicalRegister(2) circuit = QuantumCircuit(q, c) circuit.h(q[0]) circuit.measure(q[0], c[0]) circuit.measure(q[0], c[1]) job = execute(circuit, backend, shots=100) job.result().get_counts(circuit) q = QuantumRegister(2) c = ClassicalRegister(2) circuit = QuantumCircuit(q, c) circuit.h(q[0]) circuit.measure(q, c) job = execute(circuit, backend, shots=100) plot_histogram(job.result().get_counts(circuit)) q = QuantumRegister(2) c = ClassicalRegister(2) circuit = QuantumCircuit(q, c) circuit.h(q[0]) circuit.cx(q[0], q[1]) circuit.measure(q, c) job = execute(circuit, backend, shots=100) plot_histogram(job.result().get_counts(circuit)) ψ = np.array([[1], [1]])/np.sqrt(2) ρ = ψ.dot(ψ.T.conj()) Π_0 = zero_ket.dot(zero_ket.T.conj()) np.trace(Π_0.dot(ρ)) probability_0 = np.trace(Π_0.dot(ρ)) Π_0.dot(ρ).dot(Π_0)/probability_0 zero_ket = np.array([[1], [0]]) one_ket = np.array([[0], [1]]) ψ = (zero_ket + one_ket)/np.sqrt(2) print("Density matrix of the equal superposition") print(ψ.dot(ψ.T.conj())) print("Density matrix of the equally mixed state of |0><0| and |1><1|") print((zero_ket.dot(zero_ket.T.conj())+one_ket.dot(one_ket.T.conj()))/2)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np X = np.array([[0, 1], [1, 0]]) print("XX^dagger") print(X.dot(X.T.conj())) print("X^daggerX") print(X.T.conj().dot(X)) print("The norm of the state |0> before applying X") zero_ket = np.array([[1], [0]]) print(np.linalg.norm(zero_ket)) print("The norm of the state after applying X") print(np.linalg.norm(X.dot(zero_ket))) import numpy as np from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute from qiskit import BasicAer from qiskit.tools.visualization import circuit_drawer np.set_printoptions(precision=3, suppress=True) backend_statevector = BasicAer.get_backend('statevector_simulator') q = QuantumRegister(1) c = ClassicalRegister(1) circuit = QuantumCircuit(q, c) circuit.x(q[0]) circuit.x(q[0]) job = execute(circuit, backend_statevector) print(job.result().get_statevector(circuit)) def mixed_state(pure_state, visibility): density_matrix = pure_state.dot(pure_state.T.conj()) maximally_mixed_state = np.eye(4)/2**2 return visibility*density_matrix + (1-visibility)*maximally_mixed_state ϕ = np.array([[1],[0],[0],[1]])/np.sqrt(2) print("Maximum visibility is a pure state:") print(mixed_state(ϕ, 1.0)) print("The state is still entangled with visibility 0.8:") print(mixed_state(ϕ, 0.8)) print("Entanglement is lost by 0.6:") print(mixed_state(ϕ, 0.6)) print("Barely any coherence remains by 0.2:") print(mixed_state(ϕ, 0.2)) import matplotlib.pyplot as plt temperatures = [.5, 5, 2000] energies = np.linspace(0, 20, 100) fig, ax = plt.subplots() for i, T in enumerate(temperatures): probabilities = np.exp(-energies/T) Z = probabilities.sum() probabilities /= Z ax.plot(energies, probabilities, linewidth=3, label = "$T_" + str(i+1)+"$") ax.set_xlim(0, 20) ax.set_ylim(0, 1.2*probabilities.max()) ax.set_xticks([]) ax.set_yticks([]) ax.set_xlabel('Energy') ax.set_ylabel('Probability') ax.legend()
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
def calculate_energy(J, σ): return sum(J_ij*σ[i]*σ[i+1] for i, J_ij in enumerate(J)) J = [1.0, -1.0] σ = [+1, -1, +1] calculate_energy(J, σ) import itertools for σ in itertools.product(*[{+1,-1} for _ in range(3)]): print(calculate_energy(J, σ), σ) import dimod J = {(0, 1): 1.0, (1, 2): -1.0} h = {0:0, 1:0, 2:0} model = dimod.BinaryQuadraticModel(h, J, 0.0, dimod.SPIN) sampler = dimod.SimulatedAnnealingSampler() response = sampler.sample(model, num_reads=10) [solution.energy for solution in response.data()].count(-2) import numpy as np from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute from qiskit import BasicAer np.set_printoptions(precision=3, suppress=True) backend = BasicAer.get_backend('statevector_simulator') q = QuantumRegister(1) c = ClassicalRegister(1) circuit = QuantumCircuit(q, c) circuit.z(q[0]) job = execute(circuit, backend) state = job.result().get_statevector(circuit) print(state) circuit = QuantumCircuit(q, c) circuit.x(q[0]) circuit.z(q[0]) job = execute(circuit, backend) state = job.result().get_statevector(circuit) print(state) def calculate_energy_expectation(state, hamiltonian): return float(np.dot(state.T.conj(), np.dot(hamiltonian, state)).real) Z = np.array([[1, 0], [0, -1]]) IZ = np.kron(np.eye(2), Z) ZI = np.kron(Z, np.eye(2)) ZZ = np.kron(Z, Z) H = -ZZ + -0.5*(ZI+IZ) ψ = np.kron([[1], [0]], [[1], [0]]) calculate_energy_expectation(ψ, H) circuit = QuantumCircuit(q, c) circuit.x(q[0]) circuit.z(q[0]) job = execute(circuit, backend) state = job.result().get_statevector(circuit) print("Pauli-X, then Pauli-Z:", state) circuit = QuantumCircuit(q, c) circuit.z(q[0]) circuit.x(q[0]) job = execute(circuit, backend) state = job.result().get_statevector(circuit) print("Pauli-Z, then Pauli-X:", state)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute from qiskit import BasicAer from qiskit.tools.visualization import circuit_drawer, plot_histogram q = QuantumRegister(2) c = ClassicalRegister(2) circuit = QuantumCircuit(q, c) circuit.h(q[0]) circuit.cx(q[0], q[1]) circuit_drawer(circuit) circuit.measure(q, c) circuit_drawer(circuit) backend = BasicAer.get_backend('qasm_simulator') job = execute(circuit, backend, shots=100) plot_histogram(job.result().get_counts(circuit)) from qiskit import compile compiled_circuit = compile(circuit, backend) compiled_circuit.as_dict()['experiments'][0]['instructions']
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np np.set_printoptions(precision=3, suppress=True) X = np.array([[0, 1], [1, 0]]) IX = np.kron(np.eye(2), X) XI = np.kron(X, np.eye(2)) H_0 = - (IX + XI) λ, v = np.linalg.eigh(H_0) print("Eigenvalues:", λ) print("Eigenstate for lowest eigenvalue", v[:, 0]) import dimod J = {(0, 1): 1.0, (1, 2): -1.0} h = {0:0, 1:0, 2:0} model = dimod.BinaryQuadraticModel(h, J, 0.0, dimod.SPIN) sampler = dimod.SimulatedAnnealingSampler() response = sampler.sample(model, num_reads=10) print("Energy of samples:") print([solution.energy for solution in response.data()]) import matplotlib.pyplot as plt import dwave_networkx as dnx %matplotlib inline connectivity_structure = dnx.chimera_graph(2, 2) dnx.draw_chimera(connectivity_structure) plt.show() import networkx as nx G = nx.complete_graph(9) plt.axis('off') nx.draw_networkx(G, with_labels=False) import minorminer embedded_graph = minorminer.find_embedding(G.edges(), connectivity_structure.edges()) dnx.draw_chimera_embedding(connectivity_structure, embedded_graph) plt.show() max_chain_length = 0 for _, chain in embedded_graph.items(): if len(chain) > max_chain_length: max_chain_length = len(chain) print(max_chain_length)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import itertools import numpy as np from functools import partial, reduce from qiskit import BasicAer, QuantumRegister, execute from qiskit.quantum_info import Pauli from qiskit_aqua import Operator, get_aer_backend from qiskit_aqua.components.initial_states import Custom from scipy.optimize import minimize np.set_printoptions(precision=3, suppress=True) def pauli_x(qubit, coeff): eye = np.eye((n_qubits)) return Operator([[coeff, Pauli(np.zeros(n_qubits), eye[qubit])]]) n_qubits = 2 Hm = reduce(lambda x, y: x+y, [pauli_x(i, 1) for i in range(n_qubits)]) Hm.to_matrix() def pauli_z(qubit, coeff): eye = np.eye((n_qubits)) return Operator([[coeff, Pauli(eye[qubit], np.zeros(n_qubits))]]) def product_pauli_z(q1, q2, coeff): eye = np.eye((n_qubits)) return Operator([[coeff, Pauli(eye[q1], np.zeros(n_qubits)) * Pauli(eye[q2], np.zeros(n_qubits))]]) J = np.array([[0,1],[0,0]]) Hc = reduce(lambda x,y:x+y, [product_pauli_z(i,j, -J[i,j]) for i,j in itertools.product(range(n_qubits), repeat=2)]) Hc.to_matrix() n_iter = 10 # number of iterations of the optimization procedure p = 2 beta = np.random.uniform(0, np.pi*2, p) gamma = np.random.uniform(0, np.pi*2, p) init_state_vect = [1 for i in range(2**n_qubits)] init_state = Custom(n_qubits, state_vector=init_state_vect) qr = QuantumRegister(n_qubits) circuit_init = init_state.construct_circuit('circuit', qr) def evolve(hamiltonian, angle, quantum_registers): return hamiltonian.evolve(None, angle, 'circuit', 1, quantum_registers=quantum_registers, expansion_mode='suzuki', expansion_order=3) def create_circuit(qr, gamma, beta, p): circuit_evolv = reduce(lambda x,y: x+y, [evolve(Hm, beta[i], qr) + evolve(Hc, gamma[i], qr) for i in range(p)]) circuit = circuit_init + circuit_evolv return circuit def evaluate_circuit(gamma_beta, qr, p): n = len(gamma_beta)//2 circuit = create_circuit(qr, gamma_beta[:n], gamma_beta[n:], p) return np.real(Hc.eval("matrix", circuit, get_aer_backend('statevector_simulator'))[0]) evaluate = partial(evaluate_circuit, qr=qr, p=p) result = minimize(evaluate, np.concatenate([gamma, beta]), method='L-BFGS-B') result circuit = create_circuit(qr, result['x'][:p], result['x'][p:], p) backend = BasicAer.get_backend('statevector_simulator') job = execute(circuit, backend) state = np.asarray(job.result().get_statevector(circuit)) print(np.absolute(state)) print(np.angle(state)) Z0 = pauli_z(0, 1) Z1 = pauli_z(1, 1) print(Z0.eval("matrix", circuit, get_aer_backend('statevector_simulator'))[0]) print(Z1.eval("matrix", circuit, get_aer_backend('statevector_simulator'))[0])
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import itertools import matplotlib.pyplot as plt import numpy as np import dimod %matplotlib inline np.set_printoptions(precision=3, suppress=True) n_spins = 10 n_samples = 1000 h = {v: np.random.uniform(-2, 2) for v in range(n_spins)} J = {} for u, v in itertools.combinations(h, 2): if np.random.random() < .05: J[(u, v)] = np.random.uniform(-1, 1) model = dimod.BinaryQuadraticModel(h, J, 0.0, dimod.SPIN) sampler = dimod.SimulatedAnnealingSampler() temperature_0 = 1 response = sampler.sample(model, beta_range=[1/temperature_0, 1/temperature_0], num_reads=n_samples) energies_0 = [solution.energy for solution in response.data()] temperature_1 = 10 response = sampler.sample(model, beta_range=[1/temperature_1, 1/temperature_1], num_reads=n_samples) energies_1 = [solution.energy for solution in response.data()] temperature_2 = 100 response = sampler.sample(model, beta_range=[1/temperature_2, 1/temperature_2], num_reads=n_samples) energies_2 = [solution.energy for solution in response.data()] def plot_probabilities(energy_samples, temperatures): fig, ax = plt.subplots() for i, (energies, T) in enumerate(zip(energy_samples, temperatures)): probabilities = np.exp(-np.array(sorted(energies))/T) Z = probabilities.sum() probabilities /= Z ax.plot(energies, probabilities, linewidth=3, label = "$T_" + str(i+1)+"$") minimum_energy = min([min(energies) for energies in energy_samples]) maximum_energy = max([max(energies) for energies in energy_samples]) ax.set_xlim(minimum_energy, maximum_energy) ax.set_xticks([]) ax.set_yticks([]) ax.set_xlabel('Energy') ax.set_ylabel('Probability') ax.legend() plt.show() plot_probabilities([energies_0, energies_1, energies_2], [temperature_0, temperature_1, temperature_2]) import itertools import numpy as np from functools import reduce from qiskit import BasicAer, QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit import execute from qiskit.quantum_info import Pauli from qiskit_aqua import get_aer_backend, QuantumInstance from qiskit_aqua.operator import Operator from qiskit_aqua.components.optimizers import COBYLA from qiskit_aqua.algorithms import VQE from qiskit_aqua.algorithms.adaptive.qaoa.varform import QAOAVarForm n_qubits = 2 n_system = n_qubits * 2 β = 0 weights = np.array([[0,1],[0,0]]) p = 1 def pauli_z(qubit, coeff): eye = np.eye((n_system)) return Operator([[coeff, Pauli(eye[qubit], np.zeros(n_system))]]) def product_pauli_z(q1, q2, coeff): eye = np.eye((n_system)) return Operator([[coeff, Pauli(eye[q1], np.zeros(n_system)) * Pauli(eye[q2], np.zeros(n_system))]]) def ising_hamiltonian(weights): H = reduce(lambda x,y:x+y, [product_pauli_z(i,j, -weights[i,j]) for (i,j) in itertools.product(range(n_qubits), range(n_qubits))]) H.to_matrix() return H Hc = ising_hamiltonian(weights) qr = QuantumRegister(n_qubits * 2) cr = ClassicalRegister(n_qubits) backend = BasicAer.get_backend('qasm_simulator') circuit_init = QuantumCircuit(qr) α = 2 * np.arctan(np.exp(- β/2)) for i in range(n_qubits): circuit_init.rx(α, qr[n_qubits+i]) circuit_init.cx(qr[n_qubits+i], qr[i]) class InitialState: def __init__(self, β, n_qubits): self.β = β self.n_qubits = n_qubits def construct_circuit(self, mode, qr): circuit_init = QuantumCircuit(qr) alpha = 2 * np.arctan(np.exp(- self.β / 2)) for i in range(n_qubits): circuit_init.rx(alpha, qr[n_qubits+i]) circuit_init.cx(qr[n_qubits+i], qr[i]) return circuit_init class MyQAOA(VQE): def __init__(self, operator, optimizer, init_state, p=1, operator_mode='matrix', initial_point=None, batch_mode=False, aux_operators=None): self.validate(locals()) var_form = QAOAVarForm(operator, p, init_state) super().__init__(operator, var_form, optimizer, operator_mode=operator_mode, initial_point=initial_point) class MyQAOAVarForm(QAOAVarForm): def construct_circuit(self, angles, quantum_register, classical_register): if not len(angles) == self.num_parameters: raise ValueError('Incorrect number of angles: expecting {}, but {} given.'.format( self.num_parameters, len(angles) )) q = quantum_register circuit = QuantumCircuit(quantum_register, classical_register) if self._initial_state: circuit += self._initial_state.construct_circuit('circuit', q) else: circuit.u2(0, np.pi, q) for idx in range(self._p): β, γ = angles[idx], angles[idx + self._p] circuit += self._cost_operator.evolve(None, γ, 'circuit', 1, quantum_registers=q) circuit += self._mixer_operator.evolve(None, β, 'circuit', 1, quantum_registers=q) return circuit initial_state = InitialState(β, n_qubits) def get_thermal_state(weights, p): Hc = ising_hamiltonian(weights) print("Begin QAOA...") optimizer = COBYLA() qaoa = MyQAOA(Hc, optimizer, initial_state, p, "matrix") backend = get_aer_backend('statevector_simulator') quantum_instance = QuantumInstance(backend, shots=100) result = qaoa.run(quantum_instance) print("Results of QAOA", result) return result result = get_thermal_state(weights, 1) var_form = MyQAOAVarForm(Hc, p, initial_state) thermal_state = var_form.construct_circuit(result['opt_params'], qr, cr) for i in range(n_qubits): thermal_state.measure(qr[i], cr[i]) job = execute(thermal_state, backend, shots=2000) results = job.result().get_counts(thermal_state) def get_energy(spin_configuration): x = spin_configuration.reshape(-1, 1) return np.sum([[-weights[i,j] * x[i] * x[j] for j in range(n_qubits)] for i in range(n_qubits)]) list_spin_configs = np.array(np.concatenate([[list(spin_config)] * results[spin_config] for spin_config in results]), dtype="int") list_spin_configs[list_spin_configs == 0] = -1 list_energy = np.array([get_energy(spin_config) for spin_config in list_spin_configs]) hist = plt.hist(list_energy, density=True) β = 5 initial_state = InitialState(β, n_qubits) result = get_thermal_state(weights, 1) var_form = MyQAOAVarForm(Hc, p, initial_state) thermal_state = var_form.construct_circuit(result['opt_params'], qr, cr) for i in range(n_qubits): thermal_state.measure(qr[i], cr[i]) job = execute(thermal_state, backend, shots=2000) results = job.result().get_counts(thermal_state) list_spin_configs = np.array(np.concatenate([[list(spin_config)] * results[spin_config] for spin_config in results]), dtype="int") list_spin_configs[list_spin_configs == 0] = -1 list_energy = np.array([get_energy(spin_config) for spin_config in list_spin_configs]) plt.hist(list_energy, density=True)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import matplotlib.pyplot as plt import numpy as np import sklearn import sklearn.datasets import sklearn.metrics %matplotlib inline metric = sklearn.metrics.accuracy_score np.random.seed(0) data, labels = sklearn.datasets.make_circles() idx = np.arange(len(labels)) np.random.shuffle(idx) # train on a random 2/3 and test on the remaining 1/3 idx_train = idx[:2*len(idx)//3] idx_test = idx[2*len(idx)//3:] X_train = data[idx_train] X_test = data[idx_test] y_train = 2 * labels[idx_train] - 1 # binary -> spin y_test = 2 * labels[idx_test] - 1 scaler = sklearn.preprocessing.StandardScaler() normalizer = sklearn.preprocessing.Normalizer() X_train = scaler.fit_transform(X_train) X_train = normalizer.fit_transform(X_train) X_test = scaler.fit_transform(X_test) X_test = normalizer.fit_transform(X_test) plt.figure(figsize=(6, 6)) plt.subplot(111, xticks=[], yticks=[]) plt.scatter(data[labels == 0, 0], data[labels == 0, 1], color='navy') plt.scatter(data[labels == 1, 0], data[labels == 1, 1], color='c'); from sklearn.linear_model import Perceptron model_1 = Perceptron() model_1.fit(X_train, y_train) print('accuracy (train): %5.2f'%(metric(y_train, model_1.predict(X_train)))) print('accuracy (test): %5.2f'%(metric(y_test, model_1.predict(X_test)))) from sklearn.svm import SVC model_2 = SVC(kernel='rbf') model_2.fit(X_train, y_train) print('accuracy (train): %5.2f'%(metric(y_train, model_2.predict(X_train)))) print('accuracy (test): %5.2f'%(metric(y_test, model_2.predict(X_test)))) from sklearn.ensemble import AdaBoostClassifier model_3 = AdaBoostClassifier(n_estimators=3) model_3.fit(X_train, y_train) print('accuracy (train): %5.2f'%(metric(y_train, model_3.predict(X_train)))) print('accuracy (test): %5.2f'%(metric(y_test, model_3.predict(X_test)))) models = [model_1, model_2, model_3] n_models = len(models) predictions = np.array([h.predict(X_train) for h in models], dtype=np.float64) # scale hij to [-1/N, 1/N] predictions *= 1/n_models λ = 1 w = np.dot(predictions, predictions.T) wii = len(X_train) / (n_models ** 2) + λ - 2 * np.dot(predictions, y_train) w[np.diag_indices_from(w)] = wii W = {} for i in range(n_models): for j in range(i, n_models): W[(i, j)] = w[i, j] import dimod sampler = dimod.SimulatedAnnealingSampler() response = sampler.sample_qubo(W, num_reads=10) weights = list(response.first.sample.values()) def predict(models, weights, X): n_data = len(X) T = 0 y = np.zeros(n_data) for i, h in enumerate(models): y0 = weights[i] * h.predict(X) # prediction of weak classifier y += y0 T += np.sum(y0) y = np.sign(y - T / (n_data*len(models))) return y print('accuracy (train): %5.2f'%(metric(y_train, predict(models, weights, X_train)))) print('accuracy (test): %5.2f'%(metric(y_test, predict(models, weights, X_test)))) weights h, J, offset = dimod.qubo_to_ising(W) from qiskit.quantum_info import Pauli from qiskit_aqua import Operator num_nodes = w.shape[0] pauli_list = [] for i in range(num_nodes): wp = np.zeros(num_nodes) vp = np.zeros(num_nodes) vp[i] = 1 pauli_list.append([h[i], Pauli(vp, wp)]) for j in range(i+1, num_nodes): if w[i, j] != 0: wp = np.zeros(num_nodes) vp = np.zeros(num_nodes) vp[i] = 1 vp[j] = 1 pauli_list.append([J[i, j], Pauli(vp, wp)]) ising_model = Operator(paulis=pauli_list) from qiskit_aqua import get_aer_backend, QuantumInstance from qiskit_aqua.algorithms import QAOA from qiskit_aqua.components.optimizers import COBYLA p = 1 optimizer = COBYLA() qaoa = QAOA(ising_model, optimizer, p, operator_mode='matrix') backend = get_aer_backend('statevector_simulator') quantum_instance = QuantumInstance(backend, shots=100) result = qaoa.run(quantum_instance) k = np.argmax(result['eigvecs'][0]) weights = np.zeros(num_nodes) for i in range(num_nodes): weights[i] = k % 2 k >>= 1 weights print('accuracy (train): %5.2f'%(metric(y_train, predict(models, weights, X_train)))) print('accuracy (test): %5.2f'%(metric(y_test, predict(models, weights, X_test))))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D %matplotlib inline n_instances = 10 class_1 = np.random.rand(n_instances//2, 3)/5 class_2 = (0.6, 0.1, 0.05) + np.random.rand(n_instances//2, 3)/5 data = np.concatenate((class_1, class_2)) colors = ["red"] * (n_instances//2) + ["green"] * (n_instances//2) fig = plt.figure() ax = fig.add_subplot(111, projection='3d', xticks=[], yticks=[], zticks=[]) ax.scatter(data[:, 0], data[:, 1], data[:, 2], c=colors); import itertools w = np.zeros((n_instances, n_instances)) for i, j in itertools.product(*[range(n_instances)]*2): w[i, j] = np.linalg.norm(data[i]-data[j]) from qiskit_aqua import get_aer_backend, QuantumInstance from qiskit_aqua.algorithms import QAOA from qiskit_aqua.components.optimizers import COBYLA from qiskit_aqua.translators.ising import maxcut qubit_operators, offset = maxcut.get_maxcut_qubitops(w) p = 1 optimizer = COBYLA() qaoa = QAOA(qubit_operators, optimizer, p, operator_mode='matrix') backend = get_aer_backend('statevector_simulator') quantum_instance = QuantumInstance(backend, shots=100) result = qaoa.run(quantum_instance) x = maxcut.sample_most_likely(result['eigvecs'][0]) graph_solution = maxcut.get_graph_solution(x) print('energy:', result['energy']) print('maxcut objective:', result['energy'] + offset) print('solution:', maxcut.get_graph_solution(x)) print('solution objective:', maxcut.maxcut_value(x, w)) import dimod J, h = {}, {} for i in range(n_instances): h[i] = 0 for j in range(i+1, n_instances): J[(i, j)] = w[i, j] model = dimod.BinaryQuadraticModel(h, J, 0.0, dimod.SPIN) sampler = dimod.SimulatedAnnealingSampler() response = sampler.sample(model, num_reads=10) print("Energy of samples:") for solution in response.data(): print("Energy:", solution.energy, "Sample:", solution.sample)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit import execute from qiskit import BasicAer q = QuantumRegister(4) c = ClassicalRegister(4) backend = BasicAer.get_backend('qasm_simulator') training_set = [[0, 1], [0.78861006, 0.61489363]] labels = [0, 1] test_set = [[-0.549, 0.836], [0.053 , 0.999]] test_angles = [4.30417579487669/2, 3.0357101997648965/2] training_angle = 1.3245021469658966/4 def prepare_state(q, c, angles): ancilla_qubit = q[0] index_qubit = q[1] data_qubit = q[2] class_qubit = q[3] qc = QuantumCircuit(q, c) # Put the ancilla and the index qubits into uniform superposition qc.h(ancilla_qubit) qc.h(index_qubit) # Prepare the test vector qc.cx(ancilla_qubit, data_qubit) qc.u3(-angles[0], 0, 0, data_qubit) qc.cx(ancilla_qubit, data_qubit) qc.u3(angles[0], 0, 0, data_qubit) # Flip the ancilla qubit > this moves the input # vector to the |0> state of the ancilla qc.x(ancilla_qubit) qc.barrier() # Prepare the first training vector # [0,1] -> class 0 # We can prepare this with a Toffoli qc.ccx(ancilla_qubit, index_qubit, data_qubit) # Flip the index qubit > moves the first training vector to the # |0> state of the index qubit qc.x(index_qubit) qc.barrier() # Prepare the second training vector # [0.78861, 0.61489] -> class 1 qc.ccx(ancilla_qubit, index_qubit, data_qubit) qc.cx(index_qubit, data_qubit) qc.u3(angles[1], 0, 0, data_qubit) qc.cx(index_qubit, data_qubit) qc.u3(-angles[1], 0, 0, data_qubit) qc.ccx(ancilla_qubit, index_qubit, data_qubit) qc.cx(index_qubit, data_qubit) qc.u3(-angles[1], 0, 0, data_qubit) qc.cx(index_qubit, data_qubit) qc.u3(angles[1], 0, 0, data_qubit) qc.barrier() # Flip the class label for training vector #2 qc.cx(index_qubit, class_qubit) qc.barrier() return qc from qiskit.tools.visualization import circuit_drawer angles = [test_angles[0], training_angle] state_preparation_0 = prepare_state(q, c, angles) circuit_drawer(state_preparation_0) def interfere_data_and_test_instances(qc, q, c, angles): qc.h(q[0]) qc.barrier() qc.measure(q, c) return qc import matplotlib.pyplot as plt import numpy as np %matplotlib inline x = np.linspace(-2, 2, 100) plt.xlim(-2, 2) plt.ylim(0, 1.1) plt.plot(x, 1-x**2/4) def postselect(result_counts): total_samples = sum(result_counts.values()) # define lambda function that retrieves only results where the ancilla is in the |0> state post_select = lambda counts: [(state, occurences) for state, occurences in counts.items() if state[-1] == '0'] # perform the postselection postselection = dict(post_select(result_counts)) postselected_samples = sum(postselection.values()) print(f'Ancilla post-selection probability was found to be {postselected_samples/total_samples}') retrieve_class = lambda binary_class: [occurences for state, occurences in postselection.items() if state[0] == str(binary_class)] prob_class0 = sum(retrieve_class(0))/postselected_samples prob_class1 = sum(retrieve_class(1))/postselected_samples print('Probability for class 0 is', prob_class0) print('Probability for class 1 is', prob_class1) qc0 = interfere_data_and_test_instances(state_preparation_0, q, c, angles) job = execute(qc0, backend) result = job.result() postselect(result.get_counts(qc0)) angles = [test_angles[1], training_angle] state_preparation_1 = prepare_state(q, c, angles) qc1 = interfere_data_and_test_instances(state_preparation_1, q, c, angles) job = execute(qc1, backend) result = job.result() postselect(result.get_counts(qc1))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import matplotlib.pyplot as plt import numpy as np import dimod n_spins = 3 h = {v: np.random.uniform(-2, 2) for v in range(n_spins)} J = {(0, 1): np.random.uniform(-1, 1), (1, 2): np.random.uniform(-1, 1)} model = dimod.BinaryQuadraticModel(h, J, 0.0, dimod.SPIN) sampler = dimod.SimulatedAnnealingSampler() temperature = 1 response = sampler.sample(model, beta_range=[1/temperature, 1/temperature], num_reads=100) energies = [solution.energy for solution in response.data()] fig, ax = plt.subplots() probabilities = np.exp(-np.array(sorted(energies))/temperature) Z = probabilities.sum() probabilities /= Z ax.plot(energies, probabilities, linewidth=3) ax.set_xlim(min(energies), max(energies)) ax.set_xticks([]) ax.set_yticks([]) ax.set_xlabel('Energy') ax.set_ylabel('Probability') plt.show() from dimod.reference.samplers.simulated_annealing import greedy_coloring clamped_spins = {0: -1} num_sweeps = 1000 βs = [1.0 - 1.0*i / (num_sweeps - 1.) for i in range(num_sweeps)] # Set up the adjacency matrix. adj = {n: set() for n in h} for n0, n1 in J: adj[n0].add(n1) adj[n1].add(n0) # Use a vertex coloring for the graph and update the nodes by color __, colors = greedy_coloring(adj) spins = {v: np.random.choice((-1, 1)) if v not in clamped_spins else clamped_spins[v] for v in h} for β in βs: energy_diff_h = {v: -2 * spins[v] * h[v] for v in h} # for each color, do updates for color in colors: nodes = colors[color] energy_diff_J = {} for v0 in nodes: ediff = 0 for v1 in adj[v0]: if (v0, v1) in J: ediff += spins[v0] * spins[v1] * J[(v0, v1)] if (v1, v0) in J: ediff += spins[v0] * spins[v1] * J[(v1, v0)] energy_diff_J[v0] = -2. * ediff for v in filter(lambda x: x not in clamped_spins, nodes): logp = np.log(np.random.uniform(0, 1)) if logp < -1. * β * (energy_diff_h[v] + energy_diff_J[v]): spins[v] *= -1 spins
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute from qiskit import BasicAer π = np.pi q = QuantumRegister(3, 'q') c = ClassicalRegister(1, 'c') qft = QuantumCircuit(q, c) qft.h(q[0]) qft.cu1(π/2, q[1], q[0]) qft.h(q[1]) qft.cu1(π/4, q[2], q[0]) qft.cu1(π/2, q[2], q[1]) qft.h(q[2]); from qiskit.tools.visualization import circuit_drawer circuit_drawer(qft) qpe = QuantumCircuit(q, c) qpe.h(q[0]) qpe.h(q[1]); # Controlled-U0 qpe.cu3(-π / 2, -π / 2, π / 2, q[1], q[2]) qpe.cu1(3 * π / 4, q[1], q[2]) qpe.cx(q[1], q[2]) qpe.cu1(3 * π / 4, q[1], q[2]) qpe.cx(q[1], q[2]) # Controlled-U1 qpe.cx(q[0], q[2]); qpe.swap(q[0], q[1]) qpe.h(q[1]) qpe.cu1(-π / 2, q[0], q[1]) qpe.h(q[0]); circuit_drawer(qpe)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute from qiskit import BasicAer π = np.pi q = QuantumRegister(6) c = ClassicalRegister(2) hhl = QuantumCircuit(q, c) # Superposition hhl.h(q[1]) hhl.h(q[2]) # Controlled-U0 hhl.cu3(-π / 2, -π / 2, π / 2, q[2], q[3]) hhl.cu1(3 * π / 4, q[2], q[3]) hhl.cx(q[2], q[3]) hhl.cu1(3 * π / 4, q[2], q[3]) hhl.cx(q[2], q[3]) # Controlled-U1 hhl.cx(q[1], q[3]); hhl.swap(q[1], q[2]) hhl.h(q[2]) hhl.cu1(-π / 2, q[1], q[2]) hhl.h(q[1]); hhl.swap(q[1], q[2]); hhl.cu3(0.392699, 0, 0, q[1], q[0]) # Controlled-RY0 hhl.cu3(0.19634955, 0, 0, q[2], q[0]); # Controlled-RY1 hhl.swap(q[1], q[2]) hhl.h(q[1]) hhl.cu1(π / 2, q[1], q[2]) # Inverse(Dagger(Controlled-S)) hhl.h(q[2]) hhl.swap(q[2], q[1]) # Inverse(Controlled-U1) hhl.cx(q[1], q[3]) # Inverse(Controlled-U0) hhl.cx(q[2], q[3]) hhl.cu1(-3 * π / 4, q[2], q[3]) hhl.cx(q[2], q[3]) hhl.cu1(-3 * π / 4, q[2], q[3]) hhl.cu3(-π / 2, π / 2, -π / 2, q[2], q[3]) # End of Inverse(Controlled-U0) hhl.h(q[2]) hhl.h(q[1]); # Target state preparation hhl.rz(-π, q[4]) hhl.u1(π, q[4]) hhl.h(q[4]) hhl.ry(-0.9311623288419387, q[4]) hhl.rz(π, q[4]) # Swap test hhl.h(q[5]) hhl.cx(q[4], q[3]) hhl.ccx(q[5], q[3], q[4]) hhl.cx(q[4], q[3]) hhl.h(q[5]) hhl.barrier(q) hhl.measure(q[0], c[0]) hhl.measure(q[5], c[1]); def get_psuccess(counts): '''Compute the success probability of the HHL protocol from the statistics :return: (float) The success probability. ''' try: succ_rotation_fail_swap = counts['11'] except KeyError: succ_rotation_fail_swap = 0 try: succ_rotation_succ_swap = counts['01'] except KeyError: succ_rotation_succ_swap = 0 succ_rotation = succ_rotation_succ_swap + succ_rotation_fail_swap try: prob_swap_test_success = succ_rotation_succ_swap / succ_rotation except ZeroDivisionError: prob_swap_test_success = 0 return prob_swap_test_success backend = BasicAer.get_backend('qasm_simulator') job = execute(hhl, backend, shots=100) result = job.result() counts = result.get_counts(hhl) print(get_psuccess(counts))
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import qiskit from qiskit import IBMQ # requires qiskit version >= 0.6 IBMQ.save_account("MY_TOKEN") IBMQ.load_accounts() for backend in IBMQ.backends(): print(backend) backend_0 = IBMQ.backends()[0] # retrieve the Backend at index 0 print(backend_0.configuration()) print("Go check its specification at %s" % backend_0.configuration()["url"])
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import qiskit from qiskit import IBMQ # requires qiskit version >= 0.6 IBMQ.save_account("MY_TOKEN") IBMQ.load_accounts() for backend in IBMQ.backends(): print(backend) backend_0 = IBMQ.backends()[0] # retrieve the Backend at index 0 print(backend_0.configuration()) print("Go check its specification at %s" % backend_0.configuration()["url"])
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from qiskit import ClassicalRegister # Create a Classical Register with 2 bits. c = ClassicalRegister(2) from qiskit import QuantumRegister # Create a Quantum Register with 2 qubits. q = QuantumRegister(2) from qiskit import QuantumCircuit # Create a Quantum Circuit qc = QuantumCircuit(q, c) # perform a measurement of our qubits into our bits qc.measure(q, c); # ; hides the output # Jupyter command to activate matplotlib and allow the preview of our circuit %matplotlib inline from qiskit.tools.visualization import matplotlib_circuit_drawer as draw draw(qc) # visualize quantum circuit # Try both and use the one you like best from qiskit.tools.visualization import circuit_drawer as draw2 draw2(qc) # visualize quantum circuit # if you want to save it to a file from qiskit.tools.visualization import circuit_drawer diagram = circuit_drawer(qc, filename="my_first_quantum_circuit.png") diagram.show() # or even open it on an external program (no need to save first) # get the QASM representation of our circuit print(qc.qasm())
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from qiskit import ClassicalRegister # Create a Classical Register with 2 bits. c = ClassicalRegister(2) from qiskit import QuantumRegister # Create a Quantum Register with 2 qubits. q = QuantumRegister(2) from qiskit import QuantumCircuit # Create a Quantum Circuit qc = QuantumCircuit(q, c) # perform a measurement of our qubits into our bits qc.measure(q, c); # ; hides the output # Jupyter command to activate matplotlib and allow the preview of our circuit %matplotlib inline from qiskit.tools.visualization import matplotlib_circuit_drawer as draw draw(qc) # visualize quantum circuit # Try both and use the one you like best from qiskit.tools.visualization import circuit_drawer as draw2 draw2(qc) # visualize quantum circuit # if you want to save it to a file from qiskit.tools.visualization import circuit_drawer diagram = circuit_drawer(qc, filename="my_first_quantum_circuit.png") diagram.show() # or even open it on an external program (no need to save first) # get the QASM representation of our circuit print(qc.qasm())
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute # Choose the drawer you like best: from qiskit.tools.visualization import matplotlib_circuit_drawer as draw #from qiskit.tools.visualization import circuit_drawer as draw from qiskit import IBMQ IBMQ.load_accounts() # make sure you have setup your token locally to use this %matplotlib inline import matplotlib.pyplot as plt def show_results(D): # D is a dictionary with classical bits as keys and count as value # example: D = {'000': 497, '001': 527} plt.bar(range(len(D)), list(D.values()), align='center') plt.xticks(range(len(D)), list(D.keys())) plt.show() from qiskit import Aer # See a list of available local simulators print("Aer backends: ", Aer.backends()) # see a list of available remote backends (these are freely given by IBM) print("IBMQ Backends: ", IBMQ.backends()) # execute circuit and either display a histogram of the results def execute_locally(qc, draw_circuit=False): # 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() result_counts = result_sim.get_counts(qc) # Print the results print("simulation: ", result_sim, result_counts) if draw_circuit: # draw the circuit draw(qc) else: # or show the results show_results(result_counts) from qiskit.backends.ibmq import least_busy import time # Compile and run on a real device backend def execute_remotely(qc, draw_circuit=False): if draw_circuit: # draw the circuit draw(qc) try: # select least busy available device and execute. least_busy_device = least_busy(IBMQ.backends(simulator=False)) print("Running on current least busy device: ", least_busy_device) # running the job job_exp = execute(qc, backend=least_busy_device, shots=1024, max_credits=10) lapse, interval = 0, 10 while job_exp.status().name != 'DONE': print('Status @ {} seconds'.format(interval * lapse)) print(job_exp.status()) time.sleep(interval) lapse += 1 print(job_exp.status()) exp_result = job_exp.result() result_counts = exp_result.get_counts(qc) # Show the results print("experiment: ", exp_result, result_counts) if not draw_circuit: # show the results show_results(result_counts) except: print("All devices are currently unavailable.") def new_circuit(size): # Create a Quantum Register with size qubits qr = QuantumRegister(size) # Create a Classical Register with size bits cr = ClassicalRegister(size) # Create a Quantum Circuit acting on the qr and cr register return qr, cr, QuantumCircuit(qr, cr) # H gate on qubit 0 # measure the specific qubit # H gate on qubit 1 # measure the specific qubit # CNOT gate # measure the specific qubit # H gate on 2 qubits # CNOT gate # measure # measure # execute_remotely(circuit)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute # Choose the drawer you like best: from qiskit.tools.visualization import matplotlib_circuit_drawer as draw #from qiskit.tools.visualization import circuit_drawer as draw from qiskit import IBMQ IBMQ.load_accounts() # make sure you have setup your token locally to use this %matplotlib inline import matplotlib.pyplot as plt def show_results(D): # D is a dictionary with classical bits as keys and count as value # example: D = {'000': 497, '001': 527} plt.bar(range(len(D)), list(D.values()), align='center') plt.xticks(range(len(D)), list(D.keys())) plt.show() from qiskit import Aer # See a list of available local simulators print("Aer backends: ", Aer.backends()) # see a list of available remote backends (these are freely given by IBM) print("IBMQ Backends: ", IBMQ.backends()) # execute circuit and either display a histogram of the results def execute_locally(qc, draw_circuit=False): # 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() result_counts = result_sim.get_counts(qc) # Print the results print("simulation: ", result_sim, result_counts) if draw_circuit: # draw the circuit draw(qc) else: # or show the results show_results(result_counts) from qiskit.backends.ibmq import least_busy import time # Compile and run on a real device backend def execute_remotely(qc, draw_circuit=False): if draw_circuit: # draw the circuit draw(qc) try: # select least busy available device and execute. least_busy_device = least_busy(IBMQ.backends(simulator=False)) print("Running on current least busy device: ", least_busy_device) # running the job job_exp = execute(qc, backend=least_busy_device, shots=1024, max_credits=10) lapse, interval = 0, 10 while job_exp.status().name != 'DONE': print('Status @ {} seconds'.format(interval * lapse)) print(job_exp.status()) time.sleep(interval) lapse += 1 print(job_exp.status()) exp_result = job_exp.result() result_counts = exp_result.get_counts(qc) # Show the results print("experiment: ", exp_result, result_counts) if not draw_circuit: # show the results show_results(result_counts) except: print("All devices are currently unavailable.") def new_circuit(size): # Create a Quantum Register with size qubits qr = QuantumRegister(size) # Create a Classical Register with size bits cr = ClassicalRegister(size) # Create a Quantum Circuit acting on the qr and cr register return qr, cr, QuantumCircuit(qr, cr) qr, cr, circuit = new_circuit(2) # H gate on qubit 0 circuit.h(qr[0]); # measure the specific qubit circuit.measure(qr[0], cr[0]); # ; hides the output # Try both commands: execute_locally(circuit,draw_circuit=True) # execute_locally(circuit,draw_circuit=False) qr, cr, circuit = new_circuit(2) # H gate on qubit 1 circuit.x(qr[1]); # measure the specific qubit circuit.measure(qr[1], cr[0]); # ; hides the output # Try both commands: execute_locally(circuit,draw_circuit=True) # execute_circuit(circuit,draw_circuit=False) qr, cr, circuit = new_circuit(2) # CNOT gate circuit.cx(qr[0], qr[1]); # measure the specific qubit circuit.measure(qr, cr); # ; hides the output # Try both commands: execute_locally(circuit,draw_circuit=True) # execute_circuit(circuit,draw_circuit=False) qr, cr, circuit = new_circuit(2) # H gate on 2 qubits circuit.h(qr); # CNOT gate circuit.cx(qr[0], qr[1]); # measure circuit.measure(qr, cr); # ; hides the output # Try both commands: execute_locally(circuit,draw_circuit=True) # execute_circuit(circuit,draw_circuit=False) qr, cr, circuit = new_circuit(5) circuit.measure(qr, cr); execute_remotely(circuit)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute # Choose the drawer you like best: from qiskit.tools.visualization import matplotlib_circuit_drawer as draw #from qiskit.tools.visualization import circuit_drawer as draw from qiskit import IBMQ IBMQ.load_accounts() # make sure you have setup your token locally to use this %matplotlib inline import matplotlib.pyplot as plt def show_results(D): # D is a dictionary with classical bits as keys and count as value # example: D = {'000': 497, '001': 527} plt.bar(range(len(D)), list(D.values()), align='center') plt.xticks(range(len(D)), list(D.keys())) plt.show() from qiskit import Aer # See a list of available local simulators print("Aer backends: ", Aer.backends()) # see a list of available remote backends (these are freely given by IBM) print("IBMQ Backends: ", IBMQ.backends()) # execute circuit and either display a histogram of the results def execute_locally(qc, draw_circuit=False): # 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() result_counts = result_sim.get_counts(qc) # Print the results print("simulation: ", result_sim, result_counts) if draw_circuit: # draw the circuit draw(qc) else: # or show the results show_results(result_counts) from qiskit.backends.ibmq import least_busy import time # Compile and run on a real device backend def execute_remotely(qc, draw_circuit=False): if draw_circuit: # draw the circuit draw(qc) try: # select least busy available device and execute. least_busy_device = least_busy(IBMQ.backends(simulator=False)) print("Running on current least busy device: ", least_busy_device) # running the job job_exp = execute(qc, backend=least_busy_device, shots=1024, max_credits=10) lapse, interval = 0, 10 while job_exp.status().name != 'DONE': print('Status @ {} seconds'.format(interval * lapse)) print(job_exp.status()) time.sleep(interval) lapse += 1 print(job_exp.status()) exp_result = job_exp.result() result_counts = exp_result.get_counts(qc) # Show the results print("experiment: ", exp_result, result_counts) if not draw_circuit: # show the results show_results(result_counts) except: print("All devices are currently unavailable.") def new_circuit(size): # Create a Quantum Register with size qubits qr = QuantumRegister(size) # Create a Classical Register with size bits cr = ClassicalRegister(size) # Create a Quantum Circuit acting on the qr and cr register return qr, cr, QuantumCircuit(qr, cr) # create the circuit # H gate on qubit 0 # measure the qubits # create the circuit # H gate on qubit 0 # X gate on qubit 1 # measure the qubits # create the circuit execute_remotely(circuit)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute # Choose the drawer you like best: from qiskit.tools.visualization import matplotlib_circuit_drawer as draw #from qiskit.tools.visualization import circuit_drawer as draw from qiskit import IBMQ IBMQ.load_accounts() # make sure you have setup your token locally to use this %matplotlib inline import matplotlib.pyplot as plt def show_results(D): # D is a dictionary with classical bits as keys and count as value # example: D = {'000': 497, '001': 527} plt.bar(range(len(D)), list(D.values()), align='center') plt.xticks(range(len(D)), list(D.keys())) plt.show() from qiskit import Aer # See a list of available local simulators print("Aer backends: ", Aer.backends()) # see a list of available remote backends (these are freely given by IBM) print("IBMQ Backends: ", IBMQ.backends()) # execute circuit and either display a histogram of the results def execute_locally(qc, draw_circuit=False): # 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() result_counts = result_sim.get_counts(qc) # Print the results print("simulation: ", result_sim, result_counts) if draw_circuit: # draw the circuit draw(qc) else: # or show the results show_results(result_counts) from qiskit.backends.ibmq import least_busy import time # Compile and run on a real device backend def execute_remotely(qc, draw_circuit=False): if draw_circuit: # draw the circuit draw(qc) try: # select least busy available device and execute. least_busy_device = least_busy(IBMQ.backends(simulator=False)) print("Running on current least busy device: ", least_busy_device) # running the job job_exp = execute(qc, backend=least_busy_device, shots=1024, max_credits=10) lapse, interval = 0, 10 while job_exp.status().name != 'DONE': print('Status @ {} seconds'.format(interval * lapse)) print(job_exp.status()) time.sleep(interval) lapse += 1 print(job_exp.status()) exp_result = job_exp.result() result_counts = exp_result.get_counts(qc) # Show the results print("experiment: ", exp_result, result_counts) if not draw_circuit: # show the results show_results(result_counts) except: print("All devices are currently unavailable.") def new_circuit(size): # Create a Quantum Register with size qubits qr = QuantumRegister(size) # Create a Classical Register with size bits cr = ClassicalRegister(size) # Create a Quantum Circuit acting on the qr and cr register return qr, cr, QuantumCircuit(qr, cr) qr, cr, circuit = new_circuit(2) # H gate on qubit 0 circuit.h(qr[0]); circuit.cx(qr[0], qr[1]); # measure the qubits circuit.measure(qr, cr); # Try both commands: execute_locally(circuit,draw_circuit=True) # execute_locally(circuit,draw_circuit=False) print(circuit.qasm()) # create the circuit qr, cr, circuit = new_circuit(2) # H gate on qubit 0 circuit.h(qr[0]); # X gate on qubit 1 circuit.x(qr[1]); circuit.cx(qr[0], qr[1]); # measure the qubits circuit.measure(qr, cr); # Try both commands: execute_locally(circuit,draw_circuit=True) # execute_locally(circuit,draw_circuit=False) # create the circuit qr, cr, circuit = new_circuit(2) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]); circuit.h(qr); circuit.measure(qr, cr) execute_locally(circuit,draw_circuit=True) qr, cr, circuit = new_circuit(2) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.h(qr) circuit.measure(qr, cr); execute_remotely(circuit)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute # Choose the drawer you like best: from qiskit.tools.visualization import matplotlib_circuit_drawer as draw #from qiskit.tools.visualization import circuit_drawer as draw from qiskit import IBMQ IBMQ.load_accounts() # make sure you have setup your token locally to use this %matplotlib inline import matplotlib.pyplot as plt def show_results(D): # D is a dictionary with classical bits as keys and count as value # example: D = {'000': 497, '001': 527} plt.bar(range(len(D)), list(D.values()), align='center') plt.xticks(range(len(D)), list(D.keys())) plt.show() from qiskit import Aer # See a list of available local simulators print("Aer backends: ", Aer.backends()) # see a list of available remote backends (these are freely given by IBM) print("IBMQ Backends: ", IBMQ.backends()) # execute circuit and either display a histogram of the results def execute_locally(qc, draw_circuit=False): # 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() result_counts = result_sim.get_counts(qc) # Print the results print("simulation: ", result_sim, result_counts) if draw_circuit: # draw the circuit draw(qc) else: # or show the results show_results(result_counts) from qiskit.backends.ibmq import least_busy import time # Compile and run on a real device backend def execute_remotely(qc, draw_circuit=False): if draw_circuit: # draw the circuit draw(qc) try: # select least busy available device and execute. least_busy_device = least_busy(IBMQ.backends(simulator=False)) print("Running on current least busy device: ", least_busy_device) # running the job job_exp = execute(qc, backend=least_busy_device, shots=1024, max_credits=10) lapse, interval = 0, 10 while job_exp.status().name != 'DONE': print('Status @ {} seconds'.format(interval * lapse)) print(job_exp.status()) time.sleep(interval) lapse += 1 print(job_exp.status()) exp_result = job_exp.result() result_counts = exp_result.get_counts(qc) # Show the results print("experiment: ", exp_result, result_counts) if not draw_circuit: # show the results show_results(result_counts) except: print("All devices are currently unavailable.") def new_circuit(size): # Create a Quantum Register with size qubits qr = QuantumRegister(size) # Create a Classical Register with size bits cr = ClassicalRegister(size) # Create a Quantum Circuit acting on the qr and cr register return qr, cr, QuantumCircuit(qr, cr) qr, cr, circuit = new_circuit(2) # H gate on qubit 0 circuit.h(qr[0]); circuit.cx(qr[0], qr[1]); # measure the qubits circuit.measure(qr, cr); # Try both commands: execute_locally(circuit,draw_circuit=True) # execute_locally(circuit,draw_circuit=False) print(circuit.qasm()) # create the circuit qr, cr, circuit = new_circuit(2) # H gate on qubit 0 circuit.h(qr[0]); # X gate on qubit 1 circuit.x(qr[1]); circuit.cx(qr[0], qr[1]); # measure the qubits circuit.measure(qr, cr); # Try both commands: execute_locally(circuit,draw_circuit=True) # execute_locally(circuit,draw_circuit=False) # create the circuit qr, cr, circuit = new_circuit(2) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]); circuit.h(qr); circuit.measure(qr, cr) execute_locally(circuit,draw_circuit=True) qr, cr, circuit = new_circuit(2) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.h(qr) circuit.measure(qr, cr); execute_remotely(circuit)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute # Choose the drawer you like best: from qiskit.tools.visualization import matplotlib_circuit_drawer as draw #from qiskit.tools.visualization import circuit_drawer as draw from qiskit import IBMQ IBMQ.load_accounts() # make sure you have setup your token locally to use this %matplotlib inline import matplotlib.pyplot as plt def show_results(D): # D is a dictionary with classical bits as keys and count as value # example: D = {'000': 497, '001': 527} plt.bar(range(len(D)), list(D.values()), align='center') plt.xticks(range(len(D)), list(D.keys())) plt.show() from qiskit import Aer # See a list of available local simulators print("Aer backends: ", Aer.backends()) # see a list of available remote backends (these are freely given by IBM) print("IBMQ Backends: ", IBMQ.backends()) # execute circuit and either display a histogram of the results def execute_locally(qc, draw_circuit=False, show_results=False): # 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() result_counts = result_sim.get_counts(qc) if draw_circuit or show_results: # Print the results print("simulation: ", result_sim, result_counts) if draw_circuit: # draw the circuit draw(qc) elif show_results: # or show the results show_results(result_counts) return result_counts from qiskit.backends.ibmq import least_busy import time # Compile and run on a real device backend def execute_remotely(qc, draw_circuit=False, show_results=False): if draw_circuit: # draw the circuit draw(qc) try: # select least busy available device and execute. least_busy_device = least_busy(IBMQ.backends(simulator=False)) print("Running on current least busy device: ", least_busy_device) # running the job job_exp = execute(qc, backend=least_busy_device, shots=1024, max_credits=10) lapse, interval = 0, 10 while job_exp.status().name != 'DONE': print('Status @ {} seconds'.format(interval * lapse)) print(job_exp.status()) time.sleep(interval) lapse += 1 print(job_exp.status()) exp_result = job_exp.result() result_counts = exp_result.get_counts(qc) # Show the results print("experiment: ", exp_result, result_counts) if show_results: # show the results show_results(result_counts) return result_counts except: print("All devices are currently unavailable.") return {} def new_circuit(size): # Create a Quantum Register with size qubits qr = QuantumRegister(size) # Create a Classical Register with size bits cr = ClassicalRegister(size) # Create a Quantum Circuit acting on the qr and cr register return qr, cr, QuantumCircuit(qr, cr) ERROR_MESSAGE = "Looks like your Deutsch has a bug" def quantum_oracle_1(qr, cr, circuit): pass def quantum_oracle_2(qr, cr, circuit): circuit.cx(qr[0], qr[1]) def quantum_oracle_3(qr, cr, circuit): circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) circuit.cx(qr[0], qr[1]) def quantum_oracle_4(qr, cr, circuit): circuit.z(qr[1]) circuit.cx(qr[0], qr[1]) def get_deutsch_verdict(res): return "CONSTANT" or "BALANCED" print(get_deutsch_verdict(results)) def deutsch(black_box): # ... black_box(circuit) #... return "CONSTANT" or "BALANCED" assert deutsch(quantum_oracle_1) == 'CONSTANT', ERROR_MESSAGE assert deutsch(quantum_oracle_2) == 'BALANCED', "Looks like your Deutsch has a bug" assert deutsch(quantum_oracle_3) == 'BALANCED', "Looks like your Deutsch has a bug" assert deutsch(quantum_oracle_4) == 'CONSTANT', "Looks like your Deutsch has a bug"
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute # Choose the drawer you like best: from qiskit.tools.visualization import matplotlib_circuit_drawer as draw #from qiskit.tools.visualization import circuit_drawer as draw from qiskit import IBMQ IBMQ.load_accounts() # make sure you have setup your token locally to use this %matplotlib inline import matplotlib.pyplot as plt def show_results(D): # D is a dictionary with classical bits as keys and count as value # example: D = {'000': 497, '001': 527} plt.bar(range(len(D)), list(D.values()), align='center') plt.xticks(range(len(D)), list(D.keys())) plt.show() from qiskit import Aer # See a list of available local simulators print("Aer backends: ", Aer.backends()) # see a list of available remote backends (these are freely given by IBM) print("IBMQ Backends: ", IBMQ.backends()) # execute circuit and either display a histogram of the results def execute_locally(qc, draw_circuit=False, show_results=False): # 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() result_counts = result_sim.get_counts(qc) if draw_circuit or show_results: # Print the results print("simulation: ", result_sim, result_counts) if draw_circuit: # draw the circuit draw(qc) elif show_results: # or show the results show_results(result_counts) return result_counts from qiskit.backends.ibmq import least_busy import time # Compile and run on a real device backend def execute_remotely(qc, draw_circuit=False, show_results=False): if draw_circuit: # draw the circuit draw(qc) try: # select least busy available device and execute. least_busy_device = least_busy(IBMQ.backends(simulator=False)) print("Running on current least busy device: ", least_busy_device) # running the job job_exp = execute(qc, backend=least_busy_device, shots=1024, max_credits=10) lapse, interval = 0, 10 while job_exp.status().name != 'DONE': print('Status @ {} seconds'.format(interval * lapse)) print(job_exp.status()) time.sleep(interval) lapse += 1 print(job_exp.status()) exp_result = job_exp.result() result_counts = exp_result.get_counts(qc) # Show the results print("experiment: ", exp_result, result_counts) if show_results: # show the results show_results(result_counts) return result_counts except: print("All devices are currently unavailable.") return {} def new_circuit(size): # Create a Quantum Register with size qubits qr = QuantumRegister(size) # Create a Classical Register with size bits cr = ClassicalRegister(size) # Create a Quantum Circuit acting on the qr and cr register return qr, cr, QuantumCircuit(qr, cr) ERROR_MESSAGE = "Looks like your Deutsch has a bug" def quantum_oracle_1(qr, cr, circuit): pass def quantum_oracle_2(qr, cr, circuit): circuit.cx(qr[0], qr[1]) def quantum_oracle_3(qr, cr, circuit): circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) circuit.cx(qr[0], qr[1]) def quantum_oracle_4(qr, cr, circuit): circuit.z(qr[1]) circuit.cx(qr[0], qr[1]) qr, cr, circuit = new_circuit(2) # X gate on qubit 1 (bit flip) circuit.x(qr[1]); circuit.h(qr); quantum_oracle_1(qr, cr, circuit) circuit.h(qr[0]); # measure the specific qubit circuit.measure(qr[0], cr[0]); # Try both commands: # results = execute_locally(circuit, draw_circuit=False, show_results=False) # silent mode results = execute_locally(circuit, draw_circuit=True, show_results=False) # results = execute_locally(circuit, draw_circuit=False, show_results=True) # results = execute_locally(circuit, draw_circuit=True, show_results=True) # this will be the same as True, False if '00' in results: print("CONSTANT") elif '10' in results: print("BALANCED") def get_deutsch_verdict(res): # should be improved for error handling if '00' in res: return "CONSTANT" elif '01' in res: return "BALANCED" print(get_deutsch_verdict(results)) def deutsch(black_box): qr, cr, circuit = new_circuit(2) circuit.x(qr[1]) # X gate on qubit 1 (bit flip) circuit.h(qr) # Hadamard on both qubits black_box(qr, cr, circuit) circuit.h(qr[0]) # Hadamard on interesting qubit circuit.measure(qr[0], cr[0]) # measure the specific qubit results = execute_locally(circuit, draw_circuit=False, show_results=False) # silent mode return get_deutsch_verdict(results) deutsch(quantum_oracle_1) assert deutsch(quantum_oracle_1) == 'CONSTANT', ERROR_MESSAGE assert deutsch(quantum_oracle_2) == 'BALANCED', "Looks like your Deutsch has a bug" assert deutsch(quantum_oracle_3) == 'BALANCED', "Looks like your Deutsch has a bug" assert deutsch(quantum_oracle_4) == 'CONSTANT', "Looks like your Deutsch has a bug"
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import numpy as np import matplotlib.pyplot as plt %matplotlib inline # importing Qiskit from qiskit import Aer, IBMQ from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import available_backends, execute, register, get_backend, compile from qiskit.tools import visualization from qiskit.tools.visualization import circuit_drawer q = QuantumRegister(6) qc = QuantumCircuit(q) qc.x(q[2]) qc.cx(q[1], q[5]) qc.cx(q[2], q[5]) qc.cx(q[3], q[5]) qc.ccx(q[1], q[2], q[4]) qc.ccx(q[3], q[4], q[5]) qc.ccx(q[1], q[2], q[4]) qc.x(q[2]) circuit_drawer(qc) def black_box_u_f(circuit, f_in, f_out, aux, n, exactly_1_3_sat_formula): """Circuit that computes the black-box function from f_in to f_out. Create a circuit that verifies whether a given exactly-1 3-SAT formula is satisfied by the input. The exactly-1 version requires exactly one literal out of every clause to be satisfied. """ num_clauses = len(exactly_1_3_sat_formula) for (k, clause) in enumerate(exactly_1_3_sat_formula): # This loop ensures aux[k] is 1 if an odd number of literals # are true for literal in clause: if literal > 0: circuit.cx(f_in[literal-1], aux[k]) else: circuit.x(f_in[-literal-1]) circuit.cx(f_in[-literal-1], aux[k]) # Flip aux[k] if all literals are true, using auxiliary qubit # (ancilla) aux[num_clauses] circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) circuit.ccx(f_in[2], aux[num_clauses], aux[k]) # Flip back to reverse state of negative literals and ancilla circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) for literal in clause: if literal < 0: circuit.x(f_in[-literal-1]) # The formula is satisfied if and only if all auxiliary qubits # except aux[num_clauses] are 1 if (num_clauses == 1): circuit.cx(aux[0], f_out[0]) elif (num_clauses == 2): circuit.ccx(aux[0], aux[1], f_out[0]) elif (num_clauses == 3): circuit.ccx(aux[0], aux[1], aux[num_clauses]) circuit.ccx(aux[2], aux[num_clauses], f_out[0]) circuit.ccx(aux[0], aux[1], aux[num_clauses]) else: raise ValueError('We only allow at most 3 clauses') # Flip back any auxiliary qubits to make sure state is consistent # for future executions of this routine; same loop as above. for (k, clause) in enumerate(exactly_1_3_sat_formula): for literal in clause: if literal > 0: circuit.cx(f_in[literal-1], aux[k]) else: circuit.x(f_in[-literal-1]) circuit.cx(f_in[-literal-1], aux[k]) circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) circuit.ccx(f_in[2], aux[num_clauses], aux[k]) circuit.ccx(f_in[0], f_in[1], aux[num_clauses]) for literal in clause: if literal < 0: circuit.x(f_in[-literal-1]) # -- end function def n_controlled_Z(circuit, controls, target): """Implement a Z gate with multiple controls""" if (len(controls) > 2): raise ValueError('The controlled Z with more than 2 ' + 'controls is not implemented') elif (len(controls) == 1): circuit.h(target) circuit.cx(controls[0], target) circuit.h(target) elif (len(controls) == 2): circuit.h(target) circuit.ccx(controls[0], controls[1], target) circuit.h(target) # -- end function def inversion_about_mean(circuit, f_in, n): """Apply inversion about the mean step of Grover's algorithm.""" # Hadamards everywhere for j in range(n): circuit.h(f_in[j]) # D matrix: flips the sign of the state |000> only for j in range(n): circuit.x(f_in[j]) n_controlled_Z(circuit, [f_in[j] for j in range(n-1)], f_in[n-1]) for j in range(n): circuit.x(f_in[j]) # Hadamards everywhere again for j in range(n): circuit.h(f_in[j]) # -- end function qr = QuantumRegister(3) qInvAvg = QuantumCircuit(qr) inversion_about_mean(qInvAvg, qr, 3) circuit_drawer(qInvAvg) """ Grover search implemented in Qiskit. This module contains the code necessary to run Grover search on 3 qubits, both with a simulator and with a real quantum computing device. This code is the companion for the paper "An introduction to quantum computing, without the physics", Giacomo Nannicini, https://arxiv.org/abs/1708.03684. """ def input_state(circuit, f_in, f_out, n): """(n+1)-qubit input state for Grover search.""" for j in range(n): circuit.h(f_in[j]) circuit.x(f_out) circuit.h(f_out) # -- end function # Make a quantum program for the n-bit Grover search. n = 3 # Exactly-1 3-SAT formula to be satisfied, in conjunctive # normal form. We represent literals with integers, positive or # negative, to indicate a Boolean variable or its negation. exactly_1_3_sat_formula = [[1, 2, -3], [-1, -2, -3], [-1, 2, 3]] # Define three quantum registers: 'f_in' is the search space (input # to the function f), 'f_out' is bit used for the output of function # f, aux are the auxiliary bits used by f to perform its # computation. f_in = QuantumRegister(n) f_out = QuantumRegister(1) aux = QuantumRegister(len(exactly_1_3_sat_formula) + 1) # Define classical register for algorithm result ans = ClassicalRegister(n) # Define quantum circuit with above registers grover = QuantumCircuit() grover.add(f_in) grover.add(f_out) grover.add(aux) grover.add(ans) input_state(grover, f_in, f_out, n) T = 2 for t in range(T): # Apply T full iterations black_box_u_f(grover, f_in, f_out, aux, n, exactly_1_3_sat_formula) inversion_about_mean(grover, f_in, n) # Measure the output register in the computational basis for j in range(n): grover.measure(f_in[j], ans[j]) # Execute circuit backend = Aer.get_backend('qasm_simulator') job = execute([grover], backend=backend, shots=1000) result = job.result() # Get counts and plot histogram counts = result.get_counts(grover) visualization.plot_histogram(counts) IBMQ.load_accounts() # get ibmq_16_rueschlikon configuration and coupling map backend = IBMQ.get_backend('ibmq_16_melbourne') backend_config = backend.configuration() backend_coupling = backend_config['coupling_map'] # compile the circuit for ibmq_16_rueschlikon grover_compiled = compile(grover, backend=backend, coupling_map=backend_coupling, seed=1) grover_compiled_qasm = grover_compiled.experiments[0].header.compiled_circuit_qasm print("Number of gates for", backend.name(), "is", len(grover_compiled_qasm.split("\n")) - 4) circuit_drawer(grover)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import math # importing Qiskit from qiskit import Aer, IBMQ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute from qiskit.backends.ibmq import least_busy # useful additional packages from qiskit.wrapper.jupyter import * from qiskit.tools.visualization import plot_histogram IBMQ.load_accounts() def input_state(circ, q, n): """n-qubit input state for QFT that produces output 1.""" for j in range(n): circ.h(q[j]) circ.u1(math.pi/float(2**(j)), q[j]).inverse() def qft(circ, q, n): """n-qubit QFT on q in circ.""" for j in range(n): for k in range(j): circ.cu1(math.pi/float(2**(j-k)), q[j], q[k]) circ.h(q[j]) q = QuantumRegister(3) c = ClassicalRegister(3) qft3 = QuantumCircuit(q, c) input_state(qft3, q, 3) qft(qft3, q, 3) for i in range(3): qft3.measure(q[i], c[i]) print(qft3.qasm()) # run on local simulator backend = Aer.get_backend("qasm_simulator") simulate = execute(qft3, backend=backend, shots=1024).result() simulate.get_counts() %%qiskit_job_status # Use the IBM Quantum Experience backend = least_busy(IBMQ.backends(simulator=False)) shots = 1024 job_exp = execute(qft3, backend=backend, shots=shots) results = job_exp.result() plot_histogram(results.get_counts())
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from IPython.display import HTML HTML('<div align="center"><iframe width="560" height="315" align="centre" src="https://www.youtube.com/embed/hOlOY7NyMfs?start=75&end=126" frameborder="0" allowfullscreen></iframe></div>') # Brute force period finding algorithm def find_period_classical(x, N): n = 1 t = x while t != 1: t *= x t %= N n += 1 return n import random, itertools # Sieve of Eratosthenes algorithm def sieve( ): D = { } yield 2 for q in itertools.islice(itertools.count(3), 0, None, 2): p = D.pop(q, None) if p is None: D[q*q] = q yield q else: x = p + q while x in D or not (x&1): x += p D[x] = p # Creates a list of prime numbers up to the given argument def get_primes_sieve(n): return list(itertools.takewhile(lambda p: p<n, sieve())) def get_semiprime(n): primes = get_primes_sieve(n) l = len(primes) p = primes[random.randrange(l)] q = primes[random.randrange(l)] return p*q N = get_semiprime(1000) print("semiprime N =",N) import math def shors_algorithm_classical(N): x = random.randint(0,N) # step one if(math.gcd(x,N) != 1): # step two return x,0,math.gcd(x,N),N/math.gcd(x,N) r = find_period_classical(x,N) # step three while(r % 2 != 0): r = find_period_classical(x,N) p = math.gcd(x**int(r/2)+1,N) # step four, ignoring the case where (x^(r/2) +/- 1) is a multiple of N q = math.gcd(x**int(r/2)-1,N) return x,r,p,q x,r,p,q = shors_algorithm_classical(N) print("semiprime N = ",N,", coprime x = ",x,", period r = ",r,", prime factors = ",p," and ",q,sep="") from qiskit import Aer from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, register, get_backend, compile from qiskit.tools.visualization import plot_histogram, circuit_drawer # qc = quantum circuit, qr = quantum register, cr = classical register, a = 2, 7, 8, 11 or 13 def circuit_amod15(qc,qr,cr,a): if a == 2: qc.cswap(qr[4],qr[3],qr[2]) qc.cswap(qr[4],qr[2],qr[1]) qc.cswap(qr[4],qr[1],qr[0]) elif a == 7: qc.cswap(qr[4],qr[1],qr[0]) qc.cswap(qr[4],qr[2],qr[1]) qc.cswap(qr[4],qr[3],qr[2]) qc.cx(qr[4],qr[3]) qc.cx(qr[4],qr[2]) qc.cx(qr[4],qr[1]) qc.cx(qr[4],qr[0]) elif a == 8: qc.cswap(qr[4],qr[1],qr[0]) qc.cswap(qr[4],qr[2],qr[1]) qc.cswap(qr[4],qr[3],qr[2]) elif a == 11: # this is included for completeness qc.cswap(qr[4],qr[2],qr[0]) qc.cswap(qr[4],qr[3],qr[1]) qc.cx(qr[4],qr[3]) qc.cx(qr[4],qr[2]) qc.cx(qr[4],qr[1]) qc.cx(qr[4],qr[0]) elif a == 13: qc.cswap(qr[4],qr[3],qr[2]) qc.cswap(qr[4],qr[2],qr[1]) qc.cswap(qr[4],qr[1],qr[0]) qc.cx(qr[4],qr[3]) qc.cx(qr[4],qr[2]) qc.cx(qr[4],qr[1]) qc.cx(qr[4],qr[0]) # qc = quantum circuit, qr = quantum register, cr = classical register, a = 2, 7, 8, 11 or 13 def circuit_aperiod15(qc,qr,cr,a): if a == 11: circuit_11period15(qc,qr,cr) return # Initialize q[0] to |1> qc.x(qr[0]) # Apply a**4 mod 15 qc.h(qr[4]) # controlled identity on the remaining 4 qubits, which is equivalent to doing nothing qc.h(qr[4]) # measure qc.measure(qr[4],cr[0]) # reinitialise q[4] to |0> qc.reset(qr[4]) # Apply a**2 mod 15 qc.h(qr[4]) # controlled unitary qc.cx(qr[4],qr[2]) qc.cx(qr[4],qr[0]) # feed forward if cr[0] == 1: qc.u1(math.pi/2.,qr[4]) qc.h(qr[4]) # measure qc.measure(qr[4],cr[1]) # reinitialise q[4] to |0> qc.reset(qr[4]) # Apply a mod 15 qc.h(qr[4]) # controlled unitary. circuit_amod15(qc,qr,cr,a) # feed forward if cr[1] == 1: qc.u1(math.pi/2.,qr[4]) if cr[0] == 1: qc.u1(math.pi/4.,qr[4]) qc.h(qr[4]) # measure qc.measure(qr[4],cr[2]) def circuit_11period15(qc,qr,cr): # Initialize q[0] to |1> qc.x(qr[0]) # Apply a**4 mod 15 qc.h(qr[4]) # controlled identity on the remaining 4 qubits, which is equivalent to doing nothing qc.h(qr[4]) # measure qc.measure(qr[4],cr[0]) # reinitialise q[4] to |0> qc.reset(qr[4]) # Apply a**2 mod 15 qc.h(qr[4]) # controlled identity on the remaining 4 qubits, which is equivalent to doing nothing # feed forward if cr[0] == 1: qc.u1(math.pi/2.,qr[4]) qc.h(qr[4]) # measure qc.measure(qr[4],cr[1]) # reinitialise q[4] to |0> qc.reset(qr[4]) # Apply 11 mod 15 qc.h(qr[4]) # controlled unitary. qc.cx(qr[4],qr[3]) qc.cx(qr[4],qr[1]) # feed forward if cr[1] == 1: qc.u1(math.pi/2.,qr[4]) if cr[0] == 1: qc.u1(math.pi/4.,qr[4]) qc.h(qr[4]) # measure qc.measure(qr[4],cr[2]) q = QuantumRegister(5, 'q') c = ClassicalRegister(5, 'c') shor = QuantumCircuit(q, c) circuit_aperiod15(shor,q,c,7) backend = Aer.get_backend('qasm_simulator') sim_job = execute([shor], backend) sim_result = sim_job.result() sim_data = sim_result.get_counts(shor) plot_histogram(sim_data)
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
import pylab from qiskit_aqua import run_algorithm from qiskit_aqua.input import get_input_instance from qiskit.tools.visualization import matplotlib_circuit_drawer as draw from qiskit.tools.visualization import plot_histogram with open('3sat3-5.cnf', 'r') as f: sat_cnf = f.read() print(sat_cnf) algorithm_cfg = { 'name': 'Grover' } oracle_cfg = { 'name': 'SAT', 'cnf': sat_cnf } params = { 'problem': {'name': 'search', 'random_seed': 50}, 'algorithm': algorithm_cfg, 'oracle': oracle_cfg, 'backend': {'name': 'qasm_simulator'} } result = run_algorithm(params) print(result['result']) pylab.rcParams['figure.figsize'] = (8, 4) plot_histogram(result['measurements']) #draw(result['circuit'])