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


# ====================================================================
# Exercise 1
# ====================================================================
lam = 50
# 1)
N = st.poisson.rvs(4*lam) # Total number of points on the square [-1,1]
points = st.uniform.rvs(loc=-1, scale=2, size=(2,N)) # Sample of PPM
plt.figure()
plt.scatter(points[0,:],points[1,:])
plt.axis('scaled')
plt.show()
# 2)
N = st.poisson.rvs(4*lam)
points = st.uniform.rvs(loc=-1, scale=2, size=(2,N))
# Extract points that are in the L1-ball
listx=[]; listy=[] # Two empty lists
for k in range(N):
    if np.abs(points[0,k])+np.abs(points[1,k]) <= 1:
        listx += [points[0,k]]
        listy += [points[1,k]]
plt.figure()
plt.scatter(listx,listy)
plt.plot([1,0,-1,0,1],[0,1,0,-1,0], linestyle='--', color='k', linewidth=.6)
plt.axis('scaled')
plt.xlim((-1,1))
plt.ylim((-1,1))
plt.show()



# ====================================================================
# Exercise 3
# ====================================================================
T = 5
n = 1000
In = np.linspace(-T,T,num=2*n+1)
delta = T/n
# a)
Xi1 = []
for t in In:
    m = st.poisson.rvs(delta*(t**2))
    Xi1 += [t]*m
plt.figure()
Y1 = [0]*len(Xi1)
plt.scatter(Xi1,Y1)
plt.plot([-T,T],[0,0], linestyle='--', color='k', linewidth=.6)
plt.xlim((-T,T))
plt.show()
# b)
Xi2 = []
for t in In:
    m = st.bernoulli.rvs(p=min(1,delta*(t**2)))
    if m==1:
        Xi2 += [t]
plt.figure()
Y2 = [0]*len(Xi2)
plt.scatter(Xi2,Y2)
plt.plot([-T,T],[0,0], linestyle='--', color='k', linewidth=.6)
plt.xlim((-T,T))
plt.show()
# c)
Xi3 = []
for t in In:
    m = st.poisson.rvs(delta*(t**2))
    if m != 0:
        temp = st.uniform.rvs(loc=t,scale = delta, size = m)
        Xi3 += [s for s in temp]
plt.figure()
Y3 = [0]*len(Xi3)
plt.scatter(Xi3,Y3)
plt.plot([-T,T],[0,0], linestyle='--', color='k', linewidth=.6)
plt.xlim((-T,T))
plt.show()



# ====================================================================
# Exercise 4
# ====================================================================
# 1)
def g(x,y):
    return 10*(1-np.cos(np.pi*(np.sqrt(x**2+y**2))))**2

# 2)
def PPMInhom(f,T):
    M = 200 # discretization
    delta = T/M
    xval = np.linspace(-T,T,num = 2*M+1)
    yval = np.linspace(-T,T,num = 2*M+1)
    farray = np.array([[f(x,y) for y in yval] for x in xval])
    lamarray = farray * (delta**2)
    # Sample Poisson random variables with varying intensities
    poiss = st.poisson.rvs(mu = lamarray,size=(2*M+1,2*M+1))
    lx = []
    ly = []
    for i in range(2*M+1):
        for j in range(2*M+1):
            if poiss[i,j] != 0:
                lx+=[-T+(delta*i)]*poiss[i,j]
                ly+=[-T+(delta*j)]*poiss[i,j]
    return np.array([lx,ly])

T = 5
points = PPMInhom(g,T)
plt.figure()
plt.scatter(points[0,:],points[1,:])
plt.axis('scaled')
plt.xlim(-T,T)
plt.ylim(-T,T)
# t = np.linspace(-4.,4.,100)
# plt.plot(t, np.sqrt(4-t**2/4), linewidth = .5, linestyle = '--', color = 'k')
# plt.plot(t, -np.sqrt(4-t**2/4), linewidth = .5, linestyle = '--', color = 'k')
plt.show()

