File: libBornAgainFit.i

package info (click to toggle)
bornagain 23.0-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 103,956 kB
  • sloc: cpp: 423,131; python: 40,997; javascript: 11,167; awk: 630; sh: 356; ruby: 173; xml: 130; makefile: 45; ansic: 24
file content (301 lines) | stat: -rw-r--r-- 9,929 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
// ************************************************************************** //
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Wrap/Swig/libBornAgainFit.i
//! @brief     SWIG interface file for libBornAgainFit
//!
//!            Configuration is done in Fit/CMakeLists.txt
//!
//! @homepage  http://apps.jcns.fz-juelich.de/BornAgain
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2013
//! @authors   Scientific Computing Group at MLZ Garching
//
// ************************************************************************** //

%module(moduleimport="import $module") "libBornAgainFit"

%include "commons.i"

// %rename(minimize_cpp) mumufit::Minimizer::minimize;
%rename(add_cpp) mumufit::Parameters::add;

%{
#include "Fit/Kernel/Minimizer.h"
#include "Fit/Kernel/MinimizerFactory.h"
#include "Fit/Minimizer/IMinimizer.h"
%}

// The following goes verbatim from libBornAgainFit.i to libBornAgainFit_wrap.cxx.
// Note that the order matters, as base classes must be included before derived classes.

%include "Fit/Param/RealLimits.h"
%include "Fit/Param/AttLimits.h"
%include "Fit/Param/Parameter.h"
%include "Fit/Param/Parameters.h"
%include "Fit/Minimizer/IMinimizer.h"
%include "Fit/Minimizer/MinimizerResult.h"
%include "Fit/Kernel/MinimizerFactory.h"

//-----------------------------------------
// extensions for passing Python callbacks to build a simulation
//-----------------------------------------

// do not produce a Python interface to the auxiliary functions
%ignore BA_SWIG_convertPySequenceToVector;
%ignore BA_SWIG_pyCallWithParameters_Seq;
%ignore BA_SWIG_pyCallWithParameters_Float;

%inline
%{

// converts Python sequence to std::vector<double>
std::vector<double> BA_SWIG_convertPySequenceToVector(PyObject* seq)
{
    // check if object is None
    if (seq == nullptr || seq == Py_None)
        throw std::runtime_error("BA_SWIG_convertPySequenceToVector: input is None");

    // check for __len__ method
    if (!PyObject_HasAttrString(seq, "__len__"))
        throw std::runtime_error("BA_SWIG_convertPySequenceToVector: "
          "input object does not have __len__ attribute");

    // check for __getitem__ method
    if (!PyObject_HasAttrString(seq, "__getitem__"))
        throw std::runtime_error("BA_SWIG_convertPySequenceToVector: "
          "input object does not have __getitem__ attribute");

    // obtain the length of the sequence
    Py_ssize_t length = PyObject_Length(seq);
    if (length < 0)
        throw std::runtime_error("BA_SWIG_convertPySequenceToVector: "
          "sequence has negative length");

    // vector to hold the data
    std::vector<double> resultVec;
    resultVec.reserve(static_cast<int>(length));

    // convert each sequence element to double
    for (Py_ssize_t i = 0; i < length; i++) {
        // item at index i
        PyObject* item = PyObject_GetItem(seq, PyLong_FromSsize_t(i));
        if (item == nullptr)
            throw std::runtime_error("BA_SWIG_convertPySequenceToVector: "
              "failed to obtain item at index " + std::to_string(i));

        // convert to double
        double value;
        if (PyFloat_Check(item))
            value = PyFloat_AsDouble(item);
        else if (PyLong_Check(item))
            value = PyLong_AsDouble(item);
        else {
            Py_DECREF(item);
            throw std::runtime_error("BA_SWIG_convertPySequenceToVector: "
              "sequence contains non-numeric item at index " + std::to_string(i));
        }

        if (PyErr_Occurred()) {
            Py_DECREF(item);
            throw std::runtime_error("BA_SWIG_convertPySequenceToVector: "
              "error converting item to double at index " + std::to_string(i));
        }

        Py_DECREF(item);
        resultVec.push_back(value);
    }

    return resultVec;
}

std::vector<double> BA_SWIG_pyCallWithParameters_Seq(PyObject* pyFunc,
                                                     const mumufit::Parameters& parameters)
{
    // execute a Python function which accepts a Parameters instance
    // as its single input argument

    if (!PyCallable_Check(pyFunc))
        PyErr_SetString(PyExc_TypeError,
          "BA_SWIG_pyCallWithParameters_Seq: first argument must be a Python callable");

    // make a Python-wrapped Parameters instance
    // NOTE: PyObject* SWIG_NewPointerObj(void* ptr, swig_type_info* ty, int own)
    // creates a new Python pointer object.
    mumufit::Parameters* parameters_ptr = const_cast<mumufit::Parameters*>(&parameters);
    swig_type_info* pTypeInfo = SWIG_TypeQuery("mumufit::Parameters*");
    PyObject* arg1 = SWIG_NewPointerObj(SWIG_as_voidptr(parameters_ptr), pTypeInfo, 0);

    // call the Python function with the Parameters Python-object as argument
    PyObject* pResult = PyObject_CallFunctionObjArgs(pyFunc, arg1, NULL);
    Py_DECREF(arg1);

    if (!pResult)
        PyErr_SetString(PyExc_RuntimeError,
          "BA_SWIG_pyCallWithParameters_Seq: calling Python function failed.");

    // made a std::vector from the call result
    std::vector<double> resultVec { BA_SWIG_convertPySequenceToVector(pResult) };
    Py_DECREF(pResult);

    return resultVec;
}

double BA_SWIG_pyCallWithParameters_Float(PyObject* pyFunc,
                                          const mumufit::Parameters& parameters)
{
    // execute a Python function which accepts a Parameters instance
    // as its single input argument

    if (!PyCallable_Check(pyFunc))
        PyErr_SetString(PyExc_TypeError,
          "BA_SWIG_pyCallWithParameters_Float: first argument must be a Python callable");

    // make a Python-wrapped Parameters instance
    // NOTE: PyObject* SWIG_NewPointerObj(void* ptr, swig_type_info* ty, int own)
    // creates a new Python pointer object.
    mumufit::Parameters* parameters_ptr = const_cast<mumufit::Parameters*>(&parameters);
    swig_type_info* pTypeInfo = SWIG_TypeQuery("mumufit::Parameters*");
    PyObject* arg1 = SWIG_NewPointerObj(SWIG_as_voidptr(parameters_ptr), pTypeInfo, 0);

    // call the Python function with the Parameters Python-object as argument
    PyObject* pResult = PyObject_CallFunctionObjArgs(pyFunc, arg1, NULL);
    Py_DECREF(arg1);

    if (!pResult)
        PyErr_SetString(PyExc_RuntimeError,
          "BA_SWIG_pyCallWithParameters_Float: calling Python function failed.");

    // made a double from the call result
    const double value = PyFloat_AsDouble(pResult);
    Py_DECREF(pResult);

    return value;
}

%}


