source: sasview/sansmodels/src/python_wrapper/CGaussian.cpp @ 67424cd

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 67424cd was 67424cd, checked in by Mathieu Doucet <doucetm@…>, 12 years ago

Reorganizing models in preparation of cpp cleanup

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