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

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

change model orientation

  • Property mode set to 100644
File size: 17.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/** 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,"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->radius.dispersion->accept_as_source(visitor, self->model->radius.dispersion, disp_dict);
95        PyDict_SetItemString(self->dispersion, "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[0];
186        y_len = dims[0]= y->dimensions[1];
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[0]);
200                    double y_value = *(double *)(y->data + j*y->strides[1]);
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->radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "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, "radius");
233    self->model->radius.dispersion->accept_as_destination(visitor, self->model->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->radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "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, "radius");
302    self->model->radius.dispersion->accept_as_destination(visitor, self->model->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/**
342 * Function to call to evaluate model in cartesian coordinates
343 * @param args: input q or [qx, qy]]
344 * @return: function value
345 */
346static PyObject * runXY(CHardsphereStructure *self, PyObject *args) {
347        double qx_value, qy_value;
348        PyObject* pars;
349        int npars;
350       
351        // Get parameters
352       
353            // Reader parameter dictionary
354    self->model->radius = PyFloat_AsDouble( PyDict_GetItemString(self->params, "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, "radius");
360    self->model->radius.dispersion->accept_as_destination(visitor, self->model->radius.dispersion, disp_dict);
361
362       
363        // Get input and determine whether we have to supply a 1D or 2D return value.
364        if ( !PyArg_ParseTuple(args,"O",&pars) ) {
365            PyErr_SetString(CHardsphereStructureError, 
366                "CHardsphereStructure.run expects a q value.");
367                return NULL;
368        }
369         
370        // Check params
371        if( PyList_Check(pars)==1) {
372               
373                // Length of list should be 2 for I(qx, qy))
374            npars = PyList_GET_SIZE(pars); 
375            if(npars!=2) {
376                PyErr_SetString(CHardsphereStructureError, 
377                        "CHardsphereStructure.run expects a double or a list of dimension 2.");
378                return NULL;
379            }
380            // We have a vector q, get the qx and qy values at which
381            // to evaluate I(qx,qy)
382            qx_value = CHardsphereStructure_readDouble(PyList_GET_ITEM(pars,0));
383            qy_value = CHardsphereStructure_readDouble(PyList_GET_ITEM(pars,1));
384            return Py_BuildValue("d",(*(self->model))(qx_value,qy_value));
385
386        } else {
387
388                // We have a scalar q, we will evaluate I(q)
389                qx_value = CHardsphereStructure_readDouble(pars);               
390               
391                return Py_BuildValue("d",(*(self->model))(qx_value));
392        }       
393}
394
395static PyObject * reset(CHardsphereStructure *self, PyObject *args) {
396   
397
398    return Py_BuildValue("d",0.0);
399}
400
401static PyObject * set_dispersion(CHardsphereStructure *self, PyObject *args) {
402        PyObject * disp;
403        const char * par_name;
404
405        if ( !PyArg_ParseTuple(args,"sO", &par_name, &disp) ) {
406            PyErr_SetString(CHardsphereStructureError,
407                "CHardsphereStructure.set_dispersion expects a DispersionModel object.");
408                return NULL;
409        }
410        void *temp = PyCObject_AsVoidPtr(disp);
411        DispersionModel * dispersion = static_cast<DispersionModel *>(temp);
412
413
414        // Ugliness necessary to go from python to C
415            // TODO: refactor this
416    if (!strcmp(par_name, "radius")) {
417        self->model->radius.dispersion = dispersion;
418    } else {
419            PyErr_SetString(CHardsphereStructureError,
420                "CHardsphereStructure.set_dispersion expects a valid parameter name.");
421                return NULL;
422        }
423
424        DispersionVisitor* visitor = new DispersionVisitor();
425        PyObject * disp_dict = PyDict_New();
426        dispersion->accept_as_source(visitor, dispersion, disp_dict);
427        PyDict_SetItemString(self->dispersion, par_name, disp_dict);
428    return Py_BuildValue("i",1);
429}
430
431
432static PyMethodDef CHardsphereStructure_methods[] = {
433    {"run",      (PyCFunction)run     , METH_VARARGS,
434      "Evaluate the model at a given Q or Q, phi"},
435    {"runXY",      (PyCFunction)runXY     , METH_VARARGS,
436      "Evaluate the model at a given Q or Qx, Qy"},
437     
438    {"evalDistribution",  (PyCFunction)evalDistribution , METH_VARARGS,
439      "Evaluate the model at a given Q or Qx, Qy vector "},
440    {"reset",    (PyCFunction)reset   , METH_VARARGS,
441      "Reset pair correlation"},
442    {"set_dispersion",      (PyCFunction)set_dispersion     , METH_VARARGS,
443      "Set the dispersion model for a given parameter"},
444   {NULL}
445};
446
447static PyTypeObject CHardsphereStructureType = {
448    PyObject_HEAD_INIT(NULL)
449    0,                         /*ob_size*/
450    "CHardsphereStructure",             /*tp_name*/
451    sizeof(CHardsphereStructure),             /*tp_basicsize*/
452    0,                         /*tp_itemsize*/
453    (destructor)CHardsphereStructure_dealloc, /*tp_dealloc*/
454    0,                         /*tp_print*/
455    0,                         /*tp_getattr*/
456    0,                         /*tp_setattr*/
457    0,                         /*tp_compare*/
458    0,                         /*tp_repr*/
459    0,                         /*tp_as_number*/
460    0,                         /*tp_as_sequence*/
461    0,                         /*tp_as_mapping*/
462    0,                         /*tp_hash */
463    0,                         /*tp_call*/
464    0,                         /*tp_str*/
465    0,                         /*tp_getattro*/
466    0,                         /*tp_setattro*/
467    0,                         /*tp_as_buffer*/
468    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
469    "CHardsphereStructure objects",           /* tp_doc */
470    0,                         /* tp_traverse */
471    0,                         /* tp_clear */
472    0,                         /* tp_richcompare */
473    0,                         /* tp_weaklistoffset */
474    0,                         /* tp_iter */
475    0,                         /* tp_iternext */
476    CHardsphereStructure_methods,             /* tp_methods */
477    CHardsphereStructure_members,             /* tp_members */
478    0,                         /* tp_getset */
479    0,                         /* tp_base */
480    0,                         /* tp_dict */
481    0,                         /* tp_descr_get */
482    0,                         /* tp_descr_set */
483    0,                         /* tp_dictoffset */
484    (initproc)CHardsphereStructure_init,      /* tp_init */
485    0,                         /* tp_alloc */
486    CHardsphereStructure_new,                 /* tp_new */
487};
488
489
490//static PyMethodDef module_methods[] = {
491//    {NULL}
492//};
493
494/**
495 * Function used to add the model class to a module
496 * @param module: module to add the class to
497 */ 
498void addCHardsphereStructure(PyObject *module) {
499        PyObject *d;
500       
501    if (PyType_Ready(&CHardsphereStructureType) < 0)
502        return;
503
504    Py_INCREF(&CHardsphereStructureType);
505    PyModule_AddObject(module, "CHardsphereStructure", (PyObject *)&CHardsphereStructureType);
506   
507    d = PyModule_GetDict(module);
508    CHardsphereStructureError = PyErr_NewException("CHardsphereStructure.error", NULL, NULL);
509    PyDict_SetItemString(d, "CHardsphereStructureError", CHardsphereStructureError);
510}
511
Note: See TracBrowser for help on using the repository browser.