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

Commit 0805faf

Browse files
authored
Add power method and test to numpy backend. (#849)
1 parent 8451862 commit 0805faf

2 files changed

Lines changed: 35 additions & 0 deletions

File tree

tensornetwork/backends/numpy/numpy_backend.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -759,3 +759,24 @@ def deserialize_tensor(self, s: str) -> Tensor:
759759
m.write(s.encode('latin-1'))
760760
m.seek(0)
761761
return np.load(m)
762+
763+
def power(self, a: Tensor, b: Union[Tensor, float]) -> Tensor:
764+
"""
765+
Returns the exponentiation of tensor a raised to b.
766+
If b is a tensor, then the exponentiation is element-wise
767+
between the two tensors, with a as the base and b as the power.
768+
Note that a and b must be broadcastable to the same shape if
769+
b is a tensor.
770+
If b is a scalar, then the exponentiation is each value in a
771+
raised to the power of b.
772+
773+
Args:
774+
a: The tensor containing the bases.
775+
b: The tensor containing the powers; or a single scalar as the power.
776+
777+
Returns:
778+
The tensor that is each element of a raised to the
779+
power of b. Note that the shape of the returned tensor
780+
is that produced by the broadcast of a and b.
781+
"""
782+
return np.power(a, b)

tensornetwork/backends/numpy/numpy_backend_test.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -949,3 +949,17 @@ def test_serialize(dtype):
949949
s = backend.serialize_tensor(tensor)
950950
assert isinstance(s, str)
951951
assert (tensor == backend.deserialize_tensor(s)).all()
952+
953+
@pytest.mark.parametrize('dtype', np_dtypes)
954+
def test_power(dtype):
955+
shape = (4, 3, 2)
956+
backend = numpy_backend.NumPyBackend()
957+
base_tensor = np.abs(backend.randn(shape, dtype=dtype, seed=10))
958+
power_tensor = backend.randn(shape, dtype=dtype, seed=10)
959+
actual = backend.power(base_tensor, power_tensor)
960+
expected = np.power(base_tensor, power_tensor)
961+
np.testing.assert_allclose(expected, actual)
962+
power = np.random.rand(1)[0]
963+
actual = backend.power(base_tensor, power)
964+
expected = np.power(base_tensor, power)
965+
np.testing.assert_allclose(expected, actual)

0 commit comments

Comments
 (0)