#imports
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as st

# ====================================================================
# Exercise 1
# ====================================================================
T = 10.
lam = 2.
# 1)
M = st.poisson.rvs(T*lam) # Total number of points
points = st.uniform.rvs(0,T,size = M)
# 2)
# We construct the function N by iterating on the elements of points.
K = 500 # Number of points in the discretization, pick any number large enough
tvals = np.linspace(0,T,num = K) 
N = np.zeros(K) # Initialize an array of zeros for N
for m in range(M): # Iterating on points
    temp = np.array([ (t >= points[m]) for t in tvals]) # This creates a list of booleans,
    # then convert it into an np.array. In computations, a boolean array is equivalent
    # to an array of zeros and ones.
    # Alternatively, we could have simply defined temp = (tvals >= points[m])
    N += temp # Add this array to N
# Graphical representation
plt.figure()
plt.plot(tvals,N)
plt.show()


# ====================================================================
# Exercise 2
# ====================================================================
# 1)
T = 5.
lammax = 10.
def Pi(T,lammax):
    N = st.poisson.rvs(mu = T*lammax)
    xvals = st.uniform.rvs(loc = 0., scale = T, size = N)
    yvals = st.uniform.rvs(loc = 0., scale = lammax, size = N)
    return np.array([xvals,yvals])

points = Pi(T,lammax)
plt.figure()
plt.scatter(points[0,:], points[1,:])
plt.axis('scaled')
plt.xlim((0.,T))
plt.ylim((0.,lammax))
plt.show()

# 2), 3)
# Our algorithm is the following: for lam fixed, first  we look at the restriction of
# Pi on [0,T]*[0,lam], then we project each point onto its first coordinate. The
# first operation yields a PPM with intensity Leb_{[0,T]*[0,lam]}, and the second
# yields a PPM with intensity lam*Leb_{[0,T]}.
# In anticipation with the next question, we write this algorithm as a function
# of lam and the initial points Pi
def PoissonTemporel(pointsPi, lam):
    # Restriction
    xlist = []
    ylist = []
    NpointsPi = np.shape(pointsPi)[1] # Extract number of points in pointsPi
    for k in range(NpointsPi): # Iteration over pointsPi
        if pointsPi[1,k] <= lam:
            xlist += [pointsPi[0,k]]
            ylist += [pointsPi[1,k]]
    pointsPirestricted = np.array((xlist,ylist)) # Convert to an np.array
    # Return the projection on the first coordinate. 
    # Note that we can sort the points in increasing order, for convenience
    return np.sort(pointsPirestricted[0,:])
    
pointsPi = Pi(T,lammax) # Fix one realisation of Pi
print(PoissonTemporel(pointsPi,2.))
print(PoissonTemporel(pointsPi,5.))
print(PoissonTemporel(pointsPi,8.))

# 4)
# Discretize [0,T] with a fixed number of points
m = 500
tvect = np.linspace(0.,T,num = m) # Time discretization
# We define the process t -> N(t) as a function of the set of points
def NLambda(tvect,points):
    L = np.size(tvect) # Number of values for t in tvect, that we need to redefine locally
    process = np.zeros(L, dtype=int)
    # Again, instead of computing process[t] for all t in tvect, we iterate on points
    for point in points:
        addedterm = (tvect >= point)
        process += addedterm
    return process
pointsPi = Pi(T,lammax) # Fix one realisation of Pi
N2 = NLambda(tvect,PoissonTemporel(pointsPi,2.))
N5 = NLambda(tvect,PoissonTemporel(pointsPi,5.))
N8 = NLambda(tvect,PoissonTemporel(pointsPi,8.))
# Plot
plt.figure()
plt.plot(tvect,N2)
plt.plot(tvect,N5)
plt.plot(tvect,N8)
plt.show()

