Austin Schuh | 3c54231 | 2013-02-24 01:53:50 -0800 | [diff] [blame] | 1 | import controls |
| 2 | import numpy |
| 3 | |
Ben Fredrickson | 1b45f78 | 2014-02-23 07:44:36 +0000 | [diff] [blame] | 4 | class 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 Schuh | e349062 | 2013-03-13 01:24:30 -0700 | [diff] [blame] | 17 | class ControlLoopWriter(object): |
Ben Fredrickson | 1b45f78 | 2014-02-23 07:44:36 +0000 | [diff] [blame] | 18 | def __init__(self, gain_schedule_name, loops, namespaces=None, write_constants=False): |
Austin Schuh | e349062 | 2013-03-13 01:24:30 -0700 | [diff] [blame] | 19 | """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 Fredrickson | 1b45f78 | 2014-02-23 07:44:36 +0000 | [diff] [blame] | 40 | |
| 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 Schuh | e349062 | 2013-03-13 01:24:30 -0700 | [diff] [blame] | 45 | |
Brian Silverman | e51ad63 | 2014-01-08 15:12:29 -0800 | [diff] [blame] | 46 | def _TopDirectory(self): |
| 47 | return self._namespaces[0] |
| 48 | |
Austin Schuh | e349062 | 2013-03-13 01:24:30 -0700 | [diff] [blame] | 49 | def _HeaderGuard(self, header_file): |
Brian Silverman | e51ad63 | 2014-01-08 15:12:29 -0800 | [diff] [blame] | 50 | return (self._TopDirectory().upper() + '_CONTROL_LOOPS_' + |
Austin Schuh | e349062 | 2013-03-13 01:24:30 -0700 | [diff] [blame] | 51 | 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 Fredrickson | 1b45f78 | 2014-02-23 07:44:36 +0000 | [diff] [blame] | 93 | |
| 94 | for const in self._constant_list: |
| 95 | fd.write(str(const)) |
| 96 | |
Austin Schuh | e349062 | 2013-03-13 01:24:30 -0700 | [diff] [blame] | 97 | 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 Silverman | df3e7b2 | 2013-11-08 19:43:27 -0800 | [diff] [blame] | 117 | fd.write('#include \"%s/control_loops/%s\"\n' % |
Brian Silverman | e51ad63 | 2014-01-08 15:12:29 -0800 | [diff] [blame] | 118 | (self._TopDirectory(), header_file_name)) |
Austin Schuh | e349062 | 2013-03-13 01:24:30 -0700 | [diff] [blame] | 119 | 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 Schuh | 3c54231 | 2013-02-24 01:53:50 -0800 | [diff] [blame] | 160 | class 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 Schuh | c1f6889 | 2013-03-16 17:06:27 -0700 | [diff] [blame] | 169 | def ContinuousToDiscrete(self, A_continuous, B_continuous, dt): |
| 170 | """Calculates the discrete time values for A and B. |
Austin Schuh | 3c54231 | 2013-02-24 01:53:50 -0800 | [diff] [blame] | 171 | |
| 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 Schuh | c1f6889 | 2013-03-16 17:06:27 -0700 | [diff] [blame] | 176 | |
| 177 | Returns: |
| 178 | (A, B), numpy.matrix, the control matricies. |
Austin Schuh | 3c54231 | 2013-02-24 01:53:50 -0800 | [diff] [blame] | 179 | """ |
Austin Schuh | c1f6889 | 2013-03-16 17:06:27 -0700 | [diff] [blame] | 180 | return controls.c2d(A_continuous, B_continuous, dt) |
| 181 | |
| 182 | def InitializeState(self): |
| 183 | """Sets X, Y, and X_hat to zero defaults.""" |
Austin Schuh | 3c54231 | 2013-02-24 01:53:50 -0800 | [diff] [blame] | 184 | self.X = numpy.zeros((self.A.shape[0], 1)) |
Austin Schuh | c1f6889 | 2013-03-16 17:06:27 -0700 | [diff] [blame] | 185 | self.Y = self.C * self.X |
Austin Schuh | 3c54231 | 2013-02-24 01:53:50 -0800 | [diff] [blame] | 186 | 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 Schuh | e349062 | 2013-03-13 01:24:30 -0700 | [diff] [blame] | 228 | ans = [' Eigen::Matrix<double, %d, %d> %s;\n' % ( |
Austin Schuh | 3c54231 | 2013-02-24 01:53:50 -0800 | [diff] [blame] | 229 | matrix.shape[0], matrix.shape[1], matrix_name)] |
| 230 | first = True |
Brian Silverman | 0f63738 | 2013-03-03 17:44:46 -0800 | [diff] [blame] | 231 | for x in xrange(matrix.shape[0]): |
| 232 | for y in xrange(matrix.shape[1]): |
Austin Schuh | 7ec34fd | 2014-02-15 22:27:46 -0800 | [diff] [blame] | 233 | element = matrix[x, y] |
Brian Silverman | 0f63738 | 2013-03-03 17:44:46 -0800 | [diff] [blame] | 234 | if first: |
Austin Schuh | e349062 | 2013-03-13 01:24:30 -0700 | [diff] [blame] | 235 | ans.append(' %s << ' % matrix_name) |
Brian Silverman | 0f63738 | 2013-03-03 17:44:46 -0800 | [diff] [blame] | 236 | first = False |
| 237 | else: |
Austin Schuh | e349062 | 2013-03-13 01:24:30 -0700 | [diff] [blame] | 238 | ans.append(', ') |
Brian Silverman | 0f63738 | 2013-03-03 17:44:46 -0800 | [diff] [blame] | 239 | ans.append(str(element)) |
Austin Schuh | 3c54231 | 2013-02-24 01:53:50 -0800 | [diff] [blame] | 240 | |
Austin Schuh | e349062 | 2013-03-13 01:24:30 -0700 | [diff] [blame] | 241 | ans.append(';\n') |
| 242 | return ''.join(ans) |
Austin Schuh | 3c54231 | 2013-02-24 01:53:50 -0800 | [diff] [blame] | 243 | |
Austin Schuh | e349062 | 2013-03-13 01:24:30 -0700 | [diff] [blame] | 244 | def DumpPlantHeader(self): |
Austin Schuh | 3c54231 | 2013-02-24 01:53:50 -0800 | [diff] [blame] | 245 | """Writes out a c++ header declaration which will create a Plant object. |
| 246 | |
Austin Schuh | 3c54231 | 2013-02-24 01:53:50 -0800 | [diff] [blame] | 247 | 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 Schuh | e349062 | 2013-03-13 01:24:30 -0700 | [diff] [blame] | 253 | return 'StateFeedbackPlantCoefficients<%d, %d, %d> Make%sPlantCoefficients();\n' % ( |
| 254 | num_states, num_inputs, num_outputs, self._name) |
Austin Schuh | 3c54231 | 2013-02-24 01:53:50 -0800 | [diff] [blame] | 255 | |
Austin Schuh | e349062 | 2013-03-13 01:24:30 -0700 | [diff] [blame] | 256 | def DumpPlant(self): |
| 257 | """Writes out a c++ function which will create a PlantCoefficients object. |
Austin Schuh | 3c54231 | 2013-02-24 01:53:50 -0800 | [diff] [blame] | 258 | |
| 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 Schuh | e349062 | 2013-03-13 01:24:30 -0700 | [diff] [blame] | 265 | ans = ['StateFeedbackPlantCoefficients<%d, %d, %d>' |
| 266 | ' Make%sPlantCoefficients() {\n' % ( |
| 267 | num_states, num_inputs, num_outputs, self._name)] |
Austin Schuh | 3c54231 | 2013-02-24 01:53:50 -0800 | [diff] [blame] | 268 | |
Austin Schuh | e349062 | 2013-03-13 01:24:30 -0700 | [diff] [blame] | 269 | 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 Schuh | 3c54231 | 2013-02-24 01:53:50 -0800 | [diff] [blame] | 275 | |
Austin Schuh | e349062 | 2013-03-13 01:24:30 -0700 | [diff] [blame] | 276 | ans.append(' return StateFeedbackPlantCoefficients<%d, %d, %d>' |
| 277 | '(A, B, C, D, U_max, U_min);\n' % (num_states, num_inputs, |
Austin Schuh | 3c54231 | 2013-02-24 01:53:50 -0800 | [diff] [blame] | 278 | num_outputs)) |
Austin Schuh | e349062 | 2013-03-13 01:24:30 -0700 | [diff] [blame] | 279 | ans.append('}\n') |
| 280 | return ''.join(ans) |
Austin Schuh | 3c54231 | 2013-02-24 01:53:50 -0800 | [diff] [blame] | 281 | |
Austin Schuh | e349062 | 2013-03-13 01:24:30 -0700 | [diff] [blame] | 282 | def PlantFunction(self): |
| 283 | """Returns the name of the plant coefficient function.""" |
| 284 | return 'Make%sPlantCoefficients()' % self._name |
Austin Schuh | 3c54231 | 2013-02-24 01:53:50 -0800 | [diff] [blame] | 285 | |
Austin Schuh | e349062 | 2013-03-13 01:24:30 -0700 | [diff] [blame] | 286 | 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 Schuh | 3c54231 | 2013-02-24 01:53:50 -0800 | [diff] [blame] | 292 | |
| 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 Schuh | e349062 | 2013-03-13 01:24:30 -0700 | [diff] [blame] | 299 | return 'StateFeedbackController<%d, %d, %d> %s;\n' % ( |
| 300 | num_states, num_inputs, num_outputs, self.ControllerFunction()) |
Austin Schuh | 3c54231 | 2013-02-24 01:53:50 -0800 | [diff] [blame] | 301 | |
Austin Schuh | e349062 | 2013-03-13 01:24:30 -0700 | [diff] [blame] | 302 | def DumpController(self): |
| 303 | """Returns a c++ function which will create a Controller object. |
Austin Schuh | 3c54231 | 2013-02-24 01:53:50 -0800 | [diff] [blame] | 304 | |
| 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 Schuh | e349062 | 2013-03-13 01:24:30 -0700 | [diff] [blame] | 311 | ans = ['StateFeedbackController<%d, %d, %d> %s {\n' % ( |
| 312 | num_states, num_inputs, num_outputs, self.ControllerFunction())] |
Austin Schuh | 3c54231 | 2013-02-24 01:53:50 -0800 | [diff] [blame] | 313 | |
Austin Schuh | e349062 | 2013-03-13 01:24:30 -0700 | [diff] [blame] | 314 | ans.append(self._DumpMatrix('L', self.L)) |
| 315 | ans.append(self._DumpMatrix('K', self.K)) |
Austin Schuh | 3c54231 | 2013-02-24 01:53:50 -0800 | [diff] [blame] | 316 | |
Austin Schuh | e349062 | 2013-03-13 01:24:30 -0700 | [diff] [blame] | 317 | 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) |