def testHOFiniteTemperatureStates(): """ brmesolve: harmonic oscillator, finite temperature, states """ N = 10 w0 = 1.0 * 2 * np.pi g = 0.05 * w0 kappa = 0.25 times = np.linspace(0, 25, 1000) a = destroy(N) H = w0 * a.dag() * a + g * (a + a.dag()) psi0 = ket2dm((basis(N, 4) + basis(N, 2) + basis(N, 0)).unit()) n_th = 1.5 w_th = w0/np.log(1 + 1/n_th) def S_w(w): if w >= 0: return (n_th + 1) * kappa else: return (n_th + 1) * kappa * np.exp(w / w_th) c_ops = [np.sqrt(kappa * (n_th + 1)) * a, np.sqrt(kappa * n_th) * a.dag()] a_ops = [a + a.dag()] e_ops = [] res_me = mesolve(H, psi0, times, c_ops, e_ops) res_brme = brmesolve(H, psi0, times, a_ops, e_ops, [S_w]) n_me = expect(a.dag() * a, res_me.states) n_brme = expect(a.dag() * a, res_brme.states) diff = abs(n_me - n_brme).max() assert_(diff < 1e-2)
def compute(N, wc, wa, glist, use_rwa): # Pre-compute operators for the hamiltonian a = tensor(destroy(N), qeye(2)) sm = tensor(qeye(N), destroy(2)) nc = a.dag() * a na = sm.dag() * sm idx = 0 na_expt = zeros(shape(glist)) nc_expt = zeros(shape(glist)) for g in glist: # recalculate the hamiltonian for each value of g if use_rwa: H = wc * nc + wa * na + g * (a.dag() * sm + a * sm.dag()) else: H = wc * nc + wa * na + g * (a.dag() + a) * (sm + sm.dag()) # find the groundstate of the composite system evals, ekets = H.eigenstates() psi_gnd = ekets[0] na_expt[idx] = expect(na, psi_gnd) nc_expt[idx] = expect(nc, psi_gnd) idx += 1 return nc_expt, na_expt, ket2dm(psi_gnd)
def correlator(self): """correlator Measure of quantum vs semiclassical""" if not self.precalc: self._calculate() return np.abs( np.asarray([qt.expect(self.a * self.sm, rho) for rho in self.rhos_ss]) - np.asarray([qt.expect(self.a, rho) for rho in self.rhos_ss]) * np.asarray([qt.expect(self.sm, rho) for rho in self.rhos_ss]) ).T
def g2(self): if not self.precalc: self._calculate() return np.abs( np.asarray( [ qt.expect(self.a.dag() * self.a.dag() * self.a * self.a, rho) / qt.expect(self.a.dag() * self.a, rho) ** 2 for rho in self.rhos_ss ] ) ).T
def test_ho_lgmres(): "Steady state: Thermal HO - iterative-lgmres solver" # thermal steadystate of an oscillator: compare numerics with analytical # formula a = destroy(40) H = 0.5 * 2 * np.pi * a.dag() * a gamma1 = 0.05 wth_vec = np.linspace(0.1, 3, 20) p_ss = np.zeros(np.shape(wth_vec)) for idx, wth in enumerate(wth_vec): n_th = 1.0 / (np.exp(1.0 / wth) - 1) # bath temperature c_op_list = [] rate = gamma1 * (1 + n_th) c_op_list.append(np.sqrt(rate) * a) rate = gamma1 * n_th c_op_list.append(np.sqrt(rate) * a.dag()) rho_ss = steadystate(H, c_op_list, method='iterative-lgmres') p_ss[idx] = np.real(expect(a.dag() * a, rho_ss)) p_ss_analytic = 1.0 / (np.exp(1.0 / wth_vec) - 1) delta = sum(abs(p_ss_analytic - p_ss)) assert_equal(delta < 1e-3, True)
def test_qubit_power(): "Steady state: Thermal qubit - power solver" # thermal steadystate of a qubit: compare numerics with analytical formula sz = sigmaz() sm = destroy(2) H = 0.5 * 2 * np.pi * sz gamma1 = 0.05 wth_vec = np.linspace(0.1, 3, 20) p_ss = np.zeros(np.shape(wth_vec)) for idx, wth in enumerate(wth_vec): n_th = 1.0 / (np.exp(1.0 / wth) - 1) # bath temperature c_op_list = [] rate = gamma1 * (1 + n_th) c_op_list.append(np.sqrt(rate) * sm) rate = gamma1 * n_th c_op_list.append(np.sqrt(rate) * sm.dag()) rho_ss = steadystate(H, c_op_list, method='power') p_ss[idx] = expect(sm.dag() * sm, rho_ss) p_ss_analytic = np.exp(-1.0 / wth_vec) / (1 + np.exp(-1.0 / wth_vec)) delta = sum(abs(p_ss_analytic - p_ss)) assert_equal(delta < 1e-5, True)
def steady(N = 20): # number of basis states to consider n=num(N) a = destroy(N) H = a.dag() * a print H.eigenstates() #psi0 = basis(N, 10) # initial state kappa = 0.1 # coupling to oscillator c_op_list = [] n_th_a = 2 # temperature with average of 2 excitations rate = kappa * (1 + n_th_a) c_op_list.append(sqrt(rate) * a) # decay operators rate = kappa * n_th_a c_op_list.append(sqrt(rate) * a.dag()) # excitation operators final_state = steadystate(H, c_op_list) fexpt = expect(a.dag() * a, final_state) #tlist = linspace(0, 100, 100) #mcdata = mcsolve(H, psi0, tlist, c_op_list, [a.dag() * a], ntraj=100) #medata = mesolve(H, psi0, tlist, c_op_list, [a.dag() * a]) #plot(tlist, mcdata.expect[0], #plt.plot(tlist, medata.expect[0], lw=2) plt.axhline(y=fexpt, color='r', lw=1.5) # ss expt. value as horiz line (= 2) plt.ylim([0, 10]) plt.show()
def find_expect(self, vg, pwr, fd): if self.power_plot: phi, pwr=vg else: phi, fd=vg pwr_fridge=pwr-self.atten lin_pwr=0.001*10**(pwr_fridge/10.0) Omega=sqrt(lin_pwr/h*2.0) gamma, Delta=self._get_GammaDelta(fd=fd, f0=self.f0, Np=self.Np, gamma=self.gamma) g_el=self._get_Gamma_C(fd=fd) wTvec=self._get_fTvec(phi=phi, gamma=gamma, Delta=Delta, fd=fd, Psaw=lin_pwr) if self.acoustic_plot: Om=Omega*sqrt(gamma/fd) else: Om=Omega*sqrt(g_el/fd) wT = wTvec-fd*self.nvec #rotating frame of gate drive \omega_m-m*\omega_\gate transmon_levels = Qobj(diag(wT[range(self.N_dim)])) rate1 = (gamma+g_el)*(1.0 + self.N_gamma) rate2 = (gamma+g_el)*self.N_gamma c_ops=[sqrt(rate1)*self.a_op, sqrt(rate2)*self.a_dag]#, sqrt(rate3)*self.a_op, sqrt(rate4)*self.a_dag] Omega_vec=-0.5j*(Om*self.a_dag - conj(Om)*self.a_op) H=transmon_levels +Omega_vec final_state = steadystate(H, c_ops) #solve master equation fexpt=expect(self.a_op, final_state) #expectation value of relaxation operator #return fexpt if self.acoustic_plot: return 1.0*gamma/Om*fexpt else: return 1.0*sqrt(g_el*gamma)/Om*fexpt
def e_ops_func(t, rho, transformation=Utrans, e_ops=results.e_ops): """Transform the density matrix into the lab frame, and calculate the expectation values. TODO: this could probably be streamlined... need to look into qutip's code """ rho_lab_frame=Utrans(t).dag()*q.Qobj(rho)*Utrans(t) for i, e_operator in enumerate(e_ops): expectation_values[i][e_ops_func.idx]=q.expect(e_operator, rho_lab_frame).real e_ops_func.idx+=1
def essolve(H, rho0, tlist, c_op_list, expt_op_list): """ Evolution of a state vector or density matrix (`rho0`) for a given Hamiltonian (`H`) and set of collapse operators (`c_op_list`), by expressing the ODE as an exponential series. The output is either the state vector at arbitrary points in time (`tlist`), or the expectation values of the supplied operators (`expt_op_list`). Parameters ---------- H : qobj/function_type System Hamiltonian. rho0 : qobj Initial state density matrix. tlist : list/array ``list`` of times for :math:`t`. c_op_list : list ``list`` of ``qobj`` collapse operators. expt_op_list : list ``list`` of ``qobj`` operators for which to evaluate expectation values. Returns ------- expt_array : array Expectation values of wavefunctions/density matrices for the times specified in ``tlist``. .. note:: This solver does not support time-dependent Hamiltonians. """ n_expt_op = len(expt_op_list) n_tsteps = len(tlist) # Calculate the Liouvillian if c_op_list == None or len(c_op_list) == 0: L = H else: L = liouvillian(H, c_op_list) es = ode2es(L, rho0) # evaluate the expectation values if n_expt_op == 0: result_list = [Qobj() for k in range(n_tsteps)] else: result_list = zeros([n_expt_op, n_tsteps], dtype=complex) for n in range(0, n_expt_op): result_list[n,:] = esval(expect(expt_op_list[n],es),tlist) return result_list
def testCoherentState(self): """ states: coherent state """ N = 10 alpha = 0.5 c1 = coherent(N, alpha) # displacement method c2 = coherent(7, alpha, offset=3) # analytic method assert_(abs(expect(destroy(N), c1) - alpha) < 1e-10) assert_((c1[3:]-c2).norm() < 1e-7)
def get_reduced_dms(self, states, spin): """ takes a number of states and returns a list of bloch vector of the 0th spin coordinates for each """ sz = sigmaz() sy = sigmay() sx = sigmax() zs = [] ys = [] xs = [] for state in states: ptrace = state.ptrace(spin) zval = abs(expect(sz, ptrace)) yval = abs(expect(sy, ptrace)) xval = abs(expect(sx, ptrace)) zs.append(zval) ys.append(yval) xs.append(xval) return xs, ys, zs
def get_dms(states): ''' takes a number of states and returns a list of bloch vector coordinates for each ''' si = qeye(2) sz = sigmaz() sy = sigmay() sx = sigmax() zs = [] ys = [] xs = [] for state in states: ptrace = state.ptrace(0) zval = expect(sz, ptrace ) yval = expect(sy, ptrace ) xval = expect(sx, ptrace ) zs.append(zval) ys.append(yval) xs.append(xval) return xs,ys,zs
def jc_steadystate(self, N, wc, wa, g, kappa, gamma, pump, psi0, use_rwa, tlist): # Hamiltonian a = tensor(destroy(N), identity(2)) sm = tensor(identity(N), destroy(2)) if use_rwa: # use the rotating wave approxiation H = wc * a.dag( ) * a + wa * sm.dag() * sm + g * (a.dag() * sm + a * sm.dag()) else: H = wc * a.dag() * a + wa * sm.dag() * sm + g * ( a.dag() + a) * (sm + sm.dag()) # collapse operators c_op_list = [] n_th_a = 0.0 # zero temperature rate = kappa * (1 + n_th_a) c_op_list.append(np.sqrt(rate) * a) rate = kappa * n_th_a if rate > 0.0: c_op_list.append(np.sqrt(rate) * a.dag()) rate = gamma if rate > 0.0: c_op_list.append(np.sqrt(rate) * sm) rate = pump if rate > 0.0: c_op_list.append(np.sqrt(rate) * sm.dag()) # find the steady state rho_ss = steadystate(H, c_op_list) return expect(a.dag() * a, rho_ss), expect(sm.dag() * sm, rho_ss)
def test_SparseHermValsVecs(): """ Sparse eigs Hermitian """ # check using number operator N = num(10) spvals, spvecs = N.eigenstates(sparse=True) for k in range(10): # check that eigvals are in proper order assert_equal(abs(spvals[k] - k) <= 1e-13, True) # check that eigenvectors are right and in right order assert_equal(abs(expect(N, spvecs[k]) - spvals[k]) < 5e-14, True) # check ouput of only a few eigenvals/vecs spvals, spvecs = N.eigenstates(sparse=True, eigvals=7) assert_equal(len(spvals), 7) assert_equal(spvals[0] <= spvals[-1], True) for k in range(7): assert_equal(abs(spvals[k] - k) < 1e-12, True) spvals, spvecs = N.eigenstates(sparse=True, sort='high', eigvals=5) assert_equal(len(spvals), 5) assert_equal(spvals[0] >= spvals[-1], True) vals = np.arange(9, 4, -1) for k in range(5): # check that eigvals are ordered from high to low assert_equal(abs(spvals[k] - vals[k]) < 5e-14, True) assert_equal(abs(expect(N, spvecs[k]) - vals[k]) < 1e-14, True) # check using random Hermitian H = rand_herm(10) spvals, spvecs = H.eigenstates(sparse=True) # check that sorting is lowest eigval first assert_equal(spvals[0] <= spvals[-1], True) # check that spvals equal expect vals for k in range(10): assert_equal(abs(expect(H, spvecs[k]) - spvals[k]) < 5e-14, True) # check that ouput is real for Hermitian operator assert_equal(np.isreal(spvals[k]), True)
def find_expect(vg): #phi=0.1, Omega_vec=3.0): phi, Omega=vg#.shape Omega_vec=- 0.5j*(Omega*adag - conj(Omega)*a) Ej = Ejmax*absolute(cos(pi*phi)) #Josephson energy as function of Phi. wTvec = -Ej + sqrt(8.0*Ej*Ec)*(nvec+0.5)+Ecvec #\omega_m wT = wTvec-wdvec #rotating frame of gate drive \omega_m-m*\omega_\gate transmon_levels = Qobj(diag(wT[range(N)])) H=transmon_levels +Omega_vec #- 0.5j*(Omega_true*adag - conj(Omega_true)*a) final_state = steadystate(H, c_op_list) #solve master equation return expect( a, final_state) #expectation value of relaxation operator
def find_expect(vg, self=a): #phi=0.1, Omega_vec=3.0): phi, Omega=vg#.shape Omega_vec=-0.5j*(Omega*self.a_dag - conj(Omega)*self.a_op) Ej = self.Ejmax*absolute(cos(pi*phi)) #Josephson energy as function of Phi. wTvec = (-Ej + sqrt(8.0*Ej*self.Ec)*(self.nvec+0.5)+self.Ecvec)/h #\omega_m wT = wTvec-a.fdvec #rotating frame of gate drive \omega_m-m*\omega_\gate transmon_levels = Qobj(diag(wT[range(self.N_dim)])) H=transmon_levels +Omega_vec #- 0.5j*(Omega_true*adag - conj(Omega_true)*a) final_state = steadystate(H, self.c_ops) #solve master equation return expect( self.a_op, final_state) #expectation value of relaxation operator
def test_MCNoCollStates(): "Monte-carlo: Constant H with no collapse ops (states)" error = 1e-8 N = 10 # number of basis states to consider a = destroy(N) H = a.dag() * a psi0 = basis(N, 9) # initial state c_op_list = [] tlist = np.linspace(0, 10, 100) mcdata = mcsolve(H, psi0, tlist, c_op_list, [], ntraj=ntraj) states = mcdata.states expt = expect(a.dag() * a, states) actual_answer = 9.0 * np.ones(len(tlist)) diff = np.mean(abs(actual_answer - expt) / actual_answer) assert_equal(diff < error, True)
def calculate_expects(self): ''' requires: self.expects format: [[expectation for operator 1 for all times], [expectation for operator 1 for all times], ...] ''' self.sim_expects = [] for i, oper in enumerate(self.expects): expects = qt.expect(oper, self.sim_states) self.sim_expects.append(expects) self.sim_expects = np.array(self.sim_expects)
def test_MCSimpleConstStates(): "Monte-carlo: Constant H with constant collapse (states)" N = 10 # number of basis states to consider a = destroy(N) H = a.dag() * a psi0 = basis(N, 9) # initial state kappa = 0.2 # coupling to oscillator c_op_list = [np.sqrt(kappa) * a] tlist = np.linspace(0, 10, 100) mcdata = mcsolve(H, psi0, tlist, c_op_list, [], ntraj=ntraj, options=Options(average_states=True)) assert_(len(mcdata.states) == len(tlist)) assert_(isinstance(mcdata.states[0], Qobj)) expt = expect(a.dag() * a, mcdata.states) actual_answer = 9.0 * np.exp(-kappa * tlist) avg_diff = np.mean(abs(actual_answer - expt) / actual_answer) assert_equal(avg_diff < mc_error, True)
def test_SparseValsVecs(): """ Sparse eigs non-Hermitian """ U = rand_unitary(10) spvals, spvecs = U.eigenstates(sparse=True) assert_equal(np.real(spvals[0]) <= np.real(spvals[-1]), True) for k in range(10): # check that eigenvectors are right and in right order assert_equal(abs(expect(U, spvecs[k]) - spvals[k]) < 5e-14, True) assert_equal(np.iscomplex(spvals[k]), True) # check sorting spvals, spvecs = U.eigenstates(sparse=True, sort='high') assert_equal(np.real(spvals[0]) >= np.real(spvals[-1]), True) # check for N-1 eigenvals U = rand_unitary(10) spvals, spvecs = U.eigenstates(sparse=True, eigvals=9) assert_equal(len(spvals), 9)
def testMETDDecayAsFunc(self): "mesolve: time-dependent Liouvillian as single function" N = 10 # number of basis states to consider a = destroy(N) H = a.dag() * a rho0 = ket2dm(basis(N, 9)) # initial state kappa = 0.2 # coupling to oscillator def Liouvillian_func(t, args): c = np.sqrt(kappa * np.exp(-t)) * a return liouvillian(H, [c]).data tlist = np.linspace(0, 10, 100) args = {"kappa": kappa} out1 = mesolve(Liouvillian_func, rho0, tlist, [], [], args=args) expt = expect(a.dag() * a, out1.states) actual_answer = 9.0 * np.exp(-kappa * (1.0 - np.exp(-tlist))) avg_diff = np.mean(abs(actual_answer - expt) / actual_answer) assert_(avg_diff < me_error)
def test_MCNoCollExpectStates(): "Monte-carlo: Constant H with no collapse ops (expect and states)" error = 1e-8 N = 10 # number of basis states to consider a = destroy(N) H = a.dag() * a psi0 = basis(N, 9) # initial state c_op_list = [] tlist = np.linspace(0, 10, 100) mcdata = mcsolve(H, psi0, tlist, c_op_list, [a.dag() * a], ntraj=ntraj, options=Options(store_states=True)) actual_answer = 9.0 * np.ones(len(tlist)) expt = mcdata.expect[0] diff = np.mean(abs(actual_answer - expt) / actual_answer) assert_equal(diff < error, True) assert_(len(mcdata.states) == len(tlist)) assert_(isinstance(mcdata.states[0], Qobj)) expt = expect(a.dag() * a, mcdata.states) diff = np.mean(abs(actual_answer - expt) / actual_answer) assert_equal(diff < error, True)
def test_DenseValsVecs(): """ Dense eigs non-Hermitian """ W = rand_herm(10,0.5) + 1j*rand_herm(10,0.5) spvals, spvecs = W.eigenstates(sparse=False) assert_equal(np.real(spvals[0]) <= np.real(spvals[-1]), True) for k in range(10): # check that eigenvectors are right and in right order assert_equal(abs(expect(W, spvecs[k]) - spvals[k]) < 1e-14, True) assert_(np.iscomplex(spvals[k])) # check sorting spvals, spvecs = W.eigenstates(sparse=False, sort='high') assert_equal(np.real(spvals[0]) >= np.real(spvals[-1]), True) # check for N-1 eigenvals W = rand_unitary(10) spvals, spvecs = W.eigenstates(sparse=False, eigvals=9) assert_equal(len(spvals), 9)
def find_expect(phi=0.1, Omega_vec=3.0, wd=wd): wdvec=nvec*wd Ej = Ejmax*absolute(cos(pi*phi)) #; % Josephson energy as function of Phi. wq0=sqrt(8*Ej*Ec) X=Np*pi*(wq0-f0)/f0 Ba=-1*gamma*(sin(2.0*X)-2.0*X)/(2.0*X**2.0) Ecp=Ec*(1-2*Ba/wq0) Ecvec=-Ecp*(6.0*nvec**2+6.0*nvec+3.0)/12.0 wTvec = -Ej + sqrt(8.0*Ej*Ecp)*(nvec+0.5)+Ecvec #print diff(wTvec) if phi==0.4: print Ba/wq0 if 0: zr=zeros(N) X=Np*pi*(diff(wTvec)-f0)/f0 Ba=-0*gamma*(sin(2.0*X)-2.0*X)/(2.0*X**2.0) ls=-Ba#/(2*Ct)/(2*pi)#/1e6 zr[1:]=ls #print Ga0/(2*Ct)/(2*pi) #print zr wTvec=wTvec+zr wTvec = wTvec-wdvec #print wTvec+diff(wTvec) transmon_levels = Qobj(diag(wTvec[range(N)])) H=transmon_levels +Omega_vec #- 0.5j*(Omega_true*adag - conj(Omega_true)*a) final_state = steadystate(H, c_op_list) return expect( tm_l, final_state)
def find_expect(phi=0.1, Omega_vec=3.0, wd=wd): Ej = (phi**2)/(8*Ec) #Ejmax*absolute(cos(pi*phi)) #; % Josephson energy as function of Phi. wTvec = -Ej + sqrt(8.0*Ej*Ec)*(nvec+0.5)+Ecvec #wdvec=nvec*sqrt(8.0*Ej*Ec) #wdvec=nvec*wd wT = wTvec-wdvec transmon_levels = Qobj(diag(wT[range(N)])) H=transmon_levels +Omega_vec #- 0.5j*(Omega_true*adag - conj(Omega_true)*a) #final_state = steadystate(H, c_op_list) #print H.shape #print dir(H) #U,D = eig(H.full()) #print D #Uinv = Qobj(inv(D)) #U=Qobj(D) # Doing the chi integral (gives the susceptibility) #Dint = 1.0/(1.0j*(wp-wd)) #Qobj(1.0/(1.0j*(wp-wd)*diag(qeye(N**2))))# + diag(D)))) #Hint = H.expm() #U*H*Uinv #Chi_temp(i,j) += (1.0/theta_steps)*1j*trace(reshape(tm_l*Lint*(p_l - p_r)*rho_ss_c,dim,dim)) #exp1=correlation_2op_1t(H, None, wlist2, c_op_list, a, p, solver="es") #exp2=correlation_2op_1t(H, None, wlist2, c_op_list, p, a, solver="es", reverse=True) #exp1=correlation_2op_1t(H, None, wlist2, c_op_list, a, p_l-p_r, solver="es") #exp1=correlation_ss(H, wlist2, c_op_list, a, p) #exp2=correlation_ss(H, wlist2, c_op_list, p, a, reverse=True) exp1=spectrum(H, wlist2, c_op_list, a, p, solver="pi", use_pinv=False) exp2=spectrum(H, wlist2, c_op_list, p, a, solver="pi", use_pinv=False) return exp1-exp2 return expect( a, final_state) #tm_l
psi0, times, loss_ops, options=opts, progress_bar=True) psi = result.states[-1] #psi = qt.ket2dm(psi0) plot_cutoff = 13 x_fit = np.arange(N) y_fit = np.abs(psi.diag()) #popt, pcov = curve_fit(lambda x_fit,a_fit : np.exp(-a_fit*2) * np.power(a_fit, 2*x_fit) / factorial(x_fit), x_fit, y_fit, p0 = (1)) popt, pcov = curve_fit(P_coh, x_fit, y_fit) print('alpha=', popt[0], ' <N>=', qt.expect(psi, a.dag() * a), 'fidelity=', qt.fidelity(psi, qt.coherent(N, popt[0]))) x = np.linspace(0, plot_cutoff, 100) popt[0] = np.sqrt(qt.expect(psi, a.dag() * a)) pl.figure(figsize=(7, 5)) mpl.rcParams.update({'font.size': 15}) pl.plot(x, P_coh(x, popt[0])**4, label='alpha=' + str(popt[0]) + '\nN=' + str(popt[0]**2), color='k') n = np.arange(plot_cutoff) pl.bar(n, np.power(np.abs(psi.diag()), 2)[:plot_cutoff], color='b') x = np.linspace(0, plot_cutoff, 100) pl.xlabel('|n>') pl.ylabel(r'|<$\psi$|n>|$^2$')
for j in range(n-1)]\ for i in range(n)] vphases_ = [vp.arrow(pos=vspheres_[i].pos,color=vp.color.yellow, opacity=0.6,\ axis=vp.vector(phases[i].real, phases[i].imag, 0))\ for i in range(n)] vspheres = [vp.sphere(color=vcolors[i], radius=pieces[i].norm(), opacity=0.3,\ pos=vp.vector(*pts[i]))\ for i in range(n)] vstars = [[vp.sphere(radius=0.15, emissive=True,\ pos=vspheres[i].pos+vp.vector(*views[i][j])) for j in range(n-1)]\ for i in range(n)] vspins = [vp.arrow(pos=vspheres[i].pos,\ axis=2*vp.vector(qt.expect(S[i]["X"], state),\ qt.expect(S[i]["Y"], state),\ qt.expect(S[i]["Z"], state)))\ for i in range(n)] vspins_ = [vp.arrow(pos=vspheres[i].pos, visible=False,\ axis=2*vp.vector(qt.expect(S[i]["X"], state),\ qt.expect(S[i]["Y"], state),\ qt.expect(S[i]["Z"], state)))\ for i in range(n)] vphases = [vp.arrow(pos=vspheres[i].pos,color=vp.color.magenta,\ axis=vp.vector(phases[i].real, phases[i].imag, 0),\ opacity=0.6)\ for i in range(n)]
def expect(self, _I_, pts): op = jmat(dim2spin(self.dims[_I_['spin_num']]), _I_['axis']) state = pts[0].ptrace(_I_['spin_num']) return expect(op, state)
def qubit_xyz(spin): return [qt.expect(qt.sigmax(), spin),\ qt.expect(qt.sigmay(), spin),\ qt.expect(qt.sigmaz(), spin)]
def run(self, tlist, sync_state=False): """ runs qutip.mesolve for given system and synced state. Note the this runner does not run multiple systems in parallel, indeed it will perform each system sequentially. if `sync_state` is `True` then the final state will be synced to this kernel after integration. **Note** This is not possible if **e_ops** is `None`. """ assert self.compiled and self.synced if sync_state is True and self.q_e_ops is not None: raise ValueError('sync_state must be False if n_e_ops > 0.') # result data preparation tstate = None if self.q_e_ops is None: shape = (self.state.shape[0], len(tlist), *self.state.shape[1:]) tstate = np.empty(shape, dtype=settings.QOP.T_COMPLEX) texpect = None if self.q_e_ops is not None: shape = (self.state.shape[0], len(self.q_e_ops), len(tlist)) texpect = np.empty(shape, dtype=settings.QOP.T_COMPLEX) # integrate states t0 = time() q_state_new = [] zipped = zip(self.q_hu, self.q_state, self.r_y_0, self.n_dst) for (i, (q_hu, q_s, y_0, n_dst)) in enumerate(zipped): if QOP.DEBUG: print_debug('{}/{}'.format(i, len(self.q_hu))) # prepare lindblad operators C = lambda w: w**3 * (1 + n_dst(w)) if w >= 0 \ else -w**3 * n_dst(-w) L = [] for w, l in self.q_L: L.append(np.sqrt(y_0 * C(w)) * l) L.append(np.sqrt(y_0 * C(-w)) * l.dag()) # args args = None if self.args is not None: # python3.7 and some api changes later, we have to convert the numpy array to a dict. As ths is only # a reference integrator we won't care about it later.. keys = [x[0] for x in self.args[i].dtype.descr] values = self.args[i] args = dict(zip(keys, values)) # mesolve Lf = [l for l in L if not np.allclose(l.full(), 0)] H = [q_hu] + self.q_htl res = mesolve(H=H[0] if len(H) == 1 else H, rho0=q_s, tlist=tlist, c_ops=Lf, args=args) # work with result if texpect is not None: texpect[i] = [expect(e, res.states) for e in self.q_e_ops] if tstate is not None: tstate[i] = [s.full() for s in res.states] q_state_new.append(res.states[-1]) tf = time() if tstate is not None: tstate = np.swapaxes(tstate, axis1=0, axis2=1) self.debug and print_debug( "1/1 calculated {} steps, took {:.4f}s".format( tstate.shape[0:2], tf - t0)) fstate = None if tstate is not None: fstate = npmat_manylike(self.system.h0, [q_s.full() for q_s in q_state_new]) # assign inner state if sync_state: self.q_state = q_state_new self.state = fstate # copy data to avoid references return (tlist[:], fstate[:] if fstate is not None else None, tstate[:] if tstate is not None else None, texpect[:] if texpect is not None else None)
apply(unitary_x) elif key == "s": apply(unitary_z.dag()) elif key == "w": apply(unitary_z) elif key == "z": apply(unitary_y.dag()) elif key == "x": apply(unitary_y) vpython.scene.bind('keydown', keyboard) vpython.scene.autoscale=False while True: vpython.rate(100) base_state = R4_to_R3(C2_to_R4(qubit)).T[0] #base_x = qutip.expect(qutip.sigmax(), qubit) #base_y = qutip.expect(qutip.sigmay(), qubit) #base_z = qutip.expect(qutip.sigmaz(), qubit) base_x = base_state[0] base_y = base_state[1] base_z = base_state[2] vbase.pos = vpython.vector(base_x.real, base_y.real, base_z.real) photon_state = R4_to_R3(photon).T[0] #photon_x = photon_state[0] #photon_y = photon_state[1] #photon_z = photon_state[2] photon_x = qutip.expect(qutip.sigmax(), qubit) photon_y = qutip.expect(qutip.sigmay(), qubit) photon_z = qutip.expect(qutip.sigmaz(), qubit) vphoton.pos = vpython.vector(photon_x.real, photon_y.real, photon_z.real)
def expect(state): return [qutip.expect(qutip.sigmax(), state),\ qutip.expect(qutip.sigmay(), state),\ qutip.expect(qutip.sigmaz(), state)]
new_stars = q_SurfaceXYZ(state) for i in range((2**n_qubits) - 1): vstars[i].pos = vpython.vector(*new_stars[i]) old_dims = state.dims[:] state.dims = [[2] * n_qubits, [1] * n_qubits] for i in range(n_qubits): qubit = state.ptrace(i) r4 = QubitDM_to_R4(qubit) #first_latitude = qubits[i]["first_latitude"] #second_latitude = qubits[i]["second_latitude"] #longitude = qubits[i]["longitude"] #r4 = ThreeAngles_to_R4(first_latitude, second_latitude, longitude) base_x, base_y, base_z = C2_to_R3(R4_to_C2(r4)).T[0] base_x2 = qutip.expect(qutip.sigmax(), qubit) base_y2 = qutip.expect(qutip.sigmay(), qubit) base_z2 = qutip.expect(qutip.sigmaz(), qubit) vbases[i].pos = vpython.vector(base_x.real, base_y.real, base_z.real) varrows[i].pos = vpython.vector(0, 0, 0) varrows[i].axis = vpython.vector(base_x2.real, base_y2.real, base_z2.real) varrows[i].shaftwidth = 0.06 hopf_points = [R4_to_hopfCircle(r4, angle) for angle in circle] for th in range(n_points): proj = R4_to_R3(hopf_points[th]) if not isinstance(proj, tuple): x, y, z = proj.T[0] vfibers[i].modify(th, pos=vpython.vector(x.real, y.real, z.real))
def spin_axis(n, state): spin_ops = spin_operators(n) return [qutip.expect(spin_ops["X"], state),\ qutip.expect(spin_ops["Y"], state),\ qutip.expect(spin_ops["Z"], state)]
H0 = - delta/2.0 * qutip.sigmax() - eps0/2.0 * qutip.sigmaz() H1 = A/2.0 * qutip.sigmax() args = {'w': omega} H = [H0, [H1, lambda t, args: np.sin(args['w'] * t)]] # find the floquet modes for the time-dependent hamiltonian f_modes_0,f_energies = qutip.floquet_modes(H, T, args) # decompose the inital state in the floquet modes f_coeff = qutip.floquet_state_decomposition(f_modes_0, f_energies, psi0) # calculate the wavefunctions using the from the floquet modes f_modes_table_t = qutip.floquet_modes_table(f_modes_0, f_energies, tlist, H, T, args) p_ex = np.zeros(len(tlist)) for n, t in enumerate(tlist): f_modes_t = qutip.floquet_modes_t_lookup(f_modes_table_t, t, T) psi_t = qutip.floquet_wavefunction(f_modes_t, f_energies, f_coeff, t) p_ex[n] = qutip.expect(qutip.num(2), psi_t) # For reference: calculate the same thing with mesolve p_ex_ref = qutip.mesolve(H, psi0, tlist, [], [qutip.num(2)], args).expect[0] # plot the results pyplot.plot(tlist, np.real(p_ex), 'ro', tlist, 1-np.real(p_ex), 'bo') pyplot.plot(tlist, np.real(p_ex_ref), 'r', tlist, 1-np.real(p_ex_ref), 'b') pyplot.xlabel('Time') pyplot.ylabel('Occupation probability') pyplot.legend(("Floquet $P_1$", "Floquet $P_0$", "Lindblad $P_1$", "Lindblad $P_0$")) pyplot.show()
def measure(psi, measure): ps = [] for operator in measure: p = np.abs(expect(operator, psi))**2. ps.append(p) return ps
def spin_axis(self): return [qutip.expect(qutip.sigmax(), self.state),\ qutip.expect(qutip.sigmay(), self.state),\ qutip.expect(qutip.sigmaz(), self.state)]
def qubit_to_vector(qubit): return np.array([[qutip.expect(qutip.sigmax(), qubit).real],\ [qutip.expect(qutip.sigmay(), qubit).real],\ [qutip.expect(qutip.sigmaz(), qubit).real],\ [qutip.expect(qutip.identity(2), qubit).real]])
for m in range(N): op_list.append(si) op_list[n] = sx sx_list.append(tensor(op_list)) op_list[n] = sy sy_list.append(tensor(op_list)) calc = ising_calculator_FM(number_of_spins, alpha, B) H = calc.get_H() # energy,state = H.groundstate() # print 'groundstate energy', energy # print 'groundstate expectation', expect(sx_list[0], state) # print 'groundstate expectation', expect(sx_list[1], state) # print 'groundstate expectation', expect(sx_list[2], state) # print state[0:10] # print state.dag() * H * state # print expect(H, state) # print state[0:10] # print state.norm() # print expect(sx_list[3] , state) energies, states = H.eigenstates() print energies[0:2] print 'groundstate expectation', expect(sx_list[0], states[0]) print 'groundstate expectation', expect(sx_list[0], states[1]) # for i in range(number_of_spins): # print expect(sy_list[i] , states[3])
def spin_axis(self): direction = np.array([qt.expect(self.paulis()[0][0], self.state).real,\ -1*qt.expect(self.paulis()[0][1], self.state).real,\ -1*qt.expect(self.paulis()[0][2], self.state).real]) spin_squared = np.sqrt(np.sum(direction**2)) return [normalize(direction).tolist(), spin_squared]
ev1 = assert_and_recast_to_real(np.linalg.eigvals((f1 - f).full())) ev2 = assert_and_recast_to_real(np.linalg.eigvals((f2 - f).full())) assert np.all(ev1 <= 1e-6), "fom1 should be <= f" assert np.all(ev2 <= 1e-6), "fom2 should be <= f" assert np.allclose( np.max(ev1), 0 ), "there should be at least one 0 e.v. (corresponding to the target state)" assert np.allclose( np.max(ev2), 0 ), "there should be at least one 0 e.v. (corresponding to the target state)" # nb_q = 6 x_rdm = np.array( [1.70386471, 1.38266762, 3.4257722, 5.78064, 3.84102323, 2.37653078]) init = qt.tensor(*[zero] * nb_q) rot_init = qt.tensor(*[qt.ry(N=1, phi=x) for n, x in enumerate(x_rdm)]) cz = [qt.cphase(np.pi, nb_q, c, t) for c, t in edges_test] entangl = prod_listop(cz) fin = entangl * rot_init * init qt.expect(f, fin) qt.expect(f1, fin) qt.expect(f2, fin) exp_stab = [qt.expect(s, fin) for s in list_stab] N_test = 6 edges_test = [[i, i + 1] for i in range(N_test - 1)] + [[N_test - 1, 0]] graph_test = gen_graph_state(N=N_test, edges=edges_test) #gen_decomposition_paulibasis(graph_test, N = N_test, threshold=1e-6, symbolic=True)
new_stars = q_SurfaceXYZ(state) for i in range((2**n_qubits) - 1): vstars[i].pos = vpython.vector(*new_stars[i]) old_dims = state.dims[:] state.dims = [[2] * n_qubits, [1] * n_qubits] for i in range(n_qubits): qubit = state.ptrace(i) r4 = QubitDM_to_R4(qubit.full()) #first_latitude = qubits[i]["first_latitude"] #second_latitude = qubits[i]["second_latitude"] #longitude = qubits[i]["longitude"] #r4 = ThreeAngles_to_R4(first_latitude, second_latitude, longitude) #base_x, base_y, base_z = C2_to_R3(R4_to_C2(r4)).T[0] base_x = qutip.expect(qutip.sigmax(), qubit) base_y = qutip.expect(qutip.sigmay(), qubit) base_z = qutip.expect(qutip.sigmaz(), qubit) vbases[i].pos = vpython.vector(base_x.real, base_y.real, base_z.real) varrows[i].pos = vpython.vector(0, 0, 0) varrows[i].axis = vpython.vector(base_x.real, base_y.real, base_z.real) varrows[i].shaftwidth = 0.06 hopf_points = [R4_to_hopfCircle(r4, angle) for angle in circle] for th in range(n_points): proj = R4_to_R3(hopf_points[th]) if not isinstance(proj, tuple): x, y, z = proj.T[0] vfibers[i].modify(th, pos=vpython.vector(x.real, y.real, z.real)) else:
def C2_to_R4(c2): return np.array([[qutip.expect(qutip.sigmax(), c2)],\ [qutip.expect(qutip.sigmay(), c2)],\ [qutip.expect(qutip.sigmaz(), c2)],\ [qutip.expect(qutip.identity(2), c2)]])
def bloch_redfield_solve(R, ekets, rho0, tlist, e_ops=[], opt=None): """ Evolve the ODEs defined by Bloch-Redfeild master equation. """ if opt == None: opt = Odeoptions() opt.nsteps = 2500 # if opt.tidy: R.tidyup() # # check initial state # if isket(rho0): # Got a wave function as initial state: convert to density matrix. rho0 = rho0 * rho0.dag() # # prepare output array # m n_e_ops = len(e_ops) n_tsteps = len(tlist) dt = tlist[1]-tlist[0] if n_e_ops == 0: result_list = [] else: result_list = [] for op in e_ops: if op.isherm and rho0.isherm: result_list.append(zeros(n_tsteps)) else: result_list.append(zeros(n_tsteps,dtype=complex)) # # transform the initial density matrix and the e_ops opterators to the # eigenbasis # if ekets != None: rho0 = rho0.transform(ekets) for n in arange(len(e_ops)): e_ops[n] = e_ops[n].transform(ekets, False) # # setup integrator # initial_vector = mat2vec(rho0.full()) r = scipy.integrate.ode(cyq_ode_rhs) r.set_f_params(R.data.data, R.data.indices, R.data.indptr) r.set_integrator('zvode', method=opt.method, order=opt.order, atol=opt.atol, rtol=opt.rtol, #nsteps=opt.nsteps, #first_step=opt.first_step, min_step=opt.min_step, max_step=opt.max_step) r.set_initial_value(initial_vector, tlist[0]) # # start evolution # rho = Qobj(rho0) t_idx = 0 for t in tlist: if not r.successful(): break; rho.data = vec2mat(r.y) # calculate all the expectation values, or output rho if no operators if n_e_ops == 0: result_list.append(Qobj(rho)) else: for m in range(0, n_e_ops): result_list[m][t_idx] = expect(e_ops[m], rho) r.integrate(r.t + dt) t_idx += 1 return result_list
def param_evolution_with_layers(func, maxfev, l, *argus): # Start by finding the minima for first layer """ Heart of the QAOA evolution with layers. Adds layer-by-layer in order to find the optimal parameters for the wanted number of layers l. Parameters ---------- func : callable The objective function to be minimized. argus: tuple Tuple of any additional fixed parameters needed to completely specify the function. maxfev : int Maximum number of func evalution allowed. This is done in order to restrain the budget of function calls (expensive) l : int Number of layers in QAOA Returns ------- param: array set of optimal angles/times that parametrize each layer of QAOA for best result. cost: array Best approximation ratio achieved for each layer. dimension of the array is l. """ psi_0, H_0, H_c, H_c_plus = argus cost = [] param = [] if parametres.problem == 'MKC': bounds = [(-2 * np.pi, 2 * np.pi), (-2 * np.pi, 2 * np.pi)] maxit = int(maxfev / (5 * 2) - 1) print('layer 1 beginning') res = differential_evolution(func, bounds, args=argus, strategy='best1bin', maxiter=maxit * 5, popsize=5, tol=0.00001, mutation=1.6, recombination=0.7, seed=None, callback=None, disp=False, polish=True, init='latinhypercube', atol=0, updating='deferred', workers=-1) x = res.x print('approximation ratio achieved:', abs(res.fun / np.min(H_c))) param.append(x.tolist()) cost.append(np.real(res.fun / np.min(H_c))) # educated guess for next layers for i in range(l - 1): nou_pop = new_population(x) A = [(0.0001, np.pi) for i in range(len(nou_pop[0]) // 2)] B = [(0.0001, np.pi / 2) for i in range(len(nou_pop[0]) // 2)] bounds = np.concatenate((A, B)) print(i + 2, 'layers beginning') res = differential_evolution(func, bounds, args=argus, strategy='best1bin', maxiter=maxit, popsize=5, tol=0.00001, mutation=1.6, recombination=0.7, seed=None, callback=None, disp=False, polish=True, init=nou_pop, atol=0, updating='deferred', workers=-1) x = res.x print('approximation ratio achieved:', abs(res.fun / np.min(H_c))) param.append(x.tolist()) cost.append(np.real(abs(res.fun / np.min(H_c)))) if parametres.problem == 'MIS': bounds = [(-np.pi / 2, np.pi / 2), (-np.pi / 4, np.pi / 4), (-np.pi / 4, np.pi / 4)] maxit = int(maxfev / (5 * 2) - 1) print('layer 1 beginning') res = differential_evolution(func, bounds, args=argus, strategy='best1bin', maxiter=5 * maxit, popsize=5, tol=0.00001, mutation=(0.5, 1.2), recombination=0.7, seed=None, callback=None, disp=False, polish=True, init='latinhypercube', atol=0, updating='deferred', workers=-1) x = res.x psi = quantum_loop(psi_0, H_0, H_c_plus, x) mod_cost = qutip.expect(H_c, psi) print('approximation ratio achieved:', abs(res.fun / np.min(H_c))) param.append(x.tolist()) cost.append(np.real(abs(mod_cost / np.min(H_c)))) # educated guess for next layers for i in range(l - 1): nou_pop = new_population(x) f = len(nou_pop[0]) A = [(-2 * np.pi, 2 * np.pi) for i in range(f // 2)] B = [(-2 * np.pi, 2 * np.pi) for i in range(f - f // 2)] bounds = np.concatenate((A, B)) print(i + 2, 'layers beginning') res = differential_evolution(func, bounds, args=argus, strategy='best1bin', maxiter=5 * maxit, popsize=5, tol=0.00001, mutation=(0.5, 1.2), recombination=0.7, seed=None, callback=None, disp=False, polish=True, init=nou_pop, atol=0, updating='deferred', workers=-1) x = res.x func_res = res.fun for ii in range(5): if ((abs(func_res / np.min(H_c)) <= cost[-1]) or (abs(x[:f // 2][-1]) < 1e-2 and abs(x[-1] < 1e-2))): print("starting layer again..") res = differential_evolution(func, bounds, args=argus, strategy='best1bin', maxiter=5 * maxit, popsize=5, tol=0.00001, mutation=(0.5, 1.2), recombination=0.7, seed=None, callback=None, disp=False, polish=True, init=nou_pop, atol=0, updating='deferred', workers=-1) x = res.x func_res = res.fun else: break psi = quantum_loop(psi_0, H_0, H_c_plus, x) mod_cost = qutip.expect(H_c, psi) print('approximation ratio achieved:', abs(res.fun / np.min(H_c))) param.append(x.tolist()) cost.append(np.real(abs(mod_cost / np.min(H_c)))) return param, cost
def state_xyz(state, n): X, Y, Z = qutip.jmat((n-1.)/2.) x = qutip.expect((2/(n-1.))*X, state) y = qutip.expect((2/(n-1.))*Y, state) z = qutip.expect((2/(n-1.))*Z, state) return [x, y, z]
def test_pure_dephasing(self): """ HSolverDL: Compare with pure-dephasing analytical assert that the analytical result and HEOM produce the same time dephasing evoltion. """ resid_tol = 1e-4 def spectral_density(omega, lam_c, omega_c): return 2.0 * lam_c * omega * omega_c / (omega_c**2 + omega**2) def integrand(omega, lam_c, omega_c, Temp, t): J = spectral_density(omega, lam_c, omega_c) return (-4.0 * J * (1.0 - cos(omega * t)) / (tanh(omega / (2.0 * Temp)) * omega**2)) cut_freq = 0.05 coup_strength = 0.025 temperature = 1.0 / 0.95 tlist = np.linspace(0, 10, 21) # Calculate the analytical results by numerical integration lam_c = coup_strength / pi PEG_DL = [ 0.5 * np.exp( quad(integrand, 0, np.inf, args=(lam_c, cut_freq, temperature, t))[0]) for t in tlist ] H_sys = Qobj(np.zeros((2, 2))) Q = sigmaz() initial_state = 0.5 * Qobj(np.ones((2, 2))) P12p = basis(2, 0) * basis(2, 1).dag() integ_options = Options(nsteps=15000, store_states=True) test_desc = "renorm, bnd_cut_approx, and stats" hsolver = HSolverDL(H_sys, Q, coup_strength, temperature, 20, 2, cut_freq, renorm=True, bnd_cut_approx=True, options=integ_options, stats=True) result = hsolver.run(initial_state, tlist) P12_result1 = expect(result.states, P12p) resid = abs(real(P12_result1 - PEG_DL)) max_resid = max(resid) assert_( max_resid < resid_tol, "Max residual {} outside tolerence {}, " "for hsolve with {}".format(max_resid, resid_tol, test_desc)) resid_tol = 1e-3 test_desc = "renorm" hsolver.configure(H_sys, Q, coup_strength, temperature, 20, 2, cut_freq, renorm=True, bnd_cut_approx=False, options=integ_options, stats=False) assert_(hsolver.stats == None, "Failed to unset stats") result = hsolver.run(initial_state, tlist) P12_result1 = expect(result.states, P12p) resid = abs(real(P12_result1 - PEG_DL)) max_resid = max(resid) assert_( max_resid < resid_tol, "Max residual {} outside tolerence {}, " "for hsolve with {}".format(max_resid, resid_tol, test_desc)) resid_tol = 1e-4 test_desc = "bnd_cut_approx" hsolver.configure(H_sys, Q, coup_strength, temperature, 20, 2, cut_freq, renorm=False, bnd_cut_approx=True, options=integ_options, stats=False) assert_(hsolver.stats == None, "Failed to unset stats") result = hsolver.run(initial_state, tlist) P12_result1 = expect(result.states, P12p) resid = abs(real(P12_result1 - PEG_DL)) max_resid = max(resid) assert_( max_resid < resid_tol, "Max residual {} outside tolerence {}, " "for hsolve with {}".format(max_resid, resid_tol, test_desc))
# In[4]: # An entanglement witness which is appropriate for our target state, as a qutip.Qobj EntglWitness = (- qutip.qeye(4) # how do you "collapse systems together" with qutip?? we could do this with np.kron() also... - qutip.Qobj(qutip.tensor(qutip.sigmax(),qutip.sigmay()).data,dims=[[4],[4]]) + qutip.Qobj(qutip.tensor(qutip.sigmay(),qutip.sigmax()).data,dims=[[4],[4]]) - qutip.Qobj(qutip.tensor(qutip.sigmaz(),qutip.sigmaz()).data,dims=[[4],[4]]) ) display(EntglWitness) # In[5]: # Value for rho_target_Bell maximally entangled state: +2 display(qutip.expect(EntglWitness, rho_target_Bell)) # In[6]: # but you can show that for any separable state this value is <= 0. For example: display(qutip.expect(EntglWitness, qutip.qeye(4)/4)) display(qutip.expect(EntglWitness, qutip.Qobj(np.array([1,0,0,0])))) display(qutip.expect(EntglWitness, 0.5*qutip.ket2dm(qutip.Qobj(np.array([0,1,0,0]))) + 0.5*qutip.ket2dm(qutip.Qobj(np.array([0,0,1,0]))))) # In[7]: # Now, we're ready to run our tomography procedure. We'll be estimating # the expectation value of the entanglement witness.
def test_broadcast_state_list(self, operator, states, expected): result = qutip.expect(operator, states) expected_dtype = np.float64 if operator.isherm else np.complex128 assert isinstance(result, np.ndarray) assert result.dtype == expected_dtype assert list(result) == list(expected)
def test_operator_by_basis(self, operator, state, expected): result = qutip.expect(operator, state) assert result == expected assert isinstance(result, float if operator.isherm else complex)
def f(op, psi): return qt.expect(op, psi)
H1, Hint = JC(16, 0.37, 6, Phi) #H2 = JC(16,0.37,7,Phi) H1.tidyup(atol=1e-1) evals1, evecs1 = H1.eigenstates() gnd = evecs1[0] first = evecs1[1] second = evecs1[2] #gnd_to_first = gnd*first.dag() #gnd_to_first = 0.5*(gnd_to_first + gnd_to_first.dag()) #first_to_second = first*second.dag() #first_to_second = 0.5*(first_to_second + first_to_second.dag()) expect1.append(qt.expect(Hint, first * first.dag())) expect2.append(qt.expect(Hint, second * second.dag())) #expect1.append(np.abs(qt.expect(Hint,gnd_to_first))) #expect2.append(np.abs(qt.expect(Hint,first_to_second))) #evals2 = H2.eigenenergies() Eval_mat1[i, :] = np.real(evals1) #Eval_mat2[i,:] = np.real(evals2) print(first) #print(min(expect2)) for i in range(3): plt.plot(phi, (Eval_mat1[:, i] - Eval_mat1[:, 0]) / (2 * np.pi)) plt.xlabel(r'$\frac{\Phi}{2\pi}$') plt.ylabel('Frequency [GHz]') plt.title('$\omega_{01} > \omega_{r}$')
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 pretty_measurements(self, harmonic1D=False, harmonic2D=False): s = "" ops, eigs = self.paulis() signs = ["X", "Y", "Z"] keys = ["f", "g", "h"] for i in range(len(ops)): op = ops[i] L, V = eigs[i] s += " %s '%s': %.2f\n" % (signs[i], keys[i], qt.expect(op, self.state)) for j in range(len(V)): amplitude = self.state.overlap(V[j]) probability = (amplitude * np.conjugate(amplitude)).real s += "\t%.2f\t%.2f%%\n" % (L[j], probability * 100) s += " H 'y': %.2f (energy)\n" % (qt.expect( self.energy, self.state)) L, V = self.eigenenergies() for j in range(len(V)): amplitude = self.state.overlap(V[j]) probability = (amplitude * np.conjugate(amplitude)).real s += "\t%.2f\t%.2f%%\n" % (L[j], probability * 100) s += " R 't' (random)\n" if harmonic1D: fock, ops, stuff = self.fock1D() s += " -------------------------------\n" s += "\n 1d harmonic oscillator:\n" s += " position ';':\n" L, V = ops["position"].eigenstates() for j in range(len(V)): amplitude = fock.overlap(V[j]) probability = (amplitude * np.conjugate(amplitude)).real s += " \t%.2f\t%.2f%%\n" % (L[j], probability * 100) s += " momentum ''':\n" L, V = ops["momentum"].eigenstates() for j in range(len(V)): amplitude = fock.overlap(V[j]) probability = (amplitude * np.conjugate(amplitude)).real s += " \t%.2f\t%.2f%%\n" % (L[j], probability * 100) s += " number '\\': %.2f\n" % stuff["number"] L, V = ops["number"].eigenstates() for j in range(len(V)): amplitude = fock.overlap(V[j]) probability = (amplitude * np.conjugate(amplitude)).real s += " \t%.2f\t%.2f%%\n" % (L[j], probability * 100) s += " energy '=': %.2f\n" % stuff["energy"] L, V = ops["energy"].eigenstates() for j in range(len(V)): amplitude = fock.overlap(V[j]) probability = (amplitude * np.conjugate(amplitude)).real s += " \t%.2f\t%.2f%%\n" % (L[j], probability * 100) if harmonic2D: s += " -------------------------------\n" fock, ops, stuff = self.fock2D() s += "\n 2d harmonic oscillator:\n" s += " X position:\n" L, V = ops["X"]["position"].eigenstates() for j in range(len(V)): amplitude = fock.overlap(V[j]) probability = (amplitude * np.conjugate(amplitude)).real s += " \t%.2f\t%.2f%%\n" % (L[j], probability * 100) s += " Y position:\n" L, V = ops["Y"]["position"].eigenstates() for j in range(len(V)): amplitude = fock.overlap(V[j]) probability = (amplitude * np.conjugate(amplitude)).real s += " \t%.2f\t%.2f%%\n" % (L[j], probability * 100) s += " X momentum:\n" L, V = ops["X"]["momentum"].eigenstates() for j in range(len(V)): amplitude = fock.overlap(V[j]) probability = (amplitude * np.conjugate(amplitude)).real s += " \t%.2f\t%.2f%%\n" % (L[j], probability * 100) s += " Y momentum:\n" L, V = ops["Y"]["momentum"].eigenstates() for j in range(len(V)): amplitude = fock.overlap(V[j]) probability = (amplitude * np.conjugate(amplitude)).real s += " \t%.2f\t%.2f%%\n" % (L[j], probability * 100) s += " number in x: %.2f\n" % stuff["number"][0] L, V = ops["X"]["number"].eigenstates() for j in range(len(V)): amplitude = fock.overlap(V[j]) probability = (amplitude * np.conjugate(amplitude)).real s += " \t%.2f\t%.2f%%\n" % (L[j], probability * 100) s += " number in y: %.2f\n" % stuff["number"][1] L, V = ops["Y"]["number"].eigenstates() for j in range(len(V)): amplitude = fock.overlap(V[j]) probability = (amplitude * np.conjugate(amplitude)).real s += " \t%.2f\t%.2f%%\n" % (L[j], probability * 100) s += " energy: %.2f\n" % stuff["energy"] L, V = ops["T"].eigenstates() for j in range(len(V)): amplitude = fock.overlap(V[j]) probability = (amplitude * np.conjugate(amplitude)).real s += " \t%.2f\t%.2f%%\n" % (L[j], probability * 100) return s
def generic_ode_solve(r, psi0, tlist, expt_ops, opt, state_vectorize): """ Internal function for solving ODEs. """ # # prepare output array # n_tsteps = len(tlist) dt = tlist[1] - tlist[0] output = Odedata() output.times = tlist if isinstance(expt_ops, FunctionType): n_expt_op = 0 expt_callback = True elif isinstance(expt_ops, list): n_expt_op = len(expt_ops) expt_callback = False if n_expt_op == 0: output.states = [] else: output.expect = [] output.num_expect = n_expt_op for op in expt_ops: if op.isherm and psi0.isherm: output.expect.append(zeros(n_tsteps)) else: output.expect.append(zeros(n_tsteps, dtype=complex)) else: raise TypeError("Expectation parameter must be a list or a function") # # start evolution # psi = Qobj(psi0) t_idx = 0 for t in tlist: if not r.successful(): break psi.data = state_vectorize(r.y) if expt_callback: # use callback method expt_ops(t, Qobj(psi)) else: # calculate all the expectation values, or output rho if no operators if n_expt_op == 0: output.states.append(Qobj(psi)) # copy psi/rho else: for m in range(0, n_expt_op): output.expect[m][t_idx] = expect(expt_ops[m], psi) r.integrate(r.t + dt) t_idx += 1 if not opt.rhs_reuse and odeconfig.tdname != None: try: os.remove(odeconfig.tdname + ".pyx") except: print('Error removing ' + str(odeconfig.tdname) + ".pyx file") pass return output
def hermitian_basis(self): bases = self.hermitian_bases() vector = [qt.expect(basis[0], self.state) for basis in bases] return vector, bases
def channel(self, loss, dephasing, rep=1, verbose=False): """ Computes logical channel """ data_kraus = loss.kraus ancilla_phase = loss.propagate(self.ancilla_dim, self.code.N, self.M) out_phase = loss.propagate(self.code_out.dim, self.code.N, self.code_out.N) nkraus = len(data_kraus) ndata_meas = len(self.data_meas.povm_elements) nancilla_meas = len(self.ancilla_meas.povm_elements) pmat = np.zeros((nancilla_meas, nkraus), dtype=complex) cmat = np.zeros((ndata_meas, nkraus, 2, 2), dtype=complex) # compute p(x|k) and c(y|k;a;b) matrices for k, (n, p) in enumerate(zip(data_kraus, ancilla_phase)): pmat[:, k] = [qt.expect(m, p*self.ancilla_state*p.dag()) for m in self.ancilla_meas.povm_elements] cmat[:, k, :, :] = np.reshape( [qt.expect(m, n*dephasing(keta*ketb.dag())*n.dag()) for m in self.data_meas.povm_elements for keta in [self.code.plus, self.code.minus] for ketb in [self.code.plus, self.code.minus]], cmat[:, k, :, :].shape) # compute p(x1,...,xn|k) matrix pnmat = np.zeros((*[nancilla_meas]*rep, nkraus), dtype=complex) for k in range(nkraus): out = pmat[:, k] for i in range(rep-1): out = np.outer(pmat[:, k], out) pnmat[..., k] = out.reshape(*[nancilla_meas]*rep) # compute q(y|k;a) matrix qmat = np.diagonal(cmat, axis1=2, axis2=3) # compute p(x;y|k;a) = p(x|k)q(y|k;a) matrix pqmat = np.zeros((*[nancilla_meas]*rep, ndata_meas, nkraus, 2), dtype=complex) for k in range(nkraus): for a in range(2): pqmat[..., k, a] = (np.outer(pnmat[..., k], qmat[:, k, a]) ).reshape(*[nancilla_meas]*rep, ndata_meas) # determine most likely k and a kamat = np.empty((*[nancilla_meas]*rep, ndata_meas), dtype=object) # for x in range(nancilla_meas): for x in np.ndindex(*[nancilla_meas]*rep): for y in range(ndata_meas): idx = x + (y, Ellipsis) k, a = np.unravel_index(np.argmax(pqmat[idx]), pqmat[idx].shape) kamat[x + (y,)] = (k, a) # construct channel channel = qt.Qobj() clogical = [self.code_out.logical_H_allspace, self.code_out.logical_X_allspace * self.code_out.logical_H_allspace] recs = [] for k, p in enumerate(out_phase): for a, ca in enumerate(clogical): for b, cb in enumerate(clogical): # for x in range(nancilla_meas): for x in np.ndindex(*[nancilla_meas]*rep): for y in range(ndata_meas): xyidx = x + (y,) r = ( clogical[kamat[xyidx][1]].dag() * out_phase[kamat[xyidx][0]].dag()) recs.append(qt.sprepost(r, r.dag())) if verbose: tmp = np.abs(pnmat[x + (k,)]*cmat[y, k, a, b]) if (tmp > 1e-5 and (k != kamat[xyidx][0] or a != kamat[xyidx][1])): print('syndrome:', k, kamat[xyidx][0], tmp) print(a, b, kamat[xyidx][1]) channel += (pnmat[x + (k,)]*cmat[y, k, a, b] * qt.sprepost(r*p*ca, cb.dag()*p.dag()*r.dag())) self.recs = recs return 0.5*channel
def test(): gamma = 1. neq = 2 psi0 = qt.basis(neq,neq-1) #a = qt.destroy(neq) #ad = a.dag() #H = ad*a #c_ops = [gamma*a] #e_ops = [ad*a] H = qt.sigmax() c_ops = [np.sqrt(gamma)*qt.sigmax()] #c_ops = [] e_ops = [qt.sigmam()*qt.sigmap(),qt.sigmap()*qt.sigmam()] #e_ops = [] # Times T = 2.0 dt = 0.1 nstep = int(T/dt) tlist = np.linspace(0,T,nstep) ntraj=100 # set options opts = qt.Odeoptions() opts.num_cpus=2 #opts.mc_avg = True #opts.gui=False #opts.max_step=1000 #opts.atol = #opts.rtol = sol_f90 = qt.Odedata() start_time = time.time() sol_f90 = mcf90.mcsolve_f90(H,psi0,tlist,c_ops,e_ops,ntraj=ntraj,options=opts) print "mcsolve_f90 solutiton took", time.time()-start_time, "s" sol_me = qt.Odedata() start_time = time.time() sol_me = qt.mesolve(H,psi0,tlist,c_ops,e_ops,options=opts) print "mesolve solutiton took", time.time()-start_time, "s" sol_mc = qt.Odedata() start_time = time.time() sol_mc = qt.mcsolve(H,psi0,tlist,c_ops,e_ops,ntraj=ntraj,options=opts) print "mcsolve solutiton took", time.time()-start_time, "s" if (e_ops == []): e_ops = [qt.sigmam()*qt.sigmap(),qt.sigmap()*qt.sigmam()] sol_f90expect = [np.array([0.+0.j]*nstep)]*len(e_ops) sol_mcexpect = [np.array([0.+0.j]*nstep)]*len(e_ops) sol_meexpect = [np.array([0.+0.j]*nstep)]*len(e_ops) for i in range(len(e_ops)): if (not opts.mc_avg): sol_f90expect[i] = sum([qt.expect(e_ops[i], sol_f90.states[j]) for j in range(ntraj)])/ntraj sol_mcexpect[i] = sum([qt.expect(e_ops[i], sol_mc.states[j]) for j in range(ntraj)])/ntraj else: sol_f90expect[i] = qt.expect(e_ops[i],sol_f90.states) sol_mcexpect[i] = qt.expect(e_ops[i],sol_mc.states) sol_meexpect[i] = qt.expect(e_ops[i],sol_me.states) elif (not opts.mc_avg): sol_f90expect = sum(sol_f90.expect,0)/ntraj sol_mcexpect = sum(sol_f90.expect,0)/ntraj sol_meexpect = sol_me.expect else: sol_f90expect = sol_f90.expect sol_mcexpect = sol_mc.expect sol_meexpect = sol_me.expect plt.figure() for i in range(len(e_ops)): plt.plot(tlist,sol_f90expect[i],'b') plt.plot(tlist,sol_mcexpect[i],'g') plt.plot(tlist,sol_meexpect[i],'k') return sol_f90, sol_mc
def spinor_xyz(spinor): if isinstance(spinor, np.ndarray): spinor = qt.Qobj(spinor) return np.array([qt.expect(qt.sigmax(), spinor),\ qt.expect(qt.sigmay(), spinor),\ qt.expect(qt.sigmaz(), spinor)])