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