repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
from math import cos, pi, acos print("cosine of 90 degrees is zero:",cos(pi/2)) # find the degree of two unit vectors having the dot product of 0. radian_degree = acos(0) degree = 360*radian_degree/(2*pi) print("the degree of two unit vectors having the dot product of 0 is",degree,"degrees") # include our predefined functions %run qlatvia.py # draw the axes draw_qubit() # # your solution is here # draw_quantum_state(3/5,4/5,"main") draw_quantum_state(-4/5,3/5,"ort1") draw_quantum_state(4/5,-3/5,"ort2") draw_qubit() draw_quantum_state(3/5,-4/5,"main") draw_quantum_state(4/5,3/5,"ort1") # randomly create a 2-dimensional quantum state from math import cos, sin, pi from random import randrange def random_quantum_state2(): angle_degree = randrange(360) angle_radian = 2*pi*angle_degree/360 return [cos(angle_radian),sin(angle_radian)] # finding the angle of a 2-dimensional quantum state from math import acos, pi def angle_quantum_state(x,y): angle_radian = acos(x) # radian of the angle with state |0> angle_degree = 360*angle_radian/(2*pi) # degree of the angle with state |0> # if the second amplitude is negative, # then angle is (-angle_degree) # or equivalently 360 + (-angle_degree) if y<0: angle_degree = 360-angle_degree # degree of the angle # else degree of the angle is the same as degree of the angle with state |0> return angle_degree %run qlatvia.py draw_qubit() from math import acos, pi [x1,y1]=random_quantum_state() # randomly pick a quantum state first_angle = angle_quantum_state(x1,y1) print("the angle of |u> is",first_angle) [x2,y2]=random_quantum_state() # randomly pick a quantum state second_angle = angle_quantum_state(x2,y2) print("the angle of |c> is",second_angle) angle_between_1 = first_angle - second_angle if angle_between_1 < 0: angle_between_1 *= -1 if angle_between_1 >180: angle_between_1 = 360 - angle_between_1 dot_product = x1*x2+y1*y2 print("their dot prouct is",dot_product) angle_between_radian = acos(dot_product) angle_between_2 = 360 * angle_between_radian/(2*pi) print("the angle in between is calculated as",angle_between_1,"and",angle_between_2) draw_quantum_state(x1,y1,"|u>") draw_quantum_state(x2,y2,"|v>")
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# include our predefined functions %run qlatvia.py # draw the axes draw_qubit() # # your solution is here # draw_quantum_state(3/5,4/5,"main") draw_quantum_state(-4/5,3/5,"ort1") draw_quantum_state(4/5,-3/5,"ort2") # include our predefined functions %run qlatvia.py # draw the axes draw_qubit() # # your solution is here # draw_quantum_state(3/5,-4/5,"main") draw_quantum_state(-4/5,-3/5,"ort1") draw_quantum_state(4/5,3/5,"ort2") # include our predefined functions %run qlatvia.py # draw the axes draw_qubit() # # your solution is here # draw_quantum_state(-5/13,12/13,"main") draw_quantum_state(-12/13,-5/13,"ort1") draw_quantum_state(12/13,5/13,"ort2") # include our predefined functions %run qlatvia.py # draw the axes draw_qubit() # # your solution is here # sqrttwo=2**0.5 draw_quantum_state(-1/sqrttwo,-1/sqrttwo,"main") draw_quantum_state(1/sqrttwo,-1/sqrttwo,"ort1") draw_quantum_state(-1/sqrttwo,1/sqrttwo,"ort2") # randomly create a 2-dimensional quantum state from math import cos, sin, pi from random import randrange def random_quantum_state2(): angle_degree = randrange(360) angle_radian = 2*pi*angle_degree/360 return [cos(angle_radian),sin(angle_radian)] # finding the angle of a 2-dimensional quantum state from math import acos, pi def angle_quantum_state(x,y): angle_radian = acos(x) # radian of the angle with state |0> angle_degree = 360*angle_radian/(2*pi) # degree of the angle with state |0> # if the second amplitude is negative, # then angle is (-angle_degree) # or equivalently 360 + (-angle_degree) if y<0: angle_degree = 360-angle_degree # degree of the angle # else degree of the angle is the same as degree of the angle with state |0> return angle_degree %run qlatvia.py draw_qubit() from math import acos, pi [x1,y1]=random_quantum_state2() # randomly pick a quantum state first_angle = angle_quantum_state(x1,y1) print("the angle of |u> is",first_angle) [x2,y2]=random_quantum_state2() # randomly pick a quantum state second_angle = angle_quantum_state(x2,y2) print("the angle of |c> is",second_angle) angle_between_1 = first_angle - second_angle if angle_between_1 < 0: angle_between_1 *= -1 dot_product = x1*x2+y1*y2 print("their dot prouct is",dot_product) angle_between_radian = acos(dot_product) angle_between_2 = 360 * angle_between_radian/(2*pi) print("the angle in between is calculated as",angle_between_1,"and",angle_between_2) draw_quantum_state(x1,y1,"|u>") draw_quantum_state(x2,y2,"|v>") %run qlatvia.py draw_qubit() from math import acos, pi [x1,y1]=random_quantum_state() # randomly pick a quantum state first_angle = angle_quantum_state(x1,y1) print("the angle of |u> is",first_angle) [x2,y2]=random_quantum_state() # randomly pick a quantum state second_angle = angle_quantum_state(x2,y2) print("the angle of |c> is",second_angle) angle_between_1 = first_angle - second_angle if angle_between_1 < 0: angle_between_1 *= -1 if angle_between_1 >180: angle_between_1 = 360 - angle_between_1 dot_product = x1*x2+y1*y2 print("their dot prouct is",dot_product) angle_between_radian = acos(dot_product) angle_between_2 = 360 * angle_between_radian/(2*pi) print("the angle in between is calculated as",angle_between_1,"and",angle_between_2) draw_quantum_state(x1,y1,"|u>") draw_quantum_state(x2,y2,"|v>")
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
%run qlatvia.py draw_qubit() sqrttwo=2**0.5 draw_quantum_state(1,0,"") draw_quantum_state(1/sqrttwo,1/sqrttwo,"|+>") # drawing the angle with |0>-axis from matplotlib.pyplot import gca, text from matplotlib.patches import Arc gca().add_patch( Arc((0,0),0.4,0.4,angle=0,theta1=0,theta2=45) ) text(0.08,0.05,'.',fontsize=30) text(0.21,0.09,'\u03C0/4') %run qlatvia.py draw_qubit() sqrttwo=2**0.5 draw_quantum_state(0,0,"") draw_quantum_state(1/sqrttwo,1/sqrttwo,"|+>") # line of reflection for Hadamard from matplotlib.pyplot import arrow arrow(-1.109,-0.459,2.218,0.918,linestyle='dotted',color='red') # drawing the angle with |0>-axis from matplotlib.pyplot import gca, text from matplotlib.patches import Arc gca().add_patch( Arc((0,0),0.4,0.4,angle=0,theta1=0,theta2=22.5) ) text(0.09,0.015,'.',fontsize=30) text(0.25,0.03,'\u03C0/8') gca().add_patch( Arc((0,0),0.4,0.4,angle=0,theta1=22.5,theta2=45) ) text(0.075,0.065,'.',fontsize=30) text(0.21,0.16,'\u03C0/8') %run qlatvia.py draw_qubit() # line of reflection for Hadamard from matplotlib.pyplot import arrow arrow(-1.109,-0.459,2.218,0.918,linestyle='dotted',color='red') # # your code is here # # visually draw the reflections # second draw sqrttwo=2**0.5 draw_quantum_state(0,1,"|1>") draw_quantum_state(1/sqrttwo,-1/sqrttwo,"|->") %run qlatvia.py draw_qubit() # line of reflection for Hadamard from matplotlib.pyplot import arrow arrow(-1.109,-0.459,2.218,0.918,linestyle='dotted',color='red') # # your code is here # sqrttwo=2**0.5 draw_quantum_state(-1,0,"-|0>") draw_quantum_state(-1/sqrttwo,-1/sqrttwo,"-|+>") %run qlatvia.py draw_qubit() # line of reflection for Hadamard from matplotlib.pyplot import arrow arrow(-1.109,-0.459,2.218,0.918,linestyle='dotted',color='red') # # your code is here # sqrttwo=2**0.5 draw_quantum_state(0,-1,"-|1>") draw_quantum_state(-1/sqrttwo,1/sqrttwo,"-|->") %run qlatvia.py draw_qubit() # line of reflection for Hadamard from matplotlib.pyplot import arrow arrow(-1.109,-0.459,2.218,0.918,linestyle='dotted',color='red') # # your code is here # # create a random quantum state random_state = random_quantum_state2() # draw random draw_quantum_state(random_state[0],random_state[1],"randomState") # apply hadamard sqrttwo=2**0.5 next_state = [random_state[0] * (1/sqrttwo) + random_state[1] * (1/sqrttwo), random_state[0] * (1/sqrttwo) + random_state[1] * -(1/sqrttwo)] # draw the state draw_quantum_state(next_state[0],next_state[1],"refectState") %run qlatvia.py draw_qubit() # # your code is here # random_state = random_quantum_state2() # draw random draw_quantum_state(random_state[0],random_state[1],"randomState") # find the reflection to x-axis # apply hadamard sqrttwo=2**0.5 next_state = [random_state[0] * (1/sqrttwo) + random_state[1] * (1/sqrttwo), random_state[0] * (1/sqrttwo) + random_state[1] * -(1/sqrttwo)] # draw the state draw_quantum_state(next_state[0],next_state[1],"refectState") %run qlatvia.py draw_qubit() # the line y=x from matplotlib.pyplot import arrow arrow(-1,-1,2,2,linestyle='dotted',color='red') # # your code is here # random_state = random_quantum_state2() # draw random draw_quantum_state(random_state[0],random_state[1],"randomState") # find the reflection to x-axis # apply hadamard sqrttwo=2**0.5 next_state = [random_state[0] * 0 + random_state[1] * 1, random_state[0] * 1 + random_state[1] * 0] # draw the state # not operator -> switches x and y draw_quantum_state(next_state[0],next_state[1],"refectState") %run qlatvia.py draw_qubit() # # your code is here # # line of reflection from matplotlib.pyplot import arrow #arrow(x,y,dx,dy,linestyle='dotted',color='red') # # # draw_quantum_state(x,y,"name") import numpy as np import math # method for reflection matrix def get_reflection_matrix(theta): reflect_matrix = np.array([[math.cos(2 * theta), math.sin(2 * theta)],[math.sin(2 * theta), -math.cos(2 * theta)]]) return reflect_matrix # obtain a random quantum state random_quantum_state = np.array(random_quantum_state2()) draw_quantum_state(random_quantum_state[0],random_quantum_state[1],"q-state") theta = math.pi/8 reflected_state = np.matmul(get_reflection_matrix(theta), random_quantum_state) draw_quantum_state(reflected_state[0],reflected_state[1],"reflect-q-state") arrow(0,0,math.cos(theta),math.sin(theta),linestyle='dotted',color='red')
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
%run qlatvia.py draw_qubit() # line of reflection for Hadamard from matplotlib.pyplot import arrow arrow(-1.109,-0.459,2.218,0.918,linestyle='dotted',color='red') sqrttwo=2**0.5 draw_quantum_state(0,1,"") draw_quantum_state(1/sqrttwo,-1/sqrttwo,"|->") %run qlatvia.py draw_qubit() # line of reflection for Hadamard from matplotlib.pyplot import arrow arrow(-1.109,-0.459,2.218,0.918,linestyle='dotted',color='red') sqrttwo=2**0.5 draw_quantum_state(-1,0,"") draw_quantum_state(-1/sqrttwo,-1/sqrttwo,"-|+>") %run qlatvia.py draw_qubit() # line of reflection for Hadamard from matplotlib.pyplot import arrow arrow(-1.109,-0.459,2.218,0.918,linestyle='dotted',color='red') sqrttwo=2**0.5 draw_quantum_state(0,-1,"") draw_quantum_state(-1/sqrttwo,1/sqrttwo,"-|->") # randomly create a 2-dimensional quantum state from math import cos, sin, pi from random import randrange def random_quantum_state2(): angle_degree = randrange(360) angle_radian = 2*pi*angle_degree/360 return [cos(angle_radian),sin(angle_radian)] %run qlatvia.py draw_qubit() # line of reflection for Hadamard from matplotlib.pyplot import arrow arrow(-1.109,-0.459,2.218,0.918,linestyle='dotted',color='red') [x1,y1] = random_quantum_state2() print(x1,y1) sqrttwo=2**0.5 oversqrttwo = 1/sqrttwo [x2,y2] = [ oversqrttwo*x1 + oversqrttwo*y1 , oversqrttwo*x1 - oversqrttwo*y1 ] print(x2,y2) draw_quantum_state(x1,y1,"main") draw_quantum_state(x2,y2,"ref") # randomly create a 2-dimensional quantum state from math import cos, sin, pi from random import randrange def random_quantum_state2(): angle_degree = randrange(360) angle_radian = 2*pi*angle_degree/360 return [cos(angle_radian),sin(angle_radian)] %run qlatvia.py draw_qubit() [x1,y1] = random_quantum_state2() [x2,y2] = [x1,-y1] draw_quantum_state(x1,y1,"main") draw_quantum_state(x2,y2,"ref") # randomly create a 2-dimensional quantum state from math import cos, sin, pi from random import randrange def random_quantum_state2(): angle_degree = randrange(360) angle_radian = 2*pi*angle_degree/360 return [cos(angle_radian),sin(angle_radian)] %run qlatvia.py draw_qubit() # the line y=x from matplotlib.pyplot import arrow arrow(-1,-1,2,2,linestyle='dotted',color='red') [x1,y1] = random_quantum_state2() [x2,y2] = [y1,x1] draw_quantum_state(x1,y1,"main") draw_quantum_state(x2,y2,"ref")
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
%run qlatvia.py draw_qubit() sqrttwo=2**0.5 draw_quantum_state(1,0,"") draw_quantum_state(1/sqrttwo,1/sqrttwo,"|+>") # drawing the angle with |0>-axis from matplotlib.pyplot import gca, text from matplotlib.patches import Arc gca().add_patch( Arc((0,0),0.4,0.4,angle=0,theta1=0,theta2=45) ) text(0.08,0.05,'.',fontsize=30) text(0.21,0.09,'\u03C0/4') %run qlatvia.py draw_qubit() [x,y]=[1,0] draw_quantum_state(x,y,"v0") sqrttwo = 2**0.5 oversqrttwo = 1/sqrttwo R = [ [oversqrttwo, -1*oversqrttwo], [oversqrttwo,oversqrttwo] ] # # your code is here # # import numpy as np R = np.array(R) # initial state 0 s0 = np.array([x, y]) for i in range(1, 9): # rotate the matrix s0 = np.matmul(R, s0) # draw the matrix draw_quantum_state(s0[0], s0[1], "after " + str(i)) %run qlatvia.py draw_qubit() from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer 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 rotation_angle = pi/4 for i in range(1,9): 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) print("iteration",i,": the quantum state is",current_quantum_state) x_value = current_quantum_state[0].real # get the amplitude of |0> y_value = current_quantum_state[1].real # get the amplitude of |1> draw_quantum_state(x_value,y_value,"|v"+str(i)+">") # # your code is here # import math %run qlatvia.py def rotate_angle_times(angle, times): draw_qubit() 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 rotation_angle = angle for i in range(1,times): # defined for block sphere mycircuit1.ry(2*rotation_angle,qreg1[0]) # simulator gives the states job = execute(mycircuit1,Aer.get_backend('statevector_simulator')) current_quantum_state = job.result().get_statevector(mycircuit1) print("iteration",i,": the quantum state is",current_quantum_state) x_value = current_quantum_state[0].real # get the amplitude of |0> y_value = current_quantum_state[1].real # get the amplitude of |1> draw_quantum_state(x_value,y_value,"|v"+str(i)+">") rotate_angle_times((math.pi / 6), 12) rotate_angle_times(((3 * math.pi) / 8), 16) rotate_angle_times(((2**(0.5)) * math.pi ), 20) # # your code is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi from random import randrange # first qubit qreg1 = QuantumRegister(1) creg1 = ClassicalRegister(1) mycircuit1 = QuantumCircuit(qreg1,creg1) # second qubit qreg2 = QuantumRegister(1) creg2 = ClassicalRegister(1) mycircuit2 = QuantumCircuit(qreg2,creg2) # third qubit qreg3 = QuantumRegister(1) creg3 = ClassicalRegister(1) mycircuit3 = QuantumCircuit(qreg3,creg3) # randomly pick the angle of rotation r = randrange(100) theta = 2*pi*(r/100) # radians print("the picked angle is",r*3.6,"degrees and",theta,"radians") # rotate the first qubit mycircuit1.ry(2*theta,qreg1[0]) # the different angles orthogonal to theta theta1 = theta + pi/2 theta2 = theta - pi/2 # rotate the second and third qubits mycircuit2.ry(2*theta1,qreg2[0]) mycircuit3.ry(2*theta2,qreg3[0]) # read the quantum state of the first qubit job = execute(mycircuit1,Aer.get_backend('statevector_simulator')) current_quantum_state=job.result().get_statevector(mycircuit1) [x1,y1]=[current_quantum_state[0].real,current_quantum_state[1].real] print("the first qubit:",x1,y1) # read the quantum state of the second qubit job = execute(mycircuit2,Aer.get_backend('statevector_simulator')) current_quantum_state=job.result().get_statevector(mycircuit2) [x2,y2]=[current_quantum_state[0].real,current_quantum_state[1].real] print("the second qubit:",x2,y2) # read the quantum state of the third qubit job = execute(mycircuit3,Aer.get_backend('statevector_simulator')) current_quantum_state=job.result().get_statevector(mycircuit3) [x3,y3]=[current_quantum_state[0].real,current_quantum_state[1].real] print("the third qubit:",x3,y3) %run qlatvia.py draw_qubit() draw_quantum_state(x1,y1,"v0") draw_quantum_state(x2,y2,"v1") draw_quantum_state(x3,y3,"v2") print("the dot product of |v0> and |v1> is",x1*x2+y1*y2) print("the dot product of |v0> and |v2> is",x1*x3+y1*y3) print("the dot product of |v1> and |v2> is",x2*x3+y2*y3) # make a full rotation by theta + theta_prime theta_prime = 2*pi - theta # rotate all qubits with theta_prime mycircuit1.ry(2*theta_prime,qreg1[0]) mycircuit2.ry(2*theta_prime,qreg2[0]) mycircuit3.ry(2*theta_prime,qreg3[0]) # measure all qubits mycircuit1.measure(qreg1,creg1) mycircuit2.measure(qreg2,creg2) mycircuit3.measure(qreg3,creg3) # draw the first circuit mycircuit1.draw() # draw the first circuit mycircuit2.draw() # draw the first circuit mycircuit3.draw() # execute the first circuit job = execute(mycircuit1,Aer.get_backend('qasm_simulator'),shots=1000) counts = job.result().get_counts(mycircuit1) print(counts) # execute the second circuit job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=1000) counts = job.result().get_counts(mycircuit2) print(counts) # execute the third circuit job = execute(mycircuit3,Aer.get_backend('qasm_simulator'),shots=1000) counts = job.result().get_counts(mycircuit3) print(counts) # # your code is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi, cos, sin # first qubit qreg = QuantumRegister(1) creg = ClassicalRegister(1) mycircuit = QuantumCircuit(qreg,creg) theta=pi/4 for i in range(1,9): total_theta = i*theta mycircuit.ry(2*theta,qreg[0]) job = execute(mycircuit, Aer.get_backend('unitary_simulator')) current_unitary = job.result().get_unitary(mycircuit, decimals=3) print("after",i,"iteration(s):") print(current_unitary[0][0].real,current_unitary[0][1].real) print(current_unitary[1][0].real,current_unitary[1][1].real) print("calculated by python:") print(round(cos(total_theta),3),round(-sin(total_theta),3)) print(round(sin(total_theta),3),round(cos(total_theta),3)) print()
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
%run qlatvia.py draw_qubit() [x,y]=[1,0] draw_quantum_state(x,y,"v0") sqrttwo = 2**0.5 oversqrttwo = 1/sqrttwo R = [ [oversqrttwo, -1*oversqrttwo], [oversqrttwo,oversqrttwo] ] # function for rotation R def rotate(px,py): newx = R[0][0]*px + R[0][1]*py newy = R[1][0]*px + R[1][1]*py return [newx,newy] # apply rotation R 7 times for i in range(1,8): [x,y] = rotate(x,y) draw_quantum_state(x,y,"|v"+str(i)+">") from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi from random import randrange # first qubit qreg1 = QuantumRegister(1) creg1 = ClassicalRegister(1) mycircuit1 = QuantumCircuit(qreg1,creg1) # second qubit qreg2 = QuantumRegister(1) creg2 = ClassicalRegister(1) mycircuit2 = QuantumCircuit(qreg2,creg2) # third qubit qreg3 = QuantumRegister(1) creg3 = ClassicalRegister(1) mycircuit3 = QuantumCircuit(qreg3,creg3) # randomly pick the angle of rotation r = randrange(100) theta = 2*pi*(r/100) # radians print("the picked angle is",r*3.6,"degrees and",theta,"radians") # rotate the first qubit mycircuit1.ry(2*theta,qreg1[0]) # the different angles orthogonal to theta theta1 = theta + pi/2 theta2 = theta - pi/2 # rotate the second and third qubits mycircuit2.ry(2*theta1,qreg2[0]) mycircuit3.ry(2*theta2,qreg3[0]) # read the quantum state of the first qubit job = execute(mycircuit1,Aer.get_backend('statevector_simulator')) current_quantum_state=job.result().get_statevector(mycircuit1) [x1,y1]=[current_quantum_state[0].real,current_quantum_state[1].real] print("the first qubit:",x1,y1) # read the quantum state of the second qubit job = execute(mycircuit2,Aer.get_backend('statevector_simulator')) current_quantum_state=job.result().get_statevector(mycircuit2) [x2,y2]=[current_quantum_state[0].real,current_quantum_state[1].real] print("the second qubit:",x2,y2) # read the quantum state of the third qubit job = execute(mycircuit3,Aer.get_backend('statevector_simulator')) current_quantum_state=job.result().get_statevector(mycircuit3) [x3,y3]=[current_quantum_state[0].real,current_quantum_state[1].real] print("the third qubit:",x3,y3) %run qlatvia.py draw_qubit() draw_quantum_state(x1,y1,"v0") draw_quantum_state(x2,y2,"v1") draw_quantum_state(x3,y3,"v2") print("the dot product of |v0> and |v1> is",x1*x2+y1*y2) print("the dot product of |v0> and |v2> is",x1*x3+y1*y3) print("the dot product of |v1> and |v2> is",x2*x3+y2*y3) # make a full rotation by theta + theta_prime theta_prime = 2*pi - theta # rotate all qubits with theta_prime mycircuit1.ry(2*theta_prime,qreg1[0]) mycircuit2.ry(2*theta_prime,qreg2[0]) mycircuit3.ry(2*theta_prime,qreg3[0]) # measure all qubits mycircuit1.measure(qreg1,creg1) mycircuit2.measure(qreg2,creg2) mycircuit3.measure(qreg3,creg3) # draw the first circuit mycircuit1.draw() # draw the second circuit mycircuit2.draw() # draw the third circuit mycircuit3.draw() # execute the first circuit job = execute(mycircuit1,Aer.get_backend('qasm_simulator'),shots=1000) counts = job.result().get_counts(mycircuit1) print(counts) # execute the second circuit job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=1000) counts = job.result().get_counts(mycircuit2) print(counts) # execute the third circuit job = execute(mycircuit3,Aer.get_backend('qasm_simulator'),shots=1000) counts = job.result().get_counts(mycircuit3) print(counts) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi, cos, sin # first qubit qreg = QuantumRegister(1) creg = ClassicalRegister(1) mycircuit = QuantumCircuit(qreg,creg) theta=pi/4 for i in range(1,9): total_theta = i*theta mycircuit.ry(2*theta,qreg[0]) job = execute(mycircuit, Aer.get_backend('unitary_simulator')) current_unitary = job.result().get_unitary(mycircuit, decimals=3) print("after",i,"iteration(s):") print(current_unitary[0][0].real,current_unitary[0][1].real) print(current_unitary[1][0].real,current_unitary[1][1].real) print("calculated by python:") print(round(cos(total_theta),3),round(-sin(total_theta),3)) print(round(sin(total_theta),3),round(cos(total_theta),3)) print()
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# # your code is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi, cos, sin from random import randrange # quantum circuit with three qubits and three bits qreg = QuantumRegister(3) creg = ClassicalRegister(3) mycircuit = QuantumCircuit(qreg,creg) # rotate the first qubit by random angle r = randrange(100) theta = 2*pi*(r/100) # radians print("the picked angle is",r*3.6,"degrees and",theta,"radians") a = cos(theta) b = sin(theta) print("a=",round(a,3),"b=",round(b,3)) print("a*a=",round(a**2,3),"b*b=",round(b**2,3)) print() mycircuit.ry(2*theta,qreg[0]) # creating an entanglement between the second and third qubits mycircuit.h(qreg[1]) mycircuit.cx(qreg[1],qreg[2]) # CNOT operator by Asja on her qubits where the first qubit is the control qubit mycircuit.cx(qreg[0],qreg[1]) # Hadamard operator by Asja on the first qubit mycircuit.h(qreg[0]) # measurement done by Asja mycircuit.measure(qreg[0],creg[0]) mycircuit.measure(qreg[1],creg[1]) # read the state vector job = execute(mycircuit,Aer.get_backend('statevector_simulator')) current_quantum_state=job.result().get_statevector(mycircuit) print("the state vector is") for i in range(len(current_quantum_state)): print(current_quantum_state[i].real) print() # reverse the order def get_state(i): if i==0: return "000" if i==1: return "100" if i==2: return "010" if i==3: return "110" if i==4: return "001" if i==5: return "101" if i==6: return "011" if i==7: return "111" balvis_state = "" for i in range(len(current_quantum_state)): if current_quantum_state[i].real!=0: if abs(current_quantum_state[i].real-a)<0.000001: balvis_state += "+a|"+ get_state(i)+">" elif abs(current_quantum_state[i].real+a)<0.000001: balvis_state += "-a|"+ get_state(i)+">" elif abs(current_quantum_state[i].real-b)<0.000001: balvis_state += "+b|"+ get_state(i)+">" elif abs(current_quantum_state[i].real+b)<0.000001: balvis_state += "-b|"+ get_state(i)+">" print("which is",balvis_state) mycircuit.draw()
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi, cos, sin from random import randrange # quantum circuit with three qubits and three bits qreg = QuantumRegister(3) creg = ClassicalRegister(3) mycircuit = QuantumCircuit(qreg,creg) # rotate the first qubit by random angle r = randrange(100) theta = 2*pi*(r/100) # radians print("the picked angle is",r*3.6,"degrees and",theta,"radians") a = cos(theta) b = sin(theta) print("a=",round(a,3),"b=",round(b,3)) print("a*a=",round(a**2,3),"b*b=",round(b**2,3)) print() mycircuit.ry(2*theta,qreg[0]) # creating an entanglement between the second and third qubits mycircuit.h(qreg[1]) mycircuit.cx(qreg[1],qreg[2]) # CNOT operator by Asja on her qubits where the first qubit is the control qubit mycircuit.cx(qreg[0],qreg[1]) # Hadamard operator by Asja on the first qubit mycircuit.h(qreg[0]) # measurement done by Asja mycircuit.measure(qreg[0],creg[0]) mycircuit.measure(qreg[1],creg[1]) # read the state vector job = execute(mycircuit,Aer.get_backend('statevector_simulator')) current_quantum_state=job.result().get_statevector(mycircuit) print("the state vector is") for i in range(len(current_quantum_state)): print(current_quantum_state[i].real) print() # reverse the order def get_state(i): if i==0: return "000" if i==1: return "100" if i==2: return "010" if i==3: return "110" if i==4: return "001" if i==5: return "101" if i==6: return "011" if i==7: return "111" balvis_state = "" for i in range(len(current_quantum_state)): if current_quantum_state[i].real!=0: if abs(current_quantum_state[i].real-a)<0.000001: balvis_state += "+a|"+ get_state(i)+">" elif abs(current_quantum_state[i].real+a)<0.000001: balvis_state += "-a|"+ get_state(i)+">" elif abs(current_quantum_state[i].real-b)<0.000001: balvis_state += "+b|"+ get_state(i)+">" elif abs(current_quantum_state[i].real+b)<0.000001: balvis_state += "-b|"+ get_state(i)+">" print("which is",balvis_state) mycircuit.draw()
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi # the angle of rotation theta = 1 * pi/16 # we read streams of length 8, 16, 24, 32, 40, 48, 56, 64 for i in [8, 16, 24, 32, 40, 48, 56, 64]: # quantum circuit with one qubit and one bit qreg = QuantumRegister(1) creg = ClassicalRegister(1) mycircuit = QuantumCircuit(qreg,creg) # the stream of length i for j in range(i): mycircuit.ry(2*theta,qreg[0]) # apply one rotation for each symbol # we measure after reading the whole stream mycircuit.measure(qreg[0],creg[0]) # execute the circuit 100 times job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(mycircuit) d = i /8 if d % 2 == 0: print(i,"is even multiple of 8") else: print(i,"is odd multiple of 8") print("stream of lenght",i,"->",counts) print() # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi from random import randrange rand = randrange(1, 11) # random number can take any value in between 1-11 theta = (rand * 2* pi)/11 # calculating angle # the streams of lengths from 1 to 11 for i in range(1,12): # quantum circuit with one qubit and one bit qreg = QuantumRegister(1) creg = ClassicalRegister(1) mycircuit = QuantumCircuit(qreg,creg) # the stream of length i for j in range(i): mycircuit.ry(2*theta,qreg[0]) # apply one rotation for each symbol # we measure after reading the whole stream mycircuit.measure(qreg[0],creg[0]) # execute the circuit 1000 times job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1000) counts = job.result().get_counts(mycircuit) print("Length of the Stream",i,"->",counts) # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi from random import randrange # for each stream of length from 1 to 10 for i in range(1,11): # we try each angle of the form k*2*pi/11 for k=1,...,10 # we try to find the best k for which we observe 1 the most number_of_one_state = 0 best_k = 1 all_outcomes_for_i = "length "+str(i)+"-> " for k in range(1,11): theta = k*2*pi/11 # quantum circuit with one qubit and one bit qreg = QuantumRegister(1) creg = ClassicalRegister(1) mycircuit = QuantumCircuit(qreg,creg) # the stream of length i for j in range(i): mycircuit.ry(2*theta,qreg[0]) # apply one rotation for each symbol # we measure after reading the whole stream mycircuit.measure(qreg[0],creg[0]) # execute the circuit 10000 times job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=10000) counts = job.result().get_counts(mycircuit) all_outcomes_for_i = all_outcomes_for_i + str(k)+ ":" + str(counts['1']) + " " if int(counts['1']) > number_of_one_state: number_of_one_state = counts['1'] best_k = k print(all_outcomes_for_i) print("for length",i,", the best k is",best_k) # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi from random import randrange p = 31 theta1 = (3 * 2 * pi)/p theta2 = (7 * 2 * pi)/p theta3 = (11 * 2 * pi)/p # the streams of lengths from 1 to 30 for i in range(1,30): # Create a circuit with 3 Quantum States qreg = QuantumRegister(3) creg = ClassicalRegister(3) mycircuit = QuantumCircuit(qreg,creg) for j in range(i): # Rotations applied to each symbol number of length times mycircuit.ry(2*theta1,qreg[0]) mycircuit.ry(2*theta2,qreg[1]) mycircuit.ry(2*theta3,qreg[2]) # we measure the system mycircuit.measure(qreg,creg) # execute 1000 times job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots= 1000) counts = job.result().get_counts(mycircuit) # check the number of times state |000> print(counts) if '000' in counts.keys(): c = counts['000'] else: c = 0 # print the result print('000 is observed',c,'times out of',1000) percentange = round(c/1000*100,1) print("the ratio of 000 is ",percentange,"%") print() # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi from random import randrange # randomly picked angles of rotations k1 = randrange(1,31) theta1 = k1*2*pi/31 k2 = randrange(1,31) theta2 = k2*2*pi/31 k3 = randrange(1,31) theta3 = k3*2*pi/31 print("k1 =",k1,"k2 =",k2,"k3 =",k3) print() max_percentange = 0 # we read streams of length from 1 to 30 for i in range(1,31): # quantum circuit with three qubits and three bits qreg = QuantumRegister(3) creg = ClassicalRegister(3) mycircuit = QuantumCircuit(qreg,creg) # the stream of length i for j in range(i): # apply rotations for each symbol mycircuit.ry(2*theta1,qreg[0]) mycircuit.ry(2*theta2,qreg[1]) mycircuit.ry(2*theta3,qreg[2]) # we measure after reading the whole stream mycircuit.measure(qreg,creg) # execute the circuit N times N = 1000 job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=N) counts = job.result().get_counts(mycircuit) # print(counts) if '000' in counts.keys(): c = counts['000'] else: c = 0 print('000 is observed',c,'times out of',N, "for sequence length", i) percentange = round(c/N*100,1) if max_percentange < percentange: max_percentange = percentange print("the ratio of 000 is ",percentange,"%") print() print("max percentage is",max_percentange) # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi from random import randrange number_of_qubits = 4 #number_of_qubits = 5 # randomly picked angles of rotations theta = [] for i in range(number_of_qubits): k = randrange(1,31) print("k",str(i),"=",k) theta += [k*2*pi/31] print(theta) # we count the number of zeros zeros = '' for i in range(number_of_qubits): zeros = zeros + '0' print("zeros = ",zeros) print() max_percentange = 0 # we read streams of length from 1 to 30 for i in range(1,31): # quantum circuit with qubits and bits qreg = QuantumRegister(number_of_qubits) creg = ClassicalRegister(number_of_qubits) mycircuit = QuantumCircuit(qreg,creg) # the stream of length i for j in range(i): # apply rotations for each symbol for k in range(number_of_qubits): mycircuit.ry(2*theta[k],qreg[k]) # we measure after reading the whole stream mycircuit.measure(qreg,creg) # execute the circuit N times N = 1000 job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=N) counts = job.result().get_counts(mycircuit) # print(counts) if zeros in counts.keys(): c = counts[zeros] else: c = 0 # print('000 is observed',c,'times out of',N) percentange = round(c/N*100,1) if max_percentange < percentange: max_percentange = percentange # print("the ration of 000 is ",percentange,"%") # print() print("max percentage is",max_percentange)
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi from random import randrange # the angle of rotation r = randrange(1,11) print("the picked angle is",r,"times of 2pi/11") print() theta = r*2*pi/11 # we read streams of length from 1 to 11 for i in range(1,12): # quantum circuit with one qubit and one bit qreg = QuantumRegister(1) creg = ClassicalRegister(1) mycircuit = QuantumCircuit(qreg,creg) # the stream of length i for j in range(i): mycircuit.ry(2*theta,qreg[0]) # apply one rotation for each symbol # we measure after reading the whole stream mycircuit.measure(qreg[0],creg[0]) # execute the circuit 1000 times job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1000) counts = job.result().get_counts(mycircuit) print("stream of lenght",i,"->",counts) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi from random import randrange # for each stream of length from 1 to 10 for i in range(1,11): # we try each angle of the form k*2*pi/11 for k=1,...,10 # we try to find the best k for which we observe 1 the most number_of_one_state = 0 best_k = 1 all_outcomes_for_i = "length "+str(i)+"-> " for k in range(1,11): theta = k*2*pi/11 # quantum circuit with one qubit and one bit qreg = QuantumRegister(1) creg = ClassicalRegister(1) mycircuit = QuantumCircuit(qreg,creg) # the stream of length i for j in range(i): mycircuit.ry(2*theta,qreg[0]) # apply one rotation for each symbol # we measure after reading the whole stream mycircuit.measure(qreg[0],creg[0]) # execute the circuit 10000 times job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=10000) counts = job.result().get_counts(mycircuit) all_outcomes_for_i = all_outcomes_for_i + str(k)+ ":" + str(counts['1']) + " " if int(counts['1']) > number_of_one_state: number_of_one_state = counts['1'] best_k = k print(all_outcomes_for_i) print("for length",i,", the best k is",best_k) print() from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi from random import randrange # the angles of rotations theta1 = 3*2*pi/31 theta2 = 7*2*pi/31 theta3 = 11*2*pi/31 # we read streams of length from 1 to 30 for i in range(1,31): # quantum circuit with three qubits and three bits qreg = QuantumRegister(3) creg = ClassicalRegister(3) mycircuit = QuantumCircuit(qreg,creg) # the stream of length i for j in range(i): # apply rotations for each symbol mycircuit.ry(2*theta1,qreg[0]) mycircuit.ry(2*theta2,qreg[1]) mycircuit.ry(2*theta3,qreg[2]) # we measure after reading the whole stream mycircuit.measure(qreg,creg) # execute the circuit N times N = 1000 job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=N) counts = job.result().get_counts(mycircuit) print(counts) if '000' in counts.keys(): c = counts['000'] else: c = 0 print('000 is observed',c,'times out of',N) percentange = round(c/N*100,1) print("the ratio of 000 is ",percentange,"%") print() from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi from random import randrange # randomly picked angles of rotations k1 = randrange(1,31) theta1 = k1*2*pi/31 k2 = randrange(1,31) theta2 = k2*2*pi/31 k3 = randrange(1,31) theta3 = k3*2*pi/31 print("k1 =",k1,"k2 =",k2,"k3 =",k3) print() max_percentange = 0 # we read streams of length from 1 to 30 for i in range(1,31): # quantum circuit with three qubits and three bits qreg = QuantumRegister(3) creg = ClassicalRegister(3) mycircuit = QuantumCircuit(qreg,creg) # the stream of length i for j in range(i): # apply rotations for each symbol mycircuit.ry(2*theta1,qreg[0]) mycircuit.ry(2*theta2,qreg[1]) mycircuit.ry(2*theta3,qreg[2]) # we measure after reading the whole stream mycircuit.measure(qreg,creg) # execute the circuit N times N = 1000 job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=N) counts = job.result().get_counts(mycircuit) # print(counts) if '000' in counts.keys(): c = counts['000'] else: c = 0 # print('000 is observed',c,'times out of',N) percentange = round(c/N*100,1) if max_percentange < percentange: max_percentange = percentange # print("the ration of 000 is ",percentange,"%") # print() print("max percentage is",max_percentange) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi from random import randrange number_of_qubits = 4 #number_of_qubits = 5 # randomly picked angles of rotations theta = [] for i in range(number_of_qubits): k = randrange(1,31) print("k",str(i),"=",k) theta += [k*2*pi/31] # print(theta) # we count the number of zeros zeros = '' for i in range(number_of_qubits): zeros = zeros + '0' print("zeros = ",zeros) print() max_percentange = 0 # we read streams of length from 1 to 30 for i in range(1,31): # quantum circuit with qubits and bits qreg = QuantumRegister(number_of_qubits) creg = ClassicalRegister(number_of_qubits) mycircuit = QuantumCircuit(qreg,creg) # the stream of length i for j in range(i): # apply rotations for each symbol for k in range(number_of_qubits): mycircuit.ry(2*theta[k],qreg[k]) # we measure after reading the whole stream mycircuit.measure(qreg,creg) # execute the circuit N times N = 1000 job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=N) counts = job.result().get_counts(mycircuit) # print(counts) if zeros in counts.keys(): c = counts[zeros] else: c = 0 # print('000 is observed',c,'times out of',N) percentange = round(c/N*100,1) if max_percentange < percentange: max_percentange = percentange # print("the ration of 000 is ",percentange,"%") # print() print("max percentage is",max_percentange)
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi # the angles of rotations theta1 = pi/4 theta2 = pi/6 # the circuit with two qubits qreg = QuantumRegister(2) creg = ClassicalRegister(2) mycircuit = QuantumCircuit(qreg,creg) # when the second qubit is in |0>, the first qubit is rotated by theta1 mycircuit.x(qreg[1]) mycircuit.cu3(2*theta1,0,0,qreg[1],qreg[0]) mycircuit.x(qreg[1]) # when the second qubit is in |1>, the first qubit is rotated by theta2 mycircuit.cu3(2*theta2,0,0,qreg[1],qreg[0]) # we read the unitary matrix job = execute(mycircuit,Aer.get_backend('unitary_simulator')) u=job.result().get_unitary(mycircuit,decimals=3) # we print the unitary matrix in nice format for i in range(len(u)): s="" for j in range(len(u)): val = str(u[i][j].real) while(len(val)<8): val = " "+val s = s + val print(s) # # your code is here # from math import pi, sin, cos theta1 = pi/4 theta2 = pi/6 print(round(cos(theta1),3),-round(sin(theta1),3),0,0) print(round(sin(theta1),3),-round(cos(theta1),3),0,0) print(0,0,round(cos(theta2),3),-round(sin(theta2),3)) print(0,0,round(sin(theta2),3),-round(cos(theta2),3)) # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi, sin, cos # the angle of rotation theta1 = pi/23 theta2 = 2*pi/23 theta3 = 4*pi/23 precision = 3 print("a1 = theta3 => sin(a1) = ",round(sin(theta3),precision)) print("a2 = theta2+theta3 => sin(a2) = ",round(sin(theta2+theta3),precision)) print("a3 = theta1 => sin(a3) = ",round(sin(theta1),precision)) print("a4 = theta1+theta2 => sin(a4) = ",round(sin(theta1+theta2),precision)) print() qreg = QuantumRegister(3) creg = ClassicalRegister(3) circuit = QuantumCircuit(qreg,creg) # controlled rotation when the third qubit is |1> circuit.cu3(2*theta1,0,0,qreg[2],qreg[0]) # controlled rotation when the second qubit is |1> circuit.cu3(2*theta2,0,0,qreg[1],qreg[0]) # controlled rotation when the third qubit is |0> circuit.x(qreg[2]) circuit.cu3(2*theta3,0,0,qreg[2],qreg[0]) circuit.x(qreg[2]) # read the corresponding unitary matrix job = execute(circuit,Aer.get_backend('unitary_simulator')) unitary_matrix=job.result().get_unitary(circuit,decimals=precision) for i in range(len(unitary_matrix)): s="" for j in range(len(unitary_matrix)): val = str(unitary_matrix[i][j].real) while(len(val)<precision+4): val = " "+val s = s + val print(s) # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi, sin, cos from random import randrange # the angle of rotation k1 = randrange(1,31) theta1 = k1*2*pi/31 k2 = randrange(1,31) theta2 = k2*2*pi/31 k3 = randrange(1,31) theta3 = k3*2*pi/31 max_percentange = 0 # for each stream of length from 1 to 31 for i in range(1,32): # initialize the circuit qreg = QuantumRegister(3) creg = ClassicalRegister(3) circuit = QuantumCircuit(qreg,creg) # Hadamard operators before reading the stream for m in range(3): circuit.h(qreg[m]) # read the stream of length i print("stream of length",i,"is being read") for j in range(i): # controlled rotation when the third qubit is |1> circuit.cu3(2*theta1,0,0,qreg[2],qreg[0]) # controlled rotation when the second qubit is |1> circuit.cu3(2*theta2,0,0,qreg[1],qreg[0]) # controlled rotation when the third qubit is |0> circuit.x(qreg[2]) circuit.cu3(2*theta3,0,0,qreg[2],qreg[0]) circuit.x(qreg[2]) # Hadamard operators after reading the stream for m in range(3): circuit.h(qreg[m]) # we measure after reading the whole stream circuit.measure(qreg,creg) # execute the circuit N times N = 1000 job = execute(circuit,Aer.get_backend('qasm_simulator'),shots=N) counts = job.result().get_counts(circuit) print(counts) if '000' in counts.keys(): c = counts['000'] else: c = 0 print('000 is observed',c,'times out of',N) percentange = round(c/N*100,1) if max_percentange < percentange and i != 31: max_percentange = percentange print("the ration of 000 is ",percentange,"%") print() print("maximum percentage of observing unwanted '000' is",max_percentange) # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi # initialize the circuit qreg = QuantumRegister(4) circuit = QuantumCircuit(qreg) # we use the fourth qubit as the auxiliary # apply a rotation to the first qubit when the third and second qubits are in states |0> and |1> # change the state of the third qubit to |1> circuit.x(qreg[2]) # if both the third and second qubits are in states |1>, the state of auxiliary qubit is changed to |1> circuit.ccx(qreg[2],qreg[1],qreg[3]) # the rotation is applied to the first qubit if the state of auxiliary qubit is |1> circuit.cu3(2*pi/6,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[2]) circuit.draw() from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi,sin # the angles of rotations theta1 = pi/10 theta2 = 2*pi/10 theta3 = 3*pi/10 theta4 = 4*pi/10 # for verification, print sin(theta)'s print("sin(theta1) = ",round(sin(theta1),3)) print("sin(theta2) = ",round(sin(theta2),3)) print("sin(theta3) = ",round(sin(theta3),3)) print("sin(theta4) = ",round(sin(theta4),3)) print() qreg = QuantumRegister(4) circuit = QuantumCircuit(qreg) # the third qubit is in |0> # the second qubit is in |0> circuit.x(qreg[2]) circuit.x(qreg[1]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta1,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[1]) circuit.x(qreg[2]) # the third qubit is in |0> # the second qubit is in |1> circuit.x(qreg[2]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta2,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[2]) # the third qubit is in |1> # the second qubit is in |0> circuit.x(qreg[1]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta3,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[1]) # the third qubit is in |1> # the second qubit is in |1> circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta4,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) # read the corresponding unitary matrix job = execute(circuit,Aer.get_backend('unitary_simulator')) unitary_matrix=job.result().get_unitary(circuit,decimals=3) for i in range(len(unitary_matrix)): s="" for j in range(len(unitary_matrix)): val = str(unitary_matrix[i][j].real) while(len(val)<7): val = " "+val s = s + val print(s) # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi,sin # the angle of rotation k1 = randrange(1,61) theta1 = k1*2*pi/61 k2 = randrange(1,61) theta2 = k2*2*pi/61 k3 = randrange(1,61) theta3 = k3*2*pi/61 k4 = randrange(1,61) theta4 = k4*2*pi/61 max_percentange = 0 # for each stream of length of 1, 11, 21, 31, 41, 51, and 61 for i in [1,11,21,31,41,51,61]: #for i in range(1,62): # initialize the circuit qreg = QuantumRegister(4) creg = ClassicalRegister(4) circuit = QuantumCircuit(qreg,creg) # Hadamard operators before reading the stream for m in range(3): circuit.h(qreg[m]) # read the stream of length i print("stream of length",i,"is being read") for j in range(i): # the third qubit is in |0> # the second qubit is in |0> circuit.x(qreg[2]) circuit.x(qreg[1]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta1,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[1]) circuit.x(qreg[2]) # the third qubit is in |0> # the second qubit is in |1> circuit.x(qreg[2]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta2,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[2]) # the third qubit is in |1> # the second qubit is in |0> circuit.x(qreg[1]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta3,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[1]) # the third qubit is in |1> # the second qubit is in |1> circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta4,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) # Hadamard operators after reading the stream for m in range(3): circuit.h(qreg[m]) # we measure after reading the whole stream circuit.measure(qreg,creg) # execute the circuit N times N = 1000 job = execute(circuit,Aer.get_backend('qasm_simulator'),shots=N) counts = job.result().get_counts(circuit) print(counts) if '0000' in counts.keys(): c = counts['0000'] else: c = 0 print('0000 is observed',c,'times out of',N) percentange = round(c/N*100,1) if max_percentange < percentange and i != 61: max_percentange = percentange print("the ration of 0000 is ",percentange,"%") print() print("maximum percentage of observing unwanted '0000' is",max_percentange)
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
from math import pi, sin, cos theta1 = pi/4 theta2 = pi/6 print(round(cos(theta1),3),-round(sin(theta1),3),0,0) print(round(sin(theta1),3),-round(cos(theta1),3),0,0) print(0,0,round(cos(theta2),3),-round(sin(theta2),3)) print(0,0,round(sin(theta2),3),-round(cos(theta2),3)) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi, sin, cos # the angle of rotation theta1 = pi/23 theta2 = 2*pi/23 theta3 = 4*pi/23 precision = 3 print("a1 = theta3 => sin(a1) = ",round(sin(theta3),precision)) print("a2 = theta2+theta3 => sin(a2) = ",round(sin(theta2+theta3),precision)) print("a3 = theta1 => sin(a3) = ",round(sin(theta1),precision)) print("a4 = theta1+theta2 => sin(a4) = ",round(sin(theta1+theta2),precision)) print() qreg = QuantumRegister(3) creg = ClassicalRegister(3) circuit = QuantumCircuit(qreg,creg) # controlled rotation when the third qubit is |1> circuit.cu3(2*theta1,0,0,qreg[2],qreg[0]) # controlled rotation when the second qubit is |1> circuit.cu3(2*theta2,0,0,qreg[1],qreg[0]) # controlled rotation when the third qubit is |0> circuit.x(qreg[2]) circuit.cu3(2*theta3,0,0,qreg[2],qreg[0]) circuit.x(qreg[2]) # read the corresponding unitary matrix job = execute(circuit,Aer.get_backend('unitary_simulator')) unitary_matrix=job.result().get_unitary(circuit,decimals=precision) for i in range(len(unitary_matrix)): s="" for j in range(len(unitary_matrix)): val = str(unitary_matrix[i][j].real) while(len(val)<precision+4): val = " "+val s = s + val print(s) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi, sin, cos from random import randrange # the angle of rotation k1 = randrange(1,31) theta1 = k1*2*pi/31 k2 = randrange(1,31) theta2 = k2*2*pi/31 k3 = randrange(1,31) theta3 = k3*2*pi/31 max_percentange = 0 # for each stream of length from 1 to 31 for i in range(1,32): # initialize the circuit qreg = QuantumRegister(3) creg = ClassicalRegister(3) circuit = QuantumCircuit(qreg,creg) # Hadamard operators before reading the stream for m in range(3): circuit.h(qreg[m]) # read the stream of length i print("stream of length",i,"is being read") for j in range(i): # controlled rotation when the third qubit is |1> circuit.cu3(2*theta1,0,0,qreg[2],qreg[0]) # controlled rotation when the second qubit is |1> circuit.cu3(2*theta2,0,0,qreg[1],qreg[0]) # controlled rotation when the third qubit is |0> circuit.x(qreg[2]) circuit.cu3(2*theta3,0,0,qreg[2],qreg[0]) circuit.x(qreg[2]) # Hadamard operators after reading the stream for m in range(3): circuit.h(qreg[m]) # we measure after reading the whole stream circuit.measure(qreg,creg) # execute the circuit N times N = 1000 job = execute(circuit,Aer.get_backend('qasm_simulator'),shots=N) counts = job.result().get_counts(circuit) print(counts) if '000' in counts.keys(): c = counts['000'] else: c = 0 print('000 is observed',c,'times out of',N) percentange = round(c/N*100,1) if max_percentange < percentange and i != 31: max_percentange = percentange print("the ration of 000 is ",percentange,"%") print() print("maximum percentage of observing unwanted '000' is",max_percentange) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import pi,sin # the angle of rotation k1 = randrange(1,61) theta1 = k1*2*pi/61 k2 = randrange(1,61) theta2 = k2*2*pi/61 k3 = randrange(1,61) theta3 = k3*2*pi/61 k4 = randrange(1,61) theta4 = k4*2*pi/61 max_percentange = 0 # for each stream of length of 1, 11, 21, 31, 41, 51, and 61 for i in [1,11,21,31,41,51,61]: #for i in range(1,62): # initialize the circuit qreg = QuantumRegister(4) creg = ClassicalRegister(4) circuit = QuantumCircuit(qreg,creg) # Hadamard operators before reading the stream for m in range(3): circuit.h(qreg[m]) # read the stream of length i print("stream of length",i,"is being read") for j in range(i): # the third qubit is in |0> # the second qubit is in |0> circuit.x(qreg[2]) circuit.x(qreg[1]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta1,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[1]) circuit.x(qreg[2]) # the third qubit is in |0> # the second qubit is in |1> circuit.x(qreg[2]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta2,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[2]) # the third qubit is in |1> # the second qubit is in |0> circuit.x(qreg[1]) circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta3,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.x(qreg[1]) # the third qubit is in |1> # the second qubit is in |1> circuit.ccx(qreg[2],qreg[1],qreg[3]) circuit.cu3(2*theta4,0,0,qreg[3],qreg[0]) # reverse the effects circuit.ccx(qreg[2],qreg[1],qreg[3]) # Hadamard operators after reading the stream for m in range(3): circuit.h(qreg[m]) # we measure after reading the whole stream circuit.measure(qreg,creg) # execute the circuit N times N = 1000 job = execute(circuit,Aer.get_backend('qasm_simulator'),shots=N) counts = job.result().get_counts(circuit) print(counts) if '0000' in counts.keys(): c = counts['0000'] else: c = 0 print('0000 is observed',c,'times out of',N) percentange = round(c/N*100,1) if max_percentange < percentange and i != 61: max_percentange = percentange print("the ration of 0000 is ",percentange,"%") print() print("maximum percentage of observing unwanted '0000' is",max_percentange)
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
from matplotlib.pyplot import bar labels = [] L = [] for i in range(8): labels = labels + [i+1] L = L + [1] # visualize the values of elements in the list bar(labels,L) # # 1st step - query # # 4th element is marked flip the sign L[3] = -1 * L[3] # visualize the values of elements in the list bar(labels,L) # # 1st step - inversion # import numpy as np # find reflection over the mean sum = 0 for i in range(len(L)): sum += L[i] # mean of all values mean = sum / len(L) # reflection over the mean for i in range(len(L)): value = L[i] new_value = mean - (L[i]-mean) L[i] = new_value # visualize the values of elements in the list bar(labels,L) # # 2nd step - query # L[3] = -1 * L[3] # visualize the values of elements in the list bar(labels,L) # # 2nd step - inversion # sum = 0 for i in range(len(L)): sum += L[i] # mean of all values mean = sum / len(L) # reflection over the mean for i in range(len(L)): value = L[i] new_value = mean - (L[i]-mean) L[i] = new_value # visualize the values of elements in the list bar(labels,L) # # your code is here # # Construct the list with all elements 1 def query(L): L[3] = -1 * L[3] return L def inversion(L): sum = 0 for i in range(len(L)): sum += L[i] # mean of all values mean = sum / len(L) # reflection over the mean for i in range(len(L)): value = L[i] new_value = mean - (L[i]-mean) L[i] = new_value return L # iterate same steps 3 times for i in range(3): L = query(L) L = inversion(L) # visualize the values of elements in the list bar(labels,L) # # your code is here # labels = [] L = [] for i in range(16): labels = labels + [i+1] L = L + [1] def query(L): L[10] = -1 * L[10] return L def inversion(L): sum = 0 for i in range(len(L)): sum += L[i] # mean of all values mean = sum / len(L) # reflection over the mean for i in range(len(L)): value = L[i] new_value = mean - (L[i]-mean) L[i] = new_value return L # iterate the game 16 times for i in range(1, 17): L = query(L) L = inversion(L) print("Value of 11th element after ", i, " iteration: ", L[10] ) print() # visualize the values of elements in the list bar(labels,L) # # your code is here # N = 8 marked = 1 L = [] for i in range(N): L = L + [1/(N**0.5)] # print the elements of a given list with a given precision def print_list(L,precision): output = "" for i in range(len(L)): output = output + str(round(L[i],precision))+" " print(output) print_list(L,3) for i in range(10): print((i+1),"th iteration:") # flip the sign of the marked element L[marked] = -1 * L[marked] # print after query phase print_list(L,3) # summation of all values sum = 0 for i in range(len(L)): sum += L[i] # mean of all values mean = sum / len(L) print("mean = ",round(mean,3)) # reflection over mean for i in range(len(L)): value = L[i] new_value = mean - (L[i]-mean) L[i] = new_value # calculate the length of the list length_of_list = 0 for j in range(len(L)): length_of_list += L[j]*L[j] print("length of list is",round(length_of_list,3)) # print after inversion phase print_list(L,3) print() # visualize the values of elements in the list bar(labels,L) # # your code is here # N = 16 marked_elements = [0,2,9] L = [] for i in range(N): L = L + [1/(N**0.5)] # print the elements of a given list with a given precision def print_list(L,precision): output = "" for i in range(len(L)): output = output + str(round(L[i],precision))+" " print(output) print_list(L,3) for i in range(10): print((i+1),"th iteration:") # flip the sign of the marked element for marked in marked_elements: L[marked] = -1 * L[marked] # print after query phase print_list(L,3) # summation of all values sum = 0 for i in range(len(L)): sum += L[i] # mean of all values mean = sum / len(L) # reflection over mean for i in range(len(L)): value = L[i] new_value = mean - (L[i]-mean) L[i] = new_value # calculate the length of the list length_of_list = 0 for j in range(len(L)): length_of_list += L[j]*L[j] print("length of list is",round(length_of_list,3)) # print after inversion phase print_list(L,3) print() # # your code is here # N = 16 marked_elements = range(12) L = [] for i in range(N): L = L + [1/(N**0.5)] # print the elements of a given list with a given precision def print_list(L,precision): output = "" for i in range(len(L)): output = output + str(round(L[i],precision))+" " print(output) print_list(L,3) for i in range(10): print((i+1),"th iteration:") # flip the sign of the marked element for marked in marked_elements: L[marked] = -1 * L[marked] # print after query phase print_list(L,3) # summation of all values sum = 0 for i in range(len(L)): sum += L[i] # mean of all values mean = sum / len(L) # reflection over mean for i in range(len(L)): value = L[i] new_value = mean - (L[i]-mean) L[i] = new_value # calculate the length of the list length_of_list = 0 for j in range(len(L)): length_of_list += L[j]*L[j] print("length of list is",round(length_of_list,3)) # print after inversion phase print_list(L,3) print()
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
from matplotlib.pyplot import bar labels = [] L = [] for i in range(8): labels = labels + [i+1] L = L + [1] # visualize the values of elements in the list bar(labels,L) # # 1st step - query # # flip the sign of the marked element L[3] = -1 * L[3] # visualize the values of elements in the list bar(labels,L) # # 1st step - inversion # # summation of all values sum = 0 for i in range(len(L)): sum += L[i] # mean of all values mean = sum / len(L) # reflection over the mean for i in range(len(L)): value = L[i] new_value = mean - (L[i]-mean) L[i] = new_value # visualize the values of elements in the list bar(labels,L) # # 2nd step - query # # flip the sign of the marked element L[3] = -1 * L[3] # visualize the values of elements in the list bar(labels,L) # # 2nd step - inversion # # summation of all values sum = 0 for i in range(len(L)): sum += L[i] # mean of all values mean = sum / len(L) # reflection over mean for i in range(len(L)): value = L[i] new_value = mean - (L[i]-mean) L[i] = new_value # visualize the values of elements in the list bar(labels,L) for i in range(3): # flip the sign of the marked element L[3] = -1 * L[3] # summation of all values sum = 0 for i in range(len(L)): sum += L[i] # mean of all values mean = sum / len(L) # reflection over mean for i in range(len(L)): value = L[i] new_value = mean - (L[i]-mean) L[i] = new_value # visualize the values of elements in the list bar(labels,L) from matplotlib.pyplot import bar labels = [] L = [] for i in range(16): labels = labels + [i+1] L = L + [1] for i in range(20): print((i+1),"th iteration:") # flip the sign of the marked element L[11] = -1 * L[11] # print after query phase print(L[11]) # summation of all values sum = 0 for i in range(len(L)): sum += L[i] # mean of all values mean = sum / len(L) # reflection over mean for i in range(len(L)): value = L[i] new_value = mean - (L[i]-mean) L[i] = new_value # print after inversion phase print(L[11]) print() N = 8 marked = 1 L = [] for i in range(N): L = L + [1/(N**0.5)] # print the elements of a given list with a given precision def print_list(L,precision): output = "" for i in range(len(L)): output = output + str(round(L[i],precision))+" " print(output) print_list(L,3) for i in range(10): print((i+1),"th iteration:") # flip the sign of the marked element L[marked] = -1 * L[marked] # print after query phase print_list(L,3) # summation of all values sum = 0 for i in range(len(L)): sum += L[i] # mean of all values mean = sum / len(L) print("mean = ",round(mean,3)) # reflection over mean for i in range(len(L)): value = L[i] new_value = mean - (L[i]-mean) L[i] = new_value # calculate the length of the list length_of_list = 0 for j in range(len(L)): length_of_list += L[j]*L[j] print("length of list is",round(length_of_list,3)) # print after inversion phase print_list(L,3) print() N = 16 marked_elements = [0,2,9] L = [] for i in range(N): L = L + [1/(N**0.5)] # print the elements of a given list with a given precision def print_list(L,precision): output = "" for i in range(len(L)): output = output + str(round(L[i],precision))+" " print(output) print_list(L,3) for i in range(10): print((i+1),"th iteration:") # flip the sign of the marked element for marked in marked_elements: L[marked] = -1 * L[marked] # print after query phase print_list(L,3) # summation of all values sum = 0 for i in range(len(L)): sum += L[i] # mean of all values mean = sum / len(L) # reflection over mean for i in range(len(L)): value = L[i] new_value = mean - (L[i]-mean) L[i] = new_value # calculate the length of the list length_of_list = 0 for j in range(len(L)): length_of_list += L[j]*L[j] print("length of list is",round(length_of_list,3)) # print after inversion phase print_list(L,3) print() N = 16 marked_elements = range(12) L = [] for i in range(N): L = L + [1/(N**0.5)] # print the elements of a given list with a given precision def print_list(L,precision): output = "" for i in range(len(L)): output = output + str(round(L[i],precision))+" " print(output) print_list(L,3) for i in range(10): print((i+1),"th iteration:") # flip the sign of the marked element for marked in marked_elements: L[marked] = -1 * L[marked] # print after query phase print_list(L,3) # summation of all values sum = 0 for i in range(len(L)): sum += L[i] # mean of all values mean = sum / len(L) # reflection over mean for i in range(len(L)): value = L[i] new_value = mean - (L[i]-mean) L[i] = new_value # calculate the length of the list length_of_list = 0 for j in range(len(L)): length_of_list += L[j]*L[j] print("length of list is",round(length_of_list,3)) # print after inversion phase print_list(L,3) print()
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # # your code is here 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("Start state: 01, Result state: ",reverse_outcome," Observed",counts[outcome],"times") # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # # your code is here # # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # Create a circuit 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)): print("Final q-bit value for nth q-bit",(i+1),"is",reverse_outcome[i])
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer 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 # Create a circuit 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)): print("the final value of the qubit nr.",(i+1),"is",reverse_outcome[i])
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # Quantum Circuit with 4 qbits 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 Hadamard to each one of the q-bits for i in range(4): mycircuit.h(qreg[i]) # perform measurement mycircuit.measure(qreg,creg) # Execute circuit 16000 times job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1600) counts = job.result().get_counts(mycircuit) # reverse q-bits to have a readable format for outcome in counts: reverse_outcome = '' for i in outcome: reverse_outcome = i + reverse_outcome print(reverse_outcome,"is observed",counts[outcome],"times") # include our predefined functions %run qlatvia.py # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import acos, pi # after Hadamard operators u = [(13/16)**0.5,(3/16)**0.5] def angle_between_two_states(u1,u2): dot_product = u1[0]*u2[0]+u1[1]*u2[1] return acos(dot_product) theta = angle_between_two_states(u,[1,0]) all_visited_quantum_states =[] 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> by rotating it by theta mycircuit2.ry(2*theta,qreg2[0]) # read and store the current quantum state current_state = execute(mycircuit2,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit2) [x,y] = [current_state[0].real,current_state[1].real] all_visited_quantum_states.append([x,y,'u']) # the first reflection theta = angle_between_two_states([x,y],[1,0]) mycircuit2.ry(2*(-2*theta),qreg2[0]) # read and store the current quantum state current_state = execute(mycircuit2,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit2) [x,y] = [current_state[0].real,current_state[1].real] all_visited_quantum_states.append([x,y,'r']) # the second reflection theta = angle_between_two_states(u,[x,y]) mycircuit2.ry(2*(2*theta),qreg2[0]) # read and store the current quantum state current_state = execute(mycircuit2,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit2) [x,y] = [current_state[0].real,current_state[1].real] all_visited_quantum_states.append([x,y,'n']) # measure the qubit 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) print(counts2) # visualization draw_qubit() for quantum_state in all_visited_quantum_states: draw_quantum_state(quantum_state[0],quantum_state[1],quantum_state[2]) # include our predefined functions %run qlatvia.py # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import acos, pi # after Hadamard operators u = [(63/64)**0.5,(1/64)**0.5] def angle_between_two_states(u1,u2): dot_product = u1[0]*u2[0]+u1[1]*u2[1] return acos(dot_product) theta = angle_between_two_states(u,[1,0]) all_visited_quantum_states =[] 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> by rotating it by theta mycircuit3.ry(2*theta,qreg3[0]) # read and store the current quantum state current_state = execute(mycircuit3,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit3) [x,y] = [current_state[0].real,current_state[1].real] all_visited_quantum_states.append([x,y,'u']) # three iterations for i in range(3): # 4,5,6,7,8,9,10 # the first reflection theta = angle_between_two_states([x,y],[1,0]) mycircuit3.ry(2*(-2*theta),qreg3[0]) # read and store the current quantum state current_state = execute(mycircuit3,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit3) [x,y] = [current_state[0].real,current_state[1].real] all_visited_quantum_states.append([x,y,'r'+str(i+1)]) # the second reflection theta = angle_between_two_states(u,[x,y]) mycircuit3.ry(2*(2*theta),qreg3[0]) # read and store the current quantum state current_state = execute(mycircuit3,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit3) [x,y] = [current_state[0].real,current_state[1].real] all_visited_quantum_states.append([x,y,'n'+str(i+1)]) # measure the qubit 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) print(counts3) # visualization draw_qubit() for quantum_state in all_visited_quantum_states: draw_quantum_state(quantum_state[0],quantum_state[1],quantum_state[2]) # include our predefined functions %run qlatvia.py # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import acos, pi # after Hadamard operators u = [(4/16)**0.5,(12/16)**0.5] def angle_between_two_states(u1,u2): dot_product = u1[0]*u2[0]+u1[1]*u2[1] return acos(dot_product) theta = angle_between_two_states(u,[1,0]) all_visited_quantum_states = [] 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> by rotating it by theta mycircuit3.ry(2*theta,qreg3[0]) # read and store the current quantum state current_state = execute(mycircuit3,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit3) [x,y] = [current_state[0].real,current_state[1].real] all_visited_quantum_states.append([x,y,'u']) # three iterations number_of_iterations = 1 # 2, 3, and 4 for i in range(number_of_iterations): # the first reflection theta = angle_between_two_states([x,y],[1,0]) mycircuit3.ry(2*(-2*theta),qreg3[0]) # read and store the current quantum state current_state = execute(mycircuit3,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit3) [x,y] = [current_state[0].real,current_state[1].real] if i == number_of_iterations -1: all_visited_quantum_states.append([x,y,'r'+str(i+1)]) # the second reflection theta = angle_between_two_states(u,[x,y]) mycircuit3.ry(2*(2*theta),qreg3[0]) # read and store the current quantum state current_state = execute(mycircuit3,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit3) [x,y] = [current_state[0].real,current_state[1].real] if i == number_of_iterations -1: all_visited_quantum_states.append([x,y,'n'+str(i+1)]) # measure the qubit 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) print(counts3) # visualization draw_qubit() for quantum_state in all_visited_quantum_states: draw_quantum_state(quantum_state[0],quantum_state[1],quantum_state[2])
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer 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 all 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") # include our predefined functions %run qlatvia.py # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import acos, pi # after Hadamard operators u = [(13/16)**0.5,(3/16)**0.5] def angle_between_two_states(u1,u2): dot_product = u1[0]*u2[0]+u1[1]*u2[1] return acos(dot_product) theta = angle_between_two_states(u,[1,0]) all_visited_quantum_states =[] 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> by rotating it by theta mycircuit2.ry(2*theta,qreg2[0]) # read and store the current quantum state current_state = execute(mycircuit2,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit2) [x,y] = [current_state[0].real,current_state[1].real] all_visited_quantum_states.append([x,y,'u']) # the first reflection theta = angle_between_two_states([x,y],[1,0]) mycircuit2.ry(2*(-2*theta),qreg2[0]) # read and store the current quantum state current_state = execute(mycircuit2,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit2) [x,y] = [current_state[0].real,current_state[1].real] all_visited_quantum_states.append([x,y,'r']) # the second reflection theta = angle_between_two_states(u,[x,y]) mycircuit2.ry(2*(2*theta),qreg2[0]) # read and store the current quantum state current_state = execute(mycircuit2,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit2) [x,y] = [current_state[0].real,current_state[1].real] all_visited_quantum_states.append([x,y,'n']) # measure the qubit 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) print(counts2) # visualization draw_qubit() for quantum_state in all_visited_quantum_states: draw_quantum_state(quantum_state[0],quantum_state[1],quantum_state[2]) # include our predefined functions %run qlatvia.py # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import acos, pi # after Hadamard operators u = [(63/64)**0.5,(1/64)**0.5] def angle_between_two_states(u1,u2): dot_product = u1[0]*u2[0]+u1[1]*u2[1] return acos(dot_product) theta = angle_between_two_states(u,[1,0]) all_visited_quantum_states =[] 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> by rotating it by theta mycircuit3.ry(2*theta,qreg3[0]) # read and store the current quantum state current_state = execute(mycircuit3,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit3) [x,y] = [current_state[0].real,current_state[1].real] all_visited_quantum_states.append([x,y,'u']) # three iterations for i in range(3): # 4,5,6,7,8,9,10 # the first reflection theta = angle_between_two_states([x,y],[1,0]) mycircuit3.ry(2*(-2*theta),qreg3[0]) # read and store the current quantum state current_state = execute(mycircuit3,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit3) [x,y] = [current_state[0].real,current_state[1].real] all_visited_quantum_states.append([x,y,'r'+str(i+1)]) # the second reflection theta = angle_between_two_states(u,[x,y]) mycircuit3.ry(2*(2*theta),qreg3[0]) # read and store the current quantum state current_state = execute(mycircuit3,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit3) [x,y] = [current_state[0].real,current_state[1].real] all_visited_quantum_states.append([x,y,'n'+str(i+1)]) # measure the qubit 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) print(counts3) # visualization draw_qubit() for quantum_state in all_visited_quantum_states: draw_quantum_state(quantum_state[0],quantum_state[1],quantum_state[2]) # include our predefined functions %run qlatvia.py # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import acos, pi # after Hadamard operators u = [(4/16)**0.5,(12/16)**0.5] def angle_between_two_states(u1,u2): dot_product = u1[0]*u2[0]+u1[1]*u2[1] return acos(dot_product) theta = angle_between_two_states(u,[1,0]) all_visited_quantum_states = [] 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> by rotating it by theta mycircuit3.ry(2*theta,qreg3[0]) # read and store the current quantum state current_state = execute(mycircuit3,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit3) [x,y] = [current_state[0].real,current_state[1].real] all_visited_quantum_states.append([x,y,'u']) # three iterations number_of_iterations = 1 # 2, 3, and 4 for i in range(number_of_iterations): # the first reflection theta = angle_between_two_states([x,y],[1,0]) mycircuit3.ry(2*(-2*theta),qreg3[0]) # read and store the current quantum state current_state = execute(mycircuit3,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit3) [x,y] = [current_state[0].real,current_state[1].real] if i == number_of_iterations -1: all_visited_quantum_states.append([x,y,'r'+str(i+1)]) # the second reflection theta = angle_between_two_states(u,[x,y]) mycircuit3.ry(2*(2*theta),qreg3[0]) # read and store the current quantum state current_state = execute(mycircuit3,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit3) [x,y] = [current_state[0].real,current_state[1].real] if i == number_of_iterations -1: all_visited_quantum_states.append([x,y,'n'+str(i+1)]) # measure the qubit 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) print(counts3) # visualization draw_qubit() for quantum_state in all_visited_quantum_states: draw_quantum_state(quantum_state[0],quantum_state[1],quantum_state[2])
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# 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 similarly 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 square root of",length_square,"is",sqrt(length_square)) # # your solution is here # # # your solution is here #
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
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) # please execute the cell for Task 1 to define u and v # let's create a result list # the first method result=[] # fill it with zeros for i in range(dimension): result.append(0) print("by using the first method, result is initialized to",result) # the second method # alternative and shorter solution for creating a list with zeros result = [0] * 7 print("by using the second method, result is initialized 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 square 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/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# 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 dot product of",u,'and',v,'is',uv) # # your solution is here # # # your solution is here # # let's find the dot 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 dot 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 dot product of u and v is",result) # you may consider to write a function in Python for dot product # # your solution is here # # # your solution is here #
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# 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 dot(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("the dot product of u and -v (",u," and ",neg_v,") is",dot(u,neg_v)) print("the dot product of -u and v (",neg_u," and ",v,") is",dot(neg_u,v)) print("the dot product of -u and -v (",neg_u," and ",neg_v,") is",dot(neg_u,neg_v)) # let's define a function for inner product def dot(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("the dot product of v and u is",dot(v,u)) print("the dot product of -2v and 3u is",dot(v_neg_two,u_three))
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# we may 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), we do the following 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/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
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/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# 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 here 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 # import numpy as np u = [-2, -1, 0, 1] v = [1, 2, 3] uv = np.tensordot(np.array(u), np.array(v), axes = 0) print("uv: " + str(uv)) # 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 a (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]) # matrices 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 # 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]) # # your solution is here # 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/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
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/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
number = 5 # integer real = -3.4 # float name = 'Asja' # string surname = "Sarkana" # string boolean1 = True # Boolean boolean2 = 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() print("integer division:") print("a//b =",a//b) print("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 each list in a new line 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/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# 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 appear 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 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 parentheses left = 34*11 # we continue with the substruction inside the parentheses # 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/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
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/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# 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 # this means that 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 will come here #my_code_inside_for-loop_3 will come here #my_code_inside_for-loop_4 will come here # now I am out of the scope of for-loop #my_code_outside_for-loop_1 will come here #my_code_outside_for-loop_2 will come here # 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 increased by i in each iteration # alternatively, the same assignment can shortly be written as total += i similarly 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 shortened 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 between 10 and 91 that contains the multiples of 7 for j in range(14,92,7): # 14 is the first multiple of 7 greater than 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 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 =",n," S =",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 and see the results by running this cell # # your solution is here # # this is the code for including function randrange into 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/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
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 can also 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 iteratively will be first halved and then added to the summation T how_many_terms = 0 while T<=1.99: n = n/2 # half the value of n print("n = ",n) T = T + n # update the value of T how_many_terms = how_many_terms + 1 print("T = ",T) print("how many terms in the summation:",how_many_terms) # our result says that there should be 8 terms in our summation # let's calculate the summations of the first seven and eight terms, and verify our results T7 = 0 n = 2 # this value iteratively will be first halved and then added to the summation for i in range(7): n = n/2 print("n =",n) T7 = T7 + n print("the summation of the first seven terms is",T7) T8 = 0 n = 2 # this value iteratively will be first halved and then added to the summation for i in range(8): n = n/2 print("n =",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 attempt and the randomly picked number 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 loop 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 by one more level total_attempts = 0 for i in range(number_of_execution): # the middle loop 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/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# 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 see 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 not see any outcome after a single run # do the same task 100 times, and find the percentage of successful iterations (attempts) # 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 experiment most probably will give different percentage value # let's randomly pick a number between 0 and 9, and print whether it is 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 algorithm by using if-else structure 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 related conditionals, we can use if-elif-else structure # # 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 the condition here is True print("it is between 25 and 50") elif r<=75: # if both conditions above are False and the condition here is True print("it is between 51 and 75") else: # if none of the above conditions is True 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 conditional 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 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 falsified 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 takes one parameter (has one argument) 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 # by using "return" command appropriately, the programs can be shortened # 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/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
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/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# 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 automatical :-) 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 above list with its double value # L = [10, 12, 14, 16, 18, 20] # let's print the list before doubling operation print("the list before doubling operation is",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 code as #L[i] = 2 * L[i] # or #L[i] *= 2 # let's print the list after doubling operation print("the list after doubling operation is",L) # after each execution 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 result 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 having a 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 (the concatenation of L with itself) # L * 3 is L + L + L (the concatenation of L with itself twice) # L * m is L + ... + L (the 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 operation 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 that determines 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 a 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 iterations 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, the creation date of list 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/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# 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 brackets? #N = N + [ [i , i**2 , i**3 , i**2 + i**3] ] # Why using double brackets? # In the last two alternative solutions, you may try with a single bracket, # and then see why double brackets are needed for the exact answer. # print the final list print(N) # let's print the list N element by element for i in range(len(N)): print(N[i]) # let's print the list N 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/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# 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 our tutorial, you are expected to write only python codes. # Interested readers may also use HTML and LaTex, but it is not necesary to complete our 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 are few lines of python code print("hello world") str="*" for i in range(10): 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. %%writefile first.py print("hello world") str="*" for i in range(5): print(str) str+="*" %run first.py %load first.py
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# I am a comment in python print("Hello From Quantum World :-)") # please run this cell # import the objects from qiskit 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 of the cell 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) # draw circuit circuit.draw(output='mpl',reverse_bits=True) # the output will be a "matplotlib.Figure" object 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.providers.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/adarshisme/QiskitBiskit
adarshisme
!pip install qiskit !pip install pylatexenc import matplotlib.pyplot as plt import math import matplotlib as mpl import numpy as np import pandas as pd import qiskit as q from qiskit import Aer, assemble, QuantumRegister, ClassicalRegister from qiskit.circuit import QuantumCircuit import pylatexenc from qiskit.quantum_info import Statevector, PTM from qiskit.visualization import array_to_latex from qiskit import transpile from qiskit.providers.aer import QasmSimulator import random from qiskit.quantum_info import partial_trace, Statevector, DensityMatrix from numpy import kron, trace backend = QasmSimulator() def visualize_one_line(x1_vals, y1_vals, axis_labels, title, label): fig, ax = plt.subplots() plt.title(title) plt.xlabel(axis_labels[0]) plt.ylabel(axis_labels[1]) ax.plot(x1_vals, y1_vals, linestyle='-', color='red', label=label) plt.legend() def stateTomography(p): I = (np.array([[1, 0],[0, 1]])* np.array(p)).trace() X = (np.array([[0, 1],[1, 0]])* np.array(p)).trace() Y = (np.array([[0, 0- 1j],[1j, 0]])* np.array(p)).trace() Z = (np.array([[1, 0],[0, -1]])* np.array(p)).trace() return np.array([I, X, Y, Z]) def normalNoise(circ, noise): circ.cry(noise, 0, 1) circ.cnot(1, 0) circ.reset(1) def randomTwirl(circ, noise): x = random.randint(0,3) if x == 1: circ.x(0) if x == 2: circ.y(0) if x == 3: circ.z(0) circ.cry(noise, 0, 1) circ.cnot(1, 0) circ.reset(1) if x == 1: circ.x(0) if x == 2: circ.y(0) if x == 3: circ.z(0) def PauliConjugation(circ, noise, gate): if gate == 'x': circ.x(0) if gate == 'y': circ.y(0) if gate == 'z': circ.z(0) circ.cry(noise, 0, 1) circ.cnot(1, 0) circ.reset(1) if gate == 'x': circ.x(0) if gate == 'y': circ.y(0) if gate == 'z': circ.z(0) def pauli_conjug_x(circ, noise): PauliConjugation(circ, noise, 'x') def pauli_conjug_y(circ, noise): PauliConjugation(circ, noise, 'y') def pauli_conjug_z(circ, noise): PauliConjugation(circ, noise, 'z') tvals = [0.7, 1, 7, 10, 70, 100, 700, 1000, 7000, 10000] funcs = [normalNoise, randomTwirl, pauli_conjug_x, pauli_conjug_y, pauli_conjug_z] strings_to_funcs = {str(noise_func).split(' ')[1]: noise_func for noise_func in funcs} funcs_to_strings = {strings_to_funcs[a]: a for a in strings_to_funcs} success_data = {noise_func: [] for noise_func in funcs} state_tomography_data = {noise_func: [] for noise_func in funcs} for noise_func in funcs: print(funcs_to_strings[noise_func]) for val in tvals: coinQ = QuantumRegister(1) coinC = ClassicalRegister(1) t = val T_1 = 10000 turn = math.pi/500 noise = 2*math.asin(math.sqrt(1-math.e**(-t/T_1))) coinCircuit = QuantumCircuit(coinQ, coinC) coinCircuit.initialize([1, 0], 0) coinCircuit.ry(math.pi/3, 0) coinCircuit.measure(0, 0) coin_compiled = transpile(coinCircuit, backend) flip_sim = backend.run(coin_compiled, shots=1000) result_sim = flip_sim.result() counts = {} counts = result_sim.get_counts(coin_compiled) distribution = [] for i in range(counts['1']): distribution.append(1) for i in range (counts['0']): distribution.append(0) random.shuffle(distribution) unfairQ = QuantumRegister(2) unfairC = ClassicalRegister(1) unfairCircuit = QuantumCircuit(unfairQ, unfairC) unfairCircuit.initialize([1, 0], 0) unfairCircuit.initialize([1, 0], 1) for i in distribution: if i == 1: unfairCircuit.ry(-turn, 0) if i == 0: unfairCircuit.ry(turn, 0) noise_func(unfairCircuit, noise) #For Pauli conjugation comment out randomTwirl and use the below with desired gate #PauliConjugation(unfairCircuit, noise, z) #For normal noise use below #normalNoise(unfairCircuit, noise) unfairCircuit.measure(0, 0) turn_compiled = transpile(unfairCircuit, backend) turn_sim = backend.run(turn_compiled, shots = 200) unfair_sim = turn_sim.result() count_totals = unfair_sim.get_counts(turn_compiled) unfairQ = QuantumRegister(2) unfairCircuit = QuantumCircuit(unfairQ) for i in distribution: if i == 1: unfairCircuit.ry(-turn, 0) if i == 0: unfairCircuit.ry(turn, 0) unfairCircuit.cry(noise, 0, 1) unfairCircuit.cnot(1, 0) unfairCircuit.reset(1) state = Statevector.from_int(0, 2**2) state = state.evolve(unfairCircuit) rho = DensityMatrix(state) qubitOut = partial_trace(rho, [1]) qubitIn = DensityMatrix([1, 0]) stateTomographyIn = stateTomography(qubitIn) stateTomographyOut = stateTomography(qubitOut) success_data[noise_func].append(count_totals['1'] / 200 if '1' in count_totals else 0) state_tomography_data[noise_func].append(stateTomographyOut[-1]) fig, axs = plt.subplots(1, 2, figsize=(13, 5)) fig.suptitle('error correction via twirling and Pauli conjugation') axs[0].set_xscale('log') axs[0].set_xlabel('t / T_1') axs[0].set_ylabel('success probability') axs[1].set_xscale('log') axs[1].set_xlabel('t / T_1') axs[1].set_ylabel('Pauli expectation out') tvals = [t / T_1 for t in tvals] for noise_func in funcs: axs[0].plot(tvals, success_data[noise_func], label=funcs_to_strings[noise_func]) axs[1].plot(tvals, state_tomography_data[noise_func], label=funcs_to_strings[noise_func]) plt.legend()
https://github.com/IBMDeveloperUK/Hello-Quantum-World.
IBMDeveloperUK
import numpy as np import networkx as nx import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble from qiskit.quantum_info import Statevector from qiskit.aqua.algorithms import NumPyEigensolver from qiskit.quantum_info import Pauli from qiskit.aqua.operators import op_converter from qiskit.aqua.operators import WeightedPauliOperator from qiskit.visualization import plot_histogram from qiskit.providers.aer.extensions.snapshot_statevector import * from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost from utils import mapeo_grafo from collections import defaultdict from operator import itemgetter from scipy.optimize import minimize import matplotlib.pyplot as plt LAMBDA = 10 SEED = 10 SHOTS = 10000 # returns the bit index for an alpha and j def bit(i_city, l_time, num_cities): return i_city * num_cities + l_time # e^(cZZ) def append_zz_term(qc, q_i, q_j, gamma, constant_term): qc.cx(q_i, q_j) qc.rz(2*gamma*constant_term,q_j) qc.cx(q_i, q_j) # e^(cZ) def append_z_term(qc, q_i, gamma, constant_term): qc.rz(2*gamma*constant_term, q_i) # e^(cX) def append_x_term(qc,qi,beta): qc.rx(-2*beta, qi) def get_not_edge_in(G): N = G.number_of_nodes() not_edge = [] for i in range(N): for j in range(N): if i != j: buffer_tupla = (i,j) in_edges = False for edge_i, edge_j in G.edges(): if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)): in_edges = True if in_edges == False: not_edge.append((i, j)) return not_edge def get_classical_simplified_z_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # z term # z_classic_term = [0] * N**2 # first term for l in range(N): for i in range(N): z_il_index = bit(i, l, N) z_classic_term[z_il_index] += -1 * _lambda # second term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_jl z_jl_index = bit(j, l, N) z_classic_term[z_jl_index] += _lambda / 2 # third term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_ij z_ij_index = bit(i, j, N) z_classic_term[z_ij_index] += _lambda / 2 # fourth term not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 4 # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) z_classic_term[z_jlplus_index] += _lambda / 4 # fifthy term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) z_classic_term[z_il_index] += weight_ij / 4 # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) z_classic_term[z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) z_classic_term[z_il_index] += weight_ji / 4 # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) z_classic_term[z_jlplus_index] += weight_ji / 4 return z_classic_term def tsp_obj_2(x, G,_lambda): # obtenemos el valor evaluado en f(x_1, x_2,... x_n) not_edge = get_not_edge_in(G) N = G.number_of_nodes() tsp_cost=0 #Distancia weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # x_il x_il_index = bit(edge_i, l, N) # x_jlplus l_plus = (l+1) % N x_jlplus_index = bit(edge_j, l_plus, N) tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij # add order term because G.edges() do not include order tuples # # x_i'l x_il_index = bit(edge_j, l, N) # x_j'lplus x_jlplus_index = bit(edge_i, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji #Constraint 1 for l in range(N): penal1 = 1 for i in range(N): x_il_index = bit(i, l, N) penal1 -= int(x[x_il_index]) tsp_cost += _lambda * penal1**2 #Contstraint 2 for i in range(N): penal2 = 1 for l in range(N): x_il_index = bit(i, l, N) penal2 -= int(x[x_il_index]) tsp_cost += _lambda*penal2**2 #Constraint 3 for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # x_il x_il_index = bit(i, l, N) # x_j(l+1) l_plus = (l+1) % N x_jlplus_index = bit(j, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda return tsp_cost def get_classical_simplified_zz_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # zz term # zz_classic_term = [[0] * N**2 for i in range(N**2) ] # first term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) # z_jl z_jl_index = bit(j, l, N) zz_classic_term[z_il_index][z_jl_index] += _lambda / 2 # second term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) # z_ij z_ij_index = bit(i, j, N) zz_classic_term[z_il_index][z_ij_index] += _lambda / 2 # third term not_edge = get_not_edge_in(G) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4 # fourth term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4 return zz_classic_term def get_classical_simplified_hamiltonian(G, _lambda): # z term # z_classic_term = get_classical_simplified_z_term(G, _lambda) # zz term # zz_classic_term = get_classical_simplified_zz_term(G, _lambda) return z_classic_term, zz_classic_term def get_cost_circuit(G, gamma, _lambda): N = G.number_of_nodes() N_square = N**2 qc = QuantumCircuit(N_square,N_square) z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda) # z term for i in range(N_square): if z_classic_term[i] != 0: append_z_term(qc, i, gamma, z_classic_term[i]) # zz term for i in range(N_square): for j in range(N_square): if zz_classic_term[i][j] != 0: append_zz_term(qc, i, j, gamma, zz_classic_term[i][j]) return qc def get_mixer_operator(G,beta): N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) for n in range(N**2): append_x_term(qc, n, beta) return qc def get_QAOA_circuit(G, beta, gamma, _lambda): assert(len(beta)==len(gamma)) N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) # init min mix state qc.h(range(N**2)) p = len(beta) for i in range(p): qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda)) qc = qc.compose(get_mixer_operator(G, beta[i])) qc.barrier(range(N**2)) qc.snapshot_statevector("final_state") qc.measure(range(N**2),range(N**2)) return qc def invert_counts(counts): return {k[::-1] :v for k,v in counts.items()} # Sample expectation value def compute_tsp_energy_2(counts, G): energy = 0 get_counts = 0 total_counts = 0 for meas, meas_count in counts.items(): obj_for_meas = tsp_obj_2(meas, G, LAMBDA) energy += obj_for_meas*meas_count total_counts += meas_count mean = energy/total_counts return mean def get_black_box_objective_2(G,p): backend = Aer.get_backend('qasm_simulator') sim = Aer.get_backend('aer_simulator') # function f costo def f(theta): beta = theta[:p] gamma = theta[p:] # Anzats qc = get_QAOA_circuit(G, beta, gamma, LAMBDA) result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result() final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0] state_vector = Statevector(final_state_vector) probabilities = state_vector.probabilities() probabilities_states = invert_counts(state_vector.probabilities_dict()) expected_value = 0 for state,probability in probabilities_states.items(): cost = tsp_obj_2(state, G, LAMBDA) expected_value += cost*probability counts = result.get_counts() mean = compute_tsp_energy_2(invert_counts(counts),G) return mean return f def crear_grafo(cantidad_ciudades): pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) return G, mejor_costo, mejor_camino def run_QAOA(p,ciudades, grafo): if grafo == None: G, mejor_costo, mejor_camino = crear_grafo(ciudades) print("Mejor Costo") print(mejor_costo) print("Mejor Camino") print(mejor_camino) print("Bordes del grafo") print(G.edges()) print("Nodos") print(G.nodes()) print("Pesos") labels = nx.get_edge_attributes(G,'weight') print(labels) else: G = grafo intial_random = [] # beta, mixer Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,np.pi)) # gamma, cost Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,2*np.pi)) init_point = np.array(intial_random) obj = get_black_box_objective_2(G,p) res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) print(res_sample) if __name__ == '__main__': # Run QAOA parametros: profundidad p, numero d ciudades, run_QAOA(5, 3, None)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt plt.style.use("ggplot") from pprint import pprint import pickle import time import datetime %matplotlib inline with open("e2d1_raw.pkl", "rb") as f: raw = pickle.load(f) with open("e2d1_qrem.pkl", "rb") as f: qrem = pickle.load(f) with open("e2d1_zne.pkl", "rb") as f: zne = pickle.load(f) with open("e2d1_zne_pt.pkl", "rb") as f: zne_pt = pickle.load(f) num_steps_list = raw["num_steps_list"] raw_fid_list = raw["fid"] raw_stddev_list = raw["stddev"] num_steps_list = qrem["num_steps_list"] qrem_fid_list = qrem["fid"] qrem_stddev_list = qrem["stddev"] num_steps_list = zne["num_steps_list"] zne_fid_list = zne["fid"] zne_stddev_list = zne["stddev"] num_steps_list = zne_pt["num_steps_list"] zne_pt_fid_list = zne_pt["fid"] zne_pt_stddev_list = zne_pt["stddev"] plt.clf() plt.figure(dpi=200) plt.scatter(num_steps_list, raw_fid_list) plt.scatter(num_steps_list, qrem_fid_list) plt.scatter(num_steps_list, zne_fid_list) plt.scatter(num_steps_list, zne_pt_fid_list) limit = 13 plt.clf() plt.figure(dpi=200) plt.scatter(num_steps_list[:limit], raw_fid_list[:limit], marker="o") plt.scatter(num_steps_list[:limit], qrem_fid_list[:limit], marker="v") plt.scatter(num_steps_list[:limit], zne_fid_list[:limit], marker="x") plt.scatter(num_steps_list[:limit], zne_pt_fid_list[:limit], marker="*") plt.xlabel("number of trotter steps") plt.ylabel("state fidelity") plt.legend(("without error mitigations", "with QREM", "with QREM and ZNE", "with QREM, ZNE and Pauli Twirling")) plt.title("The effect of error mitigations") zne_pt_fid_list[12] import qiskit.tools.jupyter %qiskit_version_table
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt plt.style.use("ggplot") from pprint import pprint import pickle import time import datetime %matplotlib inline # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, X, Y, Z, I from qiskit.opflow.state_fns.dict_state_fn import DictStateFn from qiskit.quantum_info import DensityMatrix from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne # unused for this file import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../../solutions/utils/") import circuit_utils, zne_utils, tomography_utils importlib.reload(circuit_utils) importlib.reload(zne_utils) # unused for this file importlib.reload(tomography_utils) # unused for this file from circuit_utils import * from zne_utils import zne_wrapper, zne_decoder from tomography_utils import expvals_to_valid_rho from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() backend = Aer.get_backend("qasm_simulator") # Returns the matrix representation of the XXX Heisenberg model for 3 spin-1/2 particles in a line def H_heis3(): # Interactions (I is the identity matrix; X, Y, and Z are Pauli matricies; ^ is a tensor product) XXs = (I^X^X) + (X^X^I) YYs = (I^Y^Y) + (Y^Y^I) ZZs = (I^Z^Z) + (Z^Z^I) # Sum interactions H = XXs + YYs + ZZs # Return Hamiltonian return H # Returns the matrix representation of U_heis3(t) for a given time t assuming an XXX Heisenberg Hamiltonian for 3 spins-1/2 particles in a line def U_heis3(t): # Compute XXX Hamiltonian for 3 spins in a line H = H_heis3() # Return the exponential of -i multipled by time t multipled by the 3 spin XXX Heisenberg Hamilonian return (t * H).exp_i() # Define array of time points ts = np.linspace(0, np.pi, 100) target_state = DictStateFn({"000": 0, "001": 0, "010": 1, "011": 0, "100": 0, "101": 0, "110": 1, "111": 0}, 1 / np.sqrt(2)) print(DensityMatrix(target_state.to_density_matrix()).is_valid()) # Compute probability of remaining in |110> state over the array of time points # ~target_state gives the bra of the initial state (<110|) # @ is short hand for matrix multiplication # U_heis3(t) is the unitary time evolution at time t # t needs to be wrapped with float(t) to avoid a bug # (...).eval() returns the inner product <110|U_heis3(t)|110> # np.abs(...)**2 is the modulus squared of the innner product which is the expectation value, or probability, of remaining in |110> probs_010_110 = [np.abs((~target_state @ U_heis3(float(t)) @ target_state).eval())**2 for t in ts] # Plot evolution of |110> plt.figure(dpi=200) plt.plot(ts, probs_010_110) plt.xlabel('time') plt.ylabel(r'probability of state $|010\rangle + |110\rangle$') plt.title(r'Evolution of state $|010\rangle + |110\rangle$ under $H_{Heis3}$') # plt.grid() plt.show() num_qubits = 3 # The final time of the state evolution target_times = [i * np.pi / 20 for i in range(0, 20 + 1)] pprint(target_times) # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # unused for this file shots = 1 << 13 reps = 8 # unused target_state = np.zeros((1 << num_qubits, 1 << num_qubits)) target_state[2, 2] = target_state[6, 6] = target_state[2, 6] = target_state[6, 2] = 0.5 target_state = DensityMatrix(target_state) target_state.draw("latex") prob_list = [] for target_time in target_times: print("target_time: ", target_time) t1 = time.perf_counter() # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") cr = ClassicalRegister(num_qubits, name="c") qc = QuantumCircuit(qr, cr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) qc.h(0) qc.x(1) general_subspace_encoder(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian general_subspace_decoder(qc, targets=[0, 1, 2]) # decode qc.x(1) qc.h(0) qc.measure(qr, cr[::-1]) # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # optimize circuit t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_qc = transpile(t3_qc, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_qc (depth:", t3_qc.depth(), ")") t3_qc = transpile(t3_qc, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_qc (depth:", t3_qc.depth(), ")") job = execute(t3_qc, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) prob = job.result().get_counts().get("0" * num_qubits, 0) / shots prob_list.append(prob) t2 = time.perf_counter() print(r'probability of state |010> + |110> = {:.4f}'.format(prob)) print("time:", t2 - t1) print() plt.figure(dpi=200) plt.plot(ts, probs_010_110, label="theoretical prediction") plt.scatter(target_times, prob_list, c="green", zorder=4) plt.legend(("theoretical prediction", "proposed method")) plt.xlabel('time') plt.ylabel(r'probability of state $|010\rangle + |110\rangle$') plt.title(r'Evolution of state $|010\rangle + |110\rangle$ under $H_{Heis3}$') plt.show() import qiskit.tools.jupyter %qiskit_version_table fid_list = [] for target_time in target_times: print("target_time: ", target_time) t1 = time.perf_counter() # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) qc.h(0) qc.x(1) general_subspace_encoder(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian general_subspace_decoder(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = t3_st_qcs # zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = False) # print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) rho = StateTomographyFitter(job.result(), t3_zne_qcs).fit(method='lstsq') fid = state_fidelity(rho, target_state) fid_list.append(fid) t2 = time.perf_counter() print('state tomography fidelity = {:.4f}'.format(fid)) print("time:", t2 - t1) print()
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne # unused for this file import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../../solutions/utils/") import circuit_utils, zne_utils, tomography_utils importlib.reload(circuit_utils) importlib.reload(zne_utils) # unused for this file importlib.reload(tomography_utils) # unused for this file from circuit_utils import * from zne_utils import zne_wrapper, zne_decoder from tomography_utils import expvals_to_valid_rho from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps_list = [1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100] print("trotter step list: ", num_steps_list) scale_factors = [1.0, 2.0, 3.0] # unused for this file shots = 1 << 13 reps = 8 # unused target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') raw_fid_list = [] raw_stddev_list = [] qrem_fid_list = [] qrem_stddev_list = [] for num_steps in num_steps_list: print("trotter steps: ", num_steps) t1 = time.perf_counter() # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = t3_st_qcs # zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = False) # print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) retrieved_jobs = jobs raw_fids = [] qrem_fids = [] for job in retrieved_jobs: raw_results = job.result() mit_results = meas_fitter.filter.apply(raw_results) raw_rho = StateTomographyFitter(raw_results, t3_zne_qcs).fit(method='lstsq') qrem_rho = StateTomographyFitter(mit_results, t3_zne_qcs).fit(method='lstsq') raw_fids.append(state_fidelity(raw_rho, target_state)) qrem_fids.append(state_fidelity(qrem_rho, target_state)) raw_fid_list.append(np.mean(raw_fids)) raw_stddev_list.append(np.std(raw_fids)) qrem_fid_list.append(np.mean(qrem_fids)) qrem_stddev_list.append(np.std(qrem_fids)) t2 = time.perf_counter() print('raw state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(raw_fids), np.std(raw_fids))) print('qrem state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(qrem_fids), np.std(qrem_fids))) print("time:", t2 - t1) print() with open("e2d1_raw.pkl", "wb") as f: pickle.dump({"num_steps_list": num_steps_list, "fid": raw_fid_list, "stddev": raw_stddev_list}, f) with open("e2d1_qrem.pkl", "wb") as f: pickle.dump({"num_steps_list": num_steps_list, "fid": qrem_fid_list, "stddev": qrem_stddev_list}, f) import qiskit.tools.jupyter %qiskit_version_table plt.plot(num_steps_list, raw_fid_list) plt.plot(num_steps_list, qrem_fid_list)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne # unused for this file import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../../solutions/utils/") import circuit_utils, zne_utils, tomography_utils importlib.reload(circuit_utils) importlib.reload(zne_utils) # unused for this file importlib.reload(tomography_utils) # unused for this file from circuit_utils import * from zne_utils import zne_wrapper, zne_decoder from tomography_utils import expvals_to_valid_rho from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps_list = [1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100] print("trotter step list: ", num_steps_list) scale_factors = [1.0, 2.0, 3.0] # unused for this file shots = 1 << 13 reps = 8 # unused target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') qrem_fid_list = [] qrem_stddev_list = [] for num_steps in num_steps_list: print("trotter steps: ", num_steps) t1 = time.perf_counter() # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = t3_st_qcs # zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = False) # print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) retrieved_jobs = jobs qrem_fids = [] for job in retrieved_jobs: raw_results = job.result() mit_results = meas_fitter.filter.apply(raw_results) qrem_rho = StateTomographyFitter(mit_results, t3_zne_qcs).fit(method='lstsq') qrem_fids.append(state_fidelity(qrem_rho, target_state)) qrem_fid_list.append(np.mean(qrem_fids)) qrem_stddev_list.append(np.std(qrem_fids)) t2 = time.perf_counter() print('qrem state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(qrem_fids), np.std(qrem_fids))) print("time:", t2 - t1) print() with open("e2d2_qrem.pkl", "wb") as f: pickle.dump({"num_steps_list": num_steps_list, "fid": qrem_fid_list, "stddev": qrem_stddev_list}, f) import qiskit.tools.jupyter %qiskit_version_table plt.plot(num_steps_list, qrem_fid_list)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt plt.style.use("ggplot") from pprint import pprint import pickle import time import datetime %matplotlib inline with open("e2d1_raw.pkl", "rb") as f: raw = pickle.load(f) with open("e2d1_qrem.pkl", "rb") as f: qrem = pickle.load(f) with open("e2d1_zne.pkl", "rb") as f: zne = pickle.load(f) with open("e2d1_zne_pt.pkl", "rb") as f: zne_pt = pickle.load(f) num_steps_list = raw["num_steps_list"] raw_fid_list = raw["fid"] raw_stddev_list = raw["stddev"] num_steps_list = qrem["num_steps_list"] qrem_fid_list = qrem["fid"] qrem_stddev_list = qrem["stddev"] num_steps_list = zne["num_steps_list"] zne_fid_list = zne["fid"] zne_stddev_list = zne["stddev"] num_steps_list = zne_pt["num_steps_list"] zne_pt_fid_list = zne_pt["fid"] zne_pt_stddev_list = zne_pt["stddev"] plt.clf() plt.figure(dpi=200) plt.scatter(num_steps_list, raw_fid_list) plt.scatter(num_steps_list, qrem_fid_list) plt.scatter(num_steps_list, zne_fid_list) plt.scatter(num_steps_list, zne_pt_fid_list) limit = 13 plt.clf() plt.figure(dpi=200) plt.scatter(num_steps_list[:limit], raw_fid_list[:limit], marker="o") plt.scatter(num_steps_list[:limit], qrem_fid_list[:limit], marker="v") plt.scatter(num_steps_list[:limit], zne_fid_list[:limit], marker="x") plt.scatter(num_steps_list[:limit], zne_pt_fid_list[:limit], marker="*") plt.xlabel("number of trotter steps") plt.ylabel("state fidelity") plt.legend(("without error mitigations", "with QREM", "with QREM and ZNE", "with QREM, ZNE and Pauli Twirling")) plt.title("The effect of error mitigations") zne_pt_fid_list[12] import qiskit.tools.jupyter %qiskit_version_table
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt plt.style.use("ggplot") from pprint import pprint import pickle import time import datetime %matplotlib inline # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, X, Y, Z, I from qiskit.opflow.state_fns.dict_state_fn import DictStateFn from qiskit.quantum_info import DensityMatrix from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne # unused for this file import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../../solutions/utils/") import circuit_utils, zne_utils, tomography_utils importlib.reload(circuit_utils) importlib.reload(zne_utils) # unused for this file importlib.reload(tomography_utils) # unused for this file from circuit_utils import * from zne_utils import zne_wrapper, zne_decoder from tomography_utils import expvals_to_valid_rho from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() backend = Aer.get_backend("qasm_simulator") # Returns the matrix representation of the XXX Heisenberg model for 3 spin-1/2 particles in a line def H_heis3(): # Interactions (I is the identity matrix; X, Y, and Z are Pauli matricies; ^ is a tensor product) XXs = (I^X^X) + (X^X^I) YYs = (I^Y^Y) + (Y^Y^I) ZZs = (I^Z^Z) + (Z^Z^I) # Sum interactions H = XXs + YYs + ZZs # Return Hamiltonian return H # Returns the matrix representation of U_heis3(t) for a given time t assuming an XXX Heisenberg Hamiltonian for 3 spins-1/2 particles in a line def U_heis3(t): # Compute XXX Hamiltonian for 3 spins in a line H = H_heis3() # Return the exponential of -i multipled by time t multipled by the 3 spin XXX Heisenberg Hamilonian return (t * H).exp_i() # Define array of time points ts = np.linspace(0, np.pi, 100) target_state = DictStateFn({"000": 0, "001": 0, "010": 1, "011": 0, "100": 0, "101": 0, "110": 1, "111": 0}, 1 / np.sqrt(2)) print(DensityMatrix(target_state.to_density_matrix()).is_valid()) # Compute probability of remaining in |110> state over the array of time points # ~target_state gives the bra of the initial state (<110|) # @ is short hand for matrix multiplication # U_heis3(t) is the unitary time evolution at time t # t needs to be wrapped with float(t) to avoid a bug # (...).eval() returns the inner product <110|U_heis3(t)|110> # np.abs(...)**2 is the modulus squared of the innner product which is the expectation value, or probability, of remaining in |110> probs_010_110 = [np.abs((~target_state @ U_heis3(float(t)) @ target_state).eval())**2 for t in ts] # Plot evolution of |110> plt.figure(dpi=200) plt.plot(ts, probs_010_110) plt.xlabel('time') plt.ylabel(r'probability of state $|010\rangle + |110\rangle$') plt.title(r'Evolution of state $|010\rangle + |110\rangle$ under $H_{Heis3}$') # plt.grid() plt.show() num_qubits = 3 # The final time of the state evolution target_times = [i * np.pi / 20 for i in range(0, 20 + 1)] pprint(target_times) # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # unused for this file shots = 1 << 13 reps = 8 # unused target_state = np.zeros((1 << num_qubits, 1 << num_qubits)) target_state[2, 2] = target_state[6, 6] = target_state[2, 6] = target_state[6, 2] = 0.5 target_state = DensityMatrix(target_state) target_state.draw("latex") prob_list = [] for target_time in target_times: print("target_time: ", target_time) t1 = time.perf_counter() # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") cr = ClassicalRegister(num_qubits, name="c") qc = QuantumCircuit(qr, cr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) qc.h(0) qc.x(1) general_subspace_encoder(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian general_subspace_decoder(qc, targets=[0, 1, 2]) # decode qc.x(1) qc.h(0) qc.measure(qr, cr[::-1]) # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # optimize circuit t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_qc = transpile(t3_qc, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_qc (depth:", t3_qc.depth(), ")") t3_qc = transpile(t3_qc, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_qc (depth:", t3_qc.depth(), ")") job = execute(t3_qc, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) prob = job.result().get_counts().get("0" * num_qubits, 0) / shots prob_list.append(prob) t2 = time.perf_counter() print(r'probability of state |010> + |110> = {:.4f}'.format(prob)) print("time:", t2 - t1) print() plt.figure(dpi=200) plt.plot(ts, probs_010_110, label="theoretical prediction") plt.scatter(target_times, prob_list, c="green", zorder=4) plt.legend(("theoretical prediction", "proposed method")) plt.xlabel('time') plt.ylabel(r'probability of state $|010\rangle + |110\rangle$') plt.title(r'Evolution of state $|010\rangle + |110\rangle$ under $H_{Heis3}$') plt.show() import qiskit.tools.jupyter %qiskit_version_table fid_list = [] for target_time in target_times: print("target_time: ", target_time) t1 = time.perf_counter() # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) qc.h(0) qc.x(1) general_subspace_encoder(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian general_subspace_decoder(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = t3_st_qcs # zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = False) # print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) rho = StateTomographyFitter(job.result(), t3_zne_qcs).fit(method='lstsq') fid = state_fidelity(rho, target_state) fid_list.append(fid) t2 = time.perf_counter() print('state tomography fidelity = {:.4f}'.format(fid)) print("time:", t2 - t1) print()
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne # unused for this file import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../../solutions/utils/") import circuit_utils, zne_utils, tomography_utils importlib.reload(circuit_utils) importlib.reload(zne_utils) # unused for this file importlib.reload(tomography_utils) # unused for this file from circuit_utils import * from zne_utils import zne_wrapper, zne_decoder from tomography_utils import expvals_to_valid_rho from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps_list = [1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100] print("trotter step list: ", num_steps_list) scale_factors = [1.0, 2.0, 3.0] # unused for this file shots = 1 << 13 reps = 8 # unused target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') raw_fid_list = [] raw_stddev_list = [] qrem_fid_list = [] qrem_stddev_list = [] for num_steps in num_steps_list: print("trotter steps: ", num_steps) t1 = time.perf_counter() # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = t3_st_qcs # zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = False) # print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) retrieved_jobs = jobs raw_fids = [] qrem_fids = [] for job in retrieved_jobs: raw_results = job.result() mit_results = meas_fitter.filter.apply(raw_results) raw_rho = StateTomographyFitter(raw_results, t3_zne_qcs).fit(method='lstsq') qrem_rho = StateTomographyFitter(mit_results, t3_zne_qcs).fit(method='lstsq') raw_fids.append(state_fidelity(raw_rho, target_state)) qrem_fids.append(state_fidelity(qrem_rho, target_state)) raw_fid_list.append(np.mean(raw_fids)) raw_stddev_list.append(np.std(raw_fids)) qrem_fid_list.append(np.mean(qrem_fids)) qrem_stddev_list.append(np.std(qrem_fids)) t2 = time.perf_counter() print('raw state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(raw_fids), np.std(raw_fids))) print('qrem state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(qrem_fids), np.std(qrem_fids))) print("time:", t2 - t1) print() with open("e2d1_raw.pkl", "wb") as f: pickle.dump({"num_steps_list": num_steps_list, "fid": raw_fid_list, "stddev": raw_stddev_list}, f) with open("e2d1_qrem.pkl", "wb") as f: pickle.dump({"num_steps_list": num_steps_list, "fid": qrem_fid_list, "stddev": qrem_stddev_list}, f) import qiskit.tools.jupyter %qiskit_version_table plt.plot(num_steps_list, raw_fid_list) plt.plot(num_steps_list, qrem_fid_list)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne # unused for this file import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../../solutions/utils/") import circuit_utils, zne_utils, tomography_utils importlib.reload(circuit_utils) importlib.reload(zne_utils) # unused for this file importlib.reload(tomography_utils) # unused for this file from circuit_utils import * from zne_utils import zne_wrapper, zne_decoder from tomography_utils import expvals_to_valid_rho from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps_list = [1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100] print("trotter step list: ", num_steps_list) scale_factors = [1.0, 2.0, 3.0] # unused for this file shots = 1 << 13 reps = 8 # unused target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') qrem_fid_list = [] qrem_stddev_list = [] for num_steps in num_steps_list: print("trotter steps: ", num_steps) t1 = time.perf_counter() # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = t3_st_qcs # zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = False) # print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) retrieved_jobs = jobs qrem_fids = [] for job in retrieved_jobs: raw_results = job.result() mit_results = meas_fitter.filter.apply(raw_results) qrem_rho = StateTomographyFitter(mit_results, t3_zne_qcs).fit(method='lstsq') qrem_fids.append(state_fidelity(qrem_rho, target_state)) qrem_fid_list.append(np.mean(qrem_fids)) qrem_stddev_list.append(np.std(qrem_fids)) t2 = time.perf_counter() print('qrem state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(qrem_fids), np.std(qrem_fids))) print("time:", t2 - t1) print() with open("e2d2_qrem.pkl", "wb") as f: pickle.dump({"num_steps_list": num_steps_list, "fid": qrem_fid_list, "stddev": qrem_stddev_list}, f) import qiskit.tools.jupyter %qiskit_version_table plt.plot(num_steps_list, qrem_fid_list)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt plt.style.use("ggplot") from pprint import pprint import pickle import time import datetime %matplotlib inline # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, X, Y, Z, I from qiskit.opflow.state_fns.dict_state_fn import DictStateFn from qiskit.quantum_info import DensityMatrix from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne # unused for this file import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../../solutions/utils/") import circuit_utils, zne_utils, tomography_utils importlib.reload(circuit_utils) importlib.reload(zne_utils) # unused for this file importlib.reload(tomography_utils) # unused for this file from circuit_utils import * from zne_utils import zne_wrapper, zne_decoder from tomography_utils import expvals_to_valid_rho from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() backend = Aer.get_backend("qasm_simulator") # Returns the matrix representation of the XXX Heisenberg model for 3 spin-1/2 particles in a line def H_heis3(): # Interactions (I is the identity matrix; X, Y, and Z are Pauli matricies; ^ is a tensor product) XXs = (I^X^X) + (X^X^I) YYs = (I^Y^Y) + (Y^Y^I) ZZs = (I^Z^Z) + (Z^Z^I) # Sum interactions H = XXs + YYs + ZZs # Return Hamiltonian return H # Returns the matrix representation of U_heis3(t) for a given time t assuming an XXX Heisenberg Hamiltonian for 3 spins-1/2 particles in a line def U_heis3(t): # Compute XXX Hamiltonian for 3 spins in a line H = H_heis3() # Return the exponential of -i multipled by time t multipled by the 3 spin XXX Heisenberg Hamilonian return (t * H).exp_i() # Define array of time points ts = np.linspace(0, np.pi, 100) target_state = DictStateFn({"000": 0, "001": 0, "010": 1, "011": 0, "100": 0, "101": 0, "110": 1, "111": 0}, 1 / np.sqrt(2)) print(DensityMatrix(target_state.to_density_matrix()).is_valid()) # Compute probability of remaining in |110> state over the array of time points # ~target_state gives the bra of the initial state (<110|) # @ is short hand for matrix multiplication # U_heis3(t) is the unitary time evolution at time t # t needs to be wrapped with float(t) to avoid a bug # (...).eval() returns the inner product <110|U_heis3(t)|110> # np.abs(...)**2 is the modulus squared of the innner product which is the expectation value, or probability, of remaining in |110> probs_010_110 = [np.abs((~target_state @ U_heis3(float(t)) @ target_state).eval())**2 for t in ts] # Plot evolution of |110> plt.figure(dpi=200) plt.plot(ts, probs_010_110) plt.xlabel('time') plt.ylabel(r'probability of state $|010\rangle + |110\rangle$') plt.title(r'Evolution of state $|010\rangle + |110\rangle$ under $H_{Heis3}$') # plt.grid() plt.show() num_qubits = 3 # The final time of the state evolution target_times = [i * np.pi / 20 for i in range(0, 20 + 1)] pprint(target_times) # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # unused for this file shots = 1 << 13 reps = 8 # unused target_state = np.zeros((1 << num_qubits, 1 << num_qubits)) target_state[2, 2] = target_state[6, 6] = target_state[2, 6] = target_state[6, 2] = 0.5 target_state = DensityMatrix(target_state) target_state.draw("latex") prob_list = [] for target_time in target_times: print("target_time: ", target_time) t1 = time.perf_counter() # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") cr = ClassicalRegister(num_qubits, name="c") qc = QuantumCircuit(qr, cr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) qc.h(0) qc.x(1) general_subspace_encoder(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian general_subspace_decoder(qc, targets=[0, 1, 2]) # decode qc.x(1) qc.h(0) qc.measure(qr, cr[::-1]) # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # optimize circuit t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_qc = transpile(t3_qc, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_qc (depth:", t3_qc.depth(), ")") t3_qc = transpile(t3_qc, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_qc (depth:", t3_qc.depth(), ")") job = execute(t3_qc, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) prob = job.result().get_counts().get("0" * num_qubits, 0) / shots prob_list.append(prob) t2 = time.perf_counter() print(r'probability of state |010> + |110> = {:.4f}'.format(prob)) print("time:", t2 - t1) print() plt.figure(dpi=200) plt.plot(ts, probs_010_110, label="theoretical prediction") plt.scatter(target_times, prob_list, c="green", zorder=4) plt.legend(("theoretical prediction", "proposed method")) plt.xlabel('time') plt.ylabel(r'probability of state $|010\rangle + |110\rangle$') plt.title(r'Evolution of state $|010\rangle + |110\rangle$ under $H_{Heis3}$') plt.show() import qiskit.tools.jupyter %qiskit_version_table fid_list = [] for target_time in target_times: print("target_time: ", target_time) t1 = time.perf_counter() # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) qc.h(0) qc.x(1) general_subspace_encoder(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian general_subspace_decoder(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = t3_st_qcs # zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = False) # print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) rho = StateTomographyFitter(job.result(), t3_zne_qcs).fit(method='lstsq') fid = state_fidelity(rho, target_state) fid_list.append(fid) t2 = time.perf_counter() print('state tomography fidelity = {:.4f}'.format(fid)) print("time:", t2 - t1) print()
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt plt.style.use("ggplot") from pprint import pprint import pickle import time import datetime %matplotlib inline # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, X, Y, Z, I from qiskit.opflow.state_fns.dict_state_fn import DictStateFn from qiskit.quantum_info import DensityMatrix from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne # unused for this file import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../../solutions/utils/") import circuit_utils, zne_utils, tomography_utils importlib.reload(circuit_utils) importlib.reload(zne_utils) # unused for this file importlib.reload(tomography_utils) # unused for this file from circuit_utils import * from zne_utils import zne_wrapper, zne_decoder from tomography_utils import expvals_to_valid_rho from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() backend = Aer.get_backend("qasm_simulator") # Returns the matrix representation of the XXX Heisenberg model for 3 spin-1/2 particles in a line def H_heis3(): # Interactions (I is the identity matrix; X, Y, and Z are Pauli matricies; ^ is a tensor product) XXs = (I^X^X) + (X^X^I) YYs = (I^Y^Y) + (Y^Y^I) ZZs = (I^Z^Z) + (Z^Z^I) # Sum interactions H = XXs + YYs + ZZs # Return Hamiltonian return H # Returns the matrix representation of U_heis3(t) for a given time t assuming an XXX Heisenberg Hamiltonian for 3 spins-1/2 particles in a line def U_heis3(t): # Compute XXX Hamiltonian for 3 spins in a line H = H_heis3() # Return the exponential of -i multipled by time t multipled by the 3 spin XXX Heisenberg Hamilonian return (t * H).exp_i() # Define array of time points ts = np.linspace(0, np.pi, 100) target_state = DictStateFn({"000": 0, "001": 0, "010": 1, "011": 0, "100": 0, "101": 0, "110": 1, "111": 0}, 1 / np.sqrt(2)) print(DensityMatrix(target_state.to_density_matrix()).is_valid()) # Compute probability of remaining in |110> state over the array of time points # ~target_state gives the bra of the initial state (<110|) # @ is short hand for matrix multiplication # U_heis3(t) is the unitary time evolution at time t # t needs to be wrapped with float(t) to avoid a bug # (...).eval() returns the inner product <110|U_heis3(t)|110> # np.abs(...)**2 is the modulus squared of the innner product which is the expectation value, or probability, of remaining in |110> probs_010_110 = [np.abs((~target_state @ U_heis3(float(t)) @ target_state).eval())**2 for t in ts] # Plot evolution of |110> plt.figure(dpi=200) plt.plot(ts, probs_010_110) plt.xlabel('time') plt.ylabel(r'probability of state $|010\rangle + |110\rangle$') plt.title(r'Evolution of state $|010\rangle + |110\rangle$ under $H_{Heis3}$') # plt.grid() plt.show() num_qubits = 3 # The final time of the state evolution target_times = [i * np.pi / 20 for i in range(0, 20 + 1)] pprint(target_times) # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # unused for this file shots = 1 << 13 reps = 8 # unused target_state = np.zeros((1 << num_qubits, 1 << num_qubits)) target_state[2, 2] = target_state[6, 6] = target_state[2, 6] = target_state[6, 2] = 0.5 target_state = DensityMatrix(target_state) target_state.draw("latex") prob_list = [] for target_time in target_times: print("target_time: ", target_time) t1 = time.perf_counter() # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") cr = ClassicalRegister(num_qubits, name="c") qc = QuantumCircuit(qr, cr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) qc.h(0) qc.x(1) general_subspace_encoder(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian general_subspace_decoder(qc, targets=[0, 1, 2]) # decode qc.x(1) qc.h(0) qc.measure(qr, cr[::-1]) # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # optimize circuit t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_qc = transpile(t3_qc, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_qc (depth:", t3_qc.depth(), ")") t3_qc = transpile(t3_qc, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_qc (depth:", t3_qc.depth(), ")") job = execute(t3_qc, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) prob = job.result().get_counts().get("0" * num_qubits, 0) / shots prob_list.append(prob) t2 = time.perf_counter() print(r'probability of state |010> + |110> = {:.4f}'.format(prob)) print("time:", t2 - t1) print() plt.figure(dpi=200) plt.plot(ts, probs_010_110, label="theoretical prediction") plt.scatter(target_times, prob_list, c="green", zorder=4) plt.legend(("theoretical prediction", "proposed method")) plt.xlabel('time') plt.ylabel(r'probability of state $|010\rangle + |110\rangle$') plt.title(r'Evolution of state $|010\rangle + |110\rangle$ under $H_{Heis3}$') plt.show() import qiskit.tools.jupyter %qiskit_version_table fid_list = [] for target_time in target_times: print("target_time: ", target_time) t1 = time.perf_counter() # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) qc.h(0) qc.x(1) general_subspace_encoder(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian general_subspace_decoder(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = t3_st_qcs # zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = False) # print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) rho = StateTomographyFitter(job.result(), t3_zne_qcs).fit(method='lstsq') fid = state_fidelity(rho, target_state) fid_list.append(fid) t2 = time.perf_counter() print('state tomography fidelity = {:.4f}'.format(fid)) print("time:", t2 - t1) print()
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt plt.style.use("ggplot") from pprint import pprint import pickle import time import datetime %matplotlib inline with open("e2d1_raw.pkl", "rb") as f: raw = pickle.load(f) with open("e2d1_qrem.pkl", "rb") as f: qrem = pickle.load(f) with open("e2d1_zne.pkl", "rb") as f: zne = pickle.load(f) with open("e2d1_zne_pt.pkl", "rb") as f: zne_pt = pickle.load(f) num_steps_list = raw["num_steps_list"] raw_fid_list = raw["fid"] raw_stddev_list = raw["stddev"] num_steps_list = qrem["num_steps_list"] qrem_fid_list = qrem["fid"] qrem_stddev_list = qrem["stddev"] num_steps_list = zne["num_steps_list"] zne_fid_list = zne["fid"] zne_stddev_list = zne["stddev"] num_steps_list = zne_pt["num_steps_list"] zne_pt_fid_list = zne_pt["fid"] zne_pt_stddev_list = zne_pt["stddev"] plt.clf() plt.figure(dpi=200) plt.scatter(num_steps_list, raw_fid_list) plt.scatter(num_steps_list, qrem_fid_list) plt.scatter(num_steps_list, zne_fid_list) plt.scatter(num_steps_list, zne_pt_fid_list) limit = 13 plt.clf() plt.figure(dpi=200) plt.scatter(num_steps_list[:limit], raw_fid_list[:limit], marker="o") plt.scatter(num_steps_list[:limit], qrem_fid_list[:limit], marker="v") plt.scatter(num_steps_list[:limit], zne_fid_list[:limit], marker="x") plt.scatter(num_steps_list[:limit], zne_pt_fid_list[:limit], marker="*") plt.xlabel("number of trotter steps") plt.ylabel("state fidelity") plt.legend(("without error mitigations", "with QREM", "with QREM and ZNE", "with QREM, ZNE and Pauli Twirling")) plt.title("The effect of error mitigations") zne_pt_fid_list[12] import qiskit.tools.jupyter %qiskit_version_table
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne # unused for this file import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../../solutions/utils/") import circuit_utils, zne_utils, tomography_utils importlib.reload(circuit_utils) importlib.reload(zne_utils) # unused for this file importlib.reload(tomography_utils) # unused for this file from circuit_utils import * from zne_utils import zne_wrapper, zne_decoder from tomography_utils import expvals_to_valid_rho from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps_list = [1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100] print("trotter step list: ", num_steps_list) scale_factors = [1.0, 2.0, 3.0] # unused for this file shots = 1 << 13 reps = 8 # unused target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') raw_fid_list = [] raw_stddev_list = [] qrem_fid_list = [] qrem_stddev_list = [] for num_steps in num_steps_list: print("trotter steps: ", num_steps) t1 = time.perf_counter() # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = t3_st_qcs # zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = False) # print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) retrieved_jobs = jobs raw_fids = [] qrem_fids = [] for job in retrieved_jobs: raw_results = job.result() mit_results = meas_fitter.filter.apply(raw_results) raw_rho = StateTomographyFitter(raw_results, t3_zne_qcs).fit(method='lstsq') qrem_rho = StateTomographyFitter(mit_results, t3_zne_qcs).fit(method='lstsq') raw_fids.append(state_fidelity(raw_rho, target_state)) qrem_fids.append(state_fidelity(qrem_rho, target_state)) raw_fid_list.append(np.mean(raw_fids)) raw_stddev_list.append(np.std(raw_fids)) qrem_fid_list.append(np.mean(qrem_fids)) qrem_stddev_list.append(np.std(qrem_fids)) t2 = time.perf_counter() print('raw state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(raw_fids), np.std(raw_fids))) print('qrem state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(qrem_fids), np.std(qrem_fids))) print("time:", t2 - t1) print() with open("e2d1_raw.pkl", "wb") as f: pickle.dump({"num_steps_list": num_steps_list, "fid": raw_fid_list, "stddev": raw_stddev_list}, f) with open("e2d1_qrem.pkl", "wb") as f: pickle.dump({"num_steps_list": num_steps_list, "fid": qrem_fid_list, "stddev": qrem_stddev_list}, f) import qiskit.tools.jupyter %qiskit_version_table plt.plot(num_steps_list, raw_fid_list) plt.plot(num_steps_list, qrem_fid_list)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne # unused for this file import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../../solutions/utils/") import circuit_utils, zne_utils, tomography_utils importlib.reload(circuit_utils) importlib.reload(zne_utils) # unused for this file importlib.reload(tomography_utils) # unused for this file from circuit_utils import * from zne_utils import zne_wrapper, zne_decoder from tomography_utils import expvals_to_valid_rho from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps_list = [1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100] print("trotter step list: ", num_steps_list) scale_factors = [1.0, 2.0, 3.0] # unused for this file shots = 1 << 13 reps = 8 # unused target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') zne_fid_list = [] zne_stddev_list = [] for num_steps in num_steps_list: print("trotter steps: ", num_steps) t1 = time.perf_counter() # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = t3_st_qcs zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = False) print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) retrieved_jobs = jobs zne_fids = [] for job in retrieved_jobs: raw_results = job.result() mit_results = meas_fitter.filter.apply(raw_results) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) zne_rho = expvals_to_valid_rho(num_qubits, zne_expvals) zne_fid = state_fidelity(zne_rho, target_state) zne_fids.append(zne_fid) zne_fid_list.append(np.mean(zne_fids)) zne_stddev_list.append(np.std(zne_fids)) t2 = time.perf_counter() print('zne state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(zne_fids), np.std(zne_fids))) print("time:", t2 - t1) print() with open("e2d1_zne.pkl", "wb") as f: pickle.dump({"num_steps_list": num_steps_list, "fid": zne_fid_list, "stddev": zne_stddev_list}, f) import qiskit.tools.jupyter %qiskit_version_table plt.plot(num_steps_list, zne_fid_list)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne # unused for this file import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../../solutions/utils/") import circuit_utils, zne_utils, tomography_utils importlib.reload(circuit_utils) importlib.reload(zne_utils) # unused for this file importlib.reload(tomography_utils) # unused for this file from circuit_utils import * from zne_utils import zne_wrapper, zne_decoder from tomography_utils import expvals_to_valid_rho from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps_list = [1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100] print("trotter step list: ", num_steps_list) scale_factors = [1.0, 2.0, 3.0] # unused for this file shots = 1 << 13 reps = 8 # unused target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') zne_fid_list = [] zne_stddev_list = [] for num_steps in num_steps_list: print("trotter steps: ", num_steps) t1 = time.perf_counter() # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = t3_st_qcs zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) retrieved_jobs = jobs zne_fids = [] for job in retrieved_jobs: raw_results = job.result() mit_results = meas_fitter.filter.apply(raw_results) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) zne_rho = expvals_to_valid_rho(num_qubits, zne_expvals) zne_fid = state_fidelity(zne_rho, target_state) zne_fids.append(zne_fid) zne_fid_list.append(np.mean(zne_fids)) zne_stddev_list.append(np.std(zne_fids)) t2 = time.perf_counter() print('zne pt state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(zne_fids), np.std(zne_fids))) print("time:", t2 - t1) print() with open("e2d1_zne_pt.pkl", "wb") as f: pickle.dump({"num_steps_list": num_steps_list, "fid": zne_fid_list, "stddev": zne_stddev_list}, f) import qiskit.tools.jupyter %qiskit_version_table plt.plot(num_steps_list, zne_fid_list)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt plt.style.use("ggplot") from pprint import pprint import pickle import time import datetime %matplotlib inline with open("e2d1_raw.pkl", "rb") as f: raw = pickle.load(f) with open("e2d1_qrem.pkl", "rb") as f: qrem = pickle.load(f) with open("e2d1_zne.pkl", "rb") as f: zne = pickle.load(f) with open("e2d1_zne_pt.pkl", "rb") as f: zne_pt = pickle.load(f) num_steps_list = raw["num_steps_list"] raw_fid_list = raw["fid"] raw_stddev_list = raw["stddev"] num_steps_list = qrem["num_steps_list"] qrem_fid_list = qrem["fid"] qrem_stddev_list = qrem["stddev"] num_steps_list = zne["num_steps_list"] zne_fid_list = zne["fid"] zne_stddev_list = zne["stddev"] num_steps_list = zne_pt["num_steps_list"] zne_pt_fid_list = zne_pt["fid"] zne_pt_stddev_list = zne_pt["stddev"] plt.clf() plt.figure(dpi=200) plt.scatter(num_steps_list, raw_fid_list) plt.scatter(num_steps_list, qrem_fid_list) plt.scatter(num_steps_list, zne_fid_list) plt.scatter(num_steps_list, zne_pt_fid_list) limit = 13 plt.clf() plt.figure(dpi=200) plt.scatter(num_steps_list[:limit], raw_fid_list[:limit], marker="o") plt.scatter(num_steps_list[:limit], qrem_fid_list[:limit], marker="v") plt.scatter(num_steps_list[:limit], zne_fid_list[:limit], marker="x") plt.scatter(num_steps_list[:limit], zne_pt_fid_list[:limit], marker="*") plt.xlabel("number of trotter steps") plt.ylabel("state fidelity") plt.legend(("without error mitigations", "with QREM", "with QREM and ZNE", "with QREM, ZNE and Pauli Twirling")) plt.title("The effect of error mitigations") zne_pt_fid_list[12] import qiskit.tools.jupyter %qiskit_version_table
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne # unused for this file import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../../solutions/utils/") import circuit_utils, zne_utils, tomography_utils importlib.reload(circuit_utils) importlib.reload(zne_utils) # unused for this file importlib.reload(tomography_utils) # unused for this file from circuit_utils import * from zne_utils import zne_wrapper, zne_decoder from tomography_utils import expvals_to_valid_rho from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps_list = [1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100] print("trotter step list: ", num_steps_list) scale_factors = [1.0, 2.0, 3.0] # unused for this file shots = 1 << 13 reps = 8 # unused target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') raw_fid_list = [] raw_stddev_list = [] qrem_fid_list = [] qrem_stddev_list = [] for num_steps in num_steps_list: print("trotter steps: ", num_steps) t1 = time.perf_counter() # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = t3_st_qcs # zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = False) # print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) retrieved_jobs = jobs raw_fids = [] qrem_fids = [] for job in retrieved_jobs: raw_results = job.result() mit_results = meas_fitter.filter.apply(raw_results) raw_rho = StateTomographyFitter(raw_results, t3_zne_qcs).fit(method='lstsq') qrem_rho = StateTomographyFitter(mit_results, t3_zne_qcs).fit(method='lstsq') raw_fids.append(state_fidelity(raw_rho, target_state)) qrem_fids.append(state_fidelity(qrem_rho, target_state)) raw_fid_list.append(np.mean(raw_fids)) raw_stddev_list.append(np.std(raw_fids)) qrem_fid_list.append(np.mean(qrem_fids)) qrem_stddev_list.append(np.std(qrem_fids)) t2 = time.perf_counter() print('raw state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(raw_fids), np.std(raw_fids))) print('qrem state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(qrem_fids), np.std(qrem_fids))) print("time:", t2 - t1) print() with open("e2d1_raw.pkl", "wb") as f: pickle.dump({"num_steps_list": num_steps_list, "fid": raw_fid_list, "stddev": raw_stddev_list}, f) with open("e2d1_qrem.pkl", "wb") as f: pickle.dump({"num_steps_list": num_steps_list, "fid": qrem_fid_list, "stddev": qrem_stddev_list}, f) import qiskit.tools.jupyter %qiskit_version_table plt.plot(num_steps_list, raw_fid_list) plt.plot(num_steps_list, qrem_fid_list)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne # unused for this file import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../../solutions/utils/") import circuit_utils, zne_utils, tomography_utils importlib.reload(circuit_utils) importlib.reload(zne_utils) # unused for this file importlib.reload(tomography_utils) # unused for this file from circuit_utils import * from zne_utils import zne_wrapper, zne_decoder from tomography_utils import expvals_to_valid_rho from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps_list = [1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100] print("trotter step list: ", num_steps_list) scale_factors = [1.0, 2.0, 3.0] # unused for this file shots = 1 << 13 reps = 8 # unused target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') zne_fid_list = [] zne_stddev_list = [] for num_steps in num_steps_list: print("trotter steps: ", num_steps) t1 = time.perf_counter() # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = t3_st_qcs zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = False) print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) retrieved_jobs = jobs zne_fids = [] for job in retrieved_jobs: raw_results = job.result() mit_results = meas_fitter.filter.apply(raw_results) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) zne_rho = expvals_to_valid_rho(num_qubits, zne_expvals) zne_fid = state_fidelity(zne_rho, target_state) zne_fids.append(zne_fid) zne_fid_list.append(np.mean(zne_fids)) zne_stddev_list.append(np.std(zne_fids)) t2 = time.perf_counter() print('zne state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(zne_fids), np.std(zne_fids))) print("time:", t2 - t1) print() with open("e2d1_zne.pkl", "wb") as f: pickle.dump({"num_steps_list": num_steps_list, "fid": zne_fid_list, "stddev": zne_stddev_list}, f) import qiskit.tools.jupyter %qiskit_version_table plt.plot(num_steps_list, zne_fid_list)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne # unused for this file import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../../solutions/utils/") import circuit_utils, zne_utils, tomography_utils importlib.reload(circuit_utils) importlib.reload(zne_utils) # unused for this file importlib.reload(tomography_utils) # unused for this file from circuit_utils import * from zne_utils import zne_wrapper, zne_decoder from tomography_utils import expvals_to_valid_rho from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps_list = [1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100] print("trotter step list: ", num_steps_list) scale_factors = [1.0, 2.0, 3.0] # unused for this file shots = 1 << 13 reps = 8 # unused target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') zne_fid_list = [] zne_stddev_list = [] for num_steps in num_steps_list: print("trotter steps: ", num_steps) t1 = time.perf_counter() # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = t3_st_qcs zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) retrieved_jobs = jobs zne_fids = [] for job in retrieved_jobs: raw_results = job.result() mit_results = meas_fitter.filter.apply(raw_results) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) zne_rho = expvals_to_valid_rho(num_qubits, zne_expvals) zne_fid = state_fidelity(zne_rho, target_state) zne_fids.append(zne_fid) zne_fid_list.append(np.mean(zne_fids)) zne_stddev_list.append(np.std(zne_fids)) t2 = time.perf_counter() print('zne pt state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(zne_fids), np.std(zne_fids))) print("time:", t2 - t1) print() with open("e2d1_zne_pt.pkl", "wb") as f: pickle.dump({"num_steps_list": num_steps_list, "fid": zne_fid_list, "stddev": zne_stddev_list}, f) import qiskit.tools.jupyter %qiskit_version_table plt.plot(num_steps_list, zne_fid_list)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../../solutions/utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('2t/n') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 4 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] qc = QuantumCircuit(3) subspace_decoder(qc, targets=[0, 1, 2]) qc.draw("mpl") # Initialize quantum circuit for 3 qubits # qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(3) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) qc.barrier() general_subspace_encoder(qc, targets=[0, 1, 2]) # encode qc.barrier() trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian qc.barrier() general_subspace_decoder(qc, targets=[0, 1, 2]) # decode qc = qc.bind_parameters({dt: target_time / num_steps}) qc.draw("mpl") # Initialize quantum circuit for 3 qubits # qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(3) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) qc.barrier() subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode qc.barrier() trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian qc.barrier() subspace_decoder(qc, targets=[0, 1, 2]) # decode qc = qc.bind_parameters({dt: target_time / num_steps}) qc.draw("mpl") dt = Parameter('2t/n') mdt = Parameter('-2t/n') qc = QuantumCircuit(2) qc.rx(dt, 0) qc.rz(dt, 1) qc.h(1) qc.cx(1, 0) qc.rz(mdt, 0) qc.rx(mdt, 1) qc.rz(dt, 1) qc.cx(1, 0) qc.h(1) qc.rz(dt, 0) qc.draw("mpl") dt = Parameter('2t/n') mdt = Parameter('-2t/n') qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) qc.rz(mdt, 0) qc.rx(mdt, 1) qc.rz(dt, 1) qc.cx(1, 0) qc.h(1) qc.rx(dt, 1) qc.draw("mpl") from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") print(str(backend)) from qiskit.visualization import plot_error_map device = provider.backend.ibmq_jakarta plot_error_map(device) from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.ignis.mitigation import complete_meas_cal # QREM num_qubits = 3 qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') meas_calibs[0].draw("mpl") meas_calibs[1].draw("mpl") meas_calibs[2].draw("mpl") meas_calibs[3].draw("mpl") meas_calibs[4].draw("mpl") meas_calibs[5].draw("mpl") meas_calibs[6].draw("mpl") meas_calibs[7].draw("mpl")
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../../solutions/utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('2t/n') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 4 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] qc = QuantumCircuit(3) subspace_decoder(qc, targets=[0, 1, 2]) qc.draw("mpl") # Initialize quantum circuit for 3 qubits # qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(3) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) qc.barrier() general_subspace_encoder(qc, targets=[0, 1, 2]) # encode qc.barrier() trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian qc.barrier() general_subspace_decoder(qc, targets=[0, 1, 2]) # decode qc = qc.bind_parameters({dt: target_time / num_steps}) qc.draw("mpl") # Initialize quantum circuit for 3 qubits # qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(3) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) qc.barrier() subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode qc.barrier() trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian qc.barrier() subspace_decoder(qc, targets=[0, 1, 2]) # decode qc = qc.bind_parameters({dt: target_time / num_steps}) qc.draw("mpl") dt = Parameter('2t/n') mdt = Parameter('-2t/n') qc = QuantumCircuit(2) qc.rx(dt, 0) qc.rz(dt, 1) qc.h(1) qc.cx(1, 0) qc.rz(mdt, 0) qc.rx(mdt, 1) qc.rz(dt, 1) qc.cx(1, 0) qc.h(1) qc.rz(dt, 0) qc.draw("mpl") dt = Parameter('2t/n') mdt = Parameter('-2t/n') qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) qc.rz(mdt, 0) qc.rx(mdt, 1) qc.rz(dt, 1) qc.cx(1, 0) qc.h(1) qc.rx(dt, 1) qc.draw("mpl") from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") print(str(backend)) from qiskit.visualization import plot_error_map device = provider.backend.ibmq_jakarta plot_error_map(device) from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.ignis.mitigation import complete_meas_cal # QREM num_qubits = 3 qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') meas_calibs[0].draw("mpl") meas_calibs[1].draw("mpl") meas_calibs[2].draw("mpl") meas_calibs[3].draw("mpl") meas_calibs[4].draw("mpl") meas_calibs[5].draw("mpl") meas_calibs[6].draw("mpl") meas_calibs[7].draw("mpl")
https://github.com/BOBO1997/osp_solutions
BOBO1997
filename = "job_ids_jakarta_100step_20220412_030333_.pkl" import pickle with open(filename, "rb") as f: print(pickle.load(f)) filename = "job_ids_jakarta_100step_20220413_012425_.pkl" with open(filename, "rb") as f: print(pickle.load(f))
https://github.com/BOBO1997/osp_solutions
BOBO1997
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # 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. import numpy as np from qiskit import compiler, BasicAer, QuantumRegister from qiskit.converters import circuit_to_dag from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller def convert_to_basis_gates(circuit): # unroll the circuit using the basis u1, u2, u3, cx, and id gates unroller = Unroller(basis=['u1', 'u2', 'u3', 'cx', 'id']) pm = PassManager(passes=[unroller]) qc = compiler.transpile(circuit, BasicAer.get_backend('qasm_simulator'), pass_manager=pm) return qc def is_qubit(qb): # check if the input is a qubit, which is in the form (QuantumRegister, int) return isinstance(qb, tuple) and isinstance(qb[0], QuantumRegister) and isinstance(qb[1], int) def is_qubit_list(qbs): # check if the input is a list of qubits for qb in qbs: if not is_qubit(qb): return False return True def summarize_circuits(circuits): """Summarize circuits based on QuantumCircuit, and four metrics are summarized. Number of qubits and classical bits, and number of operations and depth of circuits. The average statistic is provided if multiple circuits are inputed. Args: circuits (QuantumCircuit or [QuantumCircuit]): the to-be-summarized circuits """ if not isinstance(circuits, list): circuits = [circuits] ret = "" ret += "Submitting {} circuits.\n".format(len(circuits)) ret += "============================================================================\n" stats = np.zeros(4) for i, circuit in enumerate(circuits): dag = circuit_to_dag(circuit) depth = dag.depth() width = dag.width() size = dag.size() classical_bits = dag.num_cbits() op_counts = dag.count_ops() stats[0] += width stats[1] += classical_bits stats[2] += size stats[3] += depth ret = ''.join([ret, "{}-th circuit: {} qubits, {} classical bits and {} operations with depth {}\n op_counts: {}\n".format( i, width, classical_bits, size, depth, op_counts)]) if len(circuits) > 1: stats /= len(circuits) ret = ''.join([ret, "Average: {:.2f} qubits, {:.2f} classical bits and {:.2f} operations with depth {:.2f}\n".format( stats[0], stats[1], stats[2], stats[3])]) ret += "============================================================================\n" return ret
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="lq") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = t3_st_qcs # CHANGED!!!! print("created zne_qcs (length:", len(zne_qcs), ")") t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[4].draw("mpl") from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") # QREM shots = 1 << 13 qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) jobs.append(job) dt_now = datetime.datetime.now() print(dt_now) import pickle with open("jobs_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in jobs: mit_results = meas_fitter.filter.apply(job.result()) rho = State fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="lq") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors=scale_factors) print("created zne_qcs (length:", len(zne_qcs), ")") t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 1 << 13 reps = 1 # unused # Number of trotter steps print("trotter step: ", num_steps) # execute: reps = 1 job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results) target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) print(fidelity)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="lq") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors) print("created zne_qcs (length:", len(zne_qcs), ")") t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) jobs.append(job) # QREM shots = 1 << 13 qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="lq") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs) print("created zne_qcs (length:", len(zne_qcs), ")") t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[32].draw("mpl") from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") # QREM shots = 1 << 13 qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) jobs.append(job) # 1回目: 2022-04-12 17:27:43.880500 # 2回目: 2022-04-13 01:19:40.602655 dt_now = datetime.datetime.now() print(dt_now) import pickle with open("jobs_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/BOBO1997/osp_solutions
BOBO1997
import re import itertools import numpy as np import random random.seed(42) import mitiq from qiskit import QuantumCircuit, QuantumRegister from qiskit.ignis.mitigation import expectation_value # Pauli Twirling def pauli_twirling(circ: QuantumCircuit) -> QuantumCircuit: """ [internal function] This function takes a quantum circuit and return a new quantum circuit with Pauli Twirling around the CNOT gates. Args: circ: QuantumCircuit Returns: QuantumCircuit """ def apply_pauli(num: int, qb: int) -> str: if (num == 0): return f'' elif (num == 1): return f'x q[{qb}];\n' elif (num == 2): return f'y q[{qb}];\n' else: return f'z q[{qb}];\n' paulis = [(i,j) for i in range(0,4) for j in range(0,4)] paulis.remove((0,0)) paulis_map = [(0, 1), (3, 2), (3, 3), (1, 1), (1, 0), (2, 3), (2, 2), (2, 1), (2, 0), (1, 3), (1, 2), (3, 0), (3, 1), (0, 2), (0, 3)] new_circ = '' ops = circ.qasm().splitlines(True) #! split the quantum circuit into qasm operators for op in ops: if (op[:2] == 'cx'): # add Pauli Twirling around the CNOT gate num = random.randrange(len(paulis)) qbs = re.findall('q\[(.)\]', op) new_circ += apply_pauli(paulis[num][0], qbs[0]) new_circ += apply_pauli(paulis[num][1], qbs[1]) new_circ += op new_circ += apply_pauli(paulis_map[num][0], qbs[0]) new_circ += apply_pauli(paulis_map[num][1], qbs[1]) else: new_circ += op return QuantumCircuit.from_qasm_str(new_circ) def zne_wrapper(qcs, scale_factors = [1.0, 2.0, 3.0], pt = False): """ This function outputs the circuit list for zero-noise extrapolation. Args: qcs: List[QuantumCircuit], the input quantum circuits. scale_factors: List[float], to what extent the noise scales are investigated. pt: bool, whether add Pauli Twirling or not. Returns: folded_qcs: List[QuantumCircuit] """ folded_qcs = [] #! ZNE用の回路 for qc in qcs: folded_qcs.append([mitiq.zne.scaling.fold_gates_at_random(qc, scale) for scale in scale_factors]) #! ここでmitiqを使用 folded_qcs = list(itertools.chain(*folded_qcs)) #! folded_qcsを平坦化 if pt: folded_qcs = [pauli_twirling(circ) for circ in folded_qcs] return folded_qcs def make_stf_basis(n, basis_elements = ["X","Y","Z"]): """ [internal function] This function outputs all the combinations of length n string for given basis_elements. When basis_elements is X, Y, and Z (default), the output becomes the n-qubit Pauli basis. Args: n: int basis_elements: List[str] Returns: basis: List[str] """ if n == 1: return basis_elements basis = [] for i in basis_elements: sub_basis = make_stf_basis(n - 1, basis_elements) basis += [i + j for j in sub_basis] return basis def reduce_hist(hist, poses): """ [internal function] This function returns the reduced histogram to the designated positions. Args: hist: Dict[str, float] poses: List[int] Returns: ret_hist: Dict[str, float] """ n = len(poses) ret_hist = {format(i, "0" + str(n) + "b"): 0 for i in range(1 << n)} for k, v in hist.items(): pos = "" for i in range(n): pos += k[poses[i]] ret_hist[pos] += v return ret_hist def make_stf_expvals(n, stf_hists): """ [internal function] This function create the expectations under expanded basis, which are used to reconstruct the density matrix. Args: n: int, the size of classical register in the measurement results. stf_hists: List[Dict[str, float]], the input State Tomography Fitter histograms. Returns: st_expvals: List[float], the output State Tomography expectation values. """ assert len(stf_hists) == 3 ** n stf_basis = make_stf_basis(n, basis_elements=["X","Y","Z"]) st_basis = make_stf_basis(n, basis_elements=["I","X","Y","Z"]) stf_hists_dict = {basis: hist for basis, hist in zip(stf_basis, stf_hists)} st_hists_dict = {basis: stf_hists_dict.get(basis, None) for basis in st_basis} # remaining for basis in sorted(set(st_basis) - set(stf_basis)): if basis == "I" * n: continue reduction_poses = [] reduction_basis = "" for i, b in enumerate(basis): if b != "I": reduction_poses.append(n - 1 - i) # big endian reduction_basis += b # こっちはそのまま(なぜならラベルはlittle endianだから) else: reduction_basis += "Z" st_hists_dict[basis] = reduce_hist(stf_hists_dict[reduction_basis], reduction_poses) st_expvals = dict() for basis, hist in st_hists_dict.items(): if basis == "I" * n: st_expvals[basis] = 1.0 continue st_expvals[basis], _ = expectation_value(hist) return st_expvals def zne_decoder(n, result, scale_factors=[1.0, 2.0, 3.0], fac_type="lin"): """ This function applies the zero-noise extrapolation to the measured results and output the mitigated zero-noise expectation values. Args: n: int, the size of classical register in the measurement results. result: Result, the returned results from job. scale_factors: List[float], this should be the same as the zne_wrapper. fac_type: str, "lin" or "exp", whether to use LinFactory option or ExpFactory option in mitiq, to extrapolate the expectation values. Returns: zne_expvals: List[float], the mitigated zero-noise expectation values. """ hists = result.get_counts() num_scale_factors = len(scale_factors) assert len(hists) % num_scale_factors == 0 scale_wise_expvals = [] # num_scale_factors * 64 for i in range(num_scale_factors): scale_wise_hists = [hists[3 * j + i] for j in range(len(hists) // num_scale_factors)] st_expvals = make_stf_expvals(n, scale_wise_hists) scale_wise_expvals.append( list(st_expvals.values()) ) scale_wise_expvals = np.array(scale_wise_expvals) linfac = mitiq.zne.inference.LinearFactory(scale_factors) expfac = mitiq.zne.ExpFactory(scale_factors) zne_expvals = [] for i in range(4 ** n): if fac_type == "lin": zne_expvals.append( linfac.extrapolate(scale_factors, scale_wise_expvals[:, i]) ) else: zne_expvals.append( expfac.extrapolate(scale_factors, scale_wise_expvals[:, i]) ) return zne_expvals
https://github.com/BOBO1997/osp_solutions
BOBO1997
filename = "job_ids_jakarta_100step_20220412_030333_.pkl" import pickle with open(filename, "rb") as f: print(pickle.load(f)) filename = "job_ids_jakarta_100step_20220413_012425_.pkl" with open(filename, "rb") as f: print(pickle.load(f))
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="lq") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = t3_st_qcs # CHANGED!!!! print("created zne_qcs (length:", len(zne_qcs), ")") t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[4].draw("mpl") from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") # QREM shots = 1 << 13 qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) jobs.append(job) dt_now = datetime.datetime.now() print(dt_now) import pickle with open("jobs_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in jobs: mit_results = meas_fitter.filter.apply(job.result()) rho = State fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="lq") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors=scale_factors) print("created zne_qcs (length:", len(zne_qcs), ")") t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 1 << 13 reps = 1 # unused # Number of trotter steps print("trotter step: ", num_steps) # execute: reps = 1 job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results) target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) print(fidelity)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="lq") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors) print("created zne_qcs (length:", len(zne_qcs), ")") t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) jobs.append(job) # QREM shots = 1 << 13 qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="lq") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs) print("created zne_qcs (length:", len(zne_qcs), ")") t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[32].draw("mpl") from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") # QREM shots = 1 << 13 qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) jobs.append(job) # 1回目: 2022-04-12 17:27:43.880500 # 2回目: 2022-04-13 01:19:40.602655 dt_now = datetime.datetime.now() print(dt_now) import pickle with open("jobs_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/BOBO1997/osp_solutions
BOBO1997
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # 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. import numpy as np from qiskit import compiler, BasicAer, QuantumRegister from qiskit.converters import circuit_to_dag from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller def convert_to_basis_gates(circuit): # unroll the circuit using the basis u1, u2, u3, cx, and id gates unroller = Unroller(basis=['u1', 'u2', 'u3', 'cx', 'id']) pm = PassManager(passes=[unroller]) qc = compiler.transpile(circuit, BasicAer.get_backend('qasm_simulator'), pass_manager=pm) return qc def is_qubit(qb): # check if the input is a qubit, which is in the form (QuantumRegister, int) return isinstance(qb, tuple) and isinstance(qb[0], QuantumRegister) and isinstance(qb[1], int) def is_qubit_list(qbs): # check if the input is a list of qubits for qb in qbs: if not is_qubit(qb): return False return True def summarize_circuits(circuits): """Summarize circuits based on QuantumCircuit, and four metrics are summarized. Number of qubits and classical bits, and number of operations and depth of circuits. The average statistic is provided if multiple circuits are inputed. Args: circuits (QuantumCircuit or [QuantumCircuit]): the to-be-summarized circuits """ if not isinstance(circuits, list): circuits = [circuits] ret = "" ret += "Submitting {} circuits.\n".format(len(circuits)) ret += "============================================================================\n" stats = np.zeros(4) for i, circuit in enumerate(circuits): dag = circuit_to_dag(circuit) depth = dag.depth() width = dag.width() size = dag.size() classical_bits = dag.num_cbits() op_counts = dag.count_ops() stats[0] += width stats[1] += classical_bits stats[2] += size stats[3] += depth ret = ''.join([ret, "{}-th circuit: {} qubits, {} classical bits and {} operations with depth {}\n op_counts: {}\n".format( i, width, classical_bits, size, depth, op_counts)]) if len(circuits) > 1: stats /= len(circuits) ret = ''.join([ret, "Average: {:.2f} qubits, {:.2f} classical bits and {:.2f} operations with depth {:.2f}\n".format( stats[0], stats[1], stats[2], stats[3])]) ret += "============================================================================\n" return ret
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0, 4.0, 5.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0,1,2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time t1 = time.perf_counter() qc = qc.bind_parameters({dt: target_time / num_steps}) t2 = time.perf_counter() print("created qc,", t2 - t1, "s") # Generate state tomography circuits to evaluate fidelity of simulation t1 = time.perf_counter() st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === t2 = time.perf_counter() print("created st_qcs (length:", len(st_qcs), "),", t2 - t1, "s") # remove barriers t1 = time.perf_counter() st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] t2 = time.perf_counter() print("removed barriers from st_qcs,", t2 - t1, "s") # optimize circuit t1 = time.perf_counter() t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("created t3_st_qcs (length:", len(t3_st_qcs), "),", t2 - t1, "s") t3_st_qcs[0].draw("mpl") # zne wrapping t1 = time.perf_counter() zne_qcs = zne_wrapper(t3_st_qcs, scale_factors=scale_factors) t2 = time.perf_counter() print("created zne_qcs (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("decomposed zne_qcs into basis gates (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(zne_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("optimized zne_qcs -> create t3_zne_qcs (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(t3_zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) t2 = time.perf_counter() print("fit the t3_zne_qcs to the initial layoit (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 1 << 13 reps = 1 # unused # Number of trotter steps print("trotter step: ", num_steps) # execute: reps = 1 job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors=scale_factors) target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) print(fidelity)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0,1,2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time t1 = time.perf_counter() qc = qc.bind_parameters({dt: target_time / num_steps}) t2 = time.perf_counter() print("created qc,", t2 - t1, "s") # Generate state tomography circuits to evaluate fidelity of simulation t1 = time.perf_counter() st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === t2 = time.perf_counter() print("created st_qcs (length:", len(st_qcs), "),", t2 - t1, "s") # remove barriers t1 = time.perf_counter() st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] t2 = time.perf_counter() print("removed barriers from st_qcs,", t2 - t1, "s") # optimize circuit t1 = time.perf_counter() t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("created t3_st_qcs (length:", len(t3_st_qcs), "),", t2 - t1, "s") t3_st_qcs[0].draw("mpl") # zne wrapping t1 = time.perf_counter() zne_qcs = zne_wrapper(t3_st_qcs) t2 = time.perf_counter() print("created zne_qcs (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("decomposed zne_qcs into basis gates (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(zne_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("optimized zne_qcs -> create t3_zne_qcs (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(t3_zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) t2 = time.perf_counter() print("fit the t3_zne_qcs to the initial layoit (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 1 << 13 reps = 1 # unused # Number of trotter steps print("trotter step: ", num_steps) # execute: reps = 1 job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results) target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) print(fidelity)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0,1,2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time t1 = time.perf_counter() qc = qc.bind_parameters({dt: target_time / num_steps}) t2 = time.perf_counter() print("created qc,", t2 - t1, "s") # Generate state tomography circuits to evaluate fidelity of simulation t1 = time.perf_counter() st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === t2 = time.perf_counter() print("created st_qcs (length:", len(st_qcs), "),", t2 - t1, "s") # remove barriers t1 = time.perf_counter() st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] t2 = time.perf_counter() print("removed barriers from st_qcs,", t2 - t1, "s") # optimize circuit t1 = time.perf_counter() t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("created t3_st_qcs (length:", len(t3_st_qcs), "),", t2 - t1, "s") t3_st_qcs[0].draw("mpl") # zne wrapping t1 = time.perf_counter() zne_qcs = zne_wrapper(t3_st_qcs) t2 = time.perf_counter() print("created zne_qcs (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("decomposed zne_qcs into basis gates (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(zne_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("optimized zne_qcs -> create t3_zne_qcs (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(t3_zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) t2 = time.perf_counter() print("fit the t3_zne_qcs to the initial layoit (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") # QREM shots = 1 << 13 qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): job = execute(t3_zne_qcs, backend, shots=shots, optimization_level = 0) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) jobs.append(job) dt_now = datetime.datetime.now() print(dt_now) import pickle with open("jobs_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results) target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) print(fidelity)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import re import itertools import numpy as np import random random.seed(42) import mitiq from qiskit import QuantumCircuit, QuantumRegister from qiskit.ignis.mitigation import expectation_value # Pauli Twirling def pauli_twirling(circ: QuantumCircuit) -> QuantumCircuit: """ [internal function] This function takes a quantum circuit and return a new quantum circuit with Pauli Twirling around the CNOT gates. Args: circ: QuantumCircuit Returns: QuantumCircuit """ def apply_pauli(num: int, qb: int) -> str: if (num == 0): return f'' elif (num == 1): return f'x q[{qb}];\n' elif (num == 2): return f'y q[{qb}];\n' else: return f'z q[{qb}];\n' paulis = [(i,j) for i in range(0,4) for j in range(0,4)] paulis.remove((0,0)) paulis_map = [(0, 1), (3, 2), (3, 3), (1, 1), (1, 0), (2, 3), (2, 2), (2, 1), (2, 0), (1, 3), (1, 2), (3, 0), (3, 1), (0, 2), (0, 3)] new_circ = '' ops = circ.qasm().splitlines(True) #! split the quantum circuit into qasm operators for op in ops: if (op[:2] == 'cx'): # add Pauli Twirling around the CNOT gate num = random.randrange(len(paulis)) qbs = re.findall('q\[(.)\]', op) new_circ += apply_pauli(paulis[num][0], qbs[0]) new_circ += apply_pauli(paulis[num][1], qbs[1]) new_circ += op new_circ += apply_pauli(paulis_map[num][0], qbs[0]) new_circ += apply_pauli(paulis_map[num][1], qbs[1]) else: new_circ += op return QuantumCircuit.from_qasm_str(new_circ) def zne_wrapper(qcs, scale_factors = [1.0, 2.0, 3.0], pt = False): """ This function outputs the circuit list for zero-noise extrapolation. Args: qcs: List[QuantumCircuit], the input quantum circuits. scale_factors: List[float], to what extent the noise scales are investigated. pt: bool, whether add Pauli Twirling or not. Returns: folded_qcs: List[QuantumCircuit] """ folded_qcs = [] #! ZNE用の回路 for qc in qcs: folded_qcs.append([mitiq.zne.scaling.fold_gates_at_random(qc, scale) for scale in scale_factors]) #! ここでmitiqを使用 folded_qcs = list(itertools.chain(*folded_qcs)) #! folded_qcsを平坦化 if pt: folded_qcs = [pauli_twirling(circ) for circ in folded_qcs] return folded_qcs def make_stf_basis(n, basis_elements = ["X","Y","Z"]): """ [internal function] This function outputs all the combinations of length n string for given basis_elements. When basis_elements is X, Y, and Z (default), the output becomes the n-qubit Pauli basis. Args: n: int basis_elements: List[str] Returns: basis: List[str] """ if n == 1: return basis_elements basis = [] for i in basis_elements: sub_basis = make_stf_basis(n - 1, basis_elements) basis += [i + j for j in sub_basis] return basis def reduce_hist(hist, poses): """ [internal function] This function returns the reduced histogram to the designated positions. Args: hist: Dict[str, float] poses: List[int] Returns: ret_hist: Dict[str, float] """ n = len(poses) ret_hist = {format(i, "0" + str(n) + "b"): 0 for i in range(1 << n)} for k, v in hist.items(): pos = "" for i in range(n): pos += k[poses[i]] ret_hist[pos] += v return ret_hist def make_stf_expvals(n, stf_hists): """ [internal function] This function create the expectations under expanded basis, which are used to reconstruct the density matrix. Args: n: int, the size of classical register in the measurement results. stf_hists: List[Dict[str, float]], the input State Tomography Fitter histograms. Returns: st_expvals: List[float], the output State Tomography expectation values. """ assert len(stf_hists) == 3 ** n stf_basis = make_stf_basis(n, basis_elements=["X","Y","Z"]) st_basis = make_stf_basis(n, basis_elements=["I","X","Y","Z"]) stf_hists_dict = {basis: hist for basis, hist in zip(stf_basis, stf_hists)} st_hists_dict = {basis: stf_hists_dict.get(basis, None) for basis in st_basis} # remaining for basis in sorted(set(st_basis) - set(stf_basis)): if basis == "I" * n: continue reduction_poses = [] reduction_basis = "" for i, b in enumerate(basis): if b != "I": reduction_poses.append(n - 1 - i) # big endian reduction_basis += b # こっちはそのまま(なぜならラベルはlittle endianだから) else: reduction_basis += "Z" st_hists_dict[basis] = reduce_hist(stf_hists_dict[reduction_basis], reduction_poses) st_expvals = dict() for basis, hist in st_hists_dict.items(): if basis == "I" * n: st_expvals[basis] = 1.0 continue st_expvals[basis], _ = expectation_value(hist) return st_expvals def zne_decoder(n, result, scale_factors=[1.0, 2.0, 3.0], fac_type="lin"): """ This function applies the zero-noise extrapolation to the measured results and output the mitigated zero-noise expectation values. Args: n: int, the size of classical register in the measurement results. result: Result, the returned results from job. scale_factors: List[float], this should be the same as the zne_wrapper. fac_type: str, "lin" or "exp", whether to use LinFactory option or ExpFactory option in mitiq, to extrapolate the expectation values. Returns: zne_expvals: List[float], the mitigated zero-noise expectation values. """ hists = result.get_counts() num_scale_factors = len(scale_factors) assert len(hists) % num_scale_factors == 0 scale_wise_expvals = [] # num_scale_factors * 64 for i in range(num_scale_factors): scale_wise_hists = [hists[3 * j + i] for j in range(len(hists) // num_scale_factors)] st_expvals = make_stf_expvals(n, scale_wise_hists) scale_wise_expvals.append( list(st_expvals.values()) ) scale_wise_expvals = np.array(scale_wise_expvals) linfac = mitiq.zne.inference.LinearFactory(scale_factors) expfac = mitiq.zne.ExpFactory(scale_factors) zne_expvals = [] for i in range(4 ** n): if fac_type == "lin": zne_expvals.append( linfac.extrapolate(scale_factors, scale_wise_expvals[:, i]) ) else: zne_expvals.append( expfac.extrapolate(scale_factors, scale_wise_expvals[:, i]) ) return zne_expvals
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0, 4.0, 5.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0,1,2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time t1 = time.perf_counter() qc = qc.bind_parameters({dt: target_time / num_steps}) t2 = time.perf_counter() print("created qc,", t2 - t1, "s") # Generate state tomography circuits to evaluate fidelity of simulation t1 = time.perf_counter() st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === t2 = time.perf_counter() print("created st_qcs (length:", len(st_qcs), "),", t2 - t1, "s") # remove barriers t1 = time.perf_counter() st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] t2 = time.perf_counter() print("removed barriers from st_qcs,", t2 - t1, "s") # optimize circuit t1 = time.perf_counter() t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("created t3_st_qcs (length:", len(t3_st_qcs), "),", t2 - t1, "s") t3_st_qcs[0].draw("mpl") # zne wrapping t1 = time.perf_counter() zne_qcs = zne_wrapper(t3_st_qcs, scale_factors=scale_factors) t2 = time.perf_counter() print("created zne_qcs (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("decomposed zne_qcs into basis gates (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(zne_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("optimized zne_qcs -> create t3_zne_qcs (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(t3_zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) t2 = time.perf_counter() print("fit the t3_zne_qcs to the initial layoit (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 1 << 13 reps = 1 # unused # Number of trotter steps print("trotter step: ", num_steps) # execute: reps = 1 job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results) target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) print(fidelity)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0,1,2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time t1 = time.perf_counter() qc = qc.bind_parameters({dt: target_time / num_steps}) t2 = time.perf_counter() print("created qc,", t2 - t1, "s") # Generate state tomography circuits to evaluate fidelity of simulation t1 = time.perf_counter() st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === t2 = time.perf_counter() print("created st_qcs (length:", len(st_qcs), "),", t2 - t1, "s") # remove barriers t1 = time.perf_counter() st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] t2 = time.perf_counter() print("removed barriers from st_qcs,", t2 - t1, "s") # optimize circuit t1 = time.perf_counter() t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("created t3_st_qcs (length:", len(t3_st_qcs), "),", t2 - t1, "s") t3_st_qcs[0].draw("mpl") # zne wrapping t1 = time.perf_counter() zne_qcs = zne_wrapper(t3_st_qcs) t2 = time.perf_counter() print("created zne_qcs (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("decomposed zne_qcs into basis gates (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(zne_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("optimized zne_qcs -> create t3_zne_qcs (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(t3_zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) t2 = time.perf_counter() print("fit the t3_zne_qcs to the initial layoit (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 1 << 13 reps = 1 # unused # Number of trotter steps print("trotter step: ", num_steps) # execute: reps = 1 job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results) target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) print(fidelity)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0,1,2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time t1 = time.perf_counter() qc = qc.bind_parameters({dt: target_time / num_steps}) t2 = time.perf_counter() print("created qc,", t2 - t1, "s") # Generate state tomography circuits to evaluate fidelity of simulation t1 = time.perf_counter() st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === t2 = time.perf_counter() print("created st_qcs (length:", len(st_qcs), "),", t2 - t1, "s") # remove barriers t1 = time.perf_counter() st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] t2 = time.perf_counter() print("removed barriers from st_qcs,", t2 - t1, "s") # optimize circuit t1 = time.perf_counter() t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("created t3_st_qcs (length:", len(t3_st_qcs), "),", t2 - t1, "s") t3_st_qcs[0].draw("mpl") # zne wrapping t1 = time.perf_counter() zne_qcs = zne_wrapper(t3_st_qcs) t2 = time.perf_counter() print("created zne_qcs (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("decomposed zne_qcs into basis gates (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(zne_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("optimized zne_qcs -> create t3_zne_qcs (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(t3_zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) t2 = time.perf_counter() print("fit the t3_zne_qcs to the initial layoit (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") # QREM shots = 1 << 13 qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): job = execute(t3_zne_qcs, backend, shots=shots, optimization_level = 0) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) jobs.append(job) dt_now = datetime.datetime.now() print(dt_now) import pickle with open("jobs_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results) target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) print(fidelity)
https://github.com/BOBO1997/osp_solutions
BOBO1997
filename = "job_ids_jakarta_100step_20220412_030333_.pkl" import pickle with open(filename, "rb") as f: print(pickle.load(f)) filename = "job_ids_jakarta_100step_20220413_012425_.pkl" with open(filename, "rb") as f: print(pickle.load(f))
https://github.com/BOBO1997/osp_solutions
BOBO1997
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # 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. import numpy as np from qiskit import compiler, BasicAer, QuantumRegister from qiskit.converters import circuit_to_dag from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller def convert_to_basis_gates(circuit): # unroll the circuit using the basis u1, u2, u3, cx, and id gates unroller = Unroller(basis=['u1', 'u2', 'u3', 'cx', 'id']) pm = PassManager(passes=[unroller]) qc = compiler.transpile(circuit, BasicAer.get_backend('qasm_simulator'), pass_manager=pm) return qc def is_qubit(qb): # check if the input is a qubit, which is in the form (QuantumRegister, int) return isinstance(qb, tuple) and isinstance(qb[0], QuantumRegister) and isinstance(qb[1], int) def is_qubit_list(qbs): # check if the input is a list of qubits for qb in qbs: if not is_qubit(qb): return False return True def summarize_circuits(circuits): """Summarize circuits based on QuantumCircuit, and four metrics are summarized. Number of qubits and classical bits, and number of operations and depth of circuits. The average statistic is provided if multiple circuits are inputed. Args: circuits (QuantumCircuit or [QuantumCircuit]): the to-be-summarized circuits """ if not isinstance(circuits, list): circuits = [circuits] ret = "" ret += "Submitting {} circuits.\n".format(len(circuits)) ret += "============================================================================\n" stats = np.zeros(4) for i, circuit in enumerate(circuits): dag = circuit_to_dag(circuit) depth = dag.depth() width = dag.width() size = dag.size() classical_bits = dag.num_cbits() op_counts = dag.count_ops() stats[0] += width stats[1] += classical_bits stats[2] += size stats[3] += depth ret = ''.join([ret, "{}-th circuit: {} qubits, {} classical bits and {} operations with depth {}\n op_counts: {}\n".format( i, width, classical_bits, size, depth, op_counts)]) if len(circuits) > 1: stats /= len(circuits) ret = ''.join([ret, "Average: {:.2f} qubits, {:.2f} classical bits and {:.2f} operations with depth {:.2f}\n".format( stats[0], stats[1], stats[2], stats[3])]) ret += "============================================================================\n" return ret
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0, 4.0, 5.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0,1,2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time t1 = time.perf_counter() qc = qc.bind_parameters({dt: target_time / num_steps}) t2 = time.perf_counter() print("created qc,", t2 - t1, "s") # Generate state tomography circuits to evaluate fidelity of simulation t1 = time.perf_counter() st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === t2 = time.perf_counter() print("created st_qcs (length:", len(st_qcs), "),", t2 - t1, "s") # remove barriers t1 = time.perf_counter() st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] t2 = time.perf_counter() print("removed barriers from st_qcs,", t2 - t1, "s") # optimize circuit t1 = time.perf_counter() t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("created t3_st_qcs (length:", len(t3_st_qcs), "),", t2 - t1, "s") t3_st_qcs[0].draw("mpl") # zne wrapping t1 = time.perf_counter() zne_qcs = zne_wrapper(t3_st_qcs, scale_factors=scale_factors) t2 = time.perf_counter() print("created zne_qcs (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("decomposed zne_qcs into basis gates (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(zne_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("optimized zne_qcs -> create t3_zne_qcs (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(t3_zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) t2 = time.perf_counter() print("fit the t3_zne_qcs to the initial layoit (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 1 << 13 reps = 1 # unused # Number of trotter steps print("trotter step: ", num_steps) # execute: reps = 1 job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors=scale_factors) target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) print(fidelity)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0,1,2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time t1 = time.perf_counter() qc = qc.bind_parameters({dt: target_time / num_steps}) t2 = time.perf_counter() print("created qc,", t2 - t1, "s") # Generate state tomography circuits to evaluate fidelity of simulation t1 = time.perf_counter() st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === t2 = time.perf_counter() print("created st_qcs (length:", len(st_qcs), "),", t2 - t1, "s") # remove barriers t1 = time.perf_counter() st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] t2 = time.perf_counter() print("removed barriers from st_qcs,", t2 - t1, "s") # optimize circuit t1 = time.perf_counter() t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("created t3_st_qcs (length:", len(t3_st_qcs), "),", t2 - t1, "s") t3_st_qcs[0].draw("mpl") # zne wrapping t1 = time.perf_counter() zne_qcs = zne_wrapper(t3_st_qcs) t2 = time.perf_counter() print("created zne_qcs (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("decomposed zne_qcs into basis gates (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(zne_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("optimized zne_qcs -> create t3_zne_qcs (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(t3_zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) t2 = time.perf_counter() print("fit the t3_zne_qcs to the initial layoit (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 1 << 13 reps = 1 # unused # Number of trotter steps print("trotter step: ", num_steps) # execute: reps = 1 job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results) target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) print(fidelity)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0,1,2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time t1 = time.perf_counter() qc = qc.bind_parameters({dt: target_time / num_steps}) t2 = time.perf_counter() print("created qc,", t2 - t1, "s") # Generate state tomography circuits to evaluate fidelity of simulation t1 = time.perf_counter() st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === t2 = time.perf_counter() print("created st_qcs (length:", len(st_qcs), "),", t2 - t1, "s") # remove barriers t1 = time.perf_counter() st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] t2 = time.perf_counter() print("removed barriers from st_qcs,", t2 - t1, "s") # optimize circuit t1 = time.perf_counter() t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("created t3_st_qcs (length:", len(t3_st_qcs), "),", t2 - t1, "s") t3_st_qcs[0].draw("mpl") # zne wrapping t1 = time.perf_counter() zne_qcs = zne_wrapper(t3_st_qcs) t2 = time.perf_counter() print("created zne_qcs (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("decomposed zne_qcs into basis gates (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(zne_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("optimized zne_qcs -> create t3_zne_qcs (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(t3_zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) t2 = time.perf_counter() print("fit the t3_zne_qcs to the initial layoit (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") # QREM shots = 1 << 13 qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): job = execute(t3_zne_qcs, backend, shots=shots, optimization_level = 0) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) jobs.append(job) dt_now = datetime.datetime.now() print(dt_now) import pickle with open("jobs_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results) target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) print(fidelity)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import re import itertools import numpy as np import random random.seed(42) import mitiq from qiskit import QuantumCircuit, QuantumRegister from qiskit.ignis.mitigation import expectation_value # Pauli Twirling def pauli_twirling(circ: QuantumCircuit) -> QuantumCircuit: """ [internal function] This function takes a quantum circuit and return a new quantum circuit with Pauli Twirling around the CNOT gates. Args: circ: QuantumCircuit Returns: QuantumCircuit """ def apply_pauli(num: int, qb: int) -> str: if (num == 0): return f'' elif (num == 1): return f'x q[{qb}];\n' elif (num == 2): return f'y q[{qb}];\n' else: return f'z q[{qb}];\n' paulis = [(i,j) for i in range(0,4) for j in range(0,4)] paulis.remove((0,0)) paulis_map = [(0, 1), (3, 2), (3, 3), (1, 1), (1, 0), (2, 3), (2, 2), (2, 1), (2, 0), (1, 3), (1, 2), (3, 0), (3, 1), (0, 2), (0, 3)] new_circ = '' ops = circ.qasm().splitlines(True) #! split the quantum circuit into qasm operators for op in ops: if (op[:2] == 'cx'): # add Pauli Twirling around the CNOT gate num = random.randrange(len(paulis)) qbs = re.findall('q\[(.)\]', op) new_circ += apply_pauli(paulis[num][0], qbs[0]) new_circ += apply_pauli(paulis[num][1], qbs[1]) new_circ += op new_circ += apply_pauli(paulis_map[num][0], qbs[0]) new_circ += apply_pauli(paulis_map[num][1], qbs[1]) else: new_circ += op return QuantumCircuit.from_qasm_str(new_circ) def zne_wrapper(qcs, scale_factors = [1.0, 2.0, 3.0], pt = False): """ This function outputs the circuit list for zero-noise extrapolation. Args: qcs: List[QuantumCircuit], the input quantum circuits. scale_factors: List[float], to what extent the noise scales are investigated. pt: bool, whether add Pauli Twirling or not. Returns: folded_qcs: List[QuantumCircuit] """ folded_qcs = [] #! ZNE用の回路 for qc in qcs: folded_qcs.append([mitiq.zne.scaling.fold_gates_at_random(qc, scale) for scale in scale_factors]) #! ここでmitiqを使用 folded_qcs = list(itertools.chain(*folded_qcs)) #! folded_qcsを平坦化 if pt: folded_qcs = [pauli_twirling(circ) for circ in folded_qcs] return folded_qcs def make_stf_basis(n, basis_elements = ["X","Y","Z"]): """ [internal function] This function outputs all the combinations of length n string for given basis_elements. When basis_elements is X, Y, and Z (default), the output becomes the n-qubit Pauli basis. Args: n: int basis_elements: List[str] Returns: basis: List[str] """ if n == 1: return basis_elements basis = [] for i in basis_elements: sub_basis = make_stf_basis(n - 1, basis_elements) basis += [i + j for j in sub_basis] return basis def reduce_hist(hist, poses): """ [internal function] This function returns the reduced histogram to the designated positions. Args: hist: Dict[str, float] poses: List[int] Returns: ret_hist: Dict[str, float] """ n = len(poses) ret_hist = {format(i, "0" + str(n) + "b"): 0 for i in range(1 << n)} for k, v in hist.items(): pos = "" for i in range(n): pos += k[poses[i]] ret_hist[pos] += v return ret_hist def make_stf_expvals(n, stf_hists): """ [internal function] This function create the expectations under expanded basis, which are used to reconstruct the density matrix. Args: n: int, the size of classical register in the measurement results. stf_hists: List[Dict[str, float]], the input State Tomography Fitter histograms. Returns: st_expvals: List[float], the output State Tomography expectation values. """ assert len(stf_hists) == 3 ** n stf_basis = make_stf_basis(n, basis_elements=["X","Y","Z"]) st_basis = make_stf_basis(n, basis_elements=["I","X","Y","Z"]) stf_hists_dict = {basis: hist for basis, hist in zip(stf_basis, stf_hists)} st_hists_dict = {basis: stf_hists_dict.get(basis, None) for basis in st_basis} # remaining for basis in sorted(set(st_basis) - set(stf_basis)): if basis == "I" * n: continue reduction_poses = [] reduction_basis = "" for i, b in enumerate(basis): if b != "I": reduction_poses.append(n - 1 - i) # big endian reduction_basis += b # こっちはそのまま(なぜならラベルはlittle endianだから) else: reduction_basis += "Z" st_hists_dict[basis] = reduce_hist(stf_hists_dict[reduction_basis], reduction_poses) st_expvals = dict() for basis, hist in st_hists_dict.items(): if basis == "I" * n: st_expvals[basis] = 1.0 continue st_expvals[basis], _ = expectation_value(hist) return st_expvals def zne_decoder(n, result, scale_factors=[1.0, 2.0, 3.0], fac_type="lin"): """ This function applies the zero-noise extrapolation to the measured results and output the mitigated zero-noise expectation values. Args: n: int, the size of classical register in the measurement results. result: Result, the returned results from job. scale_factors: List[float], this should be the same as the zne_wrapper. fac_type: str, "lin" or "exp", whether to use LinFactory option or ExpFactory option in mitiq, to extrapolate the expectation values. Returns: zne_expvals: List[float], the mitigated zero-noise expectation values. """ hists = result.get_counts() num_scale_factors = len(scale_factors) assert len(hists) % num_scale_factors == 0 scale_wise_expvals = [] # num_scale_factors * 64 for i in range(num_scale_factors): scale_wise_hists = [hists[3 * j + i] for j in range(len(hists) // num_scale_factors)] st_expvals = make_stf_expvals(n, scale_wise_hists) scale_wise_expvals.append( list(st_expvals.values()) ) scale_wise_expvals = np.array(scale_wise_expvals) linfac = mitiq.zne.inference.LinearFactory(scale_factors) expfac = mitiq.zne.ExpFactory(scale_factors) zne_expvals = [] for i in range(4 ** n): if fac_type == "lin": zne_expvals.append( linfac.extrapolate(scale_factors, scale_wise_expvals[:, i]) ) else: zne_expvals.append( expfac.extrapolate(scale_factors, scale_wise_expvals[:, i]) ) return zne_expvals
https://github.com/BOBO1997/osp_solutions
BOBO1997
filename = "job_ids_jakarta_100step_20220412_030333_.pkl" import pickle with open(filename, "rb") as f: print(pickle.load(f)) filename = "job_ids_jakarta_100step_20220413_012425_.pkl" with open(filename, "rb") as f: print(pickle.load(f))
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0, 4.0, 5.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0,1,2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time t1 = time.perf_counter() qc = qc.bind_parameters({dt: target_time / num_steps}) t2 = time.perf_counter() print("created qc,", t2 - t1, "s") # Generate state tomography circuits to evaluate fidelity of simulation t1 = time.perf_counter() st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === t2 = time.perf_counter() print("created st_qcs (length:", len(st_qcs), "),", t2 - t1, "s") # remove barriers t1 = time.perf_counter() st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] t2 = time.perf_counter() print("removed barriers from st_qcs,", t2 - t1, "s") # optimize circuit t1 = time.perf_counter() t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("created t3_st_qcs (length:", len(t3_st_qcs), "),", t2 - t1, "s") t3_st_qcs[0].draw("mpl") # zne wrapping t1 = time.perf_counter() zne_qcs = zne_wrapper(t3_st_qcs, scale_factors=scale_factors) t2 = time.perf_counter() print("created zne_qcs (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("decomposed zne_qcs into basis gates (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(zne_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("optimized zne_qcs -> create t3_zne_qcs (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(t3_zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) t2 = time.perf_counter() print("fit the t3_zne_qcs to the initial layoit (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 1 << 13 reps = 1 # unused # Number of trotter steps print("trotter step: ", num_steps) # execute: reps = 1 job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results) target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) print(fidelity)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0,1,2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time t1 = time.perf_counter() qc = qc.bind_parameters({dt: target_time / num_steps}) t2 = time.perf_counter() print("created qc,", t2 - t1, "s") # Generate state tomography circuits to evaluate fidelity of simulation t1 = time.perf_counter() st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === t2 = time.perf_counter() print("created st_qcs (length:", len(st_qcs), "),", t2 - t1, "s") # remove barriers t1 = time.perf_counter() st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] t2 = time.perf_counter() print("removed barriers from st_qcs,", t2 - t1, "s") # optimize circuit t1 = time.perf_counter() t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("created t3_st_qcs (length:", len(t3_st_qcs), "),", t2 - t1, "s") t3_st_qcs[0].draw("mpl") # zne wrapping t1 = time.perf_counter() zne_qcs = zne_wrapper(t3_st_qcs) t2 = time.perf_counter() print("created zne_qcs (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("decomposed zne_qcs into basis gates (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(zne_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("optimized zne_qcs -> create t3_zne_qcs (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(t3_zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) t2 = time.perf_counter() print("fit the t3_zne_qcs to the initial layoit (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 1 << 13 reps = 1 # unused # Number of trotter steps print("trotter step: ", num_steps) # execute: reps = 1 job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results) target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) print(fidelity)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("./") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder(qc, targets=[0,1,2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time t1 = time.perf_counter() qc = qc.bind_parameters({dt: target_time / num_steps}) t2 = time.perf_counter() print("created qc,", t2 - t1, "s") # Generate state tomography circuits to evaluate fidelity of simulation t1 = time.perf_counter() st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === t2 = time.perf_counter() print("created st_qcs (length:", len(st_qcs), "),", t2 - t1, "s") # remove barriers t1 = time.perf_counter() st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] t2 = time.perf_counter() print("removed barriers from st_qcs,", t2 - t1, "s") # optimize circuit t1 = time.perf_counter() t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("created t3_st_qcs (length:", len(t3_st_qcs), "),", t2 - t1, "s") t3_st_qcs[0].draw("mpl") # zne wrapping t1 = time.perf_counter() zne_qcs = zne_wrapper(t3_st_qcs) t2 = time.perf_counter() print("created zne_qcs (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("decomposed zne_qcs into basis gates (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(zne_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("optimized zne_qcs -> create t3_zne_qcs (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(t3_zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) t2 = time.perf_counter() print("fit the t3_zne_qcs to the initial layoit (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") # QREM shots = 1 << 13 qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): job = execute(t3_zne_qcs, backend, shots=shots, optimization_level = 0) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) jobs.append(job) dt_now = datetime.datetime.now() print(dt_now) import pickle with open("jobs_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results) target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) print(fidelity)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") # from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open(filename, "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) filename = "job_ids_ibmq_jakarta_100step_20220413_030821_.pkl" # change here with open(filename, "rb") as f: job_ids_dict = pickle.load(f) job_ids = job_ids_dict["job_ids"] cal_job_id = job_ids_dict["cal_job_id"] retrieved_jobs = [] for job_id in job_ids: retrieved_jobs.append(backend.retrieve_job(job_id)) retrieved_cal_job = backend.retrieve_job(cal_job_id) cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") # from qiskit.test.mock import FakeJakarta # backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) with open(filename, "wb") as f: pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) filename = "job_ids_ibmq_jakarta_100step_20220413_030821_.pkl" # change here with open(filename, "rb") as f: job_ids_dict = pickle.load(f) job_ids = job_ids_dict["job_ids"] cal_job_id = job_ids_dict["cal_job_id"] retrieved_jobs = [] for job_id in job_ids: retrieved_jobs.append(backend.retrieve_job(job_id)) retrieved_cal_job = backend.retrieve_job(cal_job_id) cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/BOBO1997/osp_solutions
BOBO1997
import sys, time sys.path.append("../") import Qconfig qx_config = { "APItoken": Qconfig.APItoken, "url": Qconfig.config['url']} print('Qconfig loaded from %s.' % Qconfig.__file__) # Imports import qiskit as qk from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import available_backends, execute, register, least_busy from qiskit.tools.visualization import plot_histogram from qiskit import IBMQ from qiskit import Aer from math import pi print(qk.__version__) qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr,cr) # circuit construction # preparing the wavefunction qc.h(qr[0]) qc.barrier() qc.cx(qr[0], qr[1]) qc.barrier() qc.u3(1.2309,0,0,qr[0]) qc.barrier() # if we apply phase shift gate qc.u1((2.0/3)*pi,qr[0]) qc.u1((2.0/3)*pi,qr[1]) qc.barrier() # rotating the axis for measurement #qc.cx(qr[0],qr[1]) # THE IMPLEMENTATION PROVIDED BY THE AUTHORS SKIPS THIS CNOT APPLICATION!!! it shouldn't be # it shouldn't be there. Improves accuracy #qc.barrier() qc.u3(2.1862,6.5449,pi,qr[0]) qc.u3(0.9553,2*pi,pi,qr[1]) qc.barrier() qc.measure(qr,cr) # Running locally IBM backends respond too slowly print(Aer.backends()) backend = Aer.get_backend('qasm_simulator') job = execute(qc,backend) job.status result = job.result() counts = result.get_counts(qc) print(counts) plot_histogram(counts) performance = { 'success':(counts['01']+counts['10'])/1024, 'failure':1 - (counts['01']+counts['10'])/1024 } plot_histogram(performance) IBMQ.load_accounts() # checking the backends large_enough_devices = IBMQ.backends(filters=lambda x: x.configuration()['n_qubits'] > 1 and not x.configuration()['simulator']) print(large_enough_devices) backend = IBMQ.get_backend('ibmqx4') job = execute(qc,backend,max_credits=3) job.status result = job.result() counts = result.get_counts(qc) print(counts) plot_histogram(counts) performance = { 'success':(counts['01']+counts['10'])/1024, 'failure':(counts['00']+counts['11'])/1024 } plot_histogram(performance) sqr = QuantumRegister(1) scr = ClassicalRegister(1) sqc = QuantumCircuit(sqr,scr) # constructing the circuit sqc.u3(1.1503,6.4850,2.2555,sqr[0]) sqc.barrier() # unidentified gate -- now assumed to be R2pi3. if identity then use qc.u1(0,q[0]) sqc.u1((2.0/3)*pi,sqr[0]) sqc.barrier() sqc.u3(1.231,0,0,sqr[0]) # X sqc.barrier() sqc.u1((2.0/3)*pi,sqr[0]) # U (unidentified gate) sqc.barrier() # measurement sqc.u3(0.7854,6.0214,6.1913,sqr[0]) sqc.barrier() sqc.measure(sqr,scr) # Running on local simulator backend = Aer.get_backend('qasm_simulator') job = execute(sqc,backend) result = job.result() counts = result.get_counts(sqc) print(counts) plot_histogram(counts) # Running on IBM backend = IBMQ.get_backend('ibmqx4') job = execute(sqc,backend,max_credits=3) result = job.result() counts = result.get_counts(sqc) print(counts) plot_histogram(counts)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import pandas as pd import itertools import cma import os import sys import argparse import pickle import random import re from pprint import pprint import qiskit from qiskit import * from qiskit import Aer from qiskit import IBMQ from qiskit.providers.aer.noise.noise_model import NoiseModel from qiskit.test.mock import * from qiskit.providers.aer import AerSimulator, QasmSimulator from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter import mitiq IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') provider = IBMQ.get_provider(hub='', group='internal', project='hirashi-jst') print("provider:", provider) L = 3 p = 2 dt = 1.0 tf = 20 shots = 8192 def TwirlCircuit(circ: str) -> QuantumCircuit: """ そのまま使う: 修正は後回し """ #! qasm ベタ書き def apply_pauli(num: int, qb: int) -> str: if (num == 0): return f'id q[{qb}];\n' elif (num == 1): return f'x q[{qb}];\n' elif (num == 2): return f'y q[{qb}];\n' else: return f'z q[{qb}];\n' paulis = [(i,j) for i in range(0,4) for j in range(0,4)] paulis.remove((0,0)) paulis_map = [(0, 1), (3, 2), (3, 3), (1, 1), (1, 0), (2, 3), (2, 2), (2, 1), (2, 0), (1, 3), (1, 2), (3, 0), (3, 1), (0, 2), (0, 3)] new_circ = '' ops = circ.qasm().splitlines(True) #! 生のqasmコードを持ってきてる: オペレータに分解 for op in ops: if (op[:2] == 'cx'): # can add for cz, etc. num = random.randrange(len(paulis)) #! permute paulis qbs = re.findall('q\[(.)\]', op) new_circ += apply_pauli(paulis[num][0], qbs[0]) new_circ += apply_pauli(paulis[num][1], qbs[1]) new_circ += op new_circ += apply_pauli(paulis_map[num][0], qbs[0]) new_circ += apply_pauli(paulis_map[num][1], qbs[1]) else: new_circ += op return qiskit.circuit.QuantumCircuit.from_qasm_str(new_circ) # とりあえずOK def evolve(alpha: float, q0: Union[int, QuantumRegister], q1: Union[int, QuantumRegister]) -> QuantumCircuit: """ The implementation of Fig. 4 in https://arxiv.org/abs/2112.12654 """ qc = QuantumCircuit(2) qc.rz(-np.pi / 2, q1) qc.cnot(q1, q0) qc.rz(alpha - np.pi / 2, q0) qc.ry(np.pi / 2 - alpha, q1) qc.cnot(q0, q1) qc.ry(alpha - np.pi / 2, q1) qc.cnot(q1, q0) qc.rz(np.pi / 2, q0) return qc # とりあえずOK def make_ansatz_circuit(num_qubits: int, ansatz_depth: int, parameters: np.array) -> QuantumCircuit: """ Prepare ansatz circuit code reference: https://gitlab.com/QANED/heis_dynamics method reference: https://arxiv.org/abs/1906.06343 == AnsatzCircuit(param, p) -> QuantumCircuit Args: parameters: 1d array (for 2d parameters on circuit) """ qc = QuantumCircuit(num_qubits) for l in range(ansatz_depth): if num_qubits & 1: for i in range(0, num_qubits, 2): # linear condition qc.compose(evolve(parameters[l * ansatz_depth + i] / 4), [i, i + 1], inplace = True) #! we do not have to divide the angle by 4 for i in range(1, num_qubits - 1, 2): # linear condition # ! we do not have to divide the angle by 4 qc.compose(evolve(parameters[l * ansatz_depth + i] / 4), [i, i + 1], inplace=True) else: for i in range(0, num_qubits - 1, 2): # linear condition # ! we do not have to divide the angle by 4 qc.compose(evolve(parameters[l * ansatz_depth + i]), [i, i + 1], inplace=True) for i in range(1, num_qubits - 1, 2): # linear condition # ! we do not have to divide the angle by 4 qc.compose(evolve(parameters[l * ansatz_depth + i]), [i, i + 1], inplace=True) return qc # とりあえずOK def make_trotter_circuit(num_qubits: int, time_interval: float) -> QuantumCircuit: """ Prepare Trotter circuit code reference: https://gitlab.com/QANED/heis_dynamics method reference: https://arxiv.org/abs/1906.06343 == TrotterEvolveCircuit(dt, nt, init) -> QuantumCircuit """ qc = QuantumCircuit(num_qubits) for n in range(trotter_steps): #! time_interval の符号に注意 if num_qubits & 1: for i in range(0, num_qubits, 2): # linear condition qc.compose(evolve(time_interval / 4), [i, i + 1], inplace = True) #! we do not have to divide the angle by 4 for i in range(1, num_qubits - 1, 2): # linear condition qc.compose(evolve(time_interval / 4), [i, i + 1], inplace = True) # ! we do not have to divide the angle by 4 else: for i in range(0, num_qubits - 1, 2): # linear condition qc.compose(evolve(time_interval / 4), [i, i + 1], inplace = True) #! we do not have to divide the angle by 4 for i in range(1, num_qubits - 1, 2): # linear condition qc.compose(evolve(time_interval / 4), [i, i + 1], inplace = True) # ! we do not have to divide the angle by 4 return qc #TODO VTCとは別実装?→ no, 同じ実装に。 def SimulateAndReorder(circ): """ #! execution wrapper Executes a circuit using the statevector simulator and reorders basis to match with standard """ backend = Aer.get_backend('statevector_simulator') return execute(circ.reverse_bits(), backend).result().get_statevector() def Simulate(circ): """ #! execution wrapper Executes a circuit using the statevector simulator. Doesn't reorder -- which is needed for intermediate steps in the VTC """ backend = Aer.get_backend('statevector_simulator') return execute(circ, backend).result().get_statevector() #TODO def LoschmidtEchoExecutor(circuits, backend, shots, filter): """ #! 回路を実行 Returns the expectation value to be mitigated. :param circuit: Circuit to run. #! ここでのcircuitsは :param backend: backend to run the circuit on :param shots: Number of times to execute the circuit to compute the expectation value. :param fitter: measurement error mitigator """ # circuits = [TwirlCircuit(circ) for circ in circuits] scale_factors = [1.0, 2.0, 3.0] #! ZNEのノイズスケーリングパラメタ folded_circuits = [] #! ZNE用の回路 for circuit in circuits: folded_circuits.append([mitiq.zne.scaling.fold_gates_at_random(circuit, scale) for scale in scale_factors]) #! ここでmitiqを使用 folded_circuits = list(itertools.chain(*folded_circuits)) #! folded_circuitsを平坦化 folded_circuits = [TwirlCircuit(circ) for circ in folded_circuits] #! 後からPauli Twirlingを施す! print("length of circuit in job", len(folded_circuits)) #! jobを投げる job = qiskit.execute( experiments=folded_circuits, backend=backend, optimization_level=0, shots=shots ) print("casted job") #! fidelity測定用(VTCをしないなら、ここはtomographyで良い) c = ['1','1','0'] #! これをpermutationする # c = [str((1 + (-1)**(i+1)) // 2) for i in range(L)] c = ''.join(c)[::-1] #! endianを反転 (big endianへ) res = job.result() if (filter is not None): #! QREM res = filter.apply(res) print("retrieved job") all_counts = [job.result().get_counts(i) for i in range(len(folded_circuits))] expectation_values = [] for counts in all_counts: total_allowed_shots = [counts.get(''.join(p)) for p in set(itertools.permutations(c))] #! ここでcをpermutationしている total_allowed_shots = sum([0 if x is None else x for x in total_allowed_shots]) if counts.get(c) is None: expectation_values.append(0) else: expectation_values.append(counts.get(c)/total_allowed_shots) # expectation_values = [counts.get(c) / shots for counts in all_counts] zero_noise_values = [] if isinstance(backend, qiskit.providers.aer.backends.qasm_simulator.QasmSimulator): # exact_sim for i in range(len(circuits)): zero_noise_values.append(np.mean(expectation_values[i*len(scale_factors):(i+1)*len(scale_factors)])) else: #device_sim, real_device fac = mitiq.zne.inference.LinearFactory(scale_factors) for i in range(len(circuits)): zero_noise_values.append(fac.extrapolate(scale_factors, expectation_values[i*len(scale_factors):(i+1)*len(scale_factors)])) print("zero_noise_values") pprint(zero_noise_values) print() return zero_noise_values #TODO def LoschmidtEchoCircuit(params, U_v, U_trot, init, p): """ #! 回路を作成 Cost function using the Loschmidt Echo. Just using statevectors currently -- can rewrite using shots :param params: parameters new variational circuit that represents U_trot U_v | init >. Need dagger for cost function :param U_v: variational circuit that stores the state before the trotter step :param U_trot: trotter step :param init: initial state :param p: number of ansatz steps """ U_v_prime = AnsatzCircuit(params, p) circ = init + U_v + U_trot + U_v_prime.inverse() circ.measure_all() return circ def LoschmidtEcho(params, U_v, U_trot, init, p, backend, shots, filter): """ #! 実行パート """ circs = [] for param in params: circs.append(LoschmidtEchoCircuit(param, U_v, U_trot, init, p)) #! 回路を作成 print("length of circuits without zne:", len(circs)) res = LoschmidtEchoExecutor(circs, backend, shots, filter) #! 回路を実行 return abs(1 - np.array(res)) def LoschmidtEchoExact(params, U_v, U_trot, init, p): """ #! unused function """ U_v_prime = AnsatzCircuit(params, p) circ = init + U_v + U_trot + U_v_prime.inverse() circ_vec = Simulate(circ) init_vec = Simulate(init) return 1 - abs(np.conj(circ_vec) @ init_vec)**2 def CMAES(U_v, U_trot, init, p, backend, shots, filter): """ #! 実行 + 最適化パート """ init_params = np.random.uniform(0, 2*np.pi, (L-1)*p) es = cma.CMAEvolutionStrategy(init_params, np.pi/2) es.opts.set({'ftarget':5e-3, 'maxiter':1000}) # es = pickle.load(open(f'./results_{L}/optimizer_dump', 'rb')) while not es.stop(): #! 最適化パート # solutions = es.ask(25) # ! 25 = number of returned solutions solutions = es.ask(10) print("solutions") pprint(solutions) es.tell(solutions, LoschmidtEcho(solutions, U_v, U_trot, init, p, backend, shots, filter)) #! 実行パート # es.tell(solutions, LoschmidtEchoExact(solutions, U_v, U_trot, init, p)) #! 実行パート es.disp() open(f'./results_{L}/optimizer_dump', 'wb').write(es.pickle_dumps()) return es.result_pretty() def VTC(tf, dt, p, init, backend, shots, filter): """ #! tf: 総経過時間 #! dt: trotter step size: 時間間隔 #! p: ansatzのステップ数 """ VTCParamList = [np.zeros((L-1)*p)] #! デフォルトのパラメタ(初期値) VTCStepList = [SimulateAndReorder(init.copy())] #! type: List[Statevector] # TrotterFixStepList = [init] TimeStep = [0] if (os.path.exists(f'./results_{L}/VTD_params_{tf}_{L}_{p}_{dt}_{shots}.csv')): #! 2巡目からこっち VTCParamList = pd.read_csv(f'./results_{L}/VTD_params_{tf}_{L}_{p}_{dt}_{shots}.csv', index_col=0) VTCStepList = pd.read_csv(f'./results_{L}/VTD_results_{tf}_{L}_{p}_{dt}_{shots}.csv', index_col=0) temp = VTCParamList.iloc[-1] print(temp, "th time interval") U_v = AnsatzCircuit(temp, p) else: #! 最初はこっちに入る VTCParamList = pd.DataFrame(np.array(VTCParamList), index=np.array(TimeStep)) VTCStepList = pd.DataFrame(np.array(VTCStepList), index=np.array(TimeStep)) print("0 th time interval") print() U_v = QuantumCircuit(L) ts = VTCParamList.index #! 時間間隔 U_trot = TrotterEvolveCircuit(dt, p, QuantumCircuit(L)) #! Trotter分解のunitaryを作る print() print("start CMAES") print() res = CMAES(U_v, U_trot, init, p, backend, shots, filter) #! ここでプロセスを実行!!!! print() print("res") pprint(res) #! 新しいループ結果を追加し、tsを更新 res = res.xbest # ! best solution evaluated print("res.xbest") pprint(res) VTCParamList.loc[ts[-1]+(dt*p)] = np.array(res) VTCStepList.loc[ts[-1]+(dt*p)] = np.array(SimulateAndReorder(init + AnsatzCircuit(res, p))) ts = VTCParamList.index # VTCParamList = pd.DataFrame(np.array(VTCParamList), index=np.array(TimeStep)) # VTCStepList = pd.DataFrame(np.array(VTCStepList), index=np.array(TimeStep)) #! csvファイルを更新 VTCParamList.to_csv(f'./results_{L}/VTD_params_{tf}_{L}_{p}_{dt}_{shots}.csv') VTCStepList.to_csv(f'./results_{L}/VTD_results_{tf}_{L}_{p}_{dt}_{shots}.csv') if (ts[-1] >= tf): return else: print("next step") VTC(tf, dt, p, init, backend, shots, filter) #! ここからQREM回路 qr = QuantumRegister(L) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # device_backend = FakeJakarta() # device_sim = AerSimulator.from_backend(device_backend) real_device = provider.get_backend('ibmq_jakarta') noise_model = NoiseModel.from_backend(real_device) device_sim = QasmSimulator(method='statevector', noise_model=noise_model) exact_sim = Aer.get_backend('qasm_simulator') # QasmSimulator(method='statevector') t_qc = transpile(meas_calibs) qobj = assemble(t_qc, shots=8192) # cal_results = real_device.run(qobj, shots=8192).result() cal_results = device_sim.run(qobj, shots=8192).result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') print("qrem done") # np.around(meas_fitter.cal_matrix, decimals=2) init = QuantumCircuit(L) # c = [str((1 + (-1)**(i+1)) // 2) for i in range(L)] c = ['1','1','0'] #! なぜinitial stateが110なの??????? もしかしてopen science prizeを意識??? #! けどループでこのプログラムが実行されるたびにここが|110>だとおかしくないか? for q in range(len(c)): if (c[q] == '1'): init.x(q) #! ここまでQREM回路 nt = int(np.ceil(tf / (dt * p))) # f = open(f'./results_{L}/logging.txt', 'a') # sys.stdout = f #! tf: シミュレーションの(経過)時間 #! dt: trotter分解のステップ数 #! p: ansatzのステップ数 (論文中のL) # VTC(tf, dt, p, init, real_device, shots, meas_fitter.filter) #! mainの処理 print("vtc start!!!! \n\n\n") VTC(tf, dt, p, init, device_sim, shots, meas_fitter.filter) #! mainの処理 # f.close()
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import pandas as pd import itertools import cma import os import sys import argparse import pickle import random import re from pprint import pprint import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute from qiskit import Aer from qiskit import IBMQ from qiskit.compiler import transpile from qiskit.providers.aer.noise.noise_model import NoiseModel from qiskit.test.mock import * from qiskit.providers.aer import AerSimulator, QasmSimulator from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter import mitiq IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) real_device = provider.get_backend('ibmq_jakarta') def qrem_encoder(num_qubits: int, initial_layout: list) -> list: qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') return transpile(meas_calibs, initial_layout=initial_layout, basis_gates=["sx", "rz", "cx"]) def execute_circuits(qcs: list, backend) -> (qiskit.providers.Job, str): job = exec meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') def qrem_decoder():
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import pandas as pd import itertools import cma import os import sys import argparse import pickle import random import re from pprint import pprint import qiskit from qiskit import * from qiskit import Aer from qiskit import IBMQ from qiskit.providers.aer.noise.noise_model import NoiseModel from qiskit.test.mock import * from qiskit.providers.aer import AerSimulator, QasmSimulator from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter import mitiq IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst') provider = IBMQ.get_provider(hub='', group='internal', project='hirashi-jst') print("provider:", provider) L = 3 p = 2 dt = 1.0 tf = 20 shots = 8192 def TwirlCircuit(circ: str) -> QuantumCircuit: """ そのまま使う: 修正は後回し """ #! qasm ベタ書き def apply_pauli(num: int, qb: int) -> str: if (num == 0): return f'id q[{qb}];\n' elif (num == 1): return f'x q[{qb}];\n' elif (num == 2): return f'y q[{qb}];\n' else: return f'z q[{qb}];\n' paulis = [(i,j) for i in range(0,4) for j in range(0,4)] paulis.remove((0,0)) paulis_map = [(0, 1), (3, 2), (3, 3), (1, 1), (1, 0), (2, 3), (2, 2), (2, 1), (2, 0), (1, 3), (1, 2), (3, 0), (3, 1), (0, 2), (0, 3)] new_circ = '' ops = circ.qasm().splitlines(True) #! 生のqasmコードを持ってきてる: オペレータに分解 for op in ops: if (op[:2] == 'cx'): # can add for cz, etc. num = random.randrange(len(paulis)) #! permute paulis qbs = re.findall('q\[(.)\]', op) new_circ += apply_pauli(paulis[num][0], qbs[0]) new_circ += apply_pauli(paulis[num][1], qbs[1]) new_circ += op new_circ += apply_pauli(paulis_map[num][0], qbs[0]) new_circ += apply_pauli(paulis_map[num][1], qbs[1]) else: new_circ += op return qiskit.circuit.QuantumCircuit.from_qasm_str(new_circ) # とりあえずOK def evolve(alpha: float, q0: Union[int, QuantumRegister], q1: Union[int, QuantumRegister]) -> QuantumCircuit: """ The implementation of Fig. 4 in https://arxiv.org/abs/2112.12654 """ qc = QuantumCircuit(2) qc.rz(-np.pi / 2, q1) qc.cnot(q1, q0) qc.rz(alpha - np.pi / 2, q0) qc.ry(np.pi / 2 - alpha, q1) qc.cnot(q0, q1) qc.ry(alpha - np.pi / 2, q1) qc.cnot(q1, q0) qc.rz(np.pi / 2, q0) return qc # とりあえずOK def make_ansatz_circuit(num_qubits: int, ansatz_depth: int, parameters: np.array) -> QuantumCircuit: """ Prepare ansatz circuit code reference: https://gitlab.com/QANED/heis_dynamics method reference: https://arxiv.org/abs/1906.06343 == AnsatzCircuit(param, p) -> QuantumCircuit Args: parameters: 1d array (for 2d parameters on circuit) """ qc = QuantumCircuit(num_qubits) for l in range(ansatz_depth): if num_qubits & 1: for i in range(0, num_qubits, 2): # linear condition qc.compose(evolve(parameters[l * ansatz_depth + i] / 4), [i, i + 1], inplace = True) #! we do not have to divide the angle by 4 for i in range(1, num_qubits - 1, 2): # linear condition # ! we do not have to divide the angle by 4 qc.compose(evolve(parameters[l * ansatz_depth + i] / 4), [i, i + 1], inplace=True) else: for i in range(0, num_qubits - 1, 2): # linear condition # ! we do not have to divide the angle by 4 qc.compose(evolve(parameters[l * ansatz_depth + i]), [i, i + 1], inplace=True) for i in range(1, num_qubits - 1, 2): # linear condition # ! we do not have to divide the angle by 4 qc.compose(evolve(parameters[l * ansatz_depth + i]), [i, i + 1], inplace=True) return qc # とりあえずOK def make_trotter_circuit(num_qubits: int, time_interval: float) -> QuantumCircuit: """ Prepare Trotter circuit code reference: https://gitlab.com/QANED/heis_dynamics method reference: https://arxiv.org/abs/1906.06343 == TrotterEvolveCircuit(dt, nt, init) -> QuantumCircuit """ qc = QuantumCircuit(num_qubits) for n in range(trotter_steps): #! time_interval の符号に注意 if num_qubits & 1: for i in range(0, num_qubits, 2): # linear condition qc.compose(evolve(time_interval / 4), [i, i + 1], inplace = True) #! we do not have to divide the angle by 4 for i in range(1, num_qubits - 1, 2): # linear condition qc.compose(evolve(time_interval / 4), [i, i + 1], inplace = True) # ! we do not have to divide the angle by 4 else: for i in range(0, num_qubits - 1, 2): # linear condition qc.compose(evolve(time_interval / 4), [i, i + 1], inplace = True) #! we do not have to divide the angle by 4 for i in range(1, num_qubits - 1, 2): # linear condition qc.compose(evolve(time_interval / 4), [i, i + 1], inplace = True) # ! we do not have to divide the angle by 4 return qc #TODO VTCとは別実装?→ no, 同じ実装に。 def SimulateAndReorder(circ): """ #! execution wrapper Executes a circuit using the statevector simulator and reorders basis to match with standard """ backend = Aer.get_backend('statevector_simulator') return execute(circ.reverse_bits(), backend).result().get_statevector() def Simulate(circ): """ #! execution wrapper Executes a circuit using the statevector simulator. Doesn't reorder -- which is needed for intermediate steps in the VTC """ backend = Aer.get_backend('statevector_simulator') return execute(circ, backend).result().get_statevector() #TODO def LoschmidtEchoExecutor(circuits, backend, shots, filter): """ #! 回路を実行 Returns the expectation value to be mitigated. :param circuit: Circuit to run. #! ここでのcircuitsは :param backend: backend to run the circuit on :param shots: Number of times to execute the circuit to compute the expectation value. :param fitter: measurement error mitigator """ # circuits = [TwirlCircuit(circ) for circ in circuits] scale_factors = [1.0, 2.0, 3.0] #! ZNEのノイズスケーリングパラメタ folded_circuits = [] #! ZNE用の回路 for circuit in circuits: folded_circuits.append([mitiq.zne.scaling.fold_gates_at_random(circuit, scale) for scale in scale_factors]) #! ここでmitiqを使用 folded_circuits = list(itertools.chain(*folded_circuits)) #! folded_circuitsを平坦化 folded_circuits = [TwirlCircuit(circ) for circ in folded_circuits] #! 後からPauli Twirlingを施す! print("length of circuit in job", len(folded_circuits)) #! jobを投げる job = qiskit.execute( experiments=folded_circuits, backend=backend, optimization_level=0, shots=shots ) print("casted job") #! fidelity測定用(VTCをしないなら、ここはtomographyで良い) c = ['1','1','0'] #! これをpermutationする # c = [str((1 + (-1)**(i+1)) // 2) for i in range(L)] c = ''.join(c)[::-1] #! endianを反転 (big endianへ) res = job.result() if (filter is not None): #! QREM res = filter.apply(res) print("retrieved job") all_counts = [job.result().get_counts(i) for i in range(len(folded_circuits))] expectation_values = [] for counts in all_counts: total_allowed_shots = [counts.get(''.join(p)) for p in set(itertools.permutations(c))] #! ここでcをpermutationしている total_allowed_shots = sum([0 if x is None else x for x in total_allowed_shots]) if counts.get(c) is None: expectation_values.append(0) else: expectation_values.append(counts.get(c)/total_allowed_shots) # expectation_values = [counts.get(c) / shots for counts in all_counts] zero_noise_values = [] if isinstance(backend, qiskit.providers.aer.backends.qasm_simulator.QasmSimulator): # exact_sim for i in range(len(circuits)): zero_noise_values.append(np.mean(expectation_values[i*len(scale_factors):(i+1)*len(scale_factors)])) else: #device_sim, real_device fac = mitiq.zne.inference.LinearFactory(scale_factors) for i in range(len(circuits)): zero_noise_values.append(fac.extrapolate(scale_factors, expectation_values[i*len(scale_factors):(i+1)*len(scale_factors)])) print("zero_noise_values") pprint(zero_noise_values) print() return zero_noise_values #TODO def LoschmidtEchoCircuit(params, U_v, U_trot, init, p): """ #! 回路を作成 Cost function using the Loschmidt Echo. Just using statevectors currently -- can rewrite using shots :param params: parameters new variational circuit that represents U_trot U_v | init >. Need dagger for cost function :param U_v: variational circuit that stores the state before the trotter step :param U_trot: trotter step :param init: initial state :param p: number of ansatz steps """ U_v_prime = AnsatzCircuit(params, p) circ = init + U_v + U_trot + U_v_prime.inverse() circ.measure_all() return circ def LoschmidtEcho(params, U_v, U_trot, init, p, backend, shots, filter): """ #! 実行パート """ circs = [] for param in params: circs.append(LoschmidtEchoCircuit(param, U_v, U_trot, init, p)) #! 回路を作成 print("length of circuits without zne:", len(circs)) res = LoschmidtEchoExecutor(circs, backend, shots, filter) #! 回路を実行 return abs(1 - np.array(res)) def LoschmidtEchoExact(params, U_v, U_trot, init, p): """ #! unused function """ U_v_prime = AnsatzCircuit(params, p) circ = init + U_v + U_trot + U_v_prime.inverse() circ_vec = Simulate(circ) init_vec = Simulate(init) return 1 - abs(np.conj(circ_vec) @ init_vec)**2 def CMAES(U_v, U_trot, init, p, backend, shots, filter): """ #! 実行 + 最適化パート """ init_params = np.random.uniform(0, 2*np.pi, (L-1)*p) es = cma.CMAEvolutionStrategy(init_params, np.pi/2) es.opts.set({'ftarget':5e-3, 'maxiter':1000}) # es = pickle.load(open(f'./results_{L}/optimizer_dump', 'rb')) while not es.stop(): #! 最適化パート # solutions = es.ask(25) # ! 25 = number of returned solutions solutions = es.ask(10) print("solutions") pprint(solutions) es.tell(solutions, LoschmidtEcho(solutions, U_v, U_trot, init, p, backend, shots, filter)) #! 実行パート # es.tell(solutions, LoschmidtEchoExact(solutions, U_v, U_trot, init, p)) #! 実行パート es.disp() open(f'./results_{L}/optimizer_dump', 'wb').write(es.pickle_dumps()) return es.result_pretty() def VTC(tf, dt, p, init, backend, shots, filter): """ #! tf: 総経過時間 #! dt: trotter step size: 時間間隔 #! p: ansatzのステップ数 """ VTCParamList = [np.zeros((L-1)*p)] #! デフォルトのパラメタ(初期値) VTCStepList = [SimulateAndReorder(init.copy())] #! type: List[Statevector] # TrotterFixStepList = [init] TimeStep = [0] if (os.path.exists(f'./results_{L}/VTD_params_{tf}_{L}_{p}_{dt}_{shots}.csv')): #! 2巡目からこっち VTCParamList = pd.read_csv(f'./results_{L}/VTD_params_{tf}_{L}_{p}_{dt}_{shots}.csv', index_col=0) VTCStepList = pd.read_csv(f'./results_{L}/VTD_results_{tf}_{L}_{p}_{dt}_{shots}.csv', index_col=0) temp = VTCParamList.iloc[-1] print(temp, "th time interval") U_v = AnsatzCircuit(temp, p) else: #! 最初はこっちに入る VTCParamList = pd.DataFrame(np.array(VTCParamList), index=np.array(TimeStep)) VTCStepList = pd.DataFrame(np.array(VTCStepList), index=np.array(TimeStep)) print("0 th time interval") print() U_v = QuantumCircuit(L) ts = VTCParamList.index #! 時間間隔 U_trot = TrotterEvolveCircuit(dt, p, QuantumCircuit(L)) #! Trotter分解のunitaryを作る print() print("start CMAES") print() res = CMAES(U_v, U_trot, init, p, backend, shots, filter) #! ここでプロセスを実行!!!! print() print("res") pprint(res) #! 新しいループ結果を追加し、tsを更新 res = res.xbest # ! best solution evaluated print("res.xbest") pprint(res) VTCParamList.loc[ts[-1]+(dt*p)] = np.array(res) VTCStepList.loc[ts[-1]+(dt*p)] = np.array(SimulateAndReorder(init + AnsatzCircuit(res, p))) ts = VTCParamList.index # VTCParamList = pd.DataFrame(np.array(VTCParamList), index=np.array(TimeStep)) # VTCStepList = pd.DataFrame(np.array(VTCStepList), index=np.array(TimeStep)) #! csvファイルを更新 VTCParamList.to_csv(f'./results_{L}/VTD_params_{tf}_{L}_{p}_{dt}_{shots}.csv') VTCStepList.to_csv(f'./results_{L}/VTD_results_{tf}_{L}_{p}_{dt}_{shots}.csv') if (ts[-1] >= tf): return else: print("next step") VTC(tf, dt, p, init, backend, shots, filter) #! ここからQREM回路 qr = QuantumRegister(L) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # device_backend = FakeJakarta() # device_sim = AerSimulator.from_backend(device_backend) real_device = provider.get_backend('ibmq_jakarta') noise_model = NoiseModel.from_backend(real_device) device_sim = QasmSimulator(method='statevector', noise_model=noise_model) exact_sim = Aer.get_backend('qasm_simulator') # QasmSimulator(method='statevector') t_qc = transpile(meas_calibs) qobj = assemble(t_qc, shots=8192) # cal_results = real_device.run(qobj, shots=8192).result() cal_results = device_sim.run(qobj, shots=8192).result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') print("qrem done") # np.around(meas_fitter.cal_matrix, decimals=2) init = QuantumCircuit(L) # c = [str((1 + (-1)**(i+1)) // 2) for i in range(L)] c = ['1','1','0'] #! なぜinitial stateが110なの??????? もしかしてopen science prizeを意識??? #! けどループでこのプログラムが実行されるたびにここが|110>だとおかしくないか? for q in range(len(c)): if (c[q] == '1'): init.x(q) #! ここまでQREM回路 nt = int(np.ceil(tf / (dt * p))) # f = open(f'./results_{L}/logging.txt', 'a') # sys.stdout = f #! tf: シミュレーションの(経過)時間 #! dt: trotter分解のステップ数 #! p: ansatzのステップ数 (論文中のL) # VTC(tf, dt, p, init, real_device, shots, meas_fitter.filter) #! mainの処理 print("vtc start!!!! \n\n\n") VTC(tf, dt, p, init, device_sim, shots, meas_fitter.filter) #! mainの処理 # f.close()
https://github.com/BOBO1997/osp_solutions
BOBO1997
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # 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. import numpy as np from qiskit import compiler, BasicAer, QuantumRegister from qiskit.converters import circuit_to_dag from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller def convert_to_basis_gates(circuit): # unroll the circuit using the basis u1, u2, u3, cx, and id gates unroller = Unroller(basis=['u1', 'u2', 'u3', 'cx', 'id']) pm = PassManager(passes=[unroller]) qc = compiler.transpile(circuit, BasicAer.get_backend('qasm_simulator'), pass_manager=pm) return qc def is_qubit(qb): # check if the input is a qubit, which is in the form (QuantumRegister, int) return isinstance(qb, tuple) and isinstance(qb[0], QuantumRegister) and isinstance(qb[1], int) def is_qubit_list(qbs): # check if the input is a list of qubits for qb in qbs: if not is_qubit(qb): return False return True def summarize_circuits(circuits): """Summarize circuits based on QuantumCircuit, and four metrics are summarized. Number of qubits and classical bits, and number of operations and depth of circuits. The average statistic is provided if multiple circuits are inputed. Args: circuits (QuantumCircuit or [QuantumCircuit]): the to-be-summarized circuits """ if not isinstance(circuits, list): circuits = [circuits] ret = "" ret += "Submitting {} circuits.\n".format(len(circuits)) ret += "============================================================================\n" stats = np.zeros(4) for i, circuit in enumerate(circuits): dag = circuit_to_dag(circuit) depth = dag.depth() width = dag.width() size = dag.size() classical_bits = dag.num_cbits() op_counts = dag.count_ops() stats[0] += width stats[1] += classical_bits stats[2] += size stats[3] += depth ret = ''.join([ret, "{}-th circuit: {} qubits, {} classical bits and {} operations with depth {}\n op_counts: {}\n".format( i, width, classical_bits, size, depth, op_counts)]) if len(circuits) > 1: stats /= len(circuits) ret = ''.join([ret, "Average: {:.2f} qubits, {:.2f} classical bits and {:.2f} operations with depth {:.2f}\n".format( stats[0], stats[1], stats[2], stats[3])]) ret += "============================================================================\n" return ret