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

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

change the orientation of models

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