class BlochPlot(): ''' Dynamic plot context, intended for displaying geometries. like removing axes, equal axis, dynamically tune your figure and save it. Args: figsize (tuple, default=(6,4)): figure size. filename (filename, str): filename to store generated figure, if None, it will not save a figure. Attributes: figsize (tuple, default=(6,4)): figure size. filename (filename, str): filename to store generated figure, if None, it will not save a figure. ax (Axes): matplotlib Axes instance. Examples: with BlochPlot() as bp: bp.ball.add_vectors([0.4, 0.6, 0.8]) ''' def __init__(self, figsize=(6, 4), filename=None, dpi=300): self.figsize = figsize self.filename = filename self.ax = None def __enter__(self): from qutip import Bloch3d, Bloch plt.ion() self.fig = plt.figure(figsize=self.figsize) self.ax = Axes3D(self.fig, azim=-30, elev=15) self.ball = Bloch(axes=self.ax) self.ball.zlabel = [r'$|N\rangle$', r'$|S\rangle$'] return self def __exit__(self, *args): self.ax.axis('off') self.ax.set_aspect("equal") #self.ball.make_sphere() self.ball.make_sphere() plt.close() if self.filename is not None: print('Press `c` to save figure to "%s", `Ctrl+d` to break >>' % self.filename) pdb.set_trace() plt.savefig(self.filename, dpi=300) else: pdb.set_trace() def add_polar(self, theta, phi, color=None): self.ball.add_vectors(polar2vec([1, theta, phi])) self.ball.vector_color.append(color) def text(self, vec, txt, fontsize=14): if len(vec) == 2: vec = polar2vec(*vec) self.ax.text(vec[0], vec[1], vec[2], txt, fontsize=fontsize, va='center', ha='center')
def func(f1, b, set): """ This function Perform the gate application on the initial state of qubit and then the state tomography, at the same time compute the analytical bloch state. INCOME: f1="string", b="string" fig_data="svg",fig_data2="svg" """ #### Create the bloch-sphere on qutip b1 = Bloch() b2 = Bloch() ## create the analyical quantum state and perform tranformation ## Add states to the bloch sphere and plot it b1.add_states(analytic(f1, b)) if not set: states = qtomography(f1, b) b2.add_vectors(states) else: ### implements for states = qtomography_s(f1, b) for i in states: b2.add_points(i) b2.add_vectors(np.average(states, axis=0)) ### b2.render() fig_data = print_figure(b2.fig, 'svg') b1.render() fig_data2 = print_figure(b1.fig, 'svg') #b1.show() #b2.show() b1.clear() b2.clear() return fig_data, fig_data2
def plot_quantum_state(amplitudes): """ Thin function to abstract the plotting on the Bloch sphere. """ bloch_sphere = Bloch() vec = get_vector(amplitudes[0], amplitudes[1]) bloch_sphere.add_vectors(vec) bloch_sphere.show() bloch_sphere.clear()
def bloch_plot(self, points=None, F=None): """ Plot the current state on the Bloch sphere using qutip. """ # create instance of 3d plot bloch = Bloch(figsize=[9, 9]) bloch.add_vectors([0, 0, 1]) bloch.xlabel = ['$<F_x>$', ''] bloch.ylabel = ['$<F_y>$', ''] bloch.zlabel = ['$<F_z>$', ''] if self.spin == 'half': if points is None: # convert current state into density operator rho = np.outer(self.state.H, self.state) # get Bloch vector representation points = self.get_bloch_vec(rho) # Can only plot systems of dimension 2 at this time assert len( points ) == 3, "System dimension must be spin 1/2 for Bloch sphere plot" # create instance of 3d plot bloch = Bloch(figsize=[9, 9]) elif self.spin == 'one': #points is list of items in format [[x1,x2],[y1,y2],[z1,z2]] if points is None: points = [getStars(self.state)] bloch.point_color = ['g', 'r', 'b'] #ensures point and line are same colour bloch.point_marker = ['o', 'd', 'o'] #bloch.point_color = ['g','r'] #ensures point and line are same colour #bloch.point_marker = ['o','d'] for p in points: bloch.add_points([p[0][0], p[1][0], p[2][0]]) bloch.add_points([p[0][1], p[1][1], p[2][1]]) bloch.add_points(p, meth='l') ''' bloch.point_color = ['b','b'] #ensures point and line are same colour bloch.point_marker = ['o','o'] for p in points: bloch.add_points(p) bloch.add_points(p, meth='l') ''' # add state #bloch.render(bloch.fig, bloch.axes) #bloch.fig.savefig("bloch.png",dpi=600, transparent=True) bloch.show()
def PlotStateQWP(InputState, qwpAngle): OutputState = QWP(qwpAngle) @ InputState pntsX = [ StateToBloch(QWP(th) @ InputState)[0] for th in arange(0, pi, pi / 64) ] pntsY = [ StateToBloch(QWP(th) @ InputState)[1] for th in arange(0, pi, pi / 64) ] pntsZ = [ StateToBloch(QWP(th) @ InputState)[2] for th in arange(0, pi, pi / 64) ] pnts = [pntsX, pntsY, pntsZ] bsph = Bloch() bsph.add_points(pnts) bsph.add_vectors(StateToBloch(OutputState)) bsph.add_vectors(StateToBloch(InputState)) return bsph.show()
def PlotStateAnalyzer(InputState, hwpAngle, qwpAngle): QWPstate = QWP(qwpAngle) @ InputState OutputState = HWP(hwpAngle) @ QWP(qwpAngle) @ InputState pntsX = [ StateToBloch(QWP(th) @ InputState)[0] for th in arange(0, pi, pi / 64) ] pntsY = [ StateToBloch(QWP(th) @ InputState)[1] for th in arange(0, pi, pi / 64) ] pntsZ = [ StateToBloch(QWP(th) @ InputState)[2] for th in arange(0, pi, pi / 64) ] pnts = [pntsX, pntsY, pntsZ] pntsX2 = [ StateToBloch(HWP(th) @ QWP(qwpAngle) @ InputState)[0] for th in arange(0, pi, pi / 64) ] pntsY2 = [ StateToBloch(HWP(th) @ QWP(qwpAngle) @ InputState)[1] for th in arange(0, pi, pi / 64) ] pntsZ2 = [ StateToBloch(HWP(th) @ QWP(qwpAngle) @ InputState)[2] for th in arange(0, pi, pi / 64) ] pnts2 = [pntsX2, pntsY2, pntsZ2] bsph = Bloch() bsph.add_points(pnts) bsph.add_points(pnts2) bsph.add_vectors(StateToBloch(OutputState)) bsph.add_vectors(StateToBloch(InputState)) bsph.add_vectors(StateToBloch(QWPstate)) return bsph.show()
def bloch_plot(self, points=None): """ Plot the current state on the Bloch sphere using qutip. """ if points is None: # convert current state into density operator rho = np.outer(self.state.H, self.state) # get Bloch vector representation points = self.get_bloch_vec(rho) # Can only plot systems of dimension 2 at this time assert len( points ) == 3, "System dimension must be spin 1/2 for Bloch sphere plot" # create instance of 3d plot bloch = Bloch(figsize=[9, 9]) # add state bloch.add_points(points) bloch.add_vectors([0, 0, 1]) bloch.render(bloch.fig, bloch.axes) bloch.fig.savefig("bloch.png", dpi=600, transparent=True) bloch.show()
def animate_bloch(vectors, duration=0.1, save_all=False): numberOfLoops = 1 #Enter '1' to apply only ONE mode [Excitation or Relaxation] or '2' to to apply only BOTH modes [Excitation and Relaxation] starting with the selected mode if numberOfLoops == 1: maxAngle = 2 * np.pi elif numberOfLoops == 2: maxAngle = 4 * np.pi mode = 1 #Enter '0' to activate Excitation Mode or '1' to activate Relaxation Mode omega = np.pi / 6 #Enter the angular frequency z = 0 sqAngle = np.pi / 2 a = 5 vectorM = Bloch() # vectorM.view = [90,90] #Activate this line to view magnetization’s trajectory on x-y plane images = [] for t in np.arange(omega, maxAngle, 0.1): if mode == 0: z = np.pi / 2 * np.sin(t / (4)) if t == 2 * np.pi: mode = 1 elif mode == 1: z = np.pi / 2 * np.cos(t / (4)) if t == 2 * np.pi: mode = 0 else: pass vectorM.clear() vectorM.add_vectors([ np.sin(omega) * np.cos(t), np.sin(omega) * np.sin(t), np.cos(omega) ]) vectorM.add_vectors( [np.sin(z) * np.cos(a * t), np.sin(z) * np.sin(a * t), np.cos(z)]) vectorM.add_vectors([ np.sin(sqAngle) * np.cos(t), np.sin(sqAngle) * np.sin(t), np.cos(sqAngle) ]) filename = 'temp_file.png' vectorM.save(filename) images.append(imageio.imread(filename)) imageio.mimsave('bloch_anim.gif', images, duration=duration)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jul 30 12:26:48 2019 @author: banano """ # from qutip import Bloch, Bloch3d b1 = Bloch() vec = [0,1,0] b1.add_vectors(vec) b1.vector_color = ['k'] b2 = Bloch() vec = [0,0,1] b2.add_vectors(vec) b2.vector_color = ['r'] b2.show() b1.show()
# %% -1- # Bloch() erzeugt eine Bloch # mit b verweisen wir spaeter auf diese b = Bloch() # b.show() zeigt die aktuelle Blochkugel an b.show() print('-1-') input('Press ENTER to continue.' ) # Ansonst wird Fenster sofort wieder geschlossen bzw. ueberschrieben. # %% -2- # hinzufuegen eines Vektor # x,y,z v = [1, 0, 0] # dazu geben wir einen Vektor in die x-Richtung an b.add_vectors( v) # mit b.add_vectors wird der Vektor v der Blochkugel hinzugefuegt b.show() print('-2-') input('Press ENTER to continue.') # %% -3- # Achsen koennen auch umbenannt werden # dazu kann Latex-Code verwendet werden jedoch muss beachtet werden, # dass fuer Latex-Code \ --> \\ verwendet werden sollte b.xlabel = ["$\\left|45^\\circ \\right>$", "$\\left|-45^\\circ \\right>$"] b.ylabel = ["$\\left|\\sigma^+\\right>$", "$\\left|\\sigma^- \\right>$"] b.zlabel = ["$\\left|H\\right>$", "$\\left|V\\right>$"] b.show() print('-3-') input('Press ENTER to continue.')
def bloch_plot2(self, filename, save=False, vecList=[], vecColour=[], view=[190, 10], points=None, folder=False, fig=False, ax=False): """ Plot the current state on the Bloch sphere using qutip. """ if points is None: # convert current state into density operator rho = np.outer(self.state.H, self.state) # get Bloch vector representation points = self.get_bloch_vec(rho) # Can only plot systems of dimension 2 at this time assert len( points ) == 3, "System dimension must be spin 1/2 for Bloch sphere plot" # create instance of 3d plot if not fig or not ax: bloch = Bloch(figsize=[9, 9], view=view) else: bloch = Bloch(fig=fig, axes=ax, view=view) # add state bloch.add_points(points) # bloch.zlabel = [r'$\left|+z\right>$',r'$\left|-z\right>$'] bloch.zlabel = [r'$\ket{+_z}$', r'$\ket{-_z}$'] # bloch.ylabel = [r'$\ket{+_y}$',r'$\ket{-_y}$'] # bloch.ylabel = [r'$\ket{+_y}$',r'$\ket{-_y}$'] # print(vecList.shape) # add vectors if vecList.shape[1] == 3: if len(vecColour) >= vecList.shape[0] and len(vecColour) > 0: bloch.vector_color = vecColour else: bloch.vector_color = ['#CC6600', 'royalblue', 'r', 'm', 'g'] bloch.add_vectors(vecList) # add field vector # bloch.add_vectors([1,0,0.15]) # bloch.add_vectors([0,0,1]) # bloch.add_vectors([1,0,0]) # render bloch sphere if not fig or not ax: bloch.render() else: # bloch.render(fig = fig, axes = ax) bloch.render(fig=fig) # save output if save is True: if not folder: folder = 'C:/Users/Boundsy/Desktop/Uni Work/PHS2360/Sim Results/' print('Bloch plot saved to ' + str(folder)) path1 = folder + str(filename) + '.png' path2 = folder + str(filename) + '.pdf' bloch.fig.savefig(path1, dpi=800, transparent=True) bloch.fig.savefig(path2, dpi=800, transparent=True) # return axes for annotations return bloch.fig, bloch.axes
def PlotBlochState(state): bsph = Bloch() bsph.add_vectors(StateToBloch(state)) return bsph.show()
#Input x,y = map(complex,input("enter the state: ").split()) #Normalization norm = np.sqrt(np.abs(x**2) + np.abs(y**2)) x /= norm y /= norm #Qubit allocation , define a state for the qubit,and measure it. qubit = ME.allocate_qubit() StatePreparation([x,y]) | qubit Measure | qubit read = int(qubit) #Measuring output ME.flush() print(read) #State vector to sphereical coordinates phi = np.angle(y) - np.angle(x) theta = 2 * np.arccos(np.abs(x)) vec = [np.sin(theta) * np.cos(phi), np.sin(theta) * np.sin(phi), np.cos(theta)] #Visualization b = Bloch() b.add_vectors(vec) b.show()