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