blob: 2e88faeab657a223ec23320d66a2d9a8ed6cdedc [file] [log] [blame]
Austin Schuh075a5072017-10-21 18:05:25 -07001#!/usr/bin/python3
2
3import numpy
4from matplotlib import pylab
5import scipy.integrate
6from frc971.control_loops.python import controls
7import time
8import operator
9
10K1 = 1.81e04
11K2 = -2.65e03
12
13# Make the amplitude of the fundamental 1 for ease of playing with.
14K2 /= K1
15K1 = 1
16
17vcc = 30.0 # volts
18R_motor = 0.0055 # ohms for the motor
19R = 0.008 # ohms for system
20
21L = 10.0 * 1e-6 # Henries
22M = L / 10.0
23
24Kv = 22000.0 * 2.0 * numpy.pi / 60.0 / vcc * 2.0
25J = 0.0000007
26
27R_shunt = 0.0003
28
29# RC circuit for current sense filtering.
30R_sense1 = 768.0
31R_sense2 = 1470.0
32C_sense = 10.0 * 1e-9
33
34# So, we measured the inductance by switching between ~5 and ~20 amps through
35# the motor.
36# We then looked at the change in voltage that should give us (assuming duty
37# cycle * vin), and divided it by the corresponding change in current.
38
39# We then looked at the amount of time it took to decay the current to 1/e
40# That gave us the inductance.
41
42# Overrides for experiments
43J = J * 10.0
44
45# Firing phase A -> 0.0
46# Firing phase B -> - numpy.pi * 2.0 / 3.0
47# Firing phase C -> + numpy.pi * 2.0 / 3.0
48
49hz = 20000.0
50
51#switching_pattern = 'front'
52switching_pattern = 'centered'
53#switching_pattern = 'rear'
54#switching_pattern = 'centered front shifted'
55#switching_pattern = 'anticentered'
56
57Vconv = numpy.matrix([[2.0, -1.0, -1.0],
58 [-1.0, 2.0, -1.0],
59 [-1.0, -1.0, 2.0]]) / 3.0
60
61def f_single(theta):
62 return K1 * numpy.sin(theta) + K2 * numpy.sin(theta * 5)
63
64def g_single(theta):
65 return K1 * numpy.sin(theta) - K2 * numpy.sin(theta * 5)
66
67def gdot_single(theta):
68 """Derivitive of the current.
69
70 Must be multiplied by omega externally.
71 """
72 return K1 * numpy.cos(theta) - 5.0 * K2 * numpy.cos(theta * 5.0)
73
74f = numpy.vectorize(f_single, otypes=(numpy.float,))
75g = numpy.vectorize(g_single, otypes=(numpy.float,))
76gdot = numpy.vectorize(gdot_single, otypes=(numpy.float,))
77
78def torque(theta):
79 return f(theta) * g(theta)
80
81def phase_a(function, theta):
82 return function(theta)
83
84def phase_b(function, theta):
85 return function(theta + 2 * numpy.pi / 3)
86
87def phase_c(function, theta):
88 return function(theta + 4 * numpy.pi / 3)
89
90def phases(function, theta):
91 return numpy.matrix([[phase_a(function, theta)],
92 [phase_b(function, theta)],
93 [phase_c(function, theta)]])
94
95def all_phases(function, theta_range):
96 return (phase_a(function, theta_range) +
97 phase_b(function, theta_range) +
98 phase_c(function, theta_range))
99
100theta_range = numpy.linspace(start=0, stop=4 * numpy.pi, num=10000)
101one_amp_driving_voltage = R * g(theta_range) + (L * gdot(theta_range) + M * gdot(theta_range + 2.0 / 3.0 * numpy.pi) + M * gdot(theta_range - 2.0 / 3.0 * numpy.pi)) * Kv * vcc / 2.0
102
103max_one_amp_driving_voltage = max(one_amp_driving_voltage)
104
105# The number to divide the product of the unit BEMF and the per phase current
106# by to get motor current.
107one_amp_scalar = (phases(f_single, 0.0).T * phases(g_single, 0.0))[0, 0]
108
109print 'Max BEMF', max(f(theta_range))
110print 'Max current', max(g(theta_range))
111print 'Max drive voltage (one_amp_driving_voltage)', max(one_amp_driving_voltage)
112print 'one_amp_scalar', one_amp_scalar
113
114pylab.figure()
115pylab.subplot(1, 1, 1)
116pylab.plot(theta_range, f(theta_range), label='bemf')
117pylab.plot(theta_range, g(theta_range), label='phase_current')
118pylab.plot(theta_range, torque(theta_range), label='phase_torque')
119pylab.plot(theta_range, all_phases(torque, theta_range), label='sum_torque/current')
120pylab.legend()
121
122
123def full_sample_times(Ton, Toff, dt, n, start_time):
124 """Returns n + 4 samples for the provided switching times.
125
126 We need the timesteps and Us to integrate.
127
128 Returns:
129 array of [t, U matrix]
130 """
131
132 assert((Toff <= 1.0).all())
133
134 if (Ton <= Toff).all():
135 # Verify that they are all ordered correctly.
136 on_before_off = True
137 else:
138 on_before_off = False
139
140 Toff = Toff.copy() * dt
141 Toff[Toff < 100e-9] = -1.0
142 Toff[Toff > dt] = dt
143
144 Ton = Ton.copy() * dt
145 Ton[Ton < 100e-9] = -1.0
146 Ton[Ton > dt - 100e-9] = dt + 1.0
147
148 result = []
149 t = 0
150
151 result_times = numpy.concatenate(
152 (numpy.linspace(0, dt, num=n),
153 numpy.reshape(numpy.asarray(Ton[numpy.logical_and(Ton < dt, Ton > 0.0)]), (-1,)),
154 numpy.reshape(numpy.asarray(Toff[numpy.logical_and(Toff < dt, Toff > 0.0)]), (-1,))
155 ))
156 result_times.sort()
157
158 for t in numpy.nditer(result_times):
159 if on_before_off:
160 U = numpy.matrix([[vcc], [vcc], [vcc]])
161 U[t <= Ton] = 0.0
162 U[Toff < t] = 0.0
163 else:
164 U = numpy.matrix([[0.0], [0.0], [0.0]])
165 U[t > Ton] = vcc
166 U[t <= Toff] = vcc
167 result.append((float(t + start_time), U.copy()))
168
169 return result
170
171def sample_times(T, dt, n, start_time):
172 if switching_pattern == 'rear':
173 T = 1.0 - T
174 ans = full_sample_times(T, numpy.matrix(numpy.ones((3, 1))) * 1.0, dt, n, start_time)
175 elif switching_pattern == 'centered front shifted':
176 # Centered, but shifted to the beginning of the cycle.
177 Ton = 0.5 - T / 2.0
178 Toff = 0.5 + T / 2.0
179
180 tn = min(Ton)[0, 0]
181 Ton -= tn
182 Toff -= tn
183
184 ans = full_sample_times(Ton, Toff, dt, n, start_time)
185 elif switching_pattern == 'centered':
186 # Centered, looks waaay better.
187 Ton = 0.5 - T / 2.0
188 Toff = 0.5 + T / 2.0
189
190 ans = full_sample_times(Ton, Toff, dt, n, start_time)
191 elif switching_pattern == 'anticentered':
192 # Centered, looks waaay better.
193 Toff = T / 2.0
194 Ton = 1.0 - T / 2.0
195
196 ans = full_sample_times(Ton, Toff, dt, n, start_time)
197 elif switching_pattern == 'front':
198 ans = full_sample_times(numpy.matrix(numpy.zeros((3, 1))), T, dt, n, start_time)
199 else:
200 assert(False)
201
202 return ans
203
204class DataLogger(object):
205 def __init__(self, title=None):
206 self.title = title
207 self.ia = []
208 self.ib = []
209 self.ic = []
210 self.ia_goal = []
211 self.ib_goal = []
212 self.ic_goal = []
213 self.ia_controls = []
214 self.ib_controls = []
215 self.ic_controls = []
216 self.isensea = []
217 self.isenseb = []
218 self.isensec = []
219
220 self.va = []
221 self.vb = []
222 self.vc = []
223 self.van = []
224 self.vbn = []
225 self.vcn = []
226
227 self.ea = []
228 self.eb = []
229 self.ec = []
230
231 self.theta = []
232 self.omega = []
233
234 self.i_goal = []
235
236 self.time = []
237 self.controls_time = []
238 self.predicted_time = []
239
240 self.ia_pred = []
241 self.ib_pred = []
242 self.ic_pred = []
243
244 self.voltage_time = []
245 self.estimated_velocity = []
246 self.U_last = numpy.matrix(numpy.zeros((3, 1)))
247
248 def log_predicted(self, current_time, p):
249 self.predicted_time.append(current_time)
250 self.ia_pred.append(p[0, 0])
251 self.ib_pred.append(p[1, 0])
252 self.ic_pred.append(p[2, 0])
253
254 def log_controls(self, current_time, measured_current, In, E, estimated_velocity):
255 self.controls_time.append(current_time)
256 self.ia_controls.append(measured_current[0, 0])
257 self.ib_controls.append(measured_current[1, 0])
258 self.ic_controls.append(measured_current[2, 0])
259
260 self.ea.append(E[0, 0])
261 self.eb.append(E[1, 0])
262 self.ec.append(E[2, 0])
263
264 self.ia_goal.append(In[0, 0])
265 self.ib_goal.append(In[1, 0])
266 self.ic_goal.append(In[2, 0])
267 self.estimated_velocity.append(estimated_velocity)
268
269 def log_data(self, X, U, current_time, Vn, i_goal):
270 self.ia.append(X[0, 0])
271 self.ib.append(X[1, 0])
272 self.ic.append(X[2, 0])
273
274 self.i_goal.append(i_goal)
275
276 self.isensea.append(X[5, 0])
277 self.isenseb.append(X[6, 0])
278 self.isensec.append(X[7, 0])
279
280 self.theta.append(X[3, 0])
281 self.omega.append(X[4, 0])
282
283 self.time.append(current_time)
284
285 self.van.append(Vn[0, 0])
286 self.vbn.append(Vn[1, 0])
287 self.vcn.append(Vn[2, 0])
288
289 if (self.U_last != U).any():
290 self.va.append(self.U_last[0, 0])
291 self.vb.append(self.U_last[1, 0])
292 self.vc.append(self.U_last[2, 0])
293 self.voltage_time.append(current_time)
294
295 self.va.append(U[0, 0])
296 self.vb.append(U[1, 0])
297 self.vc.append(U[2, 0])
298 self.voltage_time.append(current_time)
299 self.U_last = U.copy()
300
301 def plot(self):
302 fig = pylab.figure()
303 pylab.subplot(3, 1, 1)
304 pylab.plot(self.controls_time, self.ia_controls, 'ro', label='ia_controls')
305 pylab.plot(self.controls_time, self.ib_controls, 'go', label='ib_controls')
306 pylab.plot(self.controls_time, self.ic_controls, 'bo', label='ic_controls')
307 pylab.plot(self.controls_time, self.ia_goal, 'r--', label='ia_goal')
308 pylab.plot(self.controls_time, self.ib_goal, 'g--', label='ib_goal')
309 pylab.plot(self.controls_time, self.ic_goal, 'b--', label='ic_goal')
310
311 #pylab.plot(self.controls_time, self.ia_pred, 'r*', label='ia_pred')
312 #pylab.plot(self.controls_time, self.ib_pred, 'g*', label='ib_pred')
313 #pylab.plot(self.controls_time, self.ic_pred, 'b*', label='ic_pred')
314 pylab.plot(self.time, self.isensea, 'r:', label='ia_sense')
315 pylab.plot(self.time, self.isenseb, 'g:', label='ib_sense')
316 pylab.plot(self.time, self.isensec, 'b:', label='ic_sense')
317 pylab.plot(self.time, self.ia, 'r', label='ia')
318 pylab.plot(self.time, self.ib, 'g', label='ib')
319 pylab.plot(self.time, self.ic, 'b', label='ic')
320 pylab.plot(self.time, self.i_goal, label='i_goal')
321 if self.title is not None:
322 fig.canvas.set_window_title(self.title)
323 pylab.legend()
324
325 pylab.subplot(3, 1, 2)
326 pylab.plot(self.voltage_time, self.va, label='va')
327 pylab.plot(self.voltage_time, self.vb, label='vb')
328 pylab.plot(self.voltage_time, self.vc, label='vc')
329 pylab.plot(self.time, self.van, label='van')
330 pylab.plot(self.time, self.vbn, label='vbn')
331 pylab.plot(self.time, self.vcn, label='vcn')
332 pylab.plot(self.controls_time, self.ea, label='ea')
333 pylab.plot(self.controls_time, self.eb, label='eb')
334 pylab.plot(self.controls_time, self.ec, label='ec')
335 pylab.legend()
336
337 pylab.subplot(3, 1, 3)
338 pylab.plot(self.time, self.theta, label='theta')
339 pylab.plot(self.time, self.omega, label='omega')
340 pylab.plot(self.controls_time, self.estimated_velocity, label='estimated omega')
341
342 pylab.legend()
343
344 fig = pylab.figure()
345 pylab.plot(self.controls_time,
346 map(operator.sub, self.ia_goal, self.ia_controls), 'r', label='ia_error')
347 pylab.plot(self.controls_time,
348 map(operator.sub, self.ib_goal, self.ib_controls), 'g', label='ib_error')
349 pylab.plot(self.controls_time,
350 map(operator.sub, self.ic_goal, self.ic_controls), 'b', label='ic_error')
351 if self.title is not None:
352 fig.canvas.set_window_title(self.title)
353 pylab.legend()
354 pylab.show()
355
356
357# So, from running a bunch of math, we know the following:
358# Van + Vbn + Vcn = 0
359# ia + ib + ic = 0
360# ea + eb + ec = 0
361# d ia/dt + d ib/dt + d ic/dt = 0
362#
363# We also have:
364# [ Van ] [ 2/3 -1/3 -1/3] [Va]
365# [ Vbn ] = [ -1/3 2/3 -1/3] [Vb]
366# [ Vcn ] [ -1/3 -1/3 2/3] [Vc]
367#
368# or,
369#
370# Vabcn = Vconv * V
371#
372# The base equation is:
373#
374# [ Van ] [ R 0 0 ] [ ia ] [ L M M ] [ dia/dt ] [ ea ]
375# [ Vbn ] = [ 0 R 0 ] [ ib ] + [ M L M ] [ dib/dt ] + [ eb ]
376# [ Vbn ] [ 0 0 R ] [ ic ] [ M M L ] [ dic/dt ] [ ec ]
377#
378# or
379#
380# Vabcn = R_matrix * I + L_matrix * I_dot + E
381#
382# We can re-arrange this as:
383#
384# inv(L_matrix) * (Vconv * V - E - R_matrix * I) = I_dot
385# B * V - inv(L_matrix) * E - A * I = I_dot
386class Simulation(object):
387 def __init__(self):
388 self.R_matrix = numpy.matrix(numpy.eye(3)) * R
389 self.L_matrix = numpy.matrix([[L, M, M], [M, L, M], [M, M, L]])
390 self.L_matrix_inv = numpy.linalg.inv(self.L_matrix)
391 self.A = self.L_matrix_inv * self.R_matrix
392 self.B = self.L_matrix_inv * Vconv
393 self.A_discrete, self.B_discrete = controls.c2d(-self.A, self.B, 1.0 / hz)
394 self.B_discrete_inverse = numpy.matrix(numpy.eye(3)) / (self.B_discrete[0, 0] - self.B_discrete[1, 0])
395
396 self.R_model = R * 1.0
397 self.L_model = L * 1.0
398 self.M_model = M * 1.0
399 self.R_matrix_model = numpy.matrix(numpy.eye(3)) * self.R_model
400 self.L_matrix_model = numpy.matrix([[self.L_model, self.M_model, self.M_model],
401 [self.M_model, self.L_model, self.M_model],
402 [self.M_model, self.M_model, self.L_model]])
403 self.L_matrix_inv_model = numpy.linalg.inv(self.L_matrix_model)
404 self.A_model = self.L_matrix_inv_model * self.R_matrix_model
405 self.B_model = self.L_matrix_inv_model * Vconv
406 self.A_discrete_model, self.B_discrete_model = \
407 controls.c2d(-self.A_model, self.B_model, 1.0 / hz)
408 self.B_discrete_inverse_model = numpy.matrix(numpy.eye(3)) / (self.B_discrete_model[0, 0] - self.B_discrete_model[1, 0])
409
410 print 'constexpr double kL = %g;' % self.L_model
411 print 'constexpr double kM = %g;' % self.M_model
412 print 'constexpr double kR = %g;' % self.R_model
413 print 'constexpr float kAdiscrete_diagonal = %gf;' % self.A_discrete_model[0, 0]
414 print 'constexpr float kAdiscrete_offdiagonal = %gf;' % self.A_discrete_model[1, 0]
415 print 'constexpr float kBdiscrete_inv_diagonal = %gf;' % self.B_discrete_inverse_model[0, 0]
416 print 'constexpr float kBdiscrete_inv_offdiagonal = %gf;' % self.B_discrete_inverse_model[1, 0]
417 print 'constexpr double kOneAmpScalar = %g;' % one_amp_scalar
418 print 'constexpr double kMaxOneAmpDrivingVoltage = %g;' % max_one_amp_driving_voltage
419 print('A_discrete', self.A_discrete)
420 print('B_discrete', self.B_discrete)
421 print('B_discrete_sub', numpy.linalg.inv(self.B_discrete[0:2, 0:2]))
422 print('B_discrete_inv', self.B_discrete_inverse)
423
424 # Xdot[5:, :] = (R_sense2 + R_sense1) / R_sense2 * (
425 # (1.0 / (R_sense1 * C_sense)) * (-Isense * R_sense2 / (R_sense1 + R_sense2) * (R_sense1 / R_sense2 + 1.0) + I))
426 self.mk1 = (R_sense2 + R_sense1) / R_sense2 * (1.0 / (R_sense1 * C_sense))
427 self.mk2 = -self.mk1 * R_sense2 / (R_sense1 + R_sense2) * (R_sense1 / R_sense2 + 1.0)
428
429 # ia, ib, ic, theta, omega, isensea, isenseb, isensec
430 self.X = numpy.matrix([[0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0]])
431
432 self.K = 0.05 * Vconv
433 print('A %s' % repr(self.A))
434 print('B %s' % repr(self.B))
435 print('K %s' % repr(self.K))
436
437 print('System poles are %s' % repr(numpy.linalg.eig(self.A)[0]))
438 print('Poles are %s' % repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
439
440 controllability = controls.ctrb(self.A, self.B)
441 print('Rank of augmented controlability matrix. %d' % numpy.linalg.matrix_rank(
442 controllability))
443
444 self.data_logger = DataLogger(switching_pattern)
445 self.current_time = 0.0
446
447 self.estimated_velocity = self.X[4, 0]
448
449 def motor_diffeq(self, x, t, U):
450 I = numpy.matrix(x[0:3]).T
451 theta = x[3]
452 omega = x[4]
453 Isense = numpy.matrix(x[5:]).T
454
455 dflux = phases(f_single, theta) / Kv
456
457 Xdot = numpy.matrix(numpy.zeros((8, 1)))
458 di_dt = -self.A_model * I + self.B_model * U - self.L_matrix_inv_model * dflux * omega
459 torque = I.T * dflux
460 Xdot[0:3, :] = di_dt
461 Xdot[3, :] = omega
462 Xdot[4, :] = torque / J
463
464 Xdot[5:, :] = self.mk1 * I + self.mk2 * Isense
465 return numpy.squeeze(numpy.asarray(Xdot))
466
467 def DoControls(self, goal_current):
468 theta = self.X[3, 0]
469 # Use the actual angular velocity.
470 omega = self.X[4, 0]
471
472 measured_current = self.X[5:, :].copy()
473
474 # Ok, lets now fake it.
475 E_imag1 = numpy.exp(1j * theta) * K1 * numpy.matrix(
476 [[-1j],
477 [-1j * numpy.exp(1j * numpy.pi * 2.0 / 3.0)],
478 [-1j * numpy.exp(-1j * numpy.pi * 2.0 / 3.0)]])
479 E_imag2 = numpy.exp(1j * 5.0 * theta) * K2 * numpy.matrix(
480 [[-1j],
481 [-1j * numpy.exp(-1j * numpy.pi * 2.0 / 3.0)],
482 [-1j * numpy.exp(1j * numpy.pi * 2.0 / 3.0)]])
483
484 overall_measured_current = ((E_imag1 + E_imag2).real.T * measured_current / one_amp_scalar)[0, 0]
485
486 current_error = goal_current - overall_measured_current
487 #print(current_error)
488 self.estimated_velocity += current_error * 1.0
489 omega = self.estimated_velocity
490
491 # Now, apply the transfer function of the inductor.
492 # Use that to difference the current across the cycle.
493 Icurrent = self.Ilast
494 # No history:
495 #Icurrent = phases(g_single, theta) * goal_current
496 Inext = phases(g_single, theta + omega * 1.0 / hz) * goal_current
497
498 deltaI = Inext - Icurrent
499
500 H1 = -numpy.linalg.inv(1j * omega * self.L_matrix + self.R_matrix) * omega / Kv
501 H2 = -numpy.linalg.inv(1j * omega * 5.0 * self.L_matrix + self.R_matrix) * omega / Kv
502 p_imag = H1 * E_imag1 + H2 * E_imag2
503 p_next_imag = numpy.exp(1j * omega * 1.0 / hz) * H1 * E_imag1 + \
504 numpy.exp(1j * omega * 5.0 * 1.0 / hz) * H2 * E_imag2
505 p = p_imag.real
506
507 # So, we now know how much the change in current is due to changes in BEMF.
508 # Subtract that, and then run the stock statespace equation.
509 Vn_ff = self.B_discrete_inverse * (Inext - self.A_discrete * (Icurrent - p) - p_next_imag.real)
510 print 'Vn_ff', Vn_ff
511 print 'Inext', Inext
512 Vn = Vn_ff + self.K * (Icurrent - measured_current)
513
514 E = phases(f_single, self.X[3, 0]) / Kv * self.X[4, 0]
515 self.data_logger.log_controls(self.current_time, measured_current, Icurrent, E, self.estimated_velocity)
516
517 self.Ilast = Inext
518
519 return Vn
520
521 def Simulate(self):
522 start_wall_time = time.time()
523 self.Ilast = numpy.matrix(numpy.zeros((3, 1)))
524 for n in range(200):
525 goal_current = 10.0
526 max_current = (vcc - (self.X[4, 0] / Kv * 2.0)) / max_one_amp_driving_voltage
527 min_current = (-vcc - (self.X[4, 0] / Kv * 2.0)) / max_one_amp_driving_voltage
528 goal_current = max(min_current, min(max_current, goal_current))
529
530 Vn = self.DoControls(goal_current)
531
532 #Vn = numpy.matrix([[0.20], [0.0], [0.0]])
533 #Vn = numpy.matrix([[0.00], [0.20], [0.0]])
534 #Vn = numpy.matrix([[0.00], [0.0], [0.20]])
535
536 # T is the fractional rate.
537 T = Vn / vcc
538 tn = -numpy.min(T)
539 T += tn
540 if (T > 1.0).any():
541 T = T / numpy.max(T)
542
543 for t, U in sample_times(T = T,
544 dt = 1.0 / hz, n = 10,
545 start_time = self.current_time):
546 # Analog amplifier mode!
547 #U = Vn
548
549 self.data_logger.log_data(self.X, (U - min(U)), self.current_time, Vn, goal_current)
550 t_array = numpy.array([self.current_time, t])
551 self.X = numpy.matrix(scipy.integrate.odeint(
552 self.motor_diffeq,
553 numpy.squeeze(numpy.asarray(self.X)),
554 t_array, args=(U,)))[1, :].T
555
556 self.current_time = t
557
558 print 'Took %f to simulate' % (time.time() - start_wall_time)
559
560 self.data_logger.plot()
561
562simulation = Simulation()
563simulation.Simulate()