def test_constructor_if_assign_edge_properly(self): state1 = State(name='A') edge1 = Edge(label='a', destination=State('B')) self.assertListEqual(state1.state_edges, []) state1.add_edge(edge1) self.assertEqual(state1.state_edges, [Edge(label='a', destination=State('B'))])
def __init__(self, center, radius, color): self.center = center self.radius = radius self.color = color self.filled = True self.velocity = Edge(self.center, Point(self.center.x, self.center.y), '#00ff00') self.mass = 1.0
def loadGraphFromFile(self, infile): with open(infile) as f: lines = f.readlines() cleanlines = [x.strip() for x in lines ] #strip off any weird leading or trailing spaces. for line in cleanlines: line = line.replace('\'', '').replace('[', '').replace(']', '').replace( ' ', '').strip('()') rawEdge = line.split( ',' ) # now just have nice clean comma-separated values. Make it a list [l1, l2, label, x1, y1, x2, y2] = rawEdge # grab all the components of the edge if l1 not in self.nodeIndex: self.nodeIndex[l1] = (int(x1), int(y1)) self.nodes.append(Node(int(x1), int(y1), l1)) if l2 not in self.nodeIndex: self.nodeIndex[l2] = (int(x2), int(y2)) self.nodes.append(Node(int(x2), int(y2), l2)) # Now build and Edge object for it newEdge = Edge((int(x1), int(y1)), (int(x2), int(y2)), int(label)) newEdge.setLabels(l1, l2) self.edges.append(newEdge) f.close()
def setdata(self,node_objects,edge_objects): """ Add sRNA - sRNA edges based on their similarity @param node_objects: list of node objects @param edge_objects: list of edge objects """ try: similarityReader = csv.reader(open(self.similarity_file, 'rb'), delimiter='\t') #passage de l'entete similarityReader.next() for i in similarityReader: node1=self.getlinknode(node_objects,i[0]) node2=self.getlinknode(node_objects,i[1]) #Create edge if(node1 !=None and node2 !=None): edge_element=Edge(node1,node2) #set similarity value and scategory edge_element.similarity=float(i[2]) edge_element.category=2 #Add edge element in the list self.addelements(edge_objects,edge_element) #edge_objects+=[edge_element] except IOError: sys.exit("Error : can not open file %s"%self.similarity_file) #except: # sys.exit("Something went wrong with %s"%self.similarity_file) return(node_objects,edge_objects)
def getConvertedEdges(graph : networkx.Graph): convertedEdges = [[] * (graph.number_of_nodes()) for i in range(graph.number_of_nodes())] #--> Desta forma para evitar que as linhas sejam todas a msm referencia --> https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly counter = 0 counter2 = 0 for i in range(len(graph.nodes)): counter = 0 for u, v, data in graph.edges(data=True): if u > i: #SE CHEGOU AO FIM DA LISTAGEM DAS EDGES break elif i == u: if i == v: itemArgs = {Utils.INITIALPOINT: putAsciiValues(u, graph.number_of_nodes()), Utils.FINALPOINT: putAsciiValues(v, graph.number_of_nodes()), Utils.DISTANCE: data['weight']} convertedEdges[i].append(Edge.Edge(**itemArgs)) counter = counter + 1 if i != v: itemArgs = {Utils.INITIALPOINT: putAsciiValues(u, graph.number_of_nodes()), Utils.FINALPOINT: putAsciiValues(v, graph.number_of_nodes()), Utils.DISTANCE: data['weight']} convertedEdges[i].append(Edge.Edge(**itemArgs)) itemArgs = {Utils.INITIALPOINT: putAsciiValues(v, graph.number_of_nodes()), Utils.FINALPOINT: putAsciiValues(u, graph.number_of_nodes()), Utils.DISTANCE: data['weight']} convertedEdges[v].append(Edge.Edge(**itemArgs)) else: continue return convertedEdges
def addEdge(self, nod1, l1, nod2, l2, col): l1 = self.LayerPerm[l1] l2 = self.LayerPerm[l2] if col == 1 or col == 15: return self.addEdge_util(Edge.Edge(nod1, l1, nod2, l2, col)) return max(self.addEdge_util(Edge.Edge(nod1, l1, nod2, l2, col)), self.addEdge_util(Edge.Edge(nod2, l2, nod1, l1, col)))
def add_edge(self, v, w, wt): if v == w: return self.g[v].append(Edge(v, w, wt)) if not self.is_directed: self.g[w].append(Edge(w, v, wt)) self.edges += 1
def closest_node_on_segment_to_node(node, segment) -> Node.Node: A_start, B_start, C_start = perpendicular(segment.start, segment) A_end, B_end, C_end = perpendicular(segment.end, segment) if line_value(A_start, B_start, C_start, node) * line_value( A_end, B_end, C_end, node) < 0: node_A, node_B, node_C = perpendicular(node, segment) x = 10000 y = (-node_A * x - node_C) / node_B end = Node.Node(x, y) node_segment = Edge.Edge(node, end) if geometry.intersect(segment, node_segment): closest_node = geometry.intersection(segment, node_segment) else: x = -10000 y = (-node_A * x - node_C) / node_B end = Node.Node(x, y) node_segment = Edge.Edge(node, end) closest_node = geometry.intersection(segment, node_segment) else: closest_node = segment.start distance_to_start = dist(node, segment.start) distance_to_end = dist(node, segment.end) if distance_to_start > distance_to_end: closest_node = segment.end return closest_node
def add_edge(self, v1, v2, weight): if v1 == v2: return self.g[v1].append(Edge(v1, v2, weight)) if not self._is_directed: self.g[v2].append(Edge(v2, v1, weight))
def genRelation(self, verts, edges): for vert in verts: self.relation[vert] = [] for edge in edges: self.relation[edge.start].append( Edge.TruncEdge(edge=edge, head=True)) self.relation[edge.end].append( Edge.TruncEdge(edge=edge, head=False))
def add_edge(v1, v2, w): edge = Edge.Edge(v1,v2,w) resEdge = Edge.Edge(v2,v1,0) edge.res = resEdge resEdge.res = edge adjacency_list[v1].append(edge) adjacency_list[v2].append(resEdge) optFlow[edge] = 0 optFlow[resEdge] = 0
def _add_route_info(self, firewall, data, interface, edge): """Add informations about gateways and destinations network, and link them with the corresponding firewall and network. """ self.graph.add_node(data, object=Node(data)) self.graph.add_edge(firewall, data, object=Edge(data, firewall)) self.graph.add_edge(data, interface.network, object=Edge(data, interface))
def addDependency(self, From, to, label, type, description = None): #if self.isInvalidEdge(From, to): # return fromToken = self._map[From] toToken = self._map[to] edge = Edge(fromToken, toToken, label, type, Edge.RenderType.dependency) if description is not None: edge.description = description self._edges.append(edge)
def createNetworkByType(Ntype): NtypeEdgeCol = 14 if Ntype == 'Minor': NtypeEdgeCol = -14 network.createMonoplex( Edge.getEdgeSample(Edge.filterEdges(network.Edges, [1, NtypeEdgeCol]), 100), Ntype) print(len(network.monoplex[Ntype].G.nodes), len(network.monoplex[Ntype].G.edges))
def build(self): mainPanel = MainPanel() vertex1 = Vertex(pos = (100,100), radius = 25) vertex2 = Vertex(pos = (200,200), radius = 25) edge = Edge() edge.setVertices(vertex1, vertex2) mainPanel.add_widget(edge) mainPanel.add_widget(vertex1) mainPanel.add_widget(vertex2) return mainPanel
def Similar(src, data): ''' To create similar edges ''' for dest in data: edge = Edge(src=src, dest=dest, kind='Similar') edge.populate() #Adding edge created in graph Insert(src, edge)
def S2W(src, data): ''' To create sense to word edges ''' for dest in data: edge = Edge(src=src, dest=dest, kind='S2W') edge.populate() #Adding edge created in graph Insert(src, edge)
def Holonym(src, data): ''' To create holonym edges ''' for dest in data: edge = Edge(src=src, dest=dest, kind='Holonym') edge.populate() #Adding edge created in graph Insert(src, edge)
def Roadmap_construction(self): while len(self.vertices) < self.number_of_node: q_random = self.sampling() if self.check_collision(q_random): self.vertices.append(q_random) for vertex in self.vertices: k_nearest_neighbor = self.get_k_nearest_neighbor(vertex, self.number_of_neighbors) for neighbor in k_nearest_neighbor: if Edge.Edge(neighbor[0], vertex) not in self.edges and self.connect(neighbor[0], vertex): self.edges.append(Edge.Edge(neighbor[0], vertex))
def Entailment(src, data): ''' To create entailment edges ''' for dest in data: edge = Edge(src=src, dest=dest, kind='Entailment') edge.populate() #Adding edge created in graph Insert(src, edge)
def D2S(src, data): ''' To create word to sense definition backedges in which it occurs ''' total_freq = sum(data.values()) for dest, frequency in data.items(): edge = Edge(src=src, dest=dest, kind='D2S') edge.populate(frequency=frequency, total_freq=total_freq) #Adding edge created in graph Insert(src, edge)
def Meronym(src, data): ''' To create hypernym edges ''' num_mero = len(data) for dest in data: edge = Edge(src=src, dest=dest, kind='Meronym') edge.populate(num_mero=num_mero) #Adding edge created in graph Insert(src, edge)
def W2S(src, data): ''' To create word to sense edges ''' #Each edge is a dictionary, data list of dictionaries total_freq = sum(data.values()) for dest, frequency in data.items(): edge = Edge(src=src, dest=dest, kind='W2S') edge.populate(frequency=frequency, total_freq=total_freq) #Adding edge created in graph Insert(src, edge)
def createGraph(lines): verts = [] edges = [] for line in lines: lineverts = line.split(' ') if not lineverts[0] in verts: verts.append(lineverts[0]) if not lineverts[1] in verts: verts.append(lineverts[1]) if len(lineverts) == 2: edges.append(Edge.Edge(lineverts[0],lineverts[1])) else: edges.append(Edge.Edge(lineverts[0],lineverts[1],lineverts[2])) return Graph.Graph(verts,edges)
def collideWithCircle(self, b): axis = Edge(self.center, b.center, "#000000") axis2 = Edge(self.center, b.center, "#000000") aPerp = self.velocity.getPerpVec(axis) bPerp = b.velocity.getPerpVec(axis) aVi = self.velocity.projOnto(axis) bVi = b.velocity.projOnto(axis) aVf = (2.0*b.mass*bVi + aVi*(self.mass - b.mass))/(self.mass + b.mass) bVf = (2.0*self.mass*aVi + bVi*(b.mass - self.mass))/(self.mass + b.mass) axis.setM(aVf) aPerp.add(axis) aPerp.setOrigin(self.center) self.velocity = aPerp self.center = self.velocity.p0 axis2.setM(bVf) bPerp.add(axis2) bPerp.setOrigin(b.center) b.velocity = bPerp b.center = b.velocity.p0
def main(playerX: int, playerY: int, pipeInfo: list, stillAlive: bool): test1 = Edge(0, 3, 100, 100) test2 = Edge(1, 3, 100, 100) test3 = Edge(2, 3, 100, 100) supertest = (test1, test2, test3) NNTest = NeuralNetwork(supertest, 4, (3)) if pipeInfo[0]['x'] >= 0: print("Pipe Info = ", pipeInfo[0]['x']) else: print("Pipe Info = ", pipeInfo[1]['x']) return
def S2E(src, data): ''' To create sense to non-noise words in example ''' #Each edge is a dictionary, data is list of dictionaries for item in data: dest = item[0] frequency = item[1] total_freq = item[2] edge = Edge(src=src, dest=dest, kind='S2E') edge.populate(frequency=frequency, total_freq=total_freq) #Adding edge created in graph Insert(src, edge)
def getInAndOut(A,B, InsAndOuts): for arestaA in A.Arestas: count = 0 pontoMedio = getPontoMedioAresta(arestaA) #pontoMedio[0] = x , pontoMedio[1] = y newAresta = (Point(-1,pontoMedio.y,0),pontoMedio) edge = Edge(arestaA[0],arestaA[1]) helper = 0 for arestaB in B.Arestas: if(hasRetaIntersection(newAresta[0], newAresta[1], arestaB[0], arestaB[1])): point = getIntersection(newAresta[0], newAresta[1], arestaB[0], arestaB[1]) count += 1 if point in B.Vertices and not findMaxOrMin(point,B.Vertices): helper += 1 if helper > 0: count += 1 if(count%2 != 0): if edge not in InsAndOuts['in']: InsAndOuts['in'].append(edge) else: if edge not in InsAndOuts['out']: InsAndOuts['out'].append(edge) return InsAndOuts
def deflectFromEdge(self, e): mSquared = e.x() * e.x() + e.y() * e.y() p0 = Point(0, 0) pf = Point((-2 * e.y() * self.velocity.det(e)) / mSquared, 2 * e.x() * self.velocity.det(e) / mSquared) x = Edge(p0, pf, generateHTMLColor(255, 255, 0)) self.velocity.add(x)
def readEdgeFromTxt(self): edge_list = [] if self.txtpath: try: file = open(self.txtpath, "r") line = file.readline() print(line) s_list = line.split(",") for s in s_list: print(s) # print(len(s)) if s: # print(s[0]) s = s.strip() v_s = Vertex(-1, s[0]) v_e = Vertex(-1, s[1]) d = int(s[2]) edge = Edge(v_s, v_e, d) edge_list.append(edge) except IOError: return None else: # print(edge_list) return edge_list
def run(parameters): file_name = parameters['file_name'] stdOut = parameters['output'] ns = {'xmlns' : 'http://graphml.graphdrawing.org/xmlns', 'graphml' : 'http://www.yworks.com/xml/graphml'} try: graph = xml.etree.ElementTree.parse(file_name) except IOError as e: stdOut.print_error("Could not open specified file\nDetails:" + str(e)) graphRoot = graph.getroot() g = graphRoot.find('xmlns:graph', ns) nodes = g.findall('xmlns:node', ns) edges = g.findall('xmlns:edge', ns) for node in nodes: data = node.findall('xmlns:data', ns) node_recognized = False for dataElement in data: nodeType = None for type_string in supported_node_types: if nodeType is None: nodeType = dataElement.find(type_string, ns) id = int(node.attrib['id'].strip('n')) if nodeType is not None: label = nodeType.find('graphml:NodeLabel', ns).text if label is None: label = '' nodeList.append(Node.Node(id, [], label)) node_recognized = True if not node_recognized: stdOut.print_error('Unrecognized node type on graph! Node id: %s' % id) for edge in edges: data = edge.findall('xmlns:data', ns) for dataElement in data: edgeType = dataElement.find('graphml:PolyLineEdge', ns) if edgeType is not None: id = int(edge.attrib['id'].strip('e')) source = int(edge.attrib['source'].strip('n')) target = int(edge.attrib['target'].strip('n')) label = edgeType.find('graphml:EdgeLabel', ns) if label is not None: label_text = label.text else: label_text = '' edgeList.append(Edge.Edge(source, target, label_text)) nodeList[source].related_edges.append(edgeList[-1]) else: stdOut.print_debug("EDGE NOT KNOWN: \n[%s, %s, %s, %s, %s]" % (edgeType, id, source, target, label)) return edgeList, nodeList
def add_edge(self, v, w, element): if not v in self._structure or not w in self._structure: return None e = Edge(v, w, element) self._structure[v][w] = e self._structure[w][v] = e return e
def __init__(self, graph, s): self.s = s self.graph = graph n = graph.vertexs self.marked = [False for _ in xrange(n)] self.dist_to = [0 for _ in xrange(n)] self._from = [None for _ in xrange(n)] self.mh = IndexMinHeap(n) self._from[s] = Edge(s, s, 0) self.marked[s] = True self.mh.insert(s, self.dist_to[s]) while not self.mh.is_empty(): v = self.mh.extract_min_index() self.marked[v] = True for e in self.graph.g[v]: w = e.other(v) if not self.marked[w]: if not self.dist_to[w] or self.dist_to[v] + e.weight < self.dist_to[w]: self.dist_to[w] = self.dist_to[v] + e.weight self._from[w] = e if not self.mh.contain(w): self.mh.insert(w, self.dist_to[w]) else: self.mh.change(w, self.dist_to[w])
def build_tree (al, nodes) : """ Takes in an adjacency list, set of all nodes, and the edge set and builds a tree, and contructs edges. al is an adjacency list nodes dictionary of all nodes edges will be the Priority Queue of all edges """ for n in al : for node_info in al[n] : e = Edge() e.weight = int(node_info[1]) e.next_node = nodes[node_info[0]] e.src_node = nodes[n] nodes[n].neighbors.append(nodes[node_info[0]]) # append adjacent node... nodes[n].weights.append(e) # and its corresponding weight
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)
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)
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)