SlideShare ist ein Scribd-Unternehmen logo
1 von 21
Downloaden Sie, um offline zu lesen
Example with GCoptimization
Kevin Keraudren
Imperial College London

October 31st , 2013
Cython overview
Syntax between Python and C (keyword cdef)
C/C++ code automatically generated,
then compiled into a Python module
For a speed gain, variables must be declared
C++ templates must be instantiated (compiled code)
Choose between accessing low-level C++ or a blackbox
Documentation: docs.cython.org
Learn from examples:
scikit-learn, scikit-image, github.com/amueller

2/21
How to?

1

Organize your C/C++ code

2

Write module.pyx

3

Write setup.py

4

Build

3/21
Example 1
Interface the whole API

4/21
Graphcut (Boykov & Kolmogorov)

V (p, q ) =

1
p−q
1
p−q

2

2
2
e−(Ip −Iq ) /2σ

2

if Ip ≥ Iq
if Ip < Iq

σ : noise estimate
5/21
GCoptimisation (Boykov & Kolmogorov)
template <typename captype,
typename tcaptype,
typename flowtype> class Graph {
public:
...
Graph( int node_num_max, int edge_num_max,
void (*err_function)(const char *) = NULL);
void add_edge( node_id i, node_id j,
captype cap, captype rev_cap);
void add_tweights( node_id i,
tcaptype cap_source, tcaptype cap_sink);
flowtype maxflow( bool reuse_trees = false,
Block<node_id>* changed_list = NULL);
termtype what_segment( node_id i,
termtype default_segm = SOURCE);
...
}
6/21
Begin your module.pyx

import numpy as np
cimport numpy as np
np.import_array()
ctypedef double captype
ctypedef double tcaptype
ctypedef double flowtype

7/21
Declare what you need from C++

cdef extern from "graph.h":
cdef cppclass Graph[captype,tcaptype,flowtype]:
Graph( size_t, size_t )
size_t add_node(size_t)
void add_edge(size_t,size_t,captype,captype)
void add_tweights(size_t,tcaptype,tcaptype)
flowtype maxflow()
int what_segment(size_t)

8/21
Create your Python class

cdef class PyGraph:
# hold a C++ instance which we’re wrapping
cdef Graph[captype,tcaptype,flowtype] *thisptr
def __cinit__(self, size_t nb_nodes, size_t nb_edges):
self.thisptr = new Graph[captype,
tcaptype, flowtype](nb_nodes,nb_edges)
def __dealloc__(self):
del self.thisptr

9/21
Create your Python class

def add_node(self, size_t nb_nodes=1):
self.thisptr.add_node(nb_nodes)
def add_edge(self, size_t i, size_t j,
captype cap, captype rev_cap):
self.thisptr.add_edge(i,j,cap,rev_cap)
def add_tweights(self, size_t i,
tcaptype cap_source, tcaptype cap_sink):
self.thisptr.add_tweights(i,cap_source,cap_sink)
def maxflow(self):
return self.thisptr.maxflow()
def what_segment(self, size_t i):
return self.thisptr.what_segment(i)

10/21
Write setup.py
from
from
from
from

distutils.core import setup
distutils.extension import Extension
Cython.Distutils import build_ext
numpy.distutils.misc_util import get_numpy_include_dirs

setup(
cmdclass = {’build_ext’: build_ext},
ext_modules = [
Extension( "graphcut",
[ "graphcut.pyx",
"../maxflow-v3.02.src/graph.cpp",
"../maxflow-v3.02.src/maxflow.cpp" ],
language="c++",
include_dirs=get_numpy_include_dirs()+["../maxflow-v3.02.src"],
)
]
)

And build:

