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/apps/pathology/transforms/post/dictionary.py
Original file line number Diff line number Diff line change
Expand Up @@ -536,7 +536,7 @@ def __call__(self, data):

for k in [self.instance_info_key, self.instance_map_key]:
if k in d:
raise ValueError("The output key ['{k}'] already exists in the input dictionary!")
raise ValueError(f"The output key ['{k}'] already exists in the input dictionary!")

d[self.instance_info_key], d[self.instance_map_key] = self.instance_map_post_process(
d[self.nuclear_prediction_key], d[self.hover_map_key]
Expand Down Expand Up @@ -590,7 +590,7 @@ def __call__(self, data):
)
if self.return_type_map:
if self.type_map_key in d:
raise ValueError("The output key ['{self.type_map_key}'] already exists in the input dictionary!")
raise ValueError(f"The output key ['{self.type_map_key}'] already exists in the input dictionary!")
d[self.type_map_key] = type_map

return d
Expand Down
2 changes: 1 addition & 1 deletion monai/data/synthetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ def create_test_image_3d(
if rad_max <= rad_min:
raise ValueError(f"`rad_min` {rad_min} should be less than `rad_max` {rad_max}.")
if rad_min < 1:
raise ValueError("f`rad_min` {rad_min} should be no less than 1.")
raise ValueError(f"`rad_min` {rad_min} should be no less than 1.")
min_size = min(height, width, depth)
if min_size <= 2 * rad_max:
raise ValueError(f"the minimal size {min_size} of the image should be larger than `2 * rad_max` 2x{rad_max}.")
Expand Down
4 changes: 2 additions & 2 deletions monai/inferers/inferer.py
Original file line number Diff line number Diff line change
Expand Up @@ -1987,8 +1987,8 @@ def sample( # type: ignore[override]
and autoencoder_model.decoder.label_nc != diffusion_model.label_nc
):
raise ValueError(
"If both autoencoder_model and diffusion_model implement SPADE, the number of semantic"
"labels for each must be compatible. Got {autoencoder_model.decoder.label_nc} and {diffusion_model.label_nc}"
"If both autoencoder_model and diffusion_model implement SPADE, the number of semantic "
f"labels for each must be compatible. Got {autoencoder_model.decoder.label_nc} and {diffusion_model.label_nc}"
)

if cn_cond.shape[2:] != input_noise.shape[2:]:
Expand Down
2 changes: 1 addition & 1 deletion monai/networks/blocks/pos_embed_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ def build_sincos_position_embedding(
dim=1,
)[None, :, :]
else:
raise NotImplementedError("Spatial Dimension Size {spatial_dims} Not Implemented!")
raise NotImplementedError(f"Spatial Dimension Size {spatial_dims} Not Implemented!")

pos_embed = nn.Parameter(pos_emb)
pos_embed.requires_grad = False
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,12 @@ def test_value(self, in_type, test_data, kwargs, expected_info, expected_map):
# instance map
assert_allclose(outputs[inst_map_key], expected_map, type_test=False)

def test_existing_output_key(self):
"""Check that an existing output key raises an error naming that key."""
input = {HoVerNetBranch.NP.value: image.astype(float), "instance_map": image}
with self.assertRaisesRegex(ValueError, r"\['instance_map'\] already exists"):
HoVerNetInstanceMapPostProcessingd()(input)


if __name__ == "__main__":
unittest.main()
2 changes: 2 additions & 0 deletions tests/data/test_synthetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ def test_ill_radius(self):
img, seg = create_test_image_3d(32, 32, 32, rad_max=10, rad_min=11)
with self.assertRaisesRegex(ValueError, ""):
img, seg = create_test_image_2d(32, 32, rad_max=10, rad_min=0)
with self.assertRaisesRegex(ValueError, "`rad_min` 0 should be no less than 1"):
img, seg = create_test_image_3d(32, 32, 32, rad_max=10, rad_min=0)


if __name__ == "__main__":
Expand Down
50 changes: 50 additions & 0 deletions tests/inferers/test_controlnet_inferers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1501,6 +1501,56 @@ def test_incompatible_spade_setup(self):
seg=input_seg,
)

@skipUnless(has_einops, "Requires einops")
def test_sample_spade_label_nc_mismatch(self):
"""Check that mismatched SPADE ``label_nc`` values raise an error reporting both values."""
stage_1 = SPADEAutoencoderKL(
spatial_dims=2,
in_channels=1,
out_channels=1,
channels=(4, 4),
latent_channels=3,
attention_levels=[False, False],
num_res_blocks=1,
norm_num_groups=4,
label_nc=5,
)
stage_2 = SPADEDiffusionModelUNet(
spatial_dims=2,
in_channels=3,
out_channels=3,
channels=[4, 4],
norm_num_groups=4,
attention_levels=[False, False],
num_res_blocks=1,
num_head_channels=4,
label_nc=3,
)
controlnet = ControlNet(
spatial_dims=2,
in_channels=3,
channels=[4, 4],
attention_levels=[False, False],
num_res_blocks=1,
norm_num_groups=4,
num_head_channels=4,
conditioning_embedding_num_channels=[16],
conditioning_embedding_in_channels=1,
)
scheduler = DDPMScheduler(num_train_timesteps=10)
inferer = ControlNetLatentDiffusionInferer(scheduler=scheduler, scale_factor=1.0)
scheduler.set_timesteps(num_inference_steps=10)
with self.assertRaisesRegex(ValueError, "number of semantic labels .* Got 5 and 3"):
inferer.sample(
input_noise=torch.randn(1, 3, 4, 4),
autoencoder_model=stage_1,
diffusion_model=stage_2,
scheduler=scheduler,
seg=torch.randn(1, 5, 8, 8),
controlnet=controlnet,
cn_cond=torch.randn(1, 1, 8, 8),
)


if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,18 @@ def test_value(self, in_type, test_data, kwargs, expected):
else:
assert_allclose(outputs["type_map"], expected[2], type_test=False)

def test_existing_type_map_key(self):
"""Check that an existing ``type_map_key`` raises an error naming that key."""
input = {
HoVerNetBranch.NP.value: image.astype(float),
HoVerNetBranch.HV.value: ComputeHoVerMaps()(image.astype(int)),
HoVerNetBranch.NC.value: image,
}
outputs = HoVerNetInstanceMapPostProcessingd()(input)
outputs["custom_type_map"] = image
with self.assertRaisesRegex(ValueError, r"\['custom_type_map'\] already exists"):
HoVerNetNuclearTypePostProcessingd(type_map_key="custom_type_map")(outputs)


if __name__ == "__main__":
unittest.main()
29 changes: 29 additions & 0 deletions tests/networks/blocks/test_pos_embed_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Copyright (c) MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import annotations

import unittest

from monai.networks.blocks.pos_embed_utils import build_sincos_position_embedding


class TestBuildSincosPositionEmbedding(unittest.TestCase):
"""Tests for build_sincos_position_embedding."""

def test_unsupported_spatial_dims(self):
"""Check that an unsupported spatial_dims raises an error reporting the value."""
with self.assertRaisesRegex(NotImplementedError, "Spatial Dimension Size 4 Not Implemented"):
build_sincos_position_embedding(grid_size=[2, 2, 2, 2], embed_dim=8, spatial_dims=4)


if __name__ == "__main__":
unittest.main()
Loading