Datasets:
File size: 2,889 Bytes
02412f8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | """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]
|