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