Slide 1

Slide 1 text

Pybind11でC++とPythonの いいとこ取りをする 2020/09/13 OSK 9月LT会 @yumcyawiz

Slide 2

Slide 2 text

Motivation Pythonはnumpyとかmatplotlibとか色々あって便利!

Slide 3

Slide 3 text

Motivation だけど複雑な計算を実装すると遅い・・

Slide 4

Slide 4 text

Motivation 一方でC++は計算早いけど、可視化とか不便・・

Slide 5

Slide 5 text

Motivation C++で計算を実装して、Pythonで可視化できないか?

Slide 6

Slide 6 text

No content

Slide 7

Slide 7 text

• C++・Python間で互いのデータ型・関数を扱えるように するC++のHeader Onlyライブラリ • STLのデータ型もサポート • numpyのデータ型も扱える

Slide 8

Slide 8 text

Usage - Setup

Slide 9

Slide 9 text

Project Setup • 今回はC++側でMyLibという名 前の静的ライブラリを作成 • Python側でMyLibを呼び出せる ようにしたい

Slide 10

Slide 10 text

Project Setup - CMake • CMakeを使ってpybind11を導入 • Python Bindingをbinding.cppに 記述 • pybind11_add_moduleで binding.cppをソースに指定

Slide 11

Slide 11 text

Project Setup - Build • ビルドするとMyLib.*.soが生成 される • Python Scriptと同じディレクト リに置けばimport Mylibできる

Slide 12

Slide 12 text

Usage - Function

Slide 13

Slide 13 text

Function mylib.cpp binding.cpp Binding.cppにPython Bindingを記述していく

Slide 14

Slide 14 text

Function binding.cpp Python側から呼び出せる test.py

Slide 15

Slide 15 text

Function – default argument binding.cpp 名前付き引数&デフォルト引数も設定可能 mylib.h

Slide 16

Slide 16 text

Function – reference test.py 参照型も基本的には問題なく使える ただしstr, bool, intなどPython側でImmutableな型 は関数内の変更が反映されない mylib.cpp 0

Slide 17

Slide 17 text

Usage - Class

Slide 18

Slide 18 text

Class Vec3クラスをPythonから使えるようにする mylib.h binding.cpp test.py

Slide 19

Slide 19 text

Class - member メンバ変数へのアクセス 関数の時と同様にバインドを作成できる binding.cpp test.py

Slide 20

Slide 20 text

Class - print printでVec3の中身を表示 __repr__を定義する binding.cpp test.py (1.000000, 2.000000, 3.000000)

Slide 21

Slide 21 text

Class - element 要素アクセスしたい場合 __getitem__を定義する binding.cpp test.py 2

Slide 22

Slide 22 text

Class - numpy Vec3をnumpy arrayとして読み込めるようにしたい Buffer Protocolを利用することで可能 binding.cpp test.py [2. 4. 6.]

Slide 23

Slide 23 text

Reference 紹介したコードは以下のrepoで公開してます https://github.com/yumcyaWiz/pybind11_tutorial

Slide 24

Slide 24 text

Application

Slide 25

Slide 25 text

LensSim • Ray Tracingによって写真レンズの性能評価・映り方のシミュ レーションを行うツール

Slide 26

Slide 26 text

LensSim C++ • レンズの読み込み • レイトレーシング • 各種性能計算 • IBLによるレンダリング Python • 可視化(matplotlib) 複雑な計算を実装し、ライブラリ化 可視化周り

Slide 27

Slide 27 text

LensSim – Optical Path Diagram Python matplotlibを用いて光路図を表示する C++

Slide 28

Slide 28 text

LensSim – Exit Pupil Plot Python matplotlibを用いて射出瞳を表示する C++

Slide 29

Slide 29 text

Reference LensSimは以下のrepoで公開してます https://github.com/yumcyaWiz/LensSim

Slide 30

Slide 30 text

Thank you for listening!