source: sasview/sansmodels/src/sans/models/c_models/CHardsphereStructure.cpp @ afea8fe

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 afea8fe was 35aface, checked in by Jae Cho <jhjcho@…>, 14 years ago

addede new models and attr. non_fittable

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