source: sasview/sansmodels/src/sans/models/c_models/CLamellarPSModel.cpp @ 9bd69098

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