Kitware / kwiver

Pulls Together Computer Vision Algorithms into Highly-Modular Run-Time Configurable Systems
Other
189 stars 83 forks source link

Simplify Vital Algorithm Registration in Python #1123

Open Erotemic opened 3 years ago

Erotemic commented 3 years ago

The current way of registering vital algorithms is a bit unwieldy and verbose. It seems like a perfect job for a decorator. I made a small proof-of-concept that demos a possible implementation for said decorator.

We may be able to refactor something like this

# In vital.py

def _register_algorithm(cls, name=None, desc=''):
    if name is None:
        name = cls.__name__
    from vital.algo import algorithm_factory
    if not algorithm_factory.has_algorithm_impl_name(cls.static_type_name(), name):
        algorithm_factory.add_algorithm(name, desc, cls)
        algorithm_factory.mark_algorithm_as_loaded(name)

def register_algorithm(name=None, desc=''):
    """
    POC refactor of __vital_algorithm_register__ into a decorator
    """
    def _wrapper(cls):
        _register_algorithm(cls, name, desc)
        return cls
    return _wrapper

def lazy_register(cls, name=None, desc=''):
    ''' Alternate Proof-of-Concept '''
    def __vital_algorithm_register__():
        return _register_algorithm(cls, name, desc)
    return __vital_algorithm_register__

# Then in your class
import vital
@vial.register_algorithm(desc="PyTorch Netharn classification routine")
class MyAlgorithm(BaseAlgo):
    ...

# OR if the current lazy structure is important
import vital
class MyAlgorithm(BaseAlgo):
    ...

__vital_algorithm_register__ = vital.lazy_register(MyAlgorithm, desc="PyTorch Netharn classification routine")

# We could also play with adding class member variables for the lazy
# initialization. There is lots of room to make this better / easier.
Erotemic commented 3 years ago

@johnwparent @tao558 @mleotta @as6520 @linus-sherrill @dstoup Thoughts?

as6520 commented 3 years ago

I think using decorators to register the algorithm is an improvement over the current approach. As for the lazy registration, can it be used anywhere or should it present in the file with the algorithm?

If we decide to change the registration, I would recommend moving it out of vital into a module of its own since we would be replacing __sprokit_register__ too with a decorator