Skip to content
Closed
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
29 changes: 9 additions & 20 deletions tests/test_affine_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,29 +133,18 @@ def test_to_norm_affine_ill(self, affine, src_size, dst_size, align_corners):

class TestAffineTransform(unittest.TestCase):

def test_affine_shift(self):
affine = torch.as_tensor([[1.0, 0.0, 0.0], [0.0, 1.0, -1.0]])
@parameterized.expand([
("shift", torch.as_tensor([[1.0, 0.0, 0.0], [0.0, 1.0, -1.0]]), [[[[0, 4, 1, 3], [0, 7, 6, 8], [0, 3, 5, 3]]]]),
("shift_1", torch.as_tensor([[1.0, 0.0, -1.0], [0.0, 1.0, -1.0]]),
[[[[0, 0, 0, 0], [0, 4, 1, 3], [0, 7, 6, 8]]]]),
("shift_2", torch.as_tensor([[1.0, 0.0, -1.0], [0.0, 1.0, 0.0]]),
[[[[0, 0, 0, 0], [4, 1, 3, 2], [7, 6, 8, 5]]]]),
])
def test_affine_transforms(self, name, affine, expected):
image = torch.as_tensor([[[[4.0, 1.0, 3.0, 2.0], [7.0, 6.0, 8.0, 5.0], [3.0, 5.0, 3.0, 6.0]]]])
out = AffineTransform(align_corners=False)(image, affine)
out = out.detach().cpu().numpy()
expected = [[[[0, 4, 1, 3], [0, 7, 6, 8], [0, 3, 5, 3]]]]
np.testing.assert_allclose(out, expected, atol=1e-5, rtol=_rtol)

def test_affine_shift_1(self):
affine = torch.as_tensor([[1.0, 0.0, -1.0], [0.0, 1.0, -1.0]])
image = torch.as_tensor([[[[4.0, 1.0, 3.0, 2.0], [7.0, 6.0, 8.0, 5.0], [3.0, 5.0, 3.0, 6.0]]]])
out = AffineTransform(align_corners=False)(image, affine)
out = out.detach().cpu().numpy()
expected = [[[[0, 0, 0, 0], [0, 4, 1, 3], [0, 7, 6, 8]]]]
np.testing.assert_allclose(out, expected, atol=1e-5, rtol=_rtol)

def test_affine_shift_2(self):
affine = torch.as_tensor([[1.0, 0.0, -1.0], [0.0, 1.0, 0.0]])
image = torch.as_tensor([[[[4.0, 1.0, 3.0, 2.0], [7.0, 6.0, 8.0, 5.0], [3.0, 5.0, 3.0, 6.0]]]])
out = AffineTransform(align_corners=False)(image, affine)
out = out.detach().cpu().numpy()
expected = [[[[0, 0, 0, 0], [4, 1, 3, 2], [7, 6, 8, 5]]]]
np.testing.assert_allclose(out, expected, atol=1e-5, rtol=_rtol)
np.testing.assert_allclose(out, expected, atol=1e-5, rtol=1e-5)

def test_zoom(self):
affine = torch.as_tensor([[1.0, 0.0, 0.0], [0.0, 2.0, 0.0]])
Expand Down
1 change: 0 additions & 1 deletion tests/test_auto3dseg.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,6 @@ def test_filename_case_analyzer(self):
for batch_data in self.dataset:
d = transform(batch_data[0])
assert DataStatsKeys.BY_CASE_IMAGE_PATH in d
assert DataStatsKeys.BY_CASE_IMAGE_PATH in d

def test_filename_case_analyzer_image_only(self):
analyzer_image = FilenameStats("image", DataStatsKeys.BY_CASE_IMAGE_PATH)
Expand Down
6 changes: 3 additions & 3 deletions tests/test_bundle_ckpt_export.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,9 @@ def test_export(self, key_in_ckpt, use_trace):
_, metadata, extra_files = load_net_with_metadata(
ts_file, more_extra_files=["inference.json", "def_args.json"]
)
self.assertTrue("schema" in metadata)
self.assertTrue("meta_file" in json.loads(extra_files["def_args.json"]))
self.assertTrue("network_def" in json.loads(extra_files["inference.json"]))
self.assertIn("schema", metadata)
self.assertIn("meta_file", json.loads(extra_files["def_args.json"]))
self.assertIn("network_def", json.loads(extra_files["inference.json"]))

@parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3])
def test_default_value(self, key_in_ckpt, use_trace):
Expand Down
12 changes: 6 additions & 6 deletions tests/test_bundle_get_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,16 +51,16 @@ class TestGetBundleData(unittest.TestCase):
def test_get_all_bundles_list(self, params):
with skip_if_downloading_fails():
output = get_all_bundles_list(**params)
self.assertTrue(isinstance(output, list))
self.assertTrue(isinstance(output[0], tuple))
self.assertTrue(len(output[0]) == 2)
self.assertIsInstance(output, list)
self.assertIsInstance(output[0], tuple)
self.assertEqual(len(output[0]), 2)

@parameterized.expand([TEST_CASE_1, TEST_CASE_5])
@skip_if_quick
def test_get_bundle_versions(self, params):
with skip_if_downloading_fails():
output = get_bundle_versions(**params)
self.assertTrue(isinstance(output, dict))
self.assertIsInstance(output, dict)
self.assertTrue("latest_version" in output and "all_versions" in output)
self.assertTrue("0.1.0" in output["all_versions"])

Expand All @@ -69,7 +69,7 @@ def test_get_bundle_versions(self, params):
def test_get_bundle_info(self, params):
with skip_if_downloading_fails():
output = get_bundle_info(**params)
self.assertTrue(isinstance(output, dict))
self.assertIsInstance(output, dict)
for key in ["id", "name", "size", "download_count", "browser_download_url"]:
self.assertTrue(key in output)

Expand All @@ -78,7 +78,7 @@ def test_get_bundle_info(self, params):
def test_get_bundle_info_monaihosting(self, params):
with skip_if_downloading_fails():
output = get_bundle_info(**params)
self.assertTrue(isinstance(output, dict))
self.assertIsInstance(output, dict)
for key in ["name", "browser_download_url"]:
self.assertTrue(key in output)

Expand Down
12 changes: 6 additions & 6 deletions tests/test_bundle_trt_export.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,9 @@ def test_trt_export(self, convert_precision, input_shape, dynamic_batch):
_, metadata, extra_files = load_net_with_metadata(
ts_file, more_extra_files=["inference.json", "def_args.json"]
)
self.assertTrue("schema" in metadata)
self.assertTrue("meta_file" in json.loads(extra_files["def_args.json"]))
self.assertTrue("network_def" in json.loads(extra_files["inference.json"]))
self.assertIn("schema", metadata)
self.assertIn("meta_file", json.loads(extra_files["def_args.json"]))
self.assertIn("network_def", json.loads(extra_files["inference.json"]))

