-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
symbolic_py.cc
464 lines (443 loc) · 17.2 KB
/
symbolic_py.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
#include <map>
#include <string>
#include "fmt/format.h"
#include "fmt/ostream.h"
#include "pybind11/eigen.h"
#include "pybind11/operators.h"
#include "pybind11/pybind11.h"
#include "pybind11/stl.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/bindings/pydrake/symbolic_types_pybind.h"
#include "drake/bindings/pydrake/util/wrap_pybind.h"
namespace drake {
namespace pydrake {
using std::map;
using std::string;
// TODO(eric.cousineau): Use py::self for operator overloads?
PYBIND11_MODULE(_symbolic_py, m) {
// NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace.
using namespace drake::symbolic;
// Install NumPy warning filtres.
// N.B. This may interfere with other code, but until that is a confirmed
// issue, we should agressively try to avoid these warnings.
py::module::import("pydrake.util.deprecation")
.attr("install_numpy_warning_filters")();
m.doc() =
"Symbolic variable, variables, monomial, expression, polynomial, and "
"formula";
py::class_<Variable>(m, "Variable")
.def(py::init<const string&>())
.def("get_id", &Variable::get_id)
.def("__str__", &Variable::to_string)
.def("__repr__",
[](const Variable& self) {
return fmt::format("Variable('{}')", self.to_string());
})
.def("__hash__",
[](const Variable& self) { return std::hash<Variable>{}(self); })
.def("__copy__",
[](const Variable& self) -> Variable {
return self;
})
// Addition.
.def(py::self + py::self)
.def(py::self + double())
.def(double() + py::self)
// Subtraction.
.def(py::self - py::self)
.def(py::self - double())
.def(double() - py::self)
// Multiplication.
.def(py::self * py::self)
.def(py::self * double())
.def(double() * py::self)
// Division.
.def(py::self / py::self)
.def(py::self / double())
.def(double() / py::self)
// Pow.
.def("__pow__",
[](const Variable& self, double other) { return pow(self, other); },
py::is_operator())
.def("__pow__",
[](const Variable& self, const Variable& other) {
return pow(self, other);
},
py::is_operator())
.def("__pow__",
[](const Variable& self, const Expression& other) {
return pow(self, other);
},
py::is_operator())
// We add `EqualTo` instead of `equal_to` to maintain consistency among
// symbolic classes (Variable, Expression, Formula, Polynomial) on Python
// side. This enables us to achieve polymorphism via ducktyping in Python.
.def("EqualTo", &Variable::equal_to)
// Unary Plus.
.def(+py::self)
// Unary Minus.
.def(-py::self)
// LT(<).
// Note that for `double < Variable` case, the reflected op ('>' in this
// case) is called. For example, `1 < x` will return `x > 1`.
.def(py::self < Expression())
.def(py::self < py::self)
.def(py::self < double())
// LE(<=).
.def(py::self <= Expression())
.def(py::self <= py::self)
.def(py::self <= double())
// GT(>).
.def(py::self > Expression())
.def(py::self > py::self)
.def(py::self > double())
// GE(>=).
.def(py::self >= Expression())
.def(py::self >= py::self)
.def(py::self >= double())
// EQ(==).
.def(py::self == Expression())
.def(py::self == py::self)
.def(py::self == double())
// NE(!=).
.def(py::self != Expression())
.def(py::self != py::self)
.def(py::self != double());
py::class_<Variables>(m, "Variables")
.def(py::init<>())
.def(py::init<const Eigen::Ref<const VectorX<Variable>>&>())
.def("size", &Variables::size)
.def("empty", &Variables::empty)
.def("__str__", &Variables::to_string)
.def("__repr__",
[](const Variables& self) {
return fmt::format("<Variables \"{}\">", self);
})
.def("to_string", &Variables::to_string)
.def("__hash__",
[](const Variables& self) { return std::hash<Variables>{}(self); })
.def("insert",
[](Variables& self, const Variable& var) { self.insert(var); })
.def("insert",
[](Variables& self, const Variables& vars) { self.insert(vars); })
.def("erase",
[](Variables& self, const Variable& var) { return self.erase(var); })
.def("erase", [](Variables& self,
const Variables& vars) { return self.erase(vars); })
.def("include", &Variables::include)
.def("IsSubsetOf", &Variables::IsSubsetOf)
.def("IsSupersetOf", &Variables::IsSupersetOf)
.def("IsStrictSubsetOf", &Variables::IsStrictSubsetOf)
.def("IsStrictSupersetOf", &Variables::IsStrictSupersetOf)
.def("EqualTo", [](const Variables& self,
const Variables& vars) { return self == vars; })
.def(py::self == py::self)
.def(py::self < py::self)
.def(py::self + py::self)
.def(py::self + Variable())
.def(Variable() + py::self)
.def(py::self - py::self)
.def(py::self - Variable());
m.def("intersect", [](const Variables& vars1, const Variables& vars2) {
return intersect(vars1, vars2);
});
py::class_<Expression>(m, "Expression")
.def(py::init<>())
.def(py::init<double>())
.def(py::init<const Variable&>())
.def("__str__", &Expression::to_string)
.def("__repr__",
[](const Expression& self) {
return fmt::format("<Expression \"{}\">", self.to_string());
})
.def("__copy__",
[](const Expression& self) -> Expression { return self; })
.def("to_string", &Expression::to_string)
.def("Expand", &Expression::Expand)
.def("Evaluate", [](const Expression& self) { return self.Evaluate(); })
.def("Evaluate",
[](const Expression& self, const Environment::map& env) {
return self.Evaluate(Environment{env});
})
.def("EqualTo", &Expression::EqualTo)
// Addition
.def(py::self + py::self)
.def(py::self + Variable())
.def(py::self + double())
.def(Variable() + py::self)
.def(double() + py::self)
.def(py::self += py::self)
.def(py::self += Variable())
.def(py::self += double())
// Subtraction.
.def(py::self - py::self)
.def(py::self - Variable())
.def(py::self - double())
.def(Variable() - py::self)
.def(double() - py::self)
.def(py::self -= py::self)
.def(py::self -= Variable())
.def(py::self -= double())
// Multiplication.
.def(py::self * py::self)
.def(py::self * Variable())
.def(py::self * double())
.def(Variable() * py::self)
.def(double() * py::self)
.def(py::self *= py::self)
.def(py::self *= Variable())
.def(py::self *= double())
// Division.
.def(py::self / py::self)
.def(py::self / Variable())
.def(py::self / double())
.def(Variable() / py::self)
.def(double() / py::self)
.def(py::self /= py::self)
.def(py::self /= Variable())
.def(py::self /= double())
// Pow.
.def("__pow__", [](const Expression& self,
const double other) { return pow(self, other); })
.def("__pow__", [](const Expression& self,
const Variable& other) { return pow(self, other); })
.def("__pow__", [](const Expression& self,
const Expression& other) { return pow(self, other); })
// Unary Plus.
.def(+py::self)
// Unary Minus.
.def(-py::self)
// LT(<).
//
// Note that for `double < Expression` case, the reflected op ('>' in this
// case) is called. For example, `1 < x * y` will return `x * y > 1`.
.def(py::self < py::self)
.def(py::self < Variable())
.def(py::self < double())
// LE(<=).
.def(py::self <= py::self)
.def(py::self <= Variable())
.def(py::self <= double())
// GT(>).
.def(py::self > py::self)
.def(py::self > Variable())
.def(py::self > double())
// GE(>=).
.def(py::self >= py::self)
.def(py::self >= Variable())
.def(py::self >= double())
// EQ(==).
.def(py::self == py::self)
.def(py::self == Variable())
.def(py::self == double())
// NE(!=)
.def(py::self != py::self)
.def(py::self != Variable())
.def(py::self != double())
.def("Differentiate", &Expression::Differentiate)
.def("Jacobian", &Expression::Jacobian)
// TODO(eric.cousineau): Figure out how to consolidate with the below
// methods.
.def("log", &symbolic::log)
.def("__abs__", &symbolic::abs)
.def("exp", &symbolic::exp)
.def("sqrt", &symbolic::sqrt)
// TODO(eric.cousineau): Move `__pow__` here.
.def("sin", &symbolic::sin)
.def("cos", &symbolic::cos)
.def("tan", &symbolic::tan)
.def("arcsin", &symbolic::asin)
.def("arccos", &symbolic::acos)
.def("arctan2", &symbolic::atan2)
.def("sinh", &symbolic::sinh)
.def("cosh", &symbolic::cosh)
.def("tanh", &symbolic::tanh)
.def("min", &symbolic::min)
.def("max", &symbolic::max)
.def("ceil", &symbolic::ceil)
.def("floor", &symbolic::floor);
// TODO(eric.cousineau): Consider deprecating these methods?
auto math = py::module::import("pydrake.math");
MirrorDef<py::module, py::module>(&math, &m)
.def("log", &symbolic::log)
.def("abs", &symbolic::abs)
.def("exp", &symbolic::exp)
.def("sqrt", &symbolic::sqrt)
.def("pow", py::overload_cast<const Expression&, const Expression&>(
&symbolic::pow))
.def("sin", &symbolic::sin)
.def("cos", &symbolic::cos)
.def("tan", &symbolic::tan)
.def("asin", &symbolic::asin)
.def("acos", &symbolic::acos)
.def("atan", &symbolic::atan)
.def("atan2", &symbolic::atan2)
.def("sinh", &symbolic::sinh)
.def("cosh", &symbolic::cosh)
.def("tanh", &symbolic::tanh)
.def("min", &symbolic::min)
.def("max", &symbolic::max)
.def("ceil", &symbolic::ceil)
.def("floor", &symbolic::floor);
m.def("if_then_else", &symbolic::if_then_else);
m.def("Jacobian", [](const Eigen::Ref<const VectorX<Expression>>& f,
const Eigen::Ref<const VectorX<Variable>>& vars) {
return Jacobian(f, vars);
});
py::class_<Formula>(m, "Formula")
.def("GetFreeVariables", &Formula::GetFreeVariables)
.def("EqualTo", &Formula::EqualTo)
.def("Evaluate",
[](const Formula& self, const Environment::map& env) {
return self.Evaluate(Environment{env});
})
.def("Substitute",
[](const Formula& self, const Variable& var, const Expression& e) {
return self.Substitute(var, e);
})
.def("Substitute",
[](const Formula& self, const Variable& var1, const Variable& var2) {
return self.Substitute(var1, var2);
})
.def("Substitute", [](const Formula& self, const Variable& var,
const double c) { return self.Substitute(var, c); })
.def("Substitute",
[](const Formula& self, const Substitution& s) {
return self.Substitute(s);
})
.def("to_string", &Formula::to_string)
.def("__str__", &Formula::to_string)
.def("__repr__",
[](const Formula& self) {
return fmt::format("<Formula \"{}\">", self.to_string());
})
.def("__eq__", [](const Formula& self,
const Formula& other) { return self.EqualTo(other); })
.def("__ne__", [](const Formula& self,
const Formula& other) { return !self.EqualTo(other); })
.def("__hash__",
[](const Formula& self) { return std::hash<Formula>{}(self); })
.def_static("True", &Formula::True)
.def_static("False", &Formula::False)
.def("__nonzero__", [](const Formula&) {
throw std::runtime_error(
"Should not call `__nonzero__` on `Formula`. If you are trying to "
"make a map with `Variable`, `Expression`, or `Polynomial` as "
"keys, please use `EqualToDict`.");
});
// Cannot overload logical operators: http://stackoverflow.com/a/471561
// Defining custom function for clarity.
// Could use bitwise operators:
// https://docs.python.org/2/library/operator.html#operator.__and__
// However, this may reduce clarity and introduces constraints on order of
// operations.
m
// Hide AND and OR to permit us to make it accept 1 or more arguments in
// Python (and not have to handle type safety within C++).
.def("__logical_and",
[](const Formula& a, const Formula& b) { return a && b; })
.def("__logical_or",
[](const Formula& a, const Formula& b) { return a || b; })
.def("logical_not", [](const Formula& a) { return !a; });
py::class_<Monomial>(m, "Monomial")
.def(py::init<const Variable&>())
.def(py::init<const Variable&, int>())
.def(py::init<const map<Variable, int>&>())
.def("degree", &Monomial::degree)
.def("total_degree", &Monomial::total_degree)
.def(py::self * py::self)
.def(py::self *= py::self)
.def(py::self == py::self)
.def(py::self != py::self)
.def("__hash__",
[](const Monomial& self) { return std::hash<Monomial>{}(self); })
.def(py::self != py::self)
.def("__str__",
[](const Monomial& self) { return fmt::format("{}", self); })
.def("__repr__",
[](const Monomial& self) {
return fmt::format("<Monomial \"{}\">", self);
})
.def("EqualTo", [](const Monomial& self,
const Monomial& monomial) { return self == monomial; })
.def("GetVariables", &Monomial::GetVariables)
.def("get_powers", &Monomial::get_powers, py_reference_internal)
.def("ToExpression", &Monomial::ToExpression)
.def("Evaluate",
[](const Monomial& self, const Environment::map& env) {
return self.Evaluate(Environment{env});
})
.def("pow_in_place", &Monomial::pow_in_place, py_reference_internal)
.def("__pow__",
[](const Monomial& self, const int p) { return pow(self, p); });
m.def("MonomialBasis",
[](const Eigen::Ref<const VectorX<Variable>>& vars, const int degree) {
return MonomialBasis(Variables{vars}, degree);
})
.def("MonomialBasis", [](const Variables& vars, const int degree) {
return MonomialBasis(vars, degree);
});
py::class_<Polynomial>(m, "Polynomial")
.def(py::init<>())
.def(py::init<Polynomial::MapType>())
.def(py::init<const Monomial&>())
.def(py::init<const Expression&>())
.def(py::init<const Expression&, const Variables&>())
.def(py::init([](const Expression& e,
const Eigen::Ref<const VectorX<Variable>>& vars) {
return Polynomial{e, Variables{vars}};
}))
.def("indeterminates", &Polynomial::indeterminates)
.def("decision_variables", &Polynomial::decision_variables)
.def("Degree", &Polynomial::Degree)
.def("TotalDegree", &Polynomial::TotalDegree)
.def("monomial_to_coefficient_map",
&Polynomial::monomial_to_coefficient_map)
.def("ToExpression", &Polynomial::ToExpression)
.def("Differentiate", &Polynomial::Differentiate)
.def("AddProduct", &Polynomial::AddProduct)
.def(py::self + py::self)
.def(py::self + Monomial())
.def(Monomial() + py::self)
.def(py::self + double())
.def(double() + py::self)
.def(py::self - py::self)
.def(py::self - Monomial())
.def(Monomial() - py::self)
.def(py::self - double())
.def(double() - py::self)
.def(py::self * py::self)
.def(py::self * Monomial())
.def(Monomial() * py::self)
.def(py::self * double())
.def(double() * py::self)
.def(-py::self)
.def("EqualTo", &Polynomial::EqualTo)
.def(py::self == py::self)
.def(py::self != py::self)
.def("__hash__",
[](const Polynomial& self) { return std::hash<Polynomial>{}(self); })
.def("__str__",
[](const Polynomial& self) { return fmt::format("{}", self); })
.def("__repr__",
[](const Polynomial& self) {
return fmt::format("<Polynomial \"{}\">", self);
})
.def("__pow__",
[](const Polynomial& self, const int n) { return pow(self, n); })
.def("Evaluate",
[](const Polynomial& self, const Environment::map& env) {
return self.Evaluate(Environment{env});
})
.def("Jacobian", [](const Polynomial& p,
const Eigen::Ref<const VectorX<Variable>>& vars) {
return p.Jacobian(vars);
});
py::implicitly_convertible<double, drake::symbolic::Expression>();
py::implicitly_convertible<drake::symbolic::Variable,
drake::symbolic::Expression>();
py::implicitly_convertible<drake::symbolic::Monomial,
drake::symbolic::Polynomial>();
}
} // namespace pydrake
} // namespace drake