/
simulationsupportpythonwrapper.cpp
655 lines (459 loc) · 23.4 KB
/
simulationsupportpythonwrapper.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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
/*******************************************************************************
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 <https://gnu.org/licenses>.
*******************************************************************************/
//==============================================================================
// Simulation support Python wrapper
//==============================================================================
#include "corecliutils.h"
#include "cellmlfileruntime.h"
#include "datastorepythonwrapper.h"
#include "filemanager.h"
#include "interfaces.h"
#include "pythonqtsupport.h"
#include "simulation.h"
#include "simulationmanager.h"
#include "simulationsupportpythonwrapper.h"
//==============================================================================
#include <QApplication>
#include <QFileInfo>
#include <QWidget>
//==============================================================================
#include <array>
#include <memory>
//==============================================================================
namespace OpenCOR {
namespace SimulationSupport {
//==============================================================================
static void setOdeSolver(SimulationData *pSimulationData,
const QString &pOdeSolverName)
{
// Set the ODE solver for the given simulation data using the given ODE
// solver name
for (auto solverInterface : Core::solverInterfaces()) {
if (pOdeSolverName == solverInterface->solverName()) {
// Set the ODE solver's name
pSimulationData->setOdeSolverName(pOdeSolverName);
for (const auto &solverInterfaceProperty : solverInterface->solverProperties()) {
// Set each ODE solver property to their default value
pSimulationData->setOdeSolverProperty(solverInterfaceProperty.id(), solverInterfaceProperty.defaultValue());
}
return;
}
}
throw std::runtime_error(QObject::tr("The requested solver (%1) could not be found.").arg(pOdeSolverName).toStdString());
}
//==============================================================================
static void setNlaSolver(SimulationData *pSimulationData,
const QString &pNlaSolverName)
{
// Set the NLA solver for the given simulation data using the given NLA
// solver name
for (auto solverInterface : Core::solverInterfaces()) {
if (pNlaSolverName == solverInterface->solverName()) {
// Set the NLA solver's name
pSimulationData->setNlaSolverName(pNlaSolverName);
for (const auto &solverInterfaceProperty : solverInterface->solverProperties()) {
// Set each NLA solver property to their default value
pSimulationData->setNlaSolverProperty(solverInterfaceProperty.id(), solverInterfaceProperty.defaultValue());
}
return;
}
}
throw std::runtime_error(QObject::tr("The requested solver (%1) could not be found.").arg(pNlaSolverName).toStdString());
}
//==============================================================================
static PyObject * initializeSimulation(const QString &pFileName)
{
// Ask our simulation manager to manage our file and then retrieve the
// corresponding simulation from it
SimulationManager *simulationManager = SimulationManager::instance();
simulationManager->manage(pFileName);
Simulation *simulation = simulationManager->simulation(pFileName);
if (simulation != nullptr) {
// Check for issues with the simulation
if (simulation->hasBlockingIssues()) {
// We return the simulation to allow the user to view its issues
return PythonQt::priv()->wrapQObject(simulation);
}
// Retrieve a default ODE and NLA solver
// Note: this is useful in case our simulation is solely based on a
// CellML file...
QString odeSolverName;
QString nlaSolverName;
for (auto solverInterface : Core::solverInterfaces()) {
QString solverName = solverInterface->solverName();
if (solverInterface->solverType() == Solver::Type::Ode) {
if ( odeSolverName.isEmpty()
|| (odeSolverName.compare(solverName, Qt::CaseInsensitive) > 0)) {
odeSolverName = solverName;
}
} else if (solverInterface->solverType() == Solver::Type::Nla) {
if ( nlaSolverName.isEmpty()
|| (nlaSolverName.compare(solverName, Qt::CaseInsensitive) > 0)) {
nlaSolverName = solverName;
}
}
}
// Set our default ODE and NLA, if needed, solvers
CellMLSupport::CellmlFileRuntime *runtime = simulation->runtime();
setOdeSolver(simulation->data(), odeSolverName);
if ((runtime != nullptr) && runtime->needNlaSolver()) {
setNlaSolver(simulation->data(), nlaSolverName);
}
// Further initialise our simulation, should we be dealing with either
// a SED-ML file or a COMBINE archive
// Note: this will overwrite the default ODE and NLA solvers that we set
// above...
if ( (simulation->fileType() == SimulationSupport::Simulation::FileType::SedmlFile)
|| (simulation->fileType() == SimulationSupport::Simulation::FileType::CombineArchive)) {
QString error = simulation->furtherInitialize();
if (!error.isEmpty()) {
// We couldn't complete initialisation, so no longer manage the
// simulation and raise a Python exception
simulationManager->unmanage(pFileName);
PyErr_SetString(PyExc_ValueError, qPrintable(error));
return nullptr;
}
}
// Reset both the simulation's data and results (well, initialise in the
// case of its data), should we have a valid runtime
if ((runtime != nullptr) && runtime->isValid()) {
simulation->data()->reset();
simulation->results()->reset();
}
// Return our simulation object as a Python object
return PythonQt::priv()->wrapQObject(simulation);
}
#include "pythonbegin.h"
Py_RETURN_NONE;
#include "pythonend.h"
}
//==============================================================================
#include "opensimulation.cpp.inl"
//==============================================================================
#include "closesimulation.cpp.inl"
//==============================================================================
SimulationSupportPythonWrapper::SimulationSupportPythonWrapper(void *pModule,
QObject *pParent) :
QObject(pParent)
{
// Register some OpenCOR classes with Python and add some decorators to
// ourselves
PythonQtSupport::registerClass(&Simulation::staticMetaObject);
PythonQtSupport::registerClass(&SimulationData::staticMetaObject);
PythonQtSupport::registerClass(&SimulationResults::staticMetaObject);
PythonQtSupport::addInstanceDecorators(this);
// Add some Python wrappers
static std::array<PyMethodDef, 4> PythonSimulationSupportMethods = {{
{ "open_simulation", openSimulation, METH_VARARGS, "Open a simulation." },
{ "close_simulation", closeSimulation, METH_VARARGS, "Close a simulation." },
{ nullptr, nullptr, 0, nullptr }
}};
PyModule_AddFunctions(static_cast<PyObject *>(pModule),
PythonSimulationSupportMethods.data());
}
//==============================================================================
bool SimulationSupportPythonWrapper::valid(Simulation *pSimulation)
{
// Return whether the given simulation is valid
if (!pSimulation->hasBlockingIssues()) {
CellMLSupport::CellmlFileRuntime *runtime = pSimulation->runtime();
return (runtime != nullptr) && runtime->isValid();
}
return false;
}
//==============================================================================
bool SimulationSupportPythonWrapper::run(Simulation *pSimulation)
{
// Run the given simulation, but only if it doesn't have blocking issues and
// if it is valid
if (pSimulation->hasBlockingIssues()) {
throw std::runtime_error(tr("The simulation has blocking issues and cannot therefore be run.").toStdString());
}
if (!valid(pSimulation)) {
throw std::runtime_error(tr("The simulation has an invalid runtime and cannot therefore be run.").toStdString());
}
// Reset our internals
mElapsedTime = -1;
mErrorMessage = QString();
// Try to allocate all the memory we need by adding a run to our simulation
// and, if successful, run our simulation
// Note: we keep track of our focus widget (which might be our Python
// console window), so that we can give the focus back to it once we
// are done running our simulation...
QWidget *focusWidget = QApplication::focusWidget();
if (pSimulation->addRun()) {
// Keep track of any simulation error and of when the simulation is done
connect(pSimulation, &Simulation::error,
this, &SimulationSupportPythonWrapper::simulationError,
Qt::UniqueConnection);
connect(pSimulation, &Simulation::done,
this, &SimulationSupportPythonWrapper::simulationDone,
Qt::UniqueConnection);
// Run our simulation and wait for it to complete
// Note: we use a queued connection because the event is in our
// thread...
QEventLoop waitLoop;
auto connection = std::make_shared<QMetaObject::Connection>();
*connection = connect(pSimulation, &Simulation::done, [&]() {
waitLoop.quit();
disconnect(*connection);
});
pSimulation->run();
waitLoop.exec();
// Throw any error message that has been generated
if (!mErrorMessage.isEmpty()) {
throw std::runtime_error(mErrorMessage.toStdString());
}
} else {
throw std::runtime_error(tr("The memory required for the simulation could not be allocated.").toStdString());
}
// Restore the focus to the previous widget
if (focusWidget != nullptr) {
focusWidget->setFocus();
}
return mElapsedTime >= 0;
}
//==============================================================================
void SimulationSupportPythonWrapper::reset(Simulation *pSimulation, bool pAll)
{
// Reset the given simulation
pSimulation->reset(pAll);
}
//==============================================================================
void SimulationSupportPythonWrapper::clear_results(Simulation *pSimulation)
{
// Reset the given simulation results
pSimulation->results()->reset();
}
//==============================================================================
PyObject * SimulationSupportPythonWrapper::issues(Simulation *pSimulation) const
{
// Return a list of issues the given simulation has, if any
PyObject *issuesList = PyList_New(0);
auto simulationIssues = pSimulation->issues();
for (const auto &simulationIssue : simulationIssues) {
QString information;
if ((simulationIssue.line() != 0) && (simulationIssue.column() != 0)) {
information = QString("[%1:%2] %3: %4.").arg(simulationIssue.line())
.arg(simulationIssue.column())
.arg(simulationIssue.typeAsString(),
Core::formatMessage(simulationIssue.message()));
} else {
information = QString("%1: %2.").arg(simulationIssue.typeAsString(),
Core::formatMessage(simulationIssue.message()));
}
PyList_Append(issuesList, PyUnicode_FromString(information.toUtf8().constData()));
}
return issuesList;
}
//==============================================================================
double SimulationSupportPythonWrapper::starting_point(SimulationData *pSimulationData)
{
// Return the starting point for the given simulation data
return pSimulationData->startingPoint();
}
//==============================================================================
void SimulationSupportPythonWrapper::set_starting_point(SimulationData *pSimulationData,
double pStartingPoint)
{
// Set the starting point for the given simulation data
pSimulationData->setStartingPoint(pStartingPoint);
}
//==============================================================================
double SimulationSupportPythonWrapper::ending_point(SimulationData *pSimulationData)
{
// Return the ending point for the given simulation data
return pSimulationData->endingPoint();
}
//==============================================================================
void SimulationSupportPythonWrapper::set_ending_point(SimulationData *pSimulationData,
double pEndingPoint)
{
// Set the ending point for the given simulation data
pSimulationData->setEndingPoint(pEndingPoint);
}
//==============================================================================
double SimulationSupportPythonWrapper::point_interval(SimulationData *pSimulationData)
{
// Return the point interval for the given simulation data
return pSimulationData->pointInterval();
}
//==============================================================================
void SimulationSupportPythonWrapper::set_point_interval(SimulationData *pSimulationData,
double pPointInterval)
{
// Set the point interval for the given simulation data
pSimulationData->setPointInterval(pPointInterval);
}
//==============================================================================
QString SimulationSupportPythonWrapper::ode_solver_name(SimulationData *pSimulationData)
{
// Return the name of the ODE solver for the given simulation data
return pSimulationData->odeSolverName();
}
//==============================================================================
void SimulationSupportPythonWrapper::set_ode_solver(SimulationData *pSimulationData,
const QString &pName)
{
// Set the ODE solver for the given simulation data using the given name
SimulationSupport::setOdeSolver(pSimulationData, pName);
}
//==============================================================================
QVariant SimulationSupportPythonWrapper::ode_solver_property(SimulationData *pSimulationData,
const QString &pName)
{
// Return the value for the given ODE solver property
return pSimulationData->odeSolverProperty(pName);
}
//==============================================================================
void SimulationSupportPythonWrapper::set_ode_solver_property(SimulationData *pSimulationData,
const QString &pName,
const QVariant &pValue)
{
// Set the ODE solver property for the given simulation data using the given
// name and value
pSimulationData->setOdeSolverProperty(pName, pValue);
}
//==============================================================================
QVariant SimulationSupportPythonWrapper::nla_solver_property(SimulationData *pSimulationData,
const QString &pName)
{
// Return the value for the given NLA solver property
return pSimulationData->nlaSolverProperty(pName);
}
//==============================================================================
QString SimulationSupportPythonWrapper::nla_solver_name(SimulationData *pSimulationData)
{
// Return the name of the NLA solver for the given simulation data
return pSimulationData->nlaSolverName();
}
//==============================================================================
void SimulationSupportPythonWrapper::set_nla_solver(SimulationData *pSimulationData,
const QString &pName)
{
// Set the NLA solver for the given simulation data using the given name
SimulationSupport::setNlaSolver(pSimulationData, pName);
}
//==============================================================================
void SimulationSupportPythonWrapper::set_nla_solver_property(SimulationData *pSimulationData,
const QString &pName,
const QVariant &pValue)
{
// Set the NLA solver property for the given simulation data using the given
// name and value
pSimulationData->setNlaSolverProperty(pName, pValue);
}
//==============================================================================
PyObject * SimulationSupportPythonWrapper::constants(SimulationData *pSimulationData) const
{
// Return the constants values for the given simulation data
return DataStore::DataStorePythonWrapper::dataStoreValuesDict(pSimulationData->constantsValues(),
&(pSimulationData->simulationDataUpdatedFunction()));
}
//==============================================================================
PyObject * SimulationSupportPythonWrapper::rates(SimulationData *pSimulationData) const
{
// Return the rates values for the given simulation data
return DataStore::DataStorePythonWrapper::dataStoreValuesDict(pSimulationData->ratesValues(),
&(pSimulationData->simulationDataUpdatedFunction()));
}
//==============================================================================
PyObject * SimulationSupportPythonWrapper::states(SimulationData *pSimulationData) const
{
// Return the states values for the given simulation data
return DataStore::DataStorePythonWrapper::dataStoreValuesDict(pSimulationData->statesValues(),
&(pSimulationData->simulationDataUpdatedFunction()));
}
//==============================================================================
PyObject * SimulationSupportPythonWrapper::algebraic(SimulationData *pSimulationData) const
{
// Return the algebraic values for the given simulation data
return DataStore::DataStorePythonWrapper::dataStoreValuesDict(pSimulationData->algebraicValues(),
&(pSimulationData->simulationDataUpdatedFunction()));
}
//==============================================================================
DataStore::DataStore * SimulationSupportPythonWrapper::data_store(SimulationResults *pSimulationResults) const
{
// Return the data store for the given simulation results
return pSimulationResults->dataStore();
}
//==============================================================================
DataStore::DataStoreVariable * SimulationSupportPythonWrapper::voi(SimulationResults *pSimulationResults) const
{
// Return the VOI variable for the given simulation results
return pSimulationResults->pointsVariable();
}
//==============================================================================
PyObject * SimulationSupportPythonWrapper::constants(SimulationResults *pSimulationResults) const
{
// Return the constants variables for the given simulation results
return DataStore::DataStorePythonWrapper::dataStoreVariablesDict(pSimulationResults->constantsVariables());
}
//==============================================================================
PyObject * SimulationSupportPythonWrapper::rates(SimulationResults *pSimulationResults) const
{
// Return the rates variables for the given simulation results
return DataStore::DataStorePythonWrapper::dataStoreVariablesDict(pSimulationResults->ratesVariables());
}
//==============================================================================
PyObject * SimulationSupportPythonWrapper::states(SimulationResults *pSimulationResults) const
{
// Return the states variables for the given simulation results
return DataStore::DataStorePythonWrapper::dataStoreVariablesDict(pSimulationResults->statesVariables());
}
//==============================================================================
PyObject * SimulationSupportPythonWrapper::algebraic(SimulationResults *pSimulationResults) const
{
// Return the algebraic variables for the given simulation results
return DataStore::DataStorePythonWrapper::dataStoreVariablesDict(pSimulationResults->algebraicVariables());
}
//==============================================================================
void SimulationSupportPythonWrapper::set_value(DataStore::DataStoreValue *pDataStoreValue,
double pValue)
{
// Set the value for the given data store value
pDataStoreValue->setValue(pValue);
}
//==============================================================================
int SimulationSupportPythonWrapper::runs_count(DataStore::DataStoreVariable *pDataStoreVariable) const
{
// Return the number of runs for the given data store variable
return pDataStoreVariable->runsCount();
}
//==============================================================================
quint64 SimulationSupportPythonWrapper::values_count(DataStore::DataStoreVariable *pDataStoreVariable,
int pRun) const
{
// Return the number of values in the given run of the given data store
// variable
return pDataStoreVariable->size(pRun);
}
//==============================================================================
void SimulationSupportPythonWrapper::simulationError(const QString &pErrorMessage)
{
// Keep track for the given error message
mErrorMessage = pErrorMessage;
}
//==============================================================================
void SimulationSupportPythonWrapper::simulationDone(qint64 pElapsedTime)
{
// Save the given elapsed time and let people know that we have got it
mElapsedTime = pElapsedTime;
}
//==============================================================================
} // namespace SimulationSupport
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================