コード例 #1
0
def random_graph(node_number,
                 edge_density,
                 seed=None,
                 is_tree=False,
                 plot=False):
    if seed is not None:
        graph = nx.random_tree(node_number, seed=seed)
    else:
        graph = nx.random_tree(node_number)
    if not is_tree:
        counter = 0
        if seed is not None:
            random.seed(seed)
        while 1 + counter / graph.number_of_nodes() < edge_density:
            v = random.randint(0, graph.number_of_nodes() - 1)
            w = random.randint(0, graph.number_of_nodes() - 1)
            if w != v and not graph.has_edge(v, w):
                graph.add_edge(v, w)
                counter += 1
    if plot:
        pos = graphviz_layout(graph, prog='neato')
        nx.draw(graph, pos)
        nx.draw_networkx_labels(graph, pos, nodelist=graph.nodes())
        matplotlib.pyplot.show()

    return graph
コード例 #2
0
def r_tree(nodes, height=None):
    '''
    Generates a random tree, with random utility and demand for each node

    :param nodes: Number of nodes in the tree
    :param height: (optional) produces tree with given height.
    :return: Random tree with len{V} = nodes
    '''
    G = nx.random_tree(nodes)
    if height is not None:
        while calc_height(G, get_root(G)) is not height:
            G = nx.random_tree(nodes)
    utils = {}
    demand = {}

    # for a given node, income = util - demand
    income = {}

    # random utils and demand for each node
    for node in G.nodes:
        utils.update({node: random.randint(1, 4)})
        demand.update({node: random.randint(1, 2)})
        income.update({node: utils[node] - demand[node]})

    nx.set_node_attributes(G, name='util', values=utils)
    nx.set_node_attributes(G, name='demand', values=demand)
    nx.set_node_attributes(G, name='income', values=income)

    return G
コード例 #3
0
def generate_random_graph(n_nodes,
                          density,
                          directed=False,
                          is_tree=False,
                          seed=None,
                          draw=False):
    r"""Generate a random graph with the desired number of nodes and density.
    Draw the graph if asked. Returns the graph as a networkx object.

    Parameters:
    ----------
    n_nodes: int,
             number of nodes
    density: float (\in [0,1]),
             density of edges
    directed: bool,
              whether or not the graph is directed
    is_tree: bool,
             whether to generate a tree or not
    seed: int,
          the random seed to use
    draw: bool,
          whether to draw the graph or not

    Returns:
    -------
    graph: networkx Digraph"""

    # if we want to generate a directed graph, we generate two undirected graphs
    # of the same size and assemble them in one single directed graph by saying the
    # vertices of the first are in the direction left -> right and the inverse for the second

    # Compute the number of edges corresponding to the given density
    n_edges = int(density * n_nodes * (n_nodes - 1) / 2)
    # Create the graph
    seed_1 = None if seed is None else seed + 1
    if is_tree:
        graph_0 = nx.random_tree(n_nodes, seed=seed)
        if directed:
            graph_1 = nx.random_tree(n_nodes, seed=seed_1)
        else:
            graph_1 = graph_0
    else:
        graph_0 = nx.gnm_random_graph(n_nodes, n_edges, seed)
        if directed:
            graph_1 = nx.gnm_random_graph(n_nodes, n_edges, seed_1)
        else:
            graph_1 = graph_0
    graph_2 = nx.DiGraph()
    graph_2.add_nodes_from(graph_0.nodes())
    graph_2.add_edges_from([(u, v) for (u, v) in graph_0.edges()])
    graph_2.add_edges_from([(v, u) for (u, v) in graph_1.edges()])

    if draw:
        plot_graph(graph_2, color_type="fabulous")

    return graph_2
