Repository: python-control/python-control

Issue:
properly implement __repr__
The `__repr__` methods should implement a representation that can be 'eval'-d back into the relevant object, so
```
>>> from control import TransferFunction
>>> s = TransferFunction.s
>>> h = 1/(s+1)
>>> print(repr(h))
TransferFunction([[array([1])]],[[array([1, 1])]],0)
>>> from numpy import array
>>> h2 = eval(repr(h))
>>> print(h2)

  1
-----
s + 1
```



Discussion:
coveralls: 
[![Coverage Status](https://coveralls.io/builds/31346327/badge)](https://coveralls.io/builds/31346327)

Coverage decreased (-0.1%) to 84.102% when pulling **6b69ad493eac50767440e2a094d9f220b5fb04e4 on repagh:implement_repr** into **03183d157a5f6cd8a9918498ab8717dc7b91c9cf on python-control:master**.


Patch:
diff --git a/control/frdata.py b/control/frdata.py
index c57cf09b..8ca9dfd9 100644
--- a/control/frdata.py
+++ b/control/frdata.py
@@ -161,14 +161,14 @@ class FrequencyResponseData(LTI):
         """String representation of the transfer function."""
 
         mimo = self.inputs > 1 or self.outputs > 1
-        outstr = ['frequency response data ']
+        outstr = ['Frequency response data']
 
         mt, pt, wt = self.freqresp(self.omega)
         for i in range(self.inputs):
             for j in range(self.outputs):
                 if mimo:
                     outstr.append("Input %i to output %i:" % (i + 1, j + 1))
-                outstr.append('Freq [rad/s]  Response   ')
+                outstr.append('Freq [rad/s]  Response')
                 outstr.append('------------  ---------------------')
                 outstr.extend(
                     ['%12.3f  %10.4g%+10.4gj' % (w, m, p)
@@ -177,6 +177,15 @@ class FrequencyResponseData(LTI):
 
         return '\n'.join(outstr)
 
+    def __repr__(self):
+        """Loadable string representation,
+
+        limited for number of data points.
+        """
+        return "FrequencyResponseData({d}, {w}{smooth})".format(
+            d=repr(self.fresp), w=repr(self.omega),
+            smooth=(self.ifunc and ", smooth=True") or "")
+
     def __neg__(self):
         """Negate a transfer function."""
 
diff --git a/control/statesp.py b/control/statesp.py
index f5bb232a..522d187a 100644
--- a/control/statesp.py
+++ b/control/statesp.py
@@ -283,8 +283,14 @@ class StateSpace(LTI):
             string += "\ndt = " + self.dt.__str__() + "\n"
         return string
 
-    # represent as string, makes display work for IPython
-    __repr__ = __str__
+    # represent to implement a re-loadable version
+    # TODO: remove the conversion to array when matrix is no longer used
+    def __repr__(self):
+        """Print state-space system in loadable form."""
+        return "StateSpace({A}, {B}, {C}, {D}{dt})".format(
+            A=asarray(self.A).__repr__(), B=asarray(self.B).__repr__(),
+            C=asarray(self.C).__repr__(), D=asarray(self.D).__repr__(),
+            dt=(isdtime(self, strict=True) and ", {}".format(self.dt)) or '')
 
     # Negation of a system
     def __neg__(self):
diff --git a/control/xferfcn.py b/control/xferfcn.py
index 02f39117..f50d5141 100644
--- a/control/xferfcn.py
+++ b/control/xferfcn.py
@@ -284,8 +284,17 @@ class TransferFunction(LTI):
 
         return outstr
 
-    # represent as string, makes display work for IPython
-    __repr__ = __str__
+    # represent to implement a re-loadable version
+    def __repr__(self):
+        """Print transfer function in loadable form"""
+        if self.issiso():
+            return "TransferFunction({num}, {den}{dt})".format(
+                num=self.num[0][0].__repr__(), den=self.den[0][0].__repr__(),
+                dt=(isdtime(self, strict=True) and ', {}'.format(self.dt)) or '')
+        else:
+            return "TransferFunction({num}, {den}{dt})".format(
+                num=self.num.__repr__(), den=self.den.__repr__(),
+                dt=(isdtime(self, strict=True) and ', {}'.format(self.dt)) or '')
 
     def _repr_latex_(self, var=None):
         """LaTeX representation of transfer function, for Jupyter notebook"""


Test patch:
diff --git a/control/tests/frd_test.py b/control/tests/frd_test.py
index 629d488e..fcbc1026 100644
--- a/control/tests/frd_test.py
+++ b/control/tests/frd_test.py
@@ -10,7 +10,7 @@ import numpy as np
 import control as ct
 from control.statesp import StateSpace
 from control.xferfcn import TransferFunction
-from control.frdata import FRD, _convertToFRD
+from control.frdata import FRD, _convertToFRD, FrequencyResponseData
 from control import bdalg
 from control import freqplot
 from control.exception import slycot_check
@@ -414,6 +414,56 @@ class TestFRD(unittest.TestCase):
             # Make sure that we get a pending deprecation warning
             self.assertRaises(PendingDeprecationWarning, frd_tf.evalfr, 1.)
 
-            
+    def test_repr_str(self):
+        # repr printing
+        array = np.array
+        sys0 = FrequencyResponseData([1.0, 0.9+0.1j, 0.1+2j, 0.05+3j],
+                                     [0.1, 1.0, 10.0, 100.0])
+        sys1 = FrequencyResponseData(sys0.fresp, sys0.omega, smooth=True)
+        ref0 = "FrequencyResponseData(" \
+            "array([[[1.  +0.j , 0.9 +0.1j, 0.1 +2.j , 0.05+3.j ]]])," \
+            " array([  0.1,   1. ,  10. , 100. ]))"
+        ref1 = ref0[:-1] + ", smooth=True)"
+        sysm = FrequencyResponseData(
+            np.matmul(array([[1],[2]]), sys0.fresp), sys0.omega)
+
+        self.assertEqual(repr(sys0), ref0)
+        self.assertEqual(repr(sys1), ref1)
+        sys0r = eval(repr(sys0))
+        np.testing.assert_array_almost_equal(sys0r.fresp, sys0.fresp)
+        np.testing.assert_array_almost_equal(sys0r.omega, sys0.omega)
+        sys1r = eval(repr(sys1))
+        np.testing.assert_array_almost_equal(sys1r.fresp, sys1.fresp)
+        np.testing.assert_array_almost_equal(sys1r.omega, sys1.omega)
+        assert(sys1.ifunc is not None)
+
+        refs = """Frequency response data
+Freq [rad/s]  Response
+------------  ---------------------
+       0.100           1        +0j
+       1.000         0.9      +0.1j
+      10.000         0.1        +2j
+     100.000        0.05        +3j"""
+        self.assertEqual(str(sys0), refs)
+        self.assertEqual(str(sys1), refs)
+
+        # print multi-input system
+        refm = """Frequency response data
+Input 1 to output 1:
+Freq [rad/s]  Response
+------------  ---------------------
+       0.100           1        +0j
+       1.000         0.9      +0.1j
+      10.000         0.1        +2j
+     100.000        0.05        +3j
+Input 2 to output 1:
+Freq [rad/s]  Response
+------------  ---------------------
+       0.100           2        +0j
+       1.000         1.8      +0.2j
+      10.000         0.2        +4j
+     100.000         0.1        +6j"""
+        self.assertEqual(str(sysm), refm)
+
 if __name__ == "__main__":
     unittest.main()
diff --git a/control/tests/statesp_test.py b/control/tests/statesp_test.py
index 740ad308..96404d79 100644
--- a/control/tests/statesp_test.py
+++ b/control/tests/statesp_test.py
@@ -519,6 +519,25 @@ class TestStateSpace(unittest.TestCase):
         np.testing.assert_allclose(np.array(pk.C).reshape(-1), Cmatlab)
         np.testing.assert_allclose(np.array(pk.D).reshape(-1), Dmatlab)
 
+    def test_repr(self):
+        ref322 = """StateSpace(array([[-3.,  4.,  2.],
+       [-1., -3.,  0.],
+       [ 2.,  5.,  3.]]), array([[ 1.,  4.],
+       [-3., -3.],
+       [-2.,  1.]]), array([[ 4.,  2., -3.],
+       [ 1.,  4.,  3.]]), array([[-2.,  4.],
+       [ 0.,  1.]]){dt})"""
+        self.assertEqual(repr(self.sys322), ref322.format(dt=''))
+        sysd = StateSpace(self.sys322.A, self.sys322.B,
+                          self.sys322.C, self.sys322.D, 0.4)
+        self.assertEqual(repr(sysd), ref322.format(dt=", 0.4"))
+        array = np.array
+        sysd2 = eval(repr(sysd))
+        np.testing.assert_allclose(sysd.A, sysd2.A)
+        np.testing.assert_allclose(sysd.B, sysd2.B)
+        np.testing.assert_allclose(sysd.C, sysd2.C)
+        np.testing.assert_allclose(sysd.D, sysd2.D)
+
     def test_str(self):
         """Test that printing the system works"""
         tsys = self.sys322
@@ -653,5 +672,6 @@ class TestDrss(unittest.TestCase):
             evalfr(plant_d_warped, np.exp(wwarp*1j*Ts)), 
             decimal=4)
 
+
 if __name__ == "__main__":
     unittest.main()
diff --git a/control/tests/xferfcn_test.py b/control/tests/xferfcn_test.py
index 6e0a2ede..02e6c2b3 100644
--- a/control/tests/xferfcn_test.py
+++ b/control/tests/xferfcn_test.py
@@ -872,6 +872,46 @@ class TestXferFcn(unittest.TestCase):
                    r'+ 2.3 ' + expmul + ' 10^{-45}'
                    r'}' + suffix + '$$')
             self.assertEqual(H._repr_latex_(), ref)
+
+    def test_repr(self):
+        """Test __repr__ printout."""
+        Hc = TransferFunction([-1., 4.], [1., 3., 5.])
+        Hd = TransferFunction([2., 3., 0.], [1., -3., 4., 0], 2.0)
+        Hcm = TransferFunction(
+            [ [[0, 1], [2, 3]], [[4, 5], [6, 7]] ],
+            [ [[6, 7], [4, 5]], [[2, 3], [0, 1]] ])
+        Hdm = TransferFunction(
+            [ [[0, 1], [2, 3]], [[4, 5], [6, 7]] ],
+            [ [[6, 7], [4, 5]], [[2, 3], [0, 1]] ], 0.5)
+
+        refs = [
+            "TransferFunction(array([-1.,  4.]), array([1., 3., 5.]))",
+            "TransferFunction(array([2., 3., 0.]),"
+            " array([ 1., -3.,  4.,  0.]), 2.0)",
+            "TransferFunction([[array([1]), array([2, 3])],"
+            " [array([4, 5]), array([6, 7])]],"
+            " [[array([6, 7]), array([4, 5])],"
+            " [array([2, 3]), array([1])]])",
+            "TransferFunction([[array([1]), array([2, 3])],"
+            " [array([4, 5]), array([6, 7])]],"
+            " [[array([6, 7]), array([4, 5])],"
+            " [array([2, 3]), array([1])]], 0.5)" ]
+        self.assertEqual(repr(Hc), refs[0])
+        self.assertEqual(repr(Hd), refs[1])
+        self.assertEqual(repr(Hcm), refs[2])
+        self.assertEqual(repr(Hdm), refs[3])
+
+        # and reading back
+        array = np.array
+        for H in (Hc, Hd, Hcm, Hdm):
+            H2 = eval(H.__repr__())
+            for p in range(len(H.num)):
+                for m in range(len(H.num[0])):
+                    np.testing.assert_array_almost_equal(
+                        H.num[p][m], H2.num[p][m])
+                    np.testing.assert_array_almost_equal(
+                        H.den[p][m], H2.den[p][m])
+            self.assertEqual(H.dt, H2.dt)
     
     def test_sample_system_prewarping(self): 
         """test that prewarping works when converting from cont to discrete time system"""
@@ -893,5 +933,6 @@ class TestXferFcn(unittest.TestCase):
             evalfr(plant_d_warped, np.exp(wwarp*1j*Ts)), 
             decimal=4)
 
+
 if __name__ == "__main__":
     unittest.main()