def plot_1_blochball(add_helper_lines=True): bloch = qutip.Bloch() theta = np.pi / 3 phi = -np.pi / 4 vec = [np.exp(1j * phi) * np.cos(theta / 2), np.sin(theta / 2)] qubit = vec[0] * qutip.basis(2, 0) + vec[1] * qutip.basis(2, 1) bloch.add_states(qubit) if add_helper_lines: fig = plt.figure(figsize=(7.4, 7)) ax = fig.add_subplot(111, projection='3d') bloch.axes = ax bloch.fig = fig bloch_vec = bloch.vectors[0].copy() bloch_vec[1] = -bloch_vec[1] point_below = bloch_vec.copy() point_below[2] = 0 help_line_1 = [[p1, p2] for p1, p2 in zip(bloch_vec, point_below)] help_line_2 = [[0, p] for p in bloch_vec] help_line_3 = [[0, p] for p in point_below] bloch.axes.plot(help_line_1[0], help_line_1[1], help_line_1[2]) bloch.axes.plot(help_line_2[0], help_line_2[1], help_line_2[2]) bloch.axes.plot(help_line_3[0], help_line_3[1], help_line_3[2]) else: bloch.view = [-75, 22] bloch.save("/Users/derrkater/Desktop/mgr/mgr/img/plot1bloch")
def __init__(self): self.dm00 = qt.ket2dm(qt.tensor(qt.basis(2, 0), qt.basis(2, 0))) self.dm10 = qt.ket2dm(qt.tensor(qt.basis(2, 1), qt.basis(2, 0))) self.dm01 = qt.ket2dm(qt.tensor(qt.basis(2, 0), qt.basis(2, 1))) self.dm11 = qt.ket2dm(qt.tensor(qt.basis(2, 1), qt.basis(2, 1))) self.bloch = qt.Bloch(view=fig_params['view'])
def trajectory(self, exps=None, initial_state=None, draw=False): '''for convenience. Calculates the trajectory of an observable for one montecarlo run. Default expectation is cavity amplitude, default initial state is bipartite vacuum. todo: draw: draw trajectory on bloch sphere. Write in terms of mcsolve??''' if exps is None or draw is True: exps = [] if initial_state is None: initial_state = qt.tensor(qt.basis(self.N_field_levels, 0), qt.basis(2, 0)) self.one_traj_soln = qt.mcsolve(self.hamiltonian(), initial_state, self.tlist, self._c_ops(), exps, ntraj=1) if self.noisy: print(self.one_traj_soln.states[0][2].ptrace(1)) if not draw: return self.one_traj_soln else: self.b_sphere = qt.Bloch() self.b_sphere.add_states( [state.ptrace(1) for state in self.one_traj_soln.states[0]], 'point') self.b_sphere.point_markers = ['o'] self.b_sphere.size = (10, 10) self.b_sphere.show()
def plot_probes_on_bloch_sphere( probe_dict, # num_probes, save_to_file=None, **kwargs ): try: import qutip as qt except: print("Qutip not installed") raise bloch = qt.Bloch() # isolate 1 qubit probes probe_ids = [t for t in list(probe_dict.keys()) if t[1] == 1] for pid in probe_ids: state = probe_dict[pid] a = state[0] b = state[1] A = a * qt.basis(2, 0) B = b * qt.basis(2, 1) vec = A + B bloch.add_states(vec) if save_to_file is not None: bloch.save(save_to_file) else: bloch.show()
def plot_subset_eval_probes( true_hamiltonian, probe_dict, subset_probes, measurement_probability_function, times, fig, dynamics_ax, bloch_ax, ): r""" Retained separately in case we later want to plot all eval probes instead of just a sample """ try: import qutip as qt except: print("Qutip not installed") raise colours = ["red", "green", "cyan", "orange", "brown", "blue", "pink"] linestyles = ["dashed", "dotted", "dashdot"] linestyles = itertools.cycle(linestyles) iter_colours = itertools.cycle(colours) num_probes_per_subplot = len(colours) bloch = qt.Bloch(fig=fig, axes=bloch_ax) try: bloch_ax.axis("square") # to get a nice circular plot except: pass for pid in subset_probes: probe = probe_dict[pid] ev = [ measurement_probability_function(ham=true_hamiltonian, t=t, state=probe) for t in times ] dynamics_ax.plot( times, ev, c=next(iter_colours), ls=next(linestyles), lw=3, label="{}".format(pid[0]), ) corresponding_single_qubit_probe = probe_dict[(pid[0], 1)] A = corresponding_single_qubit_probe[0] * qt.basis(2, 0) B = corresponding_single_qubit_probe[1] * qt.basis(2, 1) vec = A + B bloch.add_states(vec) bloch.vector_color = colours bloch.render(fig=fig, axes=bloch_ax) # render to the correct subplot dynamics_ax.set_ylabel("Expectation Value") dynamics_ax.set_xlabel("Time") dynamics_ax.legend()
def tensorStateToBlochSphere(tensorState): b = qutip.Bloch() b.xlabel = '|D>', '|A>' b.ylabel = '|R>', '|L>' b.zlabel = '|H>', '|V>' state = qutip.Qobj(tensorState) b.add_states(state) return b.show()
def main(): b = qutip.Bloch() for file in sys.argv[1:]: a = parse_file(file) print "plotting: " print a b.add_states(qutip.Qobj(a)) b.show()
def make_plots(self, bvs, ns): b = qt.Bloch() b.point_color = ['r', 'g', 'b'] # b.point_marker = ['o','s','d','^'] b.add_points([bvs[:, 0, 0], bvs[:, 0, 1], bvs[:, 0, 2]], 'l') b.add_points([bvs[:, 1, 0], bvs[:, 1, 1], bvs[:, 1, 2]], 'l') b.show() if np.any(ns): plt.hist(np.real(ns), 10) plt.show()
def plot_measurements(vector_alice_list, color=True): num = len(vector_alice_list) b = qt.Bloch() if color: b.vector_color = list(map(lambda x: x.rgb, list( Color('red').range_to(Color('purple'), num)))) for i in range(num): vector_alice = vector_alice_list[i] b.add_vectors(vector_alice) b.show() plt.show()
def __init__(self, state, time, name, fps = 50): self.state = state self.time = time self.name = name self.fps = fps self.res = [] self.figr, self.ax = plt.subplots() self.ax = Axes3D(fig = self.figr)#, animated = True) self.sphere=q.Bloch(axes=self.ax, fig = self.figr) self.sphere.render(fig=self.figr, axes=self.ax) self.sphere.add_states(self.state) self.txt_pos = (q.sigmaz() - q.sigmay())*0.49
def init_bloch_sphere(**bloch_kwargs) -> qt.Bloch: """A helper function to create a Bloch instance with a default viewing angle and axis labels.""" try: import qutip as qt except ImportError as err: raise RuntimeError( 'Requirements not fulfilled. Please install Qutip') from err bloch_kwargs.setdefault('view', [-150, 30]) b = qt.Bloch(**bloch_kwargs) b.xlabel = [r'$|+\rangle$', ''] b.ylabel = [r'$|+_i\rangle$', ''] return b
def init_bloch_sphere(**bloch_kwargs) -> qt.Bloch: """A helper function to create a Bloch instance with a default viewing angle and axis labels.""" qt = _import_qutip_or_raise() bloch_kwargs.setdefault('view', [-150, 30]) b = qt.Bloch(**bloch_kwargs) # https://github.com/qutip/qutip/issues/1385 if hasattr(b.axes, 'set_box_aspect'): b.axes.set_box_aspect([1, 1, 1]) b.xlabel = [r'$|+\rangle$', ''] b.ylabel = [r'$|+_i\rangle$', ''] return b
def sphere(self): """Result a Bloch sphere QuTiP and Matplotlib are needed to generate and plot the sphere. """ try: import qutip except ImportError as e: from sys import stderr print("Unable to import QuTiP, try installing:", file=stderr) print("\tpip install qutip", file=stderr) raise e b = qutip.Bloch() b.add_vectors(self.expected_values) return b
def plot_sphere(vectors, points=None, color="#d62728"): sphere = qt.Bloch() sphere.add_vectors(vectors) if points is not None: zipped_points = [np.array(pts) for pts in zip(*points)] sphere.add_points(zipped_points) sphere.frame_alpha = 0 sphere.xlabel, sphere.ylabel, sphere.zlabel = [["", ""]] * 3 sphere.figsize = (width, width) sphere.vector_color = [color] sphere.point_color = [color] sphere.render() return sphere
def visualise_qubit(s): """ This methods uses the qutip module to visualise a qubit's superposition on a bloch sphere. This comes from the fact we can write any qubit in the form: |phi> = e^ia*(cos(x/2)|0> + (e^iy)*sin(x/2)|1> ) and ignore the global phase e^ia, giving two angles (x,y) that we can use to visualise any qubit uniquely :param s: The state object depicting the qubit we want to visualise """ # Find the global phase to remove alpha = cmath.phase(s[0]) A = s[0].real/np.cos(alpha) # find the first angle theta = 2*math.acos(A) sinThetaTwo = np.sin(theta/2.0) # Use this to find the second if (np.isclose(sinThetaTwo,s[1])): # This means phi == 0 phi = 0.0 else: # Do some stuff to find phi beta = cmath.phase(s[1]) phi = beta - alpha # Convert these angles to a unit vector using spherical coordinates x = np.sin(theta)*np.cos(phi) y = np.sin(theta)*np.sin(phi) z = np.cos(theta) vec = [x, y, z] # Plot this on a bloch sphere b = qutip.Bloch() b.add_vectors(vec) b.show() b.clear() return
def plot_ST_bloch_sphere(self): mat = self.solver_obj.get_all_density_matrices()[:, 1:3, 1:3] k = np.linspace(0, len(mat) - 1, 100, dtype=np.int) b = qt.Bloch() b.xlabel = ['S', 'T'] b.ylabel = ['S+iT', 'S-iT'] b.zlabel = ['01', '10'] b.add_states(qt.Qobj(list(mat[0]))) b.add_states(qt.Qobj(list(mat[-1]))) x = [] y = [] z = [] for i in k: x.append(qt.expect(qt.sigmax(), qt.Qobj(list(mat[i])))) y.append(qt.expect(qt.sigmay(), qt.Qobj(list(mat[i])))) z.append(qt.expect(qt.sigmaz(), qt.Qobj(list(mat[i])))) b.add_points([x, y, z], meth='l') b.show()
def plot_trajectories(self, times, trajs, plot_title=''): ''' Plot output of a simulation result on the Bloch sphere ''' f = plt.figure(figsize=(5, 5), facecolor='white') f.suptitle(plot_title, x=0.2) # plt.title(plot_title) xp2 = qu.rx(np.pi * 0.5) yp2 = qu.ry(np.pi * 0.5) zp2 = qu.rz(np.pi * 0.5) xpi = qu.sigmax() ypi = qu.sigmay() zpi = qu.sigmaz() up = qu.basis(2, 0) dn = qu.basis(2, 1) # ax = f.add_subplot(1, 1, 1, axisbg='red') # p1 = f.add_subplot(2,2,1) # plt.plot(times,trajs[0]) # legend(['OneX','OneY','OneZ'],loc='best') # p2 = f.add_subplot(2,2,3) # pure = norm(trajs[0],axis=1) # plt.plot(times,pure) # legend(['Purity'],loc='best') # ylim(-0.1,1.1) # p3 = f.add_subplot(1,2,2, projection='3d') b = qu.Bloch(fig=f) #,axes=p3) b.zlabel = [r"$\left|1\right\rangle $", r"$\left|0\right\rangle$"] b.xlabel = [r"$ X $", r""] b.ylabel = [r"$ Y $", r""] b.vector_color = sb.color_palette() b.add_states([yp2 * up, xp2 * xpi * up, up]) b.point_color = sb.color_palette('dark')[3:4] b.add_points(trajs, 'l') # b.add_points(trajs[0][0].transpose(),'s') b.font_size = 30 b.sphere_color = '000000' b.render(f) b.show()
def plot_qubit_bloch_sphere(self, npoints=100, qubit=0, fig=None): ''' NOTE: function added to see single qubit occupations performs partial trace (discard one of the qubits) and shows single-qubit state on the bloch sphere npoints: resolution qubit: which qubit to show RWR: rotating wave representation (rotating frame for each qubit) ''' if (qubit == 1): mat = (self.solver_obj.get_all_density_matrices()[:, 0:2, 0:2] + self.solver_obj.get_all_density_matrices()[:, 2:4, 2:4]) elif (qubit == 0): mat = (self.solver_obj.get_all_density_matrices()[:, ::2, ::2] + self.solver_obj.get_all_density_matrices()[:, 1::2, 1::2]) else: print('ERROR: qubit has to be 0 or 1') return k = np.linspace(0, len(mat) - 1, npoints, dtype=np.int) b = qt.Bloch(fig=fig) b.xlabel = ['0+1', '0-1' ] # TODO: Verify/fix labels according to used convention b.ylabel = ['0+i1', '0-i1'] b.zlabel = ['0', '1'] b.add_states(qt.Qobj(list(mat[0]))) b.add_states(qt.Qobj(list(mat[-1]))) x = [] y = [] z = [] for i in k: x.append(qt.expect(qt.sigmax(), qt.Qobj(list(mat[i])))) y.append(qt.expect(qt.sigmay(), qt.Qobj(list(mat[i])))) z.append(qt.expect(qt.sigmaz(), qt.Qobj(list(mat[i])))) b.add_points([x, y, z], meth='l') b.show()
## create an up bit: up = (q.Qobj([[1 + 1j], [-1j]])).unit() ## add a magnetic field Hamiltonian: t = np.linspace(0, 100, 1000) H_constants = 1 H = H_constants / 2 * q.sigmaz() res = q.mesolve(H, up, t) figr, ax = plt.subplots() ax = Axes3D(fig=figr) #, animated = True) sphere = q.Bloch(axes=ax, fig=figr) sphere.render(fig=figr, axes=ax) sphere.add_states(up) # sphere.show() plt.pause(0.1) for i in range(len(res.states)): sphere.clear() sphere.add_states(res.states[i]) sphere.make_sphere() plt.pause(0.01) def ini(): sphere.vector_color = ("r") return ax
# %% import qutip as qt from plot_helpers import tp_to_uvw # %% X_low = rev_angle_embedding(X_test[E_pred>0], 2) y_low = rev_angle_embedding(y_test[E_pred>0], 2, reshape=True) theta_low = X_low[:, 0] phi_low = X_low[:, 2] drives = tp_to_uvw(theta_low, phi_low) trans = tp_to_uvw(y_low[:3, 0], y_low[:3, 2]) trans_prime = tp_to_uvw(y_low[:3, 1], y_low[:3, 3]) # %% b = qt.Bloch() b.add_points(drives) # b.add_points(trans) # b.add_points(trans_prime) b.show() # %% X.shape y.shape # %% plt.plot(range(50), X[:50, 0], label='Theta Drive') plt.plot(range(50), X[:50, 2], label='Phi Drive') plt.plot(range(50), y[:50, 0], label='Theta trans') plt.plot(range(50), y[:50, 2], label='Phi trans') plt.plot(range(50), y[:50, 1], label='Theta trans') plt.plot(range(50), y[:50, 3], label='Phi trans')
def __init__(self): self.dm0 = qt.ket2dm(qt.basis(2, 0)) self.dm1 = qt.ket2dm(qt.basis(2, 1)) self.bloch = qt.Bloch(view=fig_params['view'])
import qutip import numpy as np from numpy import cos, sin # b = qutip.Bloch() # b.frame_color = 'grey' # init_vector = [-0.75, 0.25, 0.5] # # b.add_vectors(init_vector) # # # b.show() b = qutip.Bloch() b.point_color = ['g'] b.frame_color = 'grey' x0 = -0.5 y0 = 0.7 z0 = 0.5 init_vector = [x0, y0, z0] final_vector = [x0, -z0, y0] pts = 30 xp = [x0] * pts yp = [ y0 * cos(theta) + sin(theta) * -z0 for theta in np.linspace(0, np.pi / 2, pts) ] zp = [ z0 * cos(theta) + sin(theta) * y0 for theta in np.linspace(0, np.pi / 2, pts)
def plot_bloch_vector_evolution(forward_propagators: Sequence[OperatorMatrix], initial_state: OperatorMatrix, return_bloch: bool = False, **bloch_kwargs): """ Plots the evolution of the forward propagators of the initial state on the bloch sphere. Parameters ---------- forward_propagators: list of DenseOperators The forward propagators whose evolution shall be plotted on the Bloch sphere. initial_state: DenseOperator The initial state aka. beginning point of the plotting. return_bloch: bool, optional If True, the Bloch sphere is returned as object. bloch_kwargs: dict, optional Plotting parameters for the Bloch sphere. Returns ------- bloch_sphere: Only returned if return_bloch is set to true. """ try: import qutip as qt except ImportError as err: raise RuntimeError( 'Requirements not fulfilled. Please install Qutip') from err if not forward_propagators[0].shape[0] == 2: raise ValueError('Plotting Bloch sphere evolution only implemented ' 'for one-qubit case!') figsize = bloch_kwargs.pop('figsize', [5, 5]) view = bloch_kwargs.pop('view', [-60, 30]) fig = plt.figure(figsize=figsize) axes = mplot3d.Axes3D(fig, azim=view[0], elev=view[1]) bloch_kwargs.setdefault('view', [-150, 30]) b = qt.Bloch(fig=fig, axes=axes, **bloch_kwargs) # https://github.com/qutip/qutip/issues/1385 if hasattr(b.axes, 'set_box_aspect'): b.axes.set_box_aspect([1, 1, 1]) b.xlabel = [r'$|+\rangle$', ''] b.ylabel = [r'$|+_i\rangle$', ''] states = [ qt.Qobj((prop * initial_state).data) for prop in forward_propagators ] a = np.empty((3, len(states))) x, y, z = qt.sigmax(), qt.sigmay(), qt.sigmaz() for i, state in enumerate(states): a[:, i] = [qt.expect(x, state), qt.expect(y, state), qt.expect(z, state)] b.add_points(a.real, meth='l') b.make_sphere() if return_bloch: return b
def draw_bloch_sphere(self): """draw the qubit bloch sphere for the system steady states""" self.rhos_qb_ss = [rho.ptrace(1) for rho in self.rhos_ss] self.b_sphere = qt.Bloch() self.b_sphere.add_states(self.rhos_qb_ss) self.b_sphere.show()
def main(): # set up initial circuit params = [1.2, 2.9, 0.1] symbols = [sympy.Symbol(f"x{i}") for i in range(1,4)] q = cirq.LineQubit(0) circuit = cirq.Circuit.from_ops( cirq.Rx(np.pi/4)(q), cirq.Ry(symbols[0])(q), cirq.Rx(symbols[1])(q), cirq.Rz(symbols[2])(q)) # initialize the current state and target state current_state = None truth = np.array([0.149 + 0.238j, -0.745 - 0.607j]) truth = truth / np.linalg.norm(truth) current_loss = 1 # Bloch sphere and color palette rdbu = cm.get_cmap('bwr', 100) b = qutip.Bloch() b.sphere_color = "#ffffff" b.point_color = [1] b.xlabel = [r'$|$+$x\rangle$',''] b.ylabel = [r'$|$+$y\rangle$',''] b.show() # HACK - cycle through a showing to generate `axes` member # cache points and their color points_cache = [] colors_cache = [] # main routine: system('clear') print("Welcome. Prepare to optimize a PQC.") print("\tRed colors mean you're approaching the optimum") print("\tBlue colors mean you're moving away from the optimum") for k in range(3000): # 0) reset Bloch sphere and stage plotting of points cache # Plot current state as black, previous ones according to heatmap b.clear() b.vector_color = ["#000000"] + colors_cache # 1) Get user input for parameters print("Iteration {}".format(k + 1)) print("Pick the parameters to try this iteration:") params = [] i = 1 while len(params) < 4: try: params.append(float(input("Enter value for x{}: ".format(i)))) i += 1 except ValueError: print("Invalid input. Enter parameters again") params = [] i = 1 continue except KeyboardInterrupt: sys.exit() # be sneaky and make one parameter do nothing params = params[:2] + [params[3]] # 2) Simulate the new state current_state = cirq.Simulator().simulate( circuit, param_resolver=dict(zip(symbols, params))).final_state # color the vector and new point based on how well we guessed current_loss = cost_function(current_state, truth) current_vec = state_array_to_qobj(current_state) b.add_states(current_vec) b.add_states(points_cache) print("Current loss: {} \n".format(current_loss)) # qutip's garbage mpl interface prevents fig management with gca() b.show() # 3) stage points cache for _next_ iteration points_cache.append(current_vec) colors_cache.append(colors.to_hex(rdbu(current_loss), keep_alpha=False))
import qutip as q import matplotlib.pyplot as plt b = q.Bloch() up = q.basis(2,0) down = 4*q.basis(2,1) phi = (up * down.dag()) phi = phi.unit() b.add_states(up) b.show() #plt.show() a = input('\n')
H = -delta / 2.0 * qt.sigmax() - eps0 / 2.0 * qt.sigmaz() def ohmic_spectrum(w): if w == 0.0: # dephasing inducing noise return gamma1 else: # relaxation inducing noise return gamma1 / 2 * (w / (2 * np.pi)) * (w > 0.0) R, ekets = qt.bloch_redfield_tensor(H, [qt.sigmax()], [ohmic_spectrum]) """ Last part """ tlist = np.linspace(0, 15.0, 1000) psi0 = qt.rand_ket(2) e_ops = [qt.sigmax(), qt.sigmay(), qt.sigmaz()] expt_list = qt.bloch_redfield_solve(R, ekets, psi0, tlist, e_ops) sphere = qt.Bloch() sphere.add_points([expt_list[0], expt_list[1], expt_list[2]]) sphere.vector_color = ['r'] sphere.add_vectors(np.array([delta, 0, eps0]) / np.sqrt(delta**2 + eps0**2)) sphere.make_sphere() plt.show() logger.info('You have been terminated')
def qtbloch(self, statelist): '''Description: for use in visualising on Bloch sphere using Qutip''' a = qt.Bloch() for i in range(len(statelist)): a.add_states(statelist[i]) return a.show()
from skc.operator import * from skc.dawson.factor import * from skc.dawson import * from skc.compose import * from skc.basis import * from skc.simplify import * import skc.utils import math import qutip as qp import cmath b = qp.Bloch() b.vector_color = ['k','r'] H2 = get_hermitian_basis(d=2) theta = math.pi / 4 # 45 degrees axis = cart3d_to_h2(x=1, y=1, z=1) print "Identity Name: " + H2.identity.name theta_z = -5./16.*cmath.pi theta_y = -cmath.pi/6. #promising: -cmath.pi/6. #print "test", numpy.exp(-1j*theta_z/2.) # Compose a unitary to compile #matrix_U = axis_to_unitary(axis, theta, H2) #z-rotation: #matrix_U = matrixify([[numpy.exp(-1j * theta_z/ 2),0], [0,numpy.exp(1j * theta_z/ 2)]]) #y-rotation: matrix_U = matrixify([[numpy.cos(theta_y/ 2),-numpy.sin(theta_y/ 2)], [numpy.sin(theta_y/ 2),numpy.cos(theta_y/ 2)]]) #matrix_U = matrixify([[numpy.exp(-1j*theta_z/2),0.0], [0.0,numpy.exp(-1j*theta_z/2)]]) op_U = Operator(name="U", matrix=matrix_U)
# Show the legend, add axis titles ax.set_xlabel('Time, $t / \\frac{1}{\\omega}$') ax.set_ylabel( 'Expecation value of $\\sigma$, $\\langle\\sigma\\rangle / \\frac{\hbar}{2}$' ) ax.legend(loc='best', frameon=True, fancybox=True) # Save the plot fig.savefig('exp_sigma.pdf', filetype='pdf', bbox_inches='tight') plt.close() # Next we plot four steps in the rotation of the Bloch vector # using the functionality provided by the qutip library n_tsteps_one_oscillation = 32 sphere = qutip.Bloch() sphere.sphere_alpha = 0.0 sphere.vector_color = seaborn.color_palette('husl', n_colors=n_tsteps_one_oscillation) # Mark the initial Bloch vector for reference a_0 = [exp_sigmax[0], exp_sigmay[0], exp_sigmaz[0]] sphere.add_points(a_0) # Mark the next Bloch vector for reference of direction of motion a_1 = [exp_sigmax[1], exp_sigmay[1], exp_sigmaz[1]] sphere.add_points(a_1) sphere.add_states(psi_t.states[:n_tsteps_one_oscillation]) sphere.make_sphere() plt.savefig('bloch.pdf', filetype='pdf', bbox_inches='tight')