blob: 51ce0ffd70835a2d84c059e6ab0c1d6c6aba69f7 [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):
13 return str("\nstatic const %s %s = "+ self.formatt +";\n") % \
14 (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 = []
42 if (write_constants):
43 self._constant_list.append(Constant("kMaxExtension", "%f", 0.32385));
44 self._constant_list.append(Constant("kSpringConstant", "%f", 0.28));
Austin Schuhe3490622013-03-13 01:24:30 -070045
Brian Silvermane51ad632014-01-08 15:12:29 -080046 def _TopDirectory(self):
47 return self._namespaces[0]
48
Austin Schuhe3490622013-03-13 01:24:30 -070049 def _HeaderGuard(self, header_file):
Brian Silvermane51ad632014-01-08 15:12:29 -080050 return (self._TopDirectory().upper() + '_CONTROL_LOOPS_' +
Austin Schuhe3490622013-03-13 01:24:30 -070051 header_file.upper().replace('.', '_').replace('/', '_') +
52 '_')
53
54 def Write(self, header_file, cc_file):
55 """Writes the loops to the specified files."""
56 self.WriteHeader(header_file)
57 self.WriteCC(header_file, cc_file)
58
59 def _GenericType(self, typename):
60 """Returns a loop template using typename for the type."""
61 num_states = self._loops[0].A.shape[0]
62 num_inputs = self._loops[0].B.shape[1]
63 num_outputs = self._loops[0].C.shape[0]
64 return '%s<%d, %d, %d>' % (
65 typename, num_states, num_inputs, num_outputs)
66
67 def _ControllerType(self):
68 """Returns a template name for StateFeedbackController."""
69 return self._GenericType('StateFeedbackController')
70
71 def _LoopType(self):
72 """Returns a template name for StateFeedbackLoop."""
73 return self._GenericType('StateFeedbackLoop')
74
75 def _PlantType(self):
76 """Returns a template name for StateFeedbackPlant."""
77 return self._GenericType('StateFeedbackPlant')
78
79 def _CoeffType(self):
80 """Returns a template name for StateFeedbackPlantCoefficients."""
81 return self._GenericType('StateFeedbackPlantCoefficients')
82
83 def WriteHeader(self, header_file):
84 """Writes the header file to the file named header_file."""
85 with open(header_file, 'w') as fd:
86 header_guard = self._HeaderGuard(header_file)
87 fd.write('#ifndef %s\n'
88 '#define %s\n\n' % (header_guard, header_guard))
89 fd.write('#include \"frc971/control_loops/state_feedback_loop.h\"\n')
90 fd.write('\n')
91
92 fd.write(self._namespace_start)
Ben Fredrickson1b45f782014-02-23 07:44:36 +000093
94 for const in self._constant_list:
95 fd.write(str(const))
96
Austin Schuhe3490622013-03-13 01:24:30 -070097 fd.write('\n\n')
98 for loop in self._loops:
99 fd.write(loop.DumpPlantHeader())
100 fd.write('\n')
101 fd.write(loop.DumpControllerHeader())
102 fd.write('\n')
103
104 fd.write('%s Make%sPlant();\n\n' %
105 (self._PlantType(), self._gain_schedule_name))
106
107 fd.write('%s Make%sLoop();\n\n' %
108 (self._LoopType(), self._gain_schedule_name))
109
110 fd.write(self._namespace_end)
111 fd.write('\n\n')
112 fd.write("#endif // %s\n" % header_guard)
113
114 def WriteCC(self, header_file_name, cc_file):
115 """Writes the cc file to the file named cc_file."""
116 with open(cc_file, 'w') as fd:
Brian Silvermandf3e7b22013-11-08 19:43:27 -0800117 fd.write('#include \"%s/control_loops/%s\"\n' %
Brian Silvermane51ad632014-01-08 15:12:29 -0800118 (self._TopDirectory(), header_file_name))
Austin Schuhe3490622013-03-13 01:24:30 -0700119 fd.write('\n')
120 fd.write('#include <vector>\n')
121 fd.write('\n')
122 fd.write('#include \"frc971/control_loops/state_feedback_loop.h\"\n')
123 fd.write('\n')
124 fd.write(self._namespace_start)
125 fd.write('\n\n')
126 for loop in self._loops:
127 fd.write(loop.DumpPlant())
128 fd.write('\n')
129
130 for loop in self._loops:
131 fd.write(loop.DumpController())
132 fd.write('\n')
133
134 fd.write('%s Make%sPlant() {\n' %
135 (self._PlantType(), self._gain_schedule_name))
136 fd.write(' ::std::vector<%s *> plants(%d);\n' % (
137 self._CoeffType(), len(self._loops)))
138 for index, loop in enumerate(self._loops):
139 fd.write(' plants[%d] = new %s(%s);\n' %
140 (index, self._CoeffType(),
141 loop.PlantFunction()))
142 fd.write(' return %s(plants);\n' % self._PlantType())
143 fd.write('}\n\n')
144
145 fd.write('%s Make%sLoop() {\n' %
146 (self._LoopType(), self._gain_schedule_name))
147 fd.write(' ::std::vector<%s *> controllers(%d);\n' % (
148 self._ControllerType(), len(self._loops)))
149 for index, loop in enumerate(self._loops):
150 fd.write(' controllers[%d] = new %s(%s);\n' %
151 (index, self._ControllerType(),
152 loop.ControllerFunction()))
153 fd.write(' return %s(controllers);\n' % self._LoopType())
154 fd.write('}\n\n')
155
156 fd.write(self._namespace_end)
157 fd.write('\n')
158
159
Austin Schuh3c542312013-02-24 01:53:50 -0800160class ControlLoop(object):
161 def __init__(self, name):
162 """Constructs a control loop object.
163
164 Args:
165 name: string, The name of the loop to use when writing the C++ files.
166 """
167 self._name = name
168
Austin Schuhc1f68892013-03-16 17:06:27 -0700169 def ContinuousToDiscrete(self, A_continuous, B_continuous, dt):
170 """Calculates the discrete time values for A and B.
Austin Schuh3c542312013-02-24 01:53:50 -0800171
172 Args:
173 A_continuous: numpy.matrix, The continuous time A matrix
174 B_continuous: numpy.matrix, The continuous time B matrix
175 dt: float, The time step of the control loop
Austin Schuhc1f68892013-03-16 17:06:27 -0700176
177 Returns:
178 (A, B), numpy.matrix, the control matricies.
Austin Schuh3c542312013-02-24 01:53:50 -0800179 """
Austin Schuhc1f68892013-03-16 17:06:27 -0700180 return controls.c2d(A_continuous, B_continuous, dt)
181
182 def InitializeState(self):
183 """Sets X, Y, and X_hat to zero defaults."""
Austin Schuh3c542312013-02-24 01:53:50 -0800184 self.X = numpy.zeros((self.A.shape[0], 1))
Austin Schuhc1f68892013-03-16 17:06:27 -0700185 self.Y = self.C * self.X
Austin Schuh3c542312013-02-24 01:53:50 -0800186 self.X_hat = numpy.zeros((self.A.shape[0], 1))
187
188 def PlaceControllerPoles(self, poles):
189 """Places the controller poles.
190
191 Args:
192 poles: array, An array of poles. Must be complex conjegates if they have
193 any imaginary portions.
194 """
195 self.K = controls.dplace(self.A, self.B, poles)
196
197 def PlaceObserverPoles(self, poles):
198 """Places the observer 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.L = controls.dplace(self.A.T, self.C.T, poles).T
205
206 def Update(self, U):
207 """Simulates one time step with the provided U."""
208 U = numpy.clip(U, self.U_min, self.U_max)
209 self.X = self.A * self.X + self.B * U
210 self.Y = self.C * self.X + self.D * U
211
212 def UpdateObserver(self, U):
213 """Updates the observer given the provided U."""
214 self.X_hat = (self.A * self.X_hat + self.B * U +
215 self.L * (self.Y - self.C * self.X_hat - self.D * U))
216
217 def _DumpMatrix(self, matrix_name, matrix):
218 """Dumps the provided matrix into a variable called matrix_name.
219
220 Args:
221 matrix_name: string, The variable name to save the matrix to.
222 matrix: The matrix to dump.
223
224 Returns:
225 string, The C++ commands required to populate a variable named matrix_name
226 with the contents of matrix.
227 """
Austin Schuhe3490622013-03-13 01:24:30 -0700228 ans = [' Eigen::Matrix<double, %d, %d> %s;\n' % (
Austin Schuh3c542312013-02-24 01:53:50 -0800229 matrix.shape[0], matrix.shape[1], matrix_name)]
230 first = True
Brian Silverman0f637382013-03-03 17:44:46 -0800231 for x in xrange(matrix.shape[0]):
232 for y in xrange(matrix.shape[1]):
Austin Schuh7ec34fd2014-02-15 22:27:46 -0800233 element = matrix[x, y]
Brian Silverman0f637382013-03-03 17:44:46 -0800234 if first:
Austin Schuhe3490622013-03-13 01:24:30 -0700235 ans.append(' %s << ' % matrix_name)
Brian Silverman0f637382013-03-03 17:44:46 -0800236 first = False
237 else:
Austin Schuhe3490622013-03-13 01:24:30 -0700238 ans.append(', ')
Brian Silverman0f637382013-03-03 17:44:46 -0800239 ans.append(str(element))
Austin Schuh3c542312013-02-24 01:53:50 -0800240
Austin Schuhe3490622013-03-13 01:24:30 -0700241 ans.append(';\n')
242 return ''.join(ans)
Austin Schuh3c542312013-02-24 01:53:50 -0800243
Austin Schuhe3490622013-03-13 01:24:30 -0700244 def DumpPlantHeader(self):
Austin Schuh3c542312013-02-24 01:53:50 -0800245 """Writes out a c++ header declaration which will create a Plant object.
246
Austin Schuh3c542312013-02-24 01:53:50 -0800247 Returns:
248 string, The header declaration for the function.
249 """
250 num_states = self.A.shape[0]
251 num_inputs = self.B.shape[1]
252 num_outputs = self.C.shape[0]
Austin Schuhe3490622013-03-13 01:24:30 -0700253 return 'StateFeedbackPlantCoefficients<%d, %d, %d> Make%sPlantCoefficients();\n' % (
254 num_states, num_inputs, num_outputs, self._name)
Austin Schuh3c542312013-02-24 01:53:50 -0800255
Austin Schuhe3490622013-03-13 01:24:30 -0700256 def DumpPlant(self):
257 """Writes out a c++ function which will create a PlantCoefficients object.
Austin Schuh3c542312013-02-24 01:53:50 -0800258
259 Returns:
260 string, The function which will create the object.
261 """
262 num_states = self.A.shape[0]
263 num_inputs = self.B.shape[1]
264 num_outputs = self.C.shape[0]
Austin Schuhe3490622013-03-13 01:24:30 -0700265 ans = ['StateFeedbackPlantCoefficients<%d, %d, %d>'
266 ' Make%sPlantCoefficients() {\n' % (
267 num_states, num_inputs, num_outputs, self._name)]
Austin Schuh3c542312013-02-24 01:53:50 -0800268
Austin Schuhe3490622013-03-13 01:24:30 -0700269 ans.append(self._DumpMatrix('A', self.A))
270 ans.append(self._DumpMatrix('B', self.B))
271 ans.append(self._DumpMatrix('C', self.C))
272 ans.append(self._DumpMatrix('D', self.D))
273 ans.append(self._DumpMatrix('U_max', self.U_max))
274 ans.append(self._DumpMatrix('U_min', self.U_min))
Austin Schuh3c542312013-02-24 01:53:50 -0800275
Austin Schuhe3490622013-03-13 01:24:30 -0700276 ans.append(' return StateFeedbackPlantCoefficients<%d, %d, %d>'
277 '(A, B, C, D, U_max, U_min);\n' % (num_states, num_inputs,
Austin Schuh3c542312013-02-24 01:53:50 -0800278 num_outputs))
Austin Schuhe3490622013-03-13 01:24:30 -0700279 ans.append('}\n')
280 return ''.join(ans)
Austin Schuh3c542312013-02-24 01:53:50 -0800281
Austin Schuhe3490622013-03-13 01:24:30 -0700282 def PlantFunction(self):
283 """Returns the name of the plant coefficient function."""
284 return 'Make%sPlantCoefficients()' % self._name
Austin Schuh3c542312013-02-24 01:53:50 -0800285
Austin Schuhe3490622013-03-13 01:24:30 -0700286 def ControllerFunction(self):
287 """Returns the name of the controller function."""
288 return 'Make%sController()' % self._name
289
290 def DumpControllerHeader(self):
291 """Writes out a c++ header declaration which will create a Controller object.
Austin Schuh3c542312013-02-24 01:53:50 -0800292
293 Returns:
294 string, The header declaration for the function.
295 """
296 num_states = self.A.shape[0]
297 num_inputs = self.B.shape[1]
298 num_outputs = self.C.shape[0]
Austin Schuhe3490622013-03-13 01:24:30 -0700299 return 'StateFeedbackController<%d, %d, %d> %s;\n' % (
300 num_states, num_inputs, num_outputs, self.ControllerFunction())
Austin Schuh3c542312013-02-24 01:53:50 -0800301
Austin Schuhe3490622013-03-13 01:24:30 -0700302 def DumpController(self):
303 """Returns a c++ function which will create a Controller object.
Austin Schuh3c542312013-02-24 01:53:50 -0800304
305 Returns:
306 string, The function which will create the object.
307 """
308 num_states = self.A.shape[0]
309 num_inputs = self.B.shape[1]
310 num_outputs = self.C.shape[0]
Austin Schuhe3490622013-03-13 01:24:30 -0700311 ans = ['StateFeedbackController<%d, %d, %d> %s {\n' % (
312 num_states, num_inputs, num_outputs, self.ControllerFunction())]
Austin Schuh3c542312013-02-24 01:53:50 -0800313
Austin Schuhe3490622013-03-13 01:24:30 -0700314 ans.append(self._DumpMatrix('L', self.L))
315 ans.append(self._DumpMatrix('K', self.K))
Austin Schuh3c542312013-02-24 01:53:50 -0800316
Austin Schuhe3490622013-03-13 01:24:30 -0700317 ans.append(' return StateFeedbackController<%d, %d, %d>'
318 '(L, K, Make%sPlantCoefficients());\n' % (num_states, num_inputs,
319 num_outputs, self._name))
320 ans.append('}\n')
321 return ''.join(ans)