Beispiel #1
0
def test():
    import math

    # Make Matplotlib use a Cairo backend
    import matplotlib
    matplotlib.use("cairo")
    import matplotlib.pyplot as pyplot

    # Create the figure
    fig = pyplot.figure()

    # Create a basic plot
    axes = fig.add_subplot(111)
    xs = range(200)
    ys = [math.sin(x/10.) for x in xs]
    axes.plot(xs, ys)

    # Draw the graph over the plot
    # Two points to note here:
    # 1) we add the graph to the axes, not to the figure. This is because
    #    the axes are always drawn on top of everything in a matplotlib
    #    figure, and we want the graph to be on top of the axes.
    # 2) we set the z-order of the graph to infinity to ensure that it is
    #    drawn above all the curves drawn by the axes object itself.
    graph = Graph.GRG(100, 0.2)
    graph_artist = GraphArtist(graph, (10, 10, 150, 150), layout="kk")
    graph_artist.set_zorder(float('inf'))
    axes.artists.append(graph_artist)

    # Save the figure
    fig.savefig("test.pdf")

    print ("Plot saved to test.pdf")
Beispiel #2
0
 def testRandomWalkUndirected(self):
     g = Graph.GRG(100, 0.2)
     for i in xrange(100):
         start = random.randint(0, g.vcount()-1)
         length = random.randint(0, 10)
         walk = g.random_walk(start, length)
         self.validate_walk(g, walk, start, length)
Beispiel #3
0
 def testIsDAG(self):
     g = Graph(5, [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3)], directed=True)
     self.assertTrue(g.is_dag())
     g.to_undirected()
     self.assertFalse(g.is_dag())
     g = Graph.Barabasi(1000, 2, directed=True)
     self.assertTrue(g.is_dag())
     g = Graph.GRG(100, 0.2)
     self.assertFalse(g.is_dag())
     g = Graph.Ring(10, directed=True, mutual=False)
     self.assertFalse(g.is_dag())
def generate_GRG_DiseaseGraph(n, p):
    igraph = Graph.GRG(n, p)
    if not igraph.is_connected():
        igraph = igraph.clusters().giant()
        print(
            "Warning: generated graph not connected. Using largest subcomponent of size:",
            len(igraph.vs()))

    dgraph = DiseaseGraph(igraph)
    dgraph.setAllSusceptible()

    return dgraph
