-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
call_python.h
226 lines (183 loc) · 6.7 KB
/
call_python.h
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
#pragma once
#include <string>
#include <vector>
#include "drake/common/copyable_unique_ptr.h"
#include "drake/common/proto/call_matlab.h"
/// @file
/// @brief Utilities for calling Python from C++
///
/// Provides functionality similar to `call_matlab` (i.e., one-directional RPC),
/// leveraging an API similar to `pybind11`.
///
/// @see call_python_test.cc for C++ examples.
// TODO(eric.cousineau): Add (untested) example usage in IPython notebook.
namespace drake {
namespace common {
// begin forward declarations
// These are necessary for `PythonApi`.
class PythonRemoteVariable;
// TODO(eric.cousineau): Generalize RPC marshaling so that we do not need to
// overload a function named `ToMatlabArray`.
void ToMatlabArray(const PythonRemoteVariable& var, MatlabArray* matlab_array);
template <typename... Types>
PythonRemoteVariable CallPython(const std::string& function_name,
Types... args);
template <typename... Types>
PythonRemoteVariable ToPythonTuple(Types... args);
template <typename T>
PythonRemoteVariable NewPythonVariable(T value);
namespace internal {
class PythonItemPolicy;
class PythonAttrPolicy;
template <typename Policy>
class PythonAccessor;
// end forward declarations
using PythonItemAccessor = PythonAccessor<PythonItemPolicy>;
using PythonAttrAccessor = PythonAccessor<PythonAttrPolicy>;
// Mimic pybind11's `object_api` and `accessor<>` setup, such that we can
// chain operations together more conveniently.
template <typename Derived>
class PythonApi {
public:
/// Calls object with given arguments, returning the remote result.
template <typename... Types>
PythonRemoteVariable operator()(Types... args) const;
/// Accesses an attribute.
PythonAttrAccessor attr(const std::string& name) const;
/// Accesses an item.
template <typename Type>
PythonItemAccessor operator[](Type key) const;
/// Accesses a NumPy-friendly slice.
template <typename... Types>
PythonItemAccessor slice(Types... args) const;
private:
// Provides type-cast view for CRTP implementation.
const Derived& derived() const {
return static_cast<const Derived&>(*this);
}
};
} // namespace internal
/// Presents variable stored in Python side.
class PythonRemoteVariable : public internal::PythonApi<PythonRemoteVariable> {
public:
PythonRemoteVariable();
// TODO(eric.cousineau): To support deletion, disable copy constructor, only
// allow moving (if we want to avoid needing a global reference counter).
int64_t unique_id() const { return unique_id_; }
private:
const int64_t unique_id_{};
};
namespace internal {
// Gets/sets an object's attribute.
class PythonAttrPolicy {
public:
using KeyType = std::string;
static PythonRemoteVariable get(PythonRemoteVariable obj,
const KeyType& key) {
return CallPython("getattr", obj, key);
}
static PythonRemoteVariable set(PythonRemoteVariable obj,
const KeyType& key,
PythonRemoteVariable value) {
return CallPython("setattr", obj, key, value);
}
};
// Gets/sets an object's item.
class PythonItemPolicy {
public:
using KeyType = PythonRemoteVariable;
static PythonRemoteVariable get(PythonRemoteVariable obj,
const KeyType& key) {
return CallPython("getitem", obj, key);
}
static PythonRemoteVariable set(PythonRemoteVariable obj,
const KeyType& key,
PythonRemoteVariable value) {
return CallPython("setitem", obj, key, value);
}
};
// API-consistent mechanism to access a portion of an object (item or attr).
template <typename Policy>
class PythonAccessor : public internal::PythonApi<PythonAccessor<Policy>> {
public:
using KeyType = typename Policy::KeyType;
PythonAccessor(PythonRemoteVariable obj, const KeyType& key)
: obj_(obj), key_(key) {}
operator PythonRemoteVariable() const { return value(); }
PythonRemoteVariable operator=(const PythonAccessor& value) {
return set_value(value);
}
PythonRemoteVariable operator=(const PythonRemoteVariable& value) {
return set_value(value);
}
template <typename T>
PythonRemoteVariable operator=(const T& value) {
return set_value(NewPythonVariable(value));
}
private:
PythonRemoteVariable value() const { return Policy::get(obj_, key_); }
PythonRemoteVariable set_value(const PythonRemoteVariable& value) const {
return Policy::set(obj_, key_, value);
}
PythonRemoteVariable obj_;
KeyType key_;
};
// Now that we have our types defined, we can implement the functionality for
// the API.
template <typename Derived>
PythonAttrAccessor PythonApi<Derived>::attr(const std::string& name) const {
return {derived(), name};
}
template <typename Derived>
template <typename... Types>
PythonRemoteVariable PythonApi<Derived>::operator()(Types... args) const {
return CallPython("call", derived(), args...);
}
template <typename Derived>
template <typename Type>
PythonItemAccessor PythonApi<Derived>::operator[](Type key) const {
return {derived(), NewPythonVariable(key)};
}
template <typename Derived>
template <typename... Types>
PythonItemAccessor PythonApi<Derived>::slice(Types... args) const {
return {derived(), CallPython("make_slice_arg", args...)};
}
void PublishCallPython(const MatlabRPC& msg);
} // namespace internal
/// Initializes `CallPython` for a given file.
/// If this function is not called, then the file defaults to `/tmp/python_rpc`.
/// @throws std::runtime_error If either this function or `CallPython` have
/// already been called.
void CallPythonInit(const std::string& filename);
/// Calls a Python client with a given function and arguments, returning
/// a handle to the result.
template <typename... Types>
PythonRemoteVariable CallPython(const std::string& function_name,
Types... args) {
PythonRemoteVariable output;
MatlabRPC msg;
msg.add_lhs(output.unique_id());
internal::AssembleCallMatlabMsg(&msg, args...);
msg.set_function_name(function_name);
internal::PublishCallPython(msg);
return output;
}
/// Creates a tuple in Python.
template <typename... Types>
PythonRemoteVariable ToPythonTuple(Types... args) {
return CallPython("make_tuple", args...);
}
/// Creates a keyword-argument list to be unpacked.
/// @param args Argument list in the form of (key1, value1, key2, value2, ...).
template <typename... Types>
PythonRemoteVariable ToPythonKwargs(Types... args) {
return CallPython("make_kwargs", args...);
}
/// Creates a new remote variable with the corresponding value set.
template <typename T>
PythonRemoteVariable NewPythonVariable(T value) {
return CallPython("pass_through", value);
}
} // namespace common
} // namespace drake