|
| 1 | +import importlib |
| 2 | +import os |
| 3 | +from collections.abc import Callable |
| 4 | +from types import ModuleType |
| 5 | + |
| 6 | +from simopt.model import Model |
| 7 | + |
| 8 | + |
| 9 | +def find_model_patches(module: ModuleType) -> list[Callable]: |
| 10 | + patches: list[Callable] = [] |
| 11 | + for attr in dir(module): |
| 12 | + if not attr.startswith("patch_model"): |
| 13 | + continue |
| 14 | + candidate = getattr(module, attr) |
| 15 | + if callable(candidate): |
| 16 | + patches.append(candidate) |
| 17 | + return patches |
| 18 | + |
| 19 | + |
| 20 | +def patch(model_class: type[Model], patch_function: Callable) -> None: |
| 21 | + # Ask the extension what class to patch and with what method |
| 22 | + class_name, method = patch_function() |
| 23 | + # Patch the method into the model_class if it matches |
| 24 | + full_name = model_class.__module__ + "." + model_class.__qualname__ |
| 25 | + if full_name == class_name: |
| 26 | + model_class.replicate = method |
| 27 | + |
| 28 | + |
| 29 | +def load_module(module_name: str, model_class: type[Model]) -> None: |
| 30 | + # Import the specified library |
| 31 | + try: |
| 32 | + module = importlib.import_module(module_name) |
| 33 | + except ImportError as e: |
| 34 | + raise ImportError(f"SimOpt failed to load extension '{module_name}'") from e |
| 35 | + |
| 36 | + # Find all patch_model* functions in the library |
| 37 | + patches = find_model_patches(module) |
| 38 | + if not patches: |
| 39 | + raise ImportError(f"'{module_name}' does not have any 'patch_model*' functions") |
| 40 | + |
| 41 | + # Apply each patch to the model_class |
| 42 | + for p in patches: |
| 43 | + patch(model_class, p) |
| 44 | + |
| 45 | + |
| 46 | +def patch_model(model_class: type[Model]) -> None: |
| 47 | + env_var = os.environ.get("SIMOPT_EXT") |
| 48 | + if not env_var: |
| 49 | + return |
| 50 | + |
| 51 | + # Assume that the user has specified a comma-separated list of libraries to import. |
| 52 | + # For example, SIMOPT_EXT="simopt_extension_a,simopt_extension_b" |
| 53 | + for part in env_var.split(","): |
| 54 | + module_name = part.strip() |
| 55 | + if module_name: |
| 56 | + load_module(module_name, model_class) |
0 commit comments