Beispiel #5
0
def demo_epidemic():
    from igraph import Graph, Layout
    from random import sample, random

    # Specify the simulation parameters
    initial_outbreak_size = 3
    spread_probability = 0.05
    recovery_probability = 0.1

    # Set up the mapping from vertex states to colors
    colormap = dict(S="white", I="red", R="green")

    # Generate the graph
    graph, xs, ys = Graph.GRG(100, 0.2, return_coordinates=True)
    layout = Layout(zip(xs, ys))

    # Set up the initial state of the individuals
    graph.vs["state"] = ["S"] * graph.vcount()
    for vertex in sample(graph.vs, initial_outbreak_size):
        vertex["state"] = "I"
    graph.vs["size"] = [20] * graph.vcount()

    # Set up the video encoder
    encoder = MEncoderVideoEncoder(bbox=(600, 600), fps=5)

    # Generate frames in the animation one by one
    with encoder.encode_to("demo_epidemic.avi"):
        # Run the simulation until hell freezes over
        while True:
            # Create the plot and add to the encoder
            colors = [colormap[state] for state in graph.vs["state"]]
            encoder.add(graph,
                        layout=layout,
                        vertex_color=colors,
                        vertex_label=graph.vs["state"],
                        margin=20)
            # First, the infected individuals try to infect their neighbors
            infected = graph.vs.select(state="I")
            for vertex in infected:
                for idx in graph.neighbors(vertex.index):
                    if graph.vs[idx]["state"] == "S" and random(
                    ) < spread_probability:
                        graph.vs[idx]["state"] = "I"
            # Second, the infected individuals try to recover
            for vertex in infected:
                if random() < recovery_probability:
                    vertex["state"] = "R"
            # Okay, are there any infected people left?
            if not infected:
                break
 def testLabelPropagation(self):
     # Nothing to test there really, since the algorithm
     # is pretty nondeterministic. We just do a quick smoke
     # test.
     g = Graph.GRG(100, 0.2)
     cl = g.community_label_propagation()
     g = Graph([(0, 1), (1, 2), (2, 3)])
     g.es["weight"] = [2, 1, 2]
     g.vs["initial"] = [0, -1, -1, 1]
     cl = g.community_label_propagation("weight", "initial", [1, 0, 0, 1])
     self.assertMembershipsEqual(cl, [0, 0, 1, 1])
     cl = g.community_label_propagation(initial="initial",
                                        fixed=[1, 0, 0, 1])
     self.assertTrue(cl.membership == [0, 0, 1, 1]
                     or cl.membership == [0, 1, 1, 1]
                     or cl.membership == [0, 0, 0, 1])
    def testMaximumCardinalitySearch(self):
        g = Graph()
        alpha, alpham1 = g.maximum_cardinality_search()
        self.assertListEqual([], alpha)
        self.assertListEqual([], alpham1)

        g = Graph.Famous("petersen")
        alpha, alpham1 = g.maximum_cardinality_search()

        print(repr(alpha), repr(alpham1))
        self.assert_valid_maximum_cardinality_search_result(g, alpha, alpham1)

        g = Graph.GRG(100, 0.2)
        alpha, alpham1 = g.maximum_cardinality_search()

        self.assert_valid_maximum_cardinality_search_result(g, alpha, alpham1)
    def testAuto(self):
        def layout_test(graph, test_with_dims=(2, 3)):
            lo = graph.layout("auto")
            self.assertTrue(isinstance(lo, Layout))
            self.assertEqual(len(lo[0]), 2)
            for dim in test_with_dims:
                lo = graph.layout("auto", dim=dim)
                self.assertTrue(isinstance(lo, Layout))
                self.assertEqual(len(lo[0]), dim)
            return lo

        g = Graph.Barabasi(10)
        layout_test(g)

        g = Graph.GRG(101, 0.2)
        del g.vs["x"]
        del g.vs["y"]
        layout_test(g)

        g = Graph.Full(10) * 2
        layout_test(g)

        g["layout"] = "graphopt"
        layout_test(g, test_with_dims=())

        g.vs["x"] = list(range(20))
        g.vs["y"] = list(range(20, 40))
        layout_test(g, test_with_dims=())

        del g["layout"]
        lo = layout_test(g, test_with_dims=(2,))
        self.assertEqual(
            [tuple(item) for item in lo],
            list(zip(list(range(20)), list(range(20, 40)))),
        )

        g.vs["z"] = list(range(40, 60))
        lo = layout_test(g)
        self.assertEqual(
            [tuple(item) for item in lo],
            list(zip(list(range(20)), list(range(20, 40)), list(range(40, 60)))),
        )
Beispiel #9
0
def demo_layout():
    from igraph import Graph

    # Generate graph and find the communities
    graph = Graph.GRG(100, 0.2)
    clusters = graph.community_spinglass()

    # Specify initial layout
    layout = None

    # Set up the video encoder
    encoder = MEncoderVideoEncoder(bbox=(600, 600), fps=30)
    encoder.lavcopts = "vcodec=mpeg4:mbd=2:vbitrate=1600:trell:keyint=30"

    # Generate frames in the animation one by one
    with encoder.encode_to("demo_layout.avi"):
        for i in xrange(500):
            # Run one step of the layout algorithm
            layout = graph.layout("graphopt", niter=1, seed=layout)
            # Add the clustering to the encoder
            encoder.add(clusters, layout=layout, mark_groups=True, margin=20)
Beispiel #10
0
from igraph import Graph

####################
# To see installed modules:
help("modules")

# full graph:
# g = Graph.Full(3)

# GenerateRandomGraph:
g = Graph.GRG(50, .3)

# writes a svg file:
g.write_svg("helloGraph.svg", "auto", 300, 300)

# write_svg(self, fname, layout='auto', width=None, height=None,
# labels = 'label', colors = 'color', shapes = 'shape', vertex_size = 10,
# edge_colors = 'color', font_size = 16, *args, **kwds)
Beispiel #11
0
        raise argparse.ArgumentTypeError(
            'Program will take too long to run if s>300')
    return s


parser.add_argument('-n',
                    '--number_of_graphs',
                    metavar='number',
                    type=int,
                    default=100,
                    help='Number of graphs in file')
parser.add_argument('-s',
                    '--size_of_graph',
                    metavar='size',
                    type=SType,
                    default=40,
                    help='the size of each and every graph')
args = parser.parse_args()
print(args.number_of_graphs, args.size_of_graph)

