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

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 ab87b61 was ab87b61, checked in by Mathieu Doucet <doucetm@…>, 12 years ago

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