Exemplo n.º 1
0
def makeVertexGraph(faceGraph):
	vertexGraph = []
	faceInt = faceGraphToInts(faceGraph)
	for face in faceGraph:
		for i in range(6):
			x = getXCoor(i, face.getX())
			y = getYCoor(i, face.getY())
			
			v = findVertex(x, y, vertexGraph)
			if v != False:
				v.root = v
				v.addFace(face)
				face.addVertex(i, v)
			else:
				v = Vertex(x, y)
				v.root = v
				v.addFace(face)
				face.addVertex(i, v)
				vertexGraph.append(v)

	for face in faceGraph:
		#this assign the neighbors of the vertices, NOT the faces themsleves
		assignNeighbors(face) 

	return vertexGraph
    def Collision(self, point):
        #print("Polygon::Collision::")
        if self.first_node is None:
            print("This polygon is empty")
            return

        next_node = self.first_node.next_node
        #print("\tfirst_node = " + self.first_node.vertex.Display())
        #print("\tnext_node = " + next_node.vertex.Display())

        tempx = next_node.vertex.x - self.first_node.vertex.x
        tempy = next_node.vertex.y - self.first_node.vertex.y

        a = Vertex.Vertex(tempx, tempy)
        #print("\ta = " + a.Display())

        tempx = point.x - next_node.vertex.x
        tempy = point.y - next_node.vertex.y

        b = Vertex.Vertex(tempx, tempy)
        #print("\tb = " + b.Display())

        test = self.Cross(a, b)
        if test < 0:
            #print("\t" + point.Display() + " does not collide")
            return False

        cur = next_node
        while cur is not self.first_node:
            if (cur.next_node is None):
                print("Something is wrong, next node is null")
            next_node = cur.next_node

            tempx = next_node.vertex.x - cur.vertex.x
            tempy = next_node.vertex.y - cur.vertex.y

            a = Vertex.Vertex(tempx, tempy)

            tempx = point.x - next_node.vertex.x
            tempy = point.y - next_node.vertex.y

            b = Vertex.Vertex(tempx, tempy)
            #print("\tTesting " + a.Display() + " x " + b.Display())
            test = self.Cross(a, b)
            if test < 0:
                #print("\t" + point.Display() + " does not collide")
                return False
            cur = next_node

        return True
Exemplo n.º 3
0
    def __init__(self):
        hive = Vertex('v0')
        # the three arms
        arm1 = [Vertex('v' + str(i)) for i in range(1, 5)]
        arm2 = [Vertex('v' + str(i)) for i in range(5, 12)]
        arm3 = [Vertex('v' + str(i)) for i in range(12, 24)]
        # connects the arms to the hive
        hive.neighbors.extend([arm1[0], arm2[0], arm3[0]])

        for arm in [arm1, arm2, arm3]:
            arm[0].neighbors.append(hive)
            for i in range(len(arm) - 1):
                arm[i].neighbors.append(arm[i + 1])
                arm[i + 1].neighbors.append(arm[i])
        self.list_of_vertices = [hive] + arm1 + arm2 + arm3
Exemplo n.º 4
0
    def __init__(self, num):
        super(GridGraph, self).__init__()
        vertex_matrix = []
        v = 0
        # creates an array of arrays of vertices for the grid
        for i in range(int(floor(sqrt(num)))):
            matrix = []
            for k in range(int(ceil(sqrt(num)))):
                matrix.append(Vertex(name='v' + str(v)))
                v += 1
            vertex_matrix.append(matrix)

        # connects vertices together in a grid-like format
        for k in range(len(vertex_matrix)):
            # iterate rows
            for i in range(len(vertex_matrix[k])):
                # iterate columns
                current_vertex = vertex_matrix[k][i]
                if i > 0:
                    current_vertex.neighbors.append(vertex_matrix[k][i - 1])
                if i < len(vertex_matrix[k]) - 1:
                    current_vertex.neighbors.append(vertex_matrix[k][i + 1])
                if k > 0:
                    current_vertex.neighbors.append(vertex_matrix[k - 1][i])
                if k < len(vertex_matrix) - 1:
                    current_vertex.neighbors.append(vertex_matrix[k + 1][i])
            self.list_of_vertices.extend(vertex_matrix[k])
Exemplo n.º 5
0
    def __init__(self, class_fn, vertex_fn, edge_fn, feature_fn, meta_fn,
                 train_fn, val_fn, test_fn):
        self.class_fn = class_fn
        self.vertex_fn = vertex_fn
        self.edge_fn = edge_fn
        self.feature_fn = feature_fn
        self.meta_fn = meta_fn
        self.train_fn = train_fn
        self.val_fn = val_fn
        self.test_fn = test_fn

        self.load_meta()
        self.load_edges()
        self.train = self.load_indices(self.train_fn)
        self.val = self.load_indices(self.val_fn)
        self.test = self.load_indices(self.test_fn)

        assert self.nVertices <= self.nPapers
        assert self.nNoFeatures >= 0

        self.vertices = []
        for index in range(self.nPapers):
            self.vertices.append(Vertex.Vertex(index))

        self.load_name()
        self.load_class()
        self.load_feature()
        self.set_labels_and_masks()

        self.validate_data()
