brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 1 | #!/usr/bin/python |
| 2 | |
| 3 | """ |
| 4 | Control loop pole placement library. |
| 5 | |
| 6 | This library will grow to support many different pole placement methods. |
| 7 | Currently it only supports direct pole placement. |
| 8 | """ |
| 9 | |
| 10 | __author__ = 'Austin Schuh (austin.linux@gmail.com)' |
| 11 | |
| 12 | import numpy |
| 13 | import slycot |
Parker Schuh | 1cbabbf | 2017-04-12 19:51:11 -0700 | [diff] [blame] | 14 | import scipy.linalg |
Austin Schuh | c9177b5 | 2015-11-28 13:18:31 -0800 | [diff] [blame] | 15 | import glog |
brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 16 | |
| 17 | class Error (Exception): |
| 18 | """Base class for all control loop exceptions.""" |
| 19 | |
| 20 | |
| 21 | class 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. |
| 28 | def 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 Schuh | c8ca244 | 2013-02-23 12:29:33 -0800 | [diff] [blame] | 86 | |
Austin Schuh | c8ca244 | 2013-02-23 12:29:33 -0800 | [diff] [blame] | 87 | def c2d(A, B, dt): |
| 88 | """Converts from continuous time state space representation to discrete time. |
Parker Schuh | 1cbabbf | 2017-04-12 19:51:11 -0700 | [diff] [blame] | 89 | Returns (A, B). C and D are unchanged. |
| 90 | This code is copied from: scipy.signal.cont2discrete method zoh |
| 91 | """ |
Austin Schuh | c8ca244 | 2013-02-23 12:29:33 -0800 | [diff] [blame] | 92 | |
Parker Schuh | 1cbabbf | 2017-04-12 19:51:11 -0700 | [diff] [blame] | 93 | a, b = numpy.array(A), numpy.array(B) |
| 94 | # Build an exponential matrix |
| 95 | em_upper = numpy.hstack((a, b)) |
| 96 | |
| 97 | # Need to stack zeros under the a and b matrices |
| 98 | em_lower = numpy.hstack((numpy.zeros((b.shape[1], a.shape[0])), |
| 99 | numpy.zeros((b.shape[1], b.shape[1])))) |
| 100 | |
| 101 | em = numpy.vstack((em_upper, em_lower)) |
| 102 | ms = scipy.linalg.expm(dt * em) |
| 103 | |
| 104 | # Dispose of the lower rows |
| 105 | ms = ms[:a.shape[0], :] |
| 106 | |
| 107 | ad = ms[:, 0:a.shape[1]] |
| 108 | bd = ms[:, a.shape[1]:] |
| 109 | |
| 110 | return numpy.matrix(ad), numpy.matrix(bd) |
Austin Schuh | 7ec34fd | 2014-02-15 22:27:46 -0800 | [diff] [blame] | 111 | |
| 112 | def ctrb(A, B): |
Brian Silverman | e18cf50 | 2015-11-28 23:04:43 +0000 | [diff] [blame] | 113 | """Returns the controllability matrix. |
Austin Schuh | 7ec34fd | 2014-02-15 22:27:46 -0800 | [diff] [blame] | 114 | |
Austin Schuh | c9177b5 | 2015-11-28 13:18:31 -0800 | [diff] [blame] | 115 | This matrix must have full rank for all the states to be controllable. |
Austin Schuh | 7ec34fd | 2014-02-15 22:27:46 -0800 | [diff] [blame] | 116 | """ |
| 117 | n = A.shape[0] |
| 118 | output = B |
| 119 | intermediate = B |
| 120 | for i in xrange(0, n): |
| 121 | intermediate = A * intermediate |
| 122 | output = numpy.concatenate((output, intermediate), axis=1) |
| 123 | |
| 124 | return output |
| 125 | |
Austin Schuh | 434c837 | 2018-01-21 16:30:06 -0800 | [diff] [blame] | 126 | def dlqr(A, B, Q, R, optimal_cost_function=False): |
Austin Schuh | 7ec34fd | 2014-02-15 22:27:46 -0800 | [diff] [blame] | 127 | """Solves for the optimal lqr controller. |
| 128 | |
| 129 | x(n+1) = A * x(n) + B * u(n) |
| 130 | J = sum(0, inf, x.T * Q * x + u.T * R * u) |
| 131 | """ |
| 132 | |
| 133 | # P = (A.T * P * A) - (A.T * P * B * numpy.linalg.inv(R + B.T * P *B) * (A.T * P.T * B).T + Q |
Austin Schuh | 434c837 | 2018-01-21 16:30:06 -0800 | [diff] [blame] | 134 | # 0.5 * X.T * P * X -> optimal cost to infinity |
Austin Schuh | 7ec34fd | 2014-02-15 22:27:46 -0800 | [diff] [blame] | 135 | |
Austin Schuh | 1a38796 | 2015-01-31 16:36:20 -0800 | [diff] [blame] | 136 | P, rcond, w, S, T = slycot.sb02od( |
| 137 | n=A.shape[0], m=B.shape[1], A=A, B=B, Q=Q, R=R, dico='D') |
Austin Schuh | 7ec34fd | 2014-02-15 22:27:46 -0800 | [diff] [blame] | 138 | |
Austin Schuh | 434c837 | 2018-01-21 16:30:06 -0800 | [diff] [blame] | 139 | F = numpy.linalg.inv(R + B.T * P * B) * B.T * P * A |
| 140 | if optimal_cost_function: |
| 141 | return F, P |
| 142 | else: |
| 143 | return F |
Austin Schuh | e4a14f2 | 2015-03-01 00:12:29 -0800 | [diff] [blame] | 144 | |
| 145 | def kalman(A, B, C, Q, R): |
| 146 | """Solves for the steady state kalman gain and covariance matricies. |
| 147 | |
| 148 | Args: |
| 149 | A, B, C: SS matricies. |
| 150 | Q: The model uncertantity |
| 151 | R: The measurement uncertainty |
| 152 | |
| 153 | Returns: |
| 154 | KalmanGain, Covariance. |
| 155 | """ |
Austin Schuh | 572ff40 | 2015-11-08 12:17:50 -0800 | [diff] [blame] | 156 | I = numpy.matrix(numpy.eye(Q.shape[0])) |
| 157 | Z = numpy.matrix(numpy.zeros(Q.shape[0])) |
Austin Schuh | c9177b5 | 2015-11-28 13:18:31 -0800 | [diff] [blame] | 158 | n = A.shape[0] |
| 159 | m = C.shape[0] |
| 160 | |
| 161 | controllability_rank = numpy.linalg.matrix_rank(ctrb(A.T, C.T)) |
Brian Silverman | e18cf50 | 2015-11-28 23:04:43 +0000 | [diff] [blame] | 162 | if controllability_rank != n: |
Austin Schuh | c9177b5 | 2015-11-28 13:18:31 -0800 | [diff] [blame] | 163 | glog.warning('Observability of %d != %d, unobservable state', |
Brian Silverman | e18cf50 | 2015-11-28 23:04:43 +0000 | [diff] [blame] | 164 | controllability_rank, n) |
Austin Schuh | e4a14f2 | 2015-03-01 00:12:29 -0800 | [diff] [blame] | 165 | |
Austin Schuh | 572ff40 | 2015-11-08 12:17:50 -0800 | [diff] [blame] | 166 | # Compute the steady state covariance matrix. |
Austin Schuh | c9177b5 | 2015-11-28 13:18:31 -0800 | [diff] [blame] | 167 | 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 Schuh | 572ff40 | 2015-11-08 12:17:50 -0800 | [diff] [blame] | 168 | S = C * P_prior * C.T + R |
| 169 | K = numpy.linalg.lstsq(S.T, (P_prior * C.T).T)[0].T |
| 170 | P = (I - K * C) * P_prior |
Austin Schuh | e4a14f2 | 2015-03-01 00:12:29 -0800 | [diff] [blame] | 171 | |
| 172 | return K, P |
Austin Schuh | 86093ad | 2016-02-06 14:29:34 -0800 | [diff] [blame] | 173 | |
Austin Schuh | 3ad5ed8 | 2017-02-25 21:36:19 -0800 | [diff] [blame] | 174 | |
| 175 | def kalmd(A_continuous, B_continuous, Q_continuous, R_continuous, dt): |
| 176 | """Converts a continuous time kalman filter to discrete time. |
| 177 | |
| 178 | Args: |
| 179 | A_continuous: The A continuous matrix |
| 180 | B_continuous: the B continuous matrix |
| 181 | Q_continuous: The continuous cost matrix |
| 182 | R_continuous: The R continuous matrix |
| 183 | dt: Timestep |
| 184 | |
| 185 | The math for this is from: |
| 186 | https://www.mathworks.com/help/control/ref/kalmd.html |
| 187 | |
| 188 | Returns: |
| 189 | The discrete matrices of A, B, Q, and R. |
| 190 | """ |
| 191 | # TODO(austin): Verify that the dimensions make sense. |
| 192 | number_of_states = A_continuous.shape[0] |
| 193 | number_of_inputs = B_continuous.shape[1] |
| 194 | M = numpy.zeros((len(A_continuous) + number_of_inputs, |
| 195 | len(A_continuous) + number_of_inputs)) |
| 196 | M[0:number_of_states, 0:number_of_states] = A_continuous |
| 197 | M[0:number_of_states, number_of_states:] = B_continuous |
| 198 | M_exp = scipy.linalg.expm(M * dt) |
| 199 | A_discrete = M_exp[0:number_of_states, 0:number_of_states] |
| 200 | B_discrete = numpy.matrix(M_exp[0:number_of_states, number_of_states:]) |
| 201 | Q_continuous = (Q_continuous + Q_continuous.T) / 2.0 |
| 202 | R_continuous = (R_continuous + R_continuous.T) / 2.0 |
| 203 | M = numpy.concatenate((-A_continuous, Q_continuous), axis=1) |
| 204 | M = numpy.concatenate( |
| 205 | (M, numpy.concatenate((numpy.matrix( |
| 206 | numpy.zeros((number_of_states, number_of_states))), |
| 207 | numpy.transpose(A_continuous)), axis = 1)), axis = 0) |
| 208 | phi = numpy.matrix(scipy.linalg.expm(M*dt)) |
| 209 | phi12 = phi[0:number_of_states, number_of_states:(2*number_of_states)] |
| 210 | phi22 = phi[number_of_states:2*number_of_states, number_of_states:2*number_of_states] |
| 211 | Q_discrete = phi22.T * phi12 |
| 212 | Q_discrete = (Q_discrete + Q_discrete.T) / 2.0 |
| 213 | R_discrete = R_continuous / dt |
| 214 | return (A_discrete, B_discrete, Q_discrete, R_discrete) |
| 215 | |
| 216 | |
Austin Schuh | 86093ad | 2016-02-06 14:29:34 -0800 | [diff] [blame] | 217 | def TwoStateFeedForwards(B, Q): |
| 218 | """Computes the feed forwards constant for a 2 state controller. |
| 219 | |
| 220 | This will take the form U = Kff * (R(n + 1) - A * R(n)), where Kff is the |
| 221 | feed-forwards constant. It is important that Kff is *only* computed off |
| 222 | the goal and not the feed back terms. |
| 223 | |
| 224 | Args: |
| 225 | B: numpy.Matrix[num_states, num_inputs] The B matrix. |
| 226 | Q: numpy.Matrix[num_states, num_states] The Q (cost) matrix. |
| 227 | |
| 228 | Returns: |
| 229 | numpy.Matrix[num_inputs, num_states] |
| 230 | """ |
| 231 | |
| 232 | # We want to find the optimal U such that we minimize the tracking cost. |
| 233 | # This means that we want to minimize |
| 234 | # (B * U - (R(n+1) - A R(n)))^T * Q * (B * U - (R(n+1) - A R(n))) |
| 235 | # TODO(austin): This doesn't take into account the cost of U |
| 236 | |
| 237 | return numpy.linalg.inv(B.T * Q * B) * B.T * Q.T |