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