Exemplo n.º 6
0
    def dijkstra(self):
        que = Queue.Queue()  # kolejka wierzchołków do sprawdzenia
        shortest_paths = [
        ]  # tablica przechowująca wierzchołki z indeksem, dystansem i poprzednikiem
        for i in range(self.vertices):
            que.insert(Vertex.Vertex(i, -1, inf, ''))
        que.set_distance(self.start, 0)

        while not que.is_empty():
            current = que.remove()
            shortest_paths.append(current)
            for i in range(self.vertices):
                if que.contains(
                        i
                ):  # sprawdź, czy sprawdzany wierzchołek nie ma już wyliczonej najkrótszej ścieżki
                    if current.distance + self.adjacency_matrix[
                            current.index][i] < que[
                                i].distance:  # jeśli droga przez current jest krótsza:
                        que.set_distance(
                            i, current.distance +
                            self.adjacency_matrix[current.index][i]
                        )  # ustaw ją jako nowy dystans
                        que.set_previous(
                            i, current.index)  # aktualizuj poprzednika
                        que.set_path(i, f'{current.path}{current.index} -> '
                                     )  # aktualizuj sciezke
        return shortest_paths
def initComponents(canvas, GLOBAL_OBJ):
    createButton = Button.initButton(canvas).createButton
    createVertex = Vertex.initVertex(canvas, GLOBAL_OBJ).createVertex

    def getCoordinates(vertexId):
        return canvas.find_withtag(vertexId)

    counter = 0

    def vertexCreator(event):
        nonlocal counter
        createVertex(
            event.x - 15, event.y - 15, 30, tagName=counter)
        counter = counter + 1


    canvas.bind("<Button-3>", vertexCreator)

    returnMap = {
        "createButton": createButton,
        "createVertex": createVertex,
        "getCoordinates": getCoordinates
    }

    return SimpleNamespace(**returnMap)
Exemplo n.º 8
0
 def test_RemoveVertex(self):
     graff = Vertex.SimpleGraph(
         4
     )  # до удаления некоторые вершины имеют связи с удаляемой вершиной, после удаления этих связей нету
     graff.AddVertex(1)
     graff.AddVertex(2)
     graff.AddVertex(3)
     graff.AddVertex(4)
     graff.AddEdge(1, 2)
     #до удаления
     self.assertEqual(graff.vertex.count(None) == 0,
                      True)  # считает количкество Нан в масисиве
     self.assertEqual(
         graff.m_adjacency[1].count(0) == 3,
         True)  # считает количкество едениц в масисиве до добавления связей
     self.assertEqual(graff.m_adjacency[2][1] == 1, True)
     self.assertEqual(graff.m_adjacency[1][2] == 1, True)
     graff.RemoveVertex(1)
     #после удаления
     self.assertEqual(graff.vertex.count(None) == 1,
                      True)  # считает количкество Нан в масисиве
     self.assertEqual(
         graff.m_adjacency[1].count(0) == 4,
         True)  # считает количкество едениц в масисиве до добавления связей
     self.assertEqual(graff.m_adjacency[2][1] == 0, True)
     self.assertEqual(graff.m_adjacency[1][2] == 0, True)
Exemplo n.º 9
0
 def read_from_off(self, path):
     with open(path) as f:
         counter = 0
         h = 0
         n = 0
         m = 0
         for line in f:
             if counter == 0:
                 if line.split()[0] != 'OFF':
                     print('This is not an OFF file')
                     break
             elif counter == 1:
                 (n, m, mm) = map(int, line.split())
             elif counter < n + 2:
                 (x, y, z) = map(float, line.split())
                 self.vertices.append(Vertex(p=Vector3D(x, y, z), index=counter - 2))
             elif counter < n + m + 2:
                 indices = [int(x) for x in line.split()]
                 v = indices[0]
                 indices = indices[1:]
                 h = []
                 for i in range(v - 1):
                     h.append(self.find_edge(indices[i], indices[i+1]))
                 h.append(self.find_edge(indices[v - 1], indices[0]))
                 for i in range(v - 1):
                     h[i].nh = h[i + 1]
                     h[i + 1].ph = h[i]
                 h[v - 1].nh = h[0]
                 h[0].ph = h[v - 1]
                 face = Face(side=h[v - 1], n=v, index=len(self.faces))
                 self.faces.append(face)
                 for i in range(v):
                     h[i].polygon = face
             counter += 1
