# useful additional packages 
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np

# importing Qiskit
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, BasicAer, IBMQ

# Creating registers
qr = QuantumRegister(1)
cr = ClassicalRegister(1)

circuits = []

# Creating the circuits
phase_vector = range(0,100)
for phase_index in phase_vector:
    phase_shift = phase_index-50
    phase = 2*np.pi*phase_shift/50
    circuit_name = "phase_gate_%d"%phase_index
    qc_phase_gate = QuantumCircuit(qr, cr, name=circuit_name)
    qc_phase_gate.h(qr)
    qc_phase_gate.u1(phase, qr)
    qc_phase_gate.h(qr)
    qc_phase_gate.measure(qr[0], cr[0])
    circuits.append(qc_phase_gate)

# Visualising one of the circuits as an example
circuits[25].draw(output='mpl')

# To run using qasm simulator
backend = BasicAer.get_backend('qasm_simulator')

# the number of shots in the experiment 
shots = 1024

result = execute(circuits, backend=backend, shots=shots).result()

probz = []
phase_value = []
for phase_index in phase_vector:
    phase_shift = phase_index - 50
    phase_value.append(2*phase_shift/50)
    if '0' in result.get_counts(circuits[phase_index]):
        probz.append(2*result.get_counts(circuits[phase_index]).get('0')/shots-1)
    else:
        probz.append(-1)

plt.plot(phase_value, probz, 'b',0.25,1/np.sqrt(2),'ro',0.5,0,'ko',1,-1,'go',-0.25,1/np.sqrt(2),'rx',-0.5,0,'kx',-1,-1,'gx')
plt.xlabel('Phase value (Pi)')
plt.ylabel('Eigenvalue of X')

plt.show()

# Creating registers
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
circuits = []

# Creating the circuits
phase_vector = range(0,100)
for phase_index in phase_vector:
    phase_shift = phase_index-50
    phase = 2*np.pi*phase_shift/50
    circuit_name = "phase_gate_%d"%phase_index
    qc_phase_gate = QuantumCircuit(qr, cr, name=circuit_name)
    qc_phase_gate.u3(phase,0,np.pi, qr)
    qc_phase_gate.measure(qr[0], cr[0])
    circuits.append(qc_phase_gate)
    
# Visualising one of the circuits as an example
circuits[75].draw(output='mpl')

# To run of qasm simulator
backend = BasicAer.get_backend('qasm_simulator')

# the number of shots in the experiment 
shots = 1024

result = execute(circuits, backend=backend, shots=shots).result()

probz = []
phase_value = []
for phase_index in phase_vector:
    phase_shift = phase_index - 50
    phase_value.append(2*phase_shift/50)
    if '0' in result.get_counts(circuits[phase_index]):
        probz.append(2*result.get_counts(circuits[phase_index]).get('0')/shots-1)
    else:
        probz.append(-1)

plt.plot(phase_value, probz, 'b',0.5,0,'ko',1,-1,'go',-0.5,0,'kx',-1,-1,'gx')
plt.xlabel('Phase value (Pi)')
plt.ylabel('Eigenvalue of Z')

plt.show()

