source: sasview/sansmodels/src/sans/models/c_models/CPoly_GaussCoil.cpp @ 0b082f3

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

Re #7 Enable openmp for all models

  • Property mode set to 100644
File size: 18.7 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#pragma omp parallel for
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( Poly_GaussCoil* model, 
181                              PyArrayObject *x, PyArrayObject *y)
182 {
183    PyArrayObject *result;
184    int 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#pragma omp parallel for
209        for (int i=0; i< x_len; i++) {
210            double x_value = *(double *)(x->data + i*x->strides[0]);
211                    double y_value = *(double *)(y->data + i*y->strides[0]);
212                        double *result_value = (double *)(result->data +
213                              i*result->strides[0]);
214                        *result_value = (*model)(x_value, y_value);
215        }           
216        return PyArray_Return(result); 
217       
218        }else{
219                    PyErr_SetString(CPoly_GaussCoilError, 
220                   "CPoly_GaussCoil.evaluateTwoDimXY couldn't run.");
221                return NULL;
222                }       
223}
224/**
225 *  evalDistribution function evaluate a model function with input vector
226 *  @param args: input q as vector or [qx, qy] where qx, qy are vectors
227 *
228 */ 
229static PyObject * evalDistribution(CPoly_GaussCoil *self, PyObject *args){
230        PyObject *qx, *qy;
231        PyArrayObject * pars;
232        int npars ,mpars;
233       
234        // Get parameters
235       
236            // Reader parameter dictionary
237    self->model->poly_m = PyFloat_AsDouble( PyDict_GetItemString(self->params, "poly_m") );
238    self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") );
239    self->model->rg = PyFloat_AsDouble( PyDict_GetItemString(self->params, "rg") );
240    self->model->background = PyFloat_AsDouble( PyDict_GetItemString(self->params, "background") );
241    // Read in dispersion parameters
242    PyObject* disp_dict;
243    DispersionVisitor* visitor = new DispersionVisitor();
244    disp_dict = PyDict_GetItemString(self->dispersion, "rg");
245    self->model->rg.dispersion->accept_as_destination(visitor, self->model->rg.dispersion, disp_dict);
246
247       
248        // Get input and determine whether we have to supply a 1D or 2D return value.
249        if ( !PyArg_ParseTuple(args,"O",&pars) ) {
250            PyErr_SetString(CPoly_GaussCoilError, 
251                "CPoly_GaussCoil.evalDistribution expects a q value.");
252                return NULL;
253        }
254    // Check params
255       
256    if(PyArray_Check(pars)==1) {
257               
258            // Length of list should 1 or 2
259            npars = pars->nd; 
260            if(npars==1) {
261                // input is a numpy array
262                if (PyArray_Check(pars)) {
263                        return evaluateOneDim(self->model, (PyArrayObject*)pars); 
264                    }
265                }else{
266                    PyErr_SetString(CPoly_GaussCoilError, 
267                   "CPoly_GaussCoil.evalDistribution expect numpy array of one dimension.");
268                return NULL;
269                }
270    }else if( PyList_Check(pars)==1) {
271        // Length of list should be 2 for I(qx,qy)
272            mpars = PyList_GET_SIZE(pars); 
273            if(mpars!=2) {
274                PyErr_SetString(CPoly_GaussCoilError, 
275                        "CPoly_GaussCoil.evalDistribution expects a list of dimension 2.");
276                return NULL;
277            }
278             qx = PyList_GET_ITEM(pars,0);
279             qy = PyList_GET_ITEM(pars,1);
280             if (PyArray_Check(qx) && PyArray_Check(qy)) {
281                 return evaluateTwoDimXY(self->model, (PyArrayObject*)qx,
282                           (PyArrayObject*)qy);
283                 }else{
284                    PyErr_SetString(CPoly_GaussCoilError, 
285                   "CPoly_GaussCoil.evalDistribution expect 2 numpy arrays in list.");
286                return NULL;
287             }
288        }
289        PyErr_SetString(CPoly_GaussCoilError, 
290                   "CPoly_GaussCoil.evalDistribution couln't be run.");
291        return NULL;
292       
293}
294
295/**
296 * Function to call to evaluate model
297 * @param args: input q or [q,phi]
298 * @return: function value
299 */
300static PyObject * run(CPoly_GaussCoil *self, PyObject *args) {
301        double q_value, phi_value;
302        PyObject* pars;
303        int npars;
304       
305        // Get parameters
306       
307            // Reader parameter dictionary
308    self->model->poly_m = PyFloat_AsDouble( PyDict_GetItemString(self->params, "poly_m") );
309    self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") );
310    self->model->rg = PyFloat_AsDouble( PyDict_GetItemString(self->params, "rg") );
311    self->model->background = PyFloat_AsDouble( PyDict_GetItemString(self->params, "background") );
312    // Read in dispersion parameters
313    PyObject* disp_dict;
314    DispersionVisitor* visitor = new DispersionVisitor();
315    disp_dict = PyDict_GetItemString(self->dispersion, "rg");
316    self->model->rg.dispersion->accept_as_destination(visitor, self->model->rg.dispersion, disp_dict);
317
318       
319        // Get input and determine whether we have to supply a 1D or 2D return value.
320        if ( !PyArg_ParseTuple(args,"O",&pars) ) {
321            PyErr_SetString(CPoly_GaussCoilError, 
322                "CPoly_GaussCoil.run expects a q value.");
323                return NULL;
324        }
325         
326        // Check params
327        if( PyList_Check(pars)==1) {
328               
329                // Length of list should be 2 for I(q,phi)
330            npars = PyList_GET_SIZE(pars); 
331            if(npars!=2) {
332                PyErr_SetString(CPoly_GaussCoilError, 
333                        "CPoly_GaussCoil.run expects a double or a list of dimension 2.");
334                return NULL;
335            }
336            // We have a vector q, get the q and phi values at which
337            // to evaluate I(q,phi)
338            q_value = CPoly_GaussCoil_readDouble(PyList_GET_ITEM(pars,0));
339            phi_value = CPoly_GaussCoil_readDouble(PyList_GET_ITEM(pars,1));
340            // Skip zero
341            if (q_value==0) {
342                return Py_BuildValue("d",0.0);
343            }
344                return Py_BuildValue("d",(*(self->model)).evaluate_rphi(q_value,phi_value));
345
346        } else {
347
348                // We have a scalar q, we will evaluate I(q)
349                q_value = CPoly_GaussCoil_readDouble(pars);             
350               
351                return Py_BuildValue("d",(*(self->model))(q_value));
352        }       
353}
354/**
355 * Function to call to calculate_ER
356 * @return: effective radius value
357 */
358static PyObject * calculate_ER(CPoly_GaussCoil *self) {
359
360        // Get parameters
361       
362            // Reader parameter dictionary
363    self->model->poly_m = PyFloat_AsDouble( PyDict_GetItemString(self->params, "poly_m") );
364    self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") );
365    self->model->rg = PyFloat_AsDouble( PyDict_GetItemString(self->params, "rg") );
366    self->model->background = PyFloat_AsDouble( PyDict_GetItemString(self->params, "background") );
367    // Read in dispersion parameters
368    PyObject* disp_dict;
369    DispersionVisitor* visitor = new DispersionVisitor();
370    disp_dict = PyDict_GetItemString(self->dispersion, "rg");
371    self->model->rg.dispersion->accept_as_destination(visitor, self->model->rg.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(CPoly_GaussCoil *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->poly_m = PyFloat_AsDouble( PyDict_GetItemString(self->params, "poly_m") );
391    self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") );
392    self->model->rg = PyFloat_AsDouble( PyDict_GetItemString(self->params, "rg") );
393    self->model->background = PyFloat_AsDouble( PyDict_GetItemString(self->params, "background") );
394    // Read in dispersion parameters
395    PyObject* disp_dict;
396    DispersionVisitor* visitor = new DispersionVisitor();
397    disp_dict = PyDict_GetItemString(self->dispersion, "rg");
398    self->model->rg.dispersion->accept_as_destination(visitor, self->model->rg.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(CPoly_GaussCoilError, 
404                "CPoly_GaussCoil.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(CPoly_GaussCoilError, 
415                        "CPoly_GaussCoil.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 = CPoly_GaussCoil_readDouble(PyList_GET_ITEM(pars,0));
421            qy_value = CPoly_GaussCoil_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 = CPoly_GaussCoil_readDouble(pars);           
428               
429                return Py_BuildValue("d",(*(self->model))(qx_value));
430        }       
431}
432
433static PyObject * reset(CPoly_GaussCoil *self, PyObject *args) {
434   
435
436    return Py_BuildValue("d",0.0);
437}
438
439static PyObject * set_dispersion(CPoly_GaussCoil *self, PyObject *args) {
440        PyObject * disp;
441        const char * par_name;
442
443        if ( !PyArg_ParseTuple(args,"sO", &par_name, &disp) ) {
444            PyErr_SetString(CPoly_GaussCoilError,
445                "CPoly_GaussCoil.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, "rg")) {
455        self->model->rg.dispersion = dispersion;
456    } else {
457            PyErr_SetString(CPoly_GaussCoilError,
458                "CPoly_GaussCoil.set_dispersion expects a valid parameter name.");
459                return NULL;
460        }
461
462        DispersionVisitor* visitor = new DispersionVisitor();
463        PyObject * disp_dict = PyDict_New();
464        dispersion->accept_as_source(visitor, dispersion, disp_dict);
465        PyDict_SetItemString(self->dispersion, par_name, disp_dict);
466    return Py_BuildValue("i",1);
467}
468
469
470static PyMethodDef CPoly_GaussCoil_methods[] = {
471    {"run",      (PyCFunction)run     , METH_VARARGS,
472      "Evaluate the model at a given Q or Q, phi"},
473    {"runXY",      (PyCFunction)runXY     , METH_VARARGS,
474      "Evaluate the model at a given Q or Qx, Qy"},
475    {"calculate_ER",      (PyCFunction)calculate_ER     , METH_VARARGS,
476      "Evaluate the model at a given Q or Q, phi"},
477     
478    {"evalDistribution",  (PyCFunction)evalDistribution , METH_VARARGS,
479      "Evaluate the model at a given Q or Qx, Qy vector "},
480    {"reset",    (PyCFunction)reset   , METH_VARARGS,
481      "Reset pair correlation"},
482    {"set_dispersion",      (PyCFunction)set_dispersion     , METH_VARARGS,
483      "Set the dispersion model for a given parameter"},
484   {NULL}
485};
486
487static PyTypeObject CPoly_GaussCoilType = {
488    PyObject_HEAD_INIT(NULL)
489    0,                         /*ob_size*/
490    "CPoly_GaussCoil",             /*tp_name*/
491    sizeof(CPoly_GaussCoil),             /*tp_basicsize*/
492    0,                         /*tp_itemsize*/
493    (destructor)CPoly_GaussCoil_dealloc, /*tp_dealloc*/
494    0,                         /*tp_print*/
495    0,                         /*tp_getattr*/
496    0,                         /*tp_setattr*/
497    0,                         /*tp_compare*/
498    0,                         /*tp_repr*/
499    0,                         /*tp_as_number*/
500    0,                         /*tp_as_sequence*/
501    0,                         /*tp_as_mapping*/
502    0,                         /*tp_hash */
503    0,                         /*tp_call*/
504    0,                         /*tp_str*/
505    0,                         /*tp_getattro*/
506    0,                         /*tp_setattro*/
507    0,                         /*tp_as_buffer*/
508    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
509    "CPoly_GaussCoil objects",           /* tp_doc */
510    0,                         /* tp_traverse */
511    0,                         /* tp_clear */
512    0,                         /* tp_richcompare */
513    0,                         /* tp_weaklistoffset */
514    0,                         /* tp_iter */
515    0,                         /* tp_iternext */
516    CPoly_GaussCoil_methods,             /* tp_methods */
517    CPoly_GaussCoil_members,             /* tp_members */
518    0,                         /* tp_getset */
519    0,                         /* tp_base */
520    0,                         /* tp_dict */
521    0,                         /* tp_descr_get */
522    0,                         /* tp_descr_set */
523    0,                         /* tp_dictoffset */
524    (initproc)CPoly_GaussCoil_init,      /* tp_init */
525    0,                         /* tp_alloc */
526    CPoly_GaussCoil_new,                 /* tp_new */
527};
528
529
530//static PyMethodDef module_methods[] = {
531//    {NULL}
532//};
533
534/**
535 * Function used to add the model class to a module
536 * @param module: module to add the class to
537 */ 
538void addCPoly_GaussCoil(PyObject *module) {
539        PyObject *d;
540       
541    if (PyType_Ready(&CPoly_GaussCoilType) < 0)
542        return;
543
544    Py_INCREF(&CPoly_GaussCoilType);
545    PyModule_AddObject(module, "CPoly_GaussCoil", (PyObject *)&CPoly_GaussCoilType);
546   
547    d = PyModule_GetDict(module);
548    static char error_name[] = "CPoly_GaussCoil.error";
549    CPoly_GaussCoilError = PyErr_NewException(error_name, NULL, NULL);
550    PyDict_SetItemString(d, "CPoly_GaussCoilError", CPoly_GaussCoilError);
551}
552
Note: See TracBrowser for help on using the repository browser.