source: sasview/sansmodels/src/python_wrapper/CSLDCalFunc.cpp @ 67424cd

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

Reorganizing models in preparation of cpp cleanup

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