Skip to content

Commit

Permalink
📝 Fix docstrings (#624)
Browse files Browse the repository at this point in the history
- Fix docstrings.

---------

Co-authored-by: Mark Eastwood <[email protected]>
Co-authored-by: John Pocock <[email protected]>
  • Loading branch information
3 people authored Jul 14, 2023
1 parent 54a6803 commit 336d5e5
Show file tree
Hide file tree
Showing 18 changed files with 138 additions and 86 deletions.
56 changes: 33 additions & 23 deletions tiatoolbox/annotation/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,7 @@ def patch_many(
An iterable of properties to update.
keys (iter(str)):
An iterable of keys for each annotation to be updated.
"""
# Validate inputs
if not any([geometries, properties_iter]):
Expand Down Expand Up @@ -896,7 +897,6 @@ def bquery(
>>> store.bquery(where="props['class'] == 42")
{'foo': (0.0, 0.0, 1.0, 1.0)}
"""
query_geometry = geometry
if isinstance(query_geometry, Iterable):
Expand Down Expand Up @@ -1156,7 +1156,7 @@ def nquery(
Example bounding box query with one neighbour within a
distance of 2.0.
>>> from shapely.geometry import Point, Polyon
>>> from shapely.geometry import Point, Polygon
>>> from tiatoolbox.annotation.storage import Annotation, SQLiteStore
>>> store = SQLiteStore()
>>> annotation = Annotation(Point(0, 0), {"class": 42})
Expand Down Expand Up @@ -1412,7 +1412,7 @@ def add_from_geojson(
The scale factor to use when loading the annotations. All coordinates
will be multiplied by this factor to allow import of annotations saved
at non-baseline resolution.
origin [float, float]:
origin (Tuple[float, float]):
The x and y coordinates to use as the origin for the annotations.
"""
Expand Down Expand Up @@ -1646,15 +1646,6 @@ class SQLiteMetadata(MutableMapping):
"""Metadata storage for an SQLiteStore.
Attributes:
connection (Union[str, Path, IO]):
A reference to where the data is stored. It maybe a string (
e.g. ":memory:" or "./data.db"), a pathlib Path, or a file
handle.
path (Path):
The path to the annotation store data. This will be
":memory:" if the annotation store is in-memory. This is
derived from `connection` and normalised to be a pathlib
Path object.
con (sqlite3.Connection):
The sqlite3 database connection.
Expand Down Expand Up @@ -2167,7 +2158,7 @@ def _query(
unique: bool = False,
no_constraints_ok: bool = False,
index_warning: bool = False,
min_area=None,
min_area: Optional[float] = None,
distance: float = 0,
) -> sqlite3.Cursor:
"""Common query construction logic for `query` and `iquery`.
Expand All @@ -2177,11 +2168,17 @@ def _query(
The columns to select.
geometry(tuple or Geometry):
The geometry being queried against.
select_callable(str):
The rows to select when a callable is given to `where`.
callable_columns(str):
The columns to select when a callable is given to
`where`.
geometry_predicate(str):
A string which define which binary geometry predicate to
use when comparing the query geometry and a geometry in
the store. Only annotations for which this binary
predicate is true will be returned. Defaults to
"intersects". For more information see the `shapely
documentation on binary predicates <https://shapely.
readthedocs.io/en/stable/manual.html#binary-predicates>`_.
where (str or bytes or Callable):
The predicate to evaluate against candidate properties
during the query.
Expand All @@ -2195,6 +2192,9 @@ def _query(
index_warning(bool):
Whether to warn if the query is not using an index.
Defaults to False.
min_area (float or None):
Minimum area of the annotations to be returned.
Defaults to None.
distance (float):
Distance used when performing a distance based query.
E.g. "centers_within_k" geometry predicate.
Expand Down Expand Up @@ -2234,12 +2234,13 @@ def _query(
distance=distance,
)

# Add area column constraint to query if min_area is specified
if min_area is not None and "area" in self.table_columns:
query_string += f"\nAND area > {min_area}"
elif min_area is not None:
raise ValueError(
"""Cannot use `min_area` without an area column.
SQLiteStore.add_area_column() can be used to add an area column."""
"Cannot use `min_area` without an area column. "
"SQLiteStore.add_area_column() can be used to add an area column."
)

if unique:
Expand Down Expand Up @@ -2267,7 +2268,7 @@ def iquery(
geometry: Optional[QueryGeometry] = None,
where: Optional[Predicate] = None,
geometry_predicate="intersects",
min_area=None,
min_area: Optional[float] = None,
distance: float = 0,
) -> List[str]:
"""Query the store for annotation keys.
Expand Down Expand Up @@ -2306,14 +2307,18 @@ def iquery(
input should never be accepted to this argument as
arbitrary code can be run via pickle or the parsing of
the string statement.
geometry_predicate:
geometry_predicate (str):
A string which define which binary geometry predicate to
use when comparing the query geometry and a geometry in
the store. Only annotations for which this binary
predicate is true will be returned. Defaults to
"intersects". For more information see the `shapely
documentation on binary predicates <https://shapely.
readthedocs.io/en/stable/manual.html#binary-predicates>`_.
min_area (float or None):
Minimum area of the annotations to be returned.
Defaults to None.
distance (float):
Distance used when performing a distance based query.
E.g. "centers_within_k" geometry predicate.
Expand Down Expand Up @@ -2380,7 +2385,7 @@ def bquery(
self,
geometry: Optional[QueryGeometry] = None,
where: Union[str, bytes, Callable[[Geometry, Dict[str, Any]], bool]] = None,
min_area=None,
min_area: Optional[float] = None,
) -> Dict[str, Tuple[float, float, float, float]]:
"""Query the store for annotation bounding boxes.
Expand Down Expand Up @@ -2428,6 +2433,10 @@ def bquery(
input should never be accepted to this argument as
arbitrary code can be run via pickle or the parsing of
the string statement.
min_area (float or None):
Minimum area of the annotations to be returned.
Defaults to None.
Returns:
list:
Expand Down Expand Up @@ -2870,6 +2879,7 @@ def patch_many(
An iterable of properties to update.
keys (iter(str)):
An iterable of keys for each annotation to be updated.
"""
# Validate inputs
if not any([geometries, properties_iter]):
Expand Down Expand Up @@ -2919,9 +2929,9 @@ def _patch_geometry(
leave the properties untouched.
Args:
key: The key of the annotation to patch.
geometry: The new geometry.
cur: The cursor to use.
key (str): The key of the annotation to patch.
geometry (Geometry): The new geometry.
cur (sqlite3.Cursor): The cursor to use.
"""
bounds = dict(zip(("min_x", "min_y", "max_x", "max_y"), geometry.bounds))
Expand Down
1 change: 1 addition & 0 deletions tiatoolbox/models/architecture/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ def fetch_pretrained_weights(model_name: str, save_path: str, overwrite: bool =
corresponding `model_name`.
overwrite (bool):
Overwrite existing downloaded weights.
"""
info = PRETRAINED_INFO[model_name]
download_data(info["url"], save_path, overwrite)
Expand Down
6 changes: 4 additions & 2 deletions tiatoolbox/models/architecture/mapde.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
"""

from typing import List

import numpy as np
import torch
import torch.nn.functional as F # noqa: N812
Expand Down Expand Up @@ -254,7 +256,7 @@ def postproc(self, prediction_map: np.ndarray) -> np.ndarray:
@staticmethod
def infer_batch(
model: torch.nn.Module, batch_data: np.ndarray, on_gpu: bool
) -> np.ndarray:
) -> List[np.ndarray]:
"""Run inference on an input batch.
This contains logic for forward operation as well as batch I/O
Expand All @@ -270,7 +272,7 @@ def infer_batch(
Whether to run inference on a GPU.
Returns:
np.ndarray:
list(np.ndarray):
Probability map as numpy array.
"""
Expand Down
6 changes: 3 additions & 3 deletions tiatoolbox/models/architecture/micronet.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"""

from collections import OrderedDict
from typing import Tuple
from typing import List, Tuple

import numpy as np
import torch
Expand Down Expand Up @@ -588,7 +588,7 @@ def preproc(image: np.ndarray):
@staticmethod
def infer_batch(
model: torch.nn.Module, batch_data: np.ndarray, on_gpu: bool
) -> np.ndarray:
) -> List[np.ndarray]:
"""Run inference on an input batch.
This contains logic for forward operation as well as batch I/O
Expand All @@ -604,7 +604,7 @@ def infer_batch(
Whether to run inference on a GPU.
Returns:
np.ndarray:
list(np.ndarray):
Probability map as a numpy array.
"""
Expand Down
2 changes: 1 addition & 1 deletion tiatoolbox/models/architecture/nuclick.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ def get_block(
Size of stride in the convolution layer.
use_bias (bool):
Whether to use bias in the convolution layer.
dilation_rates (list):
dilation_rate (list):
Dilation rate for each convolution layer.
activation (str):
Name of the activation function to use.
Expand Down
6 changes: 2 additions & 4 deletions tiatoolbox/models/architecture/sccnn.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,8 @@ class SCCNN(ModelABC):
Args:
num_input_channels (int):
Number of channels in input. default=3.
out_height (int):
Output height. default=13.
out_width (int):
Output width. default=13.
patch_output_shape tuple(int):
Defines output height and output width. default=(13, 13).
radius (int):
Radius for nucleus detection, default = 12.
min_distance (int):
Expand Down
2 changes: 0 additions & 2 deletions tiatoolbox/models/dataset/classification.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,6 @@ class PatchDataset(dataset_abc.PatchDatasetABC):
labels:
List of labels for sample at the same index in `inputs`.
Default is `None`.
preproc_func:
Preprocessing function used to transform the input data.
Examples:
>>> # A user defined preproc func and expected behavior
Expand Down
2 changes: 0 additions & 2 deletions tiatoolbox/models/engine/multi_task_segmentor.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,8 +289,6 @@ def _predict_one_wsi(
wsi_idx (int): Index of the tile/wsi to be processed within `self`.
ioconfig (IOSegmentorConfig): Object which defines I/O placement during
inference and when assembling back to full tile/wsi.
loader (torch.Dataloader): The loader object which return batch of data
to be input to model.
save_path (str): Location to save output prediction as well as possible
intermediate results.
mode (str): `tile` or `wsi` to indicate run mode.
Expand Down
2 changes: 1 addition & 1 deletion tiatoolbox/models/engine/semantic_segmentor.py
Original file line number Diff line number Diff line change
Expand Up @@ -1439,7 +1439,7 @@ def _process_predictions(
"""Define how the aggregated predictions are processed.
This includes merging the prediction if necessary and also
saving afterwards.
saving afterward.
Args:
cum_batch_predictions (list):
Expand Down
2 changes: 2 additions & 0 deletions tiatoolbox/models/models_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ def preproc_func(self, func):
>>> # expected usage
>>> # model is a subclass object of this ModelABC
>>> # `func` is a user defined function
>>> model = ModelABC()
>>> model.preproc_func = func
>>> transformed_img = model.preproc_func(img)
Expand Down Expand Up @@ -112,6 +113,7 @@ def postproc_func(self, func):
>>> # expected usage
>>> # model is a subclass object of this ModelABC
>>> # `func` is a user defined function
>>> model = ModelABC()
>>> model.postproc_func = func
>>> transformed_img = model.postproc_func(img)
Expand Down
18 changes: 15 additions & 3 deletions tiatoolbox/tools/pyramid.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,9 @@ def get_tile(
The tile index in the x direction.
y (int):
The tile index in the y direction.
res (int):
The resolution of the tile. Defaults to 1, can be set to 2 for
double resolution.
pad_mode (str):
Method for padding when reading areas outside the
input image. Default is constant (0 padding). This is
Expand All @@ -183,7 +186,7 @@ def get_tile(
>>> from tiatoolbox.wsicore.wsireader import WSIReader
>>> wsi = WSIReader.open("sample.svs")
>>> tile_generator = TilePyramidGenerator(
... wsi=reader,
... wsi=wsi,
... tile_size=256,
... )
>>> tile_0_0_0 = tile_generator.get_tile(level=0, x=0, y=0)
Expand Down Expand Up @@ -381,7 +384,7 @@ class ZoomifyGenerator(TilePyramidGenerator):
\times\text{overlap}`.
downsample (int):
The downsample factor between levels. Default is 2.
tile_overlap (int):
overlap (int):
The number of extra pixel to add to each edge of the tile.
Default is 0.
Expand Down Expand Up @@ -449,7 +452,7 @@ class AnnotationTileGenerator(ZoomifyGenerator):
info (WSIMeta):
An WSIMeta Object storing the metadata of the slide this
generator is rendering tiles for
Store (AnnotationStore):
store (AnnotationStore):
An AnnotationStore Object containing annotations to be
rendered for given slide
renderer (AnnotationRenderer):
Expand Down Expand Up @@ -564,6 +567,15 @@ def get_tile(
The tile index in the x direction.
y (int):
The tile index in the y direction.
res (int):
The resolution of the tile. Defaults to 1, can be set to 2 for
double resolution.
pad_mode (str):
Method for padding at edges of the WSI. Default to
'constant'. See :func:`numpy.pad` for more information.
interpolation (str):
Method of interpolation. Possible values are: nearest,
linear, cubic, lanczos, area. Defaults to nearest.
Returns:
PIL.Image:
Expand Down
1 change: 0 additions & 1 deletion tiatoolbox/utils/magic.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,6 @@ def is_dcm(file: Union[str, Path, bytes, BytesIO, BytesIO]) -> bool:
A boolean indicating whether the file is a .dcm file or not.
"""

if is_dir(file):
return False
with _normalize_binaryio(file) as io:
Expand Down
2 changes: 1 addition & 1 deletion tiatoolbox/utils/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def pair_coordinates(set_a, set_b, radius):
This function uses the Munkres or Kuhn-Munkres algorithm behind the
scene to find the most optimal unique pairing when pairing points in
set B against points in set A, using euclidean distance as the cost
set B against points in set A, using Euclidean distance as the cost
function.
Args:
Expand Down
4 changes: 2 additions & 2 deletions tiatoolbox/utils/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -1005,7 +1005,7 @@ def make_default_dict(data: dict, subcat: str) -> dict:
The unique types in the data are given a prefix to differentiate
types from different heads of a multi-head model.
For example, types 1,2, etc in the 'Gland' head will become
For example, types 1,2, etc. in the 'Gland' head will become
'Gla: 1', 'Gla: 2', etc.
Args:
Expand Down Expand Up @@ -1055,7 +1055,7 @@ def add_from_dat(
For multi-head output, should be a dict of dicts, e.g.:
{'head1': {1: 'Epithelial Cell', 2: 'Lymphocyte', 3: ...},
'head2': {1: 'Gland', 2: 'Lumen', 3: ...}, ...}.
origin (Tuple [float, float]):
origin (tuple(float, float)):
The x and y coordinates to use as the origin for the annotations.
"""
Expand Down
Loading

0 comments on commit 336d5e5

Please sign in to comment.