forked from csc-training/hpc-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
heat.py
54 lines (42 loc) · 1.51 KB
/
heat.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
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
# Set the colormap
plt.rcParams['image.cmap'] = 'BrBG'
def evolve(u, u_previous, a, dt, dx2, dy2):
"""Explicit time evolution.
u: new temperature field
u_previous: previous field
a: diffusion constant
dt: time step. """
n, m = u.shape
for i in range(1, n-1):
for j in range(1, m-1):
u[i, j] = u_previous[i, j] + a * dt * ( \
(u_previous[i+1, j] - 2*u_previous[i, j] + \
u_previous[i-1, j]) / dx2 + \
(u_previous[i, j+1] - 2*u_previous[i, j] + \
u_previous[i, j-1]) / dy2 )
u_previous[:] = u[:]
def iterate(field, field0, a, dx, dy, timesteps, image_interval):
"""Run fixed number of time steps of heat equation"""
dx2 = dx**2
dy2 = dy**2
# For stability, this is the largest interval possible
# for the size of the time-step:
dt = dx2*dy2 / ( 2*a*(dx2+dy2) )
for m in range(1, timesteps+1):
evolve(field, field0, a, dt, dx2, dy2)
if m % image_interval == 0:
write_field(field, m)
def init_fields(filename):
# Read the initial temperature field from file
field = np.loadtxt(filename)
field0 = field.copy() # Array for field of previous time step
return field, field0
def write_field(field, step):
plt.gca().clear()
plt.imshow(field)
plt.axis('off')
plt.savefig('heat_{0:03d}.png'.format(step))