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.
@@ -0,0 +1,44 @@
1
+ """Live simulators, transports and viewers for benchmark-systems models.
2
+
3
+ Subpackages are loaded on demand, so runtime imports do not initialize HTTP
4
+ or viewer components. The numerical model library remains an independent
5
+ dependency.
6
+ """
7
+
8
+ from importlib import import_module
9
+
10
+ __version__ = '0.1.2'
11
+
12
+ __all__ = ['Simulation', 'Stepper', 'ODEStepper', 'DAEStepper',
13
+ 'InMemoryAdapter', 'SimulationPort',
14
+ 'SignalDescriptor', 'SimulationConfiguration', 'list_configurations',
15
+ 'load_configuration', 'load_configuration_file', '__version__']
16
+
17
+ _EXPORTS = {
18
+ 'SimulationConfiguration': '.catalogue',
19
+ 'list_configurations': '.catalogue',
20
+ 'load_configuration': '.catalogue',
21
+ 'load_configuration_file': '.catalogue',
22
+ 'Simulation': '.runtime.core',
23
+ 'Stepper': '.runtime.protocols',
24
+ 'ODEStepper': '.runtime.steppers',
25
+ 'DAEStepper': '.runtime.steppers',
26
+ 'InMemoryAdapter': '.comms.adapters',
27
+ 'SimulationPort': '.runtime.protocols',
28
+ 'SignalDescriptor': '.runtime.signals',
29
+ }
30
+
31
+
32
+ def __getattr__(name):
33
+ """Load and cache a public export on first access, keeping imports lazy."""
34
+ module_name = _EXPORTS.get(name)
35
+ if module_name is None:
36
+ raise AttributeError(f'module {__name__!r} has no attribute {name!r}')
37
+ value = getattr(import_module(module_name, __name__), name)
38
+ globals()[name] = value
39
+ return value
40
+
41
+
42
+ def __dir__():
43
+ """Include lazy public exports in interactive attribute discovery."""
44
+ return sorted(set(globals()) | set(__all__))
@@ -0,0 +1,12 @@
1
+ """Run ``python -m bs_simulators`` or the installed bs-simulators command."""
2
+
3
+ from .cli import app
4
+
5
+
6
+ def main(argv=None):
7
+ """Invoke the Typer application with ordinary command-line exit behavior."""
8
+ app(args=argv, prog_name='bs-simulators')
9
+
10
+
11
+ if __name__ == '__main__':
12
+ main()
@@ -0,0 +1,160 @@
1
+ """Optional data-only configurations for benchmark-systems models.
2
+
3
+ Listing and loading configurations use only the Python standard library.
4
+ Numerical dependencies are imported when create() constructs a simulation.
5
+ TOML model names are restricted to benchmark_systems.models public exports;
6
+ arbitrary numerical callables can still be supplied directly to Simulation.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Mapping
12
+ import copy
13
+ from dataclasses import dataclass, replace
14
+ from importlib import resources
15
+ import inspect
16
+ from pathlib import Path
17
+ import tomllib
18
+ from typing import Any
19
+
20
+ from ._validation import _configuration_values, _document_fields, _stepper_spec, _text
21
+
22
+
23
+ __all__ = ['SimulationConfiguration', 'list_configurations',
24
+ 'load_configuration', 'load_configuration_file']
25
+
26
+ @dataclass(frozen=True)
27
+ class SimulationConfiguration:
28
+ """Data for constructing fresh simulations without copying model equations.
29
+
30
+ Parameters are shallow-merged by key when overridden, with nested values
31
+ copied recursively. State/input overrides replace entire vectors. Every
32
+ create() call using a stepper specification constructs a new integrator;
33
+ an explicitly supplied Stepper object instead follows its usual single-use
34
+ ownership rules. This frozen dataclass contains user-editable nested data,
35
+ but creating a simulation never mutates that data. Loading and construction
36
+ operate in memory and never create or overwrite configuration files.
37
+ """
38
+
39
+ name: str
40
+ model: str
41
+ parameters: dict[str, Any]
42
+ x0: list[float]
43
+ u0: list[float]
44
+ dt: float = 0.01
45
+ active_controller: str = 'python'
46
+ viewer: str | None = None
47
+ state_signals: list[dict[str, Any]] | None = None
48
+ input_signals: list[dict[str, Any]] | None = None
49
+ stepper: dict[str, Any] | None = None
50
+ t0: float = 0.0
51
+
52
+ def __post_init__(self):
53
+ """Store validated copies of configuration data without importing the simulation runtime."""
54
+ for key, value in _configuration_values(self).items():
55
+ object.__setattr__(self, key, value)
56
+
57
+ def create(self, *, parameters=None, x0=None, u0=None, dt=None,
58
+ active_controller=None, stepper=None):
59
+ """Return a new Simulation with optional, detached user overrides.
60
+
61
+ Only public benchmark_systems.models functions are selected by name.
62
+ Unknown or missing physical parameter names raise ValueError before
63
+ the runtime starts. A stepper override may be a complete specification
64
+ mapping or an explicitly supplied fresh Stepper instance. t0, signal
65
+ descriptions and viewer settings come from the configuration. This
66
+ method never saves a TOML file or modifies the configuration source.
67
+ """
68
+ configuration = replace(self)
69
+ # Numerical imports happen only when a simulation is requested.
70
+ from benchmark_systems import models
71
+ from ..runtime.core import Simulation
72
+ from ..runtime.signals import SignalDescriptor
73
+ from ..runtime.steppers import ODEStepper, DAEStepper
74
+
75
+ if configuration.model not in models.__all__:
76
+ raise ValueError(f'unknown public benchmark model: {configuration.model!r}')
77
+ model = getattr(models, configuration.model)
78
+ model_parameters = copy.deepcopy(configuration.parameters)
79
+ if parameters is not None:
80
+ if not isinstance(parameters, Mapping) or any(not isinstance(key, str) for key in parameters):
81
+ raise ValueError('parameter overrides must be a mapping with string keys')
82
+ model_parameters.update(copy.deepcopy(dict(parameters)))
83
+ signature = inspect.signature(model)
84
+ physical = {name: parameter for name, parameter in signature.parameters.items()
85
+ if parameter.kind is inspect.Parameter.KEYWORD_ONLY and name != 'u'}
86
+ unknown = model_parameters.keys() - physical.keys()
87
+ if unknown:
88
+ raise ValueError(f'unknown parameters for {configuration.model}: {sorted(unknown)}')
89
+ missing = {name for name, parameter in physical.items()
90
+ if parameter.default is inspect.Parameter.empty and name not in model_parameters}
91
+ if missing:
92
+ raise ValueError(f'missing parameters for {configuration.model}: {sorted(missing)}')
93
+
94
+ states = copy.deepcopy(configuration.x0 if x0 is None else x0)
95
+ inputs = copy.deepcopy(configuration.u0 if u0 is None else u0)
96
+ try:
97
+ state_size = len(states)
98
+ except TypeError as exc:
99
+ raise ValueError('x0 must be a non-empty numeric vector') from exc
100
+ selected_stepper = stepper
101
+ if selected_stepper is None or isinstance(selected_stepper, Mapping):
102
+ specification = configuration.stepper if selected_stepper is None else selected_stepper
103
+ specification = _stepper_spec(specification, state_size) or {'kind': 'ode'}
104
+ options = dict(specification)
105
+ kind = options.pop('kind')
106
+ selected_stepper = ODEStepper(**options) if kind == 'ode' else DAEStepper(**options)
107
+
108
+ def descriptions(values):
109
+ """Convert optional signal tables into independent runtime descriptors."""
110
+ return None if values is None else [SignalDescriptor(**copy.deepcopy(value)) for value in values]
111
+
112
+ try:
113
+ return Simulation(
114
+ model, stepper=selected_stepper, x0=states, u0=inputs,
115
+ parameters=model_parameters,
116
+ dt=configuration.dt if dt is None else dt,
117
+ t0=configuration.t0,
118
+ active_controller=configuration.active_controller if active_controller is None else active_controller,
119
+ viewer=configuration.viewer,
120
+ state_signals=descriptions(configuration.state_signals),
121
+ input_signals=descriptions(configuration.input_signals),
122
+ )
123
+ except (TypeError, ValueError, IndexError, KeyError, ArithmeticError, RuntimeError) as exc:
124
+ raise ValueError(f'invalid configuration {configuration.name!r}: {exc}') from exc
125
+
126
+
127
+ def list_configurations() -> list[str]:
128
+ """List bundled configuration names without importing numerical modules."""
129
+ return sorted(item.name[:-5] for item in resources.files(__package__).iterdir()
130
+ if item.is_file() and item.name.endswith('.toml'))
131
+
132
+
133
+ def _load_document(text, default_name):
134
+ """Parse TOML text and construct a validated configuration using the supplied fallback name."""
135
+ try:
136
+ data = tomllib.loads(text)
137
+ except tomllib.TOMLDecodeError as exc:
138
+ raise ValueError(f'invalid configuration TOML: {exc}') from exc
139
+ return SimulationConfiguration(**_document_fields(data, default_name))
140
+
141
+
142
+ def load_configuration(name: str) -> SimulationConfiguration:
143
+ """Read a bundled TOML configuration using package resources."""
144
+ _text('configuration name', name)
145
+ available = list_configurations()
146
+ if name not in available:
147
+ raise ValueError(f'unknown configuration {name!r}; available: {", ".join(available)}')
148
+ resource = resources.files(__package__).joinpath(name + '.toml')
149
+ return _load_document(resource.read_text(encoding='utf-8'), name)
150
+
151
+
152
+ def load_configuration_file(path) -> SimulationConfiguration:
153
+ """Read a complete custom TOML file without inheritance or arbitrary imports.
154
+
155
+ Required fields are model, parameters, x0 and u0. Missing optional name
156
+ defaults to the file stem. Parsing/schema errors raise ValueError; file
157
+ access errors retain their usual OSError subclasses.
158
+ """
159
+ path = Path(path)
160
+ return _load_document(path.read_text(encoding='utf-8'), path.stem)
@@ -0,0 +1,159 @@
1
+ """Standard-library validation for catalogue data, without runtime imports."""
2
+
3
+ from collections.abc import Mapping
4
+ import copy
5
+ import json
6
+ import math
7
+
8
+
9
+ _FIELDS = {
10
+ 'name', 'model', 'parameters', 'x0', 'u0', 'dt', 't0',
11
+ 'active_controller', 'viewer', 'state_signals', 'input_signals', 'stepper',
12
+ }
13
+ _STEPPER_FIELDS = {'kind', 'method', 'rtol', 'atol', 'xdot0', 'fixed_x'}
14
+ _SIGNAL_FIELDS = {'name', 'unit', 'dtype', 'direction', 'lower', 'upper'}
15
+
16
+
17
+ def _text(name, value):
18
+ """Return a nonempty label without surrounding whitespace or control characters."""
19
+ if (not isinstance(value, str) or not value or value != value.strip()
20
+ or any(ord(character) < 32 for character in value)):
21
+ raise ValueError(f'{name} must be a non-empty string without surrounding whitespace')
22
+ return value
23
+
24
+
25
+ def _number(name, value, *, positive=False):
26
+ """Return a finite real scalar, optionally requiring a strictly positive value."""
27
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
28
+ raise ValueError(f'{name} must be a finite number')
29
+ try:
30
+ value = float(value)
31
+ except OverflowError as exc:
32
+ raise ValueError(f'{name} must be finite') from exc
33
+ if not math.isfinite(value) or (positive and value <= 0):
34
+ qualifier = 'positive and finite' if positive else 'finite'
35
+ raise ValueError(f'{name} must be {qualifier}')
36
+ return value
37
+
38
+
39
+ def _numbers(name, values, *, empty=False):
40
+ """Normalize a numeric list or tuple; allow empty inputs only when requested."""
41
+ if not isinstance(values, (list, tuple)) or (not empty and not values):
42
+ raise ValueError(f'{name} must be a {"possibly empty" if empty else "non-empty"} numeric array')
43
+ return [_number(name, value) for value in values]
44
+
45
+
46
+ def _parameters(values):
47
+ """Return detached, finite JSON-compatible model parameters with string keys."""
48
+ if not isinstance(values, Mapping) or any(not isinstance(key, str) for key in values):
49
+ raise ValueError('parameters must be a table with string keys')
50
+ try:
51
+ return json.loads(json.dumps(dict(values), allow_nan=False))
52
+ except (ValueError, TypeError, OverflowError) as exc:
53
+ raise ValueError('parameters must contain finite JSON-compatible values') from exc
54
+
55
+
56
+ def _signals(name, values, count, direction):
57
+ """Validate ordered signal tables, their dimensions, direction and inclusive bounds."""
58
+ if values is None:
59
+ return None
60
+ if not isinstance(values, (list, tuple)) or len(values) != count:
61
+ raise ValueError(f'{name} must contain {count} signal descriptions')
62
+ result = []
63
+ for value in values:
64
+ if not isinstance(value, Mapping):
65
+ raise ValueError(f'{name} entries must be signal tables')
66
+ unknown = set(value) - _SIGNAL_FIELDS
67
+ missing = {'name', 'unit', 'dtype', 'direction'} - set(value)
68
+ if unknown or missing:
69
+ raise ValueError(f'invalid {name} fields: unknown={sorted(unknown)}, missing={sorted(missing)}')
70
+ signal = dict(value)
71
+ _text('signal name', signal['name'])
72
+ if signal['name'] in ('time', 'status'):
73
+ raise ValueError('signal names cannot be time or status')
74
+ if not isinstance(signal['unit'], str) or not isinstance(signal['dtype'], str):
75
+ raise ValueError('signal unit and dtype must be strings')
76
+ if signal['direction'] != direction:
77
+ raise ValueError(f'{name} direction must be {direction!r}')
78
+ for bound in ('lower', 'upper'):
79
+ if signal.get(bound) is not None:
80
+ signal[bound] = _number(f'signal {bound}', signal[bound])
81
+ if (signal.get('lower') is not None and signal.get('upper') is not None
82
+ and signal['lower'] > signal['upper']):
83
+ raise ValueError('signal lower bound must not exceed its upper bound')
84
+ result.append(copy.deepcopy(signal))
85
+ return result
86
+
87
+
88
+ def _stepper_spec(value, state_size):
89
+ """Copy and validate integrator options against the state dimension, without importing solvers."""
90
+ if value is None:
91
+ return None
92
+ if not isinstance(value, Mapping):
93
+ raise ValueError('stepper configuration must be a table')
94
+ unknown = set(value) - _STEPPER_FIELDS
95
+ if unknown:
96
+ raise ValueError(f'unknown stepper fields: {sorted(unknown)}')
97
+ value = copy.deepcopy(dict(value))
98
+ kind = value.setdefault('kind', 'ode')
99
+ if kind not in ('ode', 'dae'):
100
+ raise ValueError("stepper kind must be 'ode' or 'dae'")
101
+ if 'method' in value:
102
+ _text('stepper method', value['method'])
103
+ for tolerance in ('rtol', 'atol'):
104
+ if tolerance in value:
105
+ value[tolerance] = _number(tolerance, value[tolerance], positive=True)
106
+ if kind == 'ode':
107
+ if {'xdot0', 'fixed_x'} & value.keys():
108
+ raise ValueError('an ODE stepper does not accept xdot0 or fixed_x')
109
+ else:
110
+ if 'xdot0' not in value:
111
+ raise ValueError('a DAE stepper requires xdot0')
112
+ value['xdot0'] = _numbers('xdot0', value['xdot0'])
113
+ if len(value['xdot0']) != state_size:
114
+ raise ValueError('xdot0 must have the same length as x0')
115
+ fixed = value.get('fixed_x')
116
+ if fixed is not None:
117
+ if (not isinstance(fixed, (list, tuple))
118
+ or any(isinstance(index, bool) or not isinstance(index, int) for index in fixed)
119
+ or any(index < 0 or index >= state_size for index in fixed)
120
+ or len(set(fixed)) != len(fixed)):
121
+ raise ValueError('fixed_x must contain unique state indices within x0')
122
+ value['fixed_x'] = list(fixed)
123
+ return value
124
+
125
+
126
+ def _configuration_values(configuration):
127
+ """Validate configuration fields and return normalized, detached values for dataclass initialization."""
128
+ _text('configuration name', configuration.name)
129
+ _text('model', configuration.model)
130
+ controller = _text('active_controller', configuration.active_controller)
131
+ if len(controller) > 128:
132
+ raise ValueError('active_controller must contain at most 128 characters')
133
+ if configuration.viewer is not None:
134
+ _text('viewer', configuration.viewer)
135
+ states = _numbers('x0', configuration.x0)
136
+ inputs = _numbers('u0', configuration.u0, empty=True)
137
+ state_signals = _signals('state_signals', configuration.state_signals, len(states), 'output')
138
+ input_signals = _signals('input_signals', configuration.input_signals, len(inputs), 'input')
139
+ names = [signal['name'] for signal in state_signals] if state_signals is not None else [f'x{i}' for i in range(len(states))]
140
+ names += [signal['name'] for signal in input_signals] if input_signals is not None else [f'u{i}' for i in range(len(inputs))]
141
+ if len(set(names)) != len(names):
142
+ raise ValueError('signal names must be unique across states and inputs')
143
+ return {
144
+ 'parameters': _parameters(configuration.parameters), 'x0': states, 'u0': inputs,
145
+ 'dt': _number('dt', configuration.dt, positive=True), 't0': _number('t0', configuration.t0),
146
+ 'state_signals': state_signals, 'input_signals': input_signals,
147
+ 'stepper': _stepper_spec(configuration.stepper, len(states)),
148
+ }
149
+
150
+ def _document_fields(data, default_name):
151
+ """Validate top-level TOML fields and supply the configuration name when omitted."""
152
+ unknown = set(data) - _FIELDS
153
+ if unknown:
154
+ raise ValueError(f'unknown configuration fields: {sorted(unknown)}')
155
+ missing = {'model', 'parameters', 'x0', 'u0'} - set(data)
156
+ if missing:
157
+ raise ValueError(f'missing configuration fields: {sorted(missing)}')
158
+ data.setdefault('name', default_name)
159
+ return data
@@ -0,0 +1,46 @@
1
+ name = "dc-motor"
2
+ model = "dc_motor"
3
+ x0 = [0.0, 0.0, 0.0]
4
+ u0 = [1.0]
5
+ dt = 0.01
6
+ t0 = 0.0
7
+ active_controller = "python"
8
+ viewer = "dc-motor"
9
+
10
+ [parameters]
11
+ J = 0.02
12
+ b = 0.1
13
+ Ke = 0.01
14
+ Kt = 0.01
15
+ R = 1.0
16
+ L = 0.5
17
+
18
+ [stepper]
19
+ kind = "ode"
20
+ method = "RK45"
21
+ rtol = 1e-7
22
+ atol = 1e-9
23
+
24
+ [[state_signals]]
25
+ name = "theta"
26
+ unit = "rad"
27
+ dtype = "float64"
28
+ direction = "output"
29
+
30
+ [[state_signals]]
31
+ name = "omega"
32
+ unit = "rad/s"
33
+ dtype = "float64"
34
+ direction = "output"
35
+
36
+ [[state_signals]]
37
+ name = "current"
38
+ unit = "A"
39
+ dtype = "float64"
40
+ direction = "output"
41
+
42
+ [[input_signals]]
43
+ name = "voltage"
44
+ unit = "V"
45
+ dtype = "float64"
46
+ direction = "input"
@@ -0,0 +1,63 @@
1
+ name = "neutralization"
2
+ model = "neutralization"
3
+ x0 = [-0.000432, 0.000528, 14.0, 7.0]
4
+ u0 = [15.6]
5
+ dt = 0.1
6
+ t0 = 0.0
7
+ active_controller = "python"
8
+ viewer = "neutralization"
9
+
10
+ [parameters]
11
+ A = 207.0
12
+ z = 11.5
13
+ Cv4 = 4.59
14
+ n = 0.607
15
+ Wa1 = 0.003
16
+ Wa2 = -0.03
17
+ Wa3 = -0.00305
18
+ Wb1 = 0.0
19
+ Wb2 = 0.03
20
+ Wb3 = 0.00005
21
+ pK1 = 6.35
22
+ pK2 = 10.33
23
+ q1 = 16.6
24
+ d = 0.55
25
+
26
+ [stepper]
27
+ kind = "dae"
28
+ method = "Radau"
29
+ xdot0 = [0.0, 0.0, 0.0, 0.0]
30
+ fixed_x = [0, 1, 2]
31
+ rtol = 1e-7
32
+ atol = 1e-9
33
+
34
+ [[state_signals]]
35
+ name = "Wa4"
36
+ unit = "mol/L"
37
+ dtype = "float64"
38
+ direction = "output"
39
+
40
+ [[state_signals]]
41
+ name = "Wb4"
42
+ unit = "mol/L"
43
+ dtype = "float64"
44
+ direction = "output"
45
+
46
+ [[state_signals]]
47
+ name = "h"
48
+ unit = "cm"
49
+ dtype = "float64"
50
+ direction = "output"
51
+
52
+ [[state_signals]]
53
+ name = "pH"
54
+ unit = ""
55
+ dtype = "float64"
56
+ direction = "output"
57
+
58
+ [[input_signals]]
59
+ name = "q3"
60
+ unit = "L/s"
61
+ dtype = "float64"
62
+ direction = "input"
63
+ lower = 0.0
@@ -0,0 +1,37 @@
1
+ name = "pendulum"
2
+ model = "pendulum"
3
+ x0 = [3.041592653589793, 0.0] # pi - 0.1 rad
4
+ u0 = [0.0]
5
+ dt = 0.01
6
+ t0 = 0.0
7
+ active_controller = "python"
8
+ viewer = "pendulum"
9
+
10
+ [parameters]
11
+ m = 1.0
12
+ L = 2.0
13
+ drag = 0.0
14
+
15
+ [stepper]
16
+ kind = "ode"
17
+ method = "RK45"
18
+ rtol = 1e-7
19
+ atol = 1e-9
20
+
21
+ [[state_signals]]
22
+ name = "theta"
23
+ unit = "rad"
24
+ dtype = "float64"
25
+ direction = "output"
26
+
27
+ [[state_signals]]
28
+ name = "omega"
29
+ unit = "rad/s"
30
+ dtype = "float64"
31
+ direction = "output"
32
+
33
+ [[input_signals]]
34
+ name = "torque"
35
+ unit = "N m"
36
+ dtype = "float64"
37
+ direction = "input"
@@ -0,0 +1,5 @@
1
+ """Typed terminal application; importing it does not initialize simulation components."""
2
+
3
+ from .commands import app
4
+
5
+ __all__ = ['app']