source: sasview/sansmodels/src/sans/models/c_models/CVesicleModel.cpp @ 870f131

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

change model orientation

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