blob: 6704526942edc2e2b77678a74bd6b7c333069601 [file] [log] [blame]
Austin Schuh3c542312013-02-24 01:53:50 -08001import controls
2import numpy
3
4class ControlLoop(object):
5 def __init__(self, name):
6 """Constructs a control loop object.
7
8 Args:
9 name: string, The name of the loop to use when writing the C++ files.
10 """
11 self._name = name
12
13 self._namespace_start = ("namespace frc971 {\n"
14 "namespace control_loops {\n\n")
15
16 self._namespace_end = ("} // namespace frc971\n"
17 "} // namespace control_loops\n")
18
Austin Schuha40624b2013-03-03 14:02:40 -080019 self._header_start = ("#ifndef FRC971_CONTROL_LOOPS_%s_%s_MOTOR_PLANT_H_\n"
20 "#define FRC971_CONTROL_LOOPS_%s_%s_MOTOR_PLANT_H_\n\n"
21 % (self._name.upper(), self._name.upper(),
22 self._name.upper(), self._name.upper()))
Austin Schuh3c542312013-02-24 01:53:50 -080023
Austin Schuha40624b2013-03-03 14:02:40 -080024 self._header_end = ("#endif // FRC971_CONTROL_LOOPS_%s_%s_MOTOR_PLANT_H_\n"
25 % (self._name.upper(), self._name.upper()))
Austin Schuh3c542312013-02-24 01:53:50 -080026
27 def ContinuousToDiscrete(self, A_continuous, B_continuous, dt, C):
28 """Calculates the discrete time values for A and B as well as initializing
29 X and Y to the correct sizes.
30
31 Args:
32 A_continuous: numpy.matrix, The continuous time A matrix
33 B_continuous: numpy.matrix, The continuous time B matrix
34 dt: float, The time step of the control loop
35 C: C
36 """
37 self.A, self.B = controls.c2d(
38 A_continuous, B_continuous, dt)
39 self.X = numpy.zeros((self.A.shape[0], 1))
40 self.Y = C * self.X
41 self.X_hat = numpy.zeros((self.A.shape[0], 1))
42
43 def PlaceControllerPoles(self, poles):
44 """Places the controller poles.
45
46 Args:
47 poles: array, An array of poles. Must be complex conjegates if they have
48 any imaginary portions.
49 """
50 self.K = controls.dplace(self.A, self.B, poles)
51
52 def PlaceObserverPoles(self, poles):
53 """Places the observer poles.
54
55 Args:
56 poles: array, An array of poles. Must be complex conjegates if they have
57 any imaginary portions.
58 """
59 self.L = controls.dplace(self.A.T, self.C.T, poles).T
60
61 def Update(self, U):
62 """Simulates one time step with the provided U."""
63 U = numpy.clip(U, self.U_min, self.U_max)
64 self.X = self.A * self.X + self.B * U
65 self.Y = self.C * self.X + self.D * U
66
67 def UpdateObserver(self, U):
68 """Updates the observer given the provided U."""
69 self.X_hat = (self.A * self.X_hat + self.B * U +
70 self.L * (self.Y - self.C * self.X_hat - self.D * U))
71
72 def _DumpMatrix(self, matrix_name, matrix):
73 """Dumps the provided matrix into a variable called matrix_name.
74
75 Args:
76 matrix_name: string, The variable name to save the matrix to.
77 matrix: The matrix to dump.
78
79 Returns:
80 string, The C++ commands required to populate a variable named matrix_name
81 with the contents of matrix.
82 """
83 ans = [" Eigen::Matrix<double, %d, %d> %s;\n" % (
84 matrix.shape[0], matrix.shape[1], matrix_name)]
85 first = True
86 for element in numpy.nditer(matrix, order='C'):
87 if first:
88 ans.append(" %s << " % matrix_name)
89 first = False
90 else:
91 ans.append(", ")
92 ans.append(str(element))
93
94 ans.append(";\n")
95 return "".join(ans)
96
97 def _DumpPlantHeader(self, plant_name):
98 """Writes out a c++ header declaration which will create a Plant object.
99
100 Args:
101 plant_name: string, the name of the plant. Used to create the name of the
102 function. The function name will be Make<plant_name>Plant().
103
104 Returns:
105 string, The header declaration for the function.
106 """
107 num_states = self.A.shape[0]
108 num_inputs = self.B.shape[1]
109 num_outputs = self.C.shape[0]
110 return "StateFeedbackPlant<%d, %d, %d> Make%sPlant();\n" % (
111 num_states, num_inputs, num_outputs, plant_name)
112
113 def _DumpPlant(self, plant_name):
114 """Writes out a c++ function which will create a Plant object.
115
116 Args:
117 plant_name: string, the name of the plant. Used to create the name of the
118 function. The function name will be Make<plant_name>Plant().
119
120 Returns:
121 string, The function which will create the object.
122 """
123 num_states = self.A.shape[0]
124 num_inputs = self.B.shape[1]
125 num_outputs = self.C.shape[0]
126 ans = ["StateFeedbackPlant<%d, %d, %d> Make%sPlant() {\n" % (
127 num_states, num_inputs, num_outputs, plant_name)]
128
129 ans.append(self._DumpMatrix("A", self.A))
130 ans.append(self._DumpMatrix("B", self.B))
131 ans.append(self._DumpMatrix("C", self.C))
132 ans.append(self._DumpMatrix("D", self.D))
133 ans.append(self._DumpMatrix("U_max", self.U_max))
134 ans.append(self._DumpMatrix("U_min", self.U_min))
135
136 ans.append(" return StateFeedbackPlant<%d, %d, %d>"
137 "(A, B, C, D, U_max, U_min);\n" % (num_states, num_inputs,
138 num_outputs))
139 ans.append("}\n")
140 return "".join(ans)
141
142 def _DumpLoopHeader(self, loop_name):
143 """Writes out a c++ header declaration which will create a Loop object.
144
145 Args:
146 loop_name: string, the name of the loop. Used to create the name of the
147 function. The function name will be Make<loop_name>Loop().
148
149 Returns:
150 string, The header declaration for the function.
151 """
152 num_states = self.A.shape[0]
153 num_inputs = self.B.shape[1]
154 num_outputs = self.C.shape[0]
155 return "StateFeedbackLoop<%d, %d, %d> Make%sLoop();\n" % (
156 num_states, num_inputs, num_outputs, loop_name)
157
158 def _DumpLoop(self, loop_name):
159 """Returns a c++ function which will create a Loop object.
160
161 Args:
162 loop_name: string, the name of the loop. Used to create the name of the
163 function and create the plant. The function name will be
164 Make<loop_name>Loop().
165
166 Returns:
167 string, The function which will create the object.
168 """
169 num_states = self.A.shape[0]
170 num_inputs = self.B.shape[1]
171 num_outputs = self.C.shape[0]
172 ans = ["StateFeedbackLoop<%d, %d, %d> Make%sLoop() {\n" % (
173 num_states, num_inputs, num_outputs, loop_name)]
174
175 ans.append(self._DumpMatrix("L", self.L))
176 ans.append(self._DumpMatrix("K", self.K))
177
178 ans.append(" return StateFeedbackLoop<%d, %d, %d>"
179 "(L, K, Make%sPlant());\n" % (num_states, num_inputs,
180 num_outputs, loop_name))
181 ans.append("}\n")
182 return "".join(ans)
183
184 def DumpHeaderFile(self, file_name):
185 """Writes the header file for creating a Plant and Loop object.
186
187 Args:
188 file_name: string, name of the file to write the header file to.
189 """
190 with open(file_name, "w") as fd:
191 fd.write(self._header_start)
192 fd.write("#include \"frc971/control_loops/state_feedback_loop.h\"\n")
193 fd.write('\n')
194 fd.write(self._namespace_start)
195 fd.write(self._DumpPlantHeader(self._name))
196 fd.write('\n')
James Kuszmaul68961712013-03-02 15:12:57 -0800197 fd.write(self._DumpLoopHeader(self._name))
Austin Schuh3c542312013-02-24 01:53:50 -0800198 fd.write('\n')
199 fd.write(self._namespace_end)
200 fd.write('\n')
201 fd.write(self._header_end)
202
203 def DumpCppFile(self, file_name, header_file_name):
204 """Writes the C++ file for creating a Plant and Loop object.
205
206 Args:
207 file_name: string, name of the file to write the header file to.
208 """
209 with open(file_name, "w") as fd:
210 fd.write("#include \"frc971/control_loops/%s\"\n" % header_file_name)
211 fd.write('\n')
212 fd.write("#include \"frc971/control_loops/state_feedback_loop.h\"\n")
213 fd.write('\n')
214 fd.write(self._namespace_start)
215 fd.write('\n')
216 fd.write(self._DumpPlant(self._name))
217 fd.write('\n')
218 fd.write(self._DumpLoop(self._name))
219 fd.write('\n')
220 fd.write(self._namespace_end)