source: sasview/sansmodels/src/sans/models/c_models/CDiamCylFunc.cpp @ 01de557

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