blob: d6bd85fca2fd78f37f8a6896f9b1d9bd1452007e [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):
Ben Fredrickson1b45f782014-02-23 07:44:36 +000019 def __init__(self, gain_schedule_name, loops, namespaces=None, write_constants=False):
Austin Schuhe3490622013-03-13 01:24:30 -070020 """Constructs a control loop writer.
21
22 Args:
23 gain_schedule_name: string, Name of the overall controller.
24 loops: array[ControlLoop], a list of control loops to gain schedule
25 in order.
26 namespaces: array[string], a list of names of namespaces to nest in
27 order. If None, the default will be used.
28 """
29 self._gain_schedule_name = gain_schedule_name
30 self._loops = loops
31 if namespaces:
32 self._namespaces = namespaces
33 else:
34 self._namespaces = ['frc971', 'control_loops']
35
36 self._namespace_start = '\n'.join(
37 ['namespace %s {' % name for name in self._namespaces])
38
39 self._namespace_end = '\n'.join(
40 ['} // namespace %s' % name for name in reversed(self._namespaces)])
Austin Schuh86093ad2016-02-06 14:29:34 -080041
Ben Fredrickson1b45f782014-02-23 07:44:36 +000042 self._constant_list = []
Austin Schuh25933852014-02-23 02:04:13 -080043
44 def AddConstant(self, constant):
45 """Adds a constant to write.
46
47 Args:
48 constant: Constant, the constant to add to the header.
49 """
50 self._constant_list.append(constant)
Austin Schuhe3490622013-03-13 01:24:30 -070051
Brian Silvermane51ad632014-01-08 15:12:29 -080052 def _TopDirectory(self):
53 return self._namespaces[0]
54
Austin Schuhe3490622013-03-13 01:24:30 -070055 def _HeaderGuard(self, header_file):
Austin Schuh16cf47a2015-11-28 13:20:33 -080056 return ('_'.join([namespace.upper() for namespace in self._namespaces]) + '_' +
Austin Schuh572ff402015-11-08 12:17:50 -080057 os.path.basename(header_file).upper()
58 .replace('.', '_').replace('/', '_') + '_')
Austin Schuhe3490622013-03-13 01:24:30 -070059
60 def Write(self, header_file, cc_file):
61 """Writes the loops to the specified files."""
62 self.WriteHeader(header_file)
Austin Schuh572ff402015-11-08 12:17:50 -080063 self.WriteCC(os.path.basename(header_file), cc_file)
Austin Schuhe3490622013-03-13 01:24:30 -070064
65 def _GenericType(self, typename):
66 """Returns a loop template using typename for the type."""
67 num_states = self._loops[0].A.shape[0]
68 num_inputs = self._loops[0].B.shape[1]
69 num_outputs = self._loops[0].C.shape[0]
70 return '%s<%d, %d, %d>' % (
71 typename, num_states, num_inputs, num_outputs)
72
73 def _ControllerType(self):
74 """Returns a template name for StateFeedbackController."""
75 return self._GenericType('StateFeedbackController')
76
77 def _LoopType(self):
78 """Returns a template name for StateFeedbackLoop."""
79 return self._GenericType('StateFeedbackLoop')
80
81 def _PlantType(self):
82 """Returns a template name for StateFeedbackPlant."""
83 return self._GenericType('StateFeedbackPlant')
84
85 def _CoeffType(self):
86 """Returns a template name for StateFeedbackPlantCoefficients."""
87 return self._GenericType('StateFeedbackPlantCoefficients')
88
James Kuszmaul0e866512014-02-21 13:12:52 -080089 def WriteHeader(self, header_file, double_appendage=False, MoI_ratio=0.0):
90 """Writes the header file to the file named header_file.
91 Set double_appendage to true in order to include a ratio of
92 moments of inertia constant. Currently, only used for 2014 claw."""
Austin Schuhe3490622013-03-13 01:24:30 -070093 with open(header_file, 'w') as fd:
94 header_guard = self._HeaderGuard(header_file)
95 fd.write('#ifndef %s\n'
96 '#define %s\n\n' % (header_guard, header_guard))
97 fd.write('#include \"frc971/control_loops/state_feedback_loop.h\"\n')
98 fd.write('\n')
99
100 fd.write(self._namespace_start)
Ben Fredrickson1b45f782014-02-23 07:44:36 +0000101
102 for const in self._constant_list:
103 fd.write(str(const))
104
Austin Schuhe3490622013-03-13 01:24:30 -0700105 fd.write('\n\n')
106 for loop in self._loops:
107 fd.write(loop.DumpPlantHeader())
108 fd.write('\n')
109 fd.write(loop.DumpControllerHeader())
110 fd.write('\n')
111
112 fd.write('%s Make%sPlant();\n\n' %
113 (self._PlantType(), self._gain_schedule_name))
114
115 fd.write('%s Make%sLoop();\n\n' %
116 (self._LoopType(), self._gain_schedule_name))
117
118 fd.write(self._namespace_end)
119 fd.write('\n\n')
120 fd.write("#endif // %s\n" % header_guard)
121
122 def WriteCC(self, header_file_name, cc_file):
123 """Writes the cc file to the file named cc_file."""
124 with open(cc_file, 'w') as fd:
Austin Schuh572ff402015-11-08 12:17:50 -0800125 fd.write('#include \"%s/%s\"\n' %
126 (os.path.join(*self._namespaces), header_file_name))
Austin Schuhe3490622013-03-13 01:24:30 -0700127 fd.write('\n')
128 fd.write('#include <vector>\n')
129 fd.write('\n')
130 fd.write('#include \"frc971/control_loops/state_feedback_loop.h\"\n')
131 fd.write('\n')
132 fd.write(self._namespace_start)
133 fd.write('\n\n')
134 for loop in self._loops:
135 fd.write(loop.DumpPlant())
136 fd.write('\n')
137
138 for loop in self._loops:
139 fd.write(loop.DumpController())
140 fd.write('\n')
141
142 fd.write('%s Make%sPlant() {\n' %
143 (self._PlantType(), self._gain_schedule_name))
Austin Schuh1a387962015-01-31 16:36:20 -0800144 fd.write(' ::std::vector< ::std::unique_ptr<%s>> plants(%d);\n' % (
Austin Schuhe3490622013-03-13 01:24:30 -0700145 self._CoeffType(), len(self._loops)))
146 for index, loop in enumerate(self._loops):
Austin Schuh1a387962015-01-31 16:36:20 -0800147 fd.write(' plants[%d] = ::std::unique_ptr<%s>(new %s(%s));\n' %
148 (index, self._CoeffType(), self._CoeffType(),
Austin Schuhe3490622013-03-13 01:24:30 -0700149 loop.PlantFunction()))
Austin Schuh1a387962015-01-31 16:36:20 -0800150 fd.write(' return %s(&plants);\n' % self._PlantType())
Austin Schuhe3490622013-03-13 01:24:30 -0700151 fd.write('}\n\n')
152
153 fd.write('%s Make%sLoop() {\n' %
154 (self._LoopType(), self._gain_schedule_name))
Austin Schuh1a387962015-01-31 16:36:20 -0800155 fd.write(' ::std::vector< ::std::unique_ptr<%s>> controllers(%d);\n' % (
Austin Schuhe3490622013-03-13 01:24:30 -0700156 self._ControllerType(), len(self._loops)))
157 for index, loop in enumerate(self._loops):
Austin Schuh1a387962015-01-31 16:36:20 -0800158 fd.write(' controllers[%d] = ::std::unique_ptr<%s>(new %s(%s));\n' %
159 (index, self._ControllerType(), self._ControllerType(),
Austin Schuhe3490622013-03-13 01:24:30 -0700160 loop.ControllerFunction()))
Austin Schuh1a387962015-01-31 16:36:20 -0800161 fd.write(' return %s(&controllers);\n' % self._LoopType())
Austin Schuhe3490622013-03-13 01:24:30 -0700162 fd.write('}\n\n')
163
164 fd.write(self._namespace_end)
165 fd.write('\n')
166
167
Austin Schuh3c542312013-02-24 01:53:50 -0800168class ControlLoop(object):
169 def __init__(self, name):
170 """Constructs a control loop object.
171
172 Args:
173 name: string, The name of the loop to use when writing the C++ files.
174 """
175 self._name = name
176
Austin Schuhc1f68892013-03-16 17:06:27 -0700177 def ContinuousToDiscrete(self, A_continuous, B_continuous, dt):
178 """Calculates the discrete time values for A and B.
Austin Schuh3c542312013-02-24 01:53:50 -0800179
180 Args:
181 A_continuous: numpy.matrix, The continuous time A matrix
182 B_continuous: numpy.matrix, The continuous time B matrix
183 dt: float, The time step of the control loop
Austin Schuhc1f68892013-03-16 17:06:27 -0700184
185 Returns:
186 (A, B), numpy.matrix, the control matricies.
Austin Schuh3c542312013-02-24 01:53:50 -0800187 """
Austin Schuhc1f68892013-03-16 17:06:27 -0700188 return controls.c2d(A_continuous, B_continuous, dt)
189
190 def InitializeState(self):
191 """Sets X, Y, and X_hat to zero defaults."""
Austin Schuh3c542312013-02-24 01:53:50 -0800192 self.X = numpy.zeros((self.A.shape[0], 1))
Austin Schuhc1f68892013-03-16 17:06:27 -0700193 self.Y = self.C * self.X
Austin Schuh3c542312013-02-24 01:53:50 -0800194 self.X_hat = numpy.zeros((self.A.shape[0], 1))
195
196 def PlaceControllerPoles(self, poles):
197 """Places the controller poles.
198
199 Args:
200 poles: array, An array of poles. Must be complex conjegates if they have
201 any imaginary portions.
202 """
203 self.K = controls.dplace(self.A, self.B, poles)
204
205 def PlaceObserverPoles(self, poles):
206 """Places the observer poles.
207
208 Args:
209 poles: array, An array of poles. Must be complex conjegates if they have
210 any imaginary portions.
211 """
212 self.L = controls.dplace(self.A.T, self.C.T, poles).T
213
214 def Update(self, U):
215 """Simulates one time step with the provided U."""
Austin Schuh1d005732015-03-01 00:10:20 -0800216 #U = numpy.clip(U, self.U_min, self.U_max)
Austin Schuh3c542312013-02-24 01:53:50 -0800217 self.X = self.A * self.X + self.B * U
218 self.Y = self.C * self.X + self.D * U
219
Austin Schuh1a387962015-01-31 16:36:20 -0800220 def PredictObserver(self, U):
221 """Runs the predict step of the observer update."""
222 self.X_hat = (self.A * self.X_hat + self.B * U)
223
224 def CorrectObserver(self, U):
225 """Runs the correct step of the observer update."""
226 self.X_hat += numpy.linalg.inv(self.A) * self.L * (
227 self.Y - self.C * self.X_hat - self.D * U)
228
Austin Schuh3c542312013-02-24 01:53:50 -0800229 def UpdateObserver(self, U):
230 """Updates the observer given the provided U."""
231 self.X_hat = (self.A * self.X_hat + self.B * U +
232 self.L * (self.Y - self.C * self.X_hat - self.D * U))
233
234 def _DumpMatrix(self, matrix_name, matrix):
235 """Dumps the provided matrix into a variable called matrix_name.
236
237 Args:
238 matrix_name: string, The variable name to save the matrix to.
239 matrix: The matrix to dump.
240
241 Returns:
242 string, The C++ commands required to populate a variable named matrix_name
243 with the contents of matrix.
244 """
Austin Schuhe3490622013-03-13 01:24:30 -0700245 ans = [' Eigen::Matrix<double, %d, %d> %s;\n' % (
Austin Schuh3c542312013-02-24 01:53:50 -0800246 matrix.shape[0], matrix.shape[1], matrix_name)]
Brian Silverman0f637382013-03-03 17:44:46 -0800247 for x in xrange(matrix.shape[0]):
248 for y in xrange(matrix.shape[1]):
Austin Schuhdf79d112016-10-15 21:25:32 -0700249 ans.append(' %s(%d, %d) = %s;\n' % (matrix_name, x, y, repr(matrix[x, y])))
Austin Schuh3c542312013-02-24 01:53:50 -0800250
Austin Schuhe3490622013-03-13 01:24:30 -0700251 return ''.join(ans)
Austin Schuh3c542312013-02-24 01:53:50 -0800252
Austin Schuhe3490622013-03-13 01:24:30 -0700253 def DumpPlantHeader(self):
Austin Schuh3c542312013-02-24 01:53:50 -0800254 """Writes out a c++ header declaration which will create a Plant object.
255
Austin Schuh3c542312013-02-24 01:53:50 -0800256 Returns:
257 string, The header declaration for the function.
258 """
259 num_states = self.A.shape[0]
260 num_inputs = self.B.shape[1]
261 num_outputs = self.C.shape[0]
Austin Schuhe3490622013-03-13 01:24:30 -0700262 return 'StateFeedbackPlantCoefficients<%d, %d, %d> Make%sPlantCoefficients();\n' % (
263 num_states, num_inputs, num_outputs, self._name)
Austin Schuh3c542312013-02-24 01:53:50 -0800264
Austin Schuhe3490622013-03-13 01:24:30 -0700265 def DumpPlant(self):
266 """Writes out a c++ function which will create a PlantCoefficients object.
Austin Schuh3c542312013-02-24 01:53:50 -0800267
268 Returns:
269 string, The function which will create the object.
270 """
271 num_states = self.A.shape[0]
272 num_inputs = self.B.shape[1]
273 num_outputs = self.C.shape[0]
Austin Schuhe3490622013-03-13 01:24:30 -0700274 ans = ['StateFeedbackPlantCoefficients<%d, %d, %d>'
275 ' Make%sPlantCoefficients() {\n' % (
276 num_states, num_inputs, num_outputs, self._name)]
Austin Schuh3c542312013-02-24 01:53:50 -0800277
Austin Schuhe3490622013-03-13 01:24:30 -0700278 ans.append(self._DumpMatrix('A', self.A))
279 ans.append(self._DumpMatrix('B', self.B))
280 ans.append(self._DumpMatrix('C', self.C))
281 ans.append(self._DumpMatrix('D', self.D))
282 ans.append(self._DumpMatrix('U_max', self.U_max))
283 ans.append(self._DumpMatrix('U_min', self.U_min))
Austin Schuh3c542312013-02-24 01:53:50 -0800284
Austin Schuhe3490622013-03-13 01:24:30 -0700285 ans.append(' return StateFeedbackPlantCoefficients<%d, %d, %d>'
286 '(A, B, C, D, U_max, U_min);\n' % (num_states, num_inputs,
Austin Schuh3c542312013-02-24 01:53:50 -0800287 num_outputs))
Austin Schuhe3490622013-03-13 01:24:30 -0700288 ans.append('}\n')
289 return ''.join(ans)
Austin Schuh3c542312013-02-24 01:53:50 -0800290
Austin Schuhe3490622013-03-13 01:24:30 -0700291 def PlantFunction(self):
292 """Returns the name of the plant coefficient function."""
293 return 'Make%sPlantCoefficients()' % self._name
Austin Schuh3c542312013-02-24 01:53:50 -0800294
Austin Schuhe3490622013-03-13 01:24:30 -0700295 def ControllerFunction(self):
296 """Returns the name of the controller function."""
297 return 'Make%sController()' % self._name
298
299 def DumpControllerHeader(self):
300 """Writes out a c++ header declaration which will create a Controller object.
Austin Schuh3c542312013-02-24 01:53:50 -0800301
302 Returns:
303 string, The header declaration for the function.
304 """
305 num_states = self.A.shape[0]
306 num_inputs = self.B.shape[1]
307 num_outputs = self.C.shape[0]
Austin Schuhe3490622013-03-13 01:24:30 -0700308 return 'StateFeedbackController<%d, %d, %d> %s;\n' % (
309 num_states, num_inputs, num_outputs, self.ControllerFunction())
Austin Schuh3c542312013-02-24 01:53:50 -0800310
Austin Schuhe3490622013-03-13 01:24:30 -0700311 def DumpController(self):
312 """Returns a c++ function which will create a Controller object.
Austin Schuh3c542312013-02-24 01:53:50 -0800313
314 Returns:
315 string, The function which will create the object.
316 """
317 num_states = self.A.shape[0]
318 num_inputs = self.B.shape[1]
319 num_outputs = self.C.shape[0]
Austin Schuhe3490622013-03-13 01:24:30 -0700320 ans = ['StateFeedbackController<%d, %d, %d> %s {\n' % (
321 num_states, num_inputs, num_outputs, self.ControllerFunction())]
Austin Schuh3c542312013-02-24 01:53:50 -0800322
Austin Schuhe3490622013-03-13 01:24:30 -0700323 ans.append(self._DumpMatrix('L', self.L))
324 ans.append(self._DumpMatrix('K', self.K))
Austin Schuh86093ad2016-02-06 14:29:34 -0800325 if not hasattr(self, 'Kff'):
326 self.Kff = numpy.matrix(numpy.zeros(self.K.shape))
327
328 ans.append(self._DumpMatrix('Kff', self.Kff))
Austin Schuh1a387962015-01-31 16:36:20 -0800329 ans.append(self._DumpMatrix('A_inv', numpy.linalg.inv(self.A)))
Austin Schuh3c542312013-02-24 01:53:50 -0800330
Austin Schuhe3490622013-03-13 01:24:30 -0700331 ans.append(' return StateFeedbackController<%d, %d, %d>'
Austin Schuh86093ad2016-02-06 14:29:34 -0800332 '(L, K, Kff, A_inv, Make%sPlantCoefficients());\n' % (
Austin Schuh1a387962015-01-31 16:36:20 -0800333 num_states, num_inputs, num_outputs, self._name))
Austin Schuhe3490622013-03-13 01:24:30 -0700334 ans.append('}\n')
335 return ''.join(ans)