├── LICENSE ├── README.md └── simulation.py /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Ideal gas simulation 2 | Ideal gas simulation in a 3D system at temperature T and volume L^3, where L is the length of the walls. 3 | 4 | Just execute it and theoretically it will work (as everything). 5 | 6 | The box is supposed to be a cube but you can change it to be the shape you want. By default, the volume remains constant during the animation but you can change it to be dynamic and study, for example, compressions and expansion. 7 | 8 | I encourage you to study, as well as volume changes, temperature (energy) changes. 9 | 10 | As allways, all comments will be very grateful. 11 | 12 | # Notes 13 | There are two important things I should remark: 14 | - In order for collisions to happen on a ''short'' period of time so as to see how the velocities converge to Maxwell-Boltzmann distribution, the radius of the particles must be `~(V/N)^(1/3)`. Otherwise, the momentum exchanged after each iteration will be small. 15 | - Second, the way preassure is calculated is a bit tricky because if `dt` is two big then the particle will pass through the wall without collinding and, as a consequence, without exchanging momenta with the walls. 16 | 17 | 18 | # License 19 | Copyright 2017 labay11 20 | 21 | Licensed under the Apache License, Version 2.0 (the "License"); 22 | you may not use this file except in compliance with the License. 23 | You may obtain a copy of the License at 24 | 25 | http://www.apache.org/licenses/LICENSE-2.0 26 | 27 | Unless required by applicable law or agreed to in writing, software 28 | distributed under the License is distributed on an "AS IS" BASIS, 29 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 30 | See the License for the specific language governing permissions and 31 | limitations under the License. 32 | -------------------------------------------------------------------------------- /simulation.py: -------------------------------------------------------------------------------- 1 | """ 2 | ================= 3 | Ideal gas simulation 4 | ================= 5 | 6 | Ideal gas simulation in a 3D system at temperature T and volume L^3, 7 | where L is the length of the walls. 8 | 9 | The particles that form the system only interact with the wall and 10 | between each other with elastic collisions, no other type of 11 | interaction is concieved (electromagnetic, gravitational...) 12 | 13 | """ 14 | import numpy as np 15 | import matplotlib.pyplot as plt 16 | import matplotlib.animation as animation 17 | import types 18 | 19 | 20 | k_B = 1.380648e-23 # boltzmann contant (J/K) 21 | 22 | 23 | def mod(v): 24 | """ 25 | computes the squared sum over the last axis of the numpy.ndarray v 26 | """ 27 | return np.sum(v * v, axis=-1) 28 | 29 | 30 | def pmod(v, T, m): 31 | """ 32 | Maxwell-Boltzmann's distribuion of probability 33 | for the length of the velocity vector v at temprature T 34 | for a particle of mass m 35 | """ 36 | 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)) 37 | 38 | 39 | class Simulation(animation.TimedAnimation): 40 | """ 41 | Complete code for the ideal gas animation. 42 | """ 43 | 44 | def __init__(self, n_particles, mass, rad, T, V, max_time, dt=0.2): 45 | """ 46 | Initiallisation of parameters 47 | 48 | ::n_particles:: number of particles in the system 49 | 50 | ::mass:: of the particles (identicle for all of them) 51 | 52 | ::rad:: radius of the particles, notice that it must be 53 | of the same order as (V/n_particles)^(1/3) in 54 | order to see them colliding. If the radius is too 55 | small then a few number of collisions would occur. 56 | To remove completely the number of cillisions set the 57 | radius to 0. 58 | 59 | ::T:: temperatura of the system, this will defie the initial 60 | velocity of the particles 61 | 62 | ::V:: volume of the system, this could be a floating-point number or 63 | a function of time. If it is a number then the volume will 64 | remain constant all the time, if it is a function then at each 65 | iteration the volume will be update over time. 66 | 67 | ::max_time:: maximum animation time 68 | """ 69 | 70 | self.PART = n_particles 71 | self.MASS = mass 72 | self.RAD = rad 73 | self.DIAM = 2 * rad 74 | 75 | self.T = T 76 | 77 | if isinstance(V, types.FunctionType): 78 | self.V0 = V(0) 79 | self.V = V 80 | self.Vconst = False 81 | else: 82 | self.V0 = V 83 | self.V = lambda t: V 84 | self.Vconst = True 85 | 86 | self.L = np.power(self.V0, 1/3) # side length 87 | self.halfL = self.L / 2 88 | self.A = 6 * self.L**2 # total superfice area 89 | 90 | self.max_time = max_time 91 | self.dt = dt 92 | self.Nt = int(max_time / self.dt) 93 | 94 | self.evaluate_properties() 95 | 96 | # velocities histogram 97 | self.min_v = 0 98 | self.max_v = self.vmax * 3 99 | self.dv = 0.2 # (m/s) 100 | self.Nv = int((self.max_v - self.min_v) / self.dv) 101 | 102 | # pressure 103 | self.dP = 1 # (s) 104 | self.NP = int(max_time / self.dP) 105 | 106 | self.init_particles() 107 | self.init_figures() 108 | 109 | animation.TimedAnimation.__init__(self, self.fig, interval=1, blit=True, repeat=False) 110 | 111 | def evaluate_properties(self): 112 | """ 113 | Calculates the initial properties of the system according 114 | to the laws of thermodynamics. 115 | """ 116 | 117 | self.P = self.PART * k_B * self.T / self.V0 118 | self.U = 1.5 * self.PART * k_B * self.T 119 | self.vrms = np.sqrt(3 * k_B * self.T / self.MASS) 120 | self.vmax = np.sqrt(2 * k_B * self.T / self.MASS) 121 | self.vmed = np.sqrt(8 * k_B * self.T / (np.pi * self.MASS)) 122 | 123 | def init_particles(self): 124 | """ 125 | Init the particles positions and velocities. 126 | 127 | The initial positions are completely random inside the box. 128 | 129 | The initial velocities are generated by a random unitary vector with 130 | a length given by the average velocity (vmed) at the system temperature. 131 | """ 132 | self.r = np.random.rand(self.PART, 3) * 2 * (self.halfL - self.RAD) - (self.halfL - self.RAD) 133 | 134 | v_polar = np.random.random((self.PART, 2)) 135 | 136 | self.v = np.zeros((self.PART, 3)) 137 | 138 | self.v[:, 0] = np.sin(v_polar[:, 0] * np.pi) * np.cos(v_polar[:, 1] * 2 * np.pi) 139 | self.v[:, 1] = np.sin(v_polar[:, 0] * np.pi) * np.sin(v_polar[:, 1] * 2 * np.pi) 140 | self.v[:, 2] = np.cos(v_polar[:, 0] * np.pi) 141 | 142 | self.v *= self.vrms 143 | 144 | def init_figures(self): 145 | """ 146 | Init the figures, axes, lines... 147 | """ 148 | 149 | self.fig = plt.figure() 150 | 151 | self.ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=2, rowspan=2, projection='3d') # 3D axes 152 | self.ax2 = plt.subplot2grid((3, 3), (2, 0)) # x-y axes 153 | self.ax3 = plt.subplot2grid((3, 3), (2, 1)) # y-z axes 154 | self.ax4 = plt.subplot2grid((3, 3), (2, 2)) # x-z axes 155 | self.ax5 = plt.subplot2grid((3, 3), (0, 2)) # velocities axes 156 | self.ax6 = plt.subplot2grid((3, 3), (1, 2)) # pressure axes 157 | 158 | # Setup ax1: 3d 159 | box_limits = [-self.halfL, self.halfL] 160 | self.ax1.set_xlim3d(box_limits) 161 | self.ax1.set_xlabel('X') 162 | 163 | self.ax1.set_ylim3d(box_limits) 164 | self.ax1.set_ylabel('Y') 165 | 166 | self.ax1.set_zlim3d(box_limits) 167 | self.ax1.set_zlabel('Z') 168 | 169 | self.line_3d = self.ax1.plot([], [], [], ls='None', marker='.')[0] 170 | self.line_3d_cm = self.ax1.plot([0], [0], [0], ls='None', marker='.', color='r')[0] 171 | 172 | # setup ax2: x-y 173 | self.ax2.set_xlabel(r'x') 174 | self.ax2.set_ylabel(r'y') 175 | self.ax2.set_xlim(box_limits) 176 | self.ax2.set_ylim(box_limits) 177 | 178 | self.line_xy = self.ax2.plot([], [], ls='None', marker='.')[0] 179 | self.line_xy_cm = self.ax2.plot([0], [0], ls='None', marker='.', color='r')[0] 180 | 181 | # setup ax3: y-z 182 | self.ax3.set_xlabel(r'y') 183 | self.ax3.set_ylabel(r'z') 184 | self.ax3.set_xlim(box_limits) 185 | self.ax3.set_ylim(box_limits) 186 | 187 | self.line_yz = self.ax3.plot([], [], ls='None', marker='.')[0] 188 | self.line_yz_cm = self.ax3.plot([0], [0], ls='None', marker='.', color='r')[0] 189 | 190 | # setup ax4: x-z 191 | self.ax4.set_xlabel(r'x') 192 | self.ax4.set_ylabel(r'z') 193 | self.ax4.set_xlim(box_limits) 194 | self.ax4.set_ylim(box_limits) 195 | 196 | self.line_xz = self.ax4.plot([], [], ls='None', marker='.')[0] 197 | self.line_xz_cm = self.ax4.plot([0], [0], ls='None', marker='.', color='r')[0] 198 | 199 | # setup ax5: velocities 200 | vs = np.linspace(0, self.vmax * 3, 50) 201 | self.ax5.set_xlabel(r'$v\ (m/s)$') 202 | self.ax5.set_ylabel(r'$N$') 203 | # ax5.set_ylim(0, np.ceil(self.PART * pmod(self.vmax, self.T, self.MASS) / 5)) 204 | self.ax5.plot(vs, self.PART * pmod(vs, self.T, self.MASS) * self.dv, color='r') 205 | 206 | self.vel_x = np.linspace(self.min_v, self.max_v, self.Nv) 207 | self.vel_y = np.zeros(self.Nv) 208 | 209 | self.line_vel = self.ax5.plot([], [], color='b', lw=0.5)[0] 210 | 211 | # setup ax5: pressure 212 | self.ax6.set_xlabel(r'$V\ (m^3)$') 213 | self.ax6.set_ylabel(r'$P\ (Pa)$') 214 | if self.Vconst: 215 | pt = self.PART * k_B * self.T / self.V0 216 | self.ax6.plot([0, self.max_time], [pt, pt], color='r', lw=0.5) 217 | else: 218 | Vx = self.V(np.linspace(0, self.max_time, self.Nt)) 219 | self.ax6.plot(Vx, self.PART * k_B * self.T / Vx, color='r', lw=0.5) 220 | 221 | self.ex_p = 0.0 # accumulated exchanged momentum with the walls 222 | self.last_P = -1 223 | self.P_x = np.zeros(self.NP) 224 | self.P_y = np.zeros(self.NP) 225 | 226 | self.line_p = self.ax6.plot([], [], color='b', lw=0.5)[0] 227 | 228 | self._drawn_artists = [ 229 | self.line_3d, self.line_3d_cm, 230 | self.line_xy, self.line_xy_cm, 231 | self.line_yz, self.line_yz_cm, 232 | self.line_xz, self.line_xz_cm, 233 | self.line_vel, self.line_p] 234 | 235 | def update_volume(self, t): 236 | """ 237 | Sets the new volume and changes the axes limits. 238 | """ 239 | 240 | self.V0 = self.V(t) 241 | self.L = np.power(self.V0, 1/3) 242 | self.halfL = self.L / 2 243 | self.A = 6 * self.L**2 244 | 245 | box_limits = [-self.halfL, self.halfL] 246 | self.ax1.set_xlim3d(box_limits) 247 | self.ax1.set_ylim3d(box_limits) 248 | self.ax1.set_zlim3d(box_limits) 249 | self.ax2.set_xlim(box_limits) 250 | self.ax2.set_ylim(box_limits) 251 | self.ax3.set_xlim(box_limits) 252 | self.ax3.set_ylim(box_limits) 253 | self.ax4.set_xlim(box_limits) 254 | self.ax4.set_ylim(box_limits) 255 | 256 | def _draw_frame(self, t): 257 | self.update_volume(t) 258 | 259 | # update the position 260 | self.r += self.dt * self.v 261 | 262 | # check for collitions with other particles 263 | dists = np.sqrt(mod(self.r - self.r[:, np.newaxis])) 264 | cols2 = (0 < dists) & (dists < self.DIAM) 265 | idx_i, idx_j = np.nonzero(cols2) 266 | # ***possibility to simplify this *** # 267 | for i, j in zip(idx_i, idx_j): 268 | if j < i: 269 | # skip duplications and same particle 270 | continue 271 | 272 | rij = self.r[i] - self.r[j] 273 | d = mod(rij) 274 | vij = self.v[i] - self.v[j] 275 | dv = np.dot(vij, rij) * rij / d 276 | self.v[i] -= dv 277 | self.v[j] += dv 278 | 279 | # update the positions so they are no longer in contact 280 | self.r[i] += self.dt * self.v[i] 281 | self.r[j] += self.dt * self.v[j] 282 | 283 | # check for collition with the walls 284 | walls = np.nonzero(np.abs(self.r) + self.RAD > self.halfL) 285 | self.v[walls] *= -1 286 | self.r[walls] -= self.RAD * np.sign(self.r[walls]) 287 | 288 | # calc the position of the center of masses 289 | CM = np.sum(self.r, axis=0) / self.PART 290 | 291 | # plot the new coordinates 292 | self.line_3d.set_data(self.r[:, 0], self.r[:, 1]) 293 | self.line_3d.set_3d_properties(self.r[:, 2]) 294 | 295 | self.line_3d_cm.set_data(CM[0], CM[1]) 296 | self.line_3d_cm.set_3d_properties(CM[2]) 297 | 298 | self.line_xy.set_data(self.r[:, 0], self.r[:, 1]) 299 | self.line_xy_cm.set_data(CM[0], CM[1]) 300 | 301 | self.line_yz.set_data(self.r[:, 1], self.r[:, 2]) 302 | self.line_yz_cm.set_data(CM[1], CM[2]) 303 | 304 | self.line_xz.set_data(self.r[:, 0], self.r[:, 2]) 305 | self.line_xz_cm.set_data(CM[0], CM[2]) 306 | 307 | # make velocities histogram 308 | v_mod = np.sqrt(mod(self.v)) 309 | 310 | for k in range(self.Nv): 311 | self.vel_y[k] = np.count_nonzero((k*self.dv < v_mod) & (v_mod < (k + 1)*self.dv)) 312 | 313 | self.line_vel.set_data(self.vel_x, self.vel_y) 314 | 315 | # add the momentum exchanged in this iteration to the accumulated one 316 | self.ex_p += 2 * self.MASS * np.sum(np.abs(self.v[walls])) 317 | i = int(t / self.dP) 318 | if i > self.last_P + 1: 319 | # calculate the pressure after self.dP seconds 320 | 321 | self.last_P = i - 1 322 | 323 | A_avg = self.A if self.Vconst else (self.A + 6 * np.power(self.V(t - self.dP), 2/3)) / 2 324 | 325 | self.P_x[self.last_P] = (t if self.Vconst else self.V0) 326 | self.P_y[self.last_P] = self.ex_p / (self.dP * A_avg) 327 | 328 | self.ex_p = 0.0 329 | 330 | self.line_p.set_data(self.P_x[:i], self.P_y[:i]) 331 | self.ax6.set_ylim(np.min(self.P_y[:i]), np.max(self.P_y[:i])) 332 | 333 | def new_frame_seq(self): 334 | return iter(np.linspace(0, self.max_time, self.Nt)) 335 | 336 | def save_data(self): 337 | with open('preassure.txt', 'w') as outf: 338 | t = np.linspace(0, self.max_time, self.NP) 339 | for i in range(self.NP): 340 | outf.write('%.5f\t%.5f\t%.5g\n' % (t[i], self.P_x[i], self.P_y[i])) 341 | 342 | with open('hist_vel.txt', 'w') as outf: 343 | for i in range(self.Nv): 344 | outf.write('%.5f\t%.5g\n' % (self.vel_x[i], self.vel_y[i])) 345 | 346 | 347 | def V(t, V0, Vf, t_max): 348 | return V0 + (Vf - V0) * t / t_max 349 | 350 | 351 | PARTICLES = 500 352 | MASS = 1.2e-20 353 | RADIUS = 0.01 354 | TEMPERATURE = 500 355 | V0, Vf = 0.5, 15 356 | T_MAX = 1000 357 | 358 | ani = Simulation(PARTICLES, MASS, RADIUS, TEMPERATURE, 2, T_MAX, 0.05) 359 | # ani = Simulation(PARTICLES, MASS, RADIUS, TEMPERATURE, lambda t: V(t, V0, Vf, T_MAX), T_MAX) 360 | # ani.save('test_sub.mp4', writer='imagemagick', fps=5) 361 | plt.show() 362 | ani.save_data() 363 | --------------------------------------------------------------------------------