# 6)
# We redefine here the parameters and sample again the PPM for the sake of completion
T = 5.
lammax = 10.
pointsPi = Pi(T,lammax) # Fix one realisation of Pi
m = 500
tvect = np.linspace(0.,T,num = m) # Time discretization
N2 = NLambda(tvect,PoissonTemporel(pointsPi,2.))
N5 = NLambda(tvect,PoissonTemporel(pointsPi,5.))
N8 = NLambda(tvect,PoissonTemporel(pointsPi,8.))
# Graphical representation
# Create a figure with 2 rows and 1 column of subplots. The option sharex allows
# us to share the x axis between the two plots
fig, (ax1,ax2) = plt.subplots(nrows=2,ncols=1,sharex=True) 
# First plot, the PPM and horizontal lines (added with the ax1.plot command)
ax1.scatter(pointsPi[0,:], pointsPi[1,:], label = '$\\Pi$')
ax1.plot([0.,T],[2.,2.], color = 'r', linestyle = '--', linewidth = .6)
ax1.plot([0.,T],[5.,5.], color = 'b', linestyle = '--', linewidth = .6)
ax1.plot([0.,T],[8.,8.], color = 'g', linestyle = '--', linewidth = .6)
ax1.legend(loc = 'upper left', framealpha = 0.9)
# Second plot, the temporal Poisson processes
ax2.plot(tvect,N2, color = 'r', label = '$N_2$')
ax2.plot(tvect,N5, color = 'b', label = '$N_5$')
ax2.plot(tvect,N8, color = 'g', label = '$N_8$')
ax2.legend()
plt.xlim((0.,T)) # Fix xlim simultaneously for both plots
ax1.set_ylim((0.,lammax)) # Fix ylim for the first plot (the original PPM)
fig.suptitle('Coupled Poisson processes')
plt.show()


# ====================================================================
# Exercise 4
# ====================================================================
# 2)
# We proceed similarly to Exercise 2.
def PiSorted(T,lammax):
    N = st.poisson.rvs(mu = T*lammax)
    xvals = st.uniform.rvs(loc = 0., scale = T, size = N)
    yvals = st.uniform.rvs(loc = 0., scale = lammax, size = N)
    order = np.argsort(xvals) # Creates the order that sorts xvals
    return np.array([xvals[order],yvals[order]]) # Both lists are sorted according to order

T = 20.
lammax = 10.
points = PiSorted(T,lammax)
plt.figure()
plt.scatter(points[0,:], points[1,:])
plt.axis('scaled')
plt.xlim((0.,T))
plt.ylim((0.,lammax))
plt.show()

# 3)
def h1(x):
    return np.exp(-x)/2

# 4)
# We define a function that takes sorted points and h, nu as arguments, and returns the Hawkes process.
def Hawkes(sp, h, nu): # sp is a set of points sorted in time
    N = np.shape(sp)[1]
    labels = [] # Initializing the list of point labels that are in the Hawkes process
    for k in range(N):
        xk = sp[0,k]
        rate = nu # Initialize the rate with nu
        for l in labels:
            rate += h(xk - sp[0,l]) # Add the contribution to the rate from previous points
        if sp[1,k] <= rate: # Check if the new point should be added to the Hawkes process
            labels += [k]
    return sp[0,labels] # Returns the times of events that where kept in the iteration

# 5)
nu = 1. # Base rate
sortedpoints = PiSorted(T,lammax) # We resample Pi here for convenience
hawkespoints = Hawkes(sortedpoints, h1, nu)
# Creatng an array of zeros for a 1d scatter
m = np.size(hawkespoints)
y = [0]*m 
plt.figure()
plt.plot([0,T],[0,0],linewidth=.5, color = 'k')
plt.scatter(hawkespoints, y, marker = '|')
plt.title('Hawkes, self-excitation')
plt.show()

# 6)
def h2(x):
    return (-1)*(x<1.)

hawkespoints2 = Hawkes(sortedpoints, h2, nu)
# Creatng an array of zeros for a 1d scatter
m = np.size(hawkespoints2)
y = [0]*m 
plt.figure()
plt.plot([0,T],[0,0],linewidth=.5, color = 'k')
plt.scatter(hawkespoints2, y, marker = '|')
plt.title('Hawkes, self-inhibition')
plt.show()

# Note that we can compare  with the case h=0, which should yield a usual Poisson temporal process
def h3(x):
    return 0.
hawkespoints3 = Hawkes(sortedpoints, h3, nu)
# Creatng an array of zeros for a 1d scatter
m = np.size(hawkespoints3)
y = [0]*m 
plt.figure()
plt.plot([0,T],[0,0],linewidth=.5, color = 'k')
plt.scatter(hawkespoints3, y, marker = '|')
plt.title('Poisson process')
plt.show()

