def _gen_(self, n):
        for _ in range(n):

            #generate p value:

            if self.distribution == "Uniform":
                p = np.random.uniform(self.metaparams[0], self.metaparams[1])
                num_v = np.random.randint(self.min_num_v, self.max_num_v)
                g = nx.binomial_graph(num_v, p)
                self.graphs.append(g)
                self.pvals.append(p)

            elif self.distribution == "Normal":
                p = min(
                    abs(
                        np.random.normal(self.metaparams[0],
                                         self.metaparams[1])), 1)
                num_v = np.random.randint(self.min_num_v, self.max_num_v)
                g = nx.binomial_graph(num_v, p)
                self.graphs.append(g)
                self.pvals.append(p)

            else:
                raise Exception(
                    "Please enter a valid distribution from: Normal, Uniform")
def main():
    G = nx.complete_graph(10)
    #完全グラフ
    G2 = nx.barbell_graph(10, 10)
    #ようわからん
    G3 = nx.watts_strogatz_graph(100, 15, 0.1)
    #small world graph
    #watts_strogatz_graph(n,k,p) n: number of node, k:nearest neoghbors,
    G4 = nx.complete_bipartite_graph(3, 3)
    #完全二部グラフ
    G5 = nx.scale_free_graph(50)
    G6 = nx.newman_watts_strogatz_graph(100, 10, 0.05)
    G7 = nx.binomial_graph(10, 0.2)
    #    z=[int(random.gammavariate(alpha=9.0,beta=2.0)) for i in range(6)]
    #    G8 = nx.configuration_model(z)
    #    aseq = [1,2,1]
    #    bseq = [2,1,1]
    #    G8 = nx.configuration_model(aseq,bseq)
    G8 = bp.random_graph(5, 5, 0.5)

    pos = nx.spring_layout(G6)
    #    pos = nx.circular_layout(G5)
    plt.axis('off')
    nx.draw(G6, pos, with_labels=False)
    plt.show()
    def create(self, model, kwargs):
        if model == 1:
            degree = kwargs.get("degree", self.degree)
            nodes = kwargs.get("nodes", self.nodes)
            self.graph = nx.random_regular_graph(degree, nodes)
        elif model == 2:
            nodes = kwargs.get("nodes", self.nodes)
            edge_prob = kwargs.get("edge_prob", self.edge_prob)
            self.graph = nx.binomial_graph(nodes, edge_prob)
        # elif model == 3:
        #     self.graph = nx.gaussian_random_partition_graph(self.nodes, self.nodes/self.neighbour_edges,
        #                                                     self.nodes / self.neighbour_edges,
        #                                                     self.edge_prob, self.edge_prob)
        elif model == 3:
            nodes = kwargs.get("nodes", self.nodes)
            neighbour_edges = kwargs.get("neighbour_edges",
                                         self.neighbour_edges)
            edge_prob = kwargs.get("edge_prob", self.edge_prob)
            self.graph = nx.powerlaw_cluster_graph(nodes, neighbour_edges,
                                                   edge_prob)
        elif model == 4:
            #     self.graph = nx.scale_free_graph(self.nodes)
            # else:
            nodes = kwargs.get("nodes", self.nodes)
            neighbour_edges = kwargs.get("neighbour_edges",
                                         self.neighbour_edges)
            self.graph = nx.barabasi_albert_graph(nodes, neighbour_edges)

        return self.graph
Пример #4
0
def createGraph(numNodes, nodeProb):
  """ Create a graph and compute and save """

  print "Creating random graph with node connectivity probability = %f ...." % nodeProb 
  
  G_fn = "bench_concomp"+str(numNodes)
  randGr = nx.binomial_graph(numNodes, nodeProb, directed=False)
  adjMat = [ [ 0 for i in range(numNodes) ] for j in range(numNodes) ]
  
  for row in range (len(randGr.adj.items())):
    for ind in ((randGr.adj.items()[row])[1]).keys():
      adjMat[row][ind] = 1
  
  # Make equivalent csc_matrix
  Gsparse = csc_matrix(adjMat, dtype=float64)
  gdir = os.path.join("bench",str(numNodes))

  if not os.path.exists(gdir):
    os.makedirs(gdir)
  sio.savemat(os.path.join(gdir ,G_fn),{"fibergraph": Gsparse}, appendmat = True)
  print "Your graph is saved in %s ...\n" % os.path.abspath(gdir)
  inv = evaluate_graph(randGr, -1)

  printUTIL(inv)
  writeUTIL(inv)
Пример #5
0
def statsForGraphs(probaAccuracy=100, nbTestPerProba=100):
    proba = []
    # Represents the largest clusters related to p
    maxiSizeCluster = []
    degreePerProb = []
    for i in range(1, 100):
        p = i / probaAccuracy
        maxiSizeClusterTemp = 0
        degreeMoy = 0
        for j in range(nbTestPerProba):
            degreeMoyPerG = 0
            print(j)
            g = nx.binomial_graph(100, p)
            lstDegre = g.degree
            temp = len(max(nx.connected_component_subgraphs(g), key=len).nodes)
            maxiSizeClusterTemp += temp

            for tuple in lstDegre:
                degreeMoyPerG += tuple[1]
            degreeMoyPerG = degreeMoyPerG / len(lstDegre)
            degreeMoy += degreeMoyPerG
            g.clear()

        degreePerProb.append(degreeMoy / nbTestPerProba)
        maxiSizeCluster.append(maxiSizeClusterTemp / nbTestPerProba)
        proba.append(p)

    return [proba, maxiSizeCluster, degreePerProb]
