From 1b28c60325e659670e0562e054d65448b94f33b9 Mon Sep 17 00:00:00 2001 From: Richard Murray Date: Sat, 14 Jul 2018 12:51:13 -0700 Subject: [PATCH 01/15] TST: unit tests for issiso() --- control/tests/lti_test.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/control/tests/lti_test.py b/control/tests/lti_test.py index 1fc05a852..e10319a0c 100644 --- a/control/tests/lti_test.py +++ b/control/tests/lti_test.py @@ -5,6 +5,7 @@ from control.lti import * from control.xferfcn import tf from control import c2d +from control.matlab import tf2ss import numpy as np class TestUtils(unittest.TestCase): @@ -18,6 +19,31 @@ def test_zero(self): np.testing.assert_equal(sys.zero(), 42) np.testing.assert_equal(zero(sys), 42) + def test_issiso(self): + self.assertEqual(issiso(1), True) + self.assertRaises(ValueError, issiso, 1, strict=True) + + # SISO transfer function + sys = tf([-1, 42], [1, 10]) + self.assertEqual(issiso(sys), True) + self.assertEqual(issiso(sys, strict=True), True) + + # SISO state space system + sys = tf2ss(sys) + self.assertEqual(issiso(sys), True) + self.assertEqual(issiso(sys, strict=True), True) + + # MIMO transfer function + sys = tf([[[-1, 41], [1]], [[1, 2], [3, 4]]], + [[[1, 10], [1, 20]], [[1, 30], [1, 40]]]); + self.assertEqual(issiso(sys), False) + self.assertEqual(issiso(sys, strict=True), False) + + # MIMO state space system + sys = tf2ss(sys) + self.assertEqual(issiso(sys), False) + self.assertEqual(issiso(sys, strict=True), False) + def test_damp(self): # Test the continuous time case. zeta = 0.1 @@ -41,3 +67,9 @@ def test_dcgain(self): sys = tf(84, [1, 2]) np.testing.assert_equal(sys.dcgain(), 42) np.testing.assert_equal(dcgain(sys), 42) + +def suite(): + return unittest.TestLoader().loadTestsFromTestCase(TestUtils) + +if __name__ == "__main__": + unittest.main() From 738524bdf7edf92f98d161face101fcf6096c4d5 Mon Sep 17 00:00:00 2001 From: Richard Murray Date: Mon, 13 May 2019 22:30:16 -0700 Subject: [PATCH 02/15] add unit test for StateSpace copy constructor --- control/tests/statesp_test.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/control/tests/statesp_test.py b/control/tests/statesp_test.py index 4ef2f9eb9..30fc2c913 100644 --- a/control/tests/statesp_test.py +++ b/control/tests/statesp_test.py @@ -568,6 +568,26 @@ def test_pole_static(self): np.testing.assert_array_equal(np.array([]), StateSpace([], [], [], [[1]]).pole()) + def test_copy_constructor(self): + # Create a set of matrices for a simple linear system + A = np.array([[-1]]) + B = np.array([[1]]) + C = np.array([[1]]) + D = np.array([[0]]) + + # Create the first linear system and a copy + linsys = StateSpace(A, B, C, D) + cpysys = StateSpace(linsys) + + # Change the original A matrix + A[0, 0] = -2 + np.testing.assert_array_equal(linsys.A, [[-1]]) # original value + np.testing.assert_array_equal(cpysys.A, [[-1]]) # original value + + # Change the A matrix for the original system + linsys.A[0, 0] = -3 + np.testing.assert_array_equal(cpysys.A, [[-1]]) # original value + def suite(): return unittest.TestLoader().loadTestsFromTestCase(TestStateSpace) From 57c8240fedee10897415a897592883b146850b11 Mon Sep 17 00:00:00 2001 From: Richard Murray Date: Sat, 18 May 2019 09:46:46 -0700 Subject: [PATCH 03/15] TRV: remove extra space --- control/tests/lti_test.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/control/tests/lti_test.py b/control/tests/lti_test.py index e10319a0c..6e2b0abbc 100644 --- a/control/tests/lti_test.py +++ b/control/tests/lti_test.py @@ -34,7 +34,7 @@ def test_issiso(self): self.assertEqual(issiso(sys, strict=True), True) # MIMO transfer function - sys = tf([[[-1, 41], [1]], [[1, 2], [3, 4]]], + sys = tf([[[-1, 41], [1]], [[1, 2], [3, 4]]], [[[1, 10], [1, 20]], [[1, 30], [1, 40]]]); self.assertEqual(issiso(sys), False) self.assertEqual(issiso(sys, strict=True), False) From 586f2467995dec7cce16914af63d90794ff1e95e Mon Sep 17 00:00:00 2001 From: Richard Murray Date: Sat, 18 May 2019 10:56:13 -0700 Subject: [PATCH 04/15] update issiso() tests for lack of slycot --- control/tests/lti_test.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/control/tests/lti_test.py b/control/tests/lti_test.py index 6e2b0abbc..65023302a 100644 --- a/control/tests/lti_test.py +++ b/control/tests/lti_test.py @@ -6,7 +6,7 @@ from control.xferfcn import tf from control import c2d from control.matlab import tf2ss -import numpy as np +from control.exception import slycot_check class TestUtils(unittest.TestCase): def test_pole(self): @@ -33,6 +33,8 @@ def test_issiso(self): self.assertEqual(issiso(sys), True) self.assertEqual(issiso(sys, strict=True), True) + @unittest.skipIf(not slycot_check(), "slycot not installed") + def test_issiso_mimo(self): # MIMO transfer function sys = tf([[[-1, 41], [1]], [[1, 2], [3, 4]]], [[[1, 10], [1, 20]], [[1, 30], [1, 40]]]); From bcdd83ee5224d50afb08a868f746d4956fac2ac4 Mon Sep 17 00:00:00 2001 From: Richard Murray Date: Sat, 25 May 2019 08:12:02 -0700 Subject: [PATCH 05/15] add unit tests for bdalg coverage + fix uncovered bug --- control/bdalg.py | 2 +- control/tests/bdalg_test.py | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/control/bdalg.py b/control/bdalg.py index 0f4a14c1a..08300e971 100644 --- a/control/bdalg.py +++ b/control/bdalg.py @@ -243,7 +243,7 @@ def feedback(sys1, sys2=1, sign=-1): elif isinstance(sys2, ss.StateSpace): sys1 = ss._convertToStateSpace(sys1) elif isinstance(sys2, frd.FRD): - sys1 = ss._convertToFRD(sys1) + sys1 = frd._convertToFRD(sys1, sys2.omega) else: # sys2 is a scalar. sys1 = tf._convert_to_transfer_function(sys1) sys2 = tf._convert_to_transfer_function(sys2) diff --git a/control/tests/bdalg_test.py b/control/tests/bdalg_test.py index 07775cb80..ae687df35 100644 --- a/control/tests/bdalg_test.py +++ b/control/tests/bdalg_test.py @@ -253,9 +253,27 @@ def assert_equal(x,y): assert_equal(ref.C, tst.C) assert_equal(ref.D, tst.D) + def test_feedback_args(self): + # Added 25 May 2019 to cover missing exception handling in feedback() + # If first argument is not LTI or convertable, generate an exception + args = ([1], self.sys2) + self.assertRaises(TypeError, ctrl.feedback, *args) + + # If second argument is not LTI or convertable, generate an exception + args = (self.sys1, np.array([1])) + self.assertRaises(TypeError, ctrl.feedback, *args) + + # Convert first argument to FRD, if needed + h = TransferFunction([1], [1, 2, 2]) + omega = np.logspace(-1, 2, 10) + frd = ctrl.FRD(h, omega) + sys = ctrl.feedback(1, frd) + self.assertTrue(isinstance(sys, ctrl.FRD)) + def suite(): return unittest.TestLoader().loadTestsFromTestCase(TestFeedback) + if __name__ == "__main__": unittest.main() From 6ad8602a4298cd2f55afaad1441dac1e1a7a0a79 Mon Sep 17 00:00:00 2001 From: Richard Murray Date: Sat, 25 May 2019 09:21:58 -0700 Subject: [PATCH 06/15] add unit tests for canonical coverage --- control/canonical.py | 4 +- control/tests/canonical_test.py | 72 +++++++++++++++++++++++++++++++-- 2 files changed, 71 insertions(+), 5 deletions(-) diff --git a/control/canonical.py b/control/canonical.py index c0244d75f..594c2e2d4 100644 --- a/control/canonical.py +++ b/control/canonical.py @@ -88,7 +88,9 @@ def reachable_form(xsys): # Transformation from one form to another Tzx = solve(Wrx.T, Wrz.T).T # matrix right division, Tzx = Wrz * inv(Wrx) - if matrix_rank(Tzx) != xsys.states: + # Check to make sure inversion was OK. Note that since we are inverting + # Wrx and we already checked its rank, this exception should never occur + if matrix_rank(Tzx) != xsys.states: # pragma: no cover raise ValueError("Transformation matrix singular to working precision.") # Finally, compute the output matrix diff --git a/control/tests/canonical_test.py b/control/tests/canonical_test.py index 5c73c1f49..7a70ef5d3 100644 --- a/control/tests/canonical_test.py +++ b/control/tests/canonical_test.py @@ -2,9 +2,10 @@ import unittest import numpy as np -from control import ss -from control.canonical import canonical_form - +from control import ss, tf +from control.canonical import canonical_form, reachable_form, \ + observable_form, modal_form +from control.exception import ControlNotImplemented class TestCanonical(unittest.TestCase): """Tests for the canonical forms class""" @@ -40,6 +41,11 @@ def test_reachable_form(self): np.testing.assert_array_almost_equal(sys_check.D, D_true) np.testing.assert_array_almost_equal(T_check, T_true) + # Reachable form only supports SISO + sys = tf([[ [1], [1] ]], [[ [1, 2, 1], [1, 2, 1] ]]) + np.testing.assert_raises(ControlNotImplemented, reachable_form, sys) + + def test_unreachable_system(self): """Test reachable canonical form with an unreachable system""" @@ -76,12 +82,50 @@ def test_modal_form(self): sys_check, T_check = canonical_form(ss(A, B, C, D), "modal") # Check against the true values - #TODO: Test in respect to ambiguous transformation (system characteristics?) + # TODO: Test in respect to ambiguous transformation (system characteristics?) np.testing.assert_array_almost_equal(sys_check.A, A_true) #np.testing.assert_array_almost_equal(sys_check.B, B_true) #np.testing.assert_array_almost_equal(sys_check.C, C_true) np.testing.assert_array_almost_equal(sys_check.D, D_true) #np.testing.assert_array_almost_equal(T_check, T_true) + + # Check conversion when there are complex eigenvalues + A_true = np.array([[-1, 1, 0, 0], + [-1, -1, 0, 0], + [ 0, 0, -2, 0], + [ 0, 0, 0, -3]]) + B_true = np.array([[0], [1], [0], [1]]) + C_true = np.array([[1, 0, 0, 1]]) + D_true = np.array([[0]]) + + A = np.linalg.solve(T_true, A_true) * T_true + B = np.linalg.solve(T_true, B_true) + C = C_true * T_true + D = D_true + + # Create state space system and convert to modal canonical form + sys_check, T_check = canonical_form(ss(A, B, C, D), 'modal') + + # Check A and D matrix, which are uniquely defined + np.testing.assert_array_almost_equal(sys_check.A, A_true) + np.testing.assert_array_almost_equal(sys_check.D, D_true) + + # B matrix should be all ones (or zero if not controllable) + # TODO: need to update modal_form() to implement this + if np.allclose(T_check, T_true): + np.testing.assert_array_almost_equal(sys_check.B, B_true) + np.testing.assert_array_almost_equal(sys_check.C, C_true) + + # Make sure Hankel coefficients are OK + from numpy.linalg import matrix_power + for i in range(A.shape[0]): + np.testing.assert_almost_equal( + np.dot(np.dot(C_true, matrix_power(A_true, i)), B_true), + np.dot(np.dot(C, matrix_power(A, i)), B)) + + # Modal form only supports SISO + sys = tf([[ [1], [1] ]], [[ [1, 2, 1], [1, 2, 1] ]]) + np.testing.assert_raises(ControlNotImplemented, modal_form, sys) def test_observable_form(self): """Test the observable canonical form""" @@ -114,6 +158,11 @@ def test_observable_form(self): np.testing.assert_array_almost_equal(sys_check.D, D_true) np.testing.assert_array_almost_equal(T_check, T_true) + # Observable form only supports SISO + sys = tf([[ [1], [1] ]], [[ [1, 2, 1], [1, 2, 1] ]]) + np.testing.assert_raises(ControlNotImplemented, observable_form, sys) + + def test_unobservable_system(self): """Test observable canonical form with an unobservable system""" @@ -126,3 +175,18 @@ def test_unobservable_system(self): # Check if an exception is raised np.testing.assert_raises(ValueError, canonical_form, sys, "observable") + + def test_arguments(self): + # Additional unit tests added on 25 May 2019 to increase coverage + + # Unknown canonical forms should generate exception + sys = tf([1], [1, 2, 1]) + np.testing.assert_raises( + ControlNotImplemented, canonical_form, sys, 'unknown') + +def suite(): + return unittest.TestLoader().loadTestsFromTestCase(TestFeedback) + + +if __name__ == "__main__": + unittest.main() From 7e8a6240c99822c32e8916daaf4080d23d060540 Mon Sep 17 00:00:00 2001 From: Richard Murray Date: Sat, 25 May 2019 10:46:40 -0700 Subject: [PATCH 07/15] add unit tests for config coverage + update docs --- control/config.py | 2 +- control/freqplot.py | 21 +++-- control/tests/config_test.py | 166 +++++++++++++++++++++++++++++++++++ 3 files changed, 181 insertions(+), 8 deletions(-) create mode 100644 control/tests/config_test.py diff --git a/control/config.py b/control/config.py index 10ab8a1ed..3f2bb0172 100644 --- a/control/config.py +++ b/control/config.py @@ -39,4 +39,4 @@ def use_fbs_defaults(): # Bode plot defaults global bode_dB; bode_dB = False global bode_deg; bode_deg = True - global bode_Hz; bode_Hz = True + global bode_Hz; bode_Hz = False diff --git a/control/freqplot.py b/control/freqplot.py index 6600a5b4a..85880740c 100644 --- a/control/freqplot.py +++ b/control/freqplot.py @@ -603,18 +603,24 @@ def default_frequency_range(syslist, Hz=None, number_of_samples=None, ---------- syslist : list of LTI List of linear input/output systems (single system is OK) - Hz: boolean + + Hz : bool If True, the limits (first and last value) of the frequencies are set to full decades in Hz so it fits plotting with logarithmic scale in Hz otherwise in rad/s. Omega is always returned in rad/sec. - number_of_samples: int - Number of samples to generate - feature_periphery_decade: float + + number_of_samples : int, optional + Number of samples to generate. Defaults to ``numpy.logspace`` default + value. + + feature_periphery_decade : float, optional Defines how many decades shall be included in the frequency range on both sides of features (poles, zeros). - Example: If there is a feature, e.g. a pole, at 1Hz and feature_periphery_decade=1. - then the range of frequencies shall span 0.1 .. 10 Hz. - The default value is read from config.bode_feature_periphery_decade. + + Example: If there is a feature, e.g. a pole, at 1 Hz and + feature_periphery_decade=1., then the range of frequencies shall span + 0.1 .. 10 Hz. The default value is read from + ``config.bode_feature_periphery_decade``. Returns ------- @@ -626,6 +632,7 @@ def default_frequency_range(syslist, Hz=None, number_of_samples=None, >>> from matlab import ss >>> sys = ss("1. -2; 3. -4", "5.; 7", "6. 8", "9.") >>> omega = default_frequency_range(sys) + """ # This code looks at the poles and zeros of all of the systems that # we are plotting and sets the frequency range to be one decade above diff --git a/control/tests/config_test.py b/control/tests/config_test.py new file mode 100644 index 000000000..7008f5328 --- /dev/null +++ b/control/tests/config_test.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python +# +# config_test.py - test config module +# RMM, 25 may 2019 +# +# This test suite checks the functionality of the config module + +import unittest +import numpy as np +import control as ct +import matplotlib.pyplot as plt +from math import pi, log10 + +class TestConfig(unittest.TestCase): + def setUp(self): + # Create a simple second order system to use for testing + self.sys = ct.tf([10], [1, 2, 1]) + + def test_fbs_bode(self): + ct.use_fbs_defaults(); + + # Generate a Bode plot + plt.figure() + omega = np.logspace(-3, 3, 100) + ct.bode_plot(self.sys, omega) + + # Get the magnitude line + mag_axis = plt.gcf().axes[0] + mag_line = mag_axis.get_lines() + mag_data = mag_line[0].get_data() + mag_x, mag_y = mag_data + + # Make sure the x-axis is in rad/sec and y-axis is in natural units + np.testing.assert_almost_equal(mag_x[0], 0.001, decimal=6) + np.testing.assert_almost_equal(mag_y[0], 10, decimal=3) + + # Get the phase line + phase_axis = plt.gcf().axes[1] + phase_line = phase_axis.get_lines() + phase_data = phase_line[0].get_data() + phase_x, phase_y = phase_data + + # Make sure the x-axis is in rad/sec and y-axis is in degrees + np.testing.assert_almost_equal(phase_x[-1], 1000, decimal=0) + np.testing.assert_almost_equal(phase_y[-1], -180, decimal=0) + + # Override the defaults and make sure that works as well + plt.figure() + ct.bode_plot(self.sys, omega, dB=True) + mag_x, mag_y = (((plt.gcf().axes[0]).get_lines())[0]).get_data() + np.testing.assert_almost_equal(mag_y[0], 20*log10(10), decimal=3) + + plt.figure() + ct.bode_plot(self.sys, omega, Hz=True) + mag_x, mag_y = (((plt.gcf().axes[0]).get_lines())[0]).get_data() + np.testing.assert_almost_equal(mag_x[0], 0.001 / (2*pi), decimal=6) + + plt.figure() + ct.bode_plot(self.sys, omega, deg=False) + phase_x, phase_y = (((plt.gcf().axes[1]).get_lines())[0]).get_data() + np.testing.assert_almost_equal(phase_y[-1], -pi, decimal=2) + + def test_matlab_bode(self): + ct.use_matlab_defaults(); + + # Generate a Bode plot + plt.figure() + omega = np.logspace(-3, 3, 100) + ct.bode_plot(self.sys, omega) + + # Get the magnitude line + mag_axis = plt.gcf().axes[0] + mag_line = mag_axis.get_lines() + mag_data = mag_line[0].get_data() + mag_x, mag_y = mag_data + + # Make sure the x-axis is in Hertz and y-axis is in dB + np.testing.assert_almost_equal(mag_x[0], 0.001 / (2*pi), decimal=6) + np.testing.assert_almost_equal(mag_y[0], 20*log10(10), decimal=3) + + # Get the phase line + phase_axis = plt.gcf().axes[1] + phase_line = phase_axis.get_lines() + phase_data = phase_line[0].get_data() + phase_x, phase_y = phase_data + + # Make sure the x-axis is in Hertz and y-axis is in degrees + np.testing.assert_almost_equal(phase_x[-1], 1000 / (2*pi), decimal=1) + np.testing.assert_almost_equal(phase_y[-1], -180, decimal=0) + + # Override the defaults and make sure that works as well + plt.figure() + ct.bode_plot(self.sys, omega, dB=True) + mag_x, mag_y = (((plt.gcf().axes[0]).get_lines())[0]).get_data() + np.testing.assert_almost_equal(mag_y[0], 20*log10(10), decimal=3) + + plt.figure() + ct.bode_plot(self.sys, omega, Hz=True) + mag_x, mag_y = (((plt.gcf().axes[0]).get_lines())[0]).get_data() + np.testing.assert_almost_equal(mag_x[0], 0.001 / (2*pi), decimal=6) + + plt.figure() + ct.bode_plot(self.sys, omega, deg=False) + phase_x, phase_y = (((plt.gcf().axes[1]).get_lines())[0]).get_data() + np.testing.assert_almost_equal(phase_y[-1], -pi, decimal=2) + + def test_custom_bode_default(self): + ct.bode_dB = True + ct.bode_deg = True + ct.bode_Hz = True + + # Generate a Bode plot + plt.figure() + omega = np.logspace(-3, 3, 100) + ct.bode_plot(self.sys, omega, dB=True) + mag_x, mag_y = (((plt.gcf().axes[0]).get_lines())[0]).get_data() + np.testing.assert_almost_equal(mag_y[0], 20*log10(10), decimal=3) + + # Override defaults + plt.figure() + ct.bode_plot(self.sys, omega, Hz=True, deg=False, dB=True) + mag_x, mag_y = (((plt.gcf().axes[0]).get_lines())[0]).get_data() + phase_x, phase_y = (((plt.gcf().axes[1]).get_lines())[0]).get_data() + np.testing.assert_almost_equal(mag_x[0], 0.001 / (2*pi), decimal=6) + np.testing.assert_almost_equal(mag_y[0], 20*log10(10), decimal=3) + np.testing.assert_almost_equal(phase_y[-1], -pi, decimal=2) + + def test_bode_number_of_samples(self): + # Set the number of samples (default is 50, from np.logspace) + mag_ret, phase_ret, omega_ret = ct.bode_plot(self.sys, omega_num=87) + self.assertEqual(len(mag_ret), 87) + + # Change the default number of samples + ct.config.bode_number_of_samples = 76 + mag_ret, phase_ret, omega_ret = ct.bode_plot(self.sys) + self.assertEqual(len(mag_ret), 76) + + # Override the default number of samples + mag_ret, phase_ret, omega_ret = ct.bode_plot(self.sys, omega_num=87) + self.assertEqual(len(mag_ret), 87) + + def test_bode_feature_periphery_decade(self): + # Generate a sample Bode plot to figure out the range it uses + mag_ret, phase_ret, omega_ret = ct.bode_plot(self.sys, Hz=False) + omega_min, omega_max = omega_ret[[0, -1]] + + # Reset the periphery decade value (should add one decade on each end) + ct.config.bode_feature_periphery_decade = 2 + mag_ret, phase_ret, omega_ret = ct.bode_plot(self.sys, Hz=False) + np.testing.assert_almost_equal(omega_ret[0], omega_min/10) + np.testing.assert_almost_equal(omega_ret[-1], omega_max * 10) + + # Make sure it also works in rad/sec, in opposite direction + mag_ret, phase_ret, omega_ret = ct.bode_plot(self.sys, Hz=True) + omega_min, omega_max = omega_ret[[0, -1]] + ct.config.bode_feature_periphery_decade = 1 + mag_ret, phase_ret, omega_ret = ct.bode_plot(self.sys, Hz=True) + np.testing.assert_almost_equal(omega_ret[0], omega_min*10) + np.testing.assert_almost_equal(omega_ret[-1], omega_max/10) + +def suite(): + return unittest.TestLoader().loadTestsFromTestCase(TestTimeresp) + + +if __name__ == '__main__': + unittest.main() From 20f44ae89ee0e62f470bb765528ca607e2d407ab Mon Sep 17 00:00:00 2001 From: Richard Murray Date: Sat, 25 May 2019 10:53:14 -0700 Subject: [PATCH 08/15] add test to complete canonical coverage for modal form, mixed real/complex --- control/tests/canonical_test.py | 34 +++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/control/tests/canonical_test.py b/control/tests/canonical_test.py index 7a70ef5d3..1f1828f50 100644 --- a/control/tests/canonical_test.py +++ b/control/tests/canonical_test.py @@ -123,6 +123,40 @@ def test_modal_form(self): np.dot(np.dot(C_true, matrix_power(A_true, i)), B_true), np.dot(np.dot(C, matrix_power(A, i)), B)) + # Reorder rows to get complete coverage (real eigenvalue cxrtvfirst) + A_true = np.array([[-1, 0, 0, 0], + [ 0, -2, 1, 0], + [ 0, -1, -2, 0], + [ 0, 0, 0, -3]]) + B_true = np.array([[0], [0], [1], [1]]) + C_true = np.array([[0, 1, 0, 1]]) + D_true = np.array([[0]]) + + A = np.linalg.solve(T_true, A_true) * T_true + B = np.linalg.solve(T_true, B_true) + C = C_true * T_true + D = D_true + + # Create state space system and convert to modal canonical form + sys_check, T_check = canonical_form(ss(A, B, C, D), 'modal') + + # Check A and D matrix, which are uniquely defined + np.testing.assert_array_almost_equal(sys_check.A, A_true) + np.testing.assert_array_almost_equal(sys_check.D, D_true) + + # B matrix should be all ones (or zero if not controllable) + # TODO: need to update modal_form() to implement this + if np.allclose(T_check, T_true): + np.testing.assert_array_almost_equal(sys_check.B, B_true) + np.testing.assert_array_almost_equal(sys_check.C, C_true) + + # Make sure Hankel coefficients are OK + from numpy.linalg import matrix_power + for i in range(A.shape[0]): + np.testing.assert_almost_equal( + np.dot(np.dot(C_true, matrix_power(A_true, i)), B_true), + np.dot(np.dot(C, matrix_power(A, i)), B)) + # Modal form only supports SISO sys = tf([[ [1], [1] ]], [[ [1, 2, 1], [1, 2, 1] ]]) np.testing.assert_raises(ControlNotImplemented, modal_form, sys) From 3a68bd44e97df5ca6136857607b8ed67e46caaf9 Mon Sep 17 00:00:00 2001 From: Richard Murray Date: Sat, 25 May 2019 12:14:15 -0700 Subject: [PATCH 09/15] fix problem with figures persisting beyond config_test --- control/config.py | 12 ++++++++++++ control/tests/config_test.py | 24 ++++++++++++++++++++++++ control/tests/freqresp_test.py | 1 + 3 files changed, 37 insertions(+) diff --git a/control/config.py b/control/config.py index 3f2bb0172..c90b9e16b 100644 --- a/control/config.py +++ b/control/config.py @@ -14,6 +14,16 @@ bode_number_of_samples = None # Bode plot number of samples bode_feature_periphery_decade = 1.0 # Bode plot feature periphery in decades + +def reset_defaults(): + """Reset configuration values to their default values.""" + global bode_dB; bode_dB = False + global bode_deg; bode_deg = True + global bode_Hz; bode_Hz = False + global bode_number_of_samples; bode_number_of_samples = None + global bode_feature_periphery_decade; bode_feature_periphery_decade = 1.0 + + # Set defaults to match MATLAB def use_matlab_defaults(): """ @@ -27,6 +37,7 @@ def use_matlab_defaults(): global bode_deg; bode_deg = True global bode_Hz; bode_Hz = True + # Set defaults to match FBS (Astrom and Murray) def use_fbs_defaults(): """ @@ -40,3 +51,4 @@ def use_fbs_defaults(): global bode_dB; bode_dB = False global bode_deg; bode_deg = True global bode_Hz; bode_Hz = False + diff --git a/control/tests/config_test.py b/control/tests/config_test.py index 7008f5328..6d485f822 100644 --- a/control/tests/config_test.py +++ b/control/tests/config_test.py @@ -59,6 +59,8 @@ def test_fbs_bode(self): ct.bode_plot(self.sys, omega, deg=False) phase_x, phase_y = (((plt.gcf().axes[1]).get_lines())[0]).get_data() np.testing.assert_almost_equal(phase_y[-1], -pi, decimal=2) + + ct.reset_defaults() def test_matlab_bode(self): ct.use_matlab_defaults(); @@ -104,6 +106,8 @@ def test_matlab_bode(self): phase_x, phase_y = (((plt.gcf().axes[1]).get_lines())[0]).get_data() np.testing.assert_almost_equal(phase_y[-1], -pi, decimal=2) + ct.reset_defaults() + def test_custom_bode_default(self): ct.bode_dB = True ct.bode_deg = True @@ -125,6 +129,8 @@ def test_custom_bode_default(self): np.testing.assert_almost_equal(mag_y[0], 20*log10(10), decimal=3) np.testing.assert_almost_equal(phase_y[-1], -pi, decimal=2) + ct.reset_defaults() + def test_bode_number_of_samples(self): # Set the number of samples (default is 50, from np.logspace) mag_ret, phase_ret, omega_ret = ct.bode_plot(self.sys, omega_num=87) @@ -139,8 +145,11 @@ def test_bode_number_of_samples(self): mag_ret, phase_ret, omega_ret = ct.bode_plot(self.sys, omega_num=87) self.assertEqual(len(mag_ret), 87) + ct.reset_defaults() + def test_bode_feature_periphery_decade(self): # Generate a sample Bode plot to figure out the range it uses + ct.reset_defaults() # Make sure starting state is correct mag_ret, phase_ret, omega_ret = ct.bode_plot(self.sys, Hz=False) omega_min, omega_max = omega_ret[[0, -1]] @@ -158,6 +167,21 @@ def test_bode_feature_periphery_decade(self): np.testing.assert_almost_equal(omega_ret[0], omega_min*10) np.testing.assert_almost_equal(omega_ret[-1], omega_max/10) + ct.reset_defaults() + + def test_reset_defaults(self): + ct.use_matlab_defaults() + ct.reset_defaults() + self.assertEquals(ct.config.bode_dB, False) + self.assertEquals(ct.config.bode_deg, True) + self.assertEquals(ct.config.bode_Hz, False) + self.assertEquals(ct.config.bode_number_of_samples, None) + self.assertEquals(ct.config.bode_feature_periphery_decade, 1.0) + + def tearDown(self): + # Get rid of any figures that we created + plt.close('all') + def suite(): return unittest.TestLoader().loadTestsFromTestCase(TestTimeresp) diff --git a/control/tests/freqresp_test.py b/control/tests/freqresp_test.py index a06e4e8e2..05247b46b 100644 --- a/control/tests/freqresp_test.py +++ b/control/tests/freqresp_test.py @@ -113,6 +113,7 @@ def test_bode_margin(self): num = [1000] den = [1, 25, 100, 0] sys = ctrl.tf(num, den) + plt.figure() ctrl.bode_plot(sys, margins=True,dB=False,deg = True, Hz=False) fig = plt.gcf() allaxes = fig.get_axes() From 0c8756d9865816508c16a0a634f19a9704b0b5c2 Mon Sep 17 00:00:00 2001 From: Richard Murray Date: Sat, 25 May 2019 16:00:47 -0700 Subject: [PATCH 10/15] add unit tests for frdata converage + fix small, uncovered errors --- control/frdata.py | 18 +++--- control/tests/frd_test.py | 123 +++++++++++++++++++++++++++++++++++++- 2 files changed, 133 insertions(+), 8 deletions(-) diff --git a/control/frdata.py b/control/frdata.py index d34200455..82da8420e 100644 --- a/control/frdata.py +++ b/control/frdata.py @@ -49,6 +49,7 @@ """ # External function declarations +from warnings import warn import numpy as np from numpy import angle, array, empty, ones, \ real, imag, matrix, absolute, eye, linalg, where, dot @@ -187,9 +188,10 @@ def __add__(self, other): if isinstance(other, FRD): # verify that the frequencies match - if (other.omega != self.omega).any(): - print("Warning: frequency points do not match; expect" - " truncation and interpolation") + if len(other.omega) != len(self.omega) or \ + (other.omega != self.omega).any(): + warn("Frequency points do not match; expect" + " truncation and interpolation.") # Convert the second argument to a frequency response function. # or re-base the frd to the current omega (if needed) @@ -340,8 +342,9 @@ def evalfr(self, omega): intermediate values. """ - warn("FRD.evalfr(omega) will be deprecated in a future release of python-control; use sys.eval(omega) instead", - PendingDeprecationWarning) + warn("FRD.evalfr(omega) will be deprecated in a future release " + "of python-control; use sys.eval(omega) instead", + PendingDeprecationWarning) # pragma: no coverage return self._evalfr(omega) # Define the `eval` function to evaluate an FRD at a given (real) @@ -352,7 +355,7 @@ def evalfr(self, omega): def eval(self, omega): """Evaluate a transfer function at a single angular frequency. - self._evalfr(omega) returns the value of the frequency response + self.evalfr(omega) returns the value of the frequency response at frequency omega. Note that a "normal" FRD only returns values for which there is an @@ -462,7 +465,8 @@ def _convertToFRD(sys, omega, inputs=1, outputs=1): if isinstance(sys, FRD): omega.sort() - if (abs(omega - sys.omega) < FRD.epsw).all(): + if len(omega) == len(sys.omega) and \ + (abs(omega - sys.omega) < FRD.epsw).all(): # frequencies match, and system was already frd; simply use return sys diff --git a/control/tests/frd_test.py b/control/tests/frd_test.py index dca1c762c..9312298a9 100644 --- a/control/tests/frd_test.py +++ b/control/tests/frd_test.py @@ -6,6 +6,7 @@ import unittest import numpy as np +import control as ct from control.statesp import StateSpace from control.xferfcn import TransferFunction from control.frdata import FRD, _convertToFRD @@ -22,6 +23,7 @@ class TestFRD(unittest.TestCase): def testBadInputType(self): """Give the constructor invalid input types.""" self.assertRaises(ValueError, FRD) + self.assertRaises(TypeError, FRD, [1]) def testInconsistentDimension(self): self.assertRaises(TypeError, FRD, [1, 1], [1, 2, 3]) @@ -278,7 +280,126 @@ def testAgainstOctave(self): np.exp(1j*f1.freqresp([1.0])[1])).reshape(3, 2), np.matrix('0.4-0.2j 0; 0 0.1-0.2j; 0 0.3-0.1j')) - + def test_string_representation(self): + sys = FRD([1, 2, 3], [4, 5, 6]) + print(sys) # Just print without checking + + def test_frequency_mismatch(self): + # Overlapping but non-equal frequency ranges + sys1 = FRD([1, 2, 3], [4, 5, 6]) + sys2 = FRD([2, 3, 4], [5, 6, 7]) + self.assertRaises(NotImplementedError, FRD.__add__, sys1, sys2) + + # One frequency range is a subset of another + sys1 = FRD([1, 2, 3], [4, 5, 6]) + sys2 = FRD([2, 3], [4, 5]) + self.assertRaises(NotImplementedError, FRD.__add__, sys1, sys2) + + def test_size_mismatch(self): + sys1 = FRD(ct.rss(2, 2, 2), np.logspace(-1, 1, 10)) + + # Different number of inputs + sys2 = FRD(ct.rss(3, 1, 2), np.logspace(-1, 1, 10)) + self.assertRaises(ValueError, FRD.__add__, sys1, sys2) + + # Different number of outputs + sys2 = FRD(ct.rss(3, 2, 1), np.logspace(-1, 1, 10)) + self.assertRaises(ValueError, FRD.__add__, sys1, sys2) + + # Inputs and outputs don't match + self.assertRaises(ValueError, FRD.__mul__, sys2, sys1) + + # Feedback mismatch + self.assertRaises(ValueError, FRD.feedback, sys2, sys1) + + def test_operator_conversion(self): + sys_tf = ct.tf([1], [1, 2, 1]) + frd_tf = FRD(sys_tf, np.logspace(-1, 1, 10)) + frd_2 = FRD(2 * np.ones(10), np.logspace(-1, 1, 10)) + + # Make sure that we can add, multiply, and feedback constants + sys_add = frd_tf + 2 + chk_add = frd_tf + frd_2 + np.testing.assert_array_almost_equal(sys_add.omega, chk_add.omega) + np.testing.assert_array_almost_equal(sys_add.fresp, chk_add.fresp) + + sys_radd = 2 + frd_tf + chk_radd = frd_2 + frd_tf + np.testing.assert_array_almost_equal(sys_radd.omega, chk_radd.omega) + np.testing.assert_array_almost_equal(sys_radd.fresp, chk_radd.fresp) + + sys_sub = frd_tf - 2 + chk_sub = frd_tf - frd_2 + np.testing.assert_array_almost_equal(sys_sub.omega, chk_sub.omega) + np.testing.assert_array_almost_equal(sys_sub.fresp, chk_sub.fresp) + + sys_rsub = 2 - frd_tf + chk_rsub = frd_2 - frd_tf + np.testing.assert_array_almost_equal(sys_rsub.omega, chk_rsub.omega) + np.testing.assert_array_almost_equal(sys_rsub.fresp, chk_rsub.fresp) + + sys_mul = frd_tf * 2 + chk_mul = frd_tf * frd_2 + np.testing.assert_array_almost_equal(sys_mul.omega, chk_mul.omega) + np.testing.assert_array_almost_equal(sys_mul.fresp, chk_mul.fresp) + + sys_rmul = 2 * frd_tf + chk_rmul = frd_2 * frd_tf + np.testing.assert_array_almost_equal(sys_rmul.omega, chk_rmul.omega) + np.testing.assert_array_almost_equal(sys_rmul.fresp, chk_rmul.fresp) + + sys_rdiv = 2 / frd_tf + chk_rdiv = frd_2 / frd_tf + np.testing.assert_array_almost_equal(sys_rdiv.omega, chk_rdiv.omega) + np.testing.assert_array_almost_equal(sys_rdiv.fresp, chk_rdiv.fresp) + + sys_pow = frd_tf**2 + chk_pow = FRD(sys_tf**2, np.logspace(-1, 1, 10)) + np.testing.assert_array_almost_equal(sys_pow.omega, chk_pow.omega) + np.testing.assert_array_almost_equal(sys_pow.fresp, chk_pow.fresp) + + sys_pow = frd_tf**-2 + chk_pow = FRD(sys_tf**-2, np.logspace(-1, 1, 10)) + np.testing.assert_array_almost_equal(sys_pow.omega, chk_pow.omega) + np.testing.assert_array_almost_equal(sys_pow.fresp, chk_pow.fresp) + + # Assertion error if we try to raise to a non-integer power + self.assertRaises(ValueError, FRD.__pow__, frd_tf, 0.5) + + # Selected testing on transfer function conversion + sys_add = frd_2 + sys_tf + chk_add = frd_2 + frd_tf + np.testing.assert_array_almost_equal(sys_add.omega, chk_add.omega) + np.testing.assert_array_almost_equal(sys_add.fresp, chk_add.fresp) + + # Input/output mismatch size mismatch in rmul + sys1 = FRD(ct.rss(2, 2, 2), np.logspace(-1, 1, 10)) + self.assertRaises(ValueError, FRD.__rmul__, frd_2, sys1) + + # Make sure conversion of something random generates exception + self.assertRaises(TypeError, FRD.__add__, frd_tf, 'string') + + def test_eval(self): + sys_tf = ct.tf([1], [1, 2, 1]) + frd_tf = FRD(sys_tf, np.logspace(-1, 1, 3)) + np.testing.assert_almost_equal(sys_tf.evalfr(1), frd_tf.eval(1)) + + # Should get an error if we evaluate at an unknown frequency + self.assertRaises(ValueError, frd_tf.eval, 2) + + # FRD.eval() is being deprecated + import warnings + with warnings.catch_warnings(record=True) as w: + # 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 + frd_tf.evalfr(1.) + assert len(w) == 1 + assert issubclass(w[-1].category, PendingDeprecationWarning) + + def suite(): return unittest.TestLoader().loadTestsFromTestCase(TestFRD) From 508775b25e730cfa3f88fb5e17c870d6763e7c68 Mon Sep 17 00:00:00 2001 From: Richard Murray Date: Sat, 25 May 2019 16:01:54 -0700 Subject: [PATCH 11/15] derive control exceptions from standard exceptions --- control/exception.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/control/exception.py b/control/exception.py index 2c4f29704..9dde243af 100644 --- a/control/exception.py +++ b/control/exception.py @@ -39,24 +39,24 @@ # # $Id$ -class ControlSlycot(Exception): +class ControlSlycot(ImportError): """Exception for Slycot import. Used when we can't import a function from the slycot package""" pass -class ControlDimension(Exception): +class ControlDimension(ValueError): """Raised when dimensions of system objects are not correct""" pass -class ControlArgument(Exception): +class ControlArgument(TypeError): """Raised when arguments to a function are not correct""" pass -class ControlMIMONotImplemented(Exception): +class ControlMIMONotImplemented(NotImplementedError): """Function is not currently implemented for MIMO systems""" pass -class ControlNotImplemented(Exception): +class ControlNotImplemented(NotImplementedError): """Functionality is not yet implemented""" pass From 82a0a83e92cc592e96b36d31bcd87c7e5a4a992c Mon Sep 17 00:00:00 2001 From: Richard Murray Date: Sat, 25 May 2019 16:02:18 -0700 Subject: [PATCH 12/15] flag coverage issue in dtime --- control/dtime.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/control/dtime.py b/control/dtime.py index 36053da33..211aa86a1 100644 --- a/control/dtime.py +++ b/control/dtime.py @@ -112,6 +112,9 @@ def c2d(sysc, Ts, method='zoh'): ''' # Call the sample_system() function to do the work sysd = sample_system(sysc, Ts, method) + + # TODO: is this check needed? If sysc is StateSpace, sysd is too? if isinstance(sysc, StateSpace) and not isinstance(sysd, StateSpace): - return _convertToStateSpace(sysd) + return _convertToStateSpace(sysd) # pragma: no cover + return sysd From af49bd64e2832fbd434f90b4e3d9911f9bcd9e85 Mon Sep 17 00:00:00 2001 From: Richard Murray Date: Sat, 25 May 2019 18:47:07 -0700 Subject: [PATCH 13/15] fix py2.7 issue with repeated warnings not showing up --- control/tests/frd_test.py | 31 +++++++++++++++++++++++-------- control/tests/xferfcn_test.py | 21 +++++++++++++++------ 2 files changed, 38 insertions(+), 14 deletions(-) diff --git a/control/tests/frd_test.py b/control/tests/frd_test.py index 9312298a9..1a6a263f3 100644 --- a/control/tests/frd_test.py +++ b/control/tests/frd_test.py @@ -5,6 +5,7 @@ import unittest +import sys as pysys import numpy as np import control as ct from control.statesp import StateSpace @@ -387,17 +388,31 @@ def test_eval(self): # Should get an error if we evaluate at an unknown frequency self.assertRaises(ValueError, frd_tf.eval, 2) - # FRD.eval() is being deprecated + # This test only works in Python 3 due to a conflict with the same + # warning type in other test modules (frd_test.py). See + # https://bugs.python.org/issue4180 for more details + @unittest.skipIf(pysys.version_info < (3, 0), "test requires Python 3+") + def test_evalfr_deprecated(self): + sys_tf = ct.tf([1], [1, 2, 1]) + frd_tf = FRD(sys_tf, np.logspace(-1, 1, 3)) + + # Deprecated version of the call (should generate warning) + import warnings + with warnings.catch_warnings(): + # Make warnings generate an exception + warnings.simplefilter('error') + + # Make sure that we get a pending deprecation warning + self.assertRaises(PendingDeprecationWarning, frd_tf.evalfr, 1.) + + # FRD.evalfr() is being deprecated import warnings - with warnings.catch_warnings(record=True) as w: - # Set up warnings filter to only show warnings in control module - warnings.filterwarnings("ignore") - warnings.filterwarnings("always", module="control") + with warnings.catch_warnings(): + # Make warnings generate an exception + warnings.simplefilter('error') # Make sure that we get a pending deprecation warning - frd_tf.evalfr(1.) - assert len(w) == 1 - assert issubclass(w[-1].category, PendingDeprecationWarning) + self.assertRaises(PendingDeprecationWarning, frd_tf.evalfr, 1.) def suite(): diff --git a/control/tests/xferfcn_test.py b/control/tests/xferfcn_test.py index 35e411bea..d96274072 100644 --- a/control/tests/xferfcn_test.py +++ b/control/tests/xferfcn_test.py @@ -4,6 +4,7 @@ # RMM, 30 Mar 2011 (based on TestXferFcn from v0.4a) import unittest +import sys as pysys import numpy as np from control.statesp import StateSpace, _convertToStateSpace, rss from control.xferfcn import TransferFunction, _convert_to_transfer_function, ss2tf @@ -332,13 +333,21 @@ def test_evalfr_siso(self): np.testing.assert_array_almost_equal(sys._evalfr(32.), np.array([[0.00281959302585077 - 0.030628473607392j]])) + # This test only works in Python 3 due to a conflict with the same + # warning type in other test modules (frd_test.py). See + # https://bugs.python.org/issue4180 for more details + @unittest.skipIf(pysys.version_info < (3, 0), "test requires Python 3+") + def test_evalfr_deprecated(self): + sys = TransferFunction([1., 3., 5], [1., 6., 2., -1]) + # Deprecated version of the call (should generate warning) import warnings - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter("always") - sys.evalfr(1.) - assert len(w) == 1 - assert issubclass(w[-1].category, PendingDeprecationWarning) + with warnings.catch_warnings(): + # Make warnings generate an exception + warnings.simplefilter('error') + + # Make sure that we get a pending deprecation warning + self.assertRaises(PendingDeprecationWarning, sys.evalfr, 1.) @unittest.skipIf(not slycot_check(), "slycot not installed") def test_evalfr_mimo(self): @@ -597,7 +606,7 @@ def test_dcgain_discr(self): # summer # causes a RuntimeWarning due to the divide by zero - sys = TransferFunction([1,-1], [1], True) + sys = TransferFunction([1, -1], [1], True) np.testing.assert_equal(sys.dcgain(), 0) def test_ss2tf(self): From 9f7fce5828bf73e23a189c5d545d1876ce2d6c1c Mon Sep 17 00:00:00 2001 From: Richard Murray Date: Sat, 25 May 2019 22:59:33 -0700 Subject: [PATCH 14/15] add unit tests for xferfcn converage --- control/tests/discrete_test.py | 1 + control/tests/xferfcn_test.py | 181 +++++++++++++++++++++++++++------ control/xferfcn.py | 3 +- 3 files changed, 153 insertions(+), 32 deletions(-) diff --git a/control/tests/discrete_test.py b/control/tests/discrete_test.py index f2e705ee5..f08a5fa5e 100644 --- a/control/tests/discrete_test.py +++ b/control/tests/discrete_test.py @@ -340,6 +340,7 @@ def test_sample_system(self): # Check errors self.assertRaises(ValueError, sample_system, self.siso_ss1d, 1) + self.assertRaises(ValueError, sample_system, self.siso_tf1d, 1) self.assertRaises(ValueError, sample_system, self.siso_ss1, 1, 'unknown') def test_sample_ss(self): diff --git a/control/tests/xferfcn_test.py b/control/tests/xferfcn_test.py index d96274072..cf4ac78da 100644 --- a/control/tests/xferfcn_test.py +++ b/control/tests/xferfcn_test.py @@ -7,9 +7,11 @@ import sys as pysys import numpy as np from control.statesp import StateSpace, _convertToStateSpace, rss -from control.xferfcn import TransferFunction, _convert_to_transfer_function, ss2tf +from control.xferfcn import TransferFunction, _convert_to_transfer_function, \ + ss2tf from control.lti import evalfr from control.exception import slycot_check +from control.dtime import sample_system # from control.lti import isdtime @@ -24,23 +26,53 @@ class TestXferFcn(unittest.TestCase): def test_constructor_bad_input_type(self): """Give the constructor invalid input types.""" - self.assertRaises(TypeError, TransferFunction, [[0., 1.], [2., 3.]], [[5., 2.], [3., 0.]]) + # MIMO requires lists of lists of vectors (not lists of vectors) + self.assertRaises( + TypeError, + TransferFunction, [[0., 1.], [2., 3.]], [[5., 2.], [3., 0.]]) + TransferFunction([[ [0., 1.], [2., 3.] ]], [[ [5., 2.], [3., 0.] ]]) + + # Single argument of the wrong type + self.assertRaises(TypeError, TransferFunction, [1]) + + # Too many arguments + self.assertRaises(ValueError, TransferFunction, 1, 2, 3, 4) + + # Different numbers of elements in numerator rows + self.assertRaises( + ValueError, + TransferFunction, [ [[0, 1], [2, 3]], + [[4, 5]] ], + [ [[6, 7], [4, 5]], + [[2, 3], [0, 1]] ]) + self.assertRaises( + ValueError, + TransferFunction, [ [[0, 1], [2, 3]], + [[4, 5], [6, 7]] ], + [ [[6, 7], [4, 5]], + [[2, 3]] ]) + TransferFunction( # This version is OK + [ [[0, 1], [2, 3]], [[4, 5], [6, 7]] ], + [ [[6, 7], [4, 5]], [[2, 3], [0, 1]] ]) def test_constructor_inconsistent_dimension(self): - """Give the constructor a numerator and denominator of different - sizes.""" + """Give constructor numerators, denominators of different sizes.""" - self.assertRaises(ValueError, TransferFunction, [[[1.]]], [[[1.], [2., 3.]]]) - self.assertRaises(ValueError, TransferFunction, [[[1.]]], [[[1.]], [[2., 3.]]]) - self.assertRaises(ValueError, TransferFunction, [[[1.]]], - [[[1.], [1., 2.]], [[5., 2.], [2., 3.]]]) + self.assertRaises(ValueError, TransferFunction, + [[[1.]]], [[[1.], [2., 3.]]]) + self.assertRaises(ValueError, TransferFunction, + [[[1.]]], [[[1.]], [[2., 3.]]]) + self.assertRaises(ValueError, TransferFunction, + [[[1.]]], [[[1.], [1., 2.]], [[5., 2.], [2., 3.]]]) def test_constructor_inconsistent_columns(self): """Give the constructor inputs that do not have the same number of columns in each row.""" - self.assertRaises(ValueError, TransferFunction, 1., [[[1.]], [[2.], [3.]]]) - self.assertRaises(ValueError, TransferFunction, [[[1.]], [[2.], [3.]]], 1.) + self.assertRaises(ValueError, TransferFunction, + 1., [[[1.]], [[2.], [3.]]]) + self.assertRaises(ValueError, TransferFunction, + [[[1.]], [[2.], [3.]]], 1.) def test_constructor_zero_denominator(self): """Give the constructor a transfer function with a zero denominator.""" @@ -54,7 +86,8 @@ def test_add_inconsistent_dimension(self): """Add two transfer function matrices of different sizes.""" sys1 = TransferFunction([[[1., 2.]]], [[[4., 5.]]]) - sys2 = TransferFunction([[[4., 3.]], [[1., 2.]]], [[[1., 6.]], [[2., 4.]]]) + sys2 = TransferFunction([[[4., 3.]], [[1., 2.]]], + [[[1., 6.]], [[2., 4.]]]) self.assertRaises(ValueError, sys1.__add__, sys2) self.assertRaises(ValueError, sys1.__sub__, sys2) self.assertRaises(ValueError, sys1.__radd__, sys2) @@ -65,7 +98,8 @@ def test_mul_inconsistent_dimension(self): sys1 = TransferFunction([[[1., 2.], [4., 5.]], [[2., 5.], [4., 3.]]], [[[6., 2.], [4., 1.]], [[6., 7.], [2., 4.]]]) - sys2 = TransferFunction([[[1.]], [[2.]], [[3.]]], [[[4.]], [[5.]], [[6.]]]) + sys2 = TransferFunction([[[1.]], [[2.]], [[3.]]], + [[[4.]], [[5.]], [[6.]]]) self.assertRaises(ValueError, sys1.__mul__, sys2) self.assertRaises(ValueError, sys2.__mul__, sys1) self.assertRaises(ValueError, sys1.__rmul__, sys2) @@ -313,6 +347,45 @@ def test_divide_siso(self): np.testing.assert_array_equal(sys4.num, sys3.den) np.testing.assert_array_equal(sys4.den, sys3.num) + def test_div(self): + # Make sure that sampling times work correctly + sys1 = TransferFunction([1., 3., 5], [1., 6., 2., -1]) + sys2 = TransferFunction([[[-1., 3.]]], [[[1., 0., -1.]]], True) + sys3 = sys1 / sys2 + self.assertEqual(sys3.dt, True) + + sys2 = TransferFunction([[[-1., 3.]]], [[[1., 0., -1.]]], 0.5) + sys3 = sys1 / sys2 + self.assertEqual(sys3.dt, 0.5) + + sys1 = TransferFunction([1., 3., 5], [1., 6., 2., -1], 0.1) + self.assertRaises(ValueError, TransferFunction.__truediv__, sys1, sys2) + + sys1 = sample_system(rss(4, 1, 1), 0.5) + sys3 = TransferFunction.__rtruediv__(sys2, sys1) + self.assertEqual(sys3.dt, 0.5) + + def test_pow(self): + sys1 = TransferFunction([1., 3., 5], [1., 6., 2., -1]) + self.assertRaises(ValueError, TransferFunction.__pow__, sys1, 0.5) + + def test_slice(self): + sys = TransferFunction( + [ [ [1], [2], [3]], [ [3], [4], [5]] ], + [ [[1, 2], [1, 3], [1, 4]], [[1, 4], [1, 5], [1, 6]] ]) + sys1 = sys[1:, 1:] + self.assertEqual((sys1.inputs, sys1.outputs), (2, 1)) + + sys2 = sys[:2, :2] + self.assertEqual((sys2.inputs, sys2.outputs), (2, 2)) + + sys = TransferFunction( + [ [ [1], [2], [3]], [ [3], [4], [5]] ], + [ [[1, 2], [1, 3], [1, 4]], [[1, 4], [1, 5], [1, 6]] ], 0.5) + sys1 = sys[1:, 1:] + self.assertEqual((sys1.inputs, sys1.outputs), (2, 1)) + self.assertEqual(sys1.dt, 0.5) + def test_evalfr_siso(self): """Evaluate the frequency response of a SISO system at one frequency.""" @@ -320,18 +393,21 @@ def test_evalfr_siso(self): np.testing.assert_array_almost_equal(evalfr(sys, 1j), np.array([[-0.5 - 0.5j]])) - np.testing.assert_array_almost_equal(evalfr(sys, 32j), - np.array([[0.00281959302585077 - 0.030628473607392j]])) + np.testing.assert_array_almost_equal( + evalfr(sys, 32j), + np.array([[0.00281959302585077 - 0.030628473607392j]])) # Test call version as well np.testing.assert_almost_equal(sys(1.j), -0.5 - 0.5j) - np.testing.assert_almost_equal(sys(32.j), 0.00281959302585077 - 0.030628473607392j) + np.testing.assert_almost_equal( + sys(32.j), 0.00281959302585077 - 0.030628473607392j) # Test internal version (with real argument) - np.testing.assert_array_almost_equal(sys._evalfr(1.), - np.array([[-0.5 - 0.5j]])) - np.testing.assert_array_almost_equal(sys._evalfr(32.), - np.array([[0.00281959302585077 - 0.030628473607392j]])) + np.testing.assert_array_almost_equal( + sys._evalfr(1.), np.array([[-0.5 - 0.5j]])) + np.testing.assert_array_almost_equal( + sys._evalfr(32.), + np.array([[0.00281959302585077 - 0.030628473607392j]])) # This test only works in Python 3 due to a conflict with the same # warning type in other test modules (frd_test.py). See @@ -349,6 +425,11 @@ def test_evalfr_deprecated(self): # Make sure that we get a pending deprecation warning self.assertRaises(PendingDeprecationWarning, sys.evalfr, 1.) + @unittest.skipIf(pysys.version_info < (3, 0), "test requires Python 3+") + def test_evalfr_dtime(self): + sys = TransferFunction([1., 3., 5], [1., 6., 2., -1], 0.1) + np.testing.assert_array_almost_equal(sys(1j), -0.5 - 0.5j) + @unittest.skipIf(not slycot_check(), "slycot not installed") def test_evalfr_mimo(self): """Evaluate the frequency response of a MIMO system at one frequency.""" @@ -368,7 +449,8 @@ def test_evalfr_mimo(self): np.testing.assert_array_almost_equal(sys(2.j), resp) def test_freqresp_siso(self): - """Evaluate the magnitude and phase of a SISO system at multiple frequencies.""" + """Evaluate the magnitude and phase of a SISO system at + multiple frequencies.""" sys = TransferFunction([1., 3., 5], [1., 6., 2., -1]) @@ -385,7 +467,8 @@ def test_freqresp_siso(self): @unittest.skipIf(not slycot_check(), "slycot not installed") def test_freqresp_mimo(self): - """Evaluate the magnitude and phase of a MIMO system at multiple frequencies.""" + """Evaluate the magnitude and phase of a MIMO system at + multiple frequencies.""" num = [[[1., 2.], [0., 3.], [2., -1.]], [[1.], [4., 0.], [1., -4., 3.]]] @@ -394,16 +477,17 @@ def test_freqresp_mimo(self): sys = TransferFunction(num, den) true_omega = [0.1, 1., 10.] - true_mag = [[[0.496287094505259, 0.307147558416976, 0.0334738176210382], + true_mag = [[[0.49628709, 0.30714755, 0.03347381], [300., 3., 0.03], [1., 1., 1.]], - [[33.3333333333333, 0.333333333333333, 0.00333333333333333], - [0.390285696125482, 1.26491106406735, 0.198759144198533], - [3.01663720059274, 4.47213595499958, 104.92378186093]]] - true_phase = [[[3.7128711165168e-4, 0.185347949995695, 1.30770596539255], - [-np.pi, -np.pi, -np.pi], [0., 0., 0.]], + [[33.333333, 0.33333333, 0.00333333], + [0.39028569, 1.26491106, 0.19875914], + [3.01663720, 4.47213595, 104.92378186]]] + true_phase = [[[3.7128711e-4, 0.18534794, + 1.30770596], [-np.pi, -np.pi, -np.pi], + [0., 0., 0.]], [[-np.pi, -np.pi, -np.pi], - [-1.66852323415362, -1.89254688119154, -1.62050658356412], - [-0.132989648369409, -1.1071487177940, -2.7504672066207]]] + [-1.66852323, -1.89254688, -1.62050658], + [-0.13298964, -1.10714871, -2.75046720]]] mag, phase, omega = sys.freqresp(true_omega) @@ -417,8 +501,9 @@ def test_freqresp_mimo(self): def test_pole_mimo(self): """Test for correct MIMO poles.""" - sys = TransferFunction([[[1.], [1.]], [[1.], [1.]]], - [[[1., 2.], [1., 3.]], [[1., 4., 4.], [1., 9., 14.]]]) + sys = TransferFunction( + [[[1.], [1.]], [[1.], [1.]]], + [[[1., 2.], [1., 3.]], [[1., 4., 4.], [1., 9., 14.]]]) p = sys.pole() np.testing.assert_array_almost_equal(p, [-2., -2., -7., -3., -2.]) @@ -619,6 +704,40 @@ def test_ss2tf(self): np.testing.assert_almost_equal(sys.num, true_sys.num) np.testing.assert_almost_equal(sys.den, true_sys.den) + def test_printing(self): + # SISO, continuous time + sys = ss2tf(rss(4, 1, 1)) + self.assertTrue(isinstance(str(sys), str)) + self.assertTrue(isinstance(sys._repr_latex_(), str)) + + # SISO, discrete time + sys = sample_system(sys, 1) + self.assertTrue(isinstance(str(sys), str)) + self.assertTrue(isinstance(sys._repr_latex_(), str)) + + # MIMO, continuous time + sys = ss2tf(rss(4, 2, 3)) + self.assertTrue(isinstance(str(sys), str)) + self.assertTrue(isinstance(sys._repr_latex_(), str)) + + def test_size_mismatch(self): + sys1 = ss2tf(rss(2, 2, 2)) + + # Different number of inputs + sys2 = ss2tf(rss(3, 1, 2)) + self.assertRaises(ValueError, TransferFunction.__add__, sys1, sys2) + + # Different number of outputs + sys2 = ss2tf(rss(3, 2, 1)) + self.assertRaises(ValueError, TransferFunction.__add__, sys1, sys2) + + # Inputs and outputs don't match + self.assertRaises(ValueError, TransferFunction.__mul__, sys2, sys1) + + # Feedback mismatch (MIMO not implemented) + self.assertRaises(NotImplementedError, + TransferFunction.feedback, sys2, sys1) + def suite(): return unittest.TestLoader().loadTestsFromTestCase(TestXferFcn) diff --git a/control/xferfcn.py b/control/xferfcn.py index 1ef0661a5..bc7aae1bd 100644 --- a/control/xferfcn.py +++ b/control/xferfcn.py @@ -121,9 +121,10 @@ def __init__(self, *args): % type(args[0])) num = args[0].num den = args[0].den + # TODO: not sure this can ever happen since dt is always present try: dt = args[0].dt - except NameError: + except NameError: # pragma: no coverage dt = None else: raise ValueError("Needs 1, 2 or 3 arguments; received %i." From de5219352e3a412bddbf5269f2be95829edef3f0 Mon Sep 17 00:00:00 2001 From: Richard Murray Date: Sat, 25 May 2019 23:08:35 -0700 Subject: [PATCH 15/15] update xferfcn mimo tests to require slycot --- control/tests/xferfcn_test.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/control/tests/xferfcn_test.py b/control/tests/xferfcn_test.py index cf4ac78da..8f212c153 100644 --- a/control/tests/xferfcn_test.py +++ b/control/tests/xferfcn_test.py @@ -715,11 +715,14 @@ def test_printing(self): self.assertTrue(isinstance(str(sys), str)) self.assertTrue(isinstance(sys._repr_latex_(), str)) + @unittest.skipIf(not slycot_check(), "slycot not installed") + def test_printing_mimo(self): # MIMO, continuous time sys = ss2tf(rss(4, 2, 3)) self.assertTrue(isinstance(str(sys), str)) self.assertTrue(isinstance(sys._repr_latex_(), str)) + @unittest.skipIf(not slycot_check(), "slycot not installed") def test_size_mismatch(self): sys1 = ss2tf(rss(2, 2, 2))