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

# ====================================================================
# Exercise 2
# ====================================================================
n = 1000
lam = 2.
# 1)
x = st.poisson.rvs(mu = lam, size = n) # sample of iid Poisson variables. In python
# the paramter of the Poisson law is named 'mu'
print(np.mean(x)) # empirical mean
print(np.var(x)) # empirical variance
# Other useful commands: 
# np.sum(x)   sum of all entries in array x
# np.std(x)   empirical standard deviation (square root of empirical variance)
# np.max(x), np.min(x)   maximum and minimum of sample
# np.quantile(x, q)   q-quantile of sample

# 2)
# Several ways to define the cumulative sums s = (s1,s2,...), and the averaged
# ones y = (s1, s2/2, s3/3,...)
# Method 1, naive but straightforward
s = [0]*(n)
y = [0.]*(n)
for k in range(n):
    s[k] = np.sum(x[:k+1]) # sum from x[0] to x[k]
    y[k] = s[k]/(k+1)
# Method 2, with np.arrays (more efficient)
s = np.cumsum(x) # built-in function to obtain cumulative sums
y = s/np.arange(1,n+1) # component-wise division by the vector (1,2,3,...,n)
# Graphical representation
t = np.arange(1,n+1) # abscissa entries
plt.figure()
plt.plot(t,y)
plt.show()

# 3)
n = 200
m = 1000
# Again, we present two methods to obtain m iid sampling of sn/n
# Method 1
v = [0.]*m
for k in range(m):
    x = st.poisson.rvs(mu = lam, size = n)
    v[k] = np.sum(x)/n
# Method 2, with np.arrays, slightly more efficient
x = st.poisson.rvs(mu = lam, size = (n,m)) # Create a n*m matrix of iid Poisson
v = np.mean(x,axis = 0) # Computes the mean along the axis 0
# Graphical representation
plt.figure()
plt.hist(v, bins = 30) # Adjust the number of bins to have a nice representation
plt.show()

# The code above is perfectly sufficient to answer question 3), but we present here
# an alternate code to create a more polished graphical representation:
binnumber = 30 # number of bins in the histogram
# Here we define the bins of the plot manually, with endpoints chosen in a relevant way
binlist = np.linspace(lam - 4*np.sqrt(lam/n), lam + 4*np.sqrt(lam/n), num = binnumber) 
# We are going to compare the histogram with the Gaussian pdf
t = np.linspace(lam - 4*np.sqrt(lam/n), lam + 4*np.sqrt(lam/n), num = 100)
vgaussian = st.norm.pdf(t, loc = lam, scale = np.sqrt(lam/n))
# Histogram
plt.figure()
plt.hist(v, bins = binlist, density = True, label='$S_n/n$') # Rescale vertically with 'density' option
plt.plot(t,vgaussian, color = 'r', label='$\mathcal{N}(\lambda, \lambda/n)$ pdf') # Plot Gaussian pdf
plt.legend() # Display legend, with labels defined above
plt.title('Frequencies of Poisson sample, $\lambda=$' + str(lam) + ', $n=$'+str(n)+', $m=$'+str(m)) # Display title
plt.show()


# ====================================================================
# Exercise 4
# ====================================================================
# 1)
T = 5.
lam = 2.
points = [] # Empty list which will then contain points of the PPM
lastpoint = 0. # Recursion will stop when this exceeds T
while lastpoint <= T:
    increment = st.expon.rvs(loc = 0., scale = 1/lam)
    lastpoint += increment
    if lastpoint <= T:
        points += [lastpoint]
print(points)
# Graphical representation
y = [0]*len(points) # Need to set y coordinates to 0 to make a 1D scatter plot
plt.figure()
plt.plot([0,T],[0,0], color='k', linewidth = .5)
plt.scatter(points,y)
plt.xlim((0.,T))
plt.show()

# 3)
nfixed = 10 # Fixed number of individuals
points = st.uniform.rvs(loc = 0., scale = T, size = nfixed)
# For the graphical representation, use the same code as in question 1.

# 4)
N = st.poisson.rvs(mu = T*lam)
points = st.uniform.rvs(loc = 0., scale = T, size = N)
# For the graphical representation, use the same code as in question 1.
# We now compare the execution time of both programs with the 'time' package
from time import time
T = 5000.
lam = 10.
# First code
starttime1 = time()
points = [] # Empty list which will then contain points of the PPM
lastpoint = 0. # Recursion will stop when this exceeds T
while lastpoint <= T:
    increment = st.expon.rvs(loc = 0., scale = 1/lam)
    lastpoint += increment
    if lastpoint <= T:
        points += [lastpoint]
