from math import*
import matplotlib.pyplot as plt
import numpy as np

V0=0
V1=200

def inittab():# Donne la valeur de V[i][j]=tab[i][j] et son statut
    B=np.zeros((N,N),bool)# B[i][j]=0 partout
    tab=np.zeros((N,N))+10# tab[i][j]=10 partout
    B[:,0]=1# B=1 au bord de gauche
    B[:,N-1]=1# B=1 au bord de droite
    B[0,:]=1# B=1 au bord supérieur
    B[N-1,:]=1# B=1 au bord inférieur

    tab[:,0]=V0# Potentiel au bord de gauche
    tab[:,N-1]=V0# Potentiel au bord de droite
    tab[0,:]=V0# Potentiel au bord supérieur
    tab[N-1,:]=V0# Potentiel au bord inférieur
    return (tab,B)

def itera(tab):#
    ecart=0
    temp=tab.copy()# tab ne sera pas affecté par temp
    for i in range(N):
        for j in range(N):
            if B[i,j]==0:
                temp[i][j]=(tab[i-1][j]+tab[i+1][j]+tab[i][j-1]+tab[i][j+1])/4
            ecart=max(ecart,abs(temp[i][j]-tab[i][j]))
    return (temp,ecart)

N=60# Dimensions du tableau
eps=0.3# Ecart maximum entre deux itérations
pot=inittab()[0]# Le potentiel prend sa valeur initiale
B=inittab()[1]# Les bords sont définis dans la matrice B

while (itera(pot)[1])>eps:# La récurrence est appliquée jusqu'à ce que e<eps
    pot=itera(pot)[0]

def graphe(B,f,a=0,nb_equipot=25):#Représentation de 25 équipotentielles
    N,N=B.shape# Les bord du domaine apparaissent comme un cadre noir
    plt.figure()
    plt.imshow(B,origin='lower',cmap='binary',interpolation='nearest')
    if (a==1):# Si a=1 les niveaux de potentiels sont colorés
        plt.imshow(f,origin='lower')
        plt.colorbar()
    x=np.linspace(0,N-1,N)# L'axe x contient N valeurs (cases)
    y=np.linspace(0,N-1,N)# L'axe y contient N valeurs
    cont=plt.contour(y,x,f,nb_equipot,colors='k')# Trace les équipotentielles
    plt.clabel(cont,fmt='%1.1f')# fmt contrôle l'affichage sur les courbes
    plt.show()

graphe(B,pot)