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

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 2e38ebb was 71e2de7, checked in by Gervaise Alina <gervyh@…>, 15 years ago

change destructor for models

  • Property mode set to 100644
File size: 16.9 KB
RevLine 
[95986b5]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
[9bd69098]15/** CLorentzian
[95986b5]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 */
[9bd69098]24#define NO_IMPORT_ARRAY
25#define PY_ARRAY_UNIQUE_SYMBOL PyArray_API_sans
[95986b5]26 
27extern "C" {
28#include <Python.h>
[9bd69098]29#include <arrayobject.h>
[95986b5]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
[9bd69098]42static PyObject * CLorentzianError = NULL;
[95986b5]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;
[9bd69098]56} CLorentzian;
[95986b5]57
58
59static void
[9bd69098]60CLorentzian_dealloc(CLorentzian* self)
[95986b5]61{
[71e2de7]62    Py_DECREF(self->params);
63    Py_DECREF(self->dispersion);
64    Py_DECREF(self->log);
65    delete self->model;
[95986b5]66    self->ob_type->tp_free((PyObject*)self);
67   
68
69}
70
71static PyObject *
[9bd69098]72CLorentzian_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
[95986b5]73{
[9bd69098]74    CLorentzian *self;
[95986b5]75   
[9bd69098]76    self = (CLorentzian *)type->tp_alloc(type, 0);
[95986b5]77   
78    return (PyObject *)self;
79}
80
81static int
[9bd69098]82CLorentzian_init(CLorentzian *self, PyObject *args, PyObject *kwds)
[95986b5]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.000000));
93        PyDict_SetItemString(self->params,"center",Py_BuildValue("d",0.000000));
94        PyDict_SetItemString(self->params,"gamma",Py_BuildValue("d",1.000000));
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
[9bd69098]110static PyMemberDef CLorentzian_members[] = {
111    {"params", T_OBJECT, offsetof(CLorentzian, params), 0,
[95986b5]112     "Parameters"},
[9bd69098]113        {"dispersion", T_OBJECT, offsetof(CLorentzian, dispersion), 0,
[95986b5]114          "Dispersion parameters"},     
[9bd69098]115    {"log", T_OBJECT, offsetof(CLorentzian, log), 0,
[95986b5]116     "Log"},
117    {NULL}  /* Sentinel */
118};
119
120/** Read double from PyObject
121    @param p PyObject
122    @return double
123*/
[9bd69098]124double CLorentzian_readDouble(PyObject *p) {
[95986b5]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}
[9bd69098]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 }
[95986b5]165
[9bd69098]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[2];
176    //check validity of input vectors
177    if (x->nd != 2 || x->descr->type_num != PyArray_DOUBLE
178        || y->nd != 2 || y->descr->type_num != PyArray_DOUBLE
179        || y->dimensions[1] != 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)) {
[a8d6888]186               
[9ce41c6]187            x_len = dims[1]= x->dimensions[1];
188        y_len = dims[0]= y->dimensions[0];
[9bd69098]189           
190            // Make a new double matrix of same dims
191        result=(PyArrayObject *) PyArray_FromDims(2,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. */
[e0a8a3c]199        for ( j=0; j< y_len; j++) {
200            for ( i=0; i< x_len; i++) {
[9ce41c6]201                double x_value = *(double *)(x->data + i*x->strides[1]);
202                    double y_value = *(double *)(y->data + j*y->strides[0]);
[9bd69098]203                        double *result_value = (double *)(result->data +
[870f131]204                              j*result->strides[0] + i*result->strides[1]);
[9bd69098]205                        *result_value = (*model)(x_value, y_value);
206            }           
207        }
208        return PyArray_Return(result); 
209       
210        }else{
211                    PyErr_SetString(CLorentzianError, 
212                   "CLorentzian.evaluateTwoDimXY couldn't run.");
213                return NULL;
214                }       
215}
216/**
217 *  evalDistribution function evaluate a model function with input vector
218 *  @param args: input q as vector or [qx, qy] where qx, qy are vectors
219 *
220 */ 
221static PyObject * evalDistribution(CLorentzian *self, PyObject *args){
222        PyObject *qx, *qy;
223        PyArrayObject * pars;
224        int npars ,mpars;
225       
226        // Get parameters
227       
228            // Reader parameter dictionary
229    self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") );
230    self->model->center = PyFloat_AsDouble( PyDict_GetItemString(self->params, "center") );
231    self->model->gamma = PyFloat_AsDouble( PyDict_GetItemString(self->params, "gamma") );
232    // Read in dispersion parameters
233    PyObject* disp_dict;
234    DispersionVisitor* visitor = new DispersionVisitor();
235
236       
237        // Get input and determine whether we have to supply a 1D or 2D return value.
238        if ( !PyArg_ParseTuple(args,"O",&pars) ) {
239            PyErr_SetString(CLorentzianError, 
240                "CLorentzian.evalDistribution expects a q value.");
241                return NULL;
242        }
243    // Check params
244       
245    if(PyArray_Check(pars)==1) {
246               
247            // Length of list should 1 or 2
248            npars = pars->nd; 
249            if(npars==1) {
250                // input is a numpy array
251                if (PyArray_Check(pars)) {
252                        return evaluateOneDim(self->model, (PyArrayObject*)pars); 
253                    }
254                }else{
255                    PyErr_SetString(CLorentzianError, 
256                   "CLorentzian.evalDistribution expect numpy array of one dimension.");
257                return NULL;
258                }
259    }else if( PyList_Check(pars)==1) {
260        // Length of list should be 2 for I(qx,qy)
261            mpars = PyList_GET_SIZE(pars); 
262            if(mpars!=2) {
263                PyErr_SetString(CLorentzianError, 
264                        "CLorentzian.evalDistribution expects a list of dimension 2.");
265                return NULL;
266            }
267             qx = PyList_GET_ITEM(pars,0);
268             qy = PyList_GET_ITEM(pars,1);
269             if (PyArray_Check(qx) && PyArray_Check(qy)) {
270                 return evaluateTwoDimXY(self->model, (PyArrayObject*)qx,
271                           (PyArrayObject*)qy);
272                 }else{
273                    PyErr_SetString(CLorentzianError, 
274                   "CLorentzian.evalDistribution expect 2 numpy arrays in list.");
275                return NULL;
276             }
277        }
[e0a8a3c]278        PyErr_SetString(CLorentzianError, 
279                   "CLorentzian.evalDistribution couln't be run.");
280        return NULL;
281       
[9bd69098]282}
[95986b5]283
284/**
285 * Function to call to evaluate model
286 * @param args: input q or [q,phi]
287 * @return: function value
288 */
[9bd69098]289static PyObject * run(CLorentzian *self, PyObject *args) {
[95986b5]290        double q_value, phi_value;
291        PyObject* pars;
292        int npars;
293       
294        // Get parameters
295       
296            // Reader parameter dictionary
297    self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") );
298    self->model->center = PyFloat_AsDouble( PyDict_GetItemString(self->params, "center") );
299    self->model->gamma = PyFloat_AsDouble( PyDict_GetItemString(self->params, "gamma") );
300    // Read in dispersion parameters
301    PyObject* disp_dict;
302    DispersionVisitor* visitor = new DispersionVisitor();
303
304       
305        // Get input and determine whether we have to supply a 1D or 2D return value.
306        if ( !PyArg_ParseTuple(args,"O",&pars) ) {
[9bd69098]307            PyErr_SetString(CLorentzianError, 
308                "CLorentzian.run expects a q value.");
[95986b5]309                return NULL;
310        }
311         
312        // Check params
313        if( PyList_Check(pars)==1) {
314               
315                // Length of list should be 2 for I(q,phi)
316            npars = PyList_GET_SIZE(pars); 
317            if(npars!=2) {
[9bd69098]318                PyErr_SetString(CLorentzianError, 
319                        "CLorentzian.run expects a double or a list of dimension 2.");
[95986b5]320                return NULL;
321            }
322            // We have a vector q, get the q and phi values at which
323            // to evaluate I(q,phi)
[9bd69098]324            q_value = CLorentzian_readDouble(PyList_GET_ITEM(pars,0));
325            phi_value = CLorentzian_readDouble(PyList_GET_ITEM(pars,1));
[95986b5]326            // Skip zero
327            if (q_value==0) {
328                return Py_BuildValue("d",0.0);
329            }
330                return Py_BuildValue("d",(*(self->model)).evaluate_rphi(q_value,phi_value));
331
332        } else {
333
334                // We have a scalar q, we will evaluate I(q)
[9bd69098]335                q_value = CLorentzian_readDouble(pars);         
[95986b5]336               
337                return Py_BuildValue("d",(*(self->model))(q_value));
338        }       
339}
[5eb9154]340/**
341 * Function to call to calculate_ER
342 * @return: effective radius value
343 */
344static PyObject * calculate_ER(CLorentzian *self) {
[95986b5]345
[5eb9154]346        PyObject* pars;
347        int npars;
348       
349        // Get parameters
350       
351            // Reader parameter dictionary
352    self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") );
353    self->model->center = PyFloat_AsDouble( PyDict_GetItemString(self->params, "center") );
354    self->model->gamma = PyFloat_AsDouble( PyDict_GetItemString(self->params, "gamma") );
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}
[95986b5]363/**
364 * Function to call to evaluate model in cartesian coordinates
365 * @param args: input q or [qx, qy]]
366 * @return: function value
367 */
[9bd69098]368static PyObject * runXY(CLorentzian *self, PyObject *args) {
[95986b5]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->center = PyFloat_AsDouble( PyDict_GetItemString(self->params, "center") );
378    self->model->gamma = PyFloat_AsDouble( PyDict_GetItemString(self->params, "gamma") );
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) ) {
[9bd69098]386            PyErr_SetString(CLorentzianError, 
387                "CLorentzian.run expects a q value.");
[95986b5]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) {
[9bd69098]397                PyErr_SetString(CLorentzianError, 
398                        "CLorentzian.run expects a double or a list of dimension 2.");
[95986b5]399                return NULL;
400            }
401            // We have a vector q, get the qx and qy values at which
402            // to evaluate I(qx,qy)
[9bd69098]403            qx_value = CLorentzian_readDouble(PyList_GET_ITEM(pars,0));
404            qy_value = CLorentzian_readDouble(PyList_GET_ITEM(pars,1));
[95986b5]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)
[9bd69098]410                qx_value = CLorentzian_readDouble(pars);               
[95986b5]411               
412                return Py_BuildValue("d",(*(self->model))(qx_value));
413        }       
414}
415
[9bd69098]416static PyObject * reset(CLorentzian *self, PyObject *args) {
[95986b5]417   
418
419    return Py_BuildValue("d",0.0);
420}
421
[9bd69098]422static PyObject * set_dispersion(CLorentzian *self, PyObject *args) {
[95986b5]423        PyObject * disp;
424        const char * par_name;
425
426        if ( !PyArg_ParseTuple(args,"sO", &par_name, &disp) ) {
[9bd69098]427            PyErr_SetString(CLorentzianError,
428                "CLorentzian.set_dispersion expects a DispersionModel object.");
[95986b5]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 {
[9bd69098]438            PyErr_SetString(CLorentzianError,
439                "CLorentzian.set_dispersion expects a valid parameter name.");
[95986b5]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
[9bd69098]451static PyMethodDef CLorentzian_methods[] = {
[95986b5]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"},
[5eb9154]456    {"calculate_ER",      (PyCFunction)calculate_ER     , METH_VARARGS,
457      "Evaluate the model at a given Q or Q, phi"},
[9bd69098]458     
459    {"evalDistribution",  (PyCFunction)evalDistribution , METH_VARARGS,
460      "Evaluate the model at a given Q or Qx, Qy vector "},
[95986b5]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
[9bd69098]468static PyTypeObject CLorentzianType = {
[95986b5]469    PyObject_HEAD_INIT(NULL)
470    0,                         /*ob_size*/
[9bd69098]471    "CLorentzian",             /*tp_name*/
472    sizeof(CLorentzian),             /*tp_basicsize*/
[95986b5]473    0,                         /*tp_itemsize*/
[9bd69098]474    (destructor)CLorentzian_dealloc, /*tp_dealloc*/
[95986b5]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*/
[9bd69098]490    "CLorentzian objects",           /* tp_doc */
[95986b5]491    0,                         /* tp_traverse */
492    0,                         /* tp_clear */
493    0,                         /* tp_richcompare */
494    0,                         /* tp_weaklistoffset */
495    0,                         /* tp_iter */
496    0,                         /* tp_iternext */
[9bd69098]497    CLorentzian_methods,             /* tp_methods */
498    CLorentzian_members,             /* tp_members */
[95986b5]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 */
[9bd69098]505    (initproc)CLorentzian_init,      /* tp_init */
[95986b5]506    0,                         /* tp_alloc */
[9bd69098]507    CLorentzian_new,                 /* tp_new */
[95986b5]508};
509
510
[9bd69098]511//static PyMethodDef module_methods[] = {
512//    {NULL}
513//};
[95986b5]514
515/**
516 * Function used to add the model class to a module
517 * @param module: module to add the class to
518 */ 
[9bd69098]519void addCLorentzian(PyObject *module) {
[95986b5]520        PyObject *d;
521       
[9bd69098]522    if (PyType_Ready(&CLorentzianType) < 0)
[95986b5]523        return;
524
[9bd69098]525    Py_INCREF(&CLorentzianType);
526    PyModule_AddObject(module, "CLorentzian", (PyObject *)&CLorentzianType);
[95986b5]527   
528    d = PyModule_GetDict(module);
[9bd69098]529    CLorentzianError = PyErr_NewException("CLorentzian.error", NULL, NULL);
530    PyDict_SetItemString(d, "CLorentzianError", CLorentzianError);
[95986b5]531}
532
Note: See TracBrowser for help on using the repository browser.