Brian Silverman | 6260c09 | 2018-01-14 15:21:36 -0800 | [diff] [blame] | 1 | #!/usr/bin/python |
| 2 | |
| 3 | from frc971.control_loops.python import control_loop |
| 4 | from frc971.control_loops.python import controls |
| 5 | import numpy |
| 6 | import sys |
| 7 | import copy |
| 8 | import scipy.interpolate |
| 9 | from matplotlib import pylab |
| 10 | |
| 11 | import gflags |
| 12 | import glog |
| 13 | |
| 14 | FLAGS = gflags.FLAGS |
| 15 | |
| 16 | gflags.DEFINE_bool('plot', False, 'If true, plot the loop response.') |
| 17 | gflags.DEFINE_string('data', None, 'If defined, plot the provided CAN data') |
| 18 | gflags.DEFINE_bool('rerun_kf', False, 'If true, rerun the KF. The torque in the data file will be interpreted as the commanded current.') |
| 19 | |
| 20 | class SystemParams(object): |
| 21 | def __init__(self, J, G, kP, kD, kCompensationTimeconstant, q_pos, q_vel, |
| 22 | q_torque, current_limit): |
| 23 | self.J = J |
| 24 | self.G = G |
| 25 | self.q_pos = q_pos |
| 26 | self.q_vel = q_vel |
| 27 | self.q_torque = q_torque |
| 28 | self.kP = kP |
| 29 | self.kD = kD |
| 30 | self.kCompensationTimeconstant = kCompensationTimeconstant |
| 31 | self.r_pos = 0.001 |
| 32 | self.current_limit = current_limit |
| 33 | |
| 34 | #[15.0, 0.25], |
| 35 | #[10.0, 0.2], |
| 36 | #[5.0, 0.13], |
| 37 | #[3.0, 0.10], |
| 38 | #[2.0, 0.08], |
| 39 | #[1.0, 0.06], |
| 40 | #[0.5, 0.05], |
| 41 | #[0.25, 0.025], |
| 42 | |
| 43 | kWheel = SystemParams(J=0.0008, |
| 44 | G=(1.25 + 0.02) / 0.35, |
| 45 | q_pos=0.001, |
| 46 | q_vel=0.20, |
| 47 | q_torque=0.005, |
| 48 | kP=7.0, |
| 49 | kD=0.0, |
| 50 | kCompensationTimeconstant=0.95, |
| 51 | current_limit=4.5) |
| 52 | kTrigger = SystemParams(J=0.00025, |
| 53 | G=(0.925 * 2.0 + 0.02) / 0.35, |
| 54 | q_pos=0.001, |
| 55 | q_vel=0.1, |
| 56 | q_torque=0.005, |
| 57 | kP=120.0, |
| 58 | kD=1.8, |
| 59 | kCompensationTimeconstant=0.95, |
| 60 | current_limit=3.0) |
| 61 | |
| 62 | class HapticInput(control_loop.ControlLoop): |
| 63 | def __init__(self, params=None, name='HapticInput'): |
| 64 | # The defaults are for the steering wheel. |
| 65 | super(HapticInput, self).__init__(name) |
| 66 | motor = self.motor = control_loop.MN3510() |
| 67 | |
| 68 | # Moment of inertia of the wheel in kg m^2 |
| 69 | self.J = params.J |
| 70 | |
| 71 | # Control loop time step |
| 72 | self.dt = 0.001 |
| 73 | |
| 74 | # Gear ratio from the motor to the input. |
| 75 | self.G = params.G |
| 76 | |
| 77 | self.A_continuous = numpy.matrix(numpy.zeros((2, 2))) |
| 78 | self.A_continuous[1, 1] = 0 |
| 79 | self.A_continuous[0, 1] = 1 |
| 80 | |
| 81 | self.B_continuous = numpy.matrix(numpy.zeros((2, 1))) |
| 82 | self.B_continuous[1, 0] = motor.Kt * self.G / self.J |
| 83 | |
| 84 | # State feedback matrices |
| 85 | # [position, angular velocity] |
| 86 | self.C = numpy.matrix([[1.0, 0.0]]) |
| 87 | self.D = numpy.matrix([[0.0]]) |
| 88 | |
| 89 | self.A, self.B = self.ContinuousToDiscrete( |
| 90 | self.A_continuous, self.B_continuous, self.dt) |
| 91 | |
| 92 | self.U_max = numpy.matrix([[2.5]]) |
| 93 | self.U_min = numpy.matrix([[-2.5]]) |
| 94 | |
| 95 | self.L = numpy.matrix([[0.0], [0.0]]) |
| 96 | self.K = numpy.matrix([[0.0, 0.0]]) |
| 97 | |
| 98 | self.InitializeState() |
| 99 | |
| 100 | |
| 101 | class IntegralHapticInput(HapticInput): |
| 102 | def __init__(self, params=None, name="IntegralHapticInput"): |
| 103 | super(IntegralHapticInput, self).__init__(name=name, params=params) |
| 104 | |
| 105 | self.A_continuous_unaugmented = self.A_continuous |
| 106 | self.B_continuous_unaugmented = self.B_continuous |
| 107 | |
| 108 | self.A_continuous = numpy.matrix(numpy.zeros((3, 3))) |
| 109 | self.A_continuous[0:2, 0:2] = self.A_continuous_unaugmented |
| 110 | self.A_continuous[1, 2] = (1 / self.J) |
| 111 | |
| 112 | self.B_continuous = numpy.matrix(numpy.zeros((3, 1))) |
| 113 | self.B_continuous[0:2, 0] = self.B_continuous_unaugmented |
| 114 | |
| 115 | self.C_unaugmented = self.C |
| 116 | self.C = numpy.matrix(numpy.zeros((1, 3))) |
| 117 | self.C[0:1, 0:2] = self.C_unaugmented |
| 118 | |
| 119 | self.A, self.B = self.ContinuousToDiscrete( |
| 120 | self.A_continuous, self.B_continuous, self.dt) |
| 121 | |
| 122 | self.Q = numpy.matrix([[(params.q_pos ** 2.0), 0.0, 0.0], |
| 123 | [0.0, (params.q_vel ** 2.0), 0.0], |
| 124 | [0.0, 0.0, (params.q_torque ** 2.0)]]) |
| 125 | |
| 126 | self.R = numpy.matrix([[(params.r_pos ** 2.0)]]) |
| 127 | |
| 128 | self.KalmanGain, self.Q_steady = controls.kalman( |
| 129 | A=self.A, B=self.B, C=self.C, Q=self.Q, R=self.R) |
| 130 | self.L = self.A * self.KalmanGain |
| 131 | |
| 132 | self.K_unaugmented = self.K |
| 133 | self.K = numpy.matrix(numpy.zeros((1, 3))) |
| 134 | self.K[0, 0:2] = self.K_unaugmented |
| 135 | self.K[0, 2] = 1.0 / (self.motor.Kt / (self.motor.resistance)) |
| 136 | |
| 137 | self.InitializeState() |
| 138 | |
| 139 | def ReadCan(filename): |
| 140 | """Reads the candump in filename and returns the 4 fields.""" |
| 141 | trigger = [] |
| 142 | trigger_velocity = [] |
| 143 | trigger_torque = [] |
| 144 | trigger_current = [] |
| 145 | wheel = [] |
| 146 | wheel_velocity = [] |
| 147 | wheel_torque = [] |
| 148 | wheel_current = [] |
| 149 | |
| 150 | trigger_request_time = [0.0] |
| 151 | trigger_request_current = [0.0] |
| 152 | wheel_request_time = [0.0] |
| 153 | wheel_request_current = [0.0] |
| 154 | |
| 155 | with open(filename, 'r') as fd: |
| 156 | for line in fd: |
| 157 | data = line.split() |
| 158 | can_id = int(data[1], 16) |
| 159 | if can_id == 0: |
| 160 | data = [int(d, 16) for d in data[3:]] |
| 161 | trigger.append(((data[0] + (data[1] << 8)) - 32768) / 32768.0) |
| 162 | trigger_velocity.append(((data[2] + (data[3] << 8)) - 32768) / 32768.0) |
| 163 | trigger_torque.append(((data[4] + (data[5] << 8)) - 32768) / 32768.0) |
| 164 | trigger_current.append(((data[6] + ((data[7] & 0x3f) << 8)) - 8192) / 8192.0) |
| 165 | elif can_id == 1: |
| 166 | data = [int(d, 16) for d in data[3:]] |
| 167 | wheel.append(((data[0] + (data[1] << 8)) - 32768) / 32768.0) |
| 168 | wheel_velocity.append(((data[2] + (data[3] << 8)) - 32768) / 32768.0) |
| 169 | wheel_torque.append(((data[4] + (data[5] << 8)) - 32768) / 32768.0) |
| 170 | wheel_current.append(((data[6] + ((data[7] & 0x3f) << 8)) - 8192) / 8192.0) |
| 171 | elif can_id == 2: |
| 172 | data = [int(d, 16) for d in data[3:]] |
| 173 | trigger_request_current.append(((data[4] + (data[5] << 8)) - 32768) / 32768.0) |
| 174 | trigger_request_time.append(len(trigger) * 0.001) |
| 175 | elif can_id == 3: |
| 176 | data = [int(d, 16) for d in data[3:]] |
| 177 | wheel_request_current.append(((data[4] + (data[5] << 8)) - 32768) / 32768.0) |
| 178 | wheel_request_time.append(len(wheel) * 0.001) |
| 179 | |
| 180 | trigger_data_time = numpy.arange(0, len(trigger)) * 0.001 |
| 181 | wheel_data_time = numpy.arange(0, len(wheel)) * 0.001 |
| 182 | |
| 183 | # Extend out the data in the interpolation table. |
| 184 | trigger_request_time.append(trigger_data_time[-1]) |
| 185 | trigger_request_current.append(trigger_request_current[-1]) |
| 186 | wheel_request_time.append(wheel_data_time[-1]) |
| 187 | wheel_request_current.append(wheel_request_current[-1]) |
| 188 | |
| 189 | return (trigger_data_time, wheel_data_time, trigger, wheel, trigger_velocity, |
| 190 | wheel_velocity, trigger_torque, wheel_torque, trigger_current, |
| 191 | wheel_current, trigger_request_time, trigger_request_current, |
| 192 | wheel_request_time, wheel_request_current) |
| 193 | |
| 194 | def rerun_and_plot_kf(data_time, data_radians, data_current, data_request_current, |
| 195 | params, run_correct=True): |
| 196 | kf_velocity = [] |
| 197 | dt_velocity = [] |
| 198 | kf_position = [] |
| 199 | adjusted_position = [] |
| 200 | last_angle = None |
| 201 | haptic_observer = IntegralHapticInput(params=params) |
| 202 | |
| 203 | # Parameter sweep J. |
| 204 | num_kf = 1 |
| 205 | min_J = max_J = params.J |
| 206 | |
| 207 | # J = 0.0022 |
| 208 | #num_kf = 15 |
| 209 | #min_J = min_J / 2.0 |
| 210 | #max_J = max_J * 2.0 |
| 211 | initial_velocity = (data_radians[1] - data_radians[0]) * 1000.0 |
| 212 | |
| 213 | def DupParamsWithJ(params, J): |
| 214 | p = copy.copy(params) |
| 215 | p.J = J |
| 216 | return p |
| 217 | haptic_observers = [IntegralHapticInput(params=DupParamsWithJ(params, j)) for j in |
| 218 | numpy.logspace(numpy.log10(min_J), |
| 219 | numpy.log10(max_J), num=num_kf)] |
| 220 | # Initialize all the KF's. |
| 221 | haptic_observer.X_hat[1, 0] = initial_velocity |
| 222 | haptic_observer.X_hat[0, 0] = data_radians[0] |
| 223 | for observer in haptic_observers: |
| 224 | observer.X_hat[1, 0] = initial_velocity |
| 225 | observer.X_hat[0, 0] = data_radians[0] |
| 226 | |
| 227 | last_request_current = data_request_current[0] |
| 228 | kf_torques = [[] for i in xrange(num_kf)] |
| 229 | for angle, current, request_current in zip(data_radians, data_current, |
| 230 | data_request_current): |
| 231 | # Predict and correct all the parameter swept observers. |
| 232 | for i, observer in enumerate(haptic_observers): |
| 233 | observer.Y = numpy.matrix([[angle]]) |
| 234 | if run_correct: |
| 235 | observer.CorrectObserver(numpy.matrix([[current]])) |
| 236 | kf_torques[i].append(-observer.X_hat[2, 0]) |
| 237 | observer.PredictObserver(numpy.matrix([[current]])) |
| 238 | observer.PredictObserver(numpy.matrix([[current]])) |
| 239 | |
| 240 | # Predict and correct the main observer. |
| 241 | haptic_observer.Y = numpy.matrix([[angle]]) |
| 242 | if run_correct: |
| 243 | haptic_observer.CorrectObserver(numpy.matrix([[current]])) |
| 244 | kf_position.append(haptic_observer.X_hat[0, 0]) |
| 245 | adjusted_position.append(kf_position[-1] - last_request_current / params.kP) |
| 246 | last_request_current = last_request_current * params.kCompensationTimeconstant + request_current * (1.0 - params.kCompensationTimeconstant) |
| 247 | kf_velocity.append(haptic_observer.X_hat[1, 0]) |
| 248 | if last_angle is None: |
| 249 | last_angle = angle |
| 250 | dt_velocity.append((angle - last_angle) / 0.001) |
| 251 | |
| 252 | haptic_observer.PredictObserver(numpy.matrix([[current]])) |
| 253 | last_angle = angle |
| 254 | |
| 255 | # Plot the wheel observers. |
| 256 | fig, ax1 = pylab.subplots() |
| 257 | ax1.plot(data_time, data_radians, '.', label='wheel') |
| 258 | ax1.plot(data_time, dt_velocity, '.', label='dt_velocity') |
| 259 | ax1.plot(data_time, kf_velocity, '.', label='kf_velocity') |
| 260 | ax1.plot(data_time, kf_position, '.', label='kf_position') |
| 261 | ax1.plot(data_time, adjusted_position, '.', label='adjusted_position') |
| 262 | |
| 263 | ax2 = ax1.twinx() |
| 264 | ax2.plot(data_time, data_current, label='data_current') |
| 265 | ax2.plot(data_time, data_request_current, label='request_current') |
| 266 | |
| 267 | for i, kf_torque in enumerate(kf_torques): |
| 268 | ax2.plot(data_time, kf_torque, |
| 269 | label='-kf_torque[%f]' % haptic_observers[i].J) |
| 270 | fig.tight_layout() |
| 271 | ax1.legend(loc=3) |
| 272 | ax2.legend(loc=4) |
| 273 | |
| 274 | def plot_input(data_time, data_radians, data_velocity, data_torque, |
| 275 | data_current, params, run_correct=True): |
| 276 | dt_velocity = [] |
| 277 | last_angle = None |
| 278 | initial_velocity = (data_radians[1] - data_radians[0]) * 1000.0 |
| 279 | |
| 280 | for angle in data_radians: |
| 281 | if last_angle is None: |
| 282 | last_angle = angle |
| 283 | dt_velocity.append((angle - last_angle) / 0.001) |
| 284 | |
| 285 | last_angle = angle |
| 286 | |
| 287 | # Plot the wheel observers. |
| 288 | fig, ax1 = pylab.subplots() |
| 289 | ax1.plot(data_time, data_radians, '.', label='angle') |
| 290 | ax1.plot(data_time, data_velocity, '-', label='velocity') |
| 291 | ax1.plot(data_time, dt_velocity, '.', label='dt_velocity') |
| 292 | |
| 293 | ax2 = ax1.twinx() |
| 294 | ax2.plot(data_time, data_torque, label='data_torque') |
| 295 | ax2.plot(data_time, data_current, label='data_current') |
| 296 | fig.tight_layout() |
| 297 | ax1.legend(loc=3) |
| 298 | ax2.legend(loc=4) |
| 299 | |
| 300 | def main(argv): |
| 301 | if FLAGS.plot: |
| 302 | if FLAGS.data is None: |
| 303 | haptic_wheel = HapticInput() |
| 304 | haptic_wheel_controller = IntegralHapticInput() |
| 305 | observer_haptic_wheel = IntegralHapticInput() |
| 306 | observer_haptic_wheel.X_hat[2, 0] = 0.01 |
| 307 | |
| 308 | R = numpy.matrix([[0.0], [0.0], [0.0]]) |
| 309 | |
| 310 | control_loop.TestSingleIntegralAxisSquareWave( |
| 311 | R, 1.0, haptic_wheel, haptic_wheel_controller, observer_haptic_wheel) |
| 312 | else: |
| 313 | # Read the CAN trace in. |
| 314 | trigger_data_time, wheel_data_time, trigger, wheel, trigger_velocity, \ |
| 315 | wheel_velocity, trigger_torque, wheel_torque, trigger_current, \ |
| 316 | wheel_current, trigger_request_time, trigger_request_current, \ |
| 317 | wheel_request_time, wheel_request_current = ReadCan(FLAGS.data) |
| 318 | |
| 319 | wheel_radians = [w * numpy.pi * (338.16 / 360.0) for w in wheel] |
| 320 | wheel_velocity = [w * 50.0 for w in wheel_velocity] |
| 321 | wheel_torque = [w / 2.0 for w in wheel_torque] |
| 322 | wheel_current = [w * 10.0 for w in wheel_current] |
| 323 | wheel_request_current = [w * 2.0 for w in wheel_request_current] |
| 324 | resampled_wheel_request_current = scipy.interpolate.interp1d( |
| 325 | wheel_request_time, wheel_request_current, kind="zero")(wheel_data_time) |
| 326 | |
| 327 | trigger_radians = [t * numpy.pi * (45.0 / 360.0) for t in trigger] |
| 328 | trigger_velocity = [t * 50.0 for t in trigger_velocity] |
| 329 | trigger_torque = [t / 2.0 for t in trigger_torque] |
| 330 | trigger_current = [t * 10.0 for t in trigger_current] |
| 331 | trigger_request_current = [t * 2.0 for t in trigger_request_current] |
| 332 | resampled_trigger_request_current = scipy.interpolate.interp1d( |
| 333 | trigger_request_time, trigger_request_current, kind="zero")(trigger_data_time) |
| 334 | |
| 335 | if FLAGS.rerun_kf: |
| 336 | rerun_and_plot_kf(trigger_data_time, trigger_radians, trigger_current, |
| 337 | resampled_trigger_request_current, kTrigger, run_correct=True) |
| 338 | rerun_and_plot_kf(wheel_data_time, wheel_radians, wheel_current, |
| 339 | resampled_wheel_request_current, kWheel, run_correct=True) |
| 340 | else: |
| 341 | plot_input(trigger_data_time, trigger_radians, trigger_velocity, |
| 342 | trigger_torque, trigger_current, kTrigger) |
| 343 | plot_input(wheel_data_time, wheel_radians, wheel_velocity, wheel_torque, |
| 344 | wheel_current, kWheel) |
| 345 | pylab.show() |
| 346 | |
| 347 | return |
| 348 | |
| 349 | if len(argv) != 9: |
| 350 | glog.fatal('Expected .h file name and .cc file name') |
| 351 | else: |
| 352 | namespaces = ['frc971', 'control_loops', 'drivetrain'] |
| 353 | for name, params, filenames in [('HapticWheel', kWheel, argv[1:5]), |
| 354 | ('HapticTrigger', kTrigger, argv[5:9])]: |
| 355 | haptic_input = HapticInput(params=params, name=name) |
| 356 | loop_writer = control_loop.ControlLoopWriter(name, [haptic_input], |
| 357 | namespaces=namespaces, |
| 358 | scalar_type='float') |
| 359 | loop_writer.Write(filenames[0], filenames[1]) |
| 360 | |
| 361 | integral_haptic_input = IntegralHapticInput(params=params, |
| 362 | name='Integral' + name) |
| 363 | integral_loop_writer = control_loop.ControlLoopWriter( |
| 364 | 'Integral' + name, [integral_haptic_input], namespaces=namespaces, |
| 365 | scalar_type='float') |
| 366 | |
| 367 | integral_loop_writer.AddConstant( |
| 368 | control_loop.Constant("k" + name + "Dt", "%f", |
| 369 | integral_haptic_input.dt)) |
| 370 | integral_loop_writer.AddConstant( |
| 371 | control_loop.Constant("k" + name + "FreeCurrent", "%f", |
| 372 | integral_haptic_input.motor.free_current)) |
| 373 | integral_loop_writer.AddConstant( |
| 374 | control_loop.Constant("k" + name + "StallTorque", "%f", |
| 375 | integral_haptic_input.motor.stall_torque)) |
| 376 | integral_loop_writer.AddConstant( |
| 377 | control_loop.Constant("k" + name + "J", "%f", |
| 378 | integral_haptic_input.J)) |
| 379 | integral_loop_writer.AddConstant( |
| 380 | control_loop.Constant("k" + name + "R", "%f", |
| 381 | integral_haptic_input.motor.resistance)) |
| 382 | integral_loop_writer.AddConstant( |
| 383 | control_loop.Constant("k" + name + "T", "%f", |
| 384 | integral_haptic_input.motor.Kt)) |
| 385 | integral_loop_writer.AddConstant( |
| 386 | control_loop.Constant("k" + name + "V", "%f", |
| 387 | integral_haptic_input.motor.Kv)) |
| 388 | integral_loop_writer.AddConstant( |
| 389 | control_loop.Constant("k" + name + "P", "%f", |
| 390 | params.kP)) |
| 391 | integral_loop_writer.AddConstant( |
| 392 | control_loop.Constant("k" + name + "D", "%f", |
| 393 | params.kD)) |
| 394 | integral_loop_writer.AddConstant( |
| 395 | control_loop.Constant("k" + name + "G", "%f", |
| 396 | params.G)) |
| 397 | integral_loop_writer.AddConstant( |
| 398 | control_loop.Constant("k" + name + "CurrentLimit", "%f", |
| 399 | params.current_limit)) |
| 400 | |
| 401 | integral_loop_writer.Write(filenames[2], filenames[3]) |
| 402 | |
| 403 | |
| 404 | if __name__ == '__main__': |
| 405 | argv = FLAGS(sys.argv) |
| 406 | sys.exit(main(argv)) |