source: sasview/sansmodels/src/sans/models/c_models/CCoreShellModel.cpp @ 1d67243

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