source: sasview/sansmodels/src/sans/models/c_models/CLamellarModel.cpp @ 27953d1

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 27953d1 was 975ec8e, checked in by Jae Cho <jhjcho@…>, 15 years ago

working on 2D models. Still need smore corrections and unit tests.

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