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