blob: a103c7997bf436ec446775b8e26b6f56b0a1dc69 [file] [log] [blame]
Austin Schuh3c542312013-02-24 01:53:50 -08001import controls
2import numpy
3
Ben Fredrickson1b45f782014-02-23 07:44:36 +00004class Constant(object):
5 def __init__ (self, name, formatt, value):
6 self.name = name
7 self.formatt = formatt
8 self.value = value
9 self.formatToType = {}
10 self.formatToType['%f'] = "double";
11 self.formatToType['%d'] = "int";
12 def __str__ (self):
Austin Schuh25933852014-02-23 02:04:13 -080013 return str("\nstatic constexpr %s %s = "+ self.formatt +";\n") % \
Ben Fredrickson1b45f782014-02-23 07:44:36 +000014 (self.formatToType[self.formatt], self.name, self.value)
15
16
Austin Schuhe3490622013-03-13 01:24:30 -070017class ControlLoopWriter(object):
Ben Fredrickson1b45f782014-02-23 07:44:36 +000018 def __init__(self, gain_schedule_name, loops, namespaces=None, write_constants=False):
Austin Schuhe3490622013-03-13 01:24:30 -070019 """Constructs a control loop writer.
20
21 Args:
22 gain_schedule_name: string, Name of the overall controller.
23 loops: array[ControlLoop], a list of control loops to gain schedule
24 in order.
25 namespaces: array[string], a list of names of namespaces to nest in
26 order. If None, the default will be used.
27 """
28 self._gain_schedule_name = gain_schedule_name
29 self._loops = loops
30 if namespaces:
31 self._namespaces = namespaces
32 else:
33 self._namespaces = ['frc971', 'control_loops']
34
35 self._namespace_start = '\n'.join(
36 ['namespace %s {' % name for name in self._namespaces])
37
38 self._namespace_end = '\n'.join(
39 ['} // namespace %s' % name for name in reversed(self._namespaces)])
Ben Fredrickson1b45f782014-02-23 07:44:36 +000040
41 self._constant_list = []
Austin Schuh25933852014-02-23 02:04:13 -080042
43 def AddConstant(self, constant):
44 """Adds a constant to write.
45
46 Args:
47 constant: Constant, the constant to add to the header.
48 """
49 self._constant_list.append(constant)
Austin Schuhe3490622013-03-13 01:24:30 -070050
Brian Silvermane51ad632014-01-08 15:12:29 -080051 def _TopDirectory(self):
52 return self._namespaces[0]
53
Austin Schuhe3490622013-03-13 01:24:30 -070054 def _HeaderGuard(self, header_file):
Brian Silvermane51ad632014-01-08 15:12:29 -080055 return (self._TopDirectory().upper() + '_CONTROL_LOOPS_' +
Austin Schuhe3490622013-03-13 01:24:30 -070056 header_file.upper().replace('.', '_').replace('/', '_') +
57 '_')
58
59 def Write(self, header_file, cc_file):
60 """Writes the loops to the specified files."""
61 self.WriteHeader(header_file)
62 self.WriteCC(header_file, cc_file)
63
64 def _GenericType(self, typename):
65 """Returns a loop template using typename for the type."""
66 num_states = self._loops[0].A.shape[0]
67 num_inputs = self._loops[0].B.shape[1]
68 num_outputs = self._loops[0].C.shape[0]
69 return '%s<%d, %d, %d>' % (
70 typename, num_states, num_inputs, num_outputs)
71
72 def _ControllerType(self):
73 """Returns a template name for StateFeedbackController."""
74 return self._GenericType('StateFeedbackController')
75
76 def _LoopType(self):
77 """Returns a template name for StateFeedbackLoop."""
78 return self._GenericType('StateFeedbackLoop')
79
80 def _PlantType(self):
81 """Returns a template name for StateFeedbackPlant."""
82 return self._GenericType('StateFeedbackPlant')
83
84 def _CoeffType(self):
85 """Returns a template name for StateFeedbackPlantCoefficients."""
86 return self._GenericType('StateFeedbackPlantCoefficients')
87
James Kuszmaul0e866512014-02-21 13:12:52 -080088 def WriteHeader(self, header_file, double_appendage=False, MoI_ratio=0.0):
89 """Writes the header file to the file named header_file.
90 Set double_appendage to true in order to include a ratio of
91 moments of inertia constant. Currently, only used for 2014 claw."""
Austin Schuhe3490622013-03-13 01:24:30 -070092 with open(header_file, 'w') as fd:
93 header_guard = self._HeaderGuard(header_file)
94 fd.write('#ifndef %s\n'
95 '#define %s\n\n' % (header_guard, header_guard))
96 fd.write('#include \"frc971/control_loops/state_feedback_loop.h\"\n')
97 fd.write('\n')
98
99 fd.write(self._namespace_start)
Ben Fredrickson1b45f782014-02-23 07:44:36 +0000100
101 for const in self._constant_list:
102 fd.write(str(const))
103
Austin Schuhe3490622013-03-13 01:24:30 -0700104 fd.write('\n\n')
105 for loop in self._loops:
106 fd.write(loop.DumpPlantHeader())
107 fd.write('\n')
108 fd.write(loop.DumpControllerHeader())
109 fd.write('\n')
110
111 fd.write('%s Make%sPlant();\n\n' %
112 (self._PlantType(), self._gain_schedule_name))
113
114 fd.write('%s Make%sLoop();\n\n' %
115 (self._LoopType(), self._gain_schedule_name))
116
James Kuszmaul0e866512014-02-21 13:12:52 -0800117 fd.write('const double k%sMomentOfInertiaRatio = %f;\n\n' %
118 (self._gain_schedule_name,
119 self._loops[0].J_top / self._loops[0].J_bottom))
120
Austin Schuhe3490622013-03-13 01:24:30 -0700121 fd.write(self._namespace_end)
122 fd.write('\n\n')
123 fd.write("#endif // %s\n" % header_guard)
124
125 def WriteCC(self, header_file_name, cc_file):
126 """Writes the cc file to the file named cc_file."""
127 with open(cc_file, 'w') as fd:
Brian Silvermandf3e7b22013-11-08 19:43:27 -0800128 fd.write('#include \"%s/control_loops/%s\"\n' %
Brian Silvermane51ad632014-01-08 15:12:29 -0800129 (self._TopDirectory(), header_file_name))
Austin Schuhe3490622013-03-13 01:24:30 -0700130 fd.write('\n')
131 fd.write('#include <vector>\n')
132 fd.write('\n')
133 fd.write('#include \"frc971/control_loops/state_feedback_loop.h\"\n')
134 fd.write('\n')
135 fd.write(self._namespace_start)
136 fd.write('\n\n')
137 for loop in self._loops:
138 fd.write(loop.DumpPlant())
139 fd.write('\n')
140
141 for loop in self._loops:
142 fd.write(loop.DumpController())
143 fd.write('\n')
144
145 fd.write('%s Make%sPlant() {\n' %
146 (self._PlantType(), self._gain_schedule_name))
147 fd.write(' ::std::vector<%s *> plants(%d);\n' % (
148 self._CoeffType(), len(self._loops)))
149 for index, loop in enumerate(self._loops):
150 fd.write(' plants[%d] = new %s(%s);\n' %
151 (index, self._CoeffType(),
152 loop.PlantFunction()))
153 fd.write(' return %s(plants);\n' % self._PlantType())
154 fd.write('}\n\n')
155
156 fd.write('%s Make%sLoop() {\n' %
157 (self._LoopType(), self._gain_schedule_name))
158 fd.write(' ::std::vector<%s *> controllers(%d);\n' % (
159 self._ControllerType(), len(self._loops)))
160 for index, loop in enumerate(self._loops):
161 fd.write(' controllers[%d] = new %s(%s);\n' %
162 (index, self._ControllerType(),
163 loop.ControllerFunction()))
164 fd.write(' return %s(controllers);\n' % self._LoopType())
165 fd.write('}\n\n')
166
167 fd.write(self._namespace_end)
168 fd.write('\n')
169
170
Austin Schuh3c542312013-02-24 01:53:50 -0800171class ControlLoop(object):
172 def __init__(self, name):
173 """Constructs a control loop object.
174
175 Args:
176 name: string, The name of the loop to use when writing the C++ files.
177 """
178 self._name = name
179
Austin Schuhc1f68892013-03-16 17:06:27 -0700180 def ContinuousToDiscrete(self, A_continuous, B_continuous, dt):
181 """Calculates the discrete time values for A and B.
Austin Schuh3c542312013-02-24 01:53:50 -0800182
183 Args:
184 A_continuous: numpy.matrix, The continuous time A matrix
185 B_continuous: numpy.matrix, The continuous time B matrix
186 dt: float, The time step of the control loop
Austin Schuhc1f68892013-03-16 17:06:27 -0700187
188 Returns:
189 (A, B), numpy.matrix, the control matricies.
Austin Schuh3c542312013-02-24 01:53:50 -0800190 """
Austin Schuhc1f68892013-03-16 17:06:27 -0700191 return controls.c2d(A_continuous, B_continuous, dt)
192
193 def InitializeState(self):
194 """Sets X, Y, and X_hat to zero defaults."""
Austin Schuh3c542312013-02-24 01:53:50 -0800195 self.X = numpy.zeros((self.A.shape[0], 1))
Austin Schuhc1f68892013-03-16 17:06:27 -0700196 self.Y = self.C * self.X
Austin Schuh3c542312013-02-24 01:53:50 -0800197 self.X_hat = numpy.zeros((self.A.shape[0], 1))
198
199 def PlaceControllerPoles(self, poles):
200 """Places the controller poles.
201
202 Args:
203 poles: array, An array of poles. Must be complex conjegates if they have
204 any imaginary portions.
205 """
206 self.K = controls.dplace(self.A, self.B, poles)
207
208 def PlaceObserverPoles(self, poles):
209 """Places the observer poles.
210
211 Args:
212 poles: array, An array of poles. Must be complex conjegates if they have
213 any imaginary portions.
214 """
215 self.L = controls.dplace(self.A.T, self.C.T, poles).T
216
217 def Update(self, U):
218 """Simulates one time step with the provided U."""
James Kuszmaulc02a39a2014-02-18 15:45:16 -0800219 #U = numpy.clip(U, self.U_min, self.U_max)
Austin Schuh3c542312013-02-24 01:53:50 -0800220 self.X = self.A * self.X + self.B * U
221 self.Y = self.C * self.X + self.D * U
222
223 def UpdateObserver(self, U):
224 """Updates the observer given the provided U."""
225 self.X_hat = (self.A * self.X_hat + self.B * U +
226 self.L * (self.Y - self.C * self.X_hat - self.D * U))
227
228 def _DumpMatrix(self, matrix_name, matrix):
229 """Dumps the provided matrix into a variable called matrix_name.
230
231 Args:
232 matrix_name: string, The variable name to save the matrix to.
233 matrix: The matrix to dump.
234
235 Returns:
236 string, The C++ commands required to populate a variable named matrix_name
237 with the contents of matrix.
238 """
Austin Schuhe3490622013-03-13 01:24:30 -0700239 ans = [' Eigen::Matrix<double, %d, %d> %s;\n' % (
Austin Schuh3c542312013-02-24 01:53:50 -0800240 matrix.shape[0], matrix.shape[1], matrix_name)]
241 first = True
Brian Silverman0f637382013-03-03 17:44:46 -0800242 for x in xrange(matrix.shape[0]):
243 for y in xrange(matrix.shape[1]):
Austin Schuh7ec34fd2014-02-15 22:27:46 -0800244 element = matrix[x, y]
Brian Silverman0f637382013-03-03 17:44:46 -0800245 if first:
Austin Schuhe3490622013-03-13 01:24:30 -0700246 ans.append(' %s << ' % matrix_name)
Brian Silverman0f637382013-03-03 17:44:46 -0800247 first = False
248 else:
Austin Schuhe3490622013-03-13 01:24:30 -0700249 ans.append(', ')
Brian Silverman0f637382013-03-03 17:44:46 -0800250 ans.append(str(element))
Austin Schuh3c542312013-02-24 01:53:50 -0800251
Austin Schuhe3490622013-03-13 01:24:30 -0700252 ans.append(';\n')
253 return ''.join(ans)
Austin Schuh3c542312013-02-24 01:53:50 -0800254
Austin Schuhe3490622013-03-13 01:24:30 -0700255 def DumpPlantHeader(self):
Austin Schuh3c542312013-02-24 01:53:50 -0800256 """Writes out a c++ header declaration which will create a Plant object.
257
Austin Schuh3c542312013-02-24 01:53:50 -0800258 Returns:
259 string, The header declaration for the function.
260 """
261 num_states = self.A.shape[0]
262 num_inputs = self.B.shape[1]
263 num_outputs = self.C.shape[0]
Austin Schuhe3490622013-03-13 01:24:30 -0700264 return 'StateFeedbackPlantCoefficients<%d, %d, %d> Make%sPlantCoefficients();\n' % (
265 num_states, num_inputs, num_outputs, self._name)
Austin Schuh3c542312013-02-24 01:53:50 -0800266
Austin Schuhe3490622013-03-13 01:24:30 -0700267 def DumpPlant(self):
268 """Writes out a c++ function which will create a PlantCoefficients object.
Austin Schuh3c542312013-02-24 01:53:50 -0800269
270 Returns:
271 string, The function which will create the object.
272 """
273 num_states = self.A.shape[0]
274 num_inputs = self.B.shape[1]
275 num_outputs = self.C.shape[0]
Austin Schuhe3490622013-03-13 01:24:30 -0700276 ans = ['StateFeedbackPlantCoefficients<%d, %d, %d>'
277 ' Make%sPlantCoefficients() {\n' % (
278 num_states, num_inputs, num_outputs, self._name)]
Austin Schuh3c542312013-02-24 01:53:50 -0800279
Austin Schuhe3490622013-03-13 01:24:30 -0700280 ans.append(self._DumpMatrix('A', self.A))
281 ans.append(self._DumpMatrix('B', self.B))
282 ans.append(self._DumpMatrix('C', self.C))
283 ans.append(self._DumpMatrix('D', self.D))
284 ans.append(self._DumpMatrix('U_max', self.U_max))
285 ans.append(self._DumpMatrix('U_min', self.U_min))
Austin Schuh3c542312013-02-24 01:53:50 -0800286
Austin Schuhe3490622013-03-13 01:24:30 -0700287 ans.append(' return StateFeedbackPlantCoefficients<%d, %d, %d>'
288 '(A, B, C, D, U_max, U_min);\n' % (num_states, num_inputs,
Austin Schuh3c542312013-02-24 01:53:50 -0800289 num_outputs))
Austin Schuhe3490622013-03-13 01:24:30 -0700290 ans.append('}\n')
291 return ''.join(ans)
Austin Schuh3c542312013-02-24 01:53:50 -0800292
Austin Schuhe3490622013-03-13 01:24:30 -0700293 def PlantFunction(self):
294 """Returns the name of the plant coefficient function."""
295 return 'Make%sPlantCoefficients()' % self._name
Austin Schuh3c542312013-02-24 01:53:50 -0800296
Austin Schuhe3490622013-03-13 01:24:30 -0700297 def ControllerFunction(self):
298 """Returns the name of the controller function."""
299 return 'Make%sController()' % self._name
300
301 def DumpControllerHeader(self):
302 """Writes out a c++ header declaration which will create a Controller object.
Austin Schuh3c542312013-02-24 01:53:50 -0800303
304 Returns:
305 string, The header declaration for the function.
306 """
307 num_states = self.A.shape[0]
308 num_inputs = self.B.shape[1]
309 num_outputs = self.C.shape[0]
Austin Schuhe3490622013-03-13 01:24:30 -0700310 return 'StateFeedbackController<%d, %d, %d> %s;\n' % (
311 num_states, num_inputs, num_outputs, self.ControllerFunction())
Austin Schuh3c542312013-02-24 01:53:50 -0800312
Austin Schuhe3490622013-03-13 01:24:30 -0700313 def DumpController(self):
314 """Returns a c++ function which will create a Controller object.
Austin Schuh3c542312013-02-24 01:53:50 -0800315
316 Returns:
317 string, The function which will create the object.
318 """
319 num_states = self.A.shape[0]
320 num_inputs = self.B.shape[1]
321 num_outputs = self.C.shape[0]
Austin Schuhe3490622013-03-13 01:24:30 -0700322 ans = ['StateFeedbackController<%d, %d, %d> %s {\n' % (
323 num_states, num_inputs, num_outputs, self.ControllerFunction())]
Austin Schuh3c542312013-02-24 01:53:50 -0800324
Austin Schuhe3490622013-03-13 01:24:30 -0700325 ans.append(self._DumpMatrix('L', self.L))
326 ans.append(self._DumpMatrix('K', self.K))
Austin Schuh3c542312013-02-24 01:53:50 -0800327
Austin Schuhe3490622013-03-13 01:24:30 -0700328 ans.append(' return StateFeedbackController<%d, %d, %d>'
329 '(L, K, Make%sPlantCoefficients());\n' % (num_states, num_inputs,
330 num_outputs, self._name))
331 ans.append('}\n')
332 return ''.join(ans)