Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions pysnptools/util/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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.
Expand Down
9 changes: 9 additions & 0 deletions pysnptools/util/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down
Loading