source: sasview/sansmodels/src/sans/models/c_models/CSphereModel.cpp @ 27953d1

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 27953d1 was 975ec8e, checked in by Jae Cho <jhjcho@…>, 15 years ago

working on 2D models. Still need smore corrections and unit tests.

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