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 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
|
// ************************************************************************** //
//
// BornAgain: simulate and fit reflection and scattering
//
//! @file Wrap/Swig/libBornAgainSim.i
//! @brief SWIG interface file for libBornAgainSim
//!
//! Configuration is done in Sim/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") "libBornAgainSim"
%include "commons.i"
%import(module="libBornAgainFit") ""
%{
#include "BAVersion.h"
#include "Base/Axis/Scale.h"
#include "Base/Axis/Frame.h"
#include "Device/Data/Datafield.h"
#include "Fit/Minimizer/MinimizerResult.h"
#include "Sample/Scattering/ISampleNode.h"
#include "Sim/Background/ConstantBackground.h"
#include "Sim/Background/PoissonBackground.h"
#include "Sim/Export/ExportToPython.h"
#include "Sim/Fitting/FitObjective.h"
#include "Sim/Fitting/IterationInfo.h"
#include "Sim/Fitting/SimDataPair.h"
#include "Sim/Residual/ChiSquaredModule.h"
#include "Sim/Residual/IIntensityFunction.h"
#include "Sim/Residual/VarianceFunctions.h"
#include "Sim/Scan/AlphaScan.h"
#include "Sim/Scan/LambdaScan.h"
#include "Sim/Scan/QzScan.h"
#include "Sim/Simulation/DepthprobeSimulation.h"
#include "Sim/Simulation/ScatteringSimulation.h"
#include "Sim/Simulation/OffspecSimulation.h"
#include "Sim/Simulation/SpecularSimulation.h"
%}
// The following goes verbatim from libBornAgainSim.i to libBornAgainSim_wrap.cxx.
// Note that the order matters, as base classes must be included before derived classes.
%include "fromBase.i"
%include "fromParam.i"
%import(module="libBornAgainSample") "Sample/Scattering/ISampleNode.h"
%import(module="libBornAgainDevice") "Device/Data/Datafield.h"
%include "BAVersion.h"
%include "Sim/Fitting/IterationInfo.h"
%include "Sim/Scan/BeamScan.h"
%include "Sim/Scan/PhysicalScan.h"
%include "Sim/Scan/AlphaScan.h"
%include "Sim/Scan/LambdaScan.h"
%include "Sim/Scan/QzScan.h"
%include "Sim/Simulation/ISimulation.h"
%include "Sim/Simulation/ScatteringSimulation.h"
%include "Sim/Simulation/DepthprobeSimulation.h"
%include "Sim/Simulation/SpecularSimulation.h"
%include "Sim/Simulation/OffspecSimulation.h"
%include "Sim/Background/IBackground.h"
%include "Sim/Background/ConstantBackground.h"
%include "Sim/Background/PoissonBackground.h"
%include "Sim/Export/ExportToPython.h"
%include "Sim/Residual/IIntensityFunction.h"
%include "Sim/Residual/IChiSquaredModule.h"
%include "Sim/Residual/ChiSquaredModule.h"
%include "Sim/Residual/VarianceFunctions.h"
%extend Vec3<double> {
Vec3<double> __add__(const Vec3<double>& rhs) const {
return *($self) + rhs; }
Vec3<double> __mul__(double c) const {
return c * *($self); }
Vec3<double> __rmul__(double c) const {
return *($self) * c; }
Vec3<double> __neg__() const {
return - *($self); }
};
//-----------------------------------------
// extensions for passing Python callbacks to build a simulation
//-----------------------------------------
// do not produce a Python interface to the auxiliary functions
%ignore BA_SWIG_ISimulationfromPyObject;
%ignore BA_SWIG_exePySimulation;
%ignore BA_SWIG_discardPyObject;
%ignore BA_SWIG_PrintFunctionName;
%ignore BA_SWIG_pyCallWithFitObjective;
%inline
%{
void BA_SWIG_PrintFunctionName(PyObject* pCallable)
{
// get the '__name__' attribute of a callable Python object;
// used for debugging purposes only.
PyObject* pName = PyObject_GetAttrString(pCallable, "__name__");
if (pName && PyUnicode_Check(pName)) {
// convert Python string to C-string
const char* fnName = PyUnicode_AsUTF8(pName);
printf("[BornAgain] Python function name: '%s'\n", fnName);
Py_DECREF(pName);
} else {
Py_XDECREF(pName);
PyErr_SetString(PyExc_TypeError,
"BA_SWIG_PrintFunctionName: "
"Could not retrieve the name of the Python function");
}
}
ISimulation* BA_SWIG_ISimulationfromPyObject(PyObject* pyObject)
{
// construct a C++ object from the Python object;
// this conversion requires a SWIG-produced Python API
const char typeName[] = "ISimulation*";
void* argp1 = nullptr;
swig_type_info* pTypeInfo = SWIG_TypeQuery(typeName);
const int res = SWIG_ConvertPtr(pyObject, &argp1, pTypeInfo, 0);
if (!SWIG_IsOK(res)) {
throw std::runtime_error(
"BA_SWIG_ISimulationfromPyObject: "
"The given Python object did not yield an ISimulation instance");
}
return reinterpret_cast<ISimulation*>(argp1);
}
void BA_SWIG_exePySimulation(void* pSimulationCallable, const mumufit::Parameters& params,
ISimulation*& sim, void*& pyObject)
{
// call a Python function with signature:
// fn(Parameters:dict) -> Python-Object which wraps a C++ ISimulation instance
PyObject* pyFunc = reinterpret_cast<PyObject*>(pSimulationCallable);
// prepare arguments for the Python function
PyObject* params_dict = PyDict_New();
for (const mumufit::Parameter& p : params)
PyDict_SetItemString(params_dict, p.name().c_str(), PyFloat_FromDouble(p.value()));
#ifdef DEBUG
if (!PyCallable_Check(pyFunc)) {
PyErr_SetString(PyExc_TypeError,
"BA_SWIG_exePySimulation: First argument must be a Python callable "
"with signature\n"
"fn(Parameters:dict) -> ISimulation");
return;
}
BA_SWIG_PrintFunctionName(pyFunc);
#endif // DEBUG
// call the Python function with arguments
PyObject* pResult = PyObject_CallFunctionObjArgs(pyFunc, params_dict, NULL);
Py_DECREF(params_dict);
if (!pResult) {
PyErr_SetString(PyExc_TypeError,
"BA_SWIG_exePySimulation: execution of Python simulation function failed.");
return;
}
pyObject = reinterpret_cast<void*>(pResult);
sim = BA_SWIG_ISimulationfromPyObject(pResult);
// NOTE: The caller is responsible for memory management of `pyObject` and `sim`
}
void BA_SWIG_discardPyObject(void* pObject)
{
// discard a PythonObject
Py_XDECREF(reinterpret_cast<PyObject*>(pObject));
}
void BA_SWIG_pyCallWithFitObjective(void* pFunc, const FitObjective& fit_objective)
{
// execute a Python function which accepts a FitObjective instance
// as its single input argument
PyObject* pyFunc = reinterpret_cast<PyObject*>(pFunc);
if (!PyCallable_Check(pyFunc)) {
PyErr_SetString(PyExc_TypeError,
"BA_SWIG_pyCallWithFitObjective: first argument must be a Python callable");
return;
}
// make a Python-wrapped FitObjective instance
// NOTE: PyObject* SWIG_NewPointerObj(void* ptr, swig_type_info* ty, int own)
// creates a new Python pointer object.
FitObjective* fitObjective_ptr = const_cast<FitObjective*>(&fit_objective);
PyObject* arg1 = SWIG_NewPointerObj(
SWIG_as_voidptr(fitObjective_ptr), SWIGTYPE_p_FitObjective, 0);
PyObject* pResult = PyObject_CallFunctionObjArgs(pyFunc, arg1, NULL);
Py_DECREF(arg1);
if (!pResult) {
PyErr_SetString(PyExc_RuntimeError,
"BA_SWIG_pyCallWithFitObjective: calling Python function failed.");
return;
}
Py_DECREF(pResult);
}
%}
//-- FitObjective
%include "Sim/Fitting/FitObjective.h"
// extend FitObjective with method to add a Python simulation-builder function
%extend FitObjective {
void addPyFitPair(PyObject* pSimulationCallable, const Datafield& expData, const double weight)
{
// verify that the given Python object is callable
if (!PyCallable_Check(pSimulationCallable)) {
PyErr_SetString(PyExc_TypeError,
"FitObjective.addFitPair (SWIG): First argument must be a Python callable "
"with signature\n"
"fn(Parameters:dict) -> ISimulation");
return;
}
#ifdef DEBUG
BA_SWIG_PrintFunctionName(pSimulationCallable);
#endif
$self->addFitPair(reinterpret_cast<void*>(pSimulationCallable),
BA_SWIG_exePySimulation, BA_SWIG_discardPyObject, expData, weight);
}
void _initPyPlot(int every_nth, PyObject* pUpdateCallable)
{
// verify that the given Python object is callable
if (!PyCallable_Check(pUpdateCallable)) {
PyErr_SetString(PyExc_TypeError,
"FitObjective._initPyPlot (SWIG): First argument must be a Python callable "
"with signature\n"
"fn(FitObjective) -> None");
return;
}
#ifdef DEBUG
BA_SWIG_PrintFunctionName(pUpdateCallable);
#endif
$self->initPlot(every_nth, reinterpret_cast<void*>(pUpdateCallable),
BA_SWIG_pyCallWithFitObjective);
}
};
// extend the Python class
%pythoncode %{
class FitObjective(FitObjective):
""" Python extention to C++ class FitObjective
NOTE: The module requires libBornAgainFit.
"""
def __init__(self):
super().__init__()
# NOTE: Callback functions must be available during the lifetime of
# the FitObjective instance; therefore, they are stored internally.
self._sim_fs = []
self._plot_fs = []
def addFitPair(self, pySimulationFn, expData, weight = 1.0):
"""
Sets simulation and experimental data to the fit objective.
Optionally accepts experimental data uncertainties and
user-defined dataset weight.
Arguments:
pySimulationFn: a user-defined function that takes a fit-parameter
dict as input, and returns a BornAgain.ISimulation object.
expData: a Datafield containing experimental data.
weight: user-defined weight of the dataset.
"""
self._sim_fs.append(pySimulationFn)
super().addPyFitPair(pySimulationFn, expData, weight) # calls the extension function defined above
def evaluate(self, params):
return super().evaluate(FitObjective._convert_params(params))
def evaluate_residuals(self, params):
return super().evaluate_residuals(FitObjective._convert_params(params))
def finalize(self, minimizer_result):
return super().finalize(FitObjective._convert_result(minimizer_result))
@staticmethod
def _convert_params(params):
"""
Converts parameters to what FitObjective::evaluate expects
"""
if str(params.__module__) != "lmfit.parameter":
return params
bapars = libBornAgainFit.Parameters()
for p in params:
bapars.add(p, params[p].value)
return bapars
@staticmethod
def _convert_result(minim_result):
"""
Converts result reported by arbitrary minimizer to ba.MinimizerResult
"""
# NOTE: needs libBornAgainFit
if str(minim_result.__module__) == "lmfit.minimizer":
return libBornAgainFit.MinimizerResult()
else:
return minim_result
def initPlot(self, every_nth, plot_callback):
self._plot_fs.append(plot_callback)
return self._initPyPlot(every_nth, plot_callback)
%};
|