Skip to content
This repository has been archived by the owner on Nov 7, 2024. It is now read-only.

Commit

Permalink
Add power method and test to numpy backend. (#849)
Browse files Browse the repository at this point in the history
  • Loading branch information
wkostuch authored Oct 12, 2020
1 parent 8451862 commit 0805faf
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
21 changes: 21 additions & 0 deletions tensornetwork/backends/numpy/numpy_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -759,3 +759,24 @@ def deserialize_tensor(self, s: str) -> Tensor:
m.write(s.encode('latin-1'))
m.seek(0)
return np.load(m)

def power(self, a: Tensor, b: Union[Tensor, float]) -> Tensor:
"""
Returns the exponentiation of tensor a raised to b.
If b is a tensor, then the exponentiation is element-wise
between the two tensors, with a as the base and b as the power.
Note that a and b must be broadcastable to the same shape if
b is a tensor.
If b is a scalar, then the exponentiation is each value in a
raised to the power of b.
Args:
a: The tensor containing the bases.
b: The tensor containing the powers; or a single scalar as the power.
Returns:
The tensor that is each element of a raised to the
power of b. Note that the shape of the returned tensor
is that produced by the broadcast of a and b.
"""
return np.power(a, b)
14 changes: 14 additions & 0 deletions tensornetwork/backends/numpy/numpy_backend_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -949,3 +949,17 @@ 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)
def test_power(dtype):
shape = (4, 3, 2)
backend = numpy_backend.NumPyBackend()
base_tensor = np.abs(backend.randn(shape, dtype=dtype, seed=10))
power_tensor = backend.randn(shape, dtype=dtype, seed=10)
actual = backend.power(base_tensor, power_tensor)
expected = np.power(base_tensor, power_tensor)
np.testing.assert_allclose(expected, actual)
power = np.random.rand(1)[0]
actual = backend.power(base_tensor, power)
expected = np.power(base_tensor, power)
np.testing.assert_allclose(expected, actual)

0 comments on commit 0805faf

Please sign in to comment.