bs-simulators 0.1.2__tar.gz → 0.1.4__tar.gz
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-0.1.2 → bs_simulators-0.1.4}/PKG-INFO +5 -2
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/README.md +2 -1
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/docs/catalogue.md +40 -2
- bs_simulators-0.1.4/docs/http.md +161 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/docs/index.md +3 -2
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/pyproject.toml +3 -1
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/src/bs_simulators/__init__.py +1 -1
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/src/bs_simulators/catalogue/__init__.py +17 -2
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/src/bs_simulators/catalogue/_validation.py +20 -1
- bs_simulators-0.1.4/src/bs_simulators/catalogue/johansson.toml +78 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/src/bs_simulators/cli/commands.py +2 -1
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/src/bs_simulators/cli/presentation.py +8 -2
- bs_simulators-0.1.4/src/bs_simulators/comms/http/__init__.py +5 -0
- bs_simulators-0.1.4/src/bs_simulators/comms/http/app.py +140 -0
- bs_simulators-0.1.4/src/bs_simulators/comms/http/middleware.py +99 -0
- bs_simulators-0.1.4/src/bs_simulators/comms/http/server.py +86 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/src/bs_simulators/viewers/__init__.py +1 -0
- bs_simulators-0.1.4/src/bs_simulators/viewers/johansson.html +25 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/src/bs_simulators/viewers/scenes.js +103 -3
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/tests/test_bundled_experiments.py +27 -4
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/tests/test_catalogue.py +18 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/tests/test_distribution.py +2 -1
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/tests/test_simulation_adapters.py +84 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/tests/viewer_scales.test.mjs +17 -0
- bs_simulators-0.1.2/docs/http.md +0 -81
- bs_simulators-0.1.2/src/bs_simulators/comms/http.py +0 -179
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/.python-version +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/.readthedocs.yaml +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/AGENTS.md +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/LICENSE +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/LICENSE.benchmark-systems +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/docs/_static/architecture/configuration-access.svg +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/docs/_static/architecture/functional-core.svg +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/docs/_static/architecture/runtime-sequence.svg +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/docs/api.md +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/docs/architecture.md +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/docs/common-pitfalls.md +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/docs/conf.py +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/docs/development.md +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/docs/installation.md +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/docs/pendulum.md +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/docs/recording.md +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/docs/requirements.txt +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/docs/simulation.md +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/examples/pendulum_core.ipynb +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/examples/pendulum_signal_adapter.py +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/examples/pendulum_sil_controller.py +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/examples/pendulum_sil_replay.py +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/src/bs_simulators/__main__.py +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/src/bs_simulators/catalogue/dc-motor.toml +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/src/bs_simulators/catalogue/neutralization.toml +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/src/bs_simulators/catalogue/pendulum.toml +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/src/bs_simulators/cli/__init__.py +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/src/bs_simulators/cli/configuration.py +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/src/bs_simulators/cli/execution.py +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/src/bs_simulators/comms/__init__.py +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/src/bs_simulators/comms/adapters.py +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/src/bs_simulators/runtime/__init__.py +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/src/bs_simulators/runtime/_validation.py +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/src/bs_simulators/runtime/core.py +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/src/bs_simulators/runtime/protocols.py +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/src/bs_simulators/runtime/signals.py +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/src/bs_simulators/runtime/steppers.py +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/src/bs_simulators/viewers/dc-motor.html +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/src/bs_simulators/viewers/neutralization.html +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/src/bs_simulators/viewers/pendulum.html +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/src/bs_simulators/viewers/viewer.css +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/src/bs_simulators/viewers/viewer.js +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/tests/test_cli.py +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/tests/test_dae_failure.py +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/tests/test_generic_simulation.py +0 -0
- {bs_simulators-0.1.2 → bs_simulators-0.1.4}/tests/test_simulation.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: bs-simulators
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.4
|
|
4
4
|
Summary: Live simulators and transport adapters for benchmark-systems models
|
|
5
5
|
License: MIT
|
|
6
6
|
Requires-Python: >=3.13
|
|
@@ -9,6 +9,8 @@ Requires-Dist: numpy>=2.1.0
|
|
|
9
9
|
Requires-Dist: scipy>=1.14.1
|
|
10
10
|
Requires-Dist: solve-dae>=0.2.4
|
|
11
11
|
Requires-Dist: typer>=0.27.3
|
|
12
|
+
Requires-Dist: fastapi<1,>=0.115
|
|
13
|
+
Requires-Dist: uvicorn<1,>=0.34
|
|
12
14
|
Provides-Extra: replay
|
|
13
15
|
Requires-Dist: benchmark-systems[anim]>=1.2.0; extra == "replay"
|
|
14
16
|
Requires-Dist: Pillow>=11.0.0; extra == "replay"
|
|
@@ -41,7 +43,8 @@ After installation, launch the bundled pendulum and open
|
|
|
41
43
|
bs-simulators --catalogue pendulum
|
|
42
44
|
```
|
|
43
45
|
|
|
44
|
-
The catalogue also includes a DC motor
|
|
46
|
+
The catalogue also includes a DC motor, a pH neutralization process, and the
|
|
47
|
+
Johansson four-tank process.
|
|
45
48
|
Use `bs-simulators --list-catalogue` to see the available configurations.
|
|
46
49
|
|
|
47
50
|
## Run a simulation from Python
|
|
@@ -25,7 +25,8 @@ After installation, launch the bundled pendulum and open
|
|
|
25
25
|
bs-simulators --catalogue pendulum
|
|
26
26
|
```
|
|
27
27
|
|
|
28
|
-
The catalogue also includes a DC motor
|
|
28
|
+
The catalogue also includes a DC motor, a pH neutralization process, and the
|
|
29
|
+
Johansson four-tank process.
|
|
29
30
|
Use `bs-simulators --list-catalogue` to see the available configurations.
|
|
30
31
|
|
|
31
32
|
## Run a simulation from Python
|
|
@@ -84,6 +84,7 @@ The bundled entries are:
|
|
|
84
84
|
| `pendulum` | `pendulum` | angle, angular velocity | torque | Pendulum Canvas |
|
|
85
85
|
| `dc-motor` | `dc_motor` | angle, angular velocity, current | voltage | Motor shaft and indicators |
|
|
86
86
|
| `neutralization` | `neutralization` (DAE) | Wa4, Wb4, height, pH | alkaline feed q3 | Reactor, level and pH gauges |
|
|
87
|
+
| `johansson` | `johansson` | Four tank heights | Two pump setpoints and two valve fractions | Tanks, crossed feeds and drainage |
|
|
87
88
|
|
|
88
89
|
Each entry includes a browser scene following its Matplotlib counterpart in
|
|
89
90
|
`benchmark-systems`. State and named signals remain available through
|
|
@@ -100,7 +101,7 @@ vectors; `--dt` and `--controller` override their configuration values.
|
|
|
100
101
|
```{doctest}
|
|
101
102
|
>>> from bs_simulators.catalogue import list_configurations, load_configuration
|
|
102
103
|
>>> list_configurations()
|
|
103
|
-
['dc-motor', 'neutralization', 'pendulum']
|
|
104
|
+
['dc-motor', 'johansson', 'neutralization', 'pendulum']
|
|
104
105
|
>>> configuration = load_configuration("pendulum")
|
|
105
106
|
>>> configuration.parameters["m"]
|
|
106
107
|
1.0
|
|
@@ -228,12 +229,13 @@ and the recording path when requested. Worker failures appear in an error
|
|
|
228
229
|
panel and return a nonzero exit code. Usage errors retain the standard
|
|
229
230
|
Typer error presentation.
|
|
230
231
|
|
|
231
|
-
##
|
|
232
|
+
## Bundled experiments
|
|
232
233
|
|
|
233
234
|
```shell
|
|
234
235
|
pdm run bs-simulators --catalogue pendulum
|
|
235
236
|
pdm run bs-simulators --catalogue dc-motor
|
|
236
237
|
pdm run bs-simulators --catalogue neutralization
|
|
238
|
+
pdm run bs-simulators --catalogue johansson
|
|
237
239
|
```
|
|
238
240
|
|
|
239
241
|
Run one command at a time and open the displayed viewer address. Use distinct
|
|
@@ -276,6 +278,42 @@ say L/s, whereas its reference experiment and Matplotlib viewer use raw
|
|
|
276
278
|
cm³/s values. No conversion is performed by this package. Keep the chosen
|
|
277
279
|
flow and geometry units consistent when overriding these parameters.
|
|
278
280
|
|
|
281
|
+
### Johansson four-tank process
|
|
282
|
+
|
|
283
|
+
The configuration starts with all four tanks at 10 cm and uses a step of
|
|
284
|
+
0.3 simulated seconds. The initial pump commands come from the first sample
|
|
285
|
+
in the reference animation. The input vector is `[u1, u2, gamma1, gamma2]`.
|
|
286
|
+
Pump setpoints are percentages from 0 to 100. Valve fractions range from
|
|
287
|
+
0 to 1 and start at 0.7 and 0.6. The states `[h1, h2, h3, h4]` are measured
|
|
288
|
+
in centimetres.
|
|
289
|
+
|
|
290
|
+
```shell
|
|
291
|
+
bs-simulators --catalogue johansson --u0 "[30, 60, 0.7, 0.6]"
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
Send the complete vector when changing a valve during a run. For example,
|
|
295
|
+
`{"u": [30, 60, 0.2, 0.8]}` keeps the two pump setpoints and changes both
|
|
296
|
+
valves. The catalogue uses the following TOML table to pass the four inputs
|
|
297
|
+
to the two vector arguments of the model.
|
|
298
|
+
|
|
299
|
+
```toml
|
|
300
|
+
[input_groups]
|
|
301
|
+
u = [0, 1]
|
|
302
|
+
gamma = [2, 3]
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
Each entry names a keyword-only model argument and its zero-based positions
|
|
306
|
+
in the input vector. The groups cover each position exactly once. A grouped
|
|
307
|
+
argument takes its value from the input vector, so set its initial
|
|
308
|
+
components in `u0`.
|
|
309
|
+
|
|
310
|
+
The viewer shows the lower tanks 1 and 2, the upper tanks 3 and 4, and the
|
|
311
|
+
split of each applied pump command. Valve fraction `gamma1` sends a share
|
|
312
|
+
of pump 1 to tank 4, and `gamma2` sends a share of pump 2 to tank 3. The
|
|
313
|
+
remaining shares feed tanks 1 and 2 respectively. Tank 3 drains into tank 1,
|
|
314
|
+
and tank 4 drains into tank 2. The water fills use the physical tank capacities
|
|
315
|
+
from `h_max` as their scales.
|
|
316
|
+
|
|
279
317
|
## Instrument scales from signal descriptions
|
|
280
318
|
|
|
281
319
|
The browser reads `/api/signals` and uses `lower` and `upper` as the scale
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
# HTTP observation and control
|
|
2
|
+
|
|
3
|
+
The local HTTP interface observes a simulation independently of its physics
|
|
4
|
+
worker. FastAPI runs on Uvicorn and listens on loopback. The browser polls
|
|
5
|
+
the latest state approximately every 50 ms.
|
|
6
|
+
|
|
7
|
+
| Endpoint | Purpose |
|
|
8
|
+
| --- | --- |
|
|
9
|
+
| `GET /api/state` | Detached state, inputs, timing and command metadata |
|
|
10
|
+
| `GET /api/measurements` | Named sensor readings, applied inputs, time and status |
|
|
11
|
+
| `GET /api/signals` | Ordered signal descriptions |
|
|
12
|
+
| `POST /api/input` | Submit a complete input vector |
|
|
13
|
+
| `GET /` | Configured browser scene, if available |
|
|
14
|
+
| `GET /assets/...` | Registered shared viewer scripts and styles |
|
|
15
|
+
| `GET /docs` | Interactive API documentation for the local server |
|
|
16
|
+
|
|
17
|
+
A request body such as `{"u": [2.0]}` submits a torque command to the pendulum.
|
|
18
|
+
An optional `source_timestamp` must be an ISO 8601 UTC timestamp; it records
|
|
19
|
+
the sender's time without scheduling the command. A successful request
|
|
20
|
+
returns HTTP 202, acknowledging acceptance.
|
|
21
|
+
|
|
22
|
+
## Select the controller
|
|
23
|
+
|
|
24
|
+
The server submits commands with controller identity `http`. Construct the
|
|
25
|
+
simulation with `active_controller="http"` to permit these writes. Other controller identities
|
|
26
|
+
can observe through HTTP, but HTTP cannot replace their input. Identities
|
|
27
|
+
provide local ownership arbitration, not device authentication.
|
|
28
|
+
|
|
29
|
+
Compare the acknowledgement's `accepted_input_seq` with the snapshot's
|
|
30
|
+
`input_seq` to observe application. `pending_input_seq` reports a pending or
|
|
31
|
+
in-flight command. `applied_at_sim_time` records its integration boundary.
|
|
32
|
+
If no command arrives, the last applied input remains active indefinitely.
|
|
33
|
+
|
|
34
|
+
`GET /api/state` returns the model state, effective input `u` and the matching
|
|
35
|
+
`input_saturated` flags. `GET /api/measurements` applies configured sensor
|
|
36
|
+
limits to state readings, matching `Simulation.read_measurements()`.
|
|
37
|
+
See [Common pitfalls](common-pitfalls.md) for examples of sensor and actuator
|
|
38
|
+
limits and how to confirm application of a command.
|
|
39
|
+
|
|
40
|
+
## Try a command from the interactive API
|
|
41
|
+
|
|
42
|
+
Start the catalogue pendulum in a terminal and leave it running.
|
|
43
|
+
|
|
44
|
+
```shell
|
|
45
|
+
bs-simulators --catalogue pendulum --controller http
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Open the local [interactive API](http://127.0.0.1:8765/docs), then use **Try it
|
|
49
|
+
out** and **Execute** on these endpoints.
|
|
50
|
+
|
|
51
|
+
1. Read `GET /api/measurements`. For the catalogue pendulum, `theta` is the
|
|
52
|
+
angle in radians, `omega` is the angular velocity in radians per second and
|
|
53
|
+
`torque` is the currently applied input in newton-metres.
|
|
54
|
+
2. Send `{"u": [2.0]}` to `POST /api/input`. The complete vector contains one
|
|
55
|
+
torque command. A `202` response includes its `accepted_input_seq`.
|
|
56
|
+
3. Read `GET /api/state` again until `input_seq` matches that sequence. The
|
|
57
|
+
snapshot then shows the effective input in `u` and the boundary at which
|
|
58
|
+
it was applied in `applied_at_sim_time`. A subsequent measurement shows
|
|
59
|
+
the applied torque under its signal name. If `input_seq` has already
|
|
60
|
+
advanced past the accepted sequence, the current snapshot alone cannot
|
|
61
|
+
confirm whether that earlier command was applied.
|
|
62
|
+
|
|
63
|
+
The same requests work from a separate SIL client. Refer to
|
|
64
|
+
`GET /api/signals` for each model's signal names, units and input order.
|
|
65
|
+
The local server also serves its OpenAPI schema at `GET /openapi.json`.
|
|
66
|
+
|
|
67
|
+
### Input errors
|
|
68
|
+
|
|
69
|
+
The application reports input errors as JSON objects with an `error` string.
|
|
70
|
+
|
|
71
|
+
| Status | Cause |
|
|
72
|
+
| --- | --- |
|
|
73
|
+
| `400` | Invalid JSON, input vector or timestamp, or unsupported transfer encoding |
|
|
74
|
+
| `403` | The request fails the Host or Origin check, or HTTP is not the active controller |
|
|
75
|
+
| `408` | The server timed out while reading the request body |
|
|
76
|
+
| `409` | The simulation has stopped accepting commands |
|
|
77
|
+
| `411` | The request lacks a valid Content-Length |
|
|
78
|
+
| `413` | The body is empty or exceeds 4096 bytes |
|
|
79
|
+
| `415` | The body has a content type other than `application/json` |
|
|
80
|
+
|
|
81
|
+
## Start a server from Python
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
import threading
|
|
85
|
+
from benchmark_systems.models import pendulum
|
|
86
|
+
from bs_simulators import Simulation
|
|
87
|
+
from bs_simulators.comms.http import create_server
|
|
88
|
+
|
|
89
|
+
simulation = Simulation(
|
|
90
|
+
pendulum,
|
|
91
|
+
x0=[0.6, 0.0],
|
|
92
|
+
u0=[0.0],
|
|
93
|
+
parameters={"m": 1.0, "L": 1.0, "drag": 0.1},
|
|
94
|
+
viewer="pendulum",
|
|
95
|
+
)
|
|
96
|
+
server = create_server(simulation, port=8765)
|
|
97
|
+
server_thread = threading.Thread(target=server.serve_forever, daemon=True)
|
|
98
|
+
server_thread.start()
|
|
99
|
+
simulation.start()
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
The server is ready at creation time but starts serving when its thread runs.
|
|
103
|
+
The simulation starts independently. This example keeps Python as controller;
|
|
104
|
+
set `active_controller="http"` in `Simulation(...)` to accept HTTP input writes.
|
|
105
|
+
In a notebook, keep these objects available and run the shutdown cell when
|
|
106
|
+
finished:
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
simulation.stop()
|
|
110
|
+
server.shutdown()
|
|
111
|
+
server.server_close()
|
|
112
|
+
server_thread.join()
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
`viewer="pendulum"`, `viewer="dc-motor"`, `viewer="neutralization"` and
|
|
116
|
+
`viewer="johansson"` select the packaged scenes for compatible model states.
|
|
117
|
+
Other models remain fully available through API endpoints without
|
|
118
|
+
requiring an animation. Reading or closing a viewer never advances or owns
|
|
119
|
+
the simulation clock.
|
|
120
|
+
|
|
121
|
+
The [adapter interaction diagram](api.md#runtime-sequence) shows the path
|
|
122
|
+
from a write request to a committed state. For terminal execution, the
|
|
123
|
+
optional [CLI](catalogue.md) accepts `--controller http` to select HTTP input.
|
|
124
|
+
|
|
125
|
+
## Open the viewer in Google Colab
|
|
126
|
+
|
|
127
|
+
Colab routes the iframe through an HTTPS proxy. Start a read-only server
|
|
128
|
+
for the viewer using the exact proxy origin returned by the notebook.
|
|
129
|
+
With the `simulation` from the example above, replace its HTTP startup
|
|
130
|
+
lines with the following cell. Use a free port in the Colab runtime.
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
from google.colab import output
|
|
134
|
+
from urllib.parse import urlsplit
|
|
135
|
+
|
|
136
|
+
port = 8766
|
|
137
|
+
proxy_url = urlsplit(output.eval_js(f"google.colab.kernel.proxyPort({port})"))
|
|
138
|
+
proxy_origin = f"{proxy_url.scheme}://{proxy_url.netloc}"
|
|
139
|
+
server = create_server(simulation, port=port, colab_origin=proxy_origin)
|
|
140
|
+
server_thread = threading.Thread(target=server.serve_forever, daemon=True)
|
|
141
|
+
server_thread.start()
|
|
142
|
+
simulation.start()
|
|
143
|
+
output.serve_kernel_port_as_iframe(port, height=650)
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
For recognized Colab proxy URLs, the read-only listener also accepts the
|
|
147
|
+
forwarded hostname for the same runtime. If the iframe returns
|
|
148
|
+
`invalid local Host` with another URL format, add
|
|
149
|
+
`colab_upstream_host="runtime.example.internal:8007"` to `create_server()`,
|
|
150
|
+
using the exact forwarded hostname and port observed in the current
|
|
151
|
+
session. Keep the public HTTPS origin in `colab_origin`. Both settings
|
|
152
|
+
apply to the read-only listener.
|
|
153
|
+
|
|
154
|
+
The iframe can read the simulation and render the scene. If an HTTP SIL
|
|
155
|
+
controller runs in the same runtime, start a separate default server on
|
|
156
|
+
another loopback port and point the controller there. Use the shutdown
|
|
157
|
+
sequence above for each server you start.
|
|
158
|
+
|
|
159
|
+
Before rerunning the startup cell, stop the current simulation, call
|
|
160
|
+
`server.server_close()` and join the server thread. The next run can use
|
|
161
|
+
the same port.
|
|
@@ -23,8 +23,9 @@ experiments once their underlying components are familiar.
|
|
|
23
23
|
the distinction between accepted and applied commands.
|
|
24
24
|
|
|
25
25
|
The runtime supports ODEs and DAE consistency of differentiation index at
|
|
26
|
-
most one. Packaged browser scenes depict the pendulum, DC motor
|
|
27
|
-
reactor. Other models can
|
|
26
|
+
most one. Packaged browser scenes depict the pendulum, DC motor, pH
|
|
27
|
+
neutralization reactor and Johansson four-tank process. Other models can
|
|
28
|
+
run through Python and HTTP without a dedicated scene.
|
|
28
29
|
|
|
29
30
|
```{toctree}
|
|
30
31
|
:maxdepth: 2
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "bs-simulators"
|
|
3
|
-
version = "0.1.
|
|
3
|
+
version = "0.1.4"
|
|
4
4
|
description = "Live simulators and transport adapters for benchmark-systems models"
|
|
5
5
|
requires-python = ">=3.13"
|
|
6
6
|
readme = "README.md"
|
|
@@ -10,6 +10,8 @@ dependencies = [
|
|
|
10
10
|
"scipy>=1.14.1",
|
|
11
11
|
"solve-dae>=0.2.4",
|
|
12
12
|
"typer>=0.27.3",
|
|
13
|
+
"fastapi>=0.115,<1",
|
|
14
|
+
"uvicorn>=0.34,<1",
|
|
13
15
|
]
|
|
14
16
|
|
|
15
17
|
[project.license]
|
|
@@ -48,6 +48,7 @@ class SimulationConfiguration:
|
|
|
48
48
|
input_signals: list[dict[str, Any]] | None = None
|
|
49
49
|
stepper: dict[str, Any] | None = None
|
|
50
50
|
t0: float = 0.0
|
|
51
|
+
input_groups: dict[str, list[int]] | None = None
|
|
51
52
|
|
|
52
53
|
def __post_init__(self):
|
|
53
54
|
"""Store validated copies of configuration data without importing the simulation runtime."""
|
|
@@ -81,8 +82,15 @@ class SimulationConfiguration:
|
|
|
81
82
|
raise ValueError('parameter overrides must be a mapping with string keys')
|
|
82
83
|
model_parameters.update(copy.deepcopy(dict(parameters)))
|
|
83
84
|
signature = inspect.signature(model)
|
|
84
|
-
|
|
85
|
-
if parameter.kind is inspect.Parameter.KEYWORD_ONLY
|
|
85
|
+
keywords = {name: parameter for name, parameter in signature.parameters.items()
|
|
86
|
+
if parameter.kind is inspect.Parameter.KEYWORD_ONLY}
|
|
87
|
+
groups = configuration.input_groups
|
|
88
|
+
input_keywords = groups.keys() if groups is not None else {'u'}
|
|
89
|
+
if groups is not None and (unknown_groups := groups.keys() - keywords.keys()):
|
|
90
|
+
raise ValueError(f'unknown input groups for {configuration.model}: {sorted(unknown_groups)}')
|
|
91
|
+
if groups is not None and (duplicates := model_parameters.keys() & groups.keys()):
|
|
92
|
+
raise ValueError(f'use the input vector for {configuration.model}: {sorted(duplicates)}')
|
|
93
|
+
physical = {name: parameter for name, parameter in keywords.items() if name not in input_keywords}
|
|
86
94
|
unknown = model_parameters.keys() - physical.keys()
|
|
87
95
|
if unknown:
|
|
88
96
|
raise ValueError(f'unknown parameters for {configuration.model}: {sorted(unknown)}')
|
|
@@ -93,6 +101,8 @@ class SimulationConfiguration:
|
|
|
93
101
|
|
|
94
102
|
states = copy.deepcopy(configuration.x0 if x0 is None else x0)
|
|
95
103
|
inputs = copy.deepcopy(configuration.u0 if u0 is None else u0)
|
|
104
|
+
if groups is not None and len(inputs) != len(configuration.u0):
|
|
105
|
+
raise ValueError(f'u0 must contain {len(configuration.u0)} inputs for {configuration.model}')
|
|
96
106
|
try:
|
|
97
107
|
state_size = len(states)
|
|
98
108
|
except TypeError as exc:
|
|
@@ -109,6 +119,10 @@ class SimulationConfiguration:
|
|
|
109
119
|
"""Convert optional signal tables into independent runtime descriptors."""
|
|
110
120
|
return None if values is None else [SignalDescriptor(**copy.deepcopy(value)) for value in values]
|
|
111
121
|
|
|
122
|
+
def map_inputs(vector):
|
|
123
|
+
"""Split the held input vector into the configured model arguments."""
|
|
124
|
+
return {keyword: vector[indices] for keyword, indices in groups.items()}
|
|
125
|
+
|
|
112
126
|
try:
|
|
113
127
|
return Simulation(
|
|
114
128
|
model, stepper=selected_stepper, x0=states, u0=inputs,
|
|
@@ -119,6 +133,7 @@ class SimulationConfiguration:
|
|
|
119
133
|
viewer=configuration.viewer,
|
|
120
134
|
state_signals=descriptions(configuration.state_signals),
|
|
121
135
|
input_signals=descriptions(configuration.input_signals),
|
|
136
|
+
input_map=map_inputs if groups is not None else None,
|
|
122
137
|
)
|
|
123
138
|
except (TypeError, ValueError, IndexError, KeyError, ArithmeticError, RuntimeError) as exc:
|
|
124
139
|
raise ValueError(f'invalid configuration {configuration.name!r}: {exc}') from exc
|
|
@@ -8,7 +8,7 @@ import math
|
|
|
8
8
|
|
|
9
9
|
_FIELDS = {
|
|
10
10
|
'name', 'model', 'parameters', 'x0', 'u0', 'dt', 't0',
|
|
11
|
-
'active_controller', 'viewer', 'state_signals', 'input_signals', 'stepper',
|
|
11
|
+
'active_controller', 'viewer', 'state_signals', 'input_signals', 'input_groups', 'stepper',
|
|
12
12
|
}
|
|
13
13
|
_STEPPER_FIELDS = {'kind', 'method', 'rtol', 'atol', 'xdot0', 'fixed_x'}
|
|
14
14
|
_SIGNAL_FIELDS = {'name', 'unit', 'dtype', 'direction', 'lower', 'upper'}
|
|
@@ -123,6 +123,24 @@ def _stepper_spec(value, state_size):
|
|
|
123
123
|
return value
|
|
124
124
|
|
|
125
125
|
|
|
126
|
+
def _input_groups(value, count):
|
|
127
|
+
"""Map every input position exactly once to a model keyword vector."""
|
|
128
|
+
if value is None:
|
|
129
|
+
return None
|
|
130
|
+
if not isinstance(value, Mapping) or not value:
|
|
131
|
+
raise ValueError('input_groups must be a non-empty table')
|
|
132
|
+
groups = {}
|
|
133
|
+
for keyword, indices in value.items():
|
|
134
|
+
if (not isinstance(keyword, str) or not keyword.isidentifier()
|
|
135
|
+
or not isinstance(indices, (list, tuple)) or not indices
|
|
136
|
+
or any(type(index) is not int for index in indices)):
|
|
137
|
+
raise ValueError('input_groups must map model keyword names to non-empty integer arrays')
|
|
138
|
+
groups[keyword] = list(indices)
|
|
139
|
+
if sorted(index for indices in groups.values() for index in indices) != list(range(count)):
|
|
140
|
+
raise ValueError('input_groups must use each input position exactly once')
|
|
141
|
+
return groups
|
|
142
|
+
|
|
143
|
+
|
|
126
144
|
def _configuration_values(configuration):
|
|
127
145
|
"""Validate configuration fields and return normalized, detached values for dataclass initialization."""
|
|
128
146
|
_text('configuration name', configuration.name)
|
|
@@ -144,6 +162,7 @@ def _configuration_values(configuration):
|
|
|
144
162
|
'parameters': _parameters(configuration.parameters), 'x0': states, 'u0': inputs,
|
|
145
163
|
'dt': _number('dt', configuration.dt, positive=True), 't0': _number('t0', configuration.t0),
|
|
146
164
|
'state_signals': state_signals, 'input_signals': input_signals,
|
|
165
|
+
'input_groups': _input_groups(configuration.input_groups, len(inputs)),
|
|
147
166
|
'stepper': _stepper_spec(configuration.stepper, len(states)),
|
|
148
167
|
}
|
|
149
168
|
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
name = "johansson"
|
|
2
|
+
model = "johansson"
|
|
3
|
+
x0 = [10.0, 10.0, 10.0, 10.0]
|
|
4
|
+
u0 = [50, 50, 0.5, 0.5]
|
|
5
|
+
dt = 0.3
|
|
6
|
+
active_controller = "python"
|
|
7
|
+
viewer = "johansson"
|
|
8
|
+
|
|
9
|
+
[parameters]
|
|
10
|
+
A = [389.16, 389.16, 389.16, 389.16]
|
|
11
|
+
a = [1.5393804002589984, 1.5393804002589984, 1.5393804002589984, 1.5393804002589984]
|
|
12
|
+
K = [6.74, 7.94]
|
|
13
|
+
h_max = [25.0, 25.0, 20.0, 20.0]
|
|
14
|
+
|
|
15
|
+
[input_groups]
|
|
16
|
+
u = [0, 1]
|
|
17
|
+
gamma = [2, 3]
|
|
18
|
+
|
|
19
|
+
[stepper]
|
|
20
|
+
kind = "ode"
|
|
21
|
+
method = "RK45"
|
|
22
|
+
rtol = 1e-6
|
|
23
|
+
|
|
24
|
+
[[state_signals]]
|
|
25
|
+
name = "h1"
|
|
26
|
+
unit = "cm"
|
|
27
|
+
dtype = "float64"
|
|
28
|
+
direction = "output"
|
|
29
|
+
|
|
30
|
+
[[state_signals]]
|
|
31
|
+
name = "h2"
|
|
32
|
+
unit = "cm"
|
|
33
|
+
dtype = "float64"
|
|
34
|
+
direction = "output"
|
|
35
|
+
|
|
36
|
+
[[state_signals]]
|
|
37
|
+
name = "h3"
|
|
38
|
+
unit = "cm"
|
|
39
|
+
dtype = "float64"
|
|
40
|
+
direction = "output"
|
|
41
|
+
|
|
42
|
+
[[state_signals]]
|
|
43
|
+
name = "h4"
|
|
44
|
+
unit = "cm"
|
|
45
|
+
dtype = "float64"
|
|
46
|
+
direction = "output"
|
|
47
|
+
|
|
48
|
+
[[input_signals]]
|
|
49
|
+
name = "u1"
|
|
50
|
+
unit = "%"
|
|
51
|
+
dtype = "float64"
|
|
52
|
+
direction = "input"
|
|
53
|
+
lower = 0.0
|
|
54
|
+
upper = 100.0
|
|
55
|
+
|
|
56
|
+
[[input_signals]]
|
|
57
|
+
name = "u2"
|
|
58
|
+
unit = "%"
|
|
59
|
+
dtype = "float64"
|
|
60
|
+
direction = "input"
|
|
61
|
+
lower = 0.0
|
|
62
|
+
upper = 100.0
|
|
63
|
+
|
|
64
|
+
[[input_signals]]
|
|
65
|
+
name = "gamma1"
|
|
66
|
+
unit = ""
|
|
67
|
+
dtype = "float64"
|
|
68
|
+
direction = "input"
|
|
69
|
+
lower = 0.0
|
|
70
|
+
upper = 1.0
|
|
71
|
+
|
|
72
|
+
[[input_signals]]
|
|
73
|
+
name = "gamma2"
|
|
74
|
+
unit = ""
|
|
75
|
+
dtype = "float64"
|
|
76
|
+
direction = "input"
|
|
77
|
+
lower = 0.0
|
|
78
|
+
upper = 1.0
|
|
@@ -133,7 +133,8 @@ def run(
|
|
|
133
133
|
t0=defaults['t0'],
|
|
134
134
|
controller=active_controller if active_controller is not None else defaults['active_controller'],
|
|
135
135
|
stepper=specification if specification is not None else defaults['stepper'],
|
|
136
|
-
viewer=defaults['viewer'])
|
|
136
|
+
viewer=defaults['viewer'], input_groups=defaults.get('input_groups'),
|
|
137
|
+
input_signals=defaults.get('input_signals'))
|
|
137
138
|
return
|
|
138
139
|
if model is not None:
|
|
139
140
|
selected = _model_function(model)
|
|
@@ -70,10 +70,14 @@ def _documentation(model):
|
|
|
70
70
|
return text
|
|
71
71
|
|
|
72
72
|
|
|
73
|
-
def show_description(model, parameters, *, initial, held, dt, t0, controller, stepper, viewer
|
|
73
|
+
def show_description(model, parameters, *, initial, held, dt, t0, controller, stepper, viewer,
|
|
74
|
+
input_groups=None, input_signals=None):
|
|
74
75
|
"""Render model signature, parameter choices, run settings and complete documentation."""
|
|
76
|
+
input_keywords = input_groups.keys() if input_groups is not None else {'u'}
|
|
77
|
+
if input_groups is not None and (duplicates := parameters.keys() & input_keywords):
|
|
78
|
+
raise ValueError(f'use the input vector for {model.__name__}: {sorted(duplicates)}')
|
|
75
79
|
physical = {name: parameter for name, parameter in inspect.signature(model).parameters.items()
|
|
76
|
-
if parameter.kind is inspect.Parameter.KEYWORD_ONLY and name
|
|
80
|
+
if parameter.kind is inspect.Parameter.KEYWORD_ONLY and name not in input_keywords}
|
|
77
81
|
unknown = parameters.keys() - physical.keys()
|
|
78
82
|
if unknown:
|
|
79
83
|
raise ValueError(f'unknown parameters for {model.__name__}: {sorted(unknown)}')
|
|
@@ -104,6 +108,8 @@ def show_description(model, parameters, *, initial, held, dt, t0, controller, st
|
|
|
104
108
|
]
|
|
105
109
|
for label, value in values:
|
|
106
110
|
_row(settings, label, value)
|
|
111
|
+
if input_signals is not None:
|
|
112
|
+
_row(settings, 'Input vector order', ', '.join(signal['name'] for signal in input_signals))
|
|
107
113
|
console.print(settings)
|
|
108
114
|
console.print(Panel(_documentation(model), title='Model documentation', border_style='blue'))
|
|
109
115
|
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""FastAPI routes, packaged viewer assets, and API schemas."""
|
|
2
|
+
|
|
3
|
+
from importlib.resources import files
|
|
4
|
+
|
|
5
|
+
from fastapi import FastAPI, HTTPException
|
|
6
|
+
from fastapi.exceptions import RequestValidationError
|
|
7
|
+
from fastapi.responses import JSONResponse, Response
|
|
8
|
+
from pydantic import BaseModel, ConfigDict, Field, FiniteFloat
|
|
9
|
+
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
10
|
+
|
|
11
|
+
from ...viewers import ASSET_FILES, VIEWER_FILES
|
|
12
|
+
from .middleware import _install_request_policy
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class _InputCommand(BaseModel):
|
|
16
|
+
"""Complete input vector received from an HTTP controller."""
|
|
17
|
+
|
|
18
|
+
model_config = ConfigDict(
|
|
19
|
+
extra='forbid', strict=True, json_schema_extra={'examples': [{'u': [2.0]}]},
|
|
20
|
+
)
|
|
21
|
+
u: list[FiniteFloat] = Field(description='Complete vector in the input order of GET /api/signals.')
|
|
22
|
+
source_timestamp: str | None = Field(
|
|
23
|
+
default=None, description='Optional ISO 8601 UTC timestamp for tracking the command.',
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class _InputAcknowledgement(BaseModel):
|
|
28
|
+
"""Metadata returned when the runtime accepts a command."""
|
|
29
|
+
|
|
30
|
+
model_config = ConfigDict(json_schema_extra={'examples': [{
|
|
31
|
+
'input_seq': 8, 'pending_input_seq': 8, 'accepted_input_seq': 8,
|
|
32
|
+
'applied_input_seq': 7, 'controller_id': 'http', 'received_at_monotonic': 123.45,
|
|
33
|
+
}]})
|
|
34
|
+
input_seq: int = Field(description='Alias of accepted_input_seq in this acknowledgement.')
|
|
35
|
+
pending_input_seq: int = Field(description='Sequence that was pending when this command was accepted.')
|
|
36
|
+
accepted_input_seq: int = Field(description='Sequence assigned to this command.')
|
|
37
|
+
applied_input_seq: int = Field(description='Last committed input sequence at acceptance.')
|
|
38
|
+
controller_id: str = Field(description='Controller identity associated with the command.')
|
|
39
|
+
received_at_monotonic: float = Field(description='Receipt time in seconds on the server monotonic clock.')
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class _RequestError(BaseModel):
|
|
43
|
+
"""Error returned by the HTTP application."""
|
|
44
|
+
|
|
45
|
+
error: str
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
_INPUT_ERROR_RESPONSES = {
|
|
49
|
+
status: {'model': _RequestError, 'description': description}
|
|
50
|
+
for status, description in {
|
|
51
|
+
400: 'Invalid JSON, input vector, timestamp, or transfer encoding.',
|
|
52
|
+
403: 'Request rejected by the Host or Origin policy, or HTTP control is unavailable.',
|
|
53
|
+
408: 'Timed out while reading the request body.',
|
|
54
|
+
409: 'The simulation has stopped accepting commands.',
|
|
55
|
+
411: 'A valid Content-Length header is required.',
|
|
56
|
+
413: 'The request body must contain 1 to 4096 bytes.',
|
|
57
|
+
415: 'Content-Type must be application/json.',
|
|
58
|
+
'4XX': 'Other client errors.',
|
|
59
|
+
}.items()
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _build_app(adapter, *, viewer, port, colab_host, colab_upstream_host=None):
|
|
64
|
+
"""Configure the FastAPI routes for the simulation and its viewer."""
|
|
65
|
+
read_only = colab_host is not None
|
|
66
|
+
app = FastAPI(title='bs-simulators', docs_url=None if read_only else '/docs',
|
|
67
|
+
redoc_url=None, openapi_url=None if read_only else '/openapi.json')
|
|
68
|
+
_install_request_policy(app, port=port, colab_host=colab_host,
|
|
69
|
+
colab_upstream_host=colab_upstream_host)
|
|
70
|
+
|
|
71
|
+
@app.exception_handler(StarletteHTTPException)
|
|
72
|
+
async def http_error(request, error):
|
|
73
|
+
return JSONResponse({'error': error.detail}, status_code=error.status_code,
|
|
74
|
+
headers=error.headers)
|
|
75
|
+
|
|
76
|
+
@app.exception_handler(RequestValidationError)
|
|
77
|
+
async def invalid_command(request, error):
|
|
78
|
+
return JSONResponse({'error': 'expected a finite numeric vector u with optional source_timestamp'},
|
|
79
|
+
status_code=400)
|
|
80
|
+
|
|
81
|
+
def resource(name, media_type):
|
|
82
|
+
try:
|
|
83
|
+
payload = files('bs_simulators.viewers').joinpath(name).read_bytes()
|
|
84
|
+
except FileNotFoundError as error:
|
|
85
|
+
raise HTTPException(404, 'viewer resource is unavailable') from error
|
|
86
|
+
return Response(payload, media_type=media_type)
|
|
87
|
+
|
|
88
|
+
@app.get('/', include_in_schema=False)
|
|
89
|
+
@app.get('/viewer.html', include_in_schema=False)
|
|
90
|
+
def scene():
|
|
91
|
+
if viewer is None:
|
|
92
|
+
raise HTTPException(404, 'no viewer is configured for this simulation')
|
|
93
|
+
return resource(VIEWER_FILES[viewer], 'text/html; charset=utf-8')
|
|
94
|
+
|
|
95
|
+
@app.get('/assets/{name}', include_in_schema=False)
|
|
96
|
+
def asset(name: str):
|
|
97
|
+
if name not in ASSET_FILES:
|
|
98
|
+
raise HTTPException(404, 'unknown viewer resource')
|
|
99
|
+
return resource(name, ASSET_FILES[name])
|
|
100
|
+
|
|
101
|
+
@app.get('/api/state')
|
|
102
|
+
def read_state():
|
|
103
|
+
"""Return the committed model state before sensor limits.
|
|
104
|
+
|
|
105
|
+
`u` contains the effective actuator inputs. `input_seq` identifies
|
|
106
|
+
the last applied command. `applied_at_sim_time` gives its step boundary.
|
|
107
|
+
"""
|
|
108
|
+
return adapter.read_snapshot()
|
|
109
|
+
|
|
110
|
+
@app.get('/api/measurements')
|
|
111
|
+
def read_measurements():
|
|
112
|
+
"""Return named sensor readings, applied inputs, simulation time and status."""
|
|
113
|
+
return adapter.read_measurements()
|
|
114
|
+
|
|
115
|
+
@app.get('/api/signals')
|
|
116
|
+
def read_signals():
|
|
117
|
+
"""Return signal names, units, types, directions and configured bounds."""
|
|
118
|
+
return adapter.describe_signals()
|
|
119
|
+
|
|
120
|
+
if not read_only:
|
|
121
|
+
@app.post('/api/input', status_code=202, response_model=_InputAcknowledgement,
|
|
122
|
+
responses=_INPUT_ERROR_RESPONSES)
|
|
123
|
+
def write_input(command: _InputCommand):
|
|
124
|
+
"""Accept an input command for a subsequent simulation interval.
|
|
125
|
+
|
|
126
|
+
Compare the acknowledgement's `accepted_input_seq` with `input_seq`
|
|
127
|
+
from GET /api/state to confirm application.
|
|
128
|
+
"""
|
|
129
|
+
try:
|
|
130
|
+
ack = adapter.write_inputs(command.u, source_timestamp=command.source_timestamp)
|
|
131
|
+
except (TypeError, ValueError) as error:
|
|
132
|
+
raise HTTPException(400, str(error)) from error
|
|
133
|
+
except PermissionError as error:
|
|
134
|
+
raise HTTPException(403, str(error)) from error
|
|
135
|
+
except RuntimeError as error:
|
|
136
|
+
raise HTTPException(409, str(error)) from error
|
|
137
|
+
# Structural simulation ports may return different metadata.
|
|
138
|
+
return JSONResponse(ack, status_code=202)
|
|
139
|
+
|
|
140
|
+
return app
|