/
datastorepythonwrapper.cpp
498 lines (359 loc) · 17.3 KB
/
datastorepythonwrapper.cpp
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
/*******************************************************************************
Copyright (C) The University of Auckland
OpenCOR 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.
OpenCOR 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/>.
*******************************************************************************/
//==============================================================================
// Data store Python wrapper
//==============================================================================
#include <Qt>
//==============================================================================
// Note: yes, these two header files must be included in this order...
#include "datastorepythonwrapper.h"
#include "datastorepythonnumpy.h"
//==============================================================================
#include "pythonqtsupport.h"
//==============================================================================
#include <array>
//==============================================================================
namespace OpenCOR {
namespace DataStore {
//==============================================================================
static bool initNumPy()
{
// Initialise NumPy
import_array1(false)
return true;
}
//==============================================================================
static DataStoreValue * getDataStoreValue(PyObject *pValuesDict, PyObject *pKey)
{
// Get and return a DataStoreValue item from a values dictionary
PythonQtInstanceWrapper *wrappedObject = PythonQtSupport::getInstanceWrapper(PyDict_GetItem(pValuesDict, pKey));
if (wrappedObject != nullptr) {
return static_cast<DataStoreValue *>(wrappedObject->_objPointerCopy);
}
return nullptr;
}
//==============================================================================
static PyObject * DataStoreValuesDict_subscript(PyObject *pValuesDict,
PyObject *pKey)
{
// Get and return a subscripted item from a values dictionary
auto *dataStoreValue = getDataStoreValue(pValuesDict, pKey);
if (dataStoreValue != nullptr) {
return PyFloat_FromDouble(dataStoreValue->value());
}
#include "pythonbegin.h"
Py_RETURN_NONE;
#include "pythonend.h"
}
//==============================================================================
using DataStoreValuesDictObject = struct {
PyDictObject mDict;
SimulationSupport::SimulationDataUpdatedFunction *mSimulationDataUpdatedFunction;
};
//==============================================================================
static int DataStoreValuesDict_ass_subscript(PyObject *pValuesDict,
PyObject *pKey, PyObject *pValue)
{
// Assign to a subscripted item in a values dictionary
if (pValue == nullptr) {
return PyDict_DelItem(pValuesDict, pKey);
}
PyNumber_Check(pValue);
auto dataStoreValue = getDataStoreValue(pValuesDict, pKey);
if (dataStoreValue != nullptr) {
#include "pythonbegin.h"
auto newValue = PyFloat_AS_DOUBLE(PyNumber_Float(pValue)); // NOLINT(cppcoreguidelines-pro-type-cstyle-cast)
#include "pythonend.h"
if (!qFuzzyCompare(dataStoreValue->value(), newValue)) {
dataStoreValue->setValue(newValue);
// Let our SimulationData object know that simulation data values
// have been updated
auto simulationDataUpdatedFunction = reinterpret_cast<DataStoreValuesDictObject *>(pValuesDict)->mSimulationDataUpdatedFunction;
if (simulationDataUpdatedFunction != nullptr) {
(*simulationDataUpdatedFunction)();
}
}
return 0;
}
PyErr_SetString(PyExc_TypeError, qPrintable(QObject::tr("invalid value.")));
return -1;
}
//==============================================================================
static PyMappingMethods DataStoreValuesDict_as_mapping = {
nullptr, // mp_length
static_cast<binaryfunc>(DataStoreValuesDict_subscript), // mp_subscript
static_cast<objobjargproc>(DataStoreValuesDict_ass_subscript) // mp_ass_subscript
};
//==============================================================================
#include "pythonbegin.h"
static PyObject * DataStoreValuesDict_repr(DataStoreValuesDictObject *pValuesDict)
{
// A string representation of a values dictionary
// Note: this is a modified version of dict_repr() from dictobject.c in the
// Python source code...
auto mp = reinterpret_cast<PyDictObject *>(pValuesDict);
Py_ssize_t i = Py_ReprEnter(reinterpret_cast<PyObject *>(mp));
PyObject *key = nullptr;
PyObject *value = nullptr;
bool first = true;
if (i != 0) {
return (i > 0)?
PyUnicode_FromString("{...}"):
nullptr;
}
if (mp->ma_used == 0) {
Py_ReprLeave(reinterpret_cast<PyObject *>(mp));
return PyUnicode_FromString("{}");
}
_PyUnicodeWriter writer;
_PyUnicodeWriter_Init(&writer);
writer.overallocate = 1;
writer.min_length = 1+4+(2+4)*(mp->ma_used-1)+1;
if (_PyUnicodeWriter_WriteChar(&writer, '{') < 0) {
goto error; // NOLINT(cppcoreguidelines-avoid-goto, hicpp-avoid-goto)
}
while (PyDict_Next(reinterpret_cast<PyObject *>(mp), &i, &key, &value) != 0) {
PyObject *s;
int res;
Py_INCREF(key);
Py_INCREF(value);
if (!first) {
if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0) {
goto error; // NOLINT(cppcoreguidelines-avoid-goto, hicpp-avoid-goto)
}
}
first = false;
s = PyObject_Repr(key);
if (s == nullptr) {
goto error; // NOLINT(cppcoreguidelines-avoid-goto, hicpp-avoid-goto)
}
res = _PyUnicodeWriter_WriteStr(&writer, s);
Py_DECREF(s);
if (res < 0) {
goto error; // NOLINT(cppcoreguidelines-avoid-goto, hicpp-avoid-goto)
}
if (_PyUnicodeWriter_WriteASCIIString(&writer, ": ", 2) < 0) {
goto error; // NOLINT(cppcoreguidelines-avoid-goto, hicpp-avoid-goto)
}
PythonQtInstanceWrapper *wrappedValue = PythonQtSupport::getInstanceWrapper(value);
if (wrappedValue != nullptr) {
auto dataStoreValue = static_cast<DataStoreValue *>(wrappedValue->_objPointerCopy);
Py_CLEAR(value);
value = PyFloat_FromDouble(dataStoreValue->value());
}
s = PyObject_Repr(value);
if (s == nullptr) {
goto error; // NOLINT(cppcoreguidelines-avoid-goto, hicpp-avoid-goto)
}
res = _PyUnicodeWriter_WriteStr(&writer, s);
Py_DECREF(s);
if (res < 0) {
goto error; // NOLINT(cppcoreguidelines-avoid-goto, hicpp-avoid-goto)
}
Py_CLEAR(key);
Py_CLEAR(value);
}
writer.overallocate = 0;
if (_PyUnicodeWriter_WriteChar(&writer, '}') < 0) {
goto error; // NOLINT(cppcoreguidelines-avoid-goto, hicpp-avoid-goto)
}
Py_ReprLeave((PyObject *)mp); // NOLINT(cppcoreguidelines-pro-type-cstyle-cast, google-readability-casting)
return _PyUnicodeWriter_Finish(&writer);
error:
Py_ReprLeave((PyObject *)mp); // NOLINT(cppcoreguidelines-pro-type-cstyle-cast, google-readability-casting)
_PyUnicodeWriter_Dealloc(&writer);
Py_XDECREF(key);
Py_XDECREF(value);
return nullptr;
}
#include "pythonend.h"
//==============================================================================
// Note: a DataStoreValuesDict is a dictionary sub-class for mapping between the
// values of a DataStoreValues list and Python...
static PyTypeObject DataStoreValuesDict_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"OpenCOR.DataStoreValuesDict", // tp_name
sizeof(DataStoreValuesDictObject), // tp_basicsize
0, // tp_itemsize
nullptr, // tp_dealloc
nullptr, // tp_print
nullptr, // tp_getattr
nullptr, // tp_setattr
nullptr, // tp_compare
reinterpret_cast<reprfunc>(DataStoreValuesDict_repr), // tp_repr
nullptr, // tp_as_number
nullptr, // tp_as_sequence
&DataStoreValuesDict_as_mapping, // tp_as_mapping
nullptr, // tp_hash
nullptr, // tp_call
nullptr, // tp_str
nullptr, // tp_getattro
nullptr, // tp_setattro
nullptr, // tp_as_buffer
Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, // tp_flags
nullptr, // tp_doc
nullptr, // tp_traverse
nullptr, // tp_clear
nullptr, // tp_richcompare
0, // tp_weaklistoffset
nullptr, // tp_iter
nullptr, // tp_iternext
nullptr, // tp_methods
nullptr, // tp_members
nullptr, // tp_getset
&PyDict_Type, // tp_base
nullptr, // tp_dict
nullptr, // tp_descr_get
nullptr, // tp_descr_set
0, // tp_dictoffset
nullptr, // tp_init
nullptr, // tp_alloc
nullptr, // tp_new
nullptr, // tp_free
nullptr, // tp_is_gc
nullptr, // tp_bases
nullptr, // tp_mro
nullptr, // tp_cache
nullptr, // tp_subclasses
nullptr, // tp_weaklist
nullptr, // tp_del
0, // tp_version_tag
nullptr, // tp_finalize
};
//==============================================================================
DataStorePythonWrapper::DataStorePythonWrapper(void *pModule,
QObject *pParent) :
QObject(pParent)
{
Q_UNUSED(pModule)
// Initialise NumPy
if (OpenCOR_Python_Wrapper_PyArray_API == nullptr) {
#ifdef QT_DEBUG
bool res =
#endif
initNumPy();
#ifdef QT_DEBUG
if (!res) {
qFatal("FATAL ERROR | %s:%d: unable to initialise NumPy.", __FILE__, __LINE__);
}
#endif
}
PyType_Ready(&DataStoreValuesDict_Type);
// Register some OpenCOR classes with Python and add some decorators to
// ourselves
PythonQtSupport::registerClass(&DataStore::staticMetaObject);
PythonQtSupport::registerClass(&DataStoreValue::staticMetaObject);
PythonQtSupport::registerClass(&DataStoreVariable::staticMetaObject);
PythonQtSupport::addInstanceDecorators(this);
}
//==============================================================================
double DataStorePythonWrapper::value(DataStoreVariable *pDataStoreVariable,
quint64 pPosition, int pRun) const
{
// Return the value of the given data store variable at the given position
// and for the given run
if ( (pDataStoreVariable != nullptr)
&& (pDataStoreVariable->array() != nullptr)) {
return pDataStoreVariable->value(pPosition, pRun);
}
throw std::runtime_error("'NoneType' object is not subscriptable.");
}
//==============================================================================
PyObject * DataStorePythonWrapper::values(DataStoreVariable *pDataStoreVariable,
int pRun) const
{
// Create and return a NumPy array for the given data store variable and run
DataStoreArray *dataStoreArray = pDataStoreVariable->array(pRun);
if ((pDataStoreVariable != nullptr) && (dataStoreArray != nullptr)) {
auto numPyArray = new NumPyPythonWrapper(dataStoreArray, pDataStoreVariable->size());
return numPyArray->numPyArray();
}
#include "pythonbegin.h"
Py_RETURN_NONE;
#include "pythonend.h"
}
//==============================================================================
PyObject * DataStorePythonWrapper::dataStoreValuesDict(const DataStoreValues *pDataStoreValues,
SimulationSupport::SimulationDataUpdatedFunction *pSimulationDataUpdatedFunction)
{
// Create and return a Python dictionary for the given data store values and
// keep track of the given simulation data updated function so that we can
// let OpenCOR know when simulation data have been updated
PyObject *res = PyDict_Type.tp_new(&DataStoreValuesDict_Type, nullptr, nullptr);
res->ob_type = &DataStoreValuesDict_Type;
reinterpret_cast<DataStoreValuesDictObject *>(res)->mSimulationDataUpdatedFunction = pSimulationDataUpdatedFunction;
if (pDataStoreValues != nullptr) {
for (int i = 0, iMax = pDataStoreValues->size(); i < iMax; ++i) {
auto value = pDataStoreValues->at(i);
PythonQtSupport::addObject(res, value->uri(), value);
}
}
return res;
}
//==============================================================================
PyObject * DataStorePythonWrapper::dataStoreVariablesDict(const DataStoreVariables &pDataStoreVariables)
{
// Create and return a Python dictionary for the given data store variables
PyObject *res = PyDict_New();
for (auto dataStoreVariable : pDataStoreVariables) {
PythonQtSupport::addObject(res, dataStoreVariable->uri(), dataStoreVariable);
}
return res;
}
//==============================================================================
PyObject * DataStorePythonWrapper::variables(DataStore *pDataStore)
{
// Return the variables in the given data store as a Python dictionary
return dataStoreVariablesDict(pDataStore->variables());
}
//==============================================================================
PyObject * DataStorePythonWrapper::voiAndVariables(DataStore *pDataStore)
{
// Return the VOI and variables in the given data store as a Python
// dictionary
return dataStoreVariablesDict(pDataStore->voiAndVariables());
}
//==============================================================================
NumPyPythonWrapper::NumPyPythonWrapper(DataStoreArray *pDataStoreArray,
quint64 pSize) :
mArray(pDataStoreArray)
{
// Tell our array that we are holding it
mArray->hold();
// Initialise ourselves
std::array<npy_intp, 1> dims = { npy_intp((pSize > 0)?pSize:pDataStoreArray->size()) };
#include "pythonbegin.h"
mNumPyArray = PyArray_SimpleNewFromData(1, dims.data(), NPY_DOUBLE, static_cast<void *>(mArray->data())); // NOLINT(cppcoreguidelines-pro-type-cstyle-cast)
PyArray_SetBaseObject(reinterpret_cast<PyArrayObject *>(mNumPyArray), // NOLINT(cppcoreguidelines-pro-type-cstyle-cast)
PythonQtSupport::wrapQObject(this));
#include "pythonend.h"
}
//==============================================================================
NumPyPythonWrapper::~NumPyPythonWrapper()
{
// Tell our array that we are releasing it
mArray->release();
}
//==============================================================================
PyObject * NumPyPythonWrapper::numPyArray() const
{
// Return our NumPy array
return mNumPyArray;
}
//==============================================================================
} // namespace DataStore
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================