python setup.py build_ext --build-temp tmp 
--build-lib lib 
--pyrex-c-in-temp
11/21
And use it!
from lib import graphcut
G = graphcut.PyGraph(nb_pixels,nb_pixels*(8+2))
G.add_node(nb_pixels)
...
print "building graph..."
for i in range(img.shape[0]):
for j in range(img.shape[1]):
for a,b in neighbourhood:
if ( 0 <= i+a < img.shape[0]
and 0 <= j+b < img.shape[1] ):
dist = np.sqrt( a**2 + b**2 )
if img[i,j] < img[i+a,j+b]:
w = 1.0/dist
else:
w = np.exp(-(img[i,j] - img[i+a,j+b])**2
w /= 2.0 * std**2 * dist
G.add_edge( index(i,j,img),
index(i+a,j+b,img),
w, 0 )
12/21
Result

13/21
Example 2
Use C++ as a blackbox

14/21
Declare C++ function

cdef extern from "_graphcut.h":
void _graphcut( voxel_t*,
int, int,
double,
unsigned char*,
unsigned char* )

15/21
And use it!
def graphcut( np.ndarray[voxel_t, ndim=2, mode="c"] img,
np.ndarray[unsigned char, ndim=2, mode="c"] mask,
double std ):
cdef np.ndarray[unsigned char,
ndim=2,
mode="c"] seg = np.zeros( (img.shape[0],
img.shape[1]),
dtype=’uint8’)
print "starting graphcut..."
_graphcut( <voxel_t*> img.data,
img.shape[0], img.shape[1],
std,
<unsigned char*> mask.data,
<unsigned char*> seg.data )
return seg
16/21
Result

17/21
Timing

Example 1: 18.01s
Example 2: 0.37s
Nearly 50 times faster...

18/21
Another result...

19/21
Conclusion

Huge speedup for a low amount of code
Perfect if C++ code already exists
Make sure your Python code is optimised (good use of numpy)
before using cython

Slides and code are on github

github.com/kevin-keraudren/talk-cython

20/21
Thanks!

21/21

Weitere ähnliche Inhalte

Was ist angesagt?

Unmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeUnmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/Invoke
Dmitri Nesteruk
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
Moriyoshi Koizumi
 
Mono + .NET Core = ❤️
Mono + .NET Core =  ❤️Mono + .NET Core =  ❤️
Mono + .NET Core = ❤️
Egor Bogatov
 
A peek on numerical programming in perl and python e christopher dyken 2005
A peek on numerical programming in perl and python  e christopher dyken  2005A peek on numerical programming in perl and python  e christopher dyken  2005
A peek on numerical programming in perl and python e christopher dyken 2005
Jules Krdenas
 

Was ist angesagt? (20)

Concurrency in Python4k
Concurrency in Python4kConcurrency in Python4k
Concurrency in Python4k
 
Unmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeUnmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/Invoke
 
Rpy2 demonstration
Rpy2 demonstrationRpy2 demonstration
Rpy2 demonstration
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
 
mpi4py.pdf
mpi4py.pdfmpi4py.pdf
mpi4py.pdf
 
Computer Science Practical File class XII
Computer Science Practical File class XIIComputer Science Practical File class XII
Computer Science Practical File class XII
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
 
Queue oop
Queue   oopQueue   oop
Queue oop
 
Mono + .NET Core = ❤️
Mono + .NET Core =  ❤️Mono + .NET Core =  ❤️
Mono + .NET Core = ❤️
 
GoFFIng around with Ruby #RubyConfPH
GoFFIng around with Ruby #RubyConfPHGoFFIng around with Ruby #RubyConfPH
GoFFIng around with Ruby #RubyConfPH
 
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizationsEgor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
 
A peek on numerical programming in perl and python e christopher dyken 2005
A peek on numerical programming in perl and python  e christopher dyken  2005A peek on numerical programming in perl and python  e christopher dyken  2005
A peek on numerical programming in perl and python e christopher dyken 2005
 
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
 
C++11 & C++14
C++11 & C++14C++11 & C++14
C++11 & C++14
 
D vs OWKN Language at LLnagoya
D vs OWKN Language at LLnagoyaD vs OWKN Language at LLnagoya
D vs OWKN Language at LLnagoya
 
C++11
C++11C++11
C++11
 
Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)
 
Activity Recognition Through Complex Event Processing: First Findings
Activity Recognition Through Complex Event Processing: First Findings Activity Recognition Through Complex Event Processing: First Findings
Activity Recognition Through Complex Event Processing: First Findings
 
Diving into byte code optimization in python
Diving into byte code optimization in python Diving into byte code optimization in python
Diving into byte code optimization in python
 
