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

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

change the orientation of models

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