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.
Files changed (61) hide show
  1. ssapling/__init__.py +12 -0
  2. ssapling/core/__init__.py +53 -0
  3. ssapling/core/_declarations.py +139 -0
  4. ssapling/core/_execution.py +155 -0
  5. ssapling/core/_plain.py +37 -0
  6. ssapling/core/_text.py +42 -0
  7. ssapling/core/errors.py +175 -0
  8. ssapling/core/loading.py +205 -0
  9. ssapling/core/registry.py +345 -0
  10. ssapling/core/settings.py +698 -0
  11. ssapling/core/spec.py +98 -0
  12. ssapling/data/__init__.py +89 -0
  13. ssapling/data/_matching.py +22 -0
  14. ssapling/data/batching.py +166 -0
  15. ssapling/data/collections.py +335 -0
  16. ssapling/data/encoding.py +107 -0
  17. ssapling/data/errors.py +104 -0
  18. ssapling/data/provenance.py +94 -0
  19. ssapling/data/records.py +546 -0
  20. ssapling/data/sampling.py +339 -0
  21. ssapling/data/storage.py +569 -0
  22. ssapling/environments/__init__.py +43 -0
  23. ssapling/environments/contracts.py +168 -0
  24. ssapling/environments/errors.py +53 -0
  25. ssapling/environments/runner.py +153 -0
  26. ssapling/environments/types.py +173 -0
  27. ssapling/evaluate/__init__.py +40 -0
  28. ssapling/evaluate/aggregation.py +173 -0
  29. ssapling/evaluate/assessment.py +429 -0
  30. ssapling/evaluate/measurement.py +165 -0
  31. ssapling/interaction/__init__.py +24 -0
  32. ssapling/interaction/episode.py +713 -0
  33. ssapling/interaction/errors.py +21 -0
  34. ssapling/interaction/hosting.py +287 -0
  35. ssapling/models/__init__.py +44 -0
  36. ssapling/models/buffering.py +189 -0
  37. ssapling/models/contracts.py +181 -0
  38. ssapling/models/errors.py +27 -0
  39. ssapling/models/types.py +75 -0
  40. ssapling/py.typed +0 -0
  41. ssapling/registries.py +37 -0
  42. ssapling/tasks/__init__.py +49 -0
  43. ssapling/tasks/contracts.py +137 -0
  44. ssapling/tasks/errors.py +37 -0
  45. ssapling/tasks/types.py +172 -0
  46. ssapling/teachers/__init__.py +34 -0
  47. ssapling/teachers/contracts.py +145 -0
  48. ssapling/teachers/errors.py +80 -0
  49. ssapling/teachers/runner.py +142 -0
  50. ssapling/teachers/types.py +178 -0
  51. ssapling/train/__init__.py +43 -0
  52. ssapling/train/components.py +194 -0
  53. ssapling/train/context.py +169 -0
  54. ssapling/train/errors.py +24 -0
  55. ssapling/train/procedure.py +316 -0
  56. ssapling/train/runner.py +398 -0
  57. ssapling/train/stages.py +463 -0
  58. ssapling-0.1.0.dist-info/METADATA +113 -0
  59. ssapling-0.1.0.dist-info/RECORD +61 -0
  60. ssapling-0.1.0.dist-info/WHEEL +4 -0
  61. ssapling-0.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,168 @@
