forked from RobotLocomotion/drake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
symbolic_codegen.cc
304 lines (261 loc) · 9.45 KB
/
symbolic_codegen.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
#include "drake/common/symbolic_codegen.h"
#include <sstream>
#include <stdexcept>
#include <fmt/format.h>
namespace drake {
namespace symbolic {
using std::ostream;
using std::ostringstream;
using std::runtime_error;
using std::string;
using std::to_string;
using std::vector;
CodeGenVisitor::CodeGenVisitor(const vector<Variable>& parameters) {
for (vector<Variable>::size_type i = 0; i < parameters.size(); ++i) {
id_to_idx_map_.emplace(parameters[i].get_id(), i);
}
}
string CodeGenVisitor::CodeGen(const Expression& e) const {
return VisitExpression<string>(this, e);
}
string CodeGenVisitor::VisitVariable(const Expression& e) const {
const Variable& v{get_variable(e)};
const auto it{id_to_idx_map_.find(v.get_id())};
if (it == id_to_idx_map_.end()) {
throw runtime_error("Variable index is not found.");
}
return "p[" + to_string(it->second) + "]";
}
string CodeGenVisitor::VisitConstant(const Expression& e) const {
return to_string(get_constant_value(e));
}
string CodeGenVisitor::VisitAddition(const Expression& e) const {
const double c{get_constant_in_addition(e)};
const auto& expr_to_coeff_map{get_expr_to_coeff_map_in_addition(e)};
ostringstream oss;
oss << "(" << c;
for (const auto& item : expr_to_coeff_map) {
const Expression& e_i{item.first};
const double c_i{item.second};
oss << " + ";
if (c_i == 1.0) {
oss << CodeGen(e_i);
} else {
oss << "(" << c_i << " * " << CodeGen(e_i) << ")";
}
}
oss << ")";
return oss.str();
}
string CodeGenVisitor::VisitMultiplication(const Expression& e) const {
const double c{get_constant_in_multiplication(e)};
const auto& base_to_exponent_map{
get_base_to_exponent_map_in_multiplication(e)};
ostringstream oss;
oss << "(" << c;
for (const auto& item : base_to_exponent_map) {
const Expression& e_1{item.first};
const Expression& e_2{item.second};
oss << " * ";
if (is_one(e_2)) {
oss << CodeGen(e_1);
} else {
oss << "pow(" << CodeGen(e_1) << ", " << CodeGen(e_2) << ")";
}
}
oss << ")";
return oss.str();
}
// Helper method to handle unary cases.
string CodeGenVisitor::VisitUnary(const string& f, const Expression& e) const {
return f + "(" + CodeGen(get_argument(e)) + ")";
}
// Helper method to handle binary cases.
string CodeGenVisitor::VisitBinary(const string& f, const Expression& e) const {
return f + "(" + CodeGen(get_first_argument(e)) + ", " +
CodeGen(get_second_argument(e)) + ")";
}
string CodeGenVisitor::VisitPow(const Expression& e) const {
return VisitBinary("pow", e);
}
string CodeGenVisitor::VisitDivision(const Expression& e) const {
return "(" + CodeGen(get_first_argument(e)) + " / " +
CodeGen(get_second_argument(e)) + ")";
}
string CodeGenVisitor::VisitAbs(const Expression& e) const {
return VisitUnary("fabs", e);
}
string CodeGenVisitor::VisitLog(const Expression& e) const {
return VisitUnary("log", e);
}
string CodeGenVisitor::VisitExp(const Expression& e) const {
return VisitUnary("exp", e);
}
string CodeGenVisitor::VisitSqrt(const Expression& e) const {
return VisitUnary("sqrt", e);
}
string CodeGenVisitor::VisitSin(const Expression& e) const {
return VisitUnary("sin", e);
}
string CodeGenVisitor::VisitCos(const Expression& e) const {
return VisitUnary("cos", e);
}
string CodeGenVisitor::VisitTan(const Expression& e) const {
return VisitUnary("tan", e);
}
string CodeGenVisitor::VisitAsin(const Expression& e) const {
return VisitUnary("asin", e);
}
string CodeGenVisitor::VisitAcos(const Expression& e) const {
return VisitUnary("acos", e);
}
string CodeGenVisitor::VisitAtan(const Expression& e) const {
return VisitUnary("atan", e);
}
string CodeGenVisitor::VisitAtan2(const Expression& e) const {
return VisitBinary("atan2", e);
}
string CodeGenVisitor::VisitSinh(const Expression& e) const {
return VisitUnary("sinh", e);
}
string CodeGenVisitor::VisitCosh(const Expression& e) const {
return VisitUnary("cosh", e);
}
string CodeGenVisitor::VisitTanh(const Expression& e) const {
return VisitUnary("tanh", e);
}
string CodeGenVisitor::VisitMin(const Expression& e) const {
return VisitBinary("fmin", e);
}
string CodeGenVisitor::VisitMax(const Expression& e) const {
return VisitBinary("fmax", e);
}
string CodeGenVisitor::VisitCeil(const Expression& e) const {
return VisitUnary("ceil", e);
}
string CodeGenVisitor::VisitFloor(const Expression& e) const {
return VisitUnary("floor", e);
}
string CodeGenVisitor::VisitIfThenElse(const Expression&) const {
throw runtime_error("Codegen does not support if-then-else expressions.");
}
string CodeGenVisitor::VisitUninterpretedFunction(const Expression&) const {
throw runtime_error("Codegen does not support uninterpreted functions.");
}
string CodeGen(const string& function_name, const vector<Variable>& parameters,
const Expression& e) {
ostringstream oss;
// Add header for the main function.
oss << "double " << function_name << "(const double* p) {\n";
// Codegen the expression.
oss << " return " << CodeGenVisitor{parameters}.CodeGen(e) << ";\n";
// Add footer for the main function.
oss << "}\n";
// <function_name>_meta_t type.
oss << "typedef struct {\n"
" /* p: input, vector */\n"
" struct { int size; } p;\n"
"} "
<< function_name << "_meta_t;\n";
// <function_name>_meta().
oss << function_name << "_meta_t " << function_name << "_meta() { return {{"
<< parameters.size() << "}}; }\n";
return oss.str();
}
namespace internal {
void CodeGenDenseData(const string& function_name,
const vector<Variable>& parameters,
const Expression* const data, const int size,
ostream* const os) {
// Add header for the main function.
(*os) << "void " << function_name << "(const double* p, double* m) {\n";
const CodeGenVisitor visitor{parameters};
for (int i = 0; i < size; ++i) {
(*os) << " "
<< "m[" << i << "] = " << visitor.CodeGen(data[i]) << ";\n";
}
// Add footer for the main function.
(*os) << "}\n";
}
void CodeGenDenseMeta(const string& function_name, const int parameter_size,
const int rows, const int cols, ostream* const os) {
// <function_name>_meta_t type.
(*os) << "typedef struct {\n"
" /* p: input, vector */\n"
" struct { int size; } p;\n"
" /* m: output, matrix */\n"
" struct { int rows; int cols; } m;\n"
"} "
<< function_name << "_meta_t;\n";
// <function_name>_meta().
(*os) << function_name << "_meta_t " << function_name << "_meta() { return {{"
<< parameter_size << "}, {" << rows << ", " << cols << "}}; }\n";
}
void CodeGenSparseData(const string& function_name,
const vector<Variable>& parameters,
const int outer_index_size, const int non_zeros,
const int* const outer_index_ptr,
const int* const inner_index_ptr,
const Expression* const value_ptr, ostream* const os) {
// Print header.
(*os) << fmt::format(
"void {}(const double* p, int* outer_indices, int* "
"inner_indices, double* values) {{\n",
function_name);
for (int i = 0; i < outer_index_size; ++i) {
(*os) << fmt::format(" outer_indices[{0}] = {1};\n", i,
outer_index_ptr[i]);
}
for (int i = 0; i < non_zeros; ++i) {
(*os) << fmt::format(" inner_indices[{0}] = {1};\n", i,
inner_index_ptr[i]);
}
const CodeGenVisitor visitor{parameters};
for (int i = 0; i < non_zeros; ++i) {
(*os) << fmt::format(" values[{0}] = {1};\n", i,
visitor.CodeGen(value_ptr[i]));
}
// Print footer.
(*os) << "}\n";
}
void CodeGenSparseMeta(const string& function_name, const int parameter_size,
const int rows, const int cols, const int non_zeros,
const int outer_indices, const int inner_indices,
ostream* const os) {
// <function_name>_meta_t type.
(*os) << "typedef struct {\n"
" /* p: input, vector */\n"
" struct { int size; } p;\n"
" /* m: output, matrix */\n"
" struct {\n"
" int rows;\n"
" int cols;\n"
" int non_zeros;\n"
" int outer_indices;\n"
" int inner_indices;\n"
" } m;\n"
"} "
<< function_name << "_meta_t;\n";
// <function_name>_meta().
(*os) << fmt::format(
"{0}_meta_t {1}_meta() {{ return {{{{{2}}}, {{{3}, {4}, {5}, {6}, "
"{7}}}}}; }}\n",
function_name, function_name, parameter_size, rows, cols, non_zeros,
outer_indices, inner_indices);
}
} // namespace internal
std::string CodeGen(
const std::string& function_name, const std::vector<Variable>& parameters,
const Eigen::Ref<const Eigen::SparseMatrix<Expression>>& M) {
DRAKE_ASSERT(M.isCompressed());
ostringstream oss;
internal::CodeGenSparseData(function_name, parameters, M.cols() + 1,
M.nonZeros(), M.outerIndexPtr(),
M.innerIndexPtr(), M.valuePtr(), &oss);
internal::CodeGenSparseMeta(function_name, parameters.size(), M.rows(),
M.cols(), M.nonZeros(), M.cols() + 1,
M.nonZeros(), &oss);
return oss.str();
}
} // namespace symbolic
} // namespace drake