source: sasview/sansmodels/src/sans/models/c_models/CFractalModel.cpp @ ab87b61

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 ab87b61 was ab87b61, checked in by Mathieu Doucet <doucetm@…>, 12 years ago

Re #7 Fix call to deprecated numpy function

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