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,51 @@
1
+ """Small numeric validators shared by the simulation runtime."""
2
+
3
+ import numpy as np
4
+
5
+
6
+ def _finite(name, value, *, positive=False, nonnegative=False):
7
+ """Return a finite real scalar, optionally requiring a positive sign."""
8
+ if isinstance(value, (bool, np.bool_, str, bytes)):
9
+ raise ValueError(f'{name} must be a finite number')
10
+ try:
11
+ raw = np.asarray(value)
12
+ if raw.ndim != 0 or raw.dtype.kind in 'bcSU':
13
+ raise ValueError
14
+ result = float(value)
15
+ except (TypeError, ValueError, OverflowError) as exc:
16
+ raise ValueError(f'{name} must be a finite number') from exc
17
+ if not np.isfinite(result):
18
+ raise ValueError(f'{name} must be finite')
19
+ if positive and result <= 0:
20
+ raise ValueError(f'{name} must be positive')
21
+ if nonnegative and result < 0:
22
+ raise ValueError(f'{name} must be nonnegative')
23
+ return result
24
+
25
+
26
+ def _vector(name, values, size=None, *, allow_empty=False):
27
+ """Return a detached finite real vector with an optional exact size.
28
+
29
+ Empty vectors are accepted only with ``allow_empty=True``. This permits
30
+ zero-input plants without allowing an empty state vector by default.
31
+ ``size=0`` is a valid exact-size requirement when empty values are allowed.
32
+ Boolean, complex, string and object arrays are rejected.
33
+ """
34
+ if size is not None:
35
+ if isinstance(size, (bool, np.bool_)) or not isinstance(size, (int, np.integer)) or size < 0:
36
+ raise ValueError('size must be a nonnegative integer or None')
37
+ try:
38
+ raw = np.asarray(values)
39
+ if raw.dtype.kind not in 'iuf':
40
+ raise ValueError
41
+ result = np.asarray(values, dtype=float)
42
+ except (TypeError, ValueError, OverflowError) as exc:
43
+ raise ValueError(f'{name} must be a finite numeric vector') from exc
44
+ if result.ndim != 1 or (not allow_empty and result.size == 0):
45
+ qualifier = '' if allow_empty else 'non-empty '
46
+ raise ValueError(f'{name} must be a {qualifier}one-dimensional vector')
47
+ if not np.isfinite(result).all():
48
+ raise ValueError(f'{name} values must be finite')
49
+ if size is not None and result.size != size:
50
+ raise ValueError(f'{name} must contain {size} values')
51
+ return result.copy()
@@ -0,0 +1,471 @@
1
+ """Simulation state and wall-clock pacing, independent of the viewer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import copy
7
+ import threading
8
+ import time
9
+ from dataclasses import dataclass
10
+ from collections.abc import Mapping
11
+ from pathlib import Path
12
+
13
+ import numpy as np
14
+ from ._validation import _finite, _vector
15
+ from .protocols import Stepper
16
+ from .steppers import ODEStepper
17
+ from .signals import SignalDescriptor, validate_source_timestamp, controller_identifier
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class _InputCommand:
22
+ """Immutable input receipt carrying its sequence, controller and diagnostic timestamps."""
23
+ seq: int
24
+ values: tuple[float, ...]
25
+ saturated: tuple[bool, ...]
26
+ controller_id: str
27
+ received_at: float
28
+ source_timestamp: str | None
29
+
30
+
31
+ class Simulation:
32
+ """Single-worker, model-independent simulator with latest-value ZOH.
33
+
34
+ Commands are accepted atomically and applied at the next step boundary.
35
+ An acknowledgement indicates acceptance, not physical application. The
36
+ browser reads copied snapshots and never owns or advances the simulation.
37
+ Pacing provides soft real time: overload accumulates visible lag, while
38
+ preserving every physical step. Completed runs cannot be restarted.
39
+ """
40
+
41
+ def __init__(self, model, *, stepper: Stepper | None = None, x0, u0, parameters=None,
42
+ dt=0.01, t0=0.0, state_signals=None, input_signals=None,
43
+ active_controller='python', viewer=None, input_map=None):
44
+ """Configure a numerical model and an optional integrator.
45
+
46
+ Parameters
47
+ ----------
48
+ model : callable
49
+ A benchmark-systems function or compatible numerical callable.
50
+ ODEs receive ``(t, x, **parameters, u=...)``; DAEs also receive
51
+ the derivative as their third positional argument. The chosen
52
+ stepper determines which signature is used.
53
+ stepper : Stepper or None, optional
54
+ Integrator configuration owned exclusively by this run. If omitted
55
+ or None, create a fresh ODEStepper(method='RK45'). Pass DAEStepper
56
+ explicitly for residual models, or another Stepper implementation
57
+ to customize integration.
58
+ x0, u0 : sequence of float
59
+ Initial state and complete held input vector. An empty input
60
+ vector denotes an autonomous model, called without ``u``.
61
+ parameters : mapping, optional
62
+ Detached, JSON-compatible model keyword arguments. NumPy arrays
63
+ and scalars are converted to lists and Python scalar values.
64
+ dt : float, optional
65
+ Positive integration interval in simulated seconds.
66
+ t0 : float, optional
67
+ Initial absolute model time. Duration and pacing are relative to it.
68
+ state_signals, input_signals : sequence of SignalDescriptor, optional
69
+ Ordered descriptions mapped to state and input vector positions.
70
+ Defaults are ``x0``, ``x1``, ... and ``u0``, ``u1``, ... .
71
+ active_controller : str, optional
72
+ Controller authorized to submit inputs; defaults to ``'python'``.
73
+ viewer : str or None, optional
74
+ Optional packaged-viewer identifier for communication adapters.
75
+ input_map : callable, optional
76
+ Map the complete input vector to model keyword arguments. By
77
+ default, one input becomes scalar ``u`` and several become vector
78
+ ``u``. Use a mapping for different names or a one-element vector.
79
+
80
+ Notes
81
+ -----
82
+ Construction initializes the stepper but does not start a thread.
83
+ A DAE stepper may adjust algebraic initial values for consistency.
84
+ Models with scalar/vector input conventions that differ from the
85
+ defaults should supply ``input_map`` explicitly.
86
+ """
87
+ if not callable(model):
88
+ raise ValueError('model must be callable')
89
+ if stepper is None:
90
+ stepper = ODEStepper(method='RK45')
91
+ if not isinstance(stepper, Stepper):
92
+ raise TypeError('stepper must implement the Stepper protocol')
93
+ if input_map is not None and not callable(input_map):
94
+ raise ValueError('input_map must be callable or None')
95
+ if viewer is not None and (not isinstance(viewer, str) or not viewer):
96
+ raise ValueError('viewer must be a non-empty identifier or None')
97
+ self.dt = _finite('dt', dt, positive=True)
98
+ self._t0 = _finite('t0', t0)
99
+ initial = _vector('x0', x0)
100
+ held = _vector('u0', u0, allow_empty=True)
101
+ self._input_size = held.size
102
+ self._active_controller = controller_identifier(active_controller)
103
+ self._parameters = self._copy_parameters(parameters)
104
+ self._state_signals = self._descriptors(state_signals, initial.size, 'x', 'output')
105
+ self._input_signals = self._descriptors(input_signals, held.size, 'u', 'input')
106
+ names = [signal.name for signal in (*self._state_signals, *self._input_signals)]
107
+ if len(set(names)) != len(names):
108
+ raise ValueError('signal names must be unique across states and inputs')
109
+ self._viewer = viewer
110
+ self._model_name = getattr(model, '__name__', type(model).__name__)
111
+ self._model = model
112
+ self._input_map = input_map
113
+ self._u, self._input_saturated = self._saturate_input(held.tolist())
114
+ self._stepper = stepper
115
+ stepper.initialize(self._evaluate, initial, t0=self._t0, u0=np.asarray(self._u, dtype=float))
116
+ self._lock = threading.Lock()
117
+ self._stop_event = threading.Event()
118
+ self._thread = None
119
+ self._pending = None
120
+ self._inflight = None
121
+ self._received_command = None
122
+ self._applied_command = None
123
+ self._command_seq = 0
124
+ self._input_seq = 0
125
+ self._applied_at = self._t0
126
+ self._seq = 0
127
+ self._status = 'ready'
128
+ self._error = None
129
+ self._started = None
130
+ self._dt_real = self.dt
131
+ self._snapshot = self._build_snapshot(0.0)
132
+
133
+ @staticmethod
134
+ def _copy_parameters(parameters):
135
+ """Detach model parameters through JSON, normalizing NumPy values and rejecting nonfinite data."""
136
+ if parameters is None:
137
+ return {}
138
+ if not isinstance(parameters, Mapping) or any(not isinstance(key, str) for key in parameters):
139
+ raise ValueError('parameters must be a mapping with string keys')
140
+
141
+ def convert(value):
142
+ """Convert NumPy arrays or scalars for JSON serialization; reject unsupported objects."""
143
+ if isinstance(value, np.ndarray):
144
+ return value.tolist()
145
+ if isinstance(value, np.generic):
146
+ return value.item()
147
+ raise TypeError('parameters must contain JSON-compatible values')
148
+
149
+ try:
150
+ return json.loads(json.dumps(dict(parameters), default=convert, allow_nan=False))
151
+ except (TypeError, ValueError) as exc:
152
+ raise ValueError('parameters must contain finite JSON-compatible values') from exc
153
+
154
+ @staticmethod
155
+ def _descriptors(descriptors, count, prefix, direction):
156
+ """Build default signal names or validate supplied descriptors against vector size and direction."""
157
+ if descriptors is None:
158
+ return tuple(SignalDescriptor(f'{prefix}{index}', '', 'float64', direction)
159
+ for index in range(count))
160
+ descriptors = tuple(descriptors)
161
+ if len(descriptors) != count:
162
+ raise ValueError(f'{direction} signal count must match its vector dimension')
163
+ result = []
164
+ for descriptor in descriptors:
165
+ if not isinstance(descriptor, SignalDescriptor):
166
+ raise TypeError('signals must be SignalDescriptor instances')
167
+ if (not isinstance(descriptor.name, str) or not descriptor.name.strip()
168
+ or descriptor.name in ('time', 'status')):
169
+ raise ValueError('signal names must be non-empty and cannot be time or status')
170
+ if descriptor.direction != direction:
171
+ raise ValueError(f'signal direction must be {direction!r}')
172
+ if not isinstance(descriptor.unit, str) or not isinstance(descriptor.dtype, str):
173
+ raise ValueError('signal unit and dtype must be strings')
174
+ lower = None if descriptor.lower is None else _finite('lower', descriptor.lower)
175
+ upper = None if descriptor.upper is None else _finite('upper', descriptor.upper)
176
+ if lower is not None and upper is not None and lower > upper:
177
+ raise ValueError('signal lower bound must not exceed its upper bound')
178
+ result.append(SignalDescriptor(descriptor.name, descriptor.unit, descriptor.dtype,
179
+ direction, lower, upper))
180
+ return tuple(result)
181
+
182
+ @property
183
+ def parameters(self):
184
+ """Return detached model parameters for interactive inspection."""
185
+ return copy.deepcopy(self._parameters)
186
+
187
+ @staticmethod
188
+ def _clamp(value, signal):
189
+ """Limit a value to the configured endpoints, if any."""
190
+ if signal.lower is not None and value < signal.lower:
191
+ return signal.lower
192
+ if signal.upper is not None and value > signal.upper:
193
+ return signal.upper
194
+ return value
195
+
196
+ def _saturate_input(self, values):
197
+ """Return effective actuator values and a flag for each clipped command."""
198
+ applied = [self._clamp(value, signal)
199
+ for value, signal in zip(values, self._input_signals)]
200
+ return applied, [value != effective for value, effective in zip(values, applied)]
201
+
202
+ def _evaluate(self, t, x, *arguments):
203
+ """Adapt stepper arguments to the model signature, binding physical parameters and mapped inputs."""
204
+ *derivative, u = arguments
205
+ if self._input_map is not None:
206
+ inputs = self._input_map(u.copy())
207
+ if not isinstance(inputs, Mapping) or any(not isinstance(key, str) for key in inputs):
208
+ raise ValueError('input_map must return keyword arguments as a mapping')
209
+ elif self._input_size == 0:
210
+ inputs = {}
211
+ else:
212
+ inputs = {'u': float(u[0]) if self._input_size == 1 else u}
213
+ if self._parameters.keys() & inputs.keys():
214
+ raise ValueError('model parameters must not duplicate mapped input names')
215
+ return self._model(t, x, *derivative, **self._parameters, **inputs)
216
+
217
+ def _build_snapshot(self, elapsed):
218
+ """Assemble committed solver state and timing metadata during initialization or while holding the lock."""
219
+ state = {
220
+ 't': self._stepper.t, 'x': self._stepper.x.tolist(),
221
+ 'u': list(self._u), 'input_saturated': list(self._input_saturated),
222
+ 'seq': self._seq, 'input_seq': self._input_seq,
223
+ 'pending_input_seq': self._pending_sequence(),
224
+ 'applied_at_sim_time': self._applied_at,
225
+ 'wall_elapsed': elapsed, 'lag': max(0.0, elapsed - self._seq * self._dt_real),
226
+ 'status': self._status, 'parameters': self.parameters,
227
+ 'model': self._model_name, 'viewer': self._viewer,
228
+ }
229
+ if self._stepper.xdot is not None:
230
+ state['xdot'] = self._stepper.xdot.tolist()
231
+ if self._error is not None:
232
+ state['error'] = self._error
233
+ state.update(self._input_metadata())
234
+ return state
235
+
236
+ def _input_metadata(self):
237
+ """Describe the latest received and applied commands; callers hold the lock after initialization."""
238
+ received = self._received_command
239
+ applied = self._applied_command
240
+ return {
241
+ 'active_controller': self._active_controller,
242
+ 'controller_id': applied.controller_id if applied else None,
243
+ 'received_input_seq': received.seq if received else 0,
244
+ 'received_at_monotonic': received.received_at if received else None,
245
+ 'source_timestamp': applied.source_timestamp if applied else None,
246
+ 'received_source_timestamp': received.source_timestamp if received else None,
247
+ 'applied_received_at_monotonic': applied.received_at if applied else None,
248
+ }
249
+
250
+ def _pending_sequence(self):
251
+ """Return the newest queued or in-flight sequence; callers hold the lock after initialization."""
252
+ command = self._pending or self._inflight
253
+ return command.seq if command else None
254
+
255
+ def snapshot(self):
256
+ """Return the committed model state before sensor limits.
257
+
258
+ The snapshot includes the applied input vector and its saturation
259
+ flags. Use read_measurements() for named sensor readings.
260
+ """
261
+ with self._lock:
262
+ result = copy.deepcopy(self._snapshot)
263
+ result['pending_input_seq'] = self._pending_sequence()
264
+ result.update(self._input_metadata())
265
+ return result
266
+
267
+ def describe_signals(self):
268
+ """Return detached metadata; direction is relative to the simulator."""
269
+ return [signal.as_dict() for signal in (*self._state_signals, *self._input_signals,
270
+ SignalDescriptor('time', 's', 'float64', 'output'),
271
+ SignalDescriptor('status', '', 'string', 'output'))]
272
+
273
+ def read_measurements(self):
274
+ """Return named sensor readings, applied inputs, time and status.
275
+
276
+ State readings are clipped at configured output bounds. Use
277
+ snapshot() to inspect the model state before sensor limits.
278
+ """
279
+ state = self.snapshot()
280
+ values = {signal.name: self._clamp(value, signal)
281
+ for signal, value in zip(self._state_signals, state['x'])}
282
+ values.update({signal.name: value for signal, value in zip(self._input_signals, state['u'])})
283
+ values.update(time=state['t'], status=state['status'])
284
+ return values
285
+
286
+ @property
287
+ def active_controller(self):
288
+ """Return the controller identity currently authorized to submit inputs."""
289
+ with self._lock:
290
+ return self._active_controller
291
+
292
+ def configure_controller(self, controller_id):
293
+ """Explicitly select one controller before start.
294
+
295
+ Switching while ready clears queued inputs and receipt metadata from
296
+ the previous controller. The held initial value remains unchanged.
297
+ """
298
+ controller_id = controller_identifier(controller_id)
299
+ with self._lock:
300
+ if self._status != 'ready':
301
+ raise RuntimeError('controller selection is only allowed before start')
302
+ if controller_id != self._active_controller:
303
+ self._active_controller = controller_id
304
+ self._pending = None
305
+ self._received_command = None
306
+
307
+ def set_input(self, u):
308
+ """Trusted Python convenience: submit as the configured active controller.
309
+
310
+ External bridges should use InMemoryAdapter with a fixed controller_id,
311
+ which enforces ownership instead of impersonating the active controller.
312
+ """
313
+ return self.submit_input(u, controller_id=self.active_controller)
314
+
315
+ def submit_input(self, u, *, controller_id, source_timestamp=None):
316
+ """Validate and atomically enqueue a complete input vector.
317
+
318
+ Receipt order uses local monotonic time and sequence numbers. A UTC
319
+ source timestamp is diagnostic metadata and never schedules commands.
320
+ Commands outside actuator bounds are clipped per input. Repeated
321
+ values are fresh receipts; rejected commands change nothing.
322
+ """
323
+ requested = _vector('u', u, self._input_size, allow_empty=True).tolist()
324
+ values, saturated = self._saturate_input(requested)
325
+ controller_id = controller_identifier(controller_id)
326
+ source_timestamp = validate_source_timestamp(source_timestamp)
327
+ with self._lock:
328
+ if self._status not in ('ready', 'running'):
329
+ raise RuntimeError('simulation is not accepting inputs')
330
+ if controller_id != self._active_controller:
331
+ raise PermissionError(f'controller {controller_id!r} is not the active controller')
332
+ self._command_seq += 1
333
+ self._pending = _InputCommand(self._command_seq, tuple(values), tuple(saturated),
334
+ controller_id, time.monotonic(), source_timestamp)
335
+ self._received_command = self._pending
336
+ return {'input_seq': self._command_seq, 'pending_input_seq': self._command_seq,
337
+ 'accepted_input_seq': self._command_seq, 'applied_input_seq': self._input_seq,
338
+ 'controller_id': controller_id, 'received_at_monotonic': self._pending.received_at}
339
+
340
+ def start(self, *, duration=None, record=None, dt_real=None):
341
+ """Start a worker; optionally record initial state and each committed step.
342
+
343
+ ``duration`` is in simulated seconds. It must be a whole number of
344
+ fixed steps so recorded time and requested duration agree exactly.
345
+ ``record`` is a JSONL path, created exclusively to avoid overwrites.
346
+ ``dt_real`` is the positive interval between step deadlines in wall-clock
347
+ seconds. It defaults to ``dt``. The solver always advances by ``dt``.
348
+ """
349
+ period = self.dt if dt_real is None else _finite('dt_real', dt_real, positive=True)
350
+ steps = None
351
+ if duration is not None:
352
+ duration = _finite('duration', duration, positive=True)
353
+ count = duration / self.dt
354
+ if not np.isfinite(count) or not np.isclose(count, round(count), rtol=0, atol=1e-8):
355
+ raise ValueError('duration must be a whole number of dt steps')
356
+ steps = int(round(count))
357
+ if steps < 1:
358
+ raise ValueError('duration must include at least one step')
359
+ with self._lock:
360
+ if self._status != 'ready':
361
+ raise RuntimeError('simulation has already been started or stopped')
362
+ stream = Path(record).open('x', encoding='utf-8') if record is not None else None
363
+ self._dt_real = period
364
+ self._started = time.monotonic()
365
+ self._status = 'running'
366
+ self._snapshot = self._build_snapshot(0.0)
367
+ self._thread = threading.Thread(target=self._run, args=(steps, stream),
368
+ name='simulation', daemon=False)
369
+ self._thread.start()
370
+ return self
371
+
372
+ def _wait_until(self, deadline):
373
+ """Wait for a wall-clock deadline, returning true on a stop request."""
374
+ remaining = deadline - time.monotonic()
375
+ while remaining > threading.TIMEOUT_MAX:
376
+ if self._stop_event.wait(threading.TIMEOUT_MAX):
377
+ return True
378
+ remaining = deadline - time.monotonic()
379
+ return self._stop_event.wait(max(0.0, remaining))
380
+
381
+ def _run(self, steps, stream):
382
+ """Pace fixed intervals, apply held inputs and publish completed steps from the worker thread.
383
+
384
+ Freeze inputs before waiting for each deadline; publish state only after a
385
+ successful step. Record initial, committed and terminal snapshots when a
386
+ stream is supplied, then close it even if integration or recording fails.
387
+ """
388
+ try:
389
+ if stream is not None:
390
+ stream.write(json.dumps(self.snapshot(), allow_nan=False) + '\n')
391
+ while not self._stop_event.is_set() and (steps is None or self._seq < steps):
392
+ with self._lock:
393
+ command = self._pending
394
+ self._pending = None
395
+ self._inflight = command
396
+ held = list(command.values if command else self._u)
397
+ input_seq = command.seq if command else self._input_seq
398
+ applied_at = self._stepper.t if command else self._applied_at
399
+ # Freeze at the interval's beginning: commands arriving while
400
+ # we wait cannot retroactively affect the preceding interval.
401
+ # Absolute deadlines avoid cumulative sleep/compute drift.
402
+ deadline = self._started + (self._seq + 1) * self._dt_real
403
+ if self._wait_until(deadline):
404
+ break
405
+ self._stepper.step(self.dt, held)
406
+ with self._lock:
407
+ self._u = held
408
+ self._input_seq = input_seq
409
+ if command is not None:
410
+ self._applied_command = command
411
+ self._input_saturated = command.saturated
412
+ self._applied_at = applied_at
413
+ self._inflight = None
414
+ self._seq += 1
415
+ self._snapshot = self._build_snapshot(time.monotonic() - self._started)
416
+ recorded = dict(self._snapshot)
417
+ if stream is not None:
418
+ stream.write(json.dumps(recorded, allow_nan=False) + '\n')
419
+ except Exception as exc:
420
+ with self._lock:
421
+ self._status = 'error'
422
+ self._error = f'{type(exc).__name__}: {exc}'
423
+ finally:
424
+ with self._lock:
425
+ if self._status != 'error':
426
+ self._status = 'finished' if steps is not None and self._seq >= steps else 'stopped'
427
+ self._pending = None
428
+ self._inflight = None
429
+ self._snapshot = self._build_snapshot(time.monotonic() - self._started)
430
+ terminal = dict(self._snapshot)
431
+ if stream is not None:
432
+ try:
433
+ stream.write(json.dumps(terminal, allow_nan=False) + '\n')
434
+ stream.close()
435
+ except Exception as exc:
436
+ try:
437
+ stream.close()
438
+ except Exception:
439
+ pass
440
+ with self._lock:
441
+ self._status = 'error'
442
+ self._error = f'{type(exc).__name__}: {exc}'
443
+ self._snapshot = self._build_snapshot(time.monotonic() - self._started)
444
+
445
+ def wait(self, timeout=None):
446
+ """Wait for completion and return whether this run has stopped.
447
+
448
+ ``timeout`` is an optional nonnegative number of wall-clock seconds.
449
+ This method does not advance the model or request a stop.
450
+ """
451
+ if timeout is not None:
452
+ timeout = _finite('timeout', timeout, nonnegative=True)
453
+ thread = self._thread
454
+ if thread is None:
455
+ return self._status != 'ready'
456
+ if thread is threading.current_thread():
457
+ raise RuntimeError('the simulation worker cannot wait for itself')
458
+ thread.join(timeout)
459
+ return not thread.is_alive()
460
+
461
+ def stop(self):
462
+ """Request shutdown and wait for the in-flight integration to complete."""
463
+ self._stop_event.set()
464
+ thread = self._thread
465
+ if thread is not None and thread is not threading.current_thread():
466
+ thread.join()
467
+ with self._lock:
468
+ if self._status == 'ready':
469
+ self._status = 'stopped'
470
+ self._pending = None
471
+ self._snapshot = self._build_snapshot(0.0)