mirror of
https://github.com/quantumjim/Quantum-Computation-course-Basel.git
synced 2026-09-30 10:28:19 +02:00
100 KiB
100 KiB
In [82]:
from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator
from qiskit.visualization import plot_histogram
import numpy as np
from scipy.linalg import expmIn [83]:
qc = QuantumCircuit(2,2)
qc.h(0)
qc.cx(0,1)
qc.measure([0,1],[0,1])
qc.draw()Out [83]:
┌───┐ ┌─┐
q_0: ┤ H ├──■──┤M├───
└───┘┌─┴─┐└╥┘┌─┐
q_1: ─────┤ X ├─╫─┤M├
└───┘ ║ └╥┘
c: 2/═══════════╩══╩═
0 1 In [84]:
backend = AerSimulator()
job = backend.run(qc, shots=2048)In [85]:
output = job.result()
counts = output.get_counts()
plot_histogram(counts)Out [85]:
In [86]:
#Use this as a skeleton
qc2 = QuantumCircuit(2,2)
#Prepare |Psi^+> (do not alter)
qc2.h(0)
qc2.cx(0,1)
## YOUR CODE GOES HERE ###
qc2.h(0)
qc2.h(1)
qc2.measure([0,1],[0,1])
qc2.draw()Out [86]:
┌───┐ ┌───┐┌─┐
q_0: ┤ H ├──■──┤ H ├┤M├───
└───┘┌─┴─┐├───┤└╥┘┌─┐
q_1: ─────┤ X ├┤ H ├─╫─┤M├
└───┘└───┘ ║ └╥┘
c: 2/════════════════╩══╩═
0 1 In [87]:
job = backend.run(qc2, shots=1024)
counts = job.result().get_counts()
plot_histogram(counts)Out [87]:
In [10]:
X = np.array([[0,1],[1,0]])
Y = np.array([[0,-1.j],[1.j,0]])
Z = np.array([[1,0],[0,-1]])
H = 1/np.sqrt(2)*np.array([[1,1],[1,-1]])In [11]:
def rotation(n, theta, varphi):
"ARGS: unit vector n=[nx,ny,nz], theta, varphi"
n_dot_sigma=(n[0]*X + n[1]*Y + n[2]*Z)
U = expm(1.j*theta*n_dot_sigma)
rot = np.exp(1.j*varphi)*U
return rot
In [12]:
your_Hadamard = rotation([1/np.sqrt(2), 0, 1/np.sqrt(2)], np.pi/2, -np.pi/2)
np.allclose(H, your_Hadamard)Out [12]:
True
In [74]:
error = {}
for n in range(1,11):
qc = QuantumCircuit(1,1)
# Implement the Trotterized Hadamard
### YOUR ANSWER GOES HERE
theta = np.pi/np.sqrt(2)
###
for j in range(n):
qc.rx(theta/n,0)
qc.rz(theta/n,0)
# We need to measure how good the above approximation is. Here's a simple way to do this.
# Step 1: Use a real Hadamard to cancel the above approximation.
# For a perfect approximation, the qubit will return to its initial state (0) since H squares to the identity.
qc.h(0)
# Step 2: Run the circuit, and see how many times we get the outcome 1. The fraction of 1s is a measure of the error.
qc.measure(0,0)
shots = 100000
job = backend.run(qc, shots=shots)
try:
error[n] = (job.result().get_counts()['1']/shots)
except:
pass
plot_histogram(error)Out [74]:
In [75]:
n_vals = []
error_vals = []
for key, val in error.items():
n_vals.append(key)
error_vals.append(val)In [76]:
def inverse_quad(n):
return 1/n**2In [77]:
degs = np.polyfit(inverse_quad(np.array(n_vals)), error_vals, 1)
polynomial_fit = np.poly1d(degs)In [78]:
import matplotlib.pyplot as pltIn [88]:
plt.scatter(n_vals, error_vals)
plt.plot(np.linspace(1,10,100), polynomial_fit(inverse_quad(np.linspace(1,10,100))))
plt.xlabel('n')
plt.ylabel('Error')
plt.show()In [ ]: