source: sasview/sansmodels/src/sans/models/c_models/CDiamCylFunc.cpp @ 58c6ba6

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 58c6ba6 was 9bd69098, checked in by Jae Cho <jhjcho@…>, 15 years ago

recompiled all due to Alina's new eval(run) function

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