diff --git a/README.rst b/README.rst index 825693c91..bef21f597 100644 --- a/README.rst +++ b/README.rst @@ -177,3 +177,7 @@ Your contributions are welcome! Simply fork the GitHub repository and send a Please see the `Developer's Wiki`_ for detailed instructions. .. _Developer's Wiki: https://github.com/python-control/python-control/wiki + +Please follow the `AI Policy of NumPy`_ when writing issues and pull requests. + +.. _AI Policy of NumPy: https://numpy.org/doc/stable/dev/ai_policy.html diff --git a/benchmarks/scipy_fallback_bench.py b/benchmarks/scipy_fallback_bench.py new file mode 100644 index 000000000..7934a3b5d --- /dev/null +++ b/benchmarks/scipy_fallback_bench.py @@ -0,0 +1,161 @@ +# scipy_fallback_bench.py - benchmarks for the SLICOT-free (scipy) fallbacks +# KL, 1 Jul 2026 +# +# This benchmark compares the pure scipy/numpy fallbacks against the SLICOT +# (slycot) implementations for the matrix-equation routines that gained a +# ``method`` argument: +# +# * generalized continuous Lyapunov lyap(A, Q, E=E) +# * generalized discrete Lyapunov dlyap(A, Q, E=E) +# * discrete Sylvester (Stein) dlyap(A, Q, C) +# +# The ``time_*`` methods time each (routine, size, method) combination. The +# ``track_*`` method records the accuracy of the generalized-Lyapunov solution +# as a function of cond(E). Every problem is constructed from a known solution +# ``X`` so that both speed and accuracy are measured against ground truth; the +# ``setup`` methods therefore build the matrices *outside* the timed region. +# +# When slycot is not installed the ``method='slycot'`` parameterizations are +# skipped (asv treats NotImplementedError raised in setup() as "skip"), so the +# suite runs with or without slycot. +# +# A single deterministic seed is used per problem, so runs are reproducible and +# comparable across commits. (The tables discussed in PR #1234 were medians +# over several seeds; the ratios here match, as asv's repeated sampling +# averages the timing.) +# +# Run, e.g.: +# +# PYTHONPATH=`pwd` asv run --python=python --bench scipy_fallback +# +# or, since these are plain classes, call the methods directly to reproduce the +# numbers without asv. + +import numpy as np + +import control as ct + +# Fixed seed: deterministic, reproducible problems across runs and commits. +SEED = 20260627 + + +def _slycot_available(): + try: + return ct.slycot_check() + except Exception: + return False + + +def _spd(rng, n): + """Return a symmetric positive-definite n-by-n matrix.""" + P = rng.standard_normal((n, n)) + return P @ P.T + n * np.eye(n) + + +def _make_gen_cont_lyap(rng, n): + # A X E' + E X A' + Q = 0, built from a known SPD solution X (A Hurwitz). + E = np.eye(n) + 0.1 * rng.standard_normal((n, n)) + M = rng.standard_normal((n, n)) + S = M - (np.linalg.norm(M, 2) + 1.0) * np.eye(n) + A = E @ S + X = _spd(rng, n) + Q = -(A @ X @ E.T + E @ X @ A.T) + Q = 0.5 * (Q + Q.T) + return ct.lyap, (A, Q), dict(E=E), X + + +def _make_gen_disc_lyap(rng, n): + # A X A' - E X E' + Q = 0, built from a known SPD solution X (A Schur). + E = np.eye(n) + 0.1 * rng.standard_normal((n, n)) + M = rng.standard_normal((n, n)) + S = M / (np.linalg.norm(M, 2) + 1.0) + A = E @ S + X = _spd(rng, n) + Q = -(A @ X @ A.T - E @ X @ E.T) + Q = 0.5 * (Q + Q.T) + return ct.dlyap, (A, Q), dict(E=E), X + + +def _make_disc_sylvester(rng, n): + # A X Q' - X + C = 0 (discrete Sylvester / Stein), from a known X. + MA = rng.standard_normal((n, n)) + MQ = rng.standard_normal((n, n)) + A = MA / (np.linalg.norm(MA, 2) + 1.0) + Q = MQ / (np.linalg.norm(MQ, 2) + 1.0) + X = rng.standard_normal((n, n)) + C = X - A @ X @ Q.T + return ct.dlyap, (A, Q, C), dict(), X + + +_MAKERS = { + 'gen_cont_lyap': _make_gen_cont_lyap, + 'gen_disc_lyap': _make_gen_disc_lyap, + 'disc_sylvester': _make_disc_sylvester, +} + + +class MatrixEquationTiming: + """Time the scipy fallback against slycot for the ``method=`` routines.""" + + params = ( + ['gen_cont_lyap', 'gen_disc_lyap', 'disc_sylvester'], + [10, 50, 100, 200, 400], + ['scipy', 'slycot'], + ) + param_names = ['routine', 'n', 'method'] + timeout = 120 + + def setup(self, routine, n, method): + if method == 'slycot' and not _slycot_available(): + raise NotImplementedError("slycot not available") + rng = np.random.default_rng(SEED) + self.func, self.args, self.kwargs, X = _MAKERS[routine](rng, n) + # Confirm the method actually solves the problem before timing it. + Xhat = self.func(*self.args, method=method, **self.kwargs) + relerr = np.linalg.norm(Xhat - X, 'fro') / np.linalg.norm(X, 'fro') + assert relerr < 1e-6, f"{routine} {method} n={n}: relerr={relerr:.1e}" + + def time_solve(self, routine, n, method): + self.func(*self.args, method=method, **self.kwargs) + + +class GenLyapAccuracy: + """Track generalized continuous Lyapunov accuracy versus cond(E). + + Both the scipy and slycot paths require E nonsingular and degrade together + as E becomes ill-conditioned (the problem is itself about cond(E)**2 + conditioned); this benchmark records that, rather than timing. + """ + + params = ( + [1e0, 1e2, 1e4, 1e6, 1e8, 1e10, 1e12], + ['scipy', 'slycot'], + ) + param_names = ['cond_E', 'method'] + unit = "relative error" + n = 100 + + def setup(self, cond_E, method): + if method == 'slycot' and not _slycot_available(): + raise NotImplementedError("slycot not available") + n = self.n + rng = np.random.default_rng(SEED) + U, _ = np.linalg.qr(rng.standard_normal((n, n))) + V, _ = np.linalg.qr(rng.standard_normal((n, n))) + M = rng.standard_normal((n, n)) + S = M - (np.linalg.norm(M, 2) + 1.0) * np.eye(n) + X = _spd(rng, n) + # E with prescribed condition number: singular values spanning cond_E. + E = (U * np.logspace(0, -np.log10(cond_E), n)) @ V.T + A = E @ S + Q = -(A @ X @ E.T + E @ X @ A.T) + self.A, self.Q, self.E, self.X = A, 0.5 * (Q + Q.T), E, X + + def track_relerr(self, cond_E, method): + import warnings + with warnings.catch_warnings(): + # Ill-conditioned E deliberately triggers the accuracy warning. + warnings.simplefilter("ignore") + Xhat = ct.lyap(self.A, self.Q, E=self.E, method=method) + return float(np.linalg.norm(Xhat - self.X, 'fro') + / np.linalg.norm(self.X, 'fro')) diff --git a/control/descfcn.py b/control/descfcn.py index 6f3f5169d..460b22601 100644 --- a/control/descfcn.py +++ b/control/descfcn.py @@ -188,8 +188,7 @@ def describing_function( # Go through all of the amplitudes we were given retdf = np.empty(np.shape(A), dtype=complex) - df = retdf # Access to the return array - df.shape = (-1, ) # as a 1D array + df = retdf.reshape((-1, )) # Access to the return array as a 1D array for i, a in enumerate(np.atleast_1d(A)): # Make sure we got a valid argument if a == 0: diff --git a/control/frdata.py b/control/frdata.py index 96d2cd5b6..17cda895c 100644 --- a/control/frdata.py +++ b/control/frdata.py @@ -121,7 +121,7 @@ class constructor, using the `frd` factory function, or Notes ----- The main data members are `omega` and `frdata`, where `omega` is a 1D - array of frequency points and and `frdata` is a 3D array of frequency + array of frequency points and `frdata` is a 3D array of frequency responses, with the first dimension corresponding to the output index of the FRD, the second dimension corresponding to the input index, and the 3rd dimension corresponding to the frequency points in omega. For example, diff --git a/control/freqplot.py b/control/freqplot.py index 475467147..35a5ee503 100644 --- a/control/freqplot.py +++ b/control/freqplot.py @@ -1312,6 +1312,8 @@ def nyquist_response( # Use existing dictionary, to keep track of processed keywords _kwargs |= kwargs + indent_direction_arg = 'indent_direction' in _kwargs + # Get values for params omega_num_given = omega_num is not None omega_num = config._get_param('freqplot', 'number_of_samples', omega_num) @@ -1469,8 +1471,21 @@ def nyquist_response( - (s - p).real # Figure out which way to offset the contour point - if p.real < 0 or (p.real == 0 and - indent_direction == 'right'): + if indent_direction_arg: + if indent_direction == 'right': + # Indent to the right + splane_contour[i] += offset + + elif indent_direction == 'left': + # Indent to the left + splane_contour[i] -= offset + + else: + raise ValueError( + "unknown value for indent_direction") + + elif p.real < 0 or (p.real == 0 and + indent_direction == 'right'): # Indent to the right splane_contour[i] += offset diff --git a/control/lti.py b/control/lti.py index 90188f556..7d4c98548 100644 --- a/control/lti.py +++ b/control/lti.py @@ -706,15 +706,15 @@ def bandwidth(sys, dbdrop=-3): Examples -------- >>> G = ct.tf([1], [1, 1]) - >>> ct.bandwidth(G) - np.float64(0.9976283451102316) + >>> ct.bandwidth(G) # doctest: +ELLIPSIS + np.float64(0.99762834511023...) >>> G1 = ct.tf(0.1, [1, 0.1]) >>> wn2 = 1 >>> zeta2 = 0.001 >>> G2 = ct.tf(wn2**2, [1, 2*zeta2*wn2, wn2**2]) - >>> ct.bandwidth(G1*G2) - np.float64(0.10184838823897456) + >>> ct.bandwidth(G1*G2) # doctest: +ELLIPSIS + np.float64(0.10184838823897...) """ if not isinstance(sys, LTI): diff --git a/control/mateqn.py b/control/mateqn.py index 9d1349b0c..1034d7d5c 100644 --- a/control/mateqn.py +++ b/control/mateqn.py @@ -14,7 +14,7 @@ import numpy as np import scipy as sp -from numpy import eye, finfo, inexact +from numpy import eye, finfo from scipy.linalg import eigvals, solve from .exception import ControlArgument, ControlDimension, ControlSlycot, \ @@ -47,21 +47,41 @@ def sb03md(n, C, A, U, dico, job='X', fact='N', trana='N', ldwork=None): try: from slycot import sb04qd except ImportError: - sb0qmd = None + sb04qd = None try: from slycot import sg03ad except ImportError: - sb04ad = None + sg03ad = None __all__ = ['lyap', 'dlyap', 'dare', 'care'] + +def _warn_ill_conditioned_E(E): + """Warn that an ill-conditioned E costs accuracy. + + The scipy generalized-Lyapunov fallback reduces the problem to a + standard Lyapunov equation by inverting E, so a poorly conditioned E + costs accuracy (continuous and discrete paths alike, regardless of + whether the underlying scipy solve happens to warn). The generalized + Lyapunov problem is itself ill-conditioned (about cond(E)**2) when E + is, so method='slycot', though it does not form inv(E) explicitly, is + not measurably more accurate in that regime. + """ + condE = np.linalg.cond(E) + if condE > 1.0 / np.sqrt(finfo(float).eps): + warnings.warn( + f"E is ill-conditioned (cond(E) = {condE:.2g}); the generalized " + "Lyapunov solution may have reduced accuracy. The problem itself " + "is ill-conditioned for such E, so method='slycot' is not " + "measurably more accurate.", UserWarning, stacklevel=3) + # # Lyapunov equation solvers lyap and dlyap # -def lyap(A, Q, C=None, E=None, method=None): +def lyap(A, Q, C=None, E=None, method=None, symmetric_kwargs=None): """Solves the continuous-time Lyapunov equation. X = lyap(A, Q) solves @@ -97,12 +117,34 @@ def lyap(A, Q, C=None, E=None, method=None): Set the method used for computing the result. Current methods are 'slycot' and 'scipy'. If set to None (default), try 'slycot' first and then 'scipy'. + symmetric_kwargs : dict, optional + Keyword arguments passed to `scipy.linalg.issymmetric` or + `scipy.linalg.ishermitian`. Returns ------- X : 2D array Solution to the Lyapunov or Sylvester equation. + Notes + ----- + For the generalized Lyapunov equation, method='slycot' uses the + SLICOT routine SG03AD, based on the generalized Schur method of + Penzl [1]_, which factors the matrix pencil without inverting E. + With method='scipy', the equation is transformed to a standard + Lyapunov equation by inverting E, which requires E to be nonsingular + and loses accuracy when E is ill-conditioned (a UserWarning is then + issued). The generalized Lyapunov problem is itself ill-conditioned + (about cond(E)**2) when E is, so method='slycot', though it does not + invert E, is not measurably more accurate in that case. Both methods + require E nonsingular; a truly singular + (descriptor) E is not currently handled by either. + + References + ---------- + .. [1] Penzl, T., "Numerical solution of generalized Lyapunov + equations", Advances in Computational Mathematics, 8:33-48, 1998. + """ # Decide what method to use method = _slycot_or_scipy(method) @@ -130,7 +172,7 @@ def lyap(A, Q, C=None, E=None, method=None): # Solve standard Lyapunov equation if C is None and E is None: # Check to make sure input matrices are the right shape and type - _check_shape(Q, n, n, square=True, symmetric=True, name="Q") + _check_shape(Q, n, n, square=True, symmetric=True, name="Q", symmetric_kwargs=symmetric_kwargs) if method == 'scipy': # Solve the Lyapunov equation using SciPy @@ -158,12 +200,29 @@ def lyap(A, Q, C=None, E=None, method=None): # Solve the generalized Lyapunov equation elif C is None and E is not None: # Check to make sure input matrices are the right shape and type - _check_shape(Q, n, n, square=True, symmetric=True, name="Q") + _check_shape(Q, n, n, square=True, symmetric=True, name="Q", symmetric_kwargs=symmetric_kwargs) _check_shape(E, n, n, square=True, name="E") if method == 'scipy': - raise ControlArgument( - "method='scipy' not valid for generalized Lyapunov equation") + # Transform to a standard Lyapunov equation by multiplying + # from the left by inv(E) and from the right by inv(E).T: + # + # (E^-1 A) X + X (E^-1 A)^T + E^-1 Q E^-T = 0 + # + # This requires E to be nonsingular. SG03AD (method='slycot', + # Penzl's generalized Schur method) factors the pencil without + # inverting E, but a truly singular E is not handled by either + # method. + try: + At = solve(E, A) + Qt = solve(E, solve(E, Q).T).T + except np.linalg.LinAlgError: + raise ControlArgument( + "method='scipy' requires E to be nonsingular; " + "a truly singular E (descriptor system) is not " + "supported by either method") + _warn_ill_conditioned_E(E) + return sp.linalg.solve_continuous_lyapunov(At, -Qt) # Make sure we have access to the write Slycot routine try: @@ -187,7 +246,7 @@ def lyap(A, Q, C=None, E=None, method=None): return X -def dlyap(A, Q, C=None, E=None, method=None): +def dlyap(A, Q, C=None, E=None, method=None, symmetric_kwargs=None): """Solves the discrete-time Lyapunov equation. X = dlyap(A, Q) solves @@ -223,12 +282,45 @@ def dlyap(A, Q, C=None, E=None, method=None): Set the method used for computing the result. Current methods are 'slycot' and 'scipy'. If set to None (default), try 'slycot' first and then 'scipy'. + symmetric_kwargs : dict, optional + Keyword arguments passed to `scipy.linalg.issymmetric` or + `scipy.linalg.ishermitian`. Returns ------- X : 2D array (or matrix) Solution to the Lyapunov or Sylvester equation. + Notes + ----- + For the generalized Lyapunov equation, method='slycot' uses the + SLICOT routine SG03AD, based on the generalized Schur method of + Penzl [1]_, which factors the matrix pencil without inverting E. + With method='scipy', the equation is transformed to a standard + Lyapunov equation by inverting E, which requires E to be nonsingular + and loses accuracy when E is ill-conditioned (a UserWarning is then + issued). The generalized Lyapunov problem is itself ill-conditioned + (about cond(E)**2) when E is, so method='slycot', though it does not + invert E, is not measurably more accurate in that case. Both methods + require E nonsingular; a truly singular + (descriptor) E is not currently handled by either. + + For the Sylvester equation, method='slycot' uses the + Hessenberg-Schur method of the SLICOT routine SB04QD [2]_ and + method='scipy' uses the Bartels-Stewart method [3]_; both reduce the + coefficient matrices to (Hessenberg-)Schur form and solve the result + by back-substitution, with O(n^3 + m^3) cost. + + References + ---------- + .. [1] Penzl, T., "Numerical solution of generalized Lyapunov + equations", Advances in Computational Mathematics, 8:33-48, 1998. + .. [2] Golub, G.H., Nash, S., and Van Loan, C., "A Hessenberg-Schur + method for the problem AX + XB = C", IEEE Trans. Automatic + Control, AC-24, pp. 909-913, 1979. + .. [3] Bartels, R.H. and Stewart, G.W., "Solution of the matrix + equation AX + XB = C", Comm. ACM, 15(9), pp. 820-826, 1972. + """ # Decide what method to use method = _slycot_or_scipy(method) @@ -260,7 +352,7 @@ def dlyap(A, Q, C=None, E=None, method=None): # Solve standard Lyapunov equation if C is None and E is None: # Check to make sure input matrices are the right shape and type - _check_shape(Q, n, n, square=True, symmetric=True, name="Q") + _check_shape(Q, n, n, square=True, symmetric=True, name="Q", symmetric_kwargs=symmetric_kwargs) if method == 'scipy': # Solve the Lyapunov equation using SciPy @@ -279,8 +371,40 @@ def dlyap(A, Q, C=None, E=None, method=None): _check_shape(C, n, m, name="C") if method == 'scipy': - raise ControlArgument( - "method='scipy' not valid for Sylvester equation") + # Solve the discrete-time Sylvester equation + # + # A X Q^T - X + C = 0 + # + # by the Bartels-Stewart method, matching the complexity of + # the Hessenberg-Schur algorithm of the SLICOT routine + # SB04QD used by method='slycot' (Golub, Nash, and Van + # Loan, 1979): with complex Schur forms A = U Ta U^H and + # Q^T = V Tq V^H and Y = U^H X V, the transformed equation + # Ta Y Tq - Y + U^H C V = 0 is solved column by column, + # each column requiring one triangular solve. O(n^3 + m^3) + # flops overall. + Ta, U = sp.linalg.schur(A, output='complex') + Tq, V = sp.linalg.schur(Q.T, output='complex') + Ct = U.conj().T @ C @ V + # Solvability requires lam_A * lam_Q != 1 for all pairs of + # eigenvalues (the diagonals of the triangular factors) + if np.min(np.abs(np.outer(np.diag(Tq), np.diag(Ta)) - 1.)) \ + < finfo(float).eps * max( + 1., np.abs(np.diag(Ta)).max() + * np.abs(np.diag(Tq)).max()): + raise ControlArgument( + "A and Q have a pair of eigenvalues whose product " + "is (almost) equal to 1; the discrete-time " + "Sylvester equation is singular") + Y = np.empty((n, m), dtype=complex) + TaY = np.empty((n, m), dtype=complex) # running Ta @ Y + In = np.eye(n) + for k in range(m): + rhs = -Ct[:, k] - TaY[:, :k] @ Tq[:k, k] + Y[:, k] = sp.linalg.solve_triangular( + Tq[k, k] * Ta - In, rhs) + TaY[:, k] = Ta @ Y[:, k] + return np.real(U @ Y @ V.conj().T) # Solve the Sylvester equation by calling Slycot function sb04qd X = sb04qd(n, m, -A, Q.T, C) @@ -288,12 +412,29 @@ def dlyap(A, Q, C=None, E=None, method=None): # Solve the generalized Lyapunov equation elif C is None and E is not None: # Check to make sure input matrices are the right shape and type - _check_shape(Q, n, n, square=True, symmetric=True, name="Q") + _check_shape(Q, n, n, square=True, symmetric=True, name="Q", symmetric_kwargs=symmetric_kwargs) _check_shape(E, n, n, square=True, name="E") if method == 'scipy': - raise ControlArgument( - "method='scipy' not valid for generalized Lyapunov equation") + # Transform to a standard Lyapunov equation by multiplying + # from the left by inv(E) and from the right by inv(E).T: + # + # (E^-1 A) X (E^-1 A)^T - X + E^-1 Q E^-T = 0 + # + # This requires E to be nonsingular. SG03AD (method='slycot', + # Penzl's generalized Schur method) factors the pencil without + # inverting E, but a truly singular E is not handled by either + # method. + try: + At = solve(E, A) + Qt = solve(E, solve(E, Q).T).T + except np.linalg.LinAlgError: + raise ControlArgument( + "method='scipy' requires E to be nonsingular; " + "a truly singular E (descriptor system) is not " + "supported by either method") + _warn_ill_conditioned_E(E) + return sp.linalg.solve_discrete_lyapunov(At, Qt) # Solve the generalized Lyapunov equation by calling Slycot # function sg03ad @@ -314,8 +455,8 @@ def dlyap(A, Q, C=None, E=None, method=None): # Riccati equation solvers care and dare # -def care(A, B, Q, R=None, S=None, E=None, stabilizing=True, method=None, - _As="A", _Bs="B", _Qs="Q", _Rs="R", _Ss="S", _Es="E"): +def care(A, B, Q, R=None, S=None, E=None, stabilizing=True, method=None, symmetric_kwargs=None, + _As="A", _Bs="B", _Qs="Q", _Rs="R", _Ss="S", _Es="E", ): """Solves the continuous-time algebraic Riccati equation. X, L, G = care(A, B, Q, R=None) solves @@ -349,6 +490,9 @@ def care(A, B, Q, R=None, S=None, E=None, stabilizing=True, method=None, Set the method used for computing the result. Current methods are 'slycot' and 'scipy'. If set to None (default), try 'slycot' first and then 'scipy'. + symmetric_kwargs : dict, optional + Keyword arguments passed to `scipy.linalg.issymmetric` or + `scipy.linalg.ishermitian`. stabilizing : bool, optional If `method` is 'slycot', unstabilized eigenvalues will be returned in the initial elements of `L`. Not supported for 'scipy'. @@ -383,8 +527,8 @@ def care(A, B, Q, R=None, S=None, E=None, stabilizing=True, method=None, # Check to make sure input matrices are the right shape and type _check_shape(A, n, n, square=True, name=_As) _check_shape(B, n, m, name=_Bs) - _check_shape(Q, n, n, square=True, symmetric=True, name=_Qs) - _check_shape(R, m, m, square=True, symmetric=True, name=_Rs) + _check_shape(Q, n, n, square=True, symmetric=True, name=_Qs, symmetric_kwargs=symmetric_kwargs) + _check_shape(R, m, m, square=True, symmetric=True, name=_Rs, symmetric_kwargs=symmetric_kwargs) # Solve the standard algebraic Riccati equation if S is None and E is None: @@ -470,7 +614,7 @@ def care(A, B, Q, R=None, S=None, E=None, stabilizing=True, method=None, # the gain matrix G return X, L, G -def dare(A, B, Q, R, S=None, E=None, stabilizing=True, method=None, +def dare(A, B, Q, R, S=None, E=None, stabilizing=True, method=None, symmetric_kwargs=None, _As="A", _Bs="B", _Qs="Q", _Rs="R", _Ss="S", _Es="E"): """Solves the discrete-time algebraic Riccati equation. @@ -505,6 +649,9 @@ def dare(A, B, Q, R, S=None, E=None, stabilizing=True, method=None, Set the method used for computing the result. Current methods are 'slycot' and 'scipy'. If set to None (default), try 'slycot' first and then 'scipy'. + symmetric_kwargs : dict, optional + Keyword arguments passed to `scipy.linalg.issymmetric` or + `scipy.linalg.ishermitian`. stabilizing : bool, optional If `method` is 'slycot', unstabilized eigenvalues will be returned in the initial elements of `L`. Not supported for 'scipy'. @@ -539,8 +686,8 @@ def dare(A, B, Q, R, S=None, E=None, stabilizing=True, method=None, # Check to make sure input matrices are the right shape and type _check_shape(A, n, n, square=True, name=_As) _check_shape(B, n, m, name=_Bs) - _check_shape(Q, n, n, square=True, symmetric=True, name=_Qs) - _check_shape(R, m, m, square=True, symmetric=True, name=_Rs) + _check_shape(Q, n, n, square=True, symmetric=True, name=_Qs, symmetric_kwargs=symmetric_kwargs) + _check_shape(R, m, m, square=True, symmetric=True, name=_Rs, symmetric_kwargs=symmetric_kwargs) if E is not None: _check_shape(E, n, n, square=True, name=_Es) if S is not None: @@ -605,7 +752,7 @@ def _slycot_or_scipy(method): # Utility function to check matrix dimensions -def _check_shape(M, n, m, square=False, symmetric=False, name="??"): +def _check_shape(M, n, m, square=False, symmetric=False, name="??", symmetric_kwargs=None): """Check the shape and properties of a 2D array. This function can be used to check to make sure a 2D array_like has the @@ -638,7 +785,7 @@ def _check_shape(M, n, m, square=False, symmetric=False, name="??"): if (square or symmetric) and M.shape[0] != M.shape[1]: raise ControlDimension("%s must be a square matrix" % name) - if symmetric and not _is_symmetric(M): + if symmetric and not _is_symmetric(M, symmetric_kwargs=symmetric_kwargs): raise ControlArgument("%s must be a symmetric matrix" % name) if M.shape[0] != n or M.shape[1] != m: @@ -650,10 +797,10 @@ def _check_shape(M, n, m, square=False, symmetric=False, name="??"): # Utility function to check if a matrix is symmetric -def _is_symmetric(M): - M = np.atleast_2d(M) - if isinstance(M[0, 0], inexact): - eps = finfo(M.dtype).eps - return ((M - M.T) < eps).all() - else: - return (M == M.T).all() +def _is_symmetric(M, symmetric_kwargs=None): + if symmetric_kwargs is None: + symmetric_kwargs = {} + + if np.iscomplexobj(M): + return sp.linalg.ishermitian(M, **symmetric_kwargs) + return sp.linalg.issymmetric(M, **symmetric_kwargs) diff --git a/control/modelsimp.py b/control/modelsimp.py index 3352cc156..a2eb065b3 100644 --- a/control/modelsimp.py +++ b/control/modelsimp.py @@ -73,7 +73,7 @@ def hankel_singular_values(sys): WoWc = Wo @ Wc w, v = np.linalg.eig(WoWc) - hsv = np.sqrt(w) + hsv = np.sqrt(w.real) hsv = np.array(hsv) hsv = np.sort(hsv) # Return the Hankel singular values, high to low diff --git a/control/nlsys.py b/control/nlsys.py index 04fda2e40..42b1f8de0 100644 --- a/control/nlsys.py +++ b/control/nlsys.py @@ -1567,7 +1567,7 @@ def input_output_response( This is often useful for interconnected control systems where the process dynamics are the first system and all other components start with zero initial condition since this can be specified as [xsys_0, 0]. - A warning is issued if the initial conditions are padded and and the + A warning is issued if the initial conditions are padded and the final listed initial state is not zero. If discontinuous inputs are given, the underlying SciPy numerical diff --git a/control/phaseplot.py b/control/phaseplot.py index cf73d62a0..0fdb9922f 100644 --- a/control/phaseplot.py +++ b/control/phaseplot.py @@ -69,9 +69,11 @@ def phase_plane_plot( List of the form [xmin, xmax, ymin, ymax] describing the boundaries of the phase plot or an array of shape (N, 2) giving points of at which to plot the vector field. - timedata : int or list of int - Time to simulate each streamline. If a list is given, a different - time can be used for each initial condition in `pointdata`. + timedata : int, 1D array, or 2D array + Time to simulate each streamline. If a 1D array is given, then the + times at which to sample the simulation for all streamlines. + If a 2D array is given, then for each row the times at which + to sample the simulation for the corresponding streamline. gridtype : str, optional The type of grid to use for generating initial conditions: 'meshgrid' (default) generates a mesh of initial conditions within @@ -544,9 +546,11 @@ def streamlines( List of the form [xmin, xmax, ymin, ymax] describing the boundaries of the phase plot or an array of shape (N, 2) giving points of at which to plot the vector field. - timedata : int or list of int - Time to simulate each streamline. If a list is given, a different - time can be used for each initial condition in `pointdata`. + timedata : int, 1D array, or 2D array + Time to simulate each streamline. If a 1D array is given, then the + times at which to sample the simulation for all streamlines. + If a 2D array is given, then for each row the times at which + to sample the simulation for the corresponding streamline. gridtype : str, optional The type of grid to use for generating initial conditions: 'meshgrid' (default) generates a mesh of initial conditions within @@ -765,9 +769,11 @@ def separatrices( List of the form [xmin, xmax, ymin, ymax] describing the boundaries of the phase plot or an array of shape (N, 2) giving points of at which to plot the vector field. - timedata : int or list of int - Time to simulate each streamline. If a list is given, a different - time can be used for each initial condition in `pointdata`. + timedata : int, 1D array, or 2D array + Time to simulate each streamline. If a 1D array is given, then the + times at which to sample the simulation for all streamlines. + If a 2D array is given, then for each row the times at which + to sample the simulation for the corresponding streamline. gridtype : str, optional The type of grid to use for generating initial conditions: 'meshgrid' (default) generates a mesh of initial conditions within @@ -886,6 +892,7 @@ def separatrices( timepts = np.linspace(0, timescale) # Run the trajectory starting in eigenvector directions + dir = dir.real # use real components only for eps in [-radius, radius]: x0 = xeq + dir * eps if evals[j].real < 0: diff --git a/control/statefbk.py b/control/statefbk.py index 414673fcf..2de8243d5 100644 --- a/control/statefbk.py +++ b/control/statefbk.py @@ -1006,7 +1006,7 @@ def _control_output(t, states, inputs, params): A_lqr = np.eye(C.shape[0]) B_lqr = np.hstack([-np.eye(C.shape[0], sys_ninputs), C]) C_lqr = -K[:, sys_nstates:] # integral gain (opt) - D_lqr = np.hstack([Kf, -K]) + D_lqr = np.hstack([Kf, -K[:, :sys_nstates]]) ctrl = ss( A_lqr, B_lqr, C_lqr, D_lqr, dt=sys.dt, name=name, diff --git a/control/statesp.py b/control/statesp.py index 65529b99d..8091e29ed 100644 --- a/control/statesp.py +++ b/control/statesp.py @@ -261,9 +261,9 @@ def __init__(self, *args, **kwargs): # Reset shapes if the system is static if static: - A.shape = (0, 0) - B.shape = (0, self.ninputs) - C.shape = (self.noutputs, 0) + A = A.reshape((0, 0)) + B = B.reshape((0, self.ninputs)) + C = C.reshape((self.noutputs, 0)) # Check to make sure everything is consistent _check_shape(A, self.nstates, self.nstates, name="A") @@ -1003,6 +1003,8 @@ def feedback(self, other=1, sign=-1): """ # Convert the system to state space, if possible try: + if np.isscalar(other) and self.ninputs == self.noutputs: + other = other * eye(self.ninputs) other = _convert_to_statespace(other) except: pass @@ -2295,7 +2297,7 @@ def _ssmatrix(data, axis=1, square=None, rows=None, cols=None, name=None): Returns ------- - arr : 2D array, with shape (0, 0) if a is empty + arr : 2D array, with shape (0, 0) for empty vectors or matrices """ # Process the name of the object, if available @@ -2310,9 +2312,9 @@ def _ssmatrix(data, axis=1, square=None, rows=None, cols=None, name=None): if (ndim > 2): raise ValueError(f"state-space matrix{name} must be 2-dimensional") - elif (ndim == 2 and shape == (1, 0)) or \ - (ndim == 1 and shape == (0, )): - # Passed an empty matrix or empty vector; change shape to (0, 0) + elif (ndim == 2 and shape == (0, 0)) or \ + (ndim == 1 and shape == (0, )): + # Passed a 0-by-0 matrix or empty vector; change shape to (0, 0) shape = (0, 0) elif ndim == 1: diff --git a/control/stochsys.py b/control/stochsys.py index 756d83e13..003958f57 100644 --- a/control/stochsys.py +++ b/control/stochsys.py @@ -33,7 +33,7 @@ # contributed by Sawyer B. Fuller -def lqe(*args, **kwargs): +def lqe(*args, symmetric_kwargs=None, **kwargs): r"""lqe(A, G, C, QN, RN, [, NN]) Continuous-time linear quadratic estimator (Kalman filter). @@ -54,9 +54,9 @@ def lqe(*args, **kwargs): .. math:: dx_e/dt = A x_e + B u + L(y - C x_e - D u) - produces a state estimate x_e that minimizes the expected squared error - using the sensor measurements y. The noise cross-correlation `NN` is - set to zero when omitted. + produces a state estimate x_e that minimizes the mean squared + estimation error x - x_e using the sensor measurements y. The noise + cross-correlation `NN` is set to zero when omitted. The function can be called with either 3, 4, 5, or 6 arguments: @@ -83,6 +83,9 @@ def lqe(*args, **kwargs): Set the method used for computing the result. Current methods are 'slycot' and 'scipy'. If set to None (default), try 'slycot' first and then 'scipy'. + symmetric_kwargs : dict, optional + Keyword arguments passed to `scipy.linalg.issymmetric` or + `scipy.linalg.ishermitian`. Returns ------- @@ -178,12 +181,12 @@ def lqe(*args, **kwargs): # Compute the result (dimension and symmetry checking done in care()) P, E, LT = care(A.T, C.T, G @ QN @ G.T, RN, method=method, - _Bs="C", _Qs="QN", _Rs="RN", _Ss="NN") + _Bs="C", _Qs="QN", _Rs="RN", _Ss="NN", symmetric_kwargs=symmetric_kwargs) return LT.T, P, E # contributed by Sawyer B. Fuller -def dlqe(*args, **kwargs): +def dlqe(*args, symmetric_kwargs=None, **kwargs): r"""dlqe(A, G, C, QN, RN, [, N]) Discrete-time linear quadratic estimator (Kalman filter). @@ -204,9 +207,9 @@ def dlqe(*args, **kwargs): .. math:: x_e[n+1] = A x_e[n] + B u[n] + L(y[n] - C x_e[n] - D u[n]) - produces a state estimate x_e[n] that minimizes the expected squared - error using the sensor measurements y. The noise cross-correlation `NN` - is set to zero when omitted. + produces a state estimate x_e[n] that minimizes the mean squared + estimation error x[n] - x_e[n] using the sensor measurements y. The + noise cross-correlation `NN` is set to zero when omitted. Parameters ---------- @@ -220,6 +223,9 @@ def dlqe(*args, **kwargs): Set the method used for computing the result. Current methods are 'slycot' and 'scipy'. If set to None (default), try 'slycot' first and then 'scipy'. + symmetric_kwargs : dict, optional + Keyword arguments passed to `scipy.linalg.issymmetric` or + `scipy.linalg.ishermitian`. Returns ------- @@ -299,7 +305,7 @@ def dlqe(*args, **kwargs): # Compute the result (dimension and symmetry checking done in dare()) P, E, LT = dare(A.T, C.T, G @ QN @ G.T, RN, method=method, - _Bs="C", _Qs="QN", _Rs="RN", _Ss="NN") + _Bs="C", _Qs="QN", _Rs="RN", _Ss="NN", symmetric_kwargs=symmetric_kwargs) return LT.T, P, E @@ -312,7 +318,7 @@ def create_estimator_iosystem( control_indices=None, disturbance_indices=None, estimate_labels='xhat[{i}]', covariance_labels='P[{i},{j}]', measurement_labels=None, control_labels=None, - inputs=None, outputs=None, states=None, **kwargs): + inputs=None, outputs=None, states=None, symmetric_kwargs=None, **kwargs): r"""Create an I/O system implementing a linear quadratic estimator. This function creates an input/output system that implements a @@ -410,6 +416,9 @@ def create_estimator_iosystem( name : string, optional System name (used for specifying signals). If unspecified, a generic name 'sys[id]' is generated with a unique integer id. + symmetric_kwargs : dict, optional + Keyword arguments passed to `scipy.linalg.issymmetric` or + `scipy.linalg.ishermitian`. Notes ----- @@ -492,7 +501,7 @@ def create_estimator_iosystem( if P0 is None: # Initialize P0 to the steady state value _, P0, _ = lqe(A, G, C, QN, RN) - P0 = _check_shape(P0, sys.nstates, sys.nstates, symmetric=True, name='P0') + P0 = _check_shape(P0, sys.nstates, sys.nstates, symmetric=True, name='P0', symmetric_kwargs=symmetric_kwargs) # Figure out the labels to use estimate_labels = _process_labels( diff --git a/control/tests/bdalg_test.py b/control/tests/bdalg_test.py index cec10f904..63d3c42cf 100644 --- a/control/tests/bdalg_test.py +++ b/control/tests/bdalg_test.py @@ -143,6 +143,31 @@ def testSSSS2(self, tsys): 0.142857142857143, -0.571428571428571, 0.857142857142857]]) np.testing.assert_array_almost_equal(ans2.D, [[-0.285714285714286]]) + def test_mimo_ss_scalar_feedback(self): + """MIMO state space system with scalar feedback block.""" + sys_static = StateSpace([], [], [], [[1, 0], [0, 2]]) + ans1 = feedback(sys_static) + ans2 = feedback(sys_static, np.eye(2)) + np.testing.assert_array_almost_equal(ans1.D, ans2.D) + + ans3 = feedback(sys_static, 2) + ans4 = feedback(sys_static, 2 * np.eye(2)) + np.testing.assert_array_almost_equal(ans3.D, ans4.D) + + sys_dynamic = StateSpace( + [[-1, 0], [0, -2]], [[1, 0], [0, 1]], + [[1, 0], [0, 1]], [[0, 0], [0, 0]]) + ans5 = feedback(sys_dynamic) + ans6 = feedback(sys_dynamic, np.eye(2)) + np.testing.assert_array_almost_equal(ans5.A, ans6.A) + np.testing.assert_array_almost_equal(ans5.B, ans6.B) + np.testing.assert_array_almost_equal(ans5.C, ans6.C) + np.testing.assert_array_almost_equal(ans5.D, ans6.D) + + sys_nonsquare = StateSpace([], [], [], [[1, 2, 3], [4, 5, 6]]) + with pytest.raises(ValueError, match="compatible inputs/outputs"): + feedback(sys_nonsquare) + def testSSTF(self, tsys): """State space system with transfer function feedback block.""" diff --git a/control/tests/ctrlplot_test.py b/control/tests/ctrlplot_test.py index bf8a075ae..a6d248bc0 100644 --- a/control/tests/ctrlplot_test.py +++ b/control/tests/ctrlplot_test.py @@ -748,8 +748,7 @@ def test_pole_zero_subplots(savefig=False): sys2 = ct.tf([1, 0.2], [1, 1, 3, 1, 1], name='sys2') ct.root_locus_plot([sys1, sys2], ax=ax_array[0, 0]) cplt = ct.root_locus_plot([sys1, sys2], ax=ax_array[1, 0]) - with pytest.warns(UserWarning, match="Tight layout not applied"): - cplt.set_plot_title("Root locus plots (w/ specified axes)") + cplt.set_plot_title("Root locus plots (w/ specified axes)") if savefig: plt.savefig("ctrlplot-pole_zero_subplots.png") diff --git a/control/tests/discrete_test.py b/control/tests/discrete_test.py index 7296c0f31..0bd3fda7c 100644 --- a/control/tests/discrete_test.py +++ b/control/tests/discrete_test.py @@ -561,3 +561,36 @@ def test_c2d_matched(num, den, dt, method): for czero in sys_ct.zeros(): zzero = zzeros[(np.abs(zzeros - cmath.exp(czero * dt))).argmin()] assert cmath.isclose(cmath.exp(czero * dt), zzero) + + +@pytest.mark.parametrize("num, den", [ + ([1.], [1., 0.]), # integrator (pole at s = 0) + ([1.], [1., 0., 0.]), # double integrator + ([2., 5.], [1., 0.]), # PI controller + ([1.], [1., 1., 0.]), # type 1 plant, 1/(s(s+1)) + ([1., 0.], [1., 2., 5.]), # differentiator (zero at s = 0) + ([2., 0., 0.], [1., 3., 3., 1.]), # double zero at s = 0 + ([1., 0.], [1., 0., 0.]), # zero and pole at s = 0 +]) +@pytest.mark.parametrize("dt", [0.1, 0.5]) +def test_c2d_matched_origin(num, den, dt): + # A pole or zero at s = 0 (integrators, PI/PID, type-1/2 plants) used to + # give an all-NaN numerator: the DC-gain match divides by the vanishing + # 1 - z factor of the origin pole/zero (#950, #951). + sys_ct = ct.tf(num, den) + sys_dt = ct.sample_system(sys_ct, dt, method='matched') + assert np.all(np.isfinite(sys_dt.num[0][0])) + assert np.all(np.isfinite(sys_dt.den[0][0])) + # the gain is matched just off the origin, so |G_d(e^jwT)| -> |G_c(jw)| + w = 1e-3 / dt + assert np.isclose(abs(sys_ct(1j * w)), + abs(sys_dt(cmath.exp(1j * w * dt))), rtol=1e-4) + + +@pytest.mark.parametrize("dt", [0.1, 0.5, 2]) +@pytest.mark.parametrize("k", [1, 2, 3]) +def test_c2d_matched_integrator(k, dt): + # matched discretization of 1/s**k is the textbook Ts**k / (z - 1)**k + sys_dt = ct.tf([1.], [1.] + [0.] * k).sample(dt, method='matched') + np.testing.assert_allclose(sys_dt.num[0][0], [dt**k]) + np.testing.assert_allclose(sys_dt.den[0][0], np.poly([1.] * k)) diff --git a/control/tests/interconnect_test.py b/control/tests/interconnect_test.py index ccce76f34..e725b29f6 100644 --- a/control/tests/interconnect_test.py +++ b/control/tests/interconnect_test.py @@ -432,6 +432,36 @@ def test_linear_interconnect(): outlist=['plant.y'], outputs='y') assert clsys.syslist[0].name == 'ctrl' + +def test_interconnect_zero_input_one_output(): + plant = ct.ss( + [[1, 1], [0, -2]], + [[0], [1]], + [[1, 0]], + [[0]], + inputs=['u'], + outputs=['y'], + name='plant', + dt=True, + ) + controller = ct.ss( + [[2.25, 1], [-5, -0.5]], + [[-1.25], [4.5]], + [[-0.5, 1.5]], + [[0]], + inputs=['y'], + outputs=['u'], + name='controller', + dt=True, + ) + + sys = ct.interconnect([plant, controller], inplist=None, outlist=['y']) + + assert sys.ninputs == 0 + assert sys.noutputs == 1 + assert sys.D.shape == (1, 0) + + @pytest.mark.parametrize( "connections, inplist, outlist, inputs, outputs", [ pytest.param( diff --git a/control/tests/mateqn_test.py b/control/tests/mateqn_test.py index 77bf553bf..d2cf7b2bf 100644 --- a/control/tests/mateqn_test.py +++ b/control/tests/mateqn_test.py @@ -39,7 +39,7 @@ import pytest from scipy.linalg import eigvals, solve -from control.mateqn import lyap, dlyap, care, dare +from control.mateqn import lyap, dlyap, care, dare, _is_symmetric from control.exception import ControlArgument, ControlDimension @@ -90,19 +90,22 @@ def test_lyap_sylvester(self, method): X_scipy = lyap(A, B, C, method='scipy') assert_array_almost_equal(X_scipy, X) - @pytest.mark.slycot - def test_lyap_g(self): + @pytest.mark.parametrize('method', + ['scipy', + pytest.param('slycot', marks=pytest.mark.slycot)]) + def test_lyap_g(self, method): A = array([[-1, 2], [-3, -4]]) Q = array([[3, 1], [1, 1]]) E = array([[1, 2], [2, 1]]) - X = lyap(A, Q, None, E) + X = lyap(A, Q, None, E, method=method) # print("The solution obtained is ", X) assert_array_almost_equal(A @ X @ E.T + E @ X @ A.T + Q, zeros((2,2))) - # Make sure that trying to solve with SciPy generates an error - with pytest.raises(ControlArgument, match="'scipy' not valid"): - X = lyap(A, Q, None, E, method='scipy') + # Compare methods + if method == 'slycot': + X_scipy = lyap(A, Q, None, E, method='scipy') + assert_array_almost_equal(X_scipy, X) @pytest.mark.parametrize('method', ['scipy', @@ -125,39 +128,73 @@ def test_dlyap(self, method): X_scipy = dlyap(A,Q, method='scipy') assert_array_almost_equal(X_scipy, X) - @pytest.mark.slycot - def test_dlyap_g(self): + @pytest.mark.parametrize('method', + ['scipy', + pytest.param('slycot', marks=pytest.mark.slycot)]) + def test_dlyap_g(self, method): A = array([[-0.6, 0],[-0.1, -0.4]]) Q = array([[3, 1],[1, 1]]) E = array([[1, 1],[2, 1]]) - X = dlyap(A, Q, None, E) + X = dlyap(A, Q, None, E, method=method) # print("The solution obtained is ", X) assert_array_almost_equal(A @ X @ A.T - E @ X @ E.T + Q, zeros((2,2))) - # Make sure that trying to solve with SciPy generates an error - with pytest.raises(ControlArgument, match="'scipy' not valid"): - X = dlyap(A, Q, None, E, method='scipy') + # Compare methods + if method == 'slycot': + X_scipy = dlyap(A, Q, None, E, method='scipy') + assert_array_almost_equal(X_scipy, X) - @pytest.mark.slycot - def test_dlyap_sylvester(self): + @pytest.mark.parametrize('method', + ['scipy', + pytest.param('slycot', marks=pytest.mark.slycot)]) + def test_dlyap_sylvester(self, method): A = 5 B = array([[4, 3], [4, 3]]) C = array([2, 1]) - X = dlyap(A,B,C) + X = dlyap(A, B, C, method=method) # print("The solution obtained is ", X) assert_array_almost_equal(A * X @ B.T - X + C, zeros((1,2))) A = array([[2, 1], [1, 2]]) B = array([[1, 2], [0.5, 0.1]]) C = array([[1, 0], [0, 1]]) - X = dlyap(A, B, C) + X = dlyap(A, B, C, method=method) # print("The solution obtained is ", X) assert_array_almost_equal(A @ X @ B.T - X + C, zeros((2,2))) - # Make sure that trying to solve with SciPy generates an error - with pytest.raises(ControlArgument, match="'scipy' not valid"): - X = dlyap(A, B, C, method='scipy') + # Compare methods + if method == 'slycot': + X_scipy = dlyap(A, B, C, method='scipy') + assert_array_almost_equal(X_scipy, X) + + @pytest.mark.parametrize("cdlyap", [lyap, dlyap]) + def test_lyap_g_singular_E_scipy(self, cdlyap): + """Generalized Lyapunov with singular E raises on scipy path""" + A = array([[-1, 2], [-3, -4]]) + Q = array([[3, 1], [1, 1]]) + E = array([[1, 2], [2, 4]]) # singular + with pytest.raises(ControlArgument, match="E to be nonsingular"): + cdlyap(A, Q, None, E, method='scipy') + + @pytest.mark.parametrize("cdlyap", [lyap, dlyap]) + def test_lyap_g_ill_conditioned_E_scipy(self, cdlyap): + """Generalized Lyapunov with ill-conditioned E warns on scipy path""" + A = array([[-1, 2], [-3, -4]]) + Q = array([[3, 1], [1, 1]]) + E = array([[1, 1], [1, 1 + 1e-12]]) # nonsingular, cond ~ 4e12 + with pytest.warns(UserWarning, match="ill-conditioned"): + cdlyap(A, Q, None, E, method='scipy') + + def test_dlyap_sylvester_singular_scipy(self): + """Discrete Sylvester with an eigenvalue product of 1 is singular""" + # eig(A) = {2, 3}, eig(Q) = {0.5, 0.7}; the product 2 * 0.5 = 1 + # makes the discrete-time Sylvester operator singular + A = array([[2., 0.], [0., 3.]]) + Q = array([[0.5, 0.], [0., 0.7]]) + C = array([[1., 0.], [0., 1.]]) + with pytest.raises(ControlArgument, match="singular"): + dlyap(A, Q, C, method='scipy') @pytest.mark.parametrize('method', ['scipy', @@ -274,7 +311,6 @@ def test_dare(self, method): lam = eigvals(A - B @ G) assert_array_less(abs(lam), 1.0) - @pytest.mark.slycot def test_dare_compare(self): A = np.array([[-0.6, 0], [-0.1, -0.4]]) Q = np.array([[2, 1], [1, 0]]) @@ -430,3 +466,25 @@ def test_raise(self): cdare(A, B, Qfs, R, S, E) with pytest.raises(ControlArgument): cdare(A, B, Q, Rfs, S, E) + + def test_is_symmetric_scale_aware(self): + M = np.array([ + [1e8, 1e8], + [1e8 + 1e-8, 1e8] + ]) + assert not _is_symmetric(M) + assert _is_symmetric(M,symmetric_kwargs={"rtol": 1e-12},) + + def test_is_symmetric_rejects_asymmetric(self): + M = np.array([ + [1., 2.], + [5., 1.] + ]) + assert not _is_symmetric(M) + + def test_is_symmetric_complex_hermitian(self): + M = np.array([ + [1., 2. + 1.j], + [2. - 1.j, 3.] + ]) + assert _is_symmetric(M) diff --git a/control/tests/nyquist_test.py b/control/tests/nyquist_test.py index 243a291d2..6beb68ef2 100644 --- a/control/tests/nyquist_test.py +++ b/control/tests/nyquist_test.py @@ -372,6 +372,29 @@ def test_nyquist_indent_im(): assert _Z(sys) == response.count + _P(sys) +def test_nyquist_indent_near_imaginary_axis(): + """Test indent direction for poles near the imaginary axis.""" + sys = ct.zpk([-10, -1], [-100, 0.001+1j, 0.001-1j], 10) + omega = np.linspace(0, 2, 21) + + _, contour_default = ct.nyquist_response( + sys, omega, indent_radius=0.1, return_contour=True, + warn_encirclements=False) + _, contour_right = ct.nyquist_response( + sys, omega, indent_radius=0.1, indent_direction='right', + return_contour=True, warn_encirclements=False) + _, contour_left = ct.nyquist_response( + sys, omega, indent_radius=0.1, indent_direction='left', + return_contour=True, warn_encirclements=False) + + # The pole near +1j has a small positive real part, so the default + # behavior indents to the left. Explicit directions override this. + pole_index = np.argmin(np.abs(contour_default.imag - 1)) + assert contour_default[pole_index].real < 0 + assert contour_right[pole_index].real > 0 + assert contour_left[pole_index].real < 0 + + def test_nyquist_exceptions(): # MIMO not implemented sys = ct.rss(2, 2, 2) diff --git a/control/tests/statefbk_test.py b/control/tests/statefbk_test.py index d0230fb18..c207ab891 100644 --- a/control/tests/statefbk_test.py +++ b/control/tests/statefbk_test.py @@ -1233,6 +1233,39 @@ def test_refgain_pattern(ninputs, Kf): np.testing.assert_almost_equal(clsys.D[:sys.nstates, :], manual.D) +def test_refgain_pattern_integral_action(): + sys = ct.ss( + [[0.0, 1.0], [-2.0, -3.0]], + [[0.0, 1.0], [1.0, 0.0]], + np.eye(2), + np.zeros((2, 2)), + ) + Kp = np.array([[1.0, 2.0], [3.0, 4.0]]) + Ki = np.array([[5.0], [6.0]]) + K = np.hstack([Kp, Ki]) + Kf = np.diag([7.0, 8.0]) + C_int = np.array([[1.0, 0.0]]) + + ctrl, clsys = ct.create_statefbk_iosystem( + sys, K, Kf, integral_action=C_int, feedfwd_pattern='refgain') + + np.testing.assert_array_equal(ctrl.A, np.zeros((1, 1))) + np.testing.assert_array_equal(ctrl.B, np.hstack([-np.eye(1, 2), C_int])) + np.testing.assert_array_equal(ctrl.C, -Ki) + np.testing.assert_array_equal(ctrl.D, np.hstack([Kf, -Kp])) + + np.testing.assert_array_equal( + clsys.A, np.block([[sys.A - sys.B @ Kp, -sys.B @ Ki], + [C_int, np.zeros((1, 1))]])) + np.testing.assert_array_equal( + clsys.B, np.vstack([sys.B @ Kf, -np.eye(1, sys.ninputs)])) + np.testing.assert_array_equal( + clsys.C, np.block([[np.eye(sys.nstates), np.zeros((sys.nstates, 1))], + [-Kp, -Ki]])) + np.testing.assert_array_equal( + clsys.D, np.vstack([np.zeros((sys.nstates, sys.ninputs)), Kf])) + + def test_create_statefbk_errors(): sys = ct.rss(2, 2, 1, strictly_proper=True) sys.C = np.eye(2) diff --git a/control/tests/stochsys_test.py b/control/tests/stochsys_test.py index 20e799643..55a0c00b8 100644 --- a/control/tests/stochsys_test.py +++ b/control/tests/stochsys_test.py @@ -35,6 +35,54 @@ def test_LQE(method): L, P, poles = lqe(A, G, C, QN, RN, method=method) check_LQE(L, P, poles, G, QN, RN) +def test_lqe_symmetric_kwargs(): + A = np.array([ + [-1., 0.], + [0., -2.] + ]) + G = np.eye(2) + C = np.eye(2) + QN = np.array([ + [1., 0.2], + [0.2 + 1e-15, 1.] + ]) + RN = np.eye(2) + + # Exact symmetry check should fail + with pytest.raises(ControlArgument, match="symmetric"): + lqe(A, G, C, QN, RN, method="scipy") + + # Passing rtol should allow the nearly symmetric matrix + lqe( + A, G, C, QN, RN, + method="scipy", + symmetric_kwargs={"rtol": 1e-12}, + ) + +def test_dlqe_symmetric_kwargs(): + A = np.array([ + [0.5, 0.], + [0., 0.4] + ]) + G = np.eye(2) + C = np.eye(2) + QN = np.array([ + [1., 0.2], + [0.2 + 1e-15, 1.] + ]) + RN = np.eye(2) + + # Exact symmetry check should fail + with pytest.raises(ControlArgument, match="symmetric"): + dlqe(A, G, C, QN, RN, method="scipy") + + # Passing rtol should allow the nearly symmetric matrix + dlqe( + A, G, C, QN, RN, + method="scipy", + symmetric_kwargs={"rtol": 1e-12}, + ) + @pytest.mark.parametrize("cdlqe", [lqe, dlqe]) def test_lqe_call_format(cdlqe): # Create a random state space system for testing diff --git a/control/tests/timeresp_test.py b/control/tests/timeresp_test.py index 16ee01a3d..ba76c2b91 100644 --- a/control/tests/timeresp_test.py +++ b/control/tests/timeresp_test.py @@ -2,6 +2,7 @@ from copy import copy from math import isclose +import warnings import numpy as np import pytest @@ -827,6 +828,14 @@ def test_auto_generated_time_vector_tfinal(self, tfsys, tfinal): T = _default_time_vector(tfsys) np.testing.assert_allclose(T[-1], tfinal, atol=0.5*ideal_dt) + def test_discrete_time_negative_one_settling(self): + #system with -1 pole + TF = TransferFunction([1,3,0],[1,3,2], dt=True) + with warnings.catch_warnings(): + warnings.simplefilter("error") + impulse_response(TF) + + @pytest.mark.parametrize("wn, zeta", [(10, 0), (100, 0), (100, .1)]) def test_auto_generated_time_vector_dt_cont1(self, wn, zeta): """Confirm a TF with a natural frequency of wn rad/s gets a diff --git a/control/timeresp.py b/control/timeresp.py index 3c49d213e..1d252b270 100644 --- a/control/timeresp.py +++ b/control/timeresp.py @@ -2172,7 +2172,7 @@ def _ideal_tfinal_and_dt(sys, is_step=True): m_z = np.abs(p) < sqrt_eps p = p[~m_z] # Negative reals- treated as oscillatory mode - m_nr = (p.real < 0) & (np.abs(p.imag) < sqrt_eps) + m_nr = (p.real < 0) & (np.abs(p.imag) < sqrt_eps) & (np.abs(p.real+1) > sqrt_eps) p_nr, p = p[m_nr], p[~m_nr] if p_nr.size > 0: t_emp = np.max(log_decay_percent / np.abs((np.log(p_nr)/dt).real)) diff --git a/control/xferfcn.py b/control/xferfcn.py index 8e51534d7..ad9ea0554 100644 --- a/control/xferfcn.py +++ b/control/xferfcn.py @@ -1334,23 +1334,40 @@ def _c2d_matched(sysC, Ts, **kwargs): raise ControlMIMONotImplemented("Not implemented for MIMO systems") # Pole-zero match method of continuous to discrete time conversion - szeros, spoles, _ = tf2zpk(sysC.num[0][0], sysC.den[0][0]) + szeros, spoles, sgain = tf2zpk(sysC.num[0][0], sysC.den[0][0]) zzeros = [0] * len(szeros) zpoles = [0] * len(spoles) - pregainnum = [0] * len(szeros) - pregainden = [0] * len(spoles) + # The gain is matched at the origin (z = 1). A pole or zero at s = 0 maps + # to z = 1, so its 1 - z factor vanishes and matching the DC gain there is + # 0/0 or inf/inf -> a NaN numerator for integrators, PI/PID and other + # type-1/type-2 systems. Keep the origin factors out of the gain product + # and restore their scaling through the z - 1 ~ s*Ts limit, which recovers + # Ts/(z - 1) for 1/s, Ts**2/(z - 1)**2 for 1/s**2, etc. (completes #951). + origin_zeros = origin_poles = 0 + numgain, dengain = sgain, 1.0 + pregainnum = pregainden = 1.0 for idx, s in enumerate(szeros): - sTs = s * Ts - z = exp(sTs) - zzeros[idx] = z - pregainnum[idx] = 1 - z + zzeros[idx] = exp(s * Ts) + if s == 0: + origin_zeros += 1 + else: + numgain *= -s + pregainnum *= 1 - zzeros[idx] for idx, s in enumerate(spoles): - sTs = s * Ts - z = exp(sTs) - zpoles[idx] = z - pregainden[idx] = 1 - z - zgain = np.multiply.reduce(pregainnum) / np.multiply.reduce(pregainden) - gain = sysC.dcgain() / zgain.real + zpoles[idx] = exp(s * Ts) + if s == 0: + origin_poles += 1 + else: + dengain *= -s + pregainden *= 1 - zpoles[idx] + zgain = pregainnum / pregainden + if origin_zeros or origin_poles: + # DC gain of the system with the origin factors divided out, rescaled + # by Ts**(origin poles - origin zeros) from the z - 1 ~ s*Ts limit + gain = (numgain / dengain).real \ + * Ts**(origin_poles - origin_zeros) / zgain.real + else: + gain = sysC.dcgain() / zgain.real sysDnum, sysDden = zpk2tf(zzeros, zpoles, gain) return TransferFunction(sysDnum, sysDden, Ts, **kwargs) diff --git a/doc/intro.rst b/doc/intro.rst index 0054bb668..22eb6d5df 100644 --- a/doc/intro.rst +++ b/doc/intro.rst @@ -190,5 +190,5 @@ This documentation has a number of notional conventions and functionality: .. doctest:: >>> sys = ct.tf([1], [1, 0.5, 1]) - >>> ct.bandwidth(sys) - np.float64(1.4839084518312828) + >>> ct.bandwidth(sys) # doctest: +ELLIPSIS + np.float64(1.4839084518312...)