source: sasview/sansmodels/src/sans/models/c_models/CLorentzian.cpp @ b1c3295

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

Re #4 This should clean up a whole bunch of C++ warnings.

  • Property mode set to 100644
File size: 17.0 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/** CLorentzian
16 *
17 * C extension
18 *
19 * WARNING: THIS FILE WAS GENERATED BY WRAPPERGENERATOR.PY
20 *          DO NOT MODIFY THIS FILE, MODIFY lorentzian.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 "lorentzian.h"
36}
37
38#include "models.hh"
39#include "dispersion_visitor.hh"
40
41/// Error object for raised exceptions
42static PyObject * CLorentzianError = 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    Lorentzian * model;
54    /// Log for unit testing
55    PyObject * log;
56} CLorentzian;
57
58
59static void
60CLorentzian_dealloc(CLorentzian* 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 *
72CLorentzian_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
73{
74    CLorentzian *self;
75   
76    self = (CLorentzian *)type->tp_alloc(type, 0);
77   
78    return (PyObject *)self;
79}
80
81static int
82CLorentzian_init(CLorentzian *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 Lorentzian();
90       
91        // Initialize parameter dictionary
92        PyDict_SetItemString(self->params,"scale",Py_BuildValue("d",1.000000000000));
93        PyDict_SetItemString(self->params,"center",Py_BuildValue("d",0.000000000000));
94        PyDict_SetItemString(self->params,"gamma",Py_BuildValue("d",1.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 CLorentzian_members[] = {
118    {name_params, T_OBJECT, offsetof(CLorentzian, params), 0, def_params},
119        {name_dispersion, T_OBJECT, offsetof(CLorentzian, dispersion), 0, def_dispersion},     
120    {name_log, T_OBJECT, offsetof(CLorentzian, log), 0, def_log},
121    {NULL}  /* Sentinel */
122};
123
124/** Read double from PyObject
125    @param p PyObject
126    @return double
127*/
128double CLorentzian_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(Lorentzian* 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), 
156                                                                                  PyArray_DOUBLE);
157        if (result == NULL) {
158        const char * message= "Could not create result ";
159        PyErr_SetString(PyExc_RuntimeError , message);
160                return NULL;
161        }
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( Lorentzian* model, 
176                              PyArrayObject *x, PyArrayObject *y)
177 {
178    PyArrayObject *result;
179    int i,j, 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        for ( i=0; i< x_len; i++) {
204            double x_value = *(double *)(x->data + i*x->strides[0]);
205                    double y_value = *(double *)(y->data + i*y->strides[0]);
206                        double *result_value = (double *)(result->data +
207                              i*result->strides[0]);
208                        *result_value = (*model)(x_value, y_value);
209        }           
210        return PyArray_Return(result); 
211       
212        }else{
213                    PyErr_SetString(CLorentzianError, 
214                   "CLorentzian.evaluateTwoDimXY couldn't run.");
215                return NULL;
216                }       
217}
218/**
219 *  evalDistribution function evaluate a model function with input vector
220 *  @param args: input q as vector or [qx, qy] where qx, qy are vectors
221 *
222 */ 
223static PyObject * evalDistribution(CLorentzian *self, PyObject *args){
224        PyObject *qx, *qy;
225        PyArrayObject * pars;
226        int npars ,mpars;
227       
228        // Get parameters
229       
230            // Reader parameter dictionary
231    self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") );
232    self->model->center = PyFloat_AsDouble( PyDict_GetItemString(self->params, "center") );
233    self->model->gamma = PyFloat_AsDouble( PyDict_GetItemString(self->params, "gamma") );
234    // Read in dispersion parameters
235    PyObject* disp_dict;
236    DispersionVisitor* visitor = new DispersionVisitor();
237
238       
239        // Get input and determine whether we have to supply a 1D or 2D return value.
240        if ( !PyArg_ParseTuple(args,"O",&pars) ) {
241            PyErr_SetString(CLorentzianError, 
242                "CLorentzian.evalDistribution expects a q value.");
243                return NULL;
244        }
245    // Check params
246       
247    if(PyArray_Check(pars)==1) {
248               
249            // Length of list should 1 or 2
250            npars = pars->nd; 
251            if(npars==1) {
252                // input is a numpy array
253                if (PyArray_Check(pars)) {
254                        return evaluateOneDim(self->model, (PyArrayObject*)pars); 
255                    }
256                }else{
257                    PyErr_SetString(CLorentzianError, 
258                   "CLorentzian.evalDistribution expect numpy array of one dimension.");
259                return NULL;
260                }
261    }else if( PyList_Check(pars)==1) {
262        // Length of list should be 2 for I(qx,qy)
263            mpars = PyList_GET_SIZE(pars); 
264            if(mpars!=2) {
265                PyErr_SetString(CLorentzianError, 
266                        "CLorentzian.evalDistribution expects a list of dimension 2.");
267                return NULL;
268            }
269             qx = PyList_GET_ITEM(pars,0);
270             qy = PyList_GET_ITEM(pars,1);
271             if (PyArray_Check(qx) && PyArray_Check(qy)) {
272                 return evaluateTwoDimXY(self->model, (PyArrayObject*)qx,
273                           (PyArrayObject*)qy);
274                 }else{
275                    PyErr_SetString(CLorentzianError, 
276                   "CLorentzian.evalDistribution expect 2 numpy arrays in list.");
277                return NULL;
278             }
279        }
280        PyErr_SetString(CLorentzianError, 
281                   "CLorentzian.evalDistribution couln't be run.");
282        return NULL;
283       
284}
285
286/**
287 * Function to call to evaluate model
288 * @param args: input q or [q,phi]
289 * @return: function value
290 */
291static PyObject * run(CLorentzian *self, PyObject *args) {
292        double q_value, phi_value;
293        PyObject* pars;
294        int npars;
295       
296        // Get parameters
297       
298            // Reader parameter dictionary
299    self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") );
300    self->model->center = PyFloat_AsDouble( PyDict_GetItemString(self->params, "center") );
301    self->model->gamma = PyFloat_AsDouble( PyDict_GetItemString(self->params, "gamma") );
302    // Read in dispersion parameters
303    PyObject* disp_dict;
304    DispersionVisitor* visitor = new DispersionVisitor();
305
306       
307        // Get input and determine whether we have to supply a 1D or 2D return value.
308        if ( !PyArg_ParseTuple(args,"O",&pars) ) {
309            PyErr_SetString(CLorentzianError, 
310                "CLorentzian.run expects a q value.");
311                return NULL;
312        }
313         
314        // Check params
315        if( PyList_Check(pars)==1) {
316               
317                // Length of list should be 2 for I(q,phi)
318            npars = PyList_GET_SIZE(pars); 
319            if(npars!=2) {
320                PyErr_SetString(CLorentzianError, 
321                        "CLorentzian.run expects a double or a list of dimension 2.");
322                return NULL;
323            }
324            // We have a vector q, get the q and phi values at which
325            // to evaluate I(q,phi)
326            q_value = CLorentzian_readDouble(PyList_GET_ITEM(pars,0));
327            phi_value = CLorentzian_readDouble(PyList_GET_ITEM(pars,1));
328            // Skip zero
329            if (q_value==0) {
330                return Py_BuildValue("d",0.0);
331            }
332                return Py_BuildValue("d",(*(self->model)).evaluate_rphi(q_value,phi_value));
333
334        } else {
335
336                // We have a scalar q, we will evaluate I(q)
337                q_value = CLorentzian_readDouble(pars);         
338               
339                return Py_BuildValue("d",(*(self->model))(q_value));
340        }       
341}
342/**
343 * Function to call to calculate_ER
344 * @return: effective radius value
345 */
346static PyObject * calculate_ER(CLorentzian *self) {
347
348        PyObject* pars;
349        int npars;
350       
351        // Get parameters
352       
353            // Reader parameter dictionary
354    self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") );
355    self->model->center = PyFloat_AsDouble( PyDict_GetItemString(self->params, "center") );
356    self->model->gamma = PyFloat_AsDouble( PyDict_GetItemString(self->params, "gamma") );
357    // Read in dispersion parameters
358    PyObject* disp_dict;
359    DispersionVisitor* visitor = new DispersionVisitor();
360
361               
362        return Py_BuildValue("d",(*(self->model)).calculate_ER());
363
364}
365/**
366 * Function to call to evaluate model in cartesian coordinates
367 * @param args: input q or [qx, qy]]
368 * @return: function value
369 */
370static PyObject * runXY(CLorentzian *self, PyObject *args) {
371        double qx_value, qy_value;
372        PyObject* pars;
373        int npars;
374       
375        // Get parameters
376       
377            // Reader parameter dictionary
378    self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") );
379    self->model->center = PyFloat_AsDouble( PyDict_GetItemString(self->params, "center") );
380    self->model->gamma = PyFloat_AsDouble( PyDict_GetItemString(self->params, "gamma") );
381    // Read in dispersion parameters
382    PyObject* disp_dict;
383    DispersionVisitor* visitor = new DispersionVisitor();
384
385       
386        // Get input and determine whether we have to supply a 1D or 2D return value.
387        if ( !PyArg_ParseTuple(args,"O",&pars) ) {
388            PyErr_SetString(CLorentzianError, 
389                "CLorentzian.run expects a q value.");
390                return NULL;
391        }
392         
393        // Check params
394        if( PyList_Check(pars)==1) {
395               
396                // Length of list should be 2 for I(qx, qy))
397            npars = PyList_GET_SIZE(pars); 
398            if(npars!=2) {
399                PyErr_SetString(CLorentzianError, 
400                        "CLorentzian.run expects a double or a list of dimension 2.");
401                return NULL;
402            }
403            // We have a vector q, get the qx and qy values at which
404            // to evaluate I(qx,qy)
405            qx_value = CLorentzian_readDouble(PyList_GET_ITEM(pars,0));
406            qy_value = CLorentzian_readDouble(PyList_GET_ITEM(pars,1));
407            return Py_BuildValue("d",(*(self->model))(qx_value,qy_value));
408
409        } else {
410
411                // We have a scalar q, we will evaluate I(q)
412                qx_value = CLorentzian_readDouble(pars);               
413               
414                return Py_BuildValue("d",(*(self->model))(qx_value));
415        }       
416}
417
418static PyObject * reset(CLorentzian *self, PyObject *args) {
419   
420
421    return Py_BuildValue("d",0.0);
422}
423
424static PyObject * set_dispersion(CLorentzian *self, PyObject *args) {
425        PyObject * disp;
426        const char * par_name;
427
428        if ( !PyArg_ParseTuple(args,"sO", &par_name, &disp) ) {
429            PyErr_SetString(CLorentzianError,
430                "CLorentzian.set_dispersion expects a DispersionModel object.");
431                return NULL;
432        }
433        void *temp = PyCObject_AsVoidPtr(disp);
434        DispersionModel * dispersion = static_cast<DispersionModel *>(temp);
435
436
437        // Ugliness necessary to go from python to C
438            // TODO: refactor this
439 {
440            PyErr_SetString(CLorentzianError,
441                "CLorentzian.set_dispersion expects a valid parameter name.");
442                return NULL;
443        }
444
445        DispersionVisitor* visitor = new DispersionVisitor();
446        PyObject * disp_dict = PyDict_New();
447        dispersion->accept_as_source(visitor, dispersion, disp_dict);
448        PyDict_SetItemString(self->dispersion, par_name, disp_dict);
449    return Py_BuildValue("i",1);
450}
451
452
453static PyMethodDef CLorentzian_methods[] = {
454    {"run",      (PyCFunction)run     , METH_VARARGS,
455      "Evaluate the model at a given Q or Q, phi"},
456    {"runXY",      (PyCFunction)runXY     , METH_VARARGS,
457      "Evaluate the model at a given Q or Qx, Qy"},
458    {"calculate_ER",      (PyCFunction)calculate_ER     , METH_VARARGS,
459      "Evaluate the model at a given Q or Q, phi"},
460     
461    {"evalDistribution",  (PyCFunction)evalDistribution , METH_VARARGS,
462      "Evaluate the model at a given Q or Qx, Qy vector "},
463    {"reset",    (PyCFunction)reset   , METH_VARARGS,
464      "Reset pair correlation"},
465    {"set_dispersion",      (PyCFunction)set_dispersion     , METH_VARARGS,
466      "Set the dispersion model for a given parameter"},
467   {NULL}
468};
469
470static PyTypeObject CLorentzianType = {
471    PyObject_HEAD_INIT(NULL)
472    0,                         /*ob_size*/
473    "CLorentzian",             /*tp_name*/
474    sizeof(CLorentzian),             /*tp_basicsize*/
475    0,                         /*tp_itemsize*/
476    (destructor)CLorentzian_dealloc, /*tp_dealloc*/
477    0,                         /*tp_print*/
478    0,                         /*tp_getattr*/
479    0,                         /*tp_setattr*/
480    0,                         /*tp_compare*/
481    0,                         /*tp_repr*/
482    0,                         /*tp_as_number*/
483    0,                         /*tp_as_sequence*/
484    0,                         /*tp_as_mapping*/
485    0,                         /*tp_hash */
486    0,                         /*tp_call*/
487    0,                         /*tp_str*/
488    0,                         /*tp_getattro*/
489    0,                         /*tp_setattro*/
490    0,                         /*tp_as_buffer*/
491    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
492    "CLorentzian objects",           /* tp_doc */
493    0,                         /* tp_traverse */
494    0,                         /* tp_clear */
495    0,                         /* tp_richcompare */
496    0,                         /* tp_weaklistoffset */
497    0,                         /* tp_iter */
498    0,                         /* tp_iternext */
499    CLorentzian_methods,             /* tp_methods */
500    CLorentzian_members,             /* tp_members */
501    0,                         /* tp_getset */
502    0,                         /* tp_base */
503    0,                         /* tp_dict */
504    0,                         /* tp_descr_get */
505    0,                         /* tp_descr_set */
506    0,                         /* tp_dictoffset */
507    (initproc)CLorentzian_init,      /* tp_init */
508    0,                         /* tp_alloc */
509    CLorentzian_new,                 /* tp_new */
510};
511
512
513//static PyMethodDef module_methods[] = {
514//    {NULL}
515//};
516
517/**
518 * Function used to add the model class to a module
519 * @param module: module to add the class to
520 */ 
521void addCLorentzian(PyObject *module) {
522        PyObject *d;
523       
524    if (PyType_Ready(&CLorentzianType) < 0)
525        return;
526
527    Py_INCREF(&CLorentzianType);
528    PyModule_AddObject(module, "CLorentzian", (PyObject *)&CLorentzianType);
529   
530    d = PyModule_GetDict(module);
531    CLorentzianError = PyErr_NewException("CLorentzian.error", NULL, NULL);
532    PyDict_SetItemString(d, "CLorentzianError", CLorentzianError);
533}
534
Note: See TracBrowser for help on using the repository browser.