Anda di halaman 1dari 8

PythonicPerambulations

(https://jakevdp.github.io/)
Musingsandramblingsthroughtheworldof
Pythonandbeyond
Atom(/atom.xml)
Search
Navigate

Archives(/archives.html)
HomePage(http://www.astro.washington.edu/users/vanderplas)

AnimatingtheLorenzSystemin3D
Feb16,2013
OneofthethingsIreallyenjoyaboutPythonishoweasyitmakesittosolveinterestingproblemsandvisualize
thosesolutionsinacompellingway.I'vedoneseveralpostsoncreatinganimationsusingmatplotlib'srelativelynew
animationtoolkit(http://matplotlib.sourceforge.net/api/animation_api.html):(someexamplesareachaoticdouble
pendulum(/blog/2012/08/18/matplotlibanimationtutorial/),thecollisionsofparticlesinabox
(/blog/2012/08/18/matplotlibanimationtutorial/),thetimeevolutionofaquantummechanicalwavefunction
(/blog/2012/09/05/quantumpython/),andevenascenefromtheclassicvideogame,SuperMarioBros.
(/blog/2013/01/13/hackingsupermariobroswithpython/)).
Recently,areadercommented(/blog/2012/08/18/matplotlibanimationtutorial/#comment799781196)askingwhether
Imightdoa3Danimationexample.Matplotlibhasadecent3Dtoolkitcalledmplot3D
(http://matplotlib.org/mpl_toolkits/mplot3d/index.html),andthoughIhaven'tpreviouslyseenitusedinconjunction
withtheanimationtools,there'snothingfundamentalthatpreventsit.
Atthecommenter'ssuggestion,Idecidedtotrythisoutwithasimpleexampleofachaoticsystem:theLorenz
equations.

SolvingtheLorenzSystem
TheLorenzEquations(http://en.wikipedia.org/wiki/Lorenz_system)areasystemofthreecoupled,firstorder,
nonlineardifferentialequationswhichdescribethetrajectoryofaparticlethroughtime.Thesystemwasoriginally
derivedbyLorenzasamodelofatmosphericconvection,butthedeceptivesimplicityoftheequationshavemade
themanoftenusedexampleinfieldsbeyondatmosphericphysics.
Theequationsdescribetheevolutionofthespatialvariables,,and,giventhegoverningparameters,,and,
throughthespecificationofthetimederivativesofthespatialvariables:
Theresultingdynamicsareentirelydeterministicgivingastartingpointandatimeinterval.Thoughitlooks
straightforward,forcertainchoicesoftheparameters,thetrajectoriesbecomechaotic,andtheresultingtrajectories
displaysomesurprisingproperties.

Thoughnogeneralanalyticsolutionexistsforthissystem,thesolutionscanbecomputednumerically.Python
makesthissortofproblemveryeasytosolve:onecansimplyuseScipy'sinterfacetoODEPACK
(https://computation.llnl.gov/casc/odepack/odepack_home.html),anoptimizedFortranpackageforsolvingordinary
differentialequations.Here'showtheproblemcanbesetup:
importnumpyasnp
fromscipyimportintegrate
#Note:t0isrequiredfortheodeintfunction,thoughit'snotusedhere.
deflorentz_deriv((x,y,z),t0,sigma=10.,beta=8./3,rho=28.0):
"""ComputethetimederivativeofaLorenzsystem."""
return[sigma*(yx),x*(rhoz)y,x*ybeta*z]
x0=[1,1,1]#startingvector
t=np.linspace(0,3,1000)#onethousandtimesteps
x_t=integrate.odeint(lorentz_deriv,x0,t)

That'sallthereistoit!

Visualizingtheresults
Nowthatwe'vecomputedtheseresults,wecanusematplotlib'sanimationand3Dplottingtoolkitstovisualizethe
trajectoriesofseveralparticles.BecauseI'vedescribedtheanimationtoolsindepthinapreviouspost
(/blog/2012/08/18/matplotlibanimationtutorial/),Iwillskipthatdiscussionhereandjumpstraightintothecode:
LorenzSystemlorentz_animation.pydownload(/downloads/code/lorentz_animation.py)
importnumpyasnp
fromscipyimportintegrate
frommatplotlibimportpyplotasplt
frommpl_toolkits.mplot3dimportAxes3D
frommatplotlib.colorsimportcnames
frommatplotlibimportanimation
N_trajectories=20

deflorentz_deriv((x,y,z),t0,sigma=10.,beta=8./3,rho=28.0):
"""ComputethetimederivativeofaLorentzsystem."""
return[sigma*(yx),x*(rhoz)y,x*ybeta*z]

#Chooserandomstartingpoints,uniformlydistributedfrom15to15
np.random.seed(1)
x0=15+30*np.random.random((N_trajectories,3))
#Solveforthetrajectories
t=np.linspace(0,4,1000)

x_t=np.asarray([integrate.odeint(lorentz_deriv,x0i,t)
forx0iinx0])
#Setupfigure&3Daxisforanimation
fig=plt.figure()
ax=fig.add_axes([0,0,1,1],projection='3d')
ax.axis('off')
#chooseadifferentcolorforeachtrajectory
colors=plt.cm.jet(np.linspace(0,1,N_trajectories))
#setuplinesandpoints
lines=sum([ax.plot([],[],[],'',c=c)
forcincolors],[])
pts=sum([ax.plot([],[],[],'o',c=c)
forcincolors],[])
#preparetheaxeslimits
ax.set_xlim((25,25))
ax.set_ylim((35,35))
ax.set_zlim((5,55))
#setpointofview:specifiedby(altitudedegrees,azimuthdegrees)
ax.view_init(30,0)
#initializationfunction:plotthebackgroundofeachframe
definit():
forline,ptinzip(lines,pts):
line.set_data([],[])
line.set_3d_properties([])
pt.set_data([],[])
pt.set_3d_properties([])
returnlines+pts
#animationfunction.Thiswillbecalledsequentiallywiththeframenumber
defanimate(i):
#we'llsteptwotimestepsperframe.Thisleadstoniceresults.
i=(2*i)%x_t.shape[1]
forline,pt,xiinzip(lines,pts,x_t):
x,y,z=xi[:i].T
line.set_data(x,y)
line.set_3d_properties(z)
pt.set_data(x[1:],y[1:])
pt.set_3d_properties(z[1:])

ax.view_init(30,0.3*i)
fig.canvas.draw()
returnlines+pts
#instantiatetheanimator.
anim=animation.FuncAnimation(fig,animate,init_func=init,
frames=500,interval=30,blit=True)
#Saveasmp4.Thisrequiresmplayerorffmpegtobeinstalled
#anim.save('lorentz_attractor.mp4',fps=15,extra_args=['vcodec','libx264'])
plt.show()

Theresultinganimationlookssomethinglikethis:

0:00
Noticethattherearetwolocationsinthespacethatseemtodrawinallpaths:thesearethesocalled"Lorenz
attractors",andhavesomeinterestingpropertieswhichyoucanreadaboutelsewhere.Thequalitative
characteristicsoftheseLorenzattractorsvaryinsomewhatsurprisingwaysastheparametersarechanged.Ifyou
aresoinclined,youmaywishtodownloadtheabovecodeandplaywiththesevaluestoseewhattheresultslook
like.
IhopethatthisbriefexercisehasshownyouthepowerandflexibilityofPythonforunderstandingandvisualizinga
largearrayofproblems,andperhapsgivenyoutheinspirationtoexploresimilarproblems.
Happycoding!
PostedbyJakeVanderplasFeb16,2013
Tweet

20

Comments
16Comments
SortbyBest

PythonicPerambulations

Login

Share Favorite

Jointhediscussion
BenRoot 2yearsago

ItisLorenz,notlorentz
1

Reply Share

jakevdp

Mod >BenRoot

2yearsago

ThanksfixedthatinallbuttheURL

Reply Share

GaelVaroquaux 2yearsago

HeyJake,
HaveyoueverplayedwiththeMayaviinteractiveexamplesoftheLorentzsystem:
http://docs.enthought.com/maya...
and
http://docs.enthought.com/maya...
Imyopinion,what'sreallyrealwiththesecondone,whichisslightlymorecomplex,isthatyou
canchangeparametersinteractivelyandwatchthesystemevolve.
1

Reply Share

jakevdp

Mod >GaelVaroquaux

2yearsago

HeyGael,
Thanksforthelinks!Mayaviseemstohavesomeprettyslick3Dtools!MaybeI'llspend
alittlemoretimeplayingaroundwiththat.

Reply Share

TimBurton 6monthsago

greatanimation...butwhenItriedtorunitlocallyinIPython(withpython3.4)iterredouton
line14"invalidsyntax"???

Reply Share

eldada 9monthsago

Thisisafantastictutorial(likemanyothersIfoundinthisblog)!
Ijustmergedthisdemoanotheroneofyours(http://jakevdp.github.io/blog/...)thisisboth
beautifulandfunaswellasveryuseful!
Manythanx!
Onesuggestionforthecode
Thelines:
#setuplinesandpoints
lines=sum([ax.plot([],[],[],'',c=c)forcincolors],[])
pts=sum([ax.plot([],[],[],'o',c=c)forcincolors],[])

Assumethe`sum`functionisnotoverloaded,whichisoftennotthecaseinscientific
programmingwithpython(e.g.%pylab).Analternativecodewhichdoesnotrelyonthe`sum`
function:
lines=[lforcincolorsforlinax.plot([],[],[],'',c=c)]
pts=[ptforcincolorsforptinax.plot([],[],[],'o',c=c)]

Reply Share

jakevdp

Mod >eldada

9monthsago

Thanks!The``sum``overloadingisoneofthemanyreasonsthattheIPythonteamis
deprecating%pylabinfavorof%matplotlib,whichdoesn'tdoanysilentoverwritingof
builtinfunctions.I'drecommendusingthelatterinthefuture.

Reply Share

DavidP.Sanders ayearago

Thisisjustamazinglybeautiful!Probablythebestanimationoutthereofthisstunningobject!
Letmecommentonthemathematics:
Yousaythatthereare"twolocationsinthespacethatseemtodrawinallpaths".Inyour
animationitindeedseemsthatthesetwolocationsareinthecenterofsomecirclelikeregions.
Thereareindeedtwospecialpointsatthecentersofthoseregions,buttheyare*unstable*
fixedpoints,andhencearerepellers,notattractors!Onceatrajectoryspendsenoughtimenear
oneofthosepoints,itwillbeejectedinaperpendiculardirectionandwindaroundthetwo
"lobes".
Toseethis,it'sprobablyeasiertorunasingletrajectoryformoretime.To*prove*it,ofcourse,
isadifferentstory(andactuallyverydifficultitwasdonein2002byWarwickTucker).
Infact,eachofthosefixedpointsis(ifIremembercorrectly)asocalled"saddlefocus".
"Focus"meansthatthereisatwodimensionalobjectlikeaplane(thesocalled"stable
manifold")wherethetrajectoryapproachesthefixedpointasymptoticallyinaspiralthisis
whatyouareseeinginthesimulation.However,perpendiculartothisplanarlikeobjectisa
onedimensionalcurve(the"unstablemanifold"),alongwhichpointwhichwereinitiallyclose
tothefixedpointmoveaway.Thusoverall,*any*initialpointwhichisnot*exactly*onthe
seemore

Reply Share

DavidP.Sanders>DavidP.Sanders ayearago

OK,Iwaswrong.
Thetwopointsatthecentresofthe"wings"(or"lobes",asIcalledthem)infacthavean
*incoming*onedimensionalstabledirection,andan*unstable*twodimensional
subspace(forthelinearisedsystem)andhenceatwodimensionalunstablemanifold.
However,theyare"onlyslightlyunstable",whichiswhyatrajectoryspendsalongtime
windingaroundthembeforeitescapes.Apologiesfortheconfusion!
Ididtheanalyticalstabilitycalculationswithsympy.WhenIfinallygetroundto
learningtousesomebloggingsoftware,I'llpostit!

Reply Share

jakevdp

Mod >DavidP.Sanders

ayearago

Thanksfortheinfo!ImustadmitIhaven'tlookedcloselyatthetheorybehind
this...it'sgoodtohavemyclaimsdoublechecked:)

Reply Share

tjc 2yearsago

Whoops.Sorry.Mybad.wasrunninginapylabcontext.'sum'works.

Reply Share

tjc 2yearsago

HiJake,
Iwasabitperplexedbythe'sum'onlines35and37.Crashesasis,forme.Didyoumean:
#setuplinesandpoints
lines=[ax.plot([],[],[],'',c=c)[0]
forcincolors]
pts=[ax.plot([],[],[],'o',c=c)[0]
forcincolors]
Thanksforyourposts.

Reply Share

uriel_sandoval>tjc ayearago

Probablyyouareusinganotebookwithpylabinline,andthatcallsyouthenp.sum
functioninsteadofthebuitinpythonsum.

Reply Share

CamDP 2yearsago

Verypretty.Thanksforsharing!

Reply Share

Lywx 2yearsago

Thatisaveryhighqualitydemostrationofmatplotlibin3D.

Reply Share

Emi 2yearsago

Wonderful!!!!Thestudentscannowseethechaoticevolutionofthissystem,andwhatsensitive
dependenceoninitialconditionsmeans.

Reply Share

WHAT'STHIS?

ALSOONPYTHONICPERAMBULATIONS

XKCDPlotsinMatplotlib:GoingtheWhole

Numbavs.Cython:Take2

XKCDPlotsinMatplotlib:GoingtheWhole
Way

Numbavs.Cython:Take2
49commentsayearago

14commentsayearago

SturlaMoldenSomethingstoremember

whenyouuseFortranandf2py:1.Alwayspassa
Fortranorderedarray,orf2pywillmakea
temporarycopy.

JasonK.MooreFirefox22stilldoesn't

supportH264codeconLinuxorMax(Ithink)
soyouranimationdoesn'tshowinthose
browsers.Ifyou

EmbeddingMatplotlibAnimationsin
IPythonNotebooks

HowBadIsYourColormap?
5commentsamonthago

20comments2yearsago

michaelayeActivelydiscussedhere:

https://github.com/matplotlib/...

JessicaHamrickThanksforthisgreat

tutorial!Incaseyouoranyoneelserunsacross
thisissuethevideosthatwerebeingcreated
byanim.save

Subscribe

AddDisqustoyoursite

Privacy

RecentPosts
TheHipsterEffect:AnIPythonInteractiveExploration(https://jakevdp.github.io/blog/2014/11/11/thehipstereffect
interactive/)
HowBadIsYourColormap?(https://jakevdp.github.io/blog/2014/10/16/howbadisyourcolormap/)
OnFrequentismandFriedChicken(https://jakevdp.github.io/blog/2014/09/02/onfrequentismandfriedchicken/)
HackingAcademia:DataScienceandtheUniversity(https://jakevdp.github.io/blog/2014/08/22/hackingacademia/)
FrequentismandBayesianismIV:HowtobeaBayesianinPython
(https://jakevdp.github.io/blog/2014/06/14/frequentismandbayesianism4bayesianinpython/)
Follow@jakevdp

4,012followers

Copyright20122014JakeVanderplasPoweredbyPelican(http://getpelican.com)

Anda mungkin juga menyukai