Пример #6
0
def create_graph_2100_edge():
    p_dict = {300: 0.0203, 400: 0.01085}

    for N in tqdm(p_dict.keys()):
    # for N in tqdm([75, 125, 150, 175]):
        p = p_dict[N]
        for up_w in [1, 5, 10, 100, 1000, 10000]:
            for up_d in [1, 5, 10, 100, 1000, 10000]:
                # generate a cyclic backbone
                backbone_graph = nx.DiGraph()
                for n in range(N):
                    backbone_graph.add_edge(n, (n + 1) % N)

                random_graph = nx.binomial_graph(n=N, p=p, seed=42, directed=True)

                graph = nx.compose(backbone_graph, random_graph)

                for edge in graph.edges:
                    graph.edges[edge]["weight"] = randint(1, up_w)

                for node in graph.nodes:
                    graph.nodes[node]["delay"] = randint(1, up_d)

                wrapper = GraphWrapper(graph)

                r = random_retime(graph)

                # randomization of the graph
                wrapper.set_retimed_graph(r)
                nx.set_node_attributes(wrapper.g, wrapper.delay, 'delay')

                nx.nx_pydot.write_dot(wrapper.g, f"../graph_files/2100edges/N_{N}_p_{parse_float(p)}_upw_{up_w}_upd_{up_d}")
Пример #7
0
def gen(N):
	global filiais_list
	for out in range(0, N):
		i = rand.randint(2, 3000)
		print "Generating Graph Number: " + str(out+1) + "/" + str(N) + "   Size(nodes): " + str(i)
		filiais = rand.randint(1, i)
		G=nx.binomial_graph(i, 0.5, True)

		for n in range(0, i):
			for e in G[n]:				
				r = rand.randint(1, 10)
				G[n][e] = r

		gen_fil(i, filiais)
		f = open(dirname + str(out), "w")
		f.write(str(i) + " " + str(filiais) + " " + str(len(G.edges())) + "\n")		 

		counter = 0

		for a in filiais_list:
			if counter < len(filiais_list):
				f.write(str(a) + " ")
			else:
				f.write(str(a))
			counter = counter + 1
		f.write("\n")
		for e in G.edges():
			f.write(str(e[0]+1) + " " + str(e[1]+1) + " " + str(G[e[0]][e[1]]) + "\n")
		f.close()
		filiais_list = []
Пример #8
0
def generate_test():
    """
    Generate test graphs as dot files.

    It is composed in three phases:

    1. It first generates a backbone_graph, i.e. a cycle (N nodes and N edges). Then, it creates a
    `binomial graph <https://networkx.github.io/documentation/stable/reference/generated/networkx.generators.random_graphs.binomial_graph.html#networkx.generators.random_graphs.binomial_graph>`_
    with a probability p, and merges the two. It is important that the graph has the cyclic backbone because it is required that every node is reachable from any other (for W and D).

    2. After the merge, given two upperbounds upW and upD, respectively for the edge weights and the node delays,
    it initialize every node with a random delay from 1 to upD, and every edge with a random weight from 1 to upW.
    It is **crucial** that the weights of the graph are always >=1, because in this way it is known that the optimal CP
    is the max{d(v)}.

    3. Now, the graph is complete, but it is in its optimal form. To randomize the graph the random_retime function (see utils)
    is used. After that, the graph is saved as dot file.

    These steps are repeated for different ranges of N, p, up_w, up_d. In particular:

    N in [5, 10, 20, 50, 75, 100, 125, 150, 175, 200, 500]

    p in [.0, .05, .1, .2, .3, .5, .75, 1]

    up_w in [1, 5, 10, 100, 1000, 10000]

    up_d in [1, 5, 10, 100, 1000, 10000]

    :return: None
    """

    for N in tqdm([5, 10, 20, 50, 100, 200, 500]):
    # for N in tqdm([75, 125, 150, 175]):
        for p in tqdm([.0, .05, .1, .2, .3, .5, .75, 1]):
            for up_w in [1, 5, 10, 100, 1000, 10000]:
                for up_d in [1, 5, 10, 100, 1000, 10000]:
                    # generate a cyclic backbone
                    backbone_graph = nx.DiGraph()
                    for n in range(N):
                        backbone_graph.add_edge(n, (n + 1) % N)

                    random_graph = nx.binomial_graph(n=N, p=p, seed=42, directed=True)

                    graph = nx.compose(backbone_graph, random_graph)

                    for edge in graph.edges:
                        graph.edges[edge]["weight"] = randint(1, up_w)

                    for node in graph.nodes:
                        graph.nodes[node]["delay"] = randint(1, up_d)

                    wrapper = GraphWrapper(graph)

                    r = random_retime(graph)

                    # randomization of the graph
                    wrapper.set_retimed_graph(r)
                    nx.set_node_attributes(wrapper.g, wrapper.delay, 'delay')

                    nx.nx_pydot.write_dot(wrapper.g, f"../graph_files/N_{N}_p_{parse_float(p)}_upw_{up_w}_upd_{up_d}")
