


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


# ====================================================================
# From TD 4 :
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()


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()

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




# ====================================================================
# TD 6
# ====================================================================
# Identify the connected components in an adjacency matrix
def ConComps(Edges):
    N = np.shape(Edges)[0] # Extract the number of vertices
    Comps = []
    Status = np.zeros(N,dtype=int)
    minimum = 0 # We store the minimum of Status here. If -1 we are still exploring
    # a component, if 0 we must explore a new one, if 1 the iteration is over.
    while minimum < 1: # Iterate until everything is explored
        if minimum == 0: # Create a new component and iterate
            k = np.argmin(Status) # Fin a vertex not explored yet
            CurrentComp = [k] # Initialize a new component
            Status[k] = 1 # Mark k as "explored"
            for j in range(N): # Look for unexplored neighbours of k
                if (Edges[k,j] == 1) and (Status[j] == 0):
                    Status[j] = -1 # Mark j as "pending"
        else: # If the minimum is not 1 or 0, then it is -1 and we explore
            # the pending vertices
            k = np.argmin(Status) # Fin a pending vertex
            CurrentComp += [k] # Add k to the current component being explored
            Status[k] = 1 # Mark k as "explored"
            for j in range(N): # Look for unexplored neighbours of k
                if (Edges[k,j] == 1) and (Status[j] == 0):
                    Status[j] = -1 # Mark j as "pending"
        # Before iterating, we must not forget to add CurrentComp to the list of
        # components if there is no pending vertex
        minimum = np.min(Status) # In both cases, ecompute the minimum and iterate
        if minimum >=0:
            Comps += [CurrentComp]
    return Comps


# 2)
def Plot2DComps(points,Tmax,Edges):
    Comps = ConComps(Edges)
    plt.figure()
    for comp in Comps:
        # Create a random color in the rgb format
        randcolor = st.uniform.rvs(0,1,size=3)
        for i in comp:
            for j in comp:
                if Edges[i,j]==1:
                    plt.plot([points[0,i],points[0,j]],[points[1,i],points[1,j]], color=randcolor)
    plt.scatter(points[0,:], points[1,:])
    plt.axis('scaled')
    plt.xlim((-Tmax,Tmax))
    plt.ylim((-Tmax,Tmax))
    plt.show()
   
T = 5
lam = 1
R = 1
points = Pi(lam,T)
Madj = BooleanEdges(points, R)
Plot2DComps(points, T, Madj)


# ====================================================================
# Exercice 2
# ====================================================================
def LargestCompSize(Edges):
    Comps = ConComps(Edges)
    Size = np.shape(Edges)[1]
    return (max([len(comp) for comp in Comps]))/Size


T = 2
lam = 1
Rnum = 20 # Number of values of R tested
Rvals = np.linspace(0,2,Rnum)
K = 30 # Number of PPM sampled

LargSizeMat = np.zeros((K,Rnum))

for k in range(K):
    points = Pi(lam,T)
    # pointsnum = np.shape(points)[1]
    for p in range(Rnum):
        Madj = BooleanEdges(points, Rvals[p])
        LargSizeMat[k,p] = LargestCompSize(Madj)
        
# 3)
Means = np.mean(LargSizeMat, axis = 0)

plt.figure()
plt.plot(Rvals,Means, label='T=2')
plt.legend()
plt.show()


# 4)
# Be sure that your computer can do this simulation in a reasonable time frame by increasing T progressively in the previous questions
Tlist = [2,4,6,8,10]
NumT = len(Tlist)
ListMeans = []
for T in Tlist:
    LargSizeMat = np.zeros((K,Rnum))
    for k in range(K):
        points = Pi(lam,T)
        pointsnum = np.shape(points)[1]
        for p in range(Rnum):
            Madj = BooleanEdges(points, Rvals[p])
            LargSizeMat[k,p] = LargestCompSize(Madj)
    Means = np.mean(LargSizeMat, axis = 0)
    ListMeans += [Means]

plt.figure()
for i in range(NumT):
    plt.plot(Rvals,ListMeans[i], label = Tlist[i])
plt.legend()
plt.show()






