import graphics
import time
import psyco
psyco.full()


update_freq=10

def show(data):
    h=len(data)
    w=len(data[0])
    for y in range(h):
        for x in range(w):
            value = data[y][x]
            if value<0: color = (0,0,min(abs(int(value)),255))
            else: color=(min(255,6*int(value)),0,0) #Max 40C so we increase
            screen.plot((x,y), color)
    screen.update()
    
def solve(data):
    global update_freq
    
    h=len(data)-1
    w=len(data[0])-1
    epsilon = 0.001*h*w
    delta = epsilon+1.0
    cnt = update_freq-1
    
    while(delta>epsilon):
        delta=0.0
        cnt=cnt+1
        if cnt==update_freq:
            show(data)
            cnt=0
        for y in range(1,h):
            for x in range(1,w):
                old=data[y][x]
                data[y][x]=0.2*(data[y][x]+data[y-1][x]+data[y+1][x]+data[y][x-1]+data[y][x+1])
                delta+=abs(old-data[y][x])

xsize=250; ysize=250

problem = [(xsize)*[0] for i in range(ysize)]
for i in range(xsize):
    problem[0][i]=  +40.0
    problem[ysize-1][i]=-273.15
for i in range(ysize):
    problem[i][0]=-273.15
    problem[i][xsize-1]=-273.15

screen = graphics.graphicsScreen(xsize,ysize)
start=time.time()
solve(problem)
stop=time.time()
print 'Solved in '+str(stop-start)+' seconds'

