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

T = 5
lam = 1
R = 1

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

def Plot2D(points,Tmax):
    plt.figure()
    plt.scatter(points[0,:], points[1,:])
    plt.axis('scaled')
    plt.xlim((-Tmax,Tmax))
    plt.ylim((-Tmax,Tmax))
    plt.show()


# ====================================================================
# Exercise 2
# ====================================================================
# 1) Creates the adjacency matrix, Boolean model
def BooleanEdges(points,R):
    N = np.shape(points)[1] # Extract the number of vertices
    Edges = np.zeros(shape=(N,N),dtype=int)
    R2 = R**2 # We will compare the square distances to be slightly more efficient
    for i in range(N):
        for j in range(i+1,N):
            dist2 = (points[0,i]-points[0,j])**2 + (points[1,i]-points[1,j])**2
            if dist2 < R2:
                Edges[i,j]=1
                Edges[j,i]=1
    return Edges

# 2)
def Plot2DEdges(points,Tmax,Edges):
    N = np.shape(points)[1]
    plt.figure()
    for i in range(N):
        for j in range(N):
            if Edges[i,j]:
                plt.plot([points[0,i],points[0,j]],[points[1,i],points[1,j]], color='r')
    plt.scatter(points[0,:], points[1,:])
    plt.axis('scaled')
    plt.xlim((-Tmax,Tmax))
    plt.ylim((-Tmax,Tmax))
    plt.show()

# 3)
pp = Pi(lam,T)
BEdges = BooleanEdges(pp,R)
Plot2DEdges(pp,T,BEdges)

# 4) Both statements are wrong: with positive probability, the Boolean graph model
# can have isolated vertices and cycles.


# ====================================================================
# Exercise 4
# ====================================================================
# 1) Creates the adjacency matrix, Nearest-neighbour model
def NearestEdges(points):
    N = np.shape(points)[1]
    Madj = np.zeros(shape=(N,N), dtype=int)
    for i in range(N):
        # Generate matrix of square distances
        tempx = points[0,:] - points[0,i]
        tempy = points[1,:] - points[1,i]
        distances2 = tempx**2 + tempy**2
        # Look for the second smallest entry in distance2 (the smallest is always zero)
        k = np.argsort(distances2)[1] # Position of the second smallest distance
        Madj[i,k] = Madj[k,i] = 1
    return Madj

# 2)
NEdges = NearestEdges(pp)
Plot2DEdges(pp,T,NEdges)

# 3) The first two statements are true, however the graph is not connected with
# positive probability.



