Ejemplo n.º 1
0
def LoadModule(name, namespace=None):
    """This function causes a SWIG module to be loaded into memory after its
    dependencies are satisfied. Information about the templates defined therein
    is looked up from a config file, and PyTemplate instances for each are
    created. These template instances are placed in a module with the given
    name that is either looked up from sys.modules or created and placed there
    if it does not already exist.
    Optionally, a 'namespace' parameter can be provided. If it is provided,
    this namespace will be updated with the new template instantiations.
    The raw classes loaded from the named module's SWIG interface are placed in
    a 'swig' sub-module. If the namespace parameter is provided, this
    information will be placed in a sub-module named 'swig' therein as well.
    This later submodule will be created if it does not already exist."""

    # find the module's name in sys.modules, or create a new module so named
    this_module = sys.modules.setdefault(name, types.ModuleType(name))

    # if this library and it's template instantiations have already been loaded
    # into sys.modules, bail out after loading the defined symbols into
    # 'namespace'
    if hasattr(this_module, '__templates_loaded'):
        if namespace is not None:
            swig = namespace.setdefault('swig', types.ModuleType('swig'))
            swig.__dict__.update(this_module.swig.__dict__)

            # don't worry about overwriting the symbols in namespace -- any
            # common symbols should be of type itkTemplate, which is a
            # singleton type. That is, they are all identical, so replacing one
            # with the other isn't a problem.
            for k, v in this_module.__dict__.items():
                if not (k.startswith('_') or k == 'swig'):
                    namespace[k] = v
        return

    # We're definitely going to load the templates. We set templates_loaded
    # here instead of at the end of the file to protect against cyclical
    # dependencies that could kill the recursive lookup below.
    this_module.__templates_loaded = True

    # Now, we definitely need to load the template instantiations from the
    # named module, and possibly also load the underlying SWIG module. Before
    # we can load the template instantiations of this module, we need to load
    # those of the modules on which this one depends. Ditto for the SWIG
    # modules.
    # So, we recursively satisfy the dependencies of named module and create
    # the template instantiations.
    # Dependencies are looked up from the auto-generated configuration files,
    # via the module_data instance defined at the bottom of this file, which
    # knows how to find those configuration files.
    data = module_data[name]
    if data:
        deps = sorted(data['depends'])
        for dep in deps:
            LoadModule(dep, namespace)

    if itkConfig.ImportCallback:
        itkConfig.ImportCallback(name, 0)

    # SWIG-generated modules have 'Python' appended. Only load the SWIG module
    # if we haven't already.
    swigModuleName = name + "Python"
    loader = LibraryLoader()
    if not swigModuleName in sys.modules:
        module = loader.load(swigModuleName)

    # OK, now the modules on which this one depends are loaded and
    # template-instantiated, and the SWIG module for this one is also loaded.
    # We're going to put the things we load and create in two places: the
    # optional 'namespace' parameter, and the this_module variable's namespace.

    # make a new 'swig' sub-module for this_module. Also look up or create a
    # different 'swig' module for 'namespace'. Since 'namespace' may be used to
    # collect symbols from multiple different ITK modules, we don't want to
    # stomp on an existing 'swig' module, nor do we want to share 'swig'
    # modules between this_module and namespace.

    this_module.swig = types.ModuleType('swig')

    if namespace is not None:
        swig = namespace.setdefault('swig', types.ModuleType('swig'))

    for k, v in module.__dict__.items():
        if not k.startswith('__'):
            setattr(this_module.swig, k, v)
            if namespace is not None:
                setattr(swig, k, v)

    data = module_data[name]
    if data:
        for template in data['templates']:
            if len(template) == 5:
                # This is a template description
                pyClassName, cppClassName, swigClassName, class_in_module, \
                    templateParams = template
                # It doesn't matter if an itkTemplate for this class name
                # already exists since every instance of itkTemplate with the
                # same name shares the same state. So we just make a new
                # instance and add the new templates.
                templateContainer = itkTemplate.itkTemplate(cppClassName)
                try:
                    templateContainer.__add__(templateParams,
                                              getattr(module, swigClassName))
                    setattr(this_module, pyClassName, templateContainer)
                    if namespace is not None:
                        curval = namespace.get(pyClassName)
                        if curval is not None and curval != templateContainer:
                            DebugPrintError("Namespace already has a value for"
                                            " %s, which is not an itkTemplate"
                                            "instance for class %s. "
                                            "Overwriting old value." %
                                            (pyClassName, cppClassName))
                        namespace[pyClassName] = templateContainer
                except Exception as e:
                    DebugPrintError("%s not loaded from module %s because of "
                                    "exception:\n %s" %
                                    (swigClassName, name, e))

            else:
                # this is a description of a non-templated class
                # It may have 3 or 4 arguments, the last one can be a boolean value
                if len(template) == 4:
                    pyClassName, cppClassName, swigClassName, class_in_module = \
                        template
                else:
                    pyClassName, cppClassName, swigClassName = template
                try:
                    swigClass = getattr(module, swigClassName)
                    itkTemplate.registerNoTpl(cppClassName, swigClass)
                    setattr(this_module, pyClassName, swigClass)
                    if namespace is not None:
                        curval = namespace.get(pyClassName)
                        if curval is not None and curval != swigClass:
                            DebugPrintError("Namespace already has a value for"
                                            " %s, which is not class %s. "
                                            "Overwriting old value." %
                                            (pyClassName, cppClassName))
                        namespace[pyClassName] = swigClass
                except Exception as e:
                    DebugPrintError("%s not found in module %s because of "
                                    "exception:\n %s" %
                                    (swigClassName, name, e))
        if 'snake_case_functions' in data:
            for snakeCaseFunction in data['snake_case_functions']:
                namespace[snakeCaseFunction] = getattr(module,
                                                       snakeCaseFunction)
                init_name = snakeCaseFunction + "_init_docstring"
                init_function = getattr(module, init_name)
                try:
                    init_function()
                except AttributeError:
                    pass

    if itkConfig.ImportCallback:
        itkConfig.ImportCallback(name, 1)
