From c20935a0ebad686b785393c5409835a46d76e750 Mon Sep 17 00:00:00 2001 From: MikeMerzl Date: Mon, 12 Oct 2020 17:37:32 +0300 Subject: [PATCH 1/8] Ones_like & zeros_like --- tensornetwork/linalg/initialization.py | 50 +++++++++++++++++++ .../linalg/tests/initialization_test.py | 32 ++++++++++++ 2 files changed, 82 insertions(+) diff --git a/tensornetwork/linalg/initialization.py b/tensornetwork/linalg/initialization.py index fe8ca7512..a86dd1b14 100644 --- a/tensornetwork/linalg/initialization.py +++ b/tensornetwork/linalg/initialization.py @@ -106,6 +106,56 @@ def ones(shape: Sequence[int], return the_tensor +def ones_like(input: Union[Any], + dtype: Optional[Type[Any]] = None, + backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor: + """Return a Tensor shape full of ones the same shape as input + Args: + input : Object to recieve shape from + dtype (optional) : dtype of object + backend(optional): The backend or its name.""" + if backend is None: + backend = backend_contextmanager.get_default_backend() + else: + backend = backend_contextmanager.backend_factory.get_backend(backend) + if isinstance(input, Tensor): # incase input of type Tensor, create Tensor normally + the_tensor = initialize_tensor("ones", input.shape, backend=input.backend, dtype=input.dtype) + return the_tensor + else: + try: + input = backend.convert_to_tensor(input) + except TypeError as e: + error = "Input to zeros_like has invalid type causing error massage: \n" + str(e) + raise TypeError(error) from e + the_tensor = initialize_tensor("ones", input.get_shape().as_list(), backend=backend, dtype=dtype) + return the_tensor + + +def zeros_like(input: Union[Any], + dtype: Optional[Any] = None, + backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor: + """Return a Tensor shape full of zeros the same shape as input + Args: + input : Object to recieve shape from + dtype (optional) : dtype of object + backend(optional): The backend or its name.""" + if backend is None: + backend = backend_contextmanager.get_default_backend() + else: + backend = backend_contextmanager.backend_factory.get_backend(backend) + if isinstance(input, Tensor): # incase input of type Tensor, create Tensor normally + the_tensor = initialize_tensor("zeros", input.shape, backend=input.backend, dtype=input.dtype) + return the_tensor + else: + try: + input = backend.convert_to_tensor(input) + except TypeError as e: + error = "Input to zeros_like has invalid type causing error massage: \n" + str(e) + raise TypeError(error) from e + the_tensor = initialize_tensor("zeros", input.shape, backend=backend, dtype=dtype) + return the_tensor + + def randn(shape: Sequence[int], dtype: Optional[Type[np.number]] = None, seed: Optional[int] = None, diff --git a/tensornetwork/linalg/tests/initialization_test.py b/tensornetwork/linalg/tests/initialization_test.py index a7186162c..d349cb248 100644 --- a/tensornetwork/linalg/tests/initialization_test.py +++ b/tensornetwork/linalg/tests/initialization_test.py @@ -138,3 +138,35 @@ def test_random_uniform(backend): npI = backend_obj.random_uniform( shape, dtype=dtype, seed=seed, boundaries=boundaries) np.testing.assert_allclose(tnI.array, npI) + +@pytest.mark.parametrize("shape", (2, 4, 1)) +@pytest.mark.parametrize("n", np.eye(2)) +def test_ones_like(backend, shape, n): + """Tests tensornetwork.ones_like against np.zeros_like""" + backend_obj = backends.backend_factory.get_backend(backend) + @pytest.mark.parametrize("dtype,expected",(dtypes[backend]["all"])) + def inner_ones_test(dtype): + objTensor = tensornetwork.ones(shape, dtype=dtype, backend=backend) + tensor = tensornetwork.ones_like(objTensor, dtype=dtype, backend=backend) # input as Tensor object + numpyT = tensornetwork.ones_like(n, dtype=dtype, backend=backend) # input as numpy array + tensorCheck = backend_obj.ones(shape, dtype=dtype) + numpyCheck = backend_obj.ones(n.shape, dtype=dtype) + np.testing.assert_allclose(tensor.array, tensorCheck) + np.testing.assert_allclose(numpyT.array, numpyCheck) + + +@pytest.mark.parametrize("shape", (2, 4, 1)) +@pytest.mark.parametrize("n", np.eye(2)) +def test_zeros_like(backend, shape, n): + """Tests tensornetwork.zeros_like against np.zeros_like""" + backend_obj = backends.backend_factory.get_backend(backend) + + @pytest.mark.parametrize("dtype,expected",(dtypes[backend]["all"])) + def inner_zero_test(dtype): + objTensor = tensornetwork.zeros(shape, dtype=dtype, backend=backend) + tensor = tensornetwork.zeros_like(objTensor, dtype=dtype, backend=backend) # input as Tensor object + numpyT = tensornetwork.zeros_like(n, dtype=dtype, backend=backend) # input as numpy array + tensorCheck = backend_obj.zeros(shape, dtype=dtype) + numpyCheck = backend_obj.zeros(n.shape, dtype=dtype) + np.testing.assert_allclose(tensor.array, tensorCheck) + np.testing.assert_allclose(numpyT.array, numpyCheck) From 1f48668f3b68422892f8868c267891beae5db075 Mon Sep 17 00:00:00 2001 From: MikeMerzl Date: Mon, 12 Oct 2020 20:49:47 +0300 Subject: [PATCH 2/8] Ones_like & zeros_like --- tensornetwork/linalg/initialization.py | 137 +++++++++--------- .../linalg/tests/initialization_test.py | 21 ++- 2 files changed, 85 insertions(+), 73 deletions(-) diff --git a/tensornetwork/linalg/initialization.py b/tensornetwork/linalg/initialization.py index a86dd1b14..39d345210 100644 --- a/tensornetwork/linalg/initialization.py +++ b/tensornetwork/linalg/initialization.py @@ -29,7 +29,7 @@ def initialize_tensor(fname: Text, *fargs: Any, backend: Optional[Union[Text, AbstractBackend]] = None, **fkwargs: Any) -> Tensor: - """Return a Tensor wrapping data obtained by an initialization function + """Return a Tensor wrapping data obtained by an initialization function implemented in a backend. The Tensor will have the same shape as the underlying array that function generates, with all Edges dangling. This function is not intended to be called directly, but doing so should @@ -44,20 +44,20 @@ def initialize_tensor(fname: Text, (the_backend).fname(*fargs, **fkwargs), with one dangling edge per axis of data. """ - if backend is None: - backend = backend_contextmanager.get_default_backend() - backend_obj = backends.backend_factory.get_backend(backend) - func = getattr(backend_obj, fname) - data = func(*fargs, **fkwargs) - tensor = Tensor(data, backend=backend) - return tensor + if backend is None: + backend = backend_contextmanager.get_default_backend() + backend_obj = backends.backend_factory.get_backend(backend) + func = getattr(backend_obj, fname) + data = func(*fargs, **fkwargs) + tensor = Tensor(data, backend=backend) + return tensor def eye(N: int, dtype: Optional[Type[np.number]] = None, M: Optional[int] = None, backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor: - """Return a Tensor representing a 2D array with ones on the diagonal and + """Return a Tensor representing a 2D array with ones on the diagonal and zeros elsewhere. The Tensor has two dangling Edges. Args: N (int): The first dimension of the returned matrix. @@ -69,14 +69,14 @@ def eye(N: int, Represents an array of all zeros except for the k'th diagonal of all ones. """ - the_tensor = initialize_tensor("eye", N, backend=backend, dtype=dtype, M=M) - return the_tensor + the_tensor = initialize_tensor("eye", N, backend=backend, dtype=dtype, M=M) + return the_tensor def zeros(shape: Sequence[int], dtype: Optional[Type[np.number]] = None, backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor: - """Return a Tensor of shape `shape` of all zeros. + """Return a Tensor of shape `shape` of all zeros. The Tensor has one dangling Edge per dimension. Args: shape : Shape of the array. @@ -85,14 +85,14 @@ def zeros(shape: Sequence[int], Returns: the_tensor : Tensor of shape `shape`. Represents an array of all zeros. """ - the_tensor = initialize_tensor("zeros", shape, backend=backend, dtype=dtype) - return the_tensor + the_tensor = initialize_tensor("zeros", shape, backend=backend, dtype=dtype) + return the_tensor def ones(shape: Sequence[int], dtype: Optional[Type[np.number]] = None, backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor: - """Return a Tensor of shape `shape` of all ones. + """Return a Tensor of shape `shape` of all ones. The Tensor has one dangling Edge per dimension. Args: shape : Shape of the array. @@ -102,65 +102,70 @@ def ones(shape: Sequence[int], the_tensor : Tensor of shape `shape` Represents an array of all ones. """ - the_tensor = initialize_tensor("ones", shape, backend=backend, dtype=dtype) - return the_tensor + the_tensor = initialize_tensor("ones", shape, backend=backend, dtype=dtype) + return the_tensor -def ones_like(input: Union[Any], - dtype: Optional[Type[Any]] = None, - backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor: - """Return a Tensor shape full of ones the same shape as input +def ones_like(tensor: Union[Any], + dtype: Optional[Type[Any]] = None, + backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor: + """Return a Tensor shape full of ones the same shape as input Args: - input : Object to recieve shape from + inputTen : Object to recieve shape from dtype (optional) : dtype of object backend(optional): The backend or its name.""" - if backend is None: - backend = backend_contextmanager.get_default_backend() - else: - backend = backend_contextmanager.backend_factory.get_backend(backend) - if isinstance(input, Tensor): # incase input of type Tensor, create Tensor normally - the_tensor = initialize_tensor("ones", input.shape, backend=input.backend, dtype=input.dtype) - return the_tensor - else: - try: - input = backend.convert_to_tensor(input) - except TypeError as e: - error = "Input to zeros_like has invalid type causing error massage: \n" + str(e) - raise TypeError(error) from e - the_tensor = initialize_tensor("ones", input.get_shape().as_list(), backend=backend, dtype=dtype) - return the_tensor - - -def zeros_like(input: Union[Any], - dtype: Optional[Any] = None, - backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor: - """Return a Tensor shape full of zeros the same shape as input + if backend is None: + backend = backend_contextmanager.get_default_backend() + else: + backend = backend_contextmanager.backend_factory.get_backend(backend) + if isinstance(tensor, Tensor): + the_tensor = initialize_tensor("ones", tensor.shape, + backend=tensor.backend, dtype=tensor.dtype) + return the_tensor + else: + try: + tensor = backend.convert_to_tensor(tensor) + except TypeError as e: + error = "Input to zeros_like has invalid type causing error massage: \n" + str(e) + raise TypeError(error) from e + the_tensor = initialize_tensor("ones", tensor.get_shape().as_list(), + backend=backend, dtype=dtype) + return the_tensor + + +def zeros_like(tensor: Union[Any], + dtype: Optional[Any] = None, + backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor: + """Return a Tensor shape full of zeros the same shape as input Args: input : Object to recieve shape from dtype (optional) : dtype of object backend(optional): The backend or its name.""" - if backend is None: - backend = backend_contextmanager.get_default_backend() - else: - backend = backend_contextmanager.backend_factory.get_backend(backend) - if isinstance(input, Tensor): # incase input of type Tensor, create Tensor normally - the_tensor = initialize_tensor("zeros", input.shape, backend=input.backend, dtype=input.dtype) - return the_tensor - else: - try: - input = backend.convert_to_tensor(input) - except TypeError as e: - error = "Input to zeros_like has invalid type causing error massage: \n" + str(e) - raise TypeError(error) from e - the_tensor = initialize_tensor("zeros", input.shape, backend=backend, dtype=dtype) - return the_tensor + if backend is None: + backend = backend_contextmanager.get_default_backend() + else: + backend = backend_contextmanager.backend_factory.get_backend(backend) + if isinstance(tensor, Tensor): + the_tensor = initialize_tensor("zeros", tensor.shape, + backend=tensor.backend, dtype=tensor.dtype) + return the_tensor + else: + try: + tensor = backend.convert_to_tensor(tensor) + except TypeError as e: + error = "Input to zeros_like has invalid " \ + "type causing error massage: \n" + str(e) + raise TypeError(error) from e + the_tensor = initialize_tensor("zeros", tensor.shape, + backend=backend, dtype=dtype) + return the_tensor def randn(shape: Sequence[int], dtype: Optional[Type[np.number]] = None, seed: Optional[int] = None, backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor: - """Return a Tensor of shape `shape` of Gaussian random floats. + """Return a Tensor of shape `shape` of Gaussian random floats. The Tensor has one dangling Edge per dimension. Args: shape : Shape of the array. @@ -170,9 +175,9 @@ def randn(shape: Sequence[int], Returns: the_tensor : Tensor of shape `shape` filled with Gaussian random data. """ - the_tensor = initialize_tensor("randn", shape, backend=backend, seed=seed, - dtype=dtype) - return the_tensor + the_tensor = initialize_tensor("randn", shape, backend=backend, seed=seed, + dtype=dtype) + return the_tensor def random_uniform(shape: Sequence[int], @@ -181,7 +186,7 @@ def random_uniform(shape: Sequence[int], boundaries: Optional[Tuple[float, float]] = (0.0, 1.0), backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor: - """Return a Tensor of shape `shape` of uniform random floats. + """Return a Tensor of shape `shape` of uniform random floats. The Tensor has one dangling Edge per dimension. Args: shape : Shape of the array. @@ -192,6 +197,6 @@ def random_uniform(shape: Sequence[int], Returns: the_tensor : Tensor of shape `shape` filled with uniform random data. """ - the_tensor = initialize_tensor("random_uniform", shape, backend=backend, - seed=seed, boundaries=boundaries, dtype=dtype) - return the_tensor + the_tensor = initialize_tensor("random_uniform", shape, backend=backend, + seed=seed, boundaries=boundaries, dtype=dtype) + return the_tensor diff --git a/tensornetwork/linalg/tests/initialization_test.py b/tensornetwork/linalg/tests/initialization_test.py index d349cb248..78418b1d8 100644 --- a/tensornetwork/linalg/tests/initialization_test.py +++ b/tensornetwork/linalg/tests/initialization_test.py @@ -139,16 +139,21 @@ def test_random_uniform(backend): shape, dtype=dtype, seed=seed, boundaries=boundaries) np.testing.assert_allclose(tnI.array, npI) + @pytest.mark.parametrize("shape", (2, 4, 1)) @pytest.mark.parametrize("n", np.eye(2)) def test_ones_like(backend, shape, n): """Tests tensornetwork.ones_like against np.zeros_like""" backend_obj = backends.backend_factory.get_backend(backend) - @pytest.mark.parametrize("dtype,expected",(dtypes[backend]["all"])) + + @pytest.mark.parametrize("dtype,expected", (dtypes[backend]["all"])) def inner_ones_test(dtype): - objTensor = tensornetwork.ones(shape, dtype=dtype, backend=backend) - tensor = tensornetwork.ones_like(objTensor, dtype=dtype, backend=backend) # input as Tensor object - numpyT = tensornetwork.ones_like(n, dtype=dtype, backend=backend) # input as numpy array + objTensor = tensornetwork.ones(shape, dtype=dtype, + backend=backend) + tensor = tensornetwork.ones_like(objTensor, dtype=dtype, + backend=backend) + numpyT = tensornetwork.ones_like(n, dtype=dtype, + backend=backend) tensorCheck = backend_obj.ones(shape, dtype=dtype) numpyCheck = backend_obj.ones(n.shape, dtype=dtype) np.testing.assert_allclose(tensor.array, tensorCheck) @@ -161,11 +166,13 @@ def test_zeros_like(backend, shape, n): """Tests tensornetwork.zeros_like against np.zeros_like""" backend_obj = backends.backend_factory.get_backend(backend) - @pytest.mark.parametrize("dtype,expected",(dtypes[backend]["all"])) + @pytest.mark.parametrize("dtype,expected", (dtypes[backend]["all"])) def inner_zero_test(dtype): objTensor = tensornetwork.zeros(shape, dtype=dtype, backend=backend) - tensor = tensornetwork.zeros_like(objTensor, dtype=dtype, backend=backend) # input as Tensor object - numpyT = tensornetwork.zeros_like(n, dtype=dtype, backend=backend) # input as numpy array + tensor = tensornetwork.zeros_like(objTensor, dtype=dtype, + backend=backend) + numpyT = tensornetwork.zeros_like(n, dtype=dtype, + backend=backend) tensorCheck = backend_obj.zeros(shape, dtype=dtype) numpyCheck = backend_obj.zeros(n.shape, dtype=dtype) np.testing.assert_allclose(tensor.array, tensorCheck) From 36c16bef7603399a3502df94d87abdec1ec3a2de Mon Sep 17 00:00:00 2001 From: MikeMerzl Date: Mon, 12 Oct 2020 22:35:42 +0300 Subject: [PATCH 3/8] Ones_like & zeros_like --- tensornetwork/linalg/initialization.py | 46 ++++++++++++++------------ 1 file changed, 24 insertions(+), 22 deletions(-) diff --git a/tensornetwork/linalg/initialization.py b/tensornetwork/linalg/initialization.py index 39d345210..8cb8850db 100644 --- a/tensornetwork/linalg/initialization.py +++ b/tensornetwork/linalg/initialization.py @@ -30,20 +30,20 @@ def initialize_tensor(fname: Text, backend: Optional[Union[Text, AbstractBackend]] = None, **fkwargs: Any) -> Tensor: """Return a Tensor wrapping data obtained by an initialization function - implemented in a backend. The Tensor will have the same shape as the - underlying array that function generates, with all Edges dangling. - This function is not intended to be called directly, but doing so should - be safe enough. - Args: - fname: Name of the method of backend to call (a string). - *fargs: Positional arguments to the initialization method. - backend: The backend or its name. - **fkwargs: Keyword arguments to the initialization method. - Returns: - tensor: A Tensor wrapping data generated by - (the_backend).fname(*fargs, **fkwargs), with one dangling edge per - axis of data. - """ + implemented in a backend. The Tensor will have the same shape as the + underlying array that function generates, with all Edges dangling. + This function is not intended to be called directly, but doing so should + be safe enough. + Args: + fname: Name of the method of backend to call (a string). + *fargs: Positional arguments to the initialization method. + backend: The backend or its name. + **fkwargs: Keyword arguments to the initialization method. + Returns: + tensor: A Tensor wrapping data generated by + (the_backend).fname(*fargs, **fkwargs), with one dangling edge per + axis of data. + """ if backend is None: backend = backend_contextmanager.get_default_backend() backend_obj = backends.backend_factory.get_backend(backend) @@ -109,9 +109,11 @@ def ones(shape: Sequence[int], def ones_like(tensor: Union[Any], dtype: Optional[Type[Any]] = None, backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor: - """Return a Tensor shape full of ones the same shape as input + """ + Return a Tensor shape full of + ones the same shape as input Args: - inputTen : Object to recieve shape from + tensor : Object to recieve shape from dtype (optional) : dtype of object backend(optional): The backend or its name.""" if backend is None: @@ -121,7 +123,6 @@ def ones_like(tensor: Union[Any], if isinstance(tensor, Tensor): the_tensor = initialize_tensor("ones", tensor.shape, backend=tensor.backend, dtype=tensor.dtype) - return the_tensor else: try: tensor = backend.convert_to_tensor(tensor) @@ -130,15 +131,17 @@ def ones_like(tensor: Union[Any], raise TypeError(error) from e the_tensor = initialize_tensor("ones", tensor.get_shape().as_list(), backend=backend, dtype=dtype) - return the_tensor + return the_tensor def zeros_like(tensor: Union[Any], dtype: Optional[Any] = None, backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor: - """Return a Tensor shape full of zeros the same shape as input + """ + Return a Tensor shape full of zeros + the same shape as input Args: - input : Object to recieve shape from + tensor : Object to recieve shape from dtype (optional) : dtype of object backend(optional): The backend or its name.""" if backend is None: @@ -148,7 +151,6 @@ def zeros_like(tensor: Union[Any], if isinstance(tensor, Tensor): the_tensor = initialize_tensor("zeros", tensor.shape, backend=tensor.backend, dtype=tensor.dtype) - return the_tensor else: try: tensor = backend.convert_to_tensor(tensor) @@ -158,7 +160,7 @@ def zeros_like(tensor: Union[Any], raise TypeError(error) from e the_tensor = initialize_tensor("zeros", tensor.shape, backend=backend, dtype=dtype) - return the_tensor + return the_tensor def randn(shape: Sequence[int], From 6911105f5c8b6ad07389227836c0148d3e754278 Mon Sep 17 00:00:00 2001 From: MikeMerzl Date: Tue, 13 Oct 2020 15:03:45 +0300 Subject: [PATCH 4/8] Ones_like & zeros_like --- tensornetwork/linalg/initialization.py | 99 +++++++++++++------------- 1 file changed, 48 insertions(+), 51 deletions(-) diff --git a/tensornetwork/linalg/initialization.py b/tensornetwork/linalg/initialization.py index 8cb8850db..088598f3c 100644 --- a/tensornetwork/linalg/initialization.py +++ b/tensornetwork/linalg/initialization.py @@ -29,7 +29,7 @@ def initialize_tensor(fname: Text, *fargs: Any, backend: Optional[Union[Text, AbstractBackend]] = None, **fkwargs: Any) -> Tensor: - """Return a Tensor wrapping data obtained by an initialization function + """Return a Tensor wrapping data obtained by an initialization function implemented in a backend. The Tensor will have the same shape as the underlying array that function generates, with all Edges dangling. This function is not intended to be called directly, but doing so should @@ -44,20 +44,20 @@ def initialize_tensor(fname: Text, (the_backend).fname(*fargs, **fkwargs), with one dangling edge per axis of data. """ - if backend is None: - backend = backend_contextmanager.get_default_backend() - backend_obj = backends.backend_factory.get_backend(backend) - func = getattr(backend_obj, fname) - data = func(*fargs, **fkwargs) - tensor = Tensor(data, backend=backend) - return tensor + if backend is None: + backend = backend_contextmanager.get_default_backend() + backend_obj = backends.backend_factory.get_backend(backend) + func = getattr(backend_obj, fname) + data = func(*fargs, **fkwargs) + tensor = Tensor(data, backend=backend) + return tensor def eye(N: int, dtype: Optional[Type[np.number]] = None, M: Optional[int] = None, backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor: - """Return a Tensor representing a 2D array with ones on the diagonal and + """Return a Tensor representing a 2D array with ones on the diagonal and zeros elsewhere. The Tensor has two dangling Edges. Args: N (int): The first dimension of the returned matrix. @@ -69,14 +69,14 @@ def eye(N: int, Represents an array of all zeros except for the k'th diagonal of all ones. """ - the_tensor = initialize_tensor("eye", N, backend=backend, dtype=dtype, M=M) - return the_tensor + the_tensor = initialize_tensor("eye", N, backend=backend, dtype=dtype, M=M) + return the_tensor def zeros(shape: Sequence[int], dtype: Optional[Type[np.number]] = None, backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor: - """Return a Tensor of shape `shape` of all zeros. + """Return a Tensor of shape `shape` of all zeros. The Tensor has one dangling Edge per dimension. Args: shape : Shape of the array. @@ -85,14 +85,14 @@ def zeros(shape: Sequence[int], Returns: the_tensor : Tensor of shape `shape`. Represents an array of all zeros. """ - the_tensor = initialize_tensor("zeros", shape, backend=backend, dtype=dtype) - return the_tensor + the_tensor = initialize_tensor("zeros", shape, backend=backend, dtype=dtype) + return the_tensor def ones(shape: Sequence[int], dtype: Optional[Type[np.number]] = None, backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor: - """Return a Tensor of shape `shape` of all ones. + """Return a Tensor of shape `shape` of all ones. The Tensor has one dangling Edge per dimension. Args: shape : Shape of the array. @@ -102,65 +102,62 @@ def ones(shape: Sequence[int], the_tensor : Tensor of shape `shape` Represents an array of all ones. """ - the_tensor = initialize_tensor("ones", shape, backend=backend, dtype=dtype) - return the_tensor + the_tensor = initialize_tensor("ones", shape, backend=backend, dtype=dtype) + return the_tensor def ones_like(tensor: Union[Any], dtype: Optional[Type[Any]] = None, backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor: - """ - Return a Tensor shape full of - ones the same shape as input + """Return a Tensor shape full of ones the same shape as input Args: tensor : Object to recieve shape from dtype (optional) : dtype of object backend(optional): The backend or its name.""" - if backend is None: - backend = backend_contextmanager.get_default_backend() - else: - backend = backend_contextmanager.backend_factory.get_backend(backend) - if isinstance(tensor, Tensor): - the_tensor = initialize_tensor("ones", tensor.shape, + if backend is None: + backend = backend_contextmanager.get_default_backend() + else: + backend = backend_contextmanager.backend_factory.get_backend(backend) + if isinstance(tensor, Tensor): + the_tensor = initialize_tensor("ones", tensor.shape, backend=tensor.backend, dtype=tensor.dtype) - else: - try: - tensor = backend.convert_to_tensor(tensor) - except TypeError as e: - error = "Input to zeros_like has invalid type causing error massage: \n" + str(e) - raise TypeError(error) from e - the_tensor = initialize_tensor("ones", tensor.get_shape().as_list(), + else: + try: + tensor = backend.convert_to_tensor(tensor) + except TypeError as e: + error = "Input to zeros_like has invalid type causing error massage: \n" + \ + str(e) + raise TypeError(error) from e + the_tensor = initialize_tensor("ones", tensor.get_shape().as_list(), backend=backend, dtype=dtype) - return the_tensor + return the_tensor def zeros_like(tensor: Union[Any], dtype: Optional[Any] = None, backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor: - """ - Return a Tensor shape full of zeros - the same shape as input + """Return a Tensor shape full of zeros the same shape as input Args: tensor : Object to recieve shape from dtype (optional) : dtype of object backend(optional): The backend or its name.""" - if backend is None: - backend = backend_contextmanager.get_default_backend() - else: - backend = backend_contextmanager.backend_factory.get_backend(backend) - if isinstance(tensor, Tensor): - the_tensor = initialize_tensor("zeros", tensor.shape, + if backend is None: + backend = backend_contextmanager.get_default_backend() + else: + backend = backend_contextmanager.backend_factory.get_backend(backend) + if isinstance(tensor, Tensor): + the_tensor = initialize_tensor("zeros", tensor.shape, backend=tensor.backend, dtype=tensor.dtype) - else: - try: - tensor = backend.convert_to_tensor(tensor) - except TypeError as e: - error = "Input to zeros_like has invalid " \ + else: + try: + tensor = backend.convert_to_tensor(tensor) + except TypeError as e: + error = "Input to zeros_like has invalid " \ "type causing error massage: \n" + str(e) - raise TypeError(error) from e - the_tensor = initialize_tensor("zeros", tensor.shape, + raise TypeError(error) from e + the_tensor = initialize_tensor("zeros", tensor.shape, backend=backend, dtype=dtype) - return the_tensor + return the_tensor def randn(shape: Sequence[int], From 21b224c0c13828300566d07d41421128afdb5cb0 Mon Sep 17 00:00:00 2001 From: MikeMerzl Date: Tue, 13 Oct 2020 15:33:00 +0300 Subject: [PATCH 5/8] Ones_like & zeros_like --- tensornetwork/linalg/initialization.py | 34 +++++++++++++------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/tensornetwork/linalg/initialization.py b/tensornetwork/linalg/initialization.py index 088598f3c..1bc4af01c 100644 --- a/tensornetwork/linalg/initialization.py +++ b/tensornetwork/linalg/initialization.py @@ -120,16 +120,16 @@ def ones_like(tensor: Union[Any], backend = backend_contextmanager.backend_factory.get_backend(backend) if isinstance(tensor, Tensor): the_tensor = initialize_tensor("ones", tensor.shape, - backend=tensor.backend, dtype=tensor.dtype) + backend=tensor.backend, dtype=tensor.dtype) else: try: - tensor = backend.convert_to_tensor(tensor) + tensor = backend.convert_to_tensor(tensor) except TypeError as e: - error = "Input to zeros_like has invalid type causing error massage: \n" + \ + error = "Input to zeros_like has invalid type causing error massage: \n" + \ str(e) - raise TypeError(error) from e + raise TypeError(error) from e the_tensor = initialize_tensor("ones", tensor.get_shape().as_list(), - backend=backend, dtype=dtype) + backend=backend, dtype=dtype) return the_tensor @@ -147,16 +147,16 @@ def zeros_like(tensor: Union[Any], backend = backend_contextmanager.backend_factory.get_backend(backend) if isinstance(tensor, Tensor): the_tensor = initialize_tensor("zeros", tensor.shape, - backend=tensor.backend, dtype=tensor.dtype) + backend=tensor.backend, dtype=tensor.dtype) else: try: - tensor = backend.convert_to_tensor(tensor) + tensor = backend.convert_to_tensor(tensor) except TypeError as e: - error = "Input to zeros_like has invalid " \ + error = "Input to zeros_like has invalid " \ "type causing error massage: \n" + str(e) - raise TypeError(error) from e + raise TypeError(error) from e the_tensor = initialize_tensor("zeros", tensor.shape, - backend=backend, dtype=dtype) + backend=backend, dtype=dtype) return the_tensor @@ -164,7 +164,7 @@ def randn(shape: Sequence[int], dtype: Optional[Type[np.number]] = None, seed: Optional[int] = None, backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor: - """Return a Tensor of shape `shape` of Gaussian random floats. + """Return a Tensor of shape `shape` of Gaussian random floats. The Tensor has one dangling Edge per dimension. Args: shape : Shape of the array. @@ -174,9 +174,9 @@ def randn(shape: Sequence[int], Returns: the_tensor : Tensor of shape `shape` filled with Gaussian random data. """ - the_tensor = initialize_tensor("randn", shape, backend=backend, seed=seed, + the_tensor = initialize_tensor("randn", shape, backend=backend, seed=seed, dtype=dtype) - return the_tensor + return the_tensor def random_uniform(shape: Sequence[int], @@ -185,7 +185,7 @@ def random_uniform(shape: Sequence[int], boundaries: Optional[Tuple[float, float]] = (0.0, 1.0), backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor: - """Return a Tensor of shape `shape` of uniform random floats. + """Return a Tensor of shape `shape` of uniform random floats. The Tensor has one dangling Edge per dimension. Args: shape : Shape of the array. @@ -196,6 +196,6 @@ def random_uniform(shape: Sequence[int], Returns: the_tensor : Tensor of shape `shape` filled with uniform random data. """ - the_tensor = initialize_tensor("random_uniform", shape, backend=backend, - seed=seed, boundaries=boundaries, dtype=dtype) - return the_tensor + the_tensor = initialize_tensor("random_uniform", shape, backend=backend, + seed=seed, boundaries=boundaries, dtype=dtype) + return the_tensor From 91d609c11fe64c3c45b6f64ac2052d86b99c74fd Mon Sep 17 00:00:00 2001 From: MikeMerzl Date: Tue, 13 Oct 2020 15:49:42 +0300 Subject: [PATCH 6/8] Ones_like & zeros_like --- tensornetwork/linalg/initialization.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/tensornetwork/linalg/initialization.py b/tensornetwork/linalg/initialization.py index 1bc4af01c..310df51f9 100644 --- a/tensornetwork/linalg/initialization.py +++ b/tensornetwork/linalg/initialization.py @@ -120,16 +120,16 @@ def ones_like(tensor: Union[Any], backend = backend_contextmanager.backend_factory.get_backend(backend) if isinstance(tensor, Tensor): the_tensor = initialize_tensor("ones", tensor.shape, - backend=tensor.backend, dtype=tensor.dtype) + backend=tensor.backend, dtype=tensor.dtype) else: try: tensor = backend.convert_to_tensor(tensor) except TypeError as e: - error = "Input to zeros_like has invalid type causing error massage: \n" + \ - str(e) + error = "Input to zeros_like has invalid type causing " \ + "error massage: \n" + str(e) raise TypeError(error) from e the_tensor = initialize_tensor("ones", tensor.get_shape().as_list(), - backend=backend, dtype=dtype) + backend=backend, dtype=dtype) return the_tensor @@ -147,7 +147,7 @@ def zeros_like(tensor: Union[Any], backend = backend_contextmanager.backend_factory.get_backend(backend) if isinstance(tensor, Tensor): the_tensor = initialize_tensor("zeros", tensor.shape, - backend=tensor.backend, dtype=tensor.dtype) + backend=tensor.backend, dtype=tensor.dtype) else: try: tensor = backend.convert_to_tensor(tensor) @@ -156,7 +156,7 @@ def zeros_like(tensor: Union[Any], "type causing error massage: \n" + str(e) raise TypeError(error) from e the_tensor = initialize_tensor("zeros", tensor.shape, - backend=backend, dtype=dtype) + backend=backend, dtype=dtype) return the_tensor @@ -175,7 +175,7 @@ def randn(shape: Sequence[int], the_tensor : Tensor of shape `shape` filled with Gaussian random data. """ the_tensor = initialize_tensor("randn", shape, backend=backend, seed=seed, - dtype=dtype) + dtype=dtype) return the_tensor @@ -197,5 +197,5 @@ def random_uniform(shape: Sequence[int], the_tensor : Tensor of shape `shape` filled with uniform random data. """ the_tensor = initialize_tensor("random_uniform", shape, backend=backend, - seed=seed, boundaries=boundaries, dtype=dtype) + seed=seed, boundaries=boundaries, dtype=dtype) return the_tensor From 4437a47ccf79cb4caed9e6d12800046eeeacc8c4 Mon Sep 17 00:00:00 2001 From: MikeMerzl Date: Tue, 13 Oct 2020 16:12:27 +0300 Subject: [PATCH 7/8] Ones_like & zeros_like --- tensornetwork/linalg/initialization.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tensornetwork/linalg/initialization.py b/tensornetwork/linalg/initialization.py index 310df51f9..a0e43402b 100644 --- a/tensornetwork/linalg/initialization.py +++ b/tensornetwork/linalg/initialization.py @@ -135,7 +135,8 @@ def ones_like(tensor: Union[Any], def zeros_like(tensor: Union[Any], dtype: Optional[Any] = None, - backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor: + backend: Optional[Union[Text, + AbstractBackend]] = None) -> Tensor: """Return a Tensor shape full of zeros the same shape as input Args: tensor : Object to recieve shape from From ca3a75dd3bc954290f2e63b97508a4850b65ea99 Mon Sep 17 00:00:00 2001 From: MikeMerzl Date: Tue, 13 Oct 2020 18:31:11 +0300 Subject: [PATCH 8/8] Support of imag and real at backend --- tensornetwork/backends/abstract_backend.py | 23 ++++++++++++- tensornetwork/backends/jax/jax_backend.py | 22 +++++++++++++ .../backends/jax/jax_backend_test.py | 24 ++++++++++++++ tensornetwork/backends/numpy/numpy_backend.py | 22 +++++++++++++ .../backends/numpy/numpy_backend_test.py | 20 ++++++++++++ .../backends/pytorch/pytorch_backend.py | 32 +++++++++++++++++++ .../backends/pytorch/pytorch_backend_test.py | 26 +++++++++++++++ .../backends/symmetric/symmetric_backend.py | 9 ++++++ .../symmetric/symmetric_backend_test.py | 22 +++++++++++++ .../backends/tensorflow/tensorflow_backend.py | 22 +++++++++++++ .../tensorflow/tensorflow_backend_test.py | 19 +++++++++++ 11 files changed, 240 insertions(+), 1 deletion(-) diff --git a/tensornetwork/backends/abstract_backend.py b/tensornetwork/backends/abstract_backend.py index 3d471e0fb..f78ea608d 100644 --- a/tensornetwork/backends/abstract_backend.py +++ b/tensornetwork/backends/abstract_backend.py @@ -1010,4 +1010,25 @@ def power(self, a: Tensor, b: Union[Tensor, float]) -> Tensor: """ raise NotImplementedError( f"Backend {self.name} has not implemented power.") - \ No newline at end of file + + def real(self, tensor: Tensor) -> Tensor: + """Return Re(tensor) + Args: + tensor: Input Tensor + + Returns: Re(tensor), real part of tensor + + """ + raise NotImplementedError( + f"Backend {self.name} has not implemented .real") + + def imag(self, tensor: Tensor) -> Tensor: + """Return Im(tensor) + Args: + tensor: Input tensor. + + Returns: Im(tensor), imaginary part of tensor. + + """ + raise NotImplementedError( + f"Backend {self.name} has not implemented .imag") \ No newline at end of file diff --git a/tensornetwork/backends/jax/jax_backend.py b/tensornetwork/backends/jax/jax_backend.py index 69f017fe8..8d15bc991 100644 --- a/tensornetwork/backends/jax/jax_backend.py +++ b/tensornetwork/backends/jax/jax_backend.py @@ -871,3 +871,25 @@ def sign(self, tensor: Tensor) -> Tensor: tensor: The input tensor. """ return jnp.sign(tensor) + + def real(self, tensor: Tensor) -> Tensor: + """ + + Args: + tensor: Input Tensor + + Returns: Re(tensor),Real part of tensor + + """ + return jnp.real(tensor) + + def imag(self, tensor: Tensor) -> Tensor: + """ + + Args: + tensor: Input Tensor + + Returns: Im(tensor), Imaginary part of tensor + + """ + return jnp.imag(tensor) diff --git a/tensornetwork/backends/jax/jax_backend_test.py b/tensornetwork/backends/jax/jax_backend_test.py index d01fed43f..cd45bcef0 100644 --- a/tensornetwork/backends/jax/jax_backend_test.py +++ b/tensornetwork/backends/jax/jax_backend_test.py @@ -1096,3 +1096,27 @@ def test_inv(dtype, atol): tensor = backend.randn((10, 10, 10), dtype=dtype, seed=10) with pytest.raises(ValueError, match="input to"): backend.inv(tensor) + + +@pytest.mark.parametrize("dtype", np_dtypes) +@pytest.mark.parametrize("input_cur", [np.array([1, 2]), + np.array([5+6j, 4+10j]), + np.array([5j, 7j])]) +def test_real(dtype,input_cur): + backend = jax_backend.JaxBackend() + cur = backend.convert_to_tensor(input_cur) + acual = backend.real(cur) + expcted = jax.numpy.real(cur) + np.testing.assert_allclose(acual, expcted) + + +@pytest.mark.parametrize("dtype", np_dtypes) +@pytest.mark.parametrize("input_cur", [np.array([1, 2]), + np.array([5+6j, 4+10j]), + np.array([5j, 7j])]) +def test_imag(dtype, input_cur): + backend = jax_backend.JaxBackend() + cur = backend.convert_to_tensor(input_cur) + acual = backend.imag(cur) + expcted = jax.numpy.imag(cur) + np.testing.assert_allclose(acual, expcted) diff --git a/tensornetwork/backends/numpy/numpy_backend.py b/tensornetwork/backends/numpy/numpy_backend.py index b7b8049f9..72f814b6a 100644 --- a/tensornetwork/backends/numpy/numpy_backend.py +++ b/tensornetwork/backends/numpy/numpy_backend.py @@ -759,3 +759,25 @@ def deserialize_tensor(self, s: str) -> Tensor: m.write(s.encode('latin-1')) m.seek(0) return np.load(m) + + def real(self, tensor: Tensor) -> Tensor: + """ + Retuns Re(tensor), returns real element in tensor given + Args: + tensor: Input Tensor + + Returns: + returns real element in tensor given + """ + return np.real(tensor) + + def imag(self, tensor: Tensor) -> Tensor: + """ + Returns Im(tensor), returns the Imaginary part of tensor + Args: + tensor: Input Tensor + + Returns: + returns the Imaginary part of tensor + """ + return np.imag(tensor) diff --git a/tensornetwork/backends/numpy/numpy_backend_test.py b/tensornetwork/backends/numpy/numpy_backend_test.py index 59782e5d8..9c66b1845 100644 --- a/tensornetwork/backends/numpy/numpy_backend_test.py +++ b/tensornetwork/backends/numpy/numpy_backend_test.py @@ -949,3 +949,23 @@ def test_serialize(dtype): s = backend.serialize_tensor(tensor) assert isinstance(s, str) assert (tensor == backend.deserialize_tensor(s)).all() + + +@pytest.mark.parametrize('dtype', np_dtypes) +@pytest.mark.parametrize("input_cur", [(np.array([1, 2, 3, 4])), (np.array([1j, 2j, 3j, 4j])), + (np.array([10+2j, 20+2j, 30+5j, 40+20j]))]) +def test_real(dtype, input_cur): + backend = numpy_backend.NumPyBackend() + cur = backend.convert_to_tensor(input_cur) + np.testing.assert_allclose(cur.real, np.real(input_cur)) + + +@pytest.mark.parametrize('dtype', np_dtypes) +@pytest.mark.parametrize("input_cur", [(np.array([1, 2, 3, 4])), (np.array([1j, 2j, 3j, 4j])), + (np.array([10+2j, 20+2j, 30+5j, 40+20j]))]) +def test_imag(dtype, input_cur): + backend = numpy_backend.NumPyBackend() + cur = backend.convert_to_tensor(input_cur) + acual = cur.imag + expected = np.imag(input_cur) + np.testing.assert_allclose(acual, expected) diff --git a/tensornetwork/backends/pytorch/pytorch_backend.py b/tensornetwork/backends/pytorch/pytorch_backend.py index 787202412..28e1abbb1 100644 --- a/tensornetwork/backends/pytorch/pytorch_backend.py +++ b/tensornetwork/backends/pytorch/pytorch_backend.py @@ -472,3 +472,35 @@ def sign(self, tensor: Tensor) -> Tensor: tensor: The input tensor. """ return torchlib.sign(tensor) + + def real(self, tensor: Tensor) -> Tensor: + """Return real part of tensor + Args: + tensor: Input Tensor + + Returns: Re(tensor),Real part of tensor + + """ + if torchlib.is_complex(tensor): + return torchlib.real(tensor) + else: + temp = torchlib.zeros_like(tensor, dtype=torchlib.cfloat) + tensor = torchlib.as_tensor(tensor, dtype=torchlib.cfloat) + torchlib.add(tensor, temp, out=tensor) + return torchlib.real(tensor) + + def imag(self,tensor: Tensor) -> Tensor: + """Return imag part of tensor + Args: + tensor: Input tensor + + Returns: Im(tensor),returns Imaginary part of tensor + + """ + if torchlib.is_complex(tensor): + return torchlib.imag(tensor) + else: + temp = torchlib.zeros_like(tensor, dtype=torchlib.cfloat) + tensor = torchlib.as_tensor(tensor, dtype=torchlib.cfloat) + torchlib.add(tensor, temp, out=tensor) + return torchlib.imag(tensor) diff --git a/tensornetwork/backends/pytorch/pytorch_backend_test.py b/tensornetwork/backends/pytorch/pytorch_backend_test.py index ffe92e44b..02d9cde8c 100644 --- a/tensornetwork/backends/pytorch/pytorch_backend_test.py +++ b/tensornetwork/backends/pytorch/pytorch_backend_test.py @@ -664,3 +664,29 @@ def test_matmul_rank2(): actual = backend.matmul(a, b) expected = np.matmul(t1, t2) np.testing.assert_allclose(expected, actual) + + +@pytest.mark.parametrize("dtype", torch_randn_dtypes) +@pytest.mark.parametrize("input_cur", [(np.array([1+6j, 2+7j])), (np.array([1j, 2j])), + (np.array([5+3j, 4+7j]))]) +def test_real(dtype, input_cur): + backend = pytorch_backend.PyTorchBackend() + cur = backend.convert_to_tensor(input_cur) + acual = backend.real(cur) + expected = torch.real(cur) + np.testing.assert_allclose(acual, expected) + cur = backend.convert_to_tensor(np.array([1, 2])) + np.testing.assert_allclose(backend.real(cur), np.array([1, 2])) + + +@pytest.mark.parametrize("dtype", torch_randn_dtypes) +@pytest.mark.parametrize("input_cur", [(np.array([1+6j, 2+7j])), (np.array([1j, 2j])), + (np.array([5+3j, 4+7j]))]) +def test_imag(dtype, input_cur): + backend = pytorch_backend.PyTorchBackend() + cur = backend.convert_to_tensor(input_cur) + acual = backend.imag(cur) + expected = torch.imag(cur) + np.testing.assert_allclose(acual, expected) + cur = backend.convert_to_tensor(np.array([1, 2])) + np.testing.assert_allclose(backend.imag(cur), np.array([0, 0])) diff --git a/tensornetwork/backends/symmetric/symmetric_backend.py b/tensornetwork/backends/symmetric/symmetric_backend.py index 643129a98..86b003599 100644 --- a/tensornetwork/backends/symmetric/symmetric_backend.py +++ b/tensornetwork/backends/symmetric/symmetric_backend.py @@ -680,3 +680,12 @@ def sign(self, tensor: Tensor) -> Tensor: def pivot(self, tensor: Tensor, pivot_axis: int = -1) -> Tensor: raise NotImplementedError("Symmetric backend doesn't support pivot.") + + def real(self, tensor: Tensor) -> Tensor: + temp = tensor.data[abs(tensor.data.imag) > 0] + return temp.real + + + def imag(self, tensor:Tensor) -> Tensor: + temp = tensor.data[abs(tensor.data.imag) < 0] + return temp.imag diff --git a/tensornetwork/backends/symmetric/symmetric_backend_test.py b/tensornetwork/backends/symmetric/symmetric_backend_test.py index 61800eabb..c586f0edd 100644 --- a/tensornetwork/backends/symmetric/symmetric_backend_test.py +++ b/tensornetwork/backends/symmetric/symmetric_backend_test.py @@ -1644,3 +1644,25 @@ def test_gmres_raises(): backend.gmres(lambda x: x, b, x0=mps, tol=-0.001) with pytest.raises(ValueError, match="atol = "): backend.gmres(lambda x: x, b, x0=mps, atol=-0.001) + + +@pytest.mark.parametrize("dtype", np_dtypes) +@pytest.mark.parametrize("R", [2, 3, 4, 5]) +@pytest.mark.parametrize("num_charges", [1, 2]) +def test_real(dtype, R, num_charges): + backend = symmetric_backend.SymmetricBackend() + a = get_tensor(R, num_charges, dtype) + a = backend.real(a) + temp = np.isreal(a) + assert(temp.all()) + + +@pytest.mark.parametrize("dtype", np_dtypes) +@pytest.mark.parametrize("R", [2, 3, 4, 5]) +@pytest.mark.parametrize("num_charges", [1, 2]) +def test_imag(dtype, R, num_charges): + backend = symmetric_backend.SymmetricBackend() + a = get_tensor(R, num_charges, dtype) + a = backend.imag(a) + temp = np.iscomplex(a) + assert(temp.all()) diff --git a/tensornetwork/backends/tensorflow/tensorflow_backend.py b/tensornetwork/backends/tensorflow/tensorflow_backend.py index 3d089c2fe..d1b45e28d 100644 --- a/tensornetwork/backends/tensorflow/tensorflow_backend.py +++ b/tensornetwork/backends/tensorflow/tensorflow_backend.py @@ -383,3 +383,25 @@ def sign(self, tensor: Tensor) -> Tensor: tensor: The input tensor. """ return tf.math.sign(tensor) + + def real(self, tensor: Tensor) -> Tensor: + """ + + Args: + tensor: Input Tensor + + Returns: Real part of tensor, Re(tensor) + + """ + return tf.math.real(tensor) + + def imag(self, tensor: Tensor) -> Tensor: + """ + + Args: + tensor: Input Tensor + + Returns: Imaginary part of tensor, Im(tensor) + + """ + return tf.math.imag(tensor) \ No newline at end of file diff --git a/tensornetwork/backends/tensorflow/tensorflow_backend_test.py b/tensornetwork/backends/tensorflow/tensorflow_backend_test.py index b63d538fa..8939e82da 100644 --- a/tensornetwork/backends/tensorflow/tensorflow_backend_test.py +++ b/tensornetwork/backends/tensorflow/tensorflow_backend_test.py @@ -599,3 +599,22 @@ def test_pivot(dtype, pivot_axis): expected = tf.reshape(tensor, pivot_shape) actual = backend.pivot(tensor, pivot_axis=pivot_axis) np.testing.assert_allclose(expected, actual) + + +@pytest.mark.parametrize("dtype", tf_dtypes) +@pytest.mark.parametrize("input_cur", [(np.array([1, 2, 3, 4])), (np.array([1j, 2j, 3j, 4j])), + (np.array([10+2j, 20+2j, 30+5j, 40+20j]))]) +def test_real(dtype, input_cur): + backend = tensorflow_backend.TensorFlowBackend() + cur = backend.convert_to_tensor(input_cur) + expected = tf.math.real(input_cur) + np.testing.assert_allclose(backend.real(cur), expected) + +@pytest.mark.parametrize("dtype", tf_dtypes) +@pytest.mark.parametrize("input_cur", [(np.array([1, 2, 3, 4])), (np.array([1j, 2j, 3j, 4j])), + (np.array([10+2j, 20+2j, 30+5j, 40+20j]))]) +def test_imag(dtype, input_cur): + backend = tensorflow_backend.TensorFlowBackend() + cur = backend.convert_to_tensor(input_cur) + expected = tf.math.imag(input_cur) + np.testing.assert_allclose(backend.imag(cur), expected) \ No newline at end of file