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

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

wrote unittest for all model untested , haven' test critial point error handling

  • 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    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                              j*result->strides[0] + i*result->strides[1]);
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 * Function to call to calculate_ER
349 * @return: effective radius value
350 */
351static PyObject * calculate_ER(CDiamCylFunc *self) {
352
353        PyObject* pars;
354        int npars;
355       
356        // Get parameters
357       
358            // Reader parameter dictionary
359    self->model->length = PyFloat_AsDouble( PyDict_GetItemString(self->params, "length") );
360    self->model->radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "radius") );
361    // Read in dispersion parameters
362    PyObject* disp_dict;
363    DispersionVisitor* visitor = new DispersionVisitor();
364    disp_dict = PyDict_GetItemString(self->dispersion, "radius");
365    self->model->radius.dispersion->accept_as_destination(visitor, self->model->radius.dispersion, disp_dict);
366    disp_dict = PyDict_GetItemString(self->dispersion, "length");
367    self->model->length.dispersion->accept_as_destination(visitor, self->model->length.dispersion, disp_dict);
368
369               
370        return Py_BuildValue("d",(*(self->model)).calculate_ER());
371
372}
373/**
374 * Function to call to evaluate model in cartesian coordinates
375 * @param args: input q or [qx, qy]]
376 * @return: function value
377 */
378static PyObject * runXY(CDiamCylFunc *self, PyObject *args) {
379        double qx_value, qy_value;
380        PyObject* pars;
381        int npars;
382       
383        // Get parameters
384       
385            // Reader parameter dictionary
386    self->model->length = PyFloat_AsDouble( PyDict_GetItemString(self->params, "length") );
387    self->model->radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "radius") );
388    // Read in dispersion parameters
389    PyObject* disp_dict;
390    DispersionVisitor* visitor = new DispersionVisitor();
391    disp_dict = PyDict_GetItemString(self->dispersion, "radius");
392    self->model->radius.dispersion->accept_as_destination(visitor, self->model->radius.dispersion, disp_dict);
393    disp_dict = PyDict_GetItemString(self->dispersion, "length");
394    self->model->length.dispersion->accept_as_destination(visitor, self->model->length.dispersion, disp_dict);
395
396       
397        // Get input and determine whether we have to supply a 1D or 2D return value.
398        if ( !PyArg_ParseTuple(args,"O",&pars) ) {
399            PyErr_SetString(CDiamCylFuncError, 
400                "CDiamCylFunc.run expects a q value.");
401                return NULL;
402        }
403         
404        // Check params
405        if( PyList_Check(pars)==1) {
406               
407                // Length of list should be 2 for I(qx, qy))
408            npars = PyList_GET_SIZE(pars); 
409            if(npars!=2) {
410                PyErr_SetString(CDiamCylFuncError, 
411                        "CDiamCylFunc.run expects a double or a list of dimension 2.");
412                return NULL;
413            }
414            // We have a vector q, get the qx and qy values at which
415            // to evaluate I(qx,qy)
416            qx_value = CDiamCylFunc_readDouble(PyList_GET_ITEM(pars,0));
417            qy_value = CDiamCylFunc_readDouble(PyList_GET_ITEM(pars,1));
418            return Py_BuildValue("d",(*(self->model))(qx_value,qy_value));
419
420        } else {
421
422                // We have a scalar q, we will evaluate I(q)
423                qx_value = CDiamCylFunc_readDouble(pars);               
424               
425                return Py_BuildValue("d",(*(self->model))(qx_value));
426        }       
427}
428
429static PyObject * reset(CDiamCylFunc *self, PyObject *args) {
430   
431
432    return Py_BuildValue("d",0.0);
433}
434
435static PyObject * set_dispersion(CDiamCylFunc *self, PyObject *args) {
436        PyObject * disp;
437        const char * par_name;
438
439        if ( !PyArg_ParseTuple(args,"sO", &par_name, &disp) ) {
440            PyErr_SetString(CDiamCylFuncError,
441                "CDiamCylFunc.set_dispersion expects a DispersionModel object.");
442                return NULL;
443        }
444        void *temp = PyCObject_AsVoidPtr(disp);
445        DispersionModel * dispersion = static_cast<DispersionModel *>(temp);
446
447
448        // Ugliness necessary to go from python to C
449            // TODO: refactor this
450    if (!strcmp(par_name, "radius")) {
451        self->model->radius.dispersion = dispersion;
452    } else    if (!strcmp(par_name, "length")) {
453        self->model->length.dispersion = dispersion;
454    } else {
455            PyErr_SetString(CDiamCylFuncError,
456                "CDiamCylFunc.set_dispersion expects a valid parameter name.");
457                return NULL;
458        }
459
460        DispersionVisitor* visitor = new DispersionVisitor();
461        PyObject * disp_dict = PyDict_New();
462        dispersion->accept_as_source(visitor, dispersion, disp_dict);
463        PyDict_SetItemString(self->dispersion, par_name, disp_dict);
464    return Py_BuildValue("i",1);
465}
466
467
468static PyMethodDef CDiamCylFunc_methods[] = {
469    {"run",      (PyCFunction)run     , METH_VARARGS,
470      "Evaluate the model at a given Q or Q, phi"},
471    {"runXY",      (PyCFunction)runXY     , METH_VARARGS,
472      "Evaluate the model at a given Q or Qx, Qy"},
473    {"calculate_ER",      (PyCFunction)calculate_ER     , METH_VARARGS,
474      "Evaluate the model at a given Q or Q, phi"},
475     
476    {"evalDistribution",  (PyCFunction)evalDistribution , METH_VARARGS,
477      "Evaluate the model at a given Q or Qx, Qy vector "},
478    {"reset",    (PyCFunction)reset   , METH_VARARGS,
479      "Reset pair correlation"},
480    {"set_dispersion",      (PyCFunction)set_dispersion     , METH_VARARGS,
481      "Set the dispersion model for a given parameter"},
482   {NULL}
483};
484
485static PyTypeObject CDiamCylFuncType = {
486    PyObject_HEAD_INIT(NULL)
487    0,                         /*ob_size*/
488    "CDiamCylFunc",             /*tp_name*/
489    sizeof(CDiamCylFunc),             /*tp_basicsize*/
490    0,                         /*tp_itemsize*/
491    (destructor)CDiamCylFunc_dealloc, /*tp_dealloc*/
492    0,                         /*tp_print*/
493    0,                         /*tp_getattr*/
494    0,                         /*tp_setattr*/
495    0,                         /*tp_compare*/
496    0,                         /*tp_repr*/
497    0,                         /*tp_as_number*/
498    0,                         /*tp_as_sequence*/
499    0,                         /*tp_as_mapping*/
500    0,                         /*tp_hash */
501    0,                         /*tp_call*/
502    0,                         /*tp_str*/
503    0,                         /*tp_getattro*/
504    0,                         /*tp_setattro*/
505    0,                         /*tp_as_buffer*/
506    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
507    "CDiamCylFunc objects",           /* tp_doc */
508    0,                         /* tp_traverse */
509    0,                         /* tp_clear */
510    0,                         /* tp_richcompare */
511    0,                         /* tp_weaklistoffset */
512    0,                         /* tp_iter */
513    0,                         /* tp_iternext */
514    CDiamCylFunc_methods,             /* tp_methods */
515    CDiamCylFunc_members,             /* tp_members */
516    0,                         /* tp_getset */
517    0,                         /* tp_base */
518    0,                         /* tp_dict */
519    0,                         /* tp_descr_get */
520    0,                         /* tp_descr_set */
521    0,                         /* tp_dictoffset */
522    (initproc)CDiamCylFunc_init,      /* tp_init */
523    0,                         /* tp_alloc */
524    CDiamCylFunc_new,                 /* tp_new */
525};
526
527
528//static PyMethodDef module_methods[] = {
529//    {NULL}
530//};
531
532/**
533 * Function used to add the model class to a module
534 * @param module: module to add the class to
535 */ 
536void addCDiamCylFunc(PyObject *module) {
537        PyObject *d;
538       
539    if (PyType_Ready(&CDiamCylFuncType) < 0)
540        return;
541
542    Py_INCREF(&CDiamCylFuncType);
543    PyModule_AddObject(module, "CDiamCylFunc", (PyObject *)&CDiamCylFuncType);
544   
545    d = PyModule_GetDict(module);
546    CDiamCylFuncError = PyErr_NewException("CDiamCylFunc.error", NULL, NULL);
547    PyDict_SetItemString(d, "CDiamCylFuncError", CDiamCylFuncError);
548}
549
Note: See TracBrowser for help on using the repository browser.