-
Notifications
You must be signed in to change notification settings - Fork 7
/
simulation.py
362 lines (273 loc) · 11.9 KB
/
simulation.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
"""
=================
Ideal gas simulation
=================
Ideal gas simulation in a 3D system at temperature T and volume L^3,
where L is the length of the walls.
The particles that form the system only interact with the wall and
between each other with elastic collisions, no other type of
interaction is concieved (electromagnetic, gravitational...)
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import types
k_B = 1.380648e-23 # boltzmann contant (J/K)
def mod(v):
"""
computes the squared sum over the last axis of the numpy.ndarray v
"""
return np.sum(v * v, axis=-1)
def pmod(v, T, m):
"""
Maxwell-Boltzmann's distribuion of probability
for the length of the velocity vector v at temprature T
for a particle of mass m
"""
return 4 * np.pi * v**2 * np.power(m / (2 * np.pi * k_B * T), 3 / 2) * np.exp(- m * v**2 / (2 * k_B * T))
class Simulation(animation.TimedAnimation):
"""
Complete code for the ideal gas animation.
"""
def __init__(self, n_particles, mass, rad, T, V, max_time, dt=0.2):
"""
Initiallisation of parameters
::n_particles:: number of particles in the system
::mass:: of the particles (identicle for all of them)
::rad:: radius of the particles, notice that it must be
of the same order as (V/n_particles)^(1/3) in
order to see them colliding. If the radius is too
small then a few number of collisions would occur.
To remove completely the number of cillisions set the
radius to 0.
::T:: temperatura of the system, this will defie the initial
velocity of the particles
::V:: volume of the system, this could be a floating-point number or
a function of time. If it is a number then the volume will
remain constant all the time, if it is a function then at each
iteration the volume will be update over time.
::max_time:: maximum animation time
"""
self.PART = n_particles
self.MASS = mass
self.RAD = rad
self.DIAM = 2 * rad
self.T = T
if isinstance(V, types.FunctionType):
self.V0 = V(0)
self.V = V
self.Vconst = False
else:
self.V0 = V
self.V = lambda t: V
self.Vconst = True
self.L = np.power(self.V0, 1/3) # side length
self.halfL = self.L / 2
self.A = 6 * self.L**2 # total superfice area
self.max_time = max_time
self.dt = dt
self.Nt = int(max_time / self.dt)
self.evaluate_properties()
# velocities histogram
self.min_v = 0
self.max_v = self.vmax * 3
self.dv = 0.2 # (m/s)
self.Nv = int((self.max_v - self.min_v) / self.dv)
# pressure
self.dP = 1 # (s)
self.NP = int(max_time / self.dP)
self.init_particles()
self.init_figures()
animation.TimedAnimation.__init__(self, self.fig, interval=1, blit=True, repeat=False)
def evaluate_properties(self):
"""
Calculates the initial properties of the system according
to the laws of thermodynamics.
"""
self.P = self.PART * k_B * self.T / self.V0
self.U = 1.5 * self.PART * k_B * self.T
self.vrms = np.sqrt(3 * k_B * self.T / self.MASS)
self.vmax = np.sqrt(2 * k_B * self.T / self.MASS)
self.vmed = np.sqrt(8 * k_B * self.T / (np.pi * self.MASS))
def init_particles(self):
"""
Init the particles positions and velocities.
The initial positions are completely random inside the box.
The initial velocities are generated by a random unitary vector with
a length given by the average velocity (vmed) at the system temperature.
"""
self.r = np.random.rand(self.PART, 3) * 2 * (self.halfL - self.RAD) - (self.halfL - self.RAD)
v_polar = np.random.random((self.PART, 2))
self.v = np.zeros((self.PART, 3))
self.v[:, 0] = np.sin(v_polar[:, 0] * np.pi) * np.cos(v_polar[:, 1] * 2 * np.pi)
self.v[:, 1] = np.sin(v_polar[:, 0] * np.pi) * np.sin(v_polar[:, 1] * 2 * np.pi)
self.v[:, 2] = np.cos(v_polar[:, 0] * np.pi)
self.v *= self.vrms
def init_figures(self):
"""
Init the figures, axes, lines...
"""
self.fig = plt.figure()
self.ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=2, rowspan=2, projection='3d') # 3D axes
self.ax2 = plt.subplot2grid((3, 3), (2, 0)) # x-y axes
self.ax3 = plt.subplot2grid((3, 3), (2, 1)) # y-z axes
self.ax4 = plt.subplot2grid((3, 3), (2, 2)) # x-z axes
self.ax5 = plt.subplot2grid((3, 3), (0, 2)) # velocities axes
self.ax6 = plt.subplot2grid((3, 3), (1, 2)) # pressure axes
# Setup ax1: 3d
box_limits = [-self.halfL, self.halfL]
self.ax1.set_xlim3d(box_limits)
self.ax1.set_xlabel('X')
self.ax1.set_ylim3d(box_limits)
self.ax1.set_ylabel('Y')
self.ax1.set_zlim3d(box_limits)
self.ax1.set_zlabel('Z')
self.line_3d = self.ax1.plot([], [], [], ls='None', marker='.')[0]
self.line_3d_cm = self.ax1.plot([0], [0], [0], ls='None', marker='.', color='r')[0]
# setup ax2: x-y
self.ax2.set_xlabel(r'x')
self.ax2.set_ylabel(r'y')
self.ax2.set_xlim(box_limits)
self.ax2.set_ylim(box_limits)
self.line_xy = self.ax2.plot([], [], ls='None', marker='.')[0]
self.line_xy_cm = self.ax2.plot([0], [0], ls='None', marker='.', color='r')[0]
# setup ax3: y-z
self.ax3.set_xlabel(r'y')
self.ax3.set_ylabel(r'z')
self.ax3.set_xlim(box_limits)
self.ax3.set_ylim(box_limits)
self.line_yz = self.ax3.plot([], [], ls='None', marker='.')[0]
self.line_yz_cm = self.ax3.plot([0], [0], ls='None', marker='.', color='r')[0]
# setup ax4: x-z
self.ax4.set_xlabel(r'x')
self.ax4.set_ylabel(r'z')
self.ax4.set_xlim(box_limits)
self.ax4.set_ylim(box_limits)
self.line_xz = self.ax4.plot([], [], ls='None', marker='.')[0]
self.line_xz_cm = self.ax4.plot([0], [0], ls='None', marker='.', color='r')[0]
# setup ax5: velocities
vs = np.linspace(0, self.vmax * 3, 50)
self.ax5.set_xlabel(r'$v\ (m/s)$')
self.ax5.set_ylabel(r'$N$')
# ax5.set_ylim(0, np.ceil(self.PART * pmod(self.vmax, self.T, self.MASS) / 5))
self.ax5.plot(vs, self.PART * pmod(vs, self.T, self.MASS) * self.dv, color='r')
self.vel_x = np.linspace(self.min_v, self.max_v, self.Nv)
self.vel_y = np.zeros(self.Nv)
self.line_vel = self.ax5.plot([], [], color='b', lw=0.5)[0]
# setup ax5: pressure
self.ax6.set_xlabel(r'$V\ (m^3)$')
self.ax6.set_ylabel(r'$P\ (Pa)$')
if self.Vconst:
pt = self.PART * k_B * self.T / self.V0
self.ax6.plot([0, self.max_time], [pt, pt], color='r', lw=0.5)
else:
Vx = self.V(np.linspace(0, self.max_time, self.Nt))
self.ax6.plot(Vx, self.PART * k_B * self.T / Vx, color='r', lw=0.5)
self.ex_p = 0.0 # accumulated exchanged momentum with the walls
self.last_P = -1
self.P_x = np.zeros(self.NP)
self.P_y = np.zeros(self.NP)
self.line_p = self.ax6.plot([], [], color='b', lw=0.5)[0]
self._drawn_artists = [
self.line_3d, self.line_3d_cm,
self.line_xy, self.line_xy_cm,
self.line_yz, self.line_yz_cm,
self.line_xz, self.line_xz_cm,
self.line_vel, self.line_p]
def update_volume(self, t):
"""
Sets the new volume and changes the axes limits.
"""
self.V0 = self.V(t)
self.L = np.power(self.V0, 1/3)
self.halfL = self.L / 2
self.A = 6 * self.L**2
box_limits = [-self.halfL, self.halfL]
self.ax1.set_xlim3d(box_limits)
self.ax1.set_ylim3d(box_limits)
self.ax1.set_zlim3d(box_limits)
self.ax2.set_xlim(box_limits)
self.ax2.set_ylim(box_limits)
self.ax3.set_xlim(box_limits)
self.ax3.set_ylim(box_limits)
self.ax4.set_xlim(box_limits)
self.ax4.set_ylim(box_limits)
def _draw_frame(self, t):
self.update_volume(t)
# update the position
self.r += self.dt * self.v
# check for collitions with other particles
dists = np.sqrt(mod(self.r - self.r[:, np.newaxis]))
cols2 = (0 < dists) & (dists < self.DIAM)
idx_i, idx_j = np.nonzero(cols2)
# ***possibility to simplify this *** #
for i, j in zip(idx_i, idx_j):
if j < i:
# skip duplications and same particle
continue
rij = self.r[i] - self.r[j]
d = mod(rij)
vij = self.v[i] - self.v[j]
dv = np.dot(vij, rij) * rij / d
self.v[i] -= dv
self.v[j] += dv
# update the positions so they are no longer in contact
self.r[i] += self.dt * self.v[i]
self.r[j] += self.dt * self.v[j]
# check for collition with the walls
walls = np.nonzero(np.abs(self.r) + self.RAD > self.halfL)
self.v[walls] *= -1
self.r[walls] -= self.RAD * np.sign(self.r[walls])
# calc the position of the center of masses
CM = np.sum(self.r, axis=0) / self.PART
# plot the new coordinates
self.line_3d.set_data(self.r[:, 0], self.r[:, 1])
self.line_3d.set_3d_properties(self.r[:, 2])
self.line_3d_cm.set_data(CM[0], CM[1])
self.line_3d_cm.set_3d_properties(CM[2])
self.line_xy.set_data(self.r[:, 0], self.r[:, 1])
self.line_xy_cm.set_data(CM[0], CM[1])
self.line_yz.set_data(self.r[:, 1], self.r[:, 2])
self.line_yz_cm.set_data(CM[1], CM[2])
self.line_xz.set_data(self.r[:, 0], self.r[:, 2])
self.line_xz_cm.set_data(CM[0], CM[2])
# make velocities histogram
v_mod = np.sqrt(mod(self.v))
for k in range(self.Nv):
self.vel_y[k] = np.count_nonzero((k*self.dv < v_mod) & (v_mod < (k + 1)*self.dv))
self.line_vel.set_data(self.vel_x, self.vel_y)
# add the momentum exchanged in this iteration to the accumulated one
self.ex_p += 2 * self.MASS * np.sum(np.abs(self.v[walls]))
i = int(t / self.dP)
if i > self.last_P + 1:
# calculate the pressure after self.dP seconds
self.last_P = i - 1
A_avg = self.A if self.Vconst else (self.A + 6 * np.power(self.V(t - self.dP), 2/3)) / 2
self.P_x[self.last_P] = (t if self.Vconst else self.V0)
self.P_y[self.last_P] = self.ex_p / (self.dP * A_avg)
self.ex_p = 0.0
self.line_p.set_data(self.P_x[:i], self.P_y[:i])
self.ax6.set_ylim(np.min(self.P_y[:i]), np.max(self.P_y[:i]))
def new_frame_seq(self):
return iter(np.linspace(0, self.max_time, self.Nt))
def save_data(self):
with open('preassure.txt', 'w') as outf:
t = np.linspace(0, self.max_time, self.NP)
for i in range(self.NP):
outf.write('%.5f\t%.5f\t%.5g\n' % (t[i], self.P_x[i], self.P_y[i]))
with open('hist_vel.txt', 'w') as outf:
for i in range(self.Nv):
outf.write('%.5f\t%.5g\n' % (self.vel_x[i], self.vel_y[i]))
def V(t, V0, Vf, t_max):
return V0 + (Vf - V0) * t / t_max
PARTICLES = 500
MASS = 1.2e-20
RADIUS = 0.01
TEMPERATURE = 500
V0, Vf = 0.5, 15
T_MAX = 1000
ani = Simulation(PARTICLES, MASS, RADIUS, TEMPERATURE, 2, T_MAX, 0.05)
# ani = Simulation(PARTICLES, MASS, RADIUS, TEMPERATURE, lambda t: V(t, V0, Vf, T_MAX), T_MAX)
# ani.save('test_sub.mp4', writer='imagemagick', fps=5)
plt.show()
ani.save_data()