source: sasview/sansmodels/src/sans/models/c_models/CDiamEllipFunc.cpp @ fe9c19b4

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

change destructor for models

  • Property mode set to 100644
File size: 18.8 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/** CDiamEllipFunc
16 *
17 * C extension
18 *
19 * WARNING: THIS FILE WAS GENERATED BY WRAPPERGENERATOR.PY
20 *          DO NOT MODIFY THIS FILE, MODIFY DiamEllip.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 "DiamEllip.h"
36}
37
38#include "models.hh"
39#include "dispersion_visitor.hh"
40
41/// Error object for raised exceptions
42static PyObject * CDiamEllipFuncError = 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    DiamEllipFunc * model;
54    /// Log for unit testing
55    PyObject * log;
56} CDiamEllipFunc;
57
58
59static void
60CDiamEllipFunc_dealloc(CDiamEllipFunc* 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 *
72CDiamEllipFunc_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
73{
74    CDiamEllipFunc *self;
75   
76    self = (CDiamEllipFunc *)type->tp_alloc(type, 0);
77   
78    return (PyObject *)self;
79}
80
81static int
82CDiamEllipFunc_init(CDiamEllipFunc *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 DiamEllipFunc();
90       
91        // Initialize parameter dictionary
92        PyDict_SetItemString(self->params,"radius_b",Py_BuildValue("d",400.000000));
93        PyDict_SetItemString(self->params,"radius_a",Py_BuildValue("d",20.000000));
94        // Initialize dispersion / averaging parameter dict
95        DispersionVisitor* visitor = new DispersionVisitor();
96        PyObject * disp_dict;
97        disp_dict = PyDict_New();
98        self->model->radius_a.dispersion->accept_as_source(visitor, self->model->radius_a.dispersion, disp_dict);
99        PyDict_SetItemString(self->dispersion, "radius_a", disp_dict);
100        disp_dict = PyDict_New();
101        self->model->radius_b.dispersion->accept_as_source(visitor, self->model->radius_b.dispersion, disp_dict);
102        PyDict_SetItemString(self->dispersion, "radius_b", 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 CDiamEllipFunc_members[] = {
116    {"params", T_OBJECT, offsetof(CDiamEllipFunc, params), 0,
117     "Parameters"},
118        {"dispersion", T_OBJECT, offsetof(CDiamEllipFunc, dispersion), 0,
119          "Dispersion parameters"},     
120    {"log", T_OBJECT, offsetof(CDiamEllipFunc, log), 0,
121     "Log"},
122    {NULL}  /* Sentinel */
123};
124
125/** Read double from PyObject
126    @param p PyObject
127    @return double
128*/
129double CDiamEllipFunc_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(DiamEllipFunc* 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( DiamEllipFunc* 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[1];
193        y_len = dims[0]= y->dimensions[0];
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[1]);
207                    double y_value = *(double *)(y->data + j*y->strides[0]);
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(CDiamEllipFuncError, 
217                   "CDiamEllipFunc.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(CDiamEllipFunc *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->radius_b = PyFloat_AsDouble( PyDict_GetItemString(self->params, "radius_b") );
235    self->model->radius_a = PyFloat_AsDouble( PyDict_GetItemString(self->params, "radius_a") );
236    // Read in dispersion parameters
237    PyObject* disp_dict;
238    DispersionVisitor* visitor = new DispersionVisitor();
239    disp_dict = PyDict_GetItemString(self->dispersion, "radius_a");
240    self->model->radius_a.dispersion->accept_as_destination(visitor, self->model->radius_a.dispersion, disp_dict);
241    disp_dict = PyDict_GetItemString(self->dispersion, "radius_b");
242    self->model->radius_b.dispersion->accept_as_destination(visitor, self->model->radius_b.dispersion, disp_dict);
243
244       
245        // Get input and determine whether we have to supply a 1D or 2D return value.
246        if ( !PyArg_ParseTuple(args,"O",&pars) ) {
247            PyErr_SetString(CDiamEllipFuncError, 
248                "CDiamEllipFunc.evalDistribution expects a q value.");
249                return NULL;
250        }
251    // Check params
252       
253    if(PyArray_Check(pars)==1) {
254               
255            // Length of list should 1 or 2
256            npars = pars->nd; 
257            if(npars==1) {
258                // input is a numpy array
259                if (PyArray_Check(pars)) {
260                        return evaluateOneDim(self->model, (PyArrayObject*)pars); 
261                    }
262                }else{
263                    PyErr_SetString(CDiamEllipFuncError, 
264                   "CDiamEllipFunc.evalDistribution expect numpy array of one dimension.");
265                return NULL;
266                }
267    }else if( PyList_Check(pars)==1) {
268        // Length of list should be 2 for I(qx,qy)
269            mpars = PyList_GET_SIZE(pars); 
270            if(mpars!=2) {
271                PyErr_SetString(CDiamEllipFuncError, 
272                        "CDiamEllipFunc.evalDistribution expects a list of dimension 2.");
273                return NULL;
274            }
275             qx = PyList_GET_ITEM(pars,0);
276             qy = PyList_GET_ITEM(pars,1);
277             if (PyArray_Check(qx) && PyArray_Check(qy)) {
278                 return evaluateTwoDimXY(self->model, (PyArrayObject*)qx,
279                           (PyArrayObject*)qy);
280                 }else{
281                    PyErr_SetString(CDiamEllipFuncError, 
282                   "CDiamEllipFunc.evalDistribution expect 2 numpy arrays in list.");
283                return NULL;
284             }
285        }
286        PyErr_SetString(CDiamEllipFuncError, 
287                   "CDiamEllipFunc.evalDistribution couln't be run.");
288        return NULL;
289       
290}
291
292/**
293 * Function to call to evaluate model
294 * @param args: input q or [q,phi]
295 * @return: function value
296 */
297static PyObject * run(CDiamEllipFunc *self, PyObject *args) {
298        double q_value, phi_value;
299        PyObject* pars;
300        int npars;
301       
302        // Get parameters
303       
304            // Reader parameter dictionary
305    self->model->radius_b = PyFloat_AsDouble( PyDict_GetItemString(self->params, "radius_b") );
306    self->model->radius_a = PyFloat_AsDouble( PyDict_GetItemString(self->params, "radius_a") );
307    // Read in dispersion parameters
308    PyObject* disp_dict;
309    DispersionVisitor* visitor = new DispersionVisitor();
310    disp_dict = PyDict_GetItemString(self->dispersion, "radius_a");
311    self->model->radius_a.dispersion->accept_as_destination(visitor, self->model->radius_a.dispersion, disp_dict);
312    disp_dict = PyDict_GetItemString(self->dispersion, "radius_b");
313    self->model->radius_b.dispersion->accept_as_destination(visitor, self->model->radius_b.dispersion, disp_dict);
314
315       
316        // Get input and determine whether we have to supply a 1D or 2D return value.
317        if ( !PyArg_ParseTuple(args,"O",&pars) ) {
318            PyErr_SetString(CDiamEllipFuncError, 
319                "CDiamEllipFunc.run expects a q value.");
320                return NULL;
321        }
322         
323        // Check params
324        if( PyList_Check(pars)==1) {
325               
326                // Length of list should be 2 for I(q,phi)
327            npars = PyList_GET_SIZE(pars); 
328            if(npars!=2) {
329                PyErr_SetString(CDiamEllipFuncError, 
330                        "CDiamEllipFunc.run expects a double or a list of dimension 2.");
331                return NULL;
332            }
333            // We have a vector q, get the q and phi values at which
334            // to evaluate I(q,phi)
335            q_value = CDiamEllipFunc_readDouble(PyList_GET_ITEM(pars,0));
336            phi_value = CDiamEllipFunc_readDouble(PyList_GET_ITEM(pars,1));
337            // Skip zero
338            if (q_value==0) {
339                return Py_BuildValue("d",0.0);
340            }
341                return Py_BuildValue("d",(*(self->model)).evaluate_rphi(q_value,phi_value));
342
343        } else {
344
345                // We have a scalar q, we will evaluate I(q)
346                q_value = CDiamEllipFunc_readDouble(pars);             
347               
348                return Py_BuildValue("d",(*(self->model))(q_value));
349        }       
350}
351/**
352 * Function to call to calculate_ER
353 * @return: effective radius value
354 */
355static PyObject * calculate_ER(CDiamEllipFunc *self) {
356
357        PyObject* pars;
358        int npars;
359       
360        // Get parameters
361       
362            // Reader parameter dictionary
363    self->model->radius_b = PyFloat_AsDouble( PyDict_GetItemString(self->params, "radius_b") );
364    self->model->radius_a = PyFloat_AsDouble( PyDict_GetItemString(self->params, "radius_a") );
365    // Read in dispersion parameters
366    PyObject* disp_dict;
367    DispersionVisitor* visitor = new DispersionVisitor();
368    disp_dict = PyDict_GetItemString(self->dispersion, "radius_a");
369    self->model->radius_a.dispersion->accept_as_destination(visitor, self->model->radius_a.dispersion, disp_dict);
370    disp_dict = PyDict_GetItemString(self->dispersion, "radius_b");
371    self->model->radius_b.dispersion->accept_as_destination(visitor, self->model->radius_b.dispersion, disp_dict);
372
373               
374        return Py_BuildValue("d",(*(self->model)).calculate_ER());
375
376}
377/**
378 * Function to call to evaluate model in cartesian coordinates
379 * @param args: input q or [qx, qy]]
380 * @return: function value
381 */
382static PyObject * runXY(CDiamEllipFunc *self, PyObject *args) {
383        double qx_value, qy_value;
384        PyObject* pars;
385        int npars;
386       
387        // Get parameters
388       
389            // Reader parameter dictionary
390    self->model->radius_b = PyFloat_AsDouble( PyDict_GetItemString(self->params, "radius_b") );
391    self->model->radius_a = PyFloat_AsDouble( PyDict_GetItemString(self->params, "radius_a") );
392    // Read in dispersion parameters
393    PyObject* disp_dict;
394    DispersionVisitor* visitor = new DispersionVisitor();
395    disp_dict = PyDict_GetItemString(self->dispersion, "radius_a");
396    self->model->radius_a.dispersion->accept_as_destination(visitor, self->model->radius_a.dispersion, disp_dict);
397    disp_dict = PyDict_GetItemString(self->dispersion, "radius_b");
398    self->model->radius_b.dispersion->accept_as_destination(visitor, self->model->radius_b.dispersion, disp_dict);
399
400       
401        // Get input and determine whether we have to supply a 1D or 2D return value.
402        if ( !PyArg_ParseTuple(args,"O",&pars) ) {
403            PyErr_SetString(CDiamEllipFuncError, 
404                "CDiamEllipFunc.run expects a q value.");
405                return NULL;
406        }
407         
408        // Check params
409        if( PyList_Check(pars)==1) {
410               
411                // Length of list should be 2 for I(qx, qy))
412            npars = PyList_GET_SIZE(pars); 
413            if(npars!=2) {
414                PyErr_SetString(CDiamEllipFuncError, 
415                        "CDiamEllipFunc.run expects a double or a list of dimension 2.");
416                return NULL;
417            }
418            // We have a vector q, get the qx and qy values at which
419            // to evaluate I(qx,qy)
420            qx_value = CDiamEllipFunc_readDouble(PyList_GET_ITEM(pars,0));
421            qy_value = CDiamEllipFunc_readDouble(PyList_GET_ITEM(pars,1));
422            return Py_BuildValue("d",(*(self->model))(qx_value,qy_value));
423
424        } else {
425
426                // We have a scalar q, we will evaluate I(q)
427                qx_value = CDiamEllipFunc_readDouble(pars);             
428               
429                return Py_BuildValue("d",(*(self->model))(qx_value));
430        }       
431}
432
433static PyObject * reset(CDiamEllipFunc *self, PyObject *args) {
434   
435
436    return Py_BuildValue("d",0.0);
437}
438
439static PyObject * set_dispersion(CDiamEllipFunc *self, PyObject *args) {
440        PyObject * disp;
441        const char * par_name;
442
443        if ( !PyArg_ParseTuple(args,"sO", &par_name, &disp) ) {
444            PyErr_SetString(CDiamEllipFuncError,
445                "CDiamEllipFunc.set_dispersion expects a DispersionModel object.");
446                return NULL;
447        }
448        void *temp = PyCObject_AsVoidPtr(disp);
449        DispersionModel * dispersion = static_cast<DispersionModel *>(temp);
450
451
452        // Ugliness necessary to go from python to C
453            // TODO: refactor this
454    if (!strcmp(par_name, "radius_a")) {
455        self->model->radius_a.dispersion = dispersion;
456    } else    if (!strcmp(par_name, "radius_b")) {
457        self->model->radius_b.dispersion = dispersion;
458    } else {
459            PyErr_SetString(CDiamEllipFuncError,
460                "CDiamEllipFunc.set_dispersion expects a valid parameter name.");
461                return NULL;
462        }
463
464        DispersionVisitor* visitor = new DispersionVisitor();
465        PyObject * disp_dict = PyDict_New();
466        dispersion->accept_as_source(visitor, dispersion, disp_dict);
467        PyDict_SetItemString(self->dispersion, par_name, disp_dict);
468    return Py_BuildValue("i",1);
469}
470
471
472static PyMethodDef CDiamEllipFunc_methods[] = {
473    {"run",      (PyCFunction)run     , METH_VARARGS,
474      "Evaluate the model at a given Q or Q, phi"},
475    {"runXY",      (PyCFunction)runXY     , METH_VARARGS,
476      "Evaluate the model at a given Q or Qx, Qy"},
477    {"calculate_ER",      (PyCFunction)calculate_ER     , METH_VARARGS,
478      "Evaluate the model at a given Q or Q, phi"},
479     
480    {"evalDistribution",  (PyCFunction)evalDistribution , METH_VARARGS,
481      "Evaluate the model at a given Q or Qx, Qy vector "},
482    {"reset",    (PyCFunction)reset   , METH_VARARGS,
483      "Reset pair correlation"},
484    {"set_dispersion",      (PyCFunction)set_dispersion     , METH_VARARGS,
485      "Set the dispersion model for a given parameter"},
486   {NULL}
487};
488
489static PyTypeObject CDiamEllipFuncType = {
490    PyObject_HEAD_INIT(NULL)
491    0,                         /*ob_size*/
492    "CDiamEllipFunc",             /*tp_name*/
493    sizeof(CDiamEllipFunc),             /*tp_basicsize*/
494    0,                         /*tp_itemsize*/
495    (destructor)CDiamEllipFunc_dealloc, /*tp_dealloc*/
496    0,                         /*tp_print*/
497    0,                         /*tp_getattr*/
498    0,                         /*tp_setattr*/
499    0,                         /*tp_compare*/
500    0,                         /*tp_repr*/
501    0,                         /*tp_as_number*/
502    0,                         /*tp_as_sequence*/
503    0,                         /*tp_as_mapping*/
504    0,                         /*tp_hash */
505    0,                         /*tp_call*/
506    0,                         /*tp_str*/
507    0,                         /*tp_getattro*/
508    0,                         /*tp_setattro*/
509    0,                         /*tp_as_buffer*/
510    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
511    "CDiamEllipFunc objects",           /* tp_doc */
512    0,                         /* tp_traverse */
513    0,                         /* tp_clear */
514    0,                         /* tp_richcompare */
515    0,                         /* tp_weaklistoffset */
516    0,                         /* tp_iter */
517    0,                         /* tp_iternext */
518    CDiamEllipFunc_methods,             /* tp_methods */
519    CDiamEllipFunc_members,             /* tp_members */
520    0,                         /* tp_getset */
521    0,                         /* tp_base */
522    0,                         /* tp_dict */
523    0,                         /* tp_descr_get */
524    0,                         /* tp_descr_set */
525    0,                         /* tp_dictoffset */
526    (initproc)CDiamEllipFunc_init,      /* tp_init */
527    0,                         /* tp_alloc */
528    CDiamEllipFunc_new,                 /* tp_new */
529};
530
531
532//static PyMethodDef module_methods[] = {
533//    {NULL}
534//};
535
536/**
537 * Function used to add the model class to a module
538 * @param module: module to add the class to
539 */ 
540void addCDiamEllipFunc(PyObject *module) {
541        PyObject *d;
542       
543    if (PyType_Ready(&CDiamEllipFuncType) < 0)
544        return;
545
546    Py_INCREF(&CDiamEllipFuncType);
547    PyModule_AddObject(module, "CDiamEllipFunc", (PyObject *)&CDiamEllipFuncType);
548   
549    d = PyModule_GetDict(module);
550    CDiamEllipFuncError = PyErr_NewException("CDiamEllipFunc.error", NULL, NULL);
551    PyDict_SetItemString(d, "CDiamEllipFuncError", CDiamEllipFuncError);
552}
553
Note: See TracBrowser for help on using the repository browser.