source: sasview/sansmodels/src/sans/models/c_models/CDiamCylFunc.cpp @ 34c2649

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