# 7)
# First we redefine the function Hawkes to have access to the exact
# labels of points from sp that are involved in the construction.
def HawkesLabels(sp, h, nu): # sp is a set of points sorted in time
    N = np.shape(sp)[1]
    labels = [] # Initializing the list of point labels that are in the Hawkes process
    for k in range(N):
        xk = sp[0,k]
        rate = nu # Initialize the rate with nu
        for l in labels:
            rate += h(xk - sp[0,l]) # Add the contribution to the rate from previous points
        if sp[1,k] <= rate: # Check if the new point should be added to the Hawkes process
            labels += [k]
    return labels

labels = HawkesLabels(sortedpoints, h1, nu)
xi = sortedpoints[0,labels] # Points in the Hawkes process.

steps = 400
t = np.linspace(0,T,num=steps)
rate = np.zeros(steps) + nu
for k in labels:
    xk = sortedpoints[0,k]
    temp = np.array( [(xk<s)*h1(s-xk) for s in t] )
    rate += temp
rate = np.maximum(rate,0)
# Notice that if rate exceeds lammax, our simulation fails because we did not sample
# a sufficient number of points in the creation of the Hawkes process...
maxrate = np.max(rate)
if maxrate>lammax:
    print("ATTENTION: le taux a dépassé le maximum simulé, la simulation est erronée...")
fig,(ax1,ax2) = plt.subplots(nrows=2,ncols=1,sharex=True, gridspec_kw={'height_ratios': [4, 1]})
ax1.scatter(sortedpoints[0,:], sortedpoints[1,:], label='$\\Pi$')
ax1.scatter(sortedpoints[0,labels], sortedpoints[1,labels], color ='r')
ax1.plot(t,rate,color='r')
# ax1.get_yaxis().set_visible(False) # Hide Value of rate
# ax1.set_aspect('equal')
ax1.set_ylim((0.,lammax))
ax2.plot([0,T],[0,0],linewidth=.6, color='k')
ax2.scatter(sortedpoints[0,labels], np.zeros(len(labels)), marker = '|', color ='r', label='$\\Xi$')
ax2.set_ylim((-.5,1.))
ax2.get_yaxis().set_visible(False)
plt.xlim((0.,T)) # Fix x lim simultaneously for both plots
# Title and legend
fig.suptitle('Hawkes, self-excitation')
ax1.legend(loc="upper left")
ax2.legend(loc="upper left")
plt.show()

# We can do the same for the other functions.
labels2 = HawkesLabels(sortedpoints, h2, nu)
xi2 = sortedpoints[0,labels] # Points in the Hawkes process.
steps = 400
t = np.linspace(0,T,num=steps)
rate = np.zeros(steps) + nu
for k in labels2:
    xk = sortedpoints[0,k]
    temp = np.array( [(xk<s)*h2(s-xk) for s in t] )
    rate += temp
rate = np.maximum(rate,0)
# It is a process with inhibition in this case, so ne need to look for a blow-up of the rate
fig,(ax1,ax2) = plt.subplots(nrows=2,ncols=1,sharex=True, gridspec_kw={'height_ratios': [4, 1]})
ax1.scatter(sortedpoints[0,:], sortedpoints[1,:], label = '$\\Pi$')
ax1.scatter(sortedpoints[0,labels2], sortedpoints[1,labels2], color ='r')
ax1.plot(t,rate,color='r')
# ax1.get_yaxis().set_visible(False) # Hide Value of rate
# ax1.set_aspect('equal')
ax1.set_ylim((0.,lammax))
ax2.plot([0,T],[0,0],linewidth=.6, color='k')
ax2.scatter(sortedpoints[0,labels2], np.zeros(len(labels2)), marker = '|', color ='r', label='$\\Xi$')
ax2.set_ylim((-.5,1.))
ax2.get_yaxis().set_visible(False)
plt.xlim((0.,T)) # Fix x lim simultaneously for both plots
# Title and legend
fig.suptitle('Hawkes, self-inhibition')
ax1.legend(loc="upper left")
ax2.legend(loc="upper left")
plt.show()
