SlideShare uma empresa Scribd logo
1 de 21
Baixar para ler offline
Making of:
The logistic map
bifurcation diagram
BradMartsberger
What is this talk about?
Makingaprettypicture
Squeezingperformance outof python
PyPy, Cython, C extensions
With atoyphysics model(chaos!)
Fun with fractals
Cool, but...
Where did that come from?
Can you show me some python already?
The logistic map
Map avalue, x, from [0, 1] to [0, 1] accordingto:
r *x *(1 -x)
Let's play...
x=0.25
r=2.5
forjinrange(limit):
print"x:",x
x=r*x*(1-x)
What do we need to make that
sweet graph?
Python
Matplotlib
Patience ... lots of patience
Simplified version
bif_diag=[[0.0]*height]*width
forkinrange(width):
#histogramofhowfrequentlyeachpixelisvisited.
h=logmap_histogram(r,x_len,x1,x2,height)
#Normalizethehistogramtogofrom0to1.
h=divide_list(h,1.0*max(h))
#stickitinupsidedowntotheimage
bif_diag[k-1]=h[::-1]
plot_bif_diag(bif_diag,plt,cm,(x1,x2),(r_lower,r_upper))
Inner loop
deflogmap_histogram(r,x_len,x1,x2,height):
result=[0]*height
dx=1.0*(x2-x1)/(height-1)
transient=500
x=0.25
forkinxrange(transient):
x=x*r*(1-x)
forkinxrange(x_len):
x=x*r*(1-x)
incr=int((x-x1)/dx)
ifincr>=0andincr<M:
result[incr]+=1
returnresult
Matplotlib bit
defplot_bif_diag(bif_diag,plt,cm,xlim,rlim):
width,height,=len(bif_diag),len(bif_diag[1])
to_plot=[[1-pixforpixincol]forcolinbif_diag]
to_plot=map(list,zip(*to_plot))
plt.imshow(to_plot,cm.gray,clim=(0.7,1))
font={'family':'serif','size':24}
plt.xlabel('r',fontdict=font)
plt.ylabel('x*',fontdict=font)
plt.xticks(linspace(1,N,9),['%.2g'%rforrinlinspace(rlim[0],rlim[1],9)])
plt.yticks(linspace(1,M-1,5),['%.2g'%xforxinlinspace(xlim[1],xlim[0],5)]
ax=plt.gca()
ax.set_position([80./(width+100.),80./(height+100.),width/(width+100.),
plt.gcf().canvas.manager.window.geometry("{0}x{1}+30+30".format(width+100,height+
plt.show()
Let's run this
thing already...
That was a little disappointing
Nothorrible, buttoo slow to do some coolstuff.
Options for doing better
0. Quitusingpython
1. PyPy
2. C extension
3. Cython
4. There are others (numpywith numexpr)
PyPy
Straightfrom pypy.org:
Fast, compliantalternative implementation of the Python
language (2.7.6 and 3.2.3) with severaladvantages:
Speed, due to Just-In-Time compiler
Takes less memory
Supports anumber of third partylibraries:
ctypes, django, sqlalchemy, twisted, etc.
Does notrequire anychange to your code!
Unfortunately, matplotlib is notsupported.
Numpyis partiallysupported.
C extensions
Write functions in C thatare callable from python
Pass python objects as arguments thatmustbe converted to C
values
Returns apython object, e.g., alist
Compiled and fast
Do this atleastonce
Let's have a look
staticPyObject*logmap_attractor_histogram(PyObject*self,PyObject*args){
doubler1,r2,x,x1,x2;
intxxlen,rrlen,M;
inttransient=500;//Shorttransientforeachr.
if(!PyArg_ParseTuple(args,"ddiiddi",&r1,&r2,&rrlen,&xxlen,&x1,&x2,&M)){
returnNULL;
}
//Storeourhistograminanintarray,copyittoapythonlistandreturn
//thelistasaPyObject*
intarray[M];
PyObject*list=PyList_New(M);
//Initializearraytoallzeros
intj,k;
for(j=0;j<M;++j){
array[j]=0;
}
doubler,dr,dx;
intincr;
//Settheamountwewillsteptogetfromr1tor2inrrlen-1steps
dr=0;
if(rrlen>1){dr=(r2-r1)/(rrlen-1);}
//Histogrambinsize
dx=(x2-x1)/(M-1);
//loopoverr(perhapschangetofor(r=r1;r<=r2;r+=dr))
Compiling to an importable module
Create asetup.pyfile, e.g:
fromdistutils.coreimportsetup,Extension
setup(name='logmap',version='1.0',
ext_modules=[Extension('logmap',['logmapmodule.c'])])
Then installit
>>>pythonsetup.pyinstall
And itcan be imported and called
importlogmap
h= logmap.attractor_histogram(...)
Let's see it already...
Cython
Directlyfrom cython.org:
Static compiler for python
Makes writingC extensions for python as easyas writing
python
Generates C code from your python code
Has the potentialto deliver the speed gains thatwe getfrom aC
extension with less hassle
How to make it work
Create setup.pyfile:
Build like this:
Then you can importfrom
logistic_map_bifurcation_diagram_cython
fromdistutils.coreimportsetup
fromCython.Buildimportcythonize
setup(
name='logmap_cython',
ext_modules=cythonize("logistic_map_bifurcation_diagram_cython.pyx"),
)
%>pythonsetup.pybuild_ext--in_place
Making cython faster
Cython's code generation is helped byprovidingithints in the
form of type declarations
deflogmap_histogram(floatr1,floatr2,intrrlen,intxxlen,floatx1,floatx2,intM)
result=[0]*M
cdeffloatdx
dx=1.0*(x2-x1)/(M-1)
transient=500
cdeffloatx
cdeffloatr
cdeffloatk
forrinlinspace(r1,r2,rrlen):
x=0.25
forkinrange(transient):
x=x*r*(1-x)
forkinrange(xxlen):
x=x*r*(1-x)
incr=int((x-x1)/dx)
ifincr>=0andincr<M:
result[incr]+=1
returnresult
Questions...Comments, etc.

Mais conteúdo relacionado

Mais procurados

Inverse trigonometric functions
Inverse trigonometric functionsInverse trigonometric functions
Inverse trigonometric functions
Leo Crisologo
 
Diploma sem 2 applied science physics-unit 5-chap-2 photoelectric effect
Diploma sem 2 applied science physics-unit 5-chap-2 photoelectric effectDiploma sem 2 applied science physics-unit 5-chap-2 photoelectric effect
Diploma sem 2 applied science physics-unit 5-chap-2 photoelectric effect
Rai University
 

Mais procurados (20)

Advance Quantum Mechanics
Advance Quantum Mechanics Advance Quantum Mechanics
Advance Quantum Mechanics
 
Introduzione allo studio di funzione
Introduzione allo studio di funzioneIntroduzione allo studio di funzione
Introduzione allo studio di funzione
 
Gravitational wave.pptx
Gravitational wave.pptxGravitational wave.pptx
Gravitational wave.pptx
 
Computational logic First Order Logic_part2
Computational logic First Order Logic_part2Computational logic First Order Logic_part2
Computational logic First Order Logic_part2
 
Chapter 4: Vector Spaces - Part 1/Slides By Pearson
Chapter 4: Vector Spaces - Part 1/Slides By PearsonChapter 4: Vector Spaces - Part 1/Slides By Pearson
Chapter 4: Vector Spaces - Part 1/Slides By Pearson
 
Inverse trigonometric functions
Inverse trigonometric functionsInverse trigonometric functions
Inverse trigonometric functions
 
Diploma sem 2 applied science physics-unit 5-chap-2 photoelectric effect
Diploma sem 2 applied science physics-unit 5-chap-2 photoelectric effectDiploma sem 2 applied science physics-unit 5-chap-2 photoelectric effect
Diploma sem 2 applied science physics-unit 5-chap-2 photoelectric effect
 
signal and system Dirac delta functions (1)
signal and system Dirac delta functions (1)signal and system Dirac delta functions (1)
signal and system Dirac delta functions (1)
 
Quantum mechanical spin
Quantum mechanical spinQuantum mechanical spin
Quantum mechanical spin
 
Bisection method in maths 4
Bisection method in maths 4Bisection method in maths 4
Bisection method in maths 4
 
Poynting vector
Poynting vectorPoynting vector
Poynting vector
 
Chapter 4 laws of motion
Chapter 4   laws of motion Chapter 4   laws of motion
Chapter 4 laws of motion
 
Diagonalization
DiagonalizationDiagonalization
Diagonalization
 
Power Series - Legendre Polynomial - Bessel's Equation
Power Series - Legendre Polynomial - Bessel's EquationPower Series - Legendre Polynomial - Bessel's Equation
Power Series - Legendre Polynomial - Bessel's Equation
 
Postulates of quantum mechanics & operators
Postulates of quantum mechanics & operatorsPostulates of quantum mechanics & operators
Postulates of quantum mechanics & operators
 
Application of vector integration
Application of vector integration Application of vector integration
Application of vector integration
 
Simple harmonic oscillator
Simple harmonic oscillator Simple harmonic oscillator
Simple harmonic oscillator
 
Fermi surface and de haas van alphen effect ppt
Fermi surface and de haas van alphen effect pptFermi surface and de haas van alphen effect ppt
Fermi surface and de haas van alphen effect ppt
 
Seminar: Calculus of Variation
Seminar: Calculus of VariationSeminar: Calculus of Variation
Seminar: Calculus of Variation
 
Asintoti
AsintotiAsintoti
Asintoti
 

Semelhante a Making of-the-logistic-map-bifurcation-diagram

Seven waystouseturtle pycon2009
Seven waystouseturtle pycon2009Seven waystouseturtle pycon2009
Seven waystouseturtle pycon2009
A Jorge Garcia
 
COMPAPPABCA49085rFunrAP__Practical Number 9 & 10.docx
COMPAPPABCA49085rFunrAP__Practical Number 9 & 10.docxCOMPAPPABCA49085rFunrAP__Practical Number 9 & 10.docx
COMPAPPABCA49085rFunrAP__Practical Number 9 & 10.docx
TashiBhutia12
 

Semelhante a Making of-the-logistic-map-bifurcation-diagram (20)

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
 
Use the Matplotlib, Luke @ PyCon Taiwan 2012
Use the Matplotlib, Luke @ PyCon Taiwan 2012Use the Matplotlib, Luke @ PyCon Taiwan 2012
Use the Matplotlib, Luke @ PyCon Taiwan 2012
 
Python grass
Python grassPython grass
Python grass
 
Gems of GameplayKit. UA Mobile 2017.
Gems of GameplayKit. UA Mobile 2017.Gems of GameplayKit. UA Mobile 2017.
Gems of GameplayKit. UA Mobile 2017.
 
Sergey Shelpuk & Olha Romaniuk - “Deep learning, Tensorflow, and Fashion: how...
Sergey Shelpuk & Olha Romaniuk - “Deep learning, Tensorflow, and Fashion: how...Sergey Shelpuk & Olha Romaniuk - “Deep learning, Tensorflow, and Fashion: how...
Sergey Shelpuk & Olha Romaniuk - “Deep learning, Tensorflow, and Fashion: how...
 
Advanced Techniques: Graphics | Pebble Developer Retreat 2014
Advanced Techniques: Graphics | Pebble Developer Retreat 2014Advanced Techniques: Graphics | Pebble Developer Retreat 2014
Advanced Techniques: Graphics | Pebble Developer Retreat 2014
 
Numba: Array-oriented Python Compiler for NumPy
Numba: Array-oriented Python Compiler for NumPyNumba: Array-oriented Python Compiler for NumPy
Numba: Array-oriented Python Compiler for NumPy
 
Swift for tensorflow
Swift for tensorflowSwift for tensorflow
Swift for tensorflow
 
Seven waystouseturtle pycon2009
Seven waystouseturtle pycon2009Seven waystouseturtle pycon2009
Seven waystouseturtle pycon2009
 
maXbox starter68 machine learning VI
maXbox starter68 machine learning VImaXbox starter68 machine learning VI
maXbox starter68 machine learning VI
 
Seminar psu 20.10.2013
Seminar psu 20.10.2013Seminar psu 20.10.2013
Seminar psu 20.10.2013
 
ATS Programming
ATS ProgrammingATS Programming
ATS Programming
 
Matlab graphics
Matlab graphicsMatlab graphics
Matlab graphics
 
Introduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdfIntroduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdf
 
Intro to Python (High School) Unit #3
Intro to Python (High School) Unit #3Intro to Python (High School) Unit #3
Intro to Python (High School) Unit #3
 
Py lecture5 python plots
Py lecture5 python plotsPy lecture5 python plots
Py lecture5 python plots
 
COMPAPPABCA49085rFunrAP__Practical Number 9 & 10.docx
COMPAPPABCA49085rFunrAP__Practical Number 9 & 10.docxCOMPAPPABCA49085rFunrAP__Practical Number 9 & 10.docx
COMPAPPABCA49085rFunrAP__Practical Number 9 & 10.docx
 
SCIPY-SYMPY.pdf
SCIPY-SYMPY.pdfSCIPY-SYMPY.pdf
SCIPY-SYMPY.pdf
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
 
Towards typesafe deep learning in scala
Towards typesafe deep learning in scalaTowards typesafe deep learning in scala
Towards typesafe deep learning in scala
 

Último

Último (20)

Weeding your micro service landscape.pdf
Weeding your micro service landscape.pdfWeeding your micro service landscape.pdf
Weeding your micro service landscape.pdf
 
Workshop: Enabling GenAI Breakthroughs with Knowledge Graphs - GraphSummit Milan
Workshop: Enabling GenAI Breakthroughs with Knowledge Graphs - GraphSummit MilanWorkshop: Enabling GenAI Breakthroughs with Knowledge Graphs - GraphSummit Milan
Workshop: Enabling GenAI Breakthroughs with Knowledge Graphs - GraphSummit Milan
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
 
What is a Recruitment Management Software?
What is a Recruitment Management Software?What is a Recruitment Management Software?
What is a Recruitment Management Software?
 
BusinessGPT - Security and Governance for Generative AI
BusinessGPT  - Security and Governance for Generative AIBusinessGPT  - Security and Governance for Generative AI
BusinessGPT - Security and Governance for Generative AI
 
Food Delivery Business App Development Guide 2024
Food Delivery Business App Development Guide 2024Food Delivery Business App Development Guide 2024
Food Delivery Business App Development Guide 2024
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In witbank
^Clinic ^%[+27788225528*Abortion Pills For Sale In witbank^Clinic ^%[+27788225528*Abortion Pills For Sale In witbank
^Clinic ^%[+27788225528*Abortion Pills For Sale In witbank
 
Abortion Pill Prices Germiston ](+27832195400*)[ 🏥 Women's Abortion Clinic in...
Abortion Pill Prices Germiston ](+27832195400*)[ 🏥 Women's Abortion Clinic in...Abortion Pill Prices Germiston ](+27832195400*)[ 🏥 Women's Abortion Clinic in...
Abortion Pill Prices Germiston ](+27832195400*)[ 🏥 Women's Abortion Clinic in...
 
Transformer Neural Network Use Cases with Links
Transformer Neural Network Use Cases with LinksTransformer Neural Network Use Cases with Links
Transformer Neural Network Use Cases with Links
 
Workshop - Architecting Innovative Graph Applications- GraphSummit Milan
Workshop -  Architecting Innovative Graph Applications- GraphSummit MilanWorkshop -  Architecting Innovative Graph Applications- GraphSummit Milan
Workshop - Architecting Innovative Graph Applications- GraphSummit Milan
 
Test Automation Design Patterns_ A Comprehensive Guide.pdf
Test Automation Design Patterns_ A Comprehensive Guide.pdfTest Automation Design Patterns_ A Comprehensive Guide.pdf
Test Automation Design Patterns_ A Comprehensive Guide.pdf
 
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
 
Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024
 
Abortion Pill Prices Jane Furse ](+27832195400*)[ 🏥 Women's Abortion Clinic i...
Abortion Pill Prices Jane Furse ](+27832195400*)[ 🏥 Women's Abortion Clinic i...Abortion Pill Prices Jane Furse ](+27832195400*)[ 🏥 Women's Abortion Clinic i...
Abortion Pill Prices Jane Furse ](+27832195400*)[ 🏥 Women's Abortion Clinic i...
 
The Strategic Impact of Buying vs Building in Test Automation
The Strategic Impact of Buying vs Building in Test AutomationThe Strategic Impact of Buying vs Building in Test Automation
The Strategic Impact of Buying vs Building in Test Automation
 
Lessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdfLessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdf
 
UNI DI NAPOLI FEDERICO II - Il ruolo dei grafi nell'AI Conversazionale Ibrida
UNI DI NAPOLI FEDERICO II - Il ruolo dei grafi nell'AI Conversazionale IbridaUNI DI NAPOLI FEDERICO II - Il ruolo dei grafi nell'AI Conversazionale Ibrida
UNI DI NAPOLI FEDERICO II - Il ruolo dei grafi nell'AI Conversazionale Ibrida
 
Encryption Recap: A Refresher on Key Concepts
Encryption Recap: A Refresher on Key ConceptsEncryption Recap: A Refresher on Key Concepts
Encryption Recap: A Refresher on Key Concepts
 
From Theory to Practice: Utilizing SpiraPlan's REST API
From Theory to Practice: Utilizing SpiraPlan's REST APIFrom Theory to Practice: Utilizing SpiraPlan's REST API
From Theory to Practice: Utilizing SpiraPlan's REST API
 
Software Engineering - Introduction + Process Models + Requirements Engineering
Software Engineering - Introduction + Process Models + Requirements EngineeringSoftware Engineering - Introduction + Process Models + Requirements Engineering
Software Engineering - Introduction + Process Models + Requirements Engineering
 

Making of-the-logistic-map-bifurcation-diagram