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

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2release_4.0.1ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since c25f1fa was 35aface, checked in by Jae Cho <jhjcho@…>, 14 years ago

addede new models and attr. non_fittable

  • Property mode set to 100644
File size: 19.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/** 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 PyMemberDef CFractalModel_members[] = {
118    {"params", T_OBJECT, offsetof(CFractalModel, params), 0,
119     "Parameters"},
120        {"dispersion", T_OBJECT, offsetof(CFractalModel, dispersion), 0,
121          "Dispersion parameters"},     
122    {"log", T_OBJECT, offsetof(CFractalModel, log), 0,
123     "Log"},
124    {NULL}  /* Sentinel */
125};
126
127/** Read double from PyObject
128    @param p PyObject
129    @return double
130*/
131double CFractalModel_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(FractalModel* 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), 
159                                                                                  PyArray_DOUBLE);
160        if (result == NULL) {
161        const char * message= "Could not create result ";
162        PyErr_SetString(PyExc_RuntimeError , message);
163                return NULL;
164        }
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( FractalModel* model, 
179                              PyArrayObject *x, PyArrayObject *y)
180 {
181    PyArrayObject *result;
182    int i,j, 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        for ( i=0; i< x_len; i++) {
207            double x_value = *(double *)(x->data + i*x->strides[0]);
208                    double y_value = *(double *)(y->data + i*y->strides[0]);
209                        double *result_value = (double *)(result->data +
210                              i*result->strides[0]);
211                        *result_value = (*model)(x_value, y_value);
212        }           
213        return PyArray_Return(result); 
214       
215        }else{
216                    PyErr_SetString(CFractalModelError, 
217                   "CFractalModel.evaluateTwoDimXY couldn't run.");
218                return NULL;
219                }       
220}
221/**
222 *  evalDistribution function evaluate a model function with input vector
223 *  @param args: input q as vector or [qx, qy] where qx, qy are vectors
224 *
225 */ 
226static PyObject * evalDistribution(CFractalModel *self, PyObject *args){
227        PyObject *qx, *qy;
228        PyArrayObject * pars;
229        int npars ,mpars;
230       
231        // Get parameters
232       
233            // Reader parameter dictionary
234    self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") );
235    self->model->fractal_dim = PyFloat_AsDouble( PyDict_GetItemString(self->params, "fractal_dim") );
236    self->model->sldSolv = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sldSolv") );
237    self->model->cor_length = PyFloat_AsDouble( PyDict_GetItemString(self->params, "cor_length") );
238    self->model->background = PyFloat_AsDouble( PyDict_GetItemString(self->params, "background") );
239    self->model->radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "radius") );
240    self->model->sldBlock = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sldBlock") );
241    // Read in dispersion parameters
242    PyObject* disp_dict;
243    DispersionVisitor* visitor = new DispersionVisitor();
244    disp_dict = PyDict_GetItemString(self->dispersion, "radius");
245    self->model->radius.dispersion->accept_as_destination(visitor, self->model->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(CFractalModelError, 
251                "CFractalModel.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(CFractalModelError, 
267                   "CFractalModel.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(CFractalModelError, 
275                        "CFractalModel.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(CFractalModelError, 
285                   "CFractalModel.evalDistribution expect 2 numpy arrays in list.");
286                return NULL;
287             }
288        }
289        PyErr_SetString(CFractalModelError, 
290                   "CFractalModel.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(CFractalModel *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->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") );
309    self->model->fractal_dim = PyFloat_AsDouble( PyDict_GetItemString(self->params, "fractal_dim") );
310    self->model->sldSolv = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sldSolv") );
311    self->model->cor_length = PyFloat_AsDouble( PyDict_GetItemString(self->params, "cor_length") );
312    self->model->background = PyFloat_AsDouble( PyDict_GetItemString(self->params, "background") );
313    self->model->radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "radius") );
314    self->model->sldBlock = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sldBlock") );
315    // Read in dispersion parameters
316    PyObject* disp_dict;
317    DispersionVisitor* visitor = new DispersionVisitor();
318    disp_dict = PyDict_GetItemString(self->dispersion, "radius");
319    self->model->radius.dispersion->accept_as_destination(visitor, self->model->radius.dispersion, disp_dict);
320
321       
322        // Get input and determine whether we have to supply a 1D or 2D return value.
323        if ( !PyArg_ParseTuple(args,"O",&pars) ) {
324            PyErr_SetString(CFractalModelError, 
325                "CFractalModel.run expects a q value.");
326                return NULL;
327        }
328         
329        // Check params
330        if( PyList_Check(pars)==1) {
331               
332                // Length of list should be 2 for I(q,phi)
333            npars = PyList_GET_SIZE(pars); 
334            if(npars!=2) {
335                PyErr_SetString(CFractalModelError, 
336                        "CFractalModel.run expects a double or a list of dimension 2.");
337                return NULL;
338            }
339            // We have a vector q, get the q and phi values at which
340            // to evaluate I(q,phi)
341            q_value = CFractalModel_readDouble(PyList_GET_ITEM(pars,0));
342            phi_value = CFractalModel_readDouble(PyList_GET_ITEM(pars,1));
343            // Skip zero
344            if (q_value==0) {
345                return Py_BuildValue("d",0.0);
346            }
347                return Py_BuildValue("d",(*(self->model)).evaluate_rphi(q_value,phi_value));
348
349        } else {
350
351                // We have a scalar q, we will evaluate I(q)
352                q_value = CFractalModel_readDouble(pars);               
353               
354                return Py_BuildValue("d",(*(self->model))(q_value));
355        }       
356}
357/**
358 * Function to call to calculate_ER
359 * @return: effective radius value
360 */
361static PyObject * calculate_ER(CFractalModel *self) {
362
363        PyObject* pars;
364        int npars;
365       
366        // Get parameters
367       
368            // Reader parameter dictionary
369    self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") );
370    self->model->fractal_dim = PyFloat_AsDouble( PyDict_GetItemString(self->params, "fractal_dim") );
371    self->model->sldSolv = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sldSolv") );
372    self->model->cor_length = PyFloat_AsDouble( PyDict_GetItemString(self->params, "cor_length") );
373    self->model->background = PyFloat_AsDouble( PyDict_GetItemString(self->params, "background") );
374    self->model->radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "radius") );
375    self->model->sldBlock = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sldBlock") );
376    // Read in dispersion parameters
377    PyObject* disp_dict;
378    DispersionVisitor* visitor = new DispersionVisitor();
379    disp_dict = PyDict_GetItemString(self->dispersion, "radius");
380    self->model->radius.dispersion->accept_as_destination(visitor, self->model->radius.dispersion, disp_dict);
381
382               
383        return Py_BuildValue("d",(*(self->model)).calculate_ER());
384
385}
386/**
387 * Function to call to evaluate model in cartesian coordinates
388 * @param args: input q or [qx, qy]]
389 * @return: function value
390 */
391static PyObject * runXY(CFractalModel *self, PyObject *args) {
392        double qx_value, qy_value;
393        PyObject* pars;
394        int npars;
395       
396        // Get parameters
397       
398            // Reader parameter dictionary
399    self->model->scale = PyFloat_AsDouble( PyDict_GetItemString(self->params, "scale") );
400    self->model->fractal_dim = PyFloat_AsDouble( PyDict_GetItemString(self->params, "fractal_dim") );
401    self->model->sldSolv = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sldSolv") );
402    self->model->cor_length = PyFloat_AsDouble( PyDict_GetItemString(self->params, "cor_length") );
403    self->model->background = PyFloat_AsDouble( PyDict_GetItemString(self->params, "background") );
404    self->model->radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "radius") );
405    self->model->sldBlock = PyFloat_AsDouble( PyDict_GetItemString(self->params, "sldBlock") );
406    // Read in dispersion parameters
407    PyObject* disp_dict;
408    DispersionVisitor* visitor = new DispersionVisitor();
409    disp_dict = PyDict_GetItemString(self->dispersion, "radius");
410    self->model->radius.dispersion->accept_as_destination(visitor, self->model->radius.dispersion, disp_dict);
411
412       
413        // Get input and determine whether we have to supply a 1D or 2D return value.
414        if ( !PyArg_ParseTuple(args,"O",&pars) ) {
415            PyErr_SetString(CFractalModelError, 
416                "CFractalModel.run expects a q value.");
417                return NULL;
418        }
419         
420        // Check params
421        if( PyList_Check(pars)==1) {
422               
423                // Length of list should be 2 for I(qx, qy))
424            npars = PyList_GET_SIZE(pars); 
425            if(npars!=2) {
426                PyErr_SetString(CFractalModelError, 
427                        "CFractalModel.run expects a double or a list of dimension 2.");
428                return NULL;
429            }
430            // We have a vector q, get the qx and qy values at which
431            // to evaluate I(qx,qy)
432            qx_value = CFractalModel_readDouble(PyList_GET_ITEM(pars,0));
433            qy_value = CFractalModel_readDouble(PyList_GET_ITEM(pars,1));
434            return Py_BuildValue("d",(*(self->model))(qx_value,qy_value));
435
436        } else {
437
438                // We have a scalar q, we will evaluate I(q)
439                qx_value = CFractalModel_readDouble(pars);             
440               
441                return Py_BuildValue("d",(*(self->model))(qx_value));
442        }       
443}
444
445static PyObject * reset(CFractalModel *self, PyObject *args) {
446   
447
448    return Py_BuildValue("d",0.0);
449}
450
451static PyObject * set_dispersion(CFractalModel *self, PyObject *args) {
452        PyObject * disp;
453        const char * par_name;
454
455        if ( !PyArg_ParseTuple(args,"sO", &par_name, &disp) ) {
456            PyErr_SetString(CFractalModelError,
457                "CFractalModel.set_dispersion expects a DispersionModel object.");
458                return NULL;
459        }
460        void *temp = PyCObject_AsVoidPtr(disp);
461        DispersionModel * dispersion = static_cast<DispersionModel *>(temp);
462
463
464        // Ugliness necessary to go from python to C
465            // TODO: refactor this
466    if (!strcmp(par_name, "radius")) {
467        self->model->radius.dispersion = dispersion;
468    } else {
469            PyErr_SetString(CFractalModelError,
470                "CFractalModel.set_dispersion expects a valid parameter name.");
471                return NULL;
472        }
473
474        DispersionVisitor* visitor = new DispersionVisitor();
475        PyObject * disp_dict = PyDict_New();
476        dispersion->accept_as_source(visitor, dispersion, disp_dict);
477        PyDict_SetItemString(self->dispersion, par_name, disp_dict);
478    return Py_BuildValue("i",1);
479}
480
481
482static PyMethodDef CFractalModel_methods[] = {
483    {"run",      (PyCFunction)run     , METH_VARARGS,
484      "Evaluate the model at a given Q or Q, phi"},
485    {"runXY",      (PyCFunction)runXY     , METH_VARARGS,
486      "Evaluate the model at a given Q or Qx, Qy"},
487    {"calculate_ER",      (PyCFunction)calculate_ER     , METH_VARARGS,
488      "Evaluate the model at a given Q or Q, phi"},
489     
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 CFractalModelType = {
500    PyObject_HEAD_INIT(NULL)
501    0,                         /*ob_size*/
502    "CFractalModel",             /*tp_name*/
503    sizeof(CFractalModel),             /*tp_basicsize*/
504    0,                         /*tp_itemsize*/
505    (destructor)CFractalModel_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    "CFractalModel 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    CFractalModel_methods,             /* tp_methods */
529    CFractalModel_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)CFractalModel_init,      /* tp_init */
537    0,                         /* tp_alloc */
538    CFractalModel_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 addCFractalModel(PyObject *module) {
551        PyObject *d;
552       
553    if (PyType_Ready(&CFractalModelType) < 0)
554        return;
555
556    Py_INCREF(&CFractalModelType);
557    PyModule_AddObject(module, "CFractalModel", (PyObject *)&CFractalModelType);
558   
559    d = PyModule_GetDict(module);
560    CFractalModelError = PyErr_NewException("CFractalModel.error", NULL, NULL);
561    PyDict_SetItemString(d, "CFractalModelError", CFractalModelError);
562}
563
Note: See TracBrowser for help on using the repository browser.