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

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 e0a8a3c was e0a8a3c, checked in by Gervaise Alina <gervyh@…>, 15 years ago

change the orientation of models

  • Property mode set to 100644
File size: 17.3 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 /**
168 * Function to call to evaluate model
169 * @param args: input numpy array  [x[],y[]]
170 * @return: numpy array object
171 */
172 static PyObject * evaluateTwoDimXY( DiamCylFunc* model, 
173                              PyArrayObject *x, PyArrayObject *y)
174 {
175    PyArrayObject *result;
176    int i,j, x_len, y_len, dims[2];
177    //check validity of input vectors
178    if (x->nd != 2 || x->descr->type_num != PyArray_DOUBLE
179        || y->nd != 2 || y->descr->type_num != PyArray_DOUBLE
180        || y->dimensions[1] != x->dimensions[0]){
181        const char * message= "evaluateTwoDimXY  expect 2 numpy arrays";
182        PyErr_SetString(PyExc_ValueError , message); 
183        return NULL;
184    }
185   
186        if (PyArray_Check(x) && PyArray_Check(y)) {
187               
188            x_len = dims[1]= x->dimensions[1];
189        y_len = dims[0]= y->dimensions[0];
190           
191            // Make a new double matrix of same dims
192        result=(PyArrayObject *) PyArray_FromDims(2,dims,NPY_DOUBLE);
193        if (result == NULL){
194            const char * message= "Could not create result ";
195        PyErr_SetString(PyExc_RuntimeError , message);
196            return NULL;
197            }
198       
199        /* Do the calculation. */
200        for ( j=0; j< y_len; j++) {
201            for ( i=0; i< x_len; i++) {
202                double x_value = *(double *)(x->data + i*x->strides[1]);
203                    double y_value = *(double *)(y->data + j*y->strides[0]);
204                        double *result_value = (double *)(result->data +
205                              i*result->strides[1] + j*result->strides[0]);
206                        *result_value = (*model)(x_value, y_value);
207            }           
208        }
209        return PyArray_Return(result); 
210       
211        }else{
212                    PyErr_SetString(CDiamCylFuncError, 
213                   "CDiamCylFunc.evaluateTwoDimXY couldn't run.");
214                return NULL;
215                }       
216}
217/**
218 *  evalDistribution function evaluate a model function with input vector
219 *  @param args: input q as vector or [qx, qy] where qx, qy are vectors
220 *
221 */ 
222static PyObject * evalDistribution(CDiamCylFunc *self, PyObject *args){
223        PyObject *qx, *qy;
224        PyArrayObject * pars;
225        int npars ,mpars;
226       
227        // Get parameters
228       
229            // Reader parameter dictionary
230    self->model->length = PyFloat_AsDouble( PyDict_GetItemString(self->params, "length") );
231    self->model->radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "radius") );
232    // Read in dispersion parameters
233    PyObject* disp_dict;
234    DispersionVisitor* visitor = new DispersionVisitor();
235    disp_dict = PyDict_GetItemString(self->dispersion, "radius");
236    self->model->radius.dispersion->accept_as_destination(visitor, self->model->radius.dispersion, disp_dict);
237    disp_dict = PyDict_GetItemString(self->dispersion, "length");
238    self->model->length.dispersion->accept_as_destination(visitor, self->model->length.dispersion, disp_dict);
239
240       
241        // Get input and determine whether we have to supply a 1D or 2D return value.
242        if ( !PyArg_ParseTuple(args,"O",&pars) ) {
243            PyErr_SetString(CDiamCylFuncError, 
244                "CDiamCylFunc.evalDistribution expects a q value.");
245                return NULL;
246        }
247    // Check params
248       
249    if(PyArray_Check(pars)==1) {
250               
251            // Length of list should 1 or 2
252            npars = pars->nd; 
253            if(npars==1) {
254                // input is a numpy array
255                if (PyArray_Check(pars)) {
256                        return evaluateOneDim(self->model, (PyArrayObject*)pars); 
257                    }
258                }else{
259                    PyErr_SetString(CDiamCylFuncError, 
260                   "CDiamCylFunc.evalDistribution expect numpy array of one dimension.");
261                return NULL;
262                }
263    }else if( PyList_Check(pars)==1) {
264        // Length of list should be 2 for I(qx,qy)
265            mpars = PyList_GET_SIZE(pars); 
266            if(mpars!=2) {
267                PyErr_SetString(CDiamCylFuncError, 
268                        "CDiamCylFunc.evalDistribution expects a list of dimension 2.");
269                return NULL;
270            }
271             qx = PyList_GET_ITEM(pars,0);
272             qy = PyList_GET_ITEM(pars,1);
273             if (PyArray_Check(qx) && PyArray_Check(qy)) {
274                 return evaluateTwoDimXY(self->model, (PyArrayObject*)qx,
275                           (PyArrayObject*)qy);
276                 }else{
277                    PyErr_SetString(CDiamCylFuncError, 
278                   "CDiamCylFunc.evalDistribution expect 2 numpy arrays in list.");
279                return NULL;
280             }
281        }
282        PyErr_SetString(CDiamCylFuncError, 
283                   "CDiamCylFunc.evalDistribution couln't be run.");
284        return NULL;
285       
286}
287
288/**
289 * Function to call to evaluate model
290 * @param args: input q or [q,phi]
291 * @return: function value
292 */
293static PyObject * run(CDiamCylFunc *self, PyObject *args) {
294        double q_value, phi_value;
295        PyObject* pars;
296        int npars;
297       
298        // Get parameters
299       
300            // Reader parameter dictionary
301    self->model->length = PyFloat_AsDouble( PyDict_GetItemString(self->params, "length") );
302    self->model->radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "radius") );
303    // Read in dispersion parameters
304    PyObject* disp_dict;
305    DispersionVisitor* visitor = new DispersionVisitor();
306    disp_dict = PyDict_GetItemString(self->dispersion, "radius");
307    self->model->radius.dispersion->accept_as_destination(visitor, self->model->radius.dispersion, disp_dict);
308    disp_dict = PyDict_GetItemString(self->dispersion, "length");
309    self->model->length.dispersion->accept_as_destination(visitor, self->model->length.dispersion, disp_dict);
310
311       
312        // Get input and determine whether we have to supply a 1D or 2D return value.
313        if ( !PyArg_ParseTuple(args,"O",&pars) ) {
314            PyErr_SetString(CDiamCylFuncError, 
315                "CDiamCylFunc.run expects a q value.");
316                return NULL;
317        }
318         
319        // Check params
320        if( PyList_Check(pars)==1) {
321               
322                // Length of list should be 2 for I(q,phi)
323            npars = PyList_GET_SIZE(pars); 
324            if(npars!=2) {
325                PyErr_SetString(CDiamCylFuncError, 
326                        "CDiamCylFunc.run expects a double or a list of dimension 2.");
327                return NULL;
328            }
329            // We have a vector q, get the q and phi values at which
330            // to evaluate I(q,phi)
331            q_value = CDiamCylFunc_readDouble(PyList_GET_ITEM(pars,0));
332            phi_value = CDiamCylFunc_readDouble(PyList_GET_ITEM(pars,1));
333            // Skip zero
334            if (q_value==0) {
335                return Py_BuildValue("d",0.0);
336            }
337                return Py_BuildValue("d",(*(self->model)).evaluate_rphi(q_value,phi_value));
338
339        } else {
340
341                // We have a scalar q, we will evaluate I(q)
342                q_value = CDiamCylFunc_readDouble(pars);               
343               
344                return Py_BuildValue("d",(*(self->model))(q_value));
345        }       
346}
347
348/**
349 * Function to call to evaluate model in cartesian coordinates
350 * @param args: input q or [qx, qy]]
351 * @return: function value
352 */
353static PyObject * runXY(CDiamCylFunc *self, PyObject *args) {
354        double qx_value, qy_value;
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        // Get input and determine whether we have to supply a 1D or 2D return value.
373        if ( !PyArg_ParseTuple(args,"O",&pars) ) {
374            PyErr_SetString(CDiamCylFuncError, 
375                "CDiamCylFunc.run expects a q value.");
376                return NULL;
377        }
378         
379        // Check params
380        if( PyList_Check(pars)==1) {
381               
382                // Length of list should be 2 for I(qx, qy))
383            npars = PyList_GET_SIZE(pars); 
384            if(npars!=2) {
385                PyErr_SetString(CDiamCylFuncError, 
386                        "CDiamCylFunc.run expects a double or a list of dimension 2.");
387                return NULL;
388            }
389            // We have a vector q, get the qx and qy values at which
390            // to evaluate I(qx,qy)
391            qx_value = CDiamCylFunc_readDouble(PyList_GET_ITEM(pars,0));
392            qy_value = CDiamCylFunc_readDouble(PyList_GET_ITEM(pars,1));
393            return Py_BuildValue("d",(*(self->model))(qx_value,qy_value));
394
395        } else {
396
397                // We have a scalar q, we will evaluate I(q)
398                qx_value = CDiamCylFunc_readDouble(pars);               
399               
400                return Py_BuildValue("d",(*(self->model))(qx_value));
401        }       
402}
403
404static PyObject * reset(CDiamCylFunc *self, PyObject *args) {
405   
406
407    return Py_BuildValue("d",0.0);
408}
409
410static PyObject * set_dispersion(CDiamCylFunc *self, PyObject *args) {
411        PyObject * disp;
412        const char * par_name;
413
414        if ( !PyArg_ParseTuple(args,"sO", &par_name, &disp) ) {
415            PyErr_SetString(CDiamCylFuncError,
416                "CDiamCylFunc.set_dispersion expects a DispersionModel object.");
417                return NULL;
418        }
419        void *temp = PyCObject_AsVoidPtr(disp);
420        DispersionModel * dispersion = static_cast<DispersionModel *>(temp);
421
422
423        // Ugliness necessary to go from python to C
424            // TODO: refactor this
425    if (!strcmp(par_name, "radius")) {
426        self->model->radius.dispersion = dispersion;
427    } else    if (!strcmp(par_name, "length")) {
428        self->model->length.dispersion = dispersion;
429    } else {
430            PyErr_SetString(CDiamCylFuncError,
431                "CDiamCylFunc.set_dispersion expects a valid parameter name.");
432                return NULL;
433        }
434
435        DispersionVisitor* visitor = new DispersionVisitor();
436        PyObject * disp_dict = PyDict_New();
437        dispersion->accept_as_source(visitor, dispersion, disp_dict);
438        PyDict_SetItemString(self->dispersion, par_name, disp_dict);
439    return Py_BuildValue("i",1);
440}
441
442
443static PyMethodDef CDiamCylFunc_methods[] = {
444    {"run",      (PyCFunction)run     , METH_VARARGS,
445      "Evaluate the model at a given Q or Q, phi"},
446    {"runXY",      (PyCFunction)runXY     , METH_VARARGS,
447      "Evaluate the model at a given Q or Qx, Qy"},
448     
449    {"evalDistribution",  (PyCFunction)evalDistribution , METH_VARARGS,
450      "Evaluate the model at a given Q or Qx, Qy vector "},
451    {"reset",    (PyCFunction)reset   , METH_VARARGS,
452      "Reset pair correlation"},
453    {"set_dispersion",      (PyCFunction)set_dispersion     , METH_VARARGS,
454      "Set the dispersion model for a given parameter"},
455   {NULL}
456};
457
458static PyTypeObject CDiamCylFuncType = {
459    PyObject_HEAD_INIT(NULL)
460    0,                         /*ob_size*/
461    "CDiamCylFunc",             /*tp_name*/
462    sizeof(CDiamCylFunc),             /*tp_basicsize*/
463    0,                         /*tp_itemsize*/
464    (destructor)CDiamCylFunc_dealloc, /*tp_dealloc*/
465    0,                         /*tp_print*/
466    0,                         /*tp_getattr*/
467    0,                         /*tp_setattr*/
468    0,                         /*tp_compare*/
469    0,                         /*tp_repr*/
470    0,                         /*tp_as_number*/
471    0,                         /*tp_as_sequence*/
472    0,                         /*tp_as_mapping*/
473    0,                         /*tp_hash */
474    0,                         /*tp_call*/
475    0,                         /*tp_str*/
476    0,                         /*tp_getattro*/
477    0,                         /*tp_setattro*/
478    0,                         /*tp_as_buffer*/
479    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
480    "CDiamCylFunc objects",           /* tp_doc */
481    0,                         /* tp_traverse */
482    0,                         /* tp_clear */
483    0,                         /* tp_richcompare */
484    0,                         /* tp_weaklistoffset */
485    0,                         /* tp_iter */
486    0,                         /* tp_iternext */
487    CDiamCylFunc_methods,             /* tp_methods */
488    CDiamCylFunc_members,             /* tp_members */
489    0,                         /* tp_getset */
490    0,                         /* tp_base */
491    0,                         /* tp_dict */
492    0,                         /* tp_descr_get */
493    0,                         /* tp_descr_set */
494    0,                         /* tp_dictoffset */
495    (initproc)CDiamCylFunc_init,      /* tp_init */
496    0,                         /* tp_alloc */
497    CDiamCylFunc_new,                 /* tp_new */
498};
499
500
501//static PyMethodDef module_methods[] = {
502//    {NULL}
503//};
504
505/**
506 * Function used to add the model class to a module
507 * @param module: module to add the class to
508 */ 
509void addCDiamCylFunc(PyObject *module) {
510        PyObject *d;
511       
512    if (PyType_Ready(&CDiamCylFuncType) < 0)
513        return;
514
515    Py_INCREF(&CDiamCylFuncType);
516    PyModule_AddObject(module, "CDiamCylFunc", (PyObject *)&CDiamCylFuncType);
517   
518    d = PyModule_GetDict(module);
519    CDiamCylFuncError = PyErr_NewException("CDiamCylFunc.error", NULL, NULL);
520    PyDict_SetItemString(d, "CDiamCylFuncError", CDiamCylFuncError);
521}
522
Note: See TracBrowser for help on using the repository browser.