blob: 8eb67fe3e90ef36c2623e539eb18696f7a67a439 [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',
21 observer_type='StateFeedbackObserver'):
Austin Schuhe3490622013-03-13 01:24:30 -070022 """Constructs a control loop writer.
23
24 Args:
25 gain_schedule_name: string, Name of the overall controller.
26 loops: array[ControlLoop], a list of control loops to gain schedule
27 in order.
28 namespaces: array[string], a list of names of namespaces to nest in
29 order. If None, the default will be used.
Austin Schuh3ad5ed82017-02-25 21:36:19 -080030 plant_type: string, The C++ type of the plant.
31 observer_type: string, The C++ type of the observer.
Austin Schuhe3490622013-03-13 01:24:30 -070032 """
33 self._gain_schedule_name = gain_schedule_name
34 self._loops = loops
35 if namespaces:
36 self._namespaces = namespaces
37 else:
38 self._namespaces = ['frc971', 'control_loops']
39
40 self._namespace_start = '\n'.join(
41 ['namespace %s {' % name for name in self._namespaces])
42
43 self._namespace_end = '\n'.join(
44 ['} // namespace %s' % name for name in reversed(self._namespaces)])
Austin Schuh86093ad2016-02-06 14:29:34 -080045
Ben Fredrickson1b45f782014-02-23 07:44:36 +000046 self._constant_list = []
Austin Schuh3ad5ed82017-02-25 21:36:19 -080047 self._plant_type = plant_type
48 self._observer_type = observer_type
Austin Schuh25933852014-02-23 02:04:13 -080049
50 def AddConstant(self, constant):
51 """Adds a constant to write.
52
53 Args:
54 constant: Constant, the constant to add to the header.
55 """
56 self._constant_list.append(constant)
Austin Schuhe3490622013-03-13 01:24:30 -070057
Brian Silvermane51ad632014-01-08 15:12:29 -080058 def _TopDirectory(self):
59 return self._namespaces[0]
60
Austin Schuhe3490622013-03-13 01:24:30 -070061 def _HeaderGuard(self, header_file):
Austin Schuh16cf47a2015-11-28 13:20:33 -080062 return ('_'.join([namespace.upper() for namespace in self._namespaces]) + '_' +
Austin Schuh572ff402015-11-08 12:17:50 -080063 os.path.basename(header_file).upper()
64 .replace('.', '_').replace('/', '_') + '_')
Austin Schuhe3490622013-03-13 01:24:30 -070065
66 def Write(self, header_file, cc_file):
67 """Writes the loops to the specified files."""
68 self.WriteHeader(header_file)
Austin Schuh572ff402015-11-08 12:17:50 -080069 self.WriteCC(os.path.basename(header_file), cc_file)
Austin Schuhe3490622013-03-13 01:24:30 -070070
Austin Schuh3ad5ed82017-02-25 21:36:19 -080071 def _GenericType(self, typename, extra_args=None):
Austin Schuhe3490622013-03-13 01:24:30 -070072 """Returns a loop template using typename for the type."""
73 num_states = self._loops[0].A.shape[0]
74 num_inputs = self._loops[0].B.shape[1]
75 num_outputs = self._loops[0].C.shape[0]
Austin Schuh3ad5ed82017-02-25 21:36:19 -080076 if extra_args is not None:
77 extra_args = ', ' + extra_args
78 else:
79 extra_args = ''
80 return '%s<%d, %d, %d%s>' % (
81 typename, num_states, num_inputs, num_outputs, extra_args)
Austin Schuhe3490622013-03-13 01:24:30 -070082
83 def _ControllerType(self):
Austin Schuh32501832017-02-25 18:32:56 -080084 """Returns a template name for StateFeedbackController."""
85 return self._GenericType('StateFeedbackController')
86
87 def _ObserverType(self):
88 """Returns a template name for StateFeedbackObserver."""
Austin Schuh3ad5ed82017-02-25 21:36:19 -080089 return self._GenericType(self._observer_type)
Austin Schuhe3490622013-03-13 01:24:30 -070090
91 def _LoopType(self):
92 """Returns a template name for StateFeedbackLoop."""
Austin Schuh3ad5ed82017-02-25 21:36:19 -080093 extra_args = '%s, %s' % (self._PlantType(), self._ObserverType())
94 return self._GenericType('StateFeedbackLoop', extra_args)
Austin Schuhe3490622013-03-13 01:24:30 -070095
96 def _PlantType(self):
97 """Returns a template name for StateFeedbackPlant."""
Austin Schuh3ad5ed82017-02-25 21:36:19 -080098 return self._GenericType(self._plant_type)
Austin Schuhe3490622013-03-13 01:24:30 -070099
Austin Schuh32501832017-02-25 18:32:56 -0800100 def _PlantCoeffType(self):
Austin Schuhe3490622013-03-13 01:24:30 -0700101 """Returns a template name for StateFeedbackPlantCoefficients."""
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800102 return self._GenericType(self._plant_type + 'Coefficients')
Austin Schuhe3490622013-03-13 01:24:30 -0700103
Austin Schuh32501832017-02-25 18:32:56 -0800104 def _ControllerCoeffType(self):
105 """Returns a template name for StateFeedbackControllerCoefficients."""
106 return self._GenericType('StateFeedbackControllerCoefficients')
107
108 def _ObserverCoeffType(self):
109 """Returns a template name for StateFeedbackObserverCoefficients."""
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800110 return self._GenericType(self._observer_type + 'Coefficients')
Austin Schuh32501832017-02-25 18:32:56 -0800111
James Kuszmaul0e866512014-02-21 13:12:52 -0800112 def WriteHeader(self, header_file, double_appendage=False, MoI_ratio=0.0):
113 """Writes the header file to the file named header_file.
114 Set double_appendage to true in order to include a ratio of
115 moments of inertia constant. Currently, only used for 2014 claw."""
Austin Schuhe3490622013-03-13 01:24:30 -0700116 with open(header_file, 'w') as fd:
117 header_guard = self._HeaderGuard(header_file)
118 fd.write('#ifndef %s\n'
119 '#define %s\n\n' % (header_guard, header_guard))
120 fd.write('#include \"frc971/control_loops/state_feedback_loop.h\"\n')
121 fd.write('\n')
122
123 fd.write(self._namespace_start)
Ben Fredrickson1b45f782014-02-23 07:44:36 +0000124
125 for const in self._constant_list:
126 fd.write(str(const))
127
Austin Schuhe3490622013-03-13 01:24:30 -0700128 fd.write('\n\n')
129 for loop in self._loops:
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800130 fd.write(loop.DumpPlantHeader(self._PlantCoeffType()))
Austin Schuhe3490622013-03-13 01:24:30 -0700131 fd.write('\n')
132 fd.write(loop.DumpControllerHeader())
133 fd.write('\n')
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800134 fd.write(loop.DumpObserverHeader(self._ObserverCoeffType()))
Austin Schuh32501832017-02-25 18:32:56 -0800135 fd.write('\n')
Austin Schuhe3490622013-03-13 01:24:30 -0700136
137 fd.write('%s Make%sPlant();\n\n' %
138 (self._PlantType(), self._gain_schedule_name))
139
Austin Schuh32501832017-02-25 18:32:56 -0800140 fd.write('%s Make%sController();\n\n' %
141 (self._ControllerType(), self._gain_schedule_name))
142
143 fd.write('%s Make%sObserver();\n\n' %
144 (self._ObserverType(), self._gain_schedule_name))
145
Austin Schuhe3490622013-03-13 01:24:30 -0700146 fd.write('%s Make%sLoop();\n\n' %
147 (self._LoopType(), self._gain_schedule_name))
148
149 fd.write(self._namespace_end)
150 fd.write('\n\n')
151 fd.write("#endif // %s\n" % header_guard)
152
153 def WriteCC(self, header_file_name, cc_file):
154 """Writes the cc file to the file named cc_file."""
155 with open(cc_file, 'w') as fd:
Austin Schuh572ff402015-11-08 12:17:50 -0800156 fd.write('#include \"%s/%s\"\n' %
157 (os.path.join(*self._namespaces), header_file_name))
Austin Schuhe3490622013-03-13 01:24:30 -0700158 fd.write('\n')
159 fd.write('#include <vector>\n')
160 fd.write('\n')
161 fd.write('#include \"frc971/control_loops/state_feedback_loop.h\"\n')
162 fd.write('\n')
163 fd.write(self._namespace_start)
164 fd.write('\n\n')
165 for loop in self._loops:
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800166 fd.write(loop.DumpPlant(self._PlantCoeffType()))
Austin Schuhe3490622013-03-13 01:24:30 -0700167 fd.write('\n')
168
169 for loop in self._loops:
170 fd.write(loop.DumpController())
171 fd.write('\n')
172
Austin Schuh32501832017-02-25 18:32:56 -0800173 for loop in self._loops:
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800174 fd.write(loop.DumpObserver(self._ObserverCoeffType()))
Austin Schuh32501832017-02-25 18:32:56 -0800175 fd.write('\n')
176
Austin Schuhe3490622013-03-13 01:24:30 -0700177 fd.write('%s Make%sPlant() {\n' %
178 (self._PlantType(), self._gain_schedule_name))
Austin Schuh1a387962015-01-31 16:36:20 -0800179 fd.write(' ::std::vector< ::std::unique_ptr<%s>> plants(%d);\n' % (
Austin Schuh32501832017-02-25 18:32:56 -0800180 self._PlantCoeffType(), len(self._loops)))
Austin Schuhe3490622013-03-13 01:24:30 -0700181 for index, loop in enumerate(self._loops):
Austin Schuh1a387962015-01-31 16:36:20 -0800182 fd.write(' plants[%d] = ::std::unique_ptr<%s>(new %s(%s));\n' %
Austin Schuh32501832017-02-25 18:32:56 -0800183 (index, self._PlantCoeffType(), self._PlantCoeffType(),
Austin Schuhe3490622013-03-13 01:24:30 -0700184 loop.PlantFunction()))
Austin Schuh1a387962015-01-31 16:36:20 -0800185 fd.write(' return %s(&plants);\n' % self._PlantType())
Austin Schuhe3490622013-03-13 01:24:30 -0700186 fd.write('}\n\n')
187
Austin Schuh32501832017-02-25 18:32:56 -0800188 fd.write('%s Make%sController() {\n' %
189 (self._ControllerType(), self._gain_schedule_name))
Austin Schuh1a387962015-01-31 16:36:20 -0800190 fd.write(' ::std::vector< ::std::unique_ptr<%s>> controllers(%d);\n' % (
Austin Schuh32501832017-02-25 18:32:56 -0800191 self._ControllerCoeffType(), len(self._loops)))
Austin Schuhe3490622013-03-13 01:24:30 -0700192 for index, loop in enumerate(self._loops):
Austin Schuh1a387962015-01-31 16:36:20 -0800193 fd.write(' controllers[%d] = ::std::unique_ptr<%s>(new %s(%s));\n' %
Austin Schuh32501832017-02-25 18:32:56 -0800194 (index, self._ControllerCoeffType(), self._ControllerCoeffType(),
Austin Schuhe3490622013-03-13 01:24:30 -0700195 loop.ControllerFunction()))
Austin Schuh32501832017-02-25 18:32:56 -0800196 fd.write(' return %s(&controllers);\n' % self._ControllerType())
197 fd.write('}\n\n')
198
199 fd.write('%s Make%sObserver() {\n' %
200 (self._ObserverType(), self._gain_schedule_name))
201 fd.write(' ::std::vector< ::std::unique_ptr<%s>> observers(%d);\n' % (
202 self._ObserverCoeffType(), len(self._loops)))
203 for index, loop in enumerate(self._loops):
204 fd.write(' observers[%d] = ::std::unique_ptr<%s>(new %s(%s));\n' %
205 (index, self._ObserverCoeffType(), self._ObserverCoeffType(),
206 loop.ObserverFunction()))
207 fd.write(' return %s(&observers);\n' % self._ObserverType())
208 fd.write('}\n\n')
209
210 fd.write('%s Make%sLoop() {\n' %
211 (self._LoopType(), self._gain_schedule_name))
212 fd.write(' return %s(Make%sPlant(), Make%sController(), Make%sObserver());\n' %
213 (self._LoopType(), self._gain_schedule_name,
214 self._gain_schedule_name, self._gain_schedule_name))
Austin Schuhe3490622013-03-13 01:24:30 -0700215 fd.write('}\n\n')
216
217 fd.write(self._namespace_end)
218 fd.write('\n')
219
220
Austin Schuh3c542312013-02-24 01:53:50 -0800221class ControlLoop(object):
222 def __init__(self, name):
223 """Constructs a control loop object.
224
225 Args:
226 name: string, The name of the loop to use when writing the C++ files.
227 """
228 self._name = name
229
Austin Schuhc1f68892013-03-16 17:06:27 -0700230 def ContinuousToDiscrete(self, A_continuous, B_continuous, dt):
231 """Calculates the discrete time values for A and B.
Austin Schuh3c542312013-02-24 01:53:50 -0800232
233 Args:
234 A_continuous: numpy.matrix, The continuous time A matrix
235 B_continuous: numpy.matrix, The continuous time B matrix
236 dt: float, The time step of the control loop
Austin Schuhc1f68892013-03-16 17:06:27 -0700237
238 Returns:
239 (A, B), numpy.matrix, the control matricies.
Austin Schuh3c542312013-02-24 01:53:50 -0800240 """
Austin Schuhc1f68892013-03-16 17:06:27 -0700241 return controls.c2d(A_continuous, B_continuous, dt)
242
243 def InitializeState(self):
244 """Sets X, Y, and X_hat to zero defaults."""
Austin Schuh3c542312013-02-24 01:53:50 -0800245 self.X = numpy.zeros((self.A.shape[0], 1))
Austin Schuhc1f68892013-03-16 17:06:27 -0700246 self.Y = self.C * self.X
Austin Schuh3c542312013-02-24 01:53:50 -0800247 self.X_hat = numpy.zeros((self.A.shape[0], 1))
248
249 def PlaceControllerPoles(self, poles):
250 """Places the controller poles.
251
252 Args:
253 poles: array, An array of poles. Must be complex conjegates if they have
254 any imaginary portions.
255 """
256 self.K = controls.dplace(self.A, self.B, poles)
257
258 def PlaceObserverPoles(self, poles):
259 """Places the observer poles.
260
261 Args:
262 poles: array, An array of poles. Must be complex conjegates if they have
263 any imaginary portions.
264 """
265 self.L = controls.dplace(self.A.T, self.C.T, poles).T
266
267 def Update(self, U):
268 """Simulates one time step with the provided U."""
Austin Schuh1d005732015-03-01 00:10:20 -0800269 #U = numpy.clip(U, self.U_min, self.U_max)
Austin Schuh3c542312013-02-24 01:53:50 -0800270 self.X = self.A * self.X + self.B * U
271 self.Y = self.C * self.X + self.D * U
272
Austin Schuh1a387962015-01-31 16:36:20 -0800273 def PredictObserver(self, U):
274 """Runs the predict step of the observer update."""
275 self.X_hat = (self.A * self.X_hat + self.B * U)
276
277 def CorrectObserver(self, U):
278 """Runs the correct step of the observer update."""
279 self.X_hat += numpy.linalg.inv(self.A) * self.L * (
280 self.Y - self.C * self.X_hat - self.D * U)
281
Austin Schuh3c542312013-02-24 01:53:50 -0800282 def UpdateObserver(self, U):
283 """Updates the observer given the provided U."""
284 self.X_hat = (self.A * self.X_hat + self.B * U +
285 self.L * (self.Y - self.C * self.X_hat - self.D * U))
286
287 def _DumpMatrix(self, matrix_name, matrix):
288 """Dumps the provided matrix into a variable called matrix_name.
289
290 Args:
291 matrix_name: string, The variable name to save the matrix to.
292 matrix: The matrix to dump.
293
294 Returns:
295 string, The C++ commands required to populate a variable named matrix_name
296 with the contents of matrix.
297 """
Austin Schuhe3490622013-03-13 01:24:30 -0700298 ans = [' Eigen::Matrix<double, %d, %d> %s;\n' % (
Austin Schuh3c542312013-02-24 01:53:50 -0800299 matrix.shape[0], matrix.shape[1], matrix_name)]
Brian Silverman0f637382013-03-03 17:44:46 -0800300 for x in xrange(matrix.shape[0]):
301 for y in xrange(matrix.shape[1]):
Austin Schuhdf79d112016-10-15 21:25:32 -0700302 ans.append(' %s(%d, %d) = %s;\n' % (matrix_name, x, y, repr(matrix[x, y])))
Austin Schuh3c542312013-02-24 01:53:50 -0800303
Austin Schuhe3490622013-03-13 01:24:30 -0700304 return ''.join(ans)
Austin Schuh3c542312013-02-24 01:53:50 -0800305
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800306 def DumpPlantHeader(self, plant_coefficient_type):
Austin Schuh3c542312013-02-24 01:53:50 -0800307 """Writes out a c++ header declaration which will create a Plant object.
308
Austin Schuh3c542312013-02-24 01:53:50 -0800309 Returns:
310 string, The header declaration for the function.
311 """
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800312 return '%s Make%sPlantCoefficients();\n' % (
313 plant_coefficient_type, self._name)
Austin Schuh3c542312013-02-24 01:53:50 -0800314
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800315 def DumpPlant(self, plant_coefficient_type):
Austin Schuhe3490622013-03-13 01:24:30 -0700316 """Writes out a c++ function which will create a PlantCoefficients object.
Austin Schuh3c542312013-02-24 01:53:50 -0800317
318 Returns:
319 string, The function which will create the object.
320 """
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800321 ans = ['%s Make%sPlantCoefficients() {\n' % (
322 plant_coefficient_type, self._name)]
Austin Schuh3c542312013-02-24 01:53:50 -0800323
Austin Schuhe3490622013-03-13 01:24:30 -0700324 ans.append(self._DumpMatrix('C', self.C))
325 ans.append(self._DumpMatrix('D', self.D))
326 ans.append(self._DumpMatrix('U_max', self.U_max))
327 ans.append(self._DumpMatrix('U_min', self.U_min))
Austin Schuh3c542312013-02-24 01:53:50 -0800328
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800329 if plant_coefficient_type.startswith('StateFeedbackPlant'):
330 ans.append(self._DumpMatrix('A', self.A))
331 ans.append(self._DumpMatrix('A_inv', numpy.linalg.inv(self.A)))
332 ans.append(self._DumpMatrix('B', self.B))
333 ans.append(' return %s'
334 '(A, A_inv, B, C, D, U_max, U_min);\n' % (
335 plant_coefficient_type))
336 elif plant_coefficient_type.startswith('StateFeedbackHybridPlant'):
337 ans.append(self._DumpMatrix('A_continuous', self.A_continuous))
338 ans.append(self._DumpMatrix('B_continuous', self.B_continuous))
339 ans.append(' return %s'
340 '(A_continuous, B_continuous, C, D, U_max, U_min);\n' % (
341 plant_coefficient_type))
342 else:
343 glog.fatal('Unsupported plant type %s', plant_coefficient_type)
344
Austin Schuhe3490622013-03-13 01:24:30 -0700345 ans.append('}\n')
346 return ''.join(ans)
Austin Schuh3c542312013-02-24 01:53:50 -0800347
Austin Schuhe3490622013-03-13 01:24:30 -0700348 def PlantFunction(self):
349 """Returns the name of the plant coefficient function."""
350 return 'Make%sPlantCoefficients()' % self._name
Austin Schuh3c542312013-02-24 01:53:50 -0800351
Austin Schuhe3490622013-03-13 01:24:30 -0700352 def ControllerFunction(self):
353 """Returns the name of the controller function."""
Austin Schuh32501832017-02-25 18:32:56 -0800354 return 'Make%sControllerCoefficients()' % self._name
355
356 def ObserverFunction(self):
357 """Returns the name of the controller function."""
358 return 'Make%sObserverCoefficients()' % self._name
Austin Schuhe3490622013-03-13 01:24:30 -0700359
360 def DumpControllerHeader(self):
361 """Writes out a c++ header declaration which will create a Controller object.
Austin Schuh3c542312013-02-24 01:53:50 -0800362
363 Returns:
364 string, The header declaration for the function.
365 """
366 num_states = self.A.shape[0]
367 num_inputs = self.B.shape[1]
368 num_outputs = self.C.shape[0]
Austin Schuh32501832017-02-25 18:32:56 -0800369 return 'StateFeedbackControllerCoefficients<%d, %d, %d> %s;\n' % (
Austin Schuhe3490622013-03-13 01:24:30 -0700370 num_states, num_inputs, num_outputs, self.ControllerFunction())
Austin Schuh3c542312013-02-24 01:53:50 -0800371
Austin Schuhe3490622013-03-13 01:24:30 -0700372 def DumpController(self):
373 """Returns a c++ function which will create a Controller object.
Austin Schuh3c542312013-02-24 01:53:50 -0800374
375 Returns:
376 string, The function which will create the object.
377 """
378 num_states = self.A.shape[0]
379 num_inputs = self.B.shape[1]
380 num_outputs = self.C.shape[0]
Austin Schuh32501832017-02-25 18:32:56 -0800381 ans = ['StateFeedbackControllerCoefficients<%d, %d, %d> %s {\n' % (
Austin Schuhe3490622013-03-13 01:24:30 -0700382 num_states, num_inputs, num_outputs, self.ControllerFunction())]
Austin Schuh3c542312013-02-24 01:53:50 -0800383
Austin Schuhe3490622013-03-13 01:24:30 -0700384 ans.append(self._DumpMatrix('K', self.K))
Austin Schuh86093ad2016-02-06 14:29:34 -0800385 if not hasattr(self, 'Kff'):
386 self.Kff = numpy.matrix(numpy.zeros(self.K.shape))
387
388 ans.append(self._DumpMatrix('Kff', self.Kff))
Austin Schuh3c542312013-02-24 01:53:50 -0800389
Austin Schuh32501832017-02-25 18:32:56 -0800390 ans.append(' return StateFeedbackControllerCoefficients<%d, %d, %d>'
391 '(K, Kff);\n' % (
Austin Schuhc5fceb82017-02-25 16:24:12 -0800392 num_states, num_inputs, num_outputs))
Austin Schuhe3490622013-03-13 01:24:30 -0700393 ans.append('}\n')
394 return ''.join(ans)
Austin Schuh32501832017-02-25 18:32:56 -0800395
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800396 def DumpObserverHeader(self, observer_coefficient_type):
Austin Schuh32501832017-02-25 18:32:56 -0800397 """Writes out a c++ header declaration which will create a Observer object.
398
399 Returns:
400 string, The header declaration for the function.
401 """
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800402 return '%s %s;\n' % (
403 observer_coefficient_type, self.ObserverFunction())
Austin Schuh32501832017-02-25 18:32:56 -0800404
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800405 def DumpObserver(self, observer_coefficient_type):
Austin Schuh32501832017-02-25 18:32:56 -0800406 """Returns a c++ function which will create a Observer object.
407
408 Returns:
409 string, The function which will create the object.
410 """
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800411 ans = ['%s %s {\n' % (
412 observer_coefficient_type, self.ObserverFunction())]
Austin Schuh32501832017-02-25 18:32:56 -0800413
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800414 if observer_coefficient_type.startswith('StateFeedbackObserver'):
415 ans.append(self._DumpMatrix('L', self.L))
416 ans.append(' return %s(L);\n' % (observer_coefficient_type,))
417 elif observer_coefficient_type.startswith('HybridKalman'):
418 ans.append(self._DumpMatrix('Q_continuous', self.Q_continuous))
419 ans.append(self._DumpMatrix('R_continuous', self.R_continuous))
420 ans.append(self._DumpMatrix('P_steady_state', self.P_steady_state))
421 ans.append(' return %s(Q_continuous, R_continuous, P_steady_state);\n' % (
422 observer_coefficient_type,))
Brian Silvermana3a20cc2017-03-05 18:35:20 -0800423 else:
424 glog.fatal('Unsupported observer type %s', observer_coefficient_type)
Austin Schuh32501832017-02-25 18:32:56 -0800425
Austin Schuh32501832017-02-25 18:32:56 -0800426 ans.append('}\n')
427 return ''.join(ans)
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800428
429class HybridControlLoop(ControlLoop):
430 def __init__(self, name):
431 super(HybridControlLoop, self).__init__(name=name)
432
Brian Silverman59c829a2017-03-05 18:36:54 -0800433 def Discretize(self, dt):
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800434 [self.A, self.B, self.Q, self.R] = \
435 controls.kalmd(self.A_continuous, self.B_continuous,
436 self.Q_continuous, self.R_continuous, dt)
437
438 def PredictHybridObserver(self, U, dt):
Brian Silverman59c829a2017-03-05 18:36:54 -0800439 self.Discretize(dt)
Austin Schuh3ad5ed82017-02-25 21:36:19 -0800440 self.X_hat = self.A * self.X_hat + self.B * U
441 self.P = (self.A * self.P * self.A.T + self.Q)
442
443 def CorrectHybridObserver(self, U):
444 Y_bar = self.Y - self.C * self.X_hat
445 C_t = self.C.T
446 S = self.C * self.P * C_t + self.R
447 self.KalmanGain = self.P * C_t * numpy.linalg.inv(S)
448 self.X_hat = self.X_hat + self.KalmanGain * Y_bar
449 self.P = (numpy.eye(len(self.A)) - self.KalmanGain * self.C) * self.P
450
451 def InitializeState(self):
452 super(HybridControlLoop, self).InitializeState()
453 if hasattr(self, 'Q_steady_state'):
454 self.P = self.Q_steady_state
455 else:
456 self.P = numpy.matrix(numpy.zeros((self.A.shape[0], self.A.shape[0])))