コード例 #4
0
def genTree(G, cliquel):
    """Generates a graph composed of a random tree in wich each leaf is one of
    the cliques in G."""
    k = len(cliquel)  #Number of cliques
    if k < 2:
        print("there must be more than 1 clique!")
    #To determine the constant "3.8" it was tested the torso_nodes/nodes ratio for
    #the function random tree, and it was discovered to be aprox 0.625, with a
    #max value of 0.76 at low number of nodes, so to be sure, I used 0.8:

    tree = nx.random_tree(int(k * 3.8))
    #list of nodes with degree = 1:
    leaves = [n for n, v in tree.nodes(data=True) if tree.degree()[n] == 1]
    #The other nodes:
    not_leaves = [n for n, v in tree.nodes(data=True) if tree.degree()[n] != 1]

    #Since the tree must have the same amount of leaves as cliques, we make sure that happens:
    cnt = 0
    while len(leaves) != k:
        #Because of the flies, we put a limit to the search of the tree:
        if cnt == 1000:
            print(
                "surpassed 1000 tries and can't find random tree with #leaves>=#cliques"
            )
            1 / 0
        cnt += 1
        #if we obtain a tree with more leaves, we cut them:
        if len(leaves) > k:
            tree.remove_node(leaves.pop(random.randint(0, len(leaves) - 1)))
        #otherwise, we try with other tree:
        else:
            tree = nx.random_tree(int(k * 3.8))
            leaves = [
                n for n, v in tree.nodes(data=True) if tree.degree()[n] == 1
            ]
            not_leaves = [
                n for n, v in tree.nodes(data=True) if tree.degree()[n] != 1
            ]

    tree = clean_waste(tree)
    #First, we make sure node ids from tree aren't repeated in G by making their
    #numbers start when the nodes on G end:
    tree = nx.convert_node_labels_to_integers(tree, len(G))
    leaves = [n for n, v in tree.nodes(data=True) if tree.degree()[n] == 1]
    not_leaves = [n for n, v in tree.nodes(data=True) if tree.degree()[n] != 1]
    #Make leaves have the same name id as one node from each clique in G:
    leaf_name_dic = dict(zip(leaves, cliquel))
    tree = nx.relabel_nodes(tree, leaf_name_dic)
    #Make the not-leaves have a new name so as to continue in order with the rest of nodes:
    not_leaf_names = [len(G) + x for x in range(len(not_leaves))]
    not_leaf_name_dic = dict(zip(not_leaves, not_leaf_names))
    tree = nx.relabel_nodes(tree, not_leaf_name_dic)
    #Combine The tree with G:
    G = nx.compose(G, tree)

    return G
コード例 #5
0
ファイル: configFiles.py プロジェクト: Lolcroc/SimulaQron
def get_random_connected(nodes, nr_edges):
    """
    Constructs a dictionary describing a random connected graph with a specified number of edges,
    with the name of the vertices are taken from the 'nodes'
    :param nodes: list of str
        Name of the nodes to be used
    :param nr_edges: int
        The number of edges that the graph should have.
    :return: dct
        keys are the names of the nodes and values their neighbors
    """
    nn = len(nodes)
    min_edges = nn - 1
    max_edges = nn * (nn - 1) / 2
    if (nr_edges < min_edges) or (nr_edges > max_edges):
        raise ValueError("Number of edges cannot be less than #vertices-1 or greater then #vertices * (#vertices-1)/2")

    G = nx.random_tree(nn)

    non_edges = list(nx.non_edges(G))

    for _ in range(min_edges, nr_edges):
        random_edge = random.choice(non_edges)
        G.add_edge(random_edge[0], random_edge[1])
        non_edges.remove(random_edge)

    # Construct mapping to relabel nodes
    mapping = {i: nodes[i] for i in range(len(nodes))}
    nx.relabel_nodes(G=G, mapping=mapping, copy=False)

    # Get the dictionary from the graph
    adjacency_dct = nx.to_dict_of_lists(G)

    return adjacency_dct
コード例 #6
0
ファイル: tree_decomp.py プロジェクト: hancockki/Overexposure
def testOriginaltoCluster(n, c, k):
    G_test = nx.random_tree(n)
    setAllNodeAttributes(G_test)
    G_cluster = buildClusteredSet(G_test, c)  #return cluster graph
    #start tree decomposition
    tree_decomp = approx.treewidth_min_degree(G_cluster)
    print("cluster dict:", clusterDict)
    print("rej node dict", rejectingNodeDict)
    clearVisitedNodesAndDictionaries(G_cluster)
    makeMatrix(G_cluster, G_cluster.number_of_nodes())

    color_map = []
    for nodeID in G_test.nodes():
        if G_test.nodes[nodeID]['criticality'] >= c:
            color_map.append('red')
        else:
            color_map.append('green')
    fig2 = plt.figure(1)
    G_tree = tree_decomp[1]
    print(
        "List of nodes, where each node is a bag, and each bag contains a set of nodes in the bag:\n",
        list(G_tree.nodes()), "\nList of edges, where each edge is listed:\n",
        list(G_tree.edges()))
    nx.draw_networkx(G_tree,
                     pos=nx.spring_layout(G_tree, iterations=200),
                     arrows=False,
                     with_labels=True)
    for i in G_tree.nodes():
        print(list(i))
    #nx.draw_networkx(G_cluster, node_color = color_map, pos=nx.spring_layout(G_test, iterations=1000), arrows=False, with_labels=True)
    return G_cluster