Ejemplo n.º 2
0
def LoadModule(name, namespace=None):
    """This function causes a SWIG module to be loaded into memory after its dependencies
  are satisfied. Information about the templates defined therein is looked up from 
  a config file, and PyTemplate instances for each are created. These template 
  instances are placed in a module with the given name that is either looked up 
  from sys.modules or created and placed there if it does not already exist.
  Optionally, a 'namespace' parameter can be provided. If it is provided, this
  namespace will be updated with the new template instantiations.
  The raw classes loaded from the named module's SWIG interface are placed in a 
  'swig' sub-module. If the namespace parameter is provided, this information will
  be placed in a sub-module named 'swig' therein as well. This latter submodule
  will be created if it does not already exist."""

    # find the module's name in sys.modules, or create a new module so named
    this_module = sys.modules.setdefault(name, imp.new_module(name))

    # if this library and it's template instantiations have already been loaded
    # into sys.modules, bail out after loading the defined symbols into 'namespace'
    if hasattr(this_module, '__templates_loaded'):
        if namespace is not None:
            swig = namespace.setdefault('swig', imp.new_module('swig'))
            swig.__dict__.update(this_module.swig.__dict__)

            # don't worry about overwriting the symbols in namespace -- any common
            # symbols should be of type itkTemplate, which is a singleton type. That
            # is, they are all identical, so replacing one with the other isn't a
            # problem.
            for k, v in this_module.__dict__.items():
                if not (k.startswith('_') or k == 'swig'): namespace[k] = v
        return

    # We're definitely going to load the templates. We set templates_loaded here
    # instead of at the end of the file to protect against cyclical dependencies
    # that could kill the recursive lookup below.
    this_module.__templates_loaded = True

    # For external projects :
    # If this_module name (variable name) is in the module_data dictionnary, then
    # this_module is an installed module (or a previously loaded module).
    # Otherwise, it may come from an external project. In this case, we must
    # search the Configuration/<name>Config.py file of this project.
    try:
        module_data[name]
    except:
        file = inspect.getfile(this_module)
        path = os.path.dirname(file)

        data = {}
        try:
            # for a linux tree
            execfile(os.path.join(path, 'Configuration', name + 'Config.py'),
                     data)
        except:
            try:
                # for a windows tree
                execfile(
                    os.path.join(path, '..', 'Configuration',
                                 name + 'Config.py'), data)
            except:
                data = None
        if (data):
            module_data[name] = data

    # Now, we we definitely need to load the template instantiations from the
    # named module, and possibly also load the underlying SWIG module. Before we
    # can load the template instantiations of this module, we need to load those
    # of the modules on which this one depends. Ditto for the SWIG modules.
    # So, we recursively satisfy the dependencies of named module and create the
    # template instantiations.
    # Dependencies are looked up from the auto-generated configuration files, via
    # the module_data instance defined at the bottom of this file, which knows how
    # to find those configuration files.
    data = module_data[name]
    if data:
        deps = list(data['depends'])
        deps.sort()
        for dep in deps:
            LoadModule(dep, namespace)

    if itkConfig.ImportCallback: itkConfig.ImportCallback(name, 0)

    # SWIG-generated modules have 'Python' appended. Only load the SWIG module if
    # we haven't already.
    swigModuleName = name + "Python"
    loader = LibraryLoader()
    if not swigModuleName in sys.modules: module = loader.load(swigModuleName)

    # OK, now the modules on which this one depends are loaded and template-instantiated,
    # and the SWIG module for this one is also loaded.
    # We're going to put the things we load and create in two places: the optional
    # 'namespace' parameter, and the this_module variable's namespace.

    # make a new 'swig' sub-module for this_module. Also look up or create a
    # different 'swig' module for 'namespace'. Since 'namespace' may be used to
    # collect symbols from multiple different ITK modules, we don't want to
    # stomp on an existing 'swig' module, nor do we want to share 'swig' modules
    # between this_module and namespace.

    this_module.swig = imp.new_module('swig')
    if namespace is not None:
        swig = namespace.setdefault('swig', imp.new_module('swig'))
    for k, v in module.__dict__.items():
        if not k.startswith('__'): setattr(this_module.swig, k, v)
        if namespace is not None and not k.startswith('__'):
            setattr(swig, k, v)

    data = module_data[name]
    if data:
        for template in data['templates']:
            if len(template) == 4:
                # this is a template description
                pyClassName, cppClassName, swigClassName, templateParams = template
                # It doesn't matter if an itkTemplate for this class name already exists
                # since every instance of itkTemplate with the same name shares the same
                # state. So we just make a new instance and add the new templates.
                templateContainer = itkTemplate.itkTemplate(cppClassName)
                try:
                    templateContainer.__add__(templateParams,
                                              getattr(module, swigClassName))
                except Exception, e:
                    DebugPrintError(
                        "%s not loaded from module %s because of exception:\n %s"
                        % (swigClassName, name, e))
                setattr(this_module, pyClassName, templateContainer)
                if namespace is not None:
                    current_value = namespace.get(pyClassName)
                    if current_value != None and current_value != templateContainer:
                        DebugPrintError(
                            "Namespace already has a value for %s, which is not an itkTemplate instance for class %s. Overwriting old value."
                            % (pyClassName, cppClassName))
                    namespace[pyClassName] = templateContainer

            else:
                # this is a description of a non-templated class
                pyClassName, cppClassName, swigClassName = template
                try:
                    swigClass = getattr(module, swigClassName)
                except Exception, e:
                    DebugPrintError(
                        "%s not found in module %s because of exception:\n %s"
                        % (swigClassName, name, e))
                itkTemplate.registerNoTpl(cppClassName, swigClass)
                setattr(this_module, pyClassName, swigClass)
                if namespace is not None:
                    current_value = namespace.get(pyClassName)
                    if current_value != None and current_value != swigClass:
                        DebugPrintError(
                            "Namespace already has a value for %s, which is not class %s. Overwriting old value."
                            % (pyClassName, cppClassName))
                    namespace[pyClassName] = swigClass