Пример #9
0
def gen_graph(n, prob=0.5):
    while True:
        G = nx.binomial_graph(n, prob, None, True)
        if nx.number_strongly_connected_components(G) == 1:
            break

    return G
Пример #10
0
def createGraph(numNodes = 10):
  
  #numNodes = int(NumNodes)
  
  G_fn = "bench_concomp"+str(numNodes)
  nodeProb = 0.4
  randGr = nx.binomial_graph(numNodes,nodeProb,directed=False)
  
  adjMat = [ [ 0 for i in range(numNodes) ] for j in range(numNodes) ]
  
  for row in range (len(randGr.adj.items())):
    for ind in ((randGr.adj.items()[row])[1]).keys():
      adjMat[row][ind] = 1
  
  # Make equivalent csc_matrix
  Gsparse = csc_matrix(adjMat, dtype=float64)
  
  if not os.path.exists(os.path.join("bench",str(numNodes))):
    os.makedirs(os.path.join("bench",str(numNodes)))
  
  sio.savemat(os.path.join("bench",str(numNodes) ,G_fn),{'fibergraph': Gsparse}, appendmat = True)
  
  inv = evaluate_graph(randGr, -1)
  
  printUTIL(inv)
  writeUTIL(inv)
Пример #11
0
 def loadData(self):
     savename = self.name
     if self.name == "Power Grid of Western States of USA": 
         self.num_of_nodes = 4941   
         self.add_nodes_from(range(self.num_of_nodes))
         linkflag = 0
         fromnode = -1
         fobj = open(os.path.join('data', 'power.txt'),'r')
         for line in fobj:
             try:
                 line = int(line)
             except ValueError:
                 continue
             if linkflag == 0:
                 fromnode = line
                 linkflag = 1
             else:
                 linkflag = 0
                 self.add_edge(fromnode,line)
         fobj.close()
     elif self.name == "Barabasi Albert Scale-Free Network":
         nx.Graph.__init__(self, nx.barabasi_albert_graph(int(self.num_of_nodes),int(self.new_node_to_existing_nodes)) )# scale-free BA model
     elif self.name == "Binomial Graph":
         nx.Graph.__init__(self, nx.binomial_graph(int(self.num_of_nodes),int(self.average_degree)*1.0/int(self.num_of_nodes)) )# Random Graph
     elif self.name == "Watts-Strogatz Small-World Model":
         nx.Graph.__init__(self, nx.watts_strogatz_graph(int(self.num_of_nodes),int(self.average_degree),0.3) )# WS model    
     self.name=savename 
Пример #12
0
def make_random_binomial_graph(N_nodes, p_edge):
    """
    random binomially connected graph with exponentially distributed potentials
    """

    # initialize and add nodes
    graph_name = nx.binomial_graph(N_nodes, p_edge)
    node_state_sizes = np.random.randint(
        10, high=20, size=graph_name.number_of_nodes())

    # add indices of node state -- seems like there should be a slick way to
    # avoid this but can't figure it out
    for n in graph_name.nodes_iter():
        graph_name.node[n]['node_state_indices'] = [
            i for i in xrange(node_state_sizes[n])]

    # add potentials to graph
    for n in graph_name.nodes_iter():
        node_potential = np.random.exponential(1, [node_state_sizes[n], 1])
        graph_name.node[n]['node_potential'] = node_potential
    for i, edge in enumerate(graph_name.edges_iter()):
        n_a, n_b = edge

        len_n_a = len(graph_name.node[n_a]['node_potential'])
        len_n_b = len(graph_name.node[n_b]['node_potential'])
        edge_potential = np.random.exponential(1, [len_n_a, len_n_b])
        graph_name.edge[n_a][n_b]['edge_potential'] = edge_potential

    return graph_name
Пример #13
0
def gen_new_random_graph(nodecount: int, prob: float) -> None:
    """
    Generate a new random graph using binomial generation.

    Will save new network to file.
    """
    newgraph = nx.binomial_graph(nodecount, prob)
    np.save('./test/testnetwork.npy', nx.adjacency_matrix(newgraph).todense())
Пример #14
0
def random_graphs():
    print("Random graphs")
    print("fast GNP random graph")
    G = nx.fast_gnp_random_graph(n=9, p=0.4)
    draw_graph(G)
    print("GNP random graph")
    G = nx.gnp_random_graph(n=9, p=0.1)
    draw_graph(G)
    print("Dense GNM random graph")
    G = nx.dense_gnm_random_graph(n=19, m=28)
    draw_graph(G)
    print("GNM random graph")
    G = nx.gnm_random_graph(n=11, m=14)
    draw_graph(G)
    print("Erdős Rényi graph")
    G = nx.erdos_renyi_graph(n=11, p=0.4)
    draw_graph(G)
    print("Binomial graph")
    G = nx.binomial_graph(n=45, p=0.4)
    draw_graph(G)
    print("Newman Watts Strogatz")
    G = nx.newman_watts_strogatz_graph(n=9, k=5, p=0.4)
    draw_graph(G)
    print("Watts Strogatz")
    G = nx.watts_strogatz_graph(n=9, k=2, p=0.4)
    draw_graph(G)
    print("Watts Strogatz")
    G = nx.watts_strogatz_graph(n=9, k=2, p=0.4)
    draw_graph(G)
    print("Connected Watts Strogatz")
    G = nx.connected_watts_strogatz_graph(n=8, k=2, p=0.1)
    draw_graph(G)
    print("Random Regular Graph")
    G = nx.random_regular_graph(d=2, n=9)
    draw_graph(G)
    print("Barabasi Albert Graph")
    G = nx.barabasi_albert_graph(n=10, m=2)
    draw_graph(G)
    print("Powerlow Cluster Graph")
    G = nx.powerlaw_cluster_graph(n=10, m=2, p=0.2)
    draw_graph(G)
    print("Duplication Divergence Graph")
    G = nx.duplication_divergence_graph(n=10, p=0.2)
    draw_graph(G)
    print("Random lobster Graph")
    G = nx.random_lobster(n=10, p1=0.2, p2=0.8)
    draw_graph(G)
    print("Random shell Graph")
    constructor = [(10, 20, 0.8), (20, 40, 0.8)]
    G = nx.random_shell_graph(constructor)
    draw_graph(G)
    print("Random Powerlow Tree")
    G = nx.random_powerlaw_tree(n=24, gamma=3)
    draw_graph(G)
    print("Random Powerlow Tree Sequence")
    G = nx.random_powerlaw_tree(n=13, gamma=3)
    draw_graph(G)
