source: sasview/sansmodels/src/sans/models/c_models/CSchulz.cpp @ 00c2141

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 00c2141 was 00c2141, checked in by Mathieu Doucet <doucetm@…>, 12 years ago

Re #4 Fixing a few more warnings

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