SlideShare uma empresa Scribd logo
1 de 21
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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)
 

Semelhante a 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
 

Semelhante a 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
 

Mais de 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
 

Mais de 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)
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+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@
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
+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...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
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...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 

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