source: sasview/sansmodels/src/sans/models/c_models/CHayterMSAStructure.cpp @ 870f131

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

change model orientation

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