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