Пример #15
0
def get_random_graph(filename, n, p, w):
    G = nx.binomial_graph(n, p)
    color = 'blue'  # all nodes are one color
    nx.set_node_attributes(G, color, 'color')
    nx.set_edge_attributes(G, w, 'weight')

    # save_graph(filename, G)

    return G
Пример #16
0
def init_graph():
    # Initialize graph
    # g = nx.binomial_graph(n, p, seed=None, directed=True)
    g = nx.binomial_graph(n, p, seed=None, directed=False)

    # Opinions
    # Initialize initial opinion values
    # Extreme values
    for i in range(0, 20):
        g.node[i]['x'] = 1

    for i in range(180, n):
        g.node[i]['x'] = 0

    # Moderate values
    for i in range(20, 180):
        g.node[i]['x'] = random.random()%0.5

    # Empathy values
    for i in range(0, n):
        g.node[i]['h'] = random.gauss(0.5, 0.01)

    # Curmudegeons 
    for i in range(0, n):
        g.node[i]['c'] = False

    for i in range(10, 50):
        g.node[i]['c'] = True

    # Edge weights - uniform as of now due to paucity of time
    e = g.edges()
    weights  = {}
    for i in range(0, len(e)):
        # Set weight to 0 if node is a curmudegeon
        if g.node[e[i][0]] == True:
            weights[e[i]] = 0
        else:
            weights[e[i]] = 1

        w[e[i][0]][e[i][1]] = 1
        w[e[i][1]][e[i][0]] = 1

    nx.set_edge_attributes(g, 'w', weights)
    for i in g.nodes():
        #g[g.node[i]][g.node[i]]['w'] = 1
        g.add_edge(i,i)
        e = nx.all_neighbors(g, i)
        l = 0
        for _ in e:
            l = l + 1

        g[i][i]['w'] = l
        w[i][i] = l


    return g
Пример #17
0
def init_graph():
    # Initialize graph
    # g = nx.binomial_graph(n, p, seed=None, directed=True)
    g = nx.binomial_graph(n, p, seed=None, directed=False)

    # Opinions
    # Initialize initial opinion values
    # Extreme values
    for i in range(0, 20):
        g.node[i]['x'] = 1

    for i in range(180, n):
        g.node[i]['x'] = 0

    # Moderate values
    for i in range(20, 180):
        g.node[i]['x'] = random.random() % 0.5

    # Empathy values
    for i in range(0, n):
        g.node[i]['h'] = random.gauss(0.5, 0.01)

    # Curmudegeons
    for i in range(0, n):
        g.node[i]['c'] = False

    for i in range(10, 50):
        g.node[i]['c'] = True

    # Edge weights - uniform as of now due to paucity of time
    e = g.edges()
    weights = {}
    for i in range(0, len(e)):
        # Set weight to 0 if node is a curmudegeon
        if g.node[e[i][0]] == True:
            weights[e[i]] = 0
        else:
            weights[e[i]] = 1

        w[e[i][0]][e[i][1]] = 1
        w[e[i][1]][e[i][0]] = 1

    nx.set_edge_attributes(g, 'w', weights)
    for i in g.nodes():
        #g[g.node[i]][g.node[i]]['w'] = 1
        g.add_edge(i, i)
        e = nx.all_neighbors(g, i)
        l = 0
        for _ in e:
            l = l + 1

        g[i][i]['w'] = l
        w[i][i] = l

    return g
Пример #18
0
def er(n, p, directed=False):
    """
    Generates an undirected (or directed) Erdös-Renyi network with link probability p.
    :param p: probability for link presence,
    :param n: number of nodes,
    :param directed: whether or not the network is directed, default False.
    :return: Adjacency matrix of the network.
    """
    return np.array(
        nx.convert_matrix.to_numpy_array(
            nx.binomial_graph(n, p, directed=directed)))
Пример #19
0
 def create(self, model):
     if model == 1:
         self.graph = nx.random_regular_graph(self.degree, self.nodes)
     elif model == 2:
         self.graph = nx.binomial_graph(self.nodes, self.edge_prob)
     elif model == 3:
         self.graph = nx.gnm_random_graph(self.nodes, self.neighbour_edges)
     elif model == 4:
         self.graph = nx.powerlaw_cluster_graph(self.nodes, self.neighbour_edges, self.edge_prob)
     elif model == 5:
         self.graph = nx.dense_gnm_random_graph(self.nodes, self.neighbour_edges)
     else:
         self.graph = nx.barabasi_albert_graph(self.nodes, self.neighbour_edges)
