Skip to content

Commit 6fbd7d1

Browse files
authored
[markov_chain_I] Hamilton's chain animation (#457)
This pull request include the animation for the convergence to a stationary distribution in our Markov Chain lecture (markov_chain_I, Hamilton's chain).
1 parent f4c78ca commit 6fbd7d1

File tree

1 file changed

+23
-9
lines changed

1 file changed

+23
-9
lines changed

lectures/markov_chains_I.md

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,9 @@ import numpy as np
5858
import networkx as nx
5959
from matplotlib import cm
6060
import matplotlib as mpl
61+
from mpl_toolkits.mplot3d import Axes3D
62+
from matplotlib.animation import FuncAnimation
63+
from IPython.display import HTML
6164
```
6265

6366
## Definitions and examples
@@ -812,16 +815,27 @@ Now we plot the sequence
812815
fig = plt.figure()
813816
ax = fig.add_subplot(projection='3d')
814817
815-
ψ_t = iterate_ψ(ψ_0, P, 20)
816-
817-
ax.scatter(ψ_t[:,0], ψ_t[:,1], ψ_t[:,2], c='r', s=60)
818-
ax.view_init(30, 210)
819-
820-
mc = qe.MarkovChain(P)
821-
ψ_star = mc.stationary_distributions[0]
822-
ax.scatter(ψ_star[0], ψ_star[1], ψ_star[2], c='k', s=60)
818+
def update(n):
819+
ψ_t = iterate_ψ(ψ_0, P, n+1)
820+
821+
ax.clear()
822+
ax.set_xlim([0, 1])
823+
ax.set_ylim([0, 1])
824+
ax.set_zlim([0, 1])
825+
ax.view_init(30, 210)
826+
827+
for i, point in enumerate(ψ_t):
828+
ax.scatter(point[0], point[1], point[2], color='r', s=60, alpha=(i+1)/len(ψ_t))
829+
830+
mc = qe.MarkovChain(P)
831+
ψ_star = mc.stationary_distributions[0]
832+
ax.scatter(ψ_star[0], ψ_star[1], ψ_star[2], c='k', s=60)
833+
834+
return fig,
823835
824-
plt.show()
836+
anim = FuncAnimation(fig, update, frames=range(20), blit=False, repeat=False)
837+
plt.close()
838+
HTML(anim.to_jshtml())
825839
```
826840

827841
Here

0 commit comments

Comments
 (0)