# You can experiment with a different function if you want.
def h(x,y):
    return 20*np.exp(-((x/2)**2+y**2-4)**2/2) 

points = PPMInhom(h,T)
plt.figure()
plt.scatter(points[0,:],points[1,:])
plt.axis('scaled')
plt.xlim(-T,T)
plt.ylim(-T,T)
# t = np.linspace(-4.,4.,100)
# plt.plot(t, np.sqrt(4-t**2/4), linewidth = .5, linestyle = '--', color = 'k')
# plt.plot(t, -np.sqrt(4-t**2/4), linewidth = .5, linestyle = '--', color = 'k')
plt.show()

# ====================================================================
# Exercise 6
# ====================================================================
# 1)
T = 5
n = 500
In = np.linspace(-T,T,num=2*n+1)
delta = T/n
Pi = []
for t in In:
    m = st.bernoulli.rvs(p=min(1,delta*(np.exp(t))))
    if m==1:
        Pi += [t]
plt.figure()
Y = [0]*len(Pi)
plt.scatter(Pi,Y)
plt.plot([-T,T],[0,0], linestyle='--', color='k', linewidth=.6)
plt.xlim((-T,T))
plt.show()

# 2)
N = st.poisson.rvs(np.exp(T)-np.exp(-T))
Pi0 = st.uniform.rvs(np.exp(-T),np.exp(T)-np.exp(-T),size = N)

# 3)
Pitilde = np.log(Pi0)
Y2 = [0]*len(Pitilde)
plt.scatter(Pitilde,Y2)
plt.plot([-T,T],[0,0], linestyle='--', color='k', linewidth=.6)
plt.xlim((-T,T))
plt.show()
# Pitilde has the same law as Pi



# ====================================================================
# Timing Exercise 3
# ====================================================================
# Here we compare the efficiency of the different algorithms from Ex 3
from time import time

T = 200
n = 2000
In = np.linspace(-T,T,num=2*n+1)
delta = T/n
# Test another function than t**2
def f(t):
    return (1+np.cos(t))/2
# a)
starttime1 = time()
Xi1 = []
for t in In:
    m = st.poisson.rvs(delta*(f(t)))
    Xi1 += [t]*m
endtime1 = time()
# b)
starttime2 = time()
Xi2 = []
for t in In:
    m = st.bernoulli.rvs(p=min(1,delta*(f(t))))
    if m==1:
        Xi2 += [t]
endtime2 = time()
# c)
starttime3 = time()
Xi3 = []
for t in In:
    m = st.poisson.rvs(delta*(f(t)))
    if m != 0:
        temp = st.uniform.rvs(loc=t,scale = delta, size = m)
        Xi3 += [s for s in temp]
endtime3 = time()

print('First algorithm: '+str(endtime1-starttime1) + ' seconds.')
print('Second algorithm: '+str(endtime2-starttime2) + ' seconds.')
print('Third algorithm: '+str(endtime3-starttime3) + ' seconds.')
# For T=100, n=2000, f(t)=t**2:
# A: 0.0518s, B: 0.0432s, C: 0.1283s

# For f(t)=(1+cos(t))/2: barely any difference !
plt.figure()
Y1 = [0]*len(Xi1)
plt.scatter(Xi1,Y1)
plt.plot([-T,T],[0,0], linestyle='--', color='k', linewidth=.6)
plt.xlim((-T,T))
plt.show()


plt.figure()
Y2 = [0]*len(Xi2)
plt.scatter(Xi2,Y2)
plt.plot([-T,T],[0,0], linestyle='--', color='k', linewidth=.6)
plt.xlim((-T,T))
plt.show()

plt.figure()
Y3 = [0]*len(Xi3)
plt.scatter(Xi3,Y3)
plt.plot([-T,T],[0,0], linestyle='--', color='k', linewidth=.6)
plt.xlim((-T,T))
plt.show()







