#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov  9 16:54:05 2026

@author: legrand
"""

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


# ====================================================================
# Exercise 1
# ====================================================================
fig,ax = plt.subplots()
circle1 = plt.Circle((0,0), .5, fill = True, color='r')
ax.add_patch(circle1)
circle2 = plt.Circle((0,1), 1, fill = False, linestyle = '--', linewidth = .5)
ax.add_patch(circle2)
plt.axis('square')
plt.xlim(-2,2)
plt.ylim(-2,2)
plt.show()

# 2) Other pictures
fig,ax = plt.subplots()
circle1 = plt.Circle((-1.5,0), .5, fill = True, color='r')
ax.add_patch(circle1)
circle2 = plt.Circle((0,0), .5, fill = True, color='g')
ax.add_patch(circle2)
circle3 = plt.Circle((1.5,0), .5, fill = True, color='b')
ax.add_patch(circle3)
plt.plot([-1.5,1.5],[0,0],color='k') # linewidth = 3, linestyle = '--'
plt.axis('square')
plt.xlim(-2,2); plt.ylim(-2,2)
plt.show()

fig,ax = plt.subplots()
t = np.linspace(-2,2,11)
for t1 in t:
    for t2 in t:
        circle1 = plt.Circle((t1,t2), .1, fill = False, linestyle = '--', linewidth = .5)
        ax.add_patch(circle1)
plt.axis('square')
plt.xlim(-2,2); plt.ylim(-2,2)
plt.show()

fig,ax = plt.subplots()
circle1 = plt.Circle((0,0), 2, fill = True, color='r')
ax.add_patch(circle1)
circle2 = plt.Circle((0,0), 1.5, fill = False, color='g', linestyle = '--')
ax.add_patch(circle2)
circle3 = plt.Circle((0,0), 1, fill = True, color='g')
ax.add_patch(circle3)
circle4 = plt.Circle((0,0), .5, fill = False, color='k')
ax.add_patch(circle4)
plt.axis('square')
plt.xlim(-2,2); plt.ylim(-2,2)
plt.show()


## Another syntax:
# circle2.set_linestyle(ls='--')
# circle2.set_linewidth(.5)

# ====================================================================
# Exercise 2
# ====================================================================
# 1) 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 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

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

T = 5
lam = 1
R = 1
points = Pi(lam,T)
edges = BooleanEdges(points,R)
Plot2DEdges(points, T, edges)

# 2)
def PlotDiscs(points,r,Tmax):
    N = np.shape(points)[1]
    fig,ax = plt.subplots()
    for i in range(N):
        circle1 = plt.Circle((points[0,i],points[1,i]), r, fill = True)
        ax.add_patch(circle1)
    plt.axis('scaled')
    plt.xlim((-Tmax,Tmax))
    plt.ylim((-Tmax,Tmax))
    plt.show()

PlotDiscs(points,R/2,T)
# In this graphical representations, two discs of radius R/2 intersect if and only if
# their centers are connected by an edge in the boolean graph at distance R

# 3)
# From TD 6 :
def ConComps(Edges):
    N = np.shape(Edges)[0]
    Comps = []
    Status = np.zeros(N,dtype=int)
    minimum = 0
    while minimum < 1:
        if minimum == 0:
            k = np.argmin(Status) 
            CurrentComp = [k] 
            Status[k] = 1 
            for j in range(N): 
                if (Edges[k,j] == 1) and (Status[j] == 0):
                    Status[j] = -1
        else: 
            k = np.argmin(Status) 
            CurrentComp += [k] 
            Status[k] = 1 
            for j in range(N):
                if (Edges[k,j] == 1) and (Status[j] == 0):
                    Status[j] = -1 
        minimum = np.min(Status)
        if minimum >=0:
            Comps += [CurrentComp]
    return Comps

def PlotDiscsColoredComps(points,r,Tmax):
    edges = BooleanEdges(points,2*r)
    comps = ConComps(edges)
    fig,ax = plt.subplots()
    for comp in comps:
        # Create a random color in the rgb format
        randcolor = st.uniform.rvs(size=3)
        for i in comp:
            circle1 = plt.Circle((points[0,i],points[1,i]), r, color = randcolor, fill = True)
            ax.add_patch(circle1)
    plt.axis('scaled')
    plt.xlim((-Tmax,Tmax))
    plt.ylim((-Tmax,Tmax))
    plt.show()

PlotDiscsColoredComps(points, R/2, T)


# ====================================================================
# Exercise 3
# ====================================================================
# 1)
T = 5
lam = 2
mu = 5

points = Pi(lam, T)
N = np.shape(points)[1] # Number of points
Rarray = st.expon.rvs(0,1/mu,size=N)

Rarray = st.expon.rvs(scale=1/mu, size = N) # Equivalent
# The joint process  (points, Rarray) encodes a Poisson point measure on (R^2)x(R_+),
# with intensity lam*mu*e^(mu*r)*1_{r>0}*(dx)*(dr).

# 2)
def PlotDiscsVaryingR(points,Rarray,Tmax):
    N = np.shape(points)[1] # Number of points
    fig,ax = plt.subplots()
    for i in range(N):
        circle1 = plt.Circle((points[0,i],points[1,i]), Rarray[i], fill = True)
        ax.add_patch(circle1)
    plt.axis('scaled')
    plt.xlim((-Tmax,Tmax))
    plt.ylim((-Tmax,Tmax))
    plt.show()
    
PlotDiscsVaryingR(points,Rarray,T)

# 3)
def BooleanEdgesVaryingR(points,Rarray):
    N = np.shape(points)[1] # Extract the number of vertices
    Edges = np.zeros(shape=(N,N),dtype=int)
    for i in range(N):
        for j in range(i+1,N):
            dist = np.sqrt( (points[0,i]-points[0,j])**2 + (points[1,i]-points[1,j])**2 ) # Euclidean distance
            if dist < (Rarray[i]+Rarray[j]):
                Edges[i,j]=1
                Edges[j,i]=1
    return Edges

M = BooleanEdgesVaryingR(points, Rarray)

# 4)
comps = ConComps(M)

fig,ax = plt.subplots()
for comp in comps:
    # Create a random color in the rgb format
    randcolor = st.uniform.rvs(size=3)
    for i in comp:
        circle1 = plt.Circle((points[0,i],points[1,i]), Rarray[i], color = randcolor, fill = True)
        ax.add_patch(circle1)
plt.axis('scaled')
plt.xlim((-T,T))
plt.ylim((-T,T))
plt.show()


# 5) Different mu
mu = 3

points = Pi(lam, T)
N = np.shape(points)[1] # Number of points
Rarray = st.expon.rvs(0,1/mu,size=N)

M = BooleanEdgesVaryingR(points, Rarray)
comps = ConComps(M)
fig,ax = plt.subplots()
for comp in comps:
    # Create a random color in the rgb format
    randcolor = st.uniform.rvs(size=3)
    for i in comp:
        circle1 = plt.Circle((points[0,i],points[1,i]), Rarray[i], color = randcolor, fill = True)
        ax.add_patch(circle1)
plt.axis('scaled')
plt.xlim((-T,T))
plt.ylim((-T,T))
plt.show()

# For mu=5, the graph is made of many small connected components.
# When mu is between 3 and 4, large connected components start appearing
# For mu = 2, there is a single large connected component, and the other components are scarce and very small
# For mu = 1, the box seems to be (almost) entirely covered by discs !

