# L-40 MCS 275 Wed 23 Apr 2008 : drawgraph.py

# A very simple GUI to display a random graph:
# (1) the user is prompted for a number of vertices,
# (2) a random adjacency matrix is generated,
# (3) vertices and edges are drawn on canvas.

from Tkinter import *
from numpy import *
import math

class DrawGraph():
   """
   GUI to draw a graph on canvas.
   """
   def __init__(self,wdw,n,A):
      """
      Canvas for graph with n vertices.
      The adjacency matrix is in A.
      """
      wdw.title('drawing of a graph')
      self.d = 400
      self.nv = n
      self.Ae = A
      self.c = Canvas(wdw,width=self.d,\
        height=self.d,bg ='white')
      self.c.grid(row=0,column=0)

   def DrawVertex(self,i):
      """
      Draws the i-th vertex on canvas.
      """
      n = self.nv
      cx = self.d/2
      cy = self.d/2
      radius = 0.43*self.d
      vx = cx + radius*math.cos(2*i*math.pi/n)
      vy = cy + radius*math.sin(2*i*math.pi/n)
      self.c.create_oval(vx-10,vy-10,vx+10,vy+10,\
          width=1,outline='black',fill='white')
      v = str(i)
      self.c.create_text(vx,vy,text=v)

   def DrawEdge(self,i,j):
      """
      Draws the edge between vertices i and j.
      """
      n = self.nv
      cx = self.d/2
      cy = self.d/2
      radius = 0.4*self.d
      ax = cx + radius*math.cos(2*i*math.pi/n)
      ay = cy + radius*math.sin(2*i*math.pi/n)
      bx = cx + radius*math.cos(2*j*math.pi/n)
      by = cy + radius*math.sin(2*j*math.pi/n)
      self.c.create_line(ax,ay,bx,by,width=2)

   def Draw(self):
      """
      Draws the graph defined by the adjacency
      matrix on n vertices.
      """
      n = self.nv
      for i in range(0,n):
         self.DrawVertex(i)
         for j in range(0,n):
            if self.Ae[i,j] == 1:
               self.DrawEdge(i,j)

def main():
   """
   Prompts the user for the number of vertices
   and generates a random adjacency matrix.
   """
   n = input('Give #vertices : ')
   B = random.randint(0,2,(n,n))
   A = (B + B.transpose()) % 2
   print A
   top = Tk()
   show = DrawGraph(top,n,A)
   show.Draw()
   top.mainloop()

if __name__ == "__main__": main()
