blob: 2ef2ece5f8d67b76011f5bd24397a51c757b9c84 [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 Schuhbcce26a2018-03-26 23:41:24 -070013
14 def Render(self, loop_type):
15 typestring = self.formatToType[self.formatt]
16 if loop_type == 'float' and typestring == 'double':
17 typestring = loop_type
Austin Schuh1a387962015-01-31 16:36:20 -080018 return str("\nstatic constexpr %s %s = "+ self.formatt +";\n") % \
Austin Schuhbcce26a2018-03-26 23:41:24 -070019 (typestring, self.name, self.value)
Ben Fredrickson1b45f782014-02-23 07:44:36 +000020
21
Austin Schuhe3490622013-03-13 01:24:30 -070022class ControlLoopWriter(object):
Austin Schuh3ad5ed82017-02-25 21:36:19 -080023 def __init__(self, gain_schedule_name, loops, namespaces=None,
24 write_constants=False, plant_type='StateFeedbackPlant',
Austin Schuh20388b62017-11-23 22:40:46 -080025 observer_type='StateFeedbackObserver',
26 scalar_type='double'):
Austin Schuhe3490622013-03-13 01:24:30 -070027 """Constructs a control loop writer.
28
29 Args:
30 gain_schedule_name: string, Name of the overall controller.
31 loops: array[ControlLoop], a list of control loops to gain schedule
32 in order.
33 namespaces: array[string], a list of names of namespaces to nest in
34 order. If None, the default will be used.
Austin Schuh3ad5ed82017-02-25 21:36:19 -080035 plant_type: string, The C++ type of the plant.
36 observer_type: string, The C++ type of the observer.
Austin Schuh20388b62017-11-23 22:40:46 -080037 scalar_type: string, The C++ type of the base scalar.
Austin Schuhe3490622013-03-13 01:24:30 -070038 """
39 self._gain_schedule_name = gain_schedule_name
40 self._loops = loops
41 if namespaces:
42 self._namespaces = namespaces
43 else:
44 self._namespaces = ['frc971', 'control_loops']
45
46 self._namespace_start = '\n'.join(
47 ['namespace %s {' % name for name in self._namespaces])
48
49 self._namespace_end = '\n'.join(
50 ['} // namespace %s' % name for name in reversed(self._namespaces)])
Austin Schuh86093ad2016-02-06 14:29:34 -080051
Ben Fredrickson1b45f782014-02-23 07:44:36 +000052 self._constant_list = []
Austin Schuh3ad5ed82017-02-25 21:36:19 -080053 self._plant_type = plant_type
54 self._observer_type = observer_type
Austin Schuh20388b62017-11-23 22:40:46 -080055 self._scalar_type = scalar_type
Austin Schuh25933852014-02-23 02:04:13 -080056
57 def AddConstant(self, constant):
58 """Adds a constant to write.
59
60 Args:
61 constant: Constant, the constant to add to the header.
62 """
63 self._constant_list.append(constant)
Austin Schuhe3490622013-03-13 01:24:30 -070064
Brian Silvermane51ad632014-01-08 15:12:29 -080065 def _TopDirectory(self):
66 return self._namespaces[0]
67
Austin Schuhe3490622013-03-13 01:24:30 -070068 def _HeaderGuard(self, header_file):
Austin Schuh16cf47a2015-11-28 13:20:33 -080069 return ('_'.join([namespace.upper() for namespace in self._namespaces]) + '_' +
Austin Schuh572ff402015-11-08 12:17:50 -080070 os.path.basename(header_file).upper()
71 .replace('.', '_').replace('/', '_') + '_')
Austin Schuhe3490622013-03-13 01:24:30 -070072
73 def Write(self, header_file, cc_file):
74 """Writes the loops to the specified files."""
75 self.WriteHeader(header_file)
Austin Schuh572ff402015-11-08 12:17:50 -080076 self.WriteCC(os.path.basename(header_file), cc_file)
Austin Schuhe3490622013-03-13 01:24:30 -070077
Austin Schuh3ad5ed82017-02-25 21:36:19 -080078 def _GenericType(self, typename, extra_args=None):
Austin Schuhe3490622013-03-13 01:24:30 -070079 """Returns a loop template using typename for the type."""
80 num_states = self._loops[0].A.shape[0]
81 num_inputs = self._loops[0].B.shape[1]
82 num_outputs = self._loops[0].C.shape[0]
Austin Schuh3ad5ed82017-02-25 21:36:19 -080083 if extra_args is not None:
84 extra_args = ', ' + extra_args
85 else:
86 extra_args = ''
Austin Schuh20388b62017-11-23 22:40:46 -080087 if self._scalar_type != 'double':
88 extra_args += ', ' + self._scalar_type
Austin Schuh3ad5ed82017-02-25 21:36:19 -080089 return '%s<%d, %d, %d%s>' % (
90 typename, num_states, num_inputs, num_outputs, extra_args)
Austin Schuhe3490622013-03-13 01:24:30 -070091
92 def _ControllerType(self):
Austin Schuh32501832017-02-25 18:32:56 -080093 """Returns a template name for StateFeedbackController."""
94 return self._GenericType('StateFeedbackController')
95
96 def _ObserverType(self):
97 """Returns a template name for StateFeedbackObserver."""
Austin Schuh3ad5ed82017-02-25 21:36:19 -080098 return self._GenericType(self._observer_type)
Austin Schuhe3490622013-03-13 01:24:30 -070099
100 def _LoopType(self):
101 """Returns a template name for StateFeedbackLoop."""
Austin Schuh20388b62017-11-23 22:40:46 -0800102 num_states = self._loops[0].A.shape[0]
103 num_inputs = self._loops[0].B.shape[1]
104 num_outputs = self._loops[0].C.shape[0]
105
106 return 'StateFeedbackLoop<%d, %d, %d, %s, %s, %s>' % (
107 num_states,
108 num_inputs,
109 num_outputs, self._scalar_type,
110 self._PlantType(), self._ObserverType())
111
Austin Schuhe3490622013-03-13 01:24:30 -0700112
113 def _PlantType(self):
114 """Returns a template name for StateFeedbackPlant."""
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800115 return self._GenericType(self._plant_type)
Austin Schuhe3490622013-03-13 01:24:30 -0700116
Austin Schuh32501832017-02-25 18:32:56 -0800117 def _PlantCoeffType(self):
Austin Schuhe3490622013-03-13 01:24:30 -0700118 """Returns a template name for StateFeedbackPlantCoefficients."""
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800119 return self._GenericType(self._plant_type + 'Coefficients')
Austin Schuhe3490622013-03-13 01:24:30 -0700120
Austin Schuh32501832017-02-25 18:32:56 -0800121 def _ControllerCoeffType(self):
122 """Returns a template name for StateFeedbackControllerCoefficients."""
123 return self._GenericType('StateFeedbackControllerCoefficients')
124
125 def _ObserverCoeffType(self):
126 """Returns a template name for StateFeedbackObserverCoefficients."""
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800127 return self._GenericType(self._observer_type + 'Coefficients')
Austin Schuh32501832017-02-25 18:32:56 -0800128
Austin Schuh20388b62017-11-23 22:40:46 -0800129 def WriteHeader(self, header_file):
130 """Writes the header file to the file named header_file."""
Austin Schuhe3490622013-03-13 01:24:30 -0700131 with open(header_file, 'w') as fd:
132 header_guard = self._HeaderGuard(header_file)
133 fd.write('#ifndef %s\n'
134 '#define %s\n\n' % (header_guard, header_guard))
135 fd.write('#include \"frc971/control_loops/state_feedback_loop.h\"\n')
Austin Schuh4cc4fe22017-11-23 19:13:09 -0800136 if (self._plant_type == 'StateFeedbackHybridPlant' or
137 self._observer_type == 'HybridKalman'):
138 fd.write('#include \"frc971/control_loops/hybrid_state_feedback_loop.h\"\n')
139
Austin Schuhe3490622013-03-13 01:24:30 -0700140 fd.write('\n')
141
142 fd.write(self._namespace_start)
Ben Fredrickson1b45f782014-02-23 07:44:36 +0000143
144 for const in self._constant_list:
Austin Schuhbcce26a2018-03-26 23:41:24 -0700145 fd.write(const.Render(self._scalar_type))
Ben Fredrickson1b45f782014-02-23 07:44:36 +0000146
Austin Schuhe3490622013-03-13 01:24:30 -0700147 fd.write('\n\n')
148 for loop in self._loops:
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800149 fd.write(loop.DumpPlantHeader(self._PlantCoeffType()))
Austin Schuhe3490622013-03-13 01:24:30 -0700150 fd.write('\n')
Austin Schuh20388b62017-11-23 22:40:46 -0800151 fd.write(loop.DumpControllerHeader(self._scalar_type))
Austin Schuhe3490622013-03-13 01:24:30 -0700152 fd.write('\n')
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800153 fd.write(loop.DumpObserverHeader(self._ObserverCoeffType()))
Austin Schuh32501832017-02-25 18:32:56 -0800154 fd.write('\n')
Austin Schuhe3490622013-03-13 01:24:30 -0700155
156 fd.write('%s Make%sPlant();\n\n' %
157 (self._PlantType(), self._gain_schedule_name))
158
Austin Schuh32501832017-02-25 18:32:56 -0800159 fd.write('%s Make%sController();\n\n' %
160 (self._ControllerType(), self._gain_schedule_name))
161
162 fd.write('%s Make%sObserver();\n\n' %
163 (self._ObserverType(), self._gain_schedule_name))
164
Austin Schuhe3490622013-03-13 01:24:30 -0700165 fd.write('%s Make%sLoop();\n\n' %
166 (self._LoopType(), self._gain_schedule_name))
167
168 fd.write(self._namespace_end)
169 fd.write('\n\n')
170 fd.write("#endif // %s\n" % header_guard)
171
172 def WriteCC(self, header_file_name, cc_file):
173 """Writes the cc file to the file named cc_file."""
174 with open(cc_file, 'w') as fd:
Austin Schuh572ff402015-11-08 12:17:50 -0800175 fd.write('#include \"%s/%s\"\n' %
176 (os.path.join(*self._namespaces), header_file_name))
Austin Schuhe3490622013-03-13 01:24:30 -0700177 fd.write('\n')
178 fd.write('#include <vector>\n')
179 fd.write('\n')
180 fd.write('#include \"frc971/control_loops/state_feedback_loop.h\"\n')
181 fd.write('\n')
182 fd.write(self._namespace_start)
183 fd.write('\n\n')
184 for loop in self._loops:
Austin Schuh20388b62017-11-23 22:40:46 -0800185 fd.write(loop.DumpPlant(self._PlantCoeffType(), self._scalar_type))
Austin Schuhe3490622013-03-13 01:24:30 -0700186 fd.write('\n')
187
188 for loop in self._loops:
Austin Schuh20388b62017-11-23 22:40:46 -0800189 fd.write(loop.DumpController(self._scalar_type))
Austin Schuhe3490622013-03-13 01:24:30 -0700190 fd.write('\n')
191
Austin Schuh32501832017-02-25 18:32:56 -0800192 for loop in self._loops:
Austin Schuh20388b62017-11-23 22:40:46 -0800193 fd.write(loop.DumpObserver(self._ObserverCoeffType(), self._scalar_type))
Austin Schuh32501832017-02-25 18:32:56 -0800194 fd.write('\n')
195
Austin Schuhe3490622013-03-13 01:24:30 -0700196 fd.write('%s Make%sPlant() {\n' %
197 (self._PlantType(), self._gain_schedule_name))
Austin Schuh1a387962015-01-31 16:36:20 -0800198 fd.write(' ::std::vector< ::std::unique_ptr<%s>> plants(%d);\n' % (
Austin Schuh32501832017-02-25 18:32:56 -0800199 self._PlantCoeffType(), len(self._loops)))
Austin Schuhe3490622013-03-13 01:24:30 -0700200 for index, loop in enumerate(self._loops):
Austin Schuh1a387962015-01-31 16:36:20 -0800201 fd.write(' plants[%d] = ::std::unique_ptr<%s>(new %s(%s));\n' %
Austin Schuh32501832017-02-25 18:32:56 -0800202 (index, self._PlantCoeffType(), self._PlantCoeffType(),
Austin Schuhe3490622013-03-13 01:24:30 -0700203 loop.PlantFunction()))
Austin Schuh1a387962015-01-31 16:36:20 -0800204 fd.write(' return %s(&plants);\n' % self._PlantType())
Austin Schuhe3490622013-03-13 01:24:30 -0700205 fd.write('}\n\n')
206
Austin Schuh32501832017-02-25 18:32:56 -0800207 fd.write('%s Make%sController() {\n' %
208 (self._ControllerType(), self._gain_schedule_name))
Austin Schuh1a387962015-01-31 16:36:20 -0800209 fd.write(' ::std::vector< ::std::unique_ptr<%s>> controllers(%d);\n' % (
Austin Schuh32501832017-02-25 18:32:56 -0800210 self._ControllerCoeffType(), len(self._loops)))
Austin Schuhe3490622013-03-13 01:24:30 -0700211 for index, loop in enumerate(self._loops):
Austin Schuh1a387962015-01-31 16:36:20 -0800212 fd.write(' controllers[%d] = ::std::unique_ptr<%s>(new %s(%s));\n' %
Austin Schuh32501832017-02-25 18:32:56 -0800213 (index, self._ControllerCoeffType(), self._ControllerCoeffType(),
Austin Schuhe3490622013-03-13 01:24:30 -0700214 loop.ControllerFunction()))
Austin Schuh32501832017-02-25 18:32:56 -0800215 fd.write(' return %s(&controllers);\n' % self._ControllerType())
216 fd.write('}\n\n')
217
218 fd.write('%s Make%sObserver() {\n' %
219 (self._ObserverType(), self._gain_schedule_name))
220 fd.write(' ::std::vector< ::std::unique_ptr<%s>> observers(%d);\n' % (
221 self._ObserverCoeffType(), len(self._loops)))
222 for index, loop in enumerate(self._loops):
223 fd.write(' observers[%d] = ::std::unique_ptr<%s>(new %s(%s));\n' %
224 (index, self._ObserverCoeffType(), self._ObserverCoeffType(),
225 loop.ObserverFunction()))
226 fd.write(' return %s(&observers);\n' % self._ObserverType())
227 fd.write('}\n\n')
228
229 fd.write('%s Make%sLoop() {\n' %
230 (self._LoopType(), self._gain_schedule_name))
231 fd.write(' return %s(Make%sPlant(), Make%sController(), Make%sObserver());\n' %
232 (self._LoopType(), self._gain_schedule_name,
233 self._gain_schedule_name, self._gain_schedule_name))
Austin Schuhe3490622013-03-13 01:24:30 -0700234 fd.write('}\n\n')
235
236 fd.write(self._namespace_end)
237 fd.write('\n')
238
239
Austin Schuh3c542312013-02-24 01:53:50 -0800240class ControlLoop(object):
241 def __init__(self, name):
242 """Constructs a control loop object.
243
244 Args:
245 name: string, The name of the loop to use when writing the C++ files.
246 """
247 self._name = name
248
Austin Schuhc1f68892013-03-16 17:06:27 -0700249 def ContinuousToDiscrete(self, A_continuous, B_continuous, dt):
250 """Calculates the discrete time values for A and B.
Austin Schuh3c542312013-02-24 01:53:50 -0800251
252 Args:
253 A_continuous: numpy.matrix, The continuous time A matrix
254 B_continuous: numpy.matrix, The continuous time B matrix
255 dt: float, The time step of the control loop
Austin Schuhc1f68892013-03-16 17:06:27 -0700256
257 Returns:
258 (A, B), numpy.matrix, the control matricies.
Austin Schuh3c542312013-02-24 01:53:50 -0800259 """
Austin Schuhc1f68892013-03-16 17:06:27 -0700260 return controls.c2d(A_continuous, B_continuous, dt)
261
262 def InitializeState(self):
263 """Sets X, Y, and X_hat to zero defaults."""
Austin Schuh3c542312013-02-24 01:53:50 -0800264 self.X = numpy.zeros((self.A.shape[0], 1))
Austin Schuhc1f68892013-03-16 17:06:27 -0700265 self.Y = self.C * self.X
Austin Schuh3c542312013-02-24 01:53:50 -0800266 self.X_hat = numpy.zeros((self.A.shape[0], 1))
267
268 def PlaceControllerPoles(self, poles):
269 """Places the controller poles.
270
271 Args:
272 poles: array, An array of poles. Must be complex conjegates if they have
273 any imaginary portions.
274 """
275 self.K = controls.dplace(self.A, self.B, poles)
276
277 def PlaceObserverPoles(self, poles):
278 """Places the observer poles.
279
280 Args:
281 poles: array, An array of poles. Must be complex conjegates if they have
282 any imaginary portions.
283 """
284 self.L = controls.dplace(self.A.T, self.C.T, poles).T
285
Sabina Davis3922dfa2018-02-10 23:10:05 -0800286
Austin Schuh3c542312013-02-24 01:53:50 -0800287 def Update(self, U):
288 """Simulates one time step with the provided U."""
Austin Schuh1d005732015-03-01 00:10:20 -0800289 #U = numpy.clip(U, self.U_min, self.U_max)
Austin Schuh3c542312013-02-24 01:53:50 -0800290 self.X = self.A * self.X + self.B * U
291 self.Y = self.C * self.X + self.D * U
292
Austin Schuh1a387962015-01-31 16:36:20 -0800293 def PredictObserver(self, U):
294 """Runs the predict step of the observer update."""
295 self.X_hat = (self.A * self.X_hat + self.B * U)
296
297 def CorrectObserver(self, U):
298 """Runs the correct step of the observer update."""
Austin Schuhf173eb82018-01-20 23:32:30 -0800299 if hasattr(self, 'KalmanGain'):
300 KalmanGain = self.KalmanGain
301 else:
302 KalmanGain = numpy.linalg.inv(self.A) * self.L
303 self.X_hat += KalmanGain * (self.Y - self.C * self.X_hat - self.D * U)
Austin Schuh1a387962015-01-31 16:36:20 -0800304
Austin Schuh3c542312013-02-24 01:53:50 -0800305 def UpdateObserver(self, U):
306 """Updates the observer given the provided U."""
Sabina Davis3922dfa2018-02-10 23:10:05 -0800307 if hasattr(self, 'KalmanGain'):
308 KalmanGain = self.KalmanGain
309 else:
310 KalmanGain = numpy.linalg.inv(self.A) * self.L
Austin Schuh3c542312013-02-24 01:53:50 -0800311 self.X_hat = (self.A * self.X_hat + self.B * U +
Sabina Davis3922dfa2018-02-10 23:10:05 -0800312 self.A * KalmanGain * (self.Y - self.C * self.X_hat - self.D * U))
Austin Schuh3c542312013-02-24 01:53:50 -0800313
Austin Schuh20388b62017-11-23 22:40:46 -0800314 def _DumpMatrix(self, matrix_name, matrix, scalar_type):
Austin Schuh3c542312013-02-24 01:53:50 -0800315 """Dumps the provided matrix into a variable called matrix_name.
316
317 Args:
318 matrix_name: string, The variable name to save the matrix to.
319 matrix: The matrix to dump.
Austin Schuh20388b62017-11-23 22:40:46 -0800320 scalar_type: The C++ type to use for the scalar in the matrix.
Austin Schuh3c542312013-02-24 01:53:50 -0800321
322 Returns:
323 string, The C++ commands required to populate a variable named matrix_name
324 with the contents of matrix.
325 """
Austin Schuh20388b62017-11-23 22:40:46 -0800326 ans = [' Eigen::Matrix<%s, %d, %d> %s;\n' % (
327 scalar_type, matrix.shape[0], matrix.shape[1], matrix_name)]
Brian Silverman0f637382013-03-03 17:44:46 -0800328 for x in xrange(matrix.shape[0]):
329 for y in xrange(matrix.shape[1]):
Austin Schuh20388b62017-11-23 22:40:46 -0800330 write_type = repr(matrix[x, y])
331 if scalar_type == 'float':
Austin Schuhbcce26a2018-03-26 23:41:24 -0700332 if '.' not in write_type:
333 write_type += '.0'
Austin Schuh20388b62017-11-23 22:40:46 -0800334 write_type += 'f'
335 ans.append(' %s(%d, %d) = %s;\n' % (matrix_name, x, y, write_type))
Austin Schuh3c542312013-02-24 01:53:50 -0800336
Austin Schuhe3490622013-03-13 01:24:30 -0700337 return ''.join(ans)
Austin Schuh3c542312013-02-24 01:53:50 -0800338
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800339 def DumpPlantHeader(self, plant_coefficient_type):
Austin Schuh3c542312013-02-24 01:53:50 -0800340 """Writes out a c++ header declaration which will create a Plant object.
341
Austin Schuh3c542312013-02-24 01:53:50 -0800342 Returns:
343 string, The header declaration for the function.
344 """
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800345 return '%s Make%sPlantCoefficients();\n' % (
346 plant_coefficient_type, self._name)
Austin Schuh3c542312013-02-24 01:53:50 -0800347
Austin Schuh20388b62017-11-23 22:40:46 -0800348 def DumpPlant(self, plant_coefficient_type, scalar_type):
Austin Schuhe3490622013-03-13 01:24:30 -0700349 """Writes out a c++ function which will create a PlantCoefficients object.
Austin Schuh3c542312013-02-24 01:53:50 -0800350
351 Returns:
352 string, The function which will create the object.
353 """
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800354 ans = ['%s Make%sPlantCoefficients() {\n' % (
355 plant_coefficient_type, self._name)]
Austin Schuh3c542312013-02-24 01:53:50 -0800356
Austin Schuh20388b62017-11-23 22:40:46 -0800357 ans.append(self._DumpMatrix('C', self.C, scalar_type))
358 ans.append(self._DumpMatrix('D', self.D, scalar_type))
359 ans.append(self._DumpMatrix('U_max', self.U_max, scalar_type))
360 ans.append(self._DumpMatrix('U_min', self.U_min, scalar_type))
Austin Schuh3c542312013-02-24 01:53:50 -0800361
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800362 if plant_coefficient_type.startswith('StateFeedbackPlant'):
Austin Schuh20388b62017-11-23 22:40:46 -0800363 ans.append(self._DumpMatrix('A', self.A, scalar_type))
Austin Schuh20388b62017-11-23 22:40:46 -0800364 ans.append(self._DumpMatrix('B', self.B, scalar_type))
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800365 ans.append(' return %s'
Sabina Davis3922dfa2018-02-10 23:10:05 -0800366 '(A, B, C, D, U_max, U_min);\n' % (
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800367 plant_coefficient_type))
368 elif plant_coefficient_type.startswith('StateFeedbackHybridPlant'):
Austin Schuh20388b62017-11-23 22:40:46 -0800369 ans.append(self._DumpMatrix('A_continuous', self.A_continuous, scalar_type))
370 ans.append(self._DumpMatrix('B_continuous', self.B_continuous, scalar_type))
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800371 ans.append(' return %s'
372 '(A_continuous, B_continuous, C, D, U_max, U_min);\n' % (
373 plant_coefficient_type))
374 else:
375 glog.fatal('Unsupported plant type %s', plant_coefficient_type)
376
Austin Schuhe3490622013-03-13 01:24:30 -0700377 ans.append('}\n')
378 return ''.join(ans)
Austin Schuh3c542312013-02-24 01:53:50 -0800379
Austin Schuhe3490622013-03-13 01:24:30 -0700380 def PlantFunction(self):
381 """Returns the name of the plant coefficient function."""
382 return 'Make%sPlantCoefficients()' % self._name
Austin Schuh3c542312013-02-24 01:53:50 -0800383
Austin Schuhe3490622013-03-13 01:24:30 -0700384 def ControllerFunction(self):
385 """Returns the name of the controller function."""
Austin Schuh32501832017-02-25 18:32:56 -0800386 return 'Make%sControllerCoefficients()' % self._name
387
388 def ObserverFunction(self):
389 """Returns the name of the controller function."""
390 return 'Make%sObserverCoefficients()' % self._name
Austin Schuhe3490622013-03-13 01:24:30 -0700391
Austin Schuh20388b62017-11-23 22:40:46 -0800392 def DumpControllerHeader(self, scalar_type):
Austin Schuhe3490622013-03-13 01:24:30 -0700393 """Writes out a c++ header declaration which will create a Controller object.
Austin Schuh3c542312013-02-24 01:53:50 -0800394
395 Returns:
396 string, The header declaration for the function.
397 """
398 num_states = self.A.shape[0]
399 num_inputs = self.B.shape[1]
400 num_outputs = self.C.shape[0]
Austin Schuh20388b62017-11-23 22:40:46 -0800401 return 'StateFeedbackControllerCoefficients<%d, %d, %d, %s> %s;\n' % (
402 num_states, num_inputs, num_outputs, scalar_type,
403 self.ControllerFunction())
Austin Schuh3c542312013-02-24 01:53:50 -0800404
Austin Schuh20388b62017-11-23 22:40:46 -0800405 def DumpController(self, scalar_type):
Austin Schuhe3490622013-03-13 01:24:30 -0700406 """Returns a c++ function which will create a Controller object.
Austin Schuh3c542312013-02-24 01:53:50 -0800407
408 Returns:
409 string, The function which will create the object.
410 """
411 num_states = self.A.shape[0]
412 num_inputs = self.B.shape[1]
413 num_outputs = self.C.shape[0]
Austin Schuh20388b62017-11-23 22:40:46 -0800414 ans = ['StateFeedbackControllerCoefficients<%d, %d, %d, %s> %s {\n' % (
415 num_states, num_inputs, num_outputs, scalar_type,
416 self.ControllerFunction())]
Austin Schuh3c542312013-02-24 01:53:50 -0800417
Austin Schuh20388b62017-11-23 22:40:46 -0800418 ans.append(self._DumpMatrix('K', self.K, scalar_type))
Austin Schuh86093ad2016-02-06 14:29:34 -0800419 if not hasattr(self, 'Kff'):
420 self.Kff = numpy.matrix(numpy.zeros(self.K.shape))
421
Austin Schuh20388b62017-11-23 22:40:46 -0800422 ans.append(self._DumpMatrix('Kff', self.Kff, scalar_type))
Austin Schuh3c542312013-02-24 01:53:50 -0800423
Austin Schuh20388b62017-11-23 22:40:46 -0800424 ans.append(' return StateFeedbackControllerCoefficients<%d, %d, %d, %s>'
Austin Schuh32501832017-02-25 18:32:56 -0800425 '(K, Kff);\n' % (
Austin Schuh20388b62017-11-23 22:40:46 -0800426 num_states, num_inputs, num_outputs, scalar_type))
Austin Schuhe3490622013-03-13 01:24:30 -0700427 ans.append('}\n')
428 return ''.join(ans)
Austin Schuh32501832017-02-25 18:32:56 -0800429
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800430 def DumpObserverHeader(self, observer_coefficient_type):
Austin Schuh32501832017-02-25 18:32:56 -0800431 """Writes out a c++ header declaration which will create a Observer object.
432
433 Returns:
434 string, The header declaration for the function.
435 """
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800436 return '%s %s;\n' % (
437 observer_coefficient_type, self.ObserverFunction())
Austin Schuh32501832017-02-25 18:32:56 -0800438
Austin Schuh20388b62017-11-23 22:40:46 -0800439 def DumpObserver(self, observer_coefficient_type, scalar_type):
Austin Schuh32501832017-02-25 18:32:56 -0800440 """Returns a c++ function which will create a Observer object.
441
442 Returns:
443 string, The function which will create the object.
444 """
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800445 ans = ['%s %s {\n' % (
446 observer_coefficient_type, self.ObserverFunction())]
Austin Schuh32501832017-02-25 18:32:56 -0800447
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800448 if observer_coefficient_type.startswith('StateFeedbackObserver'):
Sabina Davis3922dfa2018-02-10 23:10:05 -0800449 if hasattr(self, 'KalmanGain'):
450 KalmanGain = self.KalmanGain
451 else:
452 KalmanGain = numpy.linalg.inv(self.A) * self.L
453 ans.append(self._DumpMatrix('KalmanGain', KalmanGain, scalar_type))
454 ans.append(' return %s(KalmanGain);\n' % (observer_coefficient_type,))
455
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800456 elif observer_coefficient_type.startswith('HybridKalman'):
Austin Schuh20388b62017-11-23 22:40:46 -0800457 ans.append(self._DumpMatrix('Q_continuous', self.Q_continuous, scalar_type))
458 ans.append(self._DumpMatrix('R_continuous', self.R_continuous, scalar_type))
459 ans.append(self._DumpMatrix('P_steady_state', self.P_steady_state, scalar_type))
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800460 ans.append(' return %s(Q_continuous, R_continuous, P_steady_state);\n' % (
461 observer_coefficient_type,))
Brian Silvermana3a20cc2017-03-05 18:35:20 -0800462 else:
463 glog.fatal('Unsupported observer type %s', observer_coefficient_type)
Austin Schuh32501832017-02-25 18:32:56 -0800464
Austin Schuh32501832017-02-25 18:32:56 -0800465 ans.append('}\n')
466 return ''.join(ans)
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800467
468class HybridControlLoop(ControlLoop):
469 def __init__(self, name):
470 super(HybridControlLoop, self).__init__(name=name)
471
Brian Silverman59c829a2017-03-05 18:36:54 -0800472 def Discretize(self, dt):
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800473 [self.A, self.B, self.Q, self.R] = \
474 controls.kalmd(self.A_continuous, self.B_continuous,
475 self.Q_continuous, self.R_continuous, dt)
476
477 def PredictHybridObserver(self, U, dt):
Brian Silverman59c829a2017-03-05 18:36:54 -0800478 self.Discretize(dt)
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800479 self.X_hat = self.A * self.X_hat + self.B * U
480 self.P = (self.A * self.P * self.A.T + self.Q)
481
482 def CorrectHybridObserver(self, U):
483 Y_bar = self.Y - self.C * self.X_hat
484 C_t = self.C.T
485 S = self.C * self.P * C_t + self.R
486 self.KalmanGain = self.P * C_t * numpy.linalg.inv(S)
487 self.X_hat = self.X_hat + self.KalmanGain * Y_bar
488 self.P = (numpy.eye(len(self.A)) - self.KalmanGain * self.C) * self.P
489
490 def InitializeState(self):
491 super(HybridControlLoop, self).InitializeState()
492 if hasattr(self, 'Q_steady_state'):
493 self.P = self.Q_steady_state
494 else:
495 self.P = numpy.matrix(numpy.zeros((self.A.shape[0], self.A.shape[0])))
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800496
497
498class CIM(object):
499 def __init__(self):
500 # Stall Torque in N m
501 self.stall_torque = 2.42
502 # Stall Current in Amps
503 self.stall_current = 133.0
504 # Free Speed in rad/s
505 self.free_speed = 5500.0 / 60.0 * 2.0 * numpy.pi
506 # Free Current in Amps
507 self.free_current = 4.7
508 # Resistance of the motor
509 self.resistance = 12.0 / self.stall_current
510 # Motor velocity constant
511 self.Kv = (self.free_speed / (12.0 - self.resistance * self.free_current))
512 # Torque constant
513 self.Kt = self.stall_torque / self.stall_current
Lee Mracek97fc8af2018-01-13 04:38:52 -0500514
515
516class MiniCIM(object):
517 def __init__(self):
518 # Stall Torque in N m
519 self.stall_torque = 1.41
520 # Stall Current in Amps
521 self.stall_current = 89.0
522 # Free Speed in rad/s
523 self.free_speed = 5840.0 / 60.0 * 2.0 * numpy.pi
524 # Free Current in Amps
525 self.free_current = 3.0
526 # Resistance of the motor
527 self.resistance = 12.0 / self.stall_current
528 # Motor velocity constant
529 self.Kv = (self.free_speed / (12.0 - self.resistance * self.free_current))
530 # Torque constant
531 self.Kt = self.stall_torque / self.stall_current
Austin Schuhf173eb82018-01-20 23:32:30 -0800532
533
534class BAG(object):
535 # BAG motor specs available at http://motors.vex.com/vexpro-motors/bag-motor
536 def __init__(self):
537 # Stall Torque in (N m)
538 self.stall_torque = 0.43
539 # Stall Current in (Amps)
540 self.stall_current = 53.0
541 # Free Speed in (rad/s)
542 self.free_speed = 13180.0 / 60.0 * 2.0 * numpy.pi
543 # Free Current in (Amps)
544 self.free_current = 1.8
545 # Resistance of the motor (Ohms)
546 self.resistance = 12.0 / self.stall_current
547 # Motor velocity constant (radians / (sec * volt))
548 self.Kv = (self.free_speed / (12.0 - self.resistance * self.free_current))
549 # Torque constant (N * m / A)
550 self.Kt = self.stall_torque / self.stall_current
Brian Silverman6260c092018-01-14 15:21:36 -0800551
552class MN3510(object):
553 def __init__(self):
554 # http://www.robotshop.com/en/t-motor-navigator-mn3510-360kv-brushless-motor.html#Specifications
555 # Free Current in Amps
556 self.free_current = 0.0
557 # Resistance of the motor
558 self.resistance = 0.188
559 # Stall Current in Amps
560 self.stall_current = 14.0 / self.resistance
561 # Motor velocity constant
562 self.Kv = 360.0 / 60.0 * (2.0 * numpy.pi)
563 # Torque constant Nm / A
564 self.Kt = 1.0 / self.Kv
565 # Stall Torque in N m
566 self.stall_torque = self.Kt * self.stall_current