# -*- coding: utf-8 -*-
"""
Created on Thu Nov  2 17:58:36 2017

@author: jared's account
"""

from __future__ import division, print_function
from pylab import *
import numpy as np
import matplotlib
import matplotlib.pyplot as plt

# Constants
M = 100         # Grid squares on a side
V = 1.0         # Voltage at top wall
target = 1e-6   # Target accuracy

# Create arrays to hold potential values
phi = np.zeros([M+1,M+1],float)
#phi[0,:] = V
#phiprime = empty([M+1,M+1],float)

# Main loop
delta = 1.0
omega = 0.8
while delta>target:

    delta = 0
    # Calculate new values of the potential
    for i in range(1,M):
        for j in range(1,M):
            #if i==0 or i==M or j==0 or j==M:
             #   phiprime[i,j] = phi[i,j]
            
            if i==30 and j>20 and j<80:
                phi[i,j] = 1
            elif i==60 and j>20 and j<80:
                phi[i,j] = -1
            else:
	            difference = (phi[i+1,j] + phi[i-1,j] \
	                                 + phi[i,j+1] + phi[i,j-1])/4 - phi[i,j]
	            phi[i,j] = phi[i,j] + (1+omega)*difference
            if difference>delta: delta = difference
# Make a plot
#plt.imshow(phi,origin='lower')
#plt.show()
x = np.linspace (0 ,1 , M+1 )
y = np.linspace (0 ,1 , M+1 )
# meshgrid () by default orders the arrays differently from what
# I prefer . This way , (X[i,j] ,Y[i,j]) equals (x[i] ,y[j])
Y , X = np.meshgrid(y , x )
h=1/(M)
Exx,Eyy = np.gradient(phi,h,h)
plt.quiver(X,Y,-1*Exx,-1*Eyy)
plt.title('Fields lines of Electric Field')
plt.show()
CS = plt.contour(X ,Y ,phi ,200) # Make a contour plot
# plt. clabel (CS , inline =1 , fontsize =10) # Contour labels
plt.title('Point charge in the cavity of a grounded box')
CB = plt.colorbar(CS, shrink=0.8 , extend = 'both')
plt.show()
