1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
| import time import copy import multiprocessing as mp import numpy as np import matplotlib.pyplot as pl import mpl_toolkits.mplot3d.axes3d as ax3d from scipy.optimize import curve_fit
def walk(last): np.random.seed() while True: d = np.zeros(3) d[np.random.choice([0, 1, 2])] = np.random.choice([-1, 1]) if (d != last).any(): return d
def saw(steps = 500): while True: points = np.zeros((steps + 1, 3)) points[1] = walk([0,0,0]) i = 2 while i <= steps: points[i] = points[i - 1] + walk(points[i - 2] - points[i - 1]) if any(np.equal(points[:i-1], points[i]).all(1)): break i += 1 if i == steps + 1: r2 = np.power(np.linalg.norm(points, axis=1),2) return points, r2 import time import copy import multiprocessing as mp import numpy as np import matplotlib.pyplot as pl import mpl_toolkits.mplot3d.axes3d as ax3d from scipy.optimize import curve_fit
def walk(last): np.random.seed() while True: d = np.zeros(3) d[np.random.choice([0, 1, 2])] = np.random.choice([-1, 1]) if (d != last).any(): return d
def saw(steps = 50): while True: points = np.zeros((steps + 1, 3)) points[1] = walk([0,0,0]) i = 2 while i <= steps: points[i] = points[i - 1] + walk(points[i - 2] - points[i - 1]) if any(np.equal(points[:i-1], points[i]).all(1)): break i += 1 if i == steps + 1: r2 = np.power(np.linalg.norm(points, axis=1),2) return points, r2
if __name__ == '__main__': t1 = time.time() args = [60] * 1000 pool = mp.Pool() results = pool.map(saw, args) pool.close() pool.join() t2 = time.time() print('calucte time %.2f s'% (t2-t1))
r2 = np.array([x[1] for x in results]) results = np.array([x[0] for x in results]) r2_mean = np.mean(r2, axis = 0) steps = np.arange(len(r2_mean))
def func(x, a, b): return a * np.power(x, b) popt, pcov = curve_fit(func, steps, r2_mean) fit = func(steps, popt[0], popt[1])
pl.figure(figsize = (10, 10), dpi = 80) pl.plot(steps, r2_mean, 'o', markersize = 1.5, label = '$<r^2>$') pl.plot(steps, fit, 'r', label = 'fit') pl.text(10, 1, r'$<r^2> \approx %.2f t^{%.3f}$'% (popt[0], popt[1]), size = 20) pl.title('Self Avoiding Walk') pl.xlabel('Number of Steps') pl.ylabel(r'$<r^2>$') pl.legend(loc = 'center right') pl.show()
fig = pl.figure(figsize = (10, 10), dpi = 80) ax = fig.gca(projection='3d') ax.plot(results[0][:,0],results[0][:,1],results[0][:,2]) ax.plot(results[1][:,0],results[1][:,1],results[1][:,2]) pl.title('Self Avoiding Walk') pl.show()
|