def plot_wigners(rho_list): if len(rho_list) > 1: fig, ax = subplots(1, len(rho_list), figsize=(17, 6)) for j, rho in enumerate(rho_list): xvec = linspace(-sqrt(rho.dims[0][0]), sqrt(rho.dims[0][0]), 100) ax[j].contourf(xvec, xvec, qt.wigner(rho, xvec, xvec), 100, norm=clr.Normalize(-0.25, 0.25), cmap=get_cmap("RdBu")) ax[j].set_aspect("equal") ax[j].tick_params(labelsize=14) ax[j].set_xlabel(r"$x$", fontsize=14) ax[j].set_ylabel(r"$p$", fontsize=14) else: rho = rho_list[0] xvec = linspace(-sqrt(rho.dims[0][0]), sqrt(rho.dims[0][0]), 100) contourf(xvec, xvec, qt.wigner(rho, xvec, xvec), 100, norm=clr.Normalize(-0.25, 0.25), cmap=get_cmap("RdBu")) gca().set_aspect("equal") tick_params(labelsize=14) xlabel(r"$x$", fontsize=14) ylabel(r"$p$", fontsize=14)
def draw_Wigner(self, list_states, title=None): #title is a string for ii in range(self.n_t): if ii % self.spacing == 0 and ii // self.spacing < self.nbWigner + 1: if (self.syst <= -1): # Only one Cat wig = qt.wigner(list_states[ii], self.space_size, self.space_size, g=2) else: # Two cats or more wig = qt.wigner(list_states[ii].ptrace(self.syst), self.space_size, self.space_size, g=2) self.listeWigner.append(wig) for ii in range(len(self.listeWigner)): self.axes[ii // self.nbCols, ii % self.nbCols].pcolor(self.space_size, self.space_size, self.listeWigner[ii], cmap='bwr', vmin=[-2 / np.pi, 2 / np.pi]) self.axes[ii // self.nbCols, ii % self.nbCols].set_aspect('equal') if title is None: pass else: self.fig.suptitle(title)
def plot_wigners( self, target_state=None, actual_state=None, sel=None, cmap="RdBu", disp_range=(-5, 5, 201), ): """Plots the Wigner function of the final state and the target state. Args: target_state (optional, qutip.Qobj): State to which to compare the final state. Defaults to``target_unitary * init_state``. actual_state (optional, qutip.Qobj): State to compare the target_state. Defaults to ``self.mesolve_state``. sel (optional, int or list[int]): Indices of modes to keep when taking the partial trace of the target and actual states. If None, no partial trace is taken. Default: None. cmap (optional, str): Name of the matplotlib colormap to use. Default: 'RdBu' disp_range (tuple[float, float, int]): Range of displacements to use when compouting the Wigner function, specified as (start, stop, num_steps). Default: (-5, 5, 201). Returns: tuple: matplotlib Figure and Axis. """ if self.mesolve_state is None: return target_state = target_state or self.target_state actual_state = actual_state or self.mesolve_state if sel is not None: target_state = target_state.ptrace(sel) actual_state = actual_state.ptrace(sel) xs = ys = np.linspace(*disp_range) w = qutip.wigner(actual_state, xs, ys) w0 = qutip.wigner(target_state, xs, ys) clim = max(abs(w.min()), abs(w.max()), abs(w0.min()), abs(w0.max())) norm = plt.Normalize(-clim, clim) fig, axes = plt.subplots(1, 2, sharex=True, sharey=True) labels = ["target state", "mesolve state"] for ax, wigner, title in zip(axes, [w0, w], labels): im = ax.pcolormesh(xs, ys, wigner, cmap=cmap, norm=norm, shading="auto") ax.set_aspect("equal") ax.set_title(title) ax.set_xlabel(r"Re[$\alpha$]") ax.set_ylabel(r"Im[$\alpha$]") fig.colorbar(im, ax=axes, orientation="horizontal") fig.suptitle(f"{self.seq.system.name} Wigner") return fig, axes
def plot_wigner_all_states(): stabilizers, paulis, states, displacements = \ hf.GKP_state(False,100, np.array([[1,0],[0,1]])) fig, axes = plt.subplots(2, 3, sharex=True, sharey=True, figsize=(6, 6)) for i, s1 in zip([0, 1], ['+', '-']): for j, s2 in zip([0, 1, 2], ['X', 'Y', 'Z']): state = states[s2 + s1] xvec = np.linspace(-7, 7, 201) W = qt.wigner(state, xvec, xvec, g=sqrt(2)) ax = axes[i, j] ax.grid(linestyle='--', zorder=2) lim = 3.5 ax.set_xlim(-lim, lim) ax.set_ylim(-lim, lim) ticks = [-2, -1, 0, 1, 2] ax.set_xticks(ticks) ax.set_yticks(ticks) # ax.set_title(s2+s1) ax.set_aspect('equal') p = ax.pcolormesh(xvec / sqrt(pi), xvec / sqrt(pi), W, cmap='RdBu_r', vmin=-1 / pi, vmax=+1 / pi) # cbar = fig.colorbar(p, ax=ax, ticks=[-1/pi,0,1/pi]) # cbar.ax.set_yticklabels([r'$-\frac{1}{\pi}$','0',r'$+\frac{1}{\pi}$']) # axes[1,1].set_xlabel(r'$q/\sqrt{\pi}$') # axes[1,0].set_ylabel(r'$p/\sqrt{\pi}$') plt.tight_layout()
def updatefig(i): psi = sol.states[i] data = qt.wigner(psi, xvec, xvec) data = np.sum(data, axis=0) data /= np.sum(data) line.set_ydata(data) return line,
def plot(psi, borders, num=300): start, end = borders xvec = np.linspace(start, end, num) X, Y = np.meshgrid(xvec, xvec) W = qt.wigner(psi, xvec, xvec) fig = plt.figure() ax = Axes3D(fig, azim=-62.5, elev=25) ax.plot_surface(X, Y, W, rstride=2, cstride=2, cmap=cm.jet, lw=.1) #ax.set_xlim3d(-9,9) #ax.set_xlim3d(-9,9) #ax.set_zlim3d(-.2,0.2) # plt.margins(0,0) ax.set_axis_off() # ax.set_frame_on('false') # title(r'$| \psi >= \frac{1}{\sqrt{2}}(|\alpha>-|-\alpha>)$'+r' $\alpha=$'+str(round(x,2))) # savefig("cat_state_"+str(k)+".png") ##setup constants: #N = 20 # size of the Hilbert space #a = qt.destroy(N) #annihilation operator #alpha = 2 #psi=(qt.displace(N,alpha) * qt.basis(N,0) - qt.displace(N,-1*alpha) * qt.basis(N,0)).unit() # #plot(psi, [-6,6])
def qps(self): self.qps = [] for rho in self.density_matrix_list: if self.functype != "Q": self.qps.append(qt.wigner(rho, self.xvec, self.yvec)) else: self.qps.append(qt.qfunc(rho, self.xvec, self.yvec)) return self.qps
def qps(self): self.qps = [] for rho in self.density_matrix_list: if self.functype != 'Q': self.qps.append(qt.wigner(rho, self.xvec, self.yvec)) else: self.qps.append(qt.qfunc(rho, self.xvec, self.yvec)) return self.qps
def plot_max_W_func(kappa_arr, nbar_omega, rho_arr, axes): xvec = np.linspace(-7, 7, 200) max_pts = [] for i, rho in enumerate(rho_arr): # get wigner func W = qutip.wigner(rho.states[tN - 1], xvec, xvec) max_pts.append(xvec[np.argmax(W[W.shape[0]/2])]) axes.plot(kappa_arr, np.absolute(max_pts), '--b*') axes.set_xlabel("$\kappa$") axes.set_ylabel("Radius of Wigner Function") axes.set_title("$nbar(\omega)=%f$" % nbar_omega)
def updatefig(i): psi = sol.states[i] data = qt.wigner(psi, xvec, xvec) im.set_array(data) X = list(range(i)) Y = qt.expect(x, sol.states[:i]) line.set_data(X, Y) ax[1].set_xlim((0, i)) ax[1].set_ylim((0, N)) # ax.plot(qt.expect(x,sol.states),qt.expect(p,sol.states)) return im, line
def plot_wigner(rho, ax=None, cmap="RdBu", cbar=False): if ax == None: f, ax = subplots() xvec = linspace(-sqrt(rho.dims[0][0]), sqrt(rho.dims[0][0]), 100) wigner_mat = qt.wigner(rho, xvec, xvec) vmax = wigner_mat.max() # #vmax = ceil(2*wigner_mat.max())/2 handle = ax.contourf(xvec, xvec, qt.wigner(rho, xvec, xvec), 100, vmax=vmax, vmin=-vmax, cmap=get_cmap("RdBu")) #ax.contour(xvec, xvec, qt.wigner(rho,xvec,xvec), 10, vmax = vmax, vmin = -vmax, colors='k', alpha=0.1) ax.set_aspect("equal") ax.tick_params(labelsize=14) ax.set_xlabel(r"$x$", fontsize=14) ax.set_ylabel(r"$p$", fontsize=14) if cbar: colorbar(handle) return ax
def plot_wigner(state, tensorstate, cmap='seismic', title=None, savepath=None): if tensorstate: state = qt.ptrace(state, 1) xvec = np.linspace(-7,7,81) W = qt.wigner(state, xvec, xvec, g=sqrt(2)) fig, ax = plt.subplots(figsize=(6,5)) # p = ax.pcolormesh(xvec, xvec, W, cmap=cmap, vmin=-1, vmax=+1) #'RdBu_r' # ax.plot([sqrt(pi), sqrt(pi)/2, 0, 0], [0, 0, sqrt(pi), sqrt(pi)/2], # linestyle='none', marker='.',color='black') p = ax.pcolormesh(xvec/sqrt(pi), xvec/sqrt(pi), W, cmap=cmap, vmin=-1, vmax=+1) #'RdBu_r' ax.plot([1, 1/2, 0, 0], [0, 0, 1, 1/2], linestyle='none', marker='.',color='black') fig.colorbar(p, ax=ax) plt.grid() if title: ax.set_title(title) if savepath: plt.savefig(savepath)
def plot_states(n=20): xvec = np.linspace(-3., 3., 200) coherent_state = qutip.Qobj(oat_state(n, 0)) # squeezed_state_1 = qutip.Qobj(oat_state(n, optimal_theta(n))) # squeezed_state_2 = qutip.Qobj(oat_state(n, optimal_theta_review(n))) wigner_coherent = wigner(coherent_state, xvec, xvec) # wigner_squeezed_1 = wigner(squeezed_state_1, xvec, xvec) # wigner_squeezed_2 = wigner(squeezed_state_2, xvec, xvec) fig, axes = plt.subplots(1, 1, figsize=(7, 7)) axes.contourf(xvec, xvec, wigner_coherent, 100, cmap=cm.Purples) # axes.set_title("Coherent state") # axes[1].contourf(xvec, xvec, wigner_squeezed_1, 100) # axes[1].set_title("Squeezed state") # axes[2].contourf(xvec, xvec, wigner_squeezed_2, 100) # axes[2].set_title("Squeezed state") plt.show()
def cond_wigs(state, xs): mat = state.data.todense().reshape(state.dims[0]) mat = mat[:2, :] q_vecs_t, coefs, c_vecs = svd(mat, full_matrices=False) q_vecs = q_vecs_t.T assert len(q_vecs) == len(c_vecs) == 2, (c_vecs.shape, q_vecs.shape) c_vecs = np.diag(coefs).dot(c_vecs) q_vecs = list(map(qutip.Qobj, q_vecs)) c_vecs = list(map(qutip.Qobj, c_vecs)) # assert q.tensor(q_vecs[0], c_vecs[0]) + q.tensor(q_vecs[1], c_vecs[1]) == state paulis = [qutip.qeye(2), qutip.sigmax(), qutip.sigmay(), qutip.sigmaz()] wigs = [] for q_op in paulis: wig = 0 for j in range(2): wig += (q_vecs[j].dag() * q_op * q_vecs[j])[0,0] * qutip.wigner(c_vecs[j] * c_vecs[j].dag(), xs, xs, g=2) od_coef = (q_vecs[0].dag() * q_op * q_vecs[1])[0,0] od_wig = wig_imag(c_vecs[0] * c_vecs[1].dag(), xs, xs, g=2) wig += od_coef * od_wig wig += od_coef.conj() * od_wig.conj() wigs.append(wig.real) return wigs
def wigner_comp(rho, xvec, yvec): """calculate wigner function of central site from density matrix rho at a grid of points defined by xvec and yvec""" global convert_rho from operators import expect, vector_to_operator from qutip import Qobj, wigner, ptrace from basis import ldim_p, ldim_s rho_small = convert_rho.dot(rho) rho_small = vector_to_operator(rho_small) rho_q = Qobj() rho_q.data = rho_small rho_q.dims = [[ldim_p, ldim_s], [ldim_p, ldim_s]] rho_q = ptrace(rho_q, 0) w = wigner(rho_q, xvec, yvec) return w
def ratio_calc(state, n_bins=100, return_peaks=False, min_dist=10, ranges=[[40, 60], [45, 75]]): xvec = np.linspace(-15, 15, n_bins) W = np.abs(wigner(state, xvec, xvec, g=2)) if ranges is not None: W[ranges[0][0]:ranges[0][1], ranges[1][0]:ranges[1][1]] = 0 peak_indices = maximum_finder(W) peak_heights = np.array([W[peak_indices[0][idx], peak_indices[1][idx]] for idx in range(len(peak_indices[0]))]) peaks = pd.DataFrame(np.array([peak_indices[0], peak_indices[1], peak_heights]).T, columns=['i', 'j', 'height']) dtypes = {'i': int, 'j': int, 'height': float} peaks = peaks.astype(dtypes) peaks.sort_values(by='height', axis=0, ascending=False, inplace=True) i_diff = peaks.iloc[0].i - peaks.iloc[1].i j_diff = peaks.iloc[0].j - peaks.iloc[1].j dist = np.sqrt(i_diff ** 2 + j_diff ** 2) if dist < min_dist: index = peaks.index[1] peaks.drop(index=index, inplace=True) ratio = peaks['height'].iloc[1] / peaks['height'].iloc[0] if return_peaks: return ratio, peaks else: return ratio
def render(axes, state, fidelities_mean, fidelities_std, last_actions_mean, n_store_mean, n_store_std): global dim trange = np.arange(parameters_para.max_episode_steps) x, y = state # clear axis of plot axes[0].cla() axes[1].cla() axes[2].cla() axes[3].cla() axes[4].cla() # plot the Fock distribution (maybe add -0.5 as in the qutip tutorial) plt1 = axes[0].bar(np.arange(0, dim), x**2 + y**2, color='orange') axes[0].set_xlim([0 - 0.5, dim - 0.5]) axes[0].set_ylim([0, 1.0]) # plot the Wigner function graph xvec = np.linspace(-6, 6, 20) psi_f = qu.Qobj(x[:] + 1j * y[:]) W = qu.wigner(psi_f, xvec, xvec) wmap = qu.wigner_cmap(W) # Generate Wigner colormap wlim = abs(W).max() cmap = cm.get_cmap('RdBu') plt2 = axes[1].contourf(xvec, xvec, W, 20, norm=mpl.colors.Normalize(-wlim, wlim), cmap=cmap) plt3 = axes[2].plot(trange, last_actions_mean[0], color='blue', label='x controls') # plt3 = axes[2].plot(trange, last_actions_mean[1], color='red', label='y controls') axes[2].set_xlim(0, parameters_para.max_episode_steps) # axes[2].set_ylim(-parameters_para.force_mag, parameters_para.force_mag) plt5 = axes[3].plot(trange, fidelities_mean, color='red') axes[3].fill_between(trange, fidelities_mean - fidelities_std, fidelities_mean + fidelities_std, alpha=0.5) axes[3].set_xlim(0, parameters_para.max_episode_steps) axes[3].set_ylim(0.0, 1.0) plt6 = axes[4].plot(trange, n_store_mean, color='black') axes[4].fill_between(trange, n_store_mean - n_store_std, n_store_mean + n_store_std, alpha=0.3, color='black') axes[4].set_xlim(0, parameters_para.max_episode_steps) # axes[4].set_ylim(0.0, 1.0) axes[0].set_title(r'$|C|^2$') axes[1].set_title("Wigner") axes[2].set_title("u_x") axes[3].set_title("Fidelities") axes[4].set_title("<n>")
''' Cavity A occupation ''' pl.subplot(4, num_steps, i + 1 + num_steps) pl.plot(range(N), result.states[i].ptrace(1).diag()) pl.title('Cavity B occupation') pl.savefig(plot_filepath + 'Occupation.png') pl.clf() num_points = 40 xvec_2d = np.linspace(-4, 4, num_points) fig = pl.figure(figsize=(2.5 * num_steps, 10)) for i in range(num_steps): ''' Cavity A wigner ''' pl.subplot(4, num_steps, i + 1) W = qt.wigner(result.states[i].ptrace(0), xvec_2d, xvec_2d) * np.pi pl.contourf(xvec_2d, xvec_2d, W, np.linspace(-1.0, 1.0, 41, endpoint=True), cmap=mpl.cm.RdBu_r) pl.title('Cavity A wigner') pl.colorbar(ticks=np.linspace(-1.0, 1.0, 11, endpoint=True)) ''' Cavity B wigner ''' pl.subplot(4, num_steps, i + 1 + num_steps) W = qt.wigner(result.states[i].ptrace(1), xvec_2d, xvec_2d) * np.pi pl.contourf(xvec_2d, xvec_2d, W, np.linspace(-1.0, 1.0, 41, endpoint=True), cmap=mpl.cm.RdBu_r)
def Plot_W(rho, res, qmax, name_plot, name, smoothing=False, smooth_center=0, smooth_rad=0, smooth_asymmetry=1, showfig=True): xvec = np.linspace(-qmax, qmax, res) W = qt.wigner(rho, xvec, xvec, 'clenshaw') Pq = integrate.simps(W, axis=0) Pp = integrate.simps(W, axis=1) if smoothing: ##smoothing the cutoff-error for i in range(res): for j in range(res): if np.sqrt( (xvec[i] / smooth_asymmetry - np.real(smooth_center))**2 + (smooth_asymmetry * xvec[j] - np.imag(smooth_center))**2) >= smooth_rad: W[i, j] = 0 gs = gridspec.GridSpec(2, 2, width_ratios=[4, 1], height_ratios=[1, 4]) ax1 = plt.subplot(gs[0]) ax2 = plt.subplot(gs[1]) ax3 = plt.subplot(gs[2]) ax4 = plt.subplot(gs[3]) cs = ax3.contourf(xvec, xvec, W, 100, cmap='RdBu_r') ax3.set_xlabel(r'$q/\sqrt{\pi}$', fontsize=15) ax3.set_ylabel(r'$p/\sqrt{\pi}$', fontsize=15) tick_max = np.floor(qmax / np.sqrt(np.pi)) tick_num = np.arange(-tick_max, tick_max + 1, 1) ticks = tick_num * np.sqrt(np.pi) tick_lab = [int(x) for x in tick_num] ax3.set_xticks(ticks) ax3.set_xticklabels(tick_lab) ax3.set_yticks(ticks) ax3.set_yticklabels(tick_lab) ax1.plot(xvec, Pq) ax1.set_ylabel(r'$P(q)$', fontsize=15) ax1.set_xticks([], []) ax1.set_yticks([], []) ax4.set_xticks([], []) ax4.set_yticks([], []) ax4.plot(Pp, xvec) ax4.set_xlabel(r'$P(p)$', fontsize=15) ax2.text(0.5, 0.5, name_plot, horizontalalignment='center', verticalalignment='center', fontsize=20, color='black') ax2.set_axis_off() if showfig == True: plt.show() else: plt.savefig('Wigner_%s.png' % (name)) plt.clf() plt.cla()
import qutip as qt import matplotlib.animation as animation N = 30 m = 1 w = 1 a = qt.destroy(N) H = a.dag() * a psi0 = (qt.fock(N, 0) + qt.fock(N, 1)) / np.sqrt(2) psi0 = qt.coherent(N, 3) - qt.coherent(N, -3) time = np.linspace(0, 30, 1000) sol = qt.mesolve(H, psi0, time, [], []) fig, ax = plt.subplots() xvec = np.linspace(-5, 5, 100) data = np.sum(qt.wigner(psi0, xvec, xvec), axis=0) data /= np.sum(data) line, = ax.plot(xvec, data) ax.set_ylim((0, 0.1)) def updatefig(i): psi = sol.states[i] data = qt.wigner(psi, xvec, xvec) data = np.sum(data, axis=0) data /= np.sum(data) line.set_ydata(data) return line, ani = animation.FuncAnimation(fig, updatefig, interval=1, blit=False)
res = qt.mesolve([ H, ], psi_plus, tlist, cops, e_ops=eops) # Display wigner at 10 equally spaced times during the dynamics if wigner: xvec = np.linspace(-4, 4, 51) # wigner space size n_wig = 10 spacing = n_t // n_wig fig, ax = plt.subplots(2, 5, figsize=(12, 8)) print('Compute and plot wigners') wigs = [] for ii in range(n_t): if ii % spacing == 0 and ii // spacing < n_wig: wig = qt.wigner(res.states[ii], xvec, xvec, g=2) wigs.append(wig) for ii in range(len(wigs)): ax[ii // 5, ii % 5].pcolor(xvec, xvec, wigs[ii], cmap='bwr', vmin=[-2 / np.pi, 2 / np.pi]) ax[ii // 5, ii % 5].set_aspect('equal') # Display various quantities versus time p_t = [] # parity versus time a_t = [] # average of a versus time na_t = [] # average photon number versus time
if 1: chiaa = 0 chirr = 0 g = 1 psi0 = (qt.tensor(qt.coherent(N, 0), qt.coherent(N,0))).unit() opts = qt.Options(store_states=True, nsteps=100000) num_steps=5 times = np.linspace(0.0, 5, num_steps) xvec = np.linspace(-5, 5, 51) args = {'w_r':wr} H = [wa*a.dag()*a + wr*r.dag()*r + chirr*r.dag()**2*r**2 + chiaa*a.dag()**2*a**2 + g*(r.dag()*a**2+r*a.dag()**2), [drive*(r.dag()+r), exp_t]] result = qt.mesolve(H, psi0, times, kappar*r, [], options=opts, progress_bar = True, args=args) fig = pl.figure(figsize=(2 * num_steps, 4)) for i in range(num_steps): pl.subplot(2, num_steps, i+1) W1 = qt.wigner((result.states[i].ptrace(0)).unit(), xvec, xvec) pl.contourf(xvec, xvec, W1, np.linspace(-1, 1, 41, endpoint=True), cmap=mpl.cm.RdBu_r) pl.subplot(2, num_steps, i+1 + num_steps) W2 = qt.wigner((result.states[i].ptrace(1)).unit(), xvec, xvec) pl.contourf(xvec, xvec, W2, np.linspace(-1, 1, 41, endpoint=True), cmap=mpl.cm.RdBu_r)
state_final = run_operator(state_init, QI_a, QQ_a, QI_c, QQ_c, show_fid_graph=True) print("- Final fidelity:", str(qt.fidelity(state_target, state_final) * 100)[0:9] + "%") bl.add_states(qt.ptrace(state_init, 0)) bl.add_states(qt.ptrace(state_final, 0)) bl.show() xvec = np.linspace(-5, 5, 500) W_init = qt.wigner(qt.ptrace(state_init, 1), xvec, xvec) W_final = qt.wigner(qt.ptrace(state_final, 1), xvec, xvec) W_target = qt.wigner(qt.ptrace(state_target * state_init, 1), xvec, xvec) fig, axes = plt.subplots(1, 3) axes[0].contourf(xvec, xvec, W_init, 100) axes[0].set_title("Initial") axes[1].contourf(xvec, xvec, W_final, 100) axes[1].set_title("Final") axes[2].contourf(xvec, xvec, W_target, 100) axes[2].set_title("Target") fig.tight_layout()
def make_plots(plot_num, num_steps, result, psi0, psi_final, N, plot_filepath): start_fidelity = np.zeros(num_steps) final_fidelity = np.zeros_like(start_fidelity) for i in range(num_steps): start_fidelity[i] = round(qt.fidelity(result.states[i], psi0), 4) final_fidelity[i] = round(qt.fidelity(result.states[i], psi_final), 4) fit_start = 20 y_fit = final_fidelity[fit_start:] x_fit = times[fit_start:] ''' Fidelity with starting cat state ''' fig = pl.figure(figsize=(10, 15)) pl.subplot(3, 1, 1) pl.plot(times, start_fidelity, '.') pl.title('Fidelity with starting cat state') ''' Fidelity with final cat state ''' pl.subplot(3, 1, 2) pl.plot(times, final_fidelity, '.') try: popt, pcov = curve_fit(lambda x_fit, a_fit, b_fit, c_fit: a_fit * np. exp(b_fit * x_fit) + c_fit, x_fit, y_fit, p0=(-1, -.1, 0)) a_fit, b_fit, c_fit = popt print(a_fit, b_fit, c_fit) pl.plot(x_fit, a_fit * np.exp(b_fit * x_fit) + c_fit) pl.title(str(a_fit) + ',' + str(b_fit) + ',' + str(c_fit)) except: print('fit didnt work') p = (1j * np.pi * (a.dag() * a + b.dag() * b)).expm() parity = np.zeros(num_steps) for i in range(num_steps): parity[i] = round(qt.expect(p, result.states[i]), 4) pl.subplot(3, 1, 3) pl.plot(times, parity) pl.title('joint parity') pl.savefig(plot_filepath + 'Fidelity' + str(plot_num) + '.png') pl.clf() np.savetxt(plot_filepath + 'fidelity' + str(plot_num) + '.txt', [times, final_fidelity]) print('building cat array') beta_steps = 50 cat_state_arr = [] alpha_max = np.sqrt(-2j * lam.conjugate()) beta_arr = np.linspace(0, alpha_max, beta_steps) for j in range(beta_steps): alpha = alpha_max - beta_arr[j] beta = beta_arr[j] cat_state_arr.append( (np.round(np.cos(theta / 2), 5) * qt.tensor(qt.coherent(N, alpha), qt.coherent(N, beta)) + np.round(np.sin(theta / 2), 5) * np.exp(1j * phi) * qt.tensor(qt.coherent(N, -alpha), qt.coherent(N, -beta))).unit()) print('calculating 2d fidelity') fidelity_arr = np.zeros((num_steps, beta_steps)) for i in range(num_steps): print(i) for j in range(beta_steps): fidelity_arr[i][j] = round( qt.fidelity(result.states[i], cat_state_arr[j]), 4) pl.subplot(3, 1, 1) pl.imshow(fidelity_arr.transpose(), extent=(0, max_time, beta_arr[-1], beta_arr[0])) pl.colorbar() pl.ylabel('beta') pl.subplot(3, 1, 2) pl.plot(times, beta_arr[np.argmax(fidelity_arr, axis=1)] / alpha_max, label='current state') pl.plot(times, c_linear(times, args), label='steady state') pl.ylabel('beta/alpha') pl.legend() pl.subplot(3, 1, 3) pl.plot(times, np.max(fidelity_arr, axis=1)) pl.ylabel('fidelity') pl.xlabel('time') pl.savefig(plot_filepath + '2d_fidelity' + str(plot_num) + '.png') pl.clf() fig = pl.figure(figsize=(5 * num_steps, 10)) for i in range(num_steps): ''' Cavity A occupation ''' pl.subplot(4, num_steps, i + 1) pl.plot(range(N), result.states[i].ptrace(0).diag()) pl.title('Cavity A occupation') ''' Cavity A occupation ''' pl.subplot(4, num_steps, i + 1 + num_steps) pl.plot(range(N), result.states[i].ptrace(1).diag()) pl.title('Cavity B occupation') pl.savefig(plot_filepath + 'Occupation' + str(plot_num) + '.png') pl.clf() num_points = 40 xvec_2d = np.linspace(-6, 6, num_points) fig = pl.figure(figsize=(2.5 * num_steps, 10)) for i in range(num_steps): ''' Cavity A wigner ''' pl.subplot(4, num_steps, i + 1) W = qt.wigner(result.states[i].ptrace(0), xvec_2d, xvec_2d) * np.pi pl.contourf(xvec_2d, xvec_2d, W, np.linspace(-1.0, 1.0, 41, endpoint=True), cmap=mpl.cm.RdBu_r) pl.title('Cavity A wigner') pl.colorbar(ticks=np.linspace(-1.0, 1.0, 11, endpoint=True)) ''' Cavity B wigner ''' pl.subplot(4, num_steps, i + 1 + num_steps) W = qt.wigner(result.states[i].ptrace(1), xvec_2d, xvec_2d) * np.pi pl.contourf(xvec_2d, xvec_2d, W, np.linspace(-1.0, 1.0, 41, endpoint=True), cmap=mpl.cm.RdBu_r) pl.title('Cavity B wigner') pl.colorbar(ticks=np.linspace(-1.0, 1.0, 11, endpoint=True)) pl.savefig(plot_filepath + '2d_wigner' + str(plot_num) + '.png') pl.clf() #num_points = 5 #xvec = np.linspace(-4, 4, num_points) #t_start = time.time() # #fig = pl.figure(figsize=(5 * num_steps, 5)) #for n in range(num_steps): # ''' reA vs reB ''' # pl.subplot(1, num_steps, n+1) # W = wigner4d(result.states[n], xvec) # pl.contourf(xvec, xvec, W, np.linspace(-1.0, 1.0, 41, endpoint=True), cmap=mpl.cm.RdBu_r) # pl.title('reA vs reB t=' + str(times[n])) # pl.colorbar(ticks = np.linspace(-1.0, 1.0, 11, endpoint=True)) # #print(str(num_steps) + ' plots created in ' + str(time.time()-t_start) + ' sec') # #pl.savefig(plot_filepath + 'ReRe_wigner_cuts' + str(plot_num) + '.png') #pl.clf() pl.close('all')
#alpha = 0 #beta = np.sqrt(-2j * lam.conjugate()) ''' Testing middle state is steady state ''' alpha = 2 num_points = 40 xvec_2d = np.linspace(-3, 3, num_points) beta_arr = np.linspace(alpha, 0, 10) images = [] for beta in beta_arr: psi = (np.round(np.cos(theta / 2), 5) * qt.tensor(qt.coherent(N, alpha - beta), qt.coherent(N, beta)) + np.round(np.sin(theta / 2), 5) * np.exp(1j * phi) * qt.tensor( qt.coherent(N, -alpha + beta), qt.coherent(N, -beta))).unit() #W = wigner4d(psi, xvec, 0, m_lib) W = qt.wigner(psi.ptrace(0), xvec_2d, xvec_2d) * np.pi fig, ax = pl.subplots(figsize=(5, 3)) pl.contourf(xvec, xvec, W, np.linspace(-1.0, 1.0, 41, endpoint=True), cmap=mpl.cm.RdBu_r) pl.title('reA vs imA beta=' + str(beta)) pl.colorbar(ticks=np.linspace(-1.0, 1.0, 11, endpoint=True)) pl.savefig('out/temp.png') pl.clf() images.append(imageio.imread('out/temp.png')) imageio.mimsave('out/fig1.gif', images, fps=1)
''' Cavity A occupation ''' pl.subplot(4, num_steps, i + 1 + num_steps) pl.plot(range(N), result.ptrace(1).diag()) pl.title('Cavity B occupation') pl.savefig(plot_filepath + 'Occupation.png') pl.clf() num_points = 40 xvec = np.linspace(-4, 4, num_points) fig = pl.figure(figsize=(2.5 * num_steps, 10)) for i in range(num_steps): ''' Cavity A wigner ''' pl.subplot(4, num_steps, i + 1) W = qt.wigner(result.ptrace(0), xvec, xvec) * np.pi pl.contourf(xvec, xvec, W, np.linspace(-1.0, 1.0, 41, endpoint=True), cmap=mpl.cm.RdBu_r) pl.title('Cavity A wigner') pl.colorbar(ticks=np.linspace(-1.0, 1.0, 11, endpoint=True)) ''' Cavity B wigner ''' pl.subplot(4, num_steps, i + 1 + num_steps) W = qt.wigner(result.ptrace(1), xvec, xvec) * np.pi pl.contourf(xvec, xvec, W, np.linspace(-1.0, 1.0, 41, endpoint=True), cmap=mpl.cm.RdBu_r)
#partial trace #res_tab=np.load(path+'tab_size2_k2isdeltaover10.npy') #ptrace_T=[] #p_trace_C=[] #for (ii, res) in enumerate res_tab: # p_trace_T.append() path = 'C:/Users/berdou/Documents/Thèse/Posters/Images-poster/Images_CNOT/' res_CNOT = qt.qload(path + 'density_plus_k2over10') # Draw indiv Wigner fig, ax = plt.subplots() ii = int(n_t * T2 * 1.1 * 1 / T_final) space_size = [-4, 4, 1001] space_size = np.linspace(space_size[0], space_size[1], space_size[2]) wig = qt.wigner(res_CNOT.states[ii].ptrace(1), space_size, space_size, g=2) ax.pcolor(space_size, space_size, wig, cmap='bwr', vmin=[-2 / np.pi, 2 / np.pi]) ax.set_aspect('equal') # #class compute_Wigner: # def __init__(self, space_size, nbWigner,nbCols, tempsSimul, syst): # self.space_size = np.linspace(space_size[0],space_size[1],space_size[2]) # self.nbWigner = nbWigner # self.nbCols= nbCols # (self.fig,self.axes) = plt.subplots((nbWigner+1)//nbCols,nbCols,figsize=(12,8)) # self.listeWigner = [] # self.n_t = tempsSimul
def process_wigners(r1, r2, max_alpha): wigner_xs = np.linspace(-max_alpha, max_alpha, 100) wigner_fn = lambda a: wigner(a, wigner_xs, wigner_xs) return (map(wigner_fn, r1), map(wigner_fn, r2))
def f(state, xvec, yvec): return qt.wigner(state, xvec, yvec)
N = 20 n = 5 a = qt.destroy(N) x = qt.position(N) p = qt.momentum(N) H = a.dag() * a psi0 = qt.coherent(N, n**0.5) #psi0=qt.fock(N,n) time = np.linspace(0, 100, 1000) sol = qt.mesolve(H, psi0, time, [], []) fig, ax = plt.subplots(2, 1) xvec = np.linspace(-10, 10, 100) #ax.plot(qt.expect(x,sol.states),qt.expect(p,sol.states)) line, = ax[1].plot([0], [qt.expect(H, psi0)]) im = ax[0].imshow(qt.wigner(psi0, xvec, xvec)) def updatefig(i): psi = sol.states[i] data = qt.wigner(psi, xvec, xvec) im.set_array(data) X = list(range(i)) Y = qt.expect(x, sol.states[:i]) line.set_data(X, Y) ax[1].set_xlim((0, i)) ax[1].set_ylim((0, N)) # ax.plot(qt.expect(x,sol.states),qt.expect(p,sol.states)) return im, line
displace = np.dot(disp, vac) fig, ax = plt.subplots() ax.plot(range(dim),abs(displace)) ax.plot(range(dim),abs(state),'o') if 0: # qutip wigner of a coherent state time0 = time.time() alpha = 2*np.exp(1j*np.pi/3) state = qt.coherent(dim, alpha) I_mesh = np.linspace(-5,5,51) Q_mesh = np.linspace(-5,5,101) W = qt.wigner(state, I_mesh, Q_mesh, g=2) time1 = time.time() print("qutip time = ",time1-time0) if 1: # plot fig, ax = plt.subplots() cs = ax.imshow(W,origin='lower',extent=[min(I_mesh),max(I_mesh),min(Q_mesh),max(Q_mesh)]) ax.plot(np.real(alpha),np.imag(alpha),'r+') plt.grid() plt.colorbar(cs) if 0: # manual wigner of a coherent state time0 = time.time() alpha = 2*np.exp(1j*np.pi/3)
# Display wigner at 10 equally spaced times during the dynamics if wigner: xvec=np.linspace(-4, 4, 51) # wigner space size n_wig = 10 spacing = n_t//n_wig fig, ax = plt.subplots(2,5, figsize=(12,8)) fig_b, ax_b = plt.subplots(2,5, figsize=(12,8)) print('Compute and plot wigners') wigs = [] wigs_b = [] for ii in range(n_t): if ii%spacing==0 and ii//spacing<n_wig: wig = qt.wigner(res.states[ii].ptrace(0), xvec, xvec, g=2) # compute partial trace wig_b = qt.wigner(res.states[ii].ptrace(1), xvec, xvec, g=2) wigs.append(wig) wigs_b.append(wig_b) for ii in range(len(wigs)): ax[ii//5, ii%5].pcolor(xvec, xvec, wigs[ii], cmap='bwr', vmin=[-2/np.pi, 2/np.pi]) ax[ii//5, ii%5].set_aspect('equal') for ii in range(len(wigs)): ax_b[ii//5, ii%5].pcolor(xvec, xvec, wigs_b[ii], cmap='bwr', vmin=[-2/np.pi, 2/np.pi]) ax_b[ii//5, ii%5].set_aspect('equal') # si l'elimination adiabatic fonctionne correctement, # le buffer est censé rester dans le vide # Display various quantities versus time