Пример #20
0
    def __init__(self, agent_pool=[], numnodes=0, nettype="unspecified",
                 density=1.0, maxdeg=6, is_directed=False,
                 rand_seed=1, weight_type="comm_succ"):
        """[summary]

        Args:
            agent_pool (list, optional): [description]. Defaults to [].
            numnodes(int, optional): Defaults to 0.
            nettype (str, optional): [description]. Defaults to "unspecified".
            density (float, optional): [description]. Defaults to 1.0.
            maxdeg (int, optional): [description]. Defaults to 6.
            is_directed (bool, optional): [description]. Defaults to False.
            weight_type (str, optional): [description]. Defaults to "comm_succ".
            num_forests (int, optional): [description]. Defaults to 1.

        Raises:
            WrongGraphTypeException: If a 
            NullGraphException: If a networkx graph is not fed for a merged method
        """
        #object variables:
        #agent_pool
        #num_nodes
        #is_dir
        #maxdeg
        #weight_type (what kind)
        #num_forests
        
        self.agent_pool = agent_pool
        
        self.numnodes = len(agent_pool)
        
        self.nettype = nettype
        if nettype == 'complete' or nettype == 'com':
            self.nxgraph = nx.complete_graph(self.agent_pool)
        if nettype == 'scalefree' or nettype == 'sf':
            self.nxgraph = nx.scale_free_graph(self.agent_pool)
        if nettype == 'smallworld' or nettype == 'sw':
            self.nxgraph = nx.watts_strogatz_graph(self.agent_pool)
        if nettype == 'chain' or nettype == 'path' or nettype == 'ch':
            self.nxgraph = nx.path_graph(self.agent_pool)
        if nettype == 'merged' or nettype == 'm':
            if self.nxgraph is None:
                raise NullGraphException("Please feed an existing graph.")
        if nettype == 'unspecified' or nettype == 'u':
            self.nxgraph = nx.binomial_graph(self.agent_pool, seed=rand_seed, directed=self.is_directed)
            
        self.nxgraph.add_nodes_from(agent_pool)
        
        self.is_directed = is_directed
        self.weight_type = weight_type
        self.num_forests = num_forests
Пример #21
0
    def get_generated_graph(self, parameters):
        """
        Initializes graph according to the dictianary of parameters given by user.
        This graph is going to be initializes by a mathematical model such as
        Erdos - Renyi model, Albert Barabasi model, Watts Strogatz model, etc
        randomly.

        :param parameters dictionary of parameters which define the way graph is
        going to be initialized.

        """
        model = parameters['model']
        n = int(parameters['nodes'])
        directed = False
        if model != 'regular' and model != 'watts_strogatz' \
                and parameters['graphtype'] == 'Directed':
            directed = True
        if model == 'erdos':
            self.graph = nx.erdos_renyi_graph(n,
                                              float(parameters['probability']),
                                              directed=directed)
        elif model == 'binomial':
            self.graph = nx.binomial_graph(n,
                                           float(parameters['probability']),
                                           directed=directed)
        elif model == 'watts_strogatz':
            if parameters['isConnected'] == 'Yes':
                self.graph = nx.connected_watts_strogatz_graph(
                    n, int(parameters['edges']),
                    float(parameters['probability']))
            else:
                self.graph = nx.watts_strogatz_graph(
                    n, int(parameters['edges']),
                    float(parameters['probability']))
        elif model == 'regular':
            self.graph = nx.random_regular_graph(int(parameters['degree']), n)
        elif model == 'random':
            self.graph = nx.gnm_random_graph(n,
                                             int(parameters['edges']),
                                             directed=directed)
        elif model == 'barabasi':
            self.growing = True
            self._initial_nodes = n
            self.graph = self.initialize_barabasi_graph(n, directed)

        if self.graph.is_directed():
            self.graphtype = 'Directed'
        else:
            self.graphtype = 'Undirected'
Пример #22
0
    def test_negative_weight_cycle_consistency(self):
        import random
        unif = random.uniform
        for random_seed in range(2):  # range(20):
            random.seed(random_seed)
            for density in [.1, .9]:  # .3, .7, .9]:
                for N in [1, 10, 20]:  # range(1, 60 - int(30 * density)):
                    for max_cost in [1, 90]:  # [1, 10, 40, 90]:
                        G = nx.binomial_graph(N, density, seed=4, directed=True)
                        edges = ((u, v, unif(-1, max_cost)) for u, v in G.edges)
                        G.add_weighted_edges_from(edges)

                        no_heuristic = nx.negative_edge_cycle(G, heuristic=False)
                        with_heuristic = nx.negative_edge_cycle(G, heuristic=True)
                        assert no_heuristic == with_heuristic
def generate_weighted_binomial_graph(n=15, p=0.2, min_weight=3, max_weight=15):
    #generate graph
    nok = True
    while (nok):  #prevents zero degree nodes
        g = nx.binomial_graph(n, p)
        d = dict(nx.degree(g))
        if (0 not in d.values() and nx.is_connected(g)):
            nok = False

    #generate weights
    for (u, v, w) in g.edges(data=True):
        w['weight'] = randint(min_weight, max_weight)

    #initialize colormap
    global colormap
    colormap = [entity_color.get("default")] * n

    return g
