source: sasview/sansmodels/src/sans/models/c_models/CSphereModel.cpp @ 2e38ebb

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

change destructor for models

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