source: sasview/sansmodels/src/sans/models/c_models/CStickyHSStructure.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 9bd69098, checked in by Jae Cho <jhjcho@…>, 15 years ago

recompiled all due to Alina's new eval(run) function

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