blob: a6fcd3e669f0e6f6585fc889ef09877ca0c724f5 [file] [log] [blame]
Austin Schuhce7e03d2020-11-20 22:32:44 -08001import frc971.control_loops.python.controls as controls
Austin Schuh3c542312013-02-24 01:53:50 -08002import numpy
Austin Schuh572ff402015-11-08 12:17:50 -08003import os
James Kuszmauleeb98e92024-01-14 22:15:32 -08004import json
Austin Schuh3c542312013-02-24 01:53:50 -08005
Austin Schuhbcce26a2018-03-26 23:41:24 -07006
Tyler Chatow6738c362019-02-16 14:12:30 -08007class Constant(object):
Ravago Jones5127ccc2022-07-31 16:32:45 -07008
James Kuszmaul62c3bd82024-01-17 20:03:05 -08009 def __init__(self,
10 name,
11 formatt,
12 value,
13 comment=None,
14 json_name=None,
15 json_scale=1.0,
16 json_type=None):
Tyler Chatow6738c362019-02-16 14:12:30 -080017 self.name = name
18 self.formatt = formatt
19 self.value = value
20 self.formatToType = {}
21 self.formatToType['%f'] = "double"
22 self.formatToType['%d'] = "int"
Austin Schuhe8ca06a2020-03-07 22:27:39 -080023 if comment is None:
24 self.comment = ""
25 else:
26 self.comment = comment + "\n"
James Kuszmaul62c3bd82024-01-17 20:03:05 -080027 self.json_name = json_name
28 self.json_scale = json_scale
29 self.json_type = json_type
Tyler Chatow6738c362019-02-16 14:12:30 -080030
31 def Render(self, loop_type):
32 typestring = self.formatToType[self.formatt]
33 if loop_type == 'float' and typestring == 'double':
34 typestring = loop_type
Austin Schuhe8ca06a2020-03-07 22:27:39 -080035 return str("\n%sstatic constexpr %s %s = "+ self.formatt +";\n") % \
36 (self.comment, typestring, self.name, self.value)
Ben Fredrickson1b45f782014-02-23 07:44:36 +000037
James Kuszmaul62c3bd82024-01-17 20:03:05 -080038 def RenderJson(self, json_dict):
39 if self.json_name is None:
40 return
41 json_value = self.value * self.json_scale
42 json_dict[
43 self.
44 json_name] = json_value if self.json_type is None else self.json_type(
45 json_value)
46 return json_dict
47
Ben Fredrickson1b45f782014-02-23 07:44:36 +000048
James Kuszmauleeb98e92024-01-14 22:15:32 -080049def MatrixToJson(matrix):
50 """Returns JSON representation of a numpy matrix."""
51 return {
52 "rows": matrix.shape[0],
53 "cols": matrix.shape[1],
54 "storage_order": "ColMajor",
55 "data": numpy.array(matrix).flatten(order='F').tolist()
56 }
57
58
Austin Schuhe3490622013-03-13 01:24:30 -070059class ControlLoopWriter(object):
Ravago Jones5127ccc2022-07-31 16:32:45 -070060
Tyler Chatow6738c362019-02-16 14:12:30 -080061 def __init__(self,
62 gain_schedule_name,
63 loops,
64 namespaces=None,
65 write_constants=False,
66 plant_type='StateFeedbackPlant',
67 observer_type='StateFeedbackObserver',
68 scalar_type='double'):
69 """Constructs a control loop writer.
Austin Schuhe3490622013-03-13 01:24:30 -070070
Tyler Chatow6738c362019-02-16 14:12:30 -080071 Args:
72 gain_schedule_name: string, Name of the overall controller.
73 loops: array[ControlLoop], a list of control loops to gain schedule
74 in order.
75 namespaces: array[string], a list of names of namespaces to nest in
76 order. If None, the default will be used.
77 plant_type: string, The C++ type of the plant.
78 observer_type: string, The C++ type of the observer.
79 scalar_type: string, The C++ type of the base scalar.
80 """
81 self._gain_schedule_name = gain_schedule_name
82 self._loops = loops
83 if namespaces:
84 self._namespaces = namespaces
85 else:
86 self._namespaces = ['frc971', 'control_loops']
Austin Schuhe3490622013-03-13 01:24:30 -070087
Tyler Chatow6738c362019-02-16 14:12:30 -080088 self._namespace_start = '\n'.join(
89 ['namespace %s {' % name for name in self._namespaces])
Austin Schuh86093ad2016-02-06 14:29:34 -080090
Tyler Chatow6738c362019-02-16 14:12:30 -080091 self._namespace_end = '\n'.join([
92 '} // namespace %s' % name for name in reversed(self._namespaces)
93 ])
Austin Schuh25933852014-02-23 02:04:13 -080094
Tyler Chatow6738c362019-02-16 14:12:30 -080095 self._constant_list = []
96 self._plant_type = plant_type
97 self._observer_type = observer_type
98 self._scalar_type = scalar_type
Austin Schuh25933852014-02-23 02:04:13 -080099
Tyler Chatow6738c362019-02-16 14:12:30 -0800100 def AddConstant(self, constant):
101 """Adds a constant to write.
Austin Schuhe3490622013-03-13 01:24:30 -0700102
Tyler Chatow6738c362019-02-16 14:12:30 -0800103 Args:
104 constant: Constant, the constant to add to the header.
105 """
106 self._constant_list.append(constant)
Brian Silvermane51ad632014-01-08 15:12:29 -0800107
Tyler Chatow6738c362019-02-16 14:12:30 -0800108 def _TopDirectory(self):
109 return self._namespaces[0]
Austin Schuhe3490622013-03-13 01:24:30 -0700110
Tyler Chatow6738c362019-02-16 14:12:30 -0800111 def _HeaderGuard(self, header_file):
Ravago Jones5127ccc2022-07-31 16:32:45 -0700112 return ('_'.join([namespace.upper()
113 for namespace in self._namespaces]) + '_' +
114 os.path.basename(header_file).upper().replace(
Tyler Chatow6738c362019-02-16 14:12:30 -0800115 '.', '_').replace('/', '_') + '_')
Austin Schuhe3490622013-03-13 01:24:30 -0700116
James Kuszmaul62c3bd82024-01-17 20:03:05 -0800117 def Write(self, header_file, cc_file, json_file=None, json_field=None):
Tyler Chatow6738c362019-02-16 14:12:30 -0800118 """Writes the loops to the specified files."""
119 self.WriteHeader(header_file)
120 self.WriteCC(os.path.basename(header_file), cc_file)
James Kuszmauleeb98e92024-01-14 22:15:32 -0800121 if json_file is not None:
James Kuszmaul62c3bd82024-01-17 20:03:05 -0800122 self.WriteJson(json_file, json_field)
Austin Schuhe3490622013-03-13 01:24:30 -0700123
Tyler Chatow6738c362019-02-16 14:12:30 -0800124 def _GenericType(self, typename, extra_args=None):
125 """Returns a loop template using typename for the type."""
126 num_states = self._loops[0].A.shape[0]
127 num_inputs = self._loops[0].B.shape[1]
128 num_outputs = self._loops[0].C.shape[0]
129 if extra_args is not None:
130 extra_args = ', ' + extra_args
131 else:
132 extra_args = ''
133 if self._scalar_type != 'double':
134 extra_args += ', ' + self._scalar_type
135 return '%s<%d, %d, %d%s>' % (typename, num_states, num_inputs,
136 num_outputs, extra_args)
Austin Schuh32501832017-02-25 18:32:56 -0800137
Tyler Chatow6738c362019-02-16 14:12:30 -0800138 def _ControllerType(self):
139 """Returns a template name for StateFeedbackController."""
140 return self._GenericType('StateFeedbackController')
Austin Schuhe3490622013-03-13 01:24:30 -0700141
Tyler Chatow6738c362019-02-16 14:12:30 -0800142 def _ObserverType(self):
143 """Returns a template name for StateFeedbackObserver."""
144 return self._GenericType(self._observer_type)
Austin Schuh20388b62017-11-23 22:40:46 -0800145
Tyler Chatow6738c362019-02-16 14:12:30 -0800146 def _LoopType(self):
147 """Returns a template name for StateFeedbackLoop."""
148 num_states = self._loops[0].A.shape[0]
149 num_inputs = self._loops[0].B.shape[1]
150 num_outputs = self._loops[0].C.shape[0]
Austin Schuh20388b62017-11-23 22:40:46 -0800151
Tyler Chatow6738c362019-02-16 14:12:30 -0800152 return 'StateFeedbackLoop<%d, %d, %d, %s, %s, %s>' % (
153 num_states, num_inputs, num_outputs, self._scalar_type,
154 self._PlantType(), self._ObserverType())
Austin Schuhe3490622013-03-13 01:24:30 -0700155
Tyler Chatow6738c362019-02-16 14:12:30 -0800156 def _PlantType(self):
157 """Returns a template name for StateFeedbackPlant."""
158 return self._GenericType(self._plant_type)
Austin Schuhe3490622013-03-13 01:24:30 -0700159
Tyler Chatow6738c362019-02-16 14:12:30 -0800160 def _PlantCoeffType(self):
161 """Returns a template name for StateFeedbackPlantCoefficients."""
162 return self._GenericType(self._plant_type + 'Coefficients')
Austin Schuhe3490622013-03-13 01:24:30 -0700163
Tyler Chatow6738c362019-02-16 14:12:30 -0800164 def _ControllerCoeffType(self):
165 """Returns a template name for StateFeedbackControllerCoefficients."""
166 return self._GenericType('StateFeedbackControllerCoefficients')
Austin Schuh32501832017-02-25 18:32:56 -0800167
Tyler Chatow6738c362019-02-16 14:12:30 -0800168 def _ObserverCoeffType(self):
169 """Returns a template name for StateFeedbackObserverCoefficients."""
170 return self._GenericType(self._observer_type + 'Coefficients')
Austin Schuh32501832017-02-25 18:32:56 -0800171
Tyler Chatow6738c362019-02-16 14:12:30 -0800172 def WriteHeader(self, header_file):
173 """Writes the header file to the file named header_file."""
174 with open(header_file, 'w') as fd:
175 header_guard = self._HeaderGuard(header_file)
176 fd.write('#ifndef %s\n'
177 '#define %s\n\n' % (header_guard, header_guard))
178 fd.write(
179 '#include \"frc971/control_loops/state_feedback_loop.h\"\n')
Ravago Jones26f7ad02021-02-05 15:45:59 -0800180 if (self._plant_type == 'StateFeedbackHybridPlant'
181 or self._observer_type == 'HybridKalman'):
Tyler Chatow6738c362019-02-16 14:12:30 -0800182 fd.write(
183 '#include \"frc971/control_loops/hybrid_state_feedback_loop.h\"\n'
184 )
Austin Schuh4cc4fe22017-11-23 19:13:09 -0800185
Tyler Chatow6738c362019-02-16 14:12:30 -0800186 fd.write('\n')
Austin Schuhe3490622013-03-13 01:24:30 -0700187
Tyler Chatow6738c362019-02-16 14:12:30 -0800188 fd.write(self._namespace_start)
Ben Fredrickson1b45f782014-02-23 07:44:36 +0000189
Tyler Chatow6738c362019-02-16 14:12:30 -0800190 for const in self._constant_list:
191 fd.write(const.Render(self._scalar_type))
Ben Fredrickson1b45f782014-02-23 07:44:36 +0000192
Tyler Chatow6738c362019-02-16 14:12:30 -0800193 fd.write('\n\n')
194 for loop in self._loops:
195 fd.write(loop.DumpPlantHeader(self._PlantCoeffType()))
196 fd.write('\n')
197 fd.write(loop.DumpControllerHeader(self._scalar_type))
198 fd.write('\n')
199 fd.write(loop.DumpObserverHeader(self._ObserverCoeffType()))
200 fd.write('\n')
Austin Schuhe3490622013-03-13 01:24:30 -0700201
Ravago Jones5127ccc2022-07-31 16:32:45 -0700202 fd.write('%s Make%sPlant();\n\n' %
203 (self._PlantType(), self._gain_schedule_name))
Austin Schuhe3490622013-03-13 01:24:30 -0700204
Ravago Jones5127ccc2022-07-31 16:32:45 -0700205 fd.write('%s Make%sController();\n\n' %
206 (self._ControllerType(), self._gain_schedule_name))
Austin Schuh32501832017-02-25 18:32:56 -0800207
Ravago Jones5127ccc2022-07-31 16:32:45 -0700208 fd.write('%s Make%sObserver();\n\n' %
209 (self._ObserverType(), self._gain_schedule_name))
Austin Schuh32501832017-02-25 18:32:56 -0800210
Ravago Jones5127ccc2022-07-31 16:32:45 -0700211 fd.write('%s Make%sLoop();\n\n' %
212 (self._LoopType(), self._gain_schedule_name))
Austin Schuhe3490622013-03-13 01:24:30 -0700213
Tyler Chatow6738c362019-02-16 14:12:30 -0800214 fd.write(self._namespace_end)
215 fd.write('\n\n')
216 fd.write("#endif // %s\n" % header_guard)
Austin Schuhe3490622013-03-13 01:24:30 -0700217
Tyler Chatow6738c362019-02-16 14:12:30 -0800218 def WriteCC(self, header_file_name, cc_file):
219 """Writes the cc file to the file named cc_file."""
220 with open(cc_file, 'w') as fd:
Ravago Jones5127ccc2022-07-31 16:32:45 -0700221 fd.write('#include \"%s/%s\"\n' %
222 (os.path.join(*self._namespaces), header_file_name))
Tyler Chatow6738c362019-02-16 14:12:30 -0800223 fd.write('\n')
James Kuszmaul03be1242020-02-21 14:52:04 -0800224 fd.write('#include <chrono>\n')
Tyler Chatow6738c362019-02-16 14:12:30 -0800225 fd.write('#include <vector>\n')
226 fd.write('\n')
227 fd.write(
228 '#include \"frc971/control_loops/state_feedback_loop.h\"\n')
229 fd.write('\n')
230 fd.write(self._namespace_start)
231 fd.write('\n\n')
232 for loop in self._loops:
233 fd.write(
234 loop.DumpPlant(self._PlantCoeffType(), self._scalar_type))
235 fd.write('\n')
Austin Schuhe3490622013-03-13 01:24:30 -0700236
Tyler Chatow6738c362019-02-16 14:12:30 -0800237 for loop in self._loops:
238 fd.write(loop.DumpController(self._scalar_type))
239 fd.write('\n')
Austin Schuhe3490622013-03-13 01:24:30 -0700240
Tyler Chatow6738c362019-02-16 14:12:30 -0800241 for loop in self._loops:
242 fd.write(
243 loop.DumpObserver(self._ObserverCoeffType(),
244 self._scalar_type))
245 fd.write('\n')
Austin Schuh32501832017-02-25 18:32:56 -0800246
Ravago Jones5127ccc2022-07-31 16:32:45 -0700247 fd.write('%s Make%sPlant() {\n' %
248 (self._PlantType(), self._gain_schedule_name))
Tyler Chatow6738c362019-02-16 14:12:30 -0800249 fd.write(' ::std::vector< ::std::unique_ptr<%s>> plants(%d);\n' %
250 (self._PlantCoeffType(), len(self._loops)))
251 for index, loop in enumerate(self._loops):
Ravago Jones5127ccc2022-07-31 16:32:45 -0700252 fd.write(
253 ' plants[%d] = ::std::unique_ptr<%s>(new %s(%s));\n' %
254 (index, self._PlantCoeffType(), self._PlantCoeffType(),
255 loop.PlantFunction()))
Austin Schuhb02bf5b2021-07-31 21:28:21 -0700256 fd.write(' return %s(std::move(plants));\n' % self._PlantType())
Tyler Chatow6738c362019-02-16 14:12:30 -0800257 fd.write('}\n\n')
Austin Schuhe3490622013-03-13 01:24:30 -0700258
Ravago Jones5127ccc2022-07-31 16:32:45 -0700259 fd.write('%s Make%sController() {\n' %
260 (self._ControllerType(), self._gain_schedule_name))
Tyler Chatow6738c362019-02-16 14:12:30 -0800261 fd.write(
262 ' ::std::vector< ::std::unique_ptr<%s>> controllers(%d);\n' %
263 (self._ControllerCoeffType(), len(self._loops)))
264 for index, loop in enumerate(self._loops):
265 fd.write(
Ravago Jones26f7ad02021-02-05 15:45:59 -0800266 ' controllers[%d] = ::std::unique_ptr<%s>(new %s(%s));\n'
267 % (index, self._ControllerCoeffType(),
268 self._ControllerCoeffType(), loop.ControllerFunction()))
Austin Schuhb02bf5b2021-07-31 21:28:21 -0700269 fd.write(' return %s(std::move(controllers));\n' %
270 self._ControllerType())
Tyler Chatow6738c362019-02-16 14:12:30 -0800271 fd.write('}\n\n')
Austin Schuh32501832017-02-25 18:32:56 -0800272
Ravago Jones5127ccc2022-07-31 16:32:45 -0700273 fd.write('%s Make%sObserver() {\n' %
274 (self._ObserverType(), self._gain_schedule_name))
275 fd.write(
276 ' ::std::vector< ::std::unique_ptr<%s>> observers(%d);\n' %
277 (self._ObserverCoeffType(), len(self._loops)))
Tyler Chatow6738c362019-02-16 14:12:30 -0800278 for index, loop in enumerate(self._loops):
279 fd.write(
Ravago Jones5127ccc2022-07-31 16:32:45 -0700280 ' observers[%d] = ::std::unique_ptr<%s>(new %s(%s));\n' %
281 (index, self._ObserverCoeffType(),
282 self._ObserverCoeffType(), loop.ObserverFunction()))
283 fd.write(' return %s(std::move(observers));\n' %
284 self._ObserverType())
Tyler Chatow6738c362019-02-16 14:12:30 -0800285 fd.write('}\n\n')
Austin Schuh32501832017-02-25 18:32:56 -0800286
Ravago Jones5127ccc2022-07-31 16:32:45 -0700287 fd.write('%s Make%sLoop() {\n' %
288 (self._LoopType(), self._gain_schedule_name))
Tyler Chatow6738c362019-02-16 14:12:30 -0800289 fd.write(
290 ' return %s(Make%sPlant(), Make%sController(), Make%sObserver());\n'
291 % (self._LoopType(), self._gain_schedule_name,
292 self._gain_schedule_name, self._gain_schedule_name))
293 fd.write('}\n\n')
Austin Schuhe3490622013-03-13 01:24:30 -0700294
Tyler Chatow6738c362019-02-16 14:12:30 -0800295 fd.write(self._namespace_end)
296 fd.write('\n')
Austin Schuhe3490622013-03-13 01:24:30 -0700297
James Kuszmaul62c3bd82024-01-17 20:03:05 -0800298 def WriteJson(self, json_file, json_field):
James Kuszmauleeb98e92024-01-14 22:15:32 -0800299 """Writes a JSON file of the loop constants to the specified json_file."""
300 loops = []
301 for loop in self._loops:
302 loop_json = {}
303 loop_json["plant"] = loop.DumpPlantJson(self._PlantCoeffType())
304 loop_json["controller"] = loop.DumpControllerJson()
305 loop_json["observer"] = loop.DumbObserverJson(
306 self._ObserverCoeffType())
307 loops.append(loop_json)
James Kuszmaul62c3bd82024-01-17 20:03:05 -0800308 if json_field is None:
309 with open(json_file, 'w') as f:
310 f.write(json.dumps(loops))
311 return
312 loop_config = {}
313 loop_config[json_field] = loops
314 for const in self._constant_list:
315 const.RenderJson(loop_config)
James Kuszmauleeb98e92024-01-14 22:15:32 -0800316 with open(json_file, 'w') as f:
James Kuszmaul62c3bd82024-01-17 20:03:05 -0800317 f.write(json.dumps(loop_config))
James Kuszmauleeb98e92024-01-14 22:15:32 -0800318
Austin Schuhe3490622013-03-13 01:24:30 -0700319
Austin Schuh3c542312013-02-24 01:53:50 -0800320class ControlLoop(object):
Ravago Jones5127ccc2022-07-31 16:32:45 -0700321
Tyler Chatow6738c362019-02-16 14:12:30 -0800322 def __init__(self, name):
323 """Constructs a control loop object.
Austin Schuh3c542312013-02-24 01:53:50 -0800324
Tyler Chatow6738c362019-02-16 14:12:30 -0800325 Args:
326 name: string, The name of the loop to use when writing the C++ files.
327 """
328 self._name = name
Austin Schuhb39f4522022-03-27 13:29:42 -0700329 self.delayed_u = 0
Austin Schuhb5d302f2019-01-20 20:51:19 -0800330
Tyler Chatow6738c362019-02-16 14:12:30 -0800331 @property
332 def name(self):
333 """Returns the name"""
334 return self._name
Austin Schuh3c542312013-02-24 01:53:50 -0800335
Tyler Chatow6738c362019-02-16 14:12:30 -0800336 def ContinuousToDiscrete(self, A_continuous, B_continuous, dt):
337 """Calculates the discrete time values for A and B.
Austin Schuhc1f68892013-03-16 17:06:27 -0700338
Tyler Chatow6738c362019-02-16 14:12:30 -0800339 Args:
340 A_continuous: numpy.matrix, The continuous time A matrix
341 B_continuous: numpy.matrix, The continuous time B matrix
342 dt: float, The time step of the control loop
Austin Schuhc1f68892013-03-16 17:06:27 -0700343
Tyler Chatow6738c362019-02-16 14:12:30 -0800344 Returns:
345 (A, B), numpy.matrix, the control matricies.
346 """
347 return controls.c2d(A_continuous, B_continuous, dt)
Austin Schuh3c542312013-02-24 01:53:50 -0800348
Tyler Chatow6738c362019-02-16 14:12:30 -0800349 def InitializeState(self):
350 """Sets X, Y, and X_hat to zero defaults."""
Austin Schuh43b9ae92020-02-29 23:08:38 -0800351 self.X = numpy.matrix(numpy.zeros((self.A.shape[0], 1)))
Tyler Chatow6738c362019-02-16 14:12:30 -0800352 self.Y = self.C * self.X
Austin Schuh43b9ae92020-02-29 23:08:38 -0800353 self.X_hat = numpy.matrix(numpy.zeros((self.A.shape[0], 1)))
Ravago Jones5127ccc2022-07-31 16:32:45 -0700354 self.last_U = numpy.matrix(
355 numpy.zeros((self.B.shape[1], max(1, self.delayed_u))))
Austin Schuh3c542312013-02-24 01:53:50 -0800356
Tyler Chatow6738c362019-02-16 14:12:30 -0800357 def PlaceControllerPoles(self, poles):
358 """Places the controller poles.
Austin Schuh3c542312013-02-24 01:53:50 -0800359
Tyler Chatow6738c362019-02-16 14:12:30 -0800360 Args:
361 poles: array, An array of poles. Must be complex conjegates if they have
362 any imaginary portions.
363 """
364 self.K = controls.dplace(self.A, self.B, poles)
Austin Schuh3c542312013-02-24 01:53:50 -0800365
Tyler Chatow6738c362019-02-16 14:12:30 -0800366 def PlaceObserverPoles(self, poles):
367 """Places the observer poles.
Austin Schuh3c542312013-02-24 01:53:50 -0800368
Tyler Chatow6738c362019-02-16 14:12:30 -0800369 Args:
370 poles: array, An array of poles. Must be complex conjegates if they have
371 any imaginary portions.
372 """
373 self.L = controls.dplace(self.A.T, self.C.T, poles).T
Sabina Davis3922dfa2018-02-10 23:10:05 -0800374
Tyler Chatow6738c362019-02-16 14:12:30 -0800375 def Update(self, U):
376 """Simulates one time step with the provided U."""
377 #U = numpy.clip(U, self.U_min, self.U_max)
Austin Schuhb39f4522022-03-27 13:29:42 -0700378 if self.delayed_u > 0:
379 self.X = self.A * self.X + self.B * self.last_U[:, -1]
380 self.Y = self.C * self.X + self.D * self.last_U[:, -1]
381 self.last_U[:, 1:] = self.last_U[:, 0:-1]
382 self.last_U[:, 0] = U.copy()
Austin Schuh64433f12022-02-21 19:40:38 -0800383 else:
384 self.X = self.A * self.X + self.B * U
385 self.Y = self.C * self.X + self.D * U
Austin Schuh3c542312013-02-24 01:53:50 -0800386
Tyler Chatow6738c362019-02-16 14:12:30 -0800387 def PredictObserver(self, U):
388 """Runs the predict step of the observer update."""
Austin Schuhb39f4522022-03-27 13:29:42 -0700389 if self.delayed_u > 0:
390 self.X_hat = (self.A * self.X_hat + self.B * self.last_U[:, -1])
391 self.last_U[:, 1:] = self.last_U[:, 0:-1]
392 self.last_U[:, 0] = U.copy()
Austin Schuh64433f12022-02-21 19:40:38 -0800393 else:
394 self.X_hat = (self.A * self.X_hat + self.B * U)
Austin Schuh1a387962015-01-31 16:36:20 -0800395
Tyler Chatow6738c362019-02-16 14:12:30 -0800396 def CorrectObserver(self, U):
397 """Runs the correct step of the observer update."""
398 if hasattr(self, 'KalmanGain'):
399 KalmanGain = self.KalmanGain
400 else:
401 KalmanGain = numpy.linalg.inv(self.A) * self.L
Austin Schuhb39f4522022-03-27 13:29:42 -0700402 if self.delayed_u > 0:
Austin Schuh64433f12022-02-21 19:40:38 -0800403 self.X_hat += KalmanGain * (self.Y - self.C * self.X_hat -
Austin Schuhb39f4522022-03-27 13:29:42 -0700404 self.D * self.last_U[:, -1])
Tyler Chatow6738c362019-02-16 14:12:30 -0800405 else:
Austin Schuh64433f12022-02-21 19:40:38 -0800406 self.X_hat += KalmanGain * (self.Y - self.C * self.X_hat -
407 self.D * U)
Austin Schuh3c542312013-02-24 01:53:50 -0800408
Tyler Chatow6738c362019-02-16 14:12:30 -0800409 def _DumpMatrix(self, matrix_name, matrix, scalar_type):
410 """Dumps the provided matrix into a variable called matrix_name.
Austin Schuh3c542312013-02-24 01:53:50 -0800411
Tyler Chatow6738c362019-02-16 14:12:30 -0800412 Args:
413 matrix_name: string, The variable name to save the matrix to.
414 matrix: The matrix to dump.
415 scalar_type: The C++ type to use for the scalar in the matrix.
Austin Schuh3c542312013-02-24 01:53:50 -0800416
Tyler Chatow6738c362019-02-16 14:12:30 -0800417 Returns:
418 string, The C++ commands required to populate a variable named matrix_name
419 with the contents of matrix.
420 """
421 ans = [
Ravago Jones26f7ad02021-02-05 15:45:59 -0800422 ' Eigen::Matrix<%s, %d, %d> %s;\n' %
423 (scalar_type, matrix.shape[0], matrix.shape[1], matrix_name)
Tyler Chatow6738c362019-02-16 14:12:30 -0800424 ]
Austin Schuh5ea48472021-02-02 20:46:41 -0800425 for x in range(matrix.shape[0]):
426 for y in range(matrix.shape[1]):
Tyler Chatow6738c362019-02-16 14:12:30 -0800427 write_type = repr(matrix[x, y])
428 if scalar_type == 'float':
Austin Schuh085eab92020-11-26 13:54:51 -0800429 if '.' not in write_type and 'e' not in write_type:
Tyler Chatow6738c362019-02-16 14:12:30 -0800430 write_type += '.0'
431 write_type += 'f'
Ravago Jones5127ccc2022-07-31 16:32:45 -0700432 ans.append(' %s(%d, %d) = %s;\n' %
433 (matrix_name, x, y, write_type))
Austin Schuh3c542312013-02-24 01:53:50 -0800434
Tyler Chatow6738c362019-02-16 14:12:30 -0800435 return ''.join(ans)
Austin Schuh3c542312013-02-24 01:53:50 -0800436
Tyler Chatow6738c362019-02-16 14:12:30 -0800437 def DumpPlantHeader(self, plant_coefficient_type):
438 """Writes out a c++ header declaration which will create a Plant object.
Austin Schuh3c542312013-02-24 01:53:50 -0800439
Tyler Chatow6738c362019-02-16 14:12:30 -0800440 Returns:
441 string, The header declaration for the function.
442 """
443 return '%s Make%sPlantCoefficients();\n' % (plant_coefficient_type,
444 self._name)
Austin Schuh3c542312013-02-24 01:53:50 -0800445
James Kuszmauleeb98e92024-01-14 22:15:32 -0800446 def DumpPlantJson(self, plant_coefficient_type):
447 result = {
448 "c": MatrixToJson(self.C),
449 "d": MatrixToJson(self.D),
450 "u_min": MatrixToJson(self.U_min),
451 "u_max": MatrixToJson(self.U_max),
452 "u_limit_coefficient": MatrixToJson(self.U_limit_coefficient),
453 "u_limit_constant": MatrixToJson(self.U_limit_constant),
454 "delayed_u": self.delayed_u
455 }
456 if plant_coefficient_type.startswith('StateFeedbackPlant'):
457 result["a"] = MatrixToJson(self.A)
458 result["b"] = MatrixToJson(self.B)
459 result["dt"] = int(self.dt * 1e9)
460 elif plant_coefficient_type.startswith('StateFeedbackHybridPlant'):
461 result["a_continuous"] = MatrixToJson(self.A_continuous)
462 result["b_continuous"] = MatrixToJson(self.B_continuous)
463 else:
464 glog.fatal('Unsupported plant type %s', plant_coefficient_type)
465 return result
466
Tyler Chatow6738c362019-02-16 14:12:30 -0800467 def DumpPlant(self, plant_coefficient_type, scalar_type):
468 """Writes out a c++ function which will create a PlantCoefficients object.
Austin Schuh3c542312013-02-24 01:53:50 -0800469
Tyler Chatow6738c362019-02-16 14:12:30 -0800470 Returns:
471 string, The function which will create the object.
472 """
473 ans = [
Ravago Jones5127ccc2022-07-31 16:32:45 -0700474 '%s Make%sPlantCoefficients() {\n' %
475 (plant_coefficient_type, self._name)
Tyler Chatow6738c362019-02-16 14:12:30 -0800476 ]
Austin Schuh3c542312013-02-24 01:53:50 -0800477
Ravago Jonesc471ebe2023-07-05 20:37:00 -0700478 num_states = self.A.shape[0]
479 num_inputs = self.B.shape[1]
480 num_outputs = self.C.shape[0]
481
Tyler Chatow6738c362019-02-16 14:12:30 -0800482 ans.append(self._DumpMatrix('C', self.C, scalar_type))
483 ans.append(self._DumpMatrix('D', self.D, scalar_type))
484 ans.append(self._DumpMatrix('U_max', self.U_max, scalar_type))
485 ans.append(self._DumpMatrix('U_min', self.U_min, scalar_type))
Austin Schuh3c542312013-02-24 01:53:50 -0800486
Ravago Jonesc471ebe2023-07-05 20:37:00 -0700487 if not hasattr(self, 'U_limit_coefficient'):
488 self.U_limit_coefficient = numpy.matrix(
489 numpy.zeros((num_inputs, num_states)))
490
491 if not hasattr(self, 'U_limit_constant'):
492 self.U_limit_constant = self.U_max
493
494 ans.append(
495 self._DumpMatrix('U_limit_coefficient', self.U_limit_coefficient,
496 scalar_type))
497 ans.append(
498 self._DumpMatrix('U_limit_constant', self.U_limit_constant,
499 scalar_type))
500
Austin Schuhb39f4522022-03-27 13:29:42 -0700501 delayed_u_string = str(self.delayed_u)
Tyler Chatow6738c362019-02-16 14:12:30 -0800502 if plant_coefficient_type.startswith('StateFeedbackPlant'):
503 ans.append(self._DumpMatrix('A', self.A, scalar_type))
504 ans.append(self._DumpMatrix('B', self.B, scalar_type))
Ravago Jones5127ccc2022-07-31 16:32:45 -0700505 ans.append(' const std::chrono::nanoseconds dt(%d);\n' %
506 (self.dt * 1e9))
Ravago Jonesc471ebe2023-07-05 20:37:00 -0700507 ans.append(
508 ' return %s'
509 '(A, B, C, D, U_max, U_min, U_limit_coefficient, U_limit_constant, dt, %s);\n'
510 % (plant_coefficient_type, delayed_u_string))
Tyler Chatow6738c362019-02-16 14:12:30 -0800511 elif plant_coefficient_type.startswith('StateFeedbackHybridPlant'):
512 ans.append(
513 self._DumpMatrix('A_continuous', self.A_continuous,
514 scalar_type))
515 ans.append(
516 self._DumpMatrix('B_continuous', self.B_continuous,
517 scalar_type))
Ravago Jones5127ccc2022-07-31 16:32:45 -0700518 ans.append(
519 ' return %s'
Ravago Jonesc471ebe2023-07-05 20:37:00 -0700520 '(A_continuous, B_continuous, C, D, U_max, U_min, U_limit_coefficient, U_limit_constant, %s);\n'
521 % (plant_coefficient_type, delayed_u_string))
Tyler Chatow6738c362019-02-16 14:12:30 -0800522 else:
523 glog.fatal('Unsupported plant type %s', plant_coefficient_type)
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800524
Tyler Chatow6738c362019-02-16 14:12:30 -0800525 ans.append('}\n')
526 return ''.join(ans)
Austin Schuh3c542312013-02-24 01:53:50 -0800527
Tyler Chatow6738c362019-02-16 14:12:30 -0800528 def PlantFunction(self):
529 """Returns the name of the plant coefficient function."""
530 return 'Make%sPlantCoefficients()' % self._name
Austin Schuh3c542312013-02-24 01:53:50 -0800531
Tyler Chatow6738c362019-02-16 14:12:30 -0800532 def ControllerFunction(self):
533 """Returns the name of the controller function."""
534 return 'Make%sControllerCoefficients()' % self._name
Austin Schuh32501832017-02-25 18:32:56 -0800535
Tyler Chatow6738c362019-02-16 14:12:30 -0800536 def ObserverFunction(self):
537 """Returns the name of the controller function."""
538 return 'Make%sObserverCoefficients()' % self._name
Austin Schuhe3490622013-03-13 01:24:30 -0700539
Tyler Chatow6738c362019-02-16 14:12:30 -0800540 def DumpControllerHeader(self, scalar_type):
541 """Writes out a c++ header declaration which will create a Controller object.
Austin Schuh3c542312013-02-24 01:53:50 -0800542
Tyler Chatow6738c362019-02-16 14:12:30 -0800543 Returns:
544 string, The header declaration for the function.
545 """
546 num_states = self.A.shape[0]
547 num_inputs = self.B.shape[1]
548 num_outputs = self.C.shape[0]
549 return 'StateFeedbackControllerCoefficients<%d, %d, %d, %s> %s;\n' % (
550 num_states, num_inputs, num_outputs, scalar_type,
551 self.ControllerFunction())
Austin Schuh3c542312013-02-24 01:53:50 -0800552
James Kuszmauleeb98e92024-01-14 22:15:32 -0800553 def DumpControllerJson(self):
554 result = {"k": MatrixToJson(self.K), "kff": MatrixToJson(self.Kff)}
555 return result
556
Tyler Chatow6738c362019-02-16 14:12:30 -0800557 def DumpController(self, scalar_type):
558 """Returns a c++ function which will create a Controller object.
Austin Schuh3c542312013-02-24 01:53:50 -0800559
Tyler Chatow6738c362019-02-16 14:12:30 -0800560 Returns:
561 string, The function which will create the object.
562 """
563 num_states = self.A.shape[0]
564 num_inputs = self.B.shape[1]
565 num_outputs = self.C.shape[0]
566 ans = [
567 'StateFeedbackControllerCoefficients<%d, %d, %d, %s> %s {\n' %
568 (num_states, num_inputs, num_outputs, scalar_type,
569 self.ControllerFunction())
570 ]
Austin Schuh3c542312013-02-24 01:53:50 -0800571
Tyler Chatow6738c362019-02-16 14:12:30 -0800572 ans.append(self._DumpMatrix('K', self.K, scalar_type))
573 if not hasattr(self, 'Kff'):
574 self.Kff = numpy.matrix(numpy.zeros(self.K.shape))
Austin Schuh86093ad2016-02-06 14:29:34 -0800575
Tyler Chatow6738c362019-02-16 14:12:30 -0800576 ans.append(self._DumpMatrix('Kff', self.Kff, scalar_type))
Austin Schuh3c542312013-02-24 01:53:50 -0800577
Tyler Chatow6738c362019-02-16 14:12:30 -0800578 ans.append(
579 ' return StateFeedbackControllerCoefficients<%d, %d, %d, %s>'
580 '(K, Kff);\n' % (num_states, num_inputs, num_outputs, scalar_type))
581 ans.append('}\n')
582 return ''.join(ans)
Austin Schuh32501832017-02-25 18:32:56 -0800583
Tyler Chatow6738c362019-02-16 14:12:30 -0800584 def DumpObserverHeader(self, observer_coefficient_type):
585 """Writes out a c++ header declaration which will create a Observer object.
Austin Schuh32501832017-02-25 18:32:56 -0800586
Tyler Chatow6738c362019-02-16 14:12:30 -0800587 Returns:
588 string, The header declaration for the function.
589 """
Ravago Jones26f7ad02021-02-05 15:45:59 -0800590 return '%s %s;\n' % (observer_coefficient_type,
591 self.ObserverFunction())
Austin Schuh32501832017-02-25 18:32:56 -0800592
James Kuszmauleeb98e92024-01-14 22:15:32 -0800593 def GetObserverCoefficients(self):
594 if hasattr(self, 'KalmanGain'):
595 KalmanGain = self.KalmanGain
596 Q = self.Q
597 R = self.R
598 else:
599 KalmanGain = numpy.linalg.inv(self.A) * self.L
600 Q = numpy.zeros(self.A.shape)
601 R = numpy.zeros((self.C.shape[0], self.C.shape[0]))
602 return (KalmanGain, Q, R)
603
604 def DumbObserverJson(self, observer_coefficient_type):
605 result = {"delayed_u": self.delayed_u}
606 if observer_coefficient_type.startswith('StateFeedbackObserver'):
607 KalmanGain, Q, R = self.GetObserverCoefficients()
608 result["kalman_gain"] = MatrixToJson(KalmanGain)
609 result["q"] = MatrixToJson(Q)
610 result["r"] = MatrixToJson(R)
611 elif observer_coefficient_type.startswith('HybridKalman'):
612 result["q_continuous"] = MatrixToJson(self.Q_continuous)
613 result["r_continuous"] = MatrixToJson(self.R_continuous)
614 result["p_steady_state"] = MatrixToJson(self.P_steady_state)
615 else:
616 glog.fatal('Unsupported plant type %s', observer_coefficient_type)
617 return result
618
Tyler Chatow6738c362019-02-16 14:12:30 -0800619 def DumpObserver(self, observer_coefficient_type, scalar_type):
620 """Returns a c++ function which will create a Observer object.
Austin Schuh32501832017-02-25 18:32:56 -0800621
Tyler Chatow6738c362019-02-16 14:12:30 -0800622 Returns:
623 string, The function which will create the object.
624 """
625 ans = [
626 '%s %s {\n' % (observer_coefficient_type, self.ObserverFunction())
627 ]
Austin Schuh32501832017-02-25 18:32:56 -0800628
Austin Schuhb39f4522022-03-27 13:29:42 -0700629 delayed_u_string = str(self.delayed_u)
Tyler Chatow6738c362019-02-16 14:12:30 -0800630 if observer_coefficient_type.startswith('StateFeedbackObserver'):
James Kuszmauleeb98e92024-01-14 22:15:32 -0800631 KalmanGain, Q, R = self.GetObserverCoefficients()
Tyler Chatow6738c362019-02-16 14:12:30 -0800632 ans.append(self._DumpMatrix('KalmanGain', KalmanGain, scalar_type))
633 ans.append(self._DumpMatrix('Q', Q, scalar_type))
634 ans.append(self._DumpMatrix('R', R, scalar_type))
Austin Schuh64433f12022-02-21 19:40:38 -0800635 ans.append(' return %s(KalmanGain, Q, R, %s);\n' %
636 (observer_coefficient_type, delayed_u_string))
Sabina Davis3922dfa2018-02-10 23:10:05 -0800637
Tyler Chatow6738c362019-02-16 14:12:30 -0800638 elif observer_coefficient_type.startswith('HybridKalman'):
639 ans.append(
640 self._DumpMatrix('Q_continuous', self.Q_continuous,
641 scalar_type))
642 ans.append(
643 self._DumpMatrix('R_continuous', self.R_continuous,
644 scalar_type))
645 ans.append(
646 self._DumpMatrix('P_steady_state', self.P_steady_state,
647 scalar_type))
648 ans.append(
Ravago Jones5127ccc2022-07-31 16:32:45 -0700649 ' return %s(Q_continuous, R_continuous, P_steady_state, %s);\n'
650 % (observer_coefficient_type, delayed_u_string))
Tyler Chatow6738c362019-02-16 14:12:30 -0800651 else:
652 glog.fatal('Unsupported observer type %s',
653 observer_coefficient_type)
Austin Schuh32501832017-02-25 18:32:56 -0800654
Tyler Chatow6738c362019-02-16 14:12:30 -0800655 ans.append('}\n')
656 return ''.join(ans)
657
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800658
659class HybridControlLoop(ControlLoop):
Ravago Jones5127ccc2022-07-31 16:32:45 -0700660
Tyler Chatow6738c362019-02-16 14:12:30 -0800661 def __init__(self, name):
662 super(HybridControlLoop, self).__init__(name=name)
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800663
Tyler Chatow6738c362019-02-16 14:12:30 -0800664 def Discretize(self, dt):
665 [self.A, self.B, self.Q, self.R] = \
666 controls.kalmd(self.A_continuous, self.B_continuous,
667 self.Q_continuous, self.R_continuous, dt)
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800668
Tyler Chatow6738c362019-02-16 14:12:30 -0800669 def PredictHybridObserver(self, U, dt):
670 self.Discretize(dt)
Austin Schuhb39f4522022-03-27 13:29:42 -0700671 if self.delayed_u > 0:
672 self.X_hat = self.A * self.X_hat + self.B * self.last_U[:, -1]
673 self.last_U[:, 1:] = self.last_U[:, 0:-1]
674 self.last_U[:, 0] = U.copy()
Austin Schuh64433f12022-02-21 19:40:38 -0800675 else:
676 self.X_hat = self.A * self.X_hat + self.B * U
677
Tyler Chatow6738c362019-02-16 14:12:30 -0800678 self.P = (self.A * self.P * self.A.T + self.Q)
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800679
Tyler Chatow6738c362019-02-16 14:12:30 -0800680 def CorrectHybridObserver(self, U):
681 Y_bar = self.Y - self.C * self.X_hat
682 C_t = self.C.T
683 S = self.C * self.P * C_t + self.R
684 self.KalmanGain = self.P * C_t * numpy.linalg.inv(S)
685 self.X_hat = self.X_hat + self.KalmanGain * Y_bar
686 self.P = (numpy.eye(len(self.A)) - self.KalmanGain * self.C) * self.P
687
688 def InitializeState(self):
689 super(HybridControlLoop, self).InitializeState()
690 if hasattr(self, 'Q_steady_state'):
691 self.P = self.Q_steady_state
692 else:
693 self.P = numpy.matrix(
694 numpy.zeros((self.A.shape[0], self.A.shape[0])))
Campbell Crowley33e0e3d2017-12-27 17:55:40 -0800695
696
697class CIM(object):
Ravago Jones5127ccc2022-07-31 16:32:45 -0700698
Tyler Chatow6738c362019-02-16 14:12:30 -0800699 def __init__(self):
700 # Stall Torque in N m
701 self.stall_torque = 2.42
702 # Stall Current in Amps
703 self.stall_current = 133.0
704 # Free Speed in rad/s
705 self.free_speed = 5500.0 / 60.0 * 2.0 * numpy.pi
706 # Free Current in Amps
707 self.free_current = 4.7
708 # Resistance of the motor
709 self.resistance = 12.0 / self.stall_current
710 # Motor velocity constant
Ravago Jones5127ccc2022-07-31 16:32:45 -0700711 self.Kv = (self.free_speed /
712 (12.0 - self.resistance * self.free_current))
Tyler Chatow6738c362019-02-16 14:12:30 -0800713 # Torque constant
714 self.Kt = self.stall_torque / self.stall_current
Lee Mracek97fc8af2018-01-13 04:38:52 -0500715
716
717class MiniCIM(object):
Ravago Jones5127ccc2022-07-31 16:32:45 -0700718
Tyler Chatow6738c362019-02-16 14:12:30 -0800719 def __init__(self):
720 # Stall Torque in N m
721 self.stall_torque = 1.41
722 # Stall Current in Amps
723 self.stall_current = 89.0
724 # Free Speed in rad/s
725 self.free_speed = 5840.0 / 60.0 * 2.0 * numpy.pi
726 # Free Current in Amps
727 self.free_current = 3.0
728 # Resistance of the motor
729 self.resistance = 12.0 / self.stall_current
730 # Motor velocity constant
Ravago Jones5127ccc2022-07-31 16:32:45 -0700731 self.Kv = (self.free_speed /
732 (12.0 - self.resistance * self.free_current))
Tyler Chatow6738c362019-02-16 14:12:30 -0800733 # Torque constant
734 self.Kt = self.stall_torque / self.stall_current
Austin Schuhf173eb82018-01-20 23:32:30 -0800735
milind-uf70e8e12021-10-02 12:36:00 -0700736 # Motor inertia in kg m^2
737 self.motor_inertia = 0.0001634
738
Austin Schuhf173eb82018-01-20 23:32:30 -0800739
Austin Schuhb5d302f2019-01-20 20:51:19 -0800740class NMotor(object):
Ravago Jones5127ccc2022-07-31 16:32:45 -0700741
Austin Schuhb5d302f2019-01-20 20:51:19 -0800742 def __init__(self, motor, n):
743 """Gangs together n motors."""
744 self.motor = motor
745 self.stall_torque = motor.stall_torque * n
746 self.stall_current = motor.stall_current * n
747 self.free_speed = motor.free_speed
748
749 self.free_current = motor.free_current * n
750 self.resistance = motor.resistance / n
751 self.Kv = motor.Kv
752 self.Kt = motor.Kt
Austin Schuh36bb8e32019-02-18 15:02:57 -0800753 self.motor_inertia = motor.motor_inertia * n
Austin Schuhb5d302f2019-01-20 20:51:19 -0800754
755
756class Vex775Pro(object):
Ravago Jones5127ccc2022-07-31 16:32:45 -0700757
Austin Schuhb5d302f2019-01-20 20:51:19 -0800758 def __init__(self):
759 # Stall Torque in N m
760 self.stall_torque = 0.71
761 # Stall Current in Amps
762 self.stall_current = 134.0
763 # Free Speed in rad/s
764 self.free_speed = 18730.0 / 60.0 * 2.0 * numpy.pi
765 # Free Current in Amps
766 self.free_current = 0.7
767 # Resistance of the motor
768 self.resistance = 12.0 / self.stall_current
769 # Motor velocity constant
Ravago Jones5127ccc2022-07-31 16:32:45 -0700770 self.Kv = (self.free_speed /
771 (12.0 - self.resistance * self.free_current))
Austin Schuhb5d302f2019-01-20 20:51:19 -0800772 # Torque constant
773 self.Kt = self.stall_torque / self.stall_current
774 # Motor inertia in kg m^2
775 self.motor_inertia = 0.00001187
776
777
Austin Schuhf173eb82018-01-20 23:32:30 -0800778class BAG(object):
Tyler Chatow6738c362019-02-16 14:12:30 -0800779 # BAG motor specs available at http://motors.vex.com/vexpro-motors/bag-motor
780 def __init__(self):
781 # Stall Torque in (N m)
782 self.stall_torque = 0.43
783 # Stall Current in (Amps)
784 self.stall_current = 53.0
785 # Free Speed in (rad/s)
786 self.free_speed = 13180.0 / 60.0 * 2.0 * numpy.pi
787 # Free Current in (Amps)
788 self.free_current = 1.8
789 # Resistance of the motor (Ohms)
790 self.resistance = 12.0 / self.stall_current
791 # Motor velocity constant (radians / (sec * volt))
Ravago Jones5127ccc2022-07-31 16:32:45 -0700792 self.Kv = (self.free_speed /
793 (12.0 - self.resistance * self.free_current))
Tyler Chatow6738c362019-02-16 14:12:30 -0800794 # Torque constant (N * m / A)
795 self.Kt = self.stall_torque / self.stall_current
796 # Motor inertia in kg m^2
797 self.motor_inertia = 0.000006
798
Brian Silverman6260c092018-01-14 15:21:36 -0800799
800class MN3510(object):
Ravago Jones5127ccc2022-07-31 16:32:45 -0700801
Tyler Chatow6738c362019-02-16 14:12:30 -0800802 def __init__(self):
803 # http://www.robotshop.com/en/t-motor-navigator-mn3510-360kv-brushless-motor.html#Specifications
804 # Free Current in Amps
805 self.free_current = 0.0
806 # Resistance of the motor
807 self.resistance = 0.188
808 # Stall Current in Amps
809 self.stall_current = 14.0 / self.resistance
810 # Motor velocity constant
811 self.Kv = 360.0 / 60.0 * (2.0 * numpy.pi)
812 # Torque constant Nm / A
813 self.Kt = 1.0 / self.Kv
814 # Stall Torque in N m
815 self.stall_torque = self.Kt * self.stall_current
James Kuszmaulef0c18a2020-01-12 15:44:20 -0800816
817
818class Falcon(object):
819 """Class representing the VexPro Falcon 500 motor.
820
821 All numbers based on data from
822 https://www.vexrobotics.com/vexpro/falcon-500."""
823
824 def __init__(self):
825 # Stall Torque in N m
826 self.stall_torque = 4.69
827 # Stall Current in Amps
828 self.stall_current = 257.0
829 # Free Speed in rad / sec
830 self.free_speed = 6380.0 / 60.0 * 2.0 * numpy.pi
831 # Free Current in Amps
832 self.free_current = 1.5
833 # Resistance of the motor, divided by 2 to account for the 2 motors
834 self.resistance = 12.0 / self.stall_current
835 # Motor velocity constant
Ravago Jones5127ccc2022-07-31 16:32:45 -0700836 self.Kv = (self.free_speed /
837 (12.0 - self.resistance * self.free_current))
James Kuszmaulef0c18a2020-01-12 15:44:20 -0800838 # Torque constant
839 self.Kt = self.stall_torque / self.stall_current
Austin Schuhc1c957a2020-02-20 17:47:58 -0800840 # Motor inertia in kg m^2
841 # Diameter of 1.9", weight of: 100 grams
842 # TODO(austin): Get a number from Scott Westbrook for the mass
Ravago Jones26f7ad02021-02-05 15:45:59 -0800843 self.motor_inertia = 0.1 * ((0.95 * 0.0254)**2.0)
Filip Kujawa7e835182024-01-13 16:22:09 -0800844
845
846class KrakenFOC(object):
847 """Class representing the WCP Kraken X60 motor using
848 Field Oriented Controls (FOC) communication.
849
850 All numbers based on data from
851 https://wcproducts.com/products/kraken.
852 """
853
854 def __init__(self):
855 # Stall Torque in N m
856 self.stall_torque = 9.37
857 # Stall Current in Amps
858 self.stall_current = 483.0
859 # Free Speed in rad / sec
860 self.free_speed = 5800.0 / 60.0 * 2.0 * numpy.pi
861 # Free Current in Amps
862 self.free_current = 2.0
863 # Resistance of the motor, divided by 2 to account for the 2 motors
864 self.resistance = 12.0 / self.stall_current
865 # Motor velocity constant
866 self.Kv = (self.free_speed /
867 (12.0 - self.resistance * self.free_current))
868 # Torque constant
869 self.Kt = self.stall_torque / self.stall_current
870 # Motor inertia in kg m^2
871 # Diameter of 1.9", weight of: 100 grams
872 # TODO(Filip): Update motor inertia for Kraken, currently using Falcon motor inertia
873 self.motor_inertia = 0.1 * ((0.95 * 0.0254)**2.0)