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