endtime1 = time()
# Second code
starttime2 = time()
N = st.poisson.rvs(mu = T*lam)
points = st.uniform.rvs(loc = 0., scale = T, size = N)
endtime2 = time()
print('First algorithm: '+str(endtime1-starttime1) + ' seconds.')
print('Second algorithm: '+str(endtime2-starttime2) + ' seconds.')


# ====================================================================
# Exercise 5
# ====================================================================
# 2)
# One only needs to notice that a uniform r.v. on [0,1]^2 is just a pair of
# independent, uniform r.v.s on [0,1]
def unifsquare():
    return st.uniform.rvs(loc = 0., scale = 1., size = (2,1))
# Notice that we chose a column representation for the vector, i.e. size = (2,1)
unifsquare()

# 3)
def PPMsquare(lam):
    N = st.poisson.rvs(mu=lam)
    return st.uniform.rvs(loc = 0., scale = 1., size = (2,N))
lam = 20.
points = PPMsquare(lam)
plt.figure()
plt.scatter(points[0,:], points[1,:])
plt.axis('scaled')
plt.xlim((0.,1.))
plt.ylim((0.,1.))
plt.show()
# Question 1: the answer was the first picture

# 4)
# To sample the PPM on the circle, we first sample it on the square [-1,1]^2,
# then remove all points which are outside of the circle
def PPMcircle(lam):
    N = st.poisson.rvs(mu=4*lam)
    # Be careful with the loc and scale parameters below!
    squarepoints = st.uniform.rvs(loc = -1., scale = 2., size = (2,N))
    xlist = []
    ylist = []
    for k in range(N):
        x = squarepoints[0,k]
        y = squarepoints[1,k]
        if x**2+y**2 <= 1.:
            xlist += [x]
            ylist += [y]
    return np.array([xlist,ylist]) # Convert to np.array for ease of use
lam = 100
points = PPMcircle(lam)
plt.figure()
plt.scatter(points[0,:], points[1,:])
plt.axis('scaled')
plt.xlim((-1.,1.))
plt.ylim((-1.,1.))
plt.show()
# print(np.shape(points)[1]) # Check that this is of order 100*np.pi

# Optional: add the circle with the plt.subplots() and ax.add_patch() method
fig,ax = plt.subplots()
plt.scatter(points[0,:], points[1,:])
plt.axis('scaled')
plt.xlim((-1.,1.))
plt.ylim((-1.,1.))
circle = plt.Circle((0.,0.),1., color='black', fill = False)
circle.set_linestyle(ls='--')
circle.set_linewidth(.5)
ax.add_patch(circle)
plt.title('PPM with intensity '+str(lam) + ' on $B(0,1)$')
plt.show()


# ====================================================================
# Exercise 6
# ====================================================================
# 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)
# Our algorithm is the following: for lam fixed, we look at the restriction of
# Pi on [0,T]*[0,lam], and 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 PiLambda(pointsPi, lam):
    # Restriction
    xlist = []
    ylist = []
    NpointsPi = np.shape(pointsPi)[1] # Extract number of points in pointsPi
    for k in range(NpointsPi):
        if pointsPi[1,k] <= lam:
            xlist += [pointsPi[0,k]]
            ylist += [pointsPi[1,k]]
    pointsPirestricted = np.array((xlist,ylist))
    # Projection. 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(PiLambda(pointsPi,2.))
print(PiLambda(pointsPi,5.))
print(PiLambda(pointsPi,8.))

# 3)
# 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
    process = np.zeros(L, dtype=int)
    # Idea: instead of computing process[t] for all t in tvect, instead for each
    # point in points we add 1 to values of t which are to its right
    for point in points:
        addedterm = (tvect >= point)
        process += addedterm
    return process
pointsPi = Pi(T,lammax) # Fix one realisation of Pi
N2 = NLambda(tvect,PiLambda(pointsPi,2.))
N5 = NLambda(tvect,PiLambda(pointsPi,5.))
N8 = NLambda(tvect,PiLambda(pointsPi,8.))
# Plot
plt.figure()
plt.plot(tvect,N2)
plt.plot(tvect,N5)
plt.plot(tvect,N8)
plt.show()

# 5)
# 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,PiLambda(pointsPi,2.))
N5 = NLambda(tvect,PiLambda(pointsPi,5.))
N8 = NLambda(tvect,PiLambda(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()














