blob: a69e3e1bfa10e4731a0aea6972024cbcbccf0562 [file] [log] [blame]
Austin Schuh48d60c12017-02-04 21:58:58 -08001#!/usr/bin/python
2
3from aos.common.util.trapezoid_profile import TrapezoidProfile
4from frc971.control_loops.python import control_loop
5from frc971.control_loops.python import controls
6import numpy
7import sys
8import matplotlib
9from matplotlib import pylab
10import gflags
11import glog
12
13FLAGS = gflags.FLAGS
14
15try:
16 gflags.DEFINE_bool('plot', False, 'If true, plot the loop response.')
17except gflags.DuplicateFlagError:
18 pass
19
20class Turret(control_loop.ControlLoop):
21 def __init__(self, name='Turret'):
22 super(Turret, self).__init__(name)
23 # Stall Torque in N m
24 self.stall_torque = 0.43
25 # Stall Current in Amps
26 self.stall_current = 53
Brian Silverman052e69d2017-02-12 16:19:55 -080027 self.free_speed_rpm = 13180
28 # Free Speed in rotations/second.
29 self.free_speed = self.free_speed_rpm / 60.0
Austin Schuh48d60c12017-02-04 21:58:58 -080030 # Free Current in Amps
31 self.free_current = 1.8
32
33 # Resistance of the motor
34 self.R = 12.0 / self.stall_current
35 # Motor velocity constant
Brian Silverman052e69d2017-02-12 16:19:55 -080036 self.Kv = ((self.free_speed * 2.0 * numpy.pi) /
Austin Schuh48d60c12017-02-04 21:58:58 -080037 (12.0 - self.R * self.free_current))
38 # Torque constant
39 self.Kt = self.stall_torque / self.stall_current
40 # Gear ratio
41 self.G = (1.0 / 7.0) * (1.0 / 5.0) * (16.0 / 92.0)
42
43 # Motor inertia in kg * m^2
44 self.motor_inertia = 0.000006
45
46 # Moment of inertia, measured in CAD.
47 # Extra mass to compensate for friction is added on.
48 self.J = 0.05 + self.motor_inertia * ((1.0 / self.G) ** 2.0)
49
50 # Control loop time step
51 self.dt = 0.005
52
53 # State is [position, velocity]
54 # Input is [Voltage]
55
56 C1 = self.Kt / (self.R * self.J * self.Kv * self.G * self.G)
57 C2 = self.Kt / (self.J * self.R * self.G)
58
59 self.A_continuous = numpy.matrix(
60 [[0, 1],
61 [0, -C1]])
62
63 # Start with the unmodified input
64 self.B_continuous = numpy.matrix(
65 [[0],
66 [C2]])
67
68 self.C = numpy.matrix([[1, 0]])
69 self.D = numpy.matrix([[0]])
70
71 self.A, self.B = self.ContinuousToDiscrete(
72 self.A_continuous, self.B_continuous, self.dt)
73
74 controllability = controls.ctrb(self.A, self.B)
75
76 glog.debug('Free speed is %f',
77 -self.B_continuous[1, 0] / self.A_continuous[1, 1] * 12.0)
78
79 # Calculate the LQR controller gain
80 q_pos = 0.20
81 q_vel = 5.0
82 self.Q = numpy.matrix([[(1.0 / (q_pos ** 2.0)), 0.0],
83 [0.0, (1.0 / (q_vel ** 2.0))]])
84
85 self.R = numpy.matrix([[(1.0 / (12.0 ** 2.0))]])
86 self.K = controls.dlqr(self.A, self.B, self.Q, self.R)
87
88 # Calculate the feed forwards gain.
89 q_pos_ff = 0.005
90 q_vel_ff = 1.0
91 self.Qff = numpy.matrix([[(1.0 / (q_pos_ff ** 2.0)), 0.0],
92 [0.0, (1.0 / (q_vel_ff ** 2.0))]])
93
94 self.Kff = controls.TwoStateFeedForwards(self.B, self.Qff)
95
96 glog.debug('K %s', repr(self.K))
97 glog.debug('Poles are %s',
98 repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
99
100 q_pos = 0.10
101 q_vel = 1.65
102 self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0],
103 [0.0, (q_vel ** 2.0)]])
104
105 r_volts = 0.025
106 self.R = numpy.matrix([[(r_volts ** 2.0)]])
107
108 self.KalmanGain, self.Q_steady = controls.kalman(
109 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
110
111 glog.debug('Kal %s', repr(self.KalmanGain))
112 self.L = self.A * self.KalmanGain
113 glog.debug('KalL is %s', repr(self.L))
114
115 # The box formed by U_min and U_max must encompass all possible values,
116 # or else Austin's code gets angry.
117 self.U_max = numpy.matrix([[12.0]])
118 self.U_min = numpy.matrix([[-12.0]])
119
120 self.InitializeState()
121
122class IntegralTurret(Turret):
123 def __init__(self, name='IntegralTurret'):
124 super(IntegralTurret, self).__init__(name=name)
125
126 self.A_continuous_unaugmented = self.A_continuous
127 self.B_continuous_unaugmented = self.B_continuous
128
129 self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
130 self.A_continuous[0:2, 0:2] = self.A_continuous_unaugmented
131 self.A_continuous[0:2, 2] = self.B_continuous_unaugmented
132
133 self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
134 self.B_continuous[0:2, 0] = self.B_continuous_unaugmented
135
136 self.C_unaugmented = self.C
137 self.C = numpy.matrix(numpy.zeros((1, 3)))
138 self.C[0:1, 0:2] = self.C_unaugmented
139
140 self.A, self.B = self.ContinuousToDiscrete(
141 self.A_continuous, self.B_continuous, self.dt)
142
143 q_pos = 0.12
144 q_vel = 2.00
145 q_voltage = 3.0
146 self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0, 0.0],
147 [0.0, (q_vel ** 2.0), 0.0],
148 [0.0, 0.0, (q_voltage ** 2.0)]])
149
150 r_pos = 0.05
151 self.R = numpy.matrix([[(r_pos ** 2.0)]])
152
153 self.KalmanGain, self.Q_steady = controls.kalman(
154 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
155 self.L = self.A * self.KalmanGain
156
157 self.K_unaugmented = self.K
158 self.K = numpy.matrix(numpy.zeros((1, 3)))
159 self.K[0, 0:2] = self.K_unaugmented
160 self.K[0, 2] = 1
161
162 self.Kff = numpy.concatenate((self.Kff, numpy.matrix(numpy.zeros((1, 1)))), axis=1)
163
164 self.InitializeState()
165
166class ScenarioPlotter(object):
167 def __init__(self):
168 # Various lists for graphing things.
169 self.t = []
170 self.x = []
171 self.v = []
172 self.a = []
173 self.x_hat = []
174 self.u = []
175 self.offset = []
176
177 def run_test(self, turret, end_goal,
178 controller_turret,
179 observer_turret=None,
180 iterations=200):
181 """Runs the turret plant with an initial condition and goal.
182
183 Args:
184 turret: turret object to use.
185 end_goal: end_goal state.
186 controller_turret: Turret object to get K from, or None if we should
187 use turret.
188 observer_turret: Turret object to use for the observer, or None if we should
189 use the actual state.
190 iterations: Number of timesteps to run the model for.
191 """
192
193 if controller_turret is None:
194 controller_turret = turret
195
196 vbat = 12.0
197
198 if self.t:
199 initial_t = self.t[-1] + turret.dt
200 else:
201 initial_t = 0
202
203 goal = numpy.concatenate((turret.X, numpy.matrix(numpy.zeros((1, 1)))), axis=0)
204
205 profile = TrapezoidProfile(turret.dt)
206 profile.set_maximum_acceleration(100.0)
207 profile.set_maximum_velocity(7.0)
208 profile.SetGoal(goal[0, 0])
209
210 U_last = numpy.matrix(numpy.zeros((1, 1)))
211 for i in xrange(iterations):
212 observer_turret.Y = turret.Y
213 observer_turret.CorrectObserver(U_last)
214
215 self.offset.append(observer_turret.X_hat[2, 0])
216 self.x_hat.append(observer_turret.X_hat[0, 0])
217
218 next_goal = numpy.concatenate(
219 (profile.Update(end_goal[0, 0], end_goal[1, 0]),
220 numpy.matrix(numpy.zeros((1, 1)))),
221 axis=0)
222
223 ff_U = controller_turret.Kff * (next_goal - observer_turret.A * goal)
224
225 U_uncapped = controller_turret.K * (goal - observer_turret.X_hat) + ff_U
226 U_uncapped = controller_turret.K * (end_goal - observer_turret.X_hat)
227 U = U_uncapped.copy()
228 U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
229 self.x.append(turret.X[0, 0])
230
231 if self.v:
232 last_v = self.v[-1]
233 else:
234 last_v = 0
235
236 self.v.append(turret.X[1, 0])
237 self.a.append((self.v[-1] - last_v) / turret.dt)
238
239 offset = 0.0
240 if i > 100:
241 offset = 2.0
242 turret.Update(U + offset)
243
244 observer_turret.PredictObserver(U)
245
246 self.t.append(initial_t + i * turret.dt)
247 self.u.append(U[0, 0])
248
249 ff_U -= U_uncapped - U
250 goal = controller_turret.A * goal + controller_turret.B * ff_U
251
252 if U[0, 0] != U_uncapped[0, 0]:
253 profile.MoveCurrentState(
254 numpy.matrix([[goal[0, 0]], [goal[1, 0]]]))
255
256 glog.debug('Time: %f', self.t[-1])
257 glog.debug('goal_error %s', repr(end_goal - goal))
258 glog.debug('error %s', repr(observer_turret.X_hat - end_goal))
259
260 def Plot(self):
261 pylab.subplot(3, 1, 1)
262 pylab.plot(self.t, self.x, label='x')
263 pylab.plot(self.t, self.x_hat, label='x_hat')
264 pylab.legend()
265
266 pylab.subplot(3, 1, 2)
267 pylab.plot(self.t, self.u, label='u')
268 pylab.plot(self.t, self.offset, label='voltage_offset')
269 pylab.legend()
270
271 pylab.subplot(3, 1, 3)
272 pylab.plot(self.t, self.a, label='a')
273 pylab.legend()
274
275 pylab.show()
276
277
278def main(argv):
279 argv = FLAGS(argv)
280 glog.init()
281
282 scenario_plotter = ScenarioPlotter()
283
284 turret = Turret()
285 turret_controller = IntegralTurret()
286 observer_turret = IntegralTurret()
287
288 # Test moving the turret with constant separation.
289 initial_X = numpy.matrix([[0.0], [0.0]])
290 R = numpy.matrix([[numpy.pi/2.0], [0.0], [0.0]])
291 scenario_plotter.run_test(turret, end_goal=R,
292 controller_turret=turret_controller,
293 observer_turret=observer_turret, iterations=200)
294
295 if FLAGS.plot:
296 scenario_plotter.Plot()
297
298 # Write the generated constants out to a file.
299 if len(argv) != 5:
300 glog.fatal('Expected .h file name and .cc file name for the turret and integral turret.')
301 else:
302 namespaces = ['y2017', 'control_loops', 'superstructure', 'turret']
303 turret = Turret('Turret')
304 loop_writer = control_loop.ControlLoopWriter('Turret', [turret],
305 namespaces=namespaces)
Brian Silverman052e69d2017-02-12 16:19:55 -0800306 loop_writer.AddConstant(control_loop.Constant(
307 'kFreeSpeed', '%f', turret.free_speed))
308 loop_writer.AddConstant(control_loop.Constant(
309 'kOutputRatio', '%f', turret.G))
Austin Schuh48d60c12017-02-04 21:58:58 -0800310 loop_writer.Write(argv[1], argv[2])
311
312 integral_turret = IntegralTurret('IntegralTurret')
313 integral_loop_writer = control_loop.ControlLoopWriter(
314 'IntegralTurret', [integral_turret],
315 namespaces=namespaces)
316 integral_loop_writer.Write(argv[3], argv[4])
317
318if __name__ == '__main__':
319 sys.exit(main(sys.argv))