diff --git a/control/statesp.py b/control/statesp.py index 6385642eb..e0f82c132 100644 --- a/control/statesp.py +++ b/control/statesp.py @@ -85,8 +85,8 @@ def _matrix(a): """ from numpy import matrix am = matrix(a) - if (1,0) == am.shape: - am.shape = (0,0) + if (1, 0) == am.shape: + am.shape = (0, 0) return am @@ -132,14 +132,15 @@ def __init__(self, *args): if len(args) == 4: # The user provided A, B, C, and D matrices. (A, B, C, D) = args - dt = None; + dt = None elif len(args) == 5: # Discrete time system (A, B, C, D, dt) = args elif len(args) == 1: # Use the copy constructor. if not isinstance(args[0], StateSpace): - raise TypeError("The one-argument constructor can only take in a StateSpace object. Received %s." % type(args[0])) + raise TypeError("The one-argument constructor can only take in a StateSpace " + "object. Received %s." % type(args[0])) A = args[0].A B = args[0].B C = args[0].C @@ -147,7 +148,7 @@ def __init__(self, *args): try: dt = args[0].dt except NameError: - dt = None; + dt = None else: raise ValueError("Needs 1 or 4 arguments; received %i." % len(args)) @@ -199,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 duplucate indices in useless, jump to the next + # 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. @@ -221,12 +222,12 @@ def _remove_useless_states(self): def __str__(self): """String representation of the state space.""" - str = "A = " + self.A.__str__() + "\n\n" + str = "A = " + self.A.__str__() + "\n\n" str += "B = " + self.B.__str__() + "\n\n" 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 == True): + # TODO: replace with standard calls to lti functions + 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): str += "\ndt = " + self.dt.__str__() + "\n" @@ -246,10 +247,10 @@ def __add__(self, other): """Add two LTI systems (parallel connection).""" # Check for a couple of special cases - if (isinstance(other, (int, float, complex, np.number))): + if isinstance(other, (int, float, complex, np.number)): # Just adding a scalar; put it in the D matrix - A, B, C = self.A, self.B, self.C; - D = self.D + other; + A, B, C = self.A, self.B, self.C + D = self.D + other dt = self.dt else: other = _convertToStateSpace(other) @@ -260,9 +261,9 @@ def __add__(self, other): raise ValueError("Systems have different shapes.") # Figure out the sampling time to use - if (self.dt == None and other.dt != None): + if self.dt is None and other.dt is not None: dt = other.dt # use dt from second argument - elif (other.dt == None and self.dt != None) or \ + elif (other.dt is None and self.dt is not None) or \ (timebaseEqual(self, other)): dt = self.dt # use dt from first argument else: @@ -346,9 +347,9 @@ def __rmul__(self, other): # Check for a couple of special cases if isinstance(other, (int, float, complex, np.number)): # Just multiplying by a scalar; change the input - A, C = self.A, self.C; - B = self.B * other; - D = self.D * other; + A, C = self.A, self.C + B = self.B * other + D = self.D * other return StateSpace(A, B, C, D, self.dt) # is lti, and convertible? @@ -396,7 +397,7 @@ def _evalfr(self, omega): if isdtime(self, strict=True): dt = timebase(self) s = exp(1.j * omega * dt) - if (omega * dt > math.pi): + if omega * dt > math.pi: warn("_evalfr: frequency evaluation above Nyquist frequency") else: s = omega * 1.j @@ -404,10 +405,10 @@ def _evalfr(self, omega): return self.horner(s) def horner(self, s): - '''Evaluate the systems's transfer function for a complex variable + """Evaluate the systems's transfer function for a complex variable Returns a matrix of values evaluated at complex variable s. - ''' + """ resp = self.C * solve(s * eye(self.states) - self.A, self.B) + self.D return array(resp) @@ -460,7 +461,7 @@ def freqresp(self, omega): if isdtime(self, strict=True): dt = timebase(self) cmplx_freqs = exp(1.j * omega * dt) - if max(abs(omega)) * dt > math.pi: + if max(np.abs(omega)) * dt > math.pi: warn("freqresp: frequency evaluation above Nyquist frequency") else: cmplx_freqs = omega * 1.j @@ -473,8 +474,8 @@ def freqresp(self, omega): n = np.shape(self.A)[0] m = self.inputs p = self.outputs - # The first call both evalates C(sI-A)^-1 B and also returns - # hessenberg transformed matrices at, bt, ct. + # The first call both evaluates C(sI-A)^-1 B and also returns + # Hessenberg transformed matrices at, bt, ct. result = tb05ad(n, m, p, cmplx_freqs[0], self.A, self.B, self.C, job='NG') # When job='NG', result = (at, bt, ct, g_i, hinvb, info) @@ -482,7 +483,7 @@ def freqresp(self, omega): bt = result[1] ct = result[2] - # TB05AD freqency evaluation does not include direct feedthrough. + # TB05AD frequency evaluation does not include direct feedthrough. Gfrf[:, :, 0] = result[3] + self.D # Now, iterate through the remaining frequencies using the @@ -528,8 +529,8 @@ def zero(self): if nu == 0: return np.array([]) else: - return sp.linalg.eigvals(out[8][0:nu,0:nu], out[9][0:nu,0:nu]) - + return sp.linalg.eigvals(out[8][0:nu, 0:nu], out[9][0:nu, 0:nu]) + except ImportError: # Slycot unavailable. Fall back to scipy. if self.C.shape[0] != self.D.shape[1]: raise NotImplementedError("StateSpace.zero only supports " @@ -540,7 +541,7 @@ def zero(self): # from # https://dspace.mit.edu/bitstream/handle/1721.1/841/P-0802-06587335.pdf. # The QZ algorithm solves the generalized eigenvalue problem: given - # `L = [A, B; C, D]` and `M = [I_nxn 0]`, find all finite lambda + # `L = [A, B; C, D]` and `M = [I_nxn 0]`, find all finite lambda # for which there exist nontrivial solutions of the equation # `Lz - lamba Mz`. # @@ -550,8 +551,7 @@ def zero(self): concatenate((self.C, self.D), axis=1)), axis=0) M = pad(eye(self.A.shape[0]), ((0, self.C.shape[0]), (0, self.B.shape[1])), "constant") - return np.array([x for x in sp.linalg.eigvals(L, M, - overwrite_a=True) + return np.array([x for x in sp.linalg.eigvals(L, M, overwrite_a=True) if not isinf(x)]) # Feedback around a state space system @@ -561,15 +561,14 @@ def feedback(self, other=1, sign=-1): other = _convertToStateSpace(other) # 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.") + if (self.inputs != other.outputs) or (self.outputs != other.inputs): + raise ValueError("State space systems don't have compatible inputs/outputs for " + "feedback.") # Figure out the sampling time to use - if (self.dt == None and other.dt != None): + if self.dt is None and other.dt is not None: dt = other.dt # use dt from second argument - elif (other.dt == None and self.dt != None) or \ - timebaseEqual(self, other): + 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") @@ -599,12 +598,9 @@ def feedback(self, other=1, sign=-1): T1 = eye(self.outputs) + sign * D1 * E_D2 T2 = eye(self.inputs) + sign * E_D2 * D1 - A = concatenate( - (concatenate( - (A1 + sign * B1 * E_D2 * C1, sign * B1 * E_C2), axis=1), - concatenate( - (B2 * T1 * C1, A2 + sign * B2 * D1 * E_C2), axis=1)), - axis=0) + A = concatenate((concatenate((A1 + sign * B1 * E_D2 * C1, sign * B1 * E_C2), axis=1), + concatenate((B2 * T1 * C1, A2 + sign * B2 * D1 * E_C2), axis=1)), + axis=0) B = concatenate((B1 * T2, B2 * D1 * T2), axis=0) C = concatenate((T1 * C1, sign * D1 * E_C2), axis=1) D = D1 * T2 @@ -644,7 +640,7 @@ def returnScipySignalLTI(self): the 6th input to the 4th output.""" # Preallocate the output. - out = [[[] for j in range(self.inputs)] for i in range(self.outputs)] + out = [[[] for _ in range(self.inputs)] for _ in range(self.outputs)] for i in range(self.outputs): for j in range(self.inputs): @@ -666,30 +662,27 @@ def append(self, other): n = self.states + other.states m = self.inputs + other.inputs p = self.outputs + other.outputs - A = zeros( (n, n) ) - B = zeros( (n, m) ) - C = zeros( (p, n) ) - D = zeros( (p, m) ) - A[:self.states,:self.states] = self.A - A[self.states:,self.states:] = other.A - B[:self.states,:self.inputs] = self.B - B[self.states:,self.inputs:] = other.B - C[:self.outputs,:self.states] = self.C - C[self.outputs:,self.states:] = other.C - D[:self.outputs,:self.inputs] = self.D - D[self.outputs:,self.inputs:] = other.D + A = zeros((n, n)) + B = zeros((n, m)) + C = zeros((p, n)) + D = zeros((p, m)) + A[:self.states, :self.states] = self.A + A[self.states:, self.states:] = other.A + B[:self.states, :self.inputs] = self.B + B[self.states:, self.inputs:] = other.B + C[:self.outputs, :self.states] = self.C + C[self.outputs:, self.states:] = other.C + D[:self.outputs, :self.inputs] = self.D + D[self.outputs:, self.inputs:] = other.D return StateSpace(A, B, C, D, self.dt) def __getitem__(self, indices): - """Array style acces""" + """Array style access""" if len(indices) != 2: raise IOError('must provide indices of length 2 for state space') i = indices[0] j = indices[1] - return StateSpace(self.A, - self.B[:,j], - self.C[i,:], - self.D[i,j], self.dt) + return StateSpace(self.A, self.B[:, j], self.C[i, :], self.D[i, j], self.dt) def sample(self, Ts, method='zoh', alpha=None): """Convert a continuous time system to discrete time @@ -757,13 +750,12 @@ 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: # eigenvalue at DC - gain = np.tile(np.nan,(self.outputs,self.inputs)) + gain = np.tile(np.nan, (self.outputs, self.inputs)) return np.squeeze(gain) @@ -805,14 +797,12 @@ def _convertToStateSpace(sys, **kw): num, den, denorder = sys.minreal()._common_den() # transfer function to state space conversion now should work! - ssout = td04ad('C', sys.inputs, sys.outputs, + ssout = td04ad('C', sys.inputs, sys.outputs, denorder, den, num, tol=0) states = ssout[0] - return StateSpace(ssout[1][:states, :states], - ssout[2][:states, :sys.inputs], - ssout[3][:sys.outputs, :states], - ssout[4], sys.dt) + return StateSpace(ssout[1][:states, :states], ssout[2][:states, :sys.inputs], + ssout[3][:sys.outputs, :states], ssout[4], sys.dt) except ImportError: # No Slycot. Scipy tf->ss can't handle MIMO, but static # MIMO is an easy special case we can check for here @@ -820,13 +810,13 @@ def _convertToStateSpace(sys, **kw): for nrow in sys.num) maxd = max(max(len(d) for d in drow) for drow in sys.den) - if 1==maxn and 1==maxd: - D = empty((sys.outputs,sys.inputs),dtype=float) - for i,j in itertools.product(range(sys.outputs),range(sys.inputs)): - D[i,j] = sys.num[i][j][0] / sys.den[i][j][0] + if 1 == maxn and 1 == maxd: + D = empty((sys.outputs, sys.inputs), dtype=float) + for i, j in itertools.product(range(sys.outputs), range(sys.inputs)): + D[i, j] = sys.num[i][j][0] / sys.den[i][j][0] return StateSpace([], [], [], D, sys.dt) else: - if (sys.inputs != 1 or sys.outputs != 1): + if sys.inputs != 1 or sys.outputs != 1: raise TypeError("No support for MIMO without slycot") # TODO: do we want to squeeze first and check dimenations? @@ -924,8 +914,7 @@ def _rss_generate(states, inputs, outputs, type): elif type == 'd': mag = rand() phase = 2. * math.pi * rand() - poles[i] = complex(mag * cos(phase), - mag * sin(phase)) + poles[i] = complex(mag * cos(phase), mag * sin(phase)) poles[i+1] = complex(poles[i].real, -poles[i].imag) i += 2 @@ -945,7 +934,7 @@ def _rss_generate(states, inputs, outputs, type): while True: T = randn(states, states) try: - A = dot(solve(T, A), T) # A = T \ A * T + A = dot(solve(T, A), T) # A = T \ A * T break except LinAlgError: # In the unlikely event that T is rank-deficient, iterate again. @@ -959,11 +948,11 @@ def _rss_generate(states, inputs, outputs, type): # Make masks to zero out some of the elements. while True: Bmask = rand(states, inputs) < pBCmask - if any(Bmask): # Retry if we get all zeros. + if any(Bmask): # Retry if we get all zeros. break while True: Cmask = rand(outputs, states) < pBCmask - if any(Cmask): # Retry if we get all zeros. + if any(Cmask): # Retry if we get all zeros. break if rand() < pDzero: Dmask = zeros((outputs, inputs)) @@ -977,6 +966,7 @@ def _rss_generate(states, inputs, outputs, type): return StateSpace(A, B, C, D) + # Convert a MIMO system to a SISO system # TODO: add discrete time check def _mimo2siso(sys, input, output, warn_conversion=False): @@ -1003,8 +993,7 @@ def _mimo2siso(sys, input, output, warn_conversion=False): If True: print a warning message when sys is a MIMO system. Warn that a conversion will take place. - Returns: - + Returns sys: StateSpace The converted (SISO) system. """ @@ -1036,8 +1025,9 @@ def _mimo2siso(sys, input, output, warn_conversion=False): return sys + def _mimo2simo(sys, input, warn_conversion=False): - #pylint: disable=W0622 + # pylint: disable=W0622 """ Convert a MIMO system to a SIMO system. (Convert a system with multiple inputs and/or outputs, to a system with a single input but possibly @@ -1059,8 +1049,8 @@ def _mimo2simo(sys, input, warn_conversion=False): If True: print a warning message when sys is a MIMO system. Warn that a conversion will take place. - Returns: - -------- + Returns + ------- sys: StateSpace The converted (SIMO) system. """ @@ -1071,7 +1061,7 @@ def _mimo2simo(sys, input, warn_conversion=False): "Selected input: {sel}, " "number of system inputs: {ext}." .format(sel=input, ext=sys.inputs)) - #Convert sys to SISO if necessary + # Convert sys to SISO if necessary if sys.inputs > 1: if warn_conversion: warn("Converting MIMO system to SIMO system. " @@ -1084,6 +1074,7 @@ def _mimo2simo(sys, input, warn_conversion=False): return sys + def ss(*args): """ss(A, B, C, D[, dt]) @@ -1175,6 +1166,7 @@ def ss(*args): else: raise ValueError("Needs 1 or 4 arguments; received %i." % len(args)) + def tf2ss(*args): """tf2ss(sys) @@ -1246,6 +1238,7 @@ def tf2ss(*args): else: raise ValueError("Needs 1 or 2 arguments; received %i." % len(args)) + def rss(states=1, outputs=1, inputs=1): """ Create a stable *continuous* random state space object. @@ -1283,6 +1276,7 @@ def rss(states=1, outputs=1, inputs=1): return _rss_generate(states, inputs, outputs, 'c') + def drss(states=1, outputs=1, inputs=1): """ Create a stable *discrete* random state space object. @@ -1320,8 +1314,9 @@ def drss(states=1, outputs=1, inputs=1): return _rss_generate(states, inputs, outputs, 'd') + def ssdata(sys): - ''' + """ Return state space data objects for a system Parameters @@ -1333,6 +1328,6 @@ def ssdata(sys): ------- (A, B, C, D): list of matrices State space data for the system - ''' + """ ss = _convertToStateSpace(sys) - return (ss.A, ss.B, ss.C, ss.D) + return ss.A, ss.B, ss.C, ss.D diff --git a/control/tests/statesp_test.py b/control/tests/statesp_test.py index 3e9adcca6..08a8cdc22 100644 --- a/control/tests/statesp_test.py +++ b/control/tests/statesp_test.py @@ -8,78 +8,117 @@ from numpy.linalg import solve from scipy.linalg import eigvals, block_diag from control import matlab -from control.statesp import StateSpace, _convertToStateSpace -from control.xferfcn import TransferFunction +from control.statesp import StateSpace, _convertToStateSpace, tf2ss +from control.xferfcn import TransferFunction, ss2tf from control.lti import evalfr from control.exception import slycot_check + class TestStateSpace(unittest.TestCase): """Tests for the StateSpace class.""" def setUp(self): """Set up a MIMO system to test operations on.""" - A = [[-3., 4., 2.], [-1., -3., 0.], [2., 5., 3.]] - B = [[1., 4.], [-3., -3.], [-2., 1.]] - C = [[4., 2., -3.], [1., 4., 3.]] - D = [[-2., 4.], [0., 1.]] - - a = [[4., 1.], [2., -3]] - b = [[5., 2.], [-3., -3.]] - c = [[2., -4], [0., 1.]] - d = [[3., 2.], [1., -1.]] - - self.sys1 = StateSpace(A, B, C, D) - self.sys2 = StateSpace(a, b, c, d) - - def testPole(self): + # 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) + + # 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) + + # 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) + + def test_pole(self): """Evaluate the poles of a MIMO system.""" - p = np.sort(self.sys1.pole()) + p = np.sort(self.sys322.pole()) true_p = np.sort([3.34747678408874, - -3.17373839204437 + 1.47492908003839j, - -3.17373839204437 - 1.47492908003839j]) + -3.17373839204437 + 1.47492908003839j, + -3.17373839204437 - 1.47492908003839j]) np.testing.assert_array_almost_equal(p, true_p) - def testEmptyZero(self): - """Test to make sure zero() works with no zeros in system""" - sys = _convertToStateSpace(TransferFunction([1], [1,2,1])) + def test_zero_empty(self): + """Test to make sure zero() works with no zeros in system.""" + sys = _convertToStateSpace(TransferFunction([1], [1, 2, 1])) np.testing.assert_array_equal(sys.zero(), np.array([])) @unittest.skipIf(not slycot_check(), "slycot not installed") - def testMIMOZero_nonsquare(self): - """Evaluate the zeros of a MIMO system.""" + def test_zero_siso(self): + """Evaluate the zeros of a SISO system.""" + # extract only first input / first output system of sys222. This system is denoted sys111 + # or tf111 + tf111 = ss2tf(self.sys222) + sys111 = tf2ss(tf111[0, 0]) + + # compute zeros as root of the characteristic polynomial at the numerator of tf111 + # this method is simple and assumed as valid in this test + true_z = np.sort(tf111[0, 0].zero()) + # Compute the zeros through ab08nd, which is tested here + z = np.sort(sys111.zero()) + + np.testing.assert_almost_equal(true_z, z) + + @unittest.skipIf(not slycot_check(), "slycot not installed") + def test_zero_mimo_sys322_square(self): + """Evaluate the zeros of a square MIMO system.""" - z = np.sort(self.sys1.zero()) + z = np.sort(self.sys322.zero()) true_z = np.sort([44.41465, -0.490252, -5.924398]) + np.testing.assert_array_almost_equal(z, true_z) + + @unittest.skipIf(not slycot_check(), "slycot not installed") + 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]) np.testing.assert_array_almost_equal(z, true_z) - A = 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]]) - B = np.array([[0,-1], - [-1,0], - [1,-1], - [0, 0], - [0, 1], - [-1,-1]]) - C = np.array([[1, 0, 0, 1, 0, 0], - [0, 1, 0, 1, 0, 1], - [0, 0, 1, 0, 0, 1]]) - D = np.zeros((3,2)) - sys = StateSpace(A, B, C, D) + @unittest.skipIf(not slycot_check(), "slycot not installed") + def test_zero_mimo_sys623_non_square(self): + """Evaluate the zeros of a non square MIMO system.""" - z = np.sort(sys.zero()) + z = np.sort(self.sys623.zero()) true_z = np.sort([2., -1.]) - np.testing.assert_array_almost_equal(z, true_z) - def testAdd(self): + def test_add_ss(self): """Add two MIMO systems.""" A = [[-3., 4., 2., 0., 0.], [-1., -3., 0., 0., 0.], @@ -88,14 +127,14 @@ def testAdd(self): C = [[4., 2., -3., 2., -4.], [1., 4., 3., 0., 1.]] D = [[1., 6.], [1., 0.]] - sys = self.sys1 + self.sys2 + sys = self.sys322 + self.sys222 np.testing.assert_array_almost_equal(sys.A, A) np.testing.assert_array_almost_equal(sys.B, B) np.testing.assert_array_almost_equal(sys.C, C) np.testing.assert_array_almost_equal(sys.D, D) - def testSub(self): + def test_subtract_ss(self): """Subtract two MIMO systems.""" A = [[-3., 4., 2., 0., 0.], [-1., -3., 0., 0., 0.], @@ -104,14 +143,14 @@ def testSub(self): C = [[4., 2., -3., -2., 4.], [1., 4., 3., 0., -1.]] D = [[-5., 2.], [-1., 2.]] - sys = self.sys1 - self.sys2 + sys = self.sys322 - self.sys222 np.testing.assert_array_almost_equal(sys.A, A) np.testing.assert_array_almost_equal(sys.B, B) np.testing.assert_array_almost_equal(sys.C, C) np.testing.assert_array_almost_equal(sys.D, D) - def testMul(self): + def test_multiply_ss(self): """Multiply two MIMO systems.""" A = [[4., 1., 0., 0., 0.], [2., -3., 0., 0., 0.], [2., 0., -3., 4., 2.], @@ -120,14 +159,14 @@ def testMul(self): C = [[-4., 12., 4., 2., -3.], [0., 1., 1., 4., 3.]] D = [[-2., -8.], [1., -1.]] - sys = self.sys1 * self.sys2 + sys = self.sys322 * self.sys222 np.testing.assert_array_almost_equal(sys.A, A) np.testing.assert_array_almost_equal(sys.B, B) np.testing.assert_array_almost_equal(sys.C, C) np.testing.assert_array_almost_equal(sys.D, D) - def testEvalFr(self): + def test_evalfr(self): """Evaluate the frequency response at one frequency.""" A = [[-2, 0.5], [0.5, -0.3]] @@ -151,14 +190,14 @@ def testEvalFr(self): # Set up warnings filter to only show warnings in control module warnings.filterwarnings("ignore") warnings.filterwarnings("always", module="control") - + # Make sure that we get a pending deprecation warning sys.evalfr(1.) assert len(w) == 1 assert issubclass(w[-1].category, PendingDeprecationWarning) @unittest.skipIf(not slycot_check(), "slycot not installed") - def testFreqResp(self): + def test_freq_resp(self): """Evaluate the frequency response at multiple frequencies.""" A = [[-2, 0.5], [0.5, -0.3]] @@ -167,32 +206,32 @@ def testFreqResp(self): D = [[0., -0.8], [-0.3, 0.]] sys = StateSpace(A, B, C, D) - truemag = [[[0.0852992637230322, 0.00103596611395218], + true_mag = [[[0.0852992637230322, 0.00103596611395218], [0.935374692849736, 0.799380720864549]], [[0.55656854563842, 0.301542699860857], [0.609178071542849, 0.0382108097985257]]] - truephase = [[[-0.566195599644593, -1.68063565332582], + true_phase = [[[-0.566195599644593, -1.68063565332582], [3.0465958317514, 3.14141384339534]], [[2.90457947657161, 3.10601268291914], [-0.438157380501337, -1.40720969147217]]] - trueomega = [0.1, 10.] + true_omega = [0.1, 10.] - mag, phase, omega = sys.freqresp(trueomega) + mag, phase, omega = sys.freqresp(true_omega) - np.testing.assert_almost_equal(mag, truemag) - np.testing.assert_almost_equal(phase, truephase) - np.testing.assert_equal(omega, trueomega) + np.testing.assert_almost_equal(mag, true_mag) + np.testing.assert_almost_equal(phase, true_phase) + np.testing.assert_equal(omega, true_omega) @unittest.skipIf(not slycot_check(), "slycot not installed") - def testMinreal(self): - """Test a minreal model reduction""" - #A = [-2, 0.5, 0; 0.5, -0.3, 0; 0, 0, -0.1] + def test_minreal(self): + """Test a minreal model reduction.""" + # A = [-2, 0.5, 0; 0.5, -0.3, 0; 0, 0, -0.1] A = [[-2, 0.5, 0], [0.5, -0.3, 0], [0, 0, -0.1]] - #B = [0.3, -1.3; 0.1, 0; 1, 0] + # B = [0.3, -1.3; 0.1, 0; 1, 0] B = [[0.3, -1.3], [0.1, 0.], [1.0, 0.0]] - #C = [0, 0.1, 0; -0.3, -0.2, 0] + # C = [0, 0.1, 0; -0.3, -0.2, 0] C = [[0., 0.1, 0.0], [-0.3, -0.2, 0.0]] - #D = [0 -0.8; -0.3 0] + # D = [0 -0.8; -0.3 0] D = [[0., -0.8], [-0.3, 0.]] # sys = ss(A, B, C, D) @@ -204,8 +243,8 @@ def testMinreal(self): np.testing.assert_array_almost_equal( eigvals(sysr.A), [-2.136154, -0.1638459]) - def testAppendSS(self): - """Test appending two state-space systems""" + def test_append_ss(self): + """Test appending two state-space systems.""" A1 = [[-2, 0.5, 0], [0.5, -0.3, 0], [0, 0, -0.1]] B1 = [[0.3, -1.3], [0.1, 0.], [1.0, 0.0]] C1 = [[0., 0.1, 0.0], [-0.3, -0.2, 0.0]] @@ -228,62 +267,61 @@ def testAppendSS(self): np.testing.assert_array_almost_equal(sys3.C, sys3c.C) np.testing.assert_array_almost_equal(sys3.D, sys3c.D) - def testAppendTF(self): + def test_append_tf(self): """Test appending a state-space system with a tf""" A1 = [[-2, 0.5, 0], [0.5, -0.3, 0], [0, 0, -0.1]] B1 = [[0.3, -1.3], [0.1, 0.], [1.0, 0.0]] C1 = [[0., 0.1, 0.0], [-0.3, -0.2, 0.0]] D1 = [[0., -0.8], [-0.3, 0.]] s = TransferFunction([1, 0], [1]) - h = 1/(s+1)/(s+2) + h = 1 / (s + 1) / (s + 2) sys1 = StateSpace(A1, B1, C1, D1) sys2 = _convertToStateSpace(h) sys3c = sys1.append(sys2) - np.testing.assert_array_almost_equal(sys1.A, sys3c.A[:3,:3]) - np.testing.assert_array_almost_equal(sys1.B, sys3c.B[:3,:2]) - np.testing.assert_array_almost_equal(sys1.C, sys3c.C[:2,:3]) - np.testing.assert_array_almost_equal(sys1.D, sys3c.D[:2,:2]) - np.testing.assert_array_almost_equal(sys2.A, sys3c.A[3:,3:]) - np.testing.assert_array_almost_equal(sys2.B, sys3c.B[3:,2:]) - np.testing.assert_array_almost_equal(sys2.C, sys3c.C[2:,3:]) - np.testing.assert_array_almost_equal(sys2.D, sys3c.D[2:,2:]) - np.testing.assert_array_almost_equal(sys3c.A[:3,3:], np.zeros( (3, 2)) ) - np.testing.assert_array_almost_equal(sys3c.A[3:,:3], np.zeros( (2, 3)) ) - - - def testArrayAccessSS(self): + np.testing.assert_array_almost_equal(sys1.A, sys3c.A[:3, :3]) + np.testing.assert_array_almost_equal(sys1.B, sys3c.B[:3, :2]) + np.testing.assert_array_almost_equal(sys1.C, sys3c.C[:2, :3]) + np.testing.assert_array_almost_equal(sys1.D, sys3c.D[:2, :2]) + np.testing.assert_array_almost_equal(sys2.A, sys3c.A[3:, 3:]) + np.testing.assert_array_almost_equal(sys2.B, sys3c.B[3:, 2:]) + np.testing.assert_array_almost_equal(sys2.C, sys3c.C[2:, 3:]) + np.testing.assert_array_almost_equal(sys2.D, sys3c.D[2:, 2:]) + np.testing.assert_array_almost_equal(sys3c.A[:3, 3:], np.zeros((3, 2))) + 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.]], - [[13., 14.], [15., 16.]], 1) + [[5., 6.], [6., 8.]], + [[9., 10.], [11., 12.]], + [[13., 14.], [15., 16.]], 1) - sys1_11 = sys1[0,1] + sys1_11 = sys1[0, 1] np.testing.assert_array_almost_equal(sys1_11.A, - sys1.A) + sys1.A) np.testing.assert_array_almost_equal(sys1_11.B, - sys1.B[:,1]) + sys1.B[:, 1]) np.testing.assert_array_almost_equal(sys1_11.C, - sys1.C[0,:]) + sys1.C[0, :]) np.testing.assert_array_almost_equal(sys1_11.D, - sys1.D[0,1]) + sys1.D[0, 1]) assert sys1.dt == sys1_11.dt - def test_dcgain_cont(self): - """Test DC gain for continuous-time state-space systems""" - sys = StateSpace(-2.,6.,5.,0) + def test_dc_gain_cont(self): + """Test DC gain for continuous-time state-space systems.""" + sys = StateSpace(-2., 6., 5., 0) np.testing.assert_equal(sys.dcgain(), 15.) - sys2 = StateSpace(-2, [6., 4.], [[5.],[7.],[11]], np.zeros((3,2))) + sys2 = StateSpace(-2, [6., 4.], [[5.], [7.], [11]], np.zeros((3, 2))) expected = np.array([[15., 10.], [21., 14.], [33., 22.]]) np.testing.assert_array_equal(sys2.dcgain(), expected) sys3 = StateSpace(0., 1., 1., 0.) np.testing.assert_equal(sys3.dcgain(), np.nan) - def test_dcgain_discr(self): - """Test DC gain for discrete-time state-space systems""" + def test_dc_gain_discr(self): + """Test DC gain for discrete-time state-space systems.""" # static gain sys = StateSpace([], [], [], 2, True) np.testing.assert_equal(sys.dcgain(), 2) @@ -300,118 +338,115 @@ def test_dcgain_discr(self): sys = StateSpace(1, 1, 1, 0, True) np.testing.assert_equal(sys.dcgain(), np.nan) - def test_dcgain_integrator(self): - """DC gain when eigenvalue at DC returns appropriately sized array of nan""" + def test_dc_gain_integrator(self): + """DC gain when eigenvalue at DC returns appropriately sized array of nan.""" # the SISO case is also tested in test_dc_gain_{cont,discr} import itertools # iterate over input and output sizes, and continuous (dt=None) and discrete (dt=True) time - for inputs,outputs,dt in itertools.product(range(1,6),range(1,6),[None,True]): - states = max(inputs,outputs) + for inputs, outputs, dt in itertools.product(range(1, 6), range(1, 6), [None, True]): + states = max(inputs, outputs) - # a matrix that is singular at DC, and has no "useless" states as in _remove_useless_states - a = np.triu(np.tile(2,(states,states))) + # a matrix that is singular at DC, and has no "useless" states as in + # _remove_useless_states + a = np.triu(np.tile(2, (states, states))) # eigenvalues all +2, except for ... - a[0,0] = 0 if dt is None else 1 - b = np.eye(max(inputs,states))[:states,:inputs] - c = np.eye(max(outputs,states))[:outputs,:states] - d = np.zeros((outputs,inputs)) - sys = StateSpace(a,b,c,d,dt) - dc = np.squeeze(np.tile(np.nan,(outputs,inputs))) + a[0, 0] = 0 if dt is None else 1 + b = np.eye(max(inputs, states))[:states, :inputs] + c = np.eye(max(outputs, states))[:outputs, :states] + d = np.zeros((outputs, inputs)) + sys = StateSpace(a, b, c, d, dt) + dc = np.squeeze(np.tile(np.nan, (outputs, inputs))) np.testing.assert_array_equal(dc, sys.dcgain()) - - def test_scalarStaticGain(self): + def test_scalar_static_gain(self): """Regression: can we create a scalar static gain?""" - g1=StateSpace([],[],[],[2]) - g2=StateSpace([],[],[],[3]) + g1 = StateSpace([], [], [], [2]) + g2 = StateSpace([], [], [], [3]) # make sure StateSpace internals, specifically ABC matrix # sizes, are OK for LTI operations - g3 = g1*g2 - self.assertEqual(6, g3.D[0,0]) - g4 = g1+g2 - self.assertEqual(5, g4.D[0,0]) + g3 = g1 * g2 + self.assertEqual(6, g3.D[0, 0]) + g4 = g1 + g2 + self.assertEqual(5, g4.D[0, 0]) g5 = g1.feedback(g2) - self.assertAlmostEqual(2./7, g5.D[0,0]) + self.assertAlmostEqual(2. / 7, g5.D[0, 0]) g6 = g1.append(g2) - np.testing.assert_array_equal(np.diag([2,3]),g6.D) + np.testing.assert_array_equal(np.diag([2, 3]), g6.D) - def test_matrixStaticGain(self): + def test_matrix_static_gain(self): """Regression: can we create matrix static gains?""" - d1 = np.matrix([[1,2,3],[4,5,6]]) - d2 = np.matrix([[7,8],[9,10],[11,12]]) - g1=StateSpace([],[],[],d1) + d1 = np.matrix([[1, 2, 3], [4, 5, 6]]) + d2 = np.matrix([[7, 8], [9, 10], [11, 12]]) + g1 = StateSpace([], [], [], d1) # _remove_useless_states was making A = [[0]] - self.assertEqual((0,0), g1.A.shape) + self.assertEqual((0, 0), g1.A.shape) - g2=StateSpace([],[],[],d2) - g3=StateSpace([],[],[],d2.T) + g2 = StateSpace([], [], [], d2) + g3 = StateSpace([], [], [], d2.T) - h1 = g1*g2 - np.testing.assert_array_equal(d1*d2, h1.D) - h2 = g1+g3 - np.testing.assert_array_equal(d1+d2.T, h2.D) + h1 = g1 * g2 + np.testing.assert_array_equal(d1 * d2, h1.D) + h2 = g1 + g3 + 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) + np.testing.assert_array_almost_equal( + solve(np.eye(2) + d1 * d2, d1), h3.D) h4 = g1.append(g2) - np.testing.assert_array_equal(block_diag(d1,d2),h4.D) - + np.testing.assert_array_equal(block_diag(d1, d2), h4.D) def test_remove_useless_states(self): - """Regression: _remove_useless_states gives correct ABC sizes""" - g1 = StateSpace(np.zeros((3,3)), - np.zeros((3,4)), - np.zeros((5,3)), - np.zeros((5,4))) - self.assertEqual((0,0), g1.A.shape) - self.assertEqual((0,4), g1.B.shape) - self.assertEqual((5,0), g1.C.shape) - self.assertEqual((5,4), g1.D.shape) + """Regression: _remove_useless_states gives correct ABC sizes.""" + g1 = StateSpace(np.zeros((3, 3)), + np.zeros((3, 4)), + np.zeros((5, 3)), + np.zeros((5, 4))) + self.assertEqual((0, 0), g1.A.shape) + self.assertEqual((0, 4), g1.B.shape) + self.assertEqual((5, 0), g1.C.shape) + self.assertEqual((5, 4), g1.D.shape) self.assertEqual(0, g1.states) - - def test_BadEmptyMatrices(self): - """Mismatched ABCD matrices when some are empty""" - self.assertRaises(ValueError,StateSpace, [1], [], [], [1]) - self.assertRaises(ValueError,StateSpace, [1], [1], [], [1]) - self.assertRaises(ValueError,StateSpace, [1], [], [1], [1]) - self.assertRaises(ValueError,StateSpace, [], [1], [], [1]) - self.assertRaises(ValueError,StateSpace, [], [1], [1], [1]) - self.assertRaises(ValueError,StateSpace, [], [], [1], [1]) - self.assertRaises(ValueError,StateSpace, [1], [1], [1], []) - - - def test_minrealStaticGain(self): - """Regression: minreal on static gain was failing""" - g1 = StateSpace([],[],[],[1]) + def test_bad_empty_matrices(self): + """Mismatched ABCD matrices when some are empty.""" + self.assertRaises(ValueError, StateSpace, [1], [], [], [1]) + self.assertRaises(ValueError, StateSpace, [1], [1], [], [1]) + self.assertRaises(ValueError, StateSpace, [1], [], [1], [1]) + self.assertRaises(ValueError, StateSpace, [], [1], [], [1]) + self.assertRaises(ValueError, StateSpace, [], [1], [1], [1]) + self.assertRaises(ValueError, StateSpace, [], [], [1], [1]) + self.assertRaises(ValueError, StateSpace, [1], [1], [1], []) + + def test_minreal_static_gain(self): + """Regression: minreal on static gain was failing.""" + g1 = StateSpace([], [], [], [1]) g2 = g1.minreal() np.testing.assert_array_equal(g1.A, g2.A) np.testing.assert_array_equal(g1.B, g2.B) np.testing.assert_array_equal(g1.C, g2.C) np.testing.assert_array_equal(g1.D, g2.D) - - def test_Empty(self): + def test_empty(self): """Regression: can we create an empty StateSpace object?""" - g1=StateSpace([],[],[],[]) - self.assertEqual(0,g1.states) - self.assertEqual(0,g1.inputs) - self.assertEqual(0,g1.outputs) - + g1 = StateSpace([], [], [], []) + self.assertEqual(0, g1.states) + self.assertEqual(0, g1.inputs) + self.assertEqual(0, g1.outputs) - def test_MatrixToStateSpace(self): + def test_matrix_to_state_space(self): """_convertToStateSpace(matrix) gives ss([],[],[],D)""" - D = np.matrix([[1,2,3],[4,5,6]]) + D = np.matrix([[1, 2, 3], [4, 5, 6]]) g = _convertToStateSpace(D) + 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) + 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) class TestRss(unittest.TestCase): @@ -425,9 +460,8 @@ def setUp(self): # Maximum number of inputs and outputs to test + 1 self.maxIO = 5 - def testShape(self): - """Test that rss outputs have the right state, input, and output - size.""" + def test_shape(self): + """Test that rss outputs have the right state, input, and output size.""" for states in range(1, self.maxStates): for inputs in range(1, self.maxIO): @@ -437,7 +471,7 @@ def testShape(self): self.assertEqual(sys.inputs, inputs) self.assertEqual(sys.outputs, outputs) - def testPole(self): + def test_pole(self): """Test that the poles of rss outputs have a negative real part.""" for states in range(1, self.maxStates): @@ -448,20 +482,20 @@ def testPole(self): for z in p: self.assertTrue(z.real < 0) + class TestDrss(unittest.TestCase): """These are tests for the proper functionality of statesp.drss.""" def setUp(self): # Number of times to run each of the randomized tests. self.numTests = 100 - # Maxmimum number of states to test + 1 + # Maximum number of states to test + 1 self.maxStates = 10 # Maximum number of inputs and outputs to test + 1 self.maxIO = 5 - def testShape(self): - """Test that drss outputs have the right state, input, and output - size.""" + def test_shape(self): + """Test that drss outputs have the right state, input, and output size.""" for states in range(1, self.maxStates): for inputs in range(1, self.maxIO): @@ -471,7 +505,7 @@ def testShape(self): self.assertEqual(sys.inputs, inputs) self.assertEqual(sys.outputs, outputs) - def testPole(self): + def test_pole(self): """Test that the poles of drss outputs have less than unit magnitude.""" for states in range(1, self.maxStates): @@ -482,15 +516,14 @@ def testPole(self): for z in p: self.assertTrue(abs(z) < 1) - - def testPoleStatic(self): - """Regression: pole() of static gain is empty array""" + def test_pole_static(self): + """Regression: pole() of static gain is empty array.""" np.testing.assert_array_equal(np.array([]), - StateSpace([],[],[],[[1]]).pole()) + StateSpace([], [], [], [[1]]).pole()) def suite(): - return unittest.TestLoader().loadTestsFromTestCase(TestStateSpace) + return unittest.TestLoader().loadTestsFromTestCase(TestStateSpace) if __name__ == "__main__":