Skip to content

Commit 58ec5f5

Browse files
committed
Merge branch 'tmpdir_routine' of github.com:ericspod/MONAI into tmpdir_routine
2 parents 7042c77 + f2947d9 commit 58ec5f5

4 files changed

Lines changed: 36 additions & 9 deletions

File tree

monai/data/meta_tensor.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -495,7 +495,8 @@ def astype(self, dtype, device=None, *_args, **_kwargs):
495495
_kwargs: additional kwargs (currently unused).
496496
497497
Returns:
498-
data array instance
498+
``MetaTensor`` when a torch dtype is given (metadata is preserved),
499+
or ``np.ndarray`` when a numpy dtype is given.
499500
"""
500501
if isinstance(dtype, str):
501502
mod_str, *dtype = dtype.split(".", 1)
@@ -506,7 +507,7 @@ def astype(self, dtype, device=None, *_args, **_kwargs):
506507

507508
out_type: type[torch.Tensor] | type[np.ndarray] | None
508509
if mod_str == "torch":
509-
out_type = torch.Tensor
510+
out_type = type(self)
510511
elif mod_str in ("numpy", "np"):
511512
out_type = np.ndarray
512513
else:

monai/handlers/utils.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -122,15 +122,15 @@ class mean median max 5percentile 95percentile notnans
122122

123123
# add the average value of all classes to v
124124
if class_labels is None:
125-
class_labels = ["class" + str(i) for i in range(v.shape[1])]
125+
labels = ["class" + str(i) for i in range(v.shape[1])]
126126
else:
127-
class_labels = [str(i) for i in class_labels] # ensure to have a list of str
127+
labels = [str(i) for i in class_labels] # ensure to have a list of str
128128

129-
class_labels += ["mean"]
129+
labels += ["mean"]
130130
v = np.concatenate([v, np.nanmean(v, axis=1, keepdims=True)], axis=1)
131131

132132
with open(os.path.join(save_dir, f"{k}_raw.csv"), "w") as f:
133-
f.write(f"filename{deli}{deli.join(class_labels)}\n")
133+
f.write(f"filename{deli}{deli.join(labels)}\n")
134134
for i, b in enumerate(v):
135135
f.write(
136136
f"{images[i] if images is not None else str(i)}{deli}"
@@ -164,7 +164,7 @@ def _compute_op(op: str, d: np.ndarray) -> Any:
164164
with open(os.path.join(save_dir, f"{k}_summary.csv"), "w") as f:
165165
f.write(f"class{deli}{deli.join(ops)}\n")
166166
for i, c in enumerate(np.transpose(v)):
167-
f.write(f"{class_labels[i]}{deli}{deli.join([f'{_compute_op(k, c):.4f}' for k in ops])}\n")
167+
f.write(f"{labels[i]}{deli}{deli.join([f'{_compute_op(k, c):.4f}' for k in ops])}\n")
168168

169169

170170
def from_engine(keys: KeysCollection, first: bool = False) -> Callable:

tests/data/meta_tensor/test_meta_tensor.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -435,8 +435,12 @@ def test_astype(self):
435435
for np_types in ("float32", "np.float32", "numpy.float32", np.float32, float, "int", np.uint16):
436436
self.assertIsInstance(t.astype(np_types), np.ndarray)
437437
for pt_types in ("torch.float", torch.float, "torch.float64"):
438-
self.assertIsInstance(t.astype(pt_types), torch.Tensor)
439-
self.assertIsInstance(t.astype("torch.float", device="cpu"), torch.Tensor)
438+
result = t.astype(pt_types)
439+
self.assertIsInstance(result, MetaTensor)
440+
self.assertEqual(result.meta.get("fname"), "filename")
441+
result = t.astype("torch.float", device="cpu")
442+
self.assertIsInstance(result, MetaTensor)
443+
self.assertEqual(result.meta.get("fname"), "filename")
440444

441445
def test_transforms(self):
442446
key = "im"

tests/handlers/test_write_metrics_reports.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,28 @@ def test_content(self):
6363
self.assertTrue(os.path.exists(os.path.join(tempdir, "metric4_raw.csv")))
6464
self.assertTrue(os.path.exists(os.path.join(tempdir, "metric4_summary.csv")))
6565

66+
def test_multi_metric_details_headers(self):
67+
with tempfile.TemporaryDirectory() as tempdir:
68+
write_metrics_reports(
69+
save_dir=Path(tempdir),
70+
images=["img1", "img2"],
71+
metrics=None,
72+
metric_details={
73+
"m1": torch.tensor([[1, 2, 3], [4, 5, 6]]),
74+
"m2": torch.tensor([[7, 8], [9, 10]]),
75+
"m3": torch.tensor([[11, 12, 13, 14], [15, 16, 17, 18]]),
76+
},
77+
summary_ops=None,
78+
deli=",",
79+
output_type="csv",
80+
)
81+
for name, nclass in [("m1", 3), ("m2", 2), ("m3", 4)]:
82+
path = os.path.join(tempdir, f"{name}_raw.csv")
83+
self.assertTrue(os.path.exists(path))
84+
with open(path) as f:
85+
header = f.readline().strip().split(",")
86+
self.assertEqual(header, ["filename"] + [f"class{i}" for i in range(nclass)] + ["mean"])
87+
6688

6789
if __name__ == "__main__":
6890
unittest.main()

0 commit comments

Comments
 (0)