def binomial(hilbert_size, S=None, N=None, mu=None): """ Binomial code """ if S == None: S = np.random.randint(1, 10) if N == None: Nmax = int((hilbert_size)/(S+1)) - 1 try: N = np.random.randint(2, Nmax) except: N = Nmax if mu is None: mu = np.random.randint(2) c = 1/sqrt(2**(N+1)) psi = 0*fock(hilbert_size, 0) for m in range(N): psi += c*((-1)**(mu*m))*np.sqrt(binom(N+1, m))*fock(hilbert_size, (S+1)*m) rho = psi*psi.dag() return rho.unit(), mu
def vec_derivative(theta, phi, dtheta, dphi): """ """ dpsi_dt = -1 * np.sin(theta / 2) * dtheta / 2 * qt.fock(2, 0) \ + np.exp(1j * phi) * (np.cos(theta / 2) * dtheta / 2 + \ 1j * dphi * np.sin(theta / 2)) * qt.fock(2, 1) return dpsi_dt
def fock(self, *args, **kwargs): """Returns a product state in the Fock basis. States can be specified either positionally or as keyword arguments. Args: *args (tuple): Fock states of Modes in the order of self.modes. **kwargs (dict): Fock states of Modes specified as keyword arguments, mode_name=n. Returns: ``qutip.Qobj``: The requested product state. """ if args: if kwargs: raise ValueError("If positional arguments are provided, " "no keyword arguments are allowed.") if len(args) != len(self.active_modes): raise ValueError( "The number of positional argument must match " "the number of active modes.") states = [ qutip.fock(mode.levels, val) for mode, val in zip(self.active_modes, args) ] else: states = [ qutip.fock(mode.levels, kwargs.get(mode.name, 0)) for mode in self.active_modes ] return self.tensor(*states)
def measure(self, qubit_name, non_destructive): res = None M_0 = qutip.fock(2, 0).proj() M_1 = qutip.fock(2, 1).proj() self._lock() target = self._qubit_names.index(qubit_name) if self.N > 1: M_0 = qutip.gate_expand_1toN(M_0, self.N, target) M_1 = qutip.gate_expand_1toN(M_1, self.N, target) pr_0 = qutip.expect(M_0, self.data) pr_1 = qutip.expect(M_1, self.data) outcome = int(np.random.choice([0, 1], 1, p=[pr_0, pr_1])) if outcome == 0: self.data = M_0 * self.data * M_0.dag() / pr_0 res = 0 else: # M_1 = qutip.gate_expand_1toN(M_1, self.N, target) self.data = M_1 * self.data * M_1.dag() / pr_1 res = 1 if non_destructive is False: i_list = [x for x in range(self.N)] i_list.remove(target) self._qubit_names.remove(qubit_name) self.N = self.N - 1 if len(i_list) > 0: self.data = self.data.ptrace(i_list) else: self.data = qutip.Qobj() self._unlock() return res
def __init__(self, data, label, **kwargs): self.M = len(data) # number of training data self.N = len(data[0]) # length of training vectors if len(data) != len(label): exit('Error: not same number of data and labels!') self.norms = [] self.qstates = [] # Prepare quantum states of training data # Very important for states x and labels y is that the fock state |0> is not # used to encode the classical data --> indices start at 1 not 0!! for i in data: i = np.array(i) norm = np.linalg.norm(i) self.state = 1 / norm * \ sum([i[k - 1] * qt.fock(self.N + 1, k) for k in range(1, self.N + 1)]) self.qstates.append(self.state.unit()) # save quantum states self.norms.append(norm) # save classical norms # make qstate for label vector self.qlabels = 1 / (np.linalg.norm(label)) * sum([ label[i - 1] * qt.fock(self.M + 1, i) for i in range(1, self.M + 1) ]) # construct oracle operator for training self.Train_Oracle = sum([ qt.tensor( self.norms[i - 1] * self.qstates[i - 1] * qt.fock(self.M + 1, 0).dag(), qt.fock(self.M + 1, i) * qt.fock(self.M + 1, i).dag()) for i in range(1, self.M + 1) ])
def test_fn_list_td_corr2(): """ correlation: multi time-dependent factor """ # test for bug of issue #1048 sm = destroy(2) args = {} def step_func(t, args={}): return np.arctan(t - 2) / np.pi + 0.5 def inv_step_func(t, args={}): return np.arctan(-(t - 2)) / np.pi + 0.5 H1 = [[(sm + sm.dag()), step_func], [qeye(2), inv_step_func]] H2 = [[qeye(2), inv_step_func], [(sm + sm.dag()), step_func]] tlist = np.linspace(0, 5, 6) corr1 = correlation_2op_2t(H1, fock(2, 0), tlist, tlist, [sm], sm.dag(), sm, args=args) corr2 = correlation_2op_2t(H2, fock(2, 0), tlist, tlist, [sm], sm.dag(), sm, args=args) assert_(np.sum(np.abs(corr1 - corr2)) < 1e-5)
def test_fn_list_td_corr(): """ correlation: comparing TLS emission correlations (fn-list td format) """ # calculate emission zero-delay second order correlation, g2(0), for TLS # with following parameters: # gamma = 1, omega = 2, tp = 0.5 # Then: g2(0)~0.57 sm = destroy(2) args = {"t_off": 1, "tp": 0.5} H = [[2 * (sm+sm.dag()), lambda t, args: np.exp(-(t-args["t_off"])**2 / (2*args["tp"]**2))]] tlist = linspace(0, 5, 50) corr = correlation_3op_2t(H, fock(2, 0), tlist, tlist, [sm], sm.dag(), sm.dag() * sm, sm, args=args) # integrate w/ 2D trapezoidal rule dt = (tlist[-1]-tlist[0]) / (np.shape(tlist)[0]-1) s1 = corr[0, 0] + corr[-1, 0] + corr[0, -1] + corr[-1, -1] s2 = sum(corr[1:-1, 0]) + sum(corr[1:-1, -1]) + \ sum(corr[0, 1:-1]) + sum(corr[-1, 1:-1]) s3 = sum(corr[1:-1, 1:-1]) exp_n_in = np.trapz( mesolve( H, fock(2, 0), tlist, [sm], [sm.dag()*sm], args=args ).expect[0], tlist ) # factor of 2 from negative time correlations g20 = abs( sum(0.5*dt**2*(s1 + 2*s2 + 4*s3)) / exp_n_in**2 ) assert_(abs(g20-0.57) < 1e-1)
def get_single_gate_data(): inputs = [] h = tensor_fix(qt.hadamard_transform()) zero = tensor_fix(qt.fock(2, 0)) one = tensor_fix(qt.fock(2, 1)) inputs.append(h * zero) inputs.append(h * one) inputs.append(h * zero) inputs.append(h * one) gate = paulix(1, 0) ideal = get_ideal([gate], inputs, inputs, 1, 4) tag = "X" pop = input("how may data points? ") pop = int(pop) path = "SingleDoubleHada2000.csv" probabilities = [] for i in range(pop): alt_gate = alter(gate) temparray = [] for state in inputs: final = basic_b(state, [alt_gate]) prob = dis(final, state) temparray.append(prob) if within_tolerance(0.78, temparray, ideal[0]): temparray.append("tolerance") else: temparray.append(tag) probabilities.append(temparray) with open(path, 'a', newline='') as csvFile: writer = csv.writer(csvFile) writer.writerow(temparray) csvFile.close return probabilities
def test_H_str_list_td_corr(): """ correlation: comparing TLS emission corr., H td (str-list td format) """ # calculate emission zero-delay second order correlation, g2[0], for TLS # with following parameters: # gamma = 1, omega = 2, tp = 0.5 # Then: g2(0)~0.57 sm = destroy(2) args = {"t_off": 1, "tp": 0.5} H = [[2 * (sm + sm.dag()), "exp(-(t-t_off)**2 / (2*tp**2))"]] tlist = np.linspace(0, 5, 50) corr = correlation_3op_2t(H, fock(2, 0), tlist, tlist, [sm], sm.dag(), sm.dag() * sm, sm, args=args) # integrate w/ 2D trapezoidal rule dt = (tlist[-1] - tlist[0]) / (np.shape(tlist)[0] - 1) s1 = corr[0, 0] + corr[-1, 0] + corr[0, -1] + corr[-1, -1] s2 = sum(corr[1:-1, 0]) + sum(corr[1:-1, -1]) + \ sum(corr[0, 1:-1]) + sum(corr[-1, 1:-1]) s3 = sum(corr[1:-1, 1:-1]) exp_n_in = np.trapz( mesolve(H, fock(2, 0), tlist, [sm], [sm.dag() * sm], args=args).expect[0], tlist) # factor of 2 from negative time correlations g20 = abs(sum(0.5 * dt**2 * (s1 + 2 * s2 + 4 * s3)) / exp_n_in**2) assert_(abs(g20 - 0.59) < 1e-2)
def test_np_list_td_corr(): """ correlation: comparing TLS emission corr. (np-list td format) """ # both H and c_ops are time-dependent # calculate emission zero-delay second order correlation, g2[0], for TLS # with following parameters: # gamma = 1, omega = 2, tp = 0.5 # Then: g2(0)~0.85 sm = destroy(2) t_off = 1 tp = 0.5 tlist = np.linspace(0, 5, 50) H = [[2 * (sm + sm.dag()), np.exp(-(tlist - t_off)**2 / (2 * tp**2))]] c_ops = [ sm, [sm.dag() * sm * 2, np.exp(-(tlist - t_off)**2 / (2 * tp**2))] ] corr = correlation_3op_2t(H, fock(2, 0), tlist, tlist, [sm], sm.dag(), sm.dag() * sm, sm) # integrate w/ 2D trapezoidal rule dt = (tlist[-1] - tlist[0]) / (np.shape(tlist)[0] - 1) s1 = corr[0, 0] + corr[-1, 0] + corr[0, -1] + corr[-1, -1] s2 = sum(corr[1:-1, 0]) + sum(corr[1:-1, -1]) + \ sum(corr[0, 1:-1]) + sum(corr[-1, 1:-1]) s3 = sum(corr[1:-1, 1:-1]) exp_n_in = np.trapz( mesolve(H, fock(2, 0), tlist, c_ops, [sm.dag() * sm]).expect[0], tlist) # factor of 2 from negative time correlations g20 = abs(sum(0.5 * dt**2 * (s1 + 2 * s2 + 4 * s3)) / exp_n_in**2) assert_(abs(g20 - 0.85) < 1e-2)
def test_c_ops_fn_list_td_corr(): """ correlation: comparing 3LS emission corr., c_ops td (fn-list td format) """ # calculate zero-delay HOM cross-correlation, for incoherently pumped # 3LS ladder system g2ab[0] # with following parameters: # gamma = 1, 99% initialized, tp = 0.5 # Then: g2ab(0)~0.185 tlist = np.linspace(0, 6, 20) ket0 = fock(3, 0) ket1 = fock(3, 1) ket2 = fock(3, 2) sm01 = ket0 * ket1.dag() sm12 = ket1 * ket2.dag() psi0 = fock(3, 2) tp = 1 # define "pi" pulse as when 99% of population has been transferred Om = np.sqrt(-np.log(1e-2) / (tp * np.sqrt(np.pi))) c_ops = [ sm01, [ sm12 * Om, lambda t, args: np.exp(-(t - args["t_off"])**2 / (2 * args["tp"]**2)) ] ] args = {"tp": tp, "t_off": 2} H = qeye(3) * 0 # HOM cross-correlation depends on coherences (g2[0]=0) c1 = correlation_2op_2t(H, psi0, tlist, tlist, c_ops, sm01.dag(), sm01, args=args) c2 = correlation_2op_2t(H, psi0, tlist, tlist, c_ops, sm01.dag(), sm01, args=args, reverse=True) n = mesolve(H, psi0, tlist, c_ops, [sm01.dag() * sm01], args=args).expect[0] n_f = Cubic_Spline(tlist[0], tlist[-1], n) corr_ab = -c1 * c2 + np.array([[n_f(t) * n_f(t + tau) for tau in tlist] for t in tlist]) dt = tlist[1] - tlist[0] gab = abs(np.trapz(np.trapz(corr_ab, axis=0))) * dt**2 assert_(abs(gab - 0.185) < 1e-2)
def En_p(n, p, w0, N): """ Get the transmon energy to p-th order in xi; eqn 10 in Didier (2018) :param n: Hamiltonian energy level :param p: Order of energy calculation :param w0: :param N: :return: """ filename = io.get_dumpname_En(n, p, w0, N) load_check = io.load_obj(filename, io.tempdir) if load_check is not None: # must decode the json str formatting I imposed in io_tools.py return complex(load_check) # 0th order energy is Harmonic Oscillator solution if p == 0: return n * w0 # other orders are found by perturbation theory nket = qt.fock(N, n) out = 0 # reproduce eqn 10 exactly: for q in range(p): psi_raw = psi_n_p(n, q, w0, N) # if psi_n Fock space size is too small, pad it if q <= p - q: psi_n = pad_ket(psi_raw, N + 4 * (p - q)) H = H_u(p - q, w0, N + 4 * (p - q)) nbra = qt.fock(N + 4 * (p - q), n).dag() # if psi_n is larger than the Hamiltonian, H and |n> must be computed to that size elif q > p - q: psi_n = psi_raw H = H_u(p - q, w0, N + 4 * q) nbra = qt.fock(N + 4 * q, n).dag() if DEBUG: print("n=%i, q=%i, p=%i" % (n, q, p)) #print(H) print("Nbra=", nbra) # # print(psi_n_p(n, q, w0, N), N+4*(p-q)) print("PSI=", psi_n.dag()) out += nbra.overlap(H * psi_n) # dump to tempdir for future use io.dump_obj(io.complex2str(out), filename, io.tempdir) return out
def num(hilbert_size, probs=None, mu=None, alpha_range=3): """ number code """ if mu is None: mu = np.random.randint(2) state = fock(hilbert_size, 0)*0 if probs is None: probs = get_random_num_prob() for n, p in enumerate(probs[mu]): state += p*fock(hilbert_size, n) rho = state*state.dag() return rho.unit(), mu
def test_compare_solvers_coherent_state_memc(): """ correlation: comparing me and mc for driven oscillator in ground state """ N = 20 a = destroy(N) H = a.dag() * a + a + a.dag() G1 = 0.75 n_th = 2.00 c_ops = [np.sqrt(G1 * (1 + n_th)) * a, np.sqrt(G1 * n_th) * a.dag()] psi0 = fock(N, 0) taulist = np.linspace(0, 1.0, 5) corr1 = correlation_2op_2t(H, psi0, [0], taulist, c_ops, a.dag(), a, solver="me")[0] corr2 = correlation_2op_2t(H, psi0, [0], taulist, c_ops, a.dag(), a, solver="mc")[0] assert_(max(abs(corr1 - corr2)) < 5e-2)
def test_compare_solvers_coherent_state_memc(): """ correlation: comparing me and mc for driven oscillator in fock state """ N = 2 a = destroy(N) H = a.dag() * a + a + a.dag() G1 = 0.75 n_th = 2.00 c_ops = [np.sqrt(G1 * (1 + n_th)) * a, np.sqrt(G1 * n_th) * a.dag()] psi0 = fock(N, 1) taulist = np.linspace(0, 1.0, 3) corr1 = correlation_2op_2t(H, psi0, [0, 0.5], taulist, c_ops, a.dag(), a, solver="me") corr2 = correlation_2op_2t(H, psi0, [0, 0.5], taulist, c_ops, a.dag(), a, solver="mc") # pretty lax criterion, but would otherwise require a quite long simulation # time assert_(abs(corr1 - corr2).max() < 0.25)
def f(N, options): wa = 1 wc = 0.9 delta = wa - wc g = 2 kappa = 0.5 gamma = 0.1 n_th = 0.75 tspan = np.linspace(0, 10, 11) Ia = qt.qeye(2) Ic = qt.qeye(N) a = qt.destroy(N) at = qt.create(N) sm = qt.sigmam() sp = qt.sigmap() # H = wc*qt.tensor(n, Ia) + qt.tensor(Ic, wa/2.*sz) + g*(qt.tensor(at, sm) + qt.tensor(a, sp)) Ha = g * qt.tensor(at, sm) Hb = g * qt.tensor(a, sp) H = [[Ha, lambda t, args: np.exp(-1j*delta*t)], [Hb, lambda t, args: np.exp(1j*delta*t)]] c_ops = [ qt.tensor(np.sqrt(kappa*(1+n_th)) * a, Ia), qt.tensor(np.sqrt(kappa*n_th) * at, Ia), qt.tensor(Ic, np.sqrt(gamma) * sm), ] psi0 = qt.tensor(qt.fock(N, 0), (qt.basis(2, 0) + qt.basis(2, 1)).unit()) exp_n = qt.mesolve(H, psi0, tspan, c_ops, [qt.tensor(a, sp)], options=options).expect[0] return np.real(exp_n)
def qeye2(N): # create an identity out of adding outer products out = 0 for i in range(N): v = qt.fock(N, i) out += v * v.dag() return out
def test_purity(): """ Test the purity function. """ psi = qt.fock(3) rho_test = qt.ket2dm(psi) test_pure = purity(rho_test) assert_equal( test_pure, 1 )
def iniState1Q1Rsys(Nq: int, Nf: int, s: int, t: int, mode='ket'): q1 = ket(Nq, s) r1 = qt.fock(Nf, t) psi0 = qt.tensor(q1, r1) if mode == 'rho': ini = psi0 * psi0.dag() else: ini = psi0 return ini
def calcDispersiveShift(self): eigenlevels = self.Hlab.eigenstates() e0 = qt.tensor(qt.basis(self.Nq, 1), qt.fock(self.Nf, 0)) g1 = qt.tensor(qt.basis(self.Nq, 0), qt.fock(self.Nf, 1)) e1 = qt.tensor(qt.basis(self.Nq, 1), qt.fock(self.Nf, 1)) ket_try = [e0, g1, e1] ket_keys = ['e0', 'g1', 'e1'] disp_dic = {} for i in range(3): e = np.abs([(ket_try[i].dag() * eigenlevels[1])[j].tr() for j in range(self.Nq * self.Nf)]) index = np.argmax(e) disp_dic[ket_keys[i]] = eigenlevels[0][index] disp_dic['chi'] = (disp_dic['e1'] - disp_dic['e0'] - disp_dic['g1']) / 2 self.dispersiveshift = disp_dic return disp_dic
def test_c_ops_fn_list_td_corr(): """ correlation: comparing 3LS emission corr., c_ops td (fn-list td format) """ # calculate zero-delay HOM cross-correlation, for incoherently pumped # 3LS ladder system g2ab[0] # with following parameters: # gamma = 1, 99% initialized, tp = 0.5 # Then: g2ab(0)~0.185 tlist = np.linspace(0, 6, 20) ket0 = fock(3, 0) ket1 = fock(3, 1) ket2 = fock(3, 2) sm01 = ket0 * ket1.dag() sm12 = ket1 * ket2.dag() psi0 = fock(3, 2) tp = 1 # define "pi" pulse as when 99% of population has been transferred Om = np.sqrt(-np.log(1e-2) / (tp * np.sqrt(np.pi))) c_ops = [sm01, [sm12 * Om, lambda t, args: np.exp(-(t - args["t_off"]) ** 2 / (2 * args["tp"] ** 2))]] args = {"tp": tp, "t_off": 2} H = qeye(3) * 0 # HOM cross-correlation depends on coherences (g2[0]=0) c1 = correlation_2op_2t(H, psi0, tlist, tlist, c_ops, sm01.dag(), sm01, args=args) c2 = correlation_2op_2t(H, psi0, tlist, tlist, c_ops, sm01.dag(), sm01, args=args, reverse=True) n = mesolve( H, psi0, tlist, c_ops, [sm01.dag() * sm01], args=args ).expect[0] n_f = Cubic_Spline(tlist[0], tlist[-1], n) corr_ab = - c1 * c2 + np.array( [[n_f(t) * n_f(t + tau) for tau in tlist] for t in tlist]) dt = tlist[1] - tlist[0] gab = abs(np.trapz(np.trapz(corr_ab, axis=0))) * dt ** 2 assert_(abs(gab - 0.185) < 1e-2)
def tensoredQubit0(N): #Make Qubit matrix res = qt.fock( 2**N).proj() #For some reason ran faster than fock_dm(2**N) in tests #Make dims list dims = [2 for i in range(N)] dims = [dims.copy(), dims.copy()] res.dims = dims #Return return res
def psi_n_p(n, p, w0, N): """ Generate the eigenstate for transmon hamiltonian to p-th order in xi. This is done recursively, and will use calls to En_p, which calls p_sin_p in turn. eqn 11 in Didier (2018) :param n: n refers to the energy level of the system :param p: order of expansion for eigenstate, i.e. p-th order in xi :param w0: :param N: Size of the ORIGINAL Hspace; this will be modified according to the order p of calculation :return: p-th order nth eigenstate PSI, with SIZE = N + 4*p """ filename = io.get_dumpname_Psi(n, p, w0, N) load_check = io.load_obj(filename, io.tempdir) if load_check is not None: if DEBUG: print("loading psi from file %i" % filename) return load_check # adjusted size of Fock state Hspace to account for larger H_u NN = N + 4 * p nket = qt.fock(NN, n) # the zeroth order component of the psi_n is just |n>, in our expanded Hspace if p == 0: return qt.fock(N, n) out = 0 # FIXME: add "+1" to the top limit of the range? for m in range(N + 4 * p): # always ignore m=n because n-th state is fully described by 0th order term if m == n: continue # first term is the pth order hamiltonian on 0th order eigenstates first = qt.fock(N + 4 * p, m).dag() * H_u(p, w0, N + 4 * p) * qt.fock( N + 4 * p, n) * qt.fock(N + 4 * p, m) out += first / (w0 * (n - m)) # remaining terms: varying in size depending on the order of H_u, and so must be padded to N+4*p # the orders of sum over q and sum over m are switched because FIXME!!! for q in range(1, p): for m in range(N + 4 * q): if m == n: continue psi_n_q = psi_n_p(n, q, w0, N) if DEBUG: print("psi_%i(%i) calling get_E_%i(%i)" % (n, p, n, p)) qth = qt.fock(N + 4 * q, m).dag() * ( H_u(p - q, w0, N + 4 * q) - En_p(n, p - q, w0, N + 4 * q)) * psi_n_q * qt.fock( N + 4 * p, m) out += qth / (w0 * (n - m)) io.dump_obj(out, filename, io.tempdir) return out.unit()
def test_H_fn_td_corr(): """ correlation: comparing TLS emission corr., H td (fn td format) """ # calculate emission zero-delay second order correlation, g2[0], for TLS # with following parameters: # gamma = 1, omega = 2, tp = 0.5 # Then: g2(0)~0.57 sm = destroy(2) def H_func(t, args): return 2 * args["H0"] * np.exp(-2 * (t - 1)**2) tlist = linspace(0, 5, 50) corr = correlation_3op_2t(H_func, fock(2, 0), tlist, tlist, [sm], sm.dag(), sm.dag() * sm, sm, args={"H0": sm + sm.dag()}) # integrate w/ 2D trapezoidal rule dt = (tlist[-1] - tlist[0]) / (np.shape(tlist)[0] - 1) s1 = corr[0, 0] + corr[-1, 0] + corr[0, -1] + corr[-1, -1] s2 = sum(corr[1:-1, 0]) + sum(corr[1:-1, -1]) +\ sum(corr[0, 1:-1]) + sum(corr[-1, 1:-1]) s3 = sum(corr[1:-1, 1:-1]) exp_n_in = trapz( mesolve(H_func, fock(2, 0), tlist, [sm], [sm.dag() * sm], args={ "H0": sm + sm.dag() }).expect[0], tlist) # factor of 2 from negative time correlations g20 = abs(sum(0.5 * dt**2 * (s1 + 2 * s2 + 4 * s3)) / exp_n_in**2) assert_(abs(g20 - 0.59) < 1e-2)
def test_np_str_list_td_corr(): """ correlation: comparing 3LS emission corr., c_ops td (np-list td format) """ # calculate zero-delay HOM cross-correlation, for incoherently pumped # 3LS ladder system g2ab[0] # with following parameters: # gamma = 1, 99% initialized, tp = 0.5 # Then: g2ab(0)~0.185 tlist = np.linspace(0, 6, 20) ket0 = fock(3, 0) ket1 = fock(3, 1) ket2 = fock(3, 2) sm01 = ket0 * ket1.dag() sm12 = ket1 * ket2.dag() psi0 = fock(3, 2) tp = 1 t_off = 2 # define "pi" pulse as when 99% of population has been transferred Om = np.sqrt(-np.log(1e-2) / (tp * np.sqrt(np.pi))) c_ops = [sm01, [sm12 * Om, np.exp(-(tlist - t_off) ** 2 / (2 * tp ** 2))]] H = qeye(3) * 0 # HOM cross-correlation depends on coherences (g2[0]=0) c1 = correlation_2op_2t(H, psi0, tlist, tlist, c_ops, sm01.dag(), sm01) c2 = correlation_2op_2t(H, psi0, tlist, tlist, c_ops, sm01.dag(), sm01, reverse=True) n = mesolve( H, psi0, tlist, c_ops, sm01.dag() * sm01 ).expect[0] n_f = interp1d(tlist, n, kind="cubic", fill_value=0, bounds_error=False) corr_ab = - c1 * c2 + np.array( [[n_f(t) * n_f(t + tau) for tau in tlist] for t in tlist]) dt = tlist[1] - tlist[0] gab = abs(np.trapz(np.trapz(corr_ab, axis=0))) * dt ** 2 assert_(abs(gab - 0.185) < 1e-2)
def test_H_np_list_td_corr(): """ correlation: comparing TLS emission corr., H td (np-list td format) """ #from qutip.rhs_generate import rhs_clear #rhs_clear() # calculate emission zero-delay second order correlation, g2[0], for TLS # with following parameters: # gamma = 1, omega = 2, tp = 0.5 # Then: g2(0)~0.57 sm = destroy(2) tp = 0.5 t_off = 1 tlist = np.linspace(0, 5, 50) H = [[2 * (sm + sm.dag()), np.exp(-(tlist - t_off) ** 2 / (2 * tp ** 2))]] corr = correlation_3op_2t(H, fock(2, 0), tlist, tlist, [sm], sm.dag(), sm.dag() * sm, sm) # integrate w/ 2D trapezoidal rule dt = (tlist[-1] - tlist[0]) / (np.shape(tlist)[0] - 1) s1 = corr[0, 0] + corr[-1, 0] + corr[0, -1] + corr[-1, -1] s2 = sum(corr[1:-1, 0]) + sum(corr[1:-1, -1]) + \ sum(corr[0, 1:-1]) + sum(corr[-1, 1:-1]) s3 = sum(corr[1:-1, 1:-1]) exp_n_in = np.trapz( mesolve( H, fock(2, 0), tlist, [sm], [sm.dag() * sm] ).expect[0], tlist ) # factor of 2 from negative time correlations g20 = abs( sum(0.5 * dt ** 2 * (s1 + 2 * s2 + 4 * s3)) / exp_n_in ** 2 ) assert_(abs(g20 - 0.59) < 1e-2)
def test_fn_td_corr(): """ correlation: comparing TLS emission correlations (fn td format) """ # calculate emission zero-delay second order correlation, g2(0), for TLS # with following parameters: # gamma = 1, omega = 2, tp = 0.5 # Then: g2(0)~0.57 sm = destroy(2) def H_func(t, args): return 2 * args["H0"] * np.exp(-2 * (t-1)**2) tlist = linspace(0, 5, 50) corr = correlation_3op_2t(H_func, fock(2, 0), tlist, tlist, [sm], sm.dag(), sm.dag() * sm, sm, args={"H0": sm+sm.dag()}) # integrate w/ 2D trapezoidal rule dt = (tlist[-1]-tlist[0]) / (np.shape(tlist)[0]-1) s1 = corr[0, 0] + corr[-1, 0] + corr[0, -1] + corr[-1, -1] s2 = sum(corr[1:-1, 0]) + sum(corr[1:-1, -1]) +\ sum(corr[0, 1:-1]) + sum(corr[-1, 1:-1]) s3 = sum(corr[1:-1, 1:-1]) exp_n_in = trapz( mesolve( H_func, fock(2, 0), tlist, [sm], [sm.dag()*sm], args={"H0": sm+sm.dag()} ).expect[0], tlist ) # factor of 2 from negative time correlations g20 = abs( sum(0.5*dt**2*(s1 + 2*s2 + 4*s3)) / exp_n_in**2 ) assert_(abs(g20-0.57) < 1e-1)
def test_rhs_reuse(): """ rhs_reuse : pyx filenames match for rhs_reus= True """ N = 10 a = qt.destroy(N) H = [a.dag() * a, [a + a.dag(), 'sin(t)']] psi0 = qt.fock(N, 3) tlist = np.linspace(0, 10, 10) e_ops = [a.dag() * a] c_ops = [0.25 * a] # Test sesolve out1 = qt.mesolve(H, psi0, tlist, e_ops=e_ops) _temp_config_name = config.tdname out2 = qt.mesolve(H, psi0, tlist, e_ops=e_ops) assert_(config.tdname != _temp_config_name) _temp_config_name = config.tdname out3 = qt.mesolve(H, psi0, tlist, e_ops=e_ops, options=qt.Options(rhs_reuse=True)) assert_(config.tdname == _temp_config_name) # Test mesolve out1 = qt.mesolve(H, psi0, tlist, c_ops=c_ops, e_ops=e_ops) _temp_config_name = config.tdname out2 = qt.mesolve(H, psi0, tlist, c_ops=c_ops, e_ops=e_ops) assert_(config.tdname != _temp_config_name) _temp_config_name = config.tdname out3 = qt.mesolve(H, psi0, tlist, e_ops=e_ops, c_ops=c_ops, options=qt.Options(rhs_reuse=True)) assert_(config.tdname == _temp_config_name)
def test_str_list_td_corr(): """ correlation: comparing TLS emission corr. (str-list td format) """ # both H and c_ops are time-dependent # calculate emission zero-delay second order correlation, g2[0], for TLS # with following parameters: # gamma = 1, omega = 2, tp = 0.5 # Then: g2(0)~0.85 sm = destroy(2) args = {"t_off": 1, "tp": 0.5} tlist = np.linspace(0, 5, 50) H = [[2 * (sm + sm.dag()), "exp(-(t-t_off)**2 / (2*tp**2))"]] c_ops = [sm, [sm.dag() * sm * 2, "exp(-(t-t_off)**2 / (2*tp**2))"]] corr = correlation_3op_2t(H, fock(2, 0), tlist, tlist, [sm], sm.dag(), sm.dag() * sm, sm, args=args) # integrate w/ 2D trapezoidal rule dt = (tlist[-1] - tlist[0]) / (np.shape(tlist)[0] - 1) s1 = corr[0, 0] + corr[-1, 0] + corr[0, -1] + corr[-1, -1] s2 = sum(corr[1:-1, 0]) + sum(corr[1:-1, -1]) + \ sum(corr[0, 1:-1]) + sum(corr[-1, 1:-1]) s3 = sum(corr[1:-1, 1:-1]) exp_n_in = np.trapz( mesolve( H, fock(2, 0), tlist, c_ops, [sm.dag() * sm], args=args ).expect[0], tlist ) # factor of 2 from negative time correlations g20 = abs( sum(0.5 * dt ** 2 * (s1 + 2 * s2 + 4 * s3)) / exp_n_in ** 2 ) assert_(abs(g20 - 0.85) < 1e-2)
def kernel(train_oracle, qstat, m, n): # m is number of datasets, n the length of data vector #chi = 1/(np.linalg.norm(norm))*sum([norm[i]*qt.tensor(qt.fock(m,i),qstat[i]) for i in range(0,m)]) chi = train_oracle * \ sum([qt.tensor(qt.fock(m + 1, 0), qt.fock(m + 1, i)) for i in range(1, m + 1)]) # Generate chi by applying Oracle to sum(|i>|0>) #--------------------------------------------------- # Try partial trace manually. def operator(k): return qt.tensor(qt.qeye(n + 1), qt.fock(m + 1, k)) chidens = chi * chi.dag() trace = sum([operator(i).dag() * chidens * operator(i) for i in range(n)]) #------------------------------------------------------------------- # Qutip buildt in function for ptrace # all other components than the 0-th are traced out! trace2 = chidens.ptrace(0) return trace2
def test_steadystate_floquet(sparse): """ Test the steadystate solution for a periodically driven system. """ N_c = 20 a = qutip.destroy(N_c) a_d = a.dag() X_c = a + a_d w_c = 1 A_l = 0.001 w_l = w_c gam = 0.01 H = w_c * a_d * a H_t = [H, [X_c, lambda t, args: args["A_l"] * np.cos(args["w_l"] * t)]] psi0 = qutip.fock(N_c, 0) args = {"A_l": A_l, "w_l": w_l} c_ops = [] c_ops.append(np.sqrt(gam) * a) t_l = np.linspace(0, 20 / gam, 2000) expect_me = qutip.mesolve(H_t, psi0, t_l, c_ops, [a_d * a], args=args).expect[0] rho_ss = qutip.steadystate_floquet(H, c_ops, A_l * X_c, w_l, n_it=3, sparse=sparse) expect_ss = qutip.expect(a_d * a, rho_ss) np.testing.assert_allclose(expect_me[-20:], expect_ss, atol=1e-3) assert rho_ss.tr() == pytest.approx(1, abs=1e-15)
def test_rhs_reuse(): """ rhs_reuse : pyx filenames match for rhs_reus= True """ N = 10 a = qt.destroy(N) H = [a.dag()*a, [a+a.dag(), 'sin(t)']] psi0 = qt.fock(N,3) tlist = np.linspace(0,10,10) e_ops = [a.dag()*a] c_ops = [0.25*a] # Test sesolve out1 = qt.mesolve(H, psi0,tlist, e_ops=e_ops) _temp_config_name = config.tdname out2 = qt.mesolve(H, psi0,tlist, e_ops=e_ops) assert_(config.tdname != _temp_config_name) _temp_config_name = config.tdname out3 = qt.mesolve(H, psi0,tlist, e_ops=e_ops, options=qt.Options(rhs_reuse=True)) assert_(config.tdname == _temp_config_name) # Test mesolve out1 = qt.mesolve(H, psi0,tlist, c_ops=c_ops, e_ops=e_ops) _temp_config_name = config.tdname out2 = qt.mesolve(H, psi0,tlist, c_ops=c_ops, e_ops=e_ops) assert_(config.tdname != _temp_config_name) _temp_config_name = config.tdname out3 = qt.mesolve(H, psi0,tlist, e_ops=e_ops, c_ops=c_ops, options=qt.Options(rhs_reuse=True)) assert_(config.tdname == _temp_config_name)
def test_compare_solvers_coherent_state_memc(): """ correlation: comparing me and mc for driven oscillator in ground state """ N = 20 a = destroy(N) H = a.dag() * a + a + a.dag() G1 = 0.75 n_th = 2.00 c_ops = [np.sqrt(G1 * (1 + n_th)) * a, np.sqrt(G1 * n_th) * a.dag()] psi0 = fock(N, 0) taulist = np.linspace(0, 1.0, 5) corr1 = correlation_2op_2t(H, psi0, [0], taulist, c_ops, a.dag(), a, solver="me")[0] corr2 = correlation_2op_2t(H, psi0, [0], taulist, c_ops, a.dag(), a, solver="mc")[0] assert_(max(abs(corr1 - corr2)) < 5e-2)
def test_compare_solvers_coherent_state_memc(): """ correlation: comparing me and mc for driven oscillator in fock state """ N = 2 a = destroy(N) H = a.dag() * a + a + a.dag() G1 = 0.75 n_th = 2.00 c_ops = [np.sqrt(G1 * (1 + n_th)) * a, np.sqrt(G1 * n_th) * a.dag()] psi0 = fock(N, 1) taulist = np.linspace(0, 1.0, 3) corr1 = correlation_2op_2t(H, psi0, [0, 0.5], taulist, c_ops, a.dag(), a, solver="me") corr2 = correlation_2op_2t(H, psi0, [0, 0.5], taulist, c_ops, a.dag(), a, solver="mc") # pretty lax criterion, but would otherwise require a quite long simulation # time assert_(abs(corr1 - corr2).max() < 0.2)
def f(N, options): wa = 1 wc = 1 g = 2 kappa = 0.5 gamma = 0.1 n_th = 0.75 tspan = np.linspace(0, 10, 11) Ia = qt.qeye(2) Ic = qt.qeye(N) a = qt.destroy(N) at = qt.create(N) n = at * a sm = qt.sigmam() sp = qt.sigmap() sz = qt.sigmaz() H = wc * qt.tensor(n, Ia) + qt.tensor( Ic, wa / 2. * sz) + g * (qt.tensor(at, sm) + qt.tensor(a, sp)) c_ops = [ qt.tensor(np.sqrt(kappa * (1 + n_th)) * a, Ia), qt.tensor(np.sqrt(kappa * n_th) * at, Ia), qt.tensor(Ic, np.sqrt(gamma) * sm), ] psi0 = qt.tensor(qt.fock(N, 0), (qt.basis(2, 0) + qt.basis(2, 1)).unit()) exp_n = qt.mcsolve(H, psi0, tspan, c_ops, [qt.tensor(n, Ia)], ntraj=evals, options=options).expect[0] return np.real(exp_n)
def f(N, options): wa = 1 wc = 1 g = 2 tspan = np.linspace(0, 10, 11) Ia = qt.qeye(2) Ic = qt.qeye(N) a = qt.destroy(N) at = qt.create(N) n = at * a sm = qt.sigmam() sp = qt.sigmap() sz = qt.sigmaz() H = wc * qt.tensor(n, Ia) + qt.tensor( Ic, wa / 2. * sz) + g * (qt.tensor(at, sm) + qt.tensor(a, sp)) psi0 = qt.tensor(qt.fock(N, 0), (qt.basis(2, 0) + qt.basis(2, 1)).unit()) exp_n = qt.mesolve(H, psi0, tspan, [], [qt.tensor(n, Ia)], options=options).expect[0] return exp_n
def coherence_noon(rho, NH1, NH2, N): sigmax_n = qt.tensor(qt.fock(NH1,N),qt.fock(NH2,0))*qt.tensor(qt.fock(NH1,0).dag(),qt.fock(NH2,N).dag())\ +qt.tensor(qt.fock(NH1,0),qt.fock(NH2,N))*qt.tensor(qt.fock(NH1,N).dag(),qt.fock(NH2,0).dag()) sigmay_n = 1j*qt.tensor(qt.fock(NH1,N),qt.fock(NH2,0))*qt.tensor(qt.fock(NH1,0).dag(),qt.fock(NH2,N).dag())\ -1j*qt.tensor(qt.fock(NH1,0),qt.fock(NH2,N))*qt.tensor(qt.fock(NH1,N).dag(),qt.fock(NH2,0).dag()) sigmaz_n = qt.tensor(qt.fock(NH1,0),qt.fock(NH2,N))*qt.tensor(qt.fock(NH1,0).dag(),qt.fock(NH2,N).dag())\ -qt.tensor(qt.fock(NH1,N),qt.fock(NH2,0))*qt.tensor(qt.fock(NH1,N).dag(),qt.fock(NH2,0).dag()) return sqrt((sigmax_n * rho).tr()**2 + (sigmay_n * rho).tr()**2 + (sigmaz_n * rho).tr()**2)
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ############################################################################### import pytest import functools from itertools import product import numpy as np import qutip pytestmark = [pytest.mark.usefixtures("in_temporary_directory")] _equivalence_dimension = 20 _equivalence_fock = qutip.fock(_equivalence_dimension, 1) _equivalence_coherent = qutip.coherent_dm(_equivalence_dimension, 2) @pytest.mark.filterwarnings("ignore::FutureWarning") @pytest.mark.parametrize(["solver", "start", "legacy"], [ pytest.param("es", _equivalence_coherent, False, id="es"), pytest.param("es", _equivalence_coherent, True, id="es-legacy"), pytest.param("es", None, False, id="es-steady state"), pytest.param("es", None, True, id="es-steady state-legacy"), pytest.param("mc", _equivalence_fock, False, id="mc", marks=pytest.mark.slow), ]) def test_correlation_solver_equivalence(solver, start, legacy): """ Test that all of the correlation solvers give the same results for a given
def test_fock_type(): "State CSR Type: fock" st = fock(5,1) assert_equal(isspmatrix_csr(st.data), True)
args['t_c_1'] = args['t_k_1'] if varying_param == 't_k_2': args['t_c_2'] = args['t_k_2'] # Compute density matrices for each value of the varying parameter Density_matrices += [ RhoFinal(Nrealmax, Detection, args, fig_rhofinal=False, fig_qm=False) ] # Calculate the fidelity between the ideal state |10 > + exp(i*phi) |01 > and the simulated matrices # In each case, store in a dictionary the best fidelity (for a optimized value of phi) phi = np.linspace(0, 2 * np.pi, 100) Psi_ideal = {} DM_ideal = {} for i in range(len(phi)): Psi_ideal[i] = (qt.tensor(qt.fock(3, 0), qt.fock(3, 1)) + np.exp( 1j * phi[i]) * qt.tensor(qt.fock(3, 1), qt.fock(3, 0))) / np.sqrt(2) DM_ideal[i] = qt.ket2dm(Psi_ideal[i]) Fidelity = {} Max_fidelity = {} Max_index = {} for i in range(N_plots): Fidelity[i] = {} Max_fidelity[i] = 0 Max_index[i] = 0 for j in range(len(phi)): Fidelity[i][j] = ( qt.fidelity(DM_ideal[j], Density_matrices[i]) )**2 # the qt.fidelity function returns float(np.real((A * (B * A)).sqrtm().tr())) if Fidelity[i][j] > Max_fidelity[i]:
def test_smesolve_homodyne_methods(): "Stochastic: smesolve: homodyne methods with single jump operator" def arccoth(x): return 0.5*np.log((1.+x)/(x-1.)) th = 0.1 # Interaction parameter alpha = np.cos(th) beta = np.sin(th) gamma = 1. N = 30 # number of Fock states Id = qeye(N) a = destroy(N) s = 0.5*((alpha+beta)*a + (alpha-beta)*a.dag()) x = (a + a.dag()) * 2**-0.5 H = Id + gamma * a * a.dag() sc_op = [s] e_op = [x, x*x] rho0 = fock(N,0) # initial vacuum state T = 6. # final time # number of time steps for which we save the expectation values N_store = 200 Nsub = 10 tlist = np.linspace(0, T, N_store) ddt = (tlist[1]-tlist[0]) #### No analytic solution for ssesolve, taylor15 with 500 substep sol = ssesolve(H, rho0, tlist, sc_op, e_op, nsubsteps=1000, method='homodyne', solver='taylor1.5') y_an = (sol.expect[1]-sol.expect[0]*sol.expect[0].conj()) list_methods_tol = [['euler-maruyama', 3e-2], ['pc-euler', 5e-3], ['pc-euler-2', 5e-3], ['platen', 5e-3], ['milstein', 5e-3], ['milstein-imp', 5e-3], ['taylor1.5', 5e-4], ['taylor1.5-imp', 5e-4], ['explicit1.5', 5e-4], ['taylor2.0', 5e-4]] for n_method in list_methods_tol: sol = ssesolve(H, rho0, tlist, sc_op, e_op, nsubsteps=Nsub, method='homodyne', solver = n_method[0]) sol2 = ssesolve(H, rho0, tlist, sc_op, e_op, store_measurement=0, nsubsteps=Nsub, method='homodyne', solver = n_method[0], noise = sol.noise) sol3 = ssesolve(H, rho0, tlist, sc_op, e_op, nsubsteps=Nsub*5, method='homodyne', solver = n_method[0], tol=1e-8) err = 1/T * np.sum(np.abs(y_an - \ (sol.expect[1]-sol.expect[0]*sol.expect[0].conj())))*ddt err3 = 1/T * np.sum(np.abs(y_an - \ (sol3.expect[1]-sol3.expect[0]*sol3.expect[0].conj())))*ddt print(n_method[0], ': deviation =', err, err3,', tol =', n_method[1]) assert_(err < n_method[1]) # 5* more substep should decrease the error assert_(err3 < err) # just to check that noise is not affected by smesolve assert_(np.all(sol.noise == sol2.noise)) assert_(np.all(sol.expect[0] == sol2.expect[0])) sol = ssesolve(H, rho0, tlist[:2], sc_op, e_op, noise=10, ntraj=2, nsubsteps=Nsub, method='homodyne', solver='euler', store_measurement=1) sol2 = ssesolve(H, rho0, tlist[:2], sc_op, e_op, noise=10, ntraj=2, nsubsteps=Nsub, method='homodyne', solver='euler', store_measurement=0) sol3 = ssesolve(H, rho0, tlist[:2], sc_op, e_op, noise=11, ntraj=2, nsubsteps=Nsub, method='homodyne', solver='euler') # sol and sol2 have the same seed, sol3 differ. assert_(np.all(sol.noise == sol2.noise)) assert_(np.all(sol.noise != sol3.noise)) assert_(not np.all(sol.measurement[0] == 0.+0j)) assert_(np.all(sol2.measurement[0] == 0.+0j)) sol = ssesolve(H, rho0, tlist[:2], sc_op, e_op, noise=np.array([1,2]), ntraj=2, nsubsteps=Nsub, method='homodyne', solver='euler') sol2 = ssesolve(H, rho0, tlist[:2], sc_op, e_op, noise=np.array([2,1]), ntraj=2, nsubsteps=Nsub, method='homodyne', solver='euler') # sol and sol2 have the seed of traj 1 and 2 reversed. assert_(np.all(sol.noise[0,:,:,:] == sol2.noise[1,:,:,:])) assert_(np.all(sol.noise[1,:,:,:] == sol2.noise[0,:,:,:]))