blob: bda178ecc3700335d34e264ca15bdc9227d41f23 [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
88 def WriteHeader(self, header_file):
89 """Writes the header file to the file named header_file."""
90 with open(header_file, 'w') as fd:
91 header_guard = self._HeaderGuard(header_file)
92 fd.write('#ifndef %s\n'
93 '#define %s\n\n' % (header_guard, header_guard))
94 fd.write('#include \"frc971/control_loops/state_feedback_loop.h\"\n')
95 fd.write('\n')
96
97 fd.write(self._namespace_start)
Ben Fredrickson1b45f782014-02-23 07:44:36 +000098
99 for const in self._constant_list:
100 fd.write(str(const))
101
Austin Schuhe3490622013-03-13 01:24:30 -0700102 fd.write('\n\n')
103 for loop in self._loops:
104 fd.write(loop.DumpPlantHeader())
105 fd.write('\n')
106 fd.write(loop.DumpControllerHeader())
107 fd.write('\n')
108
109 fd.write('%s Make%sPlant();\n\n' %
110 (self._PlantType(), self._gain_schedule_name))
111
112 fd.write('%s Make%sLoop();\n\n' %
113 (self._LoopType(), self._gain_schedule_name))
114
115 fd.write(self._namespace_end)
116 fd.write('\n\n')
117 fd.write("#endif // %s\n" % header_guard)
118
119 def WriteCC(self, header_file_name, cc_file):
120 """Writes the cc file to the file named cc_file."""
121 with open(cc_file, 'w') as fd:
Brian Silvermandf3e7b22013-11-08 19:43:27 -0800122 fd.write('#include \"%s/control_loops/%s\"\n' %
Brian Silvermane51ad632014-01-08 15:12:29 -0800123 (self._TopDirectory(), header_file_name))
Austin Schuhe3490622013-03-13 01:24:30 -0700124 fd.write('\n')
125 fd.write('#include <vector>\n')
126 fd.write('\n')
127 fd.write('#include \"frc971/control_loops/state_feedback_loop.h\"\n')
128 fd.write('\n')
129 fd.write(self._namespace_start)
130 fd.write('\n\n')
131 for loop in self._loops:
132 fd.write(loop.DumpPlant())
133 fd.write('\n')
134
135 for loop in self._loops:
136 fd.write(loop.DumpController())
137 fd.write('\n')
138
139 fd.write('%s Make%sPlant() {\n' %
140 (self._PlantType(), self._gain_schedule_name))
141 fd.write(' ::std::vector<%s *> plants(%d);\n' % (
142 self._CoeffType(), len(self._loops)))
143 for index, loop in enumerate(self._loops):
144 fd.write(' plants[%d] = new %s(%s);\n' %
145 (index, self._CoeffType(),
146 loop.PlantFunction()))
147 fd.write(' return %s(plants);\n' % self._PlantType())
148 fd.write('}\n\n')
149
150 fd.write('%s Make%sLoop() {\n' %
151 (self._LoopType(), self._gain_schedule_name))
152 fd.write(' ::std::vector<%s *> controllers(%d);\n' % (
153 self._ControllerType(), len(self._loops)))
154 for index, loop in enumerate(self._loops):
155 fd.write(' controllers[%d] = new %s(%s);\n' %
156 (index, self._ControllerType(),
157 loop.ControllerFunction()))
158 fd.write(' return %s(controllers);\n' % self._LoopType())
159 fd.write('}\n\n')
160
161 fd.write(self._namespace_end)
162 fd.write('\n')
163
164
Austin Schuh3c542312013-02-24 01:53:50 -0800165class ControlLoop(object):
166 def __init__(self, name):
167 """Constructs a control loop object.
168
169 Args:
170 name: string, The name of the loop to use when writing the C++ files.
171 """
172 self._name = name
173
Austin Schuhc1f68892013-03-16 17:06:27 -0700174 def ContinuousToDiscrete(self, A_continuous, B_continuous, dt):
175 """Calculates the discrete time values for A and B.
Austin Schuh3c542312013-02-24 01:53:50 -0800176
177 Args:
178 A_continuous: numpy.matrix, The continuous time A matrix
179 B_continuous: numpy.matrix, The continuous time B matrix
180 dt: float, The time step of the control loop
Austin Schuhc1f68892013-03-16 17:06:27 -0700181
182 Returns:
183 (A, B), numpy.matrix, the control matricies.
Austin Schuh3c542312013-02-24 01:53:50 -0800184 """
Austin Schuhc1f68892013-03-16 17:06:27 -0700185 return controls.c2d(A_continuous, B_continuous, dt)
186
187 def InitializeState(self):
188 """Sets X, Y, and X_hat to zero defaults."""
Austin Schuh3c542312013-02-24 01:53:50 -0800189 self.X = numpy.zeros((self.A.shape[0], 1))
Austin Schuhc1f68892013-03-16 17:06:27 -0700190 self.Y = self.C * self.X
Austin Schuh3c542312013-02-24 01:53:50 -0800191 self.X_hat = numpy.zeros((self.A.shape[0], 1))
192
193 def PlaceControllerPoles(self, poles):
194 """Places the controller poles.
195
196 Args:
197 poles: array, An array of poles. Must be complex conjegates if they have
198 any imaginary portions.
199 """
200 self.K = controls.dplace(self.A, self.B, poles)
201
202 def PlaceObserverPoles(self, poles):
203 """Places the observer poles.
204
205 Args:
206 poles: array, An array of poles. Must be complex conjegates if they have
207 any imaginary portions.
208 """
209 self.L = controls.dplace(self.A.T, self.C.T, poles).T
210
211 def Update(self, U):
212 """Simulates one time step with the provided U."""
213 U = numpy.clip(U, self.U_min, self.U_max)
214 self.X = self.A * self.X + self.B * U
215 self.Y = self.C * self.X + self.D * U
216
217 def UpdateObserver(self, U):
218 """Updates the observer given the provided U."""
219 self.X_hat = (self.A * self.X_hat + self.B * U +
220 self.L * (self.Y - self.C * self.X_hat - self.D * U))
221
222 def _DumpMatrix(self, matrix_name, matrix):
223 """Dumps the provided matrix into a variable called matrix_name.
224
225 Args:
226 matrix_name: string, The variable name to save the matrix to.
227 matrix: The matrix to dump.
228
229 Returns:
230 string, The C++ commands required to populate a variable named matrix_name
231 with the contents of matrix.
232 """
Austin Schuhe3490622013-03-13 01:24:30 -0700233 ans = [' Eigen::Matrix<double, %d, %d> %s;\n' % (
Austin Schuh3c542312013-02-24 01:53:50 -0800234 matrix.shape[0], matrix.shape[1], matrix_name)]
235 first = True
Brian Silverman0f637382013-03-03 17:44:46 -0800236 for x in xrange(matrix.shape[0]):
237 for y in xrange(matrix.shape[1]):
Austin Schuh7ec34fd2014-02-15 22:27:46 -0800238 element = matrix[x, y]
Brian Silverman0f637382013-03-03 17:44:46 -0800239 if first:
Austin Schuhe3490622013-03-13 01:24:30 -0700240 ans.append(' %s << ' % matrix_name)
Brian Silverman0f637382013-03-03 17:44:46 -0800241 first = False
242 else:
Austin Schuhe3490622013-03-13 01:24:30 -0700243 ans.append(', ')
Brian Silverman0f637382013-03-03 17:44:46 -0800244 ans.append(str(element))
Austin Schuh3c542312013-02-24 01:53:50 -0800245
Austin Schuhe3490622013-03-13 01:24:30 -0700246 ans.append(';\n')
247 return ''.join(ans)
Austin Schuh3c542312013-02-24 01:53:50 -0800248
Austin Schuhe3490622013-03-13 01:24:30 -0700249 def DumpPlantHeader(self):
Austin Schuh3c542312013-02-24 01:53:50 -0800250 """Writes out a c++ header declaration which will create a Plant object.
251
Austin Schuh3c542312013-02-24 01:53:50 -0800252 Returns:
253 string, The header declaration for the function.
254 """
255 num_states = self.A.shape[0]
256 num_inputs = self.B.shape[1]
257 num_outputs = self.C.shape[0]
Austin Schuhe3490622013-03-13 01:24:30 -0700258 return 'StateFeedbackPlantCoefficients<%d, %d, %d> Make%sPlantCoefficients();\n' % (
259 num_states, num_inputs, num_outputs, self._name)
Austin Schuh3c542312013-02-24 01:53:50 -0800260
Austin Schuhe3490622013-03-13 01:24:30 -0700261 def DumpPlant(self):
262 """Writes out a c++ function which will create a PlantCoefficients object.
Austin Schuh3c542312013-02-24 01:53:50 -0800263
264 Returns:
265 string, The function which will create the object.
266 """
267 num_states = self.A.shape[0]
268 num_inputs = self.B.shape[1]
269 num_outputs = self.C.shape[0]
Austin Schuhe3490622013-03-13 01:24:30 -0700270 ans = ['StateFeedbackPlantCoefficients<%d, %d, %d>'
271 ' Make%sPlantCoefficients() {\n' % (
272 num_states, num_inputs, num_outputs, self._name)]
Austin Schuh3c542312013-02-24 01:53:50 -0800273
Austin Schuhe3490622013-03-13 01:24:30 -0700274 ans.append(self._DumpMatrix('A', self.A))
275 ans.append(self._DumpMatrix('B', self.B))
276 ans.append(self._DumpMatrix('C', self.C))
277 ans.append(self._DumpMatrix('D', self.D))
278 ans.append(self._DumpMatrix('U_max', self.U_max))
279 ans.append(self._DumpMatrix('U_min', self.U_min))
Austin Schuh3c542312013-02-24 01:53:50 -0800280
Austin Schuhe3490622013-03-13 01:24:30 -0700281 ans.append(' return StateFeedbackPlantCoefficients<%d, %d, %d>'
282 '(A, B, C, D, U_max, U_min);\n' % (num_states, num_inputs,
Austin Schuh3c542312013-02-24 01:53:50 -0800283 num_outputs))
Austin Schuhe3490622013-03-13 01:24:30 -0700284 ans.append('}\n')
285 return ''.join(ans)
Austin Schuh3c542312013-02-24 01:53:50 -0800286
Austin Schuhe3490622013-03-13 01:24:30 -0700287 def PlantFunction(self):
288 """Returns the name of the plant coefficient function."""
289 return 'Make%sPlantCoefficients()' % self._name
Austin Schuh3c542312013-02-24 01:53:50 -0800290
Austin Schuhe3490622013-03-13 01:24:30 -0700291 def ControllerFunction(self):
292 """Returns the name of the controller function."""
293 return 'Make%sController()' % self._name
294
295 def DumpControllerHeader(self):
296 """Writes out a c++ header declaration which will create a Controller object.
Austin Schuh3c542312013-02-24 01:53:50 -0800297
298 Returns:
299 string, The header declaration for the function.
300 """
301 num_states = self.A.shape[0]
302 num_inputs = self.B.shape[1]
303 num_outputs = self.C.shape[0]
Austin Schuhe3490622013-03-13 01:24:30 -0700304 return 'StateFeedbackController<%d, %d, %d> %s;\n' % (
305 num_states, num_inputs, num_outputs, self.ControllerFunction())
Austin Schuh3c542312013-02-24 01:53:50 -0800306
Austin Schuhe3490622013-03-13 01:24:30 -0700307 def DumpController(self):
308 """Returns a c++ function which will create a Controller object.
Austin Schuh3c542312013-02-24 01:53:50 -0800309
310 Returns:
311 string, The function which will create the object.
312 """
313 num_states = self.A.shape[0]
314 num_inputs = self.B.shape[1]
315 num_outputs = self.C.shape[0]
Austin Schuhe3490622013-03-13 01:24:30 -0700316 ans = ['StateFeedbackController<%d, %d, %d> %s {\n' % (
317 num_states, num_inputs, num_outputs, self.ControllerFunction())]
Austin Schuh3c542312013-02-24 01:53:50 -0800318
Austin Schuhe3490622013-03-13 01:24:30 -0700319 ans.append(self._DumpMatrix('L', self.L))
320 ans.append(self._DumpMatrix('K', self.K))
Austin Schuh3c542312013-02-24 01:53:50 -0800321
Austin Schuhe3490622013-03-13 01:24:30 -0700322 ans.append(' return StateFeedbackController<%d, %d, %d>'
323 '(L, K, Make%sPlantCoefficients());\n' % (num_states, num_inputs,
324 num_outputs, self._name))
325 ans.append('}\n')
326 return ''.join(ans)