source: sasview/sansmodels/src/sans/models/c_models/CHardsphereStructure.cpp @ c25f1fa

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 c25f1fa was 34c2649, checked in by Mathieu Doucet <doucetm@…>, 13 years ago

Re #4 Fixed warnings

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