BeepBeep 3: A declarative event stream query engine (EDOC 2015)
BeepBeep 3: A declarative event stream query engine (EDOC 2015)BeepBeep 3: A declarative event stream query engine (EDOC 2015)
BeepBeep 3: A declarative event stream query engine (EDOC 2015)
 

Ähnlich wie Introduction to cython: example of GCoptimization

20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
eugeniadean34240
 

Ähnlich wie Introduction to cython: example of GCoptimization (20)

Python Software Testing in Kytos.io
Python Software Testing in Kytos.ioPython Software Testing in Kytos.io
Python Software Testing in Kytos.io
 
PyHEP 2018: Tools to bind to Python
PyHEP 2018:  Tools to bind to PythonPyHEP 2018:  Tools to bind to Python
PyHEP 2018: Tools to bind to Python
 
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
 
C++20 the small things - Timur Doumler
C++20 the small things - Timur DoumlerC++20 the small things - Timur Doumler
C++20 the small things - Timur Doumler
 
cscript_controller.pdf
cscript_controller.pdfcscript_controller.pdf
cscript_controller.pdf
 
Story of static code analyzer development
Story of static code analyzer developmentStory of static code analyzer development
Story of static code analyzer development
 
Beyond C++17
Beyond C++17Beyond C++17
Beyond C++17
 
Chainer-Compiler 動かしてみた
Chainer-Compiler 動かしてみたChainer-Compiler 動かしてみた
Chainer-Compiler 動かしてみた
 
17 PYTHON MODULES-2.pdf
17 PYTHON MODULES-2.pdf17 PYTHON MODULES-2.pdf
17 PYTHON MODULES-2.pdf
 
GNU Compiler Collection - August 2005
GNU Compiler Collection - August 2005GNU Compiler Collection - August 2005
GNU Compiler Collection - August 2005
 
Introduction to CUDA C: NVIDIA : Notes
Introduction to CUDA C: NVIDIA : NotesIntroduction to CUDA C: NVIDIA : Notes
Introduction to CUDA C: NVIDIA : Notes
 
The Ring programming language version 1.8 book - Part 95 of 202
The Ring programming language version 1.8 book - Part 95 of 202The Ring programming language version 1.8 book - Part 95 of 202
The Ring programming language version 1.8 book - Part 95 of 202
 
Cluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CCluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in C
 
Gpu workshop cluster universe: scripting cuda
Gpu workshop cluster universe: scripting cudaGpu workshop cluster universe: scripting cuda
Gpu workshop cluster universe: scripting cuda
 
Tdd with python unittest for embedded c
Tdd with python unittest for embedded cTdd with python unittest for embedded c
Tdd with python unittest for embedded c
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code
 
alexnet.pdf
alexnet.pdfalexnet.pdf
alexnet.pdf
 
The Ring programming language version 1.6 book - Part 184 of 189
The Ring programming language version 1.6 book - Part 184 of 189The Ring programming language version 1.6 book - Part 184 of 189
The Ring programming language version 1.6 book - Part 184 of 189
 
Debugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template MetaprogramsDebugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template Metaprograms
 

Mehr von Kevin Keraudren

Automatic Localisation of the Brain in Fetal MRI (Miccai 2013 poster)
Automatic Localisation of the Brain in Fetal MRI (Miccai 2013 poster)Automatic Localisation of the Brain in Fetal MRI (Miccai 2013 poster)
Automatic Localisation of the Brain in Fetal MRI (Miccai 2013 poster)
Kevin Keraudren
 
