source: sasview/sansmodels/src/python_wrapper/classTemplate.txt @ c637521

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2release_4.0.1ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since c637521 was e63a411, checked in by Mathieu Doucet <doucetm@…>, 13 years ago

updated class template

  • Property mode set to 100644
File size: 15.1 KB
RevLine 
[af03ddd]1/**
2        This software was developed by the University of Tennessee as part of the
3        Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
4        project funded by the US National Science Foundation.
5
6        If you use DANSE applications to do scientific research that leads to
7        publication, we ask that you acknowledge the use of the software with the
8        following sentence:
9
10        "This work benefited from DANSE software developed under NSF award DMR-0520547."
11
12        copyright 2008, University of Tennessee
13 */
14
15/** [PYTHONCLASS]
16 *
17 * C extension
18 *
19 * WARNING: THIS FILE WAS GENERATED BY WRAPPERGENERATOR.PY
20 *          DO NOT MODIFY THIS FILE, MODIFY [INCLUDE_FILE]
21 *          AND RE-RUN THE GENERATOR SCRIPT
22 *
23 */
[8344c50]24#define NO_IMPORT_ARRAY
25#define PY_ARRAY_UNIQUE_SYMBOL PyArray_API_sans
[af03ddd]26 
27extern "C" {
28#include <Python.h>
[8344c50]29#include <arrayobject.h>
[af03ddd]30#include "structmember.h"
31#include <stdio.h>
32#include <stdlib.h>
33#include <math.h>
34#include <time.h>
[e63a411]35[C_INCLUDE_FILE]
[af03ddd]36}
37
[e63a411]38[CPP_INCLUDE_FILE]
[af03ddd]39#include "dispersion_visitor.hh"
40
41/// Error object for raised exceptions
42static PyObject * [PYTHONCLASS]Error = NULL;
43
44
45// Class definition
46typedef struct {
47    PyObject_HEAD
48    /// Parameters
49    PyObject * params;
50    /// Dispersion parameters
51    PyObject * dispersion;
52    /// Underlying model object
53    [CMODEL] * model;
54    /// Log for unit testing
55    PyObject * log;
56} [PYTHONCLASS];
57
58
59static void
60[PYTHONCLASS]_dealloc([PYTHONCLASS]* self)
61{
[71e2de7]62    Py_DECREF(self->params);
63    Py_DECREF(self->dispersion);
64    Py_DECREF(self->log);
65    delete self->model;
[af03ddd]66    self->ob_type->tp_free((PyObject*)self);
67    [NUMERICAL_DEALLOC]
68}
69
70static PyObject *
71[PYTHONCLASS]_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
72{
73    [PYTHONCLASS] *self;
74   
75    self = ([PYTHONCLASS] *)type->tp_alloc(type, 0);
76   
77    return (PyObject *)self;
78}
79
80static int
81[PYTHONCLASS]_init([PYTHONCLASS] *self, PyObject *args, PyObject *kwds)
82{
83    if (self != NULL) {
84       
85        // Create parameters
86        self->params = PyDict_New();
87        self->dispersion = PyDict_New();
88        self->model = new [CMODEL]();
89       
90        [INITDICTIONARY]
91         
92        // Create empty log
93        self->log = PyDict_New();
94       
95        [NUMERICAL_INIT]
96    }
97    return 0;
98}
99
[b1c3295]100static char name_params[] = "params";
101static char def_params[] = "Parameters";
102static char name_dispersion[] = "dispersion";
103static char def_dispersion[] = "Dispersion parameters";
104static char name_log[] = "log";
105static char def_log[] = "Log";
106
[af03ddd]107static PyMemberDef [PYTHONCLASS]_members[] = {
[b1c3295]108    {name_params, T_OBJECT, offsetof([PYTHONCLASS], params), 0, def_params},
109        {name_dispersion, T_OBJECT, offsetof([PYTHONCLASS], dispersion), 0, def_dispersion},     
110    {name_log, T_OBJECT, offsetof([PYTHONCLASS], log), 0, def_log},
[af03ddd]111    {NULL}  /* Sentinel */
112};
113
114/** Read double from PyObject
115    @param p PyObject
116    @return double
117*/
118double [PYTHONCLASS]_readDouble(PyObject *p) {
119    if (PyFloat_Check(p)==1) {
120        return (double)(((PyFloatObject *)(p))->ob_fval);
121    } else if (PyInt_Check(p)==1) {
122        return (double)(((PyIntObject *)(p))->ob_ival);
123    } else if (PyLong_Check(p)==1) {
124        return (double)PyLong_AsLong(p);
125    } else {
126        return 0.0;
127    }
128}
[8344c50]129/**
130 * Function to call to evaluate model
131 * @param args: input numpy array q[]
132 * @return: numpy array object
133 */
134 
135static PyObject *evaluateOneDim([CMODEL]* model, PyArrayObject *q){
136    PyArrayObject *result;
137   
138    // Check validity of array q , q must be of dimension 1, an array of double
139    if (q->nd != 1 || q->descr->type_num != PyArray_DOUBLE)
140    {
141        //const char * message= "Invalid array: q->nd=%d,type_num=%d\n",q->nd,q->descr->type_num;
142        //PyErr_SetString(PyExc_ValueError , message);
143        return NULL;
144    }
[8f5b34a]145    result = (PyArrayObject *)PyArray_FromDims(q->nd, (int *)(q->dimensions), PyArray_DOUBLE);
[8344c50]146        if (result == NULL) {
147        const char * message= "Could not create result ";
148        PyErr_SetString(PyExc_RuntimeError , message);
149                return NULL;
150        }
[0b082f3]151#pragma omp parallel for
[8344c50]152         for (int i = 0; i < q->dimensions[0]; i++){
153      double q_value  = *(double *)(q->data + i*q->strides[0]);
154      double *result_value = (double *)(result->data + i*result->strides[0]);
155      *result_value =(*model)(q_value);
156        }
157    return PyArray_Return(result);
158 }
[af03ddd]159
[8344c50]160 /**
161 * Function to call to evaluate model
162 * @param args: input numpy array  [x[],y[]]
163 * @return: numpy array object
164 */
165 static PyObject * evaluateTwoDimXY( [CMODEL]* model,
166                              PyArrayObject *x, PyArrayObject *y)
167 {
168    PyArrayObject *result;
[0b082f3]169    int x_len, y_len, dims[1];
[8344c50]170    //check validity of input vectors
[3080527]171    if (x->nd != 1 || x->descr->type_num != PyArray_DOUBLE
172        || y->nd != 1 || y->descr->type_num != PyArray_DOUBLE
173        || y->dimensions[0] != x->dimensions[0]){
[8344c50]174        const char * message= "evaluateTwoDimXY  expect 2 numpy arrays";
175        PyErr_SetString(PyExc_ValueError , message);
176        return NULL;
177    }
178   
179        if (PyArray_Check(x) && PyArray_Check(y)) {
[a8d6888]180               
[3080527]181            x_len = dims[0]= x->dimensions[0];
[9ce41c6]182        y_len = dims[0]= y->dimensions[0];
[8344c50]183           
184            // Make a new double matrix of same dims
[8f5b34a]185        result=(PyArrayObject *) PyArray_FromDims(1,dims,NPY_DOUBLE);
[8344c50]186        if (result == NULL){
187            const char * message= "Could not create result ";
188        PyErr_SetString(PyExc_RuntimeError , message);
189            return NULL;
190            }
191       
192        /* Do the calculation. */
[0b082f3]193#pragma omp parallel for
194        for (int i=0; i< x_len; i++) {
[3080527]195            double x_value = *(double *)(x->data + i*x->strides[0]);
196                    double y_value = *(double *)(y->data + i*y->strides[0]);
197                        double *result_value = (double *)(result->data +
198                              i*result->strides[0]);
199                        *result_value = (*model)(x_value, y_value);
200        }           
[8344c50]201        return PyArray_Return(result);
202       
203        }else{
204                    PyErr_SetString([PYTHONCLASS]Error,
205                   "[PYTHONCLASS].evaluateTwoDimXY couldn't run.");
206                return NULL;
207                }       
208}
209/**
210 *  evalDistribution function evaluate a model function with input vector
211 *  @param args: input q as vector or [qx, qy] where qx, qy are vectors
212 *
213 */
214static PyObject * evalDistribution([PYTHONCLASS] *self, PyObject *args){
215        PyObject *qx, *qy;
216        PyArrayObject * pars;
217        int npars ,mpars;
218       
219        // Get parameters
220       
221        [READDICTIONARY]
222       
223        // Get input and determine whether we have to supply a 1D or 2D return value.
224        if ( !PyArg_ParseTuple(args,"O",&pars) ) {
225            PyErr_SetString([PYTHONCLASS]Error,
226                "[PYTHONCLASS].evalDistribution expects a q value.");
227                return NULL;
228        }
229    // Check params
230       
231    if(PyArray_Check(pars)==1) {
232               
233            // Length of list should 1 or 2
234            npars = pars->nd;
235            if(npars==1) {
236                // input is a numpy array
237                if (PyArray_Check(pars)) {
238                        return evaluateOneDim(self->model, (PyArrayObject*)pars);
239                    }
240                }else{
241                    PyErr_SetString([PYTHONCLASS]Error,
242                   "[PYTHONCLASS].evalDistribution expect numpy array of one dimension.");
243                return NULL;
244                }
245    }else if( PyList_Check(pars)==1) {
246        // Length of list should be 2 for I(qx,qy)
247            mpars = PyList_GET_SIZE(pars);
248            if(mpars!=2) {
249                PyErr_SetString([PYTHONCLASS]Error,
250                        "[PYTHONCLASS].evalDistribution expects a list of dimension 2.");
251                return NULL;
252            }
253             qx = PyList_GET_ITEM(pars,0);
254             qy = PyList_GET_ITEM(pars,1);
255             if (PyArray_Check(qx) && PyArray_Check(qy)) {
256                 return evaluateTwoDimXY(self->model, (PyArrayObject*)qx,
257                           (PyArrayObject*)qy);
258                 }else{
259                    PyErr_SetString([PYTHONCLASS]Error,
260                   "[PYTHONCLASS].evalDistribution expect 2 numpy arrays in list.");
261                return NULL;
262             }
263        }
[e0a8a3c]264        PyErr_SetString([PYTHONCLASS]Error,
265                   "[PYTHONCLASS].evalDistribution couln't be run.");
266        return NULL;
267       
[8344c50]268}
[af03ddd]269
270/**
271 * Function to call to evaluate model
272 * @param args: input q or [q,phi]
273 * @return: function value
274 */
275static PyObject * run([PYTHONCLASS] *self, PyObject *args) {
276        double q_value, phi_value;
277        PyObject* pars;
278        int npars;
279       
280        // Get parameters
281       
282        [READDICTIONARY]
283       
284        // Get input and determine whether we have to supply a 1D or 2D return value.
285        if ( !PyArg_ParseTuple(args,"O",&pars) ) {
286            PyErr_SetString([PYTHONCLASS]Error,
287                "[PYTHONCLASS].run expects a q value.");
288                return NULL;
289        }
290         
291        // Check params
292        if( PyList_Check(pars)==1) {
293               
294                // Length of list should be 2 for I(q,phi)
295            npars = PyList_GET_SIZE(pars);
296            if(npars!=2) {
297                PyErr_SetString([PYTHONCLASS]Error,
298                        "[PYTHONCLASS].run expects a double or a list of dimension 2.");
299                return NULL;
300            }
301            // We have a vector q, get the q and phi values at which
302            // to evaluate I(q,phi)
[4176435]303            q_value = [PYTHONCLASS]_readDouble(PyList_GET_ITEM(pars,0));
304            phi_value = [PYTHONCLASS]_readDouble(PyList_GET_ITEM(pars,1));
305            // Skip zero
306            if (q_value==0) {
307                return Py_BuildValue("d",0.0);
308            }
309                return Py_BuildValue("d",(*(self->model)).evaluate_rphi(q_value,phi_value));
310
[af03ddd]311        } else {
[4176435]312
313                // We have a scalar q, we will evaluate I(q)
[af03ddd]314                q_value = [PYTHONCLASS]_readDouble(pars);               
[4176435]315               
316                return Py_BuildValue("d",(*(self->model))(q_value));
317        }       
[af03ddd]318}
[5eb9154]319/**
320 * Function to call to calculate_ER
321 * @return: effective radius value
322 */
323static PyObject * calculate_ER([PYTHONCLASS] *self) {
324
325        // Get parameters
326       
327        [READDICTIONARY]
328               
329        return Py_BuildValue("d",(*(self->model)).calculate_ER());
[af03ddd]330
[5eb9154]331}
[af03ddd]332/**
333 * Function to call to evaluate model in cartesian coordinates
334 * @param args: input q or [qx, qy]]
335 * @return: function value
336 */
337static PyObject * runXY([PYTHONCLASS] *self, PyObject *args) {
338        double qx_value, qy_value;
339        PyObject* pars;
340        int npars;
341       
342        // Get parameters
343       
344        [READDICTIONARY]
345       
346        // Get input and determine whether we have to supply a 1D or 2D return value.
347        if ( !PyArg_ParseTuple(args,"O",&pars) ) {
348            PyErr_SetString([PYTHONCLASS]Error,
349                "[PYTHONCLASS].run expects a q value.");
350                return NULL;
351        }
352         
353        // Check params
354        if( PyList_Check(pars)==1) {
355               
356                // Length of list should be 2 for I(qx, qy))
357            npars = PyList_GET_SIZE(pars);
358            if(npars!=2) {
359                PyErr_SetString([PYTHONCLASS]Error,
360                        "[PYTHONCLASS].run expects a double or a list of dimension 2.");
361                return NULL;
362            }
363            // We have a vector q, get the qx and qy values at which
364            // to evaluate I(qx,qy)
[4176435]365            qx_value = [PYTHONCLASS]_readDouble(PyList_GET_ITEM(pars,0));
366            qy_value = [PYTHONCLASS]_readDouble(PyList_GET_ITEM(pars,1));
367            return Py_BuildValue("d",(*(self->model))(qx_value,qy_value));
[af03ddd]368
369        } else {
[4176435]370
371                // We have a scalar q, we will evaluate I(q)
372                qx_value = [PYTHONCLASS]_readDouble(pars);             
[af03ddd]373               
[4176435]374                return Py_BuildValue("d",(*(self->model))(qx_value));
[af03ddd]375        }       
376}
377
378static PyObject * reset([PYTHONCLASS] *self, PyObject *args) {
379    [NUMERICAL_RESET]
380    return Py_BuildValue("d",0.0);
381}
382
383static PyObject * set_dispersion([PYTHONCLASS] *self, PyObject *args) {
384        PyObject * disp;
385        const char * par_name;
386
387        if ( !PyArg_ParseTuple(args,"sO", &par_name, &disp) ) {
388            PyErr_SetString([PYTHONCLASS]Error,
389                "[PYTHONCLASS].set_dispersion expects a DispersionModel object.");
390                return NULL;
391        }
392        void *temp = PyCObject_AsVoidPtr(disp);
393        DispersionModel * dispersion = static_cast<DispersionModel *>(temp);
394
395
396        // Ugliness necessary to go from python to C
397        [SET_DISPERSION] {
398            PyErr_SetString([PYTHONCLASS]Error,
399                "[PYTHONCLASS].set_dispersion expects a valid parameter name.");
400                return NULL;
401        }
402
403        DispersionVisitor* visitor = new DispersionVisitor();
404        PyObject * disp_dict = PyDict_New();
405        dispersion->accept_as_source(visitor, dispersion, disp_dict);
406        PyDict_SetItemString(self->dispersion, par_name, disp_dict);
407    return Py_BuildValue("i",1);
408}
409
410
411static PyMethodDef [PYTHONCLASS]_methods[] = {
412    {"run",      (PyCFunction)run     , METH_VARARGS,
413      "Evaluate the model at a given Q or Q, phi"},
414    {"runXY",      (PyCFunction)runXY     , METH_VARARGS,
415      "Evaluate the model at a given Q or Qx, Qy"},
[5eb9154]416    {"calculate_ER",      (PyCFunction)calculate_ER     , METH_VARARGS,
417      "Evaluate the model at a given Q or Q, phi"},
[8344c50]418     
419    {"evalDistribution",  (PyCFunction)evalDistribution , METH_VARARGS,
420      "Evaluate the model at a given Q or Qx, Qy vector "},
[af03ddd]421    {"reset",    (PyCFunction)reset   , METH_VARARGS,
422      "Reset pair correlation"},
423    {"set_dispersion",      (PyCFunction)set_dispersion     , METH_VARARGS,
424      "Set the dispersion model for a given parameter"},
425   {NULL}
426};
427
428static PyTypeObject [PYTHONCLASS]Type = {
429    PyObject_HEAD_INIT(NULL)
430    0,                         /*ob_size*/
431    "[PYTHONCLASS]",             /*tp_name*/
432    sizeof([PYTHONCLASS]),             /*tp_basicsize*/
433    0,                         /*tp_itemsize*/
434    (destructor)[PYTHONCLASS]_dealloc, /*tp_dealloc*/
435    0,                         /*tp_print*/
436    0,                         /*tp_getattr*/
437    0,                         /*tp_setattr*/
438    0,                         /*tp_compare*/
439    0,                         /*tp_repr*/
440    0,                         /*tp_as_number*/
441    0,                         /*tp_as_sequence*/
442    0,                         /*tp_as_mapping*/
443    0,                         /*tp_hash */
444    0,                         /*tp_call*/
445    0,                         /*tp_str*/
446    0,                         /*tp_getattro*/
447    0,                         /*tp_setattro*/
448    0,                         /*tp_as_buffer*/
449    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
450    "[PYTHONCLASS] objects",           /* tp_doc */
451    0,                         /* tp_traverse */
452    0,                         /* tp_clear */
453    0,                         /* tp_richcompare */
454    0,                         /* tp_weaklistoffset */
455    0,                         /* tp_iter */
456    0,                         /* tp_iternext */
457    [PYTHONCLASS]_methods,             /* tp_methods */
458    [PYTHONCLASS]_members,             /* tp_members */
459    0,                         /* tp_getset */
460    0,                         /* tp_base */
461    0,                         /* tp_dict */
462    0,                         /* tp_descr_get */
463    0,                         /* tp_descr_set */
464    0,                         /* tp_dictoffset */
465    (initproc)[PYTHONCLASS]_init,      /* tp_init */
466    0,                         /* tp_alloc */
467    [PYTHONCLASS]_new,                 /* tp_new */
468};
469
470
[8344c50]471//static PyMethodDef module_methods[] = {
472//    {NULL}
473//};
[4176435]474
[af03ddd]475/**
476 * Function used to add the model class to a module
477 * @param module: module to add the class to
478 */
479void add[PYTHONCLASS](PyObject *module) {
480        PyObject *d;
481       
482    if (PyType_Ready(&[PYTHONCLASS]Type) < 0)
483        return;
484
485    Py_INCREF(&[PYTHONCLASS]Type);
486    PyModule_AddObject(module, "[PYTHONCLASS]", (PyObject *)&[PYTHONCLASS]Type);
487   
488    d = PyModule_GetDict(module);
[2605da22]489    static char error_name[] = "[PYTHONCLASS].error";
490    [PYTHONCLASS]Error = PyErr_NewException(error_name, NULL, NULL);
[af03ddd]491    PyDict_SetItemString(d, "[PYTHONCLASS]Error", [PYTHONCLASS]Error);
492}
Note: See TracBrowser for help on using the repository browser.