blob: e62bff9f800ce1098c9fdd77f1cdea6f756f9f5b [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
Ben Fredrickson1b45f782014-02-23 07:44:36 +00005class Constant(object):
Austin Schuh1a387962015-01-31 16:36:20 -08006 def __init__ (self, name, formatt, value):
7 self.name = name
8 self.formatt = formatt
9 self.value = value
10 self.formatToType = {}
Brian Silverman4e55e582015-11-10 14:16:37 -050011 self.formatToType['%f'] = "double"
12 self.formatToType['%d'] = "int"
Austin Schuh1a387962015-01-31 16:36:20 -080013 def __str__ (self):
14 return str("\nstatic constexpr %s %s = "+ self.formatt +";\n") % \
15 (self.formatToType[self.formatt], self.name, self.value)
Ben Fredrickson1b45f782014-02-23 07:44:36 +000016
17
Austin Schuhe3490622013-03-13 01:24:30 -070018class ControlLoopWriter(object):
Austin Schuh3ad5ed82017-02-25 21:36:19 -080019 def __init__(self, gain_schedule_name, loops, namespaces=None,
20 write_constants=False, plant_type='StateFeedbackPlant',
Austin Schuh20388b62017-11-23 22:40:46 -080021 observer_type='StateFeedbackObserver',
22 scalar_type='double'):
Austin Schuhe3490622013-03-13 01:24:30 -070023 """Constructs a control loop writer.
24
25 Args:
26 gain_schedule_name: string, Name of the overall controller.
27 loops: array[ControlLoop], a list of control loops to gain schedule
28 in order.
29 namespaces: array[string], a list of names of namespaces to nest in
30 order. If None, the default will be used.
Austin Schuh3ad5ed82017-02-25 21:36:19 -080031 plant_type: string, The C++ type of the plant.
32 observer_type: string, The C++ type of the observer.
Austin Schuh20388b62017-11-23 22:40:46 -080033 scalar_type: string, The C++ type of the base scalar.
Austin Schuhe3490622013-03-13 01:24:30 -070034 """
35 self._gain_schedule_name = gain_schedule_name
36 self._loops = loops
37 if namespaces:
38 self._namespaces = namespaces
39 else:
40 self._namespaces = ['frc971', 'control_loops']
41
42 self._namespace_start = '\n'.join(
43 ['namespace %s {' % name for name in self._namespaces])
44
45 self._namespace_end = '\n'.join(
46 ['} // namespace %s' % name for name in reversed(self._namespaces)])
Austin Schuh86093ad2016-02-06 14:29:34 -080047
Ben Fredrickson1b45f782014-02-23 07:44:36 +000048 self._constant_list = []
Austin Schuh3ad5ed82017-02-25 21:36:19 -080049 self._plant_type = plant_type
50 self._observer_type = observer_type
Austin Schuh20388b62017-11-23 22:40:46 -080051 self._scalar_type = scalar_type
Austin Schuh25933852014-02-23 02:04:13 -080052
53 def AddConstant(self, constant):
54 """Adds a constant to write.
55
56 Args:
57 constant: Constant, the constant to add to the header.
58 """
59 self._constant_list.append(constant)
Austin Schuhe3490622013-03-13 01:24:30 -070060
Brian Silvermane51ad632014-01-08 15:12:29 -080061 def _TopDirectory(self):
62 return self._namespaces[0]
63
Austin Schuhe3490622013-03-13 01:24:30 -070064 def _HeaderGuard(self, header_file):
Austin Schuh16cf47a2015-11-28 13:20:33 -080065 return ('_'.join([namespace.upper() for namespace in self._namespaces]) + '_' +
Austin Schuh572ff402015-11-08 12:17:50 -080066 os.path.basename(header_file).upper()
67 .replace('.', '_').replace('/', '_') + '_')
Austin Schuhe3490622013-03-13 01:24:30 -070068
69 def Write(self, header_file, cc_file):
70 """Writes the loops to the specified files."""
71 self.WriteHeader(header_file)
Austin Schuh572ff402015-11-08 12:17:50 -080072 self.WriteCC(os.path.basename(header_file), cc_file)
Austin Schuhe3490622013-03-13 01:24:30 -070073
Austin Schuh3ad5ed82017-02-25 21:36:19 -080074 def _GenericType(self, typename, extra_args=None):
Austin Schuhe3490622013-03-13 01:24:30 -070075 """Returns a loop template using typename for the type."""
76 num_states = self._loops[0].A.shape[0]
77 num_inputs = self._loops[0].B.shape[1]
78 num_outputs = self._loops[0].C.shape[0]
Austin Schuh3ad5ed82017-02-25 21:36:19 -080079 if extra_args is not None:
80 extra_args = ', ' + extra_args
81 else:
82 extra_args = ''
Austin Schuh20388b62017-11-23 22:40:46 -080083 if self._scalar_type != 'double':
84 extra_args += ', ' + self._scalar_type
Austin Schuh3ad5ed82017-02-25 21:36:19 -080085 return '%s<%d, %d, %d%s>' % (
86 typename, num_states, num_inputs, num_outputs, extra_args)
Austin Schuhe3490622013-03-13 01:24:30 -070087
88 def _ControllerType(self):
Austin Schuh32501832017-02-25 18:32:56 -080089 """Returns a template name for StateFeedbackController."""
90 return self._GenericType('StateFeedbackController')
91
92 def _ObserverType(self):
93 """Returns a template name for StateFeedbackObserver."""
Austin Schuh3ad5ed82017-02-25 21:36:19 -080094 return self._GenericType(self._observer_type)
Austin Schuhe3490622013-03-13 01:24:30 -070095
96 def _LoopType(self):
97 """Returns a template name for StateFeedbackLoop."""
Austin Schuh20388b62017-11-23 22:40:46 -080098 num_states = self._loops[0].A.shape[0]
99 num_inputs = self._loops[0].B.shape[1]
100 num_outputs = self._loops[0].C.shape[0]
101
102 return 'StateFeedbackLoop<%d, %d, %d, %s, %s, %s>' % (
103 num_states,
104 num_inputs,
105 num_outputs, self._scalar_type,
106 self._PlantType(), self._ObserverType())
107
Austin Schuhe3490622013-03-13 01:24:30 -0700108
109 def _PlantType(self):
110 """Returns a template name for StateFeedbackPlant."""
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800111 return self._GenericType(self._plant_type)
Austin Schuhe3490622013-03-13 01:24:30 -0700112
Austin Schuh32501832017-02-25 18:32:56 -0800113 def _PlantCoeffType(self):
Austin Schuhe3490622013-03-13 01:24:30 -0700114 """Returns a template name for StateFeedbackPlantCoefficients."""
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800115 return self._GenericType(self._plant_type + 'Coefficients')
Austin Schuhe3490622013-03-13 01:24:30 -0700116
Austin Schuh32501832017-02-25 18:32:56 -0800117 def _ControllerCoeffType(self):
118 """Returns a template name for StateFeedbackControllerCoefficients."""
119 return self._GenericType('StateFeedbackControllerCoefficients')
120
121 def _ObserverCoeffType(self):
122 """Returns a template name for StateFeedbackObserverCoefficients."""
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800123 return self._GenericType(self._observer_type + 'Coefficients')
Austin Schuh32501832017-02-25 18:32:56 -0800124
Austin Schuh20388b62017-11-23 22:40:46 -0800125 def WriteHeader(self, header_file):
126 """Writes the header file to the file named header_file."""
Austin Schuhe3490622013-03-13 01:24:30 -0700127 with open(header_file, 'w') as fd:
128 header_guard = self._HeaderGuard(header_file)
129 fd.write('#ifndef %s\n'
130 '#define %s\n\n' % (header_guard, header_guard))
131 fd.write('#include \"frc971/control_loops/state_feedback_loop.h\"\n')
Austin Schuh4cc4fe22017-11-23 19:13:09 -0800132 if (self._plant_type == 'StateFeedbackHybridPlant' or
133 self._observer_type == 'HybridKalman'):
134 fd.write('#include \"frc971/control_loops/hybrid_state_feedback_loop.h\"\n')
135
Austin Schuhe3490622013-03-13 01:24:30 -0700136 fd.write('\n')
137
138 fd.write(self._namespace_start)
Ben Fredrickson1b45f782014-02-23 07:44:36 +0000139
140 for const in self._constant_list:
141 fd.write(str(const))
142
Austin Schuhe3490622013-03-13 01:24:30 -0700143 fd.write('\n\n')
144 for loop in self._loops:
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800145 fd.write(loop.DumpPlantHeader(self._PlantCoeffType()))
Austin Schuhe3490622013-03-13 01:24:30 -0700146 fd.write('\n')
Austin Schuh20388b62017-11-23 22:40:46 -0800147 fd.write(loop.DumpControllerHeader(self._scalar_type))
Austin Schuhe3490622013-03-13 01:24:30 -0700148 fd.write('\n')
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800149 fd.write(loop.DumpObserverHeader(self._ObserverCoeffType()))
Austin Schuh32501832017-02-25 18:32:56 -0800150 fd.write('\n')
Austin Schuhe3490622013-03-13 01:24:30 -0700151
152 fd.write('%s Make%sPlant();\n\n' %
153 (self._PlantType(), self._gain_schedule_name))
154
Austin Schuh32501832017-02-25 18:32:56 -0800155 fd.write('%s Make%sController();\n\n' %
156 (self._ControllerType(), self._gain_schedule_name))
157
158 fd.write('%s Make%sObserver();\n\n' %
159 (self._ObserverType(), self._gain_schedule_name))
160
Austin Schuhe3490622013-03-13 01:24:30 -0700161 fd.write('%s Make%sLoop();\n\n' %
162 (self._LoopType(), self._gain_schedule_name))
163
164 fd.write(self._namespace_end)
165 fd.write('\n\n')
166 fd.write("#endif // %s\n" % header_guard)
167
168 def WriteCC(self, header_file_name, cc_file):
169 """Writes the cc file to the file named cc_file."""
170 with open(cc_file, 'w') as fd:
Austin Schuh572ff402015-11-08 12:17:50 -0800171 fd.write('#include \"%s/%s\"\n' %
172 (os.path.join(*self._namespaces), header_file_name))
Austin Schuhe3490622013-03-13 01:24:30 -0700173 fd.write('\n')
174 fd.write('#include <vector>\n')
175 fd.write('\n')
176 fd.write('#include \"frc971/control_loops/state_feedback_loop.h\"\n')
177 fd.write('\n')
178 fd.write(self._namespace_start)
179 fd.write('\n\n')
180 for loop in self._loops:
Austin Schuh20388b62017-11-23 22:40:46 -0800181 fd.write(loop.DumpPlant(self._PlantCoeffType(), self._scalar_type))
Austin Schuhe3490622013-03-13 01:24:30 -0700182 fd.write('\n')
183
184 for loop in self._loops:
Austin Schuh20388b62017-11-23 22:40:46 -0800185 fd.write(loop.DumpController(self._scalar_type))
Austin Schuhe3490622013-03-13 01:24:30 -0700186 fd.write('\n')
187
Austin Schuh32501832017-02-25 18:32:56 -0800188 for loop in self._loops:
Austin Schuh20388b62017-11-23 22:40:46 -0800189 fd.write(loop.DumpObserver(self._ObserverCoeffType(), self._scalar_type))
Austin Schuh32501832017-02-25 18:32:56 -0800190 fd.write('\n')
191
Austin Schuhe3490622013-03-13 01:24:30 -0700192 fd.write('%s Make%sPlant() {\n' %
193 (self._PlantType(), self._gain_schedule_name))
Austin Schuh1a387962015-01-31 16:36:20 -0800194 fd.write(' ::std::vector< ::std::unique_ptr<%s>> plants(%d);\n' % (
Austin Schuh32501832017-02-25 18:32:56 -0800195 self._PlantCoeffType(), len(self._loops)))
Austin Schuhe3490622013-03-13 01:24:30 -0700196 for index, loop in enumerate(self._loops):
Austin Schuh1a387962015-01-31 16:36:20 -0800197 fd.write(' plants[%d] = ::std::unique_ptr<%s>(new %s(%s));\n' %
Austin Schuh32501832017-02-25 18:32:56 -0800198 (index, self._PlantCoeffType(), self._PlantCoeffType(),
Austin Schuhe3490622013-03-13 01:24:30 -0700199 loop.PlantFunction()))
Austin Schuh1a387962015-01-31 16:36:20 -0800200 fd.write(' return %s(&plants);\n' % self._PlantType())
Austin Schuhe3490622013-03-13 01:24:30 -0700201 fd.write('}\n\n')
202
Austin Schuh32501832017-02-25 18:32:56 -0800203 fd.write('%s Make%sController() {\n' %
204 (self._ControllerType(), self._gain_schedule_name))
Austin Schuh1a387962015-01-31 16:36:20 -0800205 fd.write(' ::std::vector< ::std::unique_ptr<%s>> controllers(%d);\n' % (
Austin Schuh32501832017-02-25 18:32:56 -0800206 self._ControllerCoeffType(), len(self._loops)))
Austin Schuhe3490622013-03-13 01:24:30 -0700207 for index, loop in enumerate(self._loops):
Austin Schuh1a387962015-01-31 16:36:20 -0800208 fd.write(' controllers[%d] = ::std::unique_ptr<%s>(new %s(%s));\n' %
Austin Schuh32501832017-02-25 18:32:56 -0800209 (index, self._ControllerCoeffType(), self._ControllerCoeffType(),
Austin Schuhe3490622013-03-13 01:24:30 -0700210 loop.ControllerFunction()))
Austin Schuh32501832017-02-25 18:32:56 -0800211 fd.write(' return %s(&controllers);\n' % self._ControllerType())
212 fd.write('}\n\n')
213
214 fd.write('%s Make%sObserver() {\n' %
215 (self._ObserverType(), self._gain_schedule_name))
216 fd.write(' ::std::vector< ::std::unique_ptr<%s>> observers(%d);\n' % (
217 self._ObserverCoeffType(), len(self._loops)))
218 for index, loop in enumerate(self._loops):
219 fd.write(' observers[%d] = ::std::unique_ptr<%s>(new %s(%s));\n' %
220 (index, self._ObserverCoeffType(), self._ObserverCoeffType(),
221 loop.ObserverFunction()))
222 fd.write(' return %s(&observers);\n' % self._ObserverType())
223 fd.write('}\n\n')
224
225 fd.write('%s Make%sLoop() {\n' %
226 (self._LoopType(), self._gain_schedule_name))
227 fd.write(' return %s(Make%sPlant(), Make%sController(), Make%sObserver());\n' %
228 (self._LoopType(), self._gain_schedule_name,
229 self._gain_schedule_name, self._gain_schedule_name))
Austin Schuhe3490622013-03-13 01:24:30 -0700230 fd.write('}\n\n')
231
232 fd.write(self._namespace_end)
233 fd.write('\n')
234
235
Austin Schuh3c542312013-02-24 01:53:50 -0800236class ControlLoop(object):
237 def __init__(self, name):
238 """Constructs a control loop object.
239
240 Args:
241 name: string, The name of the loop to use when writing the C++ files.
242 """
243 self._name = name
244
Austin Schuhc1f68892013-03-16 17:06:27 -0700245 def ContinuousToDiscrete(self, A_continuous, B_continuous, dt):
246 """Calculates the discrete time values for A and B.
Austin Schuh3c542312013-02-24 01:53:50 -0800247
248 Args:
249 A_continuous: numpy.matrix, The continuous time A matrix
250 B_continuous: numpy.matrix, The continuous time B matrix
251 dt: float, The time step of the control loop
Austin Schuhc1f68892013-03-16 17:06:27 -0700252
253 Returns:
254 (A, B), numpy.matrix, the control matricies.
Austin Schuh3c542312013-02-24 01:53:50 -0800255 """
Austin Schuhc1f68892013-03-16 17:06:27 -0700256 return controls.c2d(A_continuous, B_continuous, dt)
257
258 def InitializeState(self):
259 """Sets X, Y, and X_hat to zero defaults."""
Austin Schuh3c542312013-02-24 01:53:50 -0800260 self.X = numpy.zeros((self.A.shape[0], 1))
Austin Schuhc1f68892013-03-16 17:06:27 -0700261 self.Y = self.C * self.X
Austin Schuh3c542312013-02-24 01:53:50 -0800262 self.X_hat = numpy.zeros((self.A.shape[0], 1))
263
264 def PlaceControllerPoles(self, poles):
265 """Places the controller poles.
266
267 Args:
268 poles: array, An array of poles. Must be complex conjegates if they have
269 any imaginary portions.
270 """
271 self.K = controls.dplace(self.A, self.B, poles)
272
273 def PlaceObserverPoles(self, poles):
274 """Places the observer poles.
275
276 Args:
277 poles: array, An array of poles. Must be complex conjegates if they have
278 any imaginary portions.
279 """
280 self.L = controls.dplace(self.A.T, self.C.T, poles).T
281
Sabina Davis3922dfa2018-02-10 23:10:05 -0800282
Austin Schuh3c542312013-02-24 01:53:50 -0800283 def Update(self, U):
284 """Simulates one time step with the provided U."""
Austin Schuh1d005732015-03-01 00:10:20 -0800285 #U = numpy.clip(U, self.U_min, self.U_max)
Austin Schuh3c542312013-02-24 01:53:50 -0800286 self.X = self.A * self.X + self.B * U
287 self.Y = self.C * self.X + self.D * U
288
Austin Schuh1a387962015-01-31 16:36:20 -0800289 def PredictObserver(self, U):
290 """Runs the predict step of the observer update."""
291 self.X_hat = (self.A * self.X_hat + self.B * U)
292
293 def CorrectObserver(self, U):
294 """Runs the correct step of the observer update."""
Austin Schuhf173eb82018-01-20 23:32:30 -0800295 if hasattr(self, 'KalmanGain'):
296 KalmanGain = self.KalmanGain
297 else:
298 KalmanGain = numpy.linalg.inv(self.A) * self.L
299 self.X_hat += KalmanGain * (self.Y - self.C * self.X_hat - self.D * U)
Austin Schuh1a387962015-01-31 16:36:20 -0800300
Austin Schuh3c542312013-02-24 01:53:50 -0800301 def UpdateObserver(self, U):
302 """Updates the observer given the provided U."""
Sabina Davis3922dfa2018-02-10 23:10:05 -0800303 if hasattr(self, 'KalmanGain'):
304 KalmanGain = self.KalmanGain
305 else:
306 KalmanGain = numpy.linalg.inv(self.A) * self.L
Austin Schuh3c542312013-02-24 01:53:50 -0800307 self.X_hat = (self.A * self.X_hat + self.B * U +
Sabina Davis3922dfa2018-02-10 23:10:05 -0800308 self.A * KalmanGain * (self.Y - self.C * self.X_hat - self.D * U))
Austin Schuh3c542312013-02-24 01:53:50 -0800309
Austin Schuh20388b62017-11-23 22:40:46 -0800310 def _DumpMatrix(self, matrix_name, matrix, scalar_type):
Austin Schuh3c542312013-02-24 01:53:50 -0800311 """Dumps the provided matrix into a variable called matrix_name.
312
313 Args:
314 matrix_name: string, The variable name to save the matrix to.
315 matrix: The matrix to dump.
Austin Schuh20388b62017-11-23 22:40:46 -0800316 scalar_type: The C++ type to use for the scalar in the matrix.
Austin Schuh3c542312013-02-24 01:53:50 -0800317
318 Returns:
319 string, The C++ commands required to populate a variable named matrix_name
320 with the contents of matrix.
321 """
Austin Schuh20388b62017-11-23 22:40:46 -0800322 ans = [' Eigen::Matrix<%s, %d, %d> %s;\n' % (
323 scalar_type, matrix.shape[0], matrix.shape[1], matrix_name)]
Brian Silverman0f637382013-03-03 17:44:46 -0800324 for x in xrange(matrix.shape[0]):
325 for y in xrange(matrix.shape[1]):
Austin Schuh20388b62017-11-23 22:40:46 -0800326 write_type = repr(matrix[x, y])
327 if scalar_type == 'float':
328 write_type += 'f'
329 ans.append(' %s(%d, %d) = %s;\n' % (matrix_name, x, y, write_type))
Austin Schuh3c542312013-02-24 01:53:50 -0800330
Austin Schuhe3490622013-03-13 01:24:30 -0700331 return ''.join(ans)
Austin Schuh3c542312013-02-24 01:53:50 -0800332
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800333 def DumpPlantHeader(self, plant_coefficient_type):
Austin Schuh3c542312013-02-24 01:53:50 -0800334 """Writes out a c++ header declaration which will create a Plant object.
335
Austin Schuh3c542312013-02-24 01:53:50 -0800336 Returns:
337 string, The header declaration for the function.
338 """
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800339 return '%s Make%sPlantCoefficients();\n' % (
340 plant_coefficient_type, self._name)
Austin Schuh3c542312013-02-24 01:53:50 -0800341
Austin Schuh20388b62017-11-23 22:40:46 -0800342 def DumpPlant(self, plant_coefficient_type, scalar_type):
Austin Schuhe3490622013-03-13 01:24:30 -0700343 """Writes out a c++ function which will create a PlantCoefficients object.
Austin Schuh3c542312013-02-24 01:53:50 -0800344
345 Returns:
346 string, The function which will create the object.
347 """
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800348 ans = ['%s Make%sPlantCoefficients() {\n' % (
349 plant_coefficient_type, self._name)]
Austin Schuh3c542312013-02-24 01:53:50 -0800350
Austin Schuh20388b62017-11-23 22:40:46 -0800351 ans.append(self._DumpMatrix('C', self.C, scalar_type))
352 ans.append(self._DumpMatrix('D', self.D, scalar_type))
353 ans.append(self._DumpMatrix('U_max', self.U_max, scalar_type))
354 ans.append(self._DumpMatrix('U_min', self.U_min, scalar_type))
Austin Schuh3c542312013-02-24 01:53:50 -0800355
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800356 if plant_coefficient_type.startswith('StateFeedbackPlant'):
Austin Schuh20388b62017-11-23 22:40:46 -0800357 ans.append(self._DumpMatrix('A', self.A, scalar_type))
Austin Schuh20388b62017-11-23 22:40:46 -0800358 ans.append(self._DumpMatrix('B', self.B, scalar_type))
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800359 ans.append(' return %s'
Sabina Davis3922dfa2018-02-10 23:10:05 -0800360 '(A, B, C, D, U_max, U_min);\n' % (
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800361 plant_coefficient_type))
362 elif plant_coefficient_type.startswith('StateFeedbackHybridPlant'):
Austin Schuh20388b62017-11-23 22:40:46 -0800363 ans.append(self._DumpMatrix('A_continuous', self.A_continuous, scalar_type))
364 ans.append(self._DumpMatrix('B_continuous', self.B_continuous, scalar_type))
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800365 ans.append(' return %s'
366 '(A_continuous, B_continuous, C, D, U_max, U_min);\n' % (
367 plant_coefficient_type))
368 else:
369 glog.fatal('Unsupported plant type %s', plant_coefficient_type)
370
Austin Schuhe3490622013-03-13 01:24:30 -0700371 ans.append('}\n')
372 return ''.join(ans)
Austin Schuh3c542312013-02-24 01:53:50 -0800373
Austin Schuhe3490622013-03-13 01:24:30 -0700374 def PlantFunction(self):
375 """Returns the name of the plant coefficient function."""
376 return 'Make%sPlantCoefficients()' % self._name
Austin Schuh3c542312013-02-24 01:53:50 -0800377
Austin Schuhe3490622013-03-13 01:24:30 -0700378 def ControllerFunction(self):
379 """Returns the name of the controller function."""
Austin Schuh32501832017-02-25 18:32:56 -0800380 return 'Make%sControllerCoefficients()' % self._name
381
382 def ObserverFunction(self):
383 """Returns the name of the controller function."""
384 return 'Make%sObserverCoefficients()' % self._name
Austin Schuhe3490622013-03-13 01:24:30 -0700385
Austin Schuh20388b62017-11-23 22:40:46 -0800386 def DumpControllerHeader(self, scalar_type):
Austin Schuhe3490622013-03-13 01:24:30 -0700387 """Writes out a c++ header declaration which will create a Controller object.
Austin Schuh3c542312013-02-24 01:53:50 -0800388
389 Returns:
390 string, The header declaration for the function.
391 """
392 num_states = self.A.shape[0]
393 num_inputs = self.B.shape[1]
394 num_outputs = self.C.shape[0]
Austin Schuh20388b62017-11-23 22:40:46 -0800395 return 'StateFeedbackControllerCoefficients<%d, %d, %d, %s> %s;\n' % (
396 num_states, num_inputs, num_outputs, scalar_type,
397 self.ControllerFunction())
Austin Schuh3c542312013-02-24 01:53:50 -0800398
Austin Schuh20388b62017-11-23 22:40:46 -0800399 def DumpController(self, scalar_type):
Austin Schuhe3490622013-03-13 01:24:30 -0700400 """Returns a c++ function which will create a Controller object.
Austin Schuh3c542312013-02-24 01:53:50 -0800401
402 Returns:
403 string, The function which will create the object.
404 """
405 num_states = self.A.shape[0]
406 num_inputs = self.B.shape[1]
407 num_outputs = self.C.shape[0]
Austin Schuh20388b62017-11-23 22:40:46 -0800408 ans = ['StateFeedbackControllerCoefficients<%d, %d, %d, %s> %s {\n' % (
409 num_states, num_inputs, num_outputs, scalar_type,
410 self.ControllerFunction())]
Austin Schuh3c542312013-02-24 01:53:50 -0800411
Austin Schuh20388b62017-11-23 22:40:46 -0800412 ans.append(self._DumpMatrix('K', self.K, scalar_type))
Austin Schuh86093ad2016-02-06 14:29:34 -0800413 if not hasattr(self, 'Kff'):
414 self.Kff = numpy.matrix(numpy.zeros(self.K.shape))
415
Austin Schuh20388b62017-11-23 22:40:46 -0800416 ans.append(self._DumpMatrix('Kff', self.Kff, scalar_type))
Austin Schuh3c542312013-02-24 01:53:50 -0800417
Austin Schuh20388b62017-11-23 22:40:46 -0800418 ans.append(' return StateFeedbackControllerCoefficients<%d, %d, %d, %s>'
Austin Schuh32501832017-02-25 18:32:56 -0800419 '(K, Kff);\n' % (
Austin Schuh20388b62017-11-23 22:40:46 -0800420 num_states, num_inputs, num_outputs, scalar_type))
Austin Schuhe3490622013-03-13 01:24:30 -0700421 ans.append('}\n')
422 return ''.join(ans)
Austin Schuh32501832017-02-25 18:32:56 -0800423
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800424 def DumpObserverHeader(self, observer_coefficient_type):
Austin Schuh32501832017-02-25 18:32:56 -0800425 """Writes out a c++ header declaration which will create a Observer object.
426
427 Returns:
428 string, The header declaration for the function.
429 """
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800430 return '%s %s;\n' % (
431 observer_coefficient_type, self.ObserverFunction())
Austin Schuh32501832017-02-25 18:32:56 -0800432
Austin Schuh20388b62017-11-23 22:40:46 -0800433 def DumpObserver(self, observer_coefficient_type, scalar_type):
Austin Schuh32501832017-02-25 18:32:56 -0800434 """Returns a c++ function which will create a Observer object.
435
436 Returns:
437 string, The function which will create the object.
438 """
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800439 ans = ['%s %s {\n' % (
440 observer_coefficient_type, self.ObserverFunction())]
Austin Schuh32501832017-02-25 18:32:56 -0800441
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800442 if observer_coefficient_type.startswith('StateFeedbackObserver'):
Sabina Davis3922dfa2018-02-10 23:10:05 -0800443 if hasattr(self, 'KalmanGain'):
444 KalmanGain = self.KalmanGain
445 else:
446 KalmanGain = numpy.linalg.inv(self.A) * self.L
447 ans.append(self._DumpMatrix('KalmanGain', KalmanGain, scalar_type))
448 ans.append(' return %s(KalmanGain);\n' % (observer_coefficient_type,))
449
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800450 elif observer_coefficient_type.startswith('HybridKalman'):
Austin Schuh20388b62017-11-23 22:40:46 -0800451 ans.append(self._DumpMatrix('Q_continuous', self.Q_continuous, scalar_type))
452 ans.append(self._DumpMatrix('R_continuous', self.R_continuous, scalar_type))
453 ans.append(self._DumpMatrix('P_steady_state', self.P_steady_state, scalar_type))
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800454 ans.append(' return %s(Q_continuous, R_continuous, P_steady_state);\n' % (
455 observer_coefficient_type,))
Brian Silvermana3a20cc2017-03-05 18:35:20 -0800456 else:
457 glog.fatal('Unsupported observer type %s', observer_coefficient_type)
Austin Schuh32501832017-02-25 18:32:56 -0800458
Austin Schuh32501832017-02-25 18:32:56 -0800459 ans.append('}\n')
460 return ''.join(ans)
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800461
462class HybridControlLoop(ControlLoop):
463 def __init__(self, name):
464 super(HybridControlLoop, self).__init__(name=name)
465
Brian Silverman59c829a2017-03-05 18:36:54 -0800466 def Discretize(self, dt):
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800467 [self.A, self.B, self.Q, self.R] = \
468 controls.kalmd(self.A_continuous, self.B_continuous,
469 self.Q_continuous, self.R_continuous, dt)
470
471 def PredictHybridObserver(self, U, dt):
Brian Silverman59c829a2017-03-05 18:36:54 -0800472 self.Discretize(dt)
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800473 self.X_hat = self.A * self.X_hat + self.B * U
474 self.P = (self.A * self.P * self.A.T + self.Q)
475
476 def CorrectHybridObserver(self, U):
477 Y_bar = self.Y - self.C * self.X_hat
478 C_t = self.C.T
479 S = self.C * self.P * C_t + self.R
480 self.KalmanGain = self.P * C_t * numpy.linalg.inv(S)
481 self.X_hat = self.X_hat + self.KalmanGain * Y_bar
482 self.P = (numpy.eye(len(self.A)) - self.KalmanGain * self.C) * self.P
483
484 def InitializeState(self):
485 super(HybridControlLoop, self).InitializeState()
486 if hasattr(self, 'Q_steady_state'):
487 self.P = self.Q_steady_state
488 else:
489 self.P = numpy.matrix(numpy.zeros((self.A.shape[0], self.A.shape[0])))
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800490
491
492class CIM(object):
493 def __init__(self):
494 # Stall Torque in N m
495 self.stall_torque = 2.42
496 # Stall Current in Amps
497 self.stall_current = 133.0
498 # Free Speed in rad/s
499 self.free_speed = 5500.0 / 60.0 * 2.0 * numpy.pi
500 # Free Current in Amps
501 self.free_current = 4.7
502 # Resistance of the motor
503 self.resistance = 12.0 / self.stall_current
504 # Motor velocity constant
505 self.Kv = (self.free_speed / (12.0 - self.resistance * self.free_current))
506 # Torque constant
507 self.Kt = self.stall_torque / self.stall_current
Lee Mracek97fc8af2018-01-13 04:38:52 -0500508
509
510class MiniCIM(object):
511 def __init__(self):
512 # Stall Torque in N m
513 self.stall_torque = 1.41
514 # Stall Current in Amps
515 self.stall_current = 89.0
516 # Free Speed in rad/s
517 self.free_speed = 5840.0 / 60.0 * 2.0 * numpy.pi
518 # Free Current in Amps
519 self.free_current = 3.0
520 # Resistance of the motor
521 self.resistance = 12.0 / self.stall_current
522 # Motor velocity constant
523 self.Kv = (self.free_speed / (12.0 - self.resistance * self.free_current))
524 # Torque constant
525 self.Kt = self.stall_torque / self.stall_current
Austin Schuhf173eb82018-01-20 23:32:30 -0800526
527
528class BAG(object):
529 # BAG motor specs available at http://motors.vex.com/vexpro-motors/bag-motor
530 def __init__(self):
531 # Stall Torque in (N m)
532 self.stall_torque = 0.43
533 # Stall Current in (Amps)
534 self.stall_current = 53.0
535 # Free Speed in (rad/s)
536 self.free_speed = 13180.0 / 60.0 * 2.0 * numpy.pi
537 # Free Current in (Amps)
538 self.free_current = 1.8
539 # Resistance of the motor (Ohms)
540 self.resistance = 12.0 / self.stall_current
541 # Motor velocity constant (radians / (sec * volt))
542 self.Kv = (self.free_speed / (12.0 - self.resistance * self.free_current))
543 # Torque constant (N * m / A)
544 self.Kt = self.stall_torque / self.stall_current
Brian Silverman6260c092018-01-14 15:21:36 -0800545
546class MN3510(object):
547 def __init__(self):
548 # http://www.robotshop.com/en/t-motor-navigator-mn3510-360kv-brushless-motor.html#Specifications
549 # Free Current in Amps
550 self.free_current = 0.0
551 # Resistance of the motor
552 self.resistance = 0.188
553 # Stall Current in Amps
554 self.stall_current = 14.0 / self.resistance
555 # Motor velocity constant
556 self.Kv = 360.0 / 60.0 * (2.0 * numpy.pi)
557 # Torque constant Nm / A
558 self.Kt = 1.0 / self.Kv
559 # Stall Torque in N m
560 self.stall_torque = self.Kt * self.stall_current