def generate_grid_graph(self, nb_row, prob, directed=True): self.directed = directed self.bidirect = True self.generate_bloc_nodes(nb_row) for iv in range(nb_row): for ih in range(nb_row): ''' Check if there is a horizontal edge ''' if ih == 0 or ih == nb_row - 2: proba = prob * 2 else: proba = prob if random.random() < proba and ih < nb_row - 1: e = edge.Edge(self.nodes[ih + iv * nb_row], self.nodes[(ih + 1) + iv * nb_row]) self.edges.append(e) if directed: e = edge.Edge(self.nodes[(ih + 1) + iv * nb_row], self.nodes[ih + iv * nb_row]) self.edges.append(e) ''' Check if there is a vertical edge ''' if iv == 0 or iv == nb_row - 2: proba = prob * 2 else: proba = prob if random.random() < proba and iv < nb_row - 1: e = edge.Edge(self.nodes[ih + iv * nb_row], self.nodes[ih + (iv + 1) * nb_row]) self.edges.append(e) if directed: e = edge.Edge(self.nodes[ih + (iv + 1) * nb_row], self.nodes[ih + iv * nb_row]) self.edges.append(e) return
def test_edge_not_match_type(self): """ Unit test to check that edge match catches edge type not matching """ e1 = ed.Edge("O", "B") e2 = ed.Edge("P", "T") self.assertFalse(e1.matches(e2))
def test_edge_not_match_direction(self): """ Unit test to check that edge match catches edge direction not matching """ e1 = ed.Edge("O", "B") e2 = ed.Edge("O", "B") self.assertFalse(e1.matches(e2))
def test_edge_match(self): """ Unit test to check that edge match is correct """ e1 = ed.Edge("O", "B") e2 = ed.Edge("O", "T") self.assertTrue(e1.matches(e2))
def test_edge_neq(self): """ Unit test to check that edge match is correct """ e1 = ed.Edge("O", "B") e2 = ed.Edge("O", "T") self.assertFalse(e1 == e2)
def add_edge(self, v, w, weight): assert 0 <= v < self.__n assert 0 <= w < self.__n self.g[v].append(edge.Edge(v, w, weight)) if not self.__directed: self.g[w].append(edge.Edge(w, v, weight)) self.__m += 1
def generate_edges(self): for outer_nodes in self.nodes: for node in outer_nodes: if (not (node.x >= len(self.nodes) - 1)): self.edges.append( edge.Edge(node, self.nodes[node.x + 1][node.y])) if (not (node.y >= len(outer_nodes) - 1)): self.edges.append( edge.Edge(node, self.nodes[node.x][node.y + 1]))
def list_edges(self): """ Zwraca liste krawedzi wystepujacych w grafie. Krawedzie typu A-B i B-A nie sa dublowane """ L = [] for nodeA in self.graph: for nodeB in self.graph[nodeA]: if edge.Edge(nodeB, nodeA, self.graph[nodeB][nodeA]) not in L: L.append(edge.Edge(nodeA, nodeB, self.graph[nodeA][nodeB])) return L
def add_edge(self, v, w, weight): assert 0 <= v < self.__n assert 0 <= w < self.__n if self.has_edge(v, w): self.g[v][w] = None if not self.__directed: self.g[w][v] = None self.__m -= 1 self.g[v][w] = edge.Edge(v, w, weight) if not self.__directed: self.g[w][v] = edge.Edge(w, v, weight) self.__m += 1
def __init__(self, graph, s): self.__g = graph self.__s = s self.__dist_to = [0 for _ in range(graph.v())] self.__marked = [False for _ in range(graph.v())] self.__from = [None for _ in range(graph.v())] self.__ipq = index_min_heap.IndexMinHeap(graph.v()) self.__dist_to[self.__s] = 0 self.__marked[self.__s] = True self.__from[self.__s] = edge.Edge(self.__s, self.__s, 0) self.__ipq.insert(self.__s, self.__dist_to[self.__s]) while not self.__ipq.is_empty(): v = self.__ipq.extract_min_index() self.__marked[v] = True adj = self.__g.adjIterator(self.__g, v) e = adj.begin() while not adj.end(): w = e.other(v) if not self.__marked[w]: if(not self.__from[w] or self.__dist_to[v] + e.wt() < self.__dist_to[w]): self.__dist_to[w] = self.__dist_to[v] + e.wt() self.__from[w] = e if self.__ipq.contain(w): self.__ipq.change(w, self.__dist_to[w]) else: self.__ipq.insert(w, self.__dist_to[w]) e = adj.next_item()
def add_edge(self, source, destination, label=None, value=None): "Add a new edge to the graph" new_edge = edge.Edge(source, destination, label=None, value=None) if destination not in self.__adjacent_list[source]: # insert source if new_edge.get_source() not in self.__adjacent_list: self.__adjacent_list[new_edge.get_source()] = [] # insert destination if new_edge.get_destination() not in self.__adjacent_list: self.__adjacent_list[new_edge.get_destination()] = [] # insert edge and update adjacent list self.__edges[(new_edge.get_source(), new_edge.get_destination())] = new_edge self.__adjacent_list[new_edge.get_source()].append( new_edge.get_destination()) # if not directed.. do the same with the other node if not self.__directed: if source not in self.__adjacent_list[destination]: self.__edges[(new_edge.get_destination(), new_edge.get_source())] = new_edge self.__adjacent_list[new_edge.get_destination()].append( new_edge.get_source())
def create_sam_exons(self): """ Uses intron coordinates and transcript start/end to create exon objects for the transcript """ introns = self.intron_coords starts = [self.start] ends = [] # First, compute exon coordinates and put starts and ends in lists for i in range(0,len(introns)): if i % 2 == 0: # This is an intron start, i.e. an exon end. Subtract 1 to get # the exon base ends.append(introns[i] - 1) else: # This is an intron end, i.e. an exon start. Add 1 to get the # exon base starts.append(introns[i] + 1) ends.append(self.end) # Now iterate over start and end pairs and create exon objects ct = 1 for curr_start,curr_end in zip(starts,ends): exon_id = None if curr_start == curr_end: raise ValueError("Transcript " + self.identifier + \ "has exon of length zero.") exon = Edge.Edge(exon_id, self.chromosome, curr_start, curr_end, self.strand, None, None, {}) self.add_exon(exon) ct += 1 return
def test_edge_type_spec(self): """ Unit test to check that edge specification is parseable """ with self.assertRaises(ValueError): ed.Edge("Q", "T")
def process_stream(self, stream_file, output_1, output_2, output_3): with open(stream_file) as f: next(f) for line in f: tokens = self.tokenize(line) (time, src_id, des_id, amount, message) = tuple(tokens) src_node = node.Node(src_id) des_node = node.Node(des_id) transaction = edge.Edge(time, amount, message) is_level_1 = self.is_friend_trusted(src_node, des_node, level=1) is_level_2 = is_level_1 if is_level_1 else self.is_friend_trusted( src_node, des_node, level=2) is_level_4 = is_level_2 if is_level_2 else self.is_friend_trusted( src_node, des_node, level=4) if is_level_1: self.write_to_file(output_1, "trusted") else: self.write_to_file(output_1, "unverified") if is_level_2: self.write_to_file(output_2, "trusted") else: self.write_to_file(output_2, "unverified") if is_level_4: self.write_to_file(output_3, "trusted") else: self.write_to_file(output_3, "unverified") self.graph.add_friends(src_node, des_node) self.graph.add_transaction((src_node, des_node), transaction)
def addEdge(self, id, fromID, toID, prio, function, name): if id not in self._id2edge: fromN = self.addNode(fromID) toN = self.addNode(toID) e = edge.Edge(id, fromN, toN, prio, function, name) self._edges.append(e) self._id2edge[id] = e return self._id2edge[id]
def process_node(self, node, device): """ Sorts node based on it's type and starts command related to it. :param obj node node that should be sorted :param obj device the device from which the node originated, used for getting aditional information""" print("Adding device, Name: " + device.name + " Type: " + device.type) # Adding entries that are present for all nodes if (device.encrypted): node.add_emoji(emoji.emojize(":lock:")) else: node.add_emoji(emoji.emojize(":open_lock:")) # End of common entries if node.getType() == "luks/dm-crypt": self.nodeIsLuks(node) if node.getType() == "disk": self.nodeIsHarddrive(node) if (device.format.type == "disklabel"): node.addAttribute("format", device.format.labelType) if node.getType() == "partition": self.nodeIsPartition(node) if node.getType() == "lvmlv": self.nodeIsLV(node) if (device.cached): node.addAttribute("cached", "True") if node.getType() == "lvmvg": self.nodeIsVG(node) if node.getType() == "lvmthinpool": self.nodeIsLVMThinPool(node) if node.getType() == "lvmthinlv": self.nodeIsLVMThinLv(node) if (device.cached): node.addAttribute("cached", "True") if node.getType() == "btrfs volume": self.nodeIsBTRFS(node) if node.getType() == "mdarray": self.nodeIsMDRAID(node) if node.getType() == "lvmsnapshot": self.nodeIsLVMSnapshot(node) new_edge = edge.Edge(device.origin.name, node.getName()) new_edge.addGvAttribute("style", "dashed") self.edge_list.append(new_edge) node.addAttribute("Snap. origin", device.origin.name) self.node_list.append(node) for parent in device.parents: edge_to_be_added = edge.Edge(parent.name, device.name) self.edge_list.append(edge_to_be_added)
def generate_complete_graph(self, node_count): self.generate_nodes(node_count) self.edges = [] for ix1 in range(node_count): for ix2 in range(ix1 + 1, node_count): e = edge.Edge(self.nodes[ix1], self.nodes[ix2]) e.length = self.distance(self.nodes[ix1], self.nodes[ix2]) e.color = 'white' self.edges.append(e)
def generate_planar_graph(self, node_count, prob, directed=False): if directed: self.directed = True self.generate_nodes(node_count) self.edges = [] pair_dic = self.get_node_dist_dic() keys = pair_dic.keys() keys.sort() for key in keys: (ix1, ix2) = pair_dic[key] e = edge.Edge(self.nodes[ix1], self.nodes[ix2]) if not self.does_edge_intesect(e): if random.random() < prob: e.length = self.distance(self.nodes[ix1], self.nodes[ix2]) self.edges.append(e) if directed and random.random() < prob: e = edge.Edge(self.nodes[ix2], self.nodes[ix1]) e.length = self.distance(self.nodes[ix2], self.nodes[ix1]) self.edges.append(e)
def generate_geometric_graph(self, node_count, max_dist, directed=False): if directed: self.directed = True self.generate_nodes(node_count) self.edges = [] for ix1 in range(node_count): for ix2 in range(ix1 + 1, node_count): if self.distance(self.nodes[ix1], self.nodes[ix2]) < max_dist: e = edge.Edge(self.nodes[ix1], self.nodes[ix2]) e.length = self.distance(self.nodes[ix1], self.nodes[ix2]) self.edges.append(e)
def process_batch(self, batch_file): with open(batch_file) as f: next(f) for line in f: tokens = self.tokenize(line) (time, src_id, des_id, amount, message) = tuple(tokens) src_node = node.Node(src_id) des_node = node.Node(des_id) transaction = edge.Edge(time, amount, message) self.graph.add_friends(src_node, des_node) self.graph.add_transaction((src_node, des_node), transaction)
def create_sam_introns(self): introns = [] i = 0 while i < len(self.intron_coords): s = self.intron_coords[i] - 1 # adjust to vertex-based system e = self.intron_coords[i+1] + 1 # adjust to vertex-based system intron = Edge.Edge(None, self.chromosome, s, e, self.strand, None, None, {}) introns.append(intron) i += 2 self.introns = introns return
def test_get_edges(self): """ Unit test to check that edges are properly specified """ piece_spec = [["P", "T"], \ ["R", "B"], \ ["O", "B"], \ ["G", "T"]] piece = pc.Piece(piece_spec) edge = ed.Edge(piece_spec[3][0], piece_spec[3][1]) self.assertEqual(piece.get_side(3).edge_type, edge.edge_type) self.assertEqual(piece.get_side(3).edge_dirc, edge.edge_dirc)
def test_do_rotation(self): """ Unit test to check that rotation works properly """ piece_spec = [["P", "T"], \ ["R", "B"], \ ["O", "B"], \ ["G", "T"]] piece = pc.Piece(piece_spec) piece.rot_clockwise() edge = ed.Edge(piece_spec[3][0], piece_spec[3][1]) self.assertEqual(piece.get_side(0).edge_type, edge.edge_type) self.assertEqual(piece.get_side(0).edge_dirc, edge.edge_dirc)
def __init__(self, edge_spec_list): """ Holds ordered edges """ if len(edge_spec_list) != 4: raise (ValueError( "Did not specify 4 edges, insted specified {}".format( len(edge_spec_list)))) self.edge_list = [] self.rotation = 0 for ed_spec in edge_spec_list: if len(ed_spec) != 2: raise (ValueError( "Did not specify 2 edge params, instead specified{}". format(len(ed_spec)))) self.edge_list.append(edge.Edge(ed_spec[0], ed_spec[1]))
def filter_road_edge(edges, candidate_seg_id_px_list): """ filter edges whose vertices do not overlap with any candidate pixels :param edges: graph, list of edges at pixel level :param candidate_seg_id_px_list: candidate segments and the segment id to pixel mappings in the order of segment ids :param width: image width :return: filtered edges: edges whose vertices belong to the candidate pixel list """ candidate_pxs = [] for seg in candidate_seg_id_px_list: candidate_pxs += seg[1] candidate_pxs = set(candidate_pxs) edges_arr = np.empty((len(edges), 3), int) # convert list of class edges to array for i in range(0, len(edges)): _edge = edges[i] edges_arr[i][0] = _edge.a edges_arr[i][1] = _edge.b edges_arr[i][2] = _edge.w filtered_edges = [] cnt = 0 for px in candidate_pxs: # search in first column - edge.a idx = px == edges_arr[:, 0] # search other vertices of filtered edges in candidate_pxs filtered_a = edges_arr[idx] # t1 = timeit.default_timer() for _edge in filtered_a: cnt += 1 if _edge[1] in candidate_pxs: # both vertex of edge belong to candidate_pxs set filtered_edges.append(edge.Edge(_edge[0], _edge[1], _edge[2])) return filtered_edges
def add_edge(self, source, destination, label=None, value=None): """add a new connetion to the graph connects two vertex, if the graph is directed, this connection leaves the origin until the destination only. if the graph is not directed, the connection will be both the source to the destination as the destination to the source Args: source (Vertex): a source vertex destination (Vertex): a destination vertex label (stg, optional): Defaults to None. A label to this connection value (float, optional): Defaults to None. A value to this connection """ # create a new edge new_edge = edge.Edge(source, destination, label=label, value=value) # insert source if new_edge.get_source() not in self.__adjacent_list: self.__adjacent_list[new_edge.get_source()] = [] # insert destination if new_edge.get_destination() not in self.__adjacent_list: self.__adjacent_list[new_edge.get_destination()] = [] # test if the destination isn't connected with the source if destination not in self.__adjacent_list[source]: # insert edge and update adjacent list self.__edges[(new_edge.get_source(), new_edge.get_destination())] = new_edge self.__adjacent_list[new_edge.get_source()].append( new_edge.get_destination()) # if not directed.. do the same with the other node if not self.__directed: if source not in self.__adjacent_list[destination]: self.__edges[(new_edge.get_destination(), new_edge.get_source())] = new_edge self.__adjacent_list[new_edge.get_destination()].append( new_edge.get_source())
def __init__(self, graph, s): self.__g = graph self.__s = s self.__dist_to = [0 for _ in range(graph.v())] self.__from = [None for _ in range(graph.v())] self.__from[self.__s] = edge.Edge(self.__s, self.__s, 0) for _pass in range(1, self.__g.v()): for i in range(self.__g.v()): adj = self.__g.adjIterator(self.__g, i) e = adj.begin() while not adj.end(): if(not self.__from[e.w()] or self.__dist_to[e.v()] + e.wt() < self.__dist_to[e.w()]): self.__dist_to[e.w()] = self.__dist_to[e.v()] + e.wt() self.__from[e.w()] = e e = adj.next_item() self.__has_negative_cycle = self.__detect_negative_cycle()
def read_graph(self, filename): self.nodes = {} self.edges = [] f = open(filename, 'r') lines = f.readlines() f.close() flag = 0 ndIdx = 0 for line in lines: line = line.rstrip('\n\r') if line.startswith('DIRECTED'): self.directed = True continue if line.startswith('NODES'): flag = 1 continue if line.startswith('EDGES'): flag = 2 continue if flag == 0: continue segs = line.split(',') if len(segs) < 3: continue if flag == 1: self.nodes[int(segs[0])] = node.Node(float(segs[1]), float(segs[2])) self.nodes[int(segs[0])].idx = ndIdx ndIdx += 1 continue if flag == 2: e = edge.Edge(self.nodes[int(segs[0])], self.nodes[int(segs[1])]) e.length = float(segs[2]) if filename.find('complete') > -1: e.color = 'white' self.edges.append(e) return
def run_game(): """ 运行游戏 :return None: """ pygame.init() screen = pygame.display.set_mode(st.WindowSetting.size) pygame.display.set_caption(st.WindowSetting().game_tetle) my_snake = snake.Snake() my_edge = edge.Edge() my_apple = apple.Apple( (st.GameAreaSetting.width // 2, st.GameAreaSetting.hight // 2)) music.load(r"./bgm.aiff") music.play(loops=-1) while True: """游戏主循环""" begin_time = time.clock() for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT or event.key == pygame.K_d: my_snake.forward = my_snake.RIGHT elif event.key == pygame.K_LEFT or event.key == pygame.K_a: my_snake.forward = my_snake.LEFT elif event.key == pygame.K_UP or event.key == pygame.K_w: my_snake.forward = my_snake.UP elif event.key == pygame.K_DOWN or event.key == pygame.K_s: my_snake.forward = my_snake.DOWN if my_snake.is_dead(): time.sleep(0.5) sys.exit() if my_snake.is_get_apple(my_apple): my_snake.grow() while True: local = random.randint(0, st.GameAreaSetting.width - 1), random.randint( 0, st.GameAreaSetting.hight - 1) if local not in [item.local for item in my_snake.body]: break my_apple = apple.Apple(local) else: my_snake.move() screen.fill(st.GameAreaSetting.color) my_edge.draw(screen) my_apple.draw(screen) my_snake.draw(screen) pygame.display.flip() try: time.sleep(0.125 - time.clock() + begin_time) except ValueError: pass
def getInput(self): counterrorflag = False source = int(0) dest = int(0) pathlength = int self.edgelist.clear() if self.selectfilebutton.isChecked() or self.manualentrybutton.isChecked(): inputstring = self.manualdataentry.toPlainText() print(inputstring) #if statements below checks for proper input format if self.graphtype == 4 or self.graphtype == 3: datalist = [int(inputstring) for inputstring in re.findall(r'\d+',inputstring)] if (inputstring==""): counterrorflag = True self.rawresultstext.setPlainText("Error: Input Not Given") self.errordialog.showMessage("Error: Input Not Given") elif (len(datalist)%3 != 2): counterrorflag = True self.rawresultstext.setPlainText("Error: Incorrect Data Input: Enter as 0 [source] 4 [destination] ,0 1 2, 1 2 3 , 2 3 4 ... etc...") self.errordialog.showMessage("Error: Incorrect Data Input: Enter as 0 [source] 4 [destination] ,0 1 2, 1 2 3 , 2 3 4 ... etc...") else: source = datalist[0] dest = datalist[1] datalist = datalist[2 :] else: datalist = [int(inputstring) for inputstring in re.findall(r'\d+',inputstring)] if (inputstring==""): counterrorflag = True self.rawresultstext.setPlainText("Error: Input Not Given") self.errordialog.showMessage("Error: Input Not Given") elif (len(datalist)%3 != 0): counterrorflag = True self.rawresultstext.setPlainText("Error: Incorrect Data Input: Enter as 0 1 2, 1 2 3 , 2 3 4 ... etc...") self.errordialog.showMessage("Error: Incorrect Data Input: Enter as 0 1 2, 1 2 3 , 2 3 4 ... etc...") if counterrorflag is False: count = len(datalist) self.edgelist.clear() i = 0 ## if no counterror then proceed with building edgelist, which is passed to other classes while i < count: newedge = edge.Edge() newedge.Vertex1 = datalist[i] i+=1 newedge.Vertex2 = datalist[i] i+=1 newedge.weight = datalist[i] newedge.extra = 1 self.edgelist.append(newedge) i+=1 self.nodecount = self.countNodes() #if statements below run algorithms as needed depending on type if self.graphtype == 1: Prim.runPrim(self, self.edgelist, self.nodecount) if self.graphtype == 2: Kruskal.runKruskal(self, self.edgelist, self.nodecount) if self.graphtype == 3: pass #this algorithm is handled later in this class ##longest path is disabled (will be implemented by me) ##if self.graphtype == 4: ## LongestPath.runLongestPath(self, source, dest, self.edgelist, self.nodecount) if self.edgelist[0] == 99999: # check for no path error value self.rawresultstext.setPlainText("No path can be found from Source " + str(source) + " to Destination " + str(dest)) self.errordialog.showMessage("No path can be found from Source " + str(source) + " to Destination " + str(dest)) else: graph = nx.Graph() #for loop below adds edges to graph. for e in self.edgelist: if self.graphtype == 4: if e.extra == 1: graph.add_edge(e.Vertex1,e.Vertex2, weight = e.weight) else: graph.add_edge(e.Vertex1,e.Vertex2, weight = e.weight) #this if statement processes graph through nx.dijkstra if self.graphtype == 3: pathlist = nx.dijkstra_path(graph, source, dest) pathlength = nx.dijkstra_path_length(graph, source, dest) # for later display for x in range(0,len(pathlist)-1): for y in self.edgelist: if y.Vertex1 == pathlist[x] and y.Vertex2 == pathlist[x+1] or y.Vertex2 == pathlist[x] and y.Vertex1 == pathlist[x+1]: y.selected = True break selected = [] unselected = [] labels = dict([((u,v,),w['weight']) for u,v,w in graph.edges(data=True)]) if self.graphtype == 4: for x in self.edgelist: if x.selected: selected.append((x.Vertex1, x.Vertex2)) else: unselected.append((x.Vertex1, x.Vertex2)) else: for x in self.edgelist: if x.selected: selected.append((x.Vertex1, x.Vertex2)) else: unselected.append((x.Vertex1, x.Vertex2)) #begin drawing graph pos = nx.planar_layout(graph) if nx.is_connected(graph): pos = nx.spring_layout(graph) nx.draw_networkx_nodes(graph, pos, node_size = 200) nx.draw_networkx_edges(graph, pos, edgelist=selected, width=5) nx.draw_networkx_edges(graph, pos, edgelist=unselected, width=5, alpha=0.5, edge_color='b', style='dashed') nx.draw_networkx_labels(graph, pos, font_size=14, font_family='sans-serif') nx.draw_networkx_edge_labels(graph, pos, edge_labels=labels, font_size=10, font_family='sans-serif') plt.axis('off') #setting titles for graph depending on type if self.graphtype == 1 or self.graphtype == 2: plt.title("Minimum Spanning Tree/Forest") if self.graphtype == 3: plt.title("Shortest path length from node " +str(source) + " to " + str(dest) + " is: " +str(pathlength)) if self.graphtype == 4: plt.title("Longest path length from node " +str(source) + " to " + str(dest) + " shown below") figure = plt.savefig('figure.png', bbox_inches = 'tight', dpi= 150) path = "figure.png" #used to store graph image graphimage = QtGui.QImage(path) graphimagepix= QtGui.QPixmap.fromImage(graphimage) self.label.setPixmap(graphimagepix) self.label.resize(graphimage.width(),graphimage.height()) plt.close(figure) message = [] for m in self.edgelist: message.append(str(m.Vertex1) + " " +str(m.Vertex2)+ " "+ str(m.weight)+ " Sel: "+ str(m.selected) + " ") message2 = " ".join(message) self.rawresultstext.setPlainText(message2)