source: sasview/src/sans/models/c_extension/python_wrapper/generated/CStickyHSStructure.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: 19.8 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/** CStickyHSStructure
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\StickyHS.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 "StickyHS.h"
39#include "dispersion_visitor.hh"
40
41/// Error object for raised exceptions
42static PyObject * CStickyHSStructureError = 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    StickyHSStructure * model;
54    /// Log for unit testing
55    PyObject * log;
56} CStickyHSStructure;
57
58
59static void
60CStickyHSStructure_dealloc(CStickyHSStructure* 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 *
72CStickyHSStructure_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
73{
74    CStickyHSStructure *self;
75   
76    self = (CStickyHSStructure *)type->tp_alloc(type, 0);
77   
78    return (PyObject *)self;
79}
80
81static int
82CStickyHSStructure_init(CStickyHSStructure *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 StickyHSStructure();
91
92        // Initialize parameter dictionary
93        PyDict_SetItemString(self->params,"stickiness",Py_BuildValue("d",0.200000000000));
94        PyDict_SetItemString(self->params,"effect_radius",Py_BuildValue("d",50.000000000000));
95        PyDict_SetItemString(self->params,"volfraction",Py_BuildValue("d",0.100000000000));
96        PyDict_SetItemString(self->params,"perturb",Py_BuildValue("d",0.050000000000));
97        // Initialize dispersion / averaging parameter dict
98        DispersionVisitor* visitor = new DispersionVisitor();
99        PyObject * disp_dict;
100        disp_dict = PyDict_New();
101        self->model->effect_radius.dispersion->accept_as_source(visitor, self->model->effect_radius.dispersion, disp_dict);
102        PyDict_SetItemString(self->dispersion, "effect_radius", 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 CStickyHSStructure_members[] = {
123    {name_params, T_OBJECT, offsetof(CStickyHSStructure, params), 0, def_params},
124        {name_dispersion, T_OBJECT, offsetof(CStickyHSStructure, dispersion), 0, def_dispersion},     
125    {name_log, T_OBJECT, offsetof(CStickyHSStructure, log), 0, def_log},
126    {NULL}  /* Sentinel */
127};
128
129/** Read double from PyObject
130    @param p PyObject
131    @return double
132*/
133double CStickyHSStructure_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(StickyHSStructure* 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), 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( StickyHSStructure* 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(CStickyHSStructureError, 
220                   "CStickyHSStructure.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(CStickyHSStructure *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->stickiness = PyFloat_AsDouble( PyDict_GetItemString(self->params, "stickiness") );
238    self->model->effect_radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "effect_radius") );
239    self->model->volfraction = PyFloat_AsDouble( PyDict_GetItemString(self->params, "volfraction") );
240    self->model->perturb = PyFloat_AsDouble( PyDict_GetItemString(self->params, "perturb") );
241    // Read in dispersion parameters
242    PyObject* disp_dict;
243    DispersionVisitor* visitor = new DispersionVisitor();
244    disp_dict = PyDict_GetItemString(self->dispersion, "effect_radius");
245    self->model->effect_radius.dispersion->accept_as_destination(visitor, self->model->effect_radius.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(CStickyHSStructureError, 
251                "CStickyHSStructure.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(CStickyHSStructureError, 
267                   "CStickyHSStructure.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(CStickyHSStructureError, 
275                        "CStickyHSStructure.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(CStickyHSStructureError, 
285                   "CStickyHSStructure.evalDistribution expect 2 numpy arrays in list.");
286                return NULL;
287             }
288        }
289        PyErr_SetString(CStickyHSStructureError, 
290                   "CStickyHSStructure.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(CStickyHSStructure *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->stickiness = PyFloat_AsDouble( PyDict_GetItemString(self->params, "stickiness") );
309    self->model->effect_radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "effect_radius") );
310    self->model->volfraction = PyFloat_AsDouble( PyDict_GetItemString(self->params, "volfraction") );
311    self->model->perturb = PyFloat_AsDouble( PyDict_GetItemString(self->params, "perturb") );
312    // Read in dispersion parameters
313    PyObject* disp_dict;
314    DispersionVisitor* visitor = new DispersionVisitor();
315    disp_dict = PyDict_GetItemString(self->dispersion, "effect_radius");
316    self->model->effect_radius.dispersion->accept_as_destination(visitor, self->model->effect_radius.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(CStickyHSStructureError, 
322                "CStickyHSStructure.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(CStickyHSStructureError, 
333                        "CStickyHSStructure.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 = CStickyHSStructure_readDouble(PyList_GET_ITEM(pars,0));
339            phi_value = CStickyHSStructure_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 = CStickyHSStructure_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(CStickyHSStructure *self) {
359
360        // Get parameters
361       
362            // Reader parameter dictionary
363    self->model->stickiness = PyFloat_AsDouble( PyDict_GetItemString(self->params, "stickiness") );
364    self->model->effect_radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "effect_radius") );
365    self->model->volfraction = PyFloat_AsDouble( PyDict_GetItemString(self->params, "volfraction") );
366    self->model->perturb = PyFloat_AsDouble( PyDict_GetItemString(self->params, "perturb") );
367    // Read in dispersion parameters
368    PyObject* disp_dict;
369    DispersionVisitor* visitor = new DispersionVisitor();
370    disp_dict = PyDict_GetItemString(self->dispersion, "effect_radius");
371    self->model->effect_radius.dispersion->accept_as_destination(visitor, self->model->effect_radius.dispersion, disp_dict);
372
373               
374        return Py_BuildValue("d",(*(self->model)).calculate_ER());
375
376}
377/**
378 * Function to call to cal the ratio shell volume/ total volume
379 * @return: the ratio shell volume/ total volume
380 */
381static PyObject * calculate_VR(CStickyHSStructure *self) {
382
383        // Get parameters
384       
385            // Reader parameter dictionary
386    self->model->stickiness = PyFloat_AsDouble( PyDict_GetItemString(self->params, "stickiness") );
387    self->model->effect_radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "effect_radius") );
388    self->model->volfraction = PyFloat_AsDouble( PyDict_GetItemString(self->params, "volfraction") );
389    self->model->perturb = PyFloat_AsDouble( PyDict_GetItemString(self->params, "perturb") );
390    // Read in dispersion parameters
391    PyObject* disp_dict;
392    DispersionVisitor* visitor = new DispersionVisitor();
393    disp_dict = PyDict_GetItemString(self->dispersion, "effect_radius");
394    self->model->effect_radius.dispersion->accept_as_destination(visitor, self->model->effect_radius.dispersion, disp_dict);
395
396               
397        return Py_BuildValue("d",(*(self->model)).calculate_VR());
398
399}
400/**
401 * Function to call to evaluate model in cartesian coordinates
402 * @param args: input q or [qx, qy]]
403 * @return: function value
404 */
405static PyObject * runXY(CStickyHSStructure *self, PyObject *args) {
406        double qx_value, qy_value;
407        PyObject* pars;
408        int npars;
409       
410        // Get parameters
411       
412            // Reader parameter dictionary
413    self->model->stickiness = PyFloat_AsDouble( PyDict_GetItemString(self->params, "stickiness") );
414    self->model->effect_radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "effect_radius") );
415    self->model->volfraction = PyFloat_AsDouble( PyDict_GetItemString(self->params, "volfraction") );
416    self->model->perturb = PyFloat_AsDouble( PyDict_GetItemString(self->params, "perturb") );
417    // Read in dispersion parameters
418    PyObject* disp_dict;
419    DispersionVisitor* visitor = new DispersionVisitor();
420    disp_dict = PyDict_GetItemString(self->dispersion, "effect_radius");
421    self->model->effect_radius.dispersion->accept_as_destination(visitor, self->model->effect_radius.dispersion, disp_dict);
422
423       
424        // Get input and determine whether we have to supply a 1D or 2D return value.
425        if ( !PyArg_ParseTuple(args,"O",&pars) ) {
426            PyErr_SetString(CStickyHSStructureError, 
427                "CStickyHSStructure.run expects a q value.");
428                return NULL;
429        }
430         
431        // Check params
432        if( PyList_Check(pars)==1) {
433               
434                // Length of list should be 2 for I(qx, qy))
435            npars = PyList_GET_SIZE(pars); 
436            if(npars!=2) {
437                PyErr_SetString(CStickyHSStructureError, 
438                        "CStickyHSStructure.run expects a double or a list of dimension 2.");
439                return NULL;
440            }
441            // We have a vector q, get the qx and qy values at which
442            // to evaluate I(qx,qy)
443            qx_value = CStickyHSStructure_readDouble(PyList_GET_ITEM(pars,0));
444            qy_value = CStickyHSStructure_readDouble(PyList_GET_ITEM(pars,1));
445            return Py_BuildValue("d",(*(self->model))(qx_value,qy_value));
446
447        } else {
448
449                // We have a scalar q, we will evaluate I(q)
450                qx_value = CStickyHSStructure_readDouble(pars);         
451               
452                return Py_BuildValue("d",(*(self->model))(qx_value));
453        }       
454}
455
456static PyObject * reset(CStickyHSStructure *self, PyObject *args) {
457   
458
459    return Py_BuildValue("d",0.0);
460}
461
462static PyObject * set_dispersion(CStickyHSStructure *self, PyObject *args) {
463        PyObject * disp;
464        const char * par_name;
465
466        if ( !PyArg_ParseTuple(args,"sO", &par_name, &disp) ) {
467            PyErr_SetString(CStickyHSStructureError,
468                "CStickyHSStructure.set_dispersion expects a DispersionModel object.");
469                return NULL;
470        }
471        void *temp = PyCObject_AsVoidPtr(disp);
472        DispersionModel * dispersion = static_cast<DispersionModel *>(temp);
473
474
475        // Ugliness necessary to go from python to C
476            // TODO: refactor this
477    if (!strcmp(par_name, "effect_radius")) {
478        self->model->effect_radius.dispersion = dispersion;
479    } else {
480            PyErr_SetString(CStickyHSStructureError,
481                "CStickyHSStructure.set_dispersion expects a valid parameter name.");
482                return NULL;
483        }
484
485        DispersionVisitor* visitor = new DispersionVisitor();
486        PyObject * disp_dict = PyDict_New();
487        dispersion->accept_as_source(visitor, dispersion, disp_dict);
488        PyDict_SetItemString(self->dispersion, par_name, disp_dict);
489    return Py_BuildValue("i",1);
490}
491
492
493static PyMethodDef CStickyHSStructure_methods[] = {
494    {"run",      (PyCFunction)run     , METH_VARARGS,
495      "Evaluate the model at a given Q or Q, phi"},
496    {"runXY",      (PyCFunction)runXY     , METH_VARARGS,
497      "Evaluate the model at a given Q or Qx, Qy"},
498    {"calculate_ER",      (PyCFunction)calculate_ER     , METH_VARARGS,
499      "Evaluate the model at a given Q or Q, phi"},
500    {"calculate_VR",      (PyCFunction)calculate_VR     , METH_VARARGS,
501      "Evaluate VR"},   
502    {"evalDistribution",  (PyCFunction)evalDistribution , METH_VARARGS,
503      "Evaluate the model at a given Q or Qx, Qy vector "},
504    {"reset",    (PyCFunction)reset   , METH_VARARGS,
505      "Reset pair correlation"},
506    {"set_dispersion",      (PyCFunction)set_dispersion     , METH_VARARGS,
507      "Set the dispersion model for a given parameter"},
508   {NULL}
509};
510
511static PyTypeObject CStickyHSStructureType = {
512    PyObject_HEAD_INIT(NULL)
513    0,                         /*ob_size*/
514    "CStickyHSStructure",             /*tp_name*/
515    sizeof(CStickyHSStructure),             /*tp_basicsize*/
516    0,                         /*tp_itemsize*/
517    (destructor)CStickyHSStructure_dealloc, /*tp_dealloc*/
518    0,                         /*tp_print*/
519    0,                         /*tp_getattr*/
520    0,                         /*tp_setattr*/
521    0,                         /*tp_compare*/
522    0,                         /*tp_repr*/
523    0,                         /*tp_as_number*/
524    0,                         /*tp_as_sequence*/
525    0,                         /*tp_as_mapping*/
526    0,                         /*tp_hash */
527    0,                         /*tp_call*/
528    0,                         /*tp_str*/
529    0,                         /*tp_getattro*/
530    0,                         /*tp_setattro*/
531    0,                         /*tp_as_buffer*/
532    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
533    "CStickyHSStructure objects",           /* tp_doc */
534    0,                         /* tp_traverse */
535    0,                         /* tp_clear */
536    0,                         /* tp_richcompare */
537    0,                         /* tp_weaklistoffset */
538    0,                         /* tp_iter */
539    0,                         /* tp_iternext */
540    CStickyHSStructure_methods,             /* tp_methods */
541    CStickyHSStructure_members,             /* tp_members */
542    0,                         /* tp_getset */
543    0,                         /* tp_base */
544    0,                         /* tp_dict */
545    0,                         /* tp_descr_get */
546    0,                         /* tp_descr_set */
547    0,                         /* tp_dictoffset */
548    (initproc)CStickyHSStructure_init,      /* tp_init */
549    0,                         /* tp_alloc */
550    CStickyHSStructure_new,                 /* tp_new */
551};
552
553
554//static PyMethodDef module_methods[] = {
555//    {NULL}
556//};
557
558/**
559 * Function used to add the model class to a module
560 * @param module: module to add the class to
561 */ 
562void addCStickyHSStructure(PyObject *module) {
563        PyObject *d;
564       
565    if (PyType_Ready(&CStickyHSStructureType) < 0)
566        return;
567
568    Py_INCREF(&CStickyHSStructureType);
569    PyModule_AddObject(module, "CStickyHSStructure", (PyObject *)&CStickyHSStructureType);
570   
571    d = PyModule_GetDict(module);
572    static char error_name[] = "CStickyHSStructure.error";
573    CStickyHSStructureError = PyErr_NewException(error_name, NULL, NULL);
574    PyDict_SetItemString(d, "CStickyHSStructureError", CStickyHSStructureError);
575}
576
Note: See TracBrowser for help on using the repository browser.