Example #1
0
def test_init_tensor_from_backend_array(backend, dtype):
  """
  Creates an instance of the backend's array class, initializes a Tensor from
  it, and checks that all its members have been correctly initialized.
  """
  shape = (2, 3, 1)
  if backend == "pytorch":
    if dtype not in testing_utils.torch_supported_dtypes:
      with pytest.raises(TypeError):
        dtype = testing_utils.np_dtype_to_backend(backend, dtype)
      return

    dtype = testing_utils.np_dtype_to_backend(backend, dtype)
    init = torch.zeros(shape, dtype=dtype)
  elif backend == "numpy":
    dtype = testing_utils.np_dtype_to_backend(backend, dtype)
    init = np.zeros(shape, dtype=dtype)
  elif backend == "jax":
    dtype = testing_utils.np_dtype_to_backend(backend, dtype)
    init = jnp.zeros(shape, dtype=dtype)
  elif backend == "tensorflow":
    dtype = testing_utils.np_dtype_to_backend(backend, dtype)
    init = tf.zeros(shape, dtype=dtype)
  else:
    raise ValueError("Unexpected backend ", backend)
  A = tensornetwork.Tensor(init, backend=backend)
  assert A.backend.name == backend
  np.testing.assert_allclose(A.array, init)
  assert A.shape == init.shape
  assert A.size == np.prod(init.shape)
  assert A.ndim == init.ndim
Example #2
0
def polarU(A: tn.Tensor,
           pivot_axis: int = -1,
           mode: Text = "svd",
           Niter: int = 4) -> tn.Tensor:
    """
  Computes the isometric factor U in the polar decomposition, U = u @ vh
  where u and vh are the singular vector matrices in the SVD.
  Args:
    A: The input tensor.
    pivot_axis: Determines where to matricize A.
    mode: Algorithm used for the decomposition. See vumps_params.
    Niter: Maximum number of iteration allotted the QDWH algorithm.
  Returns:
    U: The decomposed tensor, reshaped to A.shape.
  """

    A_mat = tn.pivot(A, pivot_axis=pivot_axis)
    if mode == "svd":
        W, _, Vh, _ = A.backend.svd(A_mat.array)
        Umat_arr = W @ Vh
    elif mode == "QDWH":
        Umat_arr = polarU_QDWH(A_mat, Niter=Niter)
    else:
        raise ValueError(f"Mode {mode} was invalid.")
    U_mat = tn.Tensor(Umat_arr, backend=A.backend)
    U = U_mat.reshape(A.shape)
    return U
Example #3
0
def safe_zeros(shape, backend, dtype):
  """
  Creates a tensor of zeros, catching errors that occur when the
  dtype is not supported by the backend. Returns both the Tensor and the backend
  array, which are both None if the dtype and backend did not match.
  """
  init = np.zeros(shape, dtype=dtype)
  if backend == "pytorch" and dtype not in torch_supported_dtypes:
    pytest.skip("dtype unsupported by PyTorch")
  else:
    A = tensornetwork.Tensor(init, backend=backend)
  return (A, init)
Example #4
0
def test_init_tensor_default_backend(dtype):
  """ Creates a numpy array, initializes a Tensor from it, and checks that all
  its members have been correctly initialized.
  """
  backend = backend_contextmanager.get_default_backend()
  backend_obj = backends.backend_factory.get_backend(backend)
  shape = (3, 5, 2)
  testA = backend_obj.zeros(shape, dtype=dtype)
  init = np.zeros(shape, dtype=dtype)
  A = tensornetwork.Tensor(init)
  assert A.backend.name == backend
  np.testing.assert_allclose(A.array, testA)
  assert A.shape == testA.shape
  assert A.size == testA.size
  assert A.ndim == testA.ndim
Example #5
0
def sigD(backend: Optional[BackendType] = None,
         dtype: Optional[DtypeType] = None) -> tn.Tensor:
    """
  Pauli 'down' matrix.

  Args:
    backend: The backend.
    dtype  : dtype of data.
  Returns:
    D      : The Pauli D matrix, a tn.Tensor.
  """
    vals = [[0., 0], [1, 0]]
    array = np.array(vals, dtype=dtype)
    out = tn.Tensor(array, backend=backend)
    return out
Example #6
0
def sigZ(backend: Optional[BackendType] = None,
         dtype: Optional[DtypeType] = None) -> tn.Tensor:
    """
  Pauli Z matrix.

  Args:
    backend: The backend.
    dtype  : dtype of data.
  Returns:
    Z      : The Pauli Z matrix, a tn.Tensor.
  """
    vals = [[1., 0], [0, -1]]
    array = np.array(vals, dtype=dtype)
    out = tn.Tensor(array, backend=backend)
    return out
Example #7
0
def safe_randn(shape, backend, dtype):
  """
  Creates a random tensor , catching errors that occur when the
  dtype is not supported by the backend. Returns the Tensor and the backend
  array, which are both None if the dtype and backend did not match.
  """
  np.random.seed(seed=10)
  init = np.random.randn(*shape)
  if dtype == np.bool:
    init = np.round(init)
  init = init.astype(dtype)

  if dtype in np_complex:
    init_i = np.random.randn(*shape)
    init = init + 1.0j * init_i.astype(dtype)

  if backend == "pytorch" and dtype not in torch_supported_dtypes:
    pytest.skip("dtype unsupported by PyTorch")
  else:
    A = tensornetwork.Tensor(init, backend=backend)
  return (A, init)
Example #8
0
def null_space(A: tn.Tensor) -> tn.Tensor:
    """
  Returns the null space of the matrix A.
  Args:
    A: The tensor.
    pivot_axis: Where to matricize.
  Returns:
    The null space, shaped as a matrix.
  """
    if A.backend.name == "numpy":
        N_arr = scipy.linalg.null_space(A.array)
    elif A.backend.name == "jax":
        U, S, Vh = jnp.linalg.svd(A.array, full_matrices=True)
        M, N = U.shape[0], Vh.shape[1]
        rcond = np.finfo(A.dtype).eps * max(M, N)
        tol = jnp.amax(S) * rcond
        num = jnp.sum(S > tol, dtype=int)
        N_arr = Vh[num:, :].T.conj()
    else:
        raise ValueError(f"Unsupported backend {A.backend.name}.")
    return tn.Tensor(N_arr, backend=A.backend)