-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbrownian_motion_3d.py
414 lines (364 loc) · 10.7 KB
/
brownian_motion_3d.py
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
#! /usr/bin/env python
#
import numpy as np
import matplotlib.pyplot as plt
import time
from mpl_toolkits.mplot3d import Axes3D
from sys import exit
def brownian_displacement_display(k, n, m, d, t, dsq):
# *****************************************************************************80
#
# BROWNIAN_DISPLACEMENT_DISPLAY displays average Brownian motion displacement.
#
# Discussion:
#
# Thanks to Feifei Xu for pointing out a missing factor of 2 in the
# displacement calculation.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 10 June 2018
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer K, the number of repetitions.
#
# Input, integer N, the number of time steps.
#
# Input, integer M, the spatial dimension.
#
# Input, real D, the diffusion coefficient.
#
# Input, real T, the total time.
#
# Input, real DSQ(K,N), the displacements over time for each repetition.
#
# Get the T values.
tvec = np.linspace(0, t, n)
# Select 5 random trajectories for display.
for s in range(0, 5):
i = int(k * np.random.rand(1))
plt.plot(tvec, dsq[i, :], 'b-')
# Display the average displacement.
dsq_ave = np.sum(dsq, 0) / float(k)
plt.plot(tvec, dsq_ave, 'r-', linewidth=2)
# Display the ideal displacment.
dsq_ideal = 2.0 * m * d * tvec
plt.plot(tvec, dsq_ideal, 'k-', linewidth=3)
plt.grid(True)
plt.xlabel('<--T-->')
plt.ylabel('<--D^2-->')
plt.title('Squared displacement (Red), Predicted (Black), Samples (Blue)')
filename = 'displacement_' + str(m) + '.png'
plt.savefig(filename)
plt.show()
plt.clf()
print('')
print(' Plot saved as "%s".' % (filename))
return
def brownian_displacement_simulation(k=20, n=1001, m=3, d=10.0, t=1.0):
# *****************************************************************************80
#
# BROWNIAN_DISPLACEMENT_SIMULATION simulates Brownian displacement.
#
# Discussion:
#
# Thanks to Feifei Xu for pointing out a missing factor of 2 in the
# stepsize calculation, 08 March 2016.
#
# This function computes the square of the distance of the Brownian
# particle from the starting point, repeating this calculation
# several times.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 10 June 2018
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, int K, the number of repetitions.
#
# Input, int N, the number of time steps to take, plus 1.
#
# Input, int M, the spatial dimension.
#
# Input, real D, the diffusion coefficient. This might be 10.0.
# Computationally, this is simply a scale factor between time and space.
#
# Input, real T, the total time.
#
# Output, real DSQ(K,N), the displacements over time for each repetition.
# DSQ(:,1) is 0.0, because we include the displacement at the initial time.
#
dsq = np.zeros([k, n])
for i in range(0, k):
x = brownian_motion_simulation(m, n, d, t)
dsq[i, 0:n] = np.sum(x[0:m, 0:n] ** 2, 0)
return dsq
def brownian_motion_display(m, n, x):
# *****************************************************************************80
#
# BROWNIAN_MOTION_DISPLAY displays successive Brownian motion positions.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 26 April 2018
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer M, the spatial dimension.
# M should be 1, 2 or 3.
#
# Input, integer N, the number of time steps.
#
# Input, real X(M,N), the particle positions.
#
if (m == 1):
y = np.linspace(0, n - 1, n) / float(n - 1)
plt.plot(x[0, :], y[:], 'b', linewidth=2)
plt.plot(x[0, 0], y[0], 'g.', markersize=35)
plt.plot(x[0, n-1], y[n-1], 'r.', markersize=35)
plt.grid(True)
plt.xlabel('<--X-->')
plt.ylabel('<--Time-->')
plt.title('Brownian motion simulation in 1D')
filename = 'motion_' + str(m) + 'd.png'
plt.savefig(filename)
plt.show()
plt.clf()
elif (m == 2):
plt.plot(x[0, :], x[1, :], 'b', LineWidth=2)
plt.plot(x[0, 0], x[1, 0], 'g.', markersize=35)
plt.plot(x[0, n-1], x[1, n-1], 'r.', markersize=35)
plt.grid(True)
plt.xlabel('<--X-->')
plt.ylabel('<--Y-->')
plt.title('Brownian motion simulation in 2D')
plt.axis('equal')
filename = 'motion_' + str(m) + 'd.png'
plt.savefig(filename)
plt.show()
plt.clf()
elif (m == 3 or 4):
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot(x[0, :], x[1, :], x[2, :], 'b', linewidth=2)
ax.scatter(x[0, 0], x[1, 0], x[2, 0], c='g', marker='o', s=100)
ax.scatter(x[0, n-1], x[1, n-1], x[2, n-1], c='r', marker='o', s=100)
ax.grid(True)
ax.set_xlabel('<--X-->')
ax.set_ylabel('<--Y-->')
ax.set_zlabel('<--Z-->')
plt.title('Brownian motion simulation in 3D')
#plt.axis ( 'equal' )
filename = 'motion_' + str(m) + 'd.png'
plt.savefig(filename)
plt.show()
plt.clf()
else:
print('')
print('BROWNIAN_MOTION_DISPLAY - Fatal error!')
print(' Cannot display data except for M = 1, 2, 3.')
exit('BROWNIAN_MOTION_DISPLAY - Fatal error!')
print('')
print(' Plot saved as "%s".' % (filename))
return
def brownian_motion_simulation(m=3, n=1001, d=10.0, t=1.0):
# *****************************************************************************80
#
# BROWNIAN_MOTION_SIMULATION simulates Brownian motion.
#
# Discussion:
#
# Thanks to Feifei Xu for pointing out a missing factor of 2 in the
# stepsize calculation, 08 March 2016.
#
# Thanks to Joerg Peter Pfannmoeller for pointing out a missing factor
# of M in the stepsize calculation, 23 April 2018.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 10 June 2018
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, int M, the spatial dimension.
#
# Input, int N, the number of time steps to take, plus 1.
#
# Input, real D, the diffusion coefficient.
#
# Input, real T, the total time.
#
# Output, real X(M,N), the initial position at time 0.0, and
# the N-1 successive locations of the particle.
#
# Set the time step.
dt = t / float(n - 1)
# Compute the individual steps.
x = np.zeros([m, n])
if (m >= 4):
x[0, 0] = 0
x[1, 0] = 0
x[2, 0] = 1
for j in range(1, n):
# S is the stepsize
s = np.sqrt(2.0 * m * d * dt) * np.random.randn(1)
# Direction is random.
if (m == 1):
dx = np.random.randn(m)
elif (m == 4):
dx = np.random.randn(2)
norm_dx = np.sqrt(np.sum(dx ** 2))
phi = np.arctan2(x[1, j-1], x[0, j-1])
rho = np.arccos(x[2, j-1])
dx[0] = phi + s * dx[0] / norm_dx
dx[1] = rho + s * dx[1] / norm_dx
elif (m == 5):
dx = np.random.randn(3)
norm_dx = np.sqrt(np.sum(dx ** 2))
rad = np.sqrt(np.sum(x[0:3,j-1] ** 2))
phi = np.arctan2(x[1, j-1]/rad, x[0, j-1]/rad)
rho = np.arccos(x[2, j-1]/rad)
dx[0] = phi + s * dx[0] / norm_dx
dx[1] = rho + s * dx[1] / norm_dx
dx[2] = 1 + s * dx[2] / norm_dx / 2
else:
dx = np.random.randn(m)
norm_dx = np.sqrt(np.sum(dx ** 2))
for i in range(0, m):
dx[i] = s * dx[i] / norm_dx
# Each position is the sum of the previous steps.
if (m == 4):
x[0, j] = np.cos(dx[0])*np.sin(dx[1])
x[1, j] = np.sin(dx[0])*np.sin(dx[1])
x[2, j] = np.cos(dx[1])
elif (m == 5):
x[0, j] = dx[2]*np.cos(dx[0])*np.sin(dx[1])
x[1, j] = dx[2]*np.sin(dx[0])*np.sin(dx[1])
x[2, j] = dx[2]*np.cos(dx[1])
else:
x[0:m, j] = x[0:m, j-1] + dx[0:m]
return x
def brownian_motion_simulation_test():
# *****************************************************************************80
#
# BROWNIAN_MOTION_SIMULATION_TEST tests the BROWNIAN_MOTION_SIMULATION library.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 10 June 2018
#
# Author:
#
# John Burkardt
#
print('')
print('BROWNIAN_MOTION_SIMULATION_TEST')
print(' Python version')
print(' Test the BROWNIAN_MOTION_SIMULATION library.')
#
# Compute the path of a particle undergoing Brownian motion.
#
m = 1
n = 1001
d = 10.0
t = 1.0
x = brownian_motion_simulation(m, n, d, t)
brownian_motion_display(m, n, x)
#
# Estimate the average displacement of the particle from the origin
# as a function of time.
#
k = 40
n = 1001
d = 10.0
t = 1.0
dsq = brownian_displacement_simulation(k, n, m, d, t)
brownian_displacement_display(k, n, m, d, t, dsq)
#
# Terminate.
#
print('')
print('BROWNIAN_MOTION_SIMULATION_TEST')
print(' Normal end of execution.')
return
def timestamp():
# *****************************************************************************80
#
# TIMESTAMP prints the date as a timestamp.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 06 April 2013
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# None
#
t = time.time()
print(time.ctime(t))
return None
if __name__ == '__main__':
timestamp()
print('')
print('BROWNIAN_MOTION_SIMULATION_TEST')
print(' Python version')
print(' Test the BROWNIAN_MOTION_SIMULATION library.')
m = 5
n = 1001
d = 10.0
t = 1.0
k = 40
x = brownian_motion_simulation(m, n, d, t)
dsq = brownian_displacement_simulation(k, n, m, d, t)
brownian_motion_display(m, n, x)
brownian_displacement_display(k, n, m, d, t, dsq)
print('')
print('BROWNIAN_MOTION_SIMULATION_TEST')
print(' Normal end of execution.')
timestamp()