source: sasview/src/sans/models/c_extension/python_wrapper/generated/CHardsphereStructure.cpp @ 400155b

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 400155b was 400155b, checked in by gonzalezm, 9 years ago

Implementing request from ticket 261 - default number of bins in Annulus [Phi View] is now 36 and the first bin is now centered at 0 degrees

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