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/analysis.py ADDED
@@ -0,0 +1,1143 @@
1
+ """
2
+ System analysis: steady-state trimming, linearization and parameter
3
+ sensitivities.
4
+
5
+ * trim() -- find (x, u) with dx/dt = 0 and optional output targets
6
+ (exact least-squares solve, verified residuals)
7
+ * steady_state() -- trim() without free inputs: the equilibrium of the
8
+ system exactly as wired
9
+ * linearize() -- central-difference (A, B, C, D) around an operating
10
+ point, with per-variable scaled steps
11
+ * sensitivity() -- parameter sensitivities d y(t) / d p of a whole
12
+ simulation by central differences over factory-built
13
+ systems (returns a SensitivityResult)
14
+
15
+ Everything downstream of a linearization lives here too, and all of it
16
+ takes the (A, B, C, D) tuple `linearize()` returns, unchanged:
17
+
18
+ * poles/zeros/damp/dcgain -- where the modes are and what they are
19
+ * frequency_response/bode -- G(jw), magnitude and phase
20
+ * margins -- gain and phase margins, refined by
21
+ root-finding rather than read off a grid
22
+ * step_response/step_info -- exact linear step response; the shape
23
+ metrics work on any (t, y), linear or not
24
+ * is_controllable/is_observable, gramians, hankel_singular_values
25
+ * balanced_reduction -- truncate to the states the input/output
26
+ map actually depends on
27
+ * lqr/lqe -- state feedback and the dual estimator
28
+ * series/parallel/append/feedback -- build one model out of several,
29
+ with `static_gain` and `loop_gain`
30
+ for the two everyone needs anyway
31
+
32
+ Free inputs for trim/linearize are injected through
33
+ System._output_override: the named block output ports are forced to the
34
+ candidate values during evaluation, overriding whatever the block would
35
+ compute -- so any source block (typically a Constant) can serve as a
36
+ trimmable input without rewiring.
37
+ """
38
+
39
+ import numpy as np
40
+ from typing import List, Tuple
41
+ from .core import System, Block, Simulator
42
+ from ._logging import get_logger
43
+
44
+ __all__ = [
45
+ "LinearModel",
46
+ "Margins",
47
+ "SensitivityResult",
48
+ "StepInfo",
49
+ "append",
50
+ "balanced_reduction",
51
+ "bode",
52
+ "controllability_matrix",
53
+ "damp",
54
+ "dcgain",
55
+ "feedback",
56
+ "frequency_response",
57
+ "gramians",
58
+ "hankel_singular_values",
59
+ "is_controllable",
60
+ "is_observable",
61
+ "linearize",
62
+ "loop_gain",
63
+ "lqe",
64
+ "lqr",
65
+ "margins",
66
+ "negate",
67
+ "observability_matrix",
68
+ "parallel",
69
+ "poles",
70
+ "sensitivity",
71
+ "series",
72
+ "static_gain",
73
+ "steady_state",
74
+ "step_info",
75
+ "step_response",
76
+ "trim",
77
+ "zeros",
78
+ ]
79
+
80
+ log = get_logger("analysis")
81
+
82
+
83
+ def _with_override(system, inputs, u_val, fn):
84
+ """Run fn() with the free-input ports forced to u_val."""
85
+ if inputs:
86
+ system._output_override = {}
87
+ for (blk, idx), val in zip(inputs, u_val):
88
+ system._output_override.setdefault(blk, {})[idx] = val
89
+ try:
90
+ return fn()
91
+ finally:
92
+ system._output_override = None
93
+
94
+
95
+ def trim(
96
+ system: System,
97
+ x_guess: np.ndarray,
98
+ inputs: List[Tuple[Block, int]] = None,
99
+ u_guess: np.ndarray = None,
100
+ y_targets: List[Tuple[Block, int, float]] = None,
101
+ t: float = 0.0,
102
+ tol: float = 1e-6,
103
+ target_weight: float = 1.0,
104
+ ) -> Tuple[np.ndarray, np.ndarray]:
105
+ """Find a steady-state operating point (x_trim, u_trim): dx/dt = 0 with
106
+ the listed output targets met.
107
+
108
+ inputs
109
+ [(block, output_port), ...] free inputs -- these ports
110
+ are FORCED to the candidate values during the solve
111
+ (any source block works; no rewiring needed)
112
+
113
+ u_guess
114
+ initial guess for the free inputs (zeros by default)
115
+
116
+ y_targets
117
+ [(block, output_port, target_value), ...]
118
+
119
+ tol
120
+ max ``|residual|`` accepted; RuntimeError above it
121
+
122
+ target_weight
123
+ relative weight of target residuals vs. dx residuals
124
+ (only matters when no exact trim exists)
125
+
126
+ Solved as a least-squares problem on the stacked residual
127
+ [dx; w*(y - target)] -- when a consistent trim exists both groups are
128
+ driven to zero exactly (machine precision), unlike a penalty method.
129
+ """
130
+ if not system.block_order:
131
+ system.compile()
132
+
133
+ n_x = system.total_num_states
134
+ n_u = len(inputs) if inputs else 0
135
+ if u_guess is None:
136
+ u_guess = np.zeros(n_u)
137
+ x_guess = np.asarray(x_guess, dtype=float)
138
+ u_guess = np.asarray(u_guess, dtype=float)
139
+ if x_guess.size != n_x:
140
+ raise ValueError(
141
+ f"x_guess has {x_guess.size} entries; the system has {n_x} states"
142
+ )
143
+ w = np.sqrt(target_weight)
144
+
145
+ def residual(z):
146
+ x_val, u_val = z[:n_x], z[n_x:]
147
+
148
+ def evaluate():
149
+ r = [system.derivative(t, x_val)]
150
+ if y_targets:
151
+ out = system.output(t, x_val)
152
+ for blk, idx, target in y_targets:
153
+ gi = system.blocks_spec[blk].output_index[idx]
154
+ r.append(np.atleast_1d(w * (out[gi] - target)))
155
+ return np.concatenate(r) if r else np.zeros(0)
156
+
157
+ return _with_override(system, inputs, u_val, evaluate)
158
+
159
+ z0 = np.concatenate([x_guess, u_guess])
160
+ log.debug(
161
+ "trim: %d states, %d free inputs, %d target(s)",
162
+ n_x,
163
+ n_u,
164
+ len(y_targets) if y_targets else 0,
165
+ )
166
+ from scipy.optimize import least_squares
167
+
168
+ res = least_squares(residual, z0, method="trf", xtol=1e-14, ftol=1e-14, gtol=1e-14)
169
+
170
+ r_final = np.abs(residual(res.x))
171
+ if r_final.size and np.max(r_final) > tol:
172
+ raise RuntimeError(
173
+ f"trim did not converge: max |residual| = {np.max(r_final):.3g} "
174
+ f"(> tol={tol:g}). The targets may be unreachable with the "
175
+ f"given free inputs, or the guess is in the wrong basin."
176
+ )
177
+
178
+ log.debug(
179
+ "trim converged in %d evals: max|residual|=%.2e",
180
+ res.nfev,
181
+ np.max(r_final) if r_final.size else 0.0,
182
+ )
183
+ return res.x[:n_x], res.x[n_x:]
184
+
185
+
186
+ def steady_state(
187
+ system: System,
188
+ x_guess: np.ndarray,
189
+ t: float = 0.0,
190
+ tol: float = 1e-6,
191
+ ) -> np.ndarray:
192
+ """Equilibrium of the system exactly as wired (no free inputs, no
193
+ targets): the x with dx/dt = 0 nearest the guess's basin."""
194
+ x_trim, _ = trim(system, x_guess, t=t, tol=tol)
195
+ return x_trim
196
+
197
+
198
+ def linearize(
199
+ system: System,
200
+ x0: np.ndarray,
201
+ inputs: List[Tuple[Block, int]] = None,
202
+ u0: np.ndarray = None,
203
+ outputs: List[Tuple[Block, int]] = None,
204
+ t: float = 0.0,
205
+ eps: float = 1e-6,
206
+ ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
207
+ """Linearize around (x0, u0) by central differences::
208
+
209
+ dx/dt ~ A (x - x0) + B (u - u0)
210
+ y ~ C (x - x0) + D (u - u0) + y0
211
+
212
+ inputs/outputs select which ports form B, D and C, D. The finite-
213
+ difference step is scaled per variable: eps * max(1, ``|value|``).
214
+ Returns (A, B, C, D) as plain arrays -- feed them to
215
+ continuous.StateSpace or python-control's ss() for design work.
216
+ """
217
+ if not system.block_order:
218
+ system.compile()
219
+
220
+ x0 = np.asarray(x0, dtype=float)
221
+ n_x = x0.size
222
+ n_u = len(inputs) if inputs else 0
223
+ n_y = len(outputs) if outputs else 0
224
+ if u0 is None:
225
+ u0 = np.zeros(n_u)
226
+ u0 = np.asarray(u0, dtype=float)
227
+
228
+ A = np.zeros((n_x, n_x))
229
+ B = np.zeros((n_x, n_u))
230
+ C = np.zeros((n_y, n_x))
231
+ D = np.zeros((n_y, n_u))
232
+
233
+ def eval_sys(x_val, u_val):
234
+ def evaluate():
235
+ dx = system.derivative(t, x_val)
236
+ y_val = np.zeros(n_y)
237
+ if outputs:
238
+ out = system.output(t, x_val)
239
+ for k, (blk, idx) in enumerate(outputs):
240
+ y_val[k] = out[system.blocks_spec[blk].output_index[idx]]
241
+ return dx, y_val
242
+
243
+ return _with_override(system, inputs, u_val, evaluate)
244
+
245
+ for i in range(n_x):
246
+ h = eps * max(1.0, abs(x0[i]))
247
+ xp = x0.copy()
248
+ xp[i] += h
249
+ xm = x0.copy()
250
+ xm[i] -= h
251
+ dx_p, y_p = eval_sys(xp, u0)
252
+ dx_m, y_m = eval_sys(xm, u0)
253
+ A[:, i] = (dx_p - dx_m) / (2.0 * h)
254
+ C[:, i] = (y_p - y_m) / (2.0 * h)
255
+
256
+ for j in range(n_u):
257
+ h = eps * max(1.0, abs(u0[j]))
258
+ up = u0.copy()
259
+ up[j] += h
260
+ um = u0.copy()
261
+ um[j] -= h
262
+ dx_p, y_p = eval_sys(x0, up)
263
+ dx_m, y_m = eval_sys(x0, um)
264
+ B[:, j] = (dx_p - dx_m) / (2.0 * h)
265
+ D[:, j] = (y_p - y_m) / (2.0 * h)
266
+
267
+ return A, B, C, D
268
+
269
+
270
+ # ==============================================================================
271
+ # Parameter sensitivities of a whole simulation
272
+ # ==============================================================================
273
+ class SensitivityResult:
274
+ """
275
+ Result of sensitivity(): trajectories and their parameter gradients.
276
+
277
+ res.t nominal time base
278
+ res.labels channel names ("<block>.<port>")
279
+ res.y nominal trajectories, shape (n_channels, len(t))
280
+ res.dy {param_name: dy/dp matrix, same shape as y}
281
+ res.channel(p, label) one channel's sensitivity as a 1-D array
282
+ """
283
+
284
+ def __init__(self, t, labels, y, dy, params):
285
+ self.t = t
286
+ self.labels = list(labels)
287
+ self.y = y
288
+ self.dy = dy
289
+ self.params = dict(params)
290
+
291
+ def __repr__(self):
292
+ return (
293
+ f"SensitivityResult({len(self.t)} samples, "
294
+ f"{len(self.labels)} channels, "
295
+ f"params {sorted(self.dy)})"
296
+ )
297
+
298
+ def channel(self, param, label):
299
+ return self.dy[param][self.labels.index(label), :]
300
+
301
+
302
+ def sensitivity(
303
+ factory,
304
+ params: dict,
305
+ t_final: float,
306
+ t_start: float = 0.0,
307
+ dt_max: float = np.inf,
308
+ record=None,
309
+ rel_step: float = 1e-4,
310
+ simulator_cls=None,
311
+ **run_kwargs,
312
+ ):
313
+ """Central-difference sensitivities d y(t) / d p of a whole simulation.
314
+
315
+ factory
316
+ ``callable(**params)`` -> System. Called once per evaluation
317
+ with the (nominal or perturbed) parameter values; building
318
+ a FRESH system per run makes any constructor parameter --
319
+ gains, time constants, initial values, table data --
320
+ differentiable without a reset protocol.
321
+
322
+ params
323
+ {name: nominal_value} parameters to differentiate against.
324
+
325
+ record
326
+ forwarded to run(); use block-NAME strings (the factory
327
+ builds new block objects each call, so names are the stable
328
+ identifiers).
329
+
330
+ rel_step
331
+ relative perturbation; the step is rel_step*max(``|p|``, 1).
332
+
333
+ simulator_cls
334
+ Simulator by default (SimulatorClaude also works).
335
+
336
+ Perturbed runs are interpolated onto the nominal run's time base, so
337
+ adaptive-step grids pose no problem. Returns a SensitivityResult.
338
+ """
339
+ sim_cls = simulator_cls or Simulator
340
+
341
+ def run_once(values):
342
+ system = factory(**values)
343
+ res = sim_cls(system).run(
344
+ t_start, t_final, dt_max=dt_max, record=record, **run_kwargs
345
+ )
346
+ return res
347
+
348
+ res0 = run_once(dict(params))
349
+ t_ref = res0.t
350
+ labels = res0.labels
351
+
352
+ def on_ref_grid(res):
353
+ if res.labels != labels:
354
+ raise ValueError(
355
+ "factory produced different channels between runs "
356
+ f"({res.labels} vs {labels}); block names must be stable"
357
+ )
358
+ return np.vstack(
359
+ [np.interp(t_ref, res.t, res.y[i]) for i in range(res.y.shape[0])]
360
+ )
361
+
362
+ log.debug(
363
+ "sensitivity: %d parameter(s) x 2 runs each (%s)",
364
+ len(params),
365
+ ", ".join(params),
366
+ )
367
+ dy = {}
368
+ for name, p0 in params.items():
369
+ h = rel_step * max(abs(float(p0)), 1.0)
370
+ vp = dict(params)
371
+ vp[name] = p0 + h
372
+ vm = dict(params)
373
+ vm[name] = p0 - h
374
+ y_p = on_ref_grid(run_once(vp))
375
+ y_m = on_ref_grid(run_once(vm))
376
+ dy[name] = (y_p - y_m) / (2.0 * h)
377
+ log.debug("sensitivity: d/d%s done (step %.2e)", name, h)
378
+
379
+ return SensitivityResult(t_ref, labels, res0.y, dy, params)
380
+
381
+
382
+ # ==============================================================================
383
+ # Linear analysis: everything downstream of linearize()
384
+ # ==============================================================================
385
+ # `linearize()` hands back (A, B, C, D) and, until now, nothing consumed it.
386
+ # These take that tuple straight back -- `bode(linearize(sys, x0, ...))` --
387
+ # so there is no model object to build and nothing to keep in sync.
388
+
389
+
390
+ class LinearModel:
391
+ """(A, B, C, D) with its dimensions named.
392
+
393
+ Every function below accepts either one of these or the plain tuple
394
+ `linearize()` returns, so it is a convenience, never a requirement.
395
+ """
396
+
397
+ __slots__ = ("A", "B", "C", "D")
398
+
399
+ def __init__(self, A, B, C, D=None):
400
+ self.A = np.atleast_2d(np.asarray(A, dtype=float))
401
+ self.B = np.atleast_2d(np.asarray(B, dtype=float))
402
+ self.C = np.atleast_2d(np.asarray(C, dtype=float))
403
+ n_y, n_u = self.C.shape[0], self.B.shape[1]
404
+ self.D = (
405
+ np.zeros((n_y, n_u))
406
+ if D is None
407
+ else np.atleast_2d(np.asarray(D, dtype=float))
408
+ )
409
+ if self.A.shape[0] != self.A.shape[1]:
410
+ raise ValueError(f"A must be square, got {self.A.shape}")
411
+ for name, mat, want in (
412
+ ("B", self.B, (self.n_states, self.B.shape[1])),
413
+ ("C", self.C, (self.C.shape[0], self.n_states)),
414
+ ("D", self.D, (n_y, n_u)),
415
+ ):
416
+ if mat.shape != want:
417
+ raise ValueError(f"{name} is {mat.shape}, expected {want}")
418
+
419
+ @property
420
+ def n_states(self):
421
+ return self.A.shape[0]
422
+
423
+ @property
424
+ def n_inputs(self):
425
+ return self.B.shape[1]
426
+
427
+ @property
428
+ def n_outputs(self):
429
+ return self.C.shape[0]
430
+
431
+ def __iter__(self):
432
+ """So a LinearModel unpacks like the tuple it replaces."""
433
+ return iter((self.A, self.B, self.C, self.D))
434
+
435
+ def __repr__(self):
436
+ return (
437
+ f"LinearModel({self.n_states} states, "
438
+ f"{self.n_inputs} inputs, {self.n_outputs} outputs)"
439
+ )
440
+
441
+
442
+ def _model(model):
443
+ """Accept a LinearModel, an (A, B, C, D) tuple, or (A, B, C)."""
444
+ if isinstance(model, LinearModel):
445
+ return model
446
+ return LinearModel(*model)
447
+
448
+
449
+ def _siso(model, input=0, output=0):
450
+ """One input/output channel of a possibly multivariable model."""
451
+ m = _model(model)
452
+ return LinearModel(
453
+ m.A,
454
+ m.B[:, [input]],
455
+ m.C[[output], :],
456
+ m.D[[output], :][:, [input]],
457
+ )
458
+
459
+
460
+ # ---- modes -------------------------------------------------------------
461
+ def poles(model):
462
+ """Eigenvalues of A: the model's modes."""
463
+ return np.linalg.eigvals(_model(model).A)
464
+
465
+
466
+ def zeros(model, input=0, output=0):
467
+ """Transmission zeros of one input/output channel.
468
+
469
+ From the generalized eigenvalue problem of Rosenbrock's system
470
+ pencil -- the finite eigenvalues of `[[A, B], [C, D]] - s [[I, 0],
471
+ [0, 0]]` -- which stays right when D is zero and when the channel
472
+ has fewer zeros than states, where forming a transfer function and
473
+ rooting its numerator does not.
474
+ """
475
+ from scipy.linalg import eig
476
+
477
+ m = _siso(model, input, output)
478
+ n = m.n_states
479
+ pencil = np.block([[m.A, m.B], [m.C, m.D]])
480
+ mass = np.zeros_like(pencil)
481
+ mass[:n, :n] = np.eye(n)
482
+
483
+ alpha, beta = eig(pencil, mass, left=False, right=False, homogeneous_eigvals=True)
484
+ finite = np.abs(beta) > 1e-12 * max(1.0, float(np.max(np.abs(alpha))))
485
+ return alpha[finite] / beta[finite]
486
+
487
+
488
+ def damp(model):
489
+ """Per-mode (pole, natural frequency, damping ratio, time constant).
490
+
491
+ Natural frequency is ``|lambda|`` and damping ratio is -Re/``|lambda|``, so a
492
+ real pole reads as zeta = 1 and an undamped pair as zeta = 0. Time
493
+ constant is 1/``|Re|`` (inf on the imaginary axis).
494
+ """
495
+ lam = poles(model)
496
+ wn = np.abs(lam)
497
+ with np.errstate(divide="ignore", invalid="ignore"):
498
+ zeta = np.where(wn > 0, -lam.real / np.where(wn > 0, wn, 1.0), 1.0)
499
+ tau = np.where(np.abs(lam.real) > 0, 1.0 / np.abs(lam.real), np.inf)
500
+ return lam, wn, zeta.real, tau
501
+
502
+
503
+ def dcgain(model):
504
+ """y/u at steady state: D - C A^-1 B. inf where A is singular."""
505
+ m = _model(model)
506
+ try:
507
+ return m.D - m.C @ np.linalg.solve(m.A, m.B)
508
+ except np.linalg.LinAlgError:
509
+ return np.full((m.n_outputs, m.n_inputs), np.inf)
510
+
511
+
512
+ # ---- frequency response ------------------------------------------------
513
+ def frequency_response(model, w, input=None, output=None):
514
+ """G(jw) = C (jwI - A)^-1 B + D, evaluated at every w.
515
+
516
+ Returns shape (n_outputs, n_inputs, len(w)), or (len(w),) when both
517
+ `input` and `output` pick a single channel. Solved rather than
518
+ inverted, one factorization per frequency.
519
+ """
520
+ m = _model(model)
521
+ if input is not None or output is not None:
522
+ m = _siso(m, input or 0, output or 0)
523
+
524
+ w = np.atleast_1d(np.asarray(w, dtype=float))
525
+ eye = np.eye(m.n_states)
526
+ G = np.empty((m.n_outputs, m.n_inputs, w.size), dtype=complex)
527
+ for k, wk in enumerate(w):
528
+ G[:, :, k] = m.C @ np.linalg.solve(1j * wk * eye - m.A, m.B) + m.D
529
+
530
+ if input is not None and output is not None:
531
+ return G[0, 0, :]
532
+ return G
533
+
534
+
535
+ def _auto_frequencies(model, decades=2, points=500):
536
+ """A frequency grid that brackets the model's own dynamics."""
537
+ interesting = np.abs(np.concatenate([poles(model), [1.0]]))
538
+ interesting = interesting[interesting > 1e-12]
539
+ lo = np.log10(interesting.min()) - decades
540
+ hi = np.log10(interesting.max()) + decades
541
+ return np.logspace(lo, hi, points)
542
+
543
+
544
+ def bode(model, w=None, input=0, output=0, unwrap=True):
545
+ """(w, magnitude in dB, phase in degrees) for one channel.
546
+
547
+ `w=None` picks a grid two decades either side of the model's own
548
+ pole frequencies, which is almost always the plot you wanted.
549
+ """
550
+ if w is None:
551
+ w = _auto_frequencies(model)
552
+ w = np.atleast_1d(np.asarray(w, dtype=float))
553
+ G = frequency_response(model, w, input=input, output=output)
554
+
555
+ mag_db = 20.0 * np.log10(np.abs(G))
556
+ phase = np.angle(G)
557
+ if unwrap:
558
+ phase = np.unwrap(phase)
559
+ return w, mag_db, np.degrees(phase)
560
+
561
+
562
+ class Margins:
563
+ """Stability margins of one open-loop channel.
564
+
565
+ gain_margin
566
+ linear factor the loop gain can grow by (inf when
567
+ the phase never reaches -180 deg)
568
+
569
+ gain_margin_db
570
+ the same in dB
571
+
572
+ phase_margin
573
+ degrees of extra lag the loop tolerates (inf when
574
+ the gain never reaches 1)
575
+
576
+ w_gain_crossover
577
+ where ``|G|`` = 1, the phase margin is read there
578
+
579
+ w_phase_crossover
580
+ where the phase is -180 deg, the gain margin is
581
+ read there
582
+ """
583
+
584
+ __slots__ = (
585
+ "gain_margin",
586
+ "gain_margin_db",
587
+ "phase_margin",
588
+ "w_gain_crossover",
589
+ "w_phase_crossover",
590
+ )
591
+
592
+ def __init__(self, gm, pm, w_gc, w_pc):
593
+ self.gain_margin = gm
594
+ self.gain_margin_db = 20.0 * np.log10(gm) if np.isfinite(gm) else np.inf
595
+ self.phase_margin = pm
596
+ self.w_gain_crossover = w_gc
597
+ self.w_phase_crossover = w_pc
598
+
599
+ def __repr__(self):
600
+ return (
601
+ f"Margins(gain={self.gain_margin_db:.3g} dB @ "
602
+ f"{self.w_phase_crossover:.4g} rad/s, "
603
+ f"phase={self.phase_margin:.3g} deg @ "
604
+ f"{self.w_gain_crossover:.4g} rad/s)"
605
+ )
606
+
607
+
608
+ def _crossing(f, w_lo, w_hi):
609
+ """Refine a sign change of f between two frequencies."""
610
+ from scipy.optimize import brentq
611
+
612
+ return brentq(f, w_lo, w_hi, xtol=1e-14, rtol=1e-13)
613
+
614
+
615
+ def margins(model, w=None, input=0, output=0):
616
+ """Gain and phase margins of the OPEN-loop channel `model`.
617
+
618
+ The grid only brackets the crossings; each one is then refined by
619
+ root-finding on the exact response, so the answer does not inherit
620
+ the grid's resolution.
621
+ """
622
+ if w is None:
623
+ w = _auto_frequencies(model, decades=3, points=2000)
624
+ w = np.atleast_1d(np.asarray(w, dtype=float))
625
+
626
+ def response(wk):
627
+ return frequency_response(model, [wk], input=input, output=output)[0]
628
+
629
+ G = frequency_response(model, w, input=input, output=output)
630
+ mag = np.abs(G)
631
+ phase = np.unwrap(np.angle(G))
632
+
633
+ # phase margin, at the first |G| = 1
634
+ pm, w_gc = np.inf, np.nan
635
+ crossings = np.nonzero(np.diff(np.sign(mag - 1.0)))[0]
636
+ if crossings.size:
637
+ k = crossings[0]
638
+ w_gc = _crossing(lambda x: np.abs(response(x)) - 1.0, w[k], w[k + 1])
639
+ # the phase itself comes from the exact response, not from the
640
+ # grid; the interpolated value only says which branch of it the
641
+ # unwrapped curve is on
642
+ principal = float(np.angle(response(w_gc)))
643
+ approx = float(np.interp(w_gc, w, phase))
644
+ turns = np.round((approx - principal) / (2.0 * np.pi))
645
+ pm = 180.0 + np.degrees(principal + 2.0 * np.pi * turns)
646
+ pm = (pm + 180.0) % 360.0 - 180.0
647
+
648
+ # gain margin, at the first phase = -180 deg
649
+ gm, w_pc = np.inf, np.nan
650
+ target = phase + np.pi
651
+ crossings = np.nonzero(np.diff(np.sign(target)))[0]
652
+ if crossings.size:
653
+ k = crossings[0]
654
+ branch = 2.0 * np.pi * np.round((phase[k] + np.pi) / (2.0 * np.pi))
655
+
656
+ def phase_error(x):
657
+ local = np.angle(response(x))
658
+ return (local + np.pi - branch + np.pi) % (2.0 * np.pi) - np.pi
659
+
660
+ try:
661
+ w_pc = _crossing(phase_error, w[k], w[k + 1])
662
+ at_crossover = np.abs(response(w_pc))
663
+ gm = np.inf if at_crossover == 0.0 else 1.0 / at_crossover
664
+ except ValueError: # the bracket did not survive refinement
665
+ w_pc = w[k]
666
+ gm = 1.0 / max(np.abs(response(w_pc)), 1e-300)
667
+
668
+ return Margins(gm, pm, w_gc, w_pc)
669
+
670
+
671
+ # ---- time response -----------------------------------------------------
672
+ class StepInfo:
673
+ """Shape of a step response: the numbers a spec is written in.
674
+
675
+ rise_time
676
+ `rise_band` low to high fraction of the final value
677
+
678
+ settling_time
679
+ last time ``|y - y_final|`` leaves `settling_band`
680
+
681
+ overshoot
682
+ percent above the final value
683
+
684
+ peak, peak_time, steady_state
685
+ """
686
+
687
+ __slots__ = (
688
+ "rise_time",
689
+ "settling_time",
690
+ "overshoot",
691
+ "peak",
692
+ "peak_time",
693
+ "steady_state",
694
+ )
695
+
696
+ def __init__(self, rise, settle, overshoot, peak, peak_time, final):
697
+ self.rise_time = rise
698
+ self.settling_time = settle
699
+ self.overshoot = overshoot
700
+ self.peak = peak
701
+ self.peak_time = peak_time
702
+ self.steady_state = final
703
+
704
+ def __repr__(self):
705
+ return (
706
+ f"StepInfo(rise={self.rise_time:.4g}, "
707
+ f"settling={self.settling_time:.4g}, "
708
+ f"overshoot={self.overshoot:.3g}%, "
709
+ f"final={self.steady_state:.4g})"
710
+ )
711
+
712
+
713
+ def step_info(t, y, final=None, rise_band=(0.1, 0.9), settling_band=0.02):
714
+ """Step-response metrics from any (t, y) pair.
715
+
716
+ Deliberately not tied to a linear model: hand it a channel of a
717
+ nonlinear `SimulationResult` and the numbers mean the same thing.
718
+ `final` defaults to the last sample, which assumes the run was long
719
+ enough to settle -- pass it explicitly when it was not.
720
+ """
721
+ t = np.asarray(t, dtype=float)
722
+ y = np.asarray(y, dtype=float)
723
+ if t.size != y.size:
724
+ raise ValueError(f"t has {t.size} samples, y has {y.size}")
725
+ if t.size < 2:
726
+ raise ValueError("need at least two samples")
727
+
728
+ y_final = float(y[-1] if final is None else final)
729
+ y0 = float(y[0])
730
+ span = y_final - y0
731
+
732
+ def crossing_time(level):
733
+ """First time y reaches `level`, linearly interpolated."""
734
+ rising = span >= 0
735
+ hit = np.nonzero((y >= level) if rising else (y <= level))[0]
736
+ if not hit.size:
737
+ return np.nan
738
+ k = hit[0]
739
+ if k == 0:
740
+ return float(t[0])
741
+ y_lo, y_hi = y[k - 1], y[k]
742
+ if y_hi == y_lo:
743
+ return float(t[k])
744
+ return float(t[k - 1] + (level - y_lo) * (t[k] - t[k - 1]) / (y_hi - y_lo))
745
+
746
+ if span == 0.0:
747
+ rise = np.nan
748
+ else:
749
+ rise = crossing_time(y0 + rise_band[1] * span) - crossing_time(
750
+ y0 + rise_band[0] * span
751
+ )
752
+
753
+ tol = settling_band * abs(span if span else y_final)
754
+ outside = np.nonzero(np.abs(y - y_final) > tol)[0]
755
+ settle = float(t[outside[-1]]) if outside.size else float(t[0])
756
+
757
+ peak_idx = int(np.argmax(y * np.sign(span if span else 1.0)))
758
+ peak = float(y[peak_idx])
759
+ overshoot = 100.0 * (peak - y_final) / abs(span) if span else 0.0
760
+
761
+ return StepInfo(rise, settle, overshoot, peak, float(t[peak_idx]), y_final)
762
+
763
+
764
+ def step_response(model, t, input=0, output=0, x0=None):
765
+ """Exact step response of a linear model, by matrix exponential.
766
+
767
+ No integration and no step-size choice. Exponentiating the augmented
768
+ `[[A, B], [0, 0]]` gives the transition matrix and the convolution
769
+ of a held input in one shot, and a step *is* a held input -- so the
770
+ answer is right to machine precision at every sample, not to a
771
+ solver tolerance.
772
+
773
+ On a uniformly spaced `t` the exponential is taken once and iterated;
774
+ otherwise once per sample.
775
+ """
776
+ from scipy.linalg import expm
777
+
778
+ m = _siso(model, input, output)
779
+ t = np.atleast_1d(np.asarray(t, dtype=float))
780
+ n = m.n_states
781
+ x = np.zeros(n) if x0 is None else np.asarray(x0, dtype=float).copy()
782
+
783
+ aug = np.zeros((n + 1, n + 1))
784
+ aug[:n, :n] = m.A
785
+ aug[:n, n:] = m.B
786
+
787
+ def advance(state, dt):
788
+ if dt == 0.0:
789
+ return state
790
+ block = expm(aug * dt)
791
+ return block[:n, :n] @ state + block[:n, n]
792
+
793
+ steps = np.diff(t)
794
+ uniform = steps.size and np.allclose(steps, steps[0], rtol=1e-12, atol=0.0)
795
+
796
+ y = np.empty(t.size)
797
+ x = advance(x, float(t[0]))
798
+ y[0] = float((m.C @ x)[0] + m.D[0, 0])
799
+
800
+ if uniform:
801
+ block = expm(aug * float(steps[0]))
802
+ transition, hold = block[:n, :n], block[:n, n]
803
+ for k in range(1, t.size):
804
+ x = transition @ x + hold
805
+ y[k] = float((m.C @ x)[0] + m.D[0, 0])
806
+ else:
807
+ for k in range(1, t.size):
808
+ x = advance(x, float(steps[k - 1]))
809
+ y[k] = float((m.C @ x)[0] + m.D[0, 0])
810
+ return y
811
+
812
+
813
+ # ---- structural properties ---------------------------------------------
814
+ def controllability_matrix(model):
815
+ """[B, AB, ..., A^(n-1)B]."""
816
+ m = _model(model)
817
+ cols = [m.B]
818
+ for _ in range(m.n_states - 1):
819
+ cols.append(m.A @ cols[-1])
820
+ return np.hstack(cols)
821
+
822
+
823
+ def observability_matrix(model):
824
+ """[C; CA; ...; CA^(n-1)]."""
825
+ m = _model(model)
826
+ rows = [m.C]
827
+ for _ in range(m.n_states - 1):
828
+ rows.append(rows[-1] @ m.A)
829
+ return np.vstack(rows)
830
+
831
+
832
+ def is_controllable(model, tol=None):
833
+ """Full rank of the controllability matrix, by SVD rather than by a
834
+ determinant -- the Kalman matrix is famously ill-conditioned."""
835
+ m = _model(model)
836
+ return np.linalg.matrix_rank(controllability_matrix(m), tol=tol) == m.n_states
837
+
838
+
839
+ def is_observable(model, tol=None):
840
+ m = _model(model)
841
+ return np.linalg.matrix_rank(observability_matrix(m), tol=tol) == m.n_states
842
+
843
+
844
+ def gramians(model):
845
+ """(Wc, Wo) from the two Lyapunov equations. Requires a stable A."""
846
+ from scipy.linalg import solve_continuous_lyapunov
847
+
848
+ m = _model(model)
849
+ if np.max(poles(m).real) >= 0.0:
850
+ raise ValueError(
851
+ "gramians need a stable A; this model has a pole with "
852
+ f"Re = {np.max(poles(m).real):.3g} >= 0"
853
+ )
854
+ Wc = solve_continuous_lyapunov(m.A, -(m.B @ m.B.T))
855
+ Wo = solve_continuous_lyapunov(m.A.T, -(m.C.T @ m.C))
856
+ return Wc, Wo
857
+
858
+
859
+ def hankel_singular_values(model):
860
+ """sqrt of the eigenvalues of Wc Wo -- how much each balanced state
861
+ contributes to the input/output map."""
862
+ Wc, Wo = gramians(model)
863
+ lam = np.linalg.eigvals(Wc @ Wo).real
864
+ return np.sqrt(np.sort(np.clip(lam, 0.0, None))[::-1])
865
+
866
+
867
+ def balanced_reduction(model, order):
868
+ """Balanced truncation to `order` states.
869
+
870
+ Balances so that the two gramians are equal and diagonal, then keeps
871
+ the states with the largest Hankel singular values -- the ones the
872
+ input/output map actually depends on. Returns (LinearModel, hsv).
873
+ """
874
+ from scipy.linalg import cholesky, svd
875
+
876
+ m = _model(model)
877
+ if not 0 < order <= m.n_states:
878
+ raise ValueError(f"order must be in 1..{m.n_states}, got {order}")
879
+
880
+ Wc, Wo = gramians(m)
881
+ Lc = cholesky(Wc, lower=True)
882
+ Lo = cholesky(Wo, lower=True)
883
+ U, s, Vt = svd(Lo.T @ Lc)
884
+
885
+ scale = np.diag(1.0 / np.sqrt(s))
886
+ T = Lc @ Vt.T @ scale # balancing transform
887
+ Tinv = scale @ U.T @ Lo.T
888
+
889
+ keep = slice(0, order)
890
+ Ab = (Tinv @ m.A @ T)[keep, keep]
891
+ Bb = (Tinv @ m.B)[keep, :]
892
+ Cb = (m.C @ T)[:, keep]
893
+ return LinearModel(Ab, Bb, Cb, m.D), s
894
+
895
+
896
+ # ---- synthesis ---------------------------------------------------------
897
+ def lqr(model, Q, R):
898
+ """Optimal state feedback u = -K x for the cost
899
+ int (x' Q x + u' R u) dt.
900
+
901
+ Returns (K, S, closed_loop_poles), with S the solution of the
902
+ algebraic Riccati equation.
903
+ """
904
+ from scipy.linalg import solve_continuous_are
905
+
906
+ m = _model(model)
907
+ Q = np.atleast_2d(np.asarray(Q, dtype=float))
908
+ R = np.atleast_2d(np.asarray(R, dtype=float))
909
+ S = solve_continuous_are(m.A, m.B, Q, R)
910
+ K = np.linalg.solve(R, m.B.T @ S)
911
+ return K, S, np.linalg.eigvals(m.A - m.B @ K)
912
+
913
+
914
+ def lqe(model, Qn, Rn):
915
+ """Steady-state Kalman gain L for `dx = Ax + Bu + w`, `y = Cx + v`
916
+ with covariances Qn (process, on the states) and Rn (measurement).
917
+
918
+ The dual of `lqr`: returns (L, P, estimator_poles), with P the error
919
+ covariance. Feed L to `control.KalmanFilter` or wire it by hand.
920
+ """
921
+ from scipy.linalg import solve_continuous_are
922
+
923
+ m = _model(model)
924
+ Qn = np.atleast_2d(np.asarray(Qn, dtype=float))
925
+ Rn = np.atleast_2d(np.asarray(Rn, dtype=float))
926
+ P = solve_continuous_are(m.A.T, m.C.T, Qn, Rn)
927
+ L = np.linalg.solve(Rn, m.C @ P).T
928
+ return L, P, np.linalg.eigvals(m.A - L @ m.C)
929
+
930
+
931
+ # ==============================================================================
932
+ # Interconnection: building one model out of several
933
+ # ==============================================================================
934
+ # Everything above analyses a model that came from somewhere. These build
935
+ # one. The frequency response is the check that keeps them honest --
936
+ # `series` must satisfy `G(jw) = G2(jw) G1(jw)` at every frequency, and
937
+ # the test file says so rather than trusting the block algebra.
938
+
939
+
940
+ def static_gain(K):
941
+ """A `LinearModel` with no states: `y = K u`.
942
+
943
+ A gain is a perfectly good system, and the interconnection functions
944
+ take it like any other -- which is how a constant enters a loop
945
+ without a special case.
946
+ """
947
+ K = np.atleast_2d(np.asarray(K, dtype=float))
948
+ outputs, inputs = K.shape
949
+ return LinearModel(
950
+ np.zeros((0, 0)), np.zeros((0, inputs)), np.zeros((outputs, 0)), K
951
+ )
952
+
953
+
954
+ def _stack(first, second, top_right, bottom_left):
955
+ """[[A1, top_right], [bottom_left, A2]] -- the shape every one of
956
+ these interconnections has, differing only in the corners."""
957
+ return np.block([[first, top_right], [bottom_left, second]])
958
+
959
+
960
+ def series(*models):
961
+ """`models[-1] @ ... @ models[0]`: each one feeding the next.
962
+
963
+ Note the order. `series(g, h)` is h *after* g, which is how a signal
964
+ flows through a diagram left to right -- and the opposite of how the
965
+ matrix product reads. Getting that backwards is the classic way to
966
+ build a loop that analyses beautifully and describes nothing.
967
+ """
968
+ if not models:
969
+ raise ValueError("series needs at least one model")
970
+ result = _model(models[0])
971
+ for nxt in models[1:]:
972
+ result = _series_pair(result, _model(nxt))
973
+ return result
974
+
975
+
976
+ def _series_pair(first, second):
977
+ if first.n_outputs != second.n_inputs:
978
+ raise ValueError(
979
+ f"cannot put a {second.n_inputs}-input model after a "
980
+ f"{first.n_outputs}-output one"
981
+ )
982
+ A = _stack(
983
+ first.A,
984
+ second.A,
985
+ np.zeros((first.n_states, second.n_states)),
986
+ second.B @ first.C,
987
+ )
988
+ B = np.vstack([first.B, second.B @ first.D])
989
+ C = np.hstack([second.D @ first.C, second.C])
990
+ return LinearModel(A, B, C, second.D @ first.D)
991
+
992
+
993
+ def parallel(*models):
994
+ """The same input into each, their outputs summed."""
995
+ if not models:
996
+ raise ValueError("parallel needs at least one model")
997
+ result = _model(models[0])
998
+ for nxt in models[1:]:
999
+ result = _parallel_pair(result, _model(nxt))
1000
+ return result
1001
+
1002
+
1003
+ def _parallel_pair(first, second):
1004
+ if (first.n_inputs, first.n_outputs) != (second.n_inputs, second.n_outputs):
1005
+ raise ValueError(
1006
+ f"parallel needs matching shapes, got "
1007
+ f"{first.n_outputs}x{first.n_inputs} and "
1008
+ f"{second.n_outputs}x{second.n_inputs}"
1009
+ )
1010
+ A = _stack(
1011
+ first.A,
1012
+ second.A,
1013
+ np.zeros((first.n_states, second.n_states)),
1014
+ np.zeros((second.n_states, first.n_states)),
1015
+ )
1016
+ return LinearModel(
1017
+ A,
1018
+ np.vstack([first.B, second.B]),
1019
+ np.hstack([first.C, second.C]),
1020
+ first.D + second.D,
1021
+ )
1022
+
1023
+
1024
+ def append(*models):
1025
+ """Side by side: inputs and outputs stacked, nothing shared.
1026
+
1027
+ The plant of a multivariable problem, assembled from the loops that
1028
+ were designed one at a time.
1029
+ """
1030
+ if not models:
1031
+ raise ValueError("append needs at least one model")
1032
+ result = _model(models[0])
1033
+ for nxt in models[1:]:
1034
+ result = _append_pair(result, _model(nxt))
1035
+ return result
1036
+
1037
+
1038
+ def _append_pair(first, second):
1039
+ A = _stack(
1040
+ first.A,
1041
+ second.A,
1042
+ np.zeros((first.n_states, second.n_states)),
1043
+ np.zeros((second.n_states, first.n_states)),
1044
+ )
1045
+ B = _stack(
1046
+ first.B,
1047
+ second.B,
1048
+ np.zeros((first.n_states, second.n_inputs)),
1049
+ np.zeros((second.n_states, first.n_inputs)),
1050
+ )
1051
+ C = _stack(
1052
+ first.C,
1053
+ second.C,
1054
+ np.zeros((first.n_outputs, second.n_states)),
1055
+ np.zeros((second.n_outputs, first.n_states)),
1056
+ )
1057
+ D = _stack(
1058
+ first.D,
1059
+ second.D,
1060
+ np.zeros((first.n_outputs, second.n_inputs)),
1061
+ np.zeros((second.n_outputs, first.n_inputs)),
1062
+ )
1063
+ return LinearModel(A, B, C, D)
1064
+
1065
+
1066
+ def negate(model):
1067
+ """`-G`, for building a summing junction out of `parallel`."""
1068
+ m = _model(model)
1069
+ return LinearModel(m.A, m.B, -m.C, -m.D)
1070
+
1071
+
1072
+ def feedback(forward, backward=None, sign=-1):
1073
+ """Close a loop: `e = u + sign * H y`, `y = G e`.
1074
+
1075
+ `backward=None` is unity feedback, the usual case. `sign=-1` is
1076
+ negative feedback, also the usual case -- so `feedback(g)` is the
1077
+ closed loop everyone means.
1078
+
1079
+ The one thing that can fail is `I - sign * Dg * Dh` being singular,
1080
+ and it is worth knowing what that means rather than reading it as a
1081
+ numerical accident: it is an algebraic loop with no solution. Two
1082
+ direct-feedthrough blocks in a ring whose gains multiply to exactly
1083
+ one have no consistent signal, and no amount of conditioning
1084
+ produces one. `blocksim.core` refuses the same thing at runtime, from
1085
+ the other end.
1086
+ """
1087
+ forward = _model(forward)
1088
+ backward = (
1089
+ static_gain(np.eye(forward.n_outputs)) if backward is None else _model(backward)
1090
+ )
1091
+ if forward.n_outputs != backward.n_inputs:
1092
+ raise ValueError(
1093
+ f"the loop does not close: the forward path gives "
1094
+ f"{forward.n_outputs} signals, the return path takes "
1095
+ f"{backward.n_inputs}"
1096
+ )
1097
+ if backward.n_outputs != forward.n_inputs:
1098
+ raise ValueError(
1099
+ f"the loop does not close: the return path gives "
1100
+ f"{backward.n_outputs} signals, the forward path takes "
1101
+ f"{forward.n_inputs}"
1102
+ )
1103
+ sign = float(sign)
1104
+
1105
+ coupling = np.eye(forward.n_outputs) - sign * forward.D @ backward.D
1106
+ if np.linalg.matrix_rank(coupling) < coupling.shape[0]:
1107
+ raise ValueError(
1108
+ "the loop is algebraically singular: with these feedthrough "
1109
+ "terms there is no consistent signal at all. A ring of direct "
1110
+ "feedthrough whose gains multiply to one does this."
1111
+ )
1112
+ solved = np.linalg.inv(coupling)
1113
+
1114
+ # y = solved (Cg x1 + sign Dg Ch x2 + Dg u)
1115
+ # e = sign Dh solved Cg x1 + (sign Ch + Dh solved Dg Ch) x2
1116
+ # + (I + sign Dh solved Dg) u
1117
+ y_x1 = solved @ forward.C
1118
+ y_x2 = sign * solved @ forward.D @ backward.C
1119
+ y_u = solved @ forward.D
1120
+
1121
+ e_x1 = sign * backward.D @ y_x1
1122
+ e_x2 = sign * backward.C + sign * backward.D @ y_x2
1123
+ e_u = np.eye(forward.n_inputs) + sign * backward.D @ y_u
1124
+
1125
+ A = _stack(
1126
+ forward.A + forward.B @ e_x1,
1127
+ backward.A + backward.B @ y_x2,
1128
+ forward.B @ e_x2,
1129
+ backward.B @ y_x1,
1130
+ )
1131
+ B = np.vstack([forward.B @ e_u, backward.B @ y_u])
1132
+ C = np.hstack([y_x1, y_x2])
1133
+ return LinearModel(A, B, C, y_u)
1134
+
1135
+
1136
+ def loop_gain(plant, controller):
1137
+ """`L = P C`, the open loop a margin is measured on.
1138
+
1139
+ A one-line function that exists because the order is the thing
1140
+ people get wrong, and `margins(loop_gain(p, c))` reads correctly
1141
+ while `margins(series(p, c))` reads as its opposite.
1142
+ """
1143
+ return series(_model(controller), _model(plant))