blob: c5316e7c88db860e03f67093246e3acbfcbe0037 [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
Brian Silverman0f637382013-03-03 17:44:46 -080086 for x in xrange(matrix.shape[0]):
87 for y in xrange(matrix.shape[1]):
88 element = matrix[x, y]
89 if first:
90 ans.append(" %s << " % matrix_name)
91 first = False
92 else:
93 ans.append(", ")
94 ans.append(str(element))
Austin Schuh3c542312013-02-24 01:53:50 -080095
96 ans.append(";\n")
97 return "".join(ans)
98
99 def _DumpPlantHeader(self, plant_name):
100 """Writes out a c++ header declaration which will create a Plant object.
101
102 Args:
103 plant_name: string, the name of the plant. Used to create the name of the
104 function. The function name will be Make<plant_name>Plant().
105
106 Returns:
107 string, The header declaration for the function.
108 """
109 num_states = self.A.shape[0]
110 num_inputs = self.B.shape[1]
111 num_outputs = self.C.shape[0]
112 return "StateFeedbackPlant<%d, %d, %d> Make%sPlant();\n" % (
113 num_states, num_inputs, num_outputs, plant_name)
114
115 def _DumpPlant(self, plant_name):
116 """Writes out a c++ function which will create a Plant object.
117
118 Args:
119 plant_name: string, the name of the plant. Used to create the name of the
120 function. The function name will be Make<plant_name>Plant().
121
122 Returns:
123 string, The function which will create the object.
124 """
125 num_states = self.A.shape[0]
126 num_inputs = self.B.shape[1]
127 num_outputs = self.C.shape[0]
128 ans = ["StateFeedbackPlant<%d, %d, %d> Make%sPlant() {\n" % (
129 num_states, num_inputs, num_outputs, plant_name)]
130
131 ans.append(self._DumpMatrix("A", self.A))
132 ans.append(self._DumpMatrix("B", self.B))
133 ans.append(self._DumpMatrix("C", self.C))
134 ans.append(self._DumpMatrix("D", self.D))
135 ans.append(self._DumpMatrix("U_max", self.U_max))
136 ans.append(self._DumpMatrix("U_min", self.U_min))
137
138 ans.append(" return StateFeedbackPlant<%d, %d, %d>"
139 "(A, B, C, D, U_max, U_min);\n" % (num_states, num_inputs,
140 num_outputs))
141 ans.append("}\n")
142 return "".join(ans)
143
144 def _DumpLoopHeader(self, loop_name):
145 """Writes out a c++ header declaration which will create a Loop object.
146
147 Args:
148 loop_name: string, the name of the loop. Used to create the name of the
149 function. The function name will be Make<loop_name>Loop().
150
151 Returns:
152 string, The header declaration for the function.
153 """
154 num_states = self.A.shape[0]
155 num_inputs = self.B.shape[1]
156 num_outputs = self.C.shape[0]
157 return "StateFeedbackLoop<%d, %d, %d> Make%sLoop();\n" % (
158 num_states, num_inputs, num_outputs, loop_name)
159
160 def _DumpLoop(self, loop_name):
161 """Returns a c++ function which will create a Loop object.
162
163 Args:
164 loop_name: string, the name of the loop. Used to create the name of the
165 function and create the plant. The function name will be
166 Make<loop_name>Loop().
167
168 Returns:
169 string, The function which will create the object.
170 """
171 num_states = self.A.shape[0]
172 num_inputs = self.B.shape[1]
173 num_outputs = self.C.shape[0]
174 ans = ["StateFeedbackLoop<%d, %d, %d> Make%sLoop() {\n" % (
175 num_states, num_inputs, num_outputs, loop_name)]
176
177 ans.append(self._DumpMatrix("L", self.L))
178 ans.append(self._DumpMatrix("K", self.K))
179
180 ans.append(" return StateFeedbackLoop<%d, %d, %d>"
181 "(L, K, Make%sPlant());\n" % (num_states, num_inputs,
182 num_outputs, loop_name))
183 ans.append("}\n")
184 return "".join(ans)
185
186 def DumpHeaderFile(self, file_name):
187 """Writes the header file for creating a Plant and Loop object.
188
189 Args:
190 file_name: string, name of the file to write the header file to.
191 """
192 with open(file_name, "w") as fd:
193 fd.write(self._header_start)
194 fd.write("#include \"frc971/control_loops/state_feedback_loop.h\"\n")
195 fd.write('\n')
196 fd.write(self._namespace_start)
197 fd.write(self._DumpPlantHeader(self._name))
198 fd.write('\n')
James Kuszmaul68961712013-03-02 15:12:57 -0800199 fd.write(self._DumpLoopHeader(self._name))
Austin Schuh3c542312013-02-24 01:53:50 -0800200 fd.write('\n')
201 fd.write(self._namespace_end)
202 fd.write('\n')
203 fd.write(self._header_end)
204
205 def DumpCppFile(self, file_name, header_file_name):
206 """Writes the C++ file for creating a Plant and Loop object.
207
208 Args:
209 file_name: string, name of the file to write the header file to.
210 """
211 with open(file_name, "w") as fd:
212 fd.write("#include \"frc971/control_loops/%s\"\n" % header_file_name)
213 fd.write('\n')
214 fd.write("#include \"frc971/control_loops/state_feedback_loop.h\"\n")
215 fd.write('\n')
216 fd.write(self._namespace_start)
217 fd.write('\n')
218 fd.write(self._DumpPlant(self._name))
219 fd.write('\n')
220 fd.write(self._DumpLoop(self._name))
221 fd.write('\n')
222 fd.write(self._namespace_end)