def test_runstatistics_teleportation(self): """ Test circuit run_statistics on teleportation circuit """ teleportation = _teleportation_circuit() final_measurement = Measurement("start", targets=[2]) initial_measurement = Measurement("start", targets=[0]) original_state = tensor(rand_ket(2), basis(2, 0), basis(2, 0)) _, initial_probabilities = initial_measurement.measurement_comp_basis(original_state) teleportation_results = teleportation.run_statistics(original_state) states = teleportation_results.get_final_states() probabilities = teleportation_results.get_probabilities() for i, state in enumerate(states): state_final = state prob = probabilities[i] _, final_probabilities = final_measurement.measurement_comp_basis(state_final) np.testing.assert_allclose(initial_probabilities, final_probabilities) assert prob == pytest.approx(0.25, abs=1e-7) mixed_state = sum(p * ket2dm(s) for p, s in zip(probabilities, states)) dm_state = ket2dm(original_state) teleportation2 = _teleportation_circuit2() final_state = teleportation2.run(dm_state) _, probs1 = final_measurement.measurement_comp_basis(final_state) _, probs2 = final_measurement.measurement_comp_basis(mixed_state) np.testing.assert_allclose(probs1, probs2)
def create_states(): print('\n') n_max = 10 lmd = np.sqrt(0.01/1.01) # Test creating states state_all = [TMSS(lmd, n_max), PS(lmd, n_max), PA(lmd, n_max), PSA(lmd, n_max), PAS(lmd, n_max), PCS(lmd, n_max, (0.7, 0.7))] for item in state_all: name = item.state_name state = item.state print("State: {}".format(item.state_name)) print("Aver N: {:f} (numerical), {:f} (analytical)".format(item.num, item.exact_num if item.state_name != 'PCS' else 0)) print("Entropy of entanglement: {:f}\n".format(item.entanglement)) # Test two-mode mixing input1 = qu.ket2dm(qu.tensor(qu.basis(2, 0), qu.basis(2, 1))) tm_mix_op = tm_mix(0.1, 2) output1 = tm_mix_op * input1 * tm_mix_op.dag() print(input1) print(output1) # Test two-mode squeezing s = np.arctanh(lmd) input2 = qu.ket2dm(qu.tensor(qu.basis(n_max, 0), qu.basis(n_max, 0))) tm_sqz_op = tm_sqz(s, n_max) output2 = tm_sqz_op * input2 * tm_sqz_op.dag() print("\nEntropy of entanglement: {}".format(qu.entropy_vn(output2.ptrace(1))))
def test_measure_input_errors(): """ measure_povm: check input errors """ np.testing.assert_raises_regex( ValueError, "op must be all operators or all kets", measure_povm, basis(2, 0), [basis(2, 0), ket2dm(basis(2, 0))]) np.testing.assert_raises_regex(TypeError, "state must be a Qobj", measure_povm, "notqobj", [sigmaz()]) np.testing.assert_raises_regex(ValueError, "state must be a ket or a density matrix", measure_povm, basis(2, 0).dag(), [sigmaz()]) np.testing.assert_raises_regex( ValueError, "op and state dims should be compatible when state is a ket", measure_povm, basis(3, 0), [sigmaz()]) np.testing.assert_raises_regex( ValueError, "op and state dims should match when state is a density matrix", measure_povm, ket2dm(basis(3, 0)), [sigmaz()]) np.testing.assert_raises_regex( ValueError, "measurement operators must sum to identity", measure_povm, basis(2, 0), [basis(2, 0)]) np.testing.assert_raises_regex( ValueError, "measurement operators must sum to identity", measure_povm, basis(2, 0), [ket2dm(basis(2, 0))])
def solve(self): levels = self.levels if self.params['mixed']: self.rho0 = sum([ level.pop[i] * qu.ket2dm(level.states[i]) for level in levels for i in range(len(level.pop)) ]) if self.cavity: self.rho0 = qu.tensor(self.rho0, self.cavity.psi0) else: self.rho0 = qu.ket2dm( sum([ level.pop[i] * level.states[i] for level in levels for i in range(len(level.pop)) ]).unit()) if self.cavity: self.rho0 = qu.tensor(self.rho0, qu.ket2dm(self.cavity.psi0)) self.e_ops = [] for i in self.projectors.values(): self.e_ops += i if self.cavity: self.e_ops.append(self.ad * self.a) # C_spon = np.sqrt(params['gamma'])*self.sm # C_lw_g = np.sqrt(LW)*proj_g # C_lw_e = np.sqrt(LW)*proj_e # self.c_ops = [C_spon] tlist = self.params['tlist'] self.result = qu.mesolve(self.H, self.rho0, tlist, e_ops=self.e_ops) return self.result
def test_measurement_comp_basis(): """ Test measurements to test probability calculation in computational basis measurments on a 3 qubit state """ qubit_kets = [rand_ket(2), rand_ket(2), rand_ket(2)] qubit_dms = [ket2dm(qubit_kets[i]) for i in range(3)] state = tensor(qubit_kets) density_mat = tensor(qubit_dms) for i in range(3): m_i = Measurement("M" + str(i), i) final_states, probabilities_state = m_i.measurement_comp_basis(state) final_dms, probabilities_dm = m_i.measurement_comp_basis(density_mat) amps = qubit_kets[i].full() probabilities_i = [np.abs(amps[0][0])**2, np.abs(amps[1][0])**2] np.testing.assert_allclose(probabilities_state, probabilities_dm) np.testing.assert_allclose(probabilities_state, probabilities_i) for j, final_state in enumerate(final_states): np.testing.assert_allclose( final_dms[j].full(), ket2dm(final_state).full() )
def jump_operators(T1_q0,T1_q1,Tphi_q0_ket0toket0,Tphi_q0_ket1toket1,Tphi_q0_ket2toket2,Tphi_q1_ket0toket0,Tphi_q1_ket1toket1, Tphi_q0_sigmaZ_01,Tphi_q0_sigmaZ_12,Tphi_q0_sigmaZ_02,Tphi_q1_sigmaZ_01,Tphi_q1_sigmaZ_12,Tphi_q1_sigmaZ_02): # time independent case c_ops=[] if T1_q0 != 0: c_ops.append(np.sqrt(1/T1_q0)*a) if T1_q1 != 0: c_ops.append(np.sqrt(1/T1_q1)*b) if Tphi_q0_ket0toket0 != 0: collapse=qtp.tensor(qtp.qeye(3),qtp.ket2dm(qtp.basis(3,0))) c_ops.append(np.sqrt(1/Tphi_q0_ket0toket0)*collapse) if Tphi_q0_ket1toket1 != 0: collapse=qtp.tensor(qtp.qeye(3),qtp.ket2dm(qtp.basis(3,1))) c_ops.append(np.sqrt(1/Tphi_q0_ket1toket1)*collapse) if Tphi_q0_ket2toket2 != 0: collapse=qtp.tensor(qtp.qeye(3),qtp.ket2dm(qtp.basis(3,2))) c_ops.append(np.sqrt(1/Tphi_q0_ket2toket2)*collapse) if Tphi_q1_ket0toket0 != 0: collapse=qtp.tensor(qtp.ket2dm(qtp.basis(3,0)),qtp.qeye(3)) c_ops.append(np.sqrt(1/Tphi_q1_ket0toket0)*collapse) if Tphi_q1_ket1toket1 != 0: collapse=qtp.tensor(qtp.ket2dm(qtp.basis(3,1)),qtp.qeye(3)) c_ops.append(np.sqrt(1/Tphi_q1_ket1toket1)*collapse) if Tphi_q0_sigmaZ_01 != 0: sigmaZinqutrit = qtp.Qobj([[1,0,0], [0,-1,0], [0,0,0]]) collapse=qtp.tensor(qtp.qeye(3),sigmaZinqutrit) c_ops.append(np.sqrt(1/(2*Tphi_q0_sigmaZ_01))*collapse) if Tphi_q0_sigmaZ_12 != 0: sigmaZinqutrit = qtp.Qobj([[0,0,0], [0,1,0], [0,0,-1]]) collapse=qtp.tensor(qtp.qeye(3),sigmaZinqutrit) c_ops.append(np.sqrt(1/(2*Tphi_q0_sigmaZ_12))*collapse) if Tphi_q0_sigmaZ_02 != 0: sigmaZinqutrit = qtp.Qobj([[1,0,0], [0,0,0], [0,0,-1]]) collapse=qtp.tensor(qtp.qeye(3),sigmaZinqutrit) c_ops.append(np.sqrt(1/(2*Tphi_q0_sigmaZ_02))*collapse) if Tphi_q1_sigmaZ_01 != 0: sigmaZinqutrit = qtp.Qobj([[1,0,0], [0,-1,0], [0,0,0]]) collapse=qtp.tensor(sigmaZinqutrit,qtp.qeye(3)) c_ops.append(np.sqrt(1/(2*Tphi_q1_sigmaZ_01))*collapse) if Tphi_q1_sigmaZ_12 != 0: sigmaZinqutrit = qtp.Qobj([[0,0,0], [0,1,0], [0,0,-1]]) collapse=qtp.tensor(sigmaZinqutrit,qtp.qeye(3)) c_ops.append(np.sqrt(1/(2*Tphi_q1_sigmaZ_12))*collapse) if Tphi_q1_sigmaZ_02 != 0: sigmaZinqutrit = qtp.Qobj([[1,0,0], [0,0,0], [0,0,-1]]) collapse=qtp.tensor(sigmaZinqutrit,qtp.qeye(3)) c_ops.append(np.sqrt(1/(2*Tphi_q1_sigmaZ_02))*collapse) return c_ops
def seepage_from_superoperator(U): """ Calculates seepage by summing over all in and output states outside the computational subspace. L1 = 1- 1/2^{number non-computational states} sum_i sum_j abs(|<phi_i|U|phi_j>|)**2 """ if U.type=='oper': sump = 0 for i_list in [[0,2],[1,2],[2,0],[2,1],[2,2]]: for j_list in [[0,2],[1,2],[2,0],[2,1],[2,2]]: bra_i = qtp.tensor(qtp.ket([i_list[0]], dim=[3]), qtp.ket([i_list[1]], dim=[3])).dag() ket_j = qtp.tensor(qtp.ket([j_list[0]], dim=[3]), qtp.ket([j_list[1]], dim=[3])) p = np.abs((bra_i*U*ket_j).data[0, 0])**2 # could be sped up sump += p sump /= 5 # divide by number of non-computational states L1 = 1-sump return L1 elif U.type=='super': sump = 0 for i_list in [[0,2],[1,2],[2,0],[2,1],[2,2]]: for j_list in [[0,2],[1,2],[2,0],[2,1],[2,2]]: ket_i = qtp.tensor(qtp.ket([i_list[0]], dim=[3]), qtp.ket([i_list[1]], dim=[3])) rho_i=qtp.operator_to_vector(qtp.ket2dm(ket_i)) ket_j = qtp.tensor(qtp.ket([j_list[0]], dim=[3]), qtp.ket([j_list[1]], dim=[3])) rho_j=qtp.operator_to_vector(qtp.ket2dm(ket_j)) p = (rho_i.dag()*U*rho_j).data[0, 0] sump += p sump /= 5 # divide by number of non-computational states sump=np.real(sump) L1 = 1-sump return L1
def test_povm(): """ Test if povm formulation works correctly by checking probabilities for the quantum state discrimination example """ coeff = (sqrt(2) / (1 + sqrt(2))) E_1 = coeff * ket2dm(basis(2, 1)) E_2 = coeff * ket2dm((basis(2, 0) - basis(2, 1)) / (sqrt(2))) E_3 = identity(2) - E_1 - E_2 M_1 = Qobj(scipy.linalg.sqrtm(E_1)) M_2 = Qobj(scipy.linalg.sqrtm(E_2)) M_3 = Qobj(scipy.linalg.sqrtm(E_3)) ket1 = basis(2, 0) ket2 = (basis(2, 0) + basis(2, 1)) / (sqrt(2)) dm1 = ket2dm(ket1) dm2 = ket2dm(ket2) M = [M_1, M_2, M_3] _, probabilities = measurement_statistics_povm(ket1, M) np.testing.assert_allclose(probabilities, [0, 0.293, 0.707], 0.001) _, probabilities = measurement_statistics_povm(ket2, M) np.testing.assert_allclose(probabilities, [0.293, 0, 0.707], 0.001) _, probabilities = measurement_statistics_povm(dm1, M) np.testing.assert_allclose(probabilities, [0, 0.293, 0.707], 0.001) _, probabilities = measurement_statistics_povm(dm2, M) np.testing.assert_allclose(probabilities, [0.293, 0, 0.707], 0.001)
def generate_tomo_data(rho, M, R, N, M_bins = None): """ Generates data for tomography. Both returns expectation values(used for average tomo) or bin counts( if you use thresholded tomo). Generates a single multinomial set of counts to get both data types. """ #decompose the measurement operator in its spectrum eigenvals, eigenstates = M.eigenstates() if M_bins is None: M_bins = comp_projectors # now decompose the probs = [] for state in eigenstates: #calculate probability of ending up in this state probs.append(((R.dag() * (qt.ket2dm(state) * R)) * rho).tr().real) #run a multinomial distribution to determine the "experimental" measurement outcomes counts = np.random.multinomial(N, probs) # use the simulated percentages of states found to calc voltages expectations = sum((counts / float(N)) * eigenvals) #calcultate bin counts via the projections of original eigenstates onto bin measurement operator. bin_counts = [sum([counts[j] * (M_bins[i] * qt.ket2dm(eigenstates[j])).tr().real for j in range(len(eigenstates))]) for i in range(len(M_bins))] return bin_counts, expectations
def calc_hierarchy_approx(coeff, eps, n=3, order=0): k = int(len(coeff) / 2) psi = np.array(coeff[:k]) chi = np.array(coeff[k:]) global system global m_state system = q.ket2dm(state(*coeff[:k])) m_state = state(*coeff[k:]) og_res = -func(coeff, n=n) eps_psi = EpsState(list(psi), eps) eps_chi = EpsState(list(chi), eps) expec_res = -func(eps_psi + eps_chi, n=n) system = q.ket2dm(state(*coeff[:k])) m_state = state(*coeff[k:]) omega = np.sum(psi * chi) e1 = (1 + eps * eps)**2 e2 = (omega + eps**4)**(n - 1) denom = e1 * e2 numer = 1 / (2 * np.pi) * ig.quad(error_integrand, 0., 2 * np.pi, (n, chi, psi, eps, order), full_output=0)[0] return og_res, numer / denom, expec_res, (e1, omega, e2)
def H_2cat(alpha): C_p = (qt.coherent(NFock, alpha) + qt.coherent(NFock, -alpha)).unit() C_m = (qt.coherent(NFock, alpha) - qt.coherent(NFock, -alpha)).unit() H = -(qt.ket2dm(C_p) - qt.ket2dm(C_m)) return H
def __init__(self): self.dm00 = qt.ket2dm(qt.tensor(qt.basis(2, 0), qt.basis(2, 0))) self.dm10 = qt.ket2dm(qt.tensor(qt.basis(2, 1), qt.basis(2, 0))) self.dm01 = qt.ket2dm(qt.tensor(qt.basis(2, 0), qt.basis(2, 1))) self.dm11 = qt.ket2dm(qt.tensor(qt.basis(2, 1), qt.basis(2, 1))) self.bloch = qt.Bloch(view=fig_params['view'])
def calc_population_02_state(U): """ Calculates the population that escapes from |11> to |02>. Formula for unitary propagator: population = |<02|U|11>|^2 and similarly for the superoperator case. The function assumes that the computational subspace (:= the 4 energy levels chosen as the two qubits) is given by the standard basis |0> /otimes |0>, |0> /otimes |1>, |1> /otimes |0>, |1> /otimes |1>. If this is not the case, one need to change the basis to that one, before calling this function. """ if U.type == 'oper': sump = 0 for i_list in [[0, 2]]: for j_list in [[1, 1]]: bra_i = qtp.tensor(qtp.ket([i_list[0]], dim=[3]), qtp.ket([i_list[1]], dim=[3])).dag() ket_j = qtp.tensor(qtp.ket([j_list[0]], dim=[3]), qtp.ket([j_list[1]], dim=[3])) p = np.abs((bra_i * U * ket_j).data[0, 0])**2 sump += p return np.real(sump) elif U.type == 'super': sump = 0 for i_list in [[0, 2]]: for j_list in [[1, 1]]: ket_i = qtp.tensor(qtp.ket([i_list[0]], dim=[3]), qtp.ket([i_list[1]], dim=[3])) rho_i = qtp.operator_to_vector(qtp.ket2dm(ket_i)) ket_j = qtp.tensor(qtp.ket([j_list[0]], dim=[3]), qtp.ket([j_list[1]], dim=[3])) rho_j = qtp.operator_to_vector(qtp.ket2dm(ket_j)) p = (rho_i.dag() * U * rho_j).data[0, 0] sump += p return np.real(sump)
def test_base_2_or_e(self): rho = qutip.ket2dm(qutip.ket("00")) sigma = rho + qutip.ket2dm(qutip.ket("01")) sigma = sigma.unit() assert (qutip.entropy_relative(rho, sigma) == pytest.approx(np.log(2))) assert (qutip.entropy_relative(rho, sigma, base=np.e) == pytest.approx(0.69314718)) assert qutip.entropy_relative(rho, sigma, base=2) == pytest.approx(1)
def set_oracle(self, oracle=None): N = self.query.shape[0] if oracle is None: self.oracle = qu.identity(N) - 2 * qu.ket2dm(self.query) elif isinstance(oracle, qu.Qobj) and oracle.type == "ket": self.oracle = qu.identity(N) - 2 * qu.ket2dm(oracle) else: self.oracle = oracle
def test_ket_and_dm_transformations_equivalent(n_levels): """Consistency between transformations of kets and density matrices.""" psi0 = qutip.rand_ket(n_levels) # Generate a random basis _, rand_basis = qutip.rand_dm(n_levels, density=1).eigenstates() rho1 = qutip.ket2dm(psi0).transform(rand_basis, True) rho2 = qutip.ket2dm(psi0.transform(rand_basis, True)) assert (rho1 - rho2).norm() < 1e-6
def test_ket2dm(): N = 5 ket = qutip.coherent(N, 2) bra = ket.dag() oper = qutip.ket2dm(ket) oper_from_bra = qutip.ket2dm(bra) assert qutip.expect(oper, ket) == pytest.approx(1.) assert qutip.isoper(oper) assert oper == ket * bra assert oper == oper_from_bra with pytest.raises(TypeError) as e: qutip.ket2dm(oper) assert str(e.value) == "Input is not a ket or bra vector."
def test_Transformation5(): "Consistency between transformations of kets and density matrices" N = 4 psi0 = rand_ket(N) # generate a random basis evals, rand_basis = rand_dm(N, density=1).eigenstates() rho1 = ket2dm(psi0).transform(rand_basis, True) rho2 = ket2dm(psi0.transform(rand_basis, True)) assert_((rho1 - rho2).norm() < 1e-6)
def _Huu(self, freq): try: return self._Huu_cache[freq] except: self._Huu_cache[ freq] = freq * 2 * np.pi * self.two_qubit_operator( qubit1_operator=qp.ket2dm(self._tr1.e_state())) + \ 2 * freq * 2 * np.pi * self.two_qubit_operator( qubit1_operator=qp.ket2dm(self._tr1.f_state())) + \ freq * 2 * np.pi * self.two_qubit_operator( qubit2_operator=qp.ket2dm(self._tr2.e_state())) + \ 2 * freq * 2 * np.pi * self.two_qubit_operator( qubit2_operator=qp.ket2dm(self._tr2.f_state())) return self._Huu_cache[freq]
def create_projectors(): # Create all the different projectors that are required for the measurement I = qt.identity(2) zero = qt.basis(2, 0) one = qt.basis(2, 1) proj1 = qt.Qobj([ [1, 0], # single qubit projector unto 0 subspace [0, 0] ]) proj2 = qt.Qobj([ [0, 0], # single qubit projector unto 1 subspace [0, 1] ]) # Create projectors for all measurement steps projector1 = qt.tensor(I, I, I, I, proj1, I) # Projector unto 0 for first measurement projector2 = qt.tensor(I, I, I, I, proj2, I) # Projector unto 1 for first measurement projector3 = qt.tensor(I, I, I, I, I, proj1) # Projector unto 0 for second measurement projector4 = qt.tensor(I, I, I, I, I, proj2) # Projector unto 1 for second measurement projector5 = qt.tensor(proj1, I, I, I) # Projector unto 0 for third measurement projector6 = qt.tensor(proj2, I, I, I) # Projector unto 1 for third measurement projector7 = qt.tensor(I, I, proj1, I) # Projector unto 0 for fourth measurement projector8 = qt.tensor(I, I, proj2, I) # Projector unto 1 for fourth measurement # Create projector unto codespace logicalzero = qt.ket2dm( qt.tensor(zero, zero, zero, zero) + qt.tensor(one, one, one, one)).unit() logicalone = qt.ket2dm( qt.tensor(zero, zero, one, one) + qt.tensor(one, one, zero, zero)).unit() projector9 = logicalone + logicalzero # Collect all projectors projectors = [ projector1, projector2, projector3, projector4, projector5, projector6, projector7, projector8, projector9 ] return projectors
def objective_liouville(): a1 = np.random.random(100) + 1j * np.random.random(100) a2 = np.random.random(100) + 1j * np.random.random(100) H = [ tensor(sigmaz(), identity(2)) + tensor(identity(2), sigmaz()), [tensor(sigmax(), identity(2)), a1], [tensor(identity(2), sigmax()), a2], ] L = krotov.objectives.liouvillian(H, c_ops=[]) ket00 = ket((0, 0)) ket11 = ket((1, 1)) obj = krotov.Objective( initial_state=qutip.ket2dm(ket00), target=qutip.ket2dm(ket11), H=L ) return obj
def test_density_matrices_with_non_real_eigenvalues(self): rho = qutip.ket2dm(qutip.ket("00")) sigma = qutip.ket2dm(qutip.ket("01")) with pytest.raises(ValueError) as exc: qutip.entropy_relative(rho + 1j, sigma) assert str(exc.value) == "Input rho has non-real eigenvalues." with pytest.raises(ValueError) as exc: qutip.entropy_relative(rho - 1j, sigma) assert str(exc.value) == "Input rho has non-real eigenvalues." with pytest.raises(ValueError) as exc: qutip.entropy_relative(rho, sigma + 1j) assert str(exc.value) == "Input sigma has non-real eigenvalues." with pytest.raises(ValueError) as exc: qutip.entropy_relative(rho, sigma - 1j) assert str(exc.value) == "Input sigma has non-real eigenvalues."
def leakage_from_superoperator(U): if U.type == 'oper': """ Calculates leakage by summing over all in and output states in the computational subspace. L1 = 1- 1/2^{number computational qubits} sum_i sum_j abs(|<phi_i|U|phi_j>|)**2 The function assumes that the computational subspace (:= the 4 energy levels chosen as the two qubits) is given by the standard basis |0> /otimes |0>, |0> /otimes |1>, |1> /otimes |0>, |1> /otimes |1>. If this is not the case, one need to change the basis to that one, before calling this function. """ sump = 0 for i in range(4): for j in range(4): bra_i = qtp.tensor(qtp.ket([i // 2], dim=[3]), qtp.ket([i % 2], dim=[3])).dag() ket_j = qtp.tensor(qtp.ket([j // 2], dim=[3]), qtp.ket([j % 2], dim=[3])) p = np.abs((bra_i * U * ket_j).data[0, 0])**2 sump += p sump /= 4 # divide by dimension of comp subspace L1 = 1 - sump return L1 elif U.type == 'super': """ Calculates leakage by summing over all in and output states in the computational subspace. L1 = 1- 1/2^{number computational qubits} sum_i sum_j Tr(rho_{x'y'}C_U(rho_{xy})) where C_U is U in the channel representation The function assumes that the computational subspace (:= the 4 energy levels chosen as the two qubits) is given by the standard basis |0> /otimes |0>, |0> /otimes |1>, |1> /otimes |0>, |1> /otimes |1>. If this is not the case, one need to change the basis to that one, before calling this function. """ sump = 0 for i in range(4): for j in range(4): ket_i = qtp.tensor(qtp.ket([i // 2], dim=[3]), qtp.ket([i % 2], dim=[3])) #notice it's a ket rho_i = qtp.operator_to_vector(qtp.ket2dm(ket_i)) ket_j = qtp.tensor(qtp.ket([j // 2], dim=[3]), qtp.ket([j % 2], dim=[3])) rho_j = qtp.operator_to_vector(qtp.ket2dm(ket_j)) p = (rho_i.dag() * U * rho_j).data[0, 0] sump += p sump /= 4 # divide by dimension of comp subspace sump = np.real(sump) L1 = 1 - sump return L1
def rhot(self, rho0, t, tau): """ Compute the reduced system density matrix :math:`\\rho(t)` Parameters ---------- rho0 : :class:`qutip.Qobj` initial density matrix or state vector (ket) t : float current time tau : float time-delay Returns ------- : :class:`qutip.Qobj` density matrix at time :math:`t` """ if qt.isket(rho0): rho0 = qt.ket2dm(rho0) E = self.propagator(t, tau) rhovec = qt.operator_to_vector(rho0) return qt.vector_to_operator(E*rhovec)
def testHOZeroTemperature(): """ brmesolve: harmonic oscillator, zero temperature """ N = 10 w0 = 1.0 * 2 * np.pi g = 0.05 * w0 kappa = 0.15 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()) c_ops = [np.sqrt(kappa) * a] a_ops = [a + a.dag()] e_ops = [a.dag() * a, a + a.dag()] res_me = mesolve(H, psi0, times, c_ops, e_ops) res_brme = brmesolve(H, psi0, times, a_ops, e_ops, spectra_cb=[lambda w: kappa * (w >= 0)]) for idx, e in enumerate(e_ops): diff = abs(res_me.expect[idx] - res_brme.expect[idx]).max() assert_(diff < 1e-2)
def leakage(channel, subspace_basis, tlist): d = len(subspace_basis) I_subspace = sum([ket2dm(ket) for ket in subspace_basis]) return [ 1 - real(expect(I_subspace, rho)) for rho in channel(I_subspace / d, tlist) ]
def linear_entropy(dm, normalize=False): """ Returns the linear entropy of a state. Parameters ---------- dm : qobj/array-like Density operator representing the state. normalize : bool Optional argument to normalize linear entropy such that the completely mixed state has LE = 1 rather than 1-1/d. [1] Default: False ---------- le : float Linear entropy >>> """ if dm.type not in ('oper','ket'): raise TypeError("Input must be a Qobj representing a state.") if dm.type=='ket': dm = ket2dm(dm) le = 1 - (dm**2).tr() if normalize: d = dm.shape[0] le = le * d/(d-1) return le
def solve_sdeq(self, tlist, e_ops=None, sched_prob=None, sched_driver=None): annealing_time = tlist[-1] evals_driver, ekets_driver = self.H_driver.eigenstates() psi0 = ekets_driver[np.argmin(evals_driver)] if e_ops is None: e_ops = [ket2dm(ek) for ek in self.ekets_prob] Hlist = self._gen_hamil_list(sched_prob, sched_driver) result = sesolve(Hlist, psi0, tlist, e_ops=e_ops, args={'annealing_time': annealing_time}) expects = np.transpose(result.expect) arr = np.array(list(zip(tlist, expects)), dtype=[('time', float), ('expect', (float, len(expects[0])))]) return arr.view(np.recarray)
def test_harmonic_oscillator(n_th): N = 10 w0 = 1.0 * 2 * np.pi g = 0.05 * w0 kappa = 0.15 S_w = _harmonic_oscillator_spectrum_frequency(n_th, w0, kappa) a = qutip.destroy(N) H = w0 * a.dag() * a + g * (a + a.dag()) psi0 = (qutip.basis(N, 4) + qutip.basis(N, 2) + qutip.basis(N, 0)).unit() psi0 = qutip.ket2dm(psi0) times = np.linspace(0, 25, 1000) c_ops = _harmonic_oscillator_c_ops(n_th, kappa, N) a_ops = [[a + a.dag(), S_w]] e_ops = [a.dag() * a, a + a.dag()] me = qutip.mesolve(H, psi0, times, c_ops, e_ops) brme = qutip.brmesolve(H, psi0, times, a_ops, e_ops) for me_expectation, brme_expectation in zip(me.expect, brme.expect): np.testing.assert_allclose(me_expectation, brme_expectation, atol=1e-2) num = qutip.num(N) me_num = qutip.expect(num, me.states) brme_num = qutip.expect(num, brme.states) np.testing.assert_allclose(me_num, brme_num, atol=1e-2)
def testHOFiniteTemperature(self): "brmesolve: harmonic oscillator, finite temperature" N = 10 w0 = 1.0 * 2 * np.pi g = 0.05 * w0 kappa = 0.15 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 = [a.dag() * a, a + a.dag()] res_me = mesolve(H, psi0, times, c_ops, e_ops) res_brme = brmesolve(H, psi0, times, a_ops, e_ops, [S_w]) for idx, e in enumerate(e_ops): diff = abs(res_me.expect[idx] - res_brme.expect[idx]).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 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 set_mem(self, memories, scheme=None): """Sets the memory of the search Takes a list of states to remember, and a scheme of how to input them into the memory (standards: 'inclusion', 'exclusion', 'vary_phase') memories - list of binary arrays to memorize : list of bool numpy arrays scheme - the memorization scheme (standard: exclusion) : string or function handle taking a pattern and current memory state """ if not scheme: scheme = "exclusion" if isinstance(scheme, str): if scheme == "inclusion": scheme = incl_mem elif scheme == "exclusion": scheme = excl_mem elif scheme == "vary_phase": # TODO pass elif not isinstance(scheme, types.FunctionType): raise Exception("Memorization scheme is not valid") state = None mem_op = qu.Qobj() N = 2**len(memories[0]) for mem in memories: state = scheme(str_to_bit_arr(mem), state) state_ID = bit_arr_to_int(str_to_bit_arr(mem)) mem_op += qu.ket2dm(qu.basis(N, state_ID)) self.mem_op = qu.identity(N) - 2 * mem_op if state.norm() > 0: self.memory = state.unit() else: self.memory = state self.memories = memories
def testJCZeroTemperature(): """ brmesolve: Jaynes-Cummings model, zero temperature """ N = 10 a = tensor(destroy(N), identity(2)) sm = tensor(identity(N), destroy(2)) psi0 = ket2dm(tensor(basis(N, 1), basis(2, 0))) a_ops = [(a + a.dag())] e_ops = [a.dag() * a, sm.dag() * sm] w0 = 1.0 * 2 * np.pi g = 0.05 * 2 * np.pi kappa = 0.05 times = np.linspace(0, 2 * 2 * np.pi / g, 1000) c_ops = [np.sqrt(kappa) * a] H = w0 * a.dag() * a + w0 * sm.dag() * sm + \ g * (a + a.dag()) * (sm + sm.dag()) res_me = mesolve(H, psi0, times, c_ops, e_ops) res_brme = brmesolve(H, psi0, times, a_ops, e_ops, spectra_cb=[lambda w: kappa * (w >= 0)]) for idx, e in enumerate(e_ops): diff = abs(res_me.expect[idx] - res_brme.expect[idx]).max() assert_(diff < 5e-2) # accept 5% error
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 do_qt_mesolve(state,H,lindblads,steps,tau,**kwargs): progress = kwargs.pop('progress_bar',None) times = kwargs.pop('times',None) if times is None: times = np.linspace(0,steps*tau,steps,dtype=np.float_) return qt.mesolve(H,qt.ket2dm(state),times,lindblads,[], options=qt.Options(**kwargs), progress_bar=progress).states
def do_rk4(state,H,lindblads=[],steps=1000,tau=1/100,**kwargs): states = [] rho = qt.ket2dm(state) for i in range(steps): states.append(rho) rho = (rho + tau*do_rk4_step(rho,H,lindblads,tau)) rho = rho.unit() return states
def apply_dephasing(number_of_spins, alpha, B): ''' takes number of spins, alpha, and the magnetic field and returns the FM hamiltonian along with its ground state and the dephased ground state ''' calc = ising_calculator_FM(number_of_spins, alpha, B) H = calc.get_H() energy,groundstate = H.groundstate() dm_groundstate = ket2dm(groundstate) dephased = do_dephasing_dm(dm_groundstate, number_of_spins) return H, dm_groundstate, dephased
def test_EntropyConcurrence(): "Concurrence" # check concurrence = 1 for maximal entangled (Bell) state bell = ket2dm( (tensor(basis(2), basis(2)) + tensor(basis(2, 1), basis(2, 1))).unit()) assert_equal(abs(concurrence(bell) - 1.0) < 1e-15, True) # check all concurrence values >=0 rhos = [rand_dm(4, dims=[[2, 2], [2, 2]]) for k in range(10)] for k in rhos: assert_equal(concurrence(k) >= 0, True)
def do_dephasing_dm(dm, number_spins): ''' takes the state and returns the dephased densitry matrix after projecting the 0th ion onto its eigenbasis ''' N = number_spins si = qeye(2) ptrace = dm.ptrace(0) overlap,eigenstate = ptrace.eigenstates() projection0 = [si] * N projection0[0] = ket2dm(eigenstate[0]) projection0 = tensor(projection0) projection1 = [si] * N projection1[0] = ket2dm(eigenstate[1]) projection1 = tensor(projection1) #proj is the projection onto th eigenbasis of particle 0 dephased = projection0 * dm * projection0 + projection1 * dm * projection1 #dephasing checks # environment = range(1,N) # print 'do partial traces agree?', [dm.ptrace(i) == dephased.ptrace(i) for i in range(N)], dm.ptrace(environment) == dephased.ptrace(environment) # print 'but the dm is different?', not dephased == dm return dephased
def test_EntropyVN(): "von-Neumann entropy" # verify that entropy_vn gives correct binary entropy a = np.linspace(0, 1, 20) for k in range(len(a)): # a*|0><0| x = a[k] * ket2dm(basis(2, 0)) # (1-a)*|1><1| y = (1 - a[k]) * ket2dm(basis(2, 1)) rho = x + y # Von-Neumann entropy (base 2) of rho out = entropy_vn(rho, 2) if k == 0 or k == 19: assert_equal(out, -0.0) else: assert_(abs(-out - a[k] * np.log2(a[k]) - (1. - a[k]) * np.log2((1. - a[k]))) < 1e-12) # test_ entropy_vn = 0 for pure state psi = rand_ket(10) assert_equal(abs(entropy_vn(psi)) <= 1e-13, True)
def parse_states(self,results): steps = len(results) qubit_indices,cav_index = parse_dims(self.dims) cavity_sim = cav_index is not None if cavity_sim: n = qt.num(self.dims[cav_index]) bloch_vectors = np.zeros((steps,len(qubit_indices),3)) ns = np.zeros(steps) for i in range(steps): if results[i].type != 'oper': dm = qt.ket2dm(results[i]) else: dm = results[i] bloch_vectors[i] = [measure_qubit(dm.ptrace(int(j))) for j in qubit_indices] if cavity_sim: ns[i] = np.real((n*dm.ptrace(cav_index)).tr()) return bloch_vectors,ns
def compute_item(self, name, model): name += "_1" fock_dim = self.editor.fock_dim.value() timestep = self.editor.timestep.value() initial_alpha = self.editor.initial_alpha.value() steps = model.get_steps(fock_dim, timestep) res0 = coherent_dm(fock_dim, initial_alpha) qubit0 = ket2dm((basis(2, 0) + basis(2, 1)) / np.sqrt(2)) psi0 = tensor(qubit0, res0) def add_to_viewer(r): item = WignerPlotter(name, r) item.wigners_complete.connect(lambda: self.viewer.add_item(item)) win.statusBar().showMessage("Computing Wigners") args = (steps, fock_dim, psi0, timestep) run_in_process(to_state_list, add_to_viewer, args) #self.thread_is_running.emit() win.statusBar().showMessage("Computing States")
def test_general_stochastic(): "Stochastic: general_stochastic" "Reproduce smesolve homodyne" tol = 0.025 N = 4 gamma = 0.25 ntraj = 20 nsubsteps = 50 a = destroy(N) H = [[a.dag() * a,f]] psi0 = coherent(N, 0.5) sc_ops = [np.sqrt(gamma) * a, np.sqrt(gamma) * a * 0.5] e_ops = [a.dag() * a, a + a.dag(), (-1j)*(a - a.dag())] L = liouvillian(QobjEvo([[a.dag() * a,f]], args={"a":2}), c_ops = sc_ops) L.compile() sc_opsM = [QobjEvo(spre(op) + spost(op.dag())) for op in sc_ops] [op.compile() for op in sc_opsM] e_opsM = [spre(op) for op in e_ops] def d1(t, vec): return L.mul_vec(t,vec) def d2(t, vec): out = [] for op in sc_opsM: out.append(op.mul_vec(t,vec)-op.expect(t,vec)*vec) return np.stack(out) times = np.linspace(0, 0.5, 13) res_ref = mesolve(H, psi0, times, sc_ops, e_ops, args={"a":2}) list_methods_tol = ['euler-maruyama', 'platen', 'explicit15'] for solver in list_methods_tol: res = general_stochastic(ket2dm(psi0),times,d1,d2,len_d2=2, e_ops=e_opsM, normalize=False, ntraj=ntraj, nsubsteps=nsubsteps, solver=solver) assert_(all([np.mean(abs(res.expect[idx] - res_ref.expect[idx])) < tol for idx in range(len(e_ops))])) assert_(len(res.measurement) == ntraj)
def _uncoupled_ground(N): """ Generate the density matrix of the ground state in the full\ :math:`2^N`-dimensional Hilbert space. Parameters ---------- N: int The number of two-level systems. Returns ------- psi0: :class: qutip.Qobj The density matrix for the ground state in the full Hilbert space. """ N = int(N) jz = jspin(N, "z", basis="uncoupled") en, vn = jz.eigenstates() psi0 = vn[0] return ket2dm(psi0)
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 purity(dm): """ Calculates trace of density matrix squared Parameters ---------- dm: qobj/array-like Input density matrix Returns ------- purity: Purity of the state. 1 for pure, 0.5 for maximally mixed. """ if dm.type == 'ket': dm = ket2dm(dm) if dm.type != 'oper': raise TypeError("Input must be a state ket or density matrix") purity = (dm**2).tr() return purity
def entropy_linear_entg(rho, normalize=True): """ Calculates the linear entropy of entanglement of a density matrix Parameters: ----------- rho : qobj/array-like Input density matrix Returns: -------- linent_entg: Linear Entropy of Entanglement """ if rho.type == 'ket': rho = ket2dm(rho) if rho.type != 'oper': raise TypeError("Input must be density matrix") rhopartial = ptrace(rho,0) linent_entg = linear_entropy(rhopartial,normalize) return linent_entg
def entropy_entg(rho, base=2): """ Calculates the entropy of entanglement of a density matrix Parameters: ----------- rho : qobj/array-like Input density matrix base: Base of log Returns: -------- ent_entg: Entropy of Entanglement """ if rho.type == 'ket': rho = ket2dm(rho) if rho.type != 'oper': raise TypeError("Input must be density matrix") rhopartial = ptrace(rho,0) ent_entg = entropy_vn(rhopartial,base) return ent_entg
def testMETDDecayAsFunc(self): "mesolve: time-dependence as function with super as init cond" N = 10 # number of basis states to consider a = destroy(N) H = a.dag() * a rho0 = ket2dm(basis(N, 9)) # initial state rho0vec = operator_to_vector(rho0) E0 = sprepost(qeye(N), qeye(N)) kappa = 0.2 # coupling to oscillator def Liouvillian_func(t, args): c = np.sqrt(kappa * np.exp(-t)) * a data = liouvillian(H, [c]).data return data tlist = np.linspace(0, 10, 100) args = {"kappa": kappa} out1 = mesolve(Liouvillian_func, rho0, tlist, [], [], args=args) out2 = mesolve(Liouvillian_func, E0, tlist, [], [], args=args) fid = self.fidelitycheck(out1, out2, rho0vec) assert_(max(abs(1.0 - fid)) < me_error, True)
def fock_state(p, qudit_n, mode_n_entries=[], density_matrix_form=True): """ Creates specific fock states p: DictExtended object with sizes of qudit and mode Hilbert spaces qubit_n: fock level of the qudit mode_n_entries: list of lists, each with an index and a corresponding (nonground) fock state For example: mode_n_entries=[[0, 2], [4, 1]] would mean we want to have the mode with zero index be in the 2nd excited state, and mode with index 4 be in the 1st excited state. All other modes should be in their ground states. """ mode_states = [q.basis(p.N_m, 0)] * p.mode_count for entry in mode_n_entries: mode_states[entry[0]]=q.basis(p.N_m, entry[1]) state=q.tensor(q.basis(p.N_q, qudit_n), *mode_states) if density_matrix_form: return q.ket2dm(state) return state
def update_wigners(self): fd = self.state_data[0].dims[0][1] self.qubit_dms = [dm.ptrace(0) for dm in self.state_data] # todo: apply basis operation to qubit dms proj_0, proj_1 = [tensor(ket2dm(basis(2, i)), qeye(fd)) for i in (1, 0)] residuals_0 = [(proj_0 * dm * proj_0).ptrace(1) for dm in self.state_data] residuals_1 = [(proj_1 * dm * proj_1).ptrace(1) for dm in self.state_data] max_alpha = self.wigner_max.value() 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 processing_complete(res): self.data_0, self.data_1 = res self.update_plot() self.wigners_complete.emit() win.statusBar().showMessage("Wigners Finished", 2000) args = residuals_0, residuals_1, max_alpha run_in_process(process_wigners, processing_complete, args) self.calculating_wigners.emit() win.statusBar().showMessage("Calculating Wigners")
def apply_dephasing(number_of_spins, alpha, B,fm_str = 'AFM',kT = 0.0): ''' takes number of spins, alpha, and the magnetic field and returns the hamiltonian along with its ground state and the dephased ground state choose fm_str = 'FM' for ferromagnetic interaction, and 'AFM' for anti-ferromagnetic ''' if fm_str == 'FM': calc = ising_calculator_FM(number_of_spins, alpha, B) elif fm_str == 'AFM': calc = ising_calculator_AFM(number_of_spins, alpha, B) H = calc.get_H() if kT == 0.0: energy,groundstate = H.groundstate() dm_groundstate = ket2dm(groundstate) else: Hdata = H.data.todense() arr_mp = mp.matrix(-Hdata /kT) exp_mp = mp.expm(arr_mp) trace = np.array(exp_mp.tolist()).trace() normalized_mp = exp_mp / trace normalized_np = np.array(normalized_mp.tolist(), dtype = np.complex) dm_groundstate = Qobj(normalized_np, dims = 2 * [number_of_spins*[2]]) dephased = do_dephasing_dm(dm_groundstate, number_of_spins) return H, dm_groundstate, dephased
displayed_inds = np.where(np.logical_and(tau>=3*1e-6, tau<=5*1e-6))[0] res_ind = displayed_inds[np.argmin(analytical_P[displayed_inds])] t_step = tau[100]-tau[99] print tau[res_ind], analytical_P[res_ind] N_vals = np.arange(0,128,2) analytical_P = .5 * (1+analysis.calc_M_single(A, B, N_vals, omega_larmor, tau[res_ind])) res_N = N_vals[np.argmin(analytical_P[:15])] print res_N, analytical_P[res_N/2] speed = 12 num_pts = 2 * res_ind * res_N / speed print num_pts, res_ind, res_N, speed, res_ind % speed U = (-1j * t_step * speed * H).expm() rho_init = qt.tensor(qt.ket2dm(S0), .5 * (Ii + qt.sigmax())) rho = rho_init rho_s, rho_c = [rho.ptrace(0)], [rho.ptrace(1)] rotation_vector = [[0,0,-1]] counter = 0 first_pulse = True s_up = True omega_tilde = np.sqrt((A + omega_larmor) ** 2 + B ** 2) for ind in range(num_pts): if (first_pulse and counter == (res_ind/speed)) or ((not first_pulse) and counter == 2 * (res_ind/speed)): UorP = pi_pulse print "pulse ", counter, res_ind/speed counter = 0 first_pulse = False s_up = not s_up else:
def test_ket2dm_type(): "State CSR Type: ket2dm" st = ket2dm(basis(5,1)) assert_equal(isspmatrix_csr(st.data), True)
delta = 0. # detuning # time delay tau = np.pi/(eps) print 'tau =',tau dim_S = 2 Id = qt.spre(qt.qeye(dim_S))*qt.spost(qt.qeye(dim_S)) # Hamiltonian and jump operators H_S = delta*qt.sigmap()*qt.sigmam() + eps*(qt.sigmam()+qt.sigmap()) L1 = sp.sqrt(gamma)*qt.sigmam() L2 = sp.exp(1j*phi)*L1 # initial state rho0 = qt.ket2dm(qt.basis(2,0)) # times to evaluate rho(t) tlist=np.arange(0.0001,2*tau,0.01) def run(rho0=rho0,tau=tau,tlist=tlist): # run feedback simulation opts = qt.Options() opts.nsteps = 1e7 sol = np.array([rho0]*len(tlist)) for i,t in enumerate(tlist): sol[i] = cascade.rhot(rho0,t,tau,H_S,L1,L2,Id,options=opts) return tlist,sol def run_nofb(rho0=rho0,tlist=tlist): # run simulation without feedback
- 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. r = None # global variable with tomographer.jpyutil.RandWalkProgressBar() as prg: r = tomographer.tomorun.tomorun( # the dimension of the quantum system dim=4, # the tomography data