bs-simulators 0.1.2__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.
- bs_simulators/__init__.py +44 -0
- bs_simulators/__main__.py +12 -0
- bs_simulators/catalogue/__init__.py +160 -0
- bs_simulators/catalogue/_validation.py +159 -0
- bs_simulators/catalogue/dc-motor.toml +46 -0
- bs_simulators/catalogue/neutralization.toml +63 -0
- bs_simulators/catalogue/pendulum.toml +37 -0
- bs_simulators/cli/__init__.py +5 -0
- bs_simulators/cli/commands.py +154 -0
- bs_simulators/cli/configuration.py +50 -0
- bs_simulators/cli/execution.py +53 -0
- bs_simulators/cli/presentation.py +134 -0
- bs_simulators/comms/__init__.py +5 -0
- bs_simulators/comms/adapters.py +47 -0
- bs_simulators/comms/http.py +179 -0
- bs_simulators/runtime/__init__.py +9 -0
- bs_simulators/runtime/_validation.py +51 -0
- bs_simulators/runtime/core.py +471 -0
- bs_simulators/runtime/protocols.py +174 -0
- bs_simulators/runtime/signals.py +51 -0
- bs_simulators/runtime/steppers.py +275 -0
- bs_simulators/viewers/__init__.py +13 -0
- bs_simulators/viewers/dc-motor.html +25 -0
- bs_simulators/viewers/neutralization.html +25 -0
- bs_simulators/viewers/pendulum.html +25 -0
- bs_simulators/viewers/scenes.js +143 -0
- bs_simulators/viewers/viewer.css +10 -0
- bs_simulators/viewers/viewer.js +48 -0
- bs_simulators-0.1.2.dist-info/METADATA +65 -0
- bs_simulators-0.1.2.dist-info/RECORD +34 -0
- bs_simulators-0.1.2.dist-info/WHEEL +4 -0
- bs_simulators-0.1.2.dist-info/entry_points.txt +5 -0
- bs_simulators-0.1.2.dist-info/licenses/LICENSE +21 -0
- bs_simulators-0.1.2.dist-info/licenses/LICENSE.benchmark-systems +21 -0
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""Structural Python protocols used by simulation transport adapters."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Sequence
|
|
4
|
+
from typing import Any, Callable, Protocol, runtime_checkable
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@runtime_checkable
|
|
10
|
+
class SimulationPort(Protocol):
|
|
11
|
+
"""Expose measurements and input submission independently of transport.
|
|
12
|
+
|
|
13
|
+
Engines satisfy this protocol structurally: inheritance is not required.
|
|
14
|
+
Calls must return without waiting for integration or performing network
|
|
15
|
+
I/O. Implementations synchronize access to shared state and return detached,
|
|
16
|
+
JSON-compatible data that callers can inspect without changing the engine.
|
|
17
|
+
Starting and stopping an experiment are outside this protocol.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def snapshot(self) -> dict[str, Any]:
|
|
21
|
+
"""Return a detached snapshot of the latest committed simulation state.
|
|
22
|
+
|
|
23
|
+
Returns
|
|
24
|
+
-------
|
|
25
|
+
dict[str, Any]
|
|
26
|
+
Model-specific state and execution metadata. The pendulum includes
|
|
27
|
+
simulated time ``t``, state vector ``x``, applied input ``u``, and
|
|
28
|
+
execution ``status``. ``Simulation`` also reports ``input_saturated``,
|
|
29
|
+
with one flag per applied input. Its sequence fields distinguish accepted,
|
|
30
|
+
pending, and applied inputs. Transport adapters pass this data
|
|
31
|
+
through without assuming a particular state-vector layout.
|
|
32
|
+
|
|
33
|
+
Notes
|
|
34
|
+
-----
|
|
35
|
+
Reading must not advance the simulation or wait for the next step.
|
|
36
|
+
Physics values describe a committed integration result; receipt and
|
|
37
|
+
input metadata may be refreshed when the snapshot is requested.
|
|
38
|
+
"""
|
|
39
|
+
...
|
|
40
|
+
|
|
41
|
+
def read_measurements(self) -> dict[str, Any]:
|
|
42
|
+
"""Return detached measurements keyed by their public signal names.
|
|
43
|
+
|
|
44
|
+
Returns
|
|
45
|
+
-------
|
|
46
|
+
dict[str, Any]
|
|
47
|
+
Named values corresponding to the signals described by
|
|
48
|
+
``describe_signals()``. For the pendulum these are ``theta``,
|
|
49
|
+
``omega``, ``torque``, ``time``, and ``status``. Readable inputs
|
|
50
|
+
report the applied value. ``Simulation`` clips state measurements
|
|
51
|
+
at configured sensor limits and exposes the model state in ``snapshot()``.
|
|
52
|
+
|
|
53
|
+
Notes
|
|
54
|
+
-----
|
|
55
|
+
Bridges use these names to map measurements to external addresses
|
|
56
|
+
without interpreting the engine's internal state vector. Reading
|
|
57
|
+
does not advance the simulation.
|
|
58
|
+
"""
|
|
59
|
+
...
|
|
60
|
+
|
|
61
|
+
def describe_signals(self) -> list[dict[str, Any]]:
|
|
62
|
+
"""Return detached descriptions of the engine's public signals.
|
|
63
|
+
|
|
64
|
+
Returns
|
|
65
|
+
-------
|
|
66
|
+
list[dict[str, Any]]
|
|
67
|
+
Each description contains ``name``, ``unit``, ``dtype``,
|
|
68
|
+
``direction``, ``lower``, and ``upper``. Direction is relative to
|
|
69
|
+
the simulator: ``input`` permits writes and ``output`` is read-only.
|
|
70
|
+
All described signals can be read. Bounds are inclusive; ``None``
|
|
71
|
+
means no configured bound. Input descriptions define the order
|
|
72
|
+
expected by ``submit_input()``.
|
|
73
|
+
|
|
74
|
+
Notes
|
|
75
|
+
-----
|
|
76
|
+
Descriptions provide metadata, not transport addresses. An adapter's
|
|
77
|
+
named writes must supply the complete set of input signals.
|
|
78
|
+
"""
|
|
79
|
+
...
|
|
80
|
+
|
|
81
|
+
def submit_input(self, u: Sequence[float], *, controller_id: str,
|
|
82
|
+
source_timestamp: str | None = None
|
|
83
|
+
) -> dict[str, Any]:
|
|
84
|
+
"""Validate and enqueue a complete input vector for a future interval.
|
|
85
|
+
|
|
86
|
+
Parameters
|
|
87
|
+
----------
|
|
88
|
+
u : Sequence[float]
|
|
89
|
+
Complete finite input vector, ordered as the input signals from
|
|
90
|
+
``describe_signals()``. For the pendulum this is ``[torque]``.
|
|
91
|
+
``Simulation`` clips finite requests to configured actuator limits.
|
|
92
|
+
controller_id : str
|
|
93
|
+
Identity of the submitting controller. It must match the engine's
|
|
94
|
+
explicitly selected active controller; it is not authentication.
|
|
95
|
+
source_timestamp : str or None, optional
|
|
96
|
+
ISO 8601 UTC timestamp with ``Z`` or a zero UTC offset. This is
|
|
97
|
+
diagnostic metadata, not a scheduled application time. Receipt
|
|
98
|
+
times use the engine's local monotonic clock.
|
|
99
|
+
|
|
100
|
+
Returns
|
|
101
|
+
-------
|
|
102
|
+
dict[str, Any]
|
|
103
|
+
Acceptance acknowledgement. The pendulum returns
|
|
104
|
+
``accepted_input_seq`` and ``applied_input_seq`` to distinguish
|
|
105
|
+
receipt from physical application. Its snapshot reports the
|
|
106
|
+
committed input sequence as ``input_seq``.
|
|
107
|
+
|
|
108
|
+
Raises
|
|
109
|
+
------
|
|
110
|
+
ValueError
|
|
111
|
+
If the vector, controller identifier, or timestamp is invalid.
|
|
112
|
+
PermissionError
|
|
113
|
+
If the submitting controller is not the active controller.
|
|
114
|
+
RuntimeError
|
|
115
|
+
If the engine is no longer accepting inputs.
|
|
116
|
+
|
|
117
|
+
Notes
|
|
118
|
+
-----
|
|
119
|
+
Acceptance does not wait for integration or guarantee immediate
|
|
120
|
+
application. The latest pending vector replaces earlier pending
|
|
121
|
+
vectors and is held constant over an integration interval. If no new
|
|
122
|
+
command arrives, the last applied input remains active indefinitely. Rejected
|
|
123
|
+
commands must leave the accepted input and receipt metadata unchanged.
|
|
124
|
+
"""
|
|
125
|
+
...
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@runtime_checkable
|
|
129
|
+
class Stepper(Protocol):
|
|
130
|
+
"""Structural interface for one simulation's numerical integration.
|
|
131
|
+
|
|
132
|
+
A Simulation owns a fresh stepper exclusively. Only its physics worker
|
|
133
|
+
calls ``step``. Initialization and stepping must commit time, state, and
|
|
134
|
+
derivatives atomically: failed operations leave the last committed result
|
|
135
|
+
unchanged. Properties return detached state vectors.
|
|
136
|
+
"""
|
|
137
|
+
|
|
138
|
+
@property
|
|
139
|
+
def t(self) -> float:
|
|
140
|
+
"""Absolute time of the last committed integration result."""
|
|
141
|
+
...
|
|
142
|
+
|
|
143
|
+
@property
|
|
144
|
+
def x(self) -> np.ndarray:
|
|
145
|
+
"""Detached state vector at ``t``; unavailable before initialization."""
|
|
146
|
+
...
|
|
147
|
+
|
|
148
|
+
@property
|
|
149
|
+
def xdot(self) -> np.ndarray | None:
|
|
150
|
+
"""Detached DAE derivative vector at ``t``, or None for an ODE stepper."""
|
|
151
|
+
...
|
|
152
|
+
|
|
153
|
+
def initialize(self, model: Callable, x0: Sequence[float], *,
|
|
154
|
+
t0: float = 0.0, u0: Sequence[float]) -> None:
|
|
155
|
+
"""Bind a model and initial vectors without advancing simulated time.
|
|
156
|
+
|
|
157
|
+
The normalized model is called as ``model(t, x, u)`` by an ODE
|
|
158
|
+
stepper or ``model(t, x, xdot, u)`` by a DAE stepper. Input is always
|
|
159
|
+
a complete vector here; Simulation adapts model keyword arguments.
|
|
160
|
+
DAE implementations may make algebraic values consistent while
|
|
161
|
+
preserving the configured fixed states. Reinitializing a bound
|
|
162
|
+
stepper must raise RuntimeError rather than sharing its state.
|
|
163
|
+
"""
|
|
164
|
+
...
|
|
165
|
+
|
|
166
|
+
def step(self, dt: float, u: Sequence[float]) -> np.ndarray:
|
|
167
|
+
"""Advance one positive interval with a frozen input vector.
|
|
168
|
+
|
|
169
|
+
Return a detached state at ``t + dt``. Use absolute model time and
|
|
170
|
+
leave committed state unchanged on validation or solver failure.
|
|
171
|
+
Simulation calls this method internally; it is not a separate
|
|
172
|
+
public execution mode.
|
|
173
|
+
"""
|
|
174
|
+
...
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Transport-independent signal descriptions and command metadata validation."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import asdict, dataclass
|
|
4
|
+
from datetime import datetime, timedelta, timezone
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass(frozen=True)
|
|
8
|
+
class SignalDescriptor:
|
|
9
|
+
"""Describe a signal from the simulator's perspective.
|
|
10
|
+
|
|
11
|
+
``direction='input'`` permits writes; all signals can be read. Optional
|
|
12
|
+
bounds are inclusive actuator limits for inputs and sensor limits for
|
|
13
|
+
output measurements. None leaves that endpoint unbounded. Transport
|
|
14
|
+
adapters map their own addresses to these names.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
name: str
|
|
18
|
+
unit: str
|
|
19
|
+
dtype: str
|
|
20
|
+
direction: str
|
|
21
|
+
lower: float | None = None
|
|
22
|
+
upper: float | None = None
|
|
23
|
+
|
|
24
|
+
def as_dict(self):
|
|
25
|
+
"""Return an independent dictionary representation suitable for transport metadata."""
|
|
26
|
+
return asdict(self)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def controller_identifier(value):
|
|
31
|
+
"""Validate and return a controller label of at most 128 characters without whitespace padding or control characters."""
|
|
32
|
+
if not isinstance(value, str) or not value or value != value.strip() or len(value) > 128:
|
|
33
|
+
raise ValueError('controller_id must be a non-empty identifier of at most 128 characters')
|
|
34
|
+
if any(ord(character) < 32 for character in value):
|
|
35
|
+
raise ValueError('controller_id must not contain control characters')
|
|
36
|
+
return value
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def validate_source_timestamp(source_timestamp):
|
|
40
|
+
"""Normalize an optional diagnostic UTC timestamp without scheduling input."""
|
|
41
|
+
if source_timestamp is None:
|
|
42
|
+
return None
|
|
43
|
+
if not isinstance(source_timestamp, str):
|
|
44
|
+
raise ValueError('source_timestamp must be an ISO 8601 UTC timestamp')
|
|
45
|
+
try:
|
|
46
|
+
timestamp = datetime.fromisoformat(source_timestamp)
|
|
47
|
+
except ValueError as exc:
|
|
48
|
+
raise ValueError('source_timestamp must be an ISO 8601 UTC timestamp') from exc
|
|
49
|
+
if timestamp.tzinfo is None or timestamp.utcoffset() != timedelta(0):
|
|
50
|
+
raise ValueError('source_timestamp must include a UTC offset (Z or +00:00)')
|
|
51
|
+
return timestamp.astimezone(timezone.utc).isoformat().replace('+00:00', 'Z')
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
"""Numerical integration between input boundaries, independent of pacing.
|
|
2
|
+
|
|
3
|
+
Steppers have one exclusive owner. They neither wait for wall time nor perform
|
|
4
|
+
communication I/O. Models use the normalized signatures supplied by Simulation;
|
|
5
|
+
physical model implementations remain in benchmark-systems or user code.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
from scipy.integrate import solve_ivp
|
|
12
|
+
from solve_dae.integrate import consistent_initial_conditions, solve_dae
|
|
13
|
+
|
|
14
|
+
from ._validation import _finite, _vector
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _readonly_input(name, values, size=None):
|
|
18
|
+
"""Return a detached finite input vector protected against model-side writes."""
|
|
19
|
+
result = _vector(name, values, size, allow_empty=True)
|
|
20
|
+
result.flags.writeable = False
|
|
21
|
+
return result
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _fixed_indices(values):
|
|
25
|
+
"""Normalize unique nonnegative state indices; dimensional bounds are checked when the model is initialized."""
|
|
26
|
+
if values is None:
|
|
27
|
+
return None
|
|
28
|
+
try:
|
|
29
|
+
values = tuple(values)
|
|
30
|
+
except TypeError as exc:
|
|
31
|
+
raise ValueError('fixed_x must be a sequence of state indices or None') from exc
|
|
32
|
+
if any(isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, np.integer))
|
|
33
|
+
for value in values):
|
|
34
|
+
raise ValueError('fixed_x must contain integer state indices')
|
|
35
|
+
if any(value < 0 for value in values) or len(set(values)) != len(values):
|
|
36
|
+
raise ValueError('fixed_x indices must be nonnegative and unique')
|
|
37
|
+
try:
|
|
38
|
+
return np.asarray(values, dtype=int)
|
|
39
|
+
except (ValueError, OverflowError) as exc:
|
|
40
|
+
raise ValueError('fixed_x indices must be representable integers') from exc
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class _ConfiguredStepper:
|
|
44
|
+
"""Shared state access and configuration; public steppers define the solver."""
|
|
45
|
+
|
|
46
|
+
_methods = ()
|
|
47
|
+
|
|
48
|
+
def __init__(self, *, method, rtol, atol):
|
|
49
|
+
"""Validate the solver method and positive tolerances, leaving the model uninitialized."""
|
|
50
|
+
if not isinstance(method, str) or method not in self._methods:
|
|
51
|
+
raise ValueError(f'method must be one of {self._methods}')
|
|
52
|
+
self._method = method
|
|
53
|
+
self._rtol = _finite('rtol', rtol, positive=True)
|
|
54
|
+
self._atol = _finite('atol', atol, positive=True)
|
|
55
|
+
self._model = None
|
|
56
|
+
self._input_size = None
|
|
57
|
+
self._state = None
|
|
58
|
+
|
|
59
|
+
def _require_initialized(self):
|
|
60
|
+
"""Reject state access or integration before successful initialization."""
|
|
61
|
+
if self._state is None:
|
|
62
|
+
raise RuntimeError('stepper is not initialized; call initialize() first')
|
|
63
|
+
|
|
64
|
+
def _initial_values(self, model, x0, t0, u0):
|
|
65
|
+
"""Validate first-use model data and return detached time, state and read-only input values."""
|
|
66
|
+
if self._state is not None:
|
|
67
|
+
raise RuntimeError('stepper is already initialized; create a new stepper for another run')
|
|
68
|
+
if not callable(model):
|
|
69
|
+
raise ValueError('model must be callable')
|
|
70
|
+
return (_finite('t0', t0), _vector('x0', x0), _readonly_input('u0', u0))
|
|
71
|
+
|
|
72
|
+
def _step_values(self, dt, u):
|
|
73
|
+
"""Validate an integration interval and return its absolute end time and frozen input vector."""
|
|
74
|
+
self._require_initialized()
|
|
75
|
+
dt = _finite('dt', dt, positive=True)
|
|
76
|
+
held = _readonly_input('u', u, self._input_size)
|
|
77
|
+
target = self._state[0] + dt
|
|
78
|
+
if not np.isfinite(target) or target <= self._state[0]:
|
|
79
|
+
raise ValueError('dt must advance finite simulation time')
|
|
80
|
+
return target, held
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def t(self) -> float:
|
|
84
|
+
"""Current absolute simulation time; available after initialization."""
|
|
85
|
+
self._require_initialized()
|
|
86
|
+
return self._state[0]
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def x(self) -> np.ndarray:
|
|
90
|
+
"""Detached copy of the most recently committed state vector."""
|
|
91
|
+
self._require_initialized()
|
|
92
|
+
return self._state[1].copy()
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def xdot(self) -> np.ndarray | None:
|
|
96
|
+
"""Detached DAE derivatives, or None for an initialized ODE stepper."""
|
|
97
|
+
self._require_initialized()
|
|
98
|
+
return None if self._state[2] is None else self._state[2].copy()
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class ODEStepper(_ConfiguredStepper):
|
|
102
|
+
"""Advance a normalized ``model(t, x, u)`` using SciPy solve_ivp.
|
|
103
|
+
|
|
104
|
+
Parameters
|
|
105
|
+
----------
|
|
106
|
+
method : str, optional
|
|
107
|
+
SciPy integration method; default is RK45.
|
|
108
|
+
rtol, atol : float, optional
|
|
109
|
+
Positive scalar relative and absolute tolerances.
|
|
110
|
+
|
|
111
|
+
Notes
|
|
112
|
+
-----
|
|
113
|
+
Construct this object with solver configuration, then initialize it once
|
|
114
|
+
with a model, initial state, absolute time and complete input vector.
|
|
115
|
+
Every step freezes a detached, read-only input vector over its interval.
|
|
116
|
+
A failed initialization or step does not commit partial state. Successful
|
|
117
|
+
initialization is single-use; the object is not thread-safe and must be
|
|
118
|
+
owned exclusively by its simulation.
|
|
119
|
+
"""
|
|
120
|
+
|
|
121
|
+
_methods = ('RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA')
|
|
122
|
+
|
|
123
|
+
def __init__(self, *, method='RK45', rtol=1e-7, atol=1e-9):
|
|
124
|
+
"""Configure the SciPy method and error tolerances without binding a model."""
|
|
125
|
+
super().__init__(method=method, rtol=rtol, atol=atol)
|
|
126
|
+
|
|
127
|
+
def initialize(self, model, x0, *, t0=0.0, u0) -> None:
|
|
128
|
+
"""Bind a model and initial state after validating its derivative.
|
|
129
|
+
|
|
130
|
+
``model`` returns a finite one-dimensional derivative vector of the
|
|
131
|
+
same size as x0. ``u0`` defines the complete input size and may be an
|
|
132
|
+
empty vector for an autonomous plant. Time uses the model's units.
|
|
133
|
+
"""
|
|
134
|
+
time, state, held = self._initial_values(model, x0, t0, u0)
|
|
135
|
+
_vector('model derivative', model(time, state.copy(), held), state.size)
|
|
136
|
+
self._model = model
|
|
137
|
+
self._input_size = held.size
|
|
138
|
+
self._state = (time, state, None)
|
|
139
|
+
|
|
140
|
+
def step(self, dt, u) -> np.ndarray:
|
|
141
|
+
"""Advance one interval with constant input, returning detached state.
|
|
142
|
+
|
|
143
|
+
The model receives absolute time. Committed state changes only after
|
|
144
|
+
the solver succeeds and its output has been validated. ``xdot`` remains
|
|
145
|
+
None; evaluate the model separately when ODE derivatives are needed.
|
|
146
|
+
"""
|
|
147
|
+
target, held = self._step_values(dt, u)
|
|
148
|
+
start, state, _ = self._state
|
|
149
|
+
|
|
150
|
+
def rhs(time, values):
|
|
151
|
+
"""Evaluate a finite derivative vector with the interval input held constant."""
|
|
152
|
+
return _vector('model derivative', self._model(time, values, held), state.size)
|
|
153
|
+
|
|
154
|
+
result = solve_ivp(rhs, (start, target), state.copy(), t_eval=[target],
|
|
155
|
+
method=self._method, rtol=self._rtol, atol=self._atol)
|
|
156
|
+
if not result.success:
|
|
157
|
+
raise RuntimeError(f'ODE integration failed: {result.message}')
|
|
158
|
+
new_state = _vector('integrated state', result.y[:, -1], state.size)
|
|
159
|
+
self._state = (target, new_state, None)
|
|
160
|
+
return new_state.copy()
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class DAEStepper(_ConfiguredStepper):
|
|
164
|
+
"""Advance a normalized ``model(t, x, xdot, u)`` with solve-dae.
|
|
165
|
+
|
|
166
|
+
Parameters
|
|
167
|
+
----------
|
|
168
|
+
xdot0 : array-like
|
|
169
|
+
Finite one-dimensional initial derivative guess, matching the state
|
|
170
|
+
size supplied later to initialize(). A detached copy is retained.
|
|
171
|
+
fixed_x : sequence of int or None, optional
|
|
172
|
+
State indices held exactly fixed while consistency is recomputed.
|
|
173
|
+
None fixes every state component. For a differential/algebraic model,
|
|
174
|
+
supply its differential-state indices to allow algebraic states to
|
|
175
|
+
adjust at input changes. An empty sequence leaves all states free.
|
|
176
|
+
method : str, optional
|
|
177
|
+
solve-dae integration method, Radau by default; BDF is also supported.
|
|
178
|
+
rtol, atol : float, optional
|
|
179
|
+
Positive scalar relative and absolute tolerances used for consistency
|
|
180
|
+
calculation and integration.
|
|
181
|
+
|
|
182
|
+
Notes
|
|
183
|
+
-----
|
|
184
|
+
Consistency is recomputed at initialization and every step boundary with
|
|
185
|
+
the new frozen input. All calculations use local state/derivative copies;
|
|
186
|
+
a failed consistency calculation or integration leaves committed time,
|
|
187
|
+
state and derivatives unchanged. Only fixed_x indices are guaranteed
|
|
188
|
+
continuous through consistency correction. The installed consistency
|
|
189
|
+
routine supports differentiation index at most one; this wrapper does
|
|
190
|
+
not perform index reduction or promise support for higher-index systems.
|
|
191
|
+
Successful initialization is single-use and requires exclusive ownership.
|
|
192
|
+
"""
|
|
193
|
+
|
|
194
|
+
_methods = ('Radau', 'BDF')
|
|
195
|
+
|
|
196
|
+
def __init__(self, xdot0, *, fixed_x=None, method='Radau', rtol=1e-7, atol=1e-9):
|
|
197
|
+
"""Configure the solver, derivative guess and states preserved during consistency correction."""
|
|
198
|
+
super().__init__(method=method, rtol=rtol, atol=atol)
|
|
199
|
+
self._xdot0 = _vector('xdot0', xdot0)
|
|
200
|
+
self._fixed_x = _fixed_indices(fixed_x)
|
|
201
|
+
|
|
202
|
+
def _consistent(self, model, time, state, derivative, held):
|
|
203
|
+
"""Return consistent state and derivative copies, preserving fixed states and checking residual tolerances."""
|
|
204
|
+
size = state.size
|
|
205
|
+
fixed = np.arange(size) if self._fixed_x is None else self._fixed_x
|
|
206
|
+
if fixed.size and np.any(fixed >= size):
|
|
207
|
+
raise ValueError('fixed_x indices must lie within the state vector')
|
|
208
|
+
original = state.copy()
|
|
209
|
+
|
|
210
|
+
def residual(at, values, rates):
|
|
211
|
+
"""Evaluate the finite residual vector used for boundary consistency correction."""
|
|
212
|
+
return _vector('model residual', model(at, values, rates, held), size)
|
|
213
|
+
|
|
214
|
+
initial_residual = residual(time, state.copy(), derivative.copy())
|
|
215
|
+
try:
|
|
216
|
+
consistent_x, consistent_xdot, _ = consistent_initial_conditions(
|
|
217
|
+
residual, time, state.copy(), derivative.copy(),
|
|
218
|
+
fixed_y0=fixed.copy(), rtol=self._rtol, atol=self._atol,
|
|
219
|
+
)
|
|
220
|
+
except Exception as exc:
|
|
221
|
+
raise RuntimeError(f'DAE consistency calculation failed: {exc}') from exc
|
|
222
|
+
consistent_x = _vector('consistent state', consistent_x, size)
|
|
223
|
+
consistent_xdot = _vector('consistent derivatives', consistent_xdot, size)
|
|
224
|
+
# Explicit restoration preserves fixed components, including roundoff
|
|
225
|
+
# and signed zeros, even if a backend returns a perturbed copy.
|
|
226
|
+
consistent_x[fixed] = original[fixed]
|
|
227
|
+
corrected_residual = residual(time, consistent_x.copy(), consistent_xdot.copy())
|
|
228
|
+
with np.errstate(over='ignore', invalid='ignore', divide='ignore'):
|
|
229
|
+
scale = self._atol + self._rtol * np.abs(initial_residual)
|
|
230
|
+
error = np.linalg.norm(corrected_residual / scale) / np.sqrt(size)
|
|
231
|
+
if not np.isfinite(error) or error > 1.0:
|
|
232
|
+
raise RuntimeError('DAE consistency calculation did not satisfy residual tolerances')
|
|
233
|
+
return consistent_x, consistent_xdot
|
|
234
|
+
|
|
235
|
+
def initialize(self, model, x0, *, t0=0.0, u0) -> None:
|
|
236
|
+
"""Bind the plant after finding consistent initial state/derivatives.
|
|
237
|
+
|
|
238
|
+
Full state and derivative sizes must match. Initial algebraic guesses
|
|
239
|
+
come from x0; xdot0 supplies derivative guesses. The complete input
|
|
240
|
+
vector u0 determines the input size and may be empty.
|
|
241
|
+
"""
|
|
242
|
+
time, state, held = self._initial_values(model, x0, t0, u0)
|
|
243
|
+
derivative = _vector('xdot0', self._xdot0, state.size)
|
|
244
|
+
state, derivative = self._consistent(model, time, state, derivative, held)
|
|
245
|
+
self._model = model
|
|
246
|
+
self._input_size = held.size
|
|
247
|
+
self._state = (time, state, derivative)
|
|
248
|
+
|
|
249
|
+
def step(self, dt, u) -> np.ndarray:
|
|
250
|
+
"""Recompute boundary consistency, integrate, then commit atomically.
|
|
251
|
+
|
|
252
|
+
State components listed in fixed_x remain exact during the boundary
|
|
253
|
+
correction. After integration, xdot is taken from the solver's yp
|
|
254
|
+
output; it is not inferred by differencing states. All properties and
|
|
255
|
+
the returned vector expose detached copies.
|
|
256
|
+
"""
|
|
257
|
+
target, held = self._step_values(dt, u)
|
|
258
|
+
start, previous, previous_derivative = self._state
|
|
259
|
+
state, derivative = self._consistent(
|
|
260
|
+
self._model, start, previous, previous_derivative, held,
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
def residual(time, values, rates):
|
|
264
|
+
"""Evaluate a finite residual vector with the interval input held constant."""
|
|
265
|
+
return _vector('model residual', self._model(time, values, rates, held), state.size)
|
|
266
|
+
|
|
267
|
+
result = solve_dae(residual, (start, target), state.copy(), derivative.copy(),
|
|
268
|
+
method=self._method, t_eval=[target],
|
|
269
|
+
rtol=self._rtol, atol=self._atol)
|
|
270
|
+
if not result.success:
|
|
271
|
+
raise RuntimeError(f'DAE integration failed: {result.message}')
|
|
272
|
+
new_state = _vector('integrated state', result.y[:, -1], state.size)
|
|
273
|
+
new_derivative = _vector('integrated derivatives', result.yp[:, -1], state.size)
|
|
274
|
+
self._state = (target, new_state, new_derivative)
|
|
275
|
+
return new_state.copy()
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Packaged model scenes and shared browser assets; no simulation dependencies."""
|
|
2
|
+
|
|
3
|
+
VIEWER_FILES = {
|
|
4
|
+
'pendulum': 'pendulum.html',
|
|
5
|
+
'dc-motor': 'dc-motor.html',
|
|
6
|
+
'neutralization': 'neutralization.html',
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
ASSET_FILES = {
|
|
10
|
+
'viewer.js': 'text/javascript; charset=utf-8',
|
|
11
|
+
'scenes.js': 'text/javascript; charset=utf-8',
|
|
12
|
+
'viewer.css': 'text/css; charset=utf-8',
|
|
13
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en" data-viewer="dc-motor">
|
|
3
|
+
<meta charset="utf-8">
|
|
4
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
5
|
+
<title>DC motor</title>
|
|
6
|
+
<link rel="stylesheet" href="/assets/viewer.css">
|
|
7
|
+
<h1>DC motor</h1>
|
|
8
|
+
<canvas id="scene" aria-label="Motor shaft, angular velocity and current"></canvas>
|
|
9
|
+
<p id="time">t = — s</p>
|
|
10
|
+
<p id="status" role="status">Connecting to the simulator…</p>
|
|
11
|
+
<details>
|
|
12
|
+
<summary>Simulation data</summary>
|
|
13
|
+
<dl>
|
|
14
|
+
<dt>State</dt><dd id="motion">—</dd>
|
|
15
|
+
<dt>Instrument scales</dt><dd id="scales">—</dd>
|
|
16
|
+
<dt>Applied input</dt><dd id="input">—</dd>
|
|
17
|
+
<dt>Parameters</dt><dd id="parameters">—</dd>
|
|
18
|
+
<dt>Selected controller</dt><dd id="controller">—</dd>
|
|
19
|
+
<dt>Wall time / lag</dt><dd id="timing">—</dd>
|
|
20
|
+
<dt>Applied / pending sequence</dt><dd id="sequence">—</dd>
|
|
21
|
+
</dl>
|
|
22
|
+
<p id="error" role="alert"></p>
|
|
23
|
+
</details>
|
|
24
|
+
<script type="module" src="/assets/viewer.js"></script>
|
|
25
|
+
</html>
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en" data-viewer="neutralization">
|
|
3
|
+
<meta charset="utf-8">
|
|
4
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
5
|
+
<title>pH neutralization</title>
|
|
6
|
+
<link rel="stylesheet" href="/assets/viewer.css">
|
|
7
|
+
<h1>pH neutralization</h1>
|
|
8
|
+
<canvas id="scene" aria-label="Neutralization reactor with liquid level and pH gauges"></canvas>
|
|
9
|
+
<p id="time">t = — s</p>
|
|
10
|
+
<p id="status" role="status">Connecting to the simulator…</p>
|
|
11
|
+
<details>
|
|
12
|
+
<summary>Simulation data</summary>
|
|
13
|
+
<dl>
|
|
14
|
+
<dt>State</dt><dd id="motion">—</dd>
|
|
15
|
+
<dt>Instrument scales</dt><dd id="scales">—</dd>
|
|
16
|
+
<dt>Applied input</dt><dd id="input">—</dd>
|
|
17
|
+
<dt>Parameters</dt><dd id="parameters">—</dd>
|
|
18
|
+
<dt>Selected controller</dt><dd id="controller">—</dd>
|
|
19
|
+
<dt>Wall time / lag</dt><dd id="timing">—</dd>
|
|
20
|
+
<dt>Applied / pending sequence</dt><dd id="sequence">—</dd>
|
|
21
|
+
</dl>
|
|
22
|
+
<p id="error" role="alert"></p>
|
|
23
|
+
</details>
|
|
24
|
+
<script type="module" src="/assets/viewer.js"></script>
|
|
25
|
+
</html>
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en" data-viewer="pendulum">
|
|
3
|
+
<meta charset="utf-8">
|
|
4
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
5
|
+
<title>Pendulum</title>
|
|
6
|
+
<link rel="stylesheet" href="/assets/viewer.css">
|
|
7
|
+
<h1>Pendulum</h1>
|
|
8
|
+
<canvas id="scene" aria-label="Pendulum in Cartesian coordinates"></canvas>
|
|
9
|
+
<p id="time">t = — s</p>
|
|
10
|
+
<p id="status" role="status">Connecting to the simulator…</p>
|
|
11
|
+
<details>
|
|
12
|
+
<summary>Simulation data</summary>
|
|
13
|
+
<dl>
|
|
14
|
+
<dt>State</dt><dd id="motion">—</dd>
|
|
15
|
+
<dt>Instrument scales</dt><dd id="scales">—</dd>
|
|
16
|
+
<dt>Applied input</dt><dd id="input">—</dd>
|
|
17
|
+
<dt>Parameters</dt><dd id="parameters">—</dd>
|
|
18
|
+
<dt>Selected controller</dt><dd id="controller">—</dd>
|
|
19
|
+
<dt>Wall time / lag</dt><dd id="timing">—</dd>
|
|
20
|
+
<dt>Applied / pending sequence</dt><dd id="sequence">—</dd>
|
|
21
|
+
</dl>
|
|
22
|
+
<p id="error" role="alert"></p>
|
|
23
|
+
</details>
|
|
24
|
+
<script type="module" src="/assets/viewer.js"></script>
|
|
25
|
+
</html>
|