Ejemplo n.º 1
0
def test_encode_decode_adj():
    ######## code test ###########
    G = nx.ladder_graph(5)
    G = nx.grid_2d_graph(20, 20)
    G = nx.ladder_graph(200)
    G = nx.karate_club_graph()
    G = nx.connected_caveman_graph(2, 3)
    print(G.number_of_nodes())

    adj = np.asarray(nx.to_numpy_matrix(G))
    G = nx.from_numpy_matrix(adj)
    #
    start_idx = np.random.randint(adj.shape[0])
    x_idx = np.array(bfs_seq(G, start_idx))
    adj = adj[np.ix_(x_idx, x_idx)]

    print("adj\n", adj)
    adj_output = encode_adj(adj, max_prev_node=5)
    print("adj_output\n", adj_output)
    adj_recover = decode_adj(adj_output, max_prev_node=5)
    print("adj_recover\n", adj_recover)
    print("error\n", np.amin(adj_recover - adj), np.amax(adj_recover - adj))

    adj_output = encode_adj_flexible(adj)
    for i in range(len(adj_output)):
        print(len(adj_output[i]))
    adj_recover = decode_adj_flexible(adj_output)
    print(adj_recover)
    print(np.amin(adj_recover - adj), np.amax(adj_recover - adj))
Ejemplo n.º 2
0
def classic_graphs():
    print("Balanced Tree")
    BG = nx.balanced_tree(3, 2)
    draw_graph(BG)
    print("Barbell Graph")
    BBG = nx.barbell_graph(3, 2)
    draw_graph(BBG)
    print("Complete Graph")
    CG = nx.complete_graph(10)
    draw_graph(CG)
    print("Complete Multipartite Graph")
    CMG = nx.complete_multipartite_graph(1, 2, 10)
    print([CMG.node[u]['block'] for u in CMG])
    print(CMG.edges(0))
    print(CMG.edges(2))
    print(CMG.edges(4))
    draw_graph(CMG)
    print("Circular Ladder Graph")
    CLG = nx.circular_ladder_graph(5)
    draw_graph(CLG)
    print("Dorogovtsev Goltsev Mendes Graph")
    DGMG = nx.dorogovtsev_goltsev_mendes_graph(3)
    draw_graph(DGMG)
    print("Empty Graph")
    EG = nx.empty_graph(5, create_using=nx.DiGraph())
    draw_graph(EG)
    print("Grid 2D Graph")
    G2DG = nx.grid_2d_graph(5, 6)
    draw_graph(G2DG)
    print("Grid Graph")
    GDG = nx.grid_graph(dim=[5, 2])
    draw_graph(GDG)
    print("Hypercube Graph")
    HG = nx.hypercube_graph(3)
    draw_graph(HG)
    print("Ladder Graph")
    LG = nx.ladder_graph(8)
    draw_graph(LG)
    print("Ladder Graph")
    LG = nx.ladder_graph(8)
    draw_graph(LG)
    print("Lollipop Graph")
    LPG = nx.lollipop_graph(n=6, m=4)
    draw_graph(LPG)
    print("Null Graph")
    NG = nx.null_graph()
    draw_graph(NG)
    print("Path Graph")
    PG = nx.path_graph(16)
    draw_graph(PG)
    print("Star Graph")
    SG = nx.star_graph(16)
    draw_graph(SG)
    print("Trivial Graph")
    TG = nx.trivial_graph()
    draw_graph(TG)
    print("Wheel Graph")
    WG = nx.wheel_graph(n=18)
    draw_graph(WG)
Ejemplo n.º 3
0
    def test_ladder_graph(self):
        for i, G in [(0, nx.empty_graph(0)), (1, nx.path_graph(2)),
                     (2, nx.hypercube_graph(2)), (10, nx.grid_graph([2, 10]))]:
            assert is_isomorphic(nx.ladder_graph(i), G)

        pytest.raises(nx.NetworkXError,
                      nx.ladder_graph,
                      2,
                      create_using=nx.DiGraph)

        g = nx.ladder_graph(2)
        mg = nx.ladder_graph(2, create_using=nx.MultiGraph)
        assert_edges_equal(mg.edges(), g.edges())
def main():
    args = parse_arguments()
    # Generate graph for given parameters

    if args.cycle:
        graph = networkx.cycle_graph(args.vertices)
        graph = networkx.path_graph(args.vertices)
    elif args.star:
        graph = networkx.star_graph(args.vertices)
    elif args.wheel:
        graph = networkx.wheel_graph(args.vertices)
    elif args.ladder:
        graph = networkx.ladder_graph(args.vertices)
    elif args.fill_rate:
        if args.fill_rate > 50.0:
            graph = networkx.gnp_random_graph(args.vertices, args.fill_rate / 100.0, None, args.directed)
        else:
            graph = networkx.fast_gnp_random_graph(args.vertices, args.fill_rate / 100.0, None, args.directed)
    else:
        graph = networkx.gnm_random_graph(args.vertices, args.edges, None, args.directed)

    # Print generated graph
    print("{} {}".format(graph.number_of_nodes(), graph.number_of_edges()))
    for edge in graph.edges():
        print("{} {}".format(edge[0] + 1, edge[1] + 1))

    # Export generated graph to .png
    if args.image_path:
        export_to_png(graph, args.image_path)
