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

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 3eac3816 was c7a7e1b, checked in by Gervaise Alina <gervyh@…>, 13 years ago

working on model pickle

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