Exemplo n.º 10
0
 def generateProjBn(self, height, projVec, baseVec):
     translateVec = [0, 0, 0]
     newCentroid = [0, 0, 0]
     print("Normal Vector: " + str(self.normalVector))
     print("Base Vector: " + str(baseVec))
     if self.checkIfVecEqual(baseVec, self.normalVector) == False:
         for y in range(3):
             print("y: " + str(y))
             translateVec[y] = self.normalVector[y] - baseVec[y]
     else:
         translateVec = self.normalVector
     for z in range(3):
         newCentroid[z] = self.centroid[z] + translateVec[z]
     newCentroid = tuple(newCentroid)
     BnNew = B_n(self.numOfVertices, False, self.radius, newCentroid,
                 self.normalVector, False)
     #This represent the top
     self.scaleVector(translateVec, height)
     iteratedTuple = [0, 0, 0]
     for x in range(self.numOfVertices):
         iteratedTuple[
             0] = self.verticesSet[x].vertexPosition[0] + translateVec[0]
         iteratedTuple[
             1] = self.verticesSet[x].vertexPosition[1] + translateVec[1]
         iteratedTuple[
             2] = self.verticesSet[x].vertexPosition[2] + translateVec[2]
         vertexNew = Vertex(self.numOfVertices, tuple(iteratedTuple), x + 1)
         BnNew.verticesSet.append(vertexNew)
     return BnNew
Exemplo n.º 11
0
    def add_vertices(self):
        '''
        Adds vertices to all the tiles that are correctly shared by neighboring tiles.

        Args:
            None
        Returns:
            None
        '''
        for row in self.tile_array:
            for tile in row:
                for index, vertex in enumerate(tile.vertex_arr):
                    if vertex is None:
                        # initialize vertex and attach it to tile and vice versa
                        vertex = tile.vertex_arr[index] = Vertex.Vertex()
                        vertex.tile_arr[0] = tile
                        if tile.tile_arr[index]:
                            # for one neighbor (border tiles) attach vertex to neighbor and vice versa
                            tile.tile_arr[index].vertex_arr[(index + 4) %
                                                            6] = vertex
                            vertex.tile_arr[1] = tile.tile_arr[index]
                            if tile.tile_arr[index - 1] is not None:
                                # for two neighbors (center tiles) do the same again for vertices
                                tile.tile_arr[index -
                                              1].vertex_arr[(index + 2) %
                                                            6] = vertex
                                vertex.tile_arr[2] = tile.tile_arr[index - 1]
Exemplo n.º 12
0
 def grilleToVertexMatrix(self):
     vertexMatrix = list()
     for i in range(0, len(self.grille)):
         vertexMatrix.append([])
         for j in range(0, len(self.grille[0])):
             vertexMatrix[i].append(Vertex(self.grille[i][j]))
     return vertexMatrix
def leg_ik(x, y, z, l1=L1, l2=L2, l3=L3, alpha=Alpha, beta=Beta):

    l_proj = sqrt(x * x + y * y)
    d13 = l_proj - l1
    d = sqrt(z * z + d13 * d13)

    if (d13 == 0):
        a = 0
    else:
        a = atan(z / d13)

    if (d == 0):
        b = 0
    else:
        b = al_kashi(l3, l2, d)

    if (x == 0):
        theta1 = 0
    else:
        theta1 = atan(y / x)

    theta2 = b + a
    theta3 = pi - al_kashi(d, l3, l2)

    angle = Vertex(degrees(theta1), degrees(theta2), degrees(theta3))

    print(str(angle))
Exemplo n.º 14
0
def randomPoints(n):
    arr = []
    for i in range(n):
        vt = Vt.Vertex(rand.randrange(0, 100), rand.randrange(0, 100))
        vt.x = vt.x * 10
        vt.y = vt.y * 7.2
        arr.append(vt)
    return arr
Exemplo n.º 15
0
 def add_vertex(self, element, coordinates):
     v = Vertex(element)
     self._structure[v] = dict()
     self._coordinates[v] = coordinates
     # add vertex v with associated coordinates to dict
     self._elements[element] = v
     # add vertex v to dict with element as key
     return v
Exemplo n.º 16
0
 def __init__(self, aGraphName,
                    aVertices,
                    aEdges):
     self.Name       = aGraphName
     self.Vertices   = List[Vertex]([Vertex(vertex) for vertex in aVertices.split(',')])
     self.Edges      = [Edge for Edge in aEdges]
     self.Adj        = {}        
     self.__CreateAdjDict()
Exemplo n.º 17
0
def initSpace(xmax, ymax, points):
    point_list = []

    for i in range(points):
        vertex = Vertex(randint(1, xmax - 1), randint(1, ymax - 1))
        point_list.append(vertex)

    print("Tree initialized")
    return point_list
Exemplo n.º 18
0
 def getVertex(self, vertexName, propert, createNew=False):
     try:
         v = self.vertexMap.get(vertexName)
         if v is None and createNew:
             v = Vertex(vertexName, propert)
             self.vertexMap[vertexName] = v
         return v
     except KeyError as e:
         print("Exception ", e)
Exemplo n.º 19
0
    def __init__(self, num):
        super(CompleteGraph, self).__init__()

        self.list_of_vertices = [Vertex(name='v' + str(i)) for i in range(num)]

        # connects all vertices to each other
        for i in range(len(self.list_of_vertices)):
            self.list_of_vertices[i].neighbors = self.list_of_vertices[
                0:i] + self.list_of_vertices[i + 1::]
