source: sasview/sansmodels/src/sans/models/c_models/CGaussian.cpp @ 1d67243

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 1d67243 was 9bd69098, checked in by Jae Cho <jhjcho@…>, 15 years ago

recompiled all due to Alina's new eval(run) function

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