blob: ae209c3f298a1e82d2d9f5473eef80709d115246 [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
Austin Schuh48d60c12017-02-04 21:58:58 -0800102 q_pos = 0.10
103 q_vel = 1.65
104 self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0],
105 [0.0, (q_vel ** 2.0)]])
106
107 r_volts = 0.025
108 self.R = numpy.matrix([[(r_volts ** 2.0)]])
109
110 self.KalmanGain, self.Q_steady = controls.kalman(
111 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
112
113 glog.debug('Kal %s', repr(self.KalmanGain))
114 self.L = self.A * self.KalmanGain
115 glog.debug('KalL is %s', repr(self.L))
116
117 # The box formed by U_min and U_max must encompass all possible values,
118 # or else Austin's code gets angry.
119 self.U_max = numpy.matrix([[12.0]])
120 self.U_min = numpy.matrix([[-12.0]])
121
122 self.InitializeState()
123
124class IntegralIntake(Intake):
125 def __init__(self, name='IntegralIntake'):
126 super(IntegralIntake, self).__init__(name=name)
127
128 self.A_continuous_unaugmented = self.A_continuous
129 self.B_continuous_unaugmented = self.B_continuous
130
131 self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
132 self.A_continuous[0:2, 0:2] = self.A_continuous_unaugmented
133 self.A_continuous[0:2, 2] = self.B_continuous_unaugmented
134
135 self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
136 self.B_continuous[0:2, 0] = self.B_continuous_unaugmented
137
138 self.C_unaugmented = self.C
139 self.C = numpy.matrix(numpy.zeros((1, 3)))
140 self.C[0:1, 0:2] = self.C_unaugmented
141
142 self.A, self.B = self.ContinuousToDiscrete(
143 self.A_continuous, self.B_continuous, self.dt)
144
145 q_pos = 0.12
146 q_vel = 2.00
147 q_voltage = 40.0
148 self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0, 0.0],
149 [0.0, (q_vel ** 2.0), 0.0],
150 [0.0, 0.0, (q_voltage ** 2.0)]])
151
152 r_pos = 0.05
153 self.R = numpy.matrix([[(r_pos ** 2.0)]])
154
155 self.KalmanGain, self.Q_steady = controls.kalman(
156 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
157 self.L = self.A * self.KalmanGain
158
159 self.K_unaugmented = self.K
160 self.K = numpy.matrix(numpy.zeros((1, 3)))
161 self.K[0, 0:2] = self.K_unaugmented
162 self.K[0, 2] = 1
163
164 self.Kff = numpy.concatenate((self.Kff, numpy.matrix(numpy.zeros((1, 1)))), axis=1)
165
166 self.InitializeState()
167
168class ScenarioPlotter(object):
169 def __init__(self):
170 # Various lists for graphing things.
171 self.t = []
172 self.x = []
173 self.v = []
174 self.a = []
175 self.x_hat = []
176 self.u = []
177 self.offset = []
178
179 def run_test(self, intake, end_goal,
180 controller_intake,
181 observer_intake=None,
182 iterations=200):
183 """Runs the intake plant with an initial condition and goal.
184
185 Args:
186 intake: intake object to use.
187 end_goal: end_goal state.
188 controller_intake: Intake object to get K from, or None if we should
189 use intake.
190 observer_intake: Intake object to use for the observer, or None if we should
191 use the actual state.
192 iterations: Number of timesteps to run the model for.
193 """
194
195 if controller_intake is None:
196 controller_intake = intake
197
198 vbat = 12.0
199
200 if self.t:
201 initial_t = self.t[-1] + intake.dt
202 else:
203 initial_t = 0
204
205 goal = numpy.concatenate((intake.X, numpy.matrix(numpy.zeros((1, 1)))), axis=0)
206
207 profile = TrapezoidProfile(intake.dt)
208 profile.set_maximum_acceleration(10.0)
209 profile.set_maximum_velocity(0.3)
210 profile.SetGoal(goal[0, 0])
211
212 U_last = numpy.matrix(numpy.zeros((1, 1)))
213 for i in xrange(iterations):
214 observer_intake.Y = intake.Y
215 observer_intake.CorrectObserver(U_last)
216
217 self.offset.append(observer_intake.X_hat[2, 0])
218 self.x_hat.append(observer_intake.X_hat[0, 0])
219
220 next_goal = numpy.concatenate(
221 (profile.Update(end_goal[0, 0], end_goal[1, 0]),
222 numpy.matrix(numpy.zeros((1, 1)))),
223 axis=0)
224
225 ff_U = controller_intake.Kff * (next_goal - observer_intake.A * goal)
226
227 U_uncapped = controller_intake.K * (goal - observer_intake.X_hat) + ff_U
228 U_uncapped = controller_intake.K * (end_goal - observer_intake.X_hat)
229 U = U_uncapped.copy()
230 U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
231 self.x.append(intake.X[0, 0])
232
233 if self.v:
234 last_v = self.v[-1]
235 else:
236 last_v = 0
237
238 self.v.append(intake.X[1, 0])
239 self.a.append((self.v[-1] - last_v) / intake.dt)
240
241 offset = 0.0
242 if i > 100:
243 offset = 2.0
244 intake.Update(U + offset)
245
246 observer_intake.PredictObserver(U)
247
248 self.t.append(initial_t + i * intake.dt)
249 self.u.append(U[0, 0])
250
251 ff_U -= U_uncapped - U
252 goal = controller_intake.A * goal + controller_intake.B * ff_U
253
254 if U[0, 0] != U_uncapped[0, 0]:
255 profile.MoveCurrentState(
256 numpy.matrix([[goal[0, 0]], [goal[1, 0]]]))
257
258 glog.debug('Time: %f', self.t[-1])
259 glog.debug('goal_error %s', repr(end_goal - goal))
260 glog.debug('error %s', repr(observer_intake.X_hat - end_goal))
261
262 def Plot(self):
263 pylab.subplot(3, 1, 1)
264 pylab.plot(self.t, self.x, label='x')
265 pylab.plot(self.t, self.x_hat, label='x_hat')
266 pylab.legend()
267
268 pylab.subplot(3, 1, 2)
269 pylab.plot(self.t, self.u, label='u')
270 pylab.plot(self.t, self.offset, label='voltage_offset')
271 pylab.legend()
272
273 pylab.subplot(3, 1, 3)
274 pylab.plot(self.t, self.a, label='a')
275 pylab.legend()
276
277 pylab.show()
278
279
280def main(argv):
281 scenario_plotter = ScenarioPlotter()
282
283 intake = Intake()
284 intake_controller = IntegralIntake()
285 observer_intake = IntegralIntake()
286
287 # Test moving the intake with constant separation.
288 initial_X = numpy.matrix([[0.0], [0.0]])
289 R = numpy.matrix([[0.1], [0.0], [0.0]])
290 scenario_plotter.run_test(intake, end_goal=R,
291 controller_intake=intake_controller,
292 observer_intake=observer_intake, iterations=400)
293
294 if FLAGS.plot:
295 scenario_plotter.Plot()
296
297 # Write the generated constants out to a file.
298 if len(argv) != 5:
299 glog.fatal('Expected .h file name and .cc file name for the intake and integral intake.')
300 else:
301 namespaces = ['y2017', 'control_loops', 'superstructure', 'intake']
302 intake = Intake('Intake')
303 loop_writer = control_loop.ControlLoopWriter('Intake', [intake],
304 namespaces=namespaces)
Brian Silverman052e69d2017-02-12 16:19:55 -0800305 loop_writer.AddConstant(control_loop.Constant('kFreeSpeed', '%f',
306 intake.free_speed))
307 loop_writer.AddConstant(control_loop.Constant('kOutputRatio', '%f',
308 intake.G * intake.r))
Austin Schuh48d60c12017-02-04 21:58:58 -0800309 loop_writer.Write(argv[1], argv[2])
310
311 integral_intake = IntegralIntake('IntegralIntake')
312 integral_loop_writer = control_loop.ControlLoopWriter('IntegralIntake', [integral_intake],
313 namespaces=namespaces)
314 integral_loop_writer.Write(argv[3], argv[4])
315
316if __name__ == '__main__':
317 argv = FLAGS(sys.argv)
318 glog.init()
319 sys.exit(main(argv))