blob: fa34063467290d645d3625b66fcc1556b3a6eba9 [file] [log] [blame]
Adam Snaider18f44172016-10-22 15:30:21 -07001#!/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 # TODO(constants): Update all of these & retune poles.
24 # Stall Torque in N m
25 self.stall_torque = 0.71
26 # Stall Current in Amps
27 self.stall_current = 134
28 # Free Speed in RPM
29 self.free_speed = 18730
30 # 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
36 self.Kv = ((self.free_speed / 60.0 * 2.0 * numpy.pi) /
37 (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 = (56.0 / 12.0) * (54.0 / 14.0) * (64.0 / 18.0) * (48.0 / 16.0)
42
43 # Moment of inertia, measured in CAD.
44 # Extra mass to compensate for friction is added on.
45 self.J = 0.34 + 0.40
46
47 # Control loop time step
48 self.dt = 0.005
49
50 # State is [position, velocity]
51 # Input is [Voltage]
52
53 C1 = self.G * self.G * self.Kt / (self.R * self.J * self.Kv)
54 C2 = self.Kt * self.G / (self.J * self.R)
55
56 self.A_continuous = numpy.matrix(
57 [[0, 1],
58 [0, -C1]])
59
60 # Start with the unmodified input
61 self.B_continuous = numpy.matrix(
62 [[0],
63 [C2]])
64
65 self.C = numpy.matrix([[1, 0]])
66 self.D = numpy.matrix([[0]])
67
68 self.A, self.B = self.ContinuousToDiscrete(
69 self.A_continuous, self.B_continuous, self.dt)
70
71 controllability = controls.ctrb(self.A, self.B)
72
73 glog.debug("Free speed is %f", self.free_speed * numpy.pi * 2.0 / 60.0 / self.G)
74
75 q_pos = 0.20
76 q_vel = 5.0
77 self.Q = numpy.matrix([[(1.0 / (q_pos ** 2.0)), 0.0],
78 [0.0, (1.0 / (q_vel ** 2.0))]])
79
80 self.R = numpy.matrix([[(1.0 / (12.0 ** 2.0))]])
81 self.K = controls.dlqr(self.A, self.B, self.Q, self.R)
82
83 q_pos_ff = 0.005
84 q_vel_ff = 1.0
85 self.Qff = numpy.matrix([[(1.0 / (q_pos_ff ** 2.0)), 0.0],
86 [0.0, (1.0 / (q_vel_ff ** 2.0))]])
87
88 self.Kff = controls.TwoStateFeedForwards(self.B, self.Qff)
89
90 glog.debug('K %s', repr(self.K))
91 glog.debug('Poles are %s',
92 repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
93
94 self.rpl = 0.30
95 self.ipl = 0.10
96 self.PlaceObserverPoles([self.rpl + 1j * self.ipl,
97 self.rpl - 1j * self.ipl])
98
99 glog.debug('L is %s', repr(self.L))
100
101 q_pos = 0.10
102 q_vel = 1.65
103 self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0],
104 [0.0, (q_vel ** 2.0)]])
105
106 r_volts = 0.025
107 self.R = numpy.matrix([[(r_volts ** 2.0)]])
108
109 self.KalmanGain, self.Q_steady = controls.kalman(
110 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
111
112 glog.debug('Kal %s', repr(self.KalmanGain))
113 self.L = self.A * self.KalmanGain
114 glog.debug('KalL is %s', repr(self.L))
115
116 # The box formed by U_min and U_max must encompass all possible values,
117 # or else Austin's code gets angry.
118 self.U_max = numpy.matrix([[12.0]])
119 self.U_min = numpy.matrix([[-12.0]])
120
121 self.InitializeState()
122
123class IntegralIntake(Intake):
124 def __init__(self, name="IntegralIntake"):
125 super(IntegralIntake, self).__init__(name=name)
126
127 self.A_continuous_unaugmented = self.A_continuous
128 self.B_continuous_unaugmented = self.B_continuous
129
130 self.A_continuous = numpy.matrix(numpy.zeros((3, 3)))
131 self.A_continuous[0:2, 0:2] = self.A_continuous_unaugmented
132 self.A_continuous[0:2, 2] = self.B_continuous_unaugmented
133
134 self.B_continuous = numpy.matrix(numpy.zeros((3, 1)))
135 self.B_continuous[0:2, 0] = self.B_continuous_unaugmented
136
137 self.C_unaugmented = self.C
138 self.C = numpy.matrix(numpy.zeros((1, 3)))
139 self.C[0:1, 0:2] = self.C_unaugmented
140
141 self.A, self.B = self.ContinuousToDiscrete(
142 self.A_continuous, self.B_continuous, self.dt)
143
144 q_pos = 0.12
145 q_vel = 2.00
146 q_voltage = 4.0
147 self.Q = numpy.matrix([[(q_pos ** 2.0), 0.0, 0.0],
148 [0.0, (q_vel ** 2.0), 0.0],
149 [0.0, 0.0, (q_voltage ** 2.0)]])
150
151 r_pos = 0.05
152 self.R = numpy.matrix([[(r_pos ** 2.0)]])
153
154 self.KalmanGain, self.Q_steady = controls.kalman(
155 A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R)
156 self.L = self.A * self.KalmanGain
157
158 self.K_unaugmented = self.K
159 self.K = numpy.matrix(numpy.zeros((1, 3)))
160 self.K[0, 0:2] = self.K_unaugmented
161 self.K[0, 2] = 1
162
163 self.Kff = numpy.concatenate((self.Kff, numpy.matrix(numpy.zeros((1, 1)))), axis=1)
164
165 self.InitializeState()
166
167class ScenarioPlotter(object):
168 def __init__(self):
169 # Various lists for graphing things.
170 self.t = []
171 self.x = []
172 self.v = []
173 self.a = []
174 self.x_hat = []
175 self.u = []
176 self.offset = []
177
178 def run_test(self, intake, end_goal,
179 controller_intake,
180 observer_intake=None,
181 iterations=200):
182 """Runs the intake plant with an initial condition and goal.
183
184 Args:
185 intake: intake object to use.
186 end_goal: end_goal state.
187 controller_intake: Intake object to get K from, or None if we should
188 use intake.
189 observer_intake: Intake object to use for the observer, or None if we should
190 use the actual state.
191 iterations: Number of timesteps to run the model for.
192 """
193
194 if controller_intake is None:
195 controller_intake = intake
196
197 vbat = 12.0
198
199 if self.t:
200 initial_t = self.t[-1] + intake.dt
201 else:
202 initial_t = 0
203
204 goal = numpy.concatenate((intake.X, numpy.matrix(numpy.zeros((1, 1)))), axis=0)
205
206 profile = TrapezoidProfile(intake.dt)
207 profile.set_maximum_acceleration(70.0)
208 profile.set_maximum_velocity(10.0)
209 profile.SetGoal(goal[0, 0])
210
211 U_last = numpy.matrix(numpy.zeros((1, 1)))
212 for i in xrange(iterations):
213 observer_intake.Y = intake.Y
214 observer_intake.CorrectObserver(U_last)
215
216 self.offset.append(observer_intake.X_hat[2, 0])
217 self.x_hat.append(observer_intake.X_hat[0, 0])
218
219 next_goal = numpy.concatenate(
220 (profile.Update(end_goal[0, 0], end_goal[1, 0]),
221 numpy.matrix(numpy.zeros((1, 1)))),
222 axis=0)
223
224 ff_U = controller_intake.Kff * (next_goal - observer_intake.A * goal)
225
226 U_uncapped = controller_intake.K * (goal - observer_intake.X_hat) + ff_U
227 U = U_uncapped.copy()
228 U[0, 0] = numpy.clip(U[0, 0], -vbat, vbat)
229 self.x.append(intake.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(intake.X[1, 0])
237 self.a.append((self.v[-1] - last_v) / intake.dt)
238
239 offset = 0.0
240 if i > 100:
241 offset = 2.0
242 intake.Update(U + offset)
243
244 observer_intake.PredictObserver(U)
245
246 self.t.append(initial_t + i * intake.dt)
247 self.u.append(U[0, 0])
248
249 ff_U -= U_uncapped - U
250 goal = controller_intake.A * goal + controller_intake.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_intake.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 intake = Intake()
285 intake_controller = IntegralIntake()
286 observer_intake = IntegralIntake()
287
288 # Test moving the intake 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(intake, end_goal=R,
292 controller_intake=intake_controller,
293 observer_intake=observer_intake, 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 intake and integral intake.')
301 else:
302 namespaces = ['y2016_bot3', 'control_loops', 'intake']
303 intake = Intake("Intake")
304 loop_writer = control_loop.ControlLoopWriter('Intake', [intake],
305 namespaces=namespaces)
306 loop_writer.Write(argv[1], argv[2])
307
308 integral_intake = IntegralIntake("IntegralIntake")
309 integral_loop_writer = control_loop.ControlLoopWriter("IntegralIntake", [integral_intake],
310 namespaces=namespaces)
311 integral_loop_writer.Write(argv[3], argv[4])
312
313if __name__ == '__main__':
314 sys.exit(main(sys.argv))