diff --git a/pysnptools/util/__init__.py b/pysnptools/util/__init__.py index b1ba892..fc19a0d 100644 --- a/pysnptools/util/__init__.py +++ b/pysnptools/util/__init__.py @@ -342,8 +342,8 @@ def create_sub_val(dtype): logging.debug("About to call Rust matrixSubset") num_threads = get_num_threads(num_threads) if val.flags["F_CONTIGUOUS"] or val.flags["C_CONTIGUOUS"]: - row_index_list = np.asarray(row_index_list, dtype=np.uintp) - col_index_list = np.asarray(col_index_list, dtype=np.uintp) + row_index_list = _checked_index(row_index_list, iid_count, "row").astype(np.uintp) + col_index_list = _checked_index(col_index_list, sid_count, "column").astype(np.uintp) if val.dtype == np.float64: sub_val = create_sub_val(np.float64) subset_f64_f64( @@ -395,6 +395,20 @@ def create_sub_val(dtype): return sub_val +def _checked_index(index_list, count, name): + # The Rust helper panics on an out-of-range index (and a negative index in an ndarray + # wraps to a huge uintp), so check indexes first and raise a clear IndexError. + index = np.asarray(index_list, dtype=np.intp) + bad = (index < 0) | (index >= count) + if bad.any(): + raise IndexError( + "{0} index {1} is out of range for {2} {0}s".format( + name, index[bad][0], count + ) + ) + return index + + def create_directory_if_necessary(name, isfile=True, robust=False): """ Create a directory for a file if the directory doesn't already exist. diff --git a/pysnptools/util/test.py b/pysnptools/util/test.py index 0a3e630..15c456b 100644 --- a/pysnptools/util/test.py +++ b/pysnptools/util/test.py @@ -120,6 +120,15 @@ def test_sub_matrix(self): submatrix = pstutil.sub_matrix(matrix,[0,2,11],[6,5,4,3,2,1,0]) assert matrix[2,0,1] == submatrix[1,6,1] #The row # 2 is now #1, the column #0 is now #6. + def test_sub_matrix_bad_index(self): + # Out-of-range and negative indexes used to make the Rust helper panic. + import pysnptools.util as pstutil + for shape in [(12, 7), (12, 7, 3)]: + matrix = np.random.default_rng(0).random(shape) + for bad_rows, bad_cols in [([12], [0]), ([-1], [0]), (np.array([-1]), [0]), ([0], [7]), ([0], np.array([-7]))]: + with self.assertRaises(IndexError): + pstutil.sub_matrix(matrix, bad_rows, bad_cols) + def getTestSuite():