blocksim 0.1.0__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.
blocksim/continuous.py ADDED
@@ -0,0 +1,586 @@
1
+ """
2
+ Continuous-time blocks: the linear core of a signal-flow diagram.
3
+
4
+ Everything here has a continuous state vector that `solve_ivp` advances,
5
+ and between them they cover the shapes most diagrams are built from --
6
+ integration, differentiation, a PID, and a linear system written as
7
+ matrices, a transfer function or a zero-pole-gain.
8
+
9
+ Three things are worth knowing before reaching for one.
10
+
11
+ **Direct feedthrough decides the evaluation order.** A block whose output
12
+ reads its input in the same instant can close an algebraic loop; one
13
+ whose output is a pure function of its state cannot. `Integrator` and
14
+ `StateSpace` with `D = 0` break loops; `Derivative`, `PIDController` and
15
+ `StateSpace` with a `D` term do not. `StateSpace` reports this from `D`
16
+ itself rather than assuming the worst, which is why a strictly proper
17
+ plant in a feedback loop needs no algebraic solve.
18
+
19
+ **Structure hooks feed the sparsity pass.** `Integrator` and `StateSpace`
20
+ implement `derivative_pattern()` and `output_pattern()`, so
21
+ `System.jacobian_sparsity()` knows that channel `i` of a vector
22
+ integrator has nothing to do with channel `j`, and that a companion-form
23
+ transfer function has an almost empty `A`. Without them the compiler has
24
+ to assume every state couples to every other, and a stiff solve pays for
25
+ it.
26
+
27
+ **Limiting is not free.** `IntegratorLimited` and
28
+ `SecondOrderIntegratorLimited` stop by switching their derivative to
29
+ zero at the bound. That is the correct anti-windup behaviour and it is
30
+ also a discontinuity in the right-hand side, which an adaptive solver
31
+ will step over and then reject. Neither block declares an event, so the
32
+ limit is enforced but not located exactly; for a hard mechanical stop
33
+ where the instant matters, `blocksim.discontinuities` and an event are the
34
+ better tool.
35
+
36
+ SI is assumed nowhere here: these blocks carry whatever units are wired
37
+ into them, and their ports are declared without units for that reason.
38
+ """
39
+
40
+ import numpy as np
41
+
42
+ # scipy is imported inside the constructors that use it: importing it
43
+ # here would make every blocksim script that touches this module pay
44
+ # ~0.9 s for scipy.signal, which only the tf/zpk conversions need.
45
+ from .core import Block
46
+
47
+ __all__ = [
48
+ "Derivative",
49
+ "Integrator",
50
+ "IntegratorLimited",
51
+ "PIDController",
52
+ "SecondOrderIntegrator",
53
+ "SecondOrderIntegratorLimited",
54
+ "StateSpace",
55
+ "TransferFunction",
56
+ "TransportDelay",
57
+ "ZeroPole",
58
+ ]
59
+
60
+
61
+ class Derivative(Block):
62
+ """A filtered derivative: `G(s) = s / (tau s + 1)`.
63
+
64
+ A true differentiator is not realizable and would be a poor idea if
65
+ it were, because its gain grows without bound with frequency. This is
66
+ the usual compromise -- exact at low frequency, rolling off to a
67
+ gain of `1/tau` above `1/tau` rad/s.
68
+
69
+ That ceiling is the number to design with. `tau = 0.01` means
70
+ broadband noise on the input comes out multiplied by 100, so `tau` is
71
+ chosen from the noise you have, not from the bandwidth you want.
72
+
73
+ The single state is the filter, not the derivative: with
74
+ `dx/dt = -x/tau + u`, the output `(u - x/tau)/tau` reduces to
75
+ `u s /(tau s + 1)`. `initial_value` is the output wanted at `t = 0`,
76
+ and the state is set to `-tau^2 y0` to produce it, which assumes the
77
+ input starts at zero.
78
+
79
+ Inputs : u
80
+ Outputs : y, the filtered derivative of u
81
+ States : the filter state (NOT the derivative)
82
+
83
+ Has direct feedthrough: the output reads `u` at the current instant.
84
+ """
85
+
86
+ def __init__(self, tau=0.01, initial_value=0.0, name=None):
87
+ self.tau = tau
88
+ super().__init__(
89
+ num_inputs=1,
90
+ num_outputs=1,
91
+ num_states=1,
92
+ name=name,
93
+ inputs=[("u", None)],
94
+ outputs=[("y", None)],
95
+ states=[("x_filt", None)],
96
+ )
97
+ # x(0) = -tau^2 * y(0) + tau * u(0). Assuming u(0) = 0.0:
98
+ self.x0 = np.array([-tau * tau * initial_value], dtype=float)
99
+
100
+ def derivative(self, t, x, u):
101
+ return -1.0 / self.tau * x + u[0]
102
+
103
+ def output(self, t, x, u):
104
+ return (u[0] - x[0] / self.tau) / self.tau
105
+
106
+
107
+ class Integrator(Block):
108
+ """`y = integral(u) dt`, one channel per element of `initial_value`.
109
+
110
+ The block every diagram has. Passing a vector `initial_value` makes
111
+ it a bank of independent integrators, which is how a state vector is
112
+ carried without wiring `n` separate blocks.
113
+
114
+ Independent is meant literally, and the block says so: channel `i`
115
+ integrates input `i` and nothing else, declared through
116
+ `derivative_pattern()` and `output_pattern()`. Without those the
117
+ sparsity pass would see `x` in the signature and assume every channel
118
+ couples to every other, which turns a diagonal Jacobian into a dense
119
+ one and costs an implicit solver real time on a large model.
120
+
121
+ No direct feedthrough -- the output is the state -- so an integrator
122
+ is what breaks an algebraic loop in a feedback path.
123
+
124
+ Inputs : u0..un
125
+ Outputs : y0..yn
126
+ States : x0..xn
127
+ """
128
+
129
+ def __init__(self, initial_value=0.0, name=None):
130
+ self.initial_value = np.atleast_1d(initial_value).astype(float)
131
+ n = len(self.initial_value)
132
+ super().__init__(
133
+ num_inputs=n,
134
+ num_outputs=n,
135
+ num_states=n,
136
+ name=name,
137
+ inputs=[(f"u{i}", None) for i in range(n)],
138
+ outputs=[(f"y{i}", None) for i in range(n)],
139
+ states=[(f"x{i}", None) for i in range(n)],
140
+ )
141
+ self.x0 = np.copy(self.initial_value)
142
+
143
+ def derivative(self, t, x, u):
144
+ return u
145
+
146
+ def output(self, t, x):
147
+ return x
148
+
149
+ # channel i integrates input i and nothing else -- without this the
150
+ # sparsity pass would read `x` in the derivative signature and
151
+ # couple every channel to every other
152
+ def derivative_pattern(self):
153
+ n = self.num_states
154
+ return np.zeros((n, n), dtype=bool), np.eye(n, dtype=bool)
155
+
156
+ def output_pattern(self):
157
+ n = self.num_states
158
+ return np.eye(n, dtype=bool), np.zeros((n, n), dtype=bool)
159
+
160
+
161
+ class IntegratorLimited(Block):
162
+ """An integrator that stops at a bound instead of winding past it.
163
+
164
+ `y = clip(integral(u) dt, limit_min, limit_max)`, with the derivative
165
+ forced to zero when the state is at a limit and the input would push
166
+ it further out. That is the difference between clamping the output
167
+ and clamping the state: a plain `Saturation` on an integrator's
168
+ output leaves the state free to run away, so when the input reverses,
169
+ nothing happens for as long as it takes to unwind. This block comes
170
+ off the limit on the first sample of the opposite sign.
171
+
172
+ Limits may be scalars or per channel; a scalar is broadcast.
173
+
174
+ **The derivative is discontinuous at the bound.** An adaptive solver
175
+ will step across it, notice the error, and reject the step -- correct
176
+ but not free, and the crossing instant is only located to the
177
+ solver's tolerance. Nothing here declares an event. If the moment of
178
+ contact matters (a mechanical stop, a valve seating), put an event on
179
+ it or use `blocksim.discontinuities`.
180
+
181
+ Inputs : u0..un
182
+ Outputs : y0..yn, clipped
183
+ States : x0..xn, held inside the limits by the derivative
184
+ """
185
+
186
+ def __init__(self, initial_value=0.0, limit_min=-1.0, limit_max=1.0, name=None):
187
+ self.initial_value = np.atleast_1d(initial_value).astype(float)
188
+ self.limit_min = np.atleast_1d(limit_min).astype(float)
189
+ self.limit_max = np.atleast_1d(limit_max).astype(float)
190
+ n = len(self.initial_value)
191
+
192
+ if len(self.limit_min) == 1 and n > 1:
193
+ self.limit_min = np.repeat(self.limit_min, n)
194
+ if len(self.limit_max) == 1 and n > 1:
195
+ self.limit_max = np.repeat(self.limit_max, n)
196
+
197
+ super().__init__(
198
+ num_inputs=n,
199
+ num_outputs=n,
200
+ num_states=n,
201
+ name=name,
202
+ inputs=[(f"u{i}", None) for i in range(n)],
203
+ outputs=[(f"y{i}", None) for i in range(n)],
204
+ states=[(f"x{i}", None) for i in range(n)],
205
+ )
206
+ self.x0 = np.clip(self.initial_value, self.limit_min, self.limit_max)
207
+
208
+ def derivative(self, t, x, u):
209
+ dx = np.copy(u)
210
+ for i in range(len(x)):
211
+ if x[i] <= self.limit_min[i] and u[i] < 0:
212
+ dx[i] = 0.0
213
+ elif x[i] >= self.limit_max[i] and u[i] > 0:
214
+ dx[i] = 0.0
215
+ return dx
216
+
217
+ def output(self, t, x):
218
+ return np.clip(x, self.limit_min, self.limit_max)
219
+
220
+
221
+ class PIDController(Block):
222
+ """`G(s) = Kp + Ki/s + Kd s / (tau s + 1)`.
223
+
224
+ Textbook parallel form, with the derivative term filtered by the same
225
+ first-order roll-off `Derivative` uses -- see there for how to pick
226
+ `tau`, which is set by measurement noise rather than by taste.
227
+
228
+ Two states: the integral of the error, and the derivative filter.
229
+
230
+ **There is no anti-windup and no output limit here.** If the plant
231
+ saturates, this block's integrator keeps integrating and the loop
232
+ will overshoot on the way back. That is deliberate -- clamping needs
233
+ to know the actuator's limits, which this block cannot see -- but it
234
+ means a PID in front of a real actuator wants either
235
+ `IntegratorLimited` wired by hand or a saturation model in the loop.
236
+ `examples/control` shows both.
237
+
238
+ Inputs : error
239
+ Outputs : control
240
+ States : x_int (integral of the error), x_der (derivative filter)
241
+
242
+ Has direct feedthrough through the proportional and derivative paths.
243
+ """
244
+
245
+ def __init__(
246
+ self, Kp=1.0, Ki=0.0, Kd=0.0, tau=0.01, initial_value_int=0.0, name=None
247
+ ):
248
+ self.Kp = Kp
249
+ self.Ki = Ki
250
+ self.Kd = Kd
251
+ self.tau = tau
252
+ super().__init__(
253
+ num_inputs=1,
254
+ num_outputs=1,
255
+ num_states=2,
256
+ name=name,
257
+ inputs=[("error", None)],
258
+ outputs=[("control", None)],
259
+ states=[("x_int", None), ("x_der", None)],
260
+ )
261
+ self.x0 = np.array([float(initial_value_int), 0.0])
262
+
263
+ def derivative(self, t, x, u):
264
+ dx = np.zeros(2)
265
+ dx[0] = u[0] # Integral of error
266
+ dx[1] = -1.0 / self.tau * x[1] + u[0] # Derivative filter state
267
+ return dx
268
+
269
+ def output(self, t, x, u):
270
+ y_der = self.Kd * (u[0] - x[1] / self.tau) / self.tau
271
+ return np.array([self.Kp * u[0] + self.Ki * x[0] + y_der], dtype=float)
272
+
273
+
274
+ class SecondOrderIntegrator(Block):
275
+ """Acceleration in, position and velocity out.
276
+
277
+ `d(pos)/dt = vel`, `d(vel)/dt = u` -- a double integrator, which is
278
+ Newton's second law once the mass has been divided out, and the
279
+ reason it turns up in nearly every mechanical model.
280
+
281
+ Inputs : accel
282
+ Outputs : pos, vel
283
+ States : pos, vel
284
+
285
+ No direct feedthrough.
286
+ """
287
+
288
+ def __init__(self, initial_position=0.0, initial_velocity=0.0, name=None):
289
+ self.initial_position = float(initial_position)
290
+ self.initial_velocity = float(initial_velocity)
291
+ super().__init__(
292
+ num_inputs=1,
293
+ num_outputs=2,
294
+ num_states=2,
295
+ name=name,
296
+ inputs=[("accel", None)],
297
+ outputs=[("pos", None), ("vel", None)],
298
+ states=[("pos", None), ("vel", None)],
299
+ )
300
+ self.x0 = np.array([self.initial_position, self.initial_velocity])
301
+
302
+ def derivative(self, t, x, u):
303
+ return np.array([x[1], u[0]])
304
+
305
+ def output(self, t, x):
306
+ return x
307
+
308
+
309
+ class SecondOrderIntegratorLimited(Block):
310
+ """A double integrator against a hard stop.
311
+
312
+ Position is clamped to `[limit_min, limit_max]`, and on contact the
313
+ velocity is taken to zero rather than reversed: this is a stop that
314
+ absorbs, not one that bounces. Acceleration that would push further
315
+ into the stop is dropped; acceleration that pulls away is passed
316
+ through immediately, so the mass leaves the stop on the first sample
317
+ of the opposite sign.
318
+
319
+ **This is an inelastic stop with no restitution and no contact
320
+ force.** For an impact that rebounds, or where the contact force
321
+ matters, model the stop as a stiff spring and damper, or use an event
322
+ -- `examples/discontinuous/ex01_bouncing_ball.py` does the latter.
323
+
324
+ As with `IntegratorLimited`, the switching is a discontinuity in the
325
+ derivative that no event locates, so the instant of contact is only
326
+ as accurate as the solver's step.
327
+
328
+ Inputs : accel
329
+ Outputs : pos (clipped), vel (zeroed while pressed into a stop)
330
+ States : pos, vel
331
+ """
332
+
333
+ def __init__(
334
+ self,
335
+ initial_position=0.0,
336
+ initial_velocity=0.0,
337
+ limit_min=-1.0,
338
+ limit_max=1.0,
339
+ name=None,
340
+ ):
341
+ self.initial_position = float(initial_position)
342
+ self.initial_velocity = float(initial_velocity)
343
+ self.limit_min = float(limit_min)
344
+ self.limit_max = float(limit_max)
345
+ super().__init__(
346
+ num_inputs=1,
347
+ num_outputs=2,
348
+ num_states=2,
349
+ name=name,
350
+ inputs=[("accel", None)],
351
+ outputs=[("pos", None), ("vel", None)],
352
+ states=[("pos", None), ("vel", None)],
353
+ )
354
+ self.x0 = np.array(
355
+ [
356
+ np.clip(self.initial_position, self.limit_min, self.limit_max),
357
+ self.initial_velocity,
358
+ ]
359
+ )
360
+
361
+ def derivative(self, t, x, u):
362
+ dx = np.zeros(2)
363
+ dx[0] = x[1]
364
+ dx[1] = u[0]
365
+
366
+ if x[0] >= self.limit_max:
367
+ if x[1] > 0:
368
+ dx[0] = 0.0
369
+ dx[1] = min(0.0, u[0])
370
+ elif x[1] == 0 and u[0] > 0:
371
+ dx[1] = 0.0
372
+ elif x[0] <= self.limit_min:
373
+ if x[1] < 0:
374
+ dx[0] = 0.0
375
+ dx[1] = max(0.0, u[0])
376
+ elif x[1] == 0 and u[0] < 0:
377
+ dx[1] = 0.0
378
+ return dx
379
+
380
+ def output(self, t, x):
381
+ pos = np.clip(x[0], self.limit_min, self.limit_max)
382
+ vel = (
383
+ 0.0
384
+ if (x[0] >= self.limit_max and x[1] > 0)
385
+ or (x[0] <= self.limit_min and x[1] < 0)
386
+ else x[1]
387
+ )
388
+ return np.array([pos, vel])
389
+
390
+
391
+ class StateSpace(Block):
392
+ """A linear system as its four matrices.
393
+
394
+ dx/dt = A x + B u
395
+ y = C x + D u
396
+
397
+ Sizes come from the matrices: `A` fixes the state count, `B` the
398
+ inputs, `C` the outputs. `D` defaults to zero, which makes the system
399
+ strictly proper.
400
+
401
+ Two things this block tells the compiler that it would otherwise have
402
+ to guess:
403
+
404
+ * **feedthrough is read from `D`**, not assumed. `D = 0` means the
405
+ output cannot depend on the input in the same instant, so the block
406
+ breaks algebraic loops -- which is what lets a strictly proper
407
+ plant sit in a feedback loop with no algebraic solve.
408
+ * **the sparsity patterns are the matrices themselves.** A companion
409
+ realization from `TransferFunction` has an almost empty `A`, and
410
+ `jacobian_sparsity()` uses that rather than assuming a dense
411
+ coupling.
412
+
413
+ Inputs : u0..un Outputs : y0..ym States : x0..xk
414
+ """
415
+
416
+ def __init__(self, A, B, C, D=None, x0=None, name=None):
417
+ self.A = np.atleast_2d(A).astype(float)
418
+ self.B = np.atleast_2d(B).astype(float)
419
+ self.C = np.atleast_2d(C).astype(float)
420
+
421
+ n_states = self.A.shape[0]
422
+ n_inputs = self.B.shape[1]
423
+ n_outputs = self.C.shape[0]
424
+
425
+ if D is None:
426
+ self.D = np.zeros((n_outputs, n_inputs), dtype=float)
427
+ else:
428
+ self.D = np.atleast_2d(D).astype(float)
429
+
430
+ super().__init__(
431
+ num_inputs=n_inputs,
432
+ num_outputs=n_outputs,
433
+ num_states=n_states,
434
+ name=name,
435
+ inputs=[(f"u{i}", None) for i in range(n_inputs)],
436
+ outputs=[(f"y{i}", None) for i in range(n_outputs)],
437
+ states=[(f"x{i}", None) for i in range(n_states)],
438
+ )
439
+ self.x0 = np.zeros(n_states) if x0 is None else np.asarray(x0, dtype=float)
440
+
441
+ def derivative(self, t, x, u):
442
+ return self.A @ x + self.B @ u
443
+
444
+ def output(self, t, x, u):
445
+ return self.C @ x + self.D @ u
446
+
447
+ # the four matrices are the structure -- a companion-form
448
+ # TransferFunction, say, has a nearly empty A
449
+ def derivative_pattern(self):
450
+ return self.A != 0, self.B != 0
451
+
452
+ def output_pattern(self):
453
+ return self.C != 0, self.D != 0
454
+
455
+ @property
456
+ def has_direct_feedthrough(self) -> bool:
457
+ return np.any(self.D != 0)
458
+
459
+
460
+ class TransferFunction(StateSpace):
461
+ """`G(s) = num(s) / den(s)`, realized as a state space.
462
+
463
+ `num` and `den` are coefficient sequences in DESCENDING powers of
464
+ `s`, the numpy convention: `[1, 3]` is `s + 3`. The conversion is
465
+ `scipy.signal.tf2ss`, which produces the controllable companion form
466
+ -- so the states are not physically meaningful, they are whatever
467
+ that realization makes them, and `x0` should usually be left at zero
468
+ unless you know which realization you are initialising.
469
+
470
+ A transfer function with `len(num) == len(den)` is proper but not
471
+ strictly proper and gets a non-zero `D`, which means it has direct
472
+ feedthrough and can close an algebraic loop. Add a pole to avoid it.
473
+
474
+ Everything else -- ports, patterns, feedthrough -- is `StateSpace`.
475
+ """
476
+
477
+ def __init__(self, num, den, x0=None, name=None):
478
+ from scipy.signal import tf2ss
479
+
480
+ A, B, C, D = tf2ss(num, den)
481
+ super().__init__(A, B, C, D, x0=x0, name=name)
482
+
483
+
484
+ class ZeroPole(StateSpace):
485
+ """`G(s) = K prod(s - z) / prod(s - p)`, realized as a state space.
486
+
487
+ The same object as `TransferFunction` entered a different way, which
488
+ is the more natural one when the design was done by placing poles.
489
+ Conversion is `scipy.signal.zpk2ss`; complex zeros and poles must
490
+ appear in conjugate pairs for the realization to come out real.
491
+
492
+ As with `TransferFunction`, the states belong to the realization
493
+ rather than to anything physical.
494
+ """
495
+
496
+ def __init__(self, zeros, poles, gain, x0=None, name=None):
497
+ from scipy.signal import zpk2ss
498
+
499
+ A, B, C, D = zpk2ss(zeros, poles, gain)
500
+ super().__init__(A, B, C, D, x0=x0, name=name)
501
+
502
+
503
+ class TransportDelay(Block):
504
+ """A pure time delay: `y(t) = u(t - delay_time)`.
505
+
506
+ A dead time, as produced by a pipe, a conveyor, a transmission link
507
+ or a measurement pipeline. Unlike a Pade approximation this is the
508
+ real thing -- no phase error, no non-minimum-phase zero -- and it is
509
+ what makes a loop with transport lag hard to stabilise honestly.
510
+
511
+ **It works by keeping a history and interpolating.** `output()`
512
+ appends `(t, u)` on every call, looks back `delay_time`, and
513
+ interpolates linearly between the two samples that straddle it. Three
514
+ consequences follow, and all three matter:
515
+
516
+ * the solver calls `output()` at trial points it may later reject, so
517
+ the history is pruned backwards whenever time moves back. That
518
+ keeps it consistent, but it means the stored history is the
519
+ solver's step pattern and not a uniform grid.
520
+ * **accuracy is the solver's step size**, not a parameter of this
521
+ block. Linear interpolation over steps that the solver chose for a
522
+ different reason can smear a sharp edge; if the delayed signal has
523
+ one, cap `dt_max`.
524
+ * before `t = delay_time` there is nothing to look back at, and the
525
+ block outputs `initial_value`.
526
+
527
+ With a positive delay the output cannot depend on the present input,
528
+ so the block has no direct feedthrough and breaks algebraic loops. A
529
+ delay of zero or less is a pass-through, and does have feedthrough.
530
+
531
+ Inputs : u0..un Outputs : y0..yn States : none
532
+ """
533
+
534
+ def __init__(self, delay_time=1.0, initial_value=0.0, name=None):
535
+ self.delay_time = delay_time
536
+ self.initial_value = np.atleast_1d(initial_value).astype(float)
537
+
538
+ super().__init__(
539
+ num_inputs=len(self.initial_value),
540
+ num_outputs=len(self.initial_value),
541
+ name=name,
542
+ inputs=[(f"u{i}", None) for i in range(len(self.initial_value))],
543
+ outputs=[(f"y{i}", None) for i in range(len(self.initial_value))],
544
+ )
545
+ self.history_t = []
546
+ self.history_u = []
547
+
548
+ def initialize(self):
549
+ super().initialize()
550
+ self.history_t = []
551
+ self.history_u = []
552
+
553
+ def output(self, t, u):
554
+ # 1. Backtracking cleanup
555
+ while self.history_t and self.history_t[-1] > t:
556
+ self.history_t.pop()
557
+ self.history_u.pop()
558
+
559
+ # 2. Append current point
560
+ self.history_t.append(t)
561
+ self.history_u.append(np.copy(u))
562
+
563
+ # 3. Find delayed value
564
+ t_target = t - self.delay_time
565
+ if t_target <= self.history_t[0]:
566
+ return np.copy(self.initial_value)
567
+
568
+ idx = np.searchsorted(self.history_t, t_target)
569
+ t0 = self.history_t[idx - 1]
570
+ t1 = self.history_t[idx]
571
+ u0 = self.history_u[idx - 1]
572
+ u1 = self.history_u[idx]
573
+
574
+ fraction = (t_target - t0) / (t1 - t0) if t1 != t0 else 0.0
575
+ y = u0 + fraction * (u1 - u0)
576
+
577
+ # 4. Prune old history
578
+ while len(self.history_t) > 2 and self.history_t[1] < t_target:
579
+ self.history_t.pop(0)
580
+ self.history_u.pop(0)
581
+
582
+ return y
583
+
584
+ @property
585
+ def has_direct_feedthrough(self) -> bool:
586
+ return self.delay_time <= 0