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

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 9ce41c6 was 9ce41c6, checked in by Gervaise Alina <gervyh@…>, 15 years ago

wrote unittest for all model untested , haven' test critial point error handling

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