'''
This small script is intended to illustrate solutions to the
diffusion equation as discussed in the 2017-09-26 lecture of the
Theoretical biophyics course.
'''

import matplotlib.pyplot as plt
import numpy as np
plt.ion()

cols = ['b', 'm', 'g', 'r']

# return the greens function of the diffusion equation.
def diffusion_solution(x,t, D, v):
	return 1.0/np.sqrt(4*np.pi*D*t)*np.exp(-(x-v*t)**2/(4*D*t))

# return the flux for a distribution P, a diffusion coefficient D,
# advection velocity v and the step size dx (this is the discretization
# of P)
def get_flux(P, D, v, dx):
	return 0.5*v*(P[1:]+P[:-1]) - D*(P[1:] - P[:-1])/dx

# SIMPLE ELEMENTARY SOLUTIONS
x = np.linspace(-10,10,200)
D = 1.0
v = 0.5 # play with these values

fig = plt.figure()
# loop over 4 time points, plot the results
for t in [1,2,4,8]:
	sol = diffusion_solution(x, t, D, v)
	plt.plot(x, sol, label = 't='+str(t))

plt.legend()
plt.xlabel('x')


# ABSORBING BOUNDARY AT x=0
x = np.linspace(-10,10,200)
D = 1.0
v = 0.0 # this only works for v=0

fig = plt.figure()
x0=3
for t in [1,2,4,8]:
	sol = diffusion_solution(x-x0, t, D, v)
	anti_sol = diffusion_solution(x+x0, t, D, v)
	P = sol - anti_sol
	plt.plot([0,0], [-.1,.1], lw=2, c='k', alpha=0.3)
	plt.plot(x, P, label = 't='+str(t), lw=3)
	plt.plot(x, sol, lw=1, c='k')
	plt.plot(x, -anti_sol,lw=1, c='k')

plt.legend()
plt.xlabel('x')


# REFLECTING BOUNDARY AT x=0
x = np.linspace(-12,12,200)
dx = x[1]-x[0]
D = 1.0
v = 0.0

fig = plt.figure()
x0=3
for ti, t in enumerate([1,2,4,8]):
	sol = diffusion_solution(x-x0, t, D, v)
	anti_sol = diffusion_solution(x+x0, t, D, v)
	P = sol + anti_sol
	plt.plot([0,0], [-.0,.3], lw=2, c='k', alpha=0.3)
	plt.plot(x, P,c=cols[ti], label = 't='+str(t), lw=3)
	plt.plot(x, sol, lw=1, c='k')
	plt.plot(x, +anti_sol,lw=1, c='k')
	# calculate the probability mass in the x>0 area
	positive_x = x>0
	integral = np.sum(P*dx*positive_x)
	print("t="+str(t), integral)

plt.legend()
plt.xlabel('x')

# FLUX across the absorbing boundary.
fig = plt.figure()
x0=3
x = np.linspace(-20,20,200)
time_array = np.linspace(0.001, 10, 100)
flux_vs_time = []
for t in time_array:
	sol = diffusion_solution(x-x0, t, D, v)
	anti_sol = diffusion_solution(x+x0, t, D, v)
	P = sol - anti_sol
	flux = get_flux(P, D, v, dx)
	flux_vs_time.append(flux[100])

plt.plot(time_array, flux_vs_time, lw=1)
plt.xlabel('t')
