blob: 8a63620754955e2d2e9132792e5806ef7b14f295 [file] [log] [blame]
brians343bc112013-02-10 01:53:46 +00001#!/usr/bin/python
2
3"""
4Control loop pole placement library.
5
6This library will grow to support many different pole placement methods.
7Currently it only supports direct pole placement.
8"""
9
10__author__ = 'Austin Schuh (austin.linux@gmail.com)'
11
12import numpy
13import slycot
Austin Schuhc976f492015-02-22 21:28:18 -080014import scipy.signal.cont2discrete
Austin Schuhc9177b52015-11-28 13:18:31 -080015import glog
brians343bc112013-02-10 01:53:46 +000016
17class Error (Exception):
18 """Base class for all control loop exceptions."""
19
20
21class PolePlacementError(Error):
22 """Exception raised when pole placement fails."""
23
24
25# TODO(aschuh): dplace should take a control system object.
26# There should also exist a function to manipulate laplace expressions, and
27# something to plot bode plots and all that.
28def dplace(A, B, poles, alpha=1e-6):
29 """Set the poles of (A - BF) to poles.
30
31 Args:
32 A: numpy.matrix(n x n), The A matrix.
33 B: numpy.matrix(n x m), The B matrix.
34 poles: array(imaginary numbers), The poles to use. Complex conjugates poles
35 must be in pairs.
36
37 Raises:
38 ValueError: Arguments were the wrong shape or there were too many poles.
39 PolePlacementError: Pole placement failed.
40
41 Returns:
42 numpy.matrix(m x n), K
43 """
44 # See http://www.icm.tu-bs.de/NICONET/doc/SB01BD.html for a description of the
45 # fortran code that this is cleaning up the interface to.
46 n = A.shape[0]
47 if A.shape[1] != n:
48 raise ValueError("A must be square")
49 if B.shape[0] != n:
50 raise ValueError("B must have the same number of states as A.")
51 m = B.shape[1]
52
53 num_poles = len(poles)
54 if num_poles > n:
55 raise ValueError("Trying to place more poles than states.")
56
57 out = slycot.sb01bd(n=n,
58 m=m,
59 np=num_poles,
60 alpha=alpha,
61 A=A,
62 B=B,
63 w=numpy.array(poles),
64 dico='D')
65
66 A_z = numpy.matrix(out[0])
67 num_too_small_eigenvalues = out[2]
68 num_assigned_eigenvalues = out[3]
69 num_uncontrollable_eigenvalues = out[4]
70 K = numpy.matrix(-out[5])
71 Z = numpy.matrix(out[6])
72
73 if num_too_small_eigenvalues != 0:
74 raise PolePlacementError("Number of eigenvalues that are too small "
75 "and are therefore unmodified is %d." %
76 num_too_small_eigenvalues)
77 if num_assigned_eigenvalues != num_poles:
78 raise PolePlacementError("Did not place all the eigenvalues that were "
79 "requested. Only placed %d eigenvalues." %
80 num_assigned_eigenvalues)
81 if num_uncontrollable_eigenvalues != 0:
82 raise PolePlacementError("Found %d uncontrollable eigenvlaues." %
83 num_uncontrollable_eigenvalues)
84
85 return K
Austin Schuhc8ca2442013-02-23 12:29:33 -080086
87
88def c2d(A, B, dt):
89 """Converts from continuous time state space representation to discrete time.
Austin Schuhc8ca2442013-02-23 12:29:33 -080090 Returns (A, B). C and D are unchanged."""
Austin Schuhc8ca2442013-02-23 12:29:33 -080091
Austin Schuhc976f492015-02-22 21:28:18 -080092 ans_a, ans_b, _, _, _ = scipy.signal.cont2discrete((A, B, None, None), dt)
93 return numpy.matrix(ans_a), numpy.matrix(ans_b)
Austin Schuh7ec34fd2014-02-15 22:27:46 -080094
95def ctrb(A, B):
96 """Returns the controlability matrix.
97
Austin Schuhc9177b52015-11-28 13:18:31 -080098 This matrix must have full rank for all the states to be controllable.
Austin Schuh7ec34fd2014-02-15 22:27:46 -080099 """
100 n = A.shape[0]
101 output = B
102 intermediate = B
103 for i in xrange(0, n):
104 intermediate = A * intermediate
105 output = numpy.concatenate((output, intermediate), axis=1)
106
107 return output
108
109def dlqr(A, B, Q, R):
110 """Solves for the optimal lqr controller.
111
112 x(n+1) = A * x(n) + B * u(n)
113 J = sum(0, inf, x.T * Q * x + u.T * R * u)
114 """
115
116 # P = (A.T * P * A) - (A.T * P * B * numpy.linalg.inv(R + B.T * P *B) * (A.T * P.T * B).T + Q
117
Austin Schuh1a387962015-01-31 16:36:20 -0800118 P, rcond, w, S, T = slycot.sb02od(
119 n=A.shape[0], m=B.shape[1], A=A, B=B, Q=Q, R=R, dico='D')
Austin Schuh7ec34fd2014-02-15 22:27:46 -0800120
121 F = numpy.linalg.inv(R + B.T * P *B) * B.T * P * A
122 return F
Austin Schuhe4a14f22015-03-01 00:12:29 -0800123
124def kalman(A, B, C, Q, R):
125 """Solves for the steady state kalman gain and covariance matricies.
126
127 Args:
128 A, B, C: SS matricies.
129 Q: The model uncertantity
130 R: The measurement uncertainty
131
132 Returns:
133 KalmanGain, Covariance.
134 """
Austin Schuh572ff402015-11-08 12:17:50 -0800135 I = numpy.matrix(numpy.eye(Q.shape[0]))
136 Z = numpy.matrix(numpy.zeros(Q.shape[0]))
Austin Schuhc9177b52015-11-28 13:18:31 -0800137 n = A.shape[0]
138 m = C.shape[0]
139
140 controllability_rank = numpy.linalg.matrix_rank(ctrb(A.T, C.T))
141 if controlability_rank != n:
142 glog.warning('Observability of %d != %d, unobservable state',
143 controlability_rank, n)
Austin Schuhe4a14f22015-03-01 00:12:29 -0800144
Austin Schuh572ff402015-11-08 12:17:50 -0800145 # Compute the steady state covariance matrix.
Austin Schuhc9177b52015-11-28 13:18:31 -0800146 P_prior, rcond, w, S, T = slycot.sb02od(n=n, m=m, A=A.T, B=C.T, Q=Q, R=R, dico='D')
Austin Schuh572ff402015-11-08 12:17:50 -0800147 S = C * P_prior * C.T + R
148 K = numpy.linalg.lstsq(S.T, (P_prior * C.T).T)[0].T
149 P = (I - K * C) * P_prior
Austin Schuhe4a14f22015-03-01 00:12:29 -0800150
151 return K, P