Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cleaning up some very old and now obsolete infrastructure #8113

Merged
merged 11 commits into from
Sep 27, 2024
7 changes: 0 additions & 7 deletions monai/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,6 @@ def filter(self, record):
category=RuntimeWarning,
)

from .utils.module import load_submodules # noqa: E402

# handlers_* have some external decorators the users may not have installed
# *.so files and folder "_C" may not exist when the cpp extensions are not compiled
excludes = "|".join(
ericspod marked this conversation as resolved.
Show resolved Hide resolved
Expand All @@ -96,11 +94,6 @@ def filter(self, record):
]
)

# load directory modules only, skip loading individual files
load_submodules(sys.modules[__name__], False, exclude_pattern=excludes)

# load all modules, this will trigger all export decorations
load_submodules(sys.modules[__name__], True, exclude_pattern=excludes)

__all__ = [
"apps",
Expand Down
3 changes: 1 addition & 2 deletions monai/networks/nets/hovernet.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
from monai.networks.layers.factories import Conv, Dropout
from monai.networks.layers.utils import get_act_layer, get_norm_layer
from monai.utils.enums import HoVerNetBranch, HoVerNetMode, InterpolateMode, UpsampleMode
from monai.utils.module import export, look_up_option
from monai.utils.module import look_up_option

__all__ = ["HoVerNet", "Hovernet", "HoVernet", "HoVerNet"]

Expand Down Expand Up @@ -409,7 +409,6 @@ def forward(self, xin: torch.Tensor, short_cuts: list[torch.Tensor]) -> torch.Te
return x


@export("monai.networks.nets")
class HoVerNet(nn.Module):
"""HoVerNet model

Expand Down
3 changes: 0 additions & 3 deletions monai/networks/nets/unet.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,10 @@
from monai.networks.blocks.convolutions import Convolution, ResidualUnit
from monai.networks.layers.factories import Act, Norm
from monai.networks.layers.simplelayers import SkipConnection
from monai.utils import alias, export

__all__ = ["UNet", "Unet"]


@export("monai.networks.nets")
@alias("Unet")
class UNet(nn.Module):
"""
Enhanced version of UNet which has residual units implemented with the ResidualUnit class.
Expand Down
5 changes: 0 additions & 5 deletions monai/networks/nets/voxelmorph.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,10 @@
from monai.networks.blocks.upsample import UpSample
from monai.networks.blocks.warp import DVF2DDF, Warp
from monai.networks.layers.simplelayers import SkipConnection
from monai.utils import alias, export

__all__ = ["VoxelMorphUNet", "voxelmorphunet", "VoxelMorph", "voxelmorph"]


@export("monai.networks.nets")
@alias("voxelmorphunet")
class VoxelMorphUNet(nn.Module):
"""
The backbone network used in VoxelMorph. See :py:class:`monai.networks.nets.VoxelMorph` for more details.
Expand Down Expand Up @@ -340,8 +337,6 @@ def forward(self, concatenated_pairs: torch.Tensor) -> torch.Tensor:
voxelmorphunet = VoxelMorphUNet


@export("monai.networks.nets")
@alias("voxelmorph")
class VoxelMorph(nn.Module):
"""
A re-implementation of VoxelMorph framework for medical image registration as described in
Expand Down
4 changes: 0 additions & 4 deletions monai/transforms/adaptors.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,12 +125,10 @@ def __call__(self, img, seg):

from typing import Callable

from monai.utils import export as _monai_export

__all__ = ["adaptor", "apply_alias", "to_kwargs", "FunctionSignature"]


@_monai_export("monai.transforms")
def adaptor(function, outputs, inputs=None):

def must_be_types_or_none(variable_name, variable, types):
Expand Down Expand Up @@ -215,7 +213,6 @@ def _inner(ditems):
return _inner


@_monai_export("monai.transforms")
def apply_alias(fn, name_map):

def _inner(data):
Expand All @@ -236,7 +233,6 @@ def _inner(data):
return _inner


@_monai_export("monai.transforms")
def to_kwargs(fn):

def _inner(data):
Expand Down
4 changes: 1 addition & 3 deletions monai/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from __future__ import annotations

# have to explicitly bring these in here to resolve circular import issues
from .aliases import alias, resolve_name

from .component_store import ComponentStore
from .decorators import MethodReplacer, RestartGenerator
from .deprecate_utils import DeprecatedError, deprecated, deprecated_arg, deprecated_arg_default
Expand Down Expand Up @@ -109,12 +109,10 @@
allow_missing_reference,
damerau_levenshtein_distance,
exact_version,
export,
get_full_type_name,
get_package_version,
get_torch_version_tuple,
instantiate,
load_submodules,
look_up_option,
min_version,
optional_import,
Expand Down
103 changes: 0 additions & 103 deletions monai/utils/aliases.py

This file was deleted.

60 changes: 1 addition & 59 deletions monai/utils/module.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,13 @@
import os
import pdb
import re
import sys
import warnings
from collections.abc import Callable, Collection, Hashable, Mapping
from functools import partial, wraps
from importlib import import_module
from pkgutil import walk_packages
from pydoc import locate
from re import match
from types import FunctionType, ModuleType
from types import FunctionType
from typing import Any, Iterable, cast

import torch
Expand All @@ -43,13 +41,11 @@
"InvalidPyTorchVersionError",
"OptionalImportError",
"exact_version",
"export",
"damerau_levenshtein_distance",
"look_up_option",
"min_version",
"optional_import",
"require_pkg",
"load_submodules",
"instantiate",
"get_full_type_name",
"get_package_version",
Expand Down Expand Up @@ -172,60 +168,6 @@ def damerau_levenshtein_distance(s1: str, s2: str) -> int:
return d[string_1_length - 1, string_2_length - 1]


def export(modname):
"""
Make the decorated object a member of the named module. This will also add the object under its aliases if it has
a `__aliases__` member, thus this decorator should be before the `alias` decorator to pick up those names. Alias
names which conflict with package names or existing members will be ignored.
"""

def _inner(obj):
mod = import_module(modname)
if not hasattr(mod, obj.__name__):
setattr(mod, obj.__name__, obj)

# add the aliases for `obj` to the target module
for alias in getattr(obj, "__aliases__", ()):
if not hasattr(mod, alias):
setattr(mod, alias, obj)

return obj

return _inner


def load_submodules(
ericspod marked this conversation as resolved.
Show resolved Hide resolved
basemod: ModuleType, load_all: bool = True, exclude_pattern: str = "(.*[tT]est.*)|(_.*)"
) -> tuple[list[ModuleType], list[str]]:
"""
Traverse the source of the module structure starting with module `basemod`, loading all packages plus all files if
`load_all` is True, excluding anything whose name matches `exclude_pattern`.
"""
submodules = []
err_mod: list[str] = []
for importer, name, is_pkg in walk_packages(
basemod.__path__, prefix=basemod.__name__ + ".", onerror=err_mod.append
):
if (is_pkg or load_all) and name not in sys.modules and match(exclude_pattern, name) is None:
try:
mod = import_module(name)
mod_spec = importer.find_spec(name) # type: ignore
if mod_spec and mod_spec.loader:
loader = mod_spec.loader
loader.exec_module(mod)
submodules.append(mod)
except OptionalImportError:
pass # could not import the optional deps., they are ignored
except ImportError as e:
msg = (
"\nMultiple versions of MONAI may have been installed?\n"
"Please see the installation guide: https://docs.monai.io/en/stable/installation.html\n"
) # issue project-monai/monai#5193
raise type(e)(f"{e}\n{msg}").with_traceback(e.__traceback__) from e # raise with modified message

return submodules, err_mod


def instantiate(__path: str, __mode: str, **kwargs: Any) -> Any:
"""
Create an object instance or call a callable object from a class or function represented by ``_path``.
Expand Down
6 changes: 0 additions & 6 deletions tests/min_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,12 +232,6 @@ def run_testsuit():


if __name__ == "__main__":
# testing import submodules
from monai.utils.module import load_submodules

_, err_mod = load_submodules(sys.modules["monai"], True)
assert not err_mod, f"err_mod={err_mod} not empty"

# testing all modules
test_runner = unittest.TextTestRunner(stream=sys.stdout, verbosity=2)
result = test_runner.run(run_testsuit())
Expand Down
Loading