def test_add_vertex(self): g = Graph() g.add_vertex('A') g.add_vertex('B') g.add_vertex('C') g.add_vertex('D') assert g.has_vertex('A') is True assert g.has_vertex('B') is True assert g.has_vertex('C') is True assert g.has_vertex('D') is True assert g.has_vertex('E') is False assert g.has_vertex('F') is False assert g.has_vertex('G') is False assert g.has_vertex('H') is False g.add_edge('A', 'B') g.add_edge('C', 'D') self.assertCountEqual(g.get_neighbors('A'), ['B']) self.assertCountEqual(g.get_neighbors('B'), []) self.assertCountEqual(g.get_neighbors('C'), ['D']) self.assertCountEqual(g.get_neighbors('D'), []) g.add_edge('A', 'F') g.add_edge('B', 'E') self.assertCountEqual(g.get_neighbors('A'), ['B', 'F']) self.assertCountEqual(g.get_neighbors('B'), ['E'])
def _generate_graph(self): """ This function generates a graph representing the airline network. :return :The graph representing the network. """ with open(self.routes_file, encoding="utf8") as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') g = Graph() for line in csv_reader: #decode srcfrom file src_airport_cord = line[3] dst_airport_cord = line[5] if src_airport_cord in self.cordinates and dst_airport_cord in self.cordinates: d = self._haversine(self.cordinates[src_airport_cord], self.cordinates[dst_airport_cord]) #add_edge(from_node, to_node, weight, stops, airline_code) g.add_edge(line[2], line[4], d, line[7], line[0]) #decode src from file # print(self.cordinates.get(self.source.lower())) # print(self.source) if self.cordinates.get(self.source.lower(), None) == line[3]: self.source_code = line[2] self.source_airline = line[0] #decode dest from file if self.cordinates.get(self.destination.lower(), None) == line[5]: self.destination_code = line[4] return g
def read_graph_from_file(file_name): '''Read graph from a file''' file = open(file_name, 'r') file_list = file.readlines() vertices = file_list[1].rstrip().split(',') valid_types = 'gGdD' graph_type = '' directed = False weighted = False edges_list = [] if file_list[0].rstrip() in valid_types: graph_type = file_list[0].upper() else: raise ValueError('G or D is not specified') if graph_type == 'D': directed = True for item in range(2, len(file_list)): edge = file_list[item].rstrip().replace('(', '').replace(')', '').split(',') if len(edge) == 3: weighted = True edges_list.append(edge) graph = Graph(weighted, directed) for edge in edges_list: if weighted: graph.add_weighted_edge(int(edge[0]), int(edge[1]), int(edge[2])) else: graph.add_edge(int(edge[0]), int(edge[1])) return graph
def test_has_vertex(self): g = Graph() assert g.has_vertex('A') is False g.add_vertex('B') assert g.has_vertex('B') is True g.add_edge('C', 'D') assert g.has_vertex('C') is True assert g.has_vertex('D') is True
def test_get_neighbors(self): g = Graph() g.add_edge('A', 'B') g.add_edge('C', 'D') g.add_edge('E', 'F') g.add_edge('G', 'H') self.assertCountEqual(g.get_neighbors('A'), ['B']) self.assertCountEqual(g.get_neighbors('B'), []) self.assertCountEqual(g.get_neighbors('C'), ['D']) self.assertCountEqual(g.get_neighbors('D'), []) with self.assertRaises(KeyError): g.get_neighbors('Z')
def build_graph(directed): g = Graph(directed) vertices = [] for val in ['a', 'b', 'c', 'd', 'e', 'f', 'g']: vertex = Vertex(val) vertices.append(vertex) g.add_vertex(vertex) for v in range(len(vertices)): v_idx = randrange(0, len(vertices) - 1) v1 = vertices[v_idx] v_idx = randrange(0, len(vertices) - 1) v2 = vertices[v_idx] g.add_edge(v1, v2, randrange(1, 10)) print_graph(g)
def test_size(self): g = Graph() assert g.size == 0 g.add_vertex('A') g.add_vertex('B') g.add_vertex('C') g.add_vertex('D') assert g.size == 4 g.add_edge('A', 'B') g.add_edge('C', 'D') g.add_edge('E', 'F') g.add_edge('G', 'H') assert g.size == 8 with self.assertRaises(KeyError): g.add_vertex('A') assert g.size == 8
x = [graph.vertices[vertex_id].x for vertex_id in graph.vertices] y = [graph.vertices[vertex_id].y for vertex_id in graph.vertices] graph_layout = dict(zip(node_indices, zip(x, y))) graph_renderer.layout_provider = StaticLayoutProvider(graph_layout=graph_layout) plot.renderers.append(graph_renderer) labelSource = ColumnDataSource(data=dict(x=x, y=y, names=[graph.vertices[vertex_id].value for vertex_id in graph.vertices])) labels = LabelSet(x='x', y='y', text='names', level='glyph', text_align='center', text_baseline='middle', source=labelSource, render_mode='canvas') plot.add_layout(labels) output_file('graph.html') show(plot) graph = Graph() # Instantiate your graph graph.add_vertex('0') graph.add_vertex('1') graph.add_vertex('2') graph.add_vertex('3') graph.add_edge('0', '1') graph.add_edge('0', '3') graph.add_edge('1', '2') smth = BokehGraph(graph) smth.draw()
[3, 3, 2, 1, 1] ] non_fullfilling = [[4, 3, 2, 2, 2, 1, 1], [6, 6, 5, 4, 4, 2, 1], [3, 3, 3, 1]] for sequence in fullfilling + non_fullfilling: print(sequence, Graph.erdoes_gallai(sequence)) print("Add vertex 'z':") graph.add_vertex("z") print(graph) print("Add edge ('x','y'): ") graph.add_edge(('x', 'y')) print(graph) print("Add edge ('a','d'): ") graph.add_edge(('a', 'd')) print(graph) ct[start_vertex]: if vertex not in vertices_encountered: if self.is_connected(vertices_encountered, vertex): return True else: return True return False def vertex_degree(self, vertex): """ The degree of a vertex is the number of edges connecting
class Test(unittest.TestCase): def setUp(self): self.graph = Graph() self.graph.add_vertex(1) self.graph.add_vertex(2) self.graph.add_vertex(3) self.graph.add_vertex(4) self.graph.add_vertex(5) self.graph.add_vertex(6) self.graph.add_vertex(7) self.graph.add_edge(5, 3) self.graph.add_edge(6, 3) self.graph.add_edge(7, 1) self.graph.add_edge(4, 7) self.graph.add_edge(1, 2) self.graph.add_edge(7, 6) self.graph.add_edge(2, 4) self.graph.add_edge(3, 5) self.graph.add_edge(2, 3) self.graph.add_edge(4, 6) def test_vertices(self): vertices = { 1: {2}, 2: {3, 4}, 3: {5}, 4: {6, 7}, 5: {3}, 6: {3}, 7: {1, 6} } self.assertDictEqual(self.graph.vertices, vertices) def test_bft(self): bft = [ "1\n2\n3\n4\n5\n6\n7\n", "1\n2\n3\n4\n5\n7\n6\n", "1\n2\n3\n4\n6\n7\n5\n", "1\n2\n3\n4\n6\n5\n7\n", "1\n2\n3\n4\n7\n6\n5\n", "1\n2\n3\n4\n7\n5\n6\n", "1\n2\n4\n3\n5\n6\n7\n", "1\n2\n4\n3\n5\n7\n6\n", "1\n2\n4\n3\n6\n7\n5\n", "1\n2\n4\n3\n6\n5\n7\n", "1\n2\n4\n3\n7\n6\n5\n", "1\n2\n4\n3\n7\n5\n6\n" ] stdout_ = sys.stdout sys.stdout = io.StringIO() self.graph.bft(1) output = sys.stdout.getvalue() self.assertIn(output, bft) sys.stdout = stdout_ # Restore stdout def test_dft(self): dft = [ "1\n2\n3\n5\n4\n6\n7\n", "1\n2\n3\n5\n4\n7\n6\n", "1\n2\n4\n7\n6\n3\n5\n", "1\n2\n4\n6\n3\n5\n7\n" ] stdout_ = sys.stdout sys.stdout = io.StringIO() self.graph.dft(1) output = sys.stdout.getvalue() self.assertIn(output, dft) sys.stdout = stdout_ # Restore stdout def test_dft_recursive(self): dft = [ "1\n2\n3\n5\n4\n6\n7\n", "1\n2\n3\n5\n4\n7\n6\n", "1\n2\n4\n7\n6\n3\n5\n", "1\n2\n4\n6\n3\n5\n7\n" ] stdout_ = sys.stdout sys.stdout = io.StringIO() self.graph.dft_recursive(1) output = sys.stdout.getvalue() self.assertIn(output, dft) sys.stdout = stdout_ # Restore stdout def test_bfs(self): bfs = [1, 2, 4, 6] self.assertListEqual(self.graph.bfs(1, 6), bfs) def test_dfs(self): dfs = [[1, 2, 4, 6], [1, 2, 4, 7, 6]] self.assertIn(self.graph.dfs(1, 6), dfs) def test_dfs_recursive(self): dfs = [[1, 2, 4, 6], [1, 2, 4, 7, 6]] self.assertIn(self.graph.dfs_recursive(1, 6), dfs)
def main(): try: with open(sys.argv[1], 'r') as tweets, open(sys.argv[2], 'w') as output: # make a pretty global dictionary to store time and hashtag info hashtag_dict = OrderedDict() result = '0.00' # iterate over the input file, one line at a time for line in tweets: tweet = line.decode('utf-8') tweet_json = json.loads(tweet) # dict object if 'created_at' in tweet_json: # needed to address keyError # get the time of the tweet created_at = datetime.strptime( tweet_json['created_at'].encode('utf-8'), "%a %b %d %H:%M:%S +0000 %Y") # get the time of the last tweet if len(hashtag_dict.keys()) == 0: time_last_tweet = created_at else: time_last_tweet = sorted(hashtag_dict.keys())[-1] # ensure to only address tweets not over 60 seconds older # than the last time_delta = created_at - time_last_tweet if time_delta.total_seconds() > - 60: # if 'entities' in tweet_json: if 'hashtags' in tweet_json['entities']: hashtags = tweet_json['entities']['hashtags'] hashtag_list = [i['text'].encode('utf-8').strip() for i in hashtags] # keep only unique tags hashtag_list = list(set(hashtag_list)) # update hashtag_dict with tweet of at least 2 tags if len(hashtag_list) > 1: hashtag_dict[created_at] = hashtag_list # for those with 0 or 1 tag, the result is the # same as in the last else: output.write(str(result) + '\n') continue else: output.write(str(result) + '\n') continue # ignore tweets over 60 seconds older than the last else: continue # remove the tweets more than 60 second older than the # current tweet sorted_key_list = sorted(hashtag_dict.keys()) for k in sorted_key_list: time_elapsed = created_at - k if time_elapsed.total_seconds() > 60: del hashtag_dict[k] else: break # finally, initialize the graph, and derive average degree graph = Graph() for t in hashtag_dict: for tag in hashtag_dict[t]: graph.add_vertex(tag) length = len(hashtag_dict[t]) for start in range(length - 1): for end in range(start+1, length): graph.add_edge( hashtag_dict[t][start], hashtag_dict[t][end]) result = average_degree_graph(graph) # ignore those lines without 'created_at' else: continue # for each valid line, report the result print result output.write(str(result) + '\n') else: print 'All done!' except IOError as err: print 'File error:', str(err)