source: sasview/sansmodels/src/sans/models/c_models/CHardsphereStructure.cpp @ c451be9

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

change destructor for models

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