import pytest
import numpy as np
try:
import numrs2 as nr
NUMRS2_AVAILABLE = True
except ImportError:
NUMRS2_AVAILABLE = False
nr = None
pytestmark = pytest.mark.skipif(not NUMRS2_AVAILABLE, reason="numrs2 not built with Python bindings")
def test_import():
assert nr is not None
assert hasattr(nr, "__version__")
def test_array_creation_from_list():
arr = nr.array([1.0, 2.0, 3.0, 4.0])
assert arr.size == 4
assert arr.ndim == 1
assert arr.shape == [4]
def test_array_creation_from_numpy():
np_arr = np.array([1.0, 2.0, 3.0, 4.0])
nr_arr = nr.array(np_arr)
assert nr_arr.size == 4
assert list(nr_arr.tolist()) == [1.0, 2.0, 3.0, 4.0]
def test_zeros():
arr = nr.zeros([2, 3])
assert arr.shape == [2, 3]
assert arr.size == 6
assert all(x == 0.0 for x in arr.tolist())
def test_ones():
arr = nr.ones([2, 3])
assert arr.shape == [2, 3]
assert arr.size == 6
assert all(x == 1.0 for x in arr.tolist())
def test_eye():
arr = nr.eye(3)
assert arr.shape == [3, 3]
assert arr.size == 9
data = arr.tolist()
for i in range(3):
for j in range(3):
expected = 1.0 if i == j else 0.0
assert data[i * 3 + j] == expected
def test_linspace():
arr = nr.linspace(0.0, 1.0, 11)
assert arr.size == 11
assert arr.tolist()[0] == 0.0
assert arr.tolist()[-1] == 1.0
def test_arange():
arr = nr.arange(0.0, 10.0, 2.0)
assert list(arr.tolist()) == [0.0, 2.0, 4.0, 6.0, 8.0]
def test_reshape():
arr = nr.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
reshaped = arr.reshape([2, 3])
assert reshaped.shape == [2, 3]
assert reshaped.size == 6
def test_transpose():
arr = nr.zeros([2, 3])
transposed = arr.transpose()
assert transposed.shape == [3, 2]
def test_addition():
a = nr.array([1.0, 2.0, 3.0])
b = nr.array([4.0, 5.0, 6.0])
c = a + b
assert list(c.tolist()) == [5.0, 7.0, 9.0]
def test_subtraction():
a = nr.array([4.0, 5.0, 6.0])
b = nr.array([1.0, 2.0, 3.0])
c = a - b
assert list(c.tolist()) == [3.0, 3.0, 3.0]
def test_multiplication():
a = nr.array([2.0, 3.0, 4.0])
b = nr.array([5.0, 6.0, 7.0])
c = a * b
assert list(c.tolist()) == [10.0, 18.0, 28.0]
def test_division():
a = nr.array([10.0, 20.0, 30.0])
b = nr.array([2.0, 4.0, 5.0])
c = a / b
assert list(c.tolist()) == [5.0, 5.0, 6.0]
def test_negation():
a = nr.array([1.0, -2.0, 3.0])
b = -a
assert list(b.tolist()) == [-1.0, 2.0, -3.0]
def test_dot_product():
a = nr.array([1.0, 2.0, 3.0])
b = nr.array([4.0, 5.0, 6.0])
result = nr.dot(a, b)
assert result == 32.0
def test_to_numpy():
nr_arr = nr.array([1.0, 2.0, 3.0, 4.0])
np_arr = nr_arr.to_numpy(None)
assert isinstance(np_arr, np.ndarray)
assert list(np_arr) == [1.0, 2.0, 3.0, 4.0]
def test_numpy_roundtrip():
original = np.array([1.0, 2.0, 3.0, 4.0])
nr_arr = nr.array(original)
back_to_numpy = np.array(nr_arr.tolist())
assert np.allclose(original, back_to_numpy)
def test_repr():
arr = nr.array([1.0, 2.0, 3.0])
repr_str = repr(arr)
assert "Array" in repr_str
assert "shape" in repr_str
if __name__ == "__main__":
pytest.main([__file__, "-v"])