source: sasview/sansmodels/src/sans/models/c_models/CSchulz.cpp @ 2e38ebb

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 2e38ebb was 71e2de7, checked in by Gervaise Alina <gervyh@…>, 15 years ago

change destructor for models

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