File size: 1,275 Bytes
a45b7c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Load a complete geometric hypothesis from a filename containing spaces."""

from __future__ import annotations

import importlib.util
from pathlib import Path
import re
from types import ModuleType

from experiments import config

REQUIRED_CALLABLES = ("build_spatial_code", "dump_spatial_code")


def load_hypothesis(name: str) -> ModuleType:
    path = config.hypothesis_path(name)
    if not path.is_file():
        raise FileNotFoundError(f"hypothesis does not exist: {path}")
    safe_name = re.sub(r"\W+", "_", path.stem).strip("_")
    spec = importlib.util.spec_from_file_location(
        f"experiments.hypotheses.{safe_name}", path
    )
    if spec is None or spec.loader is None:
        raise ImportError(f"cannot load hypothesis: {path}")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    missing = [
        name for name in REQUIRED_CALLABLES if not callable(getattr(module, name, None))
    ]
    if missing:
        raise AttributeError(
            f"{path.name} is missing callable(s): {', '.join(missing)}"
        )
    return module


def list_hypotheses() -> list[str]:
    return sorted(
        path.stem
        for path in config.HYPOTHESES_ROOT.glob("*.py")
        if path.name != "__init__.py"
    )