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,154 @@
|
|
|
1
|
+
"""Typer options and routing between inspection and execution."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Annotated
|
|
5
|
+
|
|
6
|
+
import typer
|
|
7
|
+
|
|
8
|
+
from . import presentation
|
|
9
|
+
from .configuration import (_model_function, _model_kind, _parameter_values,
|
|
10
|
+
_toml_value, _toml_vector)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
app = typer.Typer(
|
|
14
|
+
add_completion=False,
|
|
15
|
+
pretty_exceptions_enable=False,
|
|
16
|
+
context_settings={'help_option_names': ['-h', '--help']},
|
|
17
|
+
help='Run an explicitly selected model or inspect its parameters without starting a simulation.',
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@app.command()
|
|
23
|
+
def run(
|
|
24
|
+
port: Annotated[int, typer.Option(
|
|
25
|
+
'--port', min=0, max=65535, help='Optional local HTTP port; 0 selects an available port.',
|
|
26
|
+
rich_help_panel='Execution (optional)',
|
|
27
|
+
)] = 8765,
|
|
28
|
+
dt: Annotated[float | None, typer.Option(
|
|
29
|
+
'--dt', help='Fixed interval in simulated seconds; inherits configuration, or 0.01 for --model.',
|
|
30
|
+
rich_help_panel='Integration',
|
|
31
|
+
)] = None,
|
|
32
|
+
dt_real: Annotated[float | None, typer.Option(
|
|
33
|
+
'--dt-real', help='Optional interval between step deadlines in wall-clock seconds; defaults to dt.',
|
|
34
|
+
rich_help_panel='Execution (optional)',
|
|
35
|
+
)] = None,
|
|
36
|
+
duration: Annotated[float | None, typer.Option(
|
|
37
|
+
'--duration', help='Optional simulated seconds, a multiple of dt; omit to run until stopped.',
|
|
38
|
+
rich_help_panel='Execution (optional)',
|
|
39
|
+
)] = None,
|
|
40
|
+
record: Annotated[Path | None, typer.Option(
|
|
41
|
+
'--record', dir_okay=False, help='Optional new JSONL file; omit to disable recording. Existing files are preserved.',
|
|
42
|
+
rich_help_panel='Execution (optional)',
|
|
43
|
+
)] = None,
|
|
44
|
+
active_controller: Annotated[str | None, typer.Option(
|
|
45
|
+
'--controller', '--active-controller',
|
|
46
|
+
help='Optional controller identity; inherits configuration, or python for --model.',
|
|
47
|
+
rich_help_panel='Execution (optional)',
|
|
48
|
+
)] = None,
|
|
49
|
+
catalogue: Annotated[str | None, typer.Option(
|
|
50
|
+
'--catalogue', help='Explicit bundled configuration name; use --list-catalogue.',
|
|
51
|
+
rich_help_panel='Model selection',
|
|
52
|
+
)] = None,
|
|
53
|
+
config: Annotated[Path | None, typer.Option(
|
|
54
|
+
'--config', exists=True, dir_okay=False, readable=True,
|
|
55
|
+
help='Complete custom TOML file; alternative to --catalogue or --model.',
|
|
56
|
+
rich_help_panel='Model selection',
|
|
57
|
+
)] = None,
|
|
58
|
+
model: Annotated[str | None, typer.Option(
|
|
59
|
+
'--model', help='Public benchmark-systems model; requires --x0, --u0 and physical parameters.',
|
|
60
|
+
rich_help_panel='Model selection',
|
|
61
|
+
)] = None,
|
|
62
|
+
parameter: Annotated[list[str] | None, typer.Option(
|
|
63
|
+
'--parameter', help='Override NAME=TOML_VALUE; repeat for multiple parameters.',
|
|
64
|
+
rich_help_panel='Initial data and parameters',
|
|
65
|
+
)] = None,
|
|
66
|
+
x0: Annotated[str | None, typer.Option(
|
|
67
|
+
'--x0', help='Initial state as a TOML array, e.g. [0.0, 0.0].',
|
|
68
|
+
rich_help_panel='Initial data and parameters',
|
|
69
|
+
)] = None,
|
|
70
|
+
u0: Annotated[str | None, typer.Option(
|
|
71
|
+
'--u0', help='Initial held input as a TOML array, e.g. [1.0].',
|
|
72
|
+
rich_help_panel='Initial data and parameters',
|
|
73
|
+
)] = None,
|
|
74
|
+
list_catalogue: Annotated[bool, typer.Option(
|
|
75
|
+
'--list-catalogue', help='List bundled configurations and exit.',
|
|
76
|
+
rich_help_panel='Inspection',
|
|
77
|
+
)] = False,
|
|
78
|
+
list_models: Annotated[bool, typer.Option(
|
|
79
|
+
'--list-models', help='List public benchmark-systems models and exit.',
|
|
80
|
+
rich_help_panel='Inspection',
|
|
81
|
+
)] = False,
|
|
82
|
+
describe: Annotated[bool, typer.Option(
|
|
83
|
+
'--describe', help='Show selected model parameters, defaults and documentation without running.',
|
|
84
|
+
rich_help_panel='Inspection',
|
|
85
|
+
)] = False,
|
|
86
|
+
stepper: Annotated[str | None, typer.Option(
|
|
87
|
+
'--stepper', help='Integrator as a TOML inline table, e.g. {kind="ode", method="Radau"}.',
|
|
88
|
+
rich_help_panel='Integration',
|
|
89
|
+
)] = None,
|
|
90
|
+
) -> None:
|
|
91
|
+
"""Select exactly one of --catalogue NAME, --config FILE or --model NAME.
|
|
92
|
+
|
|
93
|
+
Inspect parameters with --model pendulum --describe before constructing a run.
|
|
94
|
+
Execution options are optional; their help explains defaults and inherited settings.
|
|
95
|
+
Catalogue and file overrides affect this run only; no configuration is saved.
|
|
96
|
+
"""
|
|
97
|
+
# Help and argument parsing stay independent of scientific dependencies.
|
|
98
|
+
from ..catalogue import (list_configurations, load_configuration,
|
|
99
|
+
load_configuration_file)
|
|
100
|
+
|
|
101
|
+
if sum((list_catalogue, list_models, describe)) > 1:
|
|
102
|
+
raise typer.BadParameter('choose only one inspection action: --list-catalogue, --list-models or --describe')
|
|
103
|
+
if list_catalogue:
|
|
104
|
+
presentation.show_catalogue(list_configurations())
|
|
105
|
+
return
|
|
106
|
+
if list_models:
|
|
107
|
+
presentation.show_models()
|
|
108
|
+
return
|
|
109
|
+
if sum(value is not None for value in (catalogue, config, model)) != 1:
|
|
110
|
+
raise typer.BadParameter('select exactly one of --catalogue NAME, --config FILE or --model NAME; use --help for options')
|
|
111
|
+
|
|
112
|
+
try:
|
|
113
|
+
configuration = (load_configuration_file(config) if config is not None
|
|
114
|
+
else load_configuration(catalogue) if catalogue is not None else None)
|
|
115
|
+
parameters = _parameter_values(parameter)
|
|
116
|
+
initial = _toml_vector(x0, '--x0') if x0 is not None else None
|
|
117
|
+
held = _toml_vector(u0, '--u0') if u0 is not None else None
|
|
118
|
+
specification = _toml_value(stepper) if stepper is not None else None
|
|
119
|
+
if stepper is not None and not isinstance(specification, dict):
|
|
120
|
+
raise ValueError('--stepper expects a TOML inline table')
|
|
121
|
+
if describe:
|
|
122
|
+
selected = _model_function(model if model is not None else configuration.model)
|
|
123
|
+
defaults = vars(configuration) if configuration is not None else {
|
|
124
|
+
'parameters': {}, 'x0': None, 'u0': None, 'dt': 0.01, 't0': 0.0,
|
|
125
|
+
'active_controller': 'python', 'stepper': None, 'viewer': None,
|
|
126
|
+
}
|
|
127
|
+
values = dict(defaults['parameters'])
|
|
128
|
+
values.update(parameters)
|
|
129
|
+
presentation.show_description(selected, values,
|
|
130
|
+
initial=initial if initial is not None else defaults['x0'],
|
|
131
|
+
held=held if held is not None else defaults['u0'],
|
|
132
|
+
dt=dt if dt is not None else defaults['dt'],
|
|
133
|
+
t0=defaults['t0'],
|
|
134
|
+
controller=active_controller if active_controller is not None else defaults['active_controller'],
|
|
135
|
+
stepper=specification if specification is not None else defaults['stepper'],
|
|
136
|
+
viewer=defaults['viewer'])
|
|
137
|
+
return
|
|
138
|
+
if model is not None:
|
|
139
|
+
selected = _model_function(model)
|
|
140
|
+
if initial is None or held is None:
|
|
141
|
+
raise ValueError('--model execution requires both --x0 and --u0; use --describe for model details')
|
|
142
|
+
if _model_kind(selected) == 'dae' and (specification is None or specification.get('kind') != 'dae'):
|
|
143
|
+
raise ValueError('a DAE model requires an explicit --stepper table with kind="dae" and xdot0')
|
|
144
|
+
from ..catalogue import SimulationConfiguration
|
|
145
|
+
configuration = SimulationConfiguration(
|
|
146
|
+
name=model, model=model, parameters=parameters, x0=initial, u0=held,
|
|
147
|
+
)
|
|
148
|
+
except (ValueError, OSError, TypeError, IndexError, ArithmeticError) as exc:
|
|
149
|
+
raise typer.BadParameter(str(exc)) from exc
|
|
150
|
+
|
|
151
|
+
from .execution import run_simulation
|
|
152
|
+
run_simulation(configuration, parameters=parameters, initial=initial, held=held,
|
|
153
|
+
dt=dt, active_controller=active_controller, stepper=specification,
|
|
154
|
+
port=port, duration=duration, record=record, dt_real=dt_real)
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""CLI literal parsing and lazy public-model inspection."""
|
|
2
|
+
|
|
3
|
+
import inspect
|
|
4
|
+
import tomllib
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _toml_value(literal):
|
|
8
|
+
"""Parse one CLI value with TOML's scalar, array and inline-table syntax."""
|
|
9
|
+
parsed = tomllib.loads(f'value = {literal}')
|
|
10
|
+
if set(parsed) != {'value'}:
|
|
11
|
+
raise ValueError('expected a single TOML value')
|
|
12
|
+
return parsed['value']
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _toml_vector(literal, option):
|
|
16
|
+
"""Parse a complete state or input array; reject scalar CLI values."""
|
|
17
|
+
value = _toml_value(literal)
|
|
18
|
+
if not isinstance(value, list):
|
|
19
|
+
raise ValueError(f'{option} expects a TOML array')
|
|
20
|
+
return value
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _model_function(name):
|
|
24
|
+
"""Resolve a public benchmark-systems model name without importing the runtime."""
|
|
25
|
+
from benchmark_systems import models
|
|
26
|
+
|
|
27
|
+
if name not in models.__all__:
|
|
28
|
+
raise ValueError(f'unknown public benchmark model: {name!r}; use --list-models')
|
|
29
|
+
return getattr(models, name)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _model_kind(model):
|
|
33
|
+
"""Describe published numerical signatures; never select a DAE solver implicitly."""
|
|
34
|
+
positional = [parameter for parameter in inspect.signature(model).parameters.values()
|
|
35
|
+
if parameter.kind in (inspect.Parameter.POSITIONAL_ONLY,
|
|
36
|
+
inspect.Parameter.POSITIONAL_OR_KEYWORD)]
|
|
37
|
+
return 'dae' if len(positional) == 3 else 'ode'
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _parameter_values(items):
|
|
41
|
+
"""Parse repeated physical-parameter overrides, with the last value winning."""
|
|
42
|
+
values = {}
|
|
43
|
+
for item in items or []:
|
|
44
|
+
key, separator, literal = item.partition('=')
|
|
45
|
+
if not separator or not key.strip():
|
|
46
|
+
raise ValueError('--parameter expects NAME=TOML_VALUE')
|
|
47
|
+
values[key.strip()] = _toml_value(literal)
|
|
48
|
+
return values
|
|
49
|
+
|
|
50
|
+
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Simulation and HTTP lifecycle for terminal execution."""
|
|
2
|
+
|
|
3
|
+
import threading
|
|
4
|
+
|
|
5
|
+
import typer
|
|
6
|
+
|
|
7
|
+
from . import presentation
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def run_simulation(configuration, *, parameters, initial, held, dt,
|
|
11
|
+
active_controller, stepper, port, duration, record, dt_real=None):
|
|
12
|
+
"""Run one selected experiment, release its resources and report its outcome."""
|
|
13
|
+
from ..comms.http import create_server
|
|
14
|
+
|
|
15
|
+
simulation = None
|
|
16
|
+
server = None
|
|
17
|
+
server_thread = None
|
|
18
|
+
try:
|
|
19
|
+
try:
|
|
20
|
+
simulation = configuration.create(parameters=parameters, x0=initial, u0=held,
|
|
21
|
+
dt=dt, active_controller=active_controller,
|
|
22
|
+
stepper=stepper)
|
|
23
|
+
server = create_server(simulation, port=port)
|
|
24
|
+
simulation.start(duration=duration, record=record, dt_real=dt_real)
|
|
25
|
+
except (ValueError, OSError, TypeError, IndexError, ArithmeticError) as exc:
|
|
26
|
+
raise typer.BadParameter(str(exc)) from exc
|
|
27
|
+
server_thread = threading.Thread(
|
|
28
|
+
target=server.serve_forever, kwargs={'poll_interval': 0.1},
|
|
29
|
+
name='simulation-http', daemon=True,
|
|
30
|
+
)
|
|
31
|
+
server_thread.start()
|
|
32
|
+
base = f'http://127.0.0.1:{server.server_address[1]}'
|
|
33
|
+
presentation.show_started(base, simulation.snapshot().get('viewer'))
|
|
34
|
+
while not simulation.wait(0.1):
|
|
35
|
+
pass
|
|
36
|
+
except KeyboardInterrupt:
|
|
37
|
+
pass
|
|
38
|
+
finally:
|
|
39
|
+
if simulation is not None:
|
|
40
|
+
simulation.stop()
|
|
41
|
+
if server is not None:
|
|
42
|
+
if server_thread is not None and server_thread.ident is not None:
|
|
43
|
+
server.shutdown()
|
|
44
|
+
server.server_close()
|
|
45
|
+
if server_thread is not None and server_thread.ident is not None:
|
|
46
|
+
server_thread.join()
|
|
47
|
+
|
|
48
|
+
if simulation is not None:
|
|
49
|
+
snapshot = simulation.snapshot()
|
|
50
|
+
if snapshot['status'] == 'error':
|
|
51
|
+
presentation.show_error(snapshot['error'])
|
|
52
|
+
raise typer.Exit(code=1)
|
|
53
|
+
presentation.show_finished(snapshot, record)
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Consistent Rich tables and panels for human-facing CLI output."""
|
|
2
|
+
|
|
3
|
+
import inspect
|
|
4
|
+
|
|
5
|
+
from rich import box
|
|
6
|
+
from rich.console import Console
|
|
7
|
+
from rich.panel import Panel
|
|
8
|
+
from rich.syntax import Syntax
|
|
9
|
+
from rich.table import Table
|
|
10
|
+
from rich.text import Text
|
|
11
|
+
|
|
12
|
+
from .configuration import _model_kind
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _table(title, columns, *, expand=True, min_width=None):
|
|
16
|
+
"""Create the shared table style without creating global console state."""
|
|
17
|
+
table = Table(title=title, box=box.ROUNDED, header_style='bold',
|
|
18
|
+
row_styles=['', 'dim'], expand=expand, min_width=min_width)
|
|
19
|
+
for index, column in enumerate(columns):
|
|
20
|
+
table.add_column(column, style='cyan' if index == 0 else None)
|
|
21
|
+
return table
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _row(table, *values):
|
|
25
|
+
"""Add literal cell content, preserving brackets and avoiding markup interpretation."""
|
|
26
|
+
table.add_row(*(Text(str(value)) for value in values))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def show_catalogue(names):
|
|
30
|
+
"""Display bundled names without importing numerical dependencies."""
|
|
31
|
+
console = Console(highlight=False)
|
|
32
|
+
table = _table('Available configurations', ['Configuration'], expand=False, min_width=28)
|
|
33
|
+
table.columns[0].no_wrap = True
|
|
34
|
+
for name in names:
|
|
35
|
+
_row(table, name)
|
|
36
|
+
console.print(table)
|
|
37
|
+
console.print(Text('Inspect parameters: --catalogue NAME --describe', style='dim'))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def show_models():
|
|
41
|
+
"""Display published numerical model names, equation types and descriptions."""
|
|
42
|
+
from benchmark_systems import models
|
|
43
|
+
|
|
44
|
+
console = Console(highlight=False)
|
|
45
|
+
table = _table('Available benchmark models', ['Model', 'Type', 'Description'])
|
|
46
|
+
table.columns[0].no_wrap = True
|
|
47
|
+
table.columns[1].no_wrap = True
|
|
48
|
+
table.columns[2].ratio = 1
|
|
49
|
+
for name in models.__all__:
|
|
50
|
+
model = getattr(models, name)
|
|
51
|
+
kind = _model_kind(model).upper()
|
|
52
|
+
summary = (inspect.getdoc(model) or 'No description available.').splitlines()[0]
|
|
53
|
+
table.add_row(Text(name), Text(kind, style='green' if kind == 'ODE' else 'yellow'),
|
|
54
|
+
Text(summary))
|
|
55
|
+
console.print(table)
|
|
56
|
+
console.print(Text('Inspect parameters: --model NAME --describe', style='dim'))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _documentation(model):
|
|
60
|
+
"""Style NumPy docstring headings and parameter declarations while retaining all text."""
|
|
61
|
+
lines = (inspect.getdoc(model) or 'No documentation provided.').splitlines()
|
|
62
|
+
text = Text()
|
|
63
|
+
for index, line in enumerate(lines):
|
|
64
|
+
if line and set(line.strip()) == {'-'}:
|
|
65
|
+
continue
|
|
66
|
+
heading = index + 1 < len(lines) and lines[index + 1] and set(lines[index + 1].strip()) == {'-'}
|
|
67
|
+
declaration = line and not line.startswith(' ') and ' : ' in line
|
|
68
|
+
style = 'bold blue' if heading else 'bold cyan' if declaration else ''
|
|
69
|
+
text.append(line + '\n', style=style)
|
|
70
|
+
return text
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def show_description(model, parameters, *, initial, held, dt, t0, controller, stepper, viewer):
|
|
74
|
+
"""Render model signature, parameter choices, run settings and complete documentation."""
|
|
75
|
+
physical = {name: parameter for name, parameter in inspect.signature(model).parameters.items()
|
|
76
|
+
if parameter.kind is inspect.Parameter.KEYWORD_ONLY and name != 'u'}
|
|
77
|
+
unknown = parameters.keys() - physical.keys()
|
|
78
|
+
if unknown:
|
|
79
|
+
raise ValueError(f'unknown parameters for {model.__name__}: {sorted(unknown)}')
|
|
80
|
+
console = Console(highlight=False)
|
|
81
|
+
signature = Syntax(f'{model.__name__}{inspect.signature(model)}', 'python',
|
|
82
|
+
theme='ansi_dark', background_color='default', word_wrap=True)
|
|
83
|
+
console.print(Panel(signature, title=f'Model: {model.__name__} ({_model_kind(model).upper()})',
|
|
84
|
+
border_style='cyan'))
|
|
85
|
+
table = _table('Physical parameters · --parameter NAME=VALUE',
|
|
86
|
+
['Parameter', 'Requirement', 'Function default', 'Selected value'])
|
|
87
|
+
for name, parameter in physical.items():
|
|
88
|
+
required = parameter.default is inspect.Parameter.empty
|
|
89
|
+
default = '—' if required else repr(parameter.default)
|
|
90
|
+
selected = repr(parameters[name]) if name in parameters else 'not supplied' if required else default
|
|
91
|
+
_row(table, name, 'Required' if required else 'Optional', default, selected)
|
|
92
|
+
console.print(table)
|
|
93
|
+
|
|
94
|
+
settings = _table('Simulation settings', ['Setting', 'Value'])
|
|
95
|
+
default_stepper = ('explicit DAE stepper required' if _model_kind(model) == 'dae' else 'ODE RK45')
|
|
96
|
+
integrator = ('\n'.join(f'{key}: {value}' for key, value in stepper.items())
|
|
97
|
+
if stepper else default_stepper)
|
|
98
|
+
values = [
|
|
99
|
+
('Initial state (--x0)', initial if initial is not None else 'required for execution'),
|
|
100
|
+
('Initial input (--u0)', held if held is not None else 'required for execution'),
|
|
101
|
+
('Integration interval (--dt)', f'{dt} s'), ('Initial time', f'{t0} s'),
|
|
102
|
+
('Controller', controller), ('Stepper', integrator),
|
|
103
|
+
('Viewer', viewer or 'none'),
|
|
104
|
+
]
|
|
105
|
+
for label, value in values:
|
|
106
|
+
_row(settings, label, value)
|
|
107
|
+
console.print(settings)
|
|
108
|
+
console.print(Panel(_documentation(model), title='Model documentation', border_style='blue'))
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def show_started(base, viewer):
|
|
112
|
+
"""Show local observation endpoints and the interruption hint in a startup panel."""
|
|
113
|
+
links = Table.grid(padding=(0, 2))
|
|
114
|
+
_row(links, 'Simulation API', f'{base}/api/state')
|
|
115
|
+
if viewer is not None:
|
|
116
|
+
_row(links, 'Viewer', f'{base}/')
|
|
117
|
+
_row(links, 'Stop', 'Ctrl+C')
|
|
118
|
+
Console(highlight=False).print(Panel(links, title='Simulation running', border_style='cyan'))
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def show_finished(snapshot, record):
|
|
122
|
+
"""Report the terminal state and optional recording after resources have closed."""
|
|
123
|
+
result = Table.grid(padding=(0, 2))
|
|
124
|
+
_row(result, 'Status', snapshot['status'])
|
|
125
|
+
_row(result, 'Simulated time', f"{snapshot['t']:.6g} s")
|
|
126
|
+
if record is not None:
|
|
127
|
+
_row(result, 'Recording', record)
|
|
128
|
+
Console(highlight=False).print(Panel(result, title='Simulation complete', border_style='green'))
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def show_error(message):
|
|
132
|
+
"""Report a worker failure on stderr without interpreting message markup."""
|
|
133
|
+
Console(stderr=True, highlight=False).print(
|
|
134
|
+
Panel(Text(message), title='Simulation error', border_style='red'))
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""In-process adapter shared by HTTP and future external protocol bridges."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
|
|
5
|
+
from ..runtime.protocols import SimulationPort
|
|
6
|
+
from ..runtime.signals import controller_identifier
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class InMemoryAdapter:
|
|
10
|
+
"""Read a simulation and submit commands under one fixed controller identity.
|
|
11
|
+
|
|
12
|
+
Configure the engine's active_controller explicitly to select the controller.
|
|
13
|
+
The identity is a routing/ownership label, not authentication. A bridge
|
|
14
|
+
runs its network loop outside the simulation worker and can use this
|
|
15
|
+
adapter directly without an intermediate HTTP request.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
def __init__(self, port: SimulationPort, *, controller_id='python'):
|
|
19
|
+
"""Bind a simulation port and validate the controller identity used for every write."""
|
|
20
|
+
self._port = port
|
|
21
|
+
self.controller_id = controller_identifier(controller_id)
|
|
22
|
+
|
|
23
|
+
def read_snapshot(self):
|
|
24
|
+
"""Read the committed state and command metadata through the simulation port."""
|
|
25
|
+
return self._port.snapshot()
|
|
26
|
+
|
|
27
|
+
def read_measurements(self):
|
|
28
|
+
"""Read state and held input values by signal name, together with time and status."""
|
|
29
|
+
return self._port.read_measurements()
|
|
30
|
+
|
|
31
|
+
def describe_signals(self):
|
|
32
|
+
"""Read ordered signal descriptions for mapping named inputs and measurements."""
|
|
33
|
+
return self._port.describe_signals()
|
|
34
|
+
|
|
35
|
+
def write_inputs(self, u, *, source_timestamp=None):
|
|
36
|
+
"""Submit a complete input vector as this controller; return acceptance metadata, without waiting for application."""
|
|
37
|
+
return self._port.submit_input(u, controller_id=self.controller_id,
|
|
38
|
+
source_timestamp=source_timestamp)
|
|
39
|
+
|
|
40
|
+
def write_signals(self, values, *, source_timestamp=None):
|
|
41
|
+
"""Map a complete set of named writable signals to the input vector."""
|
|
42
|
+
names = [signal['name'] for signal in self.describe_signals()
|
|
43
|
+
if signal['direction'] == 'input']
|
|
44
|
+
if not isinstance(values, Mapping) or set(values) != set(names):
|
|
45
|
+
raise ValueError(f'expected the complete writable signal set: {names}')
|
|
46
|
+
return self.write_inputs([values[name] for name in names],
|
|
47
|
+
source_timestamp=source_timestamp)
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""Local HTTP transport for model-independent observation and input submission.
|
|
2
|
+
|
|
3
|
+
This intentionally small server binds only to loopback. It is for local
|
|
4
|
+
experiments, not public deployment. Control and observation are decoupled
|
|
5
|
+
from the simulation worker; slow browser connections do not block physics.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
12
|
+
from importlib.resources import files
|
|
13
|
+
from urllib.parse import urlsplit
|
|
14
|
+
|
|
15
|
+
from .adapters import InMemoryAdapter
|
|
16
|
+
from ..runtime.protocols import SimulationPort
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def create_server(simulation: SimulationPort, *, host='127.0.0.1', port=8765, viewer=None):
|
|
20
|
+
"""Return an unstarted local HTTP server bound to ``simulation``.
|
|
21
|
+
|
|
22
|
+
GET /api/state returns a copied snapshot. GET /api/measurements returns
|
|
23
|
+
named measurements. GET /api/signals returns signal metadata.
|
|
24
|
+
POST /api/input accepts a complete ``{"u": [...]}`` vector with optional
|
|
25
|
+
UTC ``source_timestamp``. The fixed HTTP controller identity
|
|
26
|
+
is ``http``; it can write only when that controller is explicitly selected.
|
|
27
|
+
The optional viewer is selected explicitly or from snapshot metadata.
|
|
28
|
+
Without a configured scene, API routes remain available and GET / is 404.
|
|
29
|
+
Requests acknowledge acceptance, not application.
|
|
30
|
+
The next committed snapshot's input_seq identifies an applied command.
|
|
31
|
+
"""
|
|
32
|
+
from ..viewers import VIEWER_FILES, ASSET_FILES
|
|
33
|
+
|
|
34
|
+
if host not in ('127.0.0.1', 'localhost'):
|
|
35
|
+
raise ValueError('the demo server must bind to loopback')
|
|
36
|
+
selected_viewer = viewer if viewer is not None else simulation.snapshot().get('viewer')
|
|
37
|
+
if selected_viewer is not None and selected_viewer not in VIEWER_FILES:
|
|
38
|
+
raise ValueError('unknown packaged viewer')
|
|
39
|
+
adapter = InMemoryAdapter(simulation, controller_id='http')
|
|
40
|
+
|
|
41
|
+
class Handler(BaseHTTPRequestHandler):
|
|
42
|
+
"""Handle local API and viewer requests using the server-bound simulation adapter."""
|
|
43
|
+
protocol_version = 'HTTP/1.0'
|
|
44
|
+
|
|
45
|
+
def setup(self):
|
|
46
|
+
"""Initialize request streams and limit socket waits to three seconds."""
|
|
47
|
+
super().setup()
|
|
48
|
+
self.connection.settimeout(3.0)
|
|
49
|
+
|
|
50
|
+
def log_message(self, format, *args):
|
|
51
|
+
# Polling should not flood a user's terminal at 30 Hz.
|
|
52
|
+
"""Suppress default request logging so browser polling does not flood the terminal."""
|
|
53
|
+
pass
|
|
54
|
+
|
|
55
|
+
def _send(self, code, payload, content_type='application/json; charset=utf-8'):
|
|
56
|
+
# Windows may reset a connection closed with an unread POST body,
|
|
57
|
+
# hiding the error response. Drain only small, declared bodies;
|
|
58
|
+
# the socket timeout still bounds an incomplete request.
|
|
59
|
+
"""Send JSON or raw bytes with no-cache headers, tolerating client disconnects."""
|
|
60
|
+
if code >= 400 and self.command == 'POST' and not getattr(self, '_body_consumed', False):
|
|
61
|
+
try:
|
|
62
|
+
length = int(self.headers.get('Content-Length', '0'))
|
|
63
|
+
if 0 < length <= 4096 and self.headers.get('Transfer-Encoding') is None:
|
|
64
|
+
self.rfile.read(length)
|
|
65
|
+
except (ValueError, OSError):
|
|
66
|
+
pass
|
|
67
|
+
self._body_consumed = True
|
|
68
|
+
data = payload if isinstance(payload, bytes) else json.dumps(payload, allow_nan=False).encode('utf-8')
|
|
69
|
+
self.send_response(code)
|
|
70
|
+
self.send_header('Content-Type', content_type)
|
|
71
|
+
self.send_header('Content-Length', str(len(data)))
|
|
72
|
+
self.send_header('Cache-Control', 'no-store')
|
|
73
|
+
self.send_header('X-Content-Type-Options', 'nosniff')
|
|
74
|
+
self.send_header('Connection', 'close')
|
|
75
|
+
self.end_headers()
|
|
76
|
+
try:
|
|
77
|
+
self.wfile.write(data)
|
|
78
|
+
except (BrokenPipeError, ConnectionResetError, TimeoutError):
|
|
79
|
+
pass
|
|
80
|
+
|
|
81
|
+
def _local_request(self):
|
|
82
|
+
# Validate Host too, so DNS rebinding cannot turn arbitrary sites
|
|
83
|
+
# into an apparently same-origin caller of this local service.
|
|
84
|
+
"""Reject unexpected Host or cross-origin headers, sending an error response on rejection."""
|
|
85
|
+
expected_port = self.server.server_address[1]
|
|
86
|
+
hosts = {f'127.0.0.1:{expected_port}', f'localhost:{expected_port}'}
|
|
87
|
+
if expected_port == 80:
|
|
88
|
+
hosts.update(('127.0.0.1', 'localhost'))
|
|
89
|
+
if self.headers.get('Host', '').lower() not in hosts:
|
|
90
|
+
self._send(403, {'error': 'invalid local Host'})
|
|
91
|
+
return False
|
|
92
|
+
origin = self.headers.get('Origin')
|
|
93
|
+
if origin is not None and origin.lower() != f"http://{self.headers['Host'].lower()}":
|
|
94
|
+
self._send(403, {'error': 'cross-origin requests are not allowed'})
|
|
95
|
+
return False
|
|
96
|
+
return True
|
|
97
|
+
|
|
98
|
+
def _resource(self, name, content_type):
|
|
99
|
+
"""Serve a resource chosen from the explicit scene/asset registry."""
|
|
100
|
+
try:
|
|
101
|
+
payload = files('bs_simulators.viewers').joinpath(name).read_bytes()
|
|
102
|
+
except FileNotFoundError:
|
|
103
|
+
self._send(404, {'error': 'viewer resource is unavailable'})
|
|
104
|
+
return
|
|
105
|
+
self._send(200, payload, content_type)
|
|
106
|
+
|
|
107
|
+
def do_GET(self):
|
|
108
|
+
"""Serve state, measurements, signal descriptions or the packaged viewer."""
|
|
109
|
+
if not self._local_request():
|
|
110
|
+
return
|
|
111
|
+
path = urlsplit(self.path).path
|
|
112
|
+
if path == '/api/state':
|
|
113
|
+
self._send(200, adapter.read_snapshot())
|
|
114
|
+
elif path == '/api/measurements':
|
|
115
|
+
self._send(200, adapter.read_measurements())
|
|
116
|
+
elif path == '/api/signals':
|
|
117
|
+
self._send(200, adapter.describe_signals())
|
|
118
|
+
elif path.startswith('/assets/'):
|
|
119
|
+
name = path.removeprefix('/assets/')
|
|
120
|
+
if name not in ASSET_FILES:
|
|
121
|
+
self._send(404, {'error': 'unknown viewer resource'})
|
|
122
|
+
return
|
|
123
|
+
self._resource(name, ASSET_FILES[name])
|
|
124
|
+
elif path in ('/', '/viewer.html'):
|
|
125
|
+
if selected_viewer is None:
|
|
126
|
+
self._send(404, {'error': 'no viewer is configured for this simulation'})
|
|
127
|
+
return
|
|
128
|
+
self._resource(VIEWER_FILES[selected_viewer], 'text/html; charset=utf-8')
|
|
129
|
+
else:
|
|
130
|
+
self._send(404, {'error': 'unknown endpoint'})
|
|
131
|
+
|
|
132
|
+
def do_POST(self):
|
|
133
|
+
"""Validate a bounded JSON input request and acknowledge acceptance or report its rejection."""
|
|
134
|
+
if not self._local_request():
|
|
135
|
+
return
|
|
136
|
+
if urlsplit(self.path).path != '/api/input':
|
|
137
|
+
self._send(404, {'error': 'unknown endpoint'})
|
|
138
|
+
return
|
|
139
|
+
if self.headers.get('Transfer-Encoding') is not None:
|
|
140
|
+
self._send(400, {'error': 'transfer encoding is unsupported'})
|
|
141
|
+
return
|
|
142
|
+
if self.headers.get_content_type() != 'application/json':
|
|
143
|
+
self._send(415, {'error': 'Content-Type must be application/json'})
|
|
144
|
+
return
|
|
145
|
+
try:
|
|
146
|
+
length = int(self.headers.get('Content-Length', ''))
|
|
147
|
+
except ValueError:
|
|
148
|
+
self._send(411, {'error': 'valid Content-Length is required'})
|
|
149
|
+
return
|
|
150
|
+
if not 0 < length <= 4096:
|
|
151
|
+
self._send(413, {'error': 'request body must contain 1 to 4096 bytes'})
|
|
152
|
+
return
|
|
153
|
+
try:
|
|
154
|
+
self._body_consumed = True
|
|
155
|
+
raw = self.rfile.read(length)
|
|
156
|
+
if len(raw) != length:
|
|
157
|
+
raise ValueError('incomplete request body')
|
|
158
|
+
body = json.loads(raw)
|
|
159
|
+
if (not isinstance(body, dict) or 'u' not in body or
|
|
160
|
+
not set(body) <= {'u', 'source_timestamp'}):
|
|
161
|
+
raise ValueError('expected u with optional source_timestamp')
|
|
162
|
+
ack = adapter.write_inputs(body['u'], source_timestamp=body.get('source_timestamp'))
|
|
163
|
+
except (ValueError, TypeError, UnicodeDecodeError) as exc:
|
|
164
|
+
self._send(400, {'error': str(exc)})
|
|
165
|
+
return
|
|
166
|
+
except RuntimeError as exc:
|
|
167
|
+
self._send(409, {'error': str(exc)})
|
|
168
|
+
return
|
|
169
|
+
except PermissionError as exc:
|
|
170
|
+
self._send(403, {'error': str(exc)})
|
|
171
|
+
return
|
|
172
|
+
except TimeoutError:
|
|
173
|
+
self._send(408, {'error': 'request body timed out'})
|
|
174
|
+
return
|
|
175
|
+
self._send(202, ack)
|
|
176
|
+
|
|
177
|
+
server = ThreadingHTTPServer((host, port), Handler)
|
|
178
|
+
server.daemon_threads = True
|
|
179
|
+
return server
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""Model-independent simulation, numerical steppers and Python protocols."""
|
|
2
|
+
|
|
3
|
+
from .core import Simulation
|
|
4
|
+
from .protocols import SimulationPort, Stepper
|
|
5
|
+
from .signals import SignalDescriptor
|
|
6
|
+
from .steppers import ODEStepper, DAEStepper
|
|
7
|
+
|
|
8
|
+
__all__ = ['Simulation', 'SimulationPort', 'Stepper', 'SignalDescriptor',
|
|
9
|
+
'ODEStepper', 'DAEStepper']
|