source: sasview/src/sans/models/c_extension/python_wrapper/generated/CLorentzian.cpp @ 400155b

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 400155b was 400155b, checked in by gonzalezm, 9 years ago

Implementing request from ticket 261 - default number of bins in Annulus [Phi View] is now 36 and the first bin is now centered at 0 degrees

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