source: sasview/sansmodels/src/sans/models/c_models/CSquareWellStructure.cpp @ 5eb9154

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 5eb9154 was 5eb9154, checked in by Jae Cho <jhjcho@…>, 15 years ago

calculation of the effective radius are added

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