-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathPyRun.cpp
346 lines (304 loc) · 9.5 KB
/
PyRun.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
// PyRun.cpp ---
//
// Filename: PyRun.cpp
// Description:
// Author: subha
// Created: Sat Oct 11 14:47:22 2014 (+0530)
#include "Python.h"
#include "../basecode/header.h"
#include "PyRun.h"
const int PyRun::RUNPROC = 1;
const int PyRun::RUNTRIG = 2;
const int PyRun::RUNBOTH = 0;
static SrcFinfo1<double> *outputOut()
{
static SrcFinfo1<double> outputOut(
"output",
"Sends out the value of local variable called `output`. Thus, you can"
" have Python statements which compute some value and assign it to the"
" variable called `output` (which is defined at `reinit` call). This"
" will be sent out to any target connected to the `output` field.");
return &outputOut;
}
const Cinfo *PyRun::initCinfo()
{
static ValueFinfo<PyRun, string> runstring(
"runString", "String to be executed at each time step.", &PyRun::setRunString, &PyRun::getRunString);
static ValueFinfo<PyRun, string> initstring(
"initString",
"String to be executed at initialization (reinit).",
&PyRun::setInitString,
&PyRun::getInitString);
static ValueFinfo<PyRun, string> inputvar(
"inputVar",
"Name of local variable in which input balue is to be stored. Default"
" is `input_` (to avoid conflict with Python's builtin function"
" `input`).",
&PyRun::setInputVar,
&PyRun::getInputVar);
static ValueFinfo<PyRun, string> outputvar(
"outputVar",
"Name of local variable for storing output. Default is `output`.",
&PyRun::setOutputVar,
&PyRun::getOutputVar);
static ValueFinfo<PyRun, int> mode("mode",
"Flag to indicate whether runString "
"should be executed for both trigger "
"and process, or one of them.",
&PyRun::setMode,
&PyRun::getMode);
static DestFinfo trigger(
"trigger",
"Executes the current runString whenever a message arrives. It stores"
" the incoming value in local variable named"
" `input_`, which can be used in the"
" `runString` (the underscore is added to avoid conflict with Python's"
" builtin function `input`). If debug is True, it prints the input"
" value.",
new EpFunc1<PyRun, double>(&PyRun::trigger));
static DestFinfo run("run",
"Runs a specified string. Does not modify existing "
"run or init strings.",
new EpFunc1<PyRun, string>(&PyRun::run));
static DestFinfo process(
"process",
"Handles process call. Runs the current runString.",
new ProcOpFunc<PyRun>(&PyRun::process));
static DestFinfo reinit("reinit",
"Handles reinit call. Runs the current initString.",
new ProcOpFunc<PyRun>(&PyRun::reinit));
static Finfo *processShared[] = {&process, &reinit};
static SharedFinfo proc(
"proc",
"This is a shared message to receive Process messages "
"from the scheduler objects."
"The first entry in the shared msg is a MsgDest "
"for the Process operation. It has a single argument, "
"ProcInfo, which holds lots of information about current "
"time, thread, dt and so on. The second entry is a MsgDest "
"for the Reinit operation. It also uses ProcInfo. ",
processShared,
sizeof(processShared) / sizeof(Finfo *));
static Finfo *pyRunFinfos[] = {&runstring, &initstring, &mode,
&inputvar, &outputvar, &trigger,
outputOut(), &run, &proc, };
static string doc[] = {
"Name", "PyRun",
"Author", "Subhasis Ray",
"Description", "Runs Python statements from inside MOOSE."};
static Dinfo<PyRun> dinfo;
static Cinfo pyRunCinfo("PyRun",
Neutral::initCinfo(),
pyRunFinfos,
sizeof(pyRunFinfos) / sizeof(Finfo *),
&dinfo,
doc,
sizeof(doc) / sizeof(string));
return &pyRunCinfo;
}
static const Cinfo *pyRunCinfo = PyRun::initCinfo();
PyRun::PyRun()
: mode_(0),
initstr_(""),
runstr_(""),
globals_(0),
locals_(0),
runcompiled_(0),
initcompiled_(0),
inputvar_("input_"),
outputvar_("output")
{
locals_ = PyDict_New();
if (!locals_) {
cerr << "Could not initialize locals dict" << endl;
return;
}
PyObject *value = PyFloat_FromDouble(0.0);
if (!value && PyErr_Occurred()) {
PyErr_Print();
return;
}
if (PyDict_SetItemString(locals_, inputvar_.c_str(), value)) {
PyErr_Print();
}
}
PyRun::~PyRun()
{
Py_XDECREF(globals_);
}
void PyRun::setRunString(string statement)
{
runstr_ = statement;
}
string PyRun::getRunString() const
{
return runstr_;
}
void PyRun::setInitString(string statement)
{
initstr_ = statement;
}
string PyRun::getInitString() const
{
return initstr_;
}
void PyRun::setInputVar(string name)
{
PyDict_DelItemString(locals_, inputvar_.c_str());
inputvar_ = name;
}
string PyRun::getInputVar() const
{
return inputvar_;
}
void PyRun::setOutputVar(string name)
{
PyDict_DelItemString(locals_, outputvar_.c_str());
outputvar_ = name;
}
string PyRun::getOutputVar() const
{
return outputvar_;
}
void PyRun::setMode(int flag)
{
mode_ = flag;
}
int PyRun::getMode() const
{
return mode_;
}
void PyRun::trigger(const Eref &e, double input)
{
if (!runcompiled_) {
return;
}
if (mode_ == 1) {
return;
}
PyObject *value = PyDict_GetItemString(locals_, inputvar_.c_str());
if (value) {
Py_DECREF(value);
}
value = PyFloat_FromDouble(input);
if (!value && PyErr_Occurred()) {
PyErr_Print();
}
if (PyDict_SetItemString(locals_, inputvar_.c_str(), value)) {
PyErr_Print();
}
PyEval_EvalCode(runcompiled_, globals_, locals_);
if (PyErr_Occurred()) {
PyErr_Print();
}
value = PyDict_GetItemString(locals_, outputvar_.c_str());
if (value) {
double output = PyFloat_AsDouble(value);
if (PyErr_Occurred()) {
PyErr_Print();
} else {
outputOut()->send(e, output);
}
}
}
void PyRun::run(const Eref &e, string statement)
{
PyRun_SimpleString(statement.c_str());
PyObject *value = PyDict_GetItemString(locals_, outputvar_.c_str());
if (value) {
double output = PyFloat_AsDouble(value);
if (PyErr_Occurred())
PyErr_Print();
else
outputOut()->send(e, output);
}
}
void PyRun::process(const Eref &e, ProcPtr p)
{
// Make sure the get the GIL. Ksolve/Gsolve can be multithreaded.
PyGILState_STATE gstate = PyGILState_Ensure();
// PyRun_String(runstr_.c_str(), 0, globals_, locals_);
// PyRun_SimpleString(runstr_.c_str());
if (!runcompiled_ || mode_ == 2) {
return;
}
PyEval_EvalCode(runcompiled_, globals_, locals_);
if (PyErr_Occurred()) {
PyErr_Print();
return;
}
PyObject *value = PyDict_GetItemString(locals_, outputvar_.c_str());
if (value) {
double output = PyFloat_AsDouble(value);
if (PyErr_Occurred()) {
PyErr_Print();
return;
} else
outputOut()->send(e, output);
}
PyGILState_Release(gstate);
}
/**
This is derived from:
http://effbot.org/pyfaq/how-do-i-tell-incomplete-input-from-invalid-input.htm
*/
void handleError(bool syntax)
{
PyObject *exc, *val, *trb;
char *msg;
if (syntax && PyErr_ExceptionMatches(PyExc_SyntaxError)) {
PyErr_Fetch(&exc, &val, &trb); /* clears exception! */
if (PyArg_ParseTuple(val, "sO", &msg, &trb) &&
!strcmp(msg, "unexpected EOF while parsing")) /* E_EOF */
{
Py_XDECREF(exc);
Py_XDECREF(val);
Py_XDECREF(trb);
} else /* some other syntax error */
{
PyErr_Restore(exc, val, trb);
PyErr_Print();
}
} else /* some non-syntax error */
{
PyErr_Print();
}
}
void PyRun::reinit(const Eref &e, ProcPtr p)
{
PyObject *main_module;
if (globals_ == NULL) {
main_module = PyImport_AddModule("__main__");
globals_ = PyModule_GetDict(main_module);
Py_XINCREF(globals_);
}
if (locals_ == NULL) {
locals_ = PyDict_New();
if (!locals_) {
cerr << "Could not initialize locals dict" << endl;
}
}
initcompiled_ = (PYCODEOBJECT *)Py_CompileString(
initstr_.c_str(), get_program_name().c_str(), Py_file_input);
if (!initcompiled_) {
cerr << "Error compiling initString" << endl;
handleError(true);
} else {
PyEval_EvalCode(initcompiled_, globals_, locals_);
if (PyErr_Occurred()) {
PyErr_Print();
}
}
assert(runstr_.size() > 0);
runcompiled_ = (PYCODEOBJECT *)Py_CompileString(
runstr_.c_str(), get_program_name().c_str(), Py_file_input);
if (!runcompiled_) {
cerr << "Error compiling runString" << endl;
handleError(true);
} else {
PyEval_EvalCode(runcompiled_, globals_, locals_);
if (PyErr_Occurred()) {
PyErr_Print();
}
}
}