Exemplo n.º 20
0
 def set_branch_bipartite(self, data, branch):
     start = 270 - 60 * int((data - 1) / 2)
     if (branch == 'left'):
         self.left_size = data
         self.erase_branch('left')
         for i in range(data):
             self.left_branch.append(VE.Vertex(self, 60, start + 60 * i, i,
                                               'left'))
         for vertex in self.left_branch:
             games.screen.add(vertex)
     else:
         self.right_size = data
         self.erase_branch('right')
         for i in range(data):
             self.right_branch.append(VE.Vertex(self, 400, start + 60 * i,
                                                i, 'right'))
         for vertex in self.right_branch:
             games.screen.add(vertex)
Exemplo n.º 21
0
    def __init__(self, num, sparseness=.5):
        # sparseness ranges from 0 to 1, with .5 being an average graph
        super(RandomGraph, self).__init__()

        self.list_of_vertices = [Vertex(name='v' + str(i)) for i in range(num)]
        for i in range(len(self.list_of_vertices)):
            self.list_of_vertices[i].neighbors = []

        self.generate_connections(sparseness)
 def get_vertices(self):
     Temp = {}
     for edge in self.edge_list:
         Temp[edge.start] = []
         Temp[edge.end] = []
     for edge in self.edge_list:
         Temp[edge.start].append(edge)
         Temp[edge.end].append(edge)
     for key, value in Temp.items():
         self.vertices.append(Vertex.Vertex(key, value))
Exemplo n.º 23
0
 def initializeSelf(self):
     """
     This initializes Bn with the norm vec
     where none of the positions of the vertices are given
     """
     firstVpoint = self.getFirstPoint()
     v1 = Vertex(self.numOfVertices, firstVpoint, 1)
     self.verticesSet.append(v1)
     self.currentNumOfVertices += 1
     self.generateVertices(self.verticesSet[0])
     self.printVertexCoordinate()
Exemplo n.º 24
0
 def __init__(self, vertices, aristas, dirigida):
     super(Graph, self).__init__()
     self.dirigida = dirigida
     self.vertices = [None] * vertices.__len__()
     for i in range(0, vertices.__len__()):
         self.vertices[i] = Vertex(vertices[i])
     self.aristas = [None] * aristas.__len__()
     for i in range(0, aristas.__len__()):
         self.aristas[i] = Edge(aristas[i][0], aristas[i][1], aristas[i][2])
     self.q = Queue.Queue()
     self.auxVertices = 0
Exemplo n.º 25
0
 def initializeFirst(self):
     """
     THIS IS A GARBAGE FUNCTION. DONT USE AGAIN
     """
     alpha = 2 * np.pi / self.numOfVertices
     if self.isFirst == False:
         return
     else:
         centroid = (0, 0, 0)
         #Always start at the origin
         v1 = Vertex(self.numOfVertices, (self.radius, 0, 0), 1)
         self.verticesSet.append(v1)
         xPos = 0
         yPos = 0
         vHolder = None
         for i in range(1, self.numOfVertices):
             xPos = self.radius * np.cos(i * alpha)
             yPos = self.radius * np.sin(i * alpha)
             vHolder = Vertex(self.numOfVertices, (xPos, yPos, 0), i + 1)
             self.verticesSet.append(vHolder)
def readCSV(archivo):
    graph = Graph()
    reader = csv.reader(open(os.getcwd() + "/ejemplos/" + archivo, 'r'))
    tipo = next(reader, None)
    if tipo == ['direct=1']:
        graph.set_dirigida(True)
    for row in enumerate(reader):
        if row[1][0] not in graph.get_etiquetas():
            graph.add_vertice(Vertex(row[1][0], 1, [row[1][1][2::3]]))
        else:
            for vertice in graph.vertices():
                if vertice.etiqueta == row[1][0]:
                    vertice.add_vecino(row[1][1][2::3])
        if row[1][1][2::3] not in graph.get_etiquetas():
            graph.add_vertice(Vertex(row[1][1][2::3], 1, [row[1][0]]))
        else:
            for vertice in graph.vertices():
                if vertice.etiqueta == row[1][1][2::3]:
                    vertice.add_vecino(row[1][0])
        graph.add_arista(Edges(row[1][0], row[1][1][2::3], row[1][2][1::]))
    return graph
Exemplo n.º 27
0
 def test_AddVertex(self):  #вершина имеется, связи с ней отсутствуют
     graff = Vertex.SimpleGraph(4)
     graff.AddVertex(1)
     self.assertEqual(
         graff.vertex.count(None) == len(graff.vertex) - 1,
         True)  #считает количкество Нан в масисиве
     self.assertEqual(graff.m_adjacency.count(1) == 0,
                      True)  #проверяет количество связей (едениц) в матрице
     graff.AddVertex(3)
     self.assertEqual(
         graff.vertex.count(None) == len(graff.vertex) - 2, True)
     self.assertEqual(graff.m_adjacency.count(1) == 0, True)
Exemplo n.º 28
0
def testKCenter():
    vertices = []

    for i in range(1, 1000):
        vertex = Vertex()
        vertex.pos.x = random.randint(-100, 100)
        vertex.pos.y = random.randint(-100, 100)
        vertices.append(vertex)

    kSet = solveKCenter(vertices, 10)
    graph = Graph(kSet)  # For debugging
    print graph.toString()
