quantum/07_project_qiskit.py

93 lines
2.2 KiB
Python
Raw Permalink Normal View History

2020-02-01 11:46:55 +01:00
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 31 13:37:47 2020
@author: kidiki
"""
import numpy as np
2020-02-01 21:45:05 +01:00
from qiskit import (
QuantumCircuit,
execute,
Aer)
from qiskit.visualization import plot_histogram, plot_bloch_vector
from matplotlib import pyplot as plt
2020-02-01 11:46:55 +01:00
from scipy.stats import unitary_group
from collections import defaultdict
from qiskit.quantum_info.random.utils import random_state
# Use Aer's qasm_simulator
simulator = Aer.get_backend('qasm_simulator')
2020-02-01 21:45:05 +01:00
def create_bloch_vector(theta, phi):
x =np.sin(theta)*np.cos(phi)
y =np.sin(theta)*np.sin(phi)
z =np.cos(theta)
return [x,y,z]
2020-02-01 11:46:55 +01:00
def perform_exp(iterations=100):
simulator = Aer.get_backend('qasm_simulator')
all_counts = defaultdict(int)
2020-02-01 21:45:05 +01:00
2020-02-01 11:46:55 +01:00
for i in range(iterations):
qc = QuantumCircuit(2, 2)
# uniform distribution on the sphere
t = round(np.random.uniform(0, 1), 10)
2020-02-01 21:45:05 +01:00
theta = np.arccos(1 - 2 * t)
phi = round(np.random.uniform(0, 2 * np.pi), 10)
2020-02-01 11:46:55 +01:00
# 0_case, identical states
2020-02-01 21:45:05 +01:00
# qc.r(theta, phi, 0)
# qc.r(theta, phi, 1)
2020-02-01 11:46:55 +01:00
# 1_case, orthogonal states on the same meridian
2020-02-01 21:45:05 +01:00
# qc.r(theta, phi, 0)
# qc.r(theta+np.pi, phi, 1)
2020-02-01 11:46:55 +01:00
# my_case, phase difference DOESNT WORK
2020-02-01 21:45:05 +01:00
phi1 = 2 * np.pi - phi
2020-02-01 11:46:55 +01:00
qc.r(theta, phi, 0)
2020-02-01 21:45:05 +01:00
qc.r(theta, phi1, 1)
# print(theta, phi, phi1)
# q0 = create_bloch_vector(theta, phi)
# plot_bloch_vector(q0)
# plt.show()
#
# q1 = create_bloch_vector(theta, phi1)
# plot_bloch_vector(q1)
# plt.show()
2020-02-01 11:46:55 +01:00
# Measure in the Bell's basis
qc.cx(0, 1)
qc.h(0)
2020-02-01 21:45:05 +01:00
# qc.measure_all()
2020-02-01 11:46:55 +01:00
qc.measure([0, 1], [0, 1])
2020-02-01 21:45:05 +01:00
# print(qc)
2020-02-01 11:46:55 +01:00
job = execute(qc, simulator, shots=1)
result = job.result()
2020-02-01 21:45:05 +01:00
# print(result)
2020-02-01 11:46:55 +01:00
counts = result.get_counts(qc)
2020-02-01 21:45:05 +01:00
# print(counts.keys())
2020-02-01 11:46:55 +01:00
for k, v in counts.items():
all_counts[k] += v
2020-02-01 21:45:05 +01:00
2020-02-01 11:46:55 +01:00
print("\nTotal counts are:\n")
for k, v in sorted(all_counts.items(), key=lambda x: x[0]):
print("{}: {}".format(k, v))
if __name__ == "__main__":
perform_exp()