Ejemplo n.º 5
0
 def test_3_ladder(self):
     """Test fault-tolerance of a complete ladder graph n=3"""
     stack_roots = {i: 1 for i in range(self.NUM_DPS // 2)}
     dp_links = FaucetTopoGenerator.dp_links_networkx_graph(
         networkx.ladder_graph(self.NUM_DPS // 2))
     self.set_up(self.NUM_DPS, self.NUM_VLANS, dp_links, stack_roots)
     self.network_function()
Ejemplo n.º 6
0
class GraphType:
    BALANCED_TREE = ('Balanced tree', _balanced_tree)
    BARBELL = ('Barbell', lambda n: nx.barbell_graph(int(n*.4), int(n*.3)))
    CIRCULAR_LADDER = ('Circular ladder', lambda n: nx.circular_ladder_graph(int(n/2)))
    COMPLETE = ('Complete', lambda n: nx.complete_graph(int(n)))
    COMPLETE_BIPARTITE = ('Complete bipartite',
                          lambda n: nx.complete_bipartite_graph(int(n*.6), int(n*.4)))
    CYCLE = ('Cycle', lambda n: nx.cycle_graph(int(n)))
    GRID = ('Grid', lambda n: nx.grid_graph([int(np.sqrt(n))]*2))
    HYPERCUBE = ('Hypercube', _hypercube)
    LADDER = ('Ladder', lambda n: nx.ladder_graph(int(n/2)))
    LOBSTER = ('Lobster', lambda n: nx.random_lobster(int(n / (1 + .7 + .7*.5)), .7, .5))
    LOLLIPOP = ('Lollipop', lambda n: nx.lollipop_graph(int(n/2), int(n/2)))
    PATH = ('Path', lambda n: nx.path_graph(int(n)))
    REGULAR = ('Regular', lambda n: nx.random_regular_graph(np.random.randint(10)*2, n))
    SCALEFREE = ('Scale-free', lambda n: nx.scale_free_graph(int(n)))
    SHELL = ('Shell', lambda n: nx.random_shell_graph([(int(n*.1), int(n*.1), .2),
                                                       (int(n*.3), int(n*.3), .8),
                                                       (int(n*.6), int(n*.6), .5)]))
    STAR = ('Star', lambda n: nx.star_graph(int(n - 1)))
    WAXMAN = ('Waxman', lambda n: nx.waxman_graph(int(n)))
    WHEEL = ('Wheel', lambda n: nx.wheel_graph(int(n)))

    all = (BALANCED_TREE, BARBELL, CIRCULAR_LADDER, COMPLETE, COMPLETE_BIPARTITE,
           CYCLE, GRID, HYPERCUBE, LADDER, LOBSTER, LOLLIPOP, PATH, REGULAR,
           SCALEFREE, SHELL, STAR, WAXMAN, WHEEL)
Ejemplo n.º 7
0
    def generate_topology(self, topo_type, node_count, branches = None):
        if topo_type == TopologyType.LADDER:
            total_nodes = node_count/2
            graph = networkx.ladder_graph(total_nodes)

        elif topo_type == TopologyType.LINEAR:
            graph = networkx.path_graph(node_count)

        elif topo_type == TopologyType.MESH:
            graph = networkx.complete_graph(node_count)

        elif topo_type == TopologyType.TREE:
            h = math.log(node_count + 1)/math.log(2) - 1
            graph = networkx.balanced_tree(2, h)

        elif topo_type == TopologyType.STAR:
            graph = networkx.Graph()
            graph.add_node(0)

            nodesinbranch = (node_count - 1)/ BRANCHES
            c = 1

            for i in xrange(BRANCHES):
                prev = 0
                for n in xrange(1, nodesinbranch + 1):
                    graph.add_node(c)
                    graph.add_edge(prev, c)
                    prev = c
                    c += 1

        return graph
Ejemplo n.º 8
0
    def generate_topology(self, topo_type, node_count, branches=None):
        if topo_type == TopologyType.LADDER:
            total_nodes = node_count / 2
            graph = networkx.ladder_graph(total_nodes)

        elif topo_type == TopologyType.LINEAR:
            graph = networkx.path_graph(node_count)

        elif topo_type == TopologyType.MESH:
            graph = networkx.complete_graph(node_count)

        elif topo_type == TopologyType.TREE:
            h = math.log(node_count + 1) / math.log(2) - 1
            graph = networkx.balanced_tree(2, h)

        elif topo_type == TopologyType.STAR:
            graph = networkx.Graph()
            graph.add_node(0)

            nodesinbranch = (node_count - 1) / BRANCHES
            c = 1

            for i in xrange(BRANCHES):
                prev = 0
                for n in xrange(1, nodesinbranch + 1):
                    graph.add_node(c)
                    graph.add_edge(prev, c)
                    prev = c
                    c += 1

        return graph
Ejemplo n.º 9
0
def ladder(N):
    """ Creates a ladder graph of N nodes: two rows of N/2 nodes, with each pair connected by a single edge.
        In case N is odd another node is attached to the first one. """
    G = nx.ladder_graph(N // 2)
    if N % 2 != 0:
        G.add_node(N - 1)
        G.add_edge(0, N - 1)
    return G
Ejemplo n.º 10
0
def generate_ladder_graph(
    length_of_ladder: int,
    weight_sampler: Sampler = constant_sampler(1.0),
    seed: Optional[int] = None,
) -> nx.Graph:
    graph = nx.ladder_graph(length_of_ladder)
    _weight_graph_edges(graph, weight_sampler, seed)
    return graph
Ejemplo n.º 11
0
def generate_struct_mask(struct, n_nodes, shuffle_nodes):
    # a horrible collection of ifs due to args in nx constructors
    if struct == "star":
        g = nx.star_graph(n_nodes)
    elif struct == "random_tree":
        g = nx.random_tree(n_nodes)
    elif struct == "powerlaw_tree":
        g = nx.powerlaw_tree(n_nodes, gamma=3, seed=None)
    elif struct == "binary_tree":
        raise NotImplementedError("Implement a binary tree.")
    elif struct == "path":
        g = nx.path_graph(n_nodes)
    elif struct == "cycle":
        g = nx.cycle_graph(n_nodes)
    elif struct == "ladder":
        g = nx.ladder_graph(n_nodes)
    elif struct == "grid":
        m = np.random.choice(range(1, n_nodes+1))
        n = n_nodes // m
        g = nx.grid_2d_graph(m, n)
    elif struct == "circ_ladder":
        g = nx.circular_ladder_graph(n_nodes)
    elif struct == "barbell":
        assert n_nodes >= 4
        m = np.random.choice(range(2, n_nodes-1))
        blocks = (m, n_nodes-m)
        g = nx.barbell_graph(*blocks)
    elif struct == "loll":
        assert n_nodes >= 2
        m = np.random.choice(range(2, n_nodes+1))
        g = nx.lollipop_graph(m, n_nodes-m)
    elif struct == "wheel":
        g = nx.wheel_graph(n_nodes)
    elif struct == "bipart":
        m = np.random.choice(range(n_nodes))
        blocks = (m, n_nodes-m)
        g = nx.complete_multipartite_graph(*blocks)
    elif struct == "tripart":
        # allowed to be zero
        m, M = np.random.choice(range(n_nodes), size=2)
        if m > M:
            m, M = M, m
        blocks = (m, M-m, n_nodes-M)
        g = nx.complete_multipartite_graph(*blocks)
    elif struct == "fc":
        g = nx.complete_graph(n_nodes)
    else:
        raise NotImplementedError("Structure {} not implemented yet.".format(struct))

    node_order = list(range(n_nodes))
    if shuffle_nodes:
        np.random.shuffle(node_order)

    # a weird subclass by default; raises a deprecation warning
    # with a new update of networkx, this should be updated to
    # nx.convert_matrix.to_numpy_array
    np_arr_g = nx.to_numpy_matrix(g, nodelist=node_order)
    return np_arr_g.astype(int)
Ejemplo n.º 12
0
def mock_get_local_network():
    """Return a mock neighborhood of the specified word."""
    word = flask.request.args.get('word')
    if word is None:
        return

    response_graph = nx.ladder_graph(random.randint(0, 22))
    response = nx.readwrite.json_graph.node_link_data(response_graph)
    return flask.jsonify(response)
Ejemplo n.º 13
0
def create_graph(topology, info):
    if topology == 'simple':
        return nx.barabasi_albert_graph(info['num_nodes'], info['avg_degree'])
    elif topology == 'star':
        return nx.star_graph(info['num_nodes'])
    elif topology == 'tree':
        return nx.random_tree(info['num_nodes'])
    elif topology == 'ladder':
        return nx.ladder_graph(round(info['num_nodes'] / 2))
    else:
        print("Invalid network style received. Aborting...")
        exit(1)
Ejemplo n.º 14
0
def main():
    global paths
    print("test heuristic!")
    for AppGraph1 in [
            nx.complete_graph(400),
            nx.ladder_graph(4),
            nx.complete_graph(4),
    ]:
        for Substrate in [
                nx.ladder_graph(4),
                nx.complete_graph(4),
                nx.complete_graph(300)
        ]:
            AppGraph2 = nx.ladder_graph(4)
            for v in AppGraph1.nodes():
                AppGraph1.node[v]['weight'] = 2
            for e in AppGraph1.edges():
                AppGraph1[e[0]][e[1]]['weight'] = 2
            AppGraph1.node[0]['weight'] = 3
            for v in AppGraph2.nodes():
                AppGraph2.node[v]['weight'] = 2
            for e in AppGraph2.edges():
                AppGraph2[e[0]][e[1]]['weight'] = 2
            AppGraph2.node[0]['weight'] = 3
            for v in Substrate.nodes():
                Substrate.node[v]['weight'] = 4
                Substrate.node[v]['free'] = 4
            for e in Substrate.edges():
                Substrate[e[0]][e[1]]['weight'] = 4
                Substrate[e[0]][e[1]]['free'] = 4
            gba = GreedyBorderAllocationForFogModel(None, None)
            result = gba.greedyBorderAllocation([AppGraph1, AppGraph2],
                                                Substrate, {})
            if result != None and not gba.feasibility(AppGraph1, Substrate,
                                                      result):
                print("problem")
            print("try next")
    print("done")
Ejemplo n.º 15
0
def create_graph(topology, info):
    """Create a graph depending on the information in the
    info struct provided.
    """
    if topology == 'simple':
        return nx.barabasi_albert_graph(info['num_nodes'], info['avg_degree'])
    elif topology == 'star':
        return nx.star_graph(info['num_nodes'])
    elif topology == 'tree':
        return nx.random_tree(info['num_nodes'])
    elif topology == 'ladder':
        return nx.ladder_graph(int(round(info['num_nodes'] / 2)))
    else:
        print("Invalid network style received. Aborting...")
        exit(1)
Ejemplo n.º 16
0
def LadderGraph(n):
    """
    Returns a ladder graph with 2\*n nodes.

    A ladder graph is a basic structure that is typically displayed as
    a ladder, i.e.: two parallel path graphs connected at each
    corresponding node pair.

    This constructor depends on NetworkX numeric labels.

    PLOTTING: Upon construction, the position dictionary is filled to
    override the spring-layout algorithm. By convention, each ladder
    graph will be displayed horizontally, with the first n nodes
    displayed left to right on the top horizontal line.

    EXAMPLES: Construct and show a ladder graph with 14 nodes

    ::

        sage: g = graphs.LadderGraph(7)
        sage: g.show() # long time

    Create several ladder graphs in a Sage graphics array

    ::

        sage: g = []
        sage: j = []
        sage: for i in range(9):
        ....:     k = graphs.LadderGraph(i+2)
        ....:     g.append(k)
        sage: for i in range(3):
        ....:     n = []
        ....:     for m in range(3):
        ....:         n.append(g[3*i + m].plot(vertex_size=50, vertex_labels=False))
        ....:     j.append(n)
        sage: G = sage.plot.graphics.GraphicsArray(j)
        sage: G.show() # long time
    """
    pos_dict = {}
    for i in range(n):
        pos_dict[i] = (i, 1)
    for i in range(n, 2 * n):
        x = i - n
        pos_dict[i] = (x, 0)
    import networkx
    G = networkx.ladder_graph(n)
    return graph.Graph(G, pos=pos_dict, name="Ladder graph")
Ejemplo n.º 17
0
def LadderGraph(n):
    """
    Returns a ladder graph with 2\*n nodes.

    A ladder graph is a basic structure that is typically displayed as
    a ladder, i.e.: two parallel path graphs connected at each
    corresponding node pair.

    This constructor depends on NetworkX numeric labels.

    PLOTTING: Upon construction, the position dictionary is filled to
    override the spring-layout algorithm. By convention, each ladder
    graph will be displayed horizontally, with the first n nodes
    displayed left to right on the top horizontal line.

    EXAMPLES: Construct and show a ladder graph with 14 nodes

    ::

        sage: g = graphs.LadderGraph(7)
        sage: g.show() # long time

    Create several ladder graphs in a Sage graphics array

    ::

        sage: g = []
        sage: j = []
        sage: for i in range(9):
        ....:     k = graphs.LadderGraph(i+2)
        ....:     g.append(k)
        sage: for i in range(3):
        ....:     n = []
        ....:     for m in range(3):
        ....:         n.append(g[3*i + m].plot(vertex_size=50, vertex_labels=False))
        ....:     j.append(n)
        sage: G = sage.plot.graphics.GraphicsArray(j)
        sage: G.show() # long time
    """
    pos_dict = {}
    for i in range(n):
        pos_dict[i] = (i,1)
    for i in range(n,2*n):
        x = i - n
        pos_dict[i] = (x,0)
    import networkx
    G = networkx.ladder_graph(n)
    return graph.Graph(G, pos=pos_dict, name="Ladder graph")
def make_graph(g_name, n):
    switcher = {
        "path": nx.path_graph(n),
        "complete": nx.complete_graph(n),
        "binomial tree": nx.binomial_tree(n),
        "circular ladder": nx.circular_ladder_graph(n),
        "cycle": nx.cycle_graph(n),
        "dorogovtsev": nx.dorogovtsev_goltsev_mendes_graph(n),
        "ladder": nx.ladder_graph(n),
        "star": nx.star_graph(n),
        "wheel": nx.wheel_graph(n),
        "margulis gabber galil": nx.margulis_gabber_galil_graph(n),
        "chordal cycle": nx.chordal_cycle_graph(n),
        "hypercube": nx.hypercube_graph(n),
        "mycielski": nx.mycielski_graph(n)
        }
    return switcher.get(g_name)
Ejemplo n.º 19
0
 def test_complete_to_chordal_graph(self):
     fgrg = nx.fast_gnp_random_graph
     test_graphs = [
         nx.barbell_graph(6, 2),
         nx.cycle_graph(15),
         nx.wheel_graph(20),
         nx.grid_graph([10, 4]),
         nx.ladder_graph(15),
         nx.star_graph(5),
         nx.bull_graph(),
         fgrg(20, 0.3, seed=1),
     ]
     for G in test_graphs:
         H, a = nx.complete_to_chordal_graph(G)
         assert nx.is_chordal(H)
         assert len(a) == H.number_of_nodes()
         if nx.is_chordal(G):
             assert G.number_of_edges() == H.number_of_edges()
             assert set(a.values()) == {0}
         else:
             assert len(set(a.values())) == H.number_of_nodes()
Ejemplo n.º 20
0
def ___test_for_special_graphs(graphs, size):
    cycle = nx.cycle_graph(size)
    path = nx.path_graph(size)
    star = nx.star_graph(size)
    cycl_ladder = nx.circular_ladder_graph(size)
    ladder = nx.ladder_graph(size)
    wheel = nx.wheel_graph(size)

    cycle_found = False
    path_found = False
    star_found = False
    cycl_ladder_found = False
    ladder_found = False
    wheel_found = False

    # Check if we sampled on of this special graphs
    for g in graphs:
        if nx.is_isomorphic(g, cycle):
            cycle_found = True
        if nx.is_isomorphic(g, path):
            path_found = True
        if nx.is_isomorphic(g, star):
            star_found = True
        if nx.is_isomorphic(g, cycl_ladder):
            cycl_ladder_found = True
        if nx.is_isomorphic(g, ladder):
            ladder_found = True
        if nx.is_isomorphic(g, wheel):
            wheel_found = True

    print("Sampled cycle............................{}".format(cycle_found))
    print("Sampled path.............................{}".format(path_found))
    print("Sampled star.............................{}".format(star_found))
    print("Sampled circular ladder..................{}".format(
        cycl_ladder_found))
    print("Sampled ladder...........................{}".format(ladder_found))
    print("Sampled wheel............................{}".format(wheel_found))

    passed = cycle_found and path_found and star_found and cycl_ladder_found and ladder_found and wheel_found
    return passed
 def test010_ladder_graph(self):
     """ Large ladder graph. """
     g = nx.ladder_graph(1000)
     mate1 = mv.max_cardinality_matching( g )
     mate2 = nx.max_weight_matching( g, True )
     self.assertEqual( len(mate1), len(mate2) )
Ejemplo n.º 22
0
G3T=0
mu=10
sigma=2.5
#Orden logaritmico
for logarithmOrder in range(3,5):
    print('Orden: ',logarithmOrder)
    log = 2**logarithmOrder
    ban=True
    # 3 Metodos de generación distintos
    G1 = nx.lollipop_graph(log, 2)
    for e in G1.edges():
        G1[e[0]][e[1]]['capacity'] = np.random.normal(mu, sigma)
    G2 = nx.turan_graph(log, 2)
    for e in G2.edges():
        G2[e[0]][e[1]]['capacity'] = np.random.normal(mu, sigma)
    G3 = nx.ladder_graph(log)
    for e in G3.edges():
        G3[e[0]][e[1]]['capacity'] = np.random.normal(mu, sigma)
    for newPair in range(5):
        print('Pareja: ',newPair)
        #10 Grafos
        for graphRepetition in range(10):
            if ban:
                ban=False
                while G1T==G1S:
                    G1S = choice(list(G1.nodes()))
                    G1T = choice(list(G1.nodes()))
                while G2T==G2S:
                    G2S = choice(list(G2.nodes()))
                    G2T = choice(list(G2.nodes()))
                while G3T==G3S:
Ejemplo n.º 23
0
def generate_ladder_graph(length_of_ladder: int,
                          random_weights: bool = False,
                          seed: Optional[int] = None) -> nx.Graph:
    output_graph = nx.ladder_graph(length_of_ladder)
    output_graph = weight_graph_edges(output_graph, random_weights, seed)
    return output_graph
G = nx.complete_graph(50)   # this will create a completely connected graph with 50 nodes


# %%
# plot the graph
nx.draw(G)


# %%
# for demo purpose we plot a few other network types
fig, ax = plt.subplots(3, 4, figsize=(15,12))
G = nx.scale_free_graph(50)
nx.draw(nx.complete_graph(50), ax=ax[0,0])
nx.draw(nx.star_graph(50), ax=ax[0,1])
nx.draw(nx.circular_ladder_graph(50), ax=ax[0,2])
nx.draw(nx.ladder_graph(50), ax=ax[0,3])

nx.draw(nx.path_graph(50), ax=ax[1,0])
nx.draw(nx.wheel_graph(50), ax=ax[1,1])
nx.draw(nx.erdos_renyi_graph(50, 0.3), ax=ax[1,2])
nx.draw(nx.barabasi_albert_graph(50, 5), ax=ax[1,3])

nx.draw(nx.random_powerlaw_tree(10), ax=ax[2,0])
nx.draw(nx.scale_free_graph(50), ax=ax[2,1])
nx.draw(nx.karate_club_graph(), ax=ax[2,2])
nx.draw(nx.les_miserables_graph(), ax=ax[2,3])


# %% [markdown]
# ## Network Statistics 
# Calculate basic network statistics
Ejemplo n.º 25
0
def create(args):
### load datasets
    graphs=[]
    # synthetic graphs
    if args.graph_type=='ladder':
        graphs = []
        for i in range(100, 201):
            graphs.append(nx.ladder_graph(i))
        args.max_prev_node = 10
    elif args.graph_type=='ladder_small':
        graphs = []
        for i in range(2, 11):
            graphs.append(nx.ladder_graph(i))
        args.max_prev_node = 10
    elif args.graph_type=='tree':
        graphs = []
        for i in range(2,5):
            for j in range(3,5):
                graphs.append(nx.balanced_tree(i,j))
        args.max_prev_node = 256
    elif args.graph_type=='caveman':
        # graphs = []
        # for i in range(5,10):
        #     for j in range(5,25):
        #         for k in range(5):
        #             graphs.append(nx.relaxed_caveman_graph(i, j, p=0.1))
        graphs = []
        for i in range(2, 3):
            for j in range(30, 81):
                for k in range(10):
                    graphs.append(caveman_special(i,j, p_edge=0.3))
        args.max_prev_node = 100
    elif args.graph_type=='caveman_small':
        # graphs = []
        # for i in range(2,5):
        #     for j in range(2,6):
        #         for k in range(10):
        #             graphs.append(nx.relaxed_caveman_graph(i, j, p=0.1))
        graphs = []
        for i in range(2, 3):
            for j in range(6, 11):
                for k in range(20):
                    graphs.append(caveman_special(i, j, p_edge=0.8)) # default 0.8
        args.max_prev_node = 20
    elif args.graph_type=='caveman_small_single':
        # graphs = []
        # for i in range(2,5):
        #     for j in range(2,6):
        #         for k in range(10):
        #             graphs.append(nx.relaxed_caveman_graph(i, j, p=0.1))
        graphs = []
        for i in range(2, 3):
            for j in range(8, 9):
                for k in range(100):
                    graphs.append(caveman_special(i, j, p_edge=0.5))
        args.max_prev_node = 20
    elif args.graph_type.startswith('community'):
        num_communities = int(args.graph_type[-1])
        print('Creating dataset with ', num_communities, ' communities')
        c_sizes = np.random.choice([12, 13, 14, 15, 16, 17], num_communities)
        #c_sizes = [15] * num_communities
        for k in range(3000):
            graphs.append(n_community(c_sizes, p_inter=0.01))
        args.max_prev_node = 80
    elif args.graph_type=='grid':
        graphs = []
        for i in range(10,20):
            for j in range(10,20):
                graphs.append(nx.grid_2d_graph(i,j))
        args.max_prev_node = 40
    elif args.graph_type=='grid_small':
        graphs = []
        for i in range(2,5):
            for j in range(2,6):
                graphs.append(nx.grid_2d_graph(i,j))
        args.max_prev_node = 15
    elif args.graph_type=='barabasi':
        graphs = []
        for i in range(100,200):
             for j in range(4,5):
                 for k in range(5):
                    graphs.append(nx.barabasi_albert_graph(i,j))
        args.max_prev_node = 130
    elif args.graph_type=='barabasi_small':
        graphs = []
        for i in range(4,21):
             for j in range(3,4):
                 for k in range(10):
                    graphs.append(nx.barabasi_albert_graph(i,j))
        args.max_prev_node = 20
    elif args.graph_type=='grid_big':
        graphs = []
        for i in range(36, 46):
            for j in range(36, 46):
                graphs.append(nx.grid_2d_graph(i, j))
        args.max_prev_node = 90

    elif 'barabasi_noise' in args.graph_type:
        graphs = []
        for i in range(100,101):
            for j in range(4,5):
                for k in range(500):
                    graphs.append(nx.barabasi_albert_graph(i,j))
        graphs = perturb_new(graphs,p=args.noise/10.0)
        args.max_prev_node = 99

    # real graphs
    elif args.graph_type == 'enzymes':
        graphs= Graph_load_batch(min_num_nodes=10, name='ENZYMES')
        args.max_prev_node = 25
    elif args.graph_type == 'enzymes_small':
        graphs_raw = Graph_load_batch(min_num_nodes=10, name='ENZYMES')
        graphs = []
        for G in graphs_raw:
            if G.number_of_nodes()<=20:
                graphs.append(G)
        args.max_prev_node = 15
    elif args.graph_type == 'protein':
        graphs = Graph_load_batch(min_num_nodes=20, name='PROTEINS_full')
        args.max_prev_node = 80
    elif args.graph_type == 'DD':
        graphs = Graph_load_batch(min_num_nodes=100, max_num_nodes=500, name='DD',node_attributes=False,graph_labels=True)
        args.max_prev_node = 230
    elif args.graph_type == 'citeseer':
        _, _, G = Graph_load(dataset='citeseer')
        G = max(nx.connected_component_subgraphs(G), key=len)
        G = nx.convert_node_labels_to_integers(G)
        graphs = []
        for i in range(G.number_of_nodes()):
            G_ego = nx.ego_graph(G, i, radius=3)
            if G_ego.number_of_nodes() >= 50 and (G_ego.number_of_nodes() <= 400):
                graphs.append(G_ego)
        args.max_prev_node = 250
    elif args.graph_type == 'citeseer_small':
        _, _, G = Graph_load(dataset='citeseer')
        G = max(nx.connected_component_subgraphs(G), key=len)
        G = nx.convert_node_labels_to_integers(G)
        graphs = []
        for i in range(G.number_of_nodes()):
            G_ego = nx.ego_graph(G, i, radius=1)
            if (G_ego.number_of_nodes() >= 4) and (G_ego.number_of_nodes() <= 20):
                graphs.append(G_ego)
        shuffle(graphs)
        graphs = graphs[0:200]
        args.max_prev_node = 15

    return graphs
Ejemplo n.º 26
0
def test_graph(graph):
    """
    Tests that the sampling method obtains correct counts for the path graph,
    wheel graph, and ladder graph (see networkx documentation for graph
    details). Large scale test that gives a basic sanity check of the whole sampling class.
    """
    if graph == "path":
        path_graph = nx.path_graph(5)
        lift_unordered = lt.Lift(path_graph, 3, lift_type="unordered")
        graphlet_counts = lift_unordered.get_graphlet_count(
            num_steps=NUM_STEPS)
        assert graphlet_counts["wedge"] == 3
        assert graphlet_counts["triangle"] == 0
        lift_unordered = lt.Lift(path_graph, 2, lift_type="unordered")
        graphlet_counts = lift_unordered.get_graphlet_count(
            num_steps=NUM_STEPS)
        assert graphlet_counts["2-path"] == 4

        print("Path graph passed.")
    elif graph == "wheel":
        wheel_graph = nx.wheel_graph(6) # this is a 6-cycle with a star center node
        lift_unordered = lt.Lift(wheel_graph, 3, lift_type="unordered")
        graphlet_counts = lift_unordered.get_graphlet_count(
            num_steps=NUM_STEPS)
        assert graphlet_counts["wedge"] == 10
        assert graphlet_counts["triangle"] == 5
        lift_unordered = lt.Lift(wheel_graph, 2, lift_type="unordered")
        graphlet_counts = lift_unordered.get_graphlet_count(
            num_steps=NUM_STEPS)
        assert graphlet_counts["2-path"] == 10
        print("Wheel graph passed.")
    elif graph == "ladder":
        ladder_graph = nx.ladder_graph(4) # this is two 6-paths joined one to one
        lift_unordered = lt.Lift(ladder_graph, 3, lift_type="unordered")
        graphlet_counts = lift_unordered.get_graphlet_count(
            num_steps=NUM_STEPS)
        assert graphlet_counts["wedge"] == 16
        assert graphlet_counts["triangle"] == 0
        lift_unordered = lt.Lift(ladder_graph, 2, lift_type="unordered")
        graphlet_counts = lift_unordered.get_graphlet_count(
            num_steps=NUM_STEPS)
        assert graphlet_counts["2-path"] == 10
        print("Ladder graph passed.")
    elif graph == "bio-celegansneural":
        graphlet_counts = run_test("bio-celegansneural", 3)
        actual_triangle_count = 12.6 * 10**3 / 3
        assert ((graphlet_counts["triangle"] - actual_triangle_count)
                / actual_triangle_count < THRESHOLD)
        print(graph + " passed.")
        print(graphlet_counts, "\n")
    elif graph == "ia-email-univ":
        graphlet_counts = run_test("ia-email-univ", 3)
        actual_triangle_count = 16000 / 3
        assert ((graphlet_counts["triangle"] - actual_triangle_count)
                / actual_triangle_count < THRESHOLD)
        print(graph + " passed.")
        print(graphlet_counts, "\n")
    elif graph == "misc-fullb":
        graphlet_counts = run_test("misc-fullb", 3)
        actual_triangle_count = 180.6 * 10**6 / 3
        assert ((graphlet_counts["triangle"] - actual_triangle_count)
                / actual_triangle_count < THRESHOLD)
        print(graph + " passed.")
        print(graphlet_counts, "\n")
    elif graph == "misc-polblogs":
        graphlet_counts = run_test("misc-polblogs", 3)
        actual_triangle_count = 459.4 * 10**3 / 3
        assert ((graphlet_counts["triangle"] - actual_triangle_count)
                / actual_triangle_count < THRESHOLD)
        print(graph + " passed.")
        print(graphlet_counts, "\n")
    else:
        print("Graph unknown.")
def generate_ladder_graphs(min_size: int = 100, max_size: int = 201):
    return [nx.ladder_graph(i) for i in range(min_size, max_size)]
Ejemplo n.º 28
0
def generate_ladder(n):
    graph_nx = nx.ladder_graph(n)
    return from_nx_to_torch(graph_nx)
Ejemplo n.º 29
0
n = 6
hypercube_n = 4
m = 6
r = 2
h = 3
dim = [2, 3]

# left out dorogovtsev_goltsev_mendes_graph and null_graph

graphs = [
    ("balanced_tree", nx.balanced_tree(r, h)),
    ("barbell_graph", nx.barbell_graph(n, m)),
    ("complete_graph", nx.complete_graph(n)),
    ("complete_bipartite_graph", nx.complete_bipartite_graph(n, m)),
    ("circular_ladder_graph", nx.circular_ladder_graph(n)),
    ("cycle_graph", nx.cycle_graph(n)),
    ("empty_graph", nx.empty_graph(n)),
    ("grid_2d_graph", nx.grid_2d_graph(m, n)),
    ("grid_graph", nx.grid_graph(dim)),
    ("hypercube_graph", nx.hypercube_graph(hypercube_n)),
    ("ladder_graph", nx.ladder_graph(n)),
    ("lollipop_graph", nx.lollipop_graph(m, n)),
    ("path_graph", nx.path_graph(n)),
    ("star_graph", nx.star_graph(n)),
    ("trivial_graph", nx.trivial_graph()),
    ("wheel_graph", nx.wheel_graph(n)),
]

plot_multigraph(graphs, 4, 4, node_size=50)
plt.savefig("graphs/classic.png")
Ejemplo n.º 30
0
def gen_laplacian(data_num=DATA_NUM, opt=27, cache=False):
    label = None

    if cache:
        print('Loading cached graph')
        graph = pk.load(open('tmp/g.pk', 'rb'))
    else:
        print('Generating graph opt {}'.format(opt))

        if 1 == opt:
            graph = gen_rand_graph(data_num=data_num)
        if 2 == opt:
            top_num = random.randint(1, data_num)
            bottom_num = data_num - top_num
            graph = nx.bipartite.random_graph(top_num, bottom_num, 0.9)
            label = [d['bipartite'] for n, d in graph.nodes(data=True)]
        elif 3 == opt:
            graph = nx.balanced_tree(4, 5)
        elif 4 == opt:
            graph = nx.complete_graph(data_num)
        elif 5 == opt:
            no1 = random.randint(1, data_num)
            no2 = random.randint(1, int(data_num / no1))
            no3 = data_num / no1 / no2
            graph = nx.complete_multipartite_graph(no1, no2, no3)
        elif 6 == opt:
            graph = nx.circular_ladder_graph(data_num)
        elif 7 == opt:
            graph = nx.cycle_graph(data_num)
        elif 8 == opt:
            graph = nx.dorogovtsev_goltsev_mendes_graph(5)
        elif 9 == opt:
            top_num = int(random.random() * data_num)
            bottom_num = data_num / top_num
            graph = nx.grid_2d_graph(top_num, bottom_num)
        elif 10 == opt:
            no1 = random.randint(1, data_num)
            no2 = random.randint(1, int(data_num / no1))
            no3 = data_num / no1 / no2
            graph = nx.grid_graph([no1, no2, no3])
        elif 11 == opt:
            graph = nx.hypercube_graph(10)
        elif 12 == opt:
            graph = nx.ladder_graph(data_num)
        elif 13 == opt:
            top_num = int(random.random() * data_num)
            bottom_num = data_num - top_num
            graph = nx.lollipop_graph(top_num, bottom_num)
        elif 14 == opt:
            graph = nx.path_graph(data_num)
        elif 15 == opt:
            graph = nx.star_graph(data_num)
        elif 16 == opt:
            graph = nx.wheel_graph(data_num)
        elif 17 == opt:
            graph = nx.margulis_gabber_galil_graph(35)
        elif 18 == opt:
            graph = nx.chordal_cycle_graph(data_num)
        elif 19 == opt:
            graph = nx.fast_gnp_random_graph(data_num, random.random())
        elif 20 == opt:  # jump eigen value
            graph = nx.gnp_random_graph(data_num, random.random())
        elif 21 == opt:  # disconnected graph
            graph = nx.dense_gnm_random_graph(data_num, data_num / 2)
        elif 22 == opt:  # disconnected graph
            graph = nx.gnm_random_graph(data_num, data_num / 2)
        elif 23 == opt:
            graph = nx.erdos_renyi_graph(data_num, data_num / 2)
        elif 24 == opt:
            graph = nx.binomial_graph(data_num, data_num / 2)
        elif 25 == opt:
            graph = nx.newman_watts_strogatz_graph(data_num, 5,
                                                   random.random())
        elif 26 == opt:
            graph = nx.watts_strogatz_graph(data_num, 5, random.random())
        elif 26 == opt:  # smooth eigen
            graph = nx.connected_watts_strogatz_graph(data_num, 5,
                                                      random.random())
        elif 27 == opt:  # smooth eigen
            graph = nx.random_regular_graph(5, data_num)
        elif 28 == opt:  # smooth eigen
            graph = nx.barabasi_albert_graph(data_num, 5)
        elif 29 == opt:  # smooth eigen
            graph = nx.powerlaw_cluster_graph(data_num, 5, random.random())
        elif 30 == opt:  # smooth eigen
            graph = nx.duplication_divergence_graph(data_num, random.random())
        elif 31 == opt:
            p = random.random()
            q = random.random()
            graph = nx.random_lobster(data_num, p, q)
        elif 32 == opt:
            p = random.random()
            q = random.random()
            k = random.random()

            graph = nx.random_shell_graph([(data_num / 3, 50, p),
                                           (data_num / 3, 40, q),
                                           (data_num / 3, 30, k)])
        elif 33 == opt:  # smooth eigen
            top_num = int(random.random() * data_num)
            bottom_num = data_num - top_num
            graph = nx.k_random_intersection_graph(top_num, bottom_num, 3)
        elif 34 == opt:
            graph = nx.random_geometric_graph(data_num, .1)
        elif 35 == opt:
            graph = nx.waxman_graph(data_num)
        elif 36 == opt:
            graph = nx.geographical_threshold_graph(data_num, .5)
        elif 37 == opt:
            top_num = int(random.random() * data_num)
            bottom_num = data_num - top_num
            graph = nx.uniform_random_intersection_graph(
                top_num, bottom_num, .5)

        elif 39 == opt:
            graph = nx.navigable_small_world_graph(data_num)
        elif 40 == opt:
            graph = nx.random_powerlaw_tree(data_num, tries=200)
        elif 41 == opt:
            graph = nx.karate_club_graph()
        elif 42 == opt:
            graph = nx.davis_southern_women_graph()
        elif 43 == opt:
            graph = nx.florentine_families_graph()
        elif 44 == opt:
            graph = nx.complete_multipartite_graph(data_num, data_num,
                                                   data_num)

        # OPT 1
        # norm_lap = nx.normalized_laplacian_matrix(graph).toarray()

        # OPT 2: renormalized

        # pk.dump(graph, open('tmp/g.pk', 'wb'))

    # plot_graph(graph, label)
    # note difference: normalized laplacian and normalzation by eigenvalue
    norm_lap, eigval, eigvec = normalize_lap(graph)

    return graph, norm_lap, eigval, eigvec
Ejemplo n.º 31
0
if __name__ == "__main__":

    argparser = ArgumentParser()
    argparser.add_argument("--method", default="laplacian")
    argparser.add_argument("--dataset", default="grid")
    argparser.add_argument("--cnt", default=3, type=int)
    args = argparser.parse_args()

    plt.figure(figsize=(12, 4))
    for i in range(args.cnt):

        if args.dataset == "grid":
            A = nx.to_numpy_array(nx.grid_2d_graph(i + 2, i + 2))
        if args.dataset == "ladder":
            A = nx.to_numpy_array(nx.ladder_graph(i + 4))
        if args.method == "svd":
            U, S, V = np.linalg.svd(A)
        if args.method == "laplacian":
            S, V = np.linalg.eigh(np.diag(np.sum(A, axis=0)) - A)
            V = V.T[1:, :]
        if args.method == "lle":
            U, S, V = np.linalg.svd(np.eye(len(A)) - A)

        plt.subplot(3, args.cnt, i + 1)
        plt.imshow(V.T)
        plt.axis("off")
        plt.subplot(3, args.cnt, i + args.cnt + 1)
        nx.draw_spring(nx.from_numpy_array(A),
                       node_size=20,
                       node_color="black")
Ejemplo n.º 32
0
def create(args):
    ### load datasets
    graphs = []
    # synthetic graphs
    if args.graph_type == 'ladder':
        graphs = []
        for i in range(100, 201):
            graphs.append(nx.ladder_graph(i))
        args.max_prev_node = 10
    elif args.graph_type == 'ladder_small':
        graphs = []
        for i in range(2, 11):
            graphs.append(nx.ladder_graph(i))
        args.max_prev_node = 10
    elif args.graph_type == 'tree':
        graphs = []
        for i in range(2, 5):
            for j in range(3, 5):
                graphs.append(nx.balanced_tree(i, j))
        args.max_prev_node = 256
    elif args.graph_type == 'caveman':
        # graphs = []
        # for i in range(5,10):
        #     for j in range(5,25):
        #         for k in range(5):
        #             graphs.append(nx.relaxed_caveman_graph(i, j, p=0.1))
        graphs = []
        for i in range(2, 3):
            for j in range(30, 81):
                for k in range(10):
                    graphs.append(caveman_special(i, j, p_edge=0.3))
        args.max_prev_node = 100
    elif args.graph_type == 'caveman_small':
        # graphs = []
        # for i in range(2,5):
        #     for j in range(2,6):
        #         for k in range(10):
        #             graphs.append(nx.relaxed_caveman_graph(i, j, p=0.1))
        graphs = []
        for i in range(2, 3):
            for j in range(6, 11):
                for k in range(20):
                    graphs.append(caveman_special(i, j,
                                                  p_edge=0.8))  # default 0.8
        args.max_prev_node = 20
    elif args.graph_type == 'caveman_small_single':
        # graphs = []
        # for i in range(2,5):
        #     for j in range(2,6):
        #         for k in range(10):
        #             graphs.append(nx.relaxed_caveman_graph(i, j, p=0.1))
        graphs = []
        for i in range(2, 3):
            for j in range(8, 9):
                for k in range(100):
                    graphs.append(caveman_special(i, j, p_edge=0.5))
        args.max_prev_node = 20
    elif args.graph_type.startswith('community'):
        num_communities = int(args.graph_type[-1])
        print('Creating dataset with ', num_communities, ' communities')
        c_sizes = np.random.choice([12, 13, 14, 15, 16, 17], num_communities)
        #c_sizes = [15] * num_communities
        for k in range(3000):
            graphs.append(n_community(c_sizes, p_inter=0.01))
        args.max_prev_node = 80
    elif args.graph_type == 'grid':
        graphs = []
        for i in range(10, 20):
            for j in range(10, 20):
                graphs.append(nx.grid_2d_graph(i, j))
        args.max_prev_node = 40
    elif args.graph_type == 'grid_small':
        graphs = []
        for i in range(2, 5):
            for j in range(2, 6):
                graphs.append(nx.grid_2d_graph(i, j))
        args.max_prev_node = 15
    elif args.graph_type == 'barabasi':
        graphs = []
        for i in range(100, 200):
            for j in range(4, 5):
                for k in range(5):
                    graphs.append(nx.barabasi_albert_graph(i, j))
        args.max_prev_node = 130
    elif args.graph_type == 'barabasi_small':
        graphs = []
        for i in range(4, 21):
            for j in range(3, 4):
                for k in range(10):
                    graphs.append(nx.barabasi_albert_graph(i, j))
        args.max_prev_node = 20
    elif args.graph_type == 'grid_big':
        graphs = []
        for i in range(36, 46):
            for j in range(36, 46):
                graphs.append(nx.grid_2d_graph(i, j))
        args.max_prev_node = 90

    elif 'barabasi_noise' in args.graph_type:
        graphs = []
        for i in range(100, 101):
            for j in range(4, 5):
                for k in range(500):
                    graphs.append(nx.barabasi_albert_graph(i, j))
        graphs = perturb_new(graphs, p=args.noise / 10.0)
        args.max_prev_node = 99

    # real graphs
    elif args.graph_type == 'enzymes':
        graphs = Graph_load_batch(min_num_nodes=10, name='ENZYMES')
        args.max_prev_node = 25
    elif args.graph_type == 'enzymes_small':
        graphs_raw = Graph_load_batch(min_num_nodes=10, name='ENZYMES')
        graphs = []
        for G in graphs_raw:
            if G.number_of_nodes() <= 20:
                graphs.append(G)
        args.max_prev_node = 15
    elif args.graph_type == 'protein':
        graphs = Graph_load_batch(min_num_nodes=20, name='PROTEINS_full')
        args.max_prev_node = 80
    elif args.graph_type == 'DD':
        graphs = Graph_load_batch(min_num_nodes=100,
                                  max_num_nodes=500,
                                  name='DD',
                                  node_attributes=False,
                                  graph_labels=True)
        args.max_prev_node = 230
    elif args.graph_type == 'citeseer':
        _, _, G = Graph_load(dataset='citeseer')
        G = max(nx.connected_component_subgraphs(G), key=len)
        G = nx.convert_node_labels_to_integers(G)
        graphs = []
        for i in range(G.number_of_nodes()):
            G_ego = nx.ego_graph(G, i, radius=3)
            if G_ego.number_of_nodes() >= 50 and (G_ego.number_of_nodes() <=
                                                  400):
                graphs.append(G_ego)
        args.max_prev_node = 250
    elif args.graph_type == 'citeseer_small':
        _, _, G = Graph_load(dataset='citeseer')
        G = max(nx.connected_component_subgraphs(G), key=len)
        G = nx.convert_node_labels_to_integers(G)
        graphs = []
        for i in range(G.number_of_nodes()):
            G_ego = nx.ego_graph(G, i, radius=1)
            if (G_ego.number_of_nodes() >= 4) and (G_ego.number_of_nodes() <=
                                                   20):
                graphs.append(G_ego)
        shuffle(graphs)
        graphs = graphs[0:200]
        args.max_prev_node = 15

    elif args.graph_type == 'AST' or args.graph_type == '200Graphs':
        graphs = ast_graph_load_batch(min_num_nodes=10, name=args.graph_type)
        # update edge_feature_output_dim
        if not args.max_node_feature_num:
            # print(type(graphs[1].nodes._nodes), graphs[1].nodes._nodes.keys())
            args.max_node_feature_num = len(
                list(graphs[1].nodes._nodes._atlas[1].keys())
            )  # now equals to 28
        args.max_prev_node = 120
    # TODO: args.max_edge_feature_num update

    if not args.edge_feature_output_dim:
        args.edge_feature_output_dim = args.max_edge_feature_num + 2  #int(args.max_prev_node * args.max_edge_feature_num)
        # 2 indicates two directions of edges
    if not args.node_feature_input_dim:
        args.node_feature_input_dim = args.max_node_feature_num + args.max_prev_node + args.edge_feature_output_dim
        # args.node_feature_input_dim = args.max_prev_node

    return graphs
if not os.path.exists(args.output):
    os.makedirs(args.output)

with open(args.output + '/output.csv', 'w') as output:
	helper(output, nx.balanced_tree(2, 5), "balanced_tree") # branching factor, height
	helper(output, nx.barbell_graph(50, 50), "barbell_graph")
	helper(output, nx.complete_graph(50), "complete_graph")
	helper(output, nx.complete_bipartite_graph(50, 50), "complete_bipartite_graph")
	helper(output, nx.circular_ladder_graph(50), "circular_ladder_graph")
	helper(output, nx.cycle_graph(50), "cycle_graph")
	helper(output, nx.dorogovtsev_goltsev_mendes_graph(5), "dorogovtsev_goltsev_mendes_graph")
	helper(output, nx.empty_graph(50), "empty_graph")
	helper(output, nx.grid_2d_graph(5, 20), "grid_2d_graph")
	helper(output, nx.grid_graph([2, 3]), "grid_graph")
	helper(output, nx.hypercube_graph(3), "hypercube_graph")
	helper(output, nx.ladder_graph(50), "ladder_graph")
	helper(output, nx.lollipop_graph(5, 20), "lollipop_graph")
	helper(output, nx.path_graph(50), "path_graph")
	helper(output, nx.star_graph(50), "star_graph")
	helper(output, nx.trivial_graph(), "trivial_graph")
	helper(output, nx.wheel_graph(50), "wheel_graph")
	
	helper(output, nx.random_regular_graph(1, 50, 678995), "random_regular_graph_1")
	helper(output, nx.random_regular_graph(3, 50, 683559), "random_regular_graph_3")
	helper(output, nx.random_regular_graph(5, 50, 515871), "random_regular_graph_5")
	helper(output, nx.random_regular_graph(8, 50, 243579), "random_regular_graph_8")
	helper(output, nx.random_regular_graph(13, 50, 568324), "random_regular_graph_13")
	
	
	helper(output, nx.diamond_graph(), "diamond_graph")
Ejemplo n.º 34
0
def create(args):
    ### load datasets
    graphs = []
    # synthetic graphs
    if args.graph_type == 'ladder':
        graphs = []
        for i in range(100, 201):
            graphs.append(nx.ladder_graph(i))
        args.max_prev_node = 10
    elif args.graph_type == 'ladder_small':
        graphs = []
        for i in range(2, 11):
            graphs.append(nx.ladder_graph(i))
        args.max_prev_node = 10
    elif args.graph_type == 'tree':
        graphs = []
        for i in range(2, 5):
            for j in range(3, 5):
                graphs.append(nx.balanced_tree(i, j))
        args.max_prev_node = 256
    elif args.graph_type == 'caveman':
        # graphs = []
        # for i in range(5,10):
        #     for j in range(5,25):
        #         for k in range(5):
        #             graphs.append(nx.relaxed_caveman_graph(i, j, p=0.1))
        graphs = []
        for i in range(2, 3):
            for j in range(30, 81):
                for k in range(10):
                    graphs.append(caveman_special(i, j, p_edge=0.3))
        args.max_prev_node = 100
    elif args.graph_type == 'caveman_small':
        # graphs = []
        # for i in range(2,5):
        #     for j in range(2,6):
        #         for k in range(10):
        #             graphs.append(nx.relaxed_caveman_graph(i, j, p=0.1))
        graphs = []
        for i in range(2, 3):
            for j in range(6, 11):
                for k in range(20):
                    graphs.append(caveman_special(i, j,
                                                  p_edge=0.8))  # default 0.8
        args.max_prev_node = 20
    elif args.graph_type == 'caveman_small_single':
        # graphs = []
        # for i in range(2,5):
        #     for j in range(2,6):
        #         for k in range(10):
        #             graphs.append(nx.relaxed_caveman_graph(i, j, p=0.1))
        graphs = []
        for i in range(2, 3):
            for j in range(8, 9):
                for k in range(100):
                    graphs.append(caveman_special(i, j, p_edge=0.5))
        args.max_prev_node = 20
    elif args.graph_type.startswith('community'):
        num_communities = int(args.graph_type[-1])
        print('Creating dataset with ', num_communities, ' communities')
        c_sizes = np.random.choice([12, 13, 14, 15, 16, 17], num_communities)
        #c_sizes = [15] * num_communities
        for k in range(3000):
            graphs.append(n_community(c_sizes, p_inter=0.01))
        args.max_prev_node = 80
    elif args.graph_type == 'grid':
        graphs = []
        for i in range(10, 20):
            for j in range(10, 20):
                graphs.append(nx.grid_2d_graph(i, j))
        args.max_prev_node = 40
    elif args.graph_type == 'grid_small':
        graphs = []
        for i in range(2, 5):
            for j in range(2, 6):
                graphs.append(nx.grid_2d_graph(i, j))
        args.max_prev_node = 15
    elif args.graph_type == 'barabasi':
        graphs = []
        for i in range(100, 200):
            for j in range(4, 5):
                for k in range(5):
                    graphs.append(nx.barabasi_albert_graph(i, j))
        args.max_prev_node = 130
    elif args.graph_type == 'barabasi_small':
        graphs = []
        for i in range(4, 21):
            for j in range(3, 4):
                for k in range(10):
                    graphs.append(nx.barabasi_albert_graph(i, j))
        args.max_prev_node = 20
    elif args.graph_type == 'grid_big':
        graphs = []
        for i in range(36, 46):
            for j in range(36, 46):
                graphs.append(nx.grid_2d_graph(i, j))
        args.max_prev_node = 90

    elif 'barabasi_noise' in args.graph_type:
        graphs = []
        for i in range(100, 101):
            for j in range(4, 5):
                for k in range(500):
                    graphs.append(nx.barabasi_albert_graph(i, j))
        graphs = perturb_new(graphs, p=args.noise / 10.0)
        args.max_prev_node = 99

    # real graphs
    elif args.graph_type == 'enzymes':
        graphs = Graph_load_batch(min_num_nodes=10, name='ENZYMES')
        args.max_prev_node = 25
    elif args.graph_type == 'enzymes_small':
        graphs_raw = Graph_load_batch(min_num_nodes=10, name='ENZYMES')
        graphs = []
        for G in graphs_raw:
            if G.number_of_nodes() <= 20:
                graphs.append(G)
        args.max_prev_node = 15
    elif args.graph_type == 'protein':
        graphs = Graph_load_batch(min_num_nodes=20, name='PROTEINS_full')
        args.max_prev_node = 80
    elif args.graph_type == 'DD':
        graphs = Graph_load_batch(min_num_nodes=100,
                                  max_num_nodes=500,
                                  name='DD',
                                  node_attributes=False,
                                  graph_labels=True)
        args.max_prev_node = 230
    elif args.graph_type == 'citeseer':
        _, _, G = Graph_load(dataset='citeseer')
        G = max(nx.connected_component_subgraphs(G), key=len)
        G = nx.convert_node_labels_to_integers(G)
        graphs = []
        for i in range(G.number_of_nodes()):
            G_ego = nx.ego_graph(G, i, radius=3)
            if G_ego.number_of_nodes() >= 50 and (G_ego.number_of_nodes() <=
                                                  400):
                graphs.append(G_ego)
        args.max_prev_node = 250
    elif args.graph_type == 'citeseer_small':
        _, _, G = Graph_load(dataset='citeseer')
        G = max(nx.connected_component_subgraphs(G), key=len)
        G = nx.convert_node_labels_to_integers(G)
        graphs = []
        for i in range(G.number_of_nodes()):
            G_ego = nx.ego_graph(G, i, radius=1)
            if (G_ego.number_of_nodes() >= 4) and (G_ego.number_of_nodes() <=
                                                   20):
                graphs.append(G_ego)
        shuffle(graphs)
        graphs = graphs[0:200]
        args.max_prev_node = 15

    elif args.graph_type == 'RNA1':
        args.max_prev_node = 100
        graphs = Untitled.get_all_graphs(fasta='RF00162.fa', maxgr=0)
        #graphs = pickle.load(open("RNA1.pkl","rb"))

    elif args.graph_type == 'RNA2':
        args.max_prev_node = 100
        graphs = Untitled.get_all_graphs(fasta='RF01725.fa', maxgr=0)
        #graphs = pickle.load(open("RNA2.pkl","rb"))
    #print (graphs)
    return graphs
Ejemplo n.º 35
0
def create(args):
### load datasets
    graphs=[]
    # synthetic graphs
    if args.graph_type=='ladder':
        graphs = []
        for i in range(100, 201):
            graphs.append(nx.ladder_graph(i))
        args.max_prev_node = 10
    elif args.graph_type=='ladder_small':
        graphs = []
        for i in range(2, 11):
            graphs.append(nx.ladder_graph(i))
        args.max_prev_node = 10
    elif args.graph_type=='tree':
        graphs = []
        for i in range(2,5):
            for j in range(3,5):
                graphs.append(nx.balanced_tree(i,j))
        args.max_prev_node = 256
    elif args.graph_type=='caveman':
        # graphs = []
        # for i in range(5,10):
        #     for j in range(5,25):
        #         for k in range(5):
        #             graphs.append(nx.relaxed_caveman_graph(i, j, p=0.1))
        graphs = []
        for i in range(2, 3):
            for j in range(30, 81):
                for k in range(10):
                    graphs.append(caveman_special(i,j, p_edge=0.3))
        args.max_prev_node = 100
    elif args.graph_type=='caveman_small':
        # graphs = []
        # for i in range(2,5):
        #     for j in range(2,6):
        #         for k in range(10):
        #             graphs.append(nx.relaxed_caveman_graph(i, j, p=0.1))
        graphs = []
        for i in range(2, 3):
            for j in range(6, 11):
                for k in range(20):
                    graphs.append(caveman_special(i, j, p_edge=0.8)) # default 0.8
        args.max_prev_node = 20
    elif args.graph_type=='caveman_small_single':
        # graphs = []
        # for i in range(2,5):
        #     for j in range(2,6):
        #         for k in range(10):
        #             graphs.append(nx.relaxed_caveman_graph(i, j, p=0.1))
        graphs = []
        for i in range(2, 3):
            for j in range(8, 9):
                for k in range(100):
                    graphs.append(caveman_special(i, j, p_edge=0.5))
        args.max_prev_node = 20
    elif args.graph_type.startswith('community'):
        num_communities = int(args.graph_type[-1])
        print('Creating dataset with ', num_communities, ' communities')
        c_sizes = np.random.choice([12, 13, 14, 15, 16, 17], num_communities)
        #c_sizes = [15] * num_communities
        for k in range(3000):
            graphs.append(n_community(c_sizes, p_inter=0.01))
        args.max_prev_node = 80
    elif args.graph_type=='grid':
        graphs = []
        for i in range(10,20):
            for j in range(10,20):
                graphs.append(nx.grid_2d_graph(i,j))
        args.max_prev_node = 40
    elif args.graph_type=='grid_small':
        graphs = []
        for i in range(2,5):
            for j in range(2,6):
                graphs.append(nx.grid_2d_graph(i,j))
        args.max_prev_node = 15
    elif args.graph_type=='barabasi':
        graphs = []
        for i in range(100,200):
             for j in range(4,5):
                 for k in range(5):
                    graphs.append(nx.barabasi_albert_graph(i,j))
        args.max_prev_node = 130
    elif args.graph_type=='barabasi_small':
        graphs = []
        for i in range(4,21):
             for j in range(3,4):
                 for k in range(10):
                    graphs.append(nx.barabasi_albert_graph(i,j))
        args.max_prev_node = 20
    elif args.graph_type=='grid_big':
        graphs = []
        for i in range(36, 46):
            for j in range(36, 46):
                graphs.append(nx.grid_2d_graph(i, j))
        args.max_prev_node = 90

    elif 'barabasi_noise' in args.graph_type:
        graphs = []
        for i in range(100,101):
            for j in range(4,5):
                for k in range(500):
                    graphs.append(nx.barabasi_albert_graph(i,j))
        graphs = perturb_new(graphs,p=args.noise/10.0)
        args.max_prev_node = 99

    # real graphs
    elif args.graph_type == 'enzymes':
        graphs= Graph_load_batch(min_num_nodes=10, name='ENZYMES')
        args.max_prev_node = 25
    elif args.graph_type == 'enzymes_small':
        graphs_raw = Graph_load_batch(min_num_nodes=10, name='ENZYMES')
        graphs = []
        for G in graphs_raw:
            if G.number_of_nodes()<=20:
                graphs.append(G)
        args.max_prev_node = 15
    elif args.graph_type == 'protein':
        graphs = Graph_load_batch(min_num_nodes=20, name='PROTEINS_full')
        args.max_prev_node = 80
    elif args.graph_type == 'DD':
        graphs = Graph_load_batch(min_num_nodes=100, max_num_nodes=500, name='DD',node_attributes=False,graph_labels=True)
        args.max_prev_node = 230
    elif args.graph_type == 'citeseer':
        _, _, G = Graph_load(dataset='citeseer')
        G = max(nx.connected_component_subgraphs(G), key=len)
        G = nx.convert_node_labels_to_integers(G)
        graphs = []
        for i in range(G.number_of_nodes()):
            G_ego = nx.ego_graph(G, i, radius=3)
            if G_ego.number_of_nodes() >= 50 and (G_ego.number_of_nodes() <= 400):
                graphs.append(G_ego)
        args.max_prev_node = 250
    elif args.graph_type == 'citeseer_small':
        _, _, G = Graph_load(dataset='citeseer')
        G = max(nx.connected_component_subgraphs(G), key=len)
        G = nx.convert_node_labels_to_integers(G)
        graphs = []
        for i in range(G.number_of_nodes()):
            G_ego = nx.ego_graph(G, i, radius=1)
            if (G_ego.number_of_nodes() >= 4) and (G_ego.number_of_nodes() <= 20):
                graphs.append(G_ego)
        shuffle(graphs)
        graphs = graphs[0:200]
        args.max_prev_node = 15 
    elif args.graph_type == 'generated':
        graphs = []
        file_list = glob.glob('./generated_graphs/*.pkl')
        file_list = [s for s in file_list
                    if args.generated_name in s
                    and 
                    args.generated_size in s]
        print('File_list:\n{}'.format(file_list))
        for file in file_list:
            A = pkl.load(open(file, 'rb'), encoding='latin-1')
            for graph in A['data']:    
                G = nx.from_numpy_matrix(graph)
                graphs.append(G)
        args.max_prev_node = 63
 
    return graphs
Ejemplo n.º 36
0
 def test_result_ladder_graph_200(self):
     assert (calc_and_compare(NX.ladder_graph(200)))
Ejemplo n.º 37
0
import networkx as nx
G = nx.Graph()
G.add_node(1)
G.add_node(2)
G.add_node(3)
G.add_edge(1, 2)
G.add_edge(1, 3)
G.nodes()  #to display nodes
G.edges()  #to display edges
G.order()  # tells no of nodes in the Graph
G.size()  # tells no of edges in the graph

Z = nx.complete_graph(10)  # draws a complete graph
H = nx.gnp_random_graph(
    20, 0.5
)  #draws random graph of 20 nodes with edges being contected with prob 0.5
C = nx.cycle_graph(5)
L = nx.ladder_graph(5)
P = nx.path_graph(6)
S = nx.star_graph(5)  #5 outer nodes and 1 hub node
W = nx.wheel_graph(5)
B = nx.barbell_graph(4, 2)  # 4 is no of community; 2 no of ibw nodes
O = nx.complete_graph(4)

import matplotlib.pyplot as plt
# nx.draw(G) #simply nodes
nx.draw(S, with_labels=1)
plt.show()