Exemplo n.º 29
0
def make(wheel_radius,begining_point,closoid_number,point_num,breast_wide):
    #v = [[[0,0,0],[10,0,0],[10,10,0],[0,10,0]],[[0,0,10], [10,0,10],[10,10,10],[0,10,10]]]
    v = Vertex.makeV(wheel_radius,begining_point,closoid_number,point_num,breast_wide)
    objfile_str = ""
    for i in range(len(v)):
        for j in range(len(v[i])):
            objfile_str += "v "+str(v[i][j][0])+" "+str(v[i][j][1])+" "+str(v[i][j][2])+"\n"
    for i in range(len(v)-1):
        for j in range(len(v[i])-1):
            objfile_str += "f "+str(len(v[i])*i+j+1)+" "+str(len(v[i])*i+j+2)+" "+str(len(v[i])*(i+1)+j+2)+" "+str(len(v[i])*(i+1)+j+1)+"\n"
    return objfile_str
 
    '''
Exemplo n.º 30
0
 def scaleLine(self, length):
     PointO = np.array(self.vertexSource.vertexPosition)
     PointD = np.array(self.vertexSignaled.vertexPosition)
     dist = np.linalg.norm(PointO - PointD)
     print("Distance: " + str(dist))
     print("Vec: " + str(PointO - PointD))
     vecToScale = PointD - PointO
     self.scaleVector(vecToScale, length)
     print("Scaled Vec: " + str(vecToScale))
     PointDnew = PointO + vecToScale
     idNew = self.vertexSignaled.vertexID
     self.newVertexSignaled = Vertex(self.vertexSource.numOfVertices,
                                     PointDnew, idNew)
    def ReadInFromList(self, path):
        file = open(path, "r")

        contents = file.readlines()
        for i in range(len(contents)):
            x, y = map(int, contents[i].strip('()\n\s').split(','))

            v = Vertex.Vertex(x, y)
            self.Add_Vertex(v)

        self.Connect()
        self.Display()
        file.close()
Exemplo n.º 32
0
 def test_RemoveEdge(self):
     graff = Vertex.SimpleGraph(
         4
     )  # до удаления связь между вершинами была, после удаления отсутствует
     graff.AddVertex(1)
     graff.AddVertex(2)
     graff.AddVertex(3)
     graff.AddVertex(4)
     graff.AddEdge(1, 2)
     self.assertEqual(graff.m_adjacency[1][2] == 1, True)
     self.assertEqual(graff.m_adjacency[2][1] == 1, True)
     graff.RemoveEdge(1, 2)
     self.assertEqual(graff.m_adjacency[1][2] == 0, True)
     self.assertEqual(graff.m_adjacency[2][1] == 0, True)
Exemplo n.º 33
0
Arquivo: Graph.py Projeto: zhued/intro
	def __init__(self):
		# make an empty Vertex list
		self.vertices = []
		# make an empty Edge list
		self.edges = []
		# initialize the Vertex count to be 0
		self.vertexCount = 0
		# initialize the Edge count to be 0
		self.edgeCount = 0
		# create the 'bad Vertex' 
		self.badVertex = Vertex('bad vertex')
		# set the badness flag for this bad Vertex
		self.badVertex.setBadness(True)
		# create the 'bad Edge'
		self.badEdge = Edge(0.0)
		# set the badness flag for this bad Edge
		self.badEdge.setBadness(True)
Exemplo n.º 34
0
Arquivo: Graph.py Projeto: zhued/intro
	def copyDeeply(self, g):
		# self assignment check, done in C++ a little differently
		if self.isEqual(g):
			return
		# clear out the existing Vertex and Edge data
		self.clear()
		# copy each Vertex and update the Edge array as we go
		# notice here we can use the vertexCount of the other
		# graph, g to count how many to copy
		for i in range(0, g.vertexCount):
			# make a new Vertex from g's Vertex
			v = Vertex(g.vertices[i].name)
			# add that Vertex to our Vertex list
			self.vertices.append(v)
			# update our vertexCount
			self.vertexCount += 1
			# add a new row to the edges array; this is self.edges[i], below
			self.edges.append([])
			# copy a row of Edges from g to here
			for j in range(0, g.vertexCount):
				# make a new Edge from g's edge
				e = Edge(g.edges[i][j].cost)
				# add the Edge to the end of the row
				self.edges[i].append(e)
				# count edges up if the Edge is not a zero edge
				if e.empty() == False:
					self.edgeCount += 1
		# create the 'bad Vertex' we send back when there's 
		# no good answer to getVertex()
		self.badVertex = Vertex('bad vertex')
		# set this Vertex to be bad
		self.badVertex.setBadness(True)
		# create the 'bad Edge' we send back when there's 
		# no good answer to getEdge()
		self.badEdge = Edge(0.0)
		# set this Edge to be bad
		self.badEdge.setBadness(True)
Exemplo n.º 35
0
Arquivo: Graph.py Projeto: zhued/intro
class Graph:

	# Create an empty Graph
	# This is analogous to the default constructor in C++, Graph( );
	def __init__(self):
		# make an empty Vertex list
		self.vertices = []
		# make an empty Edge list
		self.edges = []
		# initialize the Vertex count to be 0
		self.vertexCount = 0
		# initialize the Edge count to be 0
		self.edgeCount = 0
		# create the 'bad Vertex' 
		self.badVertex = Vertex('bad vertex')
		# set the badness flag for this bad Vertex
		self.badVertex.setBadness(True)
		# create the 'bad Edge'
		self.badEdge = Edge(0.0)
		# set the badness flag for this bad Edge
		self.badEdge.setBadness(True)
	
	# Clear out all the information in the Graph
	# so it is like an empty Graph again.
	# Analogous to the C++ function void clear( );
	def clear(self):
		# remove all the Edges and all the Vertices 
		# (more important in C++ than in Python)
		for i in range(0, self.vertexCount):
			for j in range(0, self.vertexCount):
				# pop the last Edge off the list 
				self.edges[self.vertexCount - 1].pop()
			# pop the last empty Edge sublist off edges
			self.edges.pop()
			# pop the last Vertex off vertices
			self.vertices.pop()
		# now everybody should be empty, and we should have
		# one empty list (vertices == []) for Vertex 
		# and one empty list (edges == []) for Edges
		# set vertexCount to 0
		self.vertexCount = 0
		# and set edgeCount to 0
		self.edgeCount = 0
		
	# Make our self's Graph be an independent copy of another Graph called g.
	# By independent, I mean that we can change our Graph (add a Vertex,
	# remove an Edge) after this and not change g the same way, as a side effect.
	# This function is loosely analogous to two functions in C++:
	# the assignment operator, Graph& operator =(const Graph& source);
    # and the copy constructor, Graph(const Graph& source);
	def copyDeeply(self, g):
		# self assignment check, done in C++ a little differently
		if self.isEqual(g):
			return
		# clear out the existing Vertex and Edge data
		self.clear()
		# copy each Vertex and update the Edge array as we go
		# notice here we can use the vertexCount of the other
		# graph, g to count how many to copy
		for i in range(0, g.vertexCount):
			# make a new Vertex from g's Vertex
			v = Vertex(g.vertices[i].name)
			# add that Vertex to our Vertex list
			self.vertices.append(v)
			# update our vertexCount
			self.vertexCount += 1
			# add a new row to the edges array; this is self.edges[i], below
			self.edges.append([])
			# copy a row of Edges from g to here
			for j in range(0, g.vertexCount):
				# make a new Edge from g's edge
				e = Edge(g.edges[i][j].cost)
				# add the Edge to the end of the row
				self.edges[i].append(e)
				# count edges up if the Edge is not a zero edge
				if e.empty() == False:
					self.edgeCount += 1
		# create the 'bad Vertex' we send back when there's 
		# no good answer to getVertex()
		self.badVertex = Vertex('bad vertex')
		# set this Vertex to be bad
		self.badVertex.setBadness(True)
		# create the 'bad Edge' we send back when there's 
		# no good answer to getEdge()
		self.badEdge = Edge(0.0)
		# set this Edge to be bad
		self.badEdge.setBadness(True)
	
	# function I wrote to compare 2 Graphs for equality
	# optional for you, but not trivial
	def isEqual(self, g):
		if self.vertexCount != g.vertexCount:
			return False
		if self.edgeCount != g.edgeCount:
			return False
		eps = 0.00000000000000000001
		for i in range(0, g.vertexCount):
			index = self.getIndex(g.vertices[i].getName())
			if self.validIndex(index) == False:
				return False
			otherRow = i
			myRow = index
			for j in range(0, g.vertexCount):
				otherCol = j
				myCol = self.getIndex(g.vertices[j].getName())
				if abs(self.edges[myRow][myCol].getCost() - g.edges[otherRow][otherCol].getCost()) > eps:
					return False
		return True
			
	# Put a new Vertex in the Graph and update the Edge list.
	# No duplicate Vertex names are allowed.
	# This function is analogous to the C++ function 
	# bool addVertex(const string& newVertexname);  
	def addVertex(self, vertexName):
		# look at each of our current Vertex
		for i in range(0, self.vertexCount):
			# check if this Vertex has the same name as the
			# one we want to add; if so, bail out without
			# adding the duplicate
			if self.vertices[i].getName() == vertexName:
				return False
		# if we didn't bail out in that for loop, then we add the new Vertex.
		# we make a new Vertex with this name
		v = Vertex(vertexName)
		# we put that Vertex in our vertices list
		self.vertices.append(v)
		# we make a new row that we'll put in the edges array 
		# for this Vertex
		newRow = []
		# we fill that row with empty Edges
		# notice that because vertexCount is still not updated
		# to count the new Vertex, we have to put one more
		# Edge in to keep the whole edges list square
		for i in range(0, self.vertexCount + 1):
			# make a new empty Edge
			e = Edge(0.0)
			# put this Edge in the new row
			newRow.append(e)
		# now add that new row to the edges array
		self.edges.append(newRow)
		# we add one extra Edge to each of the previous rows of edges,
		# which makes a new column in the edges array for this Vertex
		# Note that vertexCount is still not updated, so we only do this
		# for the rows in the edges array that we had before adding this 
		# Vertex.
		for i in range(0, self.vertexCount):
			# make one new empty Edge
			e = Edge(0.0)
			# add that Edge to the end of this row
			self.edges[i].append(e)
		# finally we update vertexCount
		self.vertexCount += 1
		# success, return True
		return True

	# Take a Vertex out of the Graph and update the Edge list, 
	# returning True if things go as expected. If this Vertex 
	# is not in the Graph, remove nothing, and return False.
	# This function is analogous to the C++ function
	# bool removeVertex(const string& unwantedVertexName);  
	def removeVertex(self, vertexName):
		# helper function getIndex tells us the position of a Vertex
		# in our vertices list.  If it's not there, getIndex gives back -1.
		index = self.getIndex(vertexName)
		# helper function validIndex checks that this index >= 0
		# and index < vertexCount. If it's outside that range,
		# we do not have a Vertex by this name, so we bail out
		# without removing anything and send back a False to 
		# indicate weirdness on the user's part.
		if (self.validIndex(index) == False):
			return False
		# if we get to here, then we really have a Vertex to remove
		# First, we have to get rid of this Vertex's row in the Edges list.
		# But we want to keep our count of nonzero Edges up to date,
		# so first we subtract any real Edges in this row from edgeCount.
		for i in range(0, self.vertexCount):
			# if the Edge we're throwing away is nonzero, 
			# count edgeCount down
			if (self.edges[index][i].empty() == False):
				self.edgeCount -= 1
		# take this whole row of Edges out of the edges list
		self.edges.pop(index)
		# now take out the column of Edges to this Vertex in the other rows
		for i in range(0, self.vertexCount - 1):
			# if the Edge we're throwing away is nonzero, 
			# count edgeCount down
			if (self.edges[i][index].empty() == False):
				self.edgeCount -= 1
			# take out the edge in this column
			self.edges[i].pop(index)
		# take out this Vertex from our list
		self.vertices.pop(index)
		# update our vertexCount to be one less
		self.vertexCount -= 1
		# send back True to show that things all went as expected
		return True
				
	# Given the names of 2 Vertex in the Graph, set an Edge 
	# between them to have a particular cost. 
	# If the Vertex both exist and are not the same Vertex, 
	# update the cost of their Edge and return True.
	# If one or both Vertex are not in the Graph, or if
	# the Edge is from one Vertex to itself, make no changes 
	# and send back a False to indicate a problem on the
	# user's end.
	# This function is analogous to the C++ function
	# bool setEdge(const string& fromVertexName, const string& toVertexName, const Edge& newEdge);
	def setEdge(self, fromVertexName, toVertexName, cost):
		# quickly check for self-edges, which are not allowed
		if fromVertexName == toVertexName:
			return False
		# use the helper function getIndex to find the position
		# of the 'from'-Vertex in our Vertex list
		fromIndex = self.getIndex(fromVertexName)
		# use the helper function getIndex to find the position
		# of the 'to'-Vertex in our Vertex list
		toIndex = self.getIndex(toVertexName)
		# check that both of these indexes are valid and update the
		# Edge if they both are
		if (self.validIndex(fromIndex) and self.validIndex(toIndex) and fromIndex != toIndex):
			# we might be overwriting a real (nonzero) Edge;
			# if so we subtract one from edgeCount
			if self.edges[fromIndex][toIndex].empty() == False:
				self.edgeCount -= 1
			# update the Edge to have the new cost
			self.edges[fromIndex][toIndex].setCost(cost)
			# check if this Edge is empty; if not, add one to  
			# edgeCount 
			if self.edges[fromIndex][toIndex].empty() == False:
				self.edgeCount += 1
			# success, we are done
			return True
		# if one or both of fromIndex or toIndex is invalid, then 
		# we don't have one or both of these Vertex, so we bail 
		# out and send back a False to indicate user weirdness
		else:
			return False
	
	# return True if the Graph is empty, which means it has no
	# Vertex at all.  Else, return False.
	# This is analogous to the C++ function bool empty( ) const;
	def empty(self):
		return self.vertexCount == 0
	
	# return True if the Graph contains a Vertex, and False if not.
	# this function is analogous to the C++ function:
	# bool containsVertex(const string& vertexName) const;
	def containsVertex(self, vertexName):
		# use the getIndex helper function to find the position
		# of the Vertex with this name in the vertices list
		index = self.getIndex(vertexName)
		# if this index is valid, the Graph contains this Vertex
		# if it's not, the Graph does not contain this Vertex
		return self.validIndex(index)
		
	# return True if the Graph contains an Edge between 2 Vertex, 
	# and False if not.
	# this function is analogous to the C++ function
	# bool containsEdge(const string& fromVertexname, const string& toVertexName) const;
	def containsEdge(self, fromVertexName, toVertexName):
		# use the getIndex helper function to find the position
		# of the 'from' Vertex with this name in the vertices list
		fromIndex = self.getIndex(fromVertexName)
		# use the getIndex helper function to find the position
		# of the 'to' Vertex with this name in the vertices list
		toIndex = self.getIndex(toVertexName)
		# if these are both valid indexes, then return True
		# if that Edge between them is not a zero edge,
		# and False if it is
		if (self.validIndex(fromIndex) and self.validIndex(toIndex)):
			return self.edges[fromIndex][toIndex].empty()
		# if these aren't valid indices, we don't have an Edge
		# for them in the Graph; return False
		else:
			return False
		
	# Given the names of 2 Vertex in the Graph, set an Edge 
	# between them to have zero cost and return True. If 
	# these Vertex aren't in the Graph, return False.
	# This function is analogous to the C++ function
	# bool removeEdge(const string& fromVertexName, const string& toVertexName);
	def removeEdge(self, fromVertexName, toVertexName):
		# use the getIndex helper function to find the position
		# of the 'from' Vertex with this name in the vertices list
		fromIndex = self.getIndex(fromVertexName)
		# use the getIndex helper function to find the position
		# of the 'to' Vertex with this name in the vertices list
		toIndex = self.getIndex(toVertexName)
		# check if these are both valid indexes, using the helper
		# function isValid; if so, then update the Edge
		# to be zero cost
		if (self.validIndex(fromIndex) and self.validIndex(toIndex)):
			# if we're changing a non-empty Edge to be empty, 
			# we need to subtract one from edgeCount
			if self.edges[fromIndex][toIndex].empty() == False:
				self.edgeCount -= 1
			# update the cost to 0
			self.edges[fromIndex][toIndex].setCost(0.0)
			# success, we're done
			return True
		# if these are not both valid indexes, then we bail and
		# return False
		else:
			return False
	
	# Given a name of a Vertex, return that Vertex if it exists
	# in the Graph.  If it does not exist, return the bad Vertex 
	# we keep around for just this situation.
	# This function is analogous to the C++ function
	# const Vertex& getVertex(const string& vertexName) const;
    # and Vertex& getVertex(const string& vertexName);            
	def getVertex(self, vertexName):
		# use the getIndex helper function to find the position
		# of the Vertex with this name in the vertices list
		index = self.getIndex(vertexName)
		# if this index is valid, return the Vertex in our list at
		# that index
		if self.validIndex(index):
			return self.vertices[index]
		# else, send back the bad Vertex
		else:
			return self.badVertex
	
	# Given the names of two Vertices, return the Edge from the first
	# Vertex to the second one, if these Vertices exist in the Graph.  
	# If one of the Vertices does not exist, or both don't, return the 
	# bad Vertex we keep around for just this situation.
	# this function is analogous to the C++ functions
	# const Edge& getEdge(const string& fromVertexName, const string& toVertexName) const;
    # and Edge& getEdge(const string& fromVertexName, const string& toVertexName);       
	def getEdge(self, fromVertexName, toVertexName):
		# use the getIndex helper function to find the position
		# of the 'from' Vertex with this name in the vertices list
		fromIndex = self.getIndex(fromVertexName)
		# use the getIndex helper function to find the position
		# of the 'to' Vertex with this name in the vertices list
		toIndex = self.getIndex(toVertexName)
		# check if these are both valid indexes, using the helper
		# function isValid; if so, then send back this Edge
		if (self.validIndex(fromIndex) and self.validIndex(toIndex)):
			return self.edges[fromIndex][toIndex]
		# if these are not both valid indexes, return the bad Edge
		else:
			return self.badEdge
			
	# tell me how many Vertex the Graph has
	def countVertices(self):
		return self.vertexCount
	
	# tell me how many nonzero Edges the Graph has
	def countEdges(self):
		return self.edgeCount
	
	# Helper function to print an array representation of the 
	# Graph, with the 'from'-Vertex names down the left hand side 
	# and the 'to'-Vertex names across the top, and the edges 
	# between then printing as their costs
	def display(self):
		s = '\t'
		for i in range(0, self.vertexCount):
			s += self.vertices[i].getName()[:7] 
			s += '\t'
		s += '\n'
		for i in range(0, self.vertexCount):
			s += self.vertices[i].getName()[:7] 
			s += '\t'
			for j in range(0, self.vertexCount):
				s += str(self.edges[i][j].getCost()) 
				s += '\t'
			s += '\n'
		print s
			
	# Helper function to look up vertex names in the vertices list
	# If the vertex name matches one in our Graph, then this returns
	# the position of that Vertex in the vertices list.
	# If not, this returns a weird value, -1, which is a bad
	# index into a list
	def getIndex(self, vertexName):
		# loop over each Vertex in the Vertex list
		for i in range(0, self.vertexCount):
			# check if the name matches the one we're looking for;
			# if so, return this index right away.
			if self.vertices[i].getName() == vertexName:
				return i
		# if we get all the way through the Vertex names,
		# and we never found a match, we don't have this Vertex
		return -1
	
	# Helper function to make sure that an index into the Vertex 
	# list is not out of bounds. Returns True if the index is 
	# valid, and False if it's out of bounds.
	def validIndex(self, index):
		return (index >= 0 and index < self.vertexCount)