source: sasview/sansmodels/src/sans/models/c_models/CSphereModel.cpp @ 812b901

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

write run function for vector also

  • Property mode set to 100644
File size: 16.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/** CSphereModel
16 *
17 * C extension
18 *
19 * WARNING: THIS FILE WAS GENERATED BY WRAPPERGENERATOR.PY
20 *          DO NOT MODIFY THIS FILE, MODIFY sphere.h
21 *          AND RE-RUN THE GENERATOR SCRIPT
22 *
23 */
24 
25#define NO_IMPORT_ARRAY
26#define PY_ARRAY_UNIQUE_SYMBOL PyArray_API_sans
27
28extern "C" {
29#include <Python.h>
30#include <arrayobject.h>
31#include "structmember.h"
32#include <stdio.h>
33#include <stdlib.h>
34#include <math.h>
35#include <time.h>
36#include "sphere.h"
37}
38
39#include "models.hh"
40#include "dispersion_visitor.hh"
41
42/// Error object for raised exceptions
43static PyObject * CSphereModelError = NULL;
44
45
46// Class definition
47typedef struct {
48    PyObject_HEAD
49    /// Parameters
50    PyObject * params;
51    /// Dispersion parameters
52    PyObject * dispersion;
53    /// Underlying model object
54    SphereModel * model;
55    /// Log for unit testing
56    PyObject * log;
57} CSphereModel;
58
59
60static void
61CSphereModel_dealloc(CSphereModel* self)
62{
63    self->ob_type->tp_free((PyObject*)self);
64   
65
66}
67
68static PyObject *
69CSphereModel_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
70{
71    CSphereModel *self;
72   
73    self = (CSphereModel *)type->tp_alloc(type, 0);
74   
75    return (PyObject *)self;
76}
77
78static int
79CSphereModel_init(CSphereModel *self, PyObject *args, PyObject *kwds)
80{
81    if (self != NULL) {
82       
83        // Create parameters
84        self->params = PyDict_New();
85        self->dispersion = PyDict_New();
86        self->model = new SphereModel();
87       
88        // Initialize parameter dictionary
89        PyDict_SetItemString(self->params,"scale",Py_BuildValue("d",1.000000));
90        PyDict_SetItemString(self->params,"radius",Py_BuildValue("d",60.000000));
91        PyDict_SetItemString(self->params,"background",Py_BuildValue("d",0.000000));
92        PyDict_SetItemString(self->params,"contrast",Py_BuildValue("d",0.000001));
93        // Initialize dispersion / averaging parameter dict
94        DispersionVisitor* visitor = new DispersionVisitor();
95        PyObject * disp_dict;
96        disp_dict = PyDict_New();
97        self->model->radius.dispersion->accept_as_source(visitor, self->model->radius.dispersion, disp_dict);
98        PyDict_SetItemString(self->dispersion, "radius", disp_dict);
99
100
101         
102        // Create empty log
103        self->log = PyDict_New();
104       
105       
106
107    }
108    return 0;
109}
110
111static PyMemberDef CSphereModel_members[] = {
112    {"params", T_OBJECT, offsetof(CSphereModel, params), 0,
113     "Parameters"},
114        {"dispersion", T_OBJECT, offsetof(CSphereModel, dispersion), 0,
115          "Dispersion parameters"},     
116    {"log", T_OBJECT, offsetof(CSphereModel, log), 0,
117     "Log"},
118    {NULL}  /* Sentinel */
119};
120
121/** Read double from PyObject
122    @param p PyObject
123    @return double
124*/
125double CSphereModel_readDouble(PyObject *p) {
126    if (PyFloat_Check(p)==1) {
127        return (double)(((PyFloatObject *)(p))->ob_fval);
128    } else if (PyInt_Check(p)==1) {
129        return (double)(((PyIntObject *)(p))->ob_ival);
130    } else if (PyLong_Check(p)==1) {
131        return (double)PyLong_AsLong(p);
132    } else {
133        return 0.0;
134    }
135}
136/**
137 * Function to call to evaluate model
138 * @param args: input numpy array q[]
139 * @return: numpy array object
140 */
141 
142static PyObject *evaluateOneDim(SphereModel* model, PyArrayObject *q){
143    PyArrayObject *result;
144   
145    // Check validity of array q , q must be of dimension 1, an array of double
146    if (q->nd != 1 || q->descr->type_num != PyArray_DOUBLE)
147    {
148        //const char * message= "Invalid array: q->nd=%d,type_num=%d\n",q->nd,q->descr->type_num;
149        //PyErr_SetString(PyExc_ValueError , message);
150        return NULL;
151    }
152    result = (PyArrayObject *)PyArray_FromDims(q->nd, (int *)(q->dimensions), 
153                                                                                  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         for (int i = 0; i < q->dimensions[0]; i++){
160      double q_value  = *(double *)(q->data + i*q->strides[0]);
161      double *result_value = (double *)(result->data + i*result->strides[0]);
162      *result_value =(*model)(q_value);
163        }
164    return PyArray_Return(result); 
165 }
166/**
167 * Function to call to evaluate model
168 * @param args: input numpy array  [q[],phi[]]
169 * @return: numpy array object
170 */
171 static PyObject * evaluateTwoDim( SphereModel* model, 
172                              PyArrayObject *q, PyArrayObject *phi)
173 {
174    PyArrayObject *result;
175    //check validity of input vectors
176    if (q->nd != 1 || q->descr->type_num != PyArray_DOUBLE
177        || phi->nd != 1 || phi->descr->type_num != PyArray_DOUBLE
178        || phi->dimensions[0] != q->dimensions[0]){
179       
180        //const char * message= "Invalid array: q->nd=%d,type_num=%d\n",q->nd,q->descr->type_num;
181        //PyErr_SetString(PyExc_ValueError , message);
182        return NULL;
183    }
184        result= (PyArrayObject *)PyArray_FromDims(q->nd,(int*)(q->dimensions), PyArray_DOUBLE);
185
186        if (result == NULL){
187            const char * message= "Could not create result ";
188        PyErr_SetString(PyExc_RuntimeError , message);
189            return NULL;
190        }
191       
192    for (int i = 0; i < q->dimensions[0]; i++) {
193      double q_value = *(double *)(q->data + i*q->strides[0]);
194      double phi_value = *(double *)(phi->data + i*phi->strides[0]);
195      double *result_value = (double *)(result->data + i*result->strides[0]);
196      if (q_value == 0)
197          *result_value = 0.0;
198      else
199          *result_value = model->evaluate_rphi(q_value, phi_value);
200    }
201    return PyArray_Return(result); 
202 }
203 
204 /**
205 * Function to call to evaluate model
206 * @param args: input numpy array  [x[],y[]]
207 * @return: numpy array object
208 */
209 static PyObject * evaluateTwoDimXY( SphereModel* model, 
210                              PyArrayObject *x, PyArrayObject *y)
211 {
212    PyArrayObject *result;
213    //check validity of input vectors
214    if (x->nd != 1 || x->descr->type_num != PyArray_DOUBLE
215        || y->nd != 1 || y->descr->type_num != PyArray_DOUBLE
216        || y->dimensions[0] != x->dimensions[0]){
217       
218        //const char * message= "Invalid array: x->nd=%d,type_num=%d\n",x->nd,x->descr->type_num;
219        //PyErr_SetString(PyExc_ValueError , message);
220        return NULL;
221    }
222        result= (PyArrayObject *)PyArray_FromDims(x->nd,(int*)(x->dimensions), PyArray_DOUBLE);
223
224        if (result == NULL){
225            const char * message= "Could not create result ";
226        PyErr_SetString(PyExc_RuntimeError , message);
227            return NULL;
228        }
229       
230    for (int i = 0; i < x->dimensions[0]; i++) {
231      double x_value = *(double *)(x->data + i*x->strides[0]);
232      double y_value = *(double *)(y->data + i*y->strides[0]);
233      double *result_value = (double *)(result->data + i*result->strides[0]);
234      if (x_value == 0)
235          *result_value = 0.0;
236      else
237          *result_value = (*model)(x_value, y_value);
238    }
239    return PyArray_Return(result); 
240 }
241 
242/**
243 * Function to call to evaluate model
244 * @param args: input q or [q,phi]
245 * @return: function value
246 */
247static PyObject * run(CSphereModel *self, PyObject *args) {
248        double q_value, phi_value;
249        PyObject* pars;
250        int npars;
251       
252        // Get parameters
253       
254            // Reader parameter dictionary
255    self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") );
256    self->model->radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "radius") );
257    self->model->background = PyFloat_AsDouble( PyDict_GetItemString(self->params, "background") );
258    self->model->contrast = PyFloat_AsDouble( PyDict_GetItemString(self->params, "contrast") );
259    // Read in dispersion parameters
260    PyObject* disp_dict;
261    DispersionVisitor* visitor = new DispersionVisitor();
262    disp_dict = PyDict_GetItemString(self->dispersion, "radius");
263    self->model->radius.dispersion->accept_as_destination(visitor, self->model->radius.dispersion, disp_dict);
264
265       
266        // Get input and determine whether we have to supply a 1D or 2D return value.
267        if ( !PyArg_ParseTuple(args,"O",&pars) ) {
268            PyErr_SetString(CSphereModelError, 
269                "CSphereModel.run expects a q value.");
270                return NULL;
271        }
272         
273        // Check params
274        if( PyList_Check(pars)==1) {
275               
276                // Length of list should be 2 for I(q,phi)
277            npars = PyList_GET_SIZE(pars); 
278            if(npars!=2) {
279                PyErr_SetString(CSphereModelError, 
280                        "CSphereModel.run expects a double or a list of dimension 2.");
281                return NULL;
282            }
283           
284            // We have a vector q, get the q and phi values at which
285            // to evaluate I(q,phi)
286            PyObject *q, *phi;
287            q = PyList_GET_ITEM(pars,0);
288            phi = PyList_GET_ITEM(pars,1);
289           
290            if (PyArray_Check(q) && PyArray_Check(phi)) {
291                  return evaluateTwoDim(self->model, (PyArrayObject*)q, (PyArrayObject*)phi); 
292            } else if (PyArray_Check(q) || PyArray_Check(phi)) {
293                return NULL;
294            } else {
295                q_value = CSphereModel_readDouble(PyList_GET_ITEM(pars,0));
296                phi_value = CSphereModel_readDouble(PyList_GET_ITEM(pars,1));
297                // Skip zero
298                if (q_value==0) {
299                    return Py_BuildValue("d",0.0);
300                }
301                    return Py_BuildValue("d",(*(self->model)).evaluate_rphi(q_value,phi_value));
302        }
303        } else {
304        if (PyArray_Check(pars)) {
305                return evaluateOneDim(self->model, (PyArrayObject*)pars); 
306    } else {
307            // We have a scalar q, we will evaluate I(q)
308                q_value = CSphereModel_readDouble(pars);               
309            return Py_BuildValue("d",(*(self->model))(q_value));
310            }   
311        }
312}
313
314/**
315 * Function to call to evaluate model in cartesian coordinates
316 * @param args: input q or [qx, qy]]
317 * @return: function value
318 */
319static PyObject * runXY(CSphereModel *self, PyObject *args) {
320        double qx_value, qy_value;
321        PyObject* pars;
322        int npars;
323       
324        // Get parameters
325       
326            // Reader parameter dictionary
327    self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") );
328    self->model->radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "radius") );
329    self->model->background = PyFloat_AsDouble( PyDict_GetItemString(self->params, "background") );
330    self->model->contrast = PyFloat_AsDouble( PyDict_GetItemString(self->params, "contrast") );
331    // Read in dispersion parameters
332    PyObject* disp_dict;
333    DispersionVisitor* visitor = new DispersionVisitor();
334    disp_dict = PyDict_GetItemString(self->dispersion, "radius");
335    self->model->radius.dispersion->accept_as_destination(visitor, self->model->radius.dispersion, disp_dict);
336
337       
338        // Get input and determine whether we have to supply a 1D or 2D return value.
339        if ( !PyArg_ParseTuple(args,"O",&pars) ) {
340            PyErr_SetString(CSphereModelError, 
341                "CSphereModel.run expects a q value.");
342                return NULL;
343        }
344         
345        // Check params
346        if( PyList_Check(pars)==1) {
347               
348                // Length of list should be 2 for I(qx, qy))
349            npars = PyList_GET_SIZE(pars); 
350            if(npars!=2) {
351                PyErr_SetString(CSphereModelError, 
352                        "CSphereModel.run expects a double or a list of dimension 2.");
353                return NULL;
354            }
355            // We have a vector q, get the qx and qy values at which
356            // to evaluate I(qx,qy)
357            PyObject *x, *y;
358            x = PyList_GET_ITEM(pars,0);
359            y = PyList_GET_ITEM(pars,1);
360           
361            if (PyArray_Check(x) && PyArray_Check(y)) {
362                  return evaluateTwoDimXY(self->model, (PyArrayObject*)x, (PyArrayObject*)y); 
363            } else if (PyArray_Check(x) || PyArray_Check(y)) {
364                return NULL;
365            } else {   
366                qx_value = CSphereModel_readDouble(PyList_GET_ITEM(pars,0));
367                qy_value = CSphereModel_readDouble(PyList_GET_ITEM(pars,1));
368                return Py_BuildValue("d",(*(self->model))(qx_value,qy_value));
369            }
370
371        } else {
372                if (PyArray_Check(pars)) {
373                    return evaluateOneDim(self->model, (PyArrayObject*)pars); 
374        } else {
375                    // We have a scalar q, we will evaluate I(q)
376                    qx_value = CSphereModel_readDouble(pars);           
377               
378                    return Py_BuildValue("d",(*(self->model))(qx_value));
379                }
380        }       
381}
382
383static PyObject * reset(CSphereModel *self, PyObject *args) {
384   
385
386    return Py_BuildValue("d",0.0);
387}
388
389static PyObject * set_dispersion(CSphereModel *self, PyObject *args) {
390        PyObject * disp;
391        const char * par_name;
392
393        if ( !PyArg_ParseTuple(args,"sO", &par_name, &disp) ) {
394            PyErr_SetString(CSphereModelError,
395                "CSphereModel.set_dispersion expects a DispersionModel object.");
396                return NULL;
397        }
398        void *temp = PyCObject_AsVoidPtr(disp);
399        DispersionModel * dispersion = static_cast<DispersionModel *>(temp);
400
401
402        // Ugliness necessary to go from python to C
403            // TODO: refactor this
404    if (!strcmp(par_name, "radius")) {
405        self->model->radius.dispersion = dispersion;
406    } else {
407            PyErr_SetString(CSphereModelError,
408                "CSphereModel.set_dispersion expects a valid parameter name.");
409                return NULL;
410        }
411
412        DispersionVisitor* visitor = new DispersionVisitor();
413        PyObject * disp_dict = PyDict_New();
414        dispersion->accept_as_source(visitor, dispersion, disp_dict);
415        PyDict_SetItemString(self->dispersion, par_name, disp_dict);
416    return Py_BuildValue("i",1);
417}
418
419
420static PyMethodDef CSphereModel_methods[] = {
421    {"run",      (PyCFunction)run     , METH_VARARGS,
422      "Evaluate the model at a given Q or Q, phi"},
423    {"runXY",      (PyCFunction)runXY     , METH_VARARGS,
424      "Evaluate the model at a given Q or Qx, Qy"},
425    {"reset",    (PyCFunction)reset   , METH_VARARGS,
426      "Reset pair correlation"},
427    {"set_dispersion",      (PyCFunction)set_dispersion     , METH_VARARGS,
428      "Set the dispersion model for a given parameter"},
429   {NULL}
430};
431
432static PyTypeObject CSphereModelType = {
433    PyObject_HEAD_INIT(NULL)
434    0,                         /*ob_size*/
435    "CSphereModel",             /*tp_name*/
436    sizeof(CSphereModel),             /*tp_basicsize*/
437    0,                         /*tp_itemsize*/
438    (destructor)CSphereModel_dealloc, /*tp_dealloc*/
439    0,                         /*tp_print*/
440    0,                         /*tp_getattr*/
441    0,                         /*tp_setattr*/
442    0,                         /*tp_compare*/
443    0,                         /*tp_repr*/
444    0,                         /*tp_as_number*/
445    0,                         /*tp_as_sequence*/
446    0,                         /*tp_as_mapping*/
447    0,                         /*tp_hash */
448    0,                         /*tp_call*/
449    0,                         /*tp_str*/
450    0,                         /*tp_getattro*/
451    0,                         /*tp_setattro*/
452    0,                         /*tp_as_buffer*/
453    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
454    "CSphereModel objects",           /* tp_doc */
455    0,                         /* tp_traverse */
456    0,                         /* tp_clear */
457    0,                         /* tp_richcompare */
458    0,                         /* tp_weaklistoffset */
459    0,                         /* tp_iter */
460    0,                         /* tp_iternext */
461    CSphereModel_methods,             /* tp_methods */
462    CSphereModel_members,             /* tp_members */
463    0,                         /* tp_getset */
464    0,                         /* tp_base */
465    0,                         /* tp_dict */
466    0,                         /* tp_descr_get */
467    0,                         /* tp_descr_set */
468    0,                         /* tp_dictoffset */
469    (initproc)CSphereModel_init,      /* tp_init */
470    0,                         /* tp_alloc */
471    CSphereModel_new,                 /* tp_new */
472};
473
474
475/**
476 * Function used to add the model class to a module
477 * @param module: module to add the class to
478 */ 
479void addCSphereModel(PyObject *module) {
480        PyObject *d;
481       
482    if (PyType_Ready(&CSphereModelType) < 0)
483        return;
484
485    Py_INCREF(&CSphereModelType);
486    PyModule_AddObject(module, "CSphereModel", (PyObject *)&CSphereModelType);
487   
488    d = PyModule_GetDict(module);
489    CSphereModelError = PyErr_NewException("CSphereModel.error", NULL, NULL);
490    PyDict_SetItemString(d, "CSphereModelError", CSphereModelError);
491}
492
Note: See TracBrowser for help on using the repository browser.