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
This comment has been removed by the author.
ReplyDeleteThank you! Mike
ReplyDeleteHere is simple instruction for window users.
[Step 1]
Download swigwin-3.0.12.zip and extract zip at a specific folder.
ex) E:\Util\SWIG\swigwin-3.0.12\
[Step 2]
Move to folder which includes 3 files (RG.cpp, RG.h, RG.i)
[Step 3]
Execute below line in cmd
E:\Util\SWIG\swigwin-3.0.12\swig.exe -c++ -python RG.i
After that, 2 files(RG.py, RG_wrap.cxx) will be generated.
[Step 4]
Make a new Win32Project and select DLL in visual stduio 2015.
or Make a new Window Desktop Wizard ("Applcation type: .dll") in visual stuido 2017.
Select “empty project” and deactivate precompiled headers.
Add three files(RG.cpp, RG.h, RG_wrap.cxx) to solution
[Step 5]
Move to (Configuration) Properties(Alt + Enter) and Add below two things.
C/C++ > General > Additional Include Directories
C:\ProgramData\Anaconda3\include
Linker > Input > Additional Dependencies
C:\ProgramData\Anaconda3\libs\python36.lib
[Step 6]
Build Solution (Build Target Configuration: Release and Platform: x64)
For my case, RG.dll will be generated.
[Step 7]
Change the file name from "RG.dll" to "_RG.pyd"
[Step 8]
Copy two files(RG.py, _RG.pyd) to SwigTester Folder.
Mingwan, Thanks a lot for your efforts and participation!
Delete-Mike