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

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 b1c3295 was b1c3295, checked in by Mathieu Doucet <doucetm@…>, 12 years ago

Re #4 This should clean up a whole bunch of C++ warnings.

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