From 27154c24ed2d20d54f2bfe964ec2b7c3220a0a63 Mon Sep 17 00:00:00 2001 From: Juhan Oskar Hennoste Date: Mon, 19 Jan 2026 21:18:06 +0200 Subject: [PATCH 01/21] Correct timedata doc comment for phase plot functions --- control/phaseplot.py | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/control/phaseplot.py b/control/phaseplot.py index cf73d62a0..deaa65636 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 From 320d01a325670e88da0d16aad8f6843577425629 Mon Sep 17 00:00:00 2001 From: marko1olo Date: Sat, 6 Jun 2026 08:33:07 +0400 Subject: [PATCH 02/21] Fix zero-input interconnect D matrix shape Preserve explicitly shaped empty state-space matrices so linearized interconnections with zero inputs and nonzero outputs keep a (noutputs, 0) D matrix. Co-authored-by: OpenAI Codex --- control/statesp.py | 8 ++++---- control/tests/interconnect_test.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/control/statesp.py b/control/statesp.py index 65529b99d..16981e62b 100644 --- a/control/statesp.py +++ b/control/statesp.py @@ -2295,7 +2295,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 +2310,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/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( From 820514dfc616ce2682abd5d7fbf15b9251390706 Mon Sep 17 00:00:00 2001 From: marko1olo Date: Sun, 7 Jun 2026 06:35:12 +0400 Subject: [PATCH 03/21] fix(nyquist): honor explicit indent direction Preserve automatic near-axis indentation when no direction is passed, but let explicit left/right override pole-side selection for poles within the indent radius. Fixes #1194 --- control/freqplot.py | 19 +++++++++++++++++-- control/tests/nyquist_test.py | 23 +++++++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) 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/tests/nyquist_test.py b/control/tests/nyquist_test.py index 243a291d2..8f42e7430 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.tf([1, 11, 10], [0.01, 1, 0.01, 1]) + 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) From b6713b888c29ff8080041b9467aee403a6affaa7 Mon Sep 17 00:00:00 2001 From: marko1olo Date: Mon, 8 Jun 2026 12:10:10 +0400 Subject: [PATCH 04/21] Fix MIMO scalar state-space feedback --- control/statesp.py | 2 ++ control/tests/bdalg_test.py | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/control/statesp.py b/control/statesp.py index 65529b99d..ee61bf9be 100644 --- a/control/statesp.py +++ b/control/statesp.py @@ -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 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.""" From 7d5019e0b31f7f9f1099808d15cedfbaf01a0a56 Mon Sep 17 00:00:00 2001 From: UbeenII Date: Sat, 16 May 2026 22:13:59 +0100 Subject: [PATCH 05/21] Fix negative real handling for tfinal of discrete-time systems Squash-merge of https://github.com/python-control/python-control/pull/1216 Fixes #1204 --- control/tests/timeresp_test.py | 9 +++++++++ control/timeresp.py | 2 +- 2 files changed, 10 insertions(+), 1 deletion(-) 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)) From 0bce6835d1b687302a467ec295a266b439910b30 Mon Sep 17 00:00:00 2001 From: "Scott C. Livingston" Date: Sat, 25 Jul 2026 00:12:33 -0700 Subject: [PATCH 06/21] DOC: follow NumPy policy for contributions that use "AI" --- README.rst | 4 ++++ 1 file changed, 4 insertions(+) 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 From ae4915c4ece5f417fa514dadeb0d30ab412a28aa Mon Sep 17 00:00:00 2001 From: Richard Murray Date: Sat, 8 Aug 2026 10:09:58 -0400 Subject: [PATCH 07/21] change unsupported "shape =" to reshape() to avoid warnings --- control/descfcn.py | 3 +-- control/statesp.py | 6 +++--- 2 files changed, 4 insertions(+), 5 deletions(-) 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/statesp.py b/control/statesp.py index 89698bb50..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") From 3b70cb41b5d41ed4aa4da9f2db2eb3d83c3ffdcd Mon Sep 17 00:00:00 2001 From: Richard Murray Date: Sat, 8 Aug 2026 10:10:36 -0400 Subject: [PATCH 08/21] remove unneeded warning check in ctrlplot_test() --- control/tests/ctrlplot_test.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) 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") From 40860d566dcd2763ea2dd587f647a411fd09958a Mon Sep 17 00:00:00 2001 From: Richard Murray Date: Sat, 8 Aug 2026 11:44:55 -0400 Subject: [PATCH 09/21] place near imaginary poles in nyquist_test to fix signs --- control/tests/nyquist_test.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/control/tests/nyquist_test.py b/control/tests/nyquist_test.py index 8f42e7430..6beb68ef2 100644 --- a/control/tests/nyquist_test.py +++ b/control/tests/nyquist_test.py @@ -374,7 +374,7 @@ def test_nyquist_indent_im(): def test_nyquist_indent_near_imaginary_axis(): """Test indent direction for poles near the imaginary axis.""" - sys = ct.tf([1, 11, 10], [0.01, 1, 0.01, 1]) + sys = ct.zpk([-10, -1], [-100, 0.001+1j, 0.001-1j], 10) omega = np.linspace(0, 2, 21) _, contour_default = ct.nyquist_response( From 84b0d0fc155a1e49580a5dd4099c01646fceff2f Mon Sep 17 00:00:00 2001 From: Richard Murray Date: Sat, 8 Aug 2026 11:45:19 -0400 Subject: [PATCH 10/21] cast eigenvectors to real to avoid imaginary initial conditions --- control/phaseplot.py | 1 + 1 file changed, 1 insertion(+) diff --git a/control/phaseplot.py b/control/phaseplot.py index deaa65636..0fdb9922f 100644 --- a/control/phaseplot.py +++ b/control/phaseplot.py @@ -892,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: From c4f248cfd6ba05400cb94abec631eae27258b63e Mon Sep 17 00:00:00 2001 From: Richard Murray Date: Sat, 8 Aug 2026 11:54:44 -0400 Subject: [PATCH 11/21] cast singular values to real (fix doctest error) --- control/modelsimp.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 From 65d1d26d9e3566a0b7add83cdcd073f484fd29fa Mon Sep 17 00:00:00 2001 From: Richard Murray Date: Sat, 8 Aug 2026 12:13:21 -0400 Subject: [PATCH 12/21] use doctest ELLIPSIS for bandwidth() values to avoid ULP failures bandwidth() gets its value from a scipy.optimize.root_scalar bisection, so the last digit or two of the repr differs across scipy/BLAS builds. The full-precision literals matched locally but failed on GitHub. Truncate to ~14 significant digits with # doctest: +ELLIPSIS. This keeps the examples verified (unlike +SKIP, used elsewhere in the repo for platform-dependent output), and trim_doctest_flags (on by default) strips the flag comment from the rendered HTML. Also applied to the G1*G2 example, which has the same origin and had not failed yet. Verified with "make doctest" in doc/: 728 tests, 0 failures. Co-Authored-By: Claude Opus 5 --- control/lti.py | 8 ++++---- doc/intro.rst | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) 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/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...) From f80d9904e7719352b82be050f511265e6f9a97fa Mon Sep 17 00:00:00 2001 From: Vincent Gao Date: Tue, 21 Jul 2026 09:22:26 +0200 Subject: [PATCH 13/21] Fix matched c2d NaN for a pole or zero at the origin TransferFunction.sample(Ts, method='matched') (and c2d) returned an all-NaN numerator for any system with a pole or zero at s = 0 - integrators, PI/PID controllers, differentiators and other type-1/2 systems. The DC-gain match divides the continuous DC gain (inf for an origin pole, 0 for an origin zero) by a zgain that carries the same vanishing 1 - z factor, so the gain is 0/0 or inf/inf. Match the gain from the non-origin factors only and restore the origin scaling analytically through the z - 1 ~ s*Ts limit, which recovers the textbook Ts/(z - 1) for 1/s, Ts**2/(z - 1)**2 for 1/s**2, and so on. Finite-DC systems are byte-for-byte unchanged. Completes the gain fix from #950/#951. --- control/tests/discrete_test.py | 33 ++++++++++++++++++++++++++ control/xferfcn.py | 43 ++++++++++++++++++++++++---------- 2 files changed, 63 insertions(+), 13 deletions(-) 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/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) From 46081238fa775efcaf67816379112cf4b711dc0d Mon Sep 17 00:00:00 2001 From: Kangwon Lee <219608255+kwlee2025cpp@users.noreply.github.com> Date: Sun, 14 Jun 2026 03:55:44 +0900 Subject: [PATCH 14/21] Add scipy fallbacks for generalized Lyapunov and discrete Sylvester equations lyap and dlyap previously raised ControlArgument for method='scipy' (explicit, or auto-selected when slycot is absent) on three cases that SLICOT handles. Add pure scipy/numpy fallbacks for all three: - Generalized Lyapunov, continuous and discrete (E != I): congruence transform by inv(E) to a standard Lyapunov equation, then scipy's solve_continuous/discrete_lyapunov. Requires E nonsingular; SLICOT sg03ad (Penzl's generalized Schur method) also handles singular E and remains the method='slycot' path. A nonsingular-E failure raises a clear ControlArgument. Because the transform inverts E, an ill-conditioned E yields reduced accuracy; this now emits a UserWarning recommending method='slycot' (the continuous path was previously silent, while the discrete path warned only incidentally). - Discrete Sylvester (A X Q^T - X + C = 0): Bartels-Stewart method via complex Schur factors of A and Q^T with column-by-column triangular solves, O(n^3 + m^3), matching the Hessenberg-Schur cost of SLICOT sb04qd. Includes the solvability check that no eigenvalue pair of A and Q^T has product (almost) equal to 1. Also fix two incorrect slycot import-fallback aliases (sb0qmd -> sb04qd, sb04ad -> sg03ad) so the names resolve to None, not NameError, when slycot is absent; and correct the dlyap Notes, which described the scipy Sylvester path as a Kronecker O((nm)^3) solve (it is now Bartels-Stewart, O(n^3 + m^3)). Tests parametrize method=[None, 'scipy', 'slycot'] and cross-check that the scipy and slycot solutions agree, and cover the nonsingular-E requirement, the ill-conditioned-E warning, and the singular discrete-Sylvester case. Co-Authored-By: Claude Fable 5 Co-Authored-By: Claude Opus 4.8 --- control/mateqn.py | 137 +++++++++++++++++++++++++++++++++-- control/tests/mateqn_test.py | 76 ++++++++++++++----- 2 files changed, 185 insertions(+), 28 deletions(-) diff --git a/control/mateqn.py b/control/mateqn.py index 9d1349b0c..df25cd4db 100644 --- a/control/mateqn.py +++ b/control/mateqn.py @@ -47,15 +47,33 @@ 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 the inv(E) congruence transform will lose 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). SLICOT sg03ad + (method='slycot') avoids inverting E and is preferable in that case. + """ + 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 " + "method='scipy' generalized Lyapunov solution may have reduced " + "accuracy. Use method='slycot' (SLICOT sg03ad) for a more " + "robust solution.", UserWarning, stacklevel=3) + # # Lyapunov equation solvers lyap and dlyap # @@ -103,6 +121,21 @@ def lyap(A, Q, C=None, E=None, method=None): 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 also handles singular 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); method='slycot' does + not invert E and is preferable in that case. + + 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) @@ -162,8 +195,23 @@ def lyap(A, Q, C=None, E=None, method=None): _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; the SLICOT routine + # SG03AD used by method='slycot' (based on the generalized + # Schur method of Penzl (1998)) also handles singular E. + 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; " + "use method='slycot' (SLICOT sg03ad) for singular E") + _warn_ill_conditioned_E(E) + return sp.linalg.solve_continuous_lyapunov(At, -Qt) # Make sure we have access to the write Slycot routine try: @@ -229,6 +277,32 @@ def dlyap(A, Q, C=None, E=None, method=None): 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 also handles singular 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); method='slycot' does + not invert E and is preferable in that case. + + 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) @@ -279,8 +353,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) @@ -292,8 +398,23 @@ def dlyap(A, Q, C=None, E=None, method=None): _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; the SLICOT routine + # SG03AD used by method='slycot' (based on the generalized + # Schur method of Penzl (1998)) also handles singular E. + 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; " + "use method='slycot' (SLICOT sg03ad) for singular E") + _warn_ill_conditioned_E(E) + return sp.linalg.solve_discrete_lyapunov(At, Qt) # Solve the generalized Lyapunov equation by calling Slycot # function sg03ad diff --git a/control/tests/mateqn_test.py b/control/tests/mateqn_test.py index 77bf553bf..5cc34c2ab 100644 --- a/control/tests/mateqn_test.py +++ b/control/tests/mateqn_test.py @@ -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]]) From 89b2f686c1d504c8fb0c480d629e143514883f65 Mon Sep 17 00:00:00 2001 From: Kangwon Lee <219608255+kwlee2025cpp@users.noreply.github.com> Date: Fri, 26 Jun 2026 04:22:14 -0400 Subject: [PATCH 15/21] Correct SG03AD singular-E claim in lyap/dlyap docs The generalized-Lyapunov Notes, the scipy-path comments, and the nonsingular-E error messages stated that SLICOT SG03AD "also handles singular E". It does not: SG03AD factors the matrix pencil without inverting E (its advantage for a nonsingular but ill-conditioned E), but a truly singular (descriptor) E returns a degenerate-pair warning and is out of scope for both the scipy and slycot paths. Correct all six spots (continuous lyap and discrete dlyap) to say so. Co-Authored-By: Claude Opus 4.8 --- control/mateqn.py | 44 ++++++++++++++++++++++++++------------------ 1 file changed, 26 insertions(+), 18 deletions(-) diff --git a/control/mateqn.py b/control/mateqn.py index df25cd4db..ec2fd5c2f 100644 --- a/control/mateqn.py +++ b/control/mateqn.py @@ -125,11 +125,13 @@ def lyap(A, Q, C=None, E=None, method=None): ----- For the generalized Lyapunov equation, method='slycot' uses the SLICOT routine SG03AD, based on the generalized Schur method of - Penzl [1]_, which also handles singular 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); method='slycot' does - not invert E and is preferable in that case. + 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); method='slycot' does not invert E and is preferable in that + case. Both methods require E nonsingular; a truly singular + (descriptor) E is not currently handled by either. References ---------- @@ -200,16 +202,18 @@ def lyap(A, Q, C=None, E=None, method=None): # # (E^-1 A) X + X (E^-1 A)^T + E^-1 Q E^-T = 0 # - # This requires E to be nonsingular; the SLICOT routine - # SG03AD used by method='slycot' (based on the generalized - # Schur method of Penzl (1998)) also handles singular E. + # 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; " - "use method='slycot' (SLICOT sg03ad) for singular E") + "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) @@ -281,11 +285,13 @@ def dlyap(A, Q, C=None, E=None, method=None): ----- For the generalized Lyapunov equation, method='slycot' uses the SLICOT routine SG03AD, based on the generalized Schur method of - Penzl [1]_, which also handles singular 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); method='slycot' does - not invert E and is preferable in that case. + 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); method='slycot' does not invert E and is preferable 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 @@ -403,16 +409,18 @@ def dlyap(A, Q, C=None, E=None, method=None): # # (E^-1 A) X (E^-1 A)^T - X + E^-1 Q E^-T = 0 # - # This requires E to be nonsingular; the SLICOT routine - # SG03AD used by method='slycot' (based on the generalized - # Schur method of Penzl (1998)) also handles singular E. + # 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; " - "use method='slycot' (SLICOT sg03ad) for singular E") + "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) From 3f6dbac2a4793b8bad535cfe16321acaf72f35eb Mon Sep 17 00:00:00 2001 From: Kangwon Lee <219608255+kwlee2025cpp@users.noreply.github.com> Date: Mon, 29 Jun 2026 23:59:43 +0900 Subject: [PATCH 16/21] Correct ill-conditioned-E accuracy claim in lyap/dlyap The generalized-Lyapunov Notes and the _warn_ill_conditioned_E helper (its docstring and warning message) claimed method='slycot' is "preferable" / "more robust" than method='scipy' for ill-conditioned E. Benchmarking (scipy vs slycot, n=100, cond(E) swept 1 to 1e12 over 5 seeds) shows both methods lose accuracy at the same rate -- slycot is in fact 1.3-2x *less* accurate for cond(E) >= 1e4, never better. The generalized Lyapunov problem is itself ill-conditioned (about cond(E)^2) when E is, so no method beats that floor. Reword to say both degrade and slycot is not measurably more accurate, and drop the false "use method='slycot' for a more robust solution" line from the warning. Co-Authored-By: Claude Opus 4.8 --- control/mateqn.py | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/control/mateqn.py b/control/mateqn.py index ec2fd5c2f..b23e42def 100644 --- a/control/mateqn.py +++ b/control/mateqn.py @@ -58,21 +58,23 @@ def sb03md(n, C, A, U, dico, job='X', fact='N', trana='N', ldwork=None): def _warn_ill_conditioned_E(E): - """Warn that the inv(E) congruence transform will lose accuracy. + """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). SLICOT sg03ad - (method='slycot') avoids inverting E and is preferable in that case. + 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 " - "method='scipy' generalized Lyapunov solution may have reduced " - "accuracy. Use method='slycot' (SLICOT sg03ad) for a more " - "robust solution.", UserWarning, stacklevel=3) + 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 @@ -129,8 +131,10 @@ def lyap(A, Q, C=None, E=None, method=None): 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); method='slycot' does not invert E and is preferable in that - case. Both methods require E nonsingular; a truly singular + 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 @@ -289,8 +293,10 @@ def dlyap(A, Q, C=None, E=None, method=None): 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); method='slycot' does not invert E and is preferable in that - case. Both methods require E nonsingular; a truly singular + 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 From 2dabe33ccd4b9b9f3cf8fc54837fc183b09b86a4 Mon Sep 17 00:00:00 2001 From: Kangwon Lee <219608255+kwlee2025cpp@users.noreply.github.com> Date: Fri, 3 Jul 2026 06:45:12 +0900 Subject: [PATCH 17/21] Add benchmarks for scipy vs slycot matrix-equation fallbacks Add benchmarks/scipy_fallback_bench.py (asv) comparing the pure-scipy fallbacks with slycot for generalized Lyapunov (continuous and discrete) and discrete Sylvester, plus an accuracy-vs-cond(E) track for the generalized Lyapunov solution. slycot parameterizations are skipped when slycot is not installed. Requested in the PR #1234 review. Co-Authored-By: Claude Opus 4.8 --- benchmarks/scipy_fallback_bench.py | 161 +++++++++++++++++++++++++++++ 1 file changed, 161 insertions(+) create mode 100644 benchmarks/scipy_fallback_bench.py 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')) From 516ba2eb754185aad78da2f88b6c0de3d8403479 Mon Sep 17 00:00:00 2001 From: marko1olo Date: Thu, 13 Aug 2026 23:28:24 +0400 Subject: [PATCH 18/21] docs: clarify lqe and dlqe error covariance wording --- control/stochsys.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/control/stochsys.py b/control/stochsys.py index 756d83e13..22e2f738b 100644 --- a/control/stochsys.py +++ b/control/stochsys.py @@ -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: @@ -204,9 +204,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 ---------- From a82cdda8ea5208a23a1b3b2774c1a4fc3c8f2750 Mon Sep 17 00:00:00 2001 From: marko1olo Date: Sun, 7 Jun 2026 05:20:32 +0400 Subject: [PATCH 19/21] fix(statefbk): trim refgain integral feedthrough --- control/statefbk.py | 2 +- control/tests/statefbk_test.py | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) 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/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) From 067cf784c099037ef4c14a19797fda83297f9b25 Mon Sep 17 00:00:00 2001 From: Miku0214 <3496048030@qq.com> Date: Sun, 13 Sep 2026 17:15:19 +0800 Subject: [PATCH 20/21] use symmetry check from SciPy https://github.com/python-control/python-control/issues/1174 --- control/mateqn.py | 58 ++++++++++++++++++++-------------- control/stochsys.py | 21 ++++++++---- control/tests/mateqn_test.py | 24 +++++++++++++- control/tests/stochsys_test.py | 48 ++++++++++++++++++++++++++++ 4 files changed, 121 insertions(+), 30 deletions(-) diff --git a/control/mateqn.py b/control/mateqn.py index b23e42def..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, \ @@ -81,7 +81,7 @@ def _warn_ill_conditioned_E(E): # -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 @@ -117,6 +117,9 @@ 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 ------- @@ -169,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 @@ -197,7 +200,7 @@ 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': @@ -243,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 @@ -279,6 +282,9 @@ 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 ------- @@ -346,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 @@ -406,7 +412,7 @@ 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': @@ -449,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 @@ -484,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'. @@ -518,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: @@ -605,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. @@ -640,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'. @@ -674,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: @@ -740,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 @@ -773,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: @@ -785,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/stochsys.py b/control/stochsys.py index 22e2f738b..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). @@ -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). @@ -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/mateqn_test.py b/control/tests/mateqn_test.py index 5cc34c2ab..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 @@ -466,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/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 From bfe9380eedcfbc6e57c0a7117e77e633575e3a18 Mon Sep 17 00:00:00 2001 From: amino <49860149+aminoh@users.noreply.github.com> Date: Wed, 28 Oct 2026 05:05:01 +0200 Subject: [PATCH 21/21] removed duplicate words (#1262) --- control/frdata.py | 2 +- control/nlsys.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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/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