blob: f07e7a58da40e296a5d760502c2ee8616fef7c39 [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
Austin Schuh48d60c12017-02-04 21:58:58 -08008from matplotlib import pylab
9import gflags
10import glog
11
12FLAGS = gflags.FLAGS
13
14try:
15 gflags.DEFINE_bool('plot', False, 'If true, plot the loop response.')
16except gflags.DuplicateFlagError:
17 pass
18
19class Turret(control_loop.ControlLoop):
20 def __init__(self, name='Turret'):
21 super(Turret, self).__init__(name)
22 # Stall Torque in N m
Austin Schuh82a66dc2017-03-04 15:06:44 -080023 self.stall_torque = 0.71
Austin Schuh48d60c12017-02-04 21:58:58 -080024 # Stall Current in Amps
Austin Schuh82a66dc2017-03-04 15:06:44 -080025 self.stall_current = 134
26 self.free_speed_rpm = 18730.0
Brian Silverman052e69d2017-02-12 16:19:55 -080027 # Free Speed in rotations/second.
28 self.free_speed = self.free_speed_rpm / 60.0
Austin Schuh48d60c12017-02-04 21:58:58 -080029 # Free Current in Amps
Austin Schuh82a66dc2017-03-04 15:06:44 -080030 self.free_current = 0.7
Austin Schuh48d60c12017-02-04 21:58:58 -080031
32 # Resistance of the motor
Austin Schuh82a66dc2017-03-04 15:06:44 -080033 self.resistance = 12.0 / self.stall_current
Austin Schuh48d60c12017-02-04 21:58:58 -080034 # Motor velocity constant
Brian Silverman052e69d2017-02-12 16:19:55 -080035 self.Kv = ((self.free_speed * 2.0 * numpy.pi) /
Austin Schuh82a66dc2017-03-04 15:06:44 -080036 (12.0 - self.resistance * self.free_current))
Austin Schuh48d60c12017-02-04 21:58:58 -080037 # Torque constant
38 self.Kt = self.stall_torque / self.stall_current
39 # Gear ratio
Austin Schuh82a66dc2017-03-04 15:06:44 -080040 self.G = (12.0 / 60.0) * (11.0 / 94.0)
Austin Schuh48d60c12017-02-04 21:58:58 -080041
42 # Motor inertia in kg * m^2
Austin Schuh82a66dc2017-03-04 15:06:44 -080043 self.motor_inertia = 0.00001187
Austin Schuh48d60c12017-02-04 21:58:58 -080044
45 # Moment of inertia, measured in CAD.
46 # Extra mass to compensate for friction is added on.
Austin Schuhfbceb1c2017-03-11 22:10:57 -080047 self.J = 0.06 + self.motor_inertia * ((1.0 / self.G) ** 2.0)
Austin Schuheb5c22e2017-04-09 18:30:28 -070048 glog.debug('Turret J is: %f', self.J)
Austin Schuh48d60c12017-02-04 21:58:58 -080049
50 # Control loop time step
51 self.dt = 0.005
52
53 # State is [position, velocity]
54 # Input is [Voltage]
55
Austin Schuh82a66dc2017-03-04 15:06:44 -080056 C1 = self.Kt / (self.resistance * self.J * self.Kv * self.G * self.G)
57 C2 = self.Kt / (self.J * self.resistance * self.G)
Austin Schuh48d60c12017-02-04 21:58:58 -080058
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
Austin Schuh48d60c12017-02-04 21:58:58 -080096 q_pos = 0.10
97 q_vel = 1.65
98 self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0],
99 [0.0, (q_vel ** 2.0)]])
100
101 r_volts = 0.025
102 self.R = numpy.matrix([[(r_volts ** 2.0)]])
103
104 self.KalmanGain, self.Q_steady = controls.kalman(
105 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
Austin Schuh48d60c12017-02-04 21:58:58 -0800106 self.L = self.A * self.KalmanGain
Austin Schuh48d60c12017-02-04 21:58:58 -0800107
108 # The box formed by U_min and U_max must encompass all possible values,
109 # or else Austin's code gets angry.
110 self.U_max = numpy.matrix([[12.0]])
111 self.U_min = numpy.matrix([[-12.0]])
112
113 self.InitializeState()
114
115class IntegralTurret(Turret):
116 def __init__(self, name='IntegralTurret'):
117 super(IntegralTurret, self).__init__(name=name)
118
119 self.A_continuous_unaugmented = self.A_continuous
120 self.B_continuous_unaugmented = self.B_continuous
121
122 self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
123 self.A_continuous[0:2, 0:2] = self.A_continuous_unaugmented
124 self.A_continuous[0:2, 2] = self.B_continuous_unaugmented
125
126 self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
127 self.B_continuous[0:2, 0] = self.B_continuous_unaugmented
128
129 self.C_unaugmented = self.C
130 self.C = numpy.matrix(numpy.zeros((1, 3)))
131 self.C[0:1, 0:2] = self.C_unaugmented
132
133 self.A, self.B = self.ContinuousToDiscrete(
134 self.A_continuous, self.B_continuous, self.dt)
135
136 q_pos = 0.12
137 q_vel = 2.00
138 q_voltage = 3.0
139 self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0, 0.0],
140 [0.0, (q_vel ** 2.0), 0.0],
141 [0.0, 0.0, (q_voltage ** 2.0)]])
142
143 r_pos = 0.05
144 self.R = numpy.matrix([[(r_pos ** 2.0)]])
145
146 self.KalmanGain, self.Q_steady = controls.kalman(
147 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
148 self.L = self.A * self.KalmanGain
149
150 self.K_unaugmented = self.K
151 self.K = numpy.matrix(numpy.zeros((1, 3)))
152 self.K[0, 0:2] = self.K_unaugmented
153 self.K[0, 2] = 1
154
155 self.Kff = numpy.concatenate((self.Kff, numpy.matrix(numpy.zeros((1, 1)))), axis=1)
156
157 self.InitializeState()
158
159class ScenarioPlotter(object):
160 def __init__(self):
161 # Various lists for graphing things.
162 self.t = []
163 self.x = []
164 self.v = []
165 self.a = []
166 self.x_hat = []
167 self.u = []
168 self.offset = []
169
170 def run_test(self, turret, end_goal,
171 controller_turret,
172 observer_turret=None,
173 iterations=200):
174 """Runs the turret plant with an initial condition and goal.
175
176 Args:
177 turret: turret object to use.
178 end_goal: end_goal state.
179 controller_turret: Turret object to get K from, or None if we should
180 use turret.
181 observer_turret: Turret object to use for the observer, or None if we should
182 use the actual state.
183 iterations: Number of timesteps to run the model for.
184 """
185
186 if controller_turret is None:
187 controller_turret = turret
188
189 vbat = 12.0
190
191 if self.t:
192 initial_t = self.t[-1] + turret.dt
193 else:
194 initial_t = 0
195
196 goal = numpy.concatenate((turret.X, numpy.matrix(numpy.zeros((1, 1)))), axis=0)
197
198 profile = TrapezoidProfile(turret.dt)
199 profile.set_maximum_acceleration(100.0)
200 profile.set_maximum_velocity(7.0)
201 profile.SetGoal(goal[0, 0])
202
203 U_last = numpy.matrix(numpy.zeros((1, 1)))
204 for i in xrange(iterations):
205 observer_turret.Y = turret.Y
206 observer_turret.CorrectObserver(U_last)
207
208 self.offset.append(observer_turret.X_hat[2, 0])
209 self.x_hat.append(observer_turret.X_hat[0, 0])
210
211 next_goal = numpy.concatenate(
212 (profile.Update(end_goal[0, 0], end_goal[1, 0]),
213 numpy.matrix(numpy.zeros((1, 1)))),
214 axis=0)
215
216 ff_U = controller_turret.Kff * (next_goal - observer_turret.A * goal)
217
218 U_uncapped = controller_turret.K * (goal - observer_turret.X_hat) + ff_U
219 U_uncapped = controller_turret.K * (end_goal - observer_turret.X_hat)
220 U = U_uncapped.copy()
221 U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
222 self.x.append(turret.X[0, 0])
223
224 if self.v:
225 last_v = self.v[-1]
226 else:
227 last_v = 0
228
229 self.v.append(turret.X[1, 0])
230 self.a.append((self.v[-1] - last_v) / turret.dt)
231
232 offset = 0.0
233 if i > 100:
234 offset = 2.0
235 turret.Update(U + offset)
236
237 observer_turret.PredictObserver(U)
238
239 self.t.append(initial_t + i * turret.dt)
240 self.u.append(U[0, 0])
241
242 ff_U -= U_uncapped - U
243 goal = controller_turret.A * goal + controller_turret.B * ff_U
244
245 if U[0, 0] != U_uncapped[0, 0]:
246 profile.MoveCurrentState(
247 numpy.matrix([[goal[0, 0]], [goal[1, 0]]]))
248
249 glog.debug('Time: %f', self.t[-1])
250 glog.debug('goal_error %s', repr(end_goal - goal))
251 glog.debug('error %s', repr(observer_turret.X_hat - end_goal))
252
253 def Plot(self):
254 pylab.subplot(3, 1, 1)
255 pylab.plot(self.t, self.x, label='x')
256 pylab.plot(self.t, self.x_hat, label='x_hat')
257 pylab.legend()
258
259 pylab.subplot(3, 1, 2)
260 pylab.plot(self.t, self.u, label='u')
261 pylab.plot(self.t, self.offset, label='voltage_offset')
262 pylab.legend()
263
264 pylab.subplot(3, 1, 3)
265 pylab.plot(self.t, self.a, label='a')
266 pylab.legend()
267
268 pylab.show()
269
270
271def main(argv):
272 argv = FLAGS(argv)
273 glog.init()
274
275 scenario_plotter = ScenarioPlotter()
276
277 turret = Turret()
278 turret_controller = IntegralTurret()
279 observer_turret = IntegralTurret()
280
281 # Test moving the turret with constant separation.
282 initial_X = numpy.matrix([[0.0], [0.0]])
283 R = numpy.matrix([[numpy.pi/2.0], [0.0], [0.0]])
284 scenario_plotter.run_test(turret, end_goal=R,
285 controller_turret=turret_controller,
286 observer_turret=observer_turret, iterations=200)
287
288 if FLAGS.plot:
289 scenario_plotter.Plot()
290
291 # Write the generated constants out to a file.
292 if len(argv) != 5:
293 glog.fatal('Expected .h file name and .cc file name for the turret and integral turret.')
294 else:
295 namespaces = ['y2017', 'control_loops', 'superstructure', 'turret']
296 turret = Turret('Turret')
297 loop_writer = control_loop.ControlLoopWriter('Turret', [turret],
298 namespaces=namespaces)
Brian Silverman052e69d2017-02-12 16:19:55 -0800299 loop_writer.AddConstant(control_loop.Constant(
300 'kFreeSpeed', '%f', turret.free_speed))
301 loop_writer.AddConstant(control_loop.Constant(
302 'kOutputRatio', '%f', turret.G))
Austin Schuh48d60c12017-02-04 21:58:58 -0800303 loop_writer.Write(argv[1], argv[2])
304
305 integral_turret = IntegralTurret('IntegralTurret')
306 integral_loop_writer = control_loop.ControlLoopWriter(
307 'IntegralTurret', [integral_turret],
308 namespaces=namespaces)
309 integral_loop_writer.Write(argv[3], argv[4])
310
311if __name__ == '__main__':
312 sys.exit(main(sys.argv))