| 1026 | |
| 1027 | @pytest.mark.filterwarnings("ignore::FutureWarning") |
| 1028 | def test_isel_fancy(self) -> None: |
| 1029 | shape = (10, 7, 6) |
| 1030 | np_array = np.random.random(shape) |
| 1031 | da = DataArray( |
| 1032 | np_array, dims=["time", "y", "x"], coords={"time": np.arange(0, 100, 10)} |
| 1033 | ) |
| 1034 | y = [1, 3] |
| 1035 | x = [3, 0] |
| 1036 | |
| 1037 | expected = da.values[:, y, x] |
| 1038 | |
| 1039 | actual = da.isel(y=(("test_coord",), y), x=(("test_coord",), x)) |
| 1040 | assert actual.coords["test_coord"].shape == (len(y),) |
| 1041 | assert list(actual.coords) == ["time"] |
| 1042 | assert actual.dims == ("time", "test_coord") |
| 1043 | |
| 1044 | np.testing.assert_equal(actual, expected) |
| 1045 | |
| 1046 | # a few corner cases |
| 1047 | da.isel( |
| 1048 | time=(("points",), [1, 2]), x=(("points",), [2, 2]), y=(("points",), [3, 4]) |
| 1049 | ) |
| 1050 | np.testing.assert_allclose( |
| 1051 | da.isel( |
| 1052 | time=(("p",), [1]), x=(("p",), [2]), y=(("p",), [4]) |
| 1053 | ).values.squeeze(), |
| 1054 | np_array[1, 4, 2].squeeze(), |
| 1055 | ) |
| 1056 | da.isel(time=(("points",), [1, 2])) |
| 1057 | y = [-1, 0] |
| 1058 | x = [-2, 2] |
| 1059 | expected2 = da.values[:, y, x] |
| 1060 | actual2 = da.isel(x=(("points",), x), y=(("points",), y)).values |
| 1061 | np.testing.assert_equal(actual2, expected2) |
| 1062 | |
| 1063 | # test that the order of the indexers doesn't matter |
| 1064 | assert_identical( |
| 1065 | da.isel(y=(("points",), y), x=(("points",), x)), |
| 1066 | da.isel(x=(("points",), x), y=(("points",), y)), |
| 1067 | ) |
| 1068 | |
| 1069 | # make sure we're raising errors in the right places |
| 1070 | with pytest.raises(IndexError, match=r"Dimensions of indexers mismatch"): |
| 1071 | da.isel(y=(("points",), [1, 2]), x=(("points",), [1, 2, 3])) |
| 1072 | |
| 1073 | # tests using index or DataArray as indexers |
| 1074 | stations = Dataset() |
| 1075 | stations["station"] = (("station",), ["A", "B", "C"]) |
| 1076 | stations["dim1s"] = (("station",), [1, 2, 3]) |
| 1077 | stations["dim2s"] = (("station",), [4, 5, 1]) |
| 1078 | |
| 1079 | actual3 = da.isel(x=stations["dim1s"], y=stations["dim2s"]) |
| 1080 | assert "station" in actual3.coords |
| 1081 | assert "station" in actual3.dims |
| 1082 | assert_identical(actual3["station"], stations["station"]) |
| 1083 | |
| 1084 | with pytest.raises(ValueError, match=r"conflicting values/indexes on "): |
| 1085 | da.isel( |