Ejemplo n.º 3
0
def itk_load_swig_module(name: str, namespace=None):
    """This function causes a SWIG module to be loaded into memory after its
    dependencies are satisfied. Information about the templates defined therein
    is looked up from a config file, and PyTemplate instances for each are
    created. These template_feature instances are placed in a module with the given
    name that is either looked up from sys.modules or created and placed there
    if it does not already exist.

    Optionally, a 'namespace' parameter can be provided. If it is provided,
    this namespace will be updated with the new template_feature instantiations.

    The raw classes loaded from the named module's SWIG interface are placed in
    a 'swig' sub-module. If the namespace parameter is provided, this
    information will be placed in a sub-module named 'swig' therein as well.
    This later submodule will be created if it does not already exist."""

    swig_module_name: str = f"itk.{name}Python"
    # find the module's name in sys.modules, or create a new module so named
    this_module = sys.modules.setdefault(swig_module_name, create_itk_module(name))

    # If this library and its template_feature instantiations have already been loaded
    # into sys.modules, bail out after loading the defined symbols into
    # 'namespace'
    if hasattr(this_module, "__templates_loaded"):
        if namespace is not None:
            swig = namespace.setdefault("swig", {})
            if hasattr(this_module, "swig"):
                swig.update(this_module.swig)

            # don't worry about overwriting the symbols in namespace -- any
            # common symbols should be of type itkTemplate, which is a
            # singleton type. That is, they are all identical, so replacing one
            # with the other isn't a problem.
            for k, v in this_module.__dict__.items():
                if not (k.startswith("_") or k.startswith("itk") or k == "swig"):
                    namespace[k] = v
        return

    # Before we can load the template_feature instantiations of this module,
    # we need to load those of the modules on which this one depends. Ditto
    # for the SWIG modules.
    # So, we recursively satisfy the dependencies of named module and create
    # the dependency template_feature instantiations.
    # Dependencies are looked up from the auto-generated configuration files,
    # via the itk_base_global_module_data instance defined at the bottom of this file, which
    # knows how to find those configuration files.
    l_data = itk_base_global_module_data[name]
    if l_data:
        deps = l_data.get_module_dependencies()
        for dep in deps:
            itk_load_swig_module(dep, namespace)

    # It is possible that template_feature instantiations from this module
    # were loaded as a side effect of dependency loading. For instance,
    # if this module defines a factory override for a base class in a
    # dependency module, that module will load and then immediately load
    # this module to ensure overrides are available.
    # We check whether this module and its template_feature instantiations have
    # already been loaded into sys.modules. If so we can copy into 'namespace'
    # and then exit early with success.
    this_module = sys.modules.setdefault(swig_module_name, create_itk_module(name))
    if hasattr(this_module, "__templates_loaded"):
        if namespace is not None:
            swig = namespace.setdefault("swig", {})
            if hasattr(this_module, "swig"):
                swig.update(this_module.swig)

            # don't worry about overwriting the symbols in namespace -- any
            # common symbols should be of type itkTemplate, which is a
            # singleton type. That is, they are all identical, so replacing one
            # with the other isn't a problem.
            for k, v in this_module.__dict__.items():
                if not (k.startswith("_") or k.startswith("itk") or k == "swig"):
                    namespace[k] = v
        return

    # All actions after this point should execute exactly once to properly load in
    # templates and factories.

    # Indicate that we are proceeding with loading templates for this module
    if itkConfig.ImportCallback:
        itkConfig.ImportCallback(name, 0)

    # SWIG-generated modules have 'Python' appended. Only load the SWIG module
    # if we haven't already.
    loader = LibraryLoader()
    l_module = loader.load(swig_module_name)

    # OK, now the modules on which this one depends are loaded and
    # template_feature-instantiated, and the SWIG module for this one is also loaded.
    # We're going to put the things we load and create in two places: the
    # optional 'namespace' parameter, and the this_module variable's namespace.

    # Populate the 'swig' sub-module namespace for this_module. Also look up or create a
    # different 'swig' namespace for 'namespace'. Since 'namespace' may be used to
    # collect symbols from multiple different ITK modules, we don't want to
    # stomp on an existing 'swig' namespace, nor do we want to share 'swig'
    # namespaces between this_module and namespace.

    if namespace is None:
        for k, v in l_module.__dict__.items():
            if not (k.startswith("__") or k.startswith("itk")):
                this_module.swig[k] = v
    else:
        swig = namespace.setdefault("swig", {})
        for k, v in l_module.__dict__.items():
            if not (k.startswith("__") or k.startswith("itk")):
                this_module.swig[k] = v
                swig[k] = v

    l_data: ITKModuleInfo = itk_base_global_module_data[name]
    for template_feature in l_data.get_all_template_features():
        if template_feature.is_itk_class():
            # Get the attribute associated with the class name if it exists,
            # otherwise make a new templated class
            # template_container =  this_module.'py_class_name'
            template_container = getattr(
                this_module,
                template_feature.get_python_class_name(),
                # Create a new template_container if not already found
                itkTemplate(template_feature.get_cpp_class_name()),
            )

            try:
                template_container.__add__(
                    template_feature.get_template_parameters(),
                    getattr(l_module, template_feature.get_swig_class_name()),
                )
                # Now set the updated template_container to this_module
                setattr(
                    this_module,
                    template_feature.get_python_class_name(),
                    template_container,
                )
                if namespace is not None:
                    current_value = namespace.get(
                        template_feature.get_python_class_name()
                    )
                    if (
                        current_value is not None
                        and current_value != template_container
                    ):
                        debug_print_error(
                            f"Namespace already has a value for "
                            f"{template_feature.get_python_class_name()}, which is not an itkTemplate "
                            f"instance for class {template_feature.get_cpp_class_name()}. "
                            f"Overwriting old value."
                        )
                    namespace[
                        template_feature.get_python_class_name()
                    ] = template_container
            except Exception as e:
                debug_print_error(
                    f"{template_feature.get_swig_class_name()} not loaded from module {name} because of "
                    f"exception:\n {e}"
                )
                pass

        else:
            # this is a description of a non-templated class
            try:
                swig_class = getattr(l_module, template_feature.get_swig_class_name())
                itkTemplate.registerNoTpl(
                    template_feature.get_cpp_class_name(), swig_class
                )
                setattr(
                    this_module, template_feature.get_python_class_name(), swig_class
                )
                if namespace is not None:
                    current_value = namespace.get(
                        template_feature.get_python_class_name()
                    )
                    if current_value is not None and current_value != swig_class:
                        debug_print_error(
                            f"Namespace already has a value for"
                            f" {template_feature.get_python_class_name()}, which is not class {template_feature.get_cpp_class_name()}. "
                            f"Overwriting old value."
                        )
                    namespace[template_feature.get_python_class_name()] = swig_class
            except Exception as e:
                debug_print_error(
                    f"{template_feature.get_swig_class_name()} not found in module {name} because of "
                    f"exception:\n {e}"
                )

    # Indicate that templates have been fully loaded from the module.
    # Any subsequent attempts to load the module will bail out early
    # if this flag is set.
    this_module.__templates_loaded = True

    # Load any modules that have been marked as defining overrides
    # for some base class(es) defined in the current module.
    # For instance, ITKImageIOBase will load any modules defining
    # ImageIO objects for reading different image file types.
    if _DefaultFactoryLoading:
        load_module_needed_factories(name)

    for snakeCaseFunction in l_data.get_snake_case_functions():
        namespace[snakeCaseFunction] = getattr(l_module, snakeCaseFunction)
        init_name = snakeCaseFunction + "_init_docstring"
        init_function = getattr(l_module, init_name)
        try:
            init_function()
        except AttributeError:
            pass

    if itkConfig.ImportCallback:
        itkConfig.ImportCallback(name, 1)
