source: sasview/sansmodels/src/sans/models/c_models/CHayterMSAStructure.cpp @ 01de557

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 01de557 was 0b082f3, checked in by Mathieu Doucet <doucetm@…>, 13 years ago

Re #7 Enable openmp for all models

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