Skip to content

Commit 1ebff1e

Browse files
committed
Added LaTeX representation method for StateSpace objects
Added StateSpace method `_repr_latex_`. Representation is as a partitioned matrix. Intended for Jupyter notebooks, and so MathJax-centric.
1 parent d3142ff commit 1ebff1e

1 file changed

Lines changed: 62 additions & 0 deletions

File tree

control/statesp.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,68 @@ def __repr__(self):
292292
C=asarray(self.C).__repr__(), D=asarray(self.D).__repr__(),
293293
dt=(isdtime(self, strict=True) and ", {}".format(self.dt)) or '')
294294

295+
def _repr_latex_(self):
296+
"""LaTeX representation of state-space model
297+
298+
Model is presented as a matrix partitioned into A, B, C, and D
299+
parts. The output is primarily intended for Jupyter
300+
notebooks, which use MathJax to render the LaTeX, and the
301+
results may look odd when processed by a 'conventional' LaTeX
302+
system.
303+
304+
Returns
305+
-------
306+
s : string with LaTeX representation of model
307+
"""
308+
309+
def _f2s(f):
310+
"""Format floating point number f as a string
311+
312+
Inserts column separators, etc., for _repr_latex_.
313+
"""
314+
prec = 3
315+
sraw = '{f:-.{prec}g}'.format(f=f, prec=prec)
316+
# significand-exponent
317+
se = sraw.split('e')
318+
# whole-fraction
319+
wf = se[0].split('.')
320+
s = wf[0]
321+
if wf[1:]:
322+
s += r'.&\hspace{{-1em}}{frac}'.format(frac=wf[1])
323+
else:
324+
s += r'\phantom{.}&\hspace{-1em}'
325+
326+
if se[1:]:
327+
s += r'&\hspace{{-1em}}\cdot10^{{{:d}}}'.format(int(se[1]))
328+
else:
329+
s += r'&\hspace{-1em}\phantom{\cdot}'
330+
331+
return s
332+
333+
lines = [
334+
r'\[',
335+
r'\left(',
336+
(r'\begin{array}'
337+
+ r'{' + 'rll' * self.states + '|' + 'rll' * self.inputs + '}')
338+
]
339+
340+
for Ai, Bi in zip(asarray(self.A), asarray(self.B)):
341+
lines.append('&'.join([_f2s(Aij) for Aij in Ai]
342+
+ [_f2s(Bij) for Bij in Bi])
343+
+ '\\\\')
344+
lines.append(r'\hline')
345+
for Ci, Di in zip(asarray(self.C), asarray(self.D)):
346+
lines.append('&'.join([_f2s(Cij) for Cij in Ci]
347+
+ [_f2s(Dij) for Dij in Di])
348+
+ '\\\\')
349+
350+
lines.extend([
351+
r'\end{array}'
352+
r'\right)',
353+
r'\]'])
354+
355+
return '\n'.join(lines)
356+
295357
# Negation of a system
296358
def __neg__(self):
297359
"""Negate a state space system."""

0 commit comments

Comments
 (0)