コード例 #7
0
def get_graph(num_nodes, k, criticality):
    G_cluster = False
    G = False
    cluster_graphs, original_graphs = sgc.make_graphs(criticality, num_nodes)
    graph_types = [
        "ba-no-cycle", "ba-cycle", "er-no-cycle", "er-cycle", "ws-no-cycle",
        "ws-cycle"
    ]
    while G_cluster == False:
        G = nx.random_tree(num_nodes)
        G_cluster = cc.testOriginaltoCluster(G, num_nodes, criticality, True,
                                             True)
    cluster_graphs.append(G_cluster)
    store_info(G_cluster, k)
    graph_types.append("cluster no cycle")
    G_cluster_cycle = False
    while G_cluster_cycle == False:
        G_cluster_cycle = cc.testOriginaltoCluster(G, num_nodes, criticality,
                                                   False, False)
    cluster_graphs.append(G_cluster_cycle)
    original_graphs.append(["tree", G])
    graph_types.append("cluster cycle")
    for original in original_graphs:
        cc.showOriginalGraph(original[1], criticality)
        plt.savefig(FILE_DIRECTORY_PREFIX + "saved-graphs/" + original[0] +
                    ".png")
        # plt.show()
    return cluster_graphs, graph_types
    """
コード例 #8
0
def create_rnd_trees(size, number, filename, dst_path, labeled=False, seed=1):
    random.seed(seed)
    for i in range(number):
        G = nx.random_tree(size, seed + i)
        GSnap = snap.TUNGraph()

        if labeled:
            labels = snap.TIntStrH()
        for node in G.nodes(data=True):
            id = node[0]
            if labeled:
                node_label = node[1]['predicate']
                labels[int(id)] = str(node_label)
            GSnap.AddNode(int(id))

        for edge in G.edges():
            GSnap.AddEdge(int(edge[0]), int(edge[1]))

        FOut = snap.TFOut(dst_path + filename + "_" +
                          str(i).zfill(math.ceil(math.log10(number + 1))) +
                          ".graph")
        GSnap.Save(FOut)
        FOut.Flush()

        if labeled:
            FOut = snap.TFOut(dst_path + filename + "_" +
                              str(i).zfill(math.ceil(math.log10(number + 1))) +
                              ".labels")
            labels.Save(FOut)
            FOut.Flush()
コード例 #9
0
def create_connected_graph(N, E):
    G = nx.random_tree(N)
    if nx.is_connected(G) == False:
        raise Exception('Not a spanning tree!')
    for (i, j) in G.edges:  #Adds data to spanning tree portion of graph
        p = random.random()
        q = 0.5 * p
        G.edges[i, j]['length'] = -np.log(p)
        G.edges[i, j]['interdicted_length'] = -np.log(q) + np.log(p)
    G_comp = nx.complete_graph(N)
    while G.number_of_edges() < 0.5 * E:  #generates remaining edges with data
        edge = random.sample(list(set(G_comp.edges) - set(G.edges)), 1)
        for (i, j) in edge:
            p = random.random()
            q = 0.5 * p
            G.add_edge(i,
                       j,
                       length=-np.log(p),
                       interdicted_length=-np.log(q) + np.log(p))
    G = G.to_directed()
    if nx.is_strongly_connected(G) == False:
        raise Exception('Directed graph is not strongly connected')
    nx.draw(G, with_labels=True)
    plt.show()
    plt.savefig("path.png")
    return G
コード例 #10
0
ファイル: rootedtree.py プロジェクト: Leo927/FindCopNum
    def random(cls, numVertices: int):
        '''Return a random tree of given size'''
        if numVertices <= 0:
            return nx.Graph()

        graph = nx.random_tree(int(numVertices))
        return cls(graph, 0)
コード例 #11
0
def generate_test ( filenum, isCyclic, nodes, edges, prefix=None ):

    while True:
        if isCyclic:
            G = nx.gnm_random_graph(nodes, edges)
        else:
            G = nx.random_tree(nodes)
        if nx.is_connected(G): # ensure connected graph
            break

    # nx.draw(G, with_labels=True, font_weight='bold')
    # plt.savefig("{}tests/test{}.png".format(prefix if prefix else "",filenum))
    # plt.close()

    with open("{}tests/test{}.txt".format(prefix if prefix else "",filenum), "w") as infile:
        infile.write("{}\n".format(nodes))
        A = nx.adjacency_matrix(G).toarray()
        for row in A:
            for col in row:
                infile.write("{} ".format(col))
            infile.write("\n")

    with open("{}queries/query{}.txt".format(prefix if prefix else "",filenum), "w") as qfile:

        source = random.randrange(nodes)
        qfile.write("{}\n".format(source))

        target = source
        while target == source:
            target = random.randrange(nodes) # make sure source and target are different nodes
        qfile.write("{}\n".format(target))

    with open("{}edgelists/edgelist{}.txt".format(prefix if prefix else "",filenum), "wb") as efile:
        nx.write_edgelist(G, efile, data=False)
コード例 #12
0
ファイル: game.py プロジェクト: gus0k/cdc20_code
def generate_random_uniform(N, T, G_method, seed=1234):

    rng = np.random.RandomState(seed)
    N_ = 4 if N >= 5 else N - 1
    switcher = {
        'complete': nx.complete_graph(N),
        'path': nx.path_graph(N),
        'cycle': nx.cycle_graph(N),
        'regular': nx.random_regular_graph(N_, N, seed=rng),
        'wheel': nx.wheel_graph(N),
        'tree': nx.random_tree(N, seed=rng),
        'chordal': nx.Graph(nx.chordal_cycle_graph(N)),
    }
    G = switcher.get(G_method)

    player_list = []
    for n in range(N):
        p = Player(x=rng.uniform(3, -3, T),
                   sm=13.5,
                   s0=0,
                   ram=5,
                   ec=0.9,
                   ed=0.9)
        player_list.append(p)

    buying_price = np.ones(T) * 3.0
    selling_price = np.ones(T) * 1.0

    game = Game(player_list, buying_price, selling_price, G)
    game.graphtype = G_method
    game.seed = seed
    return game
コード例 #13
0
ファイル: test_graph.py プロジェクト: joy-rosie/graphs
def test_from_nx_graph():
    for _ in range(10):
        nx_graph = nx.random_tree(10)
        g = Graph()
        g.from_nx_graph(nx_graph=nx_graph)
        assert compare_lists_unordered(g.vertices, list(nx_graph.nodes))
        assert compare_lists_unordered(g.edges, list(set(nx_graph.edges).union({(edge[1], edge[0]) for edge in nx_graph.edges})))
コード例 #14
0
def generate_test(filenum, isTree, nodes, edges, prefix=None):

    if isTree:
        G = nx.random_tree(nodes)
    else:
        G = nx.gnm_random_graph(nodes, edges)

    # nx.draw(G, with_labels=True, font_weight='bold')
    # plt.savefig("{}tests/test{}.png".format(prefix if prefix else "",filenum))
    # plt.close()

    with open("{}tests/test{}.txt".format(prefix if prefix else "", filenum),
              "w") as infile:
        infile.write("{}\n".format(nodes))
        A = nx.adjacency_matrix(G).toarray()
        for row in A:
            for col in row:
                infile.write("{} ".format(col))
            infile.write("\n")

    with open(
            "{}answers/answer{}.txt".format(prefix if prefix else "", filenum),
            "w") as outfile:
        try:
            cycle = nx.find_cycle(G)
        except nx.NetworkXNoCycle:
            cycle = None
        outfile.write("no" if cycle else "yes")
コード例 #15
0
def generate_graph(size, graph_type):
    if graph_type == 'random':
        G = nx.dense_gnm_random_graph(size, size * 5, seed=SEED)
    elif graph_type == 'small_world':
        G = nx.watts_strogatz_graph(size, 8, 0.25, seed=SEED)
    elif graph_type == 'small_world_sparse':
        G = nx.watts_strogatz_graph(size, size / 8, 0.25, seed=SEED)
    elif graph_type == 'scale_free':
        # regular expts
        G = nx.barabasi_albert_graph(size, 8, seed=SEED)

        # implementation, celer expts - 10 node graph
        # G = nx.barabasi_albert_graph(size, 5, seed=12)
    elif graph_type == 'scale_free_sparse':
        G = nx.barabasi_albert_graph(size, size / 8, seed=SEED)
    elif graph_type == 'tree':
        G = nx.random_tree(size, seed=SEED)

    # remove self loops and parallel edges
    G.remove_edges_from(G.selfloop_edges())
    G = nx.Graph(G)

    print('Generated a ', graph_type, ' graph')
    print('number of nodes: ', G.number_of_nodes())
    print('Number of Edges: ', G.number_of_edges())
    print('Number of connected components: ',
          nx.number_connected_components(G))
    return G
コード例 #16
0
def testOriginaltoCluster(n, c, k):
    G_test = nx.random_tree(n)
    setAllNodeAttributes(G_test)
    G_cluster = buildClusteredSet(G_test, c)

    f = open("make_matrix.txt", "a")
    f.write("cluster dictionary:" + str(clusterDict) + "\n")
    f.write("rej node dictionary: " + str(rejectingNodeDict) + "\n")
    f.write("edge data:" + str(G_cluster.edges.data()) + "\n")
    f.write("node data:" + str(G_cluster.nodes.data()) + "\n")
    f.close()
    test1 = DP(G_cluster, G_cluster.number_of_nodes(), k)
    maxval = DP_Improved(G_cluster, k)
    print("payoff test DP is: ", test1)
    print("payoff subtree DP is:", maxval)
    clearVisitedNodesAndDictionaries(G_cluster)
    makeMatrix(G_cluster, G_cluster.number_of_nodes())

    color_map = []
    for nodeID in G_test.nodes():
        if G_test.nodes[nodeID]['criticality'] >= c:
            color_map.append('red')
        else:
            color_map.append('green')
    fig2 = plt.figure(1)
    nx.draw_networkx(G_test,
                     node_color=color_map,
                     pos=nx.spring_layout(G_test, iterations=1000),
                     arrows=False,
                     with_labels=True)
    return G_cluster
コード例 #17
0
def blowUpIslands(n, p):

    G = nx.random_tree(n)
    for i in range(0, n):
        if rand.random() < p:
            G.remove_node(i)

    return nx.number_connected_components(G)
コード例 #18
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)
コード例 #19
0
def createClusterGraph(n):
    G = nx.random_tree(n)
    for i in G.nodes():
        rand = random.randint(1, 15)
        G.nodes[i]['weight'] = rand
        for neighbor in nx.neighbors(G, i):
            rand2 = random.randint(0, rand)
            G.add_edge(i, neighbor, weight=rand2)
    return G
コード例 #20
0
def create_graph(number_of_nodes):
    # Create a random tree with x nodes
    global G
    G = nx.random_tree(number_of_nodes, seed=seed)
    pos = nx.nx_pydot.graphviz_layout(G, prog='dot', root=0)

    # Draw the graph
    nx.draw(G, pos, with_labels=True)
    plt.show()
    return G
コード例 #21
0
def directed_random_tree(n, arrows_from_root, seed):
    G = nx.random_tree(n, seed)
    betweeness = nx.betweenness_centrality(G, normalized=False, seed=0)
    root = max(betweeness, key=lambda key: betweeness[key])
    T = nx.bfs_tree(G, root)  # Arrows point away from root

    if arrows_from_root:
        return T
    else:
        return nx.DiGraph(nx.reverse(T, copy=False))  # Cast from ReverseView
コード例 #22
0
ファイル: balanced_sequence.py プロジェクト: Erotemic/misc
def random_ordered_tree(n, seed=None, pool=None):
    import kwarray
    rng = kwarray.ensure_rng(seed, 'python')
    tree = nx.dfs_tree(nx.random_tree(n, seed=seed))
    otree = nx.OrderedDiGraph()
    otree.add_edges_from(tree.edges)
    if pool is not None:
        for node in otree.nodes:
            otree.nodes[node]['label'] = rng.choice(pool)
    return otree
コード例 #23
0
def make_tree(request):
    """Function for making a tree

    This function is getting a graph,
    and returns a tree or "0".
    """
    raw_data = request.GET.dict()
    graph_data = json.loads(raw_data["graph"])
    graph = nx.random_tree(len(graph_data["nodes"]))
    data = cn.to_json(nx.to_numpy_matrix(graph).tolist(), graph_data)
    return JsonResponse(data)
コード例 #24
0
ファイル: drawing graphs.py プロジェクト: brotaku13/movie_map
def practice():
    Peterson = nx.petersen_graph()
    tutte = nx.tutte_graph()
    maze = nx.sedgewick_maze_graph()
    tet = nx.tetrahedral_graph()
    G = nx.random_tree(20)

    nx.draw(G, pos=nx.spring_layout(G), with_labels=True)
    #nx.draw_shell(G, nlist=[range(5, 10), range(5)], with_labels=True, font_weight='bold')

    plt.show()
コード例 #25
0
def random_rooted_tree(n: int, mine=True) -> DiGraph:
    # Node 0 is the root
    if mine:
        # Tends to produce a wider, shorter tree
        di_g = my_random_rooted_tree(n)
    else:
        # Tends to produce a taller, skinnier tree
        # Graph starts out with all bidirectional edges
        di_g = nx.random_tree(n).to_directed()
        # Remove edges pointing towards the root
        di_g = to_directed_tree(di_g)
    return di_g
コード例 #26
0
    def test_tree(self):
        for i in range(10):
            N = np.random.randint(2, 50)
            G = nx.random_tree(N)
            mapping = {
                i: j
                for i, j in zip(range(N), np.random.permutation(range(N)))
            }
            H = nx.relabel_nodes(G, mapping)

            assert nx.is_isomorphic(G, H)
            assert is_possibly_isomorphic(G, H, N)
コード例 #27
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)
コード例 #28
0
def get_graph_by_type(graph_type: str, num_nodes: int, **kwargs) -> nx.Graph:
    if graph_type == "E-R":
        return nx.erdos_renyi_graph(n=num_nodes, **kwargs)
    elif graph_type == "Random Tree":
        return nx.random_tree(n=num_nodes, **kwargs)
    elif graph_type == "r-ary":
        return nx.full_rary_tree(n=num_nodes, **kwargs)
    elif graph_type == "Planted Partition":
        return nx.planted_partition_graph(**kwargs)
    elif graph_type == "Line":
        return nx.path_graph(n=num_nodes, **kwargs)
    elif graph_type == "Barabási–Albert":
        return nx.barabasi_albert_graph(n=num_nodes, **kwargs)
コード例 #29
0
def tree_insertion(num_nodes, num_edges, return_tree=False):
    tree = nx.random_tree(num_nodes)
    chordal = Graph(tree)
    while len(chordal.edges) < num_edges:
        u, v = random.sample(chordal.nodes, 2)
        chordal.add_edge(u, v)
        while not nx.is_chordal(chordal):
            chordal.remove_edge(u, v)
            u, v = random.sample(chordal.nodes, 2)
            chordal.add_edge(u, v)
    if not return_tree:
        return chordal
    return tree, chordal
コード例 #30
0
def test_random_forest_compare_with_tree_dp():
    # Generate tree on 50 edges, then leave only 40 random edges.
    gr_size, al_size = 50, 5
    edges = list(networkx.random_tree(gr_size).edges())
    random.shuffle(edges)
    edges = edges[0:40]
    model = PairWiseFiniteModel(gr_size, 5)
    model.set_field(np.random.random((gr_size, al_size)))
    for v1, v2 in edges:
        model.add_interaction(v1, v2, np.random.random((al_size, al_size)))

    assert_results_close(model.infer(algorithm='message_passing'),
                         model.infer(algorithm='tree_dp'))
コード例 #31
0
    def test_trees(self):
        """The barycenter of a tree is a single vertex or an edge.

        See [West01]_, p. 78.
        """
        prng = Random(0xdeadbeef)
        for i in range(50):
            RT = nx.random_tree(prng.randint(1, 75), prng)
            b = self.barycenter_as_subgraph(RT)
            if len(b) == 2:
                assert_equal(b.size(), 1)
            else:
                assert_equal(len(b), 1)
                assert_equal(b.size(), 0)
コード例 #32
0
ファイル: test_trees.py プロジェクト: ProgVal/networkx
def test_random_tree():
    """Tests that a random tree is in fact a tree."""
    T = nx.random_tree(10, seed=1234)
    assert_true(nx.is_tree(T))