blob: f1248528f52d88bf2fe6582be0ed829c55250a29 [file] [log] [blame]
Austin Schuh3c542312013-02-24 01:53:50 -08001import controls
2import numpy
Austin Schuh572ff402015-11-08 12:17:50 -08003import os
Austin Schuh3c542312013-02-24 01:53:50 -08004
Austin Schuhbcce26a2018-03-26 23:41:24 -07005
Tyler Chatow6738c362019-02-16 14:12:30 -08006class Constant(object):
7
8 def __init__(self, name, formatt, value):
9 self.name = name
10 self.formatt = formatt
11 self.value = value
12 self.formatToType = {}
13 self.formatToType['%f'] = "double"
14 self.formatToType['%d'] = "int"
15
16 def Render(self, loop_type):
17 typestring = self.formatToType[self.formatt]
18 if loop_type == 'float' and typestring == 'double':
19 typestring = loop_type
20 return str("\nstatic constexpr %s %s = "+ self.formatt +";\n") % \
21 (typestring, self.name, self.value)
Ben Fredrickson1b45f782014-02-23 07:44:36 +000022
23
Austin Schuhe3490622013-03-13 01:24:30 -070024class ControlLoopWriter(object):
Austin Schuhe3490622013-03-13 01:24:30 -070025
Tyler Chatow6738c362019-02-16 14:12:30 -080026 def __init__(self,
27 gain_schedule_name,
28 loops,
29 namespaces=None,
30 write_constants=False,
31 plant_type='StateFeedbackPlant',
32 observer_type='StateFeedbackObserver',
33 scalar_type='double'):
34 """Constructs a control loop writer.
Austin Schuhe3490622013-03-13 01:24:30 -070035
Tyler Chatow6738c362019-02-16 14:12:30 -080036 Args:
37 gain_schedule_name: string, Name of the overall controller.
38 loops: array[ControlLoop], a list of control loops to gain schedule
39 in order.
40 namespaces: array[string], a list of names of namespaces to nest in
41 order. If None, the default will be used.
42 plant_type: string, The C++ type of the plant.
43 observer_type: string, The C++ type of the observer.
44 scalar_type: string, The C++ type of the base scalar.
45 """
46 self._gain_schedule_name = gain_schedule_name
47 self._loops = loops
48 if namespaces:
49 self._namespaces = namespaces
50 else:
51 self._namespaces = ['frc971', 'control_loops']
Austin Schuhe3490622013-03-13 01:24:30 -070052
Tyler Chatow6738c362019-02-16 14:12:30 -080053 self._namespace_start = '\n'.join(
54 ['namespace %s {' % name for name in self._namespaces])
Austin Schuh86093ad2016-02-06 14:29:34 -080055
Tyler Chatow6738c362019-02-16 14:12:30 -080056 self._namespace_end = '\n'.join([
57 '} // namespace %s' % name for name in reversed(self._namespaces)
58 ])
Austin Schuh25933852014-02-23 02:04:13 -080059
Tyler Chatow6738c362019-02-16 14:12:30 -080060 self._constant_list = []
61 self._plant_type = plant_type
62 self._observer_type = observer_type
63 self._scalar_type = scalar_type
Austin Schuh25933852014-02-23 02:04:13 -080064
Tyler Chatow6738c362019-02-16 14:12:30 -080065 def AddConstant(self, constant):
66 """Adds a constant to write.
Austin Schuhe3490622013-03-13 01:24:30 -070067
Tyler Chatow6738c362019-02-16 14:12:30 -080068 Args:
69 constant: Constant, the constant to add to the header.
70 """
71 self._constant_list.append(constant)
Brian Silvermane51ad632014-01-08 15:12:29 -080072
Tyler Chatow6738c362019-02-16 14:12:30 -080073 def _TopDirectory(self):
74 return self._namespaces[0]
Austin Schuhe3490622013-03-13 01:24:30 -070075
Tyler Chatow6738c362019-02-16 14:12:30 -080076 def _HeaderGuard(self, header_file):
77 return ('_'.join([namespace.upper() for namespace in self._namespaces])
78 + '_' + os.path.basename(header_file).upper().replace(
79 '.', '_').replace('/', '_') + '_')
Austin Schuhe3490622013-03-13 01:24:30 -070080
Tyler Chatow6738c362019-02-16 14:12:30 -080081 def Write(self, header_file, cc_file):
82 """Writes the loops to the specified files."""
83 self.WriteHeader(header_file)
84 self.WriteCC(os.path.basename(header_file), cc_file)
Austin Schuhe3490622013-03-13 01:24:30 -070085
Tyler Chatow6738c362019-02-16 14:12:30 -080086 def _GenericType(self, typename, extra_args=None):
87 """Returns a loop template using typename for the type."""
88 num_states = self._loops[0].A.shape[0]
89 num_inputs = self._loops[0].B.shape[1]
90 num_outputs = self._loops[0].C.shape[0]
91 if extra_args is not None:
92 extra_args = ', ' + extra_args
93 else:
94 extra_args = ''
95 if self._scalar_type != 'double':
96 extra_args += ', ' + self._scalar_type
97 return '%s<%d, %d, %d%s>' % (typename, num_states, num_inputs,
98 num_outputs, extra_args)
Austin Schuh32501832017-02-25 18:32:56 -080099
Tyler Chatow6738c362019-02-16 14:12:30 -0800100 def _ControllerType(self):
101 """Returns a template name for StateFeedbackController."""
102 return self._GenericType('StateFeedbackController')
Austin Schuhe3490622013-03-13 01:24:30 -0700103
Tyler Chatow6738c362019-02-16 14:12:30 -0800104 def _ObserverType(self):
105 """Returns a template name for StateFeedbackObserver."""
106 return self._GenericType(self._observer_type)
Austin Schuh20388b62017-11-23 22:40:46 -0800107
Tyler Chatow6738c362019-02-16 14:12:30 -0800108 def _LoopType(self):
109 """Returns a template name for StateFeedbackLoop."""
110 num_states = self._loops[0].A.shape[0]
111 num_inputs = self._loops[0].B.shape[1]
112 num_outputs = self._loops[0].C.shape[0]
Austin Schuh20388b62017-11-23 22:40:46 -0800113
Tyler Chatow6738c362019-02-16 14:12:30 -0800114 return 'StateFeedbackLoop<%d, %d, %d, %s, %s, %s>' % (
115 num_states, num_inputs, num_outputs, self._scalar_type,
116 self._PlantType(), self._ObserverType())
Austin Schuhe3490622013-03-13 01:24:30 -0700117
Tyler Chatow6738c362019-02-16 14:12:30 -0800118 def _PlantType(self):
119 """Returns a template name for StateFeedbackPlant."""
120 return self._GenericType(self._plant_type)
Austin Schuhe3490622013-03-13 01:24:30 -0700121
Tyler Chatow6738c362019-02-16 14:12:30 -0800122 def _PlantCoeffType(self):
123 """Returns a template name for StateFeedbackPlantCoefficients."""
124 return self._GenericType(self._plant_type + 'Coefficients')
Austin Schuhe3490622013-03-13 01:24:30 -0700125
Tyler Chatow6738c362019-02-16 14:12:30 -0800126 def _ControllerCoeffType(self):
127 """Returns a template name for StateFeedbackControllerCoefficients."""
128 return self._GenericType('StateFeedbackControllerCoefficients')
Austin Schuh32501832017-02-25 18:32:56 -0800129
Tyler Chatow6738c362019-02-16 14:12:30 -0800130 def _ObserverCoeffType(self):
131 """Returns a template name for StateFeedbackObserverCoefficients."""
132 return self._GenericType(self._observer_type + 'Coefficients')
Austin Schuh32501832017-02-25 18:32:56 -0800133
Tyler Chatow6738c362019-02-16 14:12:30 -0800134 def WriteHeader(self, header_file):
135 """Writes the header file to the file named header_file."""
136 with open(header_file, 'w') as fd:
137 header_guard = self._HeaderGuard(header_file)
138 fd.write('#ifndef %s\n'
139 '#define %s\n\n' % (header_guard, header_guard))
140 fd.write(
141 '#include \"frc971/control_loops/state_feedback_loop.h\"\n')
142 if (self._plant_type == 'StateFeedbackHybridPlant' or
143 self._observer_type == 'HybridKalman'):
144 fd.write(
145 '#include \"frc971/control_loops/hybrid_state_feedback_loop.h\"\n'
146 )
Austin Schuh4cc4fe22017-11-23 19:13:09 -0800147
Tyler Chatow6738c362019-02-16 14:12:30 -0800148 fd.write('\n')
Austin Schuhe3490622013-03-13 01:24:30 -0700149
Tyler Chatow6738c362019-02-16 14:12:30 -0800150 fd.write(self._namespace_start)
Ben Fredrickson1b45f782014-02-23 07:44:36 +0000151
Tyler Chatow6738c362019-02-16 14:12:30 -0800152 for const in self._constant_list:
153 fd.write(const.Render(self._scalar_type))
Ben Fredrickson1b45f782014-02-23 07:44:36 +0000154
Tyler Chatow6738c362019-02-16 14:12:30 -0800155 fd.write('\n\n')
156 for loop in self._loops:
157 fd.write(loop.DumpPlantHeader(self._PlantCoeffType()))
158 fd.write('\n')
159 fd.write(loop.DumpControllerHeader(self._scalar_type))
160 fd.write('\n')
161 fd.write(loop.DumpObserverHeader(self._ObserverCoeffType()))
162 fd.write('\n')
Austin Schuhe3490622013-03-13 01:24:30 -0700163
Tyler Chatow6738c362019-02-16 14:12:30 -0800164 fd.write('%s Make%sPlant();\n\n' % (self._PlantType(),
165 self._gain_schedule_name))
Austin Schuhe3490622013-03-13 01:24:30 -0700166
Tyler Chatow6738c362019-02-16 14:12:30 -0800167 fd.write('%s Make%sController();\n\n' % (self._ControllerType(),
168 self._gain_schedule_name))
Austin Schuh32501832017-02-25 18:32:56 -0800169
Tyler Chatow6738c362019-02-16 14:12:30 -0800170 fd.write('%s Make%sObserver();\n\n' % (self._ObserverType(),
171 self._gain_schedule_name))
Austin Schuh32501832017-02-25 18:32:56 -0800172
Tyler Chatow6738c362019-02-16 14:12:30 -0800173 fd.write('%s Make%sLoop();\n\n' % (self._LoopType(),
174 self._gain_schedule_name))
Austin Schuhe3490622013-03-13 01:24:30 -0700175
Tyler Chatow6738c362019-02-16 14:12:30 -0800176 fd.write(self._namespace_end)
177 fd.write('\n\n')
178 fd.write("#endif // %s\n" % header_guard)
Austin Schuhe3490622013-03-13 01:24:30 -0700179
Tyler Chatow6738c362019-02-16 14:12:30 -0800180 def WriteCC(self, header_file_name, cc_file):
181 """Writes the cc file to the file named cc_file."""
182 with open(cc_file, 'w') as fd:
183 fd.write('#include \"%s/%s\"\n' % (os.path.join(*self._namespaces),
184 header_file_name))
185 fd.write('\n')
186 fd.write('#include <vector>\n')
187 fd.write('\n')
188 fd.write(
189 '#include \"frc971/control_loops/state_feedback_loop.h\"\n')
190 fd.write('\n')
191 fd.write(self._namespace_start)
192 fd.write('\n\n')
193 for loop in self._loops:
194 fd.write(
195 loop.DumpPlant(self._PlantCoeffType(), self._scalar_type))
196 fd.write('\n')
Austin Schuhe3490622013-03-13 01:24:30 -0700197
Tyler Chatow6738c362019-02-16 14:12:30 -0800198 for loop in self._loops:
199 fd.write(loop.DumpController(self._scalar_type))
200 fd.write('\n')
Austin Schuhe3490622013-03-13 01:24:30 -0700201
Tyler Chatow6738c362019-02-16 14:12:30 -0800202 for loop in self._loops:
203 fd.write(
204 loop.DumpObserver(self._ObserverCoeffType(),
205 self._scalar_type))
206 fd.write('\n')
Austin Schuh32501832017-02-25 18:32:56 -0800207
Tyler Chatow6738c362019-02-16 14:12:30 -0800208 fd.write('%s Make%sPlant() {\n' % (self._PlantType(),
209 self._gain_schedule_name))
210 fd.write(' ::std::vector< ::std::unique_ptr<%s>> plants(%d);\n' %
211 (self._PlantCoeffType(), len(self._loops)))
212 for index, loop in enumerate(self._loops):
213 fd.write(' plants[%d] = ::std::unique_ptr<%s>(new %s(%s));\n' %
214 (index, self._PlantCoeffType(), self._PlantCoeffType(),
215 loop.PlantFunction()))
216 fd.write(' return %s(&plants);\n' % self._PlantType())
217 fd.write('}\n\n')
Austin Schuhe3490622013-03-13 01:24:30 -0700218
Tyler Chatow6738c362019-02-16 14:12:30 -0800219 fd.write('%s Make%sController() {\n' % (self._ControllerType(),
220 self._gain_schedule_name))
221 fd.write(
222 ' ::std::vector< ::std::unique_ptr<%s>> controllers(%d);\n' %
223 (self._ControllerCoeffType(), len(self._loops)))
224 for index, loop in enumerate(self._loops):
225 fd.write(
226 ' controllers[%d] = ::std::unique_ptr<%s>(new %s(%s));\n' %
227 (index, self._ControllerCoeffType(),
228 self._ControllerCoeffType(), loop.ControllerFunction()))
229 fd.write(' return %s(&controllers);\n' % self._ControllerType())
230 fd.write('}\n\n')
Austin Schuh32501832017-02-25 18:32:56 -0800231
Tyler Chatow6738c362019-02-16 14:12:30 -0800232 fd.write('%s Make%sObserver() {\n' % (self._ObserverType(),
233 self._gain_schedule_name))
234 fd.write(' ::std::vector< ::std::unique_ptr<%s>> observers(%d);\n'
235 % (self._ObserverCoeffType(), len(self._loops)))
236 for index, loop in enumerate(self._loops):
237 fd.write(
238 ' observers[%d] = ::std::unique_ptr<%s>(new %s(%s));\n'
239 % (index, self._ObserverCoeffType(),
240 self._ObserverCoeffType(), loop.ObserverFunction()))
241 fd.write(' return %s(&observers);\n' % self._ObserverType())
242 fd.write('}\n\n')
Austin Schuh32501832017-02-25 18:32:56 -0800243
Tyler Chatow6738c362019-02-16 14:12:30 -0800244 fd.write('%s Make%sLoop() {\n' % (self._LoopType(),
245 self._gain_schedule_name))
246 fd.write(
247 ' return %s(Make%sPlant(), Make%sController(), Make%sObserver());\n'
248 % (self._LoopType(), self._gain_schedule_name,
249 self._gain_schedule_name, self._gain_schedule_name))
250 fd.write('}\n\n')
Austin Schuhe3490622013-03-13 01:24:30 -0700251
Tyler Chatow6738c362019-02-16 14:12:30 -0800252 fd.write(self._namespace_end)
253 fd.write('\n')
Austin Schuhe3490622013-03-13 01:24:30 -0700254
255
Austin Schuh3c542312013-02-24 01:53:50 -0800256class ControlLoop(object):
Austin Schuh3c542312013-02-24 01:53:50 -0800257
Tyler Chatow6738c362019-02-16 14:12:30 -0800258 def __init__(self, name):
259 """Constructs a control loop object.
Austin Schuh3c542312013-02-24 01:53:50 -0800260
Tyler Chatow6738c362019-02-16 14:12:30 -0800261 Args:
262 name: string, The name of the loop to use when writing the C++ files.
263 """
264 self._name = name
Austin Schuhb5d302f2019-01-20 20:51:19 -0800265
Tyler Chatow6738c362019-02-16 14:12:30 -0800266 @property
267 def name(self):
268 """Returns the name"""
269 return self._name
Austin Schuh3c542312013-02-24 01:53:50 -0800270
Tyler Chatow6738c362019-02-16 14:12:30 -0800271 def ContinuousToDiscrete(self, A_continuous, B_continuous, dt):
272 """Calculates the discrete time values for A and B.
Austin Schuhc1f68892013-03-16 17:06:27 -0700273
Tyler Chatow6738c362019-02-16 14:12:30 -0800274 Args:
275 A_continuous: numpy.matrix, The continuous time A matrix
276 B_continuous: numpy.matrix, The continuous time B matrix
277 dt: float, The time step of the control loop
Austin Schuhc1f68892013-03-16 17:06:27 -0700278
Tyler Chatow6738c362019-02-16 14:12:30 -0800279 Returns:
280 (A, B), numpy.matrix, the control matricies.
281 """
282 return controls.c2d(A_continuous, B_continuous, dt)
Austin Schuh3c542312013-02-24 01:53:50 -0800283
Tyler Chatow6738c362019-02-16 14:12:30 -0800284 def InitializeState(self):
285 """Sets X, Y, and X_hat to zero defaults."""
286 self.X = numpy.zeros((self.A.shape[0], 1))
287 self.Y = self.C * self.X
288 self.X_hat = numpy.zeros((self.A.shape[0], 1))
Austin Schuh3c542312013-02-24 01:53:50 -0800289
Tyler Chatow6738c362019-02-16 14:12:30 -0800290 def PlaceControllerPoles(self, poles):
291 """Places the controller poles.
Austin Schuh3c542312013-02-24 01:53:50 -0800292
Tyler Chatow6738c362019-02-16 14:12:30 -0800293 Args:
294 poles: array, An array of poles. Must be complex conjegates if they have
295 any imaginary portions.
296 """
297 self.K = controls.dplace(self.A, self.B, poles)
Austin Schuh3c542312013-02-24 01:53:50 -0800298
Tyler Chatow6738c362019-02-16 14:12:30 -0800299 def PlaceObserverPoles(self, poles):
300 """Places the observer poles.
Austin Schuh3c542312013-02-24 01:53:50 -0800301
Tyler Chatow6738c362019-02-16 14:12:30 -0800302 Args:
303 poles: array, An array of poles. Must be complex conjegates if they have
304 any imaginary portions.
305 """
306 self.L = controls.dplace(self.A.T, self.C.T, poles).T
Sabina Davis3922dfa2018-02-10 23:10:05 -0800307
Tyler Chatow6738c362019-02-16 14:12:30 -0800308 def Update(self, U):
309 """Simulates one time step with the provided U."""
310 #U = numpy.clip(U, self.U_min, self.U_max)
311 self.X = self.A * self.X + self.B * U
312 self.Y = self.C * self.X + self.D * U
Austin Schuh3c542312013-02-24 01:53:50 -0800313
Tyler Chatow6738c362019-02-16 14:12:30 -0800314 def PredictObserver(self, U):
315 """Runs the predict step of the observer update."""
316 self.X_hat = (self.A * self.X_hat + self.B * U)
Austin Schuh1a387962015-01-31 16:36:20 -0800317
Tyler Chatow6738c362019-02-16 14:12:30 -0800318 def CorrectObserver(self, U):
319 """Runs the correct step of the observer update."""
320 if hasattr(self, 'KalmanGain'):
321 KalmanGain = self.KalmanGain
322 else:
323 KalmanGain = numpy.linalg.inv(self.A) * self.L
324 self.X_hat += KalmanGain * (self.Y - self.C * self.X_hat - self.D * U)
Austin Schuh1a387962015-01-31 16:36:20 -0800325
Tyler Chatow6738c362019-02-16 14:12:30 -0800326 def UpdateObserver(self, U):
327 """Updates the observer given the provided U."""
328 if hasattr(self, 'KalmanGain'):
329 KalmanGain = self.KalmanGain
330 else:
331 KalmanGain = numpy.linalg.inv(self.A) * self.L
332 self.X_hat = (self.A * self.X_hat + self.B * U + self.A * KalmanGain *
333 (self.Y - self.C * self.X_hat - self.D * U))
Austin Schuh3c542312013-02-24 01:53:50 -0800334
Tyler Chatow6738c362019-02-16 14:12:30 -0800335 def _DumpMatrix(self, matrix_name, matrix, scalar_type):
336 """Dumps the provided matrix into a variable called matrix_name.
Austin Schuh3c542312013-02-24 01:53:50 -0800337
Tyler Chatow6738c362019-02-16 14:12:30 -0800338 Args:
339 matrix_name: string, The variable name to save the matrix to.
340 matrix: The matrix to dump.
341 scalar_type: The C++ type to use for the scalar in the matrix.
Austin Schuh3c542312013-02-24 01:53:50 -0800342
Tyler Chatow6738c362019-02-16 14:12:30 -0800343 Returns:
344 string, The C++ commands required to populate a variable named matrix_name
345 with the contents of matrix.
346 """
347 ans = [
348 ' Eigen::Matrix<%s, %d, %d> %s;\n' % (scalar_type, matrix.shape[0],
349 matrix.shape[1], matrix_name)
350 ]
351 for x in xrange(matrix.shape[0]):
352 for y in xrange(matrix.shape[1]):
353 write_type = repr(matrix[x, y])
354 if scalar_type == 'float':
355 if '.' not in write_type:
356 write_type += '.0'
357 write_type += 'f'
358 ans.append(
359 ' %s(%d, %d) = %s;\n' % (matrix_name, x, y, write_type))
Austin Schuh3c542312013-02-24 01:53:50 -0800360
Tyler Chatow6738c362019-02-16 14:12:30 -0800361 return ''.join(ans)
Austin Schuh3c542312013-02-24 01:53:50 -0800362
Tyler Chatow6738c362019-02-16 14:12:30 -0800363 def DumpPlantHeader(self, plant_coefficient_type):
364 """Writes out a c++ header declaration which will create a Plant object.
Austin Schuh3c542312013-02-24 01:53:50 -0800365
Tyler Chatow6738c362019-02-16 14:12:30 -0800366 Returns:
367 string, The header declaration for the function.
368 """
369 return '%s Make%sPlantCoefficients();\n' % (plant_coefficient_type,
370 self._name)
Austin Schuh3c542312013-02-24 01:53:50 -0800371
Tyler Chatow6738c362019-02-16 14:12:30 -0800372 def DumpPlant(self, plant_coefficient_type, scalar_type):
373 """Writes out a c++ function which will create a PlantCoefficients object.
Austin Schuh3c542312013-02-24 01:53:50 -0800374
Tyler Chatow6738c362019-02-16 14:12:30 -0800375 Returns:
376 string, The function which will create the object.
377 """
378 ans = [
379 '%s Make%sPlantCoefficients() {\n' % (plant_coefficient_type,
380 self._name)
381 ]
Austin Schuh3c542312013-02-24 01:53:50 -0800382
Tyler Chatow6738c362019-02-16 14:12:30 -0800383 ans.append(self._DumpMatrix('C', self.C, scalar_type))
384 ans.append(self._DumpMatrix('D', self.D, scalar_type))
385 ans.append(self._DumpMatrix('U_max', self.U_max, scalar_type))
386 ans.append(self._DumpMatrix('U_min', self.U_min, scalar_type))
Austin Schuh3c542312013-02-24 01:53:50 -0800387
Tyler Chatow6738c362019-02-16 14:12:30 -0800388 if plant_coefficient_type.startswith('StateFeedbackPlant'):
389 ans.append(self._DumpMatrix('A', self.A, scalar_type))
390 ans.append(self._DumpMatrix('B', self.B, scalar_type))
391 ans.append(
392 ' return %s'
393 '(A, B, C, D, U_max, U_min);\n' % (plant_coefficient_type))
394 elif plant_coefficient_type.startswith('StateFeedbackHybridPlant'):
395 ans.append(
396 self._DumpMatrix('A_continuous', self.A_continuous,
397 scalar_type))
398 ans.append(
399 self._DumpMatrix('B_continuous', self.B_continuous,
400 scalar_type))
401 ans.append(' return %s'
402 '(A_continuous, B_continuous, C, D, U_max, U_min);\n' %
403 (plant_coefficient_type))
404 else:
405 glog.fatal('Unsupported plant type %s', plant_coefficient_type)
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800406
Tyler Chatow6738c362019-02-16 14:12:30 -0800407 ans.append('}\n')
408 return ''.join(ans)
Austin Schuh3c542312013-02-24 01:53:50 -0800409
Tyler Chatow6738c362019-02-16 14:12:30 -0800410 def PlantFunction(self):
411 """Returns the name of the plant coefficient function."""
412 return 'Make%sPlantCoefficients()' % self._name
Austin Schuh3c542312013-02-24 01:53:50 -0800413
Tyler Chatow6738c362019-02-16 14:12:30 -0800414 def ControllerFunction(self):
415 """Returns the name of the controller function."""
416 return 'Make%sControllerCoefficients()' % self._name
Austin Schuh32501832017-02-25 18:32:56 -0800417
Tyler Chatow6738c362019-02-16 14:12:30 -0800418 def ObserverFunction(self):
419 """Returns the name of the controller function."""
420 return 'Make%sObserverCoefficients()' % self._name
Austin Schuhe3490622013-03-13 01:24:30 -0700421
Tyler Chatow6738c362019-02-16 14:12:30 -0800422 def DumpControllerHeader(self, scalar_type):
423 """Writes out a c++ header declaration which will create a Controller object.
Austin Schuh3c542312013-02-24 01:53:50 -0800424
Tyler Chatow6738c362019-02-16 14:12:30 -0800425 Returns:
426 string, The header declaration for the function.
427 """
428 num_states = self.A.shape[0]
429 num_inputs = self.B.shape[1]
430 num_outputs = self.C.shape[0]
431 return 'StateFeedbackControllerCoefficients<%d, %d, %d, %s> %s;\n' % (
432 num_states, num_inputs, num_outputs, scalar_type,
433 self.ControllerFunction())
Austin Schuh3c542312013-02-24 01:53:50 -0800434
Tyler Chatow6738c362019-02-16 14:12:30 -0800435 def DumpController(self, scalar_type):
436 """Returns a c++ function which will create a Controller object.
Austin Schuh3c542312013-02-24 01:53:50 -0800437
Tyler Chatow6738c362019-02-16 14:12:30 -0800438 Returns:
439 string, The function which will create the object.
440 """
441 num_states = self.A.shape[0]
442 num_inputs = self.B.shape[1]
443 num_outputs = self.C.shape[0]
444 ans = [
445 'StateFeedbackControllerCoefficients<%d, %d, %d, %s> %s {\n' %
446 (num_states, num_inputs, num_outputs, scalar_type,
447 self.ControllerFunction())
448 ]
Austin Schuh3c542312013-02-24 01:53:50 -0800449
Tyler Chatow6738c362019-02-16 14:12:30 -0800450 ans.append(self._DumpMatrix('K', self.K, scalar_type))
451 if not hasattr(self, 'Kff'):
452 self.Kff = numpy.matrix(numpy.zeros(self.K.shape))
Austin Schuh86093ad2016-02-06 14:29:34 -0800453
Tyler Chatow6738c362019-02-16 14:12:30 -0800454 ans.append(self._DumpMatrix('Kff', self.Kff, scalar_type))
Austin Schuh3c542312013-02-24 01:53:50 -0800455
Tyler Chatow6738c362019-02-16 14:12:30 -0800456 ans.append(
457 ' return StateFeedbackControllerCoefficients<%d, %d, %d, %s>'
458 '(K, Kff);\n' % (num_states, num_inputs, num_outputs, scalar_type))
459 ans.append('}\n')
460 return ''.join(ans)
Austin Schuh32501832017-02-25 18:32:56 -0800461
Tyler Chatow6738c362019-02-16 14:12:30 -0800462 def DumpObserverHeader(self, observer_coefficient_type):
463 """Writes out a c++ header declaration which will create a Observer object.
Austin Schuh32501832017-02-25 18:32:56 -0800464
Tyler Chatow6738c362019-02-16 14:12:30 -0800465 Returns:
466 string, The header declaration for the function.
467 """
468 return '%s %s;\n' % (observer_coefficient_type, self.ObserverFunction())
Austin Schuh32501832017-02-25 18:32:56 -0800469
Tyler Chatow6738c362019-02-16 14:12:30 -0800470 def DumpObserver(self, observer_coefficient_type, scalar_type):
471 """Returns a c++ function which will create a Observer object.
Austin Schuh32501832017-02-25 18:32:56 -0800472
Tyler Chatow6738c362019-02-16 14:12:30 -0800473 Returns:
474 string, The function which will create the object.
475 """
476 ans = [
477 '%s %s {\n' % (observer_coefficient_type, self.ObserverFunction())
478 ]
Austin Schuh32501832017-02-25 18:32:56 -0800479
Tyler Chatow6738c362019-02-16 14:12:30 -0800480 if observer_coefficient_type.startswith('StateFeedbackObserver'):
481 if hasattr(self, 'KalmanGain'):
482 KalmanGain = self.KalmanGain
483 Q = self.Q
484 R = self.R
485 else:
486 KalmanGain = numpy.linalg.inv(self.A) * self.L
487 Q = numpy.zeros(self.A.shape)
488 R = numpy.zeros((self.C.shape[0], self.C.shape[0]))
489 ans.append(self._DumpMatrix('KalmanGain', KalmanGain, scalar_type))
490 ans.append(self._DumpMatrix('Q', Q, scalar_type))
491 ans.append(self._DumpMatrix('R', R, scalar_type))
492 ans.append(' return %s(KalmanGain, Q, R);\n' %
493 (observer_coefficient_type,))
Sabina Davis3922dfa2018-02-10 23:10:05 -0800494
Tyler Chatow6738c362019-02-16 14:12:30 -0800495 elif observer_coefficient_type.startswith('HybridKalman'):
496 ans.append(
497 self._DumpMatrix('Q_continuous', self.Q_continuous,
498 scalar_type))
499 ans.append(
500 self._DumpMatrix('R_continuous', self.R_continuous,
501 scalar_type))
502 ans.append(
503 self._DumpMatrix('P_steady_state', self.P_steady_state,
504 scalar_type))
505 ans.append(
506 ' return %s(Q_continuous, R_continuous, P_steady_state);\n' %
507 (observer_coefficient_type,))
508 else:
509 glog.fatal('Unsupported observer type %s',
510 observer_coefficient_type)
Austin Schuh32501832017-02-25 18:32:56 -0800511
Tyler Chatow6738c362019-02-16 14:12:30 -0800512 ans.append('}\n')
513 return ''.join(ans)
514
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800515
516class HybridControlLoop(ControlLoop):
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800517
Tyler Chatow6738c362019-02-16 14:12:30 -0800518 def __init__(self, name):
519 super(HybridControlLoop, self).__init__(name=name)
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800520
Tyler Chatow6738c362019-02-16 14:12:30 -0800521 def Discretize(self, dt):
522 [self.A, self.B, self.Q, self.R] = \
523 controls.kalmd(self.A_continuous, self.B_continuous,
524 self.Q_continuous, self.R_continuous, dt)
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800525
Tyler Chatow6738c362019-02-16 14:12:30 -0800526 def PredictHybridObserver(self, U, dt):
527 self.Discretize(dt)
528 self.X_hat = self.A * self.X_hat + self.B * U
529 self.P = (self.A * self.P * self.A.T + self.Q)
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800530
Tyler Chatow6738c362019-02-16 14:12:30 -0800531 def CorrectHybridObserver(self, U):
532 Y_bar = self.Y - self.C * self.X_hat
533 C_t = self.C.T
534 S = self.C * self.P * C_t + self.R
535 self.KalmanGain = self.P * C_t * numpy.linalg.inv(S)
536 self.X_hat = self.X_hat + self.KalmanGain * Y_bar
537 self.P = (numpy.eye(len(self.A)) - self.KalmanGain * self.C) * self.P
538
539 def InitializeState(self):
540 super(HybridControlLoop, self).InitializeState()
541 if hasattr(self, 'Q_steady_state'):
542 self.P = self.Q_steady_state
543 else:
544 self.P = numpy.matrix(
545 numpy.zeros((self.A.shape[0], self.A.shape[0])))
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800546
547
548class CIM(object):
Tyler Chatow6738c362019-02-16 14:12:30 -0800549
550 def __init__(self):
551 # Stall Torque in N m
552 self.stall_torque = 2.42
553 # Stall Current in Amps
554 self.stall_current = 133.0
555 # Free Speed in rad/s
556 self.free_speed = 5500.0 / 60.0 * 2.0 * numpy.pi
557 # Free Current in Amps
558 self.free_current = 4.7
559 # Resistance of the motor
560 self.resistance = 12.0 / self.stall_current
561 # Motor velocity constant
562 self.Kv = (
563 self.free_speed / (12.0 - self.resistance * self.free_current))
564 # Torque constant
565 self.Kt = self.stall_torque / self.stall_current
Lee Mracek97fc8af2018-01-13 04:38:52 -0500566
567
568class MiniCIM(object):
Tyler Chatow6738c362019-02-16 14:12:30 -0800569
570 def __init__(self):
571 # Stall Torque in N m
572 self.stall_torque = 1.41
573 # Stall Current in Amps
574 self.stall_current = 89.0
575 # Free Speed in rad/s
576 self.free_speed = 5840.0 / 60.0 * 2.0 * numpy.pi
577 # Free Current in Amps
578 self.free_current = 3.0
579 # Resistance of the motor
580 self.resistance = 12.0 / self.stall_current
581 # Motor velocity constant
582 self.Kv = (
583 self.free_speed / (12.0 - self.resistance * self.free_current))
584 # Torque constant
585 self.Kt = self.stall_torque / self.stall_current
Austin Schuhf173eb82018-01-20 23:32:30 -0800586
587
Austin Schuhb5d302f2019-01-20 20:51:19 -0800588class NMotor(object):
Tyler Chatow6738c362019-02-16 14:12:30 -0800589
Austin Schuhb5d302f2019-01-20 20:51:19 -0800590 def __init__(self, motor, n):
591 """Gangs together n motors."""
592 self.motor = motor
593 self.stall_torque = motor.stall_torque * n
594 self.stall_current = motor.stall_current * n
595 self.free_speed = motor.free_speed
596
597 self.free_current = motor.free_current * n
598 self.resistance = motor.resistance / n
599 self.Kv = motor.Kv
600 self.Kt = motor.Kt
Austin Schuh36bb8e32019-02-18 15:02:57 -0800601 self.motor_inertia = motor.motor_inertia * n
Austin Schuhb5d302f2019-01-20 20:51:19 -0800602
603
604class Vex775Pro(object):
Tyler Chatow6738c362019-02-16 14:12:30 -0800605
Austin Schuhb5d302f2019-01-20 20:51:19 -0800606 def __init__(self):
607 # Stall Torque in N m
608 self.stall_torque = 0.71
609 # Stall Current in Amps
610 self.stall_current = 134.0
611 # Free Speed in rad/s
612 self.free_speed = 18730.0 / 60.0 * 2.0 * numpy.pi
613 # Free Current in Amps
614 self.free_current = 0.7
615 # Resistance of the motor
616 self.resistance = 12.0 / self.stall_current
617 # Motor velocity constant
Tyler Chatow6738c362019-02-16 14:12:30 -0800618 self.Kv = (
619 self.free_speed / (12.0 - self.resistance * self.free_current))
Austin Schuhb5d302f2019-01-20 20:51:19 -0800620 # Torque constant
621 self.Kt = self.stall_torque / self.stall_current
622 # Motor inertia in kg m^2
623 self.motor_inertia = 0.00001187
624
625
Austin Schuhf173eb82018-01-20 23:32:30 -0800626class BAG(object):
Tyler Chatow6738c362019-02-16 14:12:30 -0800627 # BAG motor specs available at http://motors.vex.com/vexpro-motors/bag-motor
628 def __init__(self):
629 # Stall Torque in (N m)
630 self.stall_torque = 0.43
631 # Stall Current in (Amps)
632 self.stall_current = 53.0
633 # Free Speed in (rad/s)
634 self.free_speed = 13180.0 / 60.0 * 2.0 * numpy.pi
635 # Free Current in (Amps)
636 self.free_current = 1.8
637 # Resistance of the motor (Ohms)
638 self.resistance = 12.0 / self.stall_current
639 # Motor velocity constant (radians / (sec * volt))
640 self.Kv = (
641 self.free_speed / (12.0 - self.resistance * self.free_current))
642 # Torque constant (N * m / A)
643 self.Kt = self.stall_torque / self.stall_current
644 # Motor inertia in kg m^2
645 self.motor_inertia = 0.000006
646
Brian Silverman6260c092018-01-14 15:21:36 -0800647
648class MN3510(object):
Tyler Chatow6738c362019-02-16 14:12:30 -0800649
650 def __init__(self):
651 # http://www.robotshop.com/en/t-motor-navigator-mn3510-360kv-brushless-motor.html#Specifications
652 # Free Current in Amps
653 self.free_current = 0.0
654 # Resistance of the motor
655 self.resistance = 0.188
656 # Stall Current in Amps
657 self.stall_current = 14.0 / self.resistance
658 # Motor velocity constant
659 self.Kv = 360.0 / 60.0 * (2.0 * numpy.pi)
660 # Torque constant Nm / A
661 self.Kt = 1.0 / self.Kv
662 # Stall Torque in N m
663 self.stall_torque = self.Kt * self.stall_current
James Kuszmaulef0c18a2020-01-12 15:44:20 -0800664
665
666class Falcon(object):
667 """Class representing the VexPro Falcon 500 motor.
668
669 All numbers based on data from
670 https://www.vexrobotics.com/vexpro/falcon-500."""
671
672 def __init__(self):
673 # Stall Torque in N m
674 self.stall_torque = 4.69
675 # Stall Current in Amps
676 self.stall_current = 257.0
677 # Free Speed in rad / sec
678 self.free_speed = 6380.0 / 60.0 * 2.0 * numpy.pi
679 # Free Current in Amps
680 self.free_current = 1.5
681 # Resistance of the motor, divided by 2 to account for the 2 motors
682 self.resistance = 12.0 / self.stall_current
683 # Motor velocity constant
684 self.Kv = (self.free_speed /
685 (12.0 - self.resistance * self.free_current))
686 # Torque constant
687 self.Kt = self.stall_torque / self.stall_current
Austin Schuhc1c957a2020-02-20 17:47:58 -0800688 # Motor inertia in kg m^2
689 # Diameter of 1.9", weight of: 100 grams
690 # TODO(austin): Get a number from Scott Westbrook for the mass
691 self.motor_inertia = 0.1 * ((0.95 * 0.0254) ** 2.0)