source: sasview/sansmodels/src/sans/models/c_models/CBinaryHSModel.cpp @ 155c088

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 155c088 was 27972c1d, checked in by Jae Cho <jhjcho@…>, 15 years ago

removed all non asc font in the units

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