From 0ef95a3336bcad3baa401a6505b160090efe053b Mon Sep 17 00:00:00 2001 From: marko1olo Date: Mon, 8 Jun 2026 10:09:12 +0400 Subject: [PATCH] Preserve complex StateSpace matrices --- control/statesp.py | 3 ++- control/tests/statesp_test.py | 18 +++++++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/control/statesp.py b/control/statesp.py index 65529b99d..edde5c411 100644 --- a/control/statesp.py +++ b/control/statesp.py @@ -2302,7 +2302,8 @@ def _ssmatrix(data, axis=1, square=None, rows=None, cols=None, name=None): name = "" if name is None else " " + name # Convert the data into an array (always making a copy) - arr = np.array(data, dtype=float) + dtype = complex if np.iscomplexobj(data) else float + arr = np.array(data, dtype=dtype) ndim = arr.ndim shape = arr.shape diff --git a/control/tests/statesp_test.py b/control/tests/statesp_test.py index 9b3c677fe..9c38135d9 100644 --- a/control/tests/statesp_test.py +++ b/control/tests/statesp_test.py @@ -8,6 +8,7 @@ """ import operator +import warnings import numpy as np import pytest @@ -136,7 +137,6 @@ def test_constructor(self, sys322ABCD, dt, argfun): ((np.ones((3, 3)), np.ones((3, 2)), np.ones((2, 3)), np.ones((2, 3))), ValueError, r"Incompatible dimensions of D matrix; expected \(2, 2\)"), - (([1j], 2, 3, 0), TypeError, "real number, not 'complex'"), ]) def test_constructor_invalid(self, args, exc, errmsg): """Test invalid input to StateSpace() constructor""" @@ -146,6 +146,22 @@ def test_constructor_invalid(self, args, exc, errmsg): with pytest.raises(exc, match=errmsg): ss(*args) + def test_constructor_complex_matrices(self): + """Test complex-valued matrices in StateSpace() constructor""" + A = np.array([[1 + 1j, 2 - 3j], [3 + 2j, 4 - 1j]]) + B = np.array([[1 - 2j], [3 + 4j]]) + C = np.array([[5 + 6j, 7 - 8j]]) + D = np.array([[9 + 10j]]) + + with warnings.catch_warnings(): + warnings.simplefilter("error") + sys = StateSpace(A, B, C, D) + + np.testing.assert_allclose(sys.A, A) + np.testing.assert_allclose(sys.B, B) + np.testing.assert_allclose(sys.C, C) + np.testing.assert_allclose(sys.D, D) + def test_constructor_warns(self, sys322ABCD): """Test ambiguos input to StateSpace() constructor""" with pytest.warns(UserWarning, match="received multiple dt"):