source: sasview/sansmodels/src/sans/models/c_models/CSchulz.cpp @ 0b082f3

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

Re #7 Enable openmp for all models

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