Skip to content

Typehinting bools #522

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 10, 2020
Merged
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
2 changes: 1 addition & 1 deletion monai/data/csv_saver.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def __init__(self, output_dir: str = "./", filename: str = "predictions.csv", ov
Args:
output_dir (str): output CSV file directory.
filename (str): name of the saved CSV file name.
overwrite (bool): whether to overwriting existing CSV file content. If we are not overwriting,
overwrite: whether to overwriting existing CSV file content. If we are not overwriting,
then we check if the results have been previously saved, and load them to the prediction_dict.

"""
Expand Down
8 changes: 4 additions & 4 deletions monai/data/dataloader.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class DataLoader(torch.utils.data.DataLoader):
dataset (Dataset): dataset from which to load the data.
batch_size: how many samples per batch to load
(default: ``1``).
shuffle (bool, optional): set to ``True`` to have the data reshuffled
shuffle: set to ``True`` to have the data reshuffled
at every epoch (default: ``False``).
sampler (Sampler, optional): defines the strategy to draw samples from
the dataset. If specified, :attr:`shuffle` must be ``False``.
Expand All @@ -35,11 +35,11 @@ class DataLoader(torch.utils.data.DataLoader):
num_workers: how many subprocesses to use for data
loading. ``0`` means that the data will be loaded in the main process.
(default: ``0``)
pin_memory (bool, optional): If ``True``, the data loader will copy Tensors
pin_memory: If ``True``, the data loader will copy Tensors
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why is this corresponding signature not updated? some compatibility issue?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, we just made the fix.

into CUDA pinned memory before returning them. If your data elements
are a custom type, or your :attr:`collate_fn` returns a batch that is a custom type,
see the example below.
drop_last (bool, optional): set to ``True`` to drop the last incomplete batch,
drop_last: set to ``True`` to drop the last incomplete batch,
if the dataset size is not divisible by the batch size. If ``False`` and
the size of dataset is not divisible by the batch size, then the last batch
will be smaller. (default: ``False``)
Expand All @@ -53,7 +53,7 @@ def __init__(
self,
dataset,
batch_size: Optional[int] = 1,
shuffle=False,
shuffle: bool = False,
sampler=None,
batch_sampler=None,
num_workers: Optional[int] = 0,
Expand Down
6 changes: 4 additions & 2 deletions monai/data/decathalon_datalist.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,17 @@ def _append_paths(base_dir, is_segmentation, items):
return items


def load_decathalon_datalist(data_list_file_path, is_segmentation=True, data_list_key="training", base_dir=None):
def load_decathalon_datalist(
data_list_file_path, is_segmentation: bool = True, data_list_key="training", base_dir=None
):
"""Load image/label paths of decathalon challenge from JSON file

Json file is similar to what you get from http://medicaldecathlon.com/
Those dataset.json files

Args:
data_list_file_path (str): the path to the json file of datalist.
is_segmentation (bool): whether the datalist is for segmentation task, default is True.
is_segmentation: whether the datalist is for segmentation task, default is True.
data_list_key (str): the key to get a list of dictionary to be used, default is "training".
base_dir (str): the base directory of the dataset, if None, use the datalist directory.

Expand Down
4 changes: 2 additions & 2 deletions monai/data/nifti_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,10 @@ def __init__(
image_files (list of str): list of image filenames
seg_files (list of str): if in segmentation task, list of segmentation filenames
labels (list or array): if in classification task, list of classification labels
as_closest_canonical (bool): if True, load the image as closest to canonical orientation
as_closest_canonical: if True, load the image as closest to canonical orientation
transform (Callable, optional): transform to apply to image arrays
seg_transform (Callable, optional): transform to apply to segmentation arrays
image_only (bool): if True return only the image volume, other return image volume and header dict
image_only: if True return only the image volume, other return image volume and header dict
dtype (np.dtype, optional): if not None convert the loaded image to this data type
"""

Expand Down
2 changes: 1 addition & 1 deletion monai/data/nifti_saver.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def __init__(
output_dir (str): output image directory.
output_postfix (str): a string appended to all output file names.
output_ext (str): output file extension name.
resample (bool): whether to resample before saving the data array.
resample: whether to resample before saving the data array.
interp_order: the order of the spline interpolation, default is InterpolationCode.SPLINE3.
The order has to be in the range 0 - 5.
https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.affine_transform.html
Expand Down
8 changes: 4 additions & 4 deletions monai/data/nifti_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def write_nifti(
file_name,
affine=None,
target_affine=None,
resample=True,
resample: bool = True,
output_shape=None,
interp_order=InterpolationCode.SPLINE3,
mode="constant",
Expand Down Expand Up @@ -63,7 +63,7 @@ def write_nifti(
target_affine (numpy.ndarray, optional): before saving
the (`data`, `affine`) as a Nifti1Image,
transform the data into the coordinates defined by `target_affine`.
resample (bool): whether to run resampling when the target affine
resample: whether to run resampling when the target affine
could not be achieved by swapping/flipping data axes.
output_shape (None or tuple of ints): output image shape.
this option is used when resample = True.
Expand Down Expand Up @@ -126,8 +126,8 @@ def write_nifti(
cval=cval,
)
)
data_chns = np.stack(data_chns, axis=-1)
data_ = data_chns.reshape(list(data_chns.shape[:3]) + list(channel_shape))
data_chns_ = np.stack(data_chns, axis=-1)
data_ = data_chns_.reshape(list(data_chns_.shape[:3]) + list(channel_shape))
else:
data_ = data.astype(dtype)
data_ = scipy.ndimage.affine_transform(
Expand Down
4 changes: 2 additions & 2 deletions monai/data/png_saver.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def __init__(
output_dir (str): output image directory.
output_postfix (str): a string appended to all output file names.
output_ext (str): output file extension name.
resample (bool): whether to resample and resize if providing spatial_shape in the metadata.
resample: whether to resample and resize if providing spatial_shape in the metadata.
interp_order: the order of the spline interpolation, default is InterpolationCode.SPLINE3.
This option is used when spatial_shape is specified and different from the data shape.
The order has to be in the range 0 - 5.
Expand All @@ -50,7 +50,7 @@ def __init__(
This option is used when spatial_shape is specified and different from the data shape.
cval (scalar): Value to fill past edges of input if mode is "constant". Default is 0.0.
This option is used when spatial_shape is specified and different from the data shape.
scale (bool): whether to scale data with 255 and convert to uint8 for data in range [0, 1].
scale: whether to scale data with 255 and convert to uint8 for data in range [0, 1].

"""
self.output_dir = output_dir
Expand Down
4 changes: 2 additions & 2 deletions monai/data/png_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def write_png(
interp_order: int = 3,
mode="constant",
cval=0,
scale=False,
scale: bool = False,
plugin=None,
**plugin_args,
):
Expand All @@ -41,7 +41,7 @@ def write_png(
this option is used when `output_shape != None`.
cval (scalar): Value to fill past edges of input if mode is "constant". Default is 0.0.
this option is used when `output_shape != None`.
scale (bool): whether to scale data with 255 and convert to uint8 for data in range [0, 1].
scale: whether to scale data with 255 and convert to uint8 for data in range [0, 1].
plugin (string): name of plugin to use in `imsave`. By default, the different plugins
are tried(starting with imageio) until a suitable candidate is found.
plugin_args (keywords): arguments passed to the given plugin.
Expand Down
4 changes: 2 additions & 2 deletions monai/data/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ def iter_patch(
arr (np.ndarray): array to iterate over
patch_size (tuple of int or None): size of patches to generate slices for, 0 or None selects whole dimension
start_pos (tuple of it, optional): starting position in the array, default is 0 for each dimension
copy_back (bool): if True data from the yielded patches is copied back to `arr` once the generator completes
copy_back: if True data from the yielded patches is copied back to `arr` once the generator completes
pad_mode (str, optional): padding mode, see `numpy.pad`
pad_opts (dict, optional): padding options, see `numpy.pad`

Expand Down Expand Up @@ -304,7 +304,7 @@ def zoom_affine(affine, scale, diagonal: bool = True):
Args:
affine (nxn matrix): a square matrix.
scale (sequence of floats): new scaling factor along each dimension.
diagonal (bool): whether to return a diagonal scaling matrix.
diagonal: whether to return a diagonal scaling matrix.
Defaults to True.

returns:
Expand Down
4 changes: 2 additions & 2 deletions monai/engines/multi_gpu_supervised_trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def create_multigpu_supervised_trainer(
loss_fn (`torch.nn` loss function): the loss function to use.
devices (list, optional): device(s) type specification (default: None).
Applies to both model and batches. None is all devices used, empty list is CPU only.
non_blocking (bool, optional): if True and this copy is between CPU and GPU, the copy may occur asynchronously
non_blocking: if True and this copy is between CPU and GPU, the copy may occur asynchronously
with respect to the host. For other cases, this argument has no effect.
prepare_batch (callable, optional): function that receives `batch`, `device`, `non_blocking` and outputs
tuple of tensors `(batch_x, batch_y)`.
Expand Down Expand Up @@ -85,7 +85,7 @@ def create_multigpu_supervised_evaluator(
metrics (dict of str - :class:`~ignite.metrics.Metric`): a map of metric names to Metrics.
devices (list, optional): device(s) type specification (default: None).
Applies to both model and batches. None is all devices used, empty list is CPU only.
non_blocking (bool, optional): if True and this copy is between CPU and GPU, the copy may occur asynchronously
non_blocking: if True and this copy is between CPU and GPU, the copy may occur asynchronously
with respect to the host. For other cases, this argument has no effect.
prepare_batch (callable, optional): function that receives `batch`, `device`, `non_blocking` and outputs
tuple of tensors `(batch_x, batch_y)`.
Expand Down
2 changes: 1 addition & 1 deletion monai/engines/trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ class SupervisedTrainer(Trainer):
and `batchdata` as input parameters. if not provided, use `self._iteration()` instead.
lr_scheduler (LR Scheduler): the lr scheduler associated to the optimizer.
inferer (Inferer): inference method that execute model forward on input data, like: SlidingWindow, etc.
amp (bool): whether to enable auto-mixed-precision training, reserved.
amp: whether to enable auto-mixed-precision training, reserved.
post_transform (Transform): execute additional transformation for the model output data.
Typically, several Tensor based transforms composed by `Compose`.
key_train_metric (ignite.metric): compute metric when every iteration completed, and save average value to
Expand Down
4 changes: 2 additions & 2 deletions monai/engines/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class Workflow(ABC, Engine):
Args:
device (torch.device): an object representing the device on which to run.
max_epochs: the total epoch number for engine to run, validator and evaluator have only 1 epoch.
amp (bool): whether to enable auto-mixed-precision training, reserved.
amp: whether to enable auto-mixed-precision training, reserved.
data_loader (torch.DataLoader): Ignite engine use data_loader to run, must be torch.DataLoader.
prepare_batch (Callable): function to parse image and label for every iteration.
iteration_update (Callable): the callable function for every iteration, expect to accept `engine`
Expand All @@ -49,7 +49,7 @@ def __init__(
self,
device,
max_epochs: int,
amp,
amp: bool,
data_loader,
prepare_batch=default_prepare_batch,
iteration_update=None,
Expand Down
6 changes: 3 additions & 3 deletions monai/handlers/checkpoint_saver.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,15 @@ class CheckpointSaver:

name (str): identifier of logging.logger to use, if None, defaulting to ``engine.logger``.
file_prefix (str): prefix for the filenames to which objects will be saved.
save_final (bool): whether to save checkpoint or session at final iteration or exception.
save_key_metric (bool): whether to save checkpoint or session when the value of key_metric is
save_final: whether to save checkpoint or session at final iteration or exception.
save_key_metric: whether to save checkpoint or session when the value of key_metric is
higher than all the previous values during training.keep 4 decimal places of metric,
checkpoint name is: {file_prefix}_key_metric=0.XXXX.pth.
key_metric_name (str): the name of key_metric in ignite metrics dictionary.
if None, use `engine.state.key_metric` instead.
key_metric_n_saved: save top N checkpoints or sessions, sorted by the value of key
metric in descending order.
epoch_level (bool): save checkpoint during training for every N epochs or every N iterations.
epoch_level: save checkpoint during training for every N epochs or every N iterations.
`True` is epoch level, `False` is iteration level.
save_interval: save checkpoint every N epochs, default is 0 to save no checkpoint.
n_saved: save latest N checkpoints of epoch level or iteration level, 'None' is to save all.
Expand Down
2 changes: 1 addition & 1 deletion monai/handlers/classification_saver.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def __init__(
Args:
output_dir (str): output CSV file directory.
filename (str): name of the saved CSV file name.
overwrite (bool): whether to overwriting existing CSV file content. If we are not overwriting,
overwrite: whether to overwriting existing CSV file content. If we are not overwriting,
then we check if the results have been previously saved, and load them to the prediction_dict.
batch_transform (Callable): a callable that is used to transform the
ignite.engine.batch into expected format to extract the meta_data dictionary.
Expand Down
4 changes: 2 additions & 2 deletions monai/handlers/lr_schedule_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ def __init__(
Args:
lr_scheduler (torch.optim.lr_scheduler): typically, lr_scheduler should be PyTorch
lr_scheduler object. If customized version, must have `step` and `get_last_lr` methods.
print_lr (bool): whether to print out the latest learning rate with logging.
print_lr: whether to print out the latest learning rate with logging.
name (str): identifier of logging.logger to use, if None, defaulting to ``engine.logger``.
epoch_level (bool): execute lr_scheduler.step() after every epoch or every iteration.
epoch_level: execute lr_scheduler.step() after every epoch or every iteration.
`True` is epoch level, `False` is iteration level.
step_transform (Callable): a callable that is used to transform the information from `engine`
to expected input data of lr_scheduler.step() function if necessary.
Expand Down
8 changes: 4 additions & 4 deletions monai/handlers/mean_dice.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,12 @@ def __init__(
"""

Args:
include_background (Bool): whether to include dice computation on the first channel of the predicted output.
include_background: whether to include dice computation on the first channel of the predicted output.
Defaults to True.
to_onehot_y (Bool): whether to convert the output prediction into the one-hot format. Defaults to False.
mutually_exclusive (Bool): if True, the output prediction will be converted into a binary matrix using
to_onehot_y: whether to convert the output prediction into the one-hot format. Defaults to False.
mutually_exclusive: if True, the output prediction will be converted into a binary matrix using
a combination of argmax and to_onehot. Defaults to False.
sigmoid (Bool): whether to add sigmoid function to the output prediction before computing Dice.
sigmoid: whether to add sigmoid function to the output prediction before computing Dice.
Defaults to False.
logit_thresh (Float): the threshold value to round value to 0.0 and 1.0. Defaults to None (no thresholding).
output_transform (Callable): transform the ignite.engine.state.output into [y_pred, y] pair.
Expand Down
4 changes: 2 additions & 2 deletions monai/handlers/segmentation_saver.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def __init__(
output_dir (str): output image directory.
output_postfix (str): a string appended to all output file names.
output_ext (str): output file extension name.
resample (bool): whether to resample before saving the data array.
resample: whether to resample before saving the data array.
interp_order: the order of the spline interpolation, default is 0.
The order has to be in the range 0 - 5.
https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.affine_transform.html
Expand All @@ -52,7 +52,7 @@ def __init__(
This option is used when `resample = True`.
cval (scalar): Value to fill past edges of input if mode is "constant". Default is 0.0.
This option is used when `resample = True`.
scale (bool): whether to scale data with 255 and convert to uint8 for data in range [0, 1].
scale: whether to scale data with 255 and convert to uint8 for data in range [0, 1].
It's used for PNG format only.
dtype (np.dtype, optional): convert the image data to save to this data type.
If None, keep the original type of data. It's used for Nifti format only.
Expand Down
4 changes: 2 additions & 2 deletions monai/handlers/tensorboard_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ def __init__(
summary_writer: Optional[SummaryWriter] = None,
log_dir: str = "./runs",
interval: int = 1,
epoch_level=True,
epoch_level: bool = True,
batch_transform: Callable = lambda x: x,
output_transform: Callable = lambda x: x,
global_iter_transform: Callable = lambda x: x,
Expand All @@ -206,7 +206,7 @@ def __init__(
default to create a new writer.
log_dir (str): if using default SummaryWriter, write logs to this directory, default is `./runs`.
interval: plot content from engine.state every N epochs or every N iterations, default is 1.
epoch_level (bool): plot content from engine.state every N epochs or N iterations. `True` is epoch level,
epoch_level: plot content from engine.state every N epochs or N iterations. `True` is epoch level,
`False` is iteration level.
batch_transform (Callable): a callable that is used to transform the
``ignite.engine.batch`` into expected format to extract several label data.
Expand Down
2 changes: 1 addition & 1 deletion monai/handlers/validation_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def __init__(self, validator: Evaluator, interval: int, epoch_level: bool = True
Args:
validator (Evaluator): run the validator when trigger validation, suppose to be Evaluator.
interval: do validation every N epochs or every N iterations during training.
epoch_level (bool): execute validation every N epochs or N iterations.
epoch_level: execute validation every N epochs or N iterations.
`True` is epoch level, `False` is iteration level.

"""
Expand Down
Loading