import numpy as np
import matplotlib.pyplot as plt

def hompoisson(rate, trials, duration) :
    spikes = []
    for k in range(trials) :
        times = []
        t = 0.0
        while t < duration :
            t += np.random.exponential(1/rate)
            times.append( t )
        spikes.append( times )
    return spikes

def inhompoisson(rate, trials, dt) :
    spikes = []
    p = rate*dt
    for k in range(trials) :
        x = np.random.rand(len(rate))
        times = dt*np.nonzero(x<p)[0]
        spikes.append( times )
    return spikes


def pifspikes(input, trials, dt, D=0.1) :
    vreset = 0.0
    vthresh = 1.0
    tau = 1.0
    spikes = []
    for k in range(trials) :
        times = []
        v = vreset
        noise = np.sqrt(2.0*D)*np.random.randn(len(input))/np.sqrt(dt)
        for k in xrange(len(noise)) :
            v += (input[k]+noise[k])*dt/tau
            if v >= vthresh :
                v = vreset
                times.append(k*dt)
        spikes.append( times )
    return spikes

# parameter:
rate = 20.0
drate = 50.0
trials = 10
duration = 2.0
dt = 0.001
tau = 0.1;

# homogeneous spike trains:
homspikes = hompoisson(rate, trials, duration)

# OU noise:
rng = np.random.RandomState(54637281)
time = np.arange(0.0, duration, dt)
x = np.zeros(time.shape)+rate
n = rng.randn(len(time))*drate*tau/np.sqrt(dt)+rate
for k in xrange(1,len(x)) :
    x[k] = x[k-1] + (n[k]-x[k-1])*dt/tau
x[x<0.0] = 0.0

# inhomogeneous spike trains:
#inhspikes = inhompoisson(x, trials, dt)
# pif spike trains:
inhspikes = pifspikes(x, trials, dt, D=0.3)

fig = plt.figure( figsize=(9,4) )
ax = fig.add_subplot(1, 2, 1)
ax.set_title('stationary')
ax.set_xlim(0.0, duration)
ax.set_ylim(-0.5, trials-0.5)
ax.set_xlabel('Time [s]')
ax.set_ylabel('Trials')
ax.eventplot(homspikes, colors=[[0, 0, 0]], linelength=0.8)

ax = fig.add_subplot(1, 2, 2)
ax.set_title('non-stationary')
ax.set_xlim(0.0, duration)
ax.set_ylim(-0.5, trials-0.5)
ax.set_xlabel('Time [s]')
ax.set_ylabel('Trials')
ax.eventplot(inhspikes, colors=[[0, 0, 0]], linelength=0.8)

plt.tight_layout()
plt.savefig('rasterexamples.pdf')
plt.close()
