source: sasview/sansmodels/src/sans/models/c_models/CPoly_GaussCoil.cpp @ 00c2141

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

Re #4 Fixing a few more warnings

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