ssapling 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ssapling/__init__.py +12 -0
- ssapling/core/__init__.py +53 -0
- ssapling/core/_declarations.py +139 -0
- ssapling/core/_execution.py +155 -0
- ssapling/core/_plain.py +37 -0
- ssapling/core/_text.py +42 -0
- ssapling/core/errors.py +175 -0
- ssapling/core/loading.py +205 -0
- ssapling/core/registry.py +345 -0
- ssapling/core/settings.py +698 -0
- ssapling/core/spec.py +98 -0
- ssapling/data/__init__.py +89 -0
- ssapling/data/_matching.py +22 -0
- ssapling/data/batching.py +166 -0
- ssapling/data/collections.py +335 -0
- ssapling/data/encoding.py +107 -0
- ssapling/data/errors.py +104 -0
- ssapling/data/provenance.py +94 -0
- ssapling/data/records.py +546 -0
- ssapling/data/sampling.py +339 -0
- ssapling/data/storage.py +569 -0
- ssapling/environments/__init__.py +43 -0
- ssapling/environments/contracts.py +168 -0
- ssapling/environments/errors.py +53 -0
- ssapling/environments/runner.py +153 -0
- ssapling/environments/types.py +173 -0
- ssapling/evaluate/__init__.py +40 -0
- ssapling/evaluate/aggregation.py +173 -0
- ssapling/evaluate/assessment.py +429 -0
- ssapling/evaluate/measurement.py +165 -0
- ssapling/interaction/__init__.py +24 -0
- ssapling/interaction/episode.py +713 -0
- ssapling/interaction/errors.py +21 -0
- ssapling/interaction/hosting.py +287 -0
- ssapling/models/__init__.py +44 -0
- ssapling/models/buffering.py +189 -0
- ssapling/models/contracts.py +181 -0
- ssapling/models/errors.py +27 -0
- ssapling/models/types.py +75 -0
- ssapling/py.typed +0 -0
- ssapling/registries.py +37 -0
- ssapling/tasks/__init__.py +49 -0
- ssapling/tasks/contracts.py +137 -0
- ssapling/tasks/errors.py +37 -0
- ssapling/tasks/types.py +172 -0
- ssapling/teachers/__init__.py +34 -0
- ssapling/teachers/contracts.py +145 -0
- ssapling/teachers/errors.py +80 -0
- ssapling/teachers/runner.py +142 -0
- ssapling/teachers/types.py +178 -0
- ssapling/train/__init__.py +43 -0
- ssapling/train/components.py +194 -0
- ssapling/train/context.py +169 -0
- ssapling/train/errors.py +24 -0
- ssapling/train/procedure.py +316 -0
- ssapling/train/runner.py +398 -0
- ssapling/train/stages.py +463 -0
- ssapling-0.1.0.dist-info/METADATA +113 -0
- ssapling-0.1.0.dist-info/RECORD +61 -0
- ssapling-0.1.0.dist-info/WHEEL +4 -0
- ssapling-0.1.0.dist-info/licenses/LICENSE +201 -0
ssapling/core/loading.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""Loading configuration files (YAML or JSON) into plain mappings, and loading what a
|
|
2
|
+
``MODULE:NAME`` in them names.
|
|
3
|
+
|
|
4
|
+
Core loads files and reads individual component entries from them. How a whole
|
|
5
|
+
experiment file is organised (which components it combines, sweeps, overrides,
|
|
6
|
+
includes, presets) is up to the downstream project.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import functools
|
|
10
|
+
import importlib
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
import sys
|
|
15
|
+
from collections.abc import Hashable, Mapping
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from ._text import join_path, show
|
|
20
|
+
from .errors import ConfigError, MissingDependencyError, Problem
|
|
21
|
+
from .spec import ComponentSpec
|
|
22
|
+
|
|
23
|
+
_YAML_SUFFIXES = (".yaml", ".yml")
|
|
24
|
+
_JSON_SUFFIXES = (".json",)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Config(dict[str, Any]):
|
|
28
|
+
"""The top-level mapping of a loaded configuration file.
|
|
29
|
+
|
|
30
|
+
It is an ordinary ``dict`` of plain values, and also remembers the file it
|
|
31
|
+
came from, so component entries read from it report that file in errors.
|
|
32
|
+
|
|
33
|
+
Attributes:
|
|
34
|
+
source: The path of the file, as given to ``load_config``.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def __init__(self, values: Mapping[str, Any], *, source: str | None = None) -> None:
|
|
38
|
+
super().__init__(values)
|
|
39
|
+
self.source = source
|
|
40
|
+
|
|
41
|
+
def component(self, path: str) -> ComponentSpec:
|
|
42
|
+
"""Read the component entry at ``path``: a key, or a dotted path like ``"run.teacher"``.
|
|
43
|
+
|
|
44
|
+
Raises:
|
|
45
|
+
ConfigError: Nothing is at ``path``, or the entry is not a valid
|
|
46
|
+
component entry. Errors name the file and the path.
|
|
47
|
+
"""
|
|
48
|
+
value: Any = self
|
|
49
|
+
walked = ""
|
|
50
|
+
for key in path.split("."):
|
|
51
|
+
walked = join_path(walked, key)
|
|
52
|
+
if not isinstance(value, Mapping) or key not in value:
|
|
53
|
+
raise ConfigError(self._subject(), [Problem(walked, "missing entry")])
|
|
54
|
+
value = value[key]
|
|
55
|
+
return ComponentSpec.from_mapping(value, source=self.source, path=path)
|
|
56
|
+
|
|
57
|
+
def _subject(self) -> str:
|
|
58
|
+
return f"configuration file {self.source}" if self.source else "configuration"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def load_config(path: str | os.PathLike[str]) -> Config:
|
|
62
|
+
"""Load a YAML (``.yaml``, ``.yml``) or JSON (``.json``) file into plain mappings.
|
|
63
|
+
|
|
64
|
+
The top level must be a mapping. Duplicate keys are rejected rather than
|
|
65
|
+
silently keeping the last one. In YAML, numbers in exponent form such as
|
|
66
|
+
``1e-4`` are read as floats, as in JSON and YAML 1.2. YAML needs the
|
|
67
|
+
optional PyYAML dependency: ``pip install "ssapling[yaml]"``.
|
|
68
|
+
|
|
69
|
+
Raises:
|
|
70
|
+
ConfigError: The file cannot be parsed, has duplicate keys, has an
|
|
71
|
+
unsupported suffix, or is not a mapping at the top level.
|
|
72
|
+
MissingDependencyError: A YAML file was given and PyYAML is not
|
|
73
|
+
installed.
|
|
74
|
+
OSError: The file cannot be read.
|
|
75
|
+
"""
|
|
76
|
+
file = Path(path)
|
|
77
|
+
source = str(path)
|
|
78
|
+
suffix = file.suffix.lower()
|
|
79
|
+
if suffix in _YAML_SUFFIXES:
|
|
80
|
+
values = _load_yaml(file.read_text(encoding="utf-8"), source)
|
|
81
|
+
elif suffix in _JSON_SUFFIXES:
|
|
82
|
+
values = _load_json(file.read_text(encoding="utf-8"), source)
|
|
83
|
+
else:
|
|
84
|
+
raise ConfigError(
|
|
85
|
+
f"configuration file {source}",
|
|
86
|
+
[Problem("", f"unsupported file type {suffix!r}; use .yaml, .yml, or .json")],
|
|
87
|
+
)
|
|
88
|
+
if not isinstance(values, Mapping):
|
|
89
|
+
found = "an empty file" if values is None else show(values)
|
|
90
|
+
raise ConfigError(
|
|
91
|
+
f"configuration file {source}",
|
|
92
|
+
[Problem("", f"expected a mapping at the top level, got {found}")],
|
|
93
|
+
)
|
|
94
|
+
return Config(values, source=source)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def load_named(spec: str, what: str) -> Any:
|
|
98
|
+
"""What ``spec`` names, as ``MODULE:NAME``: the module imported, then its attribute NAME.
|
|
99
|
+
|
|
100
|
+
A configuration file names code this way, such as a task class or a
|
|
101
|
+
factory. The current directory is searched too (it is put on ``sys.path``
|
|
102
|
+
if it isn't there), so a command run from a project's root finds the
|
|
103
|
+
project's own modules. ``what`` says what is named, for the errors.
|
|
104
|
+
|
|
105
|
+
Raises:
|
|
106
|
+
ValueError: ``spec`` isn't ``MODULE:NAME``, its module can't be
|
|
107
|
+
imported, or the module has no NAME. The error names ``what``.
|
|
108
|
+
"""
|
|
109
|
+
module_name, colon, name = spec.partition(":")
|
|
110
|
+
if not (colon and module_name and name):
|
|
111
|
+
raise ValueError(f"give the {what} as MODULE:NAME, such as package.module:Name: {spec!r}")
|
|
112
|
+
if os.getcwd() not in sys.path:
|
|
113
|
+
sys.path.insert(0, os.getcwd())
|
|
114
|
+
try:
|
|
115
|
+
module = importlib.import_module(module_name)
|
|
116
|
+
except ImportError as error:
|
|
117
|
+
raise ValueError(f"can't import {module_name!r} for the {what}: {error}") from None
|
|
118
|
+
if not hasattr(module, name):
|
|
119
|
+
raise ValueError(f"{module_name} has no {name!r} for the {what}")
|
|
120
|
+
return getattr(module, name)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
# JSON
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _load_json(text: str, source: str) -> Any:
|
|
127
|
+
duplicates: list[str] = []
|
|
128
|
+
|
|
129
|
+
def unique_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
|
130
|
+
result: dict[str, Any] = {}
|
|
131
|
+
for key, value in pairs:
|
|
132
|
+
if key in result:
|
|
133
|
+
duplicates.append(key)
|
|
134
|
+
result[key] = value
|
|
135
|
+
return result
|
|
136
|
+
|
|
137
|
+
try:
|
|
138
|
+
values = json.loads(text, object_pairs_hook=unique_keys)
|
|
139
|
+
except json.JSONDecodeError as error:
|
|
140
|
+
where = f"line {error.lineno}, column {error.colno}"
|
|
141
|
+
raise ConfigError(f"configuration file {source}", [Problem(where, error.msg)]) from None
|
|
142
|
+
if duplicates:
|
|
143
|
+
raise ConfigError(
|
|
144
|
+
f"configuration file {source}",
|
|
145
|
+
[Problem("", f"duplicate key {key!r}") for key in duplicates],
|
|
146
|
+
)
|
|
147
|
+
return values
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
# YAML
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _load_yaml(text: str, source: str) -> Any:
|
|
154
|
+
try:
|
|
155
|
+
import yaml
|
|
156
|
+
except ModuleNotFoundError as error:
|
|
157
|
+
raise MissingDependencyError(
|
|
158
|
+
f"Loading the YAML file {source} needs PyYAML, which is optional. "
|
|
159
|
+
"Install it with: pip install 'ssapling[yaml]'"
|
|
160
|
+
) from error
|
|
161
|
+
try:
|
|
162
|
+
return yaml.load(text, Loader=_yaml_loader()) # A SafeLoader subclass.
|
|
163
|
+
except yaml.MarkedYAMLError as error:
|
|
164
|
+
mark = error.problem_mark
|
|
165
|
+
where = f"line {mark.line + 1}, column {mark.column + 1}" if mark else ""
|
|
166
|
+
message = error.problem or str(error)
|
|
167
|
+
if error.context:
|
|
168
|
+
message += f" ({error.context})"
|
|
169
|
+
raise ConfigError(f"configuration file {source}", [Problem(where, message)]) from None
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
# YAML 1.1, which PyYAML implements, reads 1e-4 and 1.0e5 as strings: its float
|
|
173
|
+
# pattern needs a dot and a signed exponent. This adds the exponent forms that
|
|
174
|
+
# YAML 1.2 and JSON read as numbers.
|
|
175
|
+
_EXPONENT_FLOAT = re.compile(r"^[-+]?(?:[0-9][0-9_]*(?:\.[0-9_]*)?|\.[0-9_]+)[eE][-+]?[0-9]+$")
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
@functools.cache
|
|
179
|
+
def _yaml_loader() -> Any:
|
|
180
|
+
import yaml
|
|
181
|
+
|
|
182
|
+
class Loader(yaml.SafeLoader):
|
|
183
|
+
"""PyYAML's safe loader, with exponent floats and duplicate keys rejected."""
|
|
184
|
+
|
|
185
|
+
def construct_mapping(self, node: Any, deep: bool = False) -> Any:
|
|
186
|
+
first_line: dict[Any, int] = {}
|
|
187
|
+
for key_node, _ in node.value:
|
|
188
|
+
if key_node.tag == "tag:yaml.org,2002:merge":
|
|
189
|
+
continue # "<<: *defaults" merges; later keys may override it.
|
|
190
|
+
key = self.construct_object(key_node, deep=deep)
|
|
191
|
+
if not isinstance(key, Hashable):
|
|
192
|
+
continue # PyYAML itself reports unhashable keys.
|
|
193
|
+
line = key_node.start_mark.line + 1
|
|
194
|
+
if key in first_line:
|
|
195
|
+
raise yaml.constructor.ConstructorError(
|
|
196
|
+
None,
|
|
197
|
+
None,
|
|
198
|
+
f"duplicate key {key!r} (first on line {first_line[key]})",
|
|
199
|
+
key_node.start_mark,
|
|
200
|
+
)
|
|
201
|
+
first_line[key] = line
|
|
202
|
+
return super().construct_mapping(node, deep=deep)
|
|
203
|
+
|
|
204
|
+
Loader.add_implicit_resolver("tag:yaml.org,2002:float", _EXPONENT_FLOAT, list("-+0123456789."))
|
|
205
|
+
return Loader
|
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
"""Registries: one per kind of component, mapping names to implementations.
|
|
2
|
+
|
|
3
|
+
A registry also builds components: it validates settings against the
|
|
4
|
+
implementation's settings class and calls the implementation with them and
|
|
5
|
+
with the live objects the caller supplies.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from collections.abc import Callable, Mapping
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from typing import Any, TypedDict, cast, overload
|
|
11
|
+
|
|
12
|
+
from ._text import describe, join_path, show, summary
|
|
13
|
+
from .errors import ConfigError, DuplicateRegistrationError, Problem, UnknownComponentError
|
|
14
|
+
from .settings import check_settings_class, settings_schema, validate_settings
|
|
15
|
+
from .spec import ComponentSpec
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True, slots=True, eq=False)
|
|
19
|
+
class Registration[T]:
|
|
20
|
+
"""One registry entry.
|
|
21
|
+
|
|
22
|
+
Attributes:
|
|
23
|
+
name: The registered name.
|
|
24
|
+
implementation: The registered class or function.
|
|
25
|
+
settings: The settings dataclass the implementation accepts, or
|
|
26
|
+
``None`` if it takes no settings.
|
|
27
|
+
description: A one-line description: the one given at registration,
|
|
28
|
+
or else the first paragraph of the implementation's docstring.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
name: str
|
|
32
|
+
implementation: T
|
|
33
|
+
settings: type | None
|
|
34
|
+
description: str | None = None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class CatalogueEntry(TypedDict):
|
|
38
|
+
"""One component in a registry's catalogue, as plain JSON-ready values."""
|
|
39
|
+
|
|
40
|
+
name: str
|
|
41
|
+
description: str | None
|
|
42
|
+
settings: dict[str, Any]
|
|
43
|
+
"""JSON Schema of the component's settings; an empty object if it takes none."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class Registry[T]:
|
|
47
|
+
"""Maps names to the implementations (classes or functions) of one kind of component.
|
|
48
|
+
|
|
49
|
+
A registry stores the implementation itself, never a constructed instance.
|
|
50
|
+
Each kind of component (teachers, samplers, stages, ...) has its own
|
|
51
|
+
registry, and ``kind`` names it in error messages.
|
|
52
|
+
|
|
53
|
+
Example::
|
|
54
|
+
|
|
55
|
+
teachers = Registry("teacher")
|
|
56
|
+
teachers.register("stepwise", StepwiseTeacher)
|
|
57
|
+
teachers.get("stepwise") # -> StepwiseTeacher, the class itself
|
|
58
|
+
teachers.create("stepwise", {"explain": True}, task=task) # -> a StepwiseTeacher
|
|
59
|
+
|
|
60
|
+
An implementation's settings class is taken from its ``Settings``
|
|
61
|
+
attribute, or passed explicitly with ``settings=``; either way it is
|
|
62
|
+
checked when registered (see ``ssapling.core.settings``).
|
|
63
|
+
|
|
64
|
+
Registering the same implementation with the same settings class under
|
|
65
|
+
the same name again does nothing, so a downstream ``register_components()``
|
|
66
|
+
can safely run more than once. Registering anything different under a
|
|
67
|
+
taken name is an error unless ``replace=True`` is passed.
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
def __init__(self, kind: str) -> None:
|
|
71
|
+
self._kind = kind
|
|
72
|
+
self._entries: dict[str, Registration[T]] = {}
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def kind(self) -> str:
|
|
76
|
+
"""The kind of component this registry holds, such as ``"teacher"``."""
|
|
77
|
+
return self._kind
|
|
78
|
+
|
|
79
|
+
# Registering and looking up
|
|
80
|
+
|
|
81
|
+
def register(
|
|
82
|
+
self,
|
|
83
|
+
name: str,
|
|
84
|
+
implementation: T,
|
|
85
|
+
*,
|
|
86
|
+
settings: type | None = None,
|
|
87
|
+
description: str | None = None,
|
|
88
|
+
replace: bool = False,
|
|
89
|
+
) -> None:
|
|
90
|
+
"""Register ``implementation`` under ``name``.
|
|
91
|
+
|
|
92
|
+
Args:
|
|
93
|
+
name: The name to register under.
|
|
94
|
+
implementation: The class or function.
|
|
95
|
+
settings: The settings dataclass the implementation accepts.
|
|
96
|
+
Defaults to the implementation's ``Settings`` attribute, if any.
|
|
97
|
+
description: A one-line description for the catalogue. Defaults
|
|
98
|
+
to the first paragraph of the implementation's docstring.
|
|
99
|
+
replace: Allow replacing a different registration under ``name``.
|
|
100
|
+
|
|
101
|
+
Raises:
|
|
102
|
+
DuplicateRegistrationError: ``name`` is taken by a different
|
|
103
|
+
registration and ``replace`` is false.
|
|
104
|
+
SettingsDeclarationError: The settings class cannot be checked.
|
|
105
|
+
TypeError: ``name`` is not a string.
|
|
106
|
+
ValueError: ``name`` is empty or has surrounding whitespace.
|
|
107
|
+
"""
|
|
108
|
+
self._check_name(name)
|
|
109
|
+
if settings is None:
|
|
110
|
+
settings = getattr(implementation, "Settings", None)
|
|
111
|
+
if settings is not None:
|
|
112
|
+
check_settings_class(settings)
|
|
113
|
+
existing = self._entries.get(name)
|
|
114
|
+
if existing is not None and not replace:
|
|
115
|
+
if existing.implementation is implementation and existing.settings is settings:
|
|
116
|
+
return # registered already: nothing to do
|
|
117
|
+
raise DuplicateRegistrationError(
|
|
118
|
+
self._kind,
|
|
119
|
+
name,
|
|
120
|
+
existing.implementation,
|
|
121
|
+
implementation,
|
|
122
|
+
existing_settings=existing.settings,
|
|
123
|
+
new_settings=settings,
|
|
124
|
+
)
|
|
125
|
+
if description is None:
|
|
126
|
+
description = summary(implementation)
|
|
127
|
+
self._entries[name] = Registration(name, implementation, settings, description)
|
|
128
|
+
|
|
129
|
+
def get(self, name: str) -> T:
|
|
130
|
+
"""Return the implementation registered under ``name``.
|
|
131
|
+
|
|
132
|
+
Raises:
|
|
133
|
+
UnknownComponentError: Nothing is registered under ``name``. The
|
|
134
|
+
error suggests close matches and lists the registered names.
|
|
135
|
+
"""
|
|
136
|
+
return self.entry(name).implementation
|
|
137
|
+
|
|
138
|
+
def entry(self, name: str) -> Registration[T]:
|
|
139
|
+
"""Return the full registration under ``name``: implementation, settings, description.
|
|
140
|
+
|
|
141
|
+
Raises:
|
|
142
|
+
UnknownComponentError: Nothing is registered under ``name``.
|
|
143
|
+
"""
|
|
144
|
+
return self._entry(name, location=None)
|
|
145
|
+
|
|
146
|
+
def names(self) -> tuple[str, ...]:
|
|
147
|
+
"""Every registered name, sorted."""
|
|
148
|
+
return tuple(sorted(self._entries))
|
|
149
|
+
|
|
150
|
+
def catalogue(self) -> list[CatalogueEntry]:
|
|
151
|
+
"""Describe every registered component: name, description, and settings schema.
|
|
152
|
+
|
|
153
|
+
The result is plain, JSON-ready data, sorted by name, suitable for
|
|
154
|
+
documentation or for offering components to a procedure controller.
|
|
155
|
+
"""
|
|
156
|
+
return [
|
|
157
|
+
{
|
|
158
|
+
"name": entry.name,
|
|
159
|
+
"description": entry.description,
|
|
160
|
+
"settings": (
|
|
161
|
+
settings_schema(entry.settings) if entry.settings else _no_settings_schema()
|
|
162
|
+
),
|
|
163
|
+
}
|
|
164
|
+
for entry in (self._entries[name] for name in self.names())
|
|
165
|
+
]
|
|
166
|
+
|
|
167
|
+
# Validating and creating
|
|
168
|
+
|
|
169
|
+
def validate(self, name: str, settings: Mapping[str, Any] | object | None = None) -> Any:
|
|
170
|
+
"""Check settings for the component ``name`` without creating it.
|
|
171
|
+
|
|
172
|
+
``settings`` is a mapping of plain values, an instance of the
|
|
173
|
+
component's settings class, or ``None`` for all defaults.
|
|
174
|
+
|
|
175
|
+
Returns:
|
|
176
|
+
The validated settings instance, or ``None`` if the component
|
|
177
|
+
takes no settings.
|
|
178
|
+
|
|
179
|
+
Raises:
|
|
180
|
+
UnknownComponentError: Nothing is registered under ``name``.
|
|
181
|
+
ConfigError: The settings are invalid, listing every problem.
|
|
182
|
+
"""
|
|
183
|
+
return self._validate(self.entry(name), settings, source=None, prefix=None)
|
|
184
|
+
|
|
185
|
+
def validate_from(self, spec: ComponentSpec) -> Any:
|
|
186
|
+
"""``validate`` for a component entry; errors name the entry's file and path."""
|
|
187
|
+
entry = self._entry(spec.name, location=_location(spec, "name"))
|
|
188
|
+
return self._validate(
|
|
189
|
+
entry, spec.settings, source=spec.source, prefix=join_path(spec.path, "settings")
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
@overload
|
|
193
|
+
def create[R](
|
|
194
|
+
self: "Registry[type[R]]",
|
|
195
|
+
name: str,
|
|
196
|
+
settings: Mapping[str, Any] | object | None = None,
|
|
197
|
+
**live: Any,
|
|
198
|
+
) -> R: ...
|
|
199
|
+
|
|
200
|
+
@overload
|
|
201
|
+
def create[R](
|
|
202
|
+
self: "Registry[Callable[..., R]]",
|
|
203
|
+
name: str,
|
|
204
|
+
settings: Mapping[str, Any] | object | None = None,
|
|
205
|
+
**live: Any,
|
|
206
|
+
) -> R: ...
|
|
207
|
+
|
|
208
|
+
def create(
|
|
209
|
+
self, name: str, settings: Mapping[str, Any] | object | None = None, **live: Any
|
|
210
|
+
) -> Any:
|
|
211
|
+
"""Create the component registered under ``name``.
|
|
212
|
+
|
|
213
|
+
Validates ``settings`` (see ``validate``) and calls the implementation
|
|
214
|
+
with them as ``config=``, together with the live objects passed as
|
|
215
|
+
keyword arguments::
|
|
216
|
+
|
|
217
|
+
teachers.create("stepwise", {"explain": True}, task=task)
|
|
218
|
+
# is StepwiseTeacher(config=StepwiseTeacherSettings(explain=True), task=task)
|
|
219
|
+
|
|
220
|
+
A component that takes no settings is called with the live objects
|
|
221
|
+
only. Which live objects a component needs is part of its area's
|
|
222
|
+
contract; Core passes them on unchecked.
|
|
223
|
+
|
|
224
|
+
Raises:
|
|
225
|
+
UnknownComponentError: Nothing is registered under ``name``.
|
|
226
|
+
ConfigError: The settings are invalid.
|
|
227
|
+
TypeError: A live object is named ``config``, which is reserved
|
|
228
|
+
for the validated settings.
|
|
229
|
+
Exception: Anything the implementation raises, with a note naming
|
|
230
|
+
the component.
|
|
231
|
+
"""
|
|
232
|
+
entry = self.entry(name)
|
|
233
|
+
validated = self._validate(entry, settings, source=None, prefix=None)
|
|
234
|
+
return self._construct(entry, validated, live, location=None)
|
|
235
|
+
|
|
236
|
+
def create_from(self, spec: ComponentSpec, **live: Any) -> Any:
|
|
237
|
+
"""``create`` for a component entry; errors name the entry's file and path.
|
|
238
|
+
|
|
239
|
+
Example::
|
|
240
|
+
|
|
241
|
+
config = load_config("run.yaml")
|
|
242
|
+
teacher = teachers.create_from(config.component("teacher"), task=task)
|
|
243
|
+
"""
|
|
244
|
+
validated = self.validate_from(spec)
|
|
245
|
+
return self._construct(self.entry(spec.name), validated, live, location=_location(spec, ""))
|
|
246
|
+
|
|
247
|
+
# Internals
|
|
248
|
+
|
|
249
|
+
def _entry(self, name: str, *, location: str | None) -> Registration[T]:
|
|
250
|
+
try:
|
|
251
|
+
return self._entries[name]
|
|
252
|
+
except KeyError:
|
|
253
|
+
raise UnknownComponentError(
|
|
254
|
+
self._kind, name, self._entries, location=location
|
|
255
|
+
) from None
|
|
256
|
+
|
|
257
|
+
def _validate(
|
|
258
|
+
self,
|
|
259
|
+
entry: Registration[T],
|
|
260
|
+
settings: object,
|
|
261
|
+
*,
|
|
262
|
+
source: str | None,
|
|
263
|
+
prefix: str | None,
|
|
264
|
+
) -> Any:
|
|
265
|
+
subject = f"settings for {self._kind} {entry.name!r}"
|
|
266
|
+
if source:
|
|
267
|
+
subject += f" in {source}"
|
|
268
|
+
if entry.settings is None:
|
|
269
|
+
if settings is None or (isinstance(settings, Mapping) and not settings):
|
|
270
|
+
return None
|
|
271
|
+
problem = Problem(
|
|
272
|
+
prefix or "", f"{self._kind} {entry.name!r} takes no settings, got {show(settings)}"
|
|
273
|
+
)
|
|
274
|
+
raise ConfigError(subject, [problem])
|
|
275
|
+
try:
|
|
276
|
+
return validate_settings(entry.settings, settings)
|
|
277
|
+
except ConfigError as error:
|
|
278
|
+
problems = [
|
|
279
|
+
Problem(join_path(prefix, p.path) if prefix else p.path, p.message)
|
|
280
|
+
for p in error.problems
|
|
281
|
+
]
|
|
282
|
+
raise ConfigError(subject, problems) from None
|
|
283
|
+
|
|
284
|
+
def _construct(
|
|
285
|
+
self,
|
|
286
|
+
entry: Registration[T],
|
|
287
|
+
validated: Any,
|
|
288
|
+
live: dict[str, Any],
|
|
289
|
+
*,
|
|
290
|
+
location: str | None,
|
|
291
|
+
) -> Any:
|
|
292
|
+
arguments = dict(live)
|
|
293
|
+
if entry.settings is not None:
|
|
294
|
+
if "config" in arguments:
|
|
295
|
+
raise TypeError(
|
|
296
|
+
f"'config' cannot be passed as a live object: {self._kind} "
|
|
297
|
+
f"{entry.name!r} receives its validated settings as config=."
|
|
298
|
+
)
|
|
299
|
+
arguments["config"] = validated
|
|
300
|
+
implementation = cast(Callable[..., Any], entry.implementation)
|
|
301
|
+
try:
|
|
302
|
+
return implementation(**arguments)
|
|
303
|
+
except Exception as error:
|
|
304
|
+
where = f" for {location}" if location else ""
|
|
305
|
+
error.add_note(
|
|
306
|
+
f"While creating {self._kind} {entry.name!r} ({describe(implementation)}){where}."
|
|
307
|
+
)
|
|
308
|
+
raise
|
|
309
|
+
|
|
310
|
+
def __contains__(self, name: object) -> bool:
|
|
311
|
+
return name in self._entries
|
|
312
|
+
|
|
313
|
+
def __len__(self) -> int:
|
|
314
|
+
return len(self._entries)
|
|
315
|
+
|
|
316
|
+
def __repr__(self) -> str:
|
|
317
|
+
return f"Registry({self._kind!r}, names={list(self.names())})"
|
|
318
|
+
|
|
319
|
+
def _check_name(self, name: object) -> None:
|
|
320
|
+
if not isinstance(name, str):
|
|
321
|
+
raise TypeError(f"A {self._kind} name must be a string, not {type(name).__name__}.")
|
|
322
|
+
if not name or name != name.strip():
|
|
323
|
+
raise ValueError(
|
|
324
|
+
f"A {self._kind} name must be non-empty, without leading or trailing "
|
|
325
|
+
f"whitespace: {name!r}."
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def _location(spec: ComponentSpec, key: str) -> str | None:
|
|
330
|
+
"""Where in its source a spec's ``key`` is written, as ``"run.yaml: teacher.name"``."""
|
|
331
|
+
if not spec.source and not spec.path:
|
|
332
|
+
return None # Built in Python: the caller knows where it is.
|
|
333
|
+
path = join_path(spec.path, key) if key else spec.path
|
|
334
|
+
if spec.source and path:
|
|
335
|
+
return f"{spec.source}: {path}"
|
|
336
|
+
return spec.source or path
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def _no_settings_schema() -> dict[str, Any]:
|
|
340
|
+
return {
|
|
341
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
342
|
+
"type": "object",
|
|
343
|
+
"properties": {},
|
|
344
|
+
"additionalProperties": False,
|
|
345
|
+
}
|