Пример #24
0
def drawGraph():
    #Create Graph
    G=nx.binomial_graph(200,.003)

    #Set the positions for the nodes
    pos=nx.spring_layout(G)

    #Draw UNDERGROUND
    nx.draw_networkx_nodes(G,pos, nodelist=ulist, node_size=30, node_color='#ff0000')
    nx.draw_networkx_edges(G,pos, edgelist=uconnections, edge_color="#ff0000",width=3)

    #DRAW BUSES
    nx.draw_networkx_nodes(G,pos, nodelist=blist, node_size=20, node_color='#0000ff')
    nx.draw_networkx_edges(G,pos, edgelist=bconnections, edge_color="#0000ff",width=2)

    #Draw TAXIS
    nx.draw_networkx_nodes(G,pos, nodelist=tlist, node_size=10, node_color='#ffff00')
    nx.draw_networkx_edges(G,pos, edgelist=tconnections, edge_color="#ffff00",width=1)

    nx.draw_networkx_labels(G,pos)
    #plt.savefig("edge_colormap.png") # save as png
    plt.show() # display
    def __create__histdat__(self, no_g_per_val):
        """
		Creates a set of graphs with p=0.1 -> 0.9 in steps of 
		0.1. Used to test weakness of GNN on p_vals
		
		Parameters
		---------
		no_g_per_val : int
			Number of graphs per p value
		Returns
		-------
		Dataset of graphs p = 0.1 -> 0.9, in form ([list],p) for each p 

		"""
        test_uni = []
        pvals = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
        for p in pvals:
            p_list = []
            for i in range(no_g_per_val):
                num_v = np.random.randint(self.min_num_v, self.max_num_v)
                g = nx.binomial_graph(num_v, p)
                p_list.append(g)
            test_uni.append((p_list, p))
        return test_uni
Пример #26
0
    layout=nx.spring_layout


n=150  # 150 nodes
# p value at which giant component (of size log(n) nodes) is expected
p_giant=1.0/(n-1)     
# p value at which graph is expected to become completely connected
p_conn=math.log(n)/float(n) 
                       
# the following range of p values should be close to the threshold
pvals=[0.003, 0.006, 0.008, 0.015] 

