If the need sometimes arises, existing C++ libraries can be interfaced relatively easy to be used in Python by using
SWIG wrapper. SWIG stands for Simplified Wrapper and Interface Generator
and it is an open-source software tool used to connect computer programs or libraries written in C or C++ with scripting languages, such as Python. As one extremely motivating example,
QuantLib C++ libraries have been made available for Python by using SWIG wrappers. Complete documentation for SWIG 3.0 can be found in
here. The actual SWIG package can be downloaded in
here. By taking a look at the documentation, one may understand quickly, that in this post only the tip of the iceberg will get scratched.
Also, it should be noted at this point, that this post is assuming all operations taking place in Linux environment. Corresponding instructions for Windows users can be found in SWIG documentation. This blog post is presenting, how to interface custom C++ random generator class to be used in Python. The original (template) class implementation can be found in
here.
Header and implementation files for simple C++ random number generator class are presented below.
Header file (RG.h)
#include <algorithm>
#include <functional>
#include <random>
class Generator {
public:
Generator(unsigned long seed);
void operator()(std::vector<double>& v);
private:
std::function<double(double)> randomGenerator;
std::normal_distribution<double> distribution;
std::mt19937 uniformGenerator;
};
Implementation file (RG.cpp)
#include "RG.h"
Generator::Generator(unsigned long seed) {
// construct lambda method for processing standard normal random number
randomGenerator = [this](double x)-> double {
x = distribution(uniformGenerator);
return x;
};
uniformGenerator.seed(seed);
}
// fill client-given vector with random variates from standard normal distribtuion
void Generator::operator()(std::vector<double>& v) {
std::transform(v.begin(), v.end(), v.begin(), randomGenerator);
}
The class functionality is simple and straightforward. First, create a class implementation by giving desired seed value in constructor. In constructor, C++ function object will be created. This function object will ultimately create our normally distributed random variates. Client will request a new set of random variates by giving a reference for
STL vector by using parenthesis operator, which has been overloaded here for syntactic reasons only.
SWIG interface file (RG.i)
A simple SWIG interface for our class can be built by simply wrapping the header file as follows.
%module RG
%{
#include "RG.h"
%}
%include "std_vector.i"
%template(DoubleVector) std::vector<double>;
%include "RG.h"
Python does not know anything about std::vector. The
std_vector.i library provides support for C++ STL vector class.
Then, all we need to do is to
instantiate different versions of vector for all the specific types we would like to use in Python. For our example class, we want to use vector consisting of double data types. Using this library involves the use of the
%template directive. In Python code, C++ vector will be used by using alias
DoubleVector.
SWIG build
All in all we have now three files in our folder: RG.h, RG.cpp and RG.i. With terminal opened in the folder consisting the previous three files, the following three commands will create Python wrapper for our C++ class.
$
swig -c++ -python RG.i
$
g++ -fpic -c -I/home/mikejuniperhill/anaconda3/include/python3.7m RG.cpp RG_wrap.cxx
$
g++ -shared RG.o RG_wrap.o -o _RG.so
In the second command, a correct parameter for -I argument can be found by using the following command in terminal.
$ python3-config --cflags
After these three steps, our C++ program can be accessed and used in Python program. The following simple example program is requesting a vector of standard normal random numbers from our wrapped C++ class and uses those for calculating Monte Carlo PV for one European call option.
# import RG module
import SwigTester.RG as RG
import numpy as np
# set seed, create generator object
seed = 0
generator = RG.Generator(seed)
# set vector size, initialize vector
steps = 1000
vector = RG.DoubleVector(steps)
# request generator to fill vector with standard normal variates
generator(vector)
# copy content to numpy array
e = np.array(vector)
# use variates to value one european call option
# set parameters
s0 = 100.0
x = 100.0
t = 1.25
v = 0.25
r = 0.01
# use vectorization in numpy, pre-calculate components
drift = (r - 0.5 * v * v) * t
diffusion = v * np.sqrt(t)
df = np.exp(-r * t)
# get option value as discounted average of all terminal payoffs
c0 = np.mean(np.maximum(s0 * np.exp(drift + diffusion * e) - x, 0.0)) * df
print(c0)
Note, that I imported SwigTester.RG, because I created Python wrapper module directly into this specific folder.
As a SWIG newcomer, one may expect to face all kinds of cryptic installation and other infuriating compatibility issues. As always, Google is the best friend along this cruel and unusual phase. But, have faith - and you'll be rewarded with all wonders and joys of SWIG wrapper.
All relevant files can be found directly from my
GitHub repository. Thanks for reading my blog.
-Mike