mercredi 29 mai 2019

How to speed up drawing plots in Matplotlib?

I'm playing with random walk, I have two points. First one is walking randomly, second one is trying to escape from his area, which is given by formula e^(-t), where t is the distance between the two points. In my opinion it is not a difficult program, but it takes about a minute to run it with hundred points to calculate, so I'm asking you to help me find some way to speed it up and explain it to me.

import numpy as np
import matplotlib.pyplot as plt


def f(x, y, zx, zy):
    return np.exp(-np.sqrt((x-zx)**2+(y-zy)**2))


x = y = np.linspace(-100, 100, 1000)
X, Y = np.meshgrid(x, y)

fig, ax = plt.subplots(1, 1, figsize=(12, 6))
#random picking first location for two points
loksx = [np.random.randn(), ]
loksy = [np.random.randn(), ]
lokzx = [np.random.randn(), ]
lokzy = [np.random.randn(), ]
for i in range(100):
    lokzx.append(np.random.randn()+lokzx[-1])
    lokzy.append(np.random.randn()+lokzy[-1])
    nsx = np.random.randn()
    nsy = np.random.randn()
    #checking if the next step has smaller value than the last one 
    if f(loksx[-1]+nsx, loksy[-1]+nsy, lokzx[-1], lokzy[-1]) < f(loksx[-1], loksy[-1], lokzx[-1], lokzy[-1]):
        loksx.append(nsx+loksx[-1])
        loksy.append(nsy+loksy[-1])
Z = []
for i in range(len(lokzx)):
    Z.append(f(X, Y, lokzx[i], lokzy[i]))
ax.plot(lokzx[0], lokzy[0], 'y,',markersize=1)
ax.plot(loksx[0], loksy[0], 'w,', markersize=1)
ax.plot(lokzx[1:-1], lokzy[1:-1], 'g,',markersize=1)
ax.plot(loksx[1:-1], loksy[1:-1], 'b,', markersize=1)

ax.plot(loksx[-1], loksy[-1], 'k,', markersize=1)
ax.plot(lokzx[-1], lokzy[-1], 'r,',markersize=1)
for i in range(len(Z)):
    ax.contourf(X, Y, Z[i], 20, cmap='RdGy', alpha=0.01)
ax.plot()
ax.set_aspect('equal')
plt.show()




Aucun commentaire:

Enregistrer un commentaire