source: sasview/sansmodels/src/sans/models/c_models/CBinaryHSModel.cpp @ 1d67243

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