def test_partial_transpose_comparison(): """partial transpose: comparing sparse and dense implementations""" N = 10 rho = tensor(rand_dm(N, density=0.5), rand_dm(N, density=0.5)) # partial transpose of system 1 rho_pt1 = partial_transpose(rho, [1, 0], method="dense") rho_pt2 = partial_transpose(rho, [1, 0], method="sparse") np.abs(np.max(rho_pt1.full() - rho_pt1.full())) < 1e-12 # partial transpose of system 2 rho_pt1 = partial_transpose(rho, [0, 1], method="dense") rho_pt2 = partial_transpose(rho, [0, 1], method="sparse") np.abs(np.max(rho_pt1.full() - rho_pt2.full())) < 1e-12
def test_partial_transpose_randomized(): """partial transpose: randomized tests on tripartite system""" rho = tensor(rand_dm(2, density=1), rand_dm(2, density=1), rand_dm(2, density=1)) mask = np.random.randint(2, size=3) rho_pt_ref = _partial_transpose_reference(rho, mask) rho_pt1 = partial_transpose(rho, mask, method="dense") np.abs(np.max(rho_pt1.full() - rho_pt_ref.full())) < 1e-12 rho_pt2 = partial_transpose(rho, mask, method="sparse") np.abs(np.max(rho_pt2.full() - rho_pt_ref.full())) < 1e-12
def test_EntropyConditional(): "Entropy: Conditional entropy" # test_ S(A,B|C,D)<=S(A|C)+S(B|D) rhos = [ rand_dm(16, dims=[[2, 2, 2, 2], [2, 2, 2, 2]], pure=True) for k in range(20) ] for ABCD in rhos: AC = ptrace(ABCD, [0, 2]) BD = ptrace(ABCD, [1, 3]) assert_equal( entropy_conditional(ABCD, [2, 3]) <= (entropy_conditional(AC, 1) + entropy_conditional(BD, 1)), True) # test_ S(A|B,C)<=S(A|B) rhos = [ rand_dm(8, dims=[[2, 2, 2], [2, 2, 2]], pure=True) for k in range(20) ] for ABC in rhos: AB = ptrace(ABC, [0, 1]) assert_equal( entropy_conditional(ABC, [1, 2]) <= entropy_conditional(AB, 1), True)
class TestTypeFromDims: @pytest.mark.parametrize(["base", "expected", "enforce_square"], [ pytest.param([[2], [2]], 'oper', True), pytest.param([[2, 3], [2, 3]], 'oper', True), pytest.param([[2], [3]], 'other', True), pytest.param([[2], [3]], 'oper', False), pytest.param([[2], [1]], 'ket', True), pytest.param([[1], [2]], 'bra', True), pytest.param([[[2, 3], [2, 3]], [1]], 'operator-ket', True), pytest.param([[1], [[2, 3], [2, 3]]], 'operator-bra', True), pytest.param([[[3], [3]], [[2, 3], [2, 3]]], 'other', True), pytest.param([[[3], [3]], [[2, 3], [2, 3]]], 'super', False), pytest.param([[[2], [3, 3]], [[3], [2, 3]]], 'other', True), ]) def test_type_from_dims(self, base, expected, enforce_square): assert type_from_dims(base, enforce_square=enforce_square) == expected @pytest.mark.parametrize("qobj", [ pytest.param(qutip.rand_ket(10), id='ket'), pytest.param(qutip.rand_ket(10).dag(), id='bra'), pytest.param(qutip.rand_dm(10), id='oper'), pytest.param(qutip.to_super(qutip.rand_dm(10)), id='super'), ]) def test_qobj_dims_match_qobj(self, qobj): assert type_from_dims(qobj.dims) == qobj.type
def test_fidelity_max_dm(): """Tests for density matrices with respect to themselves to be equal to 1 (max)""" for _ in range(10): rho1 = jnp.asarray(rand_dm(25)) rho2 = jnp.asarray(rand_dm(25)) assert_almost_equal(fidelity(rho1, rho1), 1.0, decimal=4) assert_almost_equal(fidelity(rho2, rho2), 1.0, decimal=4)
def test_random_rho_sigma(self): rho = qutip.rand_dm(8, pure=False) sigma = qutip.rand_dm(8, pure=False) rel = qutip.entropy_relative(rho, sigma) assert rel >= 0 assert rel == pytest.approx( self._simple_relative_entropy_implementation(rho, sigma, np.log))
def test_invariant_under_unitary_transformation(self, dimension): rho1 = rand_dm(dimension, 0.25) rho2 = rand_dm(dimension, 0.25) U = rand_unitary(dimension, 0.25) D = tracedist(rho1, rho2) DU = tracedist(U * rho1 * U.dag(), U * rho2 * U.dag()) assert D == pytest.approx(DU, rel=1e-5)
def test_invariant_under_unitary_transformation(self, dimension): rho1 = rand_dm(dimension, 0.25) rho2 = rand_dm(dimension, 0.25) U = rand_unitary(dimension, 0.25) F = fidelity(rho1, rho2) FU = fidelity(U * rho1 * U.dag(), U * rho2 * U.dag()) assert F == pytest.approx(FU, rel=1e-5)
def test_fidelity_bounded_mixedmixed(tol=1e-7): """Tests for boundedness of fidelity among mixed states to be between [0, 1]""" for _ in range(10): rho1 = jnp.asarray(rand_dm(25)) rho2 = jnp.asarray(rand_dm(25)) F = fidelity(rho1, rho2) assert -tol <= F <= 1 + tol
def test_qfunc_is_linear(self, n_xs, n_ys, mix): xs = np.linspace(-1, 1, n_xs) ys = np.linspace(-1, 1, n_ys) qfunc = qutip.QFunc(xs, ys) left, right = qutip.rand_dm(5), qutip.rand_dm(5) qleft, qright = qfunc(left), qfunc(right) qboth = qfunc(mix * left + (1 - mix) * right) np.testing.assert_allclose(mix * qleft + (1 - mix) * qright, qboth)
def testRandDmSeed(self): "random density matrix with seed" seed = 12345 U0 = rand_dm(5, seed=seed) U1 = rand_dm(5, seed=None) U2 = rand_dm(5, seed=seed) assert_(U0 != U1) assert_(U0 == U2)
def testOperatorVectorTensor(self): """ Superoperator: Operator - vector - operator conversion with a tensor product state. """ Na = 3 Nb = 2 rhoa = rand_dm(Na) rhob = rand_dm(Nb) rho1 = tensor(rhoa, rhob) rho2 = vector_to_operator(operator_to_vector(rho1)) assert_((rho1 - rho2).norm() < 1e-8)
def test_qfunc_warns_if_insufficient_memory(self): xs = np.linspace(-1, 1, 11) state = qutip.rand_dm(4) with pytest.warns(UserWarning) as e: qutip.qfunc(state, xs, xs, precompute_memory=0) assert (e[0].message.args[0].startswith( "Falling back to iterative algorithm"))
def generate_density_matrices_entropy(n_samples, size_hilbert, step_size=0.01): """Generate n_samples density matrices with a uniform distribution of entropy Input: - n_samples (int): number of density matrices to generate - size_hilbert (int): dimension of the hilbert space of the density matrices - step_size (float): for each entropy p, sample dm with entropy in [p, p+step_size] Output: - rhos: array of dimension (n_samples, size_hilbert, size_hilbert) - entropies: array of dimension (n_samples,) """ print("Generate density matrices...") list_entropies = np.arange(0, np.log(size_hilbert), step_size) rhos = [] entropies = [] for i, s in enumerate(list_entropies): # for each entropy print(s) while len(rhos) < (i + 1) * n_samples // len(list_entropies): rho = rand_dm(size_hilbert, density=1).data.toarray() entropy = entropy_fct(rho) if s <= entropy <= s + step_size: rhos.append(rho) entropies.append(entropy) rhos = np.array(rhos) entropies = np.array(entropies) return rhos, entropies
def test_Transformation8(): "Check Qobj eigs and direct eig solver reverse transformations match" N = 10 H = rand_herm(N) # generate a random basis rand = rand_dm(N, density=1) evals, rand_basis = rand.eigenstates() evals2, rand_basis2 = sp_eigs(rand.data, isherm=1) H1 = H.transform(rand_basis, True) H2 = H.transform(rand_basis2, True) assert_((H1 - H2).norm() < 1e-6) ket = rand_ket(N) K1 = ket.transform(rand_basis,1) K2 = ket.transform(rand_basis2,1) assert_((K1 - K2).norm() < 1e-6) bra = rand_ket(N).dag() B1 = bra.transform(rand_basis,1) B2 = bra.transform(rand_basis2,1) assert_((B1 - B2).norm() < 1e-6)
def test_triangle_inequality_4_qubits(self): # S(A,B | C,D) <= S(A|C) + S(B|D) full = qutip.rand_dm(16, dims=[[2] * 4] * 2, pure=True) ac, bd = full.ptrace([0, 2]), full.ptrace([1, 3]) assert (qutip.entropy_conditional(full, [2, 3]) <= (qutip.entropy_conditional(ac, 1) + qutip.entropy_conditional(bd, 1)))
def test_function_and_class_are_equivalent(self, size, dm, n_xs, n_ys, g): xs = np.linspace(-1, 1, n_xs) ys = np.linspace(0, 2, n_ys) state = qutip.rand_dm(size) if dm else qutip.rand_ket(size) function = qutip.qfunc(state, xs, ys, g) class_ = qutip.QFunc(xs, ys, g)(state) np.testing.assert_allclose(function, class_)
def test_coo2csr_inplace_sort(): "Cython structs : COO to CSR inplace (sorted)" for k in range(20): A = rand_dm(5,0.5).data B = A.tocoo() C = _test_coo2csr_inplace_struct(B, sorted = 1) assert_(not (A!=C).data.any())
def test_coo2csr_struct(): "Cython structs : COO to CSR" for k in range(20): A = rand_dm(5,0.5).data B = A.tocoo() C = _test_coo2csr_struct(B) assert_(not (A!=C).data.any())
def test_csr2coo(): "Cython structs : CSR to COO" for k in range(20): A = rand_dm(5,0.5).data B = A.tocoo() C = _test_csr2coo_struct(A) assert_(not (B!=C).data.any())
def test_vector_roundtrip(): "BR Tools : vector roundtrip transform" dimension = 10 for _ in range(50): H = qutip.rand_herm(dimension, 0.5).full('F') vector = qutip.mat2vec(qutip.rand_dm(dimension, 0.5).full()).ravel() assert np.allclose(vector, _test_vector_roundtrip(H, vector))
def test_Transformation8(): "Check Qobj eigs and direct eig solver reverse transformations match" N = 10 H = rand_herm(N) # generate a random basis rand = rand_dm(N, density=1) evals, rand_basis = rand.eigenstates() evals2, rand_basis2 = sp_eigs(rand.data, isherm=1) H1 = H.transform(rand_basis, True) H2 = H.transform(rand_basis2, True) assert_((H1 - H2).norm() < 1e-6) ket = rand_ket(N) K1 = ket.transform(rand_basis, 1) K2 = ket.transform(rand_basis2, 1) assert_((K1 - K2).norm() < 1e-6) bra = rand_ket(N).dag() B1 = bra.transform(rand_basis, 1) B2 = bra.transform(rand_basis2, 1) assert_((B1 - B2).norm() < 1e-6)
def test_iterate_and_precompute_are_equivalent(self, size, n_xs, n_ys, g): xs = np.linspace(-1, 1, n_xs) ys = np.linspace(0, 2, n_ys) state = qutip.rand_dm(size) iterate = qutip.qfunc(state, xs, ys, g, precompute_memory=None) precompute = qutip.qfunc(state, xs, ys, g, precompute_memory=np.inf) np.testing.assert_allclose(iterate, precompute)
def test_EntropyMutual(): "Mutual information" # verify mutual information = S(A)+S(B) for pure state rhos = [rand_dm(25, dims=[[5, 5], [5, 5]], pure=True) for k in range(10)] for r in rhos: assert_equal(abs(entropy_mutual(r, [0], [1]) - ( entropy_vn(ptrace(r, 0)) + entropy_vn(ptrace(r, 1)))) < 1e-13, True) # check component selection rhos = [rand_dm(8, dims=[[2, 2, 2], [2, 2, 2]], pure=True) for k in range(10)] for r in rhos: assert_equal(abs(entropy_mutual(r, [0, 2], [1]) - (entropy_vn( ptrace(r, [0, 2])) + entropy_vn(ptrace(r, 1)))) < 1e-13, True)
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 testOperatorVector(self): """ Superoperator: Operator - vector - operator conversion. """ N = 3 rho1 = rand_dm(N) rho2 = vector_to_operator(operator_to_vector(rho1)) assert_((rho1 - rho2).norm() < 1e-8)
def test_graph_bfs(): "Graph: Breadth-First Search" A = rand_dm(25, 0.5) A = A.data A.data = np.real(A.data) seed = np.random.randint(24) arr1 = BFO(A, seed)[0] arr2 = breadth_first_search(A, seed)[0] assert_equal((arr1 - arr2).all(), 0)
def test_EntropyLinear(): "Linear entropy" # test_ entropy_vn = 0 for pure state psi = rand_ket(10) assert_equal(abs(entropy_linear(psi)) <= 1e-13, True) # test_ linear entropy always less than or equal to VN entropy rhos = [rand_dm(6) for k in range(10)] for k in rhos: assert_equal(entropy_linear(k) <= entropy_vn(k), True)
def testRanddm(self): "random density matrix" R = [rand_dm(5) for k in range(5)] for r in R: assert_(r.tr() - 1.0 < 1e-15) # verify all eigvals are >=0 assert_(not any(sp_eigs(r.data, r.isherm, vecs=False)) < 0) # verify hermitian assert_(r.isherm)
def test_diag_liou_mult(dimension): "BR Tools : Diagonal Liouvillian mult" H = qutip.rand_dm(dimension, 0.5) evals, evecs = H.eigenstates() L = qutip.liouvillian(H.transform(evecs)) coefficients = np.ones((dimension * dimension, ), dtype=np.complex128) calculated = np.zeros_like(coefficients) target = L.data.dot(coefficients) _test_diag_liou_mult(evals, coefficients, calculated, dimension) np.testing.assert_allclose(target, calculated, atol=1e-11, rtol=1e-6)
def test_EntropyLinear(): "Entropy: Linear entropy" # test_ entropy_vn = 0 for pure state psi = rand_ket(10) assert_equal(abs(entropy_linear(psi)) <= 1e-13, True) # test_ linear entropy always less than or equal to VN entropy rhos = [rand_dm(6) for k in range(10)] for k in rhos: assert_equal(entropy_linear(k) <= entropy_vn(k), True)
def testMultiLevelSystem(self): """ Test for processor with multi-level system """ N = 2 proc = Processor(N=N, dims=[2, 3]) proc.add_control(tensor(sigmaz(), rand_dm(3, density=1.)), label="sz0") proc.set_all_coeffs({"sz0": np.array([1, 2])}) proc.set_all_tlist(np.array([0., 1., 2])) proc.run_state(init_state=tensor([basis(2, 0), basis(3, 1)]))
def test_isbra(): """Tests the `isbra` method to see whether a state is a bra based on its shape""" for i in range(2, 6): assert isbra(rand_ket(i).full()) == False # tests kets for j in range(2, 6): assert isbra(dag(rand_ket(j).full())) == True # tests bras for k in range(2, 6): assert isbra(rand_dm(k).full()) == False # tests density matrices
def testLiouvillianImplem(self): """ Superoperator: Randomized comparison of standard and reference Liouvillian functions. """ N1 = 3 N2 = 4 N3 = 5 a1 = tensor(rand_dm(N1, density=0.75), identity(N2), identity(N3)) a2 = tensor(identity(N1), rand_dm(N2, density=0.75), identity(N3)) a3 = tensor(identity(N1), identity(N2), rand_dm(N3, density=0.75)) H = a1.dag() * a1 + a2.dag() * a2 + a3.dag() * a3 c_ops = [np.sqrt(0.01) * a1, np.sqrt(0.025) * a2, np.sqrt(0.05) * a3] L1 = liouvillian(H, c_ops) L2 = liouvillian_ref(H, c_ops) assert_((L1 - L2).norm('max') < 1e-8)
def test_EntropyConditional(): "Conditional entropy" # test_ S(A,B|C,D)<=S(A|C)+S(B|D) rhos = [rand_dm(16, dims=[[2, 2, 2, 2], [2, 2, 2, 2]], pure=True) for k in range(20)] for ABCD in rhos: AC = ptrace(ABCD, [0, 2]) BD = ptrace(ABCD, [1, 3]) assert_equal(entropy_conditional(ABCD, [2, 3]) <= ( entropy_conditional(AC, 1) + entropy_conditional(BD, 1)), True) # test_ S(A|B,C)<=S(A|B) rhos = [rand_dm(8, dims=[[2, 2, 2], [2, 2, 2]], pure=True) for k in range(20)] for ABC in rhos: AB = ptrace(ABC, [0, 1]) assert_equal(entropy_conditional( ABC, [1, 2]) <= entropy_conditional(AB, 1), True)
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 testOperatorUnitaryTransform(self): """ Superoperator: Unitary transformation with operators and superoperators """ N = 3 rho = rand_dm(N) U = rand_unitary(N) rho1 = U * rho * U.dag() rho2_vec = spre(U) * spost(U.dag()) * operator_to_vector(rho) rho2 = vector_to_operator(rho2_vec) assert_((rho1 - rho2).norm() < 1e-8)
def testRanddmEigs(self): "Random: Density matrix - Eigs given" R = [] for k in range(5): eigs = np.random.random(5) eigs /= np.sum(eigs) R += [rand_dm(eigs)] for r in R: assert_(r.tr() - 1.0 < 1e-15) # verify all eigvals are >=0 assert_(not any(sp_eigs(r.data, r.isherm, vecs=False)) < 0) # verify hermitian assert_(r.isherm)
def testOperatorSpreAppl(self): """ Superoperator: apply operator and superoperator from left (spre) """ N = 3 rho = rand_dm(N) U = rand_unitary(N) rho1 = U * rho rho2_vec = spre(U) * operator_to_vector(rho) rho2 = vector_to_operator(rho2_vec) assert_((rho1 - rho2).norm() < 1e-8)
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 testOperatorSpostAppl(self): """ Superoperator: apply operator and superoperator from right (spost) """ N = 3 rho = rand_dm(N) U = rand_unitary(N) rho1 = rho * U rho2_vec = spost(U) * operator_to_vector(rho) rho2 = vector_to_operator(rho2_vec) assert_((rho1 - rho2).norm() < 1e-8)
def test_graph_degree(): "Graph: Graph Degree" A = rand_dm(25, 0.1) deg = graph_degree(A.data) A = A.full() np_deg = [] for k in range(25): num = 0 inds = A[k, :].nonzero()[0] num = len(inds) if k in inds: num += 1 np_deg.append(num) np.asarray(np_deg, dtype=int) assert_equal((deg - np_deg).all(), 0)