QuantEcon / lecture-python-intro

An Undergraduate Lecture Series for the Foundations of Computational Economics
https://intro.quantecon.org/
39 stars 20 forks source link

[markov_chain_I] animation with multiple initial conditions #482

Closed longye-tian closed 2 months ago

longye-tian commented 3 months ago

Dear John @jstac,

I have updated the previous animation code to include three initial conditions and also the unit simplex.

The updated code is shown below:

ψ_1 = (0.0, 0.0, 1.0)
ψ_2 = (1.0, 0.0, 0.0)
ψ_3 = (0.0, 1.0, 0.0)                   # Three initial conditions
colors = ['blue','red', 'green']   # Different colors for each initial point

# Define the vertices of the unit simplex
v = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 0]])

# Define the faces of the unit simplex
faces = [
    [v[0], v[1], v[2]],
    [v[0], v[1], v[3]],
    [v[0], v[2], v[3]],
    [v[1], v[2], v[3]]
]

fig = plt.figure()
ax = fig.add_subplot(projection='3d')

def update(n):    
    ax.clear()
    ax.set_xlim([0, 1])
    ax.set_ylim([0, 1])
    ax.set_zlim([0, 1])
    ax.view_init(45, 45)

    simplex = Poly3DCollection(faces, alpha=0.03)
    ax.add_collection3d(simplex)

    for idx, ψ_0 in enumerate([ψ_1, ψ_2, ψ_3]):
        ψ_t = iterate_ψ(ψ_0, P, n+1)

        for i, point in enumerate(ψ_t):
            ax.scatter(point[0], point[1], point[2], color=colors[idx], s=60, alpha=(i+1)/len(ψ_t))

    mc = qe.MarkovChain(P)
    ψ_star = mc.stationary_distributions[0]
    ax.scatter(ψ_star[0], ψ_star[1], ψ_star[2], c='yellow', s=60)

    return fig,

anim = FuncAnimation(fig, update, frames=range(20), blit=False, repeat=False)
plt.close()
HTML(anim.to_jshtml())

The animation is shown below:

https://github.com/QuantEcon/lecture-python-intro/assets/133612246/be7361e7-b97d-4009-af3d-975279e3190f

What do you think about this animation? Would you like to make any changes? Hope you like my little easter egg 🤣

Best ❤️ Longye

jstac commented 3 months ago

This is great @longye-tian, very nice work.

And I like the easter egg :-)

@mmcky @thomassargent30 This is the animation of an ergodic chain, with multiple initial conditions, unit simplex shown, and dynamics shown in QuantEcon colors! I'm happy with this code. Please let us know if you want changes.

mmcky commented 3 months ago

Thanks @longye-tian really nice. Please setup a PR when you are ready.

longye-tian commented 2 months ago

This issue is now closed by recent pull request.