1
+ """The environment contract, its optional capabilities, and helpers for consumers.
2
+
3
+ An environment is any object with ``reset()`` and ``step(actions)``, written
4
+ as ``def`` or ``async def``. Everything else is optional: who takes part and
5
+ who acts next, descriptions of observations and actions, ``close()``, and the
6
+ capabilities in ``CAPABILITIES``. This is a structural protocol: a native
7
+ environment or a downstream adapter implements it and inherits from nothing.
8
+
9
+ Consumers check a capability before using it::
10
+
11
+ from ssapling import environments
12
+
13
+ if environments.supports(env, "snapshot"):
14
+ saved = env.snapshot()
15
+ """
16
+
17
+ from collections.abc import Awaitable, Callable, Mapping
18
+ from typing import Any, Protocol
19
+
20
+ from ..core._declarations import has_feature, name_of, names, takes
21
+ from .types import ResetResult, StepResult
22
+
23
+ __all__ = [
24
+ "CAPABILITIES",
25
+ "Environment",
26
+ "active_agents",
27
+ "agents",
28
+ "next_agents",
29
+ "supports",
30
+ ]
31
+
32
+
33
+ class Environment(Protocol):
34
+ """What every environment provides: starting an episode, and taking a step.
35
+
36
+ ``reset`` may also take ``seed=`` (making ``"seeded_reset"`` a
37
+ capability) and ``options=``, what the episode is set up from, such as
38
+ an instance's inputs. SSAPling passes each only when there is one.
39
+
40
+ Optional members, read without waiting:
41
+
42
+ - ``agents``: every agent id that can take part. By default, the agents
43
+ observed at reset.
44
+ - ``active_agents``: the agents currently taking part. By default, those
45
+ just given an observation whose part has not ended.
46
+ - ``next_agents``: the agents that act in the next step. By default, every
47
+ active agent, all at once. A sequential environment says whose turn it
48
+ is.
49
+ - ``observation_descriptions`` and ``action_descriptions``: each agent's
50
+ descriptions, keyed by agent id, in the environment's own form (such as
51
+ a library's space objects), passed through unchanged.
52
+
53
+ Optional methods, ``def`` or ``async def``: ``close()``, which releases
54
+ what the environment holds, and the capabilities' methods (see
55
+ ``CAPABILITIES``).
56
+ """
57
+
58
+ def reset(self) -> ResetResult | Awaitable[ResetResult]:
59
+ """Start a new episode and return each agent's initial observation."""
60
+ ...
61
+
62
+ def step(self, actions: Mapping[str, Any]) -> StepResult | Awaitable[StepResult]:
63
+ """Apply ``actions``, keyed by agent id, and return the transition result."""
64
+ ...
65
+
66
+
67
+ CAPABILITIES: Mapping[str, tuple[str, ...]] = {
68
+ "seeded_reset": ("reset",),
69
+ "render": ("render",),
70
+ "state": ("state",),
71
+ "snapshot": ("snapshot", "restore"),
72
+ "batched": ("reset_lanes", "step_lanes"),
73
+ }
74
+ """The optional capabilities of an environment, each with the methods it needs.
75
+
76
+ - ``seeded_reset``: ``reset(seed=...)`` makes the episode reproducible.
77
+ ``reset`` must take a ``seed`` parameter.
78
+ - ``render``: ``render()`` returns a view of the current state, such as an
79
+ image or text.
80
+ - ``state``: ``state()`` returns the environment's full state, including what
81
+ agents cannot observe, for inspection.
82
+ - ``snapshot``: ``snapshot()`` returns a saved state and ``restore(saved)``
83
+ returns to it.
84
+ - ``batched``: several independent copies, called lanes, stepped together.
85
+ ``lanes`` is how many; ``reset_lanes(lanes)`` resets the listed lanes
86
+ (optionally with ``seeds=`` and ``options=``, keyed by lane) and
87
+ ``step_lanes(actions)`` steps those with actions, keyed by lane, each
88
+ returning a result per lane. A lane that ends waits to be reset; nothing
89
+ resets it automatically. A batch of independent environments is not a
90
+ multi-agent world.
91
+ """
92
+
93
+
94
+ def supports(env: object, capability: str) -> bool:
95
+ """Whether ``env`` offers ``capability``: one of ``CAPABILITIES``.
96
+
97
+ An environment offers a capability when it has every method the
98
+ capability needs and, if it defines a ``supports(capability)`` method of
99
+ its own, that method agrees. So an environment declares a capability just
100
+ by implementing it, and an adapter can switch off a capability its class
101
+ implements when the environment it wraps cannot honour it, for example
102
+ seeding that is not reproducible.
103
+
104
+ An environment's own ``supports`` only switches capabilities off: it
105
+ answers ``False`` for those and ``True`` for every other capability. It
106
+ must not call this function on itself, because this function calls it.
107
+ A wrapper may call it on the environment it wraps.
108
+
109
+ Raises:
110
+ ValueError: ``capability`` is not an environment capability. That is
111
+ a mistake in the calling code.
112
+ TypeError: The environment has a ``supports`` attribute that is not a
113
+ method.
114
+ """
115
+ return has_feature(
116
+ env,
117
+ capability,
118
+ CAPABILITIES,
119
+ word="capability",
120
+ words="capabilities",
121
+ requirement=_reset_takes_a_seed if capability == "seeded_reset" else None,
122
+ )
123
+
124
+
125
+ def agents(env: object, reset: ResetResult) -> tuple[str, ...]:
126
+ """Every agent id that can take part: the environment's ``agents``, or those reset observed."""
127
+ return _participants(env, "agents", lambda: tuple(reset.observations))
128
+
129
+
130
+ def active_agents(env: object, last: ResetResult | StepResult) -> tuple[str, ...]:
131
+ """The agents taking part now, after ``last``, the latest reset or step result.
132
+
133
+ The environment's ``active_agents`` if it has them. Otherwise, the agents
134
+ ``last`` gave an observation to, except those whose part has ended.
135
+ """
136
+
137
+ def default() -> tuple[str, ...]:
138
+ ended = last.ended_agents if isinstance(last, StepResult) else frozenset()
139
+ return tuple(agent for agent in last.observations if agent not in ended)
140
+
141
+ return _participants(env, "active_agents", default)
142
+
143
+
144
+ def next_agents(env: object, last: ResetResult | StepResult) -> tuple[str, ...]:
145
+ """The agents that act in the next step, after ``last``, the latest reset or step result.
146
+
147
+ The environment's ``next_agents`` if it has them. Otherwise, every active
148
+ agent (see ``active_agents``), all at once.
149
+ """
150
+ return _participants(env, "next_agents", lambda: active_agents(env, last))
151
+
152
+
153
+ def _participants(
154
+ env: object, member: str, default: Callable[[], tuple[str, ...]]
155
+ ) -> tuple[str, ...]:
156
+ declared = getattr(env, member, None)
157
+ if declared is None:
158
+ return default()
159
+ return names(
160
+ declared,
161
+ f"{name_of(env)}.{member}",
162
+ of="agent ids",
163
+ example="('player_1',), read without calling it",
164
+ )
165
+
166
+
167
+ def _reset_takes_a_seed(env: object) -> bool:
168
+ return takes(getattr(env, "reset", None), "seed")
@@ -0,0 +1,53 @@
1
+ """Errors specific to environments."""
2
+
3
+ from ..core.errors import SSAPlingError
4
+
5
+
6
+ class EnvironmentCommunicationError(SSAPlingError, ConnectionError):
7
+ """A remote environment could not be reached, so the outcome of a call is unknown.
8
+
9
+ This is not the end of an episode: an episode ends only through the
10
+ termination and truncation signals of a ``StepResult``. A remote adapter
11
+ raises this error when it loses its connection, and the runner raises it
12
+ when an environment does not answer in time. Neither retries the call,
13
+ because a step that may already have executed must not be submitted
14
+ twice.
15
+
16
+ Attributes:
17
+ environment: The environment's class name.
18
+ operation: The call that failed, such as ``"step"``.
19
+ may_have_executed: Whether the call may have taken effect anyway, as
20
+ a step sent to a service that did not answer may have.
21
+ reason: What went wrong.
22
+ """
23
+
24
+ def __init__(
25
+ self, environment: str, operation: str, reason: str, *, may_have_executed: bool
26
+ ) -> None:
27
+ self.environment = environment
28
+ self.operation = operation
29
+ self.reason = reason
30
+ self.may_have_executed = may_have_executed
31
+ effect = (
32
+ "it may have taken effect, so it was not retried"
33
+ if may_have_executed
34
+ else "it did not take effect"
35
+ )
36
+ super().__init__(f"{environment}.{operation} failed to communicate: {reason}; {effect}.")
37
+
38
+
39
+ class UnsupportedCapabilityError(SSAPlingError, LookupError):
40
+ """An optional capability was used with an environment that does not support it.
41
+
42
+ Attributes:
43
+ environment: The environment's class name.
44
+ capability: The capability that was needed, such as ``"seeded_reset"``.
45
+ """
46
+
47
+ def __init__(self, environment: str, capability: str) -> None:
48
+ self.environment = environment
49
+ self.capability = capability
50
+ super().__init__(
51
+ f"Environment {environment} does not support {capability!r}; "
52
+ f"check environments.supports(env, {capability!r}) before using it."
53
+ )
@@ -0,0 +1,153 @@
1
+ """The environment runner: one awaitable entry point for sync and async environments."""
2
+
3
+ from collections.abc import Callable, Mapping
4
+ from concurrent.futures import Executor
5
+ from typing import Any
6
+
7
+ from ..core._declarations import name_of, takes
8
+ from ..core._execution import DeadlineExpiredError, Execution, Placement
9
+ from .contracts import supports
10
+ from .errors import EnvironmentCommunicationError, UnsupportedCapabilityError
11
+ from .types import ResetResult, StepResult
12
+
13
+ __all__ = ["EnvironmentRunner"]
14
+
15
+
16
+ class EnvironmentRunner:
17
+ """Resets, steps, and closes environments, whether written with ``def`` or ``async def``.
18
+
19
+ Example::
20
+
21
+ runner = EnvironmentRunner() # sync envs run in the loop's thread
22
+ runner = EnvironmentRunner(placement="thread") # sync envs run in a worker thread
23
+ first = await runner.reset(env, seed=7, options=instance.inputs)
24
+ result = await runner.step(env, {"student": action}, timeout=5.0)
25
+
26
+ The runner checks that each call is possible and that each result has the
27
+ right type. It never retries a call: a step that may already have
28
+ executed must not be submitted twice.
29
+
30
+ Args:
31
+ placement: Where a synchronous environment's methods run.
32
+ ``"direct"`` runs them in the event loop's thread, blocking the
33
+ loop until they return. ``"thread"`` runs them in a worker thread,
34
+ so the loop keeps going and a timeout can stop waiting. An
35
+ ``async def`` method always runs in the loop. To run an
36
+ environment in a separate process, build it with
37
+ ``ssapling.interaction.in_process``.
38
+ executor: For ``"thread"``: the thread pool to use. Pass a
39
+ ``ThreadPoolExecutor(max_workers=1)`` for an environment that must
40
+ always be called from the same thread.
41
+ """
42
+
43
+ def __init__(
44
+ self, *, placement: Placement = "direct", executor: Executor | None = None
45
+ ) -> None:
46
+ self._execution = Execution(placement, executor)
47
+
48
+ @property
49
+ def placement(self) -> Placement:
50
+ """Where a synchronous environment's methods run: ``"direct"`` or ``"thread"``."""
51
+ return self._execution.placement
52
+
53
+ async def reset(
54
+ self,
55
+ env: object,
56
+ *,
57
+ seed: int | None = None,
58
+ options: Any = None,
59
+ timeout: float | None = None,
60
+ ) -> ResetResult:
61
+ """Start a new episode of ``env``.
62
+
63
+ ``seed`` and ``options`` are passed only when given, so an environment
64
+ that takes neither needs neither parameter.
65
+
66
+ Raises:
67
+ UnsupportedCapabilityError: A seed was given, but the environment
68
+ does not support seeded reset.
69
+ EnvironmentCommunicationError: The environment did not answer
70
+ within ``timeout`` seconds, or a remote adapter lost its
71
+ connection.
72
+ TypeError: The environment does not take ``options=``, or reset
73
+ did not return a ``ResetResult``.
74
+ ValueError: An invalid ``timeout``.
75
+ """
76
+ reset = _method(env, "reset")
77
+ arguments: dict[str, Any] = {}
78
+ if seed is not None:
79
+ if not supports(env, "seeded_reset"):
80
+ raise UnsupportedCapabilityError(name_of(env), "seeded_reset")
81
+ arguments["seed"] = seed
82
+ if options is not None:
83
+ if not takes(reset, "options"):
84
+ raise TypeError(
85
+ f"{name_of(env)}.reset does not take options=, so it cannot be set up "
86
+ "from an instance's inputs; give it an options=None parameter"
87
+ )
88
+ arguments["options"] = options
89
+ result = await self._call(env, "reset", reset, timeout, **arguments)
90
+ if not isinstance(result, ResetResult):
91
+ raise TypeError(_wrong_result(env, "reset", result, "ResetResult"))
92
+ return result
93
+
94
+ async def step(
95
+ self, env: object, actions: Mapping[str, Any], *, timeout: float | None = None
96
+ ) -> StepResult:
97
+ """Apply ``actions``, keyed by agent id, to ``env`` and return the result.
98
+
99
+ Raises:
100
+ EnvironmentCommunicationError: The environment did not answer
101
+ within ``timeout`` seconds, or a remote adapter lost its
102
+ connection. The step may have executed, so it is not retried.
103
+ TypeError: ``actions`` is not keyed by agent id, or step did not
104
+ return a ``StepResult``.
105
+ ValueError: An invalid ``timeout``.
106
+ """
107
+ if not isinstance(actions, Mapping) or any(not isinstance(a, str) for a in actions):
108
+ raise TypeError(
109
+ f"actions must be keyed by agent id, even with one agent, such as "
110
+ f"{{'agent': action}}, got {actions!r}"
111
+ )
112
+ result = await self._call(env, "step", _method(env, "step"), timeout, actions)
113
+ if not isinstance(result, StepResult):
114
+ raise TypeError(_wrong_result(env, "step", result, "StepResult"))
115
+ return result
116
+
117
+ async def close(self, env: object) -> None:
118
+ """Release what ``env`` holds by calling its ``close()``, if it has one."""
119
+ close = getattr(env, "close", None)
120
+ if close is not None:
121
+ await self._execution.call(close)
122
+
123
+ async def _call(
124
+ self,
125
+ env: object,
126
+ operation: str,
127
+ method: Callable[..., Any],
128
+ timeout: float | None,
129
+ *args: Any,
130
+ **kwargs: Any,
131
+ ) -> object:
132
+ # The environment's own TimeoutError propagates as it is.
133
+ try:
134
+ return await self._execution.call_with_timeout(timeout, method, *args, **kwargs)
135
+ except DeadlineExpiredError as expired:
136
+ raise EnvironmentCommunicationError(
137
+ name_of(env), operation, str(expired), may_have_executed=True
138
+ ) from None
139
+
140
+
141
+ def _method(env: object, name: str) -> Callable[..., Any]:
142
+ method = getattr(env, name, None)
143
+ if not callable(method):
144
+ raise TypeError(f"{name_of(env)} has no {name} method, so it is not an environment")
145
+ return method # type: ignore[no-any-return]
146
+
147
+
148
+ def _wrong_result(env: object, operation: str, result: object, expected: str) -> str:
149
+ return (
150
+ f"{name_of(env)}.{operation} returned {type(result).__name__}, not a {expected}; "
151
+ f"an adapter converts the wrapped environment's result into a {expected} "
152
+ "(see docs/environments.md)"
153
+ )
@@ -0,0 +1,173 @@
1
+ """The result types of the Environments area: what reset and step return.
2
+
3
+ Data may import this module, and only this one, from ``environments``: a
4
+ record step holds the environment's transition result. So it holds plain data
5
+ and no environment behaviour.
6
+
7
+ Every per-agent value is keyed by agent id, even with one agent, so records
8
+ from single-agent and multi-agent environments have the same shape.
9
+ Episode-level signals sit beside the per-agent ones.
10
+ """
11
+
12
+ from collections.abc import Mapping, Sequence
13
+ from dataclasses import dataclass, field
14
+ from typing import Any
15
+
16
+ from ..core._declarations import keyed
17
+ from ..teachers.types import TeacherResponse
18
+
19
+ __all__ = ["ResetResult", "StepResult"]
20
+
21
+
22
+ @dataclass(frozen=True, slots=True, kw_only=True)
23
+ class ResetResult:
24
+ """What an environment returns when a new episode starts.
25
+
26
+ Attributes:
27
+ observations: Each agent's initial observation, keyed by agent id.
28
+ info: Metadata about the episode, keyed by name. SSAPling passes it
29
+ through uninterpreted.
30
+ action_restrictions: Optional. The actions each agent may currently
31
+ take, keyed by agent id, in the environment's own form (such as
32
+ a list of available actions or a mask). Whether an action fits
33
+ the interface is a separate question, answered by the action
34
+ descriptions.
35
+ """
36
+
37
+ observations: Mapping[str, Any]
38
+ info: Mapping[str, Any] = field(default_factory=dict)
39
+ action_restrictions: Mapping[str, Any] | None = None
40
+
41
+ def __post_init__(self) -> None:
42
+ object.__setattr__(self, "observations", _per_agent(self.observations, "observations"))
43
+ object.__setattr__(self, "info", keyed(self.info, "info", "names"))
44
+ if self.action_restrictions is not None:
45
+ restrictions = _per_agent(self.action_restrictions, "action_restrictions")
46
+ object.__setattr__(self, "action_restrictions", restrictions)
47
+
48
+
49
+ @dataclass(frozen=True, slots=True, kw_only=True)
50
+ class StepResult:
51
+ """What an environment returns after a step.
52
+
53
+ Attributes:
54
+ observations: Each agent's observation after the step, keyed by agent
55
+ id. For an agent whose part has just ended, this is its final
56
+ observation.
57
+ rewards: Optional. Each agent's reward, keyed by agent id. ``None``
58
+ means the environment has no rewards, which is not the same as a
59
+ reward of 0.
60
+ terminated: Optional. For each agent, whether its part ended because
61
+ the environment reached a terminal state (it won, lost, or
62
+ solved the problem). ``None`` means not reported.
63
+ truncated: Optional. For each agent, whether its part was cut off
64
+ before a terminal state, for example by a time limit. ``None``
65
+ means not reported.
66
+ episode_terminated: Whether the episode as a whole reached a terminal
67
+ state.
68
+ episode_truncated: Whether the episode as a whole was cut off.
69
+ info: Diagnostics, keyed by name, passed through uninterpreted.
70
+ executed_actions: Optional. The actions the environment actually
71
+ executed, keyed by agent id, when they may differ from those
72
+ submitted (for example after an intervention by a teacher the
73
+ environment owns). ``None`` means not reported.
74
+ teacher_responses: Optional. The responses of a teacher that the
75
+ environment owns, made during this step. ``None`` means the
76
+ environment reports no teacher.
77
+ action_restrictions: Optional. The actions each agent may take next,
78
+ keyed by agent id, in the environment's own form.
79
+
80
+ An agent finishing need not end the episode. When the episode ends is
81
+ the environment's rule: if it gives either episode signal, that is used
82
+ as given, and the other counts as ``False``. Only when it gives neither
83
+ does SSAPling fill the gap: the episode ends once every agent the result
84
+ reports on has ended, terminated if all of them terminated and truncated
85
+ otherwise. An environment that reports on only some of its agents
86
+ should give the episode signals itself.
87
+ """
88
+
89
+ observations: Mapping[str, Any]
90
+ rewards: Mapping[str, Any] | None = None
91
+ terminated: Mapping[str, bool] | None = None
92
+ truncated: Mapping[str, bool] | None = None
93
+ episode_terminated: bool | None = None
94
+ episode_truncated: bool | None = None
95
+ info: Mapping[str, Any] = field(default_factory=dict)
96
+ executed_actions: Mapping[str, Any] | None = None
97
+ teacher_responses: Sequence[TeacherResponse] | None = None
98
+ action_restrictions: Mapping[str, Any] | None = None
99
+
100
+ def __post_init__(self) -> None:
101
+ set_ = object.__setattr__
102
+ set_(self, "observations", _per_agent(self.observations, "observations"))
103
+ set_(self, "info", keyed(self.info, "info", "names"))
104
+ for name in ("rewards", "executed_actions", "action_restrictions"):
105
+ value = getattr(self, name)
106
+ if value is not None:
107
+ set_(self, name, _per_agent(value, name))
108
+ for name in ("terminated", "truncated"):
109
+ value = getattr(self, name)
110
+ if value is not None:
111
+ set_(self, name, _flags(value, name))
112
+ if self.teacher_responses is not None:
113
+ set_(self, "teacher_responses", _responses(self.teacher_responses))
114
+
115
+ for name in ("episode_terminated", "episode_truncated"):
116
+ value = getattr(self, name)
117
+ if value is not None and not isinstance(value, bool):
118
+ raise TypeError(f"{name} must be True or False, got {value!r}")
119
+ if self.episode_terminated is None and self.episode_truncated is None:
120
+ terminated, truncated = self._episode_end()
121
+ else:
122
+ terminated, truncated = bool(self.episode_terminated), bool(self.episode_truncated)
123
+ set_(self, "episode_terminated", terminated)
124
+ set_(self, "episode_truncated", truncated)
125
+
126
+ @property
127
+ def episode_over(self) -> bool:
128
+ """Whether the episode has ended, by termination or truncation."""
129
+ return bool(self.episode_terminated or self.episode_truncated)
130
+
131
+ @property
132
+ def ended_agents(self) -> frozenset[str]:
133
+ """The agents this result reports as terminated or truncated."""
134
+ terminated, truncated = self.terminated or {}, self.truncated or {}
135
+ return frozenset(
136
+ a for a in {*terminated, *truncated} if terminated.get(a) or truncated.get(a)
137
+ )
138
+
139
+ def _episode_end(self) -> tuple[bool, bool]:
140
+ """The episode signals when the environment gives neither: from the agents' own."""
141
+ agents = {*self.observations, *(self.terminated or {}), *(self.truncated or {})}
142
+ if not agents or not agents <= self.ended_agents:
143
+ return False, False
144
+ all_terminated = all((self.terminated or {}).get(agent) for agent in agents)
145
+ return all_terminated, not all_terminated
146
+
147
+
148
+ def _per_agent(value: object, what: str) -> dict[str, Any]:
149
+ if not isinstance(value, Mapping):
150
+ raise TypeError(
151
+ f"{what} must be keyed by agent id, even with one agent, such as "
152
+ f"{{'agent': ...}}, got {value!r}"
153
+ )
154
+ return keyed(value, what, "agent ids")
155
+
156
+
157
+ def _flags(value: object, what: str) -> dict[str, bool]:
158
+ flags = _per_agent(value, what)
159
+ for agent, flag in flags.items():
160
+ if not isinstance(flag, bool):
161
+ raise TypeError(
162
+ f"{what}[{agent!r}] must be True or False, got {flag!r}; "
163
+ "an adapter converts it, for example with bool()"
164
+ )
165
+ return flags
166
+
167
+
168
+ def _responses(value: object) -> tuple[TeacherResponse, ...]:
169
+ if isinstance(value, Mapping) or not isinstance(value, Sequence):
170
+ raise TypeError(f"teacher_responses must be a sequence of TeacherResponse, got {value!r}")
171
+ if any(not isinstance(response, TeacherResponse) for response in value):
172
+ raise TypeError("teacher_responses must contain only TeacherResponse objects")
173
+ return tuple(value)
@@ -0,0 +1,40 @@
1
+ """SSAPling evaluate.
2
+
3
+ Responsibility: User-defined assessments, measurement collection, and
4
+ aggregation.
5
+
6
+ Not its responsibility: Learning and choosing training instances.
7
+
8
+ May import: everything except train. Enforced by tests/test_layering.py.
9
+ """
10
+
11
+ from .aggregation import AggregationSettings, Summary, aggregate, aggregators
12
+ from .assessment import (
13
+ Assessment,
14
+ AssessmentResults,
15
+ AssessmentSettings,
16
+ StandardAssessment,
17
+ assessments,
18
+ load_results,
19
+ save_results,
20
+ )
21
+ from .measurement import InstanceResult, MeasuredValue, Trial, ValueStatus, measurements
22
+
23
+ __all__ = [
24
+ "AggregationSettings",
25
+ "Assessment",
26
+ "AssessmentResults",
27
+ "AssessmentSettings",
28
+ "InstanceResult",
29
+ "MeasuredValue",
30
+ "StandardAssessment",
31
+ "Summary",
32
+ "Trial",
33
+ "ValueStatus",
34
+ "aggregate",
35
+ "aggregators",
36
+ "assessments",
37
+ "load_results",
38
+ "measurements",
39
+ "save_results",
40
+ ]