test_arrayobject.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import pytest
  2. import numpy as np
  3. from numpy.ma import masked_array
  4. from numpy.testing import assert_array_equal
  5. def test_matrix_transpose_raises_error_for_1d():
  6. msg = "matrix transpose with ndim < 2 is undefined"
  7. ma_arr = masked_array(data=[1, 2, 3, 4, 5, 6],
  8. mask=[1, 0, 1, 1, 1, 0])
  9. with pytest.raises(ValueError, match=msg):
  10. ma_arr.mT
  11. def test_matrix_transpose_equals_transpose_2d():
  12. ma_arr = masked_array(data=[[1, 2, 3], [4, 5, 6]],
  13. mask=[[1, 0, 1], [1, 1, 0]])
  14. assert_array_equal(ma_arr.T, ma_arr.mT)
  15. ARRAY_SHAPES_TO_TEST = (
  16. (5, 2),
  17. (5, 2, 3),
  18. (5, 2, 3, 4),
  19. )
  20. @pytest.mark.parametrize("shape", ARRAY_SHAPES_TO_TEST)
  21. def test_matrix_transpose_equals_swapaxes(shape):
  22. num_of_axes = len(shape)
  23. vec = np.arange(shape[-1])
  24. arr = np.broadcast_to(vec, shape)
  25. rng = np.random.default_rng(42)
  26. mask = rng.choice([0, 1], size=shape)
  27. ma_arr = masked_array(data=arr, mask=mask)
  28. tgt = np.swapaxes(arr, num_of_axes - 2, num_of_axes - 1)
  29. assert_array_equal(tgt, ma_arr.mT)