Skip to content

Commit

Permalink
Modified subset to be a generic named subset_by_sequence.
Browse files Browse the repository at this point in the history
This gives us some more flexibility for registering downstream classes.
  • Loading branch information
LTLA committed Nov 8, 2023
1 parent 2d484e0 commit 37d579f
Show file tree
Hide file tree
Showing 5 changed files with 52 additions and 61 deletions.
3 changes: 3 additions & 0 deletions src/biocutils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,8 @@

from .extract_row_names import extract_row_names
from .extract_column_names import extract_column_names

from .subset_sequence import subset_sequence

from .show_as_cell import show_as_cell
from .convert_to_dense import convert_to_dense
40 changes: 0 additions & 40 deletions src/biocutils/subset.py

This file was deleted.

28 changes: 28 additions & 0 deletions src/biocutils/subset_sequence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from typing import Any, Sequence, Union
from functools import singledispatch
import numpy


@singledispatch
def subset_sequence(x: Any, indices: Sequence) -> Any:
"""
Subset ``x`` by ``indices`` to obtain a new object with the desired
subset of elements. This attempts to use ``x``'s ``__getitem__`` method.
Args:
x:
Any object that supports ``__getitem__`` with an integer sequence.
indices:
Sequence of non-negative integers specifying the integers of interest.
Returns:
The result of slicing ``x`` by ``indices``. The exact type
depends on what ``x``'s ``__getitem__`` method returns.
"""
return x[indices]


@subset_sequence.register
def _subset_sequence_list(x: list, indices: Sequence) -> list:
return [x[i] for i in indices]
21 changes: 0 additions & 21 deletions tests/test_subset.py

This file was deleted.

21 changes: 21 additions & 0 deletions tests/test_subset_sequence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from biocutils import subset_sequence
import numpy as np


def test_subset_list():
x = [1, 2, 3, 4, 5]
assert subset_sequence(x, [0, 2, 4]) == [1, 3, 5]

x = [1, 2, 3, 4, 5]
assert subset_sequence(x, range(5)) == x

x = [1, 2, 3, 4, 5]
assert subset_sequence(x, range(4, -1, -1)) == [5, 4, 3, 2, 1]


def test_subset_numpy():
y = np.random.rand(10)
assert (subset_sequence(y, range(5)) == y[0:5]).all()

y = np.random.rand(10, 20)
assert (subset_sequence(y, range(5)) == y[0:5, :]).all()

0 comments on commit 37d579f

Please sign in to comment.