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 test_get_vertices(self):
        g = Graph()

        g.add_vertex('A')
        g.add_vertex('B')
        g.add_vertex('C')
        g.add_vertex('D')

        self.assertCountEqual(g.get_vertices(), ['A', 'B', 'C', 'D'])
    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
示例#4
0
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
示例#6
0
        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()
示例#7
0
fullfilling = [
    [2, 2, 2, 2, 1, 1],
    [3, 3, 3, 3, 3, 3],
    [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
示例#8
0
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)