blob: fec909d4e7b9f59cbd661b6cf5d821a6015524ff [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
Ravago Jones5127ccc2022-07-31 16:32:45 -070057Vconv = numpy.matrix([[2.0, -1.0, -1.0], [-1.0, 2.0, -1.0], [-1.0, -1.0, 2.0]
58 ]) / 3.0
59
Brian Silverman6260c092018-01-14 15:21:36 -080060
61def f_single(theta):
Ravago Jones5127ccc2022-07-31 16:32:45 -070062 return K1 * numpy.sin(theta) + K2 * numpy.sin(theta * 5)
63
Brian Silverman6260c092018-01-14 15:21:36 -080064
65def g_single(theta):
Ravago Jones5127ccc2022-07-31 16:32:45 -070066 return K1 * numpy.sin(theta) - K2 * numpy.sin(theta * 5)
67
Brian Silverman6260c092018-01-14 15:21:36 -080068
69def gdot_single(theta):
Ravago Jones5127ccc2022-07-31 16:32:45 -070070 """Derivitive of the current.
Brian Silverman6260c092018-01-14 15:21:36 -080071
72 Must be multiplied by omega externally.
73 """
Ravago Jones5127ccc2022-07-31 16:32:45 -070074 return K1 * numpy.cos(theta) - 5.0 * K2 * numpy.cos(theta * 5.0)
Brian Silverman6260c092018-01-14 15:21:36 -080075
Ravago Jones5127ccc2022-07-31 16:32:45 -070076
77f = numpy.vectorize(f_single, otypes=(numpy.float, ))
78g = numpy.vectorize(g_single, otypes=(numpy.float, ))
79gdot = numpy.vectorize(gdot_single, otypes=(numpy.float, ))
80
Brian Silverman6260c092018-01-14 15:21:36 -080081
82def torque(theta):
Ravago Jones5127ccc2022-07-31 16:32:45 -070083 return f(theta) * g(theta)
84
Brian Silverman6260c092018-01-14 15:21:36 -080085
86def phase_a(function, theta):
Ravago Jones5127ccc2022-07-31 16:32:45 -070087 return function(theta)
88
Brian Silverman6260c092018-01-14 15:21:36 -080089
90def phase_b(function, theta):
Ravago Jones5127ccc2022-07-31 16:32:45 -070091 return function(theta + 2 * numpy.pi / 3)
92
Brian Silverman6260c092018-01-14 15:21:36 -080093
94def phase_c(function, theta):
Ravago Jones5127ccc2022-07-31 16:32:45 -070095 return function(theta + 4 * numpy.pi / 3)
96
Brian Silverman6260c092018-01-14 15:21:36 -080097
98def phases(function, theta):
Ravago Jones5127ccc2022-07-31 16:32:45 -070099 return numpy.matrix([[phase_a(function,
100 theta)], [phase_b(function, theta)],
101 [phase_c(function, theta)]])
102
Brian Silverman6260c092018-01-14 15:21:36 -0800103
104def all_phases(function, theta_range):
Ravago Jones5127ccc2022-07-31 16:32:45 -0700105 return (phase_a(function, theta_range) + phase_b(function, theta_range) +
106 phase_c(function, theta_range))
107
Brian Silverman6260c092018-01-14 15:21:36 -0800108
109theta_range = numpy.linspace(start=0, stop=4 * numpy.pi, num=10000)
Ravago Jones5127ccc2022-07-31 16:32:45 -0700110one_amp_driving_voltage = R * g(theta_range) + (
111 L * gdot(theta_range) + M * gdot(theta_range + 2.0 / 3.0 * numpy.pi) +
112 M * gdot(theta_range - 2.0 / 3.0 * numpy.pi)) * Kv * vcc / 2.0
Brian Silverman6260c092018-01-14 15:21:36 -0800113
114max_one_amp_driving_voltage = max(one_amp_driving_voltage)
115
116# The number to divide the product of the unit BEMF and the per phase current
117# by to get motor current.
118one_amp_scalar = (phases(f_single, 0.0).T * phases(g_single, 0.0))[0, 0]
119
120print 'Max BEMF', max(f(theta_range))
121print 'Max current', max(g(theta_range))
Ravago Jones5127ccc2022-07-31 16:32:45 -0700122print 'Max drive voltage (one_amp_driving_voltage)', max(
123 one_amp_driving_voltage)
Brian Silverman6260c092018-01-14 15:21:36 -0800124print 'one_amp_scalar', one_amp_scalar
125
126pylab.figure()
127pylab.subplot(1, 1, 1)
128pylab.plot(theta_range, f(theta_range), label='bemf')
129pylab.plot(theta_range, g(theta_range), label='phase_current')
130pylab.plot(theta_range, torque(theta_range), label='phase_torque')
Ravago Jones5127ccc2022-07-31 16:32:45 -0700131pylab.plot(theta_range,
132 all_phases(torque, theta_range),
133 label='sum_torque/current')
Brian Silverman6260c092018-01-14 15:21:36 -0800134pylab.legend()
135
136
137def full_sample_times(Ton, Toff, dt, n, start_time):
Ravago Jones5127ccc2022-07-31 16:32:45 -0700138 """Returns n + 4 samples for the provided switching times.
Brian Silverman6260c092018-01-14 15:21:36 -0800139
140 We need the timesteps and Us to integrate.
141
142 Args:
143 Ton: On times for each phase.
144 Toff: Off times for each phase.
145 dt: The cycle time.
146 n: Number of intermediate points to include in the result.
147 start_time: Starting value for the t values in the result.
148
149 Returns:
150 array of [t, U matrix]
151 """
152
Ravago Jones5127ccc2022-07-31 16:32:45 -0700153 assert ((Toff <= 1.0).all())
154 assert ((Ton <= 1.0).all())
155 assert ((Toff >= 0.0).all())
156 assert ((Ton >= 0.0).all())
Brian Silverman6260c092018-01-14 15:21:36 -0800157
Ravago Jones5127ccc2022-07-31 16:32:45 -0700158 if (Ton <= Toff).all():
159 on_before_off = True
Brian Silverman6260c092018-01-14 15:21:36 -0800160 else:
Ravago Jones5127ccc2022-07-31 16:32:45 -0700161 # Verify that they are all ordered correctly.
162 assert (not (Ton <= Toff).any())
163 on_before_off = False
Brian Silverman6260c092018-01-14 15:21:36 -0800164
Ravago Jones5127ccc2022-07-31 16:32:45 -0700165 Toff = Toff.copy() * dt
166 Toff[Toff < 100e-9] = -1.0
167 Toff[Toff > dt] = dt
168
169 Ton = Ton.copy() * dt
170 Ton[Ton < 100e-9] = -1.0
171 Ton[Ton > dt - 100e-9] = dt + 1.0
172
173 result = []
174 t = 0
175
176 result_times = numpy.concatenate(
177 (numpy.linspace(0, dt, num=n),
178 numpy.reshape(
179 numpy.asarray(Ton[numpy.logical_and(Ton < dt, Ton > 0.0)]),
180 (-1, )),
181 numpy.reshape(
182 numpy.asarray(Toff[numpy.logical_and(Toff < dt, Toff > 0.0)]),
183 (-1, ))))
184 result_times.sort()
185 assert ((result_times >= 0).all())
186 assert ((result_times <= dt).all())
187
188 for t in result_times:
189 if on_before_off:
190 U = numpy.matrix([[vcc], [vcc], [vcc]])
191 U[t <= Ton] = 0.0
192 U[Toff < t] = 0.0
193 else:
194 U = numpy.matrix([[0.0], [0.0], [0.0]])
195 U[t > Ton] = vcc
196 U[t <= Toff] = vcc
197 result.append((float(t + start_time), U.copy()))
198
199 return result
200
Brian Silverman6260c092018-01-14 15:21:36 -0800201
202def sample_times(T, dt, n, start_time):
Ravago Jones5127ccc2022-07-31 16:32:45 -0700203 if switching_pattern == 'rear':
204 T = 1.0 - T
205 ans = full_sample_times(T,
206 numpy.matrix(numpy.ones((3, 1))) * 1.0, dt, n,
207 start_time)
208 elif switching_pattern == 'centered front shifted':
209 # Centered, but shifted to the beginning of the cycle.
210 Ton = 0.5 - T / 2.0
211 Toff = 0.5 + T / 2.0
Brian Silverman6260c092018-01-14 15:21:36 -0800212
Ravago Jones5127ccc2022-07-31 16:32:45 -0700213 tn = min(Ton)[0, 0]
214 Ton -= tn
215 Toff -= tn
Brian Silverman6260c092018-01-14 15:21:36 -0800216
Ravago Jones5127ccc2022-07-31 16:32:45 -0700217 ans = full_sample_times(Ton, Toff, dt, n, start_time)
218 elif switching_pattern == 'centered':
219 # Centered, looks waaay better.
220 Ton = 0.5 - T / 2.0
221 Toff = 0.5 + T / 2.0
Brian Silverman6260c092018-01-14 15:21:36 -0800222
Ravago Jones5127ccc2022-07-31 16:32:45 -0700223 ans = full_sample_times(Ton, Toff, dt, n, start_time)
224 elif switching_pattern == 'anticentered':
225 # Centered, looks waaay better.
226 Toff = T / 2.0
227 Ton = 1.0 - T / 2.0
Brian Silverman6260c092018-01-14 15:21:36 -0800228
Ravago Jones5127ccc2022-07-31 16:32:45 -0700229 ans = full_sample_times(Ton, Toff, dt, n, start_time)
230 elif switching_pattern == 'front':
231 ans = full_sample_times(numpy.matrix(numpy.zeros((3, 1))), T, dt, n,
232 start_time)
233 else:
234 assert (False)
Brian Silverman6260c092018-01-14 15:21:36 -0800235
Ravago Jones5127ccc2022-07-31 16:32:45 -0700236 return ans
237
Brian Silverman6260c092018-01-14 15:21:36 -0800238
239class DataLogger(object):
Brian Silverman6260c092018-01-14 15:21:36 -0800240
Ravago Jones5127ccc2022-07-31 16:32:45 -0700241 def __init__(self, title=None):
242 self.title = title
243 self.ia = []
244 self.ib = []
245 self.ic = []
246 self.ia_goal = []
247 self.ib_goal = []
248 self.ic_goal = []
249 self.ia_controls = []
250 self.ib_controls = []
251 self.ic_controls = []
252 self.isensea = []
253 self.isenseb = []
254 self.isensec = []
Brian Silverman6260c092018-01-14 15:21:36 -0800255
Ravago Jones5127ccc2022-07-31 16:32:45 -0700256 self.va = []
257 self.vb = []
258 self.vc = []
259 self.van = []
260 self.vbn = []
261 self.vcn = []
Brian Silverman6260c092018-01-14 15:21:36 -0800262
Ravago Jones5127ccc2022-07-31 16:32:45 -0700263 self.ea = []
264 self.eb = []
265 self.ec = []
Brian Silverman6260c092018-01-14 15:21:36 -0800266
Ravago Jones5127ccc2022-07-31 16:32:45 -0700267 self.theta = []
268 self.omega = []
Brian Silverman6260c092018-01-14 15:21:36 -0800269
Ravago Jones5127ccc2022-07-31 16:32:45 -0700270 self.i_goal = []
Brian Silverman6260c092018-01-14 15:21:36 -0800271
Ravago Jones5127ccc2022-07-31 16:32:45 -0700272 self.time = []
273 self.controls_time = []
274 self.predicted_time = []
Brian Silverman6260c092018-01-14 15:21:36 -0800275
Ravago Jones5127ccc2022-07-31 16:32:45 -0700276 self.ia_pred = []
277 self.ib_pred = []
278 self.ic_pred = []
Brian Silverman6260c092018-01-14 15:21:36 -0800279
Ravago Jones5127ccc2022-07-31 16:32:45 -0700280 self.voltage_time = []
281 self.estimated_velocity = []
282 self.U_last = numpy.matrix(numpy.zeros((3, 1)))
Brian Silverman6260c092018-01-14 15:21:36 -0800283
Ravago Jones5127ccc2022-07-31 16:32:45 -0700284 def log_predicted(self, current_time, p):
285 self.predicted_time.append(current_time)
286 self.ia_pred.append(p[0, 0])
287 self.ib_pred.append(p[1, 0])
288 self.ic_pred.append(p[2, 0])
Brian Silverman6260c092018-01-14 15:21:36 -0800289
Ravago Jones5127ccc2022-07-31 16:32:45 -0700290 def log_controls(self, current_time, measured_current, In, E,
291 estimated_velocity):
292 self.controls_time.append(current_time)
293 self.ia_controls.append(measured_current[0, 0])
294 self.ib_controls.append(measured_current[1, 0])
295 self.ic_controls.append(measured_current[2, 0])
Brian Silverman6260c092018-01-14 15:21:36 -0800296
Ravago Jones5127ccc2022-07-31 16:32:45 -0700297 self.ea.append(E[0, 0])
298 self.eb.append(E[1, 0])
299 self.ec.append(E[2, 0])
Brian Silverman6260c092018-01-14 15:21:36 -0800300
Ravago Jones5127ccc2022-07-31 16:32:45 -0700301 self.ia_goal.append(In[0, 0])
302 self.ib_goal.append(In[1, 0])
303 self.ic_goal.append(In[2, 0])
304 self.estimated_velocity.append(estimated_velocity)
Brian Silverman6260c092018-01-14 15:21:36 -0800305
Ravago Jones5127ccc2022-07-31 16:32:45 -0700306 def log_data(self, X, U, current_time, Vn, i_goal):
307 self.ia.append(X[0, 0])
308 self.ib.append(X[1, 0])
309 self.ic.append(X[2, 0])
Brian Silverman6260c092018-01-14 15:21:36 -0800310
Ravago Jones5127ccc2022-07-31 16:32:45 -0700311 self.i_goal.append(i_goal)
Brian Silverman6260c092018-01-14 15:21:36 -0800312
Ravago Jones5127ccc2022-07-31 16:32:45 -0700313 self.isensea.append(X[5, 0])
314 self.isenseb.append(X[6, 0])
315 self.isensec.append(X[7, 0])
Brian Silverman6260c092018-01-14 15:21:36 -0800316
Ravago Jones5127ccc2022-07-31 16:32:45 -0700317 self.theta.append(X[3, 0])
318 self.omega.append(X[4, 0])
Brian Silverman6260c092018-01-14 15:21:36 -0800319
Ravago Jones5127ccc2022-07-31 16:32:45 -0700320 self.time.append(current_time)
Brian Silverman6260c092018-01-14 15:21:36 -0800321
Ravago Jones5127ccc2022-07-31 16:32:45 -0700322 self.van.append(Vn[0, 0])
323 self.vbn.append(Vn[1, 0])
324 self.vcn.append(Vn[2, 0])
Brian Silverman6260c092018-01-14 15:21:36 -0800325
Ravago Jones5127ccc2022-07-31 16:32:45 -0700326 if (self.U_last != U).any():
327 self.va.append(self.U_last[0, 0])
328 self.vb.append(self.U_last[1, 0])
329 self.vc.append(self.U_last[2, 0])
330 self.voltage_time.append(current_time)
Brian Silverman6260c092018-01-14 15:21:36 -0800331
Ravago Jones5127ccc2022-07-31 16:32:45 -0700332 self.va.append(U[0, 0])
333 self.vb.append(U[1, 0])
334 self.vc.append(U[2, 0])
335 self.voltage_time.append(current_time)
336 self.U_last = U.copy()
Brian Silverman6260c092018-01-14 15:21:36 -0800337
Ravago Jones5127ccc2022-07-31 16:32:45 -0700338 def plot(self):
339 fig = pylab.figure()
340 pylab.subplot(3, 1, 1)
341 pylab.plot(self.controls_time,
342 self.ia_controls,
343 'ro',
344 label='ia_controls')
345 pylab.plot(self.controls_time,
346 self.ib_controls,
347 'go',
348 label='ib_controls')
349 pylab.plot(self.controls_time,
350 self.ic_controls,
351 'bo',
352 label='ic_controls')
353 pylab.plot(self.controls_time, self.ia_goal, 'r--', label='ia_goal')
354 pylab.plot(self.controls_time, self.ib_goal, 'g--', label='ib_goal')
355 pylab.plot(self.controls_time, self.ic_goal, 'b--', label='ic_goal')
Brian Silverman6260c092018-01-14 15:21:36 -0800356
Ravago Jones5127ccc2022-07-31 16:32:45 -0700357 #pylab.plot(self.controls_time, self.ia_pred, 'r*', label='ia_pred')
358 #pylab.plot(self.controls_time, self.ib_pred, 'g*', label='ib_pred')
359 #pylab.plot(self.controls_time, self.ic_pred, 'b*', label='ic_pred')
360 pylab.plot(self.time, self.isensea, 'r:', label='ia_sense')
361 pylab.plot(self.time, self.isenseb, 'g:', label='ib_sense')
362 pylab.plot(self.time, self.isensec, 'b:', label='ic_sense')
363 pylab.plot(self.time, self.ia, 'r', label='ia')
364 pylab.plot(self.time, self.ib, 'g', label='ib')
365 pylab.plot(self.time, self.ic, 'b', label='ic')
366 pylab.plot(self.time, self.i_goal, label='i_goal')
367 if self.title is not None:
368 fig.canvas.set_window_title(self.title)
369 pylab.legend()
Brian Silverman6260c092018-01-14 15:21:36 -0800370
Ravago Jones5127ccc2022-07-31 16:32:45 -0700371 pylab.subplot(3, 1, 2)
372 pylab.plot(self.voltage_time, self.va, label='va')
373 pylab.plot(self.voltage_time, self.vb, label='vb')
374 pylab.plot(self.voltage_time, self.vc, label='vc')
375 pylab.plot(self.time, self.van, label='van')
376 pylab.plot(self.time, self.vbn, label='vbn')
377 pylab.plot(self.time, self.vcn, label='vcn')
378 pylab.plot(self.controls_time, self.ea, label='ea')
379 pylab.plot(self.controls_time, self.eb, label='eb')
380 pylab.plot(self.controls_time, self.ec, label='ec')
381 pylab.legend()
Brian Silverman6260c092018-01-14 15:21:36 -0800382
Ravago Jones5127ccc2022-07-31 16:32:45 -0700383 pylab.subplot(3, 1, 3)
384 pylab.plot(self.time, self.theta, label='theta')
385 pylab.plot(self.time, self.omega, label='omega')
386 #pylab.plot(self.controls_time, self.estimated_velocity, label='estimated omega')
Brian Silverman6260c092018-01-14 15:21:36 -0800387
Ravago Jones5127ccc2022-07-31 16:32:45 -0700388 pylab.legend()
389
390 fig = pylab.figure()
391 pylab.plot(self.controls_time,
392 map(operator.sub, self.ia_goal, self.ia_controls),
393 'r',
394 label='ia_error')
395 pylab.plot(self.controls_time,
396 map(operator.sub, self.ib_goal, self.ib_controls),
397 'g',
398 label='ib_error')
399 pylab.plot(self.controls_time,
400 map(operator.sub, self.ic_goal, self.ic_controls),
401 'b',
402 label='ic_error')
403 if self.title is not None:
404 fig.canvas.set_window_title(self.title)
405 pylab.legend()
406 pylab.show()
Brian Silverman6260c092018-01-14 15:21:36 -0800407
408
409# So, from running a bunch of math, we know the following:
410# Van + Vbn + Vcn = 0
411# ia + ib + ic = 0
412# ea + eb + ec = 0
413# d ia/dt + d ib/dt + d ic/dt = 0
414#
415# We also have:
416# [ Van ] [ 2/3 -1/3 -1/3] [Va]
417# [ Vbn ] = [ -1/3 2/3 -1/3] [Vb]
418# [ Vcn ] [ -1/3 -1/3 2/3] [Vc]
419#
420# or,
421#
422# Vabcn = Vconv * V
423#
424# The base equation is:
425#
426# [ Van ] [ R 0 0 ] [ ia ] [ L M M ] [ dia/dt ] [ ea ]
427# [ Vbn ] = [ 0 R 0 ] [ ib ] + [ M L M ] [ dib/dt ] + [ eb ]
428# [ Vbn ] [ 0 0 R ] [ ic ] [ M M L ] [ dic/dt ] [ ec ]
429#
430# or
431#
432# Vabcn = R_matrix * I + L_matrix * I_dot + E
433#
434# We can re-arrange this as:
435#
436# inv(L_matrix) * (Vconv * V - E - R_matrix * I) = I_dot
437# B * V - inv(L_matrix) * E - A * I = I_dot
438class Simulation(object):
Brian Silverman6260c092018-01-14 15:21:36 -0800439
Ravago Jones5127ccc2022-07-31 16:32:45 -0700440 def __init__(self):
441 self.R_matrix = numpy.matrix(numpy.eye(3)) * R
442 self.L_matrix = numpy.matrix([[L, M, M], [M, L, M], [M, M, L]])
443 self.L_matrix_inv = numpy.linalg.inv(self.L_matrix)
444 self.A = self.L_matrix_inv * self.R_matrix
445 self.B = self.L_matrix_inv * Vconv
446 self.A_discrete, self.B_discrete = controls.c2d(
447 -self.A, self.B, 1.0 / hz)
448 self.B_discrete_inverse = numpy.matrix(
449 numpy.eye(3)) / (self.B_discrete[0, 0] - self.B_discrete[1, 0])
Brian Silverman6260c092018-01-14 15:21:36 -0800450
Ravago Jones5127ccc2022-07-31 16:32:45 -0700451 self.R_model = R * 1.0
452 self.L_model = L * 1.0
453 self.M_model = M * 1.0
454 self.R_matrix_model = numpy.matrix(numpy.eye(3)) * self.R_model
455 self.L_matrix_model = numpy.matrix(
456 [[self.L_model, self.M_model, self.M_model],
457 [self.M_model, self.L_model, self.M_model],
458 [self.M_model, self.M_model, self.L_model]])
459 self.L_matrix_inv_model = numpy.linalg.inv(self.L_matrix_model)
460 self.A_model = self.L_matrix_inv_model * self.R_matrix_model
461 self.B_model = self.L_matrix_inv_model * Vconv
462 self.A_discrete_model, self.B_discrete_model = \
463 controls.c2d(-self.A_model, self.B_model, 1.0 / hz)
464 self.B_discrete_inverse_model = numpy.matrix(numpy.eye(3)) / (
465 self.B_discrete_model[0, 0] - self.B_discrete_model[1, 0])
Brian Silverman6260c092018-01-14 15:21:36 -0800466
Ravago Jones5127ccc2022-07-31 16:32:45 -0700467 print 'constexpr double kL = %g;' % self.L_model
468 print 'constexpr double kM = %g;' % self.M_model
469 print 'constexpr double kR = %g;' % self.R_model
470 print 'constexpr float kAdiscrete_diagonal = %gf;' % self.A_discrete_model[
471 0, 0]
472 print 'constexpr float kAdiscrete_offdiagonal = %gf;' % self.A_discrete_model[
473 1, 0]
474 print 'constexpr float kBdiscrete_inv_diagonal = %gf;' % self.B_discrete_inverse_model[
475 0, 0]
476 print 'constexpr float kBdiscrete_inv_offdiagonal = %gf;' % self.B_discrete_inverse_model[
477 1, 0]
478 print 'constexpr double kOneAmpScalar = %g;' % one_amp_scalar
479 print 'constexpr double kMaxOneAmpDrivingVoltage = %g;' % max_one_amp_driving_voltage
480 print('A_discrete', self.A_discrete)
481 print('B_discrete', self.B_discrete)
482 print('B_discrete_sub', numpy.linalg.inv(self.B_discrete[0:2, 0:2]))
483 print('B_discrete_inv', self.B_discrete_inverse)
Brian Silverman6260c092018-01-14 15:21:36 -0800484
Ravago Jones5127ccc2022-07-31 16:32:45 -0700485 # Xdot[5:, :] = (R_sense2 + R_sense1) / R_sense2 * (
486 # (1.0 / (R_sense1 * C_sense)) * (-Isense * R_sense2 / (R_sense1 + R_sense2) * (R_sense1 / R_sense2 + 1.0) + I))
487 self.mk1 = (R_sense2 + R_sense1) / R_sense2 * (1.0 /
488 (R_sense1 * C_sense))
489 self.mk2 = -self.mk1 * R_sense2 / (R_sense1 + R_sense2) * (
490 R_sense1 / R_sense2 + 1.0)
Brian Silverman6260c092018-01-14 15:21:36 -0800491
Ravago Jones5127ccc2022-07-31 16:32:45 -0700492 # ia, ib, ic, theta, omega, isensea, isenseb, isensec
493 self.X = numpy.matrix([[0.0], [0.0], [0.0], [-2.0 * numpy.pi / 3.0],
494 [0.0], [0.0], [0.0], [0.0]])
Brian Silverman6260c092018-01-14 15:21:36 -0800495
Ravago Jones5127ccc2022-07-31 16:32:45 -0700496 self.K = 0.05 * Vconv
497 print('A %s' % repr(self.A))
498 print('B %s' % repr(self.B))
499 print('K %s' % repr(self.K))
Brian Silverman6260c092018-01-14 15:21:36 -0800500
Ravago Jones5127ccc2022-07-31 16:32:45 -0700501 print('System poles are %s' % repr(numpy.linalg.eig(self.A)[0]))
502 print('Poles are %s' %
503 repr(numpy.linalg.eig(self.A - self.B * self.K)[0]))
Brian Silverman6260c092018-01-14 15:21:36 -0800504
Ravago Jones5127ccc2022-07-31 16:32:45 -0700505 controllability = controls.ctrb(self.A, self.B)
506 print('Rank of augmented controlability matrix. %d' %
507 numpy.linalg.matrix_rank(controllability))
Brian Silverman6260c092018-01-14 15:21:36 -0800508
Ravago Jones5127ccc2022-07-31 16:32:45 -0700509 self.data_logger = DataLogger(switching_pattern)
510 self.current_time = 0.0
Brian Silverman6260c092018-01-14 15:21:36 -0800511
Ravago Jones5127ccc2022-07-31 16:32:45 -0700512 self.estimated_velocity = self.X[4, 0]
Brian Silverman6260c092018-01-14 15:21:36 -0800513
Ravago Jones5127ccc2022-07-31 16:32:45 -0700514 def motor_diffeq(self, x, t, U):
515 I = numpy.matrix(x[0:3]).T
516 theta = x[3]
517 omega = x[4]
518 Isense = numpy.matrix(x[5:]).T
Brian Silverman6260c092018-01-14 15:21:36 -0800519
Ravago Jones5127ccc2022-07-31 16:32:45 -0700520 dflux = phases(f_single, theta) / Kv
Brian Silverman6260c092018-01-14 15:21:36 -0800521
Ravago Jones5127ccc2022-07-31 16:32:45 -0700522 Xdot = numpy.matrix(numpy.zeros((8, 1)))
523 di_dt = -self.A_model * I + self.B_model * U - self.L_matrix_inv_model * dflux * omega
524 torque = I.T * dflux
525 Xdot[0:3, :] = di_dt
526 Xdot[3, :] = omega
527 Xdot[4, :] = torque / J
Brian Silverman6260c092018-01-14 15:21:36 -0800528
Ravago Jones5127ccc2022-07-31 16:32:45 -0700529 Xdot[5:, :] = self.mk1 * I + self.mk2 * Isense
530 return numpy.squeeze(numpy.asarray(Xdot))
Brian Silverman6260c092018-01-14 15:21:36 -0800531
Ravago Jones5127ccc2022-07-31 16:32:45 -0700532 def DoControls(self, goal_current):
533 theta = self.X[3, 0]
534 # Use the actual angular velocity.
535 omega = self.X[4, 0]
Brian Silverman6260c092018-01-14 15:21:36 -0800536
Ravago Jones5127ccc2022-07-31 16:32:45 -0700537 measured_current = self.X[5:, :].copy()
538
539 # Ok, lets now fake it.
540 E_imag1 = numpy.exp(1j * theta) * K1 * numpy.matrix(
541 [[-1j], [-1j * numpy.exp(1j * numpy.pi * 2.0 / 3.0)],
Brian Silverman6260c092018-01-14 15:21:36 -0800542 [-1j * numpy.exp(-1j * numpy.pi * 2.0 / 3.0)]])
Ravago Jones5127ccc2022-07-31 16:32:45 -0700543 E_imag2 = numpy.exp(1j * 5.0 * theta) * K2 * numpy.matrix(
544 [[-1j], [-1j * numpy.exp(-1j * numpy.pi * 2.0 / 3.0)],
Brian Silverman6260c092018-01-14 15:21:36 -0800545 [-1j * numpy.exp(1j * numpy.pi * 2.0 / 3.0)]])
546
Ravago Jones5127ccc2022-07-31 16:32:45 -0700547 overall_measured_current = ((E_imag1 + E_imag2).real.T *
548 measured_current / one_amp_scalar)[0, 0]
Brian Silverman6260c092018-01-14 15:21:36 -0800549
Ravago Jones5127ccc2022-07-31 16:32:45 -0700550 current_error = goal_current - overall_measured_current
551 #print(current_error)
552 self.estimated_velocity += current_error * 1.0
553 omega = self.estimated_velocity
Brian Silverman6260c092018-01-14 15:21:36 -0800554
Ravago Jones5127ccc2022-07-31 16:32:45 -0700555 # Now, apply the transfer function of the inductor.
556 # Use that to difference the current across the cycle.
557 Icurrent = self.Ilast
558 # No history:
559 #Icurrent = phases(g_single, theta) * goal_current
560 Inext = phases(g_single, theta + omega * 1.0 / hz) * goal_current
Brian Silverman6260c092018-01-14 15:21:36 -0800561
Ravago Jones5127ccc2022-07-31 16:32:45 -0700562 deltaI = Inext - Icurrent
Brian Silverman6260c092018-01-14 15:21:36 -0800563
Ravago Jones5127ccc2022-07-31 16:32:45 -0700564 H1 = -numpy.linalg.inv(1j * omega * self.L_matrix +
565 self.R_matrix) * omega / Kv
566 H2 = -numpy.linalg.inv(1j * omega * 5.0 * self.L_matrix +
567 self.R_matrix) * omega / Kv
568 p_imag = H1 * E_imag1 + H2 * E_imag2
569 p_next_imag = numpy.exp(1j * omega * 1.0 / hz) * H1 * E_imag1 + \
570 numpy.exp(1j * omega * 5.0 * 1.0 / hz) * H2 * E_imag2
571 p = p_imag.real
Brian Silverman6260c092018-01-14 15:21:36 -0800572
Ravago Jones5127ccc2022-07-31 16:32:45 -0700573 # So, we now know how much the change in current is due to changes in BEMF.
574 # Subtract that, and then run the stock statespace equation.
575 Vn_ff = self.B_discrete_inverse * (Inext - self.A_discrete *
576 (Icurrent - p) - p_next_imag.real)
577 print 'Vn_ff', Vn_ff
578 print 'Inext', Inext
579 Vn = Vn_ff + self.K * (Icurrent - measured_current)
Brian Silverman6260c092018-01-14 15:21:36 -0800580
Ravago Jones5127ccc2022-07-31 16:32:45 -0700581 E = phases(f_single, self.X[3, 0]) / Kv * self.X[4, 0]
582 self.data_logger.log_controls(self.current_time, measured_current,
583 Icurrent, E, self.estimated_velocity)
Brian Silverman6260c092018-01-14 15:21:36 -0800584
Ravago Jones5127ccc2022-07-31 16:32:45 -0700585 self.Ilast = Inext
Brian Silverman6260c092018-01-14 15:21:36 -0800586
Ravago Jones5127ccc2022-07-31 16:32:45 -0700587 return Vn
Brian Silverman6260c092018-01-14 15:21:36 -0800588
Ravago Jones5127ccc2022-07-31 16:32:45 -0700589 def Simulate(self):
590 start_wall_time = time.time()
591 self.Ilast = numpy.matrix(numpy.zeros((3, 1)))
592 for n in range(200):
593 goal_current = 1.0
594 max_current = (
595 vcc - (self.X[4, 0] / Kv * 2.0)) / max_one_amp_driving_voltage
596 min_current = (
597 -vcc - (self.X[4, 0] / Kv * 2.0)) / max_one_amp_driving_voltage
598 goal_current = max(min_current, min(max_current, goal_current))
Brian Silverman6260c092018-01-14 15:21:36 -0800599
Ravago Jones5127ccc2022-07-31 16:32:45 -0700600 Vn = self.DoControls(goal_current)
Brian Silverman6260c092018-01-14 15:21:36 -0800601
Ravago Jones5127ccc2022-07-31 16:32:45 -0700602 #Vn = numpy.matrix([[1.00], [0.0], [0.0]])
603 Vn = numpy.matrix([[0.00], [1.00], [0.0]])
604 #Vn = numpy.matrix([[0.00], [0.0], [1.00]])
Brian Silverman6260c092018-01-14 15:21:36 -0800605
Ravago Jones5127ccc2022-07-31 16:32:45 -0700606 # T is the fractional rate.
607 T = Vn / vcc
608 tn = -numpy.min(T)
609 T += tn
610 if (T > 1.0).any():
611 T = T / numpy.max(T)
Brian Silverman6260c092018-01-14 15:21:36 -0800612
Ravago Jones5127ccc2022-07-31 16:32:45 -0700613 for t, U in sample_times(T=T,
614 dt=1.0 / hz,
615 n=10,
616 start_time=self.current_time):
617 # Analog amplifier mode!
618 #U = Vn
Brian Silverman6260c092018-01-14 15:21:36 -0800619
Ravago Jones5127ccc2022-07-31 16:32:45 -0700620 self.data_logger.log_data(self.X, (U - min(U)),
621 self.current_time, Vn, goal_current)
622 t_array = numpy.array([self.current_time, t])
623 self.X = numpy.matrix(
624 scipy.integrate.odeint(self.motor_diffeq,
625 numpy.squeeze(numpy.asarray(
626 self.X)),
627 t_array,
628 args=(U, )))[1, :].T
Brian Silverman6260c092018-01-14 15:21:36 -0800629
Ravago Jones5127ccc2022-07-31 16:32:45 -0700630 self.current_time = t
Brian Silverman6260c092018-01-14 15:21:36 -0800631
Ravago Jones5127ccc2022-07-31 16:32:45 -0700632 print 'Took %f to simulate' % (time.time() - start_wall_time)
Brian Silverman6260c092018-01-14 15:21:36 -0800633
Ravago Jones5127ccc2022-07-31 16:32:45 -0700634 self.data_logger.plot()
635
Brian Silverman6260c092018-01-14 15:21:36 -0800636
637simulation = Simulation()
638simulation.Simulate()