from visual import *
from numpy import *
from random import *

class node:
    def __init__(self,position):
        self.node = sphere(pos=position, radius=.3)

    def getPosition(self):
        return self.node.pos

class line:
    def __init__(self,node1,node2):
        pos1 = node1.getPosition()
        pos2 = node2.getPosition()

        position = (pos1+pos2)/2.0
        length = abs(mag(pos1-pos2))
        width = .02
        height = .02
        axis = norm(pos1-pos2)

        self.line = box(pos=position, axis=axis, length=length, width=width, height=height)

class planarGraph:
    def __init__(self,Nvertices,scale):
        self.adjacencyMatrix = zeros((Nvertices,Nvertices),int)
        self.Nvertices = Nvertices
        self.scale = scale
     
        self.lines = list()
        self.nodes = list()
        self.distances = list()
        
        for n in xrange(Nvertices):
            randomU = random()-.5                          
            randomV = random()-.5
            position = vector(randomU*self.scale,randomV*self.scale,0.0)
            self.nodes.append(node(position))

    def fillAdjacencyList(self):
        for n in xrange(self.Nvertices):
            newDistance = 0.0
            minDistance = self.scale*sqrt(2)
            newM = 0
            for m in xrange(self.Nvertices):
                if n != m and self.adjacencyMatrix[n][m] != 1 and self.adjacencyMatrix[m][n] != 1:
                    newDistance = abs(mag(self.nodes[n].getPosition()-self.nodes[m].getPosition()))
                    if newDistance < minDistance:
                        minDistance = newDistance
                        newM = m
            if n != m:
                self.distances.append(minDistance)
                self.adjacencyMatrix[n][newM] = 1
                self.adjacencyMatrix[newM][n] = 1
            else:
                self.adjacencyMatrix[n][m] = 0
                self.adjacencyMatrix[m][n] = 0

    def attrition(self):
        for n in xrange(self.Nvertices-1):
            newDistance = 0.0
            minDistance = self.scale*sqrt(2)
            newM = 0
            for m in xrange(self.Nvertices):
                if n != m and self.adjacencyMatrix[n][m] != 1 and self.adjacencyMatrix[m][n] != 1:
                    newDistance = abs(mag(self.nodes[n].getPosition()-self.nodes[m].getPosition()))
                    if newDistance < minDistance:
                        minDistance = newDistance
                        newM = m
            if minDistance > self.distances[n]:
                pass
            else:
                self.lines.append(line(self.nodes[n],self.nodes[newM]))

maxNodes = 17
scale = maxNodes
planeGraph = planarGraph(maxNodes,scale)
planeGraph.fillAdjacencyList()
planeGraph.attrition()

