blob: e8900af40e73dcfb4005b4fa2465bfe610a9069e [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):
Austin Schuh66c19882017-02-25 13:36:28 -080074 """Returns a template name for StateFeedbackControllerConstants."""
75 return self._GenericType('StateFeedbackControllerConstants')
Austin Schuhe3490622013-03-13 01:24:30 -070076
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 Schuhc5fceb82017-02-25 16:24:12 -0800161 fd.write(' return %s(Make%sPlant(), &controllers);\n' %
162 (self._LoopType(), self._gain_schedule_name))
Austin Schuhe3490622013-03-13 01:24:30 -0700163 fd.write('}\n\n')
164
165 fd.write(self._namespace_end)
166 fd.write('\n')
167
168
Austin Schuh3c542312013-02-24 01:53:50 -0800169class ControlLoop(object):
170 def __init__(self, name):
171 """Constructs a control loop object.
172
173 Args:
174 name: string, The name of the loop to use when writing the C++ files.
175 """
176 self._name = name
177
Austin Schuhc1f68892013-03-16 17:06:27 -0700178 def ContinuousToDiscrete(self, A_continuous, B_continuous, dt):
179 """Calculates the discrete time values for A and B.
Austin Schuh3c542312013-02-24 01:53:50 -0800180
181 Args:
182 A_continuous: numpy.matrix, The continuous time A matrix
183 B_continuous: numpy.matrix, The continuous time B matrix
184 dt: float, The time step of the control loop
Austin Schuhc1f68892013-03-16 17:06:27 -0700185
186 Returns:
187 (A, B), numpy.matrix, the control matricies.
Austin Schuh3c542312013-02-24 01:53:50 -0800188 """
Austin Schuhc1f68892013-03-16 17:06:27 -0700189 return controls.c2d(A_continuous, B_continuous, dt)
190
191 def InitializeState(self):
192 """Sets X, Y, and X_hat to zero defaults."""
Austin Schuh3c542312013-02-24 01:53:50 -0800193 self.X = numpy.zeros((self.A.shape[0], 1))
Austin Schuhc1f68892013-03-16 17:06:27 -0700194 self.Y = self.C * self.X
Austin Schuh3c542312013-02-24 01:53:50 -0800195 self.X_hat = numpy.zeros((self.A.shape[0], 1))
196
197 def PlaceControllerPoles(self, poles):
198 """Places the controller poles.
199
200 Args:
201 poles: array, An array of poles. Must be complex conjegates if they have
202 any imaginary portions.
203 """
204 self.K = controls.dplace(self.A, self.B, poles)
205
206 def PlaceObserverPoles(self, poles):
207 """Places the observer poles.
208
209 Args:
210 poles: array, An array of poles. Must be complex conjegates if they have
211 any imaginary portions.
212 """
213 self.L = controls.dplace(self.A.T, self.C.T, poles).T
214
215 def Update(self, U):
216 """Simulates one time step with the provided U."""
Austin Schuh1d005732015-03-01 00:10:20 -0800217 #U = numpy.clip(U, self.U_min, self.U_max)
Austin Schuh3c542312013-02-24 01:53:50 -0800218 self.X = self.A * self.X + self.B * U
219 self.Y = self.C * self.X + self.D * U
220
Austin Schuh1a387962015-01-31 16:36:20 -0800221 def PredictObserver(self, U):
222 """Runs the predict step of the observer update."""
223 self.X_hat = (self.A * self.X_hat + self.B * U)
224
225 def CorrectObserver(self, U):
226 """Runs the correct step of the observer update."""
227 self.X_hat += numpy.linalg.inv(self.A) * self.L * (
228 self.Y - self.C * self.X_hat - self.D * U)
229
Austin Schuh3c542312013-02-24 01:53:50 -0800230 def UpdateObserver(self, U):
231 """Updates the observer given the provided U."""
232 self.X_hat = (self.A * self.X_hat + self.B * U +
233 self.L * (self.Y - self.C * self.X_hat - self.D * U))
234
235 def _DumpMatrix(self, matrix_name, matrix):
236 """Dumps the provided matrix into a variable called matrix_name.
237
238 Args:
239 matrix_name: string, The variable name to save the matrix to.
240 matrix: The matrix to dump.
241
242 Returns:
243 string, The C++ commands required to populate a variable named matrix_name
244 with the contents of matrix.
245 """
Austin Schuhe3490622013-03-13 01:24:30 -0700246 ans = [' Eigen::Matrix<double, %d, %d> %s;\n' % (
Austin Schuh3c542312013-02-24 01:53:50 -0800247 matrix.shape[0], matrix.shape[1], matrix_name)]
Brian Silverman0f637382013-03-03 17:44:46 -0800248 for x in xrange(matrix.shape[0]):
249 for y in xrange(matrix.shape[1]):
Austin Schuhdf79d112016-10-15 21:25:32 -0700250 ans.append(' %s(%d, %d) = %s;\n' % (matrix_name, x, y, repr(matrix[x, y])))
Austin Schuh3c542312013-02-24 01:53:50 -0800251
Austin Schuhe3490622013-03-13 01:24:30 -0700252 return ''.join(ans)
Austin Schuh3c542312013-02-24 01:53:50 -0800253
Austin Schuhe3490622013-03-13 01:24:30 -0700254 def DumpPlantHeader(self):
Austin Schuh3c542312013-02-24 01:53:50 -0800255 """Writes out a c++ header declaration which will create a Plant object.
256
Austin Schuh3c542312013-02-24 01:53:50 -0800257 Returns:
258 string, The header declaration for the function.
259 """
260 num_states = self.A.shape[0]
261 num_inputs = self.B.shape[1]
262 num_outputs = self.C.shape[0]
Austin Schuhe3490622013-03-13 01:24:30 -0700263 return 'StateFeedbackPlantCoefficients<%d, %d, %d> Make%sPlantCoefficients();\n' % (
264 num_states, num_inputs, num_outputs, self._name)
Austin Schuh3c542312013-02-24 01:53:50 -0800265
Austin Schuhe3490622013-03-13 01:24:30 -0700266 def DumpPlant(self):
267 """Writes out a c++ function which will create a PlantCoefficients object.
Austin Schuh3c542312013-02-24 01:53:50 -0800268
269 Returns:
270 string, The function which will create the object.
271 """
272 num_states = self.A.shape[0]
273 num_inputs = self.B.shape[1]
274 num_outputs = self.C.shape[0]
Austin Schuhe3490622013-03-13 01:24:30 -0700275 ans = ['StateFeedbackPlantCoefficients<%d, %d, %d>'
276 ' Make%sPlantCoefficients() {\n' % (
277 num_states, num_inputs, num_outputs, self._name)]
Austin Schuh3c542312013-02-24 01:53:50 -0800278
Austin Schuhe3490622013-03-13 01:24:30 -0700279 ans.append(self._DumpMatrix('A', self.A))
Austin Schuhc5fceb82017-02-25 16:24:12 -0800280 ans.append(self._DumpMatrix('A_inv', numpy.linalg.inv(self.A)))
Austin Schuh6c20f202017-02-18 22:31:44 -0800281 ans.append(self._DumpMatrix('A_continuous', self.A_continuous))
Austin Schuhe3490622013-03-13 01:24:30 -0700282 ans.append(self._DumpMatrix('B', self.B))
Austin Schuh6c20f202017-02-18 22:31:44 -0800283 ans.append(self._DumpMatrix('B_continuous', self.B_continuous))
Austin Schuhe3490622013-03-13 01:24:30 -0700284 ans.append(self._DumpMatrix('C', self.C))
285 ans.append(self._DumpMatrix('D', self.D))
286 ans.append(self._DumpMatrix('U_max', self.U_max))
287 ans.append(self._DumpMatrix('U_min', self.U_min))
Austin Schuh3c542312013-02-24 01:53:50 -0800288
Austin Schuhe3490622013-03-13 01:24:30 -0700289 ans.append(' return StateFeedbackPlantCoefficients<%d, %d, %d>'
Austin Schuhc5fceb82017-02-25 16:24:12 -0800290 '(A, A_inv, A_continuous, B, B_continuous, C, D, U_max, U_min);\n' % (
Austin Schuh6c20f202017-02-18 22:31:44 -0800291 num_states, num_inputs, num_outputs))
Austin Schuhe3490622013-03-13 01:24:30 -0700292 ans.append('}\n')
293 return ''.join(ans)
Austin Schuh3c542312013-02-24 01:53:50 -0800294
Austin Schuhe3490622013-03-13 01:24:30 -0700295 def PlantFunction(self):
296 """Returns the name of the plant coefficient function."""
297 return 'Make%sPlantCoefficients()' % self._name
Austin Schuh3c542312013-02-24 01:53:50 -0800298
Austin Schuhe3490622013-03-13 01:24:30 -0700299 def ControllerFunction(self):
300 """Returns the name of the controller function."""
301 return 'Make%sController()' % self._name
302
303 def DumpControllerHeader(self):
304 """Writes out a c++ header declaration which will create a Controller object.
Austin Schuh3c542312013-02-24 01:53:50 -0800305
306 Returns:
307 string, The header declaration for the function.
308 """
309 num_states = self.A.shape[0]
310 num_inputs = self.B.shape[1]
311 num_outputs = self.C.shape[0]
Austin Schuh66c19882017-02-25 13:36:28 -0800312 return 'StateFeedbackControllerConstants<%d, %d, %d> %s;\n' % (
Austin Schuhe3490622013-03-13 01:24:30 -0700313 num_states, num_inputs, num_outputs, self.ControllerFunction())
Austin Schuh3c542312013-02-24 01:53:50 -0800314
Austin Schuhe3490622013-03-13 01:24:30 -0700315 def DumpController(self):
316 """Returns a c++ function which will create a Controller object.
Austin Schuh3c542312013-02-24 01:53:50 -0800317
318 Returns:
319 string, The function which will create the object.
320 """
321 num_states = self.A.shape[0]
322 num_inputs = self.B.shape[1]
323 num_outputs = self.C.shape[0]
Austin Schuh66c19882017-02-25 13:36:28 -0800324 ans = ['StateFeedbackControllerConstants<%d, %d, %d> %s {\n' % (
Austin Schuhe3490622013-03-13 01:24:30 -0700325 num_states, num_inputs, num_outputs, self.ControllerFunction())]
Austin Schuh3c542312013-02-24 01:53:50 -0800326
Austin Schuhe3490622013-03-13 01:24:30 -0700327 ans.append(self._DumpMatrix('L', self.L))
328 ans.append(self._DumpMatrix('K', self.K))
Austin Schuh86093ad2016-02-06 14:29:34 -0800329 if not hasattr(self, 'Kff'):
330 self.Kff = numpy.matrix(numpy.zeros(self.K.shape))
331
332 ans.append(self._DumpMatrix('Kff', self.Kff))
Austin Schuh3c542312013-02-24 01:53:50 -0800333
Austin Schuh66c19882017-02-25 13:36:28 -0800334 ans.append(' return StateFeedbackControllerConstants<%d, %d, %d>'
Austin Schuhc5fceb82017-02-25 16:24:12 -0800335 '(L, K, Kff);\n' % (
336 num_states, num_inputs, num_outputs))
Austin Schuhe3490622013-03-13 01:24:30 -0700337 ans.append('}\n')
338 return ''.join(ans)