source: sasview/sansmodels/src/sans/models/c_models/CVesicleModel.cpp @ 4d270706

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 4d270706 was 71e2de7, checked in by Gervaise Alina <gervyh@…>, 15 years ago

change destructor for models

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