blob: d99160d5bb00884dfb92e44a3028adefe56dc9fa [file] [log] [blame]
Comran Morshed2ae094e2016-01-23 20:43:20 +00001#!/usr/bin/python
2
Philipp Schrader1a25ee42016-02-11 07:02:03 +00003from aos.common.util.trapezoid_profile import TrapezoidProfile
Comran Morshed2ae094e2016-01-23 20:43:20 +00004from frc971.control_loops.python import control_loop
5from frc971.control_loops.python import controls
Comran Morshed2ae094e2016-01-23 20:43:20 +00006import 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):
Austin Schuh07cb5852016-01-31 00:58:46 -080021 def __init__(self, name="Intake"):
Comran Morshed2ae094e2016-01-23 20:43:20 +000022 super(Intake, self).__init__(name)
23 # TODO(constants): Update all of these & retune poles.
24 # Stall Torque in N m
Austin Schuh07cb5852016-01-31 00:58:46 -080025 self.stall_torque = 0.71
Comran Morshed2ae094e2016-01-23 20:43:20 +000026 # Stall Current in Amps
Austin Schuh07cb5852016-01-31 00:58:46 -080027 self.stall_current = 134
Comran Morshed2ae094e2016-01-23 20:43:20 +000028 # Free Speed in RPM
Austin Schuh07cb5852016-01-31 00:58:46 -080029 self.free_speed = 18730
Comran Morshed2ae094e2016-01-23 20:43:20 +000030 # Free Current in Amps
Austin Schuh07cb5852016-01-31 00:58:46 -080031 self.free_current = 0.7
Comran Morshed2ae094e2016-01-23 20:43:20 +000032
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
Austin Schuh07cb5852016-01-31 00:58:46 -080041 self.G = (56.0 / 12.0) * (54.0 / 14.0) * (64.0 / 18.0) * (48.0 / 16.0)
Comran Morshed2ae094e2016-01-23 20:43:20 +000042
Comran Morshedb6a22362016-03-05 14:14:32 +000043 # Moment of inertia, measured in CAD.
44 # Extra mass to compensate for friction is added on.
Diana Vandenberg9cc9ab62016-04-20 21:27:47 -070045 self.J = 0.34 + 0.40
Comran Morshed2ae094e2016-01-23 20:43:20 +000046
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
Austin Schuha88c4072016-02-06 14:31:03 -080073 glog.debug("Free speed is %f", self.free_speed * numpy.pi * 2.0 / 60.0 / self.G)
Comran Morshed2ae094e2016-01-23 20:43:20 +000074
Austin Schuh07cb5852016-01-31 00:58:46 -080075 q_pos = 0.20
Diana Vandenberg9cc9ab62016-04-20 21:27:47 -070076 q_vel = 5.0
Comran Morshed2ae094e2016-01-23 20:43:20 +000077 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
Austin Schuh2fc10fa2016-02-08 00:44:34 -080083 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
Austin Schuha88c4072016-02-06 14:31:03 -080090 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]))
Comran Morshed2ae094e2016-01-23 20:43:20 +000093
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
Austin Schuha88c4072016-02-06 14:31:03 -080099 glog.debug('L is %s', repr(self.L))
Comran Morshed2ae094e2016-01-23 20:43:20 +0000100
Austin Schuh1aa5ee92016-02-28 21:57:45 -0800101 q_pos = 0.10
102 q_vel = 1.65
Comran Morshed2ae094e2016-01-23 20:43:20 +0000103 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
Austin Schuha88c4072016-02-06 14:31:03 -0800112 glog.debug('Kal %s', repr(self.KalmanGain))
Comran Morshed2ae094e2016-01-23 20:43:20 +0000113 self.L = self.A * self.KalmanGain
Austin Schuha88c4072016-02-06 14:31:03 -0800114 glog.debug('KalL is %s', repr(self.L))
Comran Morshed2ae094e2016-01-23 20:43:20 +0000115
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):
Austin Schuh07cb5852016-01-31 00:58:46 -0800124 def __init__(self, name="IntegralIntake"):
125 super(IntegralIntake, self).__init__(name=name)
Comran Morshed2ae094e2016-01-23 20:43:20 +0000126
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
Austin Schuhf59b6bc2016-03-11 21:26:19 -0800141 self.A, self.B = self.ContinuousToDiscrete(
142 self.A_continuous, self.B_continuous, self.dt)
Comran Morshed2ae094e2016-01-23 20:43:20 +0000143
Austin Schuh1aa5ee92016-02-28 21:57:45 -0800144 q_pos = 0.12
145 q_vel = 2.00
Austin Schuhf59b6bc2016-03-11 21:26:19 -0800146 q_voltage = 4.0
Comran Morshed2ae094e2016-01-23 20:43:20 +0000147 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
Austin Schuh2fc10fa2016-02-08 00:44:34 -0800163 self.Kff = numpy.concatenate((self.Kff, numpy.matrix(numpy.zeros((1, 1)))), axis=1)
164
Comran Morshed2ae094e2016-01-23 20:43:20 +0000165 self.InitializeState()
Austin Schuh07cb5852016-01-31 00:58:46 -0800166
Comran Morshed2ae094e2016-01-23 20:43:20 +0000167class 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 = []
Austin Schuh07cb5852016-01-31 00:58:46 -0800176 self.offset = []
Comran Morshed2ae094e2016-01-23 20:43:20 +0000177
Austin Schuh2fc10fa2016-02-08 00:44:34 -0800178 def run_test(self, intake, end_goal,
179 controller_intake,
180 observer_intake=None,
181 iterations=200):
Comran Morshed2ae094e2016-01-23 20:43:20 +0000182 """Runs the intake plant with an initial condition and goal.
183
Comran Morshed2ae094e2016-01-23 20:43:20 +0000184 Args:
185 intake: intake object to use.
Austin Schuh2fc10fa2016-02-08 00:44:34 -0800186 end_goal: end_goal state.
Comran Morshed2ae094e2016-01-23 20:43:20 +0000187 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.
Austin Schuh2fc10fa2016-02-08 00:44:34 -0800191 iterations: Number of timesteps to run the model for.
Comran Morshed2ae094e2016-01-23 20:43:20 +0000192 """
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
Austin Schuh2fc10fa2016-02-08 00:44:34 -0800204 goal = numpy.concatenate((intake.X, numpy.matrix(numpy.zeros((1, 1)))), axis=0)
205
Philipp Schrader1a25ee42016-02-11 07:02:03 +0000206 profile = TrapezoidProfile(intake.dt)
Austin Schuh2fc10fa2016-02-08 00:44:34 -0800207 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)))
Comran Morshed2ae094e2016-01-23 20:43:20 +0000212 for i in xrange(iterations):
Austin Schuh2fc10fa2016-02-08 00:44:34 -0800213 observer_intake.Y = intake.Y
214 observer_intake.CorrectObserver(U_last)
Comran Morshed2ae094e2016-01-23 20:43:20 +0000215
Austin Schuh2fc10fa2016-02-08 00:44:34 -0800216 self.offset.append(observer_intake.X_hat[2, 0])
217 self.x_hat.append(observer_intake.X_hat[0, 0])
Comran Morshed2ae094e2016-01-23 20:43:20 +0000218
Austin Schuh2fc10fa2016-02-08 00:44:34 -0800219 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()
Comran Morshed2ae094e2016-01-23 20:43:20 +0000228 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
Austin Schuhf59b6bc2016-03-11 21:26:19 -0800239 offset = 0.0
240 if i > 100:
241 offset = 2.0
242 intake.Update(U + offset)
Comran Morshed2ae094e2016-01-23 20:43:20 +0000243
Austin Schuh2fc10fa2016-02-08 00:44:34 -0800244 observer_intake.PredictObserver(U)
Comran Morshed2ae094e2016-01-23 20:43:20 +0000245
246 self.t.append(initial_t + i * intake.dt)
247 self.u.append(U[0, 0])
248
Austin Schuh2fc10fa2016-02-08 00:44:34 -0800249 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))
Comran Morshed2ae094e2016-01-23 20:43:20 +0000259
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')
Austin Schuh07cb5852016-01-31 00:58:46 -0800268 pylab.plot(self.t, self.offset, label='voltage_offset')
269 pylab.legend()
Comran Morshed2ae094e2016-01-23 20:43:20 +0000270
271 pylab.subplot(3, 1, 3)
272 pylab.plot(self.t, self.a, label='a')
Comran Morshed2ae094e2016-01-23 20:43:20 +0000273 pylab.legend()
Austin Schuh07cb5852016-01-31 00:58:46 -0800274
Comran Morshed2ae094e2016-01-23 20:43:20 +0000275 pylab.show()
276
277
278def main(argv):
279 argv = FLAGS(argv)
Austin Schuha88c4072016-02-06 14:31:03 -0800280 glog.init()
Comran Morshed2ae094e2016-01-23 20:43:20 +0000281
Comran Morshed2ae094e2016-01-23 20:43:20 +0000282 scenario_plotter = ScenarioPlotter()
283
Austin Schuh07cb5852016-01-31 00:58:46 -0800284 intake = Intake()
285 intake_controller = IntegralIntake()
286 observer_intake = IntegralIntake()
Comran Morshed2ae094e2016-01-23 20:43:20 +0000287
288 # Test moving the intake with constant separation.
289 initial_X = numpy.matrix([[0.0], [0.0]])
Austin Schuh07cb5852016-01-31 00:58:46 -0800290 R = numpy.matrix([[numpy.pi/2.0], [0.0], [0.0]])
Austin Schuh2fc10fa2016-02-08 00:44:34 -0800291 scenario_plotter.run_test(intake, end_goal=R,
292 controller_intake=intake_controller,
Comran Morshed2ae094e2016-01-23 20:43:20 +0000293 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', 'control_loops', 'superstructure']
303 intake = Intake("Intake")
304 loop_writer = control_loop.ControlLoopWriter('Intake', [intake],
305 namespaces=namespaces)
306 loop_writer.Write(argv[1], argv[2])
307
Austin Schuh07cb5852016-01-31 00:58:46 -0800308 integral_intake = IntegralIntake("IntegralIntake")
Comran Morshed2ae094e2016-01-23 20:43:20 +0000309 integral_loop_writer = control_loop.ControlLoopWriter("IntegralIntake", [integral_intake],
Austin Schuh07cb5852016-01-31 00:58:46 -0800310 namespaces=namespaces)
Comran Morshed2ae094e2016-01-23 20:43:20 +0000311 integral_loop_writer.Write(argv[3], argv[4])
312
313if __name__ == '__main__':
314 sys.exit(main(sys.argv))