Automated Fetal Brain Segmentation from 2D MRI Slices for Motion Correction (...
Automated Fetal Brain Segmentation from 2D MRI Slices for Motion Correction (...Automated Fetal Brain Segmentation from 2D MRI Slices for Motion Correction (...
Automated Fetal Brain Segmentation from 2D MRI Slices for Motion Correction (...
Kevin Keraudren
 
Automated Localization of Fetal Organs in MRI Using Random Forests with Steer...
Automated Localization of Fetal Organs in MRI Using Random Forests with Steer...Automated Localization of Fetal Organs in MRI Using Random Forests with Steer...
Automated Localization of Fetal Organs in MRI Using Random Forests with Steer...
Kevin Keraudren
 
Automated Localization of Fetal Organs in MRI Using Random Forests with Steer...
Automated Localization of Fetal Organs in MRI Using Random Forests with Steer...Automated Localization of Fetal Organs in MRI Using Random Forests with Steer...
Automated Localization of Fetal Organs in MRI Using Random Forests with Steer...
Kevin Keraudren
 
Automatic Localisation of the Brain in Fetal MRI (Miccai 2013)
Automatic Localisation of the Brain in Fetal MRI (Miccai 2013)Automatic Localisation of the Brain in Fetal MRI (Miccai 2013)
Automatic Localisation of the Brain in Fetal MRI (Miccai 2013)
Kevin Keraudren
 
Segmenting Epithelial Cells in High-Throughput RNAi Screens (Miaab 2011)
Segmenting Epithelial Cells in High-Throughput RNAi Screens (Miaab 2011)Segmenting Epithelial Cells in High-Throughput RNAi Screens (Miaab 2011)
Segmenting Epithelial Cells in High-Throughput RNAi Screens (Miaab 2011)
Kevin Keraudren
 
Keraudren-K-2015-PhD-Thesis
Keraudren-K-2015-PhD-ThesisKeraudren-K-2015-PhD-Thesis
Keraudren-K-2015-PhD-Thesis
Kevin Keraudren
 
Slides on Photosynth.net, from my MSc at Imperial
Slides on Photosynth.net, from my MSc at ImperialSlides on Photosynth.net, from my MSc at Imperial
Slides on Photosynth.net, from my MSc at Imperial
Kevin Keraudren
 

Mehr von Kevin Keraudren (17)

Automatic Localisation of the Brain in Fetal MRI (Miccai 2013 poster)
Automatic Localisation of the Brain in Fetal MRI (Miccai 2013 poster)Automatic Localisation of the Brain in Fetal MRI (Miccai 2013 poster)
Automatic Localisation of the Brain in Fetal MRI (Miccai 2013 poster)
 
Automated Fetal Brain Segmentation from 2D MRI Slices for Motion Correction (...
Automated Fetal Brain Segmentation from 2D MRI Slices for Motion Correction (...Automated Fetal Brain Segmentation from 2D MRI Slices for Motion Correction (...
Automated Fetal Brain Segmentation from 2D MRI Slices for Motion Correction (...
 
Automated Localization of Fetal Organs in MRI Using Random Forests with Steer...
Automated Localization of Fetal Organs in MRI Using Random Forests with Steer...Automated Localization of Fetal Organs in MRI Using Random Forests with Steer...
Automated Localization of Fetal Organs in MRI Using Random Forests with Steer...
 
Automated Localization of Fetal Organs in MRI Using Random Forests with Steer...
Automated Localization of Fetal Organs in MRI Using Random Forests with Steer...Automated Localization of Fetal Organs in MRI Using Random Forests with Steer...
Automated Localization of Fetal Organs in MRI Using Random Forests with Steer...
 
Automatic Localisation of the Brain in Fetal MRI (Miccai 2013)
Automatic Localisation of the Brain in Fetal MRI (Miccai 2013)Automatic Localisation of the Brain in Fetal MRI (Miccai 2013)
Automatic Localisation of the Brain in Fetal MRI (Miccai 2013)
 
Segmenting Epithelial Cells in High-Throughput RNAi Screens (Miaab 2011)
Segmenting Epithelial Cells in High-Throughput RNAi Screens (Miaab 2011)Segmenting Epithelial Cells in High-Throughput RNAi Screens (Miaab 2011)
Segmenting Epithelial Cells in High-Throughput RNAi Screens (Miaab 2011)
 
Keraudren-K-2015-PhD-Thesis
Keraudren-K-2015-PhD-ThesisKeraudren-K-2015-PhD-Thesis
Keraudren-K-2015-PhD-Thesis
 
PhD viva - 11th November 2015
PhD viva - 11th November 2015PhD viva - 11th November 2015
PhD viva - 11th November 2015
 
PyData London 2015 - Localising Organs of the Fetus in MRI Data Using Python
PyData London 2015 - Localising Organs of the Fetus in MRI Data Using PythonPyData London 2015 - Localising Organs of the Fetus in MRI Data Using Python
PyData London 2015 - Localising Organs of the Fetus in MRI Data Using Python
 
Automated Fetal Brain Segmentation from 2D MRI Slices for Motion Correction
Automated Fetal Brain Segmentation from 2D MRI Slices for Motion CorrectionAutomated Fetal Brain Segmentation from 2D MRI Slices for Motion Correction
Automated Fetal Brain Segmentation from 2D MRI Slices for Motion Correction
 
Sparsity Based Spectral Embedding: Application to Multi-Atlas Echocardiograph...
Sparsity Based Spectral Embedding: Application to Multi-Atlas Echocardiograph...Sparsity Based Spectral Embedding: Application to Multi-Atlas Echocardiograph...
Sparsity Based Spectral Embedding: Application to Multi-Atlas Echocardiograph...
 
Endocardial 3D Ultrasound Segmentation using Autocontext Random ForestsPresen...
Endocardial 3D Ultrasound Segmentation using Autocontext Random ForestsPresen...Endocardial 3D Ultrasound Segmentation using Autocontext Random ForestsPresen...
Endocardial 3D Ultrasound Segmentation using Autocontext Random ForestsPresen...
 
Faceccrumbs: Manifold Learning on 1M Face Images, MSc group project
Faceccrumbs: Manifold Learning on 1M Face Images, MSc group projectFaceccrumbs: Manifold Learning on 1M Face Images, MSc group project
Faceccrumbs: Manifold Learning on 1M Face Images, MSc group project
 
Slides on Photosynth.net, from my MSc at Imperial
Slides on Photosynth.net, from my MSc at ImperialSlides on Photosynth.net, from my MSc at Imperial
Slides on Photosynth.net, from my MSc at Imperial
 
Slides presented at the Steiner Unit, Hammersmith Hospital, 08/06/2012
Slides presented at the Steiner Unit, Hammersmith Hospital, 08/06/2012Slides presented at the Steiner Unit, Hammersmith Hospital, 08/06/2012
Slides presented at the Steiner Unit, Hammersmith Hospital, 08/06/2012
 
Reading group - 22/05/2013
Reading group - 22/05/2013Reading group - 22/05/2013
Reading group - 22/05/2013
 
Segmenting Epithelial Cells in High-Throughput RNAi Screens (MIAAB 2011)
Segmenting Epithelial Cells in High-Throughput RNAi Screens (MIAAB 2011)Segmenting Epithelial Cells in High-Throughput RNAi Screens (MIAAB 2011)
Segmenting Epithelial Cells in High-Throughput RNAi Screens (MIAAB 2011)
 

Kürzlich hochgeladen

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Kürzlich hochgeladen (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 

Introduction to cython: example of GCoptimization

  • 1. Example with GCoptimization Kevin Keraudren Imperial College London October 31st , 2013
  • 2. Cython overview Syntax between Python and C (keyword cdef) C/C++ code automatically generated, then compiled into a Python module For a speed gain, variables must be declared C++ templates must be instantiated (compiled code) Choose between accessing low-level C++ or a blackbox Documentation: docs.cython.org Learn from examples: scikit-learn, scikit-image, github.com/amueller 2/21
  • 3. How to? 1 Organize your C/C++ code 2 Write module.pyx 3 Write setup.py 4 Build 3/21
  • 4. Example 1 Interface the whole API 4/21
  • 5. Graphcut (Boykov & Kolmogorov) V (p, q ) = 1 p−q 1 p−q 2 2 2 e−(Ip −Iq ) /2σ 2 if Ip ≥ Iq if Ip < Iq σ : noise estimate 5/21
  • 6. GCoptimisation (Boykov & Kolmogorov) template <typename captype, typename tcaptype, typename flowtype> class Graph { public: ... Graph( int node_num_max, int edge_num_max, void (*err_function)(const char *) = NULL); void add_edge( node_id i, node_id j, captype cap, captype rev_cap); void add_tweights( node_id i, tcaptype cap_source, tcaptype cap_sink); flowtype maxflow( bool reuse_trees = false, Block<node_id>* changed_list = NULL); termtype what_segment( node_id i, termtype default_segm = SOURCE); ... } 6/21
  • 7. Begin your module.pyx import numpy as np cimport numpy as np np.import_array() ctypedef double captype ctypedef double tcaptype ctypedef double flowtype 7/21
  • 8. Declare what you need from C++ cdef extern from "graph.h": cdef cppclass Graph[captype,tcaptype,flowtype]: Graph( size_t, size_t ) size_t add_node(size_t) void add_edge(size_t,size_t,captype,captype) void add_tweights(size_t,tcaptype,tcaptype) flowtype maxflow() int what_segment(size_t) 8/21
  • 9. Create your Python class cdef class PyGraph: # hold a C++ instance which we’re wrapping cdef Graph[captype,tcaptype,flowtype] *thisptr def __cinit__(self, size_t nb_nodes, size_t nb_edges): self.thisptr = new Graph[captype, tcaptype, flowtype](nb_nodes,nb_edges) def __dealloc__(self): del self.thisptr 9/21
  • 10. Create your Python class def add_node(self, size_t nb_nodes=1): self.thisptr.add_node(nb_nodes) def add_edge(self, size_t i, size_t j, captype cap, captype rev_cap): self.thisptr.add_edge(i,j,cap,rev_cap) def add_tweights(self, size_t i, tcaptype cap_source, tcaptype cap_sink): self.thisptr.add_tweights(i,cap_source,cap_sink) def maxflow(self): return self.thisptr.maxflow() def what_segment(self, size_t i): return self.thisptr.what_segment(i) 10/21
  • 11. Write setup.py from from from from distutils.core import setup distutils.extension import Extension Cython.Distutils import build_ext numpy.distutils.misc_util import get_numpy_include_dirs setup( cmdclass = {’build_ext’: build_ext}, ext_modules = [ Extension( "graphcut", [ "graphcut.pyx", "../maxflow-v3.02.src/graph.cpp", "../maxflow-v3.02.src/maxflow.cpp" ], language="c++", include_dirs=get_numpy_include_dirs()+["../maxflow-v3.02.src"], ) ] ) And build: python setup.py build_ext --build-temp tmp --build-lib lib --pyrex-c-in-temp 11/21
  • 12. And use it! from lib import graphcut G = graphcut.PyGraph(nb_pixels,nb_pixels*(8+2)) G.add_node(nb_pixels) ... print "building graph..." for i in range(img.shape[0]): for j in range(img.shape[1]): for a,b in neighbourhood: if ( 0 <= i+a < img.shape[0] and 0 <= j+b < img.shape[1] ): dist = np.sqrt( a**2 + b**2 ) if img[i,j] < img[i+a,j+b]: w = 1.0/dist else: w = np.exp(-(img[i,j] - img[i+a,j+b])**2 w /= 2.0 * std**2 * dist G.add_edge( index(i,j,img), index(i+a,j+b,img), w, 0 ) 12/21
  • 14. Example 2 Use C++ as a blackbox 14/21
  • 15. Declare C++ function cdef extern from "_graphcut.h": void _graphcut( voxel_t*, int, int, double, unsigned char*, unsigned char* ) 15/21
  • 16. And use it! def graphcut( np.ndarray[voxel_t, ndim=2, mode="c"] img, np.ndarray[unsigned char, ndim=2, mode="c"] mask, double std ): cdef np.ndarray[unsigned char, ndim=2, mode="c"] seg = np.zeros( (img.shape[0], img.shape[1]), dtype=’uint8’) print "starting graphcut..." _graphcut( <voxel_t*> img.data, img.shape[0], img.shape[1], std, <unsigned char*> mask.data, <unsigned char*> seg.data ) return seg 16/21
  • 18. Timing Example 1: 18.01s Example 2: 0.37s Nearly 50 times faster... 18/21
  • 20. Conclusion Huge speedup for a low amount of code Perfect if C++ code already exists Make sure your Python code is optimised (good use of numpy) before using cython Slides and code are on github github.com/kevin-keraudren/talk-cython 20/21