blob: b17c514a64aa6e476499d93b73c0d3b01cff719c [file] [log] [blame]
Brian Silverman6260c092018-01-14 15:21:36 -08001#!/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 = 0.0
12
13# Make the amplitude of the fundamental 1 for ease of playing with.
14K2 /= K1
15K1 = 1
16
17vcc = 14.0 # volts
18R_motor = 0.1073926073926074 # ohms for the motor
19R = R_motor + 0.080 + 0.02 # motor + fets + wires ohms for system
20
21L = 80.0 * 1e-6 # Henries
22M = L / 10.0
23
24Kv = 37.6 # rad/s/volt, where the voltage is measured from the neutral to the phase.
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 Args:
129 Ton: On times for each phase.
130 Toff: Off times for each phase.
131 dt: The cycle time.
132 n: Number of intermediate points to include in the result.
133 start_time: Starting value for the t values in the result.
134
135 Returns:
136 array of [t, U matrix]
137 """
138
139 assert((Toff <= 1.0).all())
140 assert((Ton <= 1.0).all())
141 assert((Toff >= 0.0).all())
142 assert((Ton >= 0.0).all())
143
144 if (Ton <= Toff).all():
145 on_before_off = True
146 else:
147 # Verify that they are all ordered correctly.
148 assert(not (Ton <= Toff).any())
149 on_before_off = False
150
151 Toff = Toff.copy() * dt
152 Toff[Toff < 100e-9] = -1.0
153 Toff[Toff > dt] = dt
154
155 Ton = Ton.copy() * dt
156 Ton[Ton < 100e-9] = -1.0
157 Ton[Ton > dt - 100e-9] = dt + 1.0
158
159 result = []
160 t = 0
161
162 result_times = numpy.concatenate(
163 (numpy.linspace(0, dt, num=n),
164 numpy.reshape(numpy.asarray(Ton[numpy.logical_and(Ton < dt, Ton > 0.0)]), (-1,)),
165 numpy.reshape(numpy.asarray(Toff[numpy.logical_and(Toff < dt, Toff > 0.0)]), (-1,))
166 ))
167 result_times.sort()
168 assert((result_times >= 0).all())
169 assert((result_times <= dt).all())
170
171 for t in result_times:
172 if on_before_off:
173 U = numpy.matrix([[vcc], [vcc], [vcc]])
174 U[t <= Ton] = 0.0
175 U[Toff < t] = 0.0
176 else:
177 U = numpy.matrix([[0.0], [0.0], [0.0]])
178 U[t > Ton] = vcc
179 U[t <= Toff] = vcc
180 result.append((float(t + start_time), U.copy()))
181
182 return result
183
184def sample_times(T, dt, n, start_time):
185 if switching_pattern == 'rear':
186 T = 1.0 - T
187 ans = full_sample_times(T, numpy.matrix(numpy.ones((3, 1))) * 1.0, dt, n, start_time)
188 elif switching_pattern == 'centered front shifted':
189 # Centered, but shifted to the beginning of the cycle.
190 Ton = 0.5 - T / 2.0
191 Toff = 0.5 + T / 2.0
192
193 tn = min(Ton)[0, 0]
194 Ton -= tn
195 Toff -= tn
196
197 ans = full_sample_times(Ton, Toff, dt, n, start_time)
198 elif switching_pattern == 'centered':
199 # Centered, looks waaay better.
200 Ton = 0.5 - T / 2.0
201 Toff = 0.5 + T / 2.0
202
203 ans = full_sample_times(Ton, Toff, dt, n, start_time)
204 elif switching_pattern == 'anticentered':
205 # Centered, looks waaay better.
206 Toff = T / 2.0
207 Ton = 1.0 - T / 2.0
208
209 ans = full_sample_times(Ton, Toff, dt, n, start_time)
210 elif switching_pattern == 'front':
211 ans = full_sample_times(numpy.matrix(numpy.zeros((3, 1))), T, dt, n, start_time)
212 else:
213 assert(False)
214
215 return ans
216
217class DataLogger(object):
218 def __init__(self, title=None):
219 self.title = title
220 self.ia = []
221 self.ib = []
222 self.ic = []
223 self.ia_goal = []
224 self.ib_goal = []
225 self.ic_goal = []
226 self.ia_controls = []
227 self.ib_controls = []
228 self.ic_controls = []
229 self.isensea = []
230 self.isenseb = []
231 self.isensec = []
232
233 self.va = []
234 self.vb = []
235 self.vc = []
236 self.van = []
237 self.vbn = []
238 self.vcn = []
239
240 self.ea = []
241 self.eb = []
242 self.ec = []
243
244 self.theta = []
245 self.omega = []
246
247 self.i_goal = []
248
249 self.time = []
250 self.controls_time = []
251 self.predicted_time = []
252
253 self.ia_pred = []
254 self.ib_pred = []
255 self.ic_pred = []
256
257 self.voltage_time = []
258 self.estimated_velocity = []
259 self.U_last = numpy.matrix(numpy.zeros((3, 1)))
260
261 def log_predicted(self, current_time, p):
262 self.predicted_time.append(current_time)
263 self.ia_pred.append(p[0, 0])
264 self.ib_pred.append(p[1, 0])
265 self.ic_pred.append(p[2, 0])
266
267 def log_controls(self, current_time, measured_current, In, E, estimated_velocity):
268 self.controls_time.append(current_time)
269 self.ia_controls.append(measured_current[0, 0])
270 self.ib_controls.append(measured_current[1, 0])
271 self.ic_controls.append(measured_current[2, 0])
272
273 self.ea.append(E[0, 0])
274 self.eb.append(E[1, 0])
275 self.ec.append(E[2, 0])
276
277 self.ia_goal.append(In[0, 0])
278 self.ib_goal.append(In[1, 0])
279 self.ic_goal.append(In[2, 0])
280 self.estimated_velocity.append(estimated_velocity)
281
282 def log_data(self, X, U, current_time, Vn, i_goal):
283 self.ia.append(X[0, 0])
284 self.ib.append(X[1, 0])
285 self.ic.append(X[2, 0])
286
287 self.i_goal.append(i_goal)
288
289 self.isensea.append(X[5, 0])
290 self.isenseb.append(X[6, 0])
291 self.isensec.append(X[7, 0])
292
293 self.theta.append(X[3, 0])
294 self.omega.append(X[4, 0])
295
296 self.time.append(current_time)
297
298 self.van.append(Vn[0, 0])
299 self.vbn.append(Vn[1, 0])
300 self.vcn.append(Vn[2, 0])
301
302 if (self.U_last != U).any():
303 self.va.append(self.U_last[0, 0])
304 self.vb.append(self.U_last[1, 0])
305 self.vc.append(self.U_last[2, 0])
306 self.voltage_time.append(current_time)
307
308 self.va.append(U[0, 0])
309 self.vb.append(U[1, 0])
310 self.vc.append(U[2, 0])
311 self.voltage_time.append(current_time)
312 self.U_last = U.copy()
313
314 def plot(self):
315 fig = pylab.figure()
316 pylab.subplot(3, 1, 1)
317 pylab.plot(self.controls_time, self.ia_controls, 'ro', label='ia_controls')
318 pylab.plot(self.controls_time, self.ib_controls, 'go', label='ib_controls')
319 pylab.plot(self.controls_time, self.ic_controls, 'bo', label='ic_controls')
320 pylab.plot(self.controls_time, self.ia_goal, 'r--', label='ia_goal')
321 pylab.plot(self.controls_time, self.ib_goal, 'g--', label='ib_goal')
322 pylab.plot(self.controls_time, self.ic_goal, 'b--', label='ic_goal')
323
324 #pylab.plot(self.controls_time, self.ia_pred, 'r*', label='ia_pred')
325 #pylab.plot(self.controls_time, self.ib_pred, 'g*', label='ib_pred')
326 #pylab.plot(self.controls_time, self.ic_pred, 'b*', label='ic_pred')
327 pylab.plot(self.time, self.isensea, 'r:', label='ia_sense')
328 pylab.plot(self.time, self.isenseb, 'g:', label='ib_sense')
329 pylab.plot(self.time, self.isensec, 'b:', label='ic_sense')
330 pylab.plot(self.time, self.ia, 'r', label='ia')
331 pylab.plot(self.time, self.ib, 'g', label='ib')
332 pylab.plot(self.time, self.ic, 'b', label='ic')
333 pylab.plot(self.time, self.i_goal, label='i_goal')
334 if self.title is not None:
335 fig.canvas.set_window_title(self.title)
336 pylab.legend()
337
338 pylab.subplot(3, 1, 2)
339 pylab.plot(self.voltage_time, self.va, label='va')
340 pylab.plot(self.voltage_time, self.vb, label='vb')
341 pylab.plot(self.voltage_time, self.vc, label='vc')
342 pylab.plot(self.time, self.van, label='van')
343 pylab.plot(self.time, self.vbn, label='vbn')
344 pylab.plot(self.time, self.vcn, label='vcn')
345 pylab.plot(self.controls_time, self.ea, label='ea')
346 pylab.plot(self.controls_time, self.eb, label='eb')
347 pylab.plot(self.controls_time, self.ec, label='ec')
348 pylab.legend()
349
350 pylab.subplot(3, 1, 3)
351 pylab.plot(self.time, self.theta, label='theta')
352 pylab.plot(self.time, self.omega, label='omega')
353 #pylab.plot(self.controls_time, self.estimated_velocity, label='estimated omega')
354
355 pylab.legend()
356
357 fig = pylab.figure()
358 pylab.plot(self.controls_time,
359 map(operator.sub, self.ia_goal, self.ia_controls), 'r', label='ia_error')
360 pylab.plot(self.controls_time,
361 map(operator.sub, self.ib_goal, self.ib_controls), 'g', label='ib_error')
362 pylab.plot(self.controls_time,
363 map(operator.sub, self.ic_goal, self.ic_controls), 'b', label='ic_error')
364 if self.title is not None:
365 fig.canvas.set_window_title(self.title)
366 pylab.legend()
367 pylab.show()
368
369
370# So, from running a bunch of math, we know the following:
371# Van + Vbn + Vcn = 0
372# ia + ib + ic = 0
373# ea + eb + ec = 0
374# d ia/dt + d ib/dt + d ic/dt = 0
375#
376# We also have:
377# [ Van ] [ 2/3 -1/3 -1/3] [Va]
378# [ Vbn ] = [ -1/3 2/3 -1/3] [Vb]
379# [ Vcn ] [ -1/3 -1/3 2/3] [Vc]
380#
381# or,
382#
383# Vabcn = Vconv * V
384#
385# The base equation is:
386#
387# [ Van ] [ R 0 0 ] [ ia ] [ L M M ] [ dia/dt ] [ ea ]
388# [ Vbn ] = [ 0 R 0 ] [ ib ] + [ M L M ] [ dib/dt ] + [ eb ]
389# [ Vbn ] [ 0 0 R ] [ ic ] [ M M L ] [ dic/dt ] [ ec ]
390#
391# or
392#
393# Vabcn = R_matrix * I + L_matrix * I_dot + E
394#
395# We can re-arrange this as:
396#
397# inv(L_matrix) * (Vconv * V - E - R_matrix * I) = I_dot
398# B * V - inv(L_matrix) * E - A * I = I_dot
399class Simulation(object):
400 def __init__(self):
401 self.R_matrix = numpy.matrix(numpy.eye(3)) * R
402 self.L_matrix = numpy.matrix([[L, M, M], [M, L, M], [M, M, L]])
403 self.L_matrix_inv = numpy.linalg.inv(self.L_matrix)
404 self.A = self.L_matrix_inv * self.R_matrix
405 self.B = self.L_matrix_inv * Vconv
406 self.A_discrete, self.B_discrete = controls.c2d(-self.A, self.B, 1.0 / hz)
407 self.B_discrete_inverse = numpy.matrix(numpy.eye(3)) / (self.B_discrete[0, 0] - self.B_discrete[1, 0])
408
409 self.R_model = R * 1.0
410 self.L_model = L * 1.0
411 self.M_model = M * 1.0
412 self.R_matrix_model = numpy.matrix(numpy.eye(3)) * self.R_model
413 self.L_matrix_model = numpy.matrix([[self.L_model, self.M_model, self.M_model],
414 [self.M_model, self.L_model, self.M_model],
415 [self.M_model, self.M_model, self.L_model]])
416 self.L_matrix_inv_model = numpy.linalg.inv(self.L_matrix_model)
417 self.A_model = self.L_matrix_inv_model * self.R_matrix_model
418 self.B_model = self.L_matrix_inv_model * Vconv
419 self.A_discrete_model, self.B_discrete_model = \
420 controls.c2d(-self.A_model, self.B_model, 1.0 / hz)
421 self.B_discrete_inverse_model = numpy.matrix(numpy.eye(3)) / (self.B_discrete_model[0, 0] - self.B_discrete_model[1, 0])
422
423 print 'constexpr double kL = %g;' % self.L_model
424 print 'constexpr double kM = %g;' % self.M_model
425 print 'constexpr double kR = %g;' % self.R_model
426 print 'constexpr float kAdiscrete_diagonal = %gf;' % self.A_discrete_model[0, 0]
427 print 'constexpr float kAdiscrete_offdiagonal = %gf;' % self.A_discrete_model[1, 0]
428 print 'constexpr float kBdiscrete_inv_diagonal = %gf;' % self.B_discrete_inverse_model[0, 0]
429 print 'constexpr float kBdiscrete_inv_offdiagonal = %gf;' % self.B_discrete_inverse_model[1, 0]
430 print 'constexpr double kOneAmpScalar = %g;' % one_amp_scalar
431 print 'constexpr double kMaxOneAmpDrivingVoltage = %g;' % max_one_amp_driving_voltage
432 print('A_discrete', self.A_discrete)
433 print('B_discrete', self.B_discrete)
434 print('B_discrete_sub', numpy.linalg.inv(self.B_discrete[0:2, 0:2]))
435 print('B_discrete_inv', self.B_discrete_inverse)
436
437 # Xdot[5:, :] = (R_sense2 + R_sense1) / R_sense2 * (
438 # (1.0 / (R_sense1 * C_sense)) * (-Isense * R_sense2 / (R_sense1 + R_sense2) * (R_sense1 / R_sense2 + 1.0) + I))
439 self.mk1 = (R_sense2 + R_sense1) / R_sense2 * (1.0 / (R_sense1 * C_sense))
440 self.mk2 = -self.mk1 * R_sense2 / (R_sense1 + R_sense2) * (R_sense1 / R_sense2 + 1.0)
441
442 # ia, ib, ic, theta, omega, isensea, isenseb, isensec
443 self.X = numpy.matrix([[0.0], [0.0], [0.0], [-2.0 * numpy.pi / 3.0], [0.0], [0.0], [0.0], [0.0]])
444
445 self.K = 0.05 * Vconv
446 print('A %s' % repr(self.A))
447 print('B %s' % repr(self.B))
448 print('K %s' % repr(self.K))
449
450 print('System poles are %s' % repr(numpy.linalg.eig(self.A)[0]))
451 print('Poles are %s' % repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
452
453 controllability = controls.ctrb(self.A, self.B)
454 print('Rank of augmented controlability matrix. %d' % numpy.linalg.matrix_rank(
455 controllability))
456
457 self.data_logger = DataLogger(switching_pattern)
458 self.current_time = 0.0
459
460 self.estimated_velocity = self.X[4, 0]
461
462 def motor_diffeq(self, x, t, U):
463 I = numpy.matrix(x[0:3]).T
464 theta = x[3]
465 omega = x[4]
466 Isense = numpy.matrix(x[5:]).T
467
468 dflux = phases(f_single, theta) / Kv
469
470 Xdot = numpy.matrix(numpy.zeros((8, 1)))
471 di_dt = -self.A_model * I + self.B_model * U - self.L_matrix_inv_model * dflux * omega
472 torque = I.T * dflux
473 Xdot[0:3, :] = di_dt
474 Xdot[3, :] = omega
475 Xdot[4, :] = torque / J
476
477 Xdot[5:, :] = self.mk1 * I + self.mk2 * Isense
478 return numpy.squeeze(numpy.asarray(Xdot))
479
480 def DoControls(self, goal_current):
481 theta = self.X[3, 0]
482 # Use the actual angular velocity.
483 omega = self.X[4, 0]
484
485 measured_current = self.X[5:, :].copy()
486
487 # Ok, lets now fake it.
488 E_imag1 = numpy.exp(1j * theta) * K1 * numpy.matrix(
489 [[-1j],
490 [-1j * numpy.exp(1j * numpy.pi * 2.0 / 3.0)],
491 [-1j * numpy.exp(-1j * numpy.pi * 2.0 / 3.0)]])
492 E_imag2 = numpy.exp(1j * 5.0 * theta) * K2 * numpy.matrix(
493 [[-1j],
494 [-1j * numpy.exp(-1j * numpy.pi * 2.0 / 3.0)],
495 [-1j * numpy.exp(1j * numpy.pi * 2.0 / 3.0)]])
496
497 overall_measured_current = ((E_imag1 + E_imag2).real.T * measured_current / one_amp_scalar)[0, 0]
498
499 current_error = goal_current - overall_measured_current
500 #print(current_error)
501 self.estimated_velocity += current_error * 1.0
502 omega = self.estimated_velocity
503
504 # Now, apply the transfer function of the inductor.
505 # Use that to difference the current across the cycle.
506 Icurrent = self.Ilast
507 # No history:
508 #Icurrent = phases(g_single, theta) * goal_current
509 Inext = phases(g_single, theta + omega * 1.0 / hz) * goal_current
510
511 deltaI = Inext - Icurrent
512
513 H1 = -numpy.linalg.inv(1j * omega * self.L_matrix + self.R_matrix) * omega / Kv
514 H2 = -numpy.linalg.inv(1j * omega * 5.0 * self.L_matrix + self.R_matrix) * omega / Kv
515 p_imag = H1 * E_imag1 + H2 * E_imag2
516 p_next_imag = numpy.exp(1j * omega * 1.0 / hz) * H1 * E_imag1 + \
517 numpy.exp(1j * omega * 5.0 * 1.0 / hz) * H2 * E_imag2
518 p = p_imag.real
519
520 # So, we now know how much the change in current is due to changes in BEMF.
521 # Subtract that, and then run the stock statespace equation.
522 Vn_ff = self.B_discrete_inverse * (Inext - self.A_discrete * (Icurrent - p) - p_next_imag.real)
523 print 'Vn_ff', Vn_ff
524 print 'Inext', Inext
525 Vn = Vn_ff + self.K * (Icurrent - measured_current)
526
527 E = phases(f_single, self.X[3, 0]) / Kv * self.X[4, 0]
528 self.data_logger.log_controls(self.current_time, measured_current, Icurrent, E, self.estimated_velocity)
529
530 self.Ilast = Inext
531
532 return Vn
533
534 def Simulate(self):
535 start_wall_time = time.time()
536 self.Ilast = numpy.matrix(numpy.zeros((3, 1)))
537 for n in range(200):
538 goal_current = 1.0
539 max_current = (vcc - (self.X[4, 0] / Kv * 2.0)) / max_one_amp_driving_voltage
540 min_current = (-vcc - (self.X[4, 0] / Kv * 2.0)) / max_one_amp_driving_voltage
541 goal_current = max(min_current, min(max_current, goal_current))
542
543 Vn = self.DoControls(goal_current)
544
545 #Vn = numpy.matrix([[1.00], [0.0], [0.0]])
546 Vn = numpy.matrix([[0.00], [1.00], [0.0]])
547 #Vn = numpy.matrix([[0.00], [0.0], [1.00]])
548
549 # T is the fractional rate.
550 T = Vn / vcc
551 tn = -numpy.min(T)
552 T += tn
553 if (T > 1.0).any():
554 T = T / numpy.max(T)
555
556 for t, U in sample_times(T = T,
557 dt = 1.0 / hz, n = 10,
558 start_time = self.current_time):
559 # Analog amplifier mode!
560 #U = Vn
561
562 self.data_logger.log_data(self.X, (U - min(U)), self.current_time, Vn, goal_current)
563 t_array = numpy.array([self.current_time, t])
564 self.X = numpy.matrix(scipy.integrate.odeint(
565 self.motor_diffeq,
566 numpy.squeeze(numpy.asarray(self.X)),
567 t_array, args=(U,)))[1, :].T
568
569 self.current_time = t
570
571 print 'Took %f to simulate' % (time.time() - start_wall_time)
572
573 self.data_logger.plot()
574
575simulation = Simulation()
576simulation.Simulate()