namespace mumufit {

//--- Parameter x.value attribute
%extend Parameter{

%pythoncode %{
#--- Parameter x.value attribute
value = property(value, setValue)
error = property(error, setError)
%}

};

// Parameters accessors
%extend Parameters {
    const Parameter& __getitem__(std::string name) const
    {
        return (*($self))[name];
    }
    const Parameter& __getitem__(size_t index) const
    {
        return (*($self))[index];
    }

%pythoncode %{

def __iter__(self):
    self._index = -1
    return self

def __next__(self):
    self._index += 1
    if self._index < self.size():
        return self[self._index]
    else:
        raise StopIteration

def add(self, name, value=None, vary=True,
        min=-float('inf'), max=float('inf'), step=0.0):
    par = None
    if isinstance(name, Parameter):
        par = name
    else:
        limits = AttLimits.limitless()
        if min != -float('inf') and max != float('inf'):
            limits = AttLimits.limited(min, max)
        elif min != -float('inf') and max == float('inf'):
            limits = AttLimits.lowerLimited(min)
        elif min == -float('inf') and max != float('inf'):
            limits = AttLimits.upperLimited(max)
        if not vary:
            limits = AttLimits.fixed()
        par = Parameter(name, value, limits, step)

    self.add_cpp(par)
%}
};

}


%include "Fit/Kernel/Minimizer.h"

// --- Setting up Minimizer callback ---

namespace mumufit {

%extend Minimizer {

mumufit::MinimizerResult _minimizeWithPyCallable_SCALAR(
    PyObject* pCallable, const mumufit::Parameters& parameters)
{
    fcn_scalar_t fcn = [pCallable](const mumufit::Parameters& pars)
        { return BA_SWIG_pyCallWithParameters_Float(pCallable, pars); };
    return $self->minimize(fcn, parameters);
}

mumufit::MinimizerResult _minimizeWithPyCallable_SEQUENCE(
    PyObject* pCallable, const mumufit::Parameters& parameters)
{
    fcn_residual_t fcn = [pCallable](const mumufit::Parameters& pars)
        { return BA_SWIG_pyCallWithParameters_Seq(pCallable, pars); };
    return $self->minimize(fcn, parameters);
}

};


%pythoncode %{

class Minimizer(Minimizer):
    def __init__(self):
        super().__init__();
        # NOTE: Callback functions must be available during the lifetime of
        # the Minimizer instance; therefore, they are stored internally.
        self._min_fs = []

    @staticmethod
    def _isPySequence(obj):
        """ Checks if a Python object is a sequence """
        return (hasattr(obj, '__len__') and hasattr(obj, '__getitem__'))

    def minimize(self, pyCallable:'objective fn', pars):
        if not callable(pyCallable):
            raise Exception("Minimizer (Python API): "
                            "The first argument is not a Python callable")

        # single call to the callable to check return type
        result = pyCallable(pars)

        if isinstance(result, float):
            self._min_fs.append(pyCallable)
            return self._minimizeWithPyCallable_SCALAR(pyCallable, pars)
        elif Minimizer._isPySequence(result):
            self._min_fs.append(pyCallable)
            return self._minimizeWithPyCallable_SEQUENCE(pyCallable, pars)
        else:
            raise Exception("Minimizer (Python API): Wrong callable type; "
                "the return value must be either a Python float or sequence")
%}

} // namespace mumufit