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