source: sasview/sansmodels/src/sans/models/c_models/CSLDCalFunc.cpp @ 34c2649

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 34c2649 was 96d19c6, checked in by Jae Cho <jhjcho@…>, 14 years ago

added models and unit tests

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