# in this step, we will generate a 2 dim random statevector using quantum_info random_statevector method
from qiskit.quantum_info import random_statevector, Statevector

rand_sv  = random_statevector(2).data
print(rand_sv)  # print the vector components (complex amplitudes) associated with bais |0> and |1> from rand_sv


#Lets plot the rand_sv using plot_bloch_multivector, before that import plot_bloch vector from qiskit.visualization 
from qiskit.visualization import plot_bloch_multivector
plot_bloch_multivector(rand_sv)

# once we will have the cartesian cordinates calculated we can use plot_bloch_vector from visualization as shown below
from qiskit.visualization import plot_bloch_vector
plot_bloch_vector([1,0,0])

# break down complex amplitudes α and β in real and imaginary parts to express same in polar form. 
import math
import numpy as np

print('The random statevector', rand_sv)
alpha_real = rand_sv[0].real
alpha_imag = rand_sv[0].imag
alpha_theta = math.atan(alpha_imag/alpha_real) 

if alpha_real < 0 and alpha_imag > 0 :
    alpha_theta = math.atan(alpha_imag/alpha_real) + math.pi

if alpha_real < 0 and alpha_imag < 0 :
    alpha_theta = math.atan(alpha_imag/alpha_real) + math.pi

print ('alpha and alpha_theta ', np.around(alpha_real,8), np.around(alpha_imag,8), math.degrees(alpha_theta))
r_alpha = math.sqrt((alpha_real**2) + (alpha_imag**2))

beta_real = rand_sv[1].real
beta_imag = rand_sv[1].imag
beta_theta = math.atan(beta_imag/beta_real) 

if beta_real < 0 and beta_imag > 0 :
    beta_theta = math.atan(beta_imag/beta_real) + math.pi

if beta_real < 0 and beta_imag < 0 :
    beta_theta = math.atan(beta_imag/beta_real) + math.pi

print ('beta and beta_theta ', np.around(beta_real,8), np.around(beta_imag,8), math.degrees(beta_theta))

r_beta = math.sqrt((beta_real**2) + (beta_imag**2))

# use global phase to get a real only value for amplitude associated with state |0> on bloch sphere
phi = beta_theta - alpha_theta
print('r_alpha, r_beta, Phase differnce phi: ',phi)




theta = 2 * np.arccos(r_alpha)
print('Spherical Coordinates of Blochsphere are theta and phi : 1, ', theta, beta_theta - alpha_theta)
x = math.sin(theta)*math.cos(phi)
y = math.sin(theta)*math.sin(phi)
z = math.cos(theta)
print(x,y,z)

plot_bloch_vector([x,y,z])
#plot_bloch_vector([1, theta, phi], coord_type='spherical')  # also try it out with spherical coordinates

#once agian we plot rand_sv state to check if that is same as what we have calculated above
plot_bloch_multivector(rand_sv)

