blob: 4fdf1e9179df74ba0694d582447e1b724ae045f0 [file] [log] [blame]
Austin Schuh085eab92020-11-26 13:54:51 -08001#!/usr/bin/python3
brians343bc112013-02-10 01:53:46 +00002
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
Parker Schuh1cbabbf2017-04-12 19:51:11 -070013import scipy.linalg
Austin Schuh085eab92020-11-26 13:54:51 -080014import scipy.signal
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
brians343bc112013-02-10 01:53:46 +000021# TODO(aschuh): dplace should take a control system object.
22# There should also exist a function to manipulate laplace expressions, and
23# something to plot bode plots and all that.
Austin Schuh085eab92020-11-26 13:54:51 -080024def dplace(A, B, poles):
brians343bc112013-02-10 01:53:46 +000025 """Set the poles of (A - BF) to poles.
26
27 Args:
28 A: numpy.matrix(n x n), The A matrix.
29 B: numpy.matrix(n x m), The B matrix.
30 poles: array(imaginary numbers), The poles to use. Complex conjugates poles
31 must be in pairs.
32
brians343bc112013-02-10 01:53:46 +000033 Returns:
34 numpy.matrix(m x n), K
35 """
Austin Schuh085eab92020-11-26 13:54:51 -080036 return scipy.signal.place_poles(A=A, B=B, poles=numpy.array(poles)).gain_matrix
Austin Schuhc8ca2442013-02-23 12:29:33 -080037
Austin Schuhc8ca2442013-02-23 12:29:33 -080038def c2d(A, B, dt):
39 """Converts from continuous time state space representation to discrete time.
Parker Schuh1cbabbf2017-04-12 19:51:11 -070040 Returns (A, B). C and D are unchanged.
41 This code is copied from: scipy.signal.cont2discrete method zoh
42 """
Austin Schuhc8ca2442013-02-23 12:29:33 -080043
Parker Schuh1cbabbf2017-04-12 19:51:11 -070044 a, b = numpy.array(A), numpy.array(B)
45 # Build an exponential matrix
46 em_upper = numpy.hstack((a, b))
47
48 # Need to stack zeros under the a and b matrices
49 em_lower = numpy.hstack((numpy.zeros((b.shape[1], a.shape[0])),
50 numpy.zeros((b.shape[1], b.shape[1]))))
51
52 em = numpy.vstack((em_upper, em_lower))
53 ms = scipy.linalg.expm(dt * em)
54
55 # Dispose of the lower rows
56 ms = ms[:a.shape[0], :]
57
58 ad = ms[:, 0:a.shape[1]]
59 bd = ms[:, a.shape[1]:]
60
61 return numpy.matrix(ad), numpy.matrix(bd)
Austin Schuh7ec34fd2014-02-15 22:27:46 -080062
63def ctrb(A, B):
Brian Silvermane18cf502015-11-28 23:04:43 +000064 """Returns the controllability matrix.
Austin Schuh7ec34fd2014-02-15 22:27:46 -080065
Austin Schuhc9177b52015-11-28 13:18:31 -080066 This matrix must have full rank for all the states to be controllable.
Austin Schuh7ec34fd2014-02-15 22:27:46 -080067 """
68 n = A.shape[0]
69 output = B
70 intermediate = B
Austin Schuh5ea48472021-02-02 20:46:41 -080071 for i in range(0, n):
Austin Schuh7ec34fd2014-02-15 22:27:46 -080072 intermediate = A * intermediate
73 output = numpy.concatenate((output, intermediate), axis=1)
74
75 return output
76
Austin Schuh434c8372018-01-21 16:30:06 -080077def dlqr(A, B, Q, R, optimal_cost_function=False):
Austin Schuh7ec34fd2014-02-15 22:27:46 -080078 """Solves for the optimal lqr controller.
79
80 x(n+1) = A * x(n) + B * u(n)
81 J = sum(0, inf, x.T * Q * x + u.T * R * u)
82 """
83
84 # 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 Schuh434c8372018-01-21 16:30:06 -080085 # 0.5 * X.T * P * X -> optimal cost to infinity
Austin Schuh7ec34fd2014-02-15 22:27:46 -080086
Austin Schuh085eab92020-11-26 13:54:51 -080087 P = scipy.linalg.solve_discrete_are(a=A, b=B, q=Q, r=R)
Austin Schuh434c8372018-01-21 16:30:06 -080088 F = numpy.linalg.inv(R + B.T * P * B) * B.T * P * A
89 if optimal_cost_function:
90 return F, P
91 else:
92 return F
Austin Schuhe4a14f22015-03-01 00:12:29 -080093
94def kalman(A, B, C, Q, R):
95 """Solves for the steady state kalman gain and covariance matricies.
96
97 Args:
98 A, B, C: SS matricies.
99 Q: The model uncertantity
100 R: The measurement uncertainty
101
102 Returns:
103 KalmanGain, Covariance.
104 """
Austin Schuh572ff402015-11-08 12:17:50 -0800105 I = numpy.matrix(numpy.eye(Q.shape[0]))
106 Z = numpy.matrix(numpy.zeros(Q.shape[0]))
Austin Schuhc9177b52015-11-28 13:18:31 -0800107 n = A.shape[0]
108 m = C.shape[0]
109
110 controllability_rank = numpy.linalg.matrix_rank(ctrb(A.T, C.T))
Brian Silvermane18cf502015-11-28 23:04:43 +0000111 if controllability_rank != n:
Austin Schuhc9177b52015-11-28 13:18:31 -0800112 glog.warning('Observability of %d != %d, unobservable state',
Brian Silvermane18cf502015-11-28 23:04:43 +0000113 controllability_rank, n)
Austin Schuhe4a14f22015-03-01 00:12:29 -0800114
Austin Schuh572ff402015-11-08 12:17:50 -0800115 # Compute the steady state covariance matrix.
Austin Schuh085eab92020-11-26 13:54:51 -0800116 P_prior = scipy.linalg.solve_discrete_are(a=A.T, b=C.T, q=Q, r=R)
Austin Schuh572ff402015-11-08 12:17:50 -0800117 S = C * P_prior * C.T + R
Austin Schuh085eab92020-11-26 13:54:51 -0800118 K = numpy.linalg.lstsq(S.T, (P_prior * C.T).T, rcond=None)[0].T
Austin Schuh572ff402015-11-08 12:17:50 -0800119 P = (I - K * C) * P_prior
Austin Schuhe4a14f22015-03-01 00:12:29 -0800120
121 return K, P
Austin Schuh86093ad2016-02-06 14:29:34 -0800122
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800123
124def kalmd(A_continuous, B_continuous, Q_continuous, R_continuous, dt):
125 """Converts a continuous time kalman filter to discrete time.
126
127 Args:
128 A_continuous: The A continuous matrix
129 B_continuous: the B continuous matrix
130 Q_continuous: The continuous cost matrix
131 R_continuous: The R continuous matrix
132 dt: Timestep
133
134 The math for this is from:
135 https://www.mathworks.com/help/control/ref/kalmd.html
136
137 Returns:
138 The discrete matrices of A, B, Q, and R.
139 """
140 # TODO(austin): Verify that the dimensions make sense.
141 number_of_states = A_continuous.shape[0]
142 number_of_inputs = B_continuous.shape[1]
143 M = numpy.zeros((len(A_continuous) + number_of_inputs,
144 len(A_continuous) + number_of_inputs))
145 M[0:number_of_states, 0:number_of_states] = A_continuous
146 M[0:number_of_states, number_of_states:] = B_continuous
147 M_exp = scipy.linalg.expm(M * dt)
148 A_discrete = M_exp[0:number_of_states, 0:number_of_states]
149 B_discrete = numpy.matrix(M_exp[0:number_of_states, number_of_states:])
150 Q_continuous = (Q_continuous + Q_continuous.T) / 2.0
151 R_continuous = (R_continuous + R_continuous.T) / 2.0
152 M = numpy.concatenate((-A_continuous, Q_continuous), axis=1)
153 M = numpy.concatenate(
154 (M, numpy.concatenate((numpy.matrix(
155 numpy.zeros((number_of_states, number_of_states))),
156 numpy.transpose(A_continuous)), axis = 1)), axis = 0)
157 phi = numpy.matrix(scipy.linalg.expm(M*dt))
158 phi12 = phi[0:number_of_states, number_of_states:(2*number_of_states)]
159 phi22 = phi[number_of_states:2*number_of_states, number_of_states:2*number_of_states]
160 Q_discrete = phi22.T * phi12
161 Q_discrete = (Q_discrete + Q_discrete.T) / 2.0
162 R_discrete = R_continuous / dt
163 return (A_discrete, B_discrete, Q_discrete, R_discrete)
164
165
Austin Schuh86093ad2016-02-06 14:29:34 -0800166def TwoStateFeedForwards(B, Q):
167 """Computes the feed forwards constant for a 2 state controller.
168
169 This will take the form U = Kff * (R(n + 1) - A * R(n)), where Kff is the
170 feed-forwards constant. It is important that Kff is *only* computed off
171 the goal and not the feed back terms.
172
173 Args:
174 B: numpy.Matrix[num_states, num_inputs] The B matrix.
175 Q: numpy.Matrix[num_states, num_states] The Q (cost) matrix.
176
177 Returns:
178 numpy.Matrix[num_inputs, num_states]
179 """
180
181 # We want to find the optimal U such that we minimize the tracking cost.
182 # This means that we want to minimize
183 # (B * U - (R(n+1) - A R(n)))^T * Q * (B * U - (R(n+1) - A R(n)))
184 # TODO(austin): This doesn't take into account the cost of U
185
186 return numpy.linalg.inv(B.T * Q * B) * B.T * Q.T