Skip to content

Commit

Permalink
sync feature branch with dev (#4138)
Browse files Browse the repository at this point in the history
* update citation (#4133)

Signed-off-by: Wenqi Li <wenqil@nvidia.com>

* `ToMetaTensor` and `FromMetaTensor` transforms (#4115)

to and from meta

Co-authored-by: Richard Brown <33289025+rijobro@users.noreply.github.com>
  • Loading branch information
wyli and rijobro authored Apr 14, 2022
1 parent 5e180c6 commit 3d98c8e
Show file tree
Hide file tree
Showing 9 changed files with 342 additions and 11 deletions.
12 changes: 8 additions & 4 deletions CITATION.cff
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,15 @@ title: "MONAI: Medical Open Network for AI"
abstract: "AI Toolkit for Healthcare Imaging"
authors:
- name: "MONAI Consortium"
date-released: 2020-03-28
version: "0.6.0"
doi: "10.5281/zenodo.4323058"
date-released: 2022-02-16
version: "0.8.1"
identifiers:
- description: "This DOI represents all versions of MONAI, and will always resolve to the latest one."
type: doi
value: "10.5281/zenodo.4323058"
license: "Apache-2.0"
repository-code: "https://github.com/Project-MONAI/MONAI"
cff-version: "1.1.0"
url: "https://monai.io"
cff-version: "1.2.0"
message: "If you use this software, please cite it using these metadata."
...
15 changes: 15 additions & 0 deletions docs/source/transforms.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1842,6 +1842,21 @@ Utility (Dict)
:members:
:special-members: __call__

MetaTensor
^^^^^^^^^^

`ToMetaTensord`
"""""""""""""""
.. autoclass:: ToMetaTensord
:members:
:special-members: __call__

`FromMetaTensord`
"""""""""""""""""
.. autoclass:: FromMetaTensord
:members:
:special-members: __call__

Transform Adaptors
------------------
.. automodule:: monai.transforms.adaptors
Expand Down
5 changes: 5 additions & 0 deletions monai/data/meta_tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from __future__ import annotations

import warnings
from copy import deepcopy
from typing import Callable

import torch
Expand Down Expand Up @@ -88,6 +89,10 @@ def __init__(self, x, affine: torch.Tensor | None = None, meta: dict | None = No
self.affine = x.affine
else:
self.affine = self.get_default_affine()

# if we are creating a new MetaTensor, then deep copy attributes
if isinstance(x, torch.Tensor) and not isinstance(x, MetaTensor):
self.meta = deepcopy(self.meta)
self.affine = self.affine.to(self.device)

def _copy_attr(self, attribute: str, input_objs: list[MetaObj], default_fn: Callable, deep_copy: bool) -> None:
Expand Down
8 changes: 8 additions & 0 deletions monai/transforms/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,14 @@
from .inverse_batch_transform import BatchInverseTransform, Decollated, DecollateD, DecollateDict
from .io.array import SUPPORTED_READERS, LoadImage, SaveImage
from .io.dictionary import LoadImaged, LoadImageD, LoadImageDict, SaveImaged, SaveImageD, SaveImageDict
from .meta_utility.dictionary import (
FromMetaTensord,
FromMetaTensorD,
FromMetaTensorDict,
ToMetaTensord,
ToMetaTensorD,
ToMetaTensorDict,
)
from .nvtx import (
Mark,
Markd,
Expand Down
10 changes: 10 additions & 0 deletions monai/transforms/meta_utility/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# 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.
102 changes: 102 additions & 0 deletions monai/transforms/meta_utility/dictionary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# 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.
"""
A collection of dictionary-based wrappers for moving between MetaTensor types and dictionaries of data.
These can be used to make backwards compatible code.
Class names are ended with 'd' to denote dictionary-based transforms.
"""

from copy import deepcopy
from typing import Dict, Hashable, Mapping

from monai.config.type_definitions import NdarrayOrTensor
from monai.data.meta_tensor import MetaTensor
from monai.transforms.inverse import InvertibleTransform
from monai.transforms.transform import MapTransform
from monai.utils.enums import PostFix, TransformBackends

__all__ = [
"FromMetaTensord",
"FromMetaTensorD",
"FromMetaTensorDict",
"ToMetaTensord",
"ToMetaTensorD",
"ToMetaTensorDict",
]


class FromMetaTensord(MapTransform, InvertibleTransform):
"""
Dictionary-based transform to convert MetaTensor to a dictionary.
If input is `{"a": MetaTensor, "b": MetaTensor}`, then output will
have the form `{"a": torch.Tensor, "a_meta_dict": dict, "b": ...}`.
"""

backend = [TransformBackends.TORCH, TransformBackends.NUMPY]

def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> Dict[Hashable, NdarrayOrTensor]:
d = dict(data)
for key in self.key_iterator(d):
self.push_transform(d, key)
im: MetaTensor = d[key] # type: ignore
d.update(im.as_dict(key))
return d

def inverse(self, data: Mapping[Hashable, NdarrayOrTensor]) -> Dict[Hashable, NdarrayOrTensor]:
d = deepcopy(dict(data))
for key in self.key_iterator(d):
# check transform
_ = self.get_most_recent_transform(d, key)
# do the inverse
im, meta = d[key], d.pop(PostFix.meta(key), None)
im = MetaTensor(im, meta=meta) # type: ignore
d[key] = im
# Remove the applied transform
self.pop_transform(d, key)
return d


class ToMetaTensord(MapTransform, InvertibleTransform):
"""
Dictionary-based transform to convert a dictionary to MetaTensor.
If input is `{"a": torch.Tensor, "a_meta_dict": dict, "b": ...}`, then output will
have the form `{"a": MetaTensor, "b": MetaTensor}`.
"""

backend = [TransformBackends.TORCH, TransformBackends.NUMPY]

def __call__(self, data: Mapping[Hashable, NdarrayOrTensor]) -> Dict[Hashable, NdarrayOrTensor]:
d = dict(data)
for key in self.key_iterator(d):
self.push_transform(d, key)
im, meta = d[key], d.pop(PostFix.meta(key), None)
im = MetaTensor(im, meta=meta) # type: ignore
d[key] = im
return d

def inverse(self, data: Mapping[Hashable, NdarrayOrTensor]) -> Dict[Hashable, NdarrayOrTensor]:
d = deepcopy(dict(data))
for key in self.key_iterator(d):
# check transform
_ = self.get_most_recent_transform(d, key)
# do the inverse
im: MetaTensor = d[key] # type: ignore
d.update(im.as_dict(key))
# Remove the applied transform
self.pop_transform(d, key)
return d


FromMetaTensorD = FromMetaTensorDict = FromMetaTensord
ToMetaTensorD = ToMetaTensorDict = ToMetaTensord
18 changes: 11 additions & 7 deletions monai/utils/enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,13 +227,13 @@ class ForwardMode(Enum):
class TraceKeys:
"""Extra meta data keys used for traceable transforms."""

CLASS_NAME = "class"
ID = "id"
ORIG_SIZE = "orig_size"
EXTRA_INFO = "extra_info"
DO_TRANSFORM = "do_transforms"
KEY_SUFFIX = "_transforms"
NONE = "none"
CLASS_NAME: str = "class"
ID: str = "id"
ORIG_SIZE: str = "orig_size"
EXTRA_INFO: str = "extra_info"
DO_TRANSFORM: str = "do_transforms"
KEY_SUFFIX: str = "_transforms"
NONE: str = "none"


@deprecated(since="0.8.0", msg_suffix="use monai.utils.enums.TraceKeys instead.")
Expand Down Expand Up @@ -287,6 +287,10 @@ def meta(key: Optional[str] = None):
def orig_meta(key: Optional[str] = None):
return PostFix._get_str(key, "orig_meta_dict")

@staticmethod
def transforms(key: Optional[str] = None):
return PostFix._get_str(key, TraceKeys.KEY_SUFFIX[1:])


class TransformBackends(Enum):
"""
Expand Down
1 change: 1 addition & 0 deletions tests/test_module_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ def test_transform_api(self):
to_exclude = {"MapTransform"} # except for these transforms
to_exclude_docs = {"Decollate", "Ensemble", "Invert", "SaveClassification", "RandTorchVision"}
to_exclude_docs.update({"DeleteItems", "SelectItems", "CopyItems", "ConcatItems"})
to_exclude_docs.update({"ToMetaTensor", "FromMetaTensor"})
xforms = {
name: obj
for name, obj in monai.transforms.__dict__.items()
Expand Down
Loading

0 comments on commit 3d98c8e

Please sign in to comment.