Skip to content
Snippets Groups Projects
Commit 1479aa58 authored by Jonathan Lambrechts's avatar Jonathan Lambrechts
Browse files

add python field

parent 1aec02c9
Branches
Tags
No related merge requests found
#ifndef _FIELD_PYTHON_H_
#define _FIELD_PYTHON_H_
#include "Field.h"
#include "Python.h"
class FieldPython : public Field
{
PyObject *_callback;
public:
const char *getName()
{
return "Python";
}
std::string getDescription()
{
return "simple call to a python function";
}
FieldPython(PyObject *cb, PyObject *arg = NULL)
{
_callback = cb;
Py_INCREF(_callback);
}
~FieldPython()
{
Py_DECREF(_callback);
}
double operator() (double x, double y, double z, GEntity *ge=0)
{
PyObject *pyge = SWIG_NewPointerObj((void*) ge, SWIGTYPE_p_GEntity, 0);
PyObject *args = Py_BuildValue("(dddO)", x, y, z, pyge);
PyObject *result = PyEval_CallObject(_callback, args);
Py_DECREF(args);
if (result) {
double r = PyFloat_AsDouble(result);
if (PyErr_Occurred()) {
PyErr_Print();
PyErr_Clear();
Msg::Error("Result of python function of field %i cannot be interpreted as a float.", id);
r = MAX_LC;
}
Py_DECREF(result);
return r;
}
else {
if (PyErr_Occurred()) {
PyErr_Print();
PyErr_Clear();
}
Msg::Error("An error occurs while evaluating python function of field %i.", id);
return MAX_LC;
}
}
};
#endif
......@@ -21,6 +21,7 @@
#include "meshPartition.h"
#endif
#include "Field.h"
#include "FieldPython.h"
#include "meshMetric.h"
#if defined(HAVE_ANN)
#include "CenterlineField.h"
......@@ -58,6 +59,21 @@ namespace std {
%include "meshPartition.h"
#endif
%include "Field.h"
%extend FieldManager {
int addPythonField(PyObject *callback, int id = -1) {
if (id == -1) {
id = $self->newId();
}
if($self->find(id) != $self->end()) {
Msg::Error("Field id %i is already defined", id);
return -1;
}
Field *f = new FieldPython(callback);
f->id = id;
$self->operator[](id) = f;
return id;
}
}
%include "meshMetric.h"
#if defined(HAVE_ANN)
%include "CenterlineField.h"
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment