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

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