SlideShare a Scribd company logo
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.

More Related Content

DOCX
Importancia de las integrales definidas
PPT
Wye delta transformations
DOCX
Teoremas Booleanos
PDF
Grafos
PDF
Problemas Electronica Digital
PPTX
Grafos eulerianos
PDF
Aplicaciones de la transforma de Laplace, Fourier y Circuitos Lineales
Importancia de las integrales definidas
Wye delta transformations
Teoremas Booleanos
Grafos
Problemas Electronica Digital
Grafos eulerianos
Aplicaciones de la transforma de Laplace, Fourier y Circuitos Lineales

What's hot (20)

PDF
Algebra de boole y simplificacion logica
DOCX
Practica 2 ey m
PPT
Leyes de kirchhoff
PPTX
kirchoff law
PPTX
Historia y algunos conceptos de Probabilidad y Estadística
PDF
Presentacion teoremas thevenin
PDF
joseph endminister electromagnetismo-serie-schaum
PDF
Coeficientes y transformada de Fourier en Matlab
PDF
Unidad electrotecnia (ley de kirchoff y ohm)
PPTX
Electromagnetic fields: Review of vector algebra
PDF
Ley de composición interna algebra ii
PPTX
Familias lógicas digitales
DOCX
Funciones trascendentales
PPT
Circuitos Serie-Paralelo
PPTX
Teorema de thévenin
PPTX
Algebra booleana
PPTX
Atomo y cristal
PDF
Monografia contador digital
PPT
Ley de Ohm - Ejercicios
Algebra de boole y simplificacion logica
Practica 2 ey m
Leyes de kirchhoff
kirchoff law
Historia y algunos conceptos de Probabilidad y Estadística
Presentacion teoremas thevenin
joseph endminister electromagnetismo-serie-schaum
Coeficientes y transformada de Fourier en Matlab
Unidad electrotecnia (ley de kirchoff y ohm)
Electromagnetic fields: Review of vector algebra
Ley de composición interna algebra ii
Familias lógicas digitales
Funciones trascendentales
Circuitos Serie-Paralelo
Teorema de thévenin
Algebra booleana
Atomo y cristal
Monografia contador digital
Ley de Ohm - Ejercicios
Ad

Recently uploaded (20)

PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Designing Intelligence for the Shop Floor.pdf
PPT
Introduction Database Management System for Course Database
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PPTX
Introduction to Artificial Intelligence
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PPTX
ai tools demonstartion for schools and inter college
PPTX
history of c programming in notes for students .pptx
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
assetexplorer- product-overview - presentation
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
CHAPTER 2 - PM Management and IT Context
Wondershare Filmora 15 Crack With Activation Key [2025
Designing Intelligence for the Shop Floor.pdf
Introduction Database Management System for Course Database
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Navsoft: AI-Powered Business Solutions & Custom Software Development
wealthsignaloriginal-com-DS-text-... (1).pdf
Introduction to Artificial Intelligence
PTS Company Brochure 2025 (1).pdf.......
2025 Textile ERP Trends: SAP, Odoo & Oracle
ai tools demonstartion for schools and inter college
history of c programming in notes for students .pptx
How to Migrate SBCGlobal Email to Yahoo Easily
Reimagine Home Health with the Power of Agentic AI​
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
VVF-Customer-Presentation2025-Ver1.9.pptx
Odoo Companies in India – Driving Business Transformation.pdf
Softaken Excel to vCard Converter Software.pdf
assetexplorer- product-overview - presentation
Ad

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