def test_eigsh_lanczos_reorthogonalize_sanity_check(dtype, numeig): np.random.seed(10) D = 24 backend = symmetric_backend.SymmetricBackend() index = Index(U1Charge.random(D, 0, 0), True) indices = [index, index.copy().flip_flow()] H = BlockSparseTensor.random(indices, dtype=dtype) H = H + H.conj().T def mv(x, mat): return mat @ x eta1, U1 = backend.eigsh_lanczos(mv, [H], shape=(H.sparse_shape[1].flip_flow(), ), dtype=dtype, numeig=numeig, num_krylov_vecs=D, reorthogonalize=True, ndiag=1, tol=10**(-12), delta=10**(-12)) eta2, U2 = np.linalg.eigh(H.todense()) np.testing.assert_allclose(eta1[0:numeig], eta2[0:numeig]) for n in range(numeig): v2 = U2[:, n] v2 /= np.sum(v2) #fix phases v1 = np.reshape(U1[n].todense(), (D)) v1 /= np.sum(v1) np.testing.assert_allclose(v1, v2, rtol=10**(-5), atol=10**(-5))
def test_eigsh_lanczos_sanity_check_2(dtype): np.random.seed(10) D = 16 backend = symmetric_backend.SymmetricBackend() index = Index(U1Charge.random(D, 0, 0), True) indices = [index, index.copy().flip_flow()] H = BlockSparseTensor.random(indices, dtype=dtype) H = H + H.conj().T def mv(x, mat): return mat @ x eta1, U1 = backend.eigsh_lanczos(mv, [H], shape=(H.sparse_shape[1].flip_flow(), ), dtype=dtype) eta2, U2 = np.linalg.eigh(H.todense()) v1 = np.reshape(U1[0].todense(), (D)) v1 = v1 / sum(v1) v2 = U2[:, 0] v2 = v2 / sum(v2) np.testing.assert_allclose(eta1[0], min(eta2)) np.testing.assert_allclose(v1, v2)
def test_eigsh_caching(): def matvec(mps, A, B, C): return ncon([A, mps, B, C], [[3, 1, -1], [1, 2, 4], [3, 5, -2, 2], [5, 4, -3]], backend='symmetric') backend = symmetric_backend.SymmetricBackend() D = 100 M = 5 mpsinds = [ Index(U1Charge(np.random.randint(5, 15, D, dtype=np.int16)), False), Index(U1Charge(np.array([0, 1, 2, 3], dtype=np.int16)), False), Index(U1Charge(np.random.randint(5, 18, D, dtype=np.int16)), True) ] mpoinds = [ Index(U1Charge(np.random.randint(0, 5, M)), False), Index(U1Charge(np.random.randint(0, 10, M)), True), mpsinds[1], mpsinds[1].flip_flow() ] Linds = [mpoinds[0].flip_flow(), mpsinds[0].flip_flow(), mpsinds[0]] Rinds = [mpoinds[1].flip_flow(), mpsinds[2].flip_flow(), mpsinds[2]] mps = BlockSparseTensor.random(mpsinds) mpo = BlockSparseTensor.random(mpoinds) L = BlockSparseTensor.random(Linds) R = BlockSparseTensor.random(Rinds) ncv = 20 backend.eigsh_lanczos(matvec, [L, mpo, R], initial_state=mps, num_krylov_vecs=ncv) assert get_cacher().cache == {}
def test_eigsh_lanczos_raises(): backend = symmetric_backend.SymmetricBackend() with pytest.raises(ValueError, match='`num_krylov_vecs` >= `numeig` required!'): backend.eigsh_lanczos(lambda x: x, numeig=10, num_krylov_vecs=9) with pytest.raises( ValueError, match="Got numeig = 2 > 1 and `reorthogonalize = False`. " "Use `reorthogonalize=True` for `numeig > 1`"): backend.eigsh_lanczos(lambda x: x, numeig=2, reorthogonalize=False) with pytest.raises( ValueError, match="if no `initial_state` is passed, then `shape` and" "`dtype` have to be provided"): backend.eigsh_lanczos(lambda x: x, shape=(10, ), dtype=None) with pytest.raises( ValueError, match="if no `initial_state` is passed, then `shape` and" "`dtype` have to be provided"): backend.eigsh_lanczos(lambda x: x, shape=None, dtype=np.float64) with pytest.raises( ValueError, match="if no `initial_state` is passed, then `shape` and" "`dtype` have to be provided"): backend.eigsh_lanczos(lambda x: x) with pytest.raises( TypeError, match="Expected a `BlockSparseTensor`. Got <class 'list'>"): backend.eigsh_lanczos(lambda x: x, initial_state=[1, 2, 3])
def test_eigs_raises(): np.random.seed(10) dtype = np.float64 backend = symmetric_backend.SymmetricBackend() D = 16 index = Index(U1Charge.random(D, 0, 0), True) indices = [index, index.copy().flip_flow()] H = BlockSparseTensor.random(indices, dtype=dtype) init = BlockSparseTensor.random([index], dtype=dtype) with pytest.raises(ValueError, match='which = SI is currently not supported.'): backend.eigs(lambda x: x, [H], initial_state=init, which='SI') with pytest.raises(ValueError, match='which = LI is currently not supported.'): backend.eigs(lambda x: x, [H], initial_state=init, which='LI') with pytest.raises( ValueError, match="if no `initial_state` is passed, then `shape` and" "`dtype` have to be provided"): backend.eigs(lambda x: x, [H]) with pytest.raises(ValueError, match="`num_krylov_vecs`"): backend.eigs(lambda x: x, [H], numeig=3, num_krylov_vecs=3) with pytest.raises(TypeError, match="Expected a"): backend.eigs(lambda x: x, [H], initial_state=[])
def test_shape_concat(): backend = symmetric_backend.SymmetricBackend() a = np.asarray((2 * np.ones((1, 3, 1)))) b = np.asarray(np.ones((1, 2, 1))) expected = backend.shape_concat((a, b), axis=1) actual = np.array([[[2.0], [2.0], [2.0], [1.0], [1.0]]]) np.testing.assert_allclose(expected, actual)
def test_conj(dtype, num_charges): np.random.seed(10) R = 4 backend = symmetric_backend.SymmetricBackend() a = get_tensor(R, num_charges, dtype) aconj = backend.conj(a) np.testing.assert_allclose(aconj.data, np.conj(a.data))
def test_eigsh_valid_init_operator_with_shape(dtype): np.random.seed(100) backend = symmetric_backend.SymmetricBackend() np_backend = numpy_backend.NumPyBackend() D = 16 index = Index(U1Charge.random(D, -1, 1), True) indices = [index, index.copy().flip_flow()] a = BlockSparseTensor.random(indices, dtype=dtype) H = a + a.T.conj() def mv(vec, mat): return mat @ vec init = BlockSparseTensor.random([index], dtype=dtype) # note: this will only find eigenvalues in the charge (0,0) # block of H because `init` only has non-zero values there. # To find eigen values in other sectors we need to support non-zero # divergence for block-sparse tensors eta1, U1 = backend.eigsh_lanczos(mv, [H], init) eta2, U2 = np_backend.eigsh_lanczos(mv, [H.todense()], init.todense()) v1 = np.reshape(U1[0].todense(), (D)) v1 = v1 / sum(v1) v1 /= np.linalg.norm(v1) v2 = np.reshape(U2[0], (D)) v2 = v2 / sum(v2) v2[np.abs(v2) < 1E-12] = 0.0 v2 /= np.linalg.norm(v2) np.testing.assert_allclose(eta1[0], min(eta2)) np.testing.assert_allclose(v1, v2)
def test_diagonal(Ds, dtype, num_charges, flow): np.random.seed(10) backend = symmetric_backend.SymmetricBackend() np_flow = -np.int((np.int(flow) - 0.5) * 2) indices = [ Index( BaseCharge(np.random.randint(-2, 3, (Ds[n], num_charges)), charge_types=[U1Charge] * num_charges), flow) for n in range(2) ] arr = BlockSparseTensor.random(indices, dtype=dtype) fused = fuse_charges(arr.flat_charges, arr.flat_flows) inds = np.nonzero(fused == np.zeros((1, num_charges), dtype=np.int16))[0] # pylint: disable=no-member left, _ = np.divmod(inds, Ds[1]) unique = np.unique(np_flow * (indices[0]._charges[0].charges[left, :]), axis=0) diagonal = backend.diagonal(arr) sparse_blocks, _, block_shapes = _find_diagonal_sparse_blocks( arr.flat_charges, arr.flat_flows, 1) data = np.concatenate([ np.diag(np.reshape(arr.data[sparse_blocks[n]], block_shapes[:, n])) for n in range(len(sparse_blocks)) ]) np.testing.assert_allclose(data, diagonal.data) np.testing.assert_allclose(unique, diagonal.flat_charges[0].unique_charges) with pytest.raises(NotImplementedError): diagonal = backend.diagonal(arr, axis1=0) with pytest.raises(NotImplementedError): diagonal = backend.diagonal(arr, axis2=1) with pytest.raises(NotImplementedError): diagonal = backend.diagonal(arr, offset=1)
def test_addition(R, dtype, num_charges): np.random.seed(10) backend = symmetric_backend.SymmetricBackend() a = get_tensor(R, num_charges, dtype) b = BlockSparseTensor.random(a.sparse_shape) res = backend.addition(a, b) np.testing.assert_allclose(res.data, a.data + b.data)
def test_truediv(dtype, num_charges): np.random.seed(10) R = 4 backend = symmetric_backend.SymmetricBackend() a = get_tensor(R, num_charges, dtype) res = backend.divide(a, 5.1) np.testing.assert_allclose(res.data, a.data / 5.1)
def test_trace(dtype, num_charges): np.random.seed(10) backend = symmetric_backend.SymmetricBackend() a = get_square_matrix(num_charges, dtype) actual = backend.trace(a) expected = trace(a) np.testing.assert_allclose(actual.data, expected.data)
def test_truediv_raises(dtype, num_charges): np.random.seed(10) R = 4 backend = symmetric_backend.SymmetricBackend() a = get_tensor(R, num_charges, dtype) with pytest.raises(TypeError): backend.divide(a, np.array([5.1]))
def test_shape_tensor(): backend = symmetric_backend.SymmetricBackend() a = np.asarray(np.ones([2, 3, 4])) assert isinstance(backend.shape_tensor(a), tuple) actual = backend.shape_tensor(a) expected = np.array([2, 3, 4]) np.testing.assert_allclose(expected, actual)
def test_eye_dtype(dtype, num_charges): np.random.seed(10) backend = symmetric_backend.SymmetricBackend() index = Index( BaseCharge(np.random.randint(-5, 6, (num_charges, 100)), charge_types=[U1Charge] * num_charges), False) actual = backend.eye(index, dtype=dtype) assert actual.dtype == dtype
def test_sqrt(R, dtype, num_charges): np.random.seed(10) backend = symmetric_backend.SymmetricBackend() a = get_tensor(R, num_charges, dtype) actual = backend.sqrt(a) expected = sqrt(a) np.testing.assert_allclose(expected.data, actual.data) assert np.all([ charge_equal(expected._charges[n], actual._charges[n]) for n in range(len(actual._charges)) ])
def test_random_uniform_non_zero_imag(R, dtype, num_charges): np.random.seed(10) backend = symmetric_backend.SymmetricBackend() indices = [ Index( BaseCharge(np.random.randint(-5, 6, (num_charges, 10)), charge_types=[U1Charge] * num_charges), False) for _ in range(R) ] actual = backend.random_uniform(indices, dtype=dtype, seed=10) assert np.linalg.norm(np.imag(actual.data)) != 0.0
def test_zeros_dtype(R, dtype, num_charges): np.random.seed(10) backend = symmetric_backend.SymmetricBackend() indices = [ Index( BaseCharge(np.random.randint(-5, 6, (num_charges, 10)), charge_types=[U1Charge] * num_charges), False) for _ in range(R) ] actual = backend.zeros(indices, dtype=dtype) assert actual.dtype == dtype
def test_subbtraction_raises(R, dtype, num_charges): np.random.seed(10) backend = symmetric_backend.SymmetricBackend() a = get_tensor(R, num_charges, dtype) b = get_tensor(R + 1, num_charges, dtype) with pytest.raises(ValueError): backend.subtraction(a, b) shape = b.sparse_shape c = BlockSparseTensor.random([shape[n] for n in reversed(range(len(shape)))]) with pytest.raises(ValueError): backend.subtraction(a, c)
def test_matrix_inv(dtype, num_charges): np.random.seed(10) backend = symmetric_backend.SymmetricBackend() H = get_hermitian_matrix(num_charges, dtype) Hinv = backend.inv(H) Hinv_ac = inv(H) np.testing.assert_allclose(Hinv_ac.data, Hinv.data) assert np.all([ charge_equal(Hinv._charges[n], Hinv_ac._charges[n]) for n in range(len(Hinv._charges)) ])
def test_tensordot(R1, R2, cont, dtype, num_charges): np.random.seed(10) backend = symmetric_backend.SymmetricBackend() a, b, indsa, indsb = get_contractable_tensors(R1, R2, cont, dtype, num_charges) actual = backend.tensordot(a, b, (indsa, indsb)) expected = tensordot(a, b, (indsa, indsb)) np.testing.assert_allclose(expected.data, actual.data) assert np.all([ charge_equal(expected._charges[n], actual._charges[n]) for n in range(len(actual._charges)) ])
def test_outer_product(R1, R2, dtype, num_charges): np.random.seed(10) backend = symmetric_backend.SymmetricBackend() a = get_tensor(R1, num_charges, dtype) b = get_tensor(R2, num_charges, dtype) actual = backend.outer_product(a, b) expected = tensordot(a, b, 0) np.testing.assert_allclose(expected.data, actual.data) assert np.all([ charge_equal(expected._charges[n], actual._charges[n]) for n in range(len(actual._charges)) ])
def test_random_uniform_dtype(dtype, num_charges): np.random.seed(10) R = 4 backend = symmetric_backend.SymmetricBackend() indices = [ Index( BaseCharge(np.random.randint(-5, 6, (num_charges, 10)), charge_types=[U1Charge] * num_charges), False) for _ in range(R) ] actual = backend.random_uniform(indices, dtype=dtype, seed=10) assert actual.dtype == dtype
def test_transpose(R, dtype, num_charges): np.random.seed(10) backend = symmetric_backend.SymmetricBackend() a = get_tensor(R, num_charges, dtype) order = np.arange(R) np.random.shuffle(order) actual = backend.transpose(a, order) expected = transpose(a, order) np.testing.assert_allclose(expected.data, actual.data) assert np.all([ charge_equal(expected._charges[n], actual._charges[n]) for n in range(len(actual._charges)) ])
def test_eigh(dtype, num_charges): np.random.seed(10) backend = symmetric_backend.SymmetricBackend() H = get_hermitian_matrix(num_charges, dtype) eta, U = backend.eigh(H) eta_ac, U_ac = eigh(H) np.testing.assert_allclose(eta.data, eta_ac.data) np.testing.assert_allclose(U.data, U_ac.data) assert charge_equal(eta._charges[0], eta_ac._charges[0]) assert np.all([ charge_equal(U._charges[n], U_ac._charges[n]) for n in range(len(U._charges)) ])
def test_eye(dtype, num_charges): np.random.seed(10) backend = symmetric_backend.SymmetricBackend() index = Index( BaseCharge(np.random.randint(-5, 6, (num_charges, 100)), charge_types=[U1Charge] * num_charges), False) actual = backend.eye(index, dtype=dtype) expected = eye(index, dtype=dtype) np.testing.assert_allclose(expected.data, actual.data) assert np.all([ charge_equal(expected._charges[n], actual._charges[n]) for n in range(len(actual._charges)) ])
def test_trace(dtype, num_charges, offset, axis1, axis2): np.random.seed(10) backend = symmetric_backend.SymmetricBackend() a = get_square_matrix(num_charges, dtype) if offset != 0: with pytest.raises(NotImplementedError): actual = backend.trace(a, offset=offset, axis1=axis1, axis2=axis2) elif axis1 == axis2: with pytest.raises(ValueError): actual = backend.trace(a, offset=offset, axis1=axis1, axis2=axis2) else: actual = backend.trace(a, offset=offset, axis1=axis1, axis2=axis2) expected = trace(a, [axis1, axis2]) np.testing.assert_allclose(actual.data, expected.data)
def test_sparse_shape(dtype, num_charges): np.random.seed(10) Ds = [11, 12, 13] R = len(Ds) charges = [ BaseCharge(np.random.randint(-5, 6, (num_charges, Ds[n])), charge_types=[U1Charge] * num_charges) for n in range(R) ] flows = list(np.full(R, fill_value=False, dtype=np.bool)) indices = [Index(charges[n], flows[n]) for n in range(R)] a = BlockSparseTensor.random(indices=indices, dtype=dtype) backend = symmetric_backend.SymmetricBackend() for s1, s2 in zip(a.sparse_shape, backend.sparse_shape(a)): assert s1 == s2
def test_diag(dtype, num_charges): np.random.seed(10) backend = symmetric_backend.SymmetricBackend() a = get_tensor(3, num_charges, dtype) with pytest.raises(ValueError): backend.diag(a) b = get_chargearray(num_charges, dtype) expected = diag(b) actual = backend.diag(b) np.testing.assert_allclose(expected.data, actual.data) assert np.all([ charge_equal(expected._charges[n], actual._charges[n]) for n in range(len(actual._charges)) ])
def test_broadcast_right_multiplication_raises(): np.random.seed(10) backend = symmetric_backend.SymmetricBackend() num_charges = 1 Ds = [10, 30, 24] R = len(Ds) indices = [ Index( BaseCharge(np.random.randint(-5, 6, (num_charges, Ds[n])), charge_types=[U1Charge] * num_charges), False) for n in range(R) ] tensor1 = backend.randn(indices) tensor2 = ChargeArray.random(indices=indices) with pytest.raises(ValueError): backend.broadcast_right_multiplication(tensor1, tensor2)