for i in range(args.number_of_graphs):
    g = Graph.GRG(args.size_of_graph, random.random() * 0.7 + 0.15)
    print(write(g), end='')

for i, v in dic.items():
    print('# %2d: %d' % (i, v))
'''

g = Graph.GRG(10,0.5)
print(str(g.vs()))'''
Beispiel #12
0
"""
Given the number of nodes and edges, generated a graph with random edges.

Will also provide a random initial coloring of the nodes up to M colors. Pass
in M as 0 to set all nodes as uncolored.

Usage:
python generate_graph.py num_nodes num_edges num_colors
"""
import sys
from igraph import Graph

num_nodes = int(sys.argv[1])

graph = Graph.GRG(num_nodes, 0.5)

# Print the resulting graph to stdout
print(num_nodes, len(graph.get_edgelist()))
for edge in graph.get_edgelist():
    print(f"{edge[0] + 1} {edge[1] + 1}")

for i in range(num_nodes):
    print(0, end=" ")
 def testCohesiveBlockingErrors(self):
     g = Graph.GRG(100, 0.2)
     g.to_directed()
     self.assertRaises(InternalError, g.cohesive_blocks)
Beispiel #14
0
from igraph import Graph, Plot
from igraph.drawing.text import TextDrawer
import cairo

# Construct the plot
plot = Plot("plot.png", bbox=(600, 650), background="white")

# Create the graph and add it to the plot
g = Graph.GRG(100, 0.2)
plot.add(g, bbox=(20, 70, 580, 630))

# Make the plot draw itself on the Cairo surface
plot.redraw()

# Grab the surface, construct a drawing context and a TextDrawer
ctx = cairo.Context(plot.surface)
ctx.set_font_size(36)
drawer = TextDrawer(ctx, "Test title", halign=TextDrawer.CENTER)
drawer.draw_at(0, 40, width=600)

# Save the plot
plot.save()
def random_graph(nodes=20):
    return Graph.GRG(nodes, 0.5)
Beispiel #16
0
def test():
    g = Graph.GRG(100, 0.2)

    ### Adding network attributes
    g["name"] = "Network name"
    g["version"] = 5
    g["obsolete"] = False
    g["density"] = g.density()

    ### Adding vertex attributes
    # String attribute
    g.vs["name"] = ["Node %d" % (i + 1) for i in xrange(g.vcount())]
    # Integer attribute
    g.vs["degree"] = g.degree()
    # Float attribute
    g.vs["pagerank"] = g.pagerank()
    # Boolean attribute
    g.vs["even"] = [i % 2 for i in xrange(g.vcount())]
    # Mixed attribute
    g.vs["mixed"] = ["abc", 123, None, 1.0] * ((g.vcount() + 3) / 4)
    # Special attribute with Hungarian accents
    g.vs[0]["name"] = u"árvíztűrő tükörfúrógép ÁRVÍZTŰRŐ TÜKÖRFÚRÓGÉP"

    ### Adding edge attributes
    # String attribute
    g.es["name"] = ["Edge %d -- %d" % edge.tuple for edge in g.es]
    # Integer attribute
    g.es["multiplicity"] = g.count_multiple()
    # Float attribute
    g.es["betweenness"] = g.edge_betweenness()
    # Boolean attribute
    g.es["even"] = [i % 2 for i in xrange(g.ecount())]
    # Mixed attribute
    g.es["mixed"] = [u"yay", 123, None, 0.7] * ((g.ecount() + 3) / 4)

    # Sending graph
    drawer = CytoscapeGraphDrawer()
    drawer.draw(g, layout="fr")

    # Fetching graph
    g2 = drawer.fetch()
    del g2.vs["hiddenLabel"]
    del g2.es["interaction"]

    # Check isomorphism
    result = g2.isomorphic(g)
    if not result:
        raise ValueError("g2 not isomorphic to g")

    # Check the graph attributes
    if set(g.attributes()) != set(g2.attributes()):
        raise ValueError("Graph attribute name set mismatch")
    for attr_name in g.attributes():
        if g[attr_name] != g2[attr_name]:
            raise ValueError("Graph attribute mismatch for %r" % attr_name)

    # Check the vertex attribute names
    if set(g.vertex_attributes()) != set(g2.vertex_attributes()):
        raise ValueError("Vertex attribute name set mismatch")

    # Check the edge attribute names
    if set(g.edge_attributes()) != set(g2.edge_attributes()):
        raise ValueError("Edge attribute name set mismatch")