Skip to content

Commit

Permalink
minor edits to method names and docstrings
Browse files Browse the repository at this point in the history
  • Loading branch information
jkanche committed Dec 28, 2023
1 parent 197328d commit 8c11bef
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 76 deletions.
80 changes: 52 additions & 28 deletions src/summarizedexperiment/BaseSE.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import warnings
from collections import OrderedDict
from collections import OrderedDict, namedtuple
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
from warnings import warn

Expand All @@ -8,12 +8,24 @@

from ._frameutils import _sanitize_frame
from .type_checks import is_matrix_like
from .types import SliceResult

__author__ = "jkanche, keviny2"
__copyright__ = "jkanche"
__license__ = "MIT"

SliceResult = namedtuple(
"SlicerResult",
[
"rows",
"columns",
"assays",
"row_names",
"column_names",
"row_indices",
"col_indices",
],
)


def _guess_assay_shape(assays, rows, cols) -> tuple:
_keys = list(assays.keys())
Expand Down Expand Up @@ -164,6 +176,12 @@ def __init__(
self._assays = assays

self._shape = _guess_assay_shape(assays, row_data, column_data)

if self._shape is None:
raise RuntimeError(
"Failed to guess the 'shape' from the provided parameters!"
)

self._rows = _sanitize_frame(row_data, self._shape[0])
self._cols = _sanitize_frame(column_data, self._shape[1])

Expand All @@ -181,7 +199,7 @@ def __init__(
_validate_assays(self._assays, self._shape)

if self._shape is None:
raise RuntimeError("Cannot extract 'shape' from assays!")
raise RuntimeError("Cannot guess 'shape' from assays!")

_validate_rows(self._rows, self._row_names, self._shape)
_validate_cols(self._cols, self._column_names, self._shape)
Expand Down Expand Up @@ -375,15 +393,15 @@ def assays(self, assays: Dict[str, Any]):
######>> row_data <<######
##########################

def get_rowdata(self) -> biocframe.BiocFrame:
def get_row_data(self) -> biocframe.BiocFrame:
"""Get features.
Returns:
Feature information.
"""
return self._rows

def set_rowdata(
def set_row_data(
self, rows: Optional[biocframe.BiocFrame], in_place: bool = False
) -> "BaseSE":
"""Set new feature information.
Expand Down Expand Up @@ -413,7 +431,7 @@ def set_rowdata(
@property
def rowdata(self) -> Dict[str, Any]:
"""Alias for :py:meth:`~get_rowdata`."""
return self.get_rowdata()
return self.get_row_data()

@rowdata.setter
def rowdata(self, rows: Optional[biocframe.BiocFrame]):
Expand All @@ -425,12 +443,12 @@ def rowdata(self, rows: Optional[biocframe.BiocFrame]):
"Setting property 'rowdata' is an in-place operation, use 'set_rowdata' instead",
UserWarning,
)
self.set_rowdata(rows, in_place=True)
self.set_row_data(rows, in_place=True)

@property
def row_data(self) -> Dict[str, Any]:
"""Alias for :py:meth:`~get_rowdata`."""
return self.get_rowdata()
return self.get_row_data()

@row_data.setter
def row_data(self, rows: Optional[biocframe.BiocFrame]):
Expand All @@ -442,21 +460,21 @@ def row_data(self, rows: Optional[biocframe.BiocFrame]):
"Setting property 'rowdata' is an in-place operation, use 'set_rowdata' instead",
UserWarning,
)
self.set_rowdata(rows, in_place=True)
self.set_row_data(rows, in_place=True)

##########################
######>> col_data <<######
##########################

def get_columndata(self) -> biocframe.BiocFrame:
def get_column_data(self) -> biocframe.BiocFrame:
"""Get sample data.
Returns:
Sample information.
"""
return self._cols

def set_columndata(
def set_column_data(
self, cols: Optional[biocframe.BiocFrame], in_place: bool = False
) -> "BaseSE":
"""Set sample data.
Expand Down Expand Up @@ -486,10 +504,10 @@ def set_columndata(
@property
def columndata(self) -> Dict[str, Any]:
"""Alias for :py:meth:`~get_coldata`."""
return self.get_columndata()
return self.get_column_data()

@columndata.setter
def columndata(self, rows: Optional[biocframe.BiocFrame]):
def columndata(self, cols: Optional[biocframe.BiocFrame]):
"""Alias for :py:meth:`~set_coldata` with ``in_place = True``.
As this mutates the original object, a warning is raised.
Expand All @@ -498,15 +516,15 @@ def columndata(self, rows: Optional[biocframe.BiocFrame]):
"Setting property 'coldata' is an in-place operation, use 'set_columndata' instead",
UserWarning,
)
self.set_columndata(rows, in_place=True)
self.set_column_data(cols, in_place=True)

@property
def coldata(self) -> Dict[str, Any]:
"""Alias for :py:meth:`~get_coldata`."""
return self.get_columndata()
return self.get_column_data()

@coldata.setter
def coldata(self, rows: Optional[biocframe.BiocFrame]):
def coldata(self, cols: Optional[biocframe.BiocFrame]):
"""Alias for :py:meth:`~set_coldata` with ``in_place = True``.
As this mutates the original object, a warning is raised.
Expand All @@ -515,15 +533,15 @@ def coldata(self, rows: Optional[biocframe.BiocFrame]):
"Setting property 'coldata' is an in-place operation, use 'set_columndata' instead",
UserWarning,
)
self.set_columndata(rows, in_place=True)
self.set_column_data(cols, in_place=True)

@property
def column_data(self) -> Dict[str, Any]:
"""Alias for :py:meth:`~get_coldata`."""
return self.get_columndata()
return self.get_column_data()

@column_data.setter
def column_data(self, rows: Optional[biocframe.BiocFrame]):
def column_data(self, cols: Optional[biocframe.BiocFrame]):
"""Alias for :py:meth:`~set_coldata` with ``in_place = True``.
As this mutates the original object, a warning is raised.
Expand All @@ -532,15 +550,15 @@ def column_data(self, rows: Optional[biocframe.BiocFrame]):
"Setting property 'coldata' is an in-place operation, use 'set_coldata' instead",
UserWarning,
)
self.set_columndata(rows, in_place=True)
self.set_column_data(cols, in_place=True)

@property
def col_data(self) -> Dict[str, Any]:
"""Alias for :py:meth:`~get_coldata`."""
return self.get_columndata()
return self.get_column_data()

@col_data.setter
def col_data(self, rows: Optional[biocframe.BiocFrame]):
def col_data(self, cols: Optional[biocframe.BiocFrame]):
"""Alias for :py:meth:`~set_coldata` with ``in_place = True``.
As this mutates the original object, a warning is raised.
Expand All @@ -549,7 +567,7 @@ def col_data(self, rows: Optional[biocframe.BiocFrame]):
"Setting property 'coldata' is an in-place operation, use 'set_columndata' instead",
UserWarning,
)
self.set_columndata(rows, in_place=True)
self.set_column_data(cols, in_place=True)

##########################
######>> row names <<#####
Expand Down Expand Up @@ -855,7 +873,10 @@ def assay(self, assay: Union[int, str]) -> Any:
Experiment data.
"""
if isinstance(assay, int):
if assay < 0 or assay > len(self.assay_names):
if assay < 0:
raise IndexError("Index cannot be negative.")

if assay > len(self.assay_names):
raise IndexError("Index greater than the number of assays.")

return self.assays[self.assay_names[assay]]
Expand All @@ -865,7 +886,9 @@ def assay(self, assay: Union[int, str]) -> Any:

return self.assays[assay]

raise TypeError(f"'assay' must be a string or integer, provided {type(assay)}.")
raise TypeError(
f"'assay' must be a string or integer, provided '{type(assay)}'."
)

##########################
######>> slicers <<#######
Expand Down Expand Up @@ -1025,7 +1048,7 @@ def __getitem__(
self,
args: Union[int, str, Sequence, tuple],
) -> "BaseSE":
"""Subset a `SummarizedExperiment`.
"""Subset a ``SummarizedExperiment``.
Args:
args:
Expand All @@ -1041,7 +1064,8 @@ def __getitem__(
columns to retain, based on their names or indices.
Raises:
ValueError: If too many or too few slices provided.
ValueError:
If too many or too few slices provided.
Returns:
Same type as caller with the sliced rows and columns.
Expand Down Expand Up @@ -1074,7 +1098,7 @@ def to_anndata(self):
"""Transform :py:class:`~BaseSE`-like into a :py:class:`~anndata.AnnData` representation.
Returns:
An `AnnData` representation of the experiment.
An ``AnnData`` representation of the experiment.
"""
from anndata import AnnData

Expand Down
17 changes: 8 additions & 9 deletions src/summarizedexperiment/RangedSummarizedExperiment.py
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,8 @@ def nearest(
Whether to ignore strand. Defaults to False.
Raises:
If ``query`` is not a ``RangedSummarizedExperiment``
TypeError:
If ``query`` is not a ``RangedSummarizedExperiment``
or ``GenomicRanges``.
Returns:
Expand Down Expand Up @@ -494,8 +495,9 @@ def precede(
Whether to ignore strand. Defaults to False.
Raises:
If ``query`` is not a ``RangedSummarizedExperiment`` or
``GenomicRanges``.
TypeError:
If ``query`` is not a ``RangedSummarizedExperiment`` or
``GenomicRanges``.
Returns:
A List with the same length as ``query``,
Expand Down Expand Up @@ -754,9 +756,6 @@ def narrow(
in_place:
Whether to modify the ``GenomicRanges`` object in place.
Raises:
When parameters were set incorrectly or row_ranges is empty
Returns:
A new `RangedSummarizedExperiment` object with narrow positions,
either as a copy of the original or as a reference to the
Expand Down Expand Up @@ -814,7 +813,8 @@ def find_overlaps(
Whether to ignore strands. Defaults to False.
Raises:
TypeError: If query is not a `RangedSummarizedExperiment` or `GenomicRanges`.
TypeError:
If `query` is not a `RangedSummarizedExperiment` or `GenomicRanges`.
Returns:
A list with the same length as ``query``,
Expand Down Expand Up @@ -922,8 +922,7 @@ def sort(
Whether to modify the object in place. Defaults to False.
Returns:
A new sorted
`RangedSummarizedExperiment` object.
A new sorted `RangedSummarizedExperiment` object.
"""
_order = self.row_ranges.order(decreasing=decreasing)

Expand Down
21 changes: 1 addition & 20 deletions src/summarizedexperiment/type_checks.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, Callable
from typing import Any

# from .RangedSummarizedExperiment import RangedSummarizedExperiment

Expand Down Expand Up @@ -55,22 +55,3 @@ def is_matrix_like(x: Any) -> bool:
# TODO: this only work for python 3.8 and below.
# return isinstance(x, MatrixProtocol)
return hasattr(x, "__getitem__") and hasattr(x, "shape")


def is_list_of_type(x: Any, target_type: Callable) -> bool:
"""Checks if ``x`` is a list or tuple and and whether all elements are of the same type.
Args:
x:
Any object.
target_type:
Type to check for, e.g. ``str``, ``int``.
Returns:
True if ``x`` is :py:class:`~list` and all
elements are of the same type.
"""
return (isinstance(x, list) or isinstance(x, tuple)) and all(
isinstance(item, target_type) for item in x
)
19 changes: 0 additions & 19 deletions src/summarizedexperiment/types.py

This file was deleted.

0 comments on commit 8c11bef

Please sign in to comment.