MacroLens / code /methods /_registry.py
itouchz's picture
Upload methods/ (18-method baseline panel implementations)
02412f8 verified
Raw
History Blame Contribute Delete
2.89 kB
"""Method registry for the MacroLens unified API.
Concrete method classes register themselves via the :func:`register`
decorator. The orchestrator (``experiments/run_all.py``) and the public
API (``macrolens.list_methods``, ``macrolens.methods``) read from
:data:`ALL_METHODS`.
Usage:
from .base import Method, _JoblibSaveMixin
from ._registry import register
from ._config import LightGBMConfig
@register(name="lightgbm", family="classical",
tasks={"T1","T2","T3","T4","T5","T6","T7"},
config_class=LightGBMConfig)
class LightGBMRegressor(_JoblibSaveMixin, Method):
...
This avoids the historical pattern of hand-maintaining a `__init__.py`
re-export list that drifted from the actual class set.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Iterable
if TYPE_CHECKING:
from .base import Method
from ._config import MethodConfig
# Single source of truth: name -> concrete Method class
ALL_METHODS: dict[str, type["Method"]] = {}
def register(
*,
name: str,
family: str,
tasks: Iterable[str],
config_class: type["MethodConfig"],
):
"""Decorator that registers a concrete Method subclass.
Sets the four class-level attributes (``name``, ``family``, ``tasks``,
plus a ``_config_class`` private hook used by ``default_config``) and
inserts the class into :data:`ALL_METHODS`.
"""
tasks_frozen = frozenset(tasks)
def _decorator(cls):
cls.name = name
cls.family = family
cls.tasks = tasks_frozen
cls._config_class = config_class
if not hasattr(cls, "default_config") or cls.default_config is _undefined_default_config:
@classmethod
def default_config(cls_inner):
return cls_inner._config_class()
cls.default_config = default_config # type: ignore[assignment]
if name in ALL_METHODS:
raise ValueError(f"method '{name}' already registered")
ALL_METHODS[name] = cls
return cls
return _decorator
def _undefined_default_config(cls): # pragma: no cover -- placeholder sentinel
raise NotImplementedError
def list_methods(*, family: str | None = None, task: str | None = None) -> list[str]:
"""Return registered method names, optionally filtered by family or task."""
out = []
for n, cls in sorted(ALL_METHODS.items()):
if family is not None and cls.family != family:
continue
if task is not None and task not in cls.tasks:
continue
out.append(n)
return out
def get(name: str) -> type["Method"]:
"""Lookup a registered method class by name."""
if name not in ALL_METHODS:
raise KeyError(
f"method '{name}' not registered; "
f"available: {sorted(ALL_METHODS)}"
)
return ALL_METHODS[name]