-
Notifications
You must be signed in to change notification settings - Fork 182
/
script_interface.pyx
407 lines (318 loc) · 12.3 KB
/
script_interface.pyx
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
# Copyright (C) 2010-2019 The ESPResSo project
#
# This file is part of ESPResSo.
#
# ESPResSo is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ESPResSo is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import numpy as np
from .utils import to_char_pointer, to_str, handle_errors
from .utils cimport Vector3d, make_array_locked
from libcpp.memory cimport make_shared
cdef shared_ptr[ContextManager] _om
cdef class PObjectRef:
def __richcmp__(PObjectRef a, PObjectRef b, op):
if op == 2:
return a.sip == b.sip
else:
raise NotImplementedError
cdef shared_ptr[ObjectHandle] sip
cdef class PScriptInterface:
"""
Python interface to a core ScriptInterface object. The core ScriptInterface
class is itself an interface for other core classes, such as constraints,
shapes, observables, etc.
This class can be instantiated in two ways: (1) with the object id of an
existing core ScriptInterface object, or (2) with parameters to construct
a new ScriptInterface object in the core.
Parameters
----------
name : :obj:`str`
Name of the core class to instantiate (method 1).
\*\*kwargs
Parameters for the core class constructor (method 1).
sip : :class:`PObjectRef`
Object id of an existing core object (method 2).
policy : :obj:`str`, \{'GLOBAL', 'LOCAL'\}
Creation policy.
Attributes
----------
sip: :class:`PObjectRef`
Pointer to a ScriptInterface object in the core.
policy_: :obj:`str`
Creation policy.
"""
cdef shared_ptr[ObjectHandle] sip
cdef set_sip(self, shared_ptr[ObjectHandle] sip)
cdef VariantMap _sanitize_params(self, in_params) except *
def __init__(self, name=None, policy="GLOBAL", sip=None, **kwargs):
cdef CreationPolicy policy_
cdef PObjectRef sip_
if policy == "GLOBAL":
policy_ = GLOBAL
elif policy == "LOCAL":
policy_ = LOCAL
else:
raise Exception("Unknown policy '{}'.".format(policy))
if sip:
sip_ = sip
self.sip = sip_.sip
else:
global _om
self.set_sip(
_om.get().make_shared(
policy_,
to_char_pointer(name),
self._sanitize_params(kwargs)))
def __richcmp__(a, b, op):
if op == 2:
return a.get_sip() == b.get_sip()
else:
raise NotImplementedError
def _ref_count(self):
return self.sip.use_count()
def _valid_parameters(self):
return [to_str(p.data()) for p in self.sip.get().valid_parameters()]
def get_sip(self):
"""
Get pointer to the core object.
"""
ret = PObjectRef()
ret.sip = self.sip
return ret
cdef set_sip(self, shared_ptr[ObjectHandle] sip):
"""
Set the shared_ptr to an existing core object.
"""
self.sip = sip
def call_method(self, method, **kwargs):
"""
Call a method of the core class.
Parameters
----------
method : Creation policy.
Name of the core method.
\*\*kwargs
Arguments for the method.
"""
cdef VariantMap parameters
for name in kwargs:
parameters[to_char_pointer(name)] = python_object_to_variant(
kwargs[name])
res = variant_to_python_object(
self.sip.get().call_method(to_char_pointer(method), parameters))
handle_errors("")
return res
def name(self):
"""Return name of the core class."""
return to_str(self.sip.get().name().data())
def _serialize(self):
global _om
return _om.get().serialize(self.sip.get())
def _unserialize(self, state):
global _om
cdef shared_ptr[ObjectHandle] so_ptr = _om.get().deserialize(state)
self.set_sip(so_ptr)
cdef VariantMap _sanitize_params(self, in_params) except *:
cdef VariantMap out_params
for pname in in_params:
out_params[to_char_pointer(pname)] = python_object_to_variant(
in_params[pname])
return out_params
def set_params(self, **kwargs):
for name, value in kwargs.items():
self.sip.get().set_parameter(to_char_pointer(name),
python_object_to_variant(value))
def get_parameter(self, name):
cdef Variant value = self.sip.get().get_parameter(to_char_pointer(name))
return variant_to_python_object(value)
def get_params(self):
odict = {}
for pair in self.sip.get().get_parameters():
odict[to_str(pair.first)] = variant_to_python_object(
pair.second)
return odict
cdef Variant python_object_to_variant(value):
"""Convert Python objects to C++ Variant objects."""
cdef vector[Variant] vec
cdef unordered_map[int, Variant] vmap
cdef PObjectRef oref
if value is None:
return Variant()
# The order is important, the object character should
# be preserved even if the PScriptInterface derived class
# is iterable.
if isinstance(value, PScriptInterface):
oref = value.get_sip()
return make_variant(oref.sip)
elif isinstance(value, dict):
for k, v in value.items():
if not isinstance(k, int):
raise TypeError(
f"No conversion from type dict_item([({type(k).__name__}, {type(v).__name__})]) to Variant[std::unordered_map<int, Variant>]")
vmap[k] = python_object_to_variant(v)
return make_variant[unordered_map[int, Variant]](vmap)
elif hasattr(value, '__iter__') and not(type(value) == str):
for e in value:
vec.push_back(python_object_to_variant(e))
return make_variant[vector[Variant]](vec)
elif type(value) == str:
return make_variant[string](to_char_pointer(value))
elif type(value) == type(True):
return make_variant[bool](value)
elif np.issubdtype(np.dtype(type(value)), np.signedinteger):
return make_variant[int](value)
elif np.issubdtype(np.dtype(type(value)), np.floating):
return make_variant[double](value)
else:
raise TypeError(
f"No conversion from type {type(value).__name__} to Variant")
cdef variant_to_python_object(const Variant & value) except +:
"""Convert C++ Variant objects to Python objects."""
cdef vector[Variant] vec
cdef unordered_map[int, Variant] vmap
cdef shared_ptr[ObjectHandle] ptr
if is_none(value):
return None
if is_type[bool](value):
return get_value[bool](value)
if is_type[int](value):
return get_value[int](value)
if is_type[double](value):
return get_value[double](value)
if is_type[string](value):
return to_str(get_value[string](value))
if is_type[vector[int]](value):
return get_value[vector[int]](value)
if is_type[vector[double]](value):
return get_value[vector[double]](value)
if is_type[Vector3d](value):
return make_array_locked(get_value[Vector3d](value))
if is_type[shared_ptr[ObjectHandle]](value):
# Get the id and build a corresponding object
ptr = get_value[shared_ptr[ObjectHandle]](value)
if ptr:
so_name = to_str(ptr.get().name().data())
if not so_name:
raise Exception(
"Script object without name returned from the core")
# Look up python type for object
try:
pclass = _python_class_by_so_name[so_name]
except KeyError:
# Fallback class, if nothing more specific is registered
# for the script object name
pclass = ScriptInterfaceHelper
pptr = PObjectRef()
pptr.sip = ptr
return pclass(sip=pptr)
else:
return None
if is_type[vector[Variant]](value):
vec = get_value[vector[Variant]](value)
res = []
for i in vec:
res.append(variant_to_python_object(i))
return res
if is_type[unordered_map[int, Variant]](value):
vmap = get_value[unordered_map[int, Variant]](value)
res = {}
for kv in vmap:
res[kv.first] = variant_to_python_object(kv.second)
return res
raise TypeError("Unknown type")
def _unpickle_so_class(so_name, state):
cdef PObjectRef so_ptr
so_ptr = PObjectRef()
global _om
so_ptr.sip = _om.get().deserialize(state)
so = _python_class_by_so_name[so_name](sip=so_ptr)
so.define_bound_methods()
return so
class ScriptInterfaceHelper(PScriptInterface):
_so_name = None
_so_bind_methods = ()
_so_creation_policy = "GLOBAL"
def __init__(self, **kwargs):
super().__init__(self._so_name, policy=self._so_creation_policy,
**kwargs)
self.define_bound_methods()
def __reduce__(self):
return (_unpickle_so_class, (self._so_name, self._serialize()))
def __dir__(self):
return self.__dict__.keys() + self._valid_parameters()
def __getattr__(self, attr):
if attr in self._valid_parameters():
return self.get_parameter(attr)
if attr in self.__dict__:
return self.__dict__[attr]
raise AttributeError(
"Class " + self.__class__.__name__ + " does not have an attribute " + attr)
def __setattr__(self, attr, value):
if attr in self._valid_parameters():
self.set_params(**{attr: value})
else:
self.__dict__[attr] = value
def generate_caller(self, method_name):
def template_method(**kwargs):
res = self.call_method(method_name, **kwargs)
return res
return template_method
def define_bound_methods(self):
for method_name in self._so_bind_methods:
setattr(self, method_name, self.generate_caller(method_name))
class ScriptObjectRegistry(ScriptInterfaceHelper):
"""
Base class for container-like classes such as
:class:`~espressomd.constraints.Constraints` and
:class:`~espressomd.lbboundaries.LBBoundaries`. Derived classes must
implement an ``add()`` method which adds a single item to the container.
The core class should derive from ScriptObjectRegistry or provide
``"get_elements"`` and ``"size"`` as callable methods.
"""
def __getitem__(self, key):
return self.call_method("get_elements")[key]
def __iter__(self):
elements = self.call_method("get_elements")
for e in elements:
yield e
def __len__(self):
return self.call_method("size")
def __reduce__(self):
res = []
for item in self.__iter__():
res.append(item)
return (_unpickle_script_object_registry,
(self._so_name, self.get_params(), res))
def _unpickle_script_object_registry(so_name, params, items):
so = _python_class_by_so_name[so_name](**params)
for item in items:
so.add(item)
return so
# Map from script object names to their corresponding python classes
_python_class_by_so_name = {}
def script_interface_register(c):
"""
Decorator used to register script interface classes.
This will store a name<->class relationship in a registry, so that
parameters of type object can be instantiated as the correct python class.
"""
if not hasattr(c, "_so_name"):
raise Exception("Python classes representing a script object must "
"define an _so_name attribute at class level")
_python_class_by_so_name[c._so_name] = c
return c
cdef void init(MpiCallbacks & cb):
cdef Factory[ObjectHandle] f
initialize( & f)
global _om
_om = make_shared[ContextManager](cb, f)