From 27f83e40fdf6f66340a559fff15295bec739b406 Mon Sep 17 00:00:00 2001 From: Anthony De Bortoli Date: Sat, 5 Jan 2019 20:44:20 +0100 Subject: [PATCH 1/2] [statesp.py] Fix pep8 warnings --- control/statesp.py | 95 +++++++++++++++++++++++----------------------- 1 file changed, 47 insertions(+), 48 deletions(-) diff --git a/control/statesp.py b/control/statesp.py index 172b392c0..b579f7e9e 100644 --- a/control/statesp.py +++ b/control/statesp.py @@ -10,7 +10,7 @@ # Python 3 compatibility (needs to go here) from __future__ import print_function -from __future__ import division # for _convertToStateSpace +from __future__ import division # for _convertToStateSpace """Copyright (c) 2010 by California Institute of Technology All rights reserved. @@ -166,9 +166,9 @@ def __init__(self, *args): if 0 == self.states: # static gain # matrix's default "empty" shape is 1x0 - A.shape = (0,0) - B.shape = (0,self.inputs) - C.shape = (self.outputs,0) + A.shape = (0, 0) + B.shape = (0, self.inputs) + C.shape = (self.outputs, 0) # Check that the matrix sizes are consistent. if self.states != A.shape[0]: @@ -200,13 +200,13 @@ def _remove_useless_states(self): # Search for useless states. for i in range(self.states): if (all(self.A[i, :] == zeros((1, self.states))) and - all(self.B[i, :] == zeros((1, self.inputs)))): + all(self.B[i, :] == zeros((1, self.inputs)))): useless.append(i) # To avoid duplicate indices in useless, jump to the next # iteration. continue if (all(self.A[:, i] == zeros((self.states, 1))) and - all(self.C[:, i] == zeros((self.outputs, 1)))): + all(self.C[:, i] == zeros((self.outputs, 1)))): useless.append(i) # Remove the useless states. @@ -227,9 +227,9 @@ def __str__(self): str += "C = " + self.C.__str__() + "\n\n" str += "D = " + self.D.__str__() + "\n" # TODO: replace with standard calls to lti functions - if (type(self.dt) == bool and self.dt is True): + if type(self.dt) == bool and self.dt is True: str += "\ndt unspecified\n" - elif (not (self.dt is None) and type(self.dt) != bool and self.dt > 0): + elif not (self.dt is None) and type(self.dt) != bool and self.dt > 0: str += "\ndt = " + self.dt.__str__() + "\n" return str @@ -262,20 +262,20 @@ def __add__(self, other): # Figure out the sampling time to use if self.dt is None and other.dt is not None: - dt = other.dt # use dt from second argument + dt = other.dt # use dt from second argument elif (other.dt is None and self.dt is not None) or \ (timebaseEqual(self, other)): - dt = self.dt # use dt from first argument + dt = self.dt # use dt from first argument else: raise ValueError("Systems have different sampling times") # Concatenate the various arrays A = concatenate(( concatenate((self.A, zeros((self.A.shape[0], - other.A.shape[-1]))),axis=1), + other.A.shape[-1]))), axis=1), concatenate((zeros((other.A.shape[0], self.A.shape[-1])), - other.A),axis=1) - ),axis=0) + other.A), axis=1) + ), axis=0) B = concatenate((self.B, other.B), axis=0) C = concatenate((self.C, other.C), axis=1) D = self.D + other.D @@ -319,21 +319,20 @@ def __mul__(self, other): but B has %i row(s)\n(output(s))." % (self.inputs, other.outputs)) # Figure out the sampling time to use - if (self.dt == None and other.dt != None): - dt = other.dt # use dt from second argument - elif (other.dt == None and self.dt != None) or \ - (timebaseEqual(self, other)): - dt = self.dt # use dt from first argument + if self.dt is None and other.dt is not None: + dt = other.dt # use dt from second argument + elif other.dt is None and self.dt is not None or timebaseEqual(self, other): + dt = self.dt # use dt from first argument else: raise ValueError("Systems have different sampling times") # Concatenate the various arrays A = concatenate( - (concatenate((other.A, zeros((other.A.shape[0], self.A.shape[1]))), - axis=1), - concatenate((self.B * other.C, self.A), axis=1)), axis=0) + (concatenate((other.A, zeros((other.A.shape[0], self.A.shape[1]))), + axis=1), + concatenate((self.B * other.C, self.A), axis=1)), axis=0) B = concatenate((other.B, self.B * other.D), axis=0) - C = concatenate((self.D * other.C, self.C),axis=1) + C = concatenate((self.D * other.C, self.C), axis=1) D = self.D * other.D return StateSpace(A, B, C, D, dt) @@ -497,7 +496,7 @@ def freqresp(self, omega): # kk+1 because enumerate starts at kk = 0. # but zero-th spot is already filled. - Gfrf[:, :, kk+1] = result[0] + self.D + Gfrf[:, :, kk + 1] = result[0] + self.D except ImportError: # Slycot unavailable. Fall back to horner. for kk, cmplx_freqs_kk in enumerate(cmplx_freqs): @@ -562,14 +561,14 @@ def feedback(self, other=1, sign=-1): # Check to make sure the dimensions are OK if (self.inputs != other.outputs) or (self.outputs != other.inputs): - raise ValueError("State space systems don't have compatible inputs/outputs for " - "feedback.") + raise ValueError("State space systems don't have compatible inputs/outputs for " + "feedback.") # Figure out the sampling time to use if self.dt is None and other.dt is not None: - dt = other.dt # use dt from second argument + dt = other.dt # use dt from second argument elif other.dt is None and self.dt is not None or timebaseEqual(self, other): - dt = self.dt # use dt from first argument + dt = self.dt # use dt from first argument else: raise ValueError("Systems have different sampling times") @@ -614,19 +613,18 @@ def minreal(self, tol=0.0): try: from slycot import tb01pd B = empty((self.states, max(self.inputs, self.outputs))) - B[:,:self.inputs] = self.B + B[:, :self.inputs] = self.B C = empty((max(self.outputs, self.inputs), self.states)) - C[:self.outputs,:] = self.C + C[:self.outputs, :] = self.C A, B, C, nr = tb01pd(self.states, self.inputs, self.outputs, self.A, B, C, tol=tol) - return StateSpace(A[:nr,:nr], B[:nr,:self.inputs], - C[:self.outputs,:nr], self.D) + return StateSpace(A[:nr, :nr], B[:nr, :self.inputs], + C[:self.outputs, :nr], self.D) except ImportError: raise TypeError("minreal requires slycot tb01pd") else: return StateSpace(self) - # TODO: add discrete time check def returnScipySignalLTI(self): """Return a list of a list of scipy.signal.lti objects. @@ -750,7 +748,7 @@ def dcgain(self): """ try: if self.isctime(): - gain = np.asarray(self.D-self.C.dot(np.linalg.solve(self.A, self.B))) + gain = np.asarray(self.D - self.C.dot(np.linalg.solve(self.A, self.B))) else: gain = self.horner(1) except LinAlgError: @@ -839,7 +837,7 @@ def _convertToStateSpace(sys, **kw): # The following Doesn't work due to inconsistencies in ltisys: # return StateSpace([[]], [[]], [[]], eye(outputs, inputs)) return StateSpace(0., zeros((1, inputs)), zeros((outputs, 1)), - sys * ones((outputs, inputs))) + sys * ones((outputs, inputs))) # If this is a matrix, try to create a constant feedthrough try: @@ -847,10 +845,11 @@ def _convertToStateSpace(sys, **kw): return StateSpace([], [], [], D) except Exception as e: print("Failure to assume argument is matrix-like in" \ - " _convertToStateSpace, result %s" % e) + " _convertToStateSpace, result %s" % e) raise TypeError("Can't convert given type to StateSpace system.") + # TODO: add discrete time option def _rss_generate(states, inputs, outputs, type): """Generate a random state space. @@ -876,13 +875,13 @@ def _rss_generate(states, inputs, outputs, type): # Check for valid input arguments. if states < 1 or states % 1: raise ValueError("states must be a positive integer. states = %g." % - states) + states) if inputs < 1 or inputs % 1: raise ValueError("inputs must be a positive integer. inputs = %g." % - inputs) + inputs) if outputs < 1 or outputs % 1: raise ValueError("outputs must be a positive integer. outputs = %g." % - outputs) + outputs) # Make some poles for A. Preallocate a complex array. poles = zeros(states) + zeros(states) * 0.j @@ -892,13 +891,13 @@ def _rss_generate(states, inputs, outputs, type): if rand() < pRepeat and i != 0 and i != states - 1: # Small chance of copying poles, if we're not at the first or last # element. - if poles[i-1].imag == 0: + if poles[i - 1].imag == 0: # Copy previous real pole. - poles[i] = poles[i-1] + poles[i] = poles[i - 1] i += 1 else: # Copy previous complex conjugate pair of poles. - poles[i:i+2] = poles[i-2:i] + poles[i:i + 2] = poles[i - 2:i] i += 2 elif rand() < pReal or i == states - 1: # No-oscillation pole. @@ -915,7 +914,7 @@ def _rss_generate(states, inputs, outputs, type): mag = rand() phase = 2. * math.pi * rand() poles[i] = complex(mag * cos(phase), mag * sin(phase)) - poles[i+1] = complex(poles[i].real, -poles[i].imag) + poles[i + 1] = complex(poles[i].real, -poles[i].imag) i += 2 # Now put the poles in A as real blocks on the diagonal. @@ -926,9 +925,9 @@ def _rss_generate(states, inputs, outputs, type): A[i, i] = poles[i].real i += 1 else: - A[i, i] = A[i+1, i+1] = poles[i].real - A[i, i+1] = poles[i].imag - A[i+1, i] = -poles[i].imag + A[i, i] = A[i + 1, i + 1] = poles[i].real + A[i, i + 1] = poles[i].imag + A[i + 1, i] = -poles[i].imag i += 2 # Finally, apply a transformation so that A is not block-diagonal. while True: @@ -970,7 +969,7 @@ def _rss_generate(states, inputs, outputs, type): # Convert a MIMO system to a SISO system # TODO: add discrete time check def _mimo2siso(sys, input, output, warn_conversion=False): - #pylint: disable=W0622 + # pylint: disable=W0622 """ Convert a MIMO system to a SISO system. (Convert a system with multiple inputs and/or outputs, to a system with a single input and output.) @@ -1010,7 +1009,7 @@ def _mimo2siso(sys, input, output, warn_conversion=False): "Selected output: {sel}, " "number of system outputs: {ext}." .format(sel=output, ext=sys.outputs)) - #Convert sys to SISO if necessary + # Convert sys to SISO if necessary if sys.inputs > 1 or sys.outputs > 1: if warn_conversion: warn("Converting MIMO system to SISO system. " @@ -1065,7 +1064,7 @@ def _mimo2simo(sys, input, warn_conversion=False): if sys.inputs > 1: if warn_conversion: warn("Converting MIMO system to SIMO system. " - "Only input {i} is used." .format(i=input)) + "Only input {i} is used.".format(i=input)) # $X = A*X + B*U # Y = C*X + D*U new_B = sys.B[:, input] From 7859f8ce93b0710056a3abafaa22fe7b5ea83648 Mon Sep 17 00:00:00 2001 From: Anthony De Bortoli Date: Sat, 5 Jan 2019 22:48:53 +0100 Subject: [PATCH 2/2] [statesp.py] Add a function checking consistency between statespace matrices --- control/exception.py | 4 +- control/statesp.py | 103 ++++++++++++++++++++++++++++ control/tests/statesp_test.py | 123 +++++++++++++++++++++------------- 3 files changed, 181 insertions(+), 49 deletions(-) diff --git a/control/exception.py b/control/exception.py index 2c4f29704..8a4ed155d 100644 --- a/control/exception.py +++ b/control/exception.py @@ -46,7 +46,9 @@ class ControlSlycot(Exception): class ControlDimension(Exception): """Raised when dimensions of system objects are not correct""" - pass + def __init__(self, error): + print("[Control] Dimension error.") + print(error) class ControlArgument(Exception): """Raised when arguments to a function are not correct""" diff --git a/control/statesp.py b/control/statesp.py index b579f7e9e..d9c9247e1 100644 --- a/control/statesp.py +++ b/control/statesp.py @@ -64,6 +64,7 @@ from .lti import LTI, timebase, timebaseEqual, isdtime from .xferfcn import _convert_to_transfer_function from copy import deepcopy +from .exception import ControlArgument, ControlDimension __all__ = ['StateSpace', 'ss', 'rss', 'drss', 'tf2ss', 'ssdata'] @@ -1330,3 +1331,105 @@ def ssdata(sys): """ ss = _convertToStateSpace(sys) return ss.A, ss.B, ss.C, ss.D + + +def consistent_dimensions(A=None, B=None, C=None, D=None): + """ + Return a boolean stating if dimensions of the state-space matrices are consistent. + + A state space representation should verify: + - A square matrix [n_states x n_states] + - B [n_states x n_inputs] + - C [n_outputs x n_states] + - D [n_outputs x n_inputs] + Parameters + ---------- + A: ndarray - optional + State space system matrix + B: ndarray - optional + State space input matrix + C: ndarray - optional + State space output matrix + D: ndarray - optional + State space feedthrough matrix + + Returns + ------- + consistency: boolean + True if state space input matrices have consistent dimensions + False otherwise + """ + try: + if A is not None: + if not isinstance(A, np.ndarray): + raise ControlArgument("A is not a numpy array.") + else: + + n_row_A = A.shape[0] + n_col_A = A.shape[1] + if n_row_A != n_col_A: + raise ControlDimension("System matrix is not square. " + "(n_row_A: {} != n_col_A: {}).".format(n_row_A, n_col_A)) + else: + n_states = n_row_A + + if B is not None: + if not isinstance(B, np.ndarray): + raise ControlArgument("B is not a numpy array.") + + n_row_B = B.shape[0] + n_col_B = B.shape[1] + + try: + if n_row_B != n_states: + raise ControlDimension("Input matrix has not the right number of states. " + "(n_row_B: {} != n_states: {}).".format(n_row_B, n_states)) + else: + n_inputs = n_col_B + except NameError: + warn("State space representation has no System matrix.") + n_states = n_row_B + + if C is not None: + if not isinstance(C, np.ndarray): + raise ControlArgument("C is not a numpy array.") + + n_row_C = C.shape[0] + n_col_C = C.shape[1] + + try: + if n_col_C != n_states: + raise ControlDimension("Output matrix has not the right number of states. " + "(n_row_C: {} != n_states: {}).".format(n_row_C, + n_states)) + else: + n_outputs = n_row_C + except NameError: + warn("State space representation has no system matrix nor input matrix.") + + if D is not None: + if not isinstance(D, np.ndarray): + raise ControlArgument("D is not a numpy array.") + + n_row_D = D.shape[0] + n_col_D = D.shape[1] + + try: + if n_row_D != n_outputs: + raise ControlDimension("Feedthrough matrix has not the right number of " + "outputs. (n_row_D: {} != n_outputs: " + "{}).".format(n_row_D, n_outputs)) + except NameError: + warn("State space representation has no output matrix.") + + try: + if n_col_D != n_inputs: + raise ControlDimension("Feedthrough matrix has not the right number of inputs. " + "(n_row_D: {} != n_inputs: {}).".format(n_col_D, + n_inputs)) + except NameError: + warn("State space representation has no input matrix.") + except ControlDimension: + return False + + return True diff --git a/control/tests/statesp_test.py b/control/tests/statesp_test.py index 08a8cdc22..c36ff70e0 100644 --- a/control/tests/statesp_test.py +++ b/control/tests/statesp_test.py @@ -8,7 +8,7 @@ from numpy.linalg import solve from scipy.linalg import eigvals, block_diag from control import matlab -from control.statesp import StateSpace, _convertToStateSpace, tf2ss +from control.statesp import StateSpace, _convertToStateSpace, tf2ss, consistent_dimensions from control.xferfcn import TransferFunction, ss2tf from control.lti import evalfr from control.exception import slycot_check @@ -21,47 +21,47 @@ def setUp(self): """Set up a MIMO system to test operations on.""" # sys1: 3-states square system (2 inputs x 2 outputs) - A322 = [[-3., 4., 2.], - [-1., -3., 0.], - [2., 5., 3.]] - B322 = [[1., 4.], - [-3., -3.], - [-2., 1.]] - C322 = [[4., 2., -3.], - [1., 4., 3.]] - D322 = [[-2., 4.], - [0., 1.]] - self.sys322 = StateSpace(A322, B322, C322, D322) + self.A322 = np.array([[-3., 4., 2.], + [-1., -3., 0.], + [2., 5., 3.]]) + self.B322 = np.array([[1., 4.], + [-3., -3.], + [-2., 1.]]) + self.C322 = np.array([[4., 2., -3.], + [1., 4., 3.]]) + self.D322 = np.array([[-2., 4.], + [0., 1.]]) + self.sys322 = StateSpace(self.A322, self.B322, self.C322, self.D322) # sys1: 2-states square system (2 inputs x 2 outputs) - A222 = [[4., 1.], - [2., -3]] - B222 = [[5., 2.], - [-3., -3.]] - C222 = [[2., -4], - [0., 1.]] - D222 = [[3., 2.], - [1., -1.]] - self.sys222 = StateSpace(A222, B222, C222, D222) + self.A222 = np.array([[4., 1.], + [2., -3]]) + self.B222 = np.array([[5., 2.], + [-3., -3.]]) + self.C222 = np.array([[2., -4], + [0., 1.]]) + self.D222 = np.array([[3., 2.], + [1., -1.]]) + self.sys222 = StateSpace(self.A222, self.B222, self.C222, self.D222) # sys3: 6 states non square system (2 inputs x 3 outputs) - A623 = np.array([[1, 0, 0, 0, 0, 0], - [0, 1, 0, 0, 0, 0], - [0, 0, 3, 0, 0, 0], - [0, 0, 0, -4, 0, 0], - [0, 0, 0, 0, -1, 0], - [0, 0, 0, 0, 0, 3]]) - B623 = np.array([[0, -1], - [-1, 0], - [1, -1], - [0, 0], - [0, 1], - [-1, -1]]) - C623 = np.array([[1, 0, 0, 1, 0, 0], - [0, 1, 0, 1, 0, 1], - [0, 0, 1, 0, 0, 1]]) - D623 = np.zeros((3, 2)) - self.sys623 = StateSpace(A623, B623, C623, D623) + self.A623 = np.array([[1, 0, 0, 0, 0, 0], + [0, 1, 0, 0, 0, 0], + [0, 0, 3, 0, 0, 0], + [0, 0, 0, -4, 0, 0], + [0, 0, 0, 0, -1, 0], + [0, 0, 0, 0, 0, 3]]) + self.B623 = np.array([[0, -1], + [-1, 0], + [1, -1], + [0, 0], + [0, 1], + [-1, -1]]) + self.C623 = np.array([[1, 0, 0, 1, 0, 0], + [0, 1, 0, 1, 0, 1], + [0, 0, 1, 0, 0, 1]]) + self.D623 = np.zeros((3, 2)) + self.sys623 = StateSpace(self.A623, self.B623, self.C623, self.D623) def test_pole(self): """Evaluate the poles of a MIMO system.""" @@ -107,7 +107,7 @@ def test_zero_mimo_sys222_square(self): """Evaluate the zeros of a square MIMO system.""" z = np.sort(self.sys222.zero()) - true_z = np.sort([-10.568501, 3.368501]) + true_z = np.sort([-10.568501, 3.368501]) np.testing.assert_array_almost_equal(z, true_z) @unittest.skipIf(not slycot_check(), "slycot not installed") @@ -207,13 +207,13 @@ def test_freq_resp(self): sys = StateSpace(A, B, C, D) true_mag = [[[0.0852992637230322, 0.00103596611395218], - [0.935374692849736, 0.799380720864549]], - [[0.55656854563842, 0.301542699860857], - [0.609178071542849, 0.0382108097985257]]] + [0.935374692849736, 0.799380720864549]], + [[0.55656854563842, 0.301542699860857], + [0.609178071542849, 0.0382108097985257]]] true_phase = [[[-0.566195599644593, -1.68063565332582], - [3.0465958317514, 3.14141384339534]], - [[2.90457947657161, 3.10601268291914], - [-0.438157380501337, -1.40720969147217]]] + [3.0465958317514, 3.14141384339534]], + [[2.90457947657161, 3.10601268291914], + [-0.438157380501337, -1.40720969147217]]] true_omega = [0.1, 10.] mag, phase, omega = sys.freqresp(true_omega) @@ -241,7 +241,7 @@ def test_minreal(self): self.assertEqual(sysr.inputs, sys.inputs) self.assertEqual(sysr.outputs, sys.outputs) np.testing.assert_array_almost_equal( - eigvals(sysr.A), [-2.136154, -0.1638459]) + eigvals(sysr.A), [-2.136154, -0.1638459]) def test_append_ss(self): """Test appending two state-space systems.""" @@ -290,7 +290,6 @@ def test_append_tf(self): np.testing.assert_array_almost_equal(sys3c.A[3:, :3], np.zeros((2, 3))) def test_array_access_ss(self): - sys1 = StateSpace([[1., 2.], [3., 4.]], [[5., 6.], [6., 8.]], [[9., 10.], [11., 12.]], @@ -392,7 +391,7 @@ def test_matrix_static_gain(self): np.testing.assert_array_equal(d1 + d2.T, h2.D) h3 = g1.feedback(g2) np.testing.assert_array_almost_equal( - solve(np.eye(2) + d1 * d2, d1), h3.D) + solve(np.eye(2) + d1 * d2, d1), h3.D) h4 = g1.append(g2) np.testing.assert_array_equal(block_diag(d1, d2), h4.D) @@ -443,11 +442,39 @@ def empty(shape): m = np.matrix([]) m.shape = shape return m + np.testing.assert_array_equal(empty((0, 0)), g.A) np.testing.assert_array_equal(empty((0, D.shape[1])), g.B) np.testing.assert_array_equal(empty((D.shape[0], 0)), g.C) np.testing.assert_array_equal(D, g.D) + def test_consistent_dimensions_322(self): + true = consistent_dimensions(self.A322, self.B322, self.C322, self.D322) + np.testing.assert_(true) + true = consistent_dimensions(B=self.B322, C=self.C322, D=self.D322) + np.testing.assert_(true) + true = consistent_dimensions(A=self.A322, C=self.C322, D=self.D322) + np.testing.assert_(true) + true = consistent_dimensions(A=self.A322, B=self.B322, D=self.D322) + np.testing.assert_(true) + true = consistent_dimensions(A=self.A322, B=self.B322, C=self.C322) + np.testing.assert_(true) + + def test_consistent_dimensions_bad_inputs(self): + # Number of states not consistent + true = consistent_dimensions(A=self.A222, B=self.B322, C=self.C322, D=self.D322) + np.testing.assert_(not true) + true = consistent_dimensions(self.A322, self.B222, self.C322, self.D322) + np.testing.assert_(not true) + true = consistent_dimensions(A=self.A322, C=self.C222, D=self.D322) + np.testing.assert_(not true) + # Number of input not consistent + true = consistent_dimensions(A=self.A322, B=self.B322, D=self.A322) + np.testing.assert_(not true) + # Number of output not consistent + true = consistent_dimensions(A=self.A322, C=self.C322, D=self.A322) + np.testing.assert_(not true) + class TestRss(unittest.TestCase): """These are tests for the proper functionality of statesp.rss."""