region=220 # for pylab 2x2 subplot layout
plt.subplots_adjust(left=0,right=1,bottom=0,top=0.95,wspace=0.01,hspace=0.01)
for p in pvals:    
    G=nx.binomial_graph(n,p)
    pos=layout(G)
    region+=1
    plt.subplot(region)
    plt.title("p = %6.3f"%(p))
    nx.draw(G,pos,
            with_labels=False,
            node_size=10
            )
    # identify largest connected component
    Gcc=sorted(nx.connected_component_subgraphs(G), key = len, reverse=True)
    G0=Gcc[0] 
    nx.draw_networkx_edges(G0,pos,
                           with_labels=False,
                           edge_color='r',
                           width=6.0
Пример #27
0
def simuleer_uitbraak(n, initgeinf, netwerk, fractie_gevac, strategie):
    similatiestappen = 10
    if netwerk == "willekeurig":
        p = 10.0 / n
        G = nx.binomial_graph(n=n, p=p)
    elif netwerk == "schaalvrij":
        G = nx.barabasi_albert_graph(n=n, m=2)
    else:
        raise (
            AttributeError("Netwerk is ofwel 'willekeurig' of 'schaalvrij'"))
    A = geef_verbindingsmatrix(G)
    posities = nx.spring_layout(G)
    x = np.zeros((n, 1), dtype=int)
    x[:initgeinf] = 1  # eerste persoon is geinfecteerd
    resistent = []
    if strategie == "willekeurig":
        resistent = random.sample(range(initgeinf, n), int(n * fractie_gevac))
    elif strategie == "best connecteerd":
        if fractie_gevac > 0:
            D = -A.sum(0)
            resistent = D.argsort(1).tolist()[0][:int(n * fractie_gevac)]
            resistent = list(set(resistent) - set(range(initgeinf)))
    else:
        raise (AttributeError(
            "strategie is ofwel 'willeurig' of 'best connecteerd'"))
    geinfecteerd = [sum(x) / n]
    for t in range(similatiestappen):
        update_toestand(A, x, resistent)
        geinfecteerd.append(sum(x) / n)
    # plot resultaat
    fig, axes = plt.subplots(ncols=2, figsize=(15, 10))
    # plot het netwerk
    knoopkleuren = [blauw] * initgeinf
    for i in range(initgeinf, n):
        if i in resistent:
            knoopkleuren.append(groen)
        elif x[i]:
            knoopkleuren.append(rood)
        else:
            knoopkleuren.append(geel)
    nx.draw_networkx_nodes(G,
                           posities,
                           node_size=10,
                           alpha=0.8,
                           node_color=knoopkleuren,
                           ax=axes[0])
    nx.draw_networkx_edges(G,
                           posities,
                           ax=axes[0],
                           edge_color=blauw,
                           width=0.5,
                           alpha=0.8)
    deax(axes[0])
    axes[0].set_title("Eindtoestand van de het netwerk na {} stappen".format(
        similatiestappen))

    # plot nu de toestanden
    vatbaar = 1 - np.array(geinfecteerd) - fractie_gevac
    axes[1].plot(geinfecteerd, color=rood, ls="--", lw=2, label="geinfecteerd")
    axes[1].plot([0, similatiestappen], [fractie_gevac, fractie_gevac],
                 color=groen,
                 ls=":",
                 lw=2,
                 label="resistent")
    axes[1].plot(vatbaar, color=geel, lw=2, label="vatbaar")
    axes[1].legend(loc=1)
    axes[1].set_xlabel(r"$t$")
    axes[1].set_ylabel(r"Fractie van de knopen")
    axes[1].set_title("Evolutie van de toestanden.")
Пример #28
0
    nx.draw_networkx_labels(netwerk_voorbeeld,
                            posities,
                            labels=labels,
                            ax=ax,
                            label_color=zwart)

    deax(ax)

    fig.savefig("figuren/socialnetwerk.png")

    # Figuur gradenverdeling standaard netwerken
    # ------------------------------------------

    fig, ax = plt.subplots(figsize=(10, 8))

    netwerk_random = nx.binomial_graph(n=1000, p=0.05)
    ax.plot(bereken_gradenverdeling(netwerk_random),
            color=groen,
            label="willekeurig netwerk")

    netwerk_schaalvrij = nx.barabasi_albert_graph(n=1000, m=10)
    ax.plot(bereken_gradenverdeling(netwerk_schaalvrij),
            color=rood,
            ls=':',
            label="schaalvrij netwerk")
    """
    netwerk_grid = nx.grid_2d_graph(n=50, m=20)
    ax.plot(bereken_gradenverdeling(netwerk_grid), color=oranje, ls=":",
                                            label="grid netwerk")
    """
    ax.set_xlabel(r"Graad $k$")
Пример #29
0
p_giant = 1.0 / (n - 1)
# p value at which graph is expected to become completely connected
p_conn = math.log(n) / float(n)

# the following range of p values should be close to the threshold
pvals = [0.003, 0.006, 0.008, 0.015]

region = 220  # for pylab 2x2 subplot layout
plt.subplots_adjust(left=0,
                    right=1,
                    bottom=0,
                    top=0.95,
                    wspace=0.01,
                    hspace=0.01)
for p in pvals:
    G = nx.binomial_graph(n, p)
    pos = layout(G)
    region += 1
    plt.subplot(region)
    plt.title("p = %6.3f" % (p))
    nx.draw(G, pos, with_labels=False, node_size=10)
    # identify largest connected component
    Gcc = sorted(nx.connected_component_subgraphs(G), key=len, reverse=True)
    G0 = Gcc[0]
    nx.draw_networkx_edges(G0,
                           pos,
                           with_labels=False,
                           edge_color='r',
                           width=6.0)
    # show other connected components
    for Gi in Gcc[1:]:
import matplotlib.pyplot as plt
import networkx as nx

n = 150  # 150 nodes
# p value at which giant component (of size log(n) nodes) is expected
p_giant = 1.0 / (n - 1)
# p value at which graph is expected to become completely connected
p_conn = math.log(n) / n

# the following range of p values should be close to the threshold
pvals = [0.003, 0.006, 0.008, 0.015]

fig, axes = plt.subplots(2, 2)
for p, ax, seed in zip(pvals, axes.ravel(), range(len(pvals))):
    #### generate graph ####
    G = nx.binomial_graph(n, p, seed=seed)
    # identify connected/disconnected nodes
    connected = [n for n, d in G.degree() if d > 0]
    disconnected = list(set(G.nodes()) - set(connected))
    # identify largest connected component
    Gcc = sorted(nx.connected_components(G), key=len, reverse=True)
    G0 = G.subgraph(Gcc[0])
    #### draw graph ####
    pos = nx.nx_agraph.graphviz_layout(G)
    ax.set_title(f"p = {p:.3f}")
    # draw largest connected component
    options = {"ax": ax, "edge_color": "tab:red"}
    nx.draw_networkx_edges(G0, pos, width=6.0, **options)
    # draw other connected components
    for Gi in Gcc[1:]:
        if len(Gi) > 1:
Пример #31
0
"""
Using another style
===================

In this example, we show how to use another default Matplotlib style.
"""

import networkx as nx
import matplotlib.pyplot as plt
from grave import plot_network

network = nx.binomial_graph(50, .05)

fig, ax_mat = plt.subplots(ncols=2)

plot_network(network, ax=ax_mat[0])
ax_mat[0].set_axis_on()
with plt.style.context(('ggplot')):
    plot_network(network, ax=ax_mat[1])

ax_mat[1].set_axis_on()
for ax in ax_mat:
    ax.set_axis_on()
    ax.tick_params(which='both',
                   bottom=False,
                   top=False,
                   left=False,
                   right=False,
                   labelbottom=False,
                   labelleft=False)
plt.show()
Пример #32
0
import os
import networkx as nx
import matplotlib.pyplot as plt
os.chdir('/Users/xueyiheng/Desktop')
filename = 'cit-HepTh_3.txt'
G=nx.DiGraph()
with open(filename) as file:
    for line in file:
        head, tail = [float(x) for x in line.split()]
        G.add_edge(head,tail)
pr=nx.pagerank(G,alpha=0.85)
x = 0;
for node, value in pr.items():
    x = x + value
print(x)

G=nx.binomial_graph(1000, 0.3, directed=True)
layout = nx.spring_layout(G)
plt.figure(1)
nx.draw(G, pos=layout, node_color='y')

pr=nx.pagerank(G,alpha=0.85)
print(pr)
for node, pageRankValue in pr.items():
    print("%d,%.4f" %(node,pageRankValue))

plt.figure(2)
nx.draw(G, pos=layout, node_size=[x * 6000 for x in pr.values()],node_color='m',with_labels=True)
plt.show()
Пример #33
0
import random as rnd
import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt

G = nx.binomial_graph(30, 0.30, seed=None)

plt.figure(figsize=(4, 4))
position = nx.spring_layout(G, scale=5, iterations=200)
nx.draw_networkx_nodes(G,
                       position,
                       node_size=50,
                       node_color="#093ea8",
                       node_shape="8")
nx.draw_networkx_edges(G, position, width=0.5, edge_color='black')

plt.axis("off")
plt.savefig("binomial_graph.png", bbox_inches='tight')
plt.savefig("binomial_graph.eps", bbox_inches='tight')
plt.show(G)
Пример #34
0
        # set seed
        axl.seed(tournament_size)

        for sample_players in range (num_sample_players) :
            # create players
            axl.seed(sample_players)
            players = random.sample(ordinary_players, tournament_size)

            for parameter in range(1, ub_parameter + 1) :

                p = parameter/(ub_parameter)
                for seed in range(ub_seed) :

                    axl.seed(seed)
                    # Define graph
                    G = nx.binomial_graph(len(players), p)

                    # check for connected nodes
                    connections = [len(c) for c in
                                   sorted(nx.connected_components(G), key=len,
                                                                  reverse=True)]

                    if connections and (1 not in connections):
                    # if connections is empty, or equal to 1, it means
                    # at least on node is disconnected. Thus, skip this
                    # tournament and generate next
                        edges = G.edges()

                        tournament_id += 1
                        results = tournament_results(G, seed, p, players, turns,
                                                             edges, repetitions,
Пример #35
0
def create_random_graph(n):
    g = networkx.binomial_graph(n, 0.5)
    while not networkx.is_connected(g):
        g = networkx.binomial_graph(n, 0.5)
    return g.nodes(), g.edges()
Пример #36
0
"""
Created on Fri Dec 20 13:26:58 2019

@author: tangu
"""

import networkx as nx
import matplotlib.pyplot as plt

n = 100
pIteration = 100
probabilities = []
clusterSize = []
maxDegree = []

G = nx.binomial_graph(100,1)
nx.draw(G,with_labels=True, font_weight='bold')


for i in range(0,pIteration):
    probabilities.append([])
    clusterSize.append([])
    maxDegree.append([])
print(probabilities)
for i in range(0,100) :
    print(i)
    for tempP in range(0,pIteration) :
        p = tempP/(pIteration*10)
        probabilities[tempP].append(p)
        G = nx.binomial_graph(n,p)
        Gc = max(nx.connected_component_subgraphs(G), key=len)
import networkx as nx
import random
import pickle

numberOfNodes = 50
numberOfRouters = 15
edgeProbability = 0.1
budget=32

connected = False
while (connected == False):
    randomGraph = nx.binomial_graph(numberOfNodes, edgeProbability)
    connected = nx.is_connected(randomGraph)

V_P = range(0, numberOfNodes)
V_L = random.sample(V_P, numberOfRouters)
E_P = randomGraph.edges()
C_P = dict()
for (u,v) in E_P:
    C_P[(u,v)] = 4

print E_P, "\n\n", V_P

myDictionary = dict()
myDictionary['B'] = budget
myDictionary['C_P'] = C_P
myDictionary['E_P'] = E_P
myDictionary['V_L'] = V_L
myDictionary['V_P'] = V_P

pickle.dump(myDictionary, open("save.p", "wb"))
Пример #38
0
import networkx as nx

def first_return_times(G,k):
	return_times = dict()

	# length = shortest path lengths <= k
	# length[i][j] = length of shortest path i->j, if <= k
        # length[i] a dict keyed by neighbors of node i, with values
        # length of path to j
	length = nx.all_pairs_shortest_path_length(G,k)
	for i in G.nodes_iter():
		# nodes = list of successors j which return to i
		nodes = filter(lambda j: length[j].has_key(i),G.successors(i))
		# distances for each successor j
		distances = [length[j][i]+1 for j in nodes]
		if distances:
			return_times[i] = min(distances)

	return return_times, length


if __name__ == "__main__":
	G = nx.binomial_graph(10,0.1,directed=True)
	d, ld = first_return_times(G,4) # return times <= 4
	print "return times", d
Пример #39
0
import networkx as nx

def print_g(G):
	for line in nx.generate_adjlist(G):
		print line
	print ""

ngames = 1
for i in range(0,ngames):
	n = 10
	#G = nx.fast_gnp_random_graph(n, 0.7, None, True)
	G = nx.binomial_graph(n, 0.3, None, True)
	print n # number of verts
	print_g(G) # left's game graph
	print n # number of verts
	print_g(G) # right's game graph
	print_g(G) # allowed moves for left
	print_g(G) # allowed moves for right
	print n # number of final states
	for i in range(0,n): # final states
		print i,
		print "",
		print i
	print ""
	print 0 # starting positions
	print 2
	print ""