Ejemplo n.º 4
0
                    swigClass = getattr(module, swigClassName)
                except Exception, e:
                    DebugPrintError(
                        "%s not found in module %s because of exception:\n %s"
                        % (swigClassName, name, e))
                itkTemplate.registerNoTpl(cppClassName, swigClass)
                setattr(this_module, pyClassName, swigClass)
                if namespace is not None:
                    current_value = namespace.get(pyClassName)
                    if current_value != None and current_value != swigClass:
                        DebugPrintError(
                            "Namespace already has a value for %s, which is not class %s. Overwriting old value."
                            % (pyClassName, cppClassName))
                    namespace[pyClassName] = swigClass

    if itkConfig.ImportCallback: itkConfig.ImportCallback(name, 1)


def DebugPrintError(error):
    if itkConfig.DebugLevel == itkConfig.WARN:
        print >> sys.stderr, error
    elif itkConfig.DebugLevel == itkConfig.ERROR:
        raise RuntimeError(error)


class LibraryLoader(object):
    """Do all the work to set up the environment so that a SWIG-generated library
  can be properly loaded. This invloves setting paths, etc., defined in itkConfig."""

    # To share symbols across extension modules, we must set
    #     sys.setdlopenflags(dl.RTLD_NOW|dl.RTLD_GLOBAL)