source: sasview/sansmodels/src/sans/models/c_models/CHayterMSAStructure.cpp @ 1d67243

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 1d67243 was 9bd69098, checked in by Jae Cho <jhjcho@…>, 15 years ago

recompiled all due to Alina's new eval(run) function

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