-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathframework_py_systems.cc
396 lines (360 loc) · 16.1 KB
/
framework_py_systems.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
#include "drake/bindings/pydrake/systems/framework_py_systems.h"
#include "pybind11/eigen.h"
#include "pybind11/eval.h"
#include "pybind11/functional.h"
#include "pybind11/pybind11.h"
#include "pybind11/stl.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/bindings/pydrake/systems/systems_pybind.h"
#include "drake/bindings/pydrake/util/drake_optional_pybind.h"
#include "drake/bindings/pydrake/util/eigen_pybind.h"
#include "drake/systems/framework/diagram.h"
#include "drake/systems/framework/leaf_system.h"
#include "drake/systems/framework/system.h"
#include "drake/systems/framework/vector_system.h"
using std::make_unique;
using std::string;
using std::unique_ptr;
using std::vector;
namespace drake {
namespace pydrake {
namespace {
using systems::System;
using systems::LeafSystem;
using systems::Context;
using systems::VectorSystem;
using systems::PublishEvent;
using systems::DiscreteUpdateEvent;
using systems::DiscreteValues;
// Provides a templated 'namespace'.
template <typename T>
struct Impl {
class PySystem : public py::wrapper<System<T>> {
public:
using Base = py::wrapper<System<T>>;
using Base::Base;
// Expose protected methods for binding.
using Base::DeclareInputPort;
};
class LeafSystemPublic : public LeafSystem<T> {
public:
using Base = LeafSystem<T>;
using Base::Base;
// N.B. These function methods are still typed as (LeafSystem<T>::*)(...),
// since they are more or less visibility imports.
// Defining methods here won't work, as it will become
// (LeafSystemPublic::*)(...), since this typeid is not exposed in pybind.
// If needed, solution is to expose it as an intermediate type if needed.
// Expose protected methods for binding, no need for virtual overrides
// (ordered by how they are bound).
using Base::DeclareVectorOutputPort;
using Base::DeclarePeriodicPublish;
using Base::DeclareContinuousState;
using Base::DeclareDiscreteState;
using Base::DeclarePeriodicDiscreteUpdate;
using Base::DeclareAbstractState;
// Because `LeafSystem<T>::DoPublish` is protected, and we had to override
// this method in `PyLeafSystem`, expose the method here for direct(-ish)
// access.
// (Otherwise, we get an error about inaccessible downcasting when trying to
// bind `PyLeafSystem::DoPublish` to `py::class_<LeafSystem<T>, ...>`.
using Base::DoPublish;
using Base::DoHasDirectFeedthrough;
using Base::DoCalcDiscreteVariableUpdates;
};
// Provide flexible inheritance to leverage prior binding information, per
// documentation:
// http://pybind11.readthedocs.io/en/stable/advanced/classes.html#combining-virtual-functions-and-inheritance // NOLINT
template <typename LeafSystemBase = LeafSystemPublic>
class PyLeafSystemBase : public py::wrapper<LeafSystemBase> {
public:
using Base = py::wrapper<LeafSystemBase>;
using Base::Base;
// Trampoline virtual methods.
void DoPublish(
const Context<T>& context,
const vector<const PublishEvent<T>*>& events) const override {
// Yuck! We have to dig in and use internals :(
// We must ensure that pybind only sees pointers, since this method may
// be called from C++, and pybind will not have seen these objects yet.
// @see https://github.com/pybind/pybind11/issues/1241
// TODO(eric.cousineau): Figure out how to supply different behavior,
// possibly using function wrapping.
PYBIND11_OVERLOAD_INT(
void, LeafSystem<T>, "_DoPublish", &context, events);
// If the macro did not return, use default functionality.
Base::DoPublish(context, events);
}
optional<bool> DoHasDirectFeedthrough(
int input_port, int output_port) const override {
PYBIND11_OVERLOAD_INT(
optional<bool>, LeafSystem<T>, "_DoHasDirectFeedthrough",
input_port, output_port);
// If the macro did not return, use default functionality.
return Base::DoHasDirectFeedthrough(input_port, output_port);
}
void DoCalcDiscreteVariableUpdates(
const Context<T>& context,
const std::vector<const DiscreteUpdateEvent<T>*>& events,
DiscreteValues<T>* discrete_state) const override {
// See `DoPublish` for explanation.
PYBIND11_OVERLOAD_INT(
void, LeafSystem<T>, "_DoCalcDiscreteVariableUpdates",
&context, events, discrete_state);
// If the macro did not return, use default functionality.
Base::DoCalcDiscreteVariableUpdates(context, events, discrete_state);
}
};
using PyLeafSystem = PyLeafSystemBase<>;
class VectorSystemPublic : public VectorSystem<T> {
public:
using Base = VectorSystem<T>;
VectorSystemPublic(int inputs, int outputs)
: Base(inputs, outputs) {}
using Base::EvalVectorInput;
using Base::GetVectorState;
// Virtual methods, for explicit bindings.
using Base::DoCalcVectorOutput;
using Base::DoCalcVectorTimeDerivatives;
using Base::DoCalcVectorDiscreteVariableUpdates;
};
class PyVectorSystem : public py::wrapper<VectorSystemPublic> {
public:
using Base = py::wrapper<VectorSystemPublic>;
using Base::Base;
// Trampoline virtual methods.
void DoPublish(
const Context<T>& context,
const vector<const PublishEvent<T>*>& events) const override {
// Copied from above, since we cannot use `PyLeafSystemBase` due to final
// overrides of some methods.
// TODO(eric.cousineau): Make this more granular?
PYBIND11_OVERLOAD_INT(
void, VectorSystem<T>, "_DoPublish", &context, events);
// If the macro did not return, use default functionality.
Base::DoPublish(context, events);
}
optional<bool> DoHasDirectFeedthrough(
int input_port, int output_port) const override {
PYBIND11_OVERLOAD_INT(
optional<bool>, VectorSystem<T>, "_DoHasDirectFeedthrough",
input_port, output_port);
// If the macro did not return, use default functionality.
return Base::DoHasDirectFeedthrough(input_port, output_port);
}
void DoCalcVectorOutput(
const Context<T>& context,
const Eigen::VectorBlock<const VectorX<T>>& input,
const Eigen::VectorBlock<const VectorX<T>>& state,
Eigen::VectorBlock<VectorX<T>>* output) const override {
// WARNING: Mutating `output` will not work when T is AutoDiffXd,
// Expression, etc.
// @see https://github.com/pybind/pybind11/pull/1152#issuecomment-340091423 // NOLINT
// TODO(eric.cousineau): Either wrap to have this return a value (blech),
// or solve the upstream issue.
PYBIND11_OVERLOAD_INT(
void, VectorSystem<T>, "_DoCalcVectorOutput",
// N.B. Passing `Eigen::Map<>` derived classes by reference rather
// than pointer to ensure conceptual clarity. pybind11 `type_caster`
// struggles with types of `Map<Derived>*`, but not `Map<Derived>&`.
&context, input, state, ToEigenRef(output));
// If the macro did not return, use default functionality.
Base::DoCalcVectorOutput(context, input, state, output);
}
void DoCalcVectorTimeDerivatives(
const Context<T>& context,
const Eigen::VectorBlock<const VectorX<T>>& input,
const Eigen::VectorBlock<const VectorX<T>>& state,
Eigen::VectorBlock<VectorX<T>>* derivatives) const override {
// WARNING: Mutating `derivatives` will not work when T is AutoDiffXd,
// Expression, etc. See above.
PYBIND11_OVERLOAD_INT(
void, VectorSystem<T>, "_DoCalcVectorTimeDerivatives",
&context, input, state, ToEigenRef(derivatives));
// If the macro did not return, use default functionality.
Base::DoCalcVectorOutput(context, input, state, derivatives);
}
void DoCalcVectorDiscreteVariableUpdates(
const Context<T>& context,
const Eigen::VectorBlock<const VectorX<T>>& input,
const Eigen::VectorBlock<const VectorX<T>>& state,
Eigen::VectorBlock<VectorX<T>>* next_state) const override {
// WARNING: Mutating `next_state` will not work when T is AutoDiffXd,
// Expression, etc. See above.
PYBIND11_OVERLOAD_INT(
void, VectorSystem<T>, "_DoCalcVectorDiscreteVariableUpdates",
&context, input, state, ToEigenRef(next_state));
// If the macro did not return, use default functionality.
Base::DoCalcVectorDiscreteVariableUpdates(
context, input, state, next_state);
}
};
static void DoDefinitions(py::module m) {
// NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace.
using namespace drake::systems;
// TODO(eric.cousineau): Resolve `str_py` workaround.
auto str_py = py::eval("str");
// TODO(eric.cousineau): Show constructor, but somehow make sure `pybind11`
// knows this is abstract?
DefineTemplateClassWithDefault<System<T>, PySystem>(
m, "System", GetPyParam<T>())
.def("set_name", &System<T>::set_name)
// Topology.
.def("get_input_port",
&System<T>::get_input_port, py_reference_internal)
.def("get_output_port",
&System<T>::get_output_port, py_reference_internal)
.def(
"_DeclareInputPort", &PySystem::DeclareInputPort,
py_reference_internal,
py::arg("type"), py::arg("size"), py::arg("random_type") = nullopt)
// - Feedthrough.
.def("HasAnyDirectFeedthrough", &System<T>::HasAnyDirectFeedthrough)
.def("HasDirectFeedthrough",
overload_cast_explicit<bool, int>(
&System<T>::HasDirectFeedthrough),
py::arg("output_port"))
.def("HasDirectFeedthrough",
overload_cast_explicit<bool, int, int>(
&System<T>::HasDirectFeedthrough),
py::arg("input_port"), py::arg("output_port"))
// Context.
.def("CreateDefaultContext", &System<T>::CreateDefaultContext)
.def("AllocateOutput", &System<T>::AllocateOutput)
.def(
"EvalVectorInput",
[](const System<T>* self, const Context<T>& arg1, int arg2) {
return self->EvalVectorInput(arg1, arg2);
}, py_reference,
// Keep alive, ownership: `return` keeps `Context` alive.
py::keep_alive<0, 2>())
.def(
"EvalAbstractInput",
[](const System<T>* self, const Context<T>& arg1, int arg2) {
return self->EvalAbstractInput(arg1, arg2);
}, py_reference,
// Keep alive, ownership: `return` keeps `Context` alive.
py::keep_alive<0, 2>())
.def("CalcOutput", &System<T>::CalcOutput)
// Sugar.
.def(
"GetGraphvizString",
[str_py](const System<T>* self) {
// @note This is a workaround; for some reason,
// casting this using `py::str` does not work, but directly
// calling the Python function (`str_py`) does.
return str_py(self->GetGraphvizString());
})
// Events.
.def("Publish",
overload_cast_explicit<void, const Context<T>&>(
&System<T>::Publish))
// Scalar types.
.def("ToAutoDiffXd", [](const System<T>& self) {
return self.ToAutoDiffXd();
})
.def("ToAutoDiffXdMaybe", &System<T>::ToAutoDiffXdMaybe)
.def("ToSymbolic", [](const System<T>& self) {
return self.ToSymbolic();
})
.def("ToSymbolicMaybe", &System<T>::ToSymbolicMaybe);
// Don't use a const-rvalue as a function handle parameter, as pybind11
// wants to copy it?
// TODO(eric.cousineau): Make a helper wrapper for this; file a bug in
// pybind11 (since these are arguments).
using CalcVectorPtrCallback =
std::function<void(const Context<T>*, BasicVector<T>*)>;
DefineTemplateClassWithDefault<LeafSystem<T>, PyLeafSystem, System<T>>(
m, "LeafSystem", GetPyParam<T>())
.def(py::init<>())
.def(
"_DeclareVectorOutputPort",
[](PyLeafSystem* self, const BasicVector<T>& arg1,
CalcVectorPtrCallback arg2) -> auto&& {
typename LeafOutputPort<T>::CalcVectorCallback wrapped =
[arg2](const Context<T>& nest_arg1, BasicVector<T>* nest_arg2) {
return arg2(&nest_arg1, nest_arg2);
};
return self->DeclareVectorOutputPort(arg1, wrapped);
}, py_reference_internal)
.def("_DeclarePeriodicPublish", &PyLeafSystem::DeclarePeriodicPublish,
py::arg("period_sec"), py::arg("offset_sec") = 0.)
.def("_DoPublish", &LeafSystemPublic::DoPublish)
// System attributes.
.def("_DoHasDirectFeedthrough",
&LeafSystemPublic::DoHasDirectFeedthrough)
// Continuous state.
.def("_DeclareContinuousState",
py::overload_cast<int>(&LeafSystemPublic::DeclareContinuousState),
py::arg("num_state_variables"))
.def("_DeclareContinuousState",
py::overload_cast<int, int, int>(
&LeafSystemPublic::DeclareContinuousState),
py::arg("num_q"), py::arg("num_v"), py::arg("num_z"))
.def("_DeclareContinuousState",
py::overload_cast<const BasicVector<T>&>(
&LeafSystemPublic::DeclareContinuousState),
py::arg("model_vector"))
// TODO(eric.cousineau): Ideally the downstream class of `BasicVector<T>`
// should expose `num_q`, `num_v`, and `num_z`?
.def("_DeclareContinuousState",
py::overload_cast<const BasicVector<T>&, int, int, int>(
&LeafSystemPublic::DeclareContinuousState),
py::arg("model_vector"),
py::arg("num_q"), py::arg("num_v"), py::arg("num_z"))
// Discrete state.
// TODO(eric.cousineau): Should there be a `BasicVector<>` overload?
.def("_DeclareDiscreteState", &LeafSystemPublic::DeclareDiscreteState)
.def("_DeclarePeriodicDiscreteUpdate",
&LeafSystemPublic::DeclarePeriodicDiscreteUpdate,
py::arg("period_sec"), py::arg("offset_sec") = 0.)
.def("_DoCalcDiscreteVariableUpdates",
&LeafSystemPublic::DoCalcDiscreteVariableUpdates)
// Abstract state.
.def("_DeclareAbstractState",
&LeafSystemPublic::DeclareAbstractState,
// Keep alive, ownership: `AbstractValue` keeps `self` alive.
py::keep_alive<2, 1>());
DefineTemplateClassWithDefault<Diagram<T>, System<T>>(
m, "Diagram", GetPyParam<T>())
.def("GetMutableSubsystemState",
[](Diagram<T>* self, const System<T>& arg1, Context<T>* arg2)
-> auto& {
// @note Compiler does not like `py::overload_cast` with this setup?
return self->GetMutableSubsystemState(arg1, arg2);
}, py_reference,
// Keep alive, ownership: `return` keeps `Context` alive.
py::keep_alive<0, 3>())
.def("GetMutableSubsystemContext",
[](Diagram<T>* self, const System<T>& arg1, Context<T>* arg2)
-> auto&& {
return self->GetMutableSubsystemContext(arg1, arg2);
}, py_reference,
// Keep alive, ownership: `return` keeps `Context` alive.
py::keep_alive<0, 3>());
// N.B. This will effectively allow derived classes of `VectorSystem` to
// override `LeafSystem` methods, disrespecting `final`-ity.
// This could be changed (see https://stackoverflow.com/a/2425785), but meh,
// we're already abusing Python and C++ enough.
DefineTemplateClassWithDefault<
VectorSystem<T>, PyVectorSystem, LeafSystem<T>>(
m, "VectorSystem", GetPyParam<T>())
.def(py::init([](int inputs, int outputs) {
return new PyVectorSystem(inputs, outputs);
}));
// TODO(eric.cousineau): Bind virtual methods once we provide a function
// wrapper to convert `Map<Derived>*` arguments.
// N.B. This could be mitigated by using `EigenPtr` in public interfaces in
// upstream code.
}
};
} // namespace
void DefineFrameworkPySystems(py::module m) {
auto bind_common_scalar_types = [m](auto dummy) {
using T = decltype(dummy);
Impl<T>::DoDefinitions(m);
};
type_visit(bind_common_scalar_types, pysystems::CommonScalarPack{});
}
} // namespace pydrake
} // namespace drake