@parameterized.expand([TEST_CASE_3, TEST_CASE_4])
@unittest.skipUnless(
Expand Down Expand Up @@ -129,9 +129,9 @@ def test_onnx_trt_export(self, convert_precision, input_shape, dynamic_batch):
_, metadata, extra_files = load_net_with_metadata(
ts_file, more_extra_files=["inference.json", "def_args.json"]
)
self.assertTrue("schema" in metadata)
self.assertTrue("meta_file" in json.loads(extra_files["def_args.json"]))
self.assertTrue("network_def" in json.loads(extra_files["inference.json"]))
self.assertIn("schema", metadata)
self.assertIn("meta_file", json.loads(extra_files["def_args.json"]))
self.assertIn("network_def", json.loads(extra_files["inference.json"]))


if __name__ == "__main__":
Expand Down
6 changes: 3 additions & 3 deletions tests/test_bundle_workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,11 +138,11 @@ def test_train_config(self, config_file):
self.assertListEqual(trainer.check_properties(), [])
# test read / write the properties
dataset = trainer.train_dataset
self.assertTrue(isinstance(dataset, Dataset))
self.assertIsInstance(dataset, Dataset)
inferer = trainer.train_inferer
self.assertTrue(isinstance(inferer, SimpleInferer))
self.assertIsInstance(inferer, SimpleInferer)
# test optional properties get
self.assertTrue(trainer.train_key_metric is None)
self.assertIsNone(trainer.train_key_metric)
trainer.train_dataset = deepcopy(dataset)
trainer.train_inferer = deepcopy(inferer)
# test optional properties set
Expand Down
8 changes: 4 additions & 4 deletions tests/test_component_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,17 +48,17 @@ def test_add2(self):
self.cs.add("test_obj2", "Test object", test_obj2)

self.assertEqual(len(self.cs), 2)
self.assertTrue("test_obj1" in self.cs)
self.assertTrue("test_obj2" in self.cs)
self.assertIn("test_obj1", self.cs)
self.assertIn("test_obj2", self.cs)

def test_add_def(self):
self.assertFalse("test_func" in self.cs)
self.assertNotIn("test_func", self.cs)

@self.cs.add_def("test_func", "Test function")
def test_func():
return 123

self.assertTrue("test_func" in self.cs)
self.assertIn("test_func", self.cs)

self.assertEqual(len(self.cs), 1)
self.assertEqual(list(self.cs), [("test_func", test_func)])
Expand Down
28 changes: 9 additions & 19 deletions tests/test_compute_f_beta.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from __future__ import annotations

import unittest
from parameterized import parameterized

import numpy as np
import torch
Expand All @@ -33,26 +34,15 @@ def test_expecting_success_and_device(self):
assert_allclose(result, torch.Tensor([0.714286]), atol=1e-6, rtol=1e-6)
np.testing.assert_equal(result.device, y_pred.device)

def test_expecting_success2(self):
metric = FBetaScore(beta=0.5)
metric(
y_pred=torch.Tensor([[1, 1, 1], [1, 1, 1], [1, 1, 1]]), y=torch.Tensor([[1, 0, 1], [0, 1, 0], [1, 0, 1]])
)
assert_allclose(metric.aggregate()[0], torch.Tensor([0.609756]), atol=1e-6, rtol=1e-6)
@parameterized.expand([
("success_beta_0_5", FBetaScore(beta=0.5), torch.Tensor([[1, 0, 1], [0, 1, 0], [1, 0, 1]]), torch.Tensor([0.609756])),
("success_beta_2", FBetaScore(beta=2), torch.Tensor([[1, 0, 1], [0, 1, 0], [1, 0, 1]]), torch.Tensor([0.862069])),
("denominator_zero", FBetaScore(beta=2), torch.Tensor([[0, 0, 0], [0, 0, 0], [0, 0, 0]]), torch.Tensor([0.0])),
])
def test_success_and_zero(self, name, metric, y, expected_score):
metric(y_pred=torch.Tensor([[1, 1, 1], [1, 1, 1], [1, 1, 1]]), y=y)
assert_allclose(metric.aggregate()[0], expected_score, atol=1e-6, rtol=1e-6)

def test_expecting_success3(self):
metric = FBetaScore(beta=2)
metric(
y_pred=torch.Tensor([[1, 1, 1], [1, 1, 1], [1, 1, 1]]), y=torch.Tensor([[1, 0, 1], [0, 1, 0], [1, 0, 1]])
)
assert_allclose(metric.aggregate()[0], torch.Tensor([0.862069]), atol=1e-6, rtol=1e-6)

def test_denominator_is_zero(self):
metric = FBetaScore(beta=2)
metric(
y_pred=torch.Tensor([[1, 1, 1], [1, 1, 1], [1, 1, 1]]), y=torch.Tensor([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
)
assert_allclose(metric.aggregate()[0], torch.Tensor([0.0]), atol=1e-6, rtol=1e-6)

def test_number_of_dimensions_less_than_2_should_raise_error(self):
metric = FBetaScore()
Expand Down
4 changes: 2 additions & 2 deletions tests/test_compute_ho_ver_maps.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,8 @@ class ComputeHoVerMapsTests(unittest.TestCase):
def test_horizontal_certical_maps(self, in_type, arguments, mask, hv_mask):
input_image = in_type(mask)
result = ComputeHoVerMaps(**arguments)(input_image)
self.assertTrue(isinstance(result, torch.Tensor))
self.assertTrue(str(result.dtype).split(".")[1] == arguments.get("dtype", "float32"))
self.assertIsInstance(result, torch.Tensor)
self.assertEqual(str(result.dtype).split(".")[1], arguments.get("dtype", "float32"))
assert_allclose(result, hv_mask, type_test="tensor")


Expand Down
4 changes: 2 additions & 2 deletions tests/test_compute_ho_ver_maps_d.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,8 @@ def test_horizontal_certical_maps(self, in_type, arguments, mask, hv_mask):
for k in mask.keys():
input_image[k] = in_type(mask[k])
result = ComputeHoVerMapsd(keys="mask", **arguments)(input_image)[hv_key]
self.assertTrue(isinstance(result, torch.Tensor))
self.assertTrue(str(result.dtype).split(".")[1] == arguments.get("dtype", "float32"))
self.assertIsInstance(result, torch.Tensor)
self.assertEqual(str(result.dtype).split(".")[1], arguments.get("dtype", "float32"))
assert_allclose(result, hv_mask[hv_key], type_test="tensor")


Expand Down
10 changes: 6 additions & 4 deletions tests/test_compute_regression_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,22 +70,24 @@ def test_shape_reduction(self):
mt = mt_fn(reduction="mean")
mt(in_tensor, in_tensor)
out_tensor = mt.aggregate()
self.assertTrue(len(out_tensor.shape) == 1)
self.assertEqual(len(out_tensor.shape), 1)

mt = mt_fn(reduction="sum")
mt(in_tensor, in_tensor)
out_tensor = mt.aggregate()
self.assertTrue(len(out_tensor.shape) == 0)
self.assertEqual(len(out_tensor.shape), 0)

mt = mt_fn(reduction="sum") # test reduction arg overriding
mt(in_tensor, in_tensor)
out_tensor = mt.aggregate(reduction="mean_channel")
self.assertTrue(len(out_tensor.shape) == 1 and out_tensor.shape[0] == batch)
self.assertEqual(len(out_tensor.shape), 1)
self.assertEqual(out_tensor.shape[0], batch)

mt = mt_fn(reduction="sum_channel")
mt(in_tensor, in_tensor)
out_tensor = mt.aggregate()
self.assertTrue(len(out_tensor.shape) == 1 and out_tensor.shape[0] == batch)
self.assertEqual(len(out_tensor.shape), 1)
self.assertEqual(out_tensor.shape[0], batch)

def test_compare_numpy(self):
set_determinism(seed=123)
Expand Down
8 changes: 4 additions & 4 deletions tests/test_concat_itemsd.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def test_tensor_values(self):
"img2": torch.tensor([[0, 1], [1, 2]], device=device),
}
result = ConcatItemsd(keys=["img1", "img2"], name="cat_img")(input_data)
self.assertTrue("cat_img" in result)
self.assertIn("cat_img", result)
result["cat_img"] += 1
assert_allclose(result["img1"], torch.tensor([[0, 1], [1, 2]], device=device))
assert_allclose(result["cat_img"], torch.tensor([[1, 2], [2, 3], [1, 2], [2, 3]], device=device))
Expand All @@ -42,8 +42,8 @@ def test_metatensor_values(self):
"img2": MetaTensor([[0, 1], [1, 2]], device=device),
}
result = ConcatItemsd(keys=["img1", "img2"], name="cat_img")(input_data)
self.assertTrue("cat_img" in result)
self.assertTrue(isinstance(result["cat_img"], MetaTensor))
self.assertIn("cat_img", result)
self.assertIsInstance(result["cat_img"], MetaTensor)
self.assertEqual(result["img1"].meta, result["cat_img"].meta)
result["cat_img"] += 1
assert_allclose(result["img1"], torch.tensor([[0, 1], [1, 2]], device=device))
Expand All @@ -52,7 +52,7 @@ def test_metatensor_values(self):
def test_numpy_values(self):
input_data = {"img1": np.array([[0, 1], [1, 2]]), "img2": np.array([[0, 1], [1, 2]])}
result = ConcatItemsd(keys=["img1", "img2"], name="cat_img")(input_data)
self.assertTrue("cat_img" in result)
self.assertIn("cat_img", result)
result["cat_img"] += 1
np.testing.assert_allclose(result["img1"], np.array([[0, 1], [1, 2]]))
np.testing.assert_allclose(result["cat_img"], np.array([[1, 2], [2, 3], [1, 2], [2, 3]]))
Expand Down
2 changes: 1 addition & 1 deletion tests/test_config_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ def test_function(self, config):
if id in ("compute", "cls_compute"):
parser[f"{id}#_mode_"] = "callable"
func = parser.get_parsed_content(id=id)
self.assertTrue(id in parser.ref_resolver.resolved_content)
self.assertIn(id, parser.ref_resolver.resolved_content)
if id == "error_func":
with self.assertRaises(TypeError):
func(1, 2)
Expand Down
16 changes: 8 additions & 8 deletions tests/test_cucim_dict_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@ class TestCuCIMDict(unittest.TestCase):
def test_tramsforms_numpy_single(self, params, input, expected):
input = {"image": input}
output = CuCIMd(keys="image", **params)(input)["image"]
self.assertTrue(output.dtype == expected.dtype)
self.assertTrue(isinstance(output, np.ndarray))
self.assertEqual(output.dtype, expected.dtype)
self.assertIsInstance(output, np.ndarray)
cp.testing.assert_allclose(output, expected)

@parameterized.expand(
Expand All @@ -98,8 +98,8 @@ def test_tramsforms_numpy_batch(self, params, input, expected):
input = {"image": input[cp.newaxis, ...]}
expected = expected[cp.newaxis, ...]
output = CuCIMd(keys="image", **params)(input)["image"]
self.assertTrue(output.dtype == expected.dtype)
self.assertTrue(isinstance(output, np.ndarray))
self.assertEqual(output.dtype, expected.dtype)
self.assertIsInstance(output, np.ndarray)
cp.testing.assert_allclose(output, expected)

@parameterized.expand(
Expand All @@ -116,8 +116,8 @@ def test_tramsforms_cupy_single(self, params, input, expected):
input = {"image": cp.asarray(input)}
expected = cp.asarray(expected)
output = CuCIMd(keys="image", **params)(input)["image"]
self.assertTrue(output.dtype == expected.dtype)
self.assertTrue(isinstance(output, cp.ndarray))
self.assertEqual(output.dtype, expected.dtype)
self.assertIsInstance(output, cp.ndarray)
cp.testing.assert_allclose(output, expected)

@parameterized.expand(
Expand All @@ -134,8 +134,8 @@ def test_tramsforms_cupy_batch(self, params, input, expected):
input = {"image": cp.asarray(input)[cp.newaxis, ...]}
expected = cp.asarray(expected)[cp.newaxis, ...]
output = CuCIMd(keys="image", **params)(input)["image"]
self.assertTrue(output.dtype == expected.dtype)
self.assertTrue(isinstance(output, cp.ndarray))
self.assertEqual(output.dtype, expected.dtype)
self.assertIsInstance(output, cp.ndarray)
cp.testing.assert_allclose(output, expected)


Expand Down
16 changes: 8 additions & 8 deletions tests/test_cucim_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,8 @@ class TestCuCIM(unittest.TestCase):
)
def test_tramsforms_numpy_single(self, params, input, expected):
output = CuCIM(**params)(input)
self.assertTrue(output.dtype == expected.dtype)
self.assertTrue(isinstance(output, np.ndarray))
self.assertEqual(output.dtype, expected.dtype)
self.assertIsInstance(output, np.ndarray)
cp.testing.assert_allclose(output, expected)

@parameterized.expand(
Expand All @@ -97,8 +97,8 @@ def test_tramsforms_numpy_batch(self, params, input, expected):
input = input[cp.newaxis, ...]
expected = expected[cp.newaxis, ...]
output = CuCIM(**params)(input)
self.assertTrue(output.dtype == expected.dtype)
self.assertTrue(isinstance(output, np.ndarray))
self.assertEqual(output.dtype, expected.dtype)
self.assertIsInstance(output, np.ndarray)
cp.testing.assert_allclose(output, expected)

@parameterized.expand(
Expand All @@ -115,8 +115,8 @@ def test_tramsforms_cupy_single(self, params, input, expected):
input = cp.asarray(input)
expected = cp.asarray(expected)
output = CuCIM(**params)(input)
self.assertTrue(output.dtype == expected.dtype)
self.assertTrue(isinstance(output, cp.ndarray))
self.assertEqual(output.dtype, expected.dtype)
self.assertIsInstance(output, cp.ndarray)
cp.testing.assert_allclose(output, expected)

@parameterized.expand(
Expand All @@ -133,8 +133,8 @@ def test_tramsforms_cupy_batch(self, params, input, expected):
input = cp.asarray(input)[cp.newaxis, ...]
expected = cp.asarray(expected)[cp.newaxis, ...]
output = CuCIM(**params)(input)
self.assertTrue(output.dtype == expected.dtype)
self.assertTrue(isinstance(output, cp.ndarray))
self.assertEqual(output.dtype, expected.dtype)
self.assertIsInstance(output, cp.ndarray)
cp.testing.assert_allclose(output, expected)


Expand Down
Loading