Skip to content
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
4 changes: 2 additions & 2 deletions monai/data/synthetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def create_test_image_2d(
random_state: the random generator to use. Defaults to `np.random`.
"""
image = np.zeros((width, height))
rs = np.random if random_state is None else random_state
rs: np.random.RandomState = np.random.random.__self__ if random_state is None else random_state # type: ignore

for _ in range(num_objs):
x = rs.randint(rad_max, width - rad_max)
Expand Down Expand Up @@ -111,7 +111,7 @@ def create_test_image_3d(
:py:meth:`~create_test_image_2d`
"""
image = np.zeros((width, height, depth))
rs = np.random if random_state is None else random_state
rs: np.random.RandomState = np.random.random.__self__ if random_state is None else random_state # type: ignore

for _ in range(num_objs):
x = rs.randint(rad_max, width - rad_max)
Expand Down
2 changes: 1 addition & 1 deletion monai/data/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -605,7 +605,7 @@ def to_affine_nd(r: Union[np.ndarray, int], affine: np.ndarray) -> np.ndarray:
raise ValueError(f"affine must have 2 dimensions, got {affine_np.ndim}.")
new_affine = np.array(r, dtype=np.float64, copy=True)
if new_affine.ndim == 0:
sr = new_affine.astype(int)
sr: int = int(new_affine.astype(np.uint))
if not np.isfinite(sr) or sr < 0:
raise ValueError(f"r must be positive, got {sr}.")
new_affine = np.eye(sr + 1, dtype=np.float64)
Expand Down
10 changes: 5 additions & 5 deletions monai/handlers/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,12 +206,12 @@ class mean median max 5percentile 95percentile notnans
if summary_ops is not None:
supported_ops = OrderedDict(
{
"mean": np.nanmean,
"median": np.nanmedian,
"max": np.nanmax,
"min": np.nanmin,
"mean": lambda x: np.nanmean(x),
"median": lambda x: np.nanmedian(x),
"max": lambda x: np.nanmax(x),
"min": lambda x: np.nanmin(x),
"90percentile": lambda x: np.nanpercentile(x[0], x[1]),
"std": np.nanstd,
"std": lambda x: np.nanstd(x),
"notnans": lambda x: (~np.isnan(x)).sum(),
}
)
Expand Down
12 changes: 6 additions & 6 deletions monai/transforms/intensity/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def __init__(self, prob: float = 0.1, mean: Union[Sequence[float], float] = 0.0,
RandomizableTransform.__init__(self, prob)
self.mean = mean
self.std = std
self._noise = None
self._noise: np.ndarray

def randomize(self, im_shape: Sequence[int]) -> None:
super().randomize(None)
Expand Down Expand Up @@ -133,8 +133,8 @@ def __init__(
self.channel_wise = channel_wise
self.relative = relative
self.sample_std = sample_std
self._noise1 = None
self._noise2 = None
self._noise1: np.ndarray
self._noise2: np.ndarray

def _add_noise(self, img: Union[torch.Tensor, np.ndarray], mean: float, std: float):
im_shape = img.shape
Expand Down Expand Up @@ -463,7 +463,7 @@ def randomize(self, data: np.ndarray) -> None:
self.spatial_shape = data.shape[1:]
self.rank = len(self.spatial_shape)
n_coeff = int(np.prod([(self.degree + k) / k for k in range(1, self.rank + 1)]))
self._coeff = self.R.uniform(*self.coeff_range, n_coeff)
self._coeff = self.R.uniform(*self.coeff_range, n_coeff).tolist()

def __call__(self, img: np.ndarray):
"""
Expand Down Expand Up @@ -670,13 +670,13 @@ def __init__(self, prob: float = 0.1, gamma: Union[Sequence[float], float] = (0.
raise AssertionError("gamma should be a number or pair of numbers.")
self.gamma = (min(gamma), max(gamma))

self.gamma_value = None
self.gamma_value: float

def randomize(self, data: Optional[Any] = None) -> None:
super().randomize(None)
self.gamma_value = self.R.uniform(low=self.gamma[0], high=self.gamma[1])

def __call__(self, img: np.ndarray) -> np.ndarray:
def __call__(self, img: np.ndarray):
"""
Apply the transform to `img`.
"""
Expand Down
9 changes: 5 additions & 4 deletions monai/transforms/spatial/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,7 @@ def __call__(
raise ValueError(f"Unsupported img dimension: {input_ndim}, available options are [2, 3].")
_angle = ensure_tuple_rep(self.angle, 1 if input_ndim == 2 else 3)
transform = create_rotate(input_ndim, _angle)
shift = create_translate(input_ndim, (im_shape - 1) / 2)
shift = create_translate(input_ndim, ((im_shape - 1) / 2).tolist())
if self.keep_size:
output_shape = im_shape
else:
Expand All @@ -473,7 +473,7 @@ def __call__(
)
corners = transform[:-1, :-1] @ corners
output_shape = np.asarray(corners.ptp(axis=1) + 0.5, dtype=int)
shift_1 = create_translate(input_ndim, -(output_shape - 1) / 2)
shift_1 = create_translate(input_ndim, (-(output_shape - 1) / 2).tolist())
transform = shift @ transform @ shift_1

xform = AffineTransform(
Expand Down Expand Up @@ -985,6 +985,7 @@ def __call__(
else:
raise ValueError("Incompatible values: grid=None and spatial_size=None.")

affine: Union[torch.Tensor, np.ndarray]
if self.affine is None:
spatial_dims = len(grid.shape) - 1
affine = np.eye(spatial_dims + 1)
Expand Down Expand Up @@ -1138,7 +1139,7 @@ def __init__(

self.rand_mag = 1.0
self.as_tensor_output = as_tensor_output
self.random_offset = 0.0
self.random_offset: np.ndarray
self.device = device

def randomize(self, grid_size: Sequence[int]) -> None:
Expand Down Expand Up @@ -1694,7 +1695,7 @@ def __init__(
self.padding_mode: GridSamplePadMode = GridSamplePadMode(padding_mode)
self.device = device

self.rand_offset = None
self.rand_offset: np.ndarray
self.magnitude = 1.0
self.sigma = 1.0

Expand Down
4 changes: 2 additions & 2 deletions monai/transforms/spatial/dictionary.py
Original file line number Diff line number Diff line change
Expand Up @@ -1521,7 +1521,7 @@ def inverse(self, data: Mapping[Hashable, np.ndarray]) -> Dict[Hashable, np.ndar
transform = self.get_most_recent_transform(d, key)
# Create inverse transform
zoom = np.array(self.zoomer.zoom)
inverse_transform = Zoom(zoom=1 / zoom, keep_size=self.zoomer.keep_size)
inverse_transform = Zoom(zoom=(1 / zoom).tolist(), keep_size=self.zoomer.keep_size)
mode = transform[InverseKeys.EXTRA_INFO]["mode"]
padding_mode = transform[InverseKeys.EXTRA_INFO]["padding_mode"]
align_corners = transform[InverseKeys.EXTRA_INFO]["align_corners"]
Expand Down Expand Up @@ -1649,7 +1649,7 @@ def inverse(self, data: Mapping[Hashable, np.ndarray]) -> Dict[Hashable, np.ndar
mode = transform[InverseKeys.EXTRA_INFO]["mode"]
padding_mode = transform[InverseKeys.EXTRA_INFO]["padding_mode"]
align_corners = transform[InverseKeys.EXTRA_INFO]["align_corners"]
inverse_transform = Zoom(zoom=1 / zoom, keep_size=self.keep_size)
inverse_transform = Zoom(zoom=(1 / zoom).tolist(), keep_size=self.keep_size)
# Apply inverse
d[key] = inverse_transform(
d[key],
Expand Down
12 changes: 8 additions & 4 deletions monai/transforms/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,8 +224,8 @@ def resize_center(img: np.ndarray, *resize_dims: Optional[int], fill_value: floa

resize_dims = fall_back_tuple(resize_dims, img.shape)

half_img_shape = np.asarray(img.shape) // 2
half_dest_shape = np.asarray(resize_dims) // 2
half_img_shape = (np.asarray(img.shape) // 2).tolist()
half_dest_shape = (np.asarray(resize_dims) // 2).tolist()
srcslices, destslices = copypaste_arrays(img.shape, resize_dims, half_img_shape, half_dest_shape, resize_dims)

if not inplace:
Expand Down Expand Up @@ -318,7 +318,7 @@ def generate_pos_neg_label_crop_centers(
label_spatial_shape: Sequence[int],
fg_indices: np.ndarray,
bg_indices: np.ndarray,
rand_state: np.random.RandomState = np.random,
rand_state: Optional[np.random.RandomState] = None,
) -> List[List[np.ndarray]]:
"""
Generate valid sample locations based on the label with option for specifying foreground ratio
Expand All @@ -338,6 +338,8 @@ def generate_pos_neg_label_crop_centers(
ValueError: When the foreground and background indices lengths are 0.

"""
if rand_state is None:
rand_state = np.random.random.__self__ # type: ignore
spatial_size = fall_back_tuple(spatial_size, default=label_spatial_shape)
if not (np.subtract(label_spatial_shape, spatial_size) >= 0).all():
raise ValueError("The size of the proposed random crop ROI is larger than the image size.")
Expand Down Expand Up @@ -602,7 +604,7 @@ def get_largest_connected_component_mask(img: torch.Tensor, connectivity: Option


def get_extreme_points(
img: np.ndarray, rand_state: np.random.RandomState = np.random, background: int = 0, pert: float = 0.0
img: np.ndarray, rand_state: Optional[np.random.RandomState] = None, background: int = 0, pert: float = 0.0
) -> List[Tuple[int, ...]]:
"""
Generate extreme points from an image. These are used to generate initial segmentation
Expand All @@ -624,6 +626,8 @@ def get_extreme_points(
Raises:
ValueError: When the input image does not have any foreground pixel.
"""
if rand_state is None:
rand_state = np.random.random.__self__ # type: ignore
indices = np.where(img != background)
if np.size(indices[0]) == 0:
raise ValueError("get_extreme_points: no foreground object in mask!")
Expand Down
2 changes: 1 addition & 1 deletion tests/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ def make_nifti_image(array, affine=None):

def make_rand_affine(ndim: int = 3, random_state: Optional[np.random.RandomState] = None):
"""Create random affine transformation (with values == -1, 0 or 1)."""
rs = np.random if random_state is None else random_state
rs = np.random.random.__self__ if random_state is None else random_state # type: ignore

vals = rs.choice([-1, 1], size=ndim)
positions = rs.choice(range(ndim), size=ndim, replace=False)
Expand Down