def planeIntersect(p1, p2, zval): #plane definitely doesn't cross line seg if not (((p1.z <= zval) and (p2.z >= zval)) or ((p1.z >= zval) and (p2.z <= zval))): #print "no intersection" return Vertex(0, 0, -2) x = (float(p1.x), p2.x - p1.x) y = (float(p1.y), p2.y - p1.y) z = (float(p1.z), p2.z - p1.z) #print "z = %.2f %.2f" % (z[0], z[1]) if z[1] == 0: if z[0] == zval: #line is on plane #print "line is on the plane" return Vertex(0, 0, -1) else: #line parallel to plane #print "line parallel to plane" return Vertex(0, 0, -2) else: #print "t = %.2f/%.2f" % (zval - z[0], z[1]) t = (zval - z[0]) / float(z[1]) #print ">>>>>>>>>>plane intersection" #print "t = %.2f" % t #p1.show() #p2.show() #p3 = Vertex(x[0]+x[1]*t, y[0]+y[1]*t, zval) #p3.show() #print "<<<<<<<<<<<<<<<<<<<<<<<<<<<<" return Vertex(x[0] + x[1] * t, y[0] + y[1] * t, zval)
def create_graph(self, start_position, initial_pheromone): # calculate the cooverages of each sensor at each power level for sensor in self.__repository.sensors.values(): sensor.calculate_coverage(self.__repository.mapp) self.__graph = UndirectedGraph() # transform the starting point and each sensor's different states into vertices start_vertex = Vertex(start_position, 0, 0) self.__graph.add_vertex(start_vertex) for sensor in self.__repository.sensors.values(): for i, coverage in enumerate(sensor.coverages): vertex = Vertex(sensor.position, i, coverage) self.__graph.add_vertex(vertex) vertices = list(self.__graph.parse_vertices()) for i in range(len(vertices) - 1): start = vertices[i] for j in range(i + 1, len(vertices)): end = vertices[j] if start.position[0] != end.position[0] and start.position[1] != end.position[1]: path = self.search_a_star( start.position[0], start.position[1], end.position[0], end.position[1]) cost = len(path) edge = Edge(start, end, cost, path, initial_pheromone) self.__graph.add_edge(edge)
def __init__(self, numpoints, dimension, k_n): self.Dimension = dimension # dimension of vertex self.V = [Vertex(dimension, i) for i in range(numpoints)] # index range {0,1,2,...,V-1} self.num_V = numpoints self.num_E = 0 # number of edges in graph self.adj = {} # adjacent list # initialize adjacent dictionary for i in range(self.num_V): self.adj[i] = [] # if dimension = 0 -> assign weights randomly if self.Dimension == 0: for i in range(numpoints - 1): for j in range(i + 1, numpoints): new_edge = Edge(self.V[i], self.V[j], 'random') if new_edge.weight <= k_n: self.adj[i].append(new_edge) self.adj[j].append(new_edge) self.num_E += 1 else: # initialize edge for complete undirected graph for i in range(numpoints - 1): for j in range(i + 1, numpoints): if Vertex.Euclidean_distance(self.V[i], self.V[j]) < k_n: new_edge = Edge(self.V[i], self.V[j], 'Euclidean') self.adj[i].append(new_edge) self.adj[j].append(new_edge) self.num_E += 1
def build_graph(): graph = Graph() # MAKE ROOMS INTO VERTICES BELOW.. entrace=Vertex("entrace") graph.add_vertex(entrace) # ADD ROOMS TO GRAPH BELOW... ante_chamber=Vertex("ante chamber") kings_room=Vertex("king's room") graph.add_vertex(ante_chamber) graph.add_vertex(kings_room) graph.add_edge(entrace,ante_chamber,7) graph.add_edge(entrace,kings_room,3) graph.add_edge(kings_room,ante_chamber,1) grand_gallery=Vertex("grand_gallery") graph.add_vertex(grand_gallery) graph.add_edge(grand_gallery,ante_chamber,2) graph.add_edge(grand_gallery,kings_room,2) treasure_room=Vertex("treasure room") graph.add_vertex(treasure_room) graph.add_edge(treasure_room,ante_chamber,6) graph.add_edge(treasure_room,grand_gallery,4) # ADD EDGES BETWEEN ROOMS BELOW... # DON'T CHANGE THIS CODE graph.print_map() return graph
def build_graph(): graph = Graph() # MAKE ROOMS INTO VERTICES BELOW... entrance = Vertex('entrance') ante_chamber = Vertex('ante-chamber') kings_room = Vertex('king\'s room') grand_gallery = Vertex('grand gallery') treasure_room = Vertex('treasure room') # ADD ROOMS TO GRAPH BELOW... graph.add_vertex(entrance) graph.add_vertex(ante_chamber) graph.add_vertex(kings_room) graph.add_vertex(grand_gallery) graph.add_vertex(treasure_room) # ADD EDGES BETWEEN ROOMS BELOW... graph.add_edge(entrance, ante_chamber, 7) graph.add_edge(entrance, kings_room, 3) graph.add_edge(kings_room, ante_chamber, 1) graph.add_edge(grand_gallery, ante_chamber, 2) graph.add_edge(grand_gallery, kings_room, 2) graph.add_edge(treasure_room, ante_chamber, 6) graph.add_edge(treasure_room, grand_gallery, 4) # DON'T CHANGE THIS CODE graph.print_map() return graph
def build_graph(): graph = Graph() #create rooms entrance = Vertex('entrance') ante_chamber = Vertex('ante-chamber') kings_room = Vertex('king\'s room') grand_gallery = Vertex('grand gallery') treasure_room = Vertex('treasure room') #add rooms to graph graph.add_vertex(entrance) graph.add_vertex(ante_chamber) graph.add_vertex(kings_room) graph.add_vertex(grand_gallery) graph.add_vertex(treasure_room) #add edges to vertices graph.add_edge(entrance, ante_chamber, 7) graph.add_edge(entrance, kings_room, 3) graph.add_edge(kings_room, ante_chamber, 1) graph.add_edge(grand_gallery, ante_chamber, 2) graph.add_edge(grand_gallery, kings_room, 2) graph.add_edge(treasure_room, ante_chamber, 6) graph.add_edge(treasure_room, grand_gallery, 4) # don't change graph.print_map() return graph
def load_graph(graph): in_file = open(graph, "r") # open graph, read location_dictionary = {} # create dictionary # read through lines for line in in_file: line = line.strip() information = line.split(";") adjacents = information[1].split(",") coordinates = information[2].split(",") vertex = Vertex(information[0], adjacents, coordinates[0], coordinates[1]) # create objects using parts of each line location_dictionary[vertex.name] = vertex # create it in dictionary with key in_file.close() # close # open and go through the lines to create a list of objects, adjacency, for every vertex in_file = open(graph, "r") for line in in_file: # create a list for every object adjacency_list = [] line = line.strip() information = line.split(";") vertex = location_dictionary[information[0]] # add each object searched to into a list, attach list to object, overwrite original adjacency list of strings for i in range(len(vertex.adjacency_list)): adjacency_list.append(location_dictionary[vertex.adjacency_list[i].strip()]) vertex.adjacency_list = adjacency_list # return the dictionary return location_dictionary
def build_graph(): graph = Graph() # MAKE ROOMS INTO VERTICES BELOW... entrance = Vertex("Entrance") ante_chamber = Vertex("Ante Chamber") kings_room = Vertex("King's Room") grand_gallery = Vertex("Grand Gallery") treasure_room = Vertex("Treasure Room") # ADD ROOMS TO GRAPH BELOW... graph.add_vertex(entrance) graph.add_vertex(ante_chamber) graph.add_vertex(kings_room) graph.add_vertex(grand_gallery) graph.add_vertex(treasure_room) # ADD EDGES BETWEEN ROOMS BELOW... graph.add_edge(entrance, ante_chamber, 7) graph.add_edge(entrance, kings_room, 3) graph.add_edge(ante_chamber, kings_room, 1) graph.add_edge(ante_chamber, grand_gallery, 2) graph.add_edge(ante_chamber, treasure_room, 6) graph.add_edge(kings_room, grand_gallery, 2) graph.add_edge(grand_gallery, treasure_room, 4) # DON'T CHANGE THIS CODE graph.print_map() return graph
def test(): a = Vertex('a') s = Vertex('s') c = Vertex('c') d = Vertex('d') b = Vertex('b') z = Vertex('z') x = Vertex('x') v = Vertex('v') f = Vertex('f') e = Vertex('e') # undirected graph G = Graph({ a: [s, z], z: [a], s: [a, x], x: [s, d, c], d: [x, c, f], c: [x, d, f, v], f: [d, c, v], v: [f, c] }) G.BFS(s) G.shortestpath(s, f) G.shortestpath(s, v) G.shortestpath(s, z) # directed graph G = Graph({a: [b, c], b: [d], c: [d, f], d: [e], e: [], f: []}) G.BFS(a) G.shortestpath(a, e) G.shortestpath(a, f) G.shortestpath(s, e)
def __init__(self): UnitDistanceGraph.__init__(self) P = RegularPentagon() S = UnitDistanceGraph() pentagon_angle = 0.6 * math.pi x = 1.4960521549993508 v0 = Vertex(0, 0) v1 = Vertex(1, 0) z_list = [] for i in range(5): z_list.append(v0.rotate(-x, center=v1)) v2 = v0.rotate(-pentagon_angle, center=v1) v0, v1 = v1, v2 for z in z_list: S.add_node(z) PG = P.union(S) PG = PG.reflection(0.5) self.graph = PG.graph self.update()
def build_graph(): graph = Graph() entrance = Vertex("entrance") graph.add_vertex(entrance) ante_chamber = Vertex("ante_chamber") graph.add_vertex(ante_chamber) kings_room = Vertex("king's room") graph.add_vertex(kings_room) graph.add_edge(entrance, ante_chamber, 7) graph.add_edge(entrance, kings_room, 3) graph.add_edge(kings_room, ante_chamber, 1) grand_gallery = Vertex("grand gallery") graph.add_vertex(grand_gallery) graph.add_edge(grand_gallery, ante_chamber, 2) graph.add_edge(grand_gallery, kings_room, 2) treasure_room = Vertex("treasure room") graph.add_vertex(treasure_room) graph.add_edge(treasure_room, ante_chamber, 6) graph.add_edge(treasure_room, grand_gallery, 4) graph.print_map() return graph
def build_graph(): graph = Graph() #Creating the rooms entrance = Vertex("entrance") ante_chamber = Vertex("ante-chamber") kings_room = Vertex("kings room") grand_gallery = Vertex("grand gallery") treasure_room = Vertex("treasure room") # Adding the rooms to the graph graph.add_vertex(entrance) graph.add_vertex(ante_chamber) graph.add_vertex(kings_room) graph.add_vertex(grand_gallery) graph.add_vertex(treasure_room) # Connecting the rooms graph.add_edge(entrance, ante_chamber, 7) graph.add_edge(entrance, kings_room, 3) graph.add_edge(kings_room, ante_chamber, 1) graph.add_edge(grand_gallery, ante_chamber, 2) graph.add_edge(grand_gallery, kings_room, 2) graph.add_edge(treasure_room, ante_chamber, 6) graph.add_edge(treasure_room, grand_gallery, 4) graph.print_map() return graph
def test_remove_vertex(self): g = Graph() v1 = Vertex(0) v2 = Vertex(1) v3 = Vertex(2) g.add_vertex(v1) g.add_vertex(v2) g.add_vertex(v3) self.assertFalse(g.is_empty()) vertices = g.get_vertices() num_vertices = 0 vertices.to_first() while vertices.has_access(): num_vertices += 1 vertices.next() self.assertEqual(num_vertices, 3) g.remove_vertex(v1) vertices = g.get_vertices() num_vertices = 0 vertices.to_first() while vertices.has_access(): num_vertices += 1 vertices.next() self.assertEqual(num_vertices, 2)
def build_graph(): graph = Graph() entrance = Vertex('entrance') ante_chamber = Vertex('ante-chamber') kings_room = Vertex("king's room") grand_gallery = Vertex('grand gallery') treasure_room = Vertex('treasure room') graph.add_vertex(entrance) graph.add_vertex(ante_chamber) graph.add_vertex(kings_room) graph.add_vertex(grand_gallery) graph.add_vertex(treasure_room) graph.add_edge(entrance, ante_chamber, 7) graph.add_edge(entrance, kings_room, 3) graph.add_edge(kings_room, ante_chamber, 1) graph.add_edge(kings_room, grand_gallery, 2) graph.add_edge(ante_chamber, grand_gallery, 2) graph.add_edge(treasure_room, ante_chamber, 6) graph.add_edge(treasure_room, grand_gallery, 4) graph.print_map() return graph
def load_graph(file_name="dartmouth_graph.txt"): """ :param file_name: input file name :return: dictionary containing all the vertex name as key with a vertex object as value """ data = [] # Dictionary that will contain all the vertices vertex_dict = {} with open(file_name) as file: # First pass, read the file line by line and add key and vertex object to the dictionary for line in file: data.append(line) name = str(line.split("; ")[0]) coordinates = line.split("; ")[2] x = int(coordinates.split(", ")[0]) y = int(coordinates.split(", ")[1]) new_vertex = Vertex() new_vertex.name = name new_vertex.x = x new_vertex.y = y new_vertex.adjacent_vertices = [] vertex_dict[name] = new_vertex for line in data: # Second pass, add vertex object to adjacency list name = str(line.split("; ")[0]) adjacent_string = line.split("; ")[1] adjacency_list = adjacent_string.split(", ") for vertex in adjacency_list: vertex_dict[name].adjacent_vertices.append(vertex_dict[vertex]) return vertex_dict
def build_mcis_graph(vlist, graph): # erstellt Graphen-Objekt aus Liste gematchter Knoten new_graph = Graph() neighbor_list = [] # speichert alle im new_graph benötigten edges for edge in graph.edges: neighbor_list.append("(" + edge.vertex_a.name + "," + edge.vertex_b.name + ")") # aus der Vlist(enthaelt strings) werden Vertex_objekt erstellt, durch abgleich mit Ursprungsgraphen for gv in range(0, len(graph.vertices)): if graph.vertices[gv].label is not None and graph.vertices[ gv].name in vlist: o_vertex = Vertex(name=graph.vertices[gv].name, label=graph.vertices[gv].label ) # TODO: Labels noch nicht getestet new_graph.add_vertex(o_vertex) elif graph.vertices[gv].label is None and graph.vertices[ gv].name in vlist: o_vertex = Vertex(name=graph.vertices[gv].name) new_graph.add_vertex(o_vertex) # Fuer jede Kombination aus Vertices aus New_graph wird durch Abgleich mit der neighbor_list getestet, ob eine # Kante erstellt werden soll. ACHTUNG: bisher nur ungerichteter Fall behandelt! for v1 in range(0, len(new_graph.vertices)): for v2 in range(1, len(new_graph.vertices)): if "("+new_graph.vertices[v1].name+","+new_graph.vertices[v2].name+")" in neighbor_list \ or "("+new_graph.vertices[v2].name+","+new_graph.vertices[v1].name+")" in neighbor_list: new_edge = Edge(new_graph.vertices[v1], new_graph.vertices[v2]) new_graph.add_edges(new_edge) return new_graph
def build_graph(): graph = Graph() # ROOMS INTO VERTICES entrance = Vertex("entrance") ante_chamber = Vertex("ante-chamber") kings_room = Vertex("king's room") grand_gallery = Vertex("grand gallery") treasure_room = Vertex("treasure room") # ROOMS TO GRAPH graph.add_vertex(entrance) graph.add_vertex(ante_chamber) graph.add_vertex(kings_room) graph.add_vertex(grand_gallery) graph.add_vertex(treasure_room) # EDGES BETWEEN ROOMS graph.add_edge(entrance, ante_chamber, 7) graph.add_edge(entrance, kings_room, 3) graph.add_edge(kings_room, ante_chamber, 1) graph.add_edge(ante_chamber, grand_gallery, 2) graph.add_edge(kings_room, grand_gallery, 2) graph.add_edge(treasure_room, ante_chamber, 6) graph.add_edge(treasure_room, grand_gallery, 4) graph.print_map() return graph
def vertex(self, substate): if substate not in self.vertices: vertex = Vertex(substate, self) self.vertices[substate] = vertex if self.start.includes(vertex.substate): vertex.initial = True vertex.set_reachable() return self.vertices[substate]
def get_vertex(self, label): """ Return the instance of the vertex with the label. @param label the label of the wanted vertex """ if Vertex(label) not in self.vertices: raise Exception("There is no vertex with this label") return self.vertices[self.vertices.index(Vertex(label))]
def main(args): V = [Vertex("A"), Vertex("B"), Vertex("C"), Vertex("D"), Vertex("E")] E = [Edge(9,V[0],V[1]), Edge(5,V[0],V[2]), Edge(10,V[0],V[4]), Edge(1,V[1],V[3]), Edge(11,V[2],V[3])] G = Graph(V, E) MST = kruskal(G) print "================= Original Graph ======================" print G print "================= MST ======================" print MST
def main(): # test pA = Vertex(2,1) pB = Vertex(2,2) e = Edge(pA,pB) e.either() ==pA.index e.other(1)==pB.index e.toString()
def crossProduct(self, other): self = self.normalize() other = other.normalize() return Vector( Vertex( (self.dest.y * other.dest.z) - (self.dest.z * other.dest.y), (self.dest.z * other.dest.x) - (self.dest.x * other.dest.z), (self.dest.x * other.dest.y) - (self.dest.y * other.dest.x)), Vertex(0, 0, 0, 1))
def load_graph(file1): graph = open(file1, "r") # Making the first pass. Looping over the lines in dartmouth_graph.txt for line in graph: # Stripping the lines and turning each line into a list, with elements separated by semicolons. line = line.strip() graph_list = line.split(";") # Since the x, y coordinates are stored as one element in graph_list, # I can split them up into a separate list by their separating comma. coordinate_list = graph_list[2].split(",") # Clearing up spaces coordinate_list[0] = coordinate_list[0].strip() coordinate_list[1] = coordinate_list[1].strip() # Creating the vertex object with the name, x, y coordinates and no adjacency list yet. vertex = Vertex(graph_list[0], coordinate_list[0], coordinate_list[1]) # Putting each new vertex object into the dictionary initialized above. dictionary[vertex.name] = vertex # Closing and reopening files in between looping over dartmouth_graph.txt graph.close() graph = open(file1, "r") # Making the second pass. for line in graph: # Repeating the process so I can access the names in order of lines in the file. line = line.strip() graph_list = line.split(";") # Grabbing the name of each vertex and creating a list of the vertexes adjacent to it. # (The adjacent vertices will be separated by commas in the second list item of graph_list) vertex_name = graph_list[0] adjacent_list = graph_list[1].split(",") # Getting the current vertex out of the dictionary. current_vertex = dictionary[vertex_name] # Looping over all of the adjacent vertices. for vertex in adjacent_list: # Removing spaces from the names, finding the adjacent vertices in the dictionary, and # adding them to the relevant adjacency list of the current vertex. vertex = vertex.strip() adjacent_vertex = dictionary[vertex] current_vertex.ad_list.append(adjacent_vertex) return dictionary
def post_node(json): node = Vertex("new param", True, -1) try: node.open_json(json) except TypeError: return "It was not parsed." graph.add_vertex(node) return node.node_id + " is parsed."
def cnf_trimming(self, cnfFile, dictFile): """ Given a filename, this trims the current graph using the CNF formula in 'cnf/cnfFile.cnf' It takes a dictFile as well, that must be located in cnf folder. """ vtoid = dict() idtov = dict() # Load dict file with open(os.path.join('cnf', dictFile), 'r') as f: for line in f: currLine = line.split() currLine = [ int(currLine[0]), float(currLine[1]), float(currLine[2]) ] idtov[currLine[0]] = Vertex(currLine[1], currLine[2]) vtoid[Vertex(currLine[1], currLine[2])] = currLine[0] n = len(vtoid) if n != self.n: raise Exception('Wrong file') vertices = [False] * n vertices = [None] + vertices with open(os.path.join('cnf', cnfFile), 'r') as f: for line in f: if line[0] == 'c': continue elif line[0] == 'p': maxColors = int(line.split()[2]) // n else: clause = line.split()[:-1] clause = [int(literal) for literal in clause] if len(clause) == 1: literal = int(fabs(clause[0] % n)) vertices[literal] = True elif len(clause) == maxColors: literal = clause[0] % n if literal == 0: literal = n vertices[literal] = True for v in list(self.graph.nodes): if not vertices[vtoid[v]]: self.remove_node(v) self.update()
def addEdge(self, label1: str, label2: str, weight: int): vertex: Vertex = Vertex(label2, weight) index: int = self.findIndexByLabel(label2) vertex.index = index self.adjacencyList[label1].append(vertex) vertex = Vertex(label1, weight) index: int = self.findIndexByLabel(label1) vertex.index = index self.adjacencyList[label2].append(vertex)
def generate_tree_function(function, path=[]): path_len = len(path) if path_len<self.n: v = Vertex(index=path_len+1) v.low = generate_tree_function(function, path+[False]) v.high = generate_tree_function(function, path+[True]) return v elif path_len==self.n: # reached leafes return Vertex(value=function(*path))
def test_get_edge_weight(self): v1 = Vertex(1) v2 = Vertex(2) v3 = Vertex(3) # Test default weight variable v2.add_neighbor(v1) assert v2.get_edge_weight(v1) == 1 # Test passed in weight variable v2.add_neighbor(v3, 3) assert v2.get_edge_weight(v3) == 3
def create_graph(): """creates a graph based off of user input.""" graph = [] name = input("Add an initial vertex name: ") v1 = Vertex(name) graph.append(v1) while input("Would you like to add another vertex? Y/N: ") == "Y": name = input("Add a vertex name: ") vn = Vertex(name) # vertex n adjacencies = input( "What existing vertices would you like this vertex to be connected to? Please enter their names separated only by a single space. " ) adjacencies = adjacencies.split( ) # this is now a list of adjacent vertex names for adjacency in adjacencies: a = Vertex(adjacency) vn.add_adjacency(a) a.add_adjacency(vn) graph.append(vn) return graph
def main(): display = Display(600, 400, "Software Renderer") stars = Star3D(1000, 64.0, 20.0) shape = RenderContext(display.get_target(), 600, 400) minYVert = Vertex(-1, -1, 0) midYVert = Vertex(0, 1, 0) maxYVert = Vertex(1, -1, 0) # projection matrix projection = Matrix4f().init_perspective(math.radians(70.0), display.get_aspect_ratio(), 0.1, 1000.0) rotCounter = 0.0 while display.is_running(): display.poll_events() # stars.update_and_render(display.get_target(), display.get_delta()) rotCounter += display.get_delta() translation = Matrix4f().init_translation(0.0, 0.0, 3.0) rotation = Matrix4f().init_rotation(0.0, rotCounter, 0.0) finalTransform = projection * translation * rotation # Clear screen to black display.get_target().fill((0, 0, 0)) # Draw shape shape.fill_triangle(midYVert.transform(finalTransform), maxYVert.transform(finalTransform), minYVert.transform(finalTransform)) display.render() display.clean_up()
def graphfunction3(): print "****************************Output for graph three********************************\n" f = open('input3.txt', 'r') node = [] connecting_node = [] for line in f: temp = line.split(" ") node.append(int(temp[0].strip())) connecting_node.append(int(temp[1].strip())) counter = 1 temp = [] nodeset = { 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 10: [] } while (counter <= 10): temp = [] for i in range(0, node.__len__()): if (node[i] == counter): temp.append(connecting_node[i]) nodeset[counter] = temp counter += 1 print 'Vertex Distance [Path]' implement_bfs(nodeset) print nodeset a = Vertex('1') b = Vertex('2') c = Vertex('3') d = Vertex('4') e = Vertex('5') f = Vertex('6') g = Vertex('7') h = Vertex('8') i = Vertex('9') j = Vertex('10') # directed graph in form of vertices for keeping track of discovery and finish time of a node. G = Graph( OrderedDict([(a, [h]), (b, [a, c, g]), (c, [b, f]), (d, [b]), (e, [f]), (f, []), (g, [c, h]), (h, [c, d, i]), (i, [f, h, j]), (j, [a, i])])) G.DFS() G.classifyedges() G.toposort() print "**********************************************************************************\n\n\n\n"
def __init__(self, x, y, length=20, outgoing_roads=[], incoming_roads=[], name=None): Vertex.__init__(self, incoming_edge_set=incoming_roads, outgoing_edge_set=outgoing_roads) self.x = float(x) self.y = float(y) # Only one car can be in an intersection at a time. self.in_intersection = threading.Semaphore(1) self.name = name
def main(): v = Vertex('v') w = Vertex('w') a = Vertex('a') e = Edge(v,w) e2 = Edge(w,v) g = Graph([v,w], [e]) g.add_edge(e2) print(g.verticies()) print(g.edges())
def generate_tree_values(values, level=0): if level<self.n: v = Vertex(index=level+1) v.low = generate_tree_values(values, level+1) v.high = generate_tree_values(values, level+1) return v elif level==self.n: # reached leafes v = Vertex(value=values[self._vcount]) self._vcount = self._vcount + 1 return v
def parsing (self,value): if 'vertices' in value: for i in value['vertices']: tmpVertex = Vertex() tmpVertex.parsing(i) self.verticesList.append(tmpVertex) if 'streets' in value: for i in value['streets']: tmpStreet = Street() tmpStreet.parsing(i) self.streetsList.append(tmpStreet) if 'bridges' in value: for i in value['bridges']: tmpBridge = Bridge() tmpBridge.parsing(i) self.bridgesList.append(tmpBridge) if 'weight' in value: self.weight.parsing(value['weight'])
def _apply(v1, v2, f): # Check if v1 and v2 have already been calculated key = str(v1.id) + ' ' + str(v2.id) if key in cache: return cache[key] # Result vertex u = Vertex() # If the vertices are both leafs, # apply the boolean function to them if v1.value!=None and v2.value!=None: u = leafs[f(v1.value, v2.value)] #u = Vertex(value=f(v1.value, v2.value)) cache[key] = u return u # v1.index < v2.index if v1.value==None and (v2.value!=None or v1.index<v2.index): u.index = v1.index u.low = _apply(v1.low, v2, f) u.high = _apply(v1.high, v2, f) # v1.index > v2.index elif v1.value!=None or v1.index>v2.index: u.index = v2.index u.low = _apply(v1, v2.low, f) u.high = _apply(v1, v2.high, f) # v1.index == v2.index else: u.index = v1.index u.low = _apply(v1.low, v2.low, f) u.high = _apply(v1.high, v2.high, f) #u.erase_children_redundancy() cache[key] = u return u
def create_initial_ring( surface, points, size ): vertex_ring = VertexRing( points ) midx, midy = surface.get_width()/2.0, surface.get_height()/2.0 radius = min( surface.get_width(), surface.get_height() )*0.4 th = 2.0*math.pi*random.randint( 0, 72 )/72.0 for i in range( 0, points ): a = 2.0*math.pi*i/points + th # b = Vertex() b.position = Cartesian( midx + radius*math.sin( a ), midy + radius*math.cos( a ) ) b.velocity = Cartesian( 0, 0 ) b.reset_acceleration() b.size = size vertex_ring.append( b ) return vertex_ring