示例#1
0
    def test_multi(self):

        vm = MultiPlot()

        g = nx.erdos_renyi_graph(1000, 0.1)
        model = epd.SIRModel(g)
        config = mc.Configuration()
        config.add_model_parameter('beta', 0.001)
        config.add_model_parameter('gamma', 0.01)
        config.add_model_parameter("percentage_infected", 0.05)
        model.set_initial_status(config)
        iterations = model.iteration_bunch(200)
        trends = model.build_trends(iterations)
        viz = DiffusionTrend(model, trends)
        p = viz.plot()

        vm.add_plot(p)

        g = nx.erdos_renyi_graph(1000, 0.1)
        model = epd.SIRModel(g)
        config = mc.Configuration()
        config.add_model_parameter('beta', 0.001)
        config.add_model_parameter('gamma', 0.01)
        config.add_model_parameter("percentage_infected", 0.05)
        model.set_initial_status(config)
        iterations = model.iteration_bunch(200)
        trends = model.build_trends(iterations)
        viz = DiffusionPrevalence(model, trends)
        p1 = viz.plot()

        vm.add_plot(p1)
        m = vm.plot()
        self.assertIsInstance(m, Column)
def synthetic_three_level(n,p1,p2,p3,J_isolates=False,F_isolates=False,D_isolates=False):#,isolate_up=True,isolate_down=True):
    
    k=n

    J=nx.erdos_renyi_graph(n,p1) #The first layer graph
    Jis = nx.isolates(J)
    F=nx.erdos_renyi_graph(n,p2) #The second layer graph
    Fis = nx.isolates(F)
    D=nx.erdos_renyi_graph(n,p3) #The third layer graph
    Dis = nx.isolates(D)

    def translation_graph(J,F,D):
        H1=nx.Graph()
        H2=nx.Graph()
        for i in range(n):
            H1.add_edges_from([(J.nodes()[i],F.nodes()[i])])
            H2.add_edges_from([(F.nodes()[i],D.nodes()[i])])
        return H1, H2

    Jed = set(J.edges())
    Fed = set(F.edges())
    Ded = set(D.edges())
    l=[Jed,Fed,Ded]
    lu = list(set.union(*l))
    JFD=nx.Graph()
    JFD.add_edges_from(lu)

    G=nx.Graph()  #The synthetic two-layer graph
    
    # Relabing nodes maps
    
    mappingF={}
    for i in range(2*n):
        mappingF[i]=n+i
    FF=nx.relabel_nodes(F,mappingF,copy=True)
    
    mappingD={}
    for i in range(2*n):
        if i >n-1:
            mappingD[i]=i-n
        else:
            mappingD[i]=2*n+i
    DD=nx.relabel_nodes(D,mappingD,copy=True)
    
    H1, HH2 = translation_graph(J,FF,DD)
    
    G.add_edges_from(J.edges())
    G.add_edges_from(H1.edges())
    G.add_edges_from(DD.edges())
    G.add_edges_from(HH2.edges())
    G.add_edges_from(FF.edges())

    edgeList = []
    for e in H1.edges():
        edgeList.append(e)
    for e in HH2.edges():
        edgeList.append(e)
    
    return G, J, FF, DD, JFD, edgeList  
示例#3
0
def test_strong_product():
    null=nx.null_graph()
    empty1=nx.empty_graph(1)
    empty10=nx.empty_graph(10)
    K2=nx.complete_graph(2)
    K3=nx.complete_graph(3)
    K5=nx.complete_graph(5)
    K10=nx.complete_graph(10)
    P2=nx.path_graph(2)
    P3=nx.path_graph(3)
    P5=nx.path_graph(5)
    P10=nx.path_graph(10)
    # null graph
    G=strong_product(null,null)
    assert_true(nx.is_isomorphic(G,null))
    # null_graph X anything = null_graph and v.v.
    G=strong_product(null,empty10)
    assert_true(nx.is_isomorphic(G,null))
    G=strong_product(null,K3)
    assert_true(nx.is_isomorphic(G,null))
    G=strong_product(null,K10)
    assert_true(nx.is_isomorphic(G,null))
    G=strong_product(null,P3)
    assert_true(nx.is_isomorphic(G,null))
    G=strong_product(null,P10)
    assert_true(nx.is_isomorphic(G,null))
    G=strong_product(empty10,null)
    assert_true(nx.is_isomorphic(G,null))
    G=strong_product(K3,null)
    assert_true(nx.is_isomorphic(G,null))
    G=strong_product(K10,null)
    assert_true(nx.is_isomorphic(G,null))
    G=strong_product(P3,null)
    assert_true(nx.is_isomorphic(G,null))
    G=strong_product(P10,null)
    assert_true(nx.is_isomorphic(G,null))

    G=strong_product(P5,K3)
    assert_equal(nx.number_of_nodes(G),5*3)
    G=strong_product(K3,K5)
    assert_equal(nx.number_of_nodes(G),3*5)

    #No classic easily found classic results for strong product

    G = nx.erdos_renyi_graph(10,2/10.)
    H = nx.erdos_renyi_graph(10,2/10.)
    GH = strong_product(G,H)

    for (u_G,u_H) in GH.nodes_iter():
        for (v_G,v_H) in GH.nodes_iter():
            if (u_G==v_G and H.has_edge(u_H,v_H)) or \
               (u_H==v_H and G.has_edge(u_G,v_G)) or \
               (G.has_edge(u_G,v_G) and H.has_edge(u_H,v_H)):
                assert_true(GH.has_edge((u_G,u_H),(v_G,v_H)))
            else:
                assert_true(not GH.has_edge((u_G,u_H),(v_G,v_H)))
示例#4
0
def create_list_of_adj_mats(n_runs):
    adj_mats = []
    for i in xrange(n_runs):
        # Creating connected adj matrix
        net = nx.erdos_renyi_graph(N, link_density)
        while len(list(nx.connected_components(net))) > 1:
            print "Network has isolated components. Try again!"
            net = nx.erdos_renyi_graph(N, link_density)
        adj_mats.append(nx.adj_matrix(net).toarray())

    return adj_mats
示例#5
0
def test_lexicographic_product_random():
    G = nx.erdos_renyi_graph(10,2/10.)
    H = nx.erdos_renyi_graph(10,2/10.)
    GH = lexicographic_product(G,H)

    for (u_G,u_H) in GH.nodes_iter():
        for (v_G,v_H) in GH.nodes_iter():
            if G.has_edge(u_G,v_G) or (u_G==v_G and H.has_edge(u_H,v_H)):
                assert_true(GH.has_edge((u_G,u_H),(v_G,v_H)))
            else:
                assert_true(not GH.has_edge((u_G,u_H),(v_G,v_H)))
示例#6
0
def test_tensor_product_random():
    G = nx.erdos_renyi_graph(10,2/10.)
    H = nx.erdos_renyi_graph(10,2/10.)
    GH = tensor_product(G,H)

    for (u_G,u_H) in GH.nodes_iter():
        for (v_G,v_H) in GH.nodes_iter():
            if H.has_edge(u_H,v_H) and G.has_edge(u_G,v_G):
                assert_true(GH.has_edge((u_G,u_H),(v_G,v_H)))
            else:
                assert_true(not GH.has_edge((u_G,u_H),(v_G,v_H)))
示例#7
0
def test_cartesian_product_random():
    G = nx.erdos_renyi_graph(10,2/10.)
    H = nx.erdos_renyi_graph(10,2/10.)
    GH = cartesian_product(G,H)

    for (u_G,u_H) in GH.nodes_iter():
        for (v_G,v_H) in GH.nodes_iter():
            if (u_G==v_G and H.has_edge(u_H,v_H)) or \
               (u_H==v_H and G.has_edge(u_G,v_G)):
                assert_true(GH.has_edge((u_G,u_H),(v_G,v_H)))
            else:
                assert_true(not GH.has_edge((u_G,u_H),(v_G,v_H)))
示例#8
0
def createBridge(numOfNodes, edgeProb, bridgeNodes):
	'''
	numOfNodes: Number of nodes in the clustered part of the Bridge Graph
	edgeProb: Probability of existance of an edge between any two vertices.
	bridgeNodes: Number of nodes in the bridge
	This function creates a Bridge Graph with 2 main clusters connected by a bridge.
	'''	
	print "Generating and Saving Bridge Network..."	
	G1 = nx.erdos_renyi_graph(2*numOfNodes + bridgeNodes, edgeProb) #Create an ER graph with number of vertices equal to twice the number of vertices in the clusters plus the number of bridge nodes.
	G = nx.Graph() #Create an empty graph so that it can be filled with the required components from G1
	G.add_edges_from(G1.subgraph(range(numOfNodes)).edges()) #Generate an induced subgraph of the nodes, ranging from 0 to numOfNodes, from G1 and add it to G
	G.add_edges_from(G1.subgraph(range(numOfNodes + bridgeNodes,2*numOfNodes + bridgeNodes)).edges()) #Generate an induced subgraph of the nodes, ranging from (numOfNodes + bridgeNodes) to (2*numOfNodes + bridgeNodes)

	A = random.randrange(numOfNodes) #Choose a random vertex from the first component
	B = random.randrange(numOfNodes + bridgeNodes,2*numOfNodes + bridgeNodes) #Choose a random vertex from the second component

	prev = A #creating a connection from A to B via the bridge nodes
	for i in range(numOfNodes, numOfNodes + bridgeNodes):
		G.add_edge(prev, i)
		prev = i
	G.add_edge(i, B)
	
	StrMap = {}
	for node in G.nodes():
		StrMap[node] = str(node)
	G = nx.convert.relabel_nodes(G,StrMap)
	filename = "BG_" + str(numOfNodes) + "_" + str(edgeProb) + "_" + str(bridgeNodes) + ".gpickle"
	nx.write_gpickle(G,filename)#generate a gpickle file of the learnt graph.
	print "Successfully written into " + filename
def compare_graphs(graph):
    n = nx.number_of_nodes(graph)
    m = nx.number_of_edges(graph)
    k = np.mean(list(nx.degree(graph).values()))
    erdos = nx.erdos_renyi_graph(n, p=m/float(n*(n-1)/2))
    barabasi = nx.barabasi_albert_graph(n, m=int(k)-7)
    small_world = nx.watts_strogatz_graph(n, int(k), p=0.04)
    print(' ')
    print('Compare the number of edges')
    print(' ')
    print('My network: ' + str(nx.number_of_edges(graph)))
    print('Erdos: ' + str(nx.number_of_edges(erdos)))
    print('Barabasi: ' + str(nx.number_of_edges(barabasi)))
    print('SW: ' + str(nx.number_of_edges(small_world)))
    print(' ')
    print('Compare average clustering coefficients')
    print(' ')
    print('My network: ' + str(nx.average_clustering(graph)))
    print('Erdos: ' + str(nx.average_clustering(erdos)))
    print('Barabasi: ' + str(nx.average_clustering(barabasi)))
    print('SW: ' + str(nx.average_clustering(small_world)))
    print(' ')
    print('Compare average path length')
    print(' ')
    print('My network: ' + str(nx.average_shortest_path_length(graph)))
    print('Erdos: ' + str(nx.average_shortest_path_length(erdos)))
    print('Barabasi: ' + str(nx.average_shortest_path_length(barabasi)))
    print('SW: ' + str(nx.average_shortest_path_length(small_world)))
    print(' ')
    print('Compare graph diameter')
    print(' ')
    print('My network: ' + str(nx.diameter(graph)))
    print('Erdos: ' + str(nx.diameter(erdos)))
    print('Barabasi: ' + str(nx.diameter(barabasi)))
    print('SW: ' + str(nx.diameter(small_world)))
示例#10
0
def createBridge(numOfNodes, edgeProb, bridgeNodes):
	'''
	numOfNodes: Number of nodes in the clustered part of the Bridge Graph
	edgeProb: Probability of existance of an edge between any two vertices.
	bridgeNodes: Number of nodes in the bridge
	This function creates a Bridge Graph with 2 main clusters connected by a bridge.
	'''
	G1 = nx.erdos_renyi_graph(2*numOfNodes + bridgeNodes, edgeProb) #Create an ER graph with number of vertices equal to twice the number of vertices in the clusters plus the number of bridge nodes.
	G = nx.Graph() #Create an empty graph so that it can be filled with the required components from G1
	G.add_edges_from(G1.subgraph(range(numOfNodes)).edges()) #Generate an induced subgraph of the nodes, ranging from 0 to numOfNodes, from G1 and add it to G
	G.add_edges_from(G1.subgraph(range(numOfNodes + bridgeNodes,2*numOfNodes + bridgeNodes)).edges()) #Generate an induced subgraph of the nodes, ranging from (numOfNodes + bridgeNodes) to (2*numOfNodes + bridgeNodes)

	A = random.randrange(numOfNodes) #Choose a random vertex from the first component
	B = random.randrange(numOfNodes + bridgeNodes,2*numOfNodes + bridgeNodes) #Choose a random vertex from the second component

	prev = A #creating a connection from A to B via the bridge nodes
	for i in range(numOfNodes, numOfNodes + bridgeNodes):
		G.add_edge(prev, i)
		prev = i
	G.add_edge(i, B)

	fout = open("BG_" + str(2*numOfNodes + bridgeNodes) + "_" + str(edgeProb) + ".graph", 'w') #create a file handler and open the corresponding file in write mode
	string = pickle.dumps(G) #Convert the generated graph into the string and store it into a file. It is later retrieved in the main module
	fout.write(string) #write the string into the file and close the file handler
	fout.close()
	print "Bridge Graph successfully generated and written into the file."
	print "File Name: ", "BG_" + str(2*numOfNodes + bridgeNodes) + "_" + str(edgeProb) + ".graph"
	print "Undergoing Machine Learning..."
	reinforce(G,"BG", edgeProb) #Enforce Machine Learning to generate two files
示例#11
0
def initialize_graph(size):
    points_x = []
    points_y = []
    terminals = []
    for i in range(size):
        points_x.append(random.uniform(-100, 100))
        points_y.append(random.uniform(-100, 100))
    for i in range(size):
        if i % 2 == 0:
            terminals.append(i)

    h = nx.erdos_renyi_graph(size, 0.3)
    g = nx.Graph()
    for i in range(size):
        g.add_node(i)

    for i in range(size):
        for j in range(i, size):
            if h.has_edge(i, j):
                g.add_edge(i, j)
                # weight=manhattan_distance((points_x[i], points_y[i]), (points_x[j], points_y[j])))

    length_shortest_paths = nx.all_pairs_dijkstra_path_length(g)
    shortest_paths = nx.all_pairs_shortest_path(g)

    metric_closure = nx.Graph()
    for i in range(size):
        metric_closure.add_node(i)
    for i in range(size):
        for j in range(size):
            metric_closure.add_edge(i, j, weight=length_shortest_paths[i][j])

    print metric_closure
    return (terminals, shortest_paths, metric_closure, points_x, points_y, g)
示例#12
0
def get_sim_setting() :
    g = nx.erdos_renyi_graph( 10, .3 )
    g = nx.connected_component_subgraphs( g )[0]
    
    roadnet = nx.MultiDiGraph()
    
    def roadmaker() :
        for i in itertools.count() : yield 'road%d' % i, np.random.exponential()
    road_iter = roadmaker()
    
    for i, ( u,v,data ) in enumerate( g.edges_iter( data=True ) ) :
        label, length = road_iter.next()
        roadnet.add_edge( u, v, label, length=length )
    
    
    rates = nx.DiGraph()
    ROADS = [ key for u,v,key in roadnet.edges_iter( keys=True ) ]
    for i in range(5) :
        r1 = random.choice( ROADS )
        r2 = random.choice( ROADS )
        if not rates.has_edge( r1, r2 ) :
            rates.add_edge( r1, r2, rate=0. )
        
        data = rates.get_edge_data( r1, r2 )
        data['rate'] += .25 * (1./5) * np.random.exponential()
        
    return roadnet, rates
    def test_dyn_node_stochastic(self):

        dg = dn.DynGraph()

        for t in past.builtins.xrange(0, 3):
            g = nx.erdos_renyi_graph(200, 0.05)
            dg.add_interactions_from(g.edges(), t)

        model = gc.DynamicCompositeModel(dg)

        model.add_status("Susceptible")
        model.add_status("Infected")
        model.add_status("Removed")

        c1 = cpm.NodeStochastic(0.02, "Infected")
        c2 = cpm.NodeStochastic(0.01)
        c3 = cpm.NodeStochastic(0.5)

        model.add_rule("Susceptible", "Infected", c1)
        model.add_rule("Infected", "Removed", c2)
        model.add_rule("Infected", "Susceptible", c3)

        config = mc.Configuration()
        config.add_model_parameter('percentage_infected', 0.1)

        model.set_initial_status(config)
        iterations = model.execute_snapshots()
        self.assertEqual(len(iterations), 3)

        iterations = model.execute_iterations()
        trends = model.build_trends(iterations)
        self.assertEqual(len(trends[0]['trends']['status_delta'][1]),
                         len([x for x in dg.stream_interactions() if x[2] == "+"]))
示例#14
0
def spread_size_distribution_vs_time():

    probabilities = [float(i) / 10. for i in range(2, 7)]

    graph = sm.SISModel.get_opera_graph()
    seed = sm.SISModel.get_random_seed(graph, 100)
    for t in [1, 5, 10]:
        time_series = []
        for i in xrange(len(probabilities)):
            model = sm.SISModel(graph, seed, probabilities[i], t, True, 100)
            model.spread()
            time_series.append(model.get_time_series())
        print(time_series)
        sm.SISModel.plot_spread_size_distribution(
            xrange(len(time_series[0])),
            time_series,
            ['blue', 'red', 'green', 'orange', 'black'],
            sm.SISModel.get_data_dir()
            + sm.SISModel.RESULT_DIR
            + 'o_spread_size_distribution_time_series_t{}.png'.format(str(t)),
            't, steps'
        )

    graph = nx.barabasi_albert_graph(4604, 11)
    seed = sm.SISModel.get_random_seed(graph, 100)
    for t in [1, 5, 10]:
        time_series = []
        for i in xrange(len(probabilities)):
            model = sm.SISModel(graph, seed, probabilities[i], t, True, 100)
            model.spread()
            time_series.append(model.get_time_series())
        print(time_series)
        sm.SISModel.plot_spread_size_distribution(
            xrange(len(time_series[0])),
            time_series,
            ['blue', 'red', 'green', 'orange', 'black'],
            sm.SISModel.get_data_dir()
            + sm.SISModel.RESULT_DIR
            + 'ba_spread_size_distribution_time_series_t{}.png'.format(str(t)),
            't, steps'
        )

    graph = nx.erdos_renyi_graph(4604, 0.0047)
    seed = sm.SISModel.get_random_seed(graph, 100)
    for t in [1, 5, 10]:
        time_series = []
        for i in xrange(len(probabilities)):
            model = sm.SISModel(graph, seed, probabilities[i], t, True, 100)
            model.spread()
            time_series.append(model.get_time_series())
        print(time_series)
        sm.SISModel.plot_spread_size_distribution(
            xrange(len(time_series[0])),
            time_series,
            ['blue', 'red', 'green', 'orange', 'black'],
            sm.SISModel.get_data_dir()
            + sm.SISModel.RESULT_DIR
            + 'er_spread_size_distribution_time_series_t{}.png'.format(str(t)),
            't, steps'
        )
示例#15
0
def spread_size_distribution_vs_probability():
    probabilities = [float(i) / 100. for i in range(100)]
    t = 1

    graph = sm.SISModel.get_opera_graph()
    seed = sm.SISModel.get_random_seed(graph, 100)
    print(seed)
    o_sizes = []

    for i in xrange(len(probabilities)):
        print(probabilities[i])
        o_sizes.append(sm.SISModel(graph, seed, probabilities[i], t).spread())
    print(o_sizes)

    graph = nx.barabasi_albert_graph(4604, 11)
    seed = sm.SISModel.get_random_seed(graph, 100)
    ba_sizes = []
    for i in xrange(len(probabilities)):
        ba_sizes.append(sm.SISModel(graph, seed, probabilities[i], t).spread())
    print(ba_sizes)

    graph = nx.erdos_renyi_graph(4604, 0.0047)
    seed = sm.SISModel.get_random_seed(graph, 100)
    er_sizes = []
    for i in xrange(len(probabilities)):
        er_sizes.append(sm.SISModel(graph, seed, probabilities[i], t).spread())
    print(er_sizes)

    sm.SISModel.plot_spread_size_distribution(
        probabilities,
        [o_sizes, ba_sizes, er_sizes],
        ['blue', 'black', 'red'],
        sm.SISModel.get_data_dir() + sm.SISModel.RESULT_DIR + 'spread_size_distribution.png',
        'p'
    )
 def __init__(self, name, para1, para2):
     if name == "PAM":
         # nodes, edges, and nodes > edges
         self.G = nx.barabasi_albert_graph(para1, para2)
         # nodes, prob
     elif name == "ER":
         self.G = nx.erdos_renyi_graph(para1, para2)
    def __init__(self, size, probability):
        self.size = size
        self.probability = probability
        self.network = nx.erdos_renyi_graph(self.size, self.probability, directed=False)

        # Network stats object
        self.networkStats = Networkstats(self.network, self.size)
示例#18
0
def get_sim_setting( N=10, p=.3, mu=1., K=5, lam=1. ) :
    """
    get largest connected component of Erdos(N,p) graph
    with exponentially distr. road lengths (avg. mu);
    Choose k road pairs randomly and assign intensity randomly,
    exponential lam
    """
    g = nx.erdos_renyi_graph( N, p )
    g = nx.connected_component_subgraphs( g )[0]
    
    roadnet = nx.MultiDiGraph()
    
    def roadmaker() :
        for i in itertools.count() : yield 'road%d' % i, np.random.exponential( mu )
    road_iter = roadmaker()
    
    for i, ( u,v,data ) in enumerate( g.edges_iter( data=True ) ) :
        label, length = road_iter.next()
        roadnet.add_edge( u, v, label, length=length )
    
    rates = nx.DiGraph()
    ROADS = [ key for u,v,key in roadnet.edges_iter( keys=True ) ]
    for i in range( K ) :
        r1 = random.choice( ROADS )
        r2 = random.choice( ROADS )
        if not rates.has_edge( r1, r2 ) :
            rates.add_edge( r1, r2, rate=0. )
        
        data = rates.get_edge_data( r1, r2 )
        data['rate'] += np.random.exponential( lam )
        
    return roadnet, rates
示例#19
0
def generate_graph(n, expected_degree, model="ba"):
    """
    Generates a graph with a given model and expected_mean
    degree

    :param n: int Number of nodes of the graph
    :param expected_degree: int Expected mean degree
    :param model: string Model (ba, er, or ws)
    :return: networkx graph
    """

    global m
    global ws_p

    g = None
    if model == "ba":
        # BA expected avg. degree? m = ba_mean_degrees()
        if m is None:
            m = ba_mean_degrees(n, expected_degree)
        g = nx.barabasi_albert_graph(n, m, seed=None)
    if model == "er":
        # ER expected avg. degree: d = p*(n-1)
        p = float(expected_degree) / float(n - 1)
        g = nx.erdos_renyi_graph(n, p, seed=None, directed=False)
    if model == "ws":
        # WS expected degree == k
        g = nx.watts_strogatz_graph(n, expected_degree, ws_p)

    return g
def generateRandomNetworks(randomSeed=622527):
    seed(randomSeed)
    # Network size will be 10^1, 10 ^2, 10^3, 10^4
    for exponent in range(1, 4): # 1 .. 4
        n = 10 ** exponent

        for p in [0.1, 0.3, 0.5, 0.7, 0.9]:
            m = round(n * p)

            # Generate erdos Renyi networks
            graph = nx.erdos_renyi_graph(n, p, randomNum())
            graphName = "erdos_renyi_n{}_p{}.graph6".format(n, p)
            nx.write_graph6(graph, directory + graphName)

            # Generate Barabasi Albert networks
            graph = nx.barabasi_albert_graph(n, m, randomNum())
            graphName = "barabasi_albert_n{}_m{}.graph6".format(n, m)
            nx.write_graph6(graph, directory + graphName)

            for k in [0.1, 0.3, 0.5, 0.7, 0.9]:
                k = round(n * k)
                # Generate Watts Strogatz networks
                graph = nx.watts_strogatz_graph(n, k, p, randomNum())
                graphName = "watts_strogatz_n{}_k{}_p{}.graph6".format(n, k, p)
                nx.write_graph6(graph, directory + graphName)
示例#21
0
文件: model.py 项目: bangtree/mesa
    def __init__(self, num_nodes=10, avg_node_degree=3, initial_outbreak_size=1, virus_spread_chance=0.4,
                virus_check_frequency=0.4, recovery_chance=0.3, gain_resistance_chance=0.5):

        self.num_nodes = num_nodes
        prob = avg_node_degree / self.num_nodes
        self.G = nx.erdos_renyi_graph(n=self.num_nodes, p=prob)
        self.grid = NetworkGrid(self.G)
        self.schedule = RandomActivation(self)
        self.initial_outbreak_size = initial_outbreak_size if initial_outbreak_size <= num_nodes else num_nodes
        self.virus_spread_chance = virus_spread_chance
        self.virus_check_frequency = virus_check_frequency
        self.recovery_chance = recovery_chance
        self.gain_resistance_chance = gain_resistance_chance

        self.datacollector = DataCollector({"Infected": number_infected,
                                            "Susceptible": number_susceptible,
                                            "Resistant": number_resistant})

        # Create agents
        for i, node in enumerate(self.G.nodes()):
            a = VirusAgent(i, self, State.SUSCEPTIBLE, self.virus_spread_chance, self.virus_check_frequency,
                           self.recovery_chance, self.gain_resistance_chance)
            self.schedule.add(a)
            # Add the agent to the node
            self.grid.place_agent(a, node)

        # Infect some nodes
        infected_nodes = self.random.sample(self.G.nodes(), self.initial_outbreak_size)
        for a in self.grid.get_cell_list_contents(infected_nodes):
            a.state = State.INFECTED

        self.running = True
        self.datacollector.collect(self)
def init():
    global op1, op2, grouping, network, adj_mat
    op1 = [(-1 + 2 * random.random()) for agents in range(no_of_agents)]
    op2 = [(-1 + 2 * random.random()) for agents in range(no_of_agents)]
    grouping = [random.randint(1,m) for agents in range(no_of_agents)]
    network = nx.erdos_renyi_graph(no_of_agents,p)
    adj_mat = nx.adjacency_matrix(network)
 def test_bad_graph_input(self) :
     """modularity is only defined with undirected graph"""
     g = nx.erdos_renyi_graph(50, 0.1, directed=True)
     part = dict([])
     for node in g :
         part[node] = 0
     self.assertRaises(TypeError, co.modularity, part, g)
示例#24
0
def get_random_graph():
    G = nx.erdos_renyi_graph(100, 0.1)
    H = nx.Graph()
    for u,v in G.edges():
        d = random.uniform(1,10)
        H.add_edge(u, v, weight=d)
    return H
示例#25
0
def gen_erdos(n,m):
    """
    The expected number of edges in an Erdos-Renyi graph
    is m = p*n*(n-1)/2
    """
    p = 2*m/(n*(n-1))
    return nx.erdos_renyi_graph(n,p,directed=True)
示例#26
0
def q1():
  lada = nx.read_gml("../../data/network_analysis/LadaFacebookAnon.gml")
  print_stats(lada, "LadaFacebookAnon")
  p = compute_edge_creation_probability(
    lada.number_of_nodes(), lada.number_of_edges())
  erg = nx.erdos_renyi_graph(lada.number_of_nodes(), p)
  print_stats(erg, "Erdos-Renyi Random")
示例#27
0
def q2():
  gnutella = read_gdf("../../data/network_analysis/gnutella2.gdf")
  print_stats(gnutella, "Gnutella")
  p = compute_edge_creation_probability(
    gnutella.number_of_nodes(), gnutella.number_of_edges())
  erg = nx.erdos_renyi_graph(gnutella.number_of_nodes(), p)
  print_stats(erg, "Erdos-Renyi Random")
示例#28
0
def test_directed_havel_hakimi():
    # Test range of valid directed degree sequences
    n, r = 100, 10
    p = 1.0 / r
    for i in range(r):
        G1 = nx.erdos_renyi_graph(n, p * (i + 1), None, True)
        din1 = list(d for n, d in G1.in_degree())
        dout1 = list(d for n, d in G1.out_degree())
        G2 = nx.directed_havel_hakimi_graph(din1, dout1)
        din2 = list(d for n, d in G2.in_degree())
        dout2 = list(d for n, d in G2.out_degree())
        assert_equal(sorted(din1), sorted(din2))
        assert_equal(sorted(dout1), sorted(dout2))

    # Test non-graphical sequence
    dout = [1000, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
    din = [103, 102, 102, 102, 102, 102, 102, 102, 102, 102]
    assert_raises(nx.exception.NetworkXError,
                  nx.directed_havel_hakimi_graph, din, dout)
    # Test valid sequences
    dout = [1, 1, 1, 1, 1, 2, 2, 2, 3, 4]
    din = [2, 2, 2, 2, 2, 2, 2, 2, 0, 2]
    G2 = nx.directed_havel_hakimi_graph(din, dout)
    dout2 = (d for n, d in G2.out_degree())
    din2 = (d for n, d in G2.in_degree())
    assert_equal(sorted(dout), sorted(dout2))
    assert_equal(sorted(din), sorted(din2))
    # Test unequal sums
    din = [2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
    assert_raises(nx.exception.NetworkXError,
                  nx.directed_havel_hakimi_graph, din, dout)
    # Test for negative values
    din = [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, -2]
    assert_raises(nx.exception.NetworkXError,
                  nx.directed_havel_hakimi_graph, din, dout)
示例#29
0
def sampleroadnet( n=10, p=.3, n_oneway=0 ) :
    # based on Erdos Renyi ; n=# of nodes, p=probability any two nodes are linked
    g = nx.erdos_renyi_graph( n, p )
    # ...then just get the biggest connected component
    g = nx.connected_component_subgraphs( g )[0]
    
    # create a roadnet with such connectivity and random street lengths
    roadnet = nx.MultiDiGraph()
    def roadmaker() :
        for i in itertools.count() : yield 'road%d' % i, np.random.exponential()
    road_iter = roadmaker()
    
    for i, ( u,v,data ) in enumerate( g.edges_iter( data=True ) ) :
        label, length = road_iter.next()
        roadnet.add_edge( u, v, label, length=length )
        
    # add some random one-way roads
    nodes = roadnet.nodes()
    for i in range( n_oneway ) :
        u = random.choice( nodes )
        v = random.choice( nodes )
        label, length = road_iter.next()
        roadnet.add_edge( u, v, label, length=length, oneway=True )
        
    return roadnet
示例#30
0
def iterated_test(seed=None, testparams=None, params=None):        
    import algorithms
    print 'Starting iterative replication test...'
    if seed == None:
        seed = npr.randint(1E6)
        print 'Setting random number generator seed: %d'%seed
        random.seed(seed)
        npr.seed(seed)
    if params == None:
        params = {}
    defparams = {'edge_edit_rate':[0.05, 0.05], 'node_edit_rate':[0.05, 0.05], 'verbose':False, }
    defparams.update(params)
    params = defparams
    print 'params'
    print params
    if testparams == None:
        testparams = {}
    if 'G' not in testparams:
        nn = 1000
        p  = 0.01
        G = nx.erdos_renyi_graph(nn, p)
        G.add_edges_from(nx.path_graph(nn).edges())
    else:
        G = testparams['G']
    alg = testparams.get('algorithm', algorithms.generate_graph)

    num_rounds = testparams.get('num_rounds', 10)
    print 'Round: 1. Initial graph ' + getattr(G, 'name', '_')
    for trial in xrange(2, num_rounds+1):
        new_G = alg(original=G, params=params)
        seed = npr.randint(1E6)
        print 'Round: %d. New seed: %d'%(trial,seed)
        random.seed(seed)
        npr.seed(seed)
    print 'PASSED'
示例#31
0
#usr/bin/env python
#-*- coding:UTF-8 -*-
#author@blue
#time:2019.07.31

#generate a graph and show

import numpy as np
import random
import networkx as nx
from IPython.display import Image
import matplotlib.pyplot as plt

# Generate the graph
n = 70
p = 0.2
G_erdos = nx.erdos_renyi_graph(n, p, seed=100)
# Plot the graph
plt.figure(figsize=(12, 8))
nx.draw(G_erdos, node_size=10)
fig = plt.gcf()
plt.show()
fig.savefig('a generate graph1.png', dpi=100)

print('that is generate graph and nice')
示例#32
0
def ER_graph(node_num, prob):  ## unweighted
    G = nx.erdos_renyi_graph(node_num, prob)
    adj = nx.to_numpy_matrix(G)
    adj = np.asarray(adj)
    #adj=adj+np.identity(node_num)
    return adj
示例#33
0
def basic_operation():
	# Create a graph.
	G = nx.Graph()

	# Nodes.
	G.add_node(1)
	G.add_nodes_from([2, 3])

	H = nx.path_graph(10)  # Creates a graph.
	G.add_nodes_from(H)
	G.add_node(H)

	#print('G.nodes =', G.nodes)
	print('G.nodes =', list(G.nodes))

	# Edges.
	G.add_edge(1, 2)
	e = (2, 3)
	G.add_edge(*e)  # Unpack edge tuple.

	G.add_edges_from([(1, 2), (1, 3)])

	G.add_edges_from(H.edges)

	#print('G.edges =', G.edges)
	print('G.edges =', list(G.edges))

	# Remove all nodes and edges.
	G.clear()

	#--------------------
	G.add_edges_from([(1, 2), (1, 3)])
	G.add_node(1)
	G.add_edge(1, 2)
	G.add_node('spam')  # Adds node 'spam'.
	G.add_nodes_from('spam')  # Adds 4 nodes: 's', 'p', 'a', 'm'.
	G.add_edge(3, 'm')

	print('G.number_of_nodes() =', G.number_of_nodes())
	print('G.number_of_edges() =', G.number_of_edges())

	# Set-like views of the nodes, edges, neighbors (adjacencies), and degrees of nodes in a graph.
	print('G.adj[1] =', list(G.adj[1]))  # or G.neighbors(1).
	print('G.degree[1] =', G.degree[1])  # The number of edges incident to 1.

	# Report the edges and degree from a subset of all nodes using an nbunch.
	# An nbunch is any of: None (meaning all nodes), a node, or an iterable container of nodes that is not itself a node in the graph.
	print("G.edges([2, 'm']) =", G.edges([2, 'm']))
	print('G.degree([2, 3]) =', G.degree([2, 3]))

	# Remove nodes and edges from the graph in a similar fashion to adding.
	G.remove_node(2)
	G.remove_nodes_from('spam')
	print('G.nodes =', list(G.nodes))
	G.remove_edge(1, 3)

	# When creating a graph structure by instantiating one of the graph classes you can specify data in several formats.
	G.add_edge(1, 2)
	H = nx.DiGraph(G)  # Creates a DiGraph using the connections from G.
	print('H.edges() =', list(H.edges()))

	edgelist = [(0, 1), (1, 2), (2, 3)]
	H = nx.Graph(edgelist)

	#--------------------
	# Access edges and neighbors.
	print('G[1] =', G[1])  # Same as G.adj[1].
	print('G[1][2] =', G[1][2])  # Edge 1-2.
	print('G.edges[1, 2] =', G.edges[1, 2])

	# Get/set the attributes of an edge using subscript notation if the edge already exists.
	G.add_edge(1, 3)
	G[1][3]['color'] = 'blue'
	G.edges[1, 2]['color'] = 'red'

	# Fast examination of all (node, adjacency) pairs is achieved using G.adjacency(), or G.adj.items().
	# Note that for undirected graphs, adjacency iteration sees each edge twice.
	FG = nx.Graph()
	FG.add_weighted_edges_from([(1, 2, 0.125), (1, 3, 0.75), (2, 4, 1.2), (3, 4, 0.375)])
	for n, nbrs in FG.adj.items():
		for nbr, eattr in nbrs.items():
			wt = eattr['weight']
			if wt < 0.5: print(f'({n}, {nbr}, {wt:.3})')

	# Convenient access to all edges is achieved with the edges property.
	for (u, v, wt) in FG.edges.data('weight'):
		if wt < 0.5: print(f'({u}, {v}, {wt:.3})')

	#--------------------
	# Attributes.

	# Graph attributes.
	G = nx.Graph(day='Friday')
	print('G.graph =', G.graph)

	G.graph['day'] = 'Monday'

	# Node attributes: add_node(), add_nodes_from(), or G.nodes.
	G.add_node(1, time='5pm')
	G.add_nodes_from([3], time='2pm')
	print('G.nodes[1] =', G.nodes[1])
	G.nodes[1]['room'] = 714
	print('G.nodes.data() =', G.nodes.data())

	# Edge attributes: add_edge(), add_edges_from(), or subscript notation.
	G.add_edge(1, 2, weight=4.7)
	G.add_edges_from([(3, 4), (4, 5)], color='red')
	G.add_edges_from([(1, 2, {'color': 'blue'}), (2, 3, {'weight': 8})])
	G[1][2]['weight'] = 4.7
	G.edges[3, 4]['weight'] = 4.2
	print('G.edges.data() =', G.edges.data())

	#--------------------
	# Directed graphs.

	DG = nx.DiGraph()
	DG.add_weighted_edges_from([(1, 2, 0.5), (3, 1, 0.75)])
	print("DG.out_degree(1, weight='weight') =", DG.out_degree(1, weight='weight'))
	print("DG.degree(1, weight='weight') =", DG.degree(1, weight='weight'))  # The sum of in_degree() and out_degree().
	print('DG.successors(1) =', list(DG.successors(1)))
	print('DG.neighbors(1) =', list(DG.neighbors(1)))

	# Convert G to undirected graph.
	#H = DG.to_undirected()
	H = nx.Graph(DG)

	#--------------------
	# Multigraphs: Graphs which allow multiple edges between any pair of nodes.

	MG = nx.MultiGraph()
	#MDG = nx.MultiDiGraph()
	MG.add_weighted_edges_from([(1, 2, 0.5), (1, 2, 0.75), (2, 3, 0.5)])
	print("MG.degree(weight='weight') =", dict(MG.degree(weight='weight')))

	GG = nx.Graph()
	for n, nbrs in MG.adjacency():
			for nbr, edict in nbrs.items():
				minvalue = min([d['weight'] for d in edict.values()])
				GG.add_edge(n, nbr, weight = minvalue)
	print('nx.shortest_path(GG, 1, 3) =', nx.shortest_path(GG, 1, 3))

	#--------------------
	# Classic graph operations:

	"""
	subgraph(G, nbunch):		induced subgraph view of G on nodes in nbunch
	union(G1,G2):				graph union
	disjoint_union(G1,G2):		graph union assuming all nodes are different
	cartesian_product(G1,G2):	return Cartesian product graph
	compose(G1,G2):				combine graphs identifying nodes common to both
	complement(G):				graph complement
	create_empty_copy(G):		return an empty copy of the same graph class
	to_undirected(G):			return an undirected representation of G
	to_directed(G):				return a directed representation of G
	"""

	#--------------------
	# Graph generators.

	# Use a call to one of the classic small graphs:
	petersen = nx.petersen_graph()
	tutte = nx.tutte_graph()
	maze = nx.sedgewick_maze_graph()
	tet = nx.tetrahedral_graph()

	# Use a (constructive) generator for a classic graph:
	K_5 = nx.complete_graph(5)
	K_3_5 = nx.complete_bipartite_graph(3, 5)
	barbell = nx.barbell_graph(10, 10)
	lollipop = nx.lollipop_graph(10, 20)

	# Use a stochastic graph generator:
	er = nx.erdos_renyi_graph(100, 0.15)
	ws = nx.watts_strogatz_graph(30, 3, 0.1)
	ba = nx.barabasi_albert_graph(100, 5)
	red = nx.random_lobster(100, 0.9, 0.9)

	#--------------------
	# Read a graph stored in a file using common graph formats, such as edge lists, adjacency lists, GML, GraphML, pickle, LEDA and others.

	nx.write_gml(red, 'path.to.file')
	mygraph = nx.read_gml('path.to.file')
示例#34
0
文件: lab5.py 项目: BK874/CS1656-Labs
    for node in graph.nodes():
        if graph.degree(node) > maxDegree:
            maxDegree = graph.degree(node)
        if graph.degree(node) < minDegree:
            minDegree = graph.degree(node)
    print("Max graph", num, "degree:", maxDegree)
    print("Min graph", num, "degree:", minDegree)
    return [minDegree, maxDegree]

# Task 1: Given code generating three graphs, compute the degree for each node and
# report the highest and lowest degree over all nodes for each graph
graph1 = nx.barabasi_albert_graph(30, 4)
nx.draw(graph1, with_labels=True)
plt.show()

graph2 = nx.erdos_renyi_graph(30, 0.15)
nx.draw(graph2, with_labels=True)
plt.show()

graph3 = nx.complete_bipartite_graph(3, 5)
nx.draw(graph3, with_labels=True)
plt.show()

minMaxDegree(graph1, 1)
minMaxDegree(graph2, 2)
minMaxDegree(graph3, 3)

# Task 2: Create a directional graph with 5 nodes, 10 edges, and at least
# one node with a single outgoing edge and no incoming edges
DG = nx.DiGraph()
newnodes = (1,2,3,4,5)
示例#35
0
 def setUp(self) -> None:
     self.graphs = [
         nx.erdos_renyi_graph(1000, 0.2),
         nx.erdos_renyi_graph(1000, 0.5)
     ]
示例#36
0
def randomGraphErdos(N, P):
    G = nx.erdos_renyi_graph(N, P)
    while (nx.is_connected(G) != True):
        G = nx.erdos_renyi_graph(N, P)
    return G
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
from sklearn.cluster import KMeans, AgglomerativeClustering, SpectralClustering
import community as community_louvain

G = nx.erdos_renyi_graph(100, 0.5)


def spectralPartitioning(G, n=None, **kwargs):
    mat = nx.to_numpy_matrix(G)
    if n is None:
        model = SpectralClustering(affinity="precomputed", **kwargs)
    else:
        model = SpectralClustering(n, affinity="precomputed", **kwargs)
    fit = model.fit(mat)
    return {n: fit.labels_[i] for i, n in enumerate(G.nodes())}


def hierarchicalPartitioning(G, n=None, **kwargs):
    mat = nx.to_numpy_matrix(G)
    if n is None:
        model = AgglomerativeClustering(**kwargs)
    else:
        model = AgglomerativeClustering(n, **kwargs)
    fit = model.fit(mat)
    return {n: fit.labels_[i] for i, n in enumerate(G.nodes())}


def kMeansPartitioning(G, n, **kwargs):
    mat = nx.to_numpy_matrix(G)
def get_Erdos_Renyi(Nodes, density):

    G = nx.erdos_renyi_graph(Nodes, density)
    return (G)
示例#39
0
def create_ER_bipartite_graph(N, p):
    g = nx.erdos_renyi_graph(N, p)
    alist = g.degree().values()
    blist = create_blist(alist)
    return nx.bipartite.configuration_model(alist, blist.astype(int))
示例#40
0
import networkx as nx
import numpy as np

n = 2**10
#n=10
cnct_prob = 4 / n
G = nx.erdos_renyi_graph(n, cnct_prob)
edge_list = []
for line in nx.generate_edgelist(G, data=False):
    edge_list.append(line)
#nx.write_edgelist(graph,"input_matrix.txt")

f = open('input_matrix.txt', 'w')
time = 0
times = []
for i in range(2 * n):
    #print (i)
    time += np.random.exponential(1)
    times.append(time)
    edge = np.random.choice(edge_list)
    #string = str(i) + ": " + edge + ' ' +str(time) + '\n'
    string = edge + ' ' + str(time) + '\n'
    print(string)
    f.write(string)

times = np.array(times)
#diffs = np.diff(times)
m = np.mean(times)
s = np.std(times)
b = (s - m) / (s + m)
print(b)
示例#41
0
generate.py a program to generate a random graph's exponential.

Usage:
    python generate.py number_of_nodes matrix_file exponential_file
"""
from sys import argv
from networkx import erdos_renyi_graph, to_scipy_sparse_matrix
from scipy.linalg import funm
from scipy.io import mmwrite
from scipy.sparse import csr_matrix
from numpy import exp

###############################################################################
if __name__ == "__main__":
    # Generate a random directed graph
    nodes = int(argv[1])
    prob = 0.05
    graph = erdos_renyi_graph(nodes, prob, directed=True)
    matrix = to_scipy_sparse_matrix(graph).todense()
    for i in range(0, matrix.shape[0]):
        for j in range(0, matrix.shape[1]):
            if matrix[i, j] != 0 and matrix[j, i] != 0:
                matrix[i, j] = 0

    # Compute The Exponential
    emat = funm(matrix, lambda x: exp(x))

    # Write To File
    mmwrite(argv[2], csr_matrix(matrix * 1.0))
    mmwrite(argv[3], csr_matrix(emat))
示例#42
0

V, N, K = get_args()

seed = 3
np.random.seed(seed)

name = "adjacency-N{}-K{}".format(V, K)

with h5py.File('data/' + name + '.h5', 'w') as h5_file:

    feature_shape = (2 * N, V, V)

    labels_shape = (2 * N, )
    features_df = h5_file.create_dataset('features', shape=feature_shape)
    labels_df = h5_file.create_dataset('labels', shape=labels_shape)

    data = []
    labels = []
    for n in tqdm(range(2 * N)):
        g = nx.erdos_renyi_graph(V, 0.5, seed=seed * n)
        print list(g.edges)

        if n < N:
            labels_df[n] = 0
        else:
            add_random_k_clique(g, K)  # Add K clique in the graph
            labels_df[n] = 1

        features_df[n] = nx.adjacency_matrix(g).todense()
示例#43
0
#!/usr/bin/python

import networkx as nx
import random

import sys

r = random

G = nx.erdos_renyi_graph(int(sys.argv[1]), float(sys.argv[2]),
                         int(sys.argv[3]))
nx.write_adjlist(G, "tmp")
"""edges=G.edges()
for edge in edges:
    ran=r.randint(0,1)   
    (u,v)=edge
    if ran==0:
        G.remove_edge(u,v)
    else:
        G.remove_edge(v,u)"""
g = nx.read_adjlist("tmp", create_using=nx.DiGraph())
C = nx.condensation(g)

nx.write_adjlist(C, "erg")

#G=nx.powerlaw_cluster_graph(100000,200,0.3)
#nx.write_adjlist(G, "powerlowc")
    # Calculate the degree of each node: G.node[n]['degree']
    G.node[n]['degree'] = nx.degree(G, n)

# Create the CircosPlot object: c
# c = CircosPlot(G, node_order='degree',
#                node_grouping='grouping', node_color='grouping')
c = CircosPlot(G, node_order='degree')

# Draw the CircosPlot object to the screen
c.draw()
plt.show()
 """

################# Finding Cliques
G = nx.erdos_renyi_graph(n=57, p=0.67, seed=123)

# Calculate the maximal cliques in G: cliques
cliques = nx.find_cliques(G)

# Count and print the number of maximal cliques in G
print(len(list(cliques)))

# Plotting the cliques
# Find the nodes that are part of the largest maximal clique: largest_clique
largest_clique = sorted(nx.find_cliques(G), key=lambda x: len(x))[-1]
print(len(largest_clique))
# Create the subgraph of the largest_clique: G_lc
G_lc = G.subgraph(largest_clique)

# Create the CircosPlot object: c
示例#45
0
if args.dump:
    results_dir = r'results/mutualistic/' + args.network
    makedirs(results_dir)

# Build network # A: Adjacency matrix, L: Laplacian Matrix,  OM: Base Operator
n = args.n  # e.g nodes number 400
N = int(np.ceil(np.sqrt(n)))  # grid-layout pixels :20
seed = args.seed
if args.network == 'grid':
    print("Choose graph: " + args.network)
    A = grid_8_neighbor_graph(N)
    G = nx.from_numpy_array(A.numpy())
elif args.network == 'random':
    print("Choose graph: " + args.network)
    G = nx.erdos_renyi_graph(n, 0.1, seed=seed)
    G = networkx_reorder_nodes(G, args.layout)
    A = torch.FloatTensor(nx.to_numpy_array(G))
elif args.network == 'power_law':
    print("Choose graph: " + args.network)
    G = nx.barabasi_albert_graph(n, 5, seed=seed)
    G = networkx_reorder_nodes(G, args.layout)
    A = torch.FloatTensor(nx.to_numpy_array(G))
elif args.network == 'small_world':
    print("Choose graph: " + args.network)
    G = nx.newman_watts_strogatz_graph(400, 5, 0.5, seed=seed)
    G = networkx_reorder_nodes(G, args.layout)
    A = torch.FloatTensor(nx.to_numpy_array(G))
elif args.network == 'community':
    print("Choose graph: " + args.network)
    n1 = int(n / 3)
示例#46
0
def Plague(G=None,
           Gtype='erdos',
           erdosval=0.15,
           node_num=50,
           mode='Game',
           ethics='Good',
           difficulty='Brutal',
           starttype='random',
           starters=None,
           numstarters=4,
           vaccines='on',
           quarantines='on',
           antivax=0,
           vaxcost=100,
           startermoney=500,
           allowance=200,
           quarantinecost=300,
           beta=0.6,
           gamma=0.3,
           curechance=0,
           icost=50,
           dcost=50,
           ccost=300,
           zcost=400,
           betainc=0.02,
           gammadec=0.02,
           campchance=0.1):
    turnNum = 0
    money = startermoney
    gameOver = False
    if ((mode != 'Game' and mode != 'Simulation') or (Gtype != 'erdos')
            or (difficulty != 'Baby' and difficulty != 'Custom'
                and difficulty != 'Normal' and difficulty != 'Brutal'
                and difficulty != 'Mega Brutal' and difficulty != 'Impossible')
            or (starttype != 'random' and starttype != 'choice'
                and starttype != 'high degree')
            or (vaccines != 'on' and vaccines != 'off')
            or (quarantines != 'on' and quarantines != 'off')):
        raise Exception("Something is wrong with your inputs. ")
    if (starters != None):
        numstarters = len(starters)
    if (difficulty == 'Baby'):
        if (ethics == 'Good'):
            startermoney = 600
            allowance = 300
            vaxcost = 100
            quarantinecost = 300
            beta = 0.5
            gamma = 0.5
        if (ethics == 'Evil'):
            G = nx.erdos_renyi_graph(30, 0.25)
            startermoney = 600
            allowance = 300
    if (difficulty == 'Normal'):
        if (ethics == 'Good'):
            startermoney = 500
            allowance = 250
            beta = 0.5
            gamma = 0.25
        if (ethics == 'Evil'):
            G = nx.erdos_renyi_graph(40, 0.15)
            startermoney = 500
            allowance = 150
    if (difficulty == 'Brutal'):
        if (ethics == 'Good'):
            startermoney = 500
            allowance = 150
            beta = 0.6
            gamma = 0.25
        if (ethics == 'Evil'):
            G = nx.erdos_renyi_graph(40, 0.05)
            startermoney = 500
            allowance = 100

    if (G == None):
        G = nx.erdos_renyi_graph(node_num, erdosval)
    if (difficulty == 'Mega Brutal'):
        if (ethics == 'Good'):
            G = nx.erdos_renyi_graph(70, 0.08)
            startermoney = 500
            allowance = 100
            vaxcost = 100
            quarantinecost = 300
            beta = 0.75
            gamma = 0.1
            antivax = 0.2
            numstarters = 4
            starttype = 'random'
            campchance = 0.1
        # 4 random starters
        if (ethics == 'Evil'):
            G = nx.erdos_renyi_graph(70, 0.05)
            startermoney = 400
            allowance = 100
            icost = 50
            dcost = 50
            ccost = 300
            zcost = 400
            betainc = 0.02
            gammadec = 0.02
            numstarters = 3
            starttype = 'random'
    if (difficulty == 'Impossible'):
        if (ethics == 'Good'):
            G = nx.erdos_renyi_graph(70, 0.15)
            startermoney = 200
            allowance = 50
            vaxcost = 100
            quarantinecost = 300
            beta = 1
            gamma = 0.1
            antivax = 0.4
            numstarters = 6
            starttype = 'high degree'
            campchance = 0.1
        if (ethics == 'Evil'):
            G = nx.erdos_renyi_graph(70, 0.02)
            startermoney = 200
            allowance = 50
            icost = 50
            dcost = 50
            ccost = 300
            zcost = 400
            betainc = 0.02
            gammadec = 0.02
            numstarters = 1
            starttype = 'random'

    if (mode == 'Simulation'):
        vaccines = 'off'
        quarantines = 'off'
        ethics = 'Good'

    # numstarters
    z = np.zeros(G.number_of_nodes())

    # Tested all start types. Works.

    if (starttype == 'random'):
        #initialize z randomly
        a = random.sample(range(0, G.number_of_nodes()), numstarters)
        for i in a:
            z[i] = 1
        #print(z)
    elif (starttype == 'high degree'):
        count = copy.deepcopy(numstarters)
        finals = []
        eye = []
        jay = []
        for i in G.nodes():
            eye.append(i)
            jay.append(G.degree[i])
        #print(jay)
        while (count != 0):
            loc = jay.index(max(jay))
            finals.append(loc)
            #print(loc[0])
            jay[loc] = -1
            count -= 1
            #print(count)
            #print(jay)
        for i in finals:
            #print(i)
            z[i] = 1
        #print(z)
        #print(jay)
    elif (starttype == 'choice'):
        for i in starters:
            z[i] = 1
        #print(z)

    def Menu():
        if (ethics == 'Good'):
            print('Turn number - ' + str(turnNum))
            print('Money - ' + str(money))
            print('\nCommands: ')
            print('N - Visualize netwulf representation')
            if (quarantines == 'on'):
                print('Q - Quarantine a node')
            if (vaccines == 'on'):
                print('V - Vaccinate a node')
            print('P - Progress to the next turn')
            print('H - View the help menu')
            print('E - Exit the game')
        elif (ethics == 'Evil'):
            print('Turn number - ' + str(turnNum))
            print('Money - ' + str(money))
            print('\nCommands: ')
            print('N - Visualize netwulf representation')
            print('I - Make your disease more infectious')
            print('D - Make your disease less deadly')
            print('C - Create an anti-vaxx marketing campaign')
            print('Z - Infect a node')
            print('P - Progress to the next turn')
            print('H - View the help menu')
            print('E - Exit the game')
        else:
            raise Exception("ethics is not correctly specified.")
        inp = input()
        return (inp)

    while (gameOver == False):  #start of a turn
        #print("are you looping")
        turnNum += 1
        money += allowance
        turnOver = False
        while (turnOver == False):
            inp = Menu()
            if (inp == 'N'):
                netwulf.visualize(zToG(G, z))
            elif (inp == 'P'):
                turnOver = True
            elif (inp == 'E'):
                raise Exception("You are a quitter.")
            elif (inp == 'H'):
                print("A few tips:")
                print(
                    "In the netwulf interface, press 'post to python' to exit. Otherwise it might glitch."
                )
                print(
                    "Green nodes are susceptible, yellow nodes are infected, and red nodes are dead."
                )
                print(
                    "Blue nodes are immune, black nodes are quarantined, and pink nodes are anti-vaxx."
                )
                print("Quarantined nodes update at the end of each turn.")
                print(
                    "More information can be found on the github page: https://github.com/thekadenh/betternx/"
                )
            if (ethics == 'Good'):
                if (inp == 'Q'):
                    yn = input(
                        str("Do you want to quarantine a node for $" +
                            str(quarantinecost) + "? (y/n)"))
                    if (yn == 'y'):
                        if (money >= quarantinecost):
                            money -= quarantinecost
                            q = input("Which node do you want to quarantine? ")
                            q = int(q)
                            zq = z[q]
                            if (zq == 2):
                                print(
                                    str(q) +
                                    " is literally dead. You're quarantining a dead person. Nice one."
                                )
                            if (zq == 3):
                                print(
                                    str(q) +
                                    " can't get the virus. No idea why you're quarantining it but you do you."
                                )
                            if (zq == 4):
                                print(
                                    "I mean... technically you CAN quarantine "
                                    + str(q) +
                                    " twice... It's not against the rules or anything..."
                                )
                            if (zq == 5):
                                print("Excellent choice")
                                z[q] = 4
                            else:
                                z[q] = 4
                        else:
                            print("Sorry, you're too poor")

                elif (inp == 'V'):
                    yn = input(
                        str("Do you want to vaccinate a node for $" +
                            str(vaxcost) + "? (y/n)"))
                    if (yn == 'y'):
                        if (money >= vaxcost):
                            money -= vaxcost
                            q = input("Which node do you want to vaccinate? ")
                            q = int(q)
                            zq = z[q]
                            if (zq == 1):
                                print(
                                    str(q) +
                                    " is already infected, dummy. Vaccination doesn't do anything at this point."
                                )
                            elif (zq == 2):
                                print(str(q) + "... They're dead.")
                            elif (zq == 3):
                                print("You make... questionable... decisions.")
                            elif (zq == 4):
                                print("They're quarantined.")
                            elif (zq == 5):
                                print(
                                    "They refuse, citing the 100% true nonrefutable fact that vaccinations cause autism."
                                )
                            else:
                                z[q] = 3
                        else:
                            print("Sorry, you're too poor")
            elif (ethics == 'Evil'):
                if (inp == 'I'):
                    yn = input(
                        str("Do you want to increase beta by " + str(betainc) +
                            " for $" + str(icost) + "? (y/n)"))
                    if (yn == 'y'):
                        if (money >= icost):
                            beta = beta + betainc
                            money -= icost
                        else:
                            print("Sorry, you're too poor")
                elif (inp == 'D'):
                    yn = input(
                        str("Do you want to decrease gamma by " +
                            str(gammadec) + " for $" + str(dcost) + "? (y/n)"))
                    if (yn == 'y'):
                        if (money >= dcost):
                            gamma = gamma - gammadec
                            money -= dcost
                        else:
                            print("Sorry, you're too poor")
                elif (inp == 'C'):
                    yn = input(
                        str("Do you want to fund an anti-vax campaign for $" +
                            str(ccost) + "? (y/n)"))
                    if (yn == 'y'):
                        if (money >= ccost):
                            money -= ccost
                            for i in G.nodes():
                                if (z[i] == 0):
                                    if (random.random() < campchance):
                                        z[i] == 5
                        else:
                            print("Sorry, you're too poor")

                elif (inp == 'Z'):
                    yn = input(
                        str("Do you want to infect ANY node for $" +
                            str(zcost) + "? (y/n)"))
                    if (yn == 'y'):
                        if (money >= zcost):
                            money -= zcost
                            nod = input(
                                str("Which node would you like to infect?"))
                            nod = int(nod)
                            znod = z[nod]
                            if (znod == 2):
                                print(
                                    "You brought back node " + str(nod) +
                                    " from the dead. The zombie apocalypse is imminent!"
                                )
                                z[nod] = 1
                            if (znod == 3):
                                print(
                                    "You used voodoo magic to anti-vaccinate node "
                                    + str(nod) + ".")
                                z[nod] = 1
                            if (znod == 4):
                                print("You successfully broke node " +
                                      str(nod) + " out of the quarantine!")
                                z[nod] = 1
                            if (znod == 5):
                                print(
                                    "I mean... node " + str(nod) +
                                    " basically wanted to get infected anyway")
                                z[nod] = 1
                            else:
                                z[nod] = 1
                        else:
                            print("Sorry, you're too poor")

        # at the end of the turn cycle through the quarantined ones and separate the edges.
#         bunch=[(1,2),(2,3)]
#         G.remove_edges_from(ebunch)
            if (turnOver == True):
                for i, j in enumerate(z):
                    if (j == 4):
                        for k in G.nodes():
                            G.remove_edges_from([(i, k)])
                #Then, run a cycle of the thingy
                z2 = copy.deepcopy(z)
                for i, j in enumerate(z):
                    if (j == 1):  # it's infected, time to spread!
                        for k in G.edges(i):
                            if (z[k[1]] == 0 or z[k[1]] == 5):
                                if (random.random() < beta):
                                    z2[k[1]] = 1
                        if (random.random() < gamma):
                            z2[i] = 2
                z = z2
                if not 1 in z:
                    gameOver = True
    #drawGz(G, z)
    sus = 0
    dead = 0
    recovered = 0
    qud = 0
    antvd = 0
    for i in z:
        if (i == 0):
            sus += 1
        if (i == 2):
            dead += 1
        if (i == 3):
            recovered += 1
        if (i == 4):
            qud += 1
        if (i == 5):
            antvd += 1
    print("Game over! Thanks for playing.")
    print(
        "I'm not going to tell you how well you did. That's for you to decide."
    )
    print("However, these stats may offer some insight.\n")
    print("# Susceptible: " + str(sus))
    print("# Dead: " + str(dead))
    print("# Vaccinated or recovered: " + str(recovered))
    print("# Quarantined: " + str(qud))
    print("# Alive Anti-vaxxers: " + str(antvd))
def genNet(n, k=4, pRewire=.1, type='grid'):
    # create net
    if type == 'grid':  #wrap the grid
        net = nx.grid_2d_graph(int(n**.5), int(n**.5), periodic=True)
        #net = nx.grid_2d_graph(3, 3, periodic=True)
        #net = nx.grid_2d_graph(2, 2, periodic=False)
        #plotNet(net)
        #print(len(net.edges()))
        #assert(0)
        # rewire
        numRewired = 0
        #while numRewired < (pRewire * nx.number_of_nodes(net)):
        while numRewired < 1:
            tries = 0
            while tries < 100:
                tries = tries + 1
                #print([numRewired, pRewire * nx.number_of_nodes(net), tries])
                v1 = random.choice(net.nodes())
                v2 = random.choice(net.nodes())
                if not (
                        net.has_edge(v1, v2) or v1 == v2
                        or len(net.neighbors(v1)) <= 1
                ):  #net.neighbors is sometimes (often?) a blank set, changed so v1 needs 2 nb
                    #print net.neighbors(v1)
                    break
            v1Neighbors = net.neighbors(v1)
            #print v1Neighbors
            #print v1
            #print v2
            #print(len(net.edges()))
            tobeDeleted = random.choice(v1Neighbors)
            net.remove_edge(v1, tobeDeleted)
            #print(len(net.edges()))
            #print([v1, tobeDeleted, v2])
            net.add_edge(v1, v2)
            numRewired = numRewired + 1
        #plotNet(net)
        #assert(0)
        return net, nx.to_numpy_matrix(net, dtype=np.float)

    elif type == 'smallworld':
        #net = nx.connected_watts_strogatz_graph(n, k, .15)
        net = nx.connected_watts_strogatz_graph(n, k, pRewire)
        return net, nx.to_numpy_matrix(net, dtype=np.float)
    elif type == 'pref':
        net = nx.barabasi_albert_graph(n, 2)
        return net, nx.to_numpy_matrix(net, dtype=np.float)
    elif type == 'ER':
        #net = nx.erdos_renyi_graph(n, .006)
        targetDegree = 4.
        nEdgesPossible = ((n * n) - n) / 2.
        pEdge = (n * targetDegree) / (2. * nEdgesPossible)
        assert (pEdge <= 1)

        # spare networks will likely be disconnected, so try a bunch
        tries = 100
        while tries > 0:
            net = nx.erdos_renyi_graph(n, pEdge)
            if nx.number_connected_components(net) > 1:
                tries = tries - 1
            else:
                break
        return net, nx.to_numpy_matrix(net, dtype=np.float)
示例#48
0
#         if not node_list.__contains__(r[2]):
#             node_list.append(r[2])

# print 'type of'
# print(type(test_file))
# print 'edge list'
# print edge_list
# print'#######'
# print(node_list)
n = 4  #len(node_list) # finding total nodes
p = 1

g = nx.read_edgelist(test_file,
                     delimiter=',',
                     nodetype=str,
                     create_using=nx.erdos_renyi_graph(n, p))

attr = {n: {"infected": False} for n in g.nodes()}
nx.set_node_attributes(g, attr)

#g.add_nodes_from(node_list) #NOT NEEDED
nx.draw(g, with_labels=True)
print(g.edges(data=True))

print '##########'
print 'Atrribute for one node'
#print(g.node['A']['infected'])
#print(g.node['P']['infected'])
print '#Atrribute for one node'  #'
#plt.draw()
#plt.show()
示例#49
0
import networkx as nx
import matplotlib.pyplot as plt
from textwrap import wrap
import json
import random

GRAPH_SIZE = 30
host_num = 1
short_paths = {}

graph = nx.erdos_renyi_graph(GRAPH_SIZE, 0.3)

while not nx.is_connected(graph):
    graph = nx.erdos_renyi_graph(GRAPH_SIZE, 0.3)

for s_node in range(GRAPH_SIZE):
    short_paths['s' + str(s_node + 1)] = {}

    for t_node in range(GRAPH_SIZE):
        paths = [path for path in nx.all_shortest_paths(graph, s_node, t_node)]
        short_paths['s' + str(s_node + 1)]['s' + str(t_node + 1)] = map(
            lambda x: map(lambda y: 's' + str(y + 1), x), paths)

ids = map(lambda x: 's' + str(x + 1), range(GRAPH_SIZE))
dpids = map(lambda x: ':'.join(wrap('%016x' % (x + 1), 2)), range(GRAPH_SIZE))

hosts = []
links = []
switches = map(
    lambda x: {
        "id": ids[x],
示例#50
0
xdata, ydata = [], []


def run(data):
    # update the data
    t, y = data
    xdata.append(t)
    ydata.append(y)
    xmin, xmax = ax.get_xlim()

    if t >= xmax:
        ax.set_xlim(xmin, 2*xmax)
        ax.figure.canvas.draw()
    line.set_data(xdata, ydata)

    return line,

ani = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=10,
                              repeat=False, init_func=init)
plt.show()




"""
Network graph
"""

G = nx.erdos_renyi_graph(50, 0.5)
nx.draw_spring(G, node_color='purple', node_size=200, edge_color='pink', width=2)
示例#51
0
plt.figure()
G = nx.complete_graph(10)
nx.draw(G)
plt.savefig("complete10.png")

plt.figure()
G = nx.complete_bipartite_graph(3, 100)
nx.draw(G)
plt.savefig("compbipartite.png")

plt.figure()
G = nx.barbell_graph(10, 10)
nx.draw(G)
plt.savefig("barbell.png")

plt.figure()
G = nx.lollipop_graph(10, 20)
nx.draw(G)
plt.savefig("lollipop.png")

plt.figure()
G = nx.karate_club_graph()
nx.draw(G)
plt.savefig("karate_club.png")

plt.figure()
G = nx.erdos_renyi_graph(500, 0.01)
nx.draw(G)
plt.savefig("erdos_renyi.png")
#plt.show()
示例#52
0
"""
Some rudimentary tests. Instantiates a Plot object, but doesn't test plotting.

Discovered that this set of rudimentary tests might be necessary after seeing
the following issue:

    https://github.com/ericmjl/nxviz/issues/160
"""

from random import random

import networkx as nx

from nxviz import ArcPlot, CircosPlot, GeoPlot, MatrixPlot

G = nx.erdos_renyi_graph(n=20, p=0.2)

G_geo = G.copy()
for n, d in G_geo.nodes(data=True):
    G_geo.node[n]['latitude'] = random()
    G_geo.node[n]['longitude'] = random()
    G_geo.node[n]['dpcapacity'] = random()


def test_circos_plot():
    c = CircosPlot(G)  # noqa: F841


def test_matrix_plot():
    m = MatrixPlot(G)  # noqa: F841
示例#53
0
def weights_allocation(A, Y):
    A_exp = expanded_adjacency(A)
    pinv = np.linalg.pinv(A_exp)
    sol = np.dot(pinv, Y)
    return sol


complete = networkx.complete_graph(5)
A_complete = networkx.to_numpy_matrix(complete)
A_complete = np.asarray(A_complete)

star = networkx.star_graph(4)
A_star = networkx.to_numpy_matrix(star)
A_star = np.asarray(A_star)

er = networkx.erdos_renyi_graph(5, 0.5)
networkx.draw(er)
A_er = networkx.to_numpy_matrix(er)
A_er = np.asarray(A_er)

cycle = networkx.cycle_graph(5)
A_cycle = networkx.to_numpy_matrix(cycle)
A_cycle = np.asarray(A_cycle)

y = np.zeros((5, 1))
y[0, 0] = 100
y[1, 0] = -100
y[2, 0] = 200
y[3, 0] = -100
y[4, 0] = -100
    def __init__(self,
                 nr_infected=5,
                 nr_exposed=10,
                 nr_recovered_immune=0,
                 simultanousAct=True,
                 network_type='watts_strogatz_graph',
                 human_population=200,
                 ratio_vectors_per_person=.5,
                 intrinsic_incubation_period=5.5,
                 extrinsic_incubation_period=7,
                 m_prob_reproduce=.02,
                 transmission_prob_human_to_vector=.9,
                 transmission_prob_vector_to_human=.9,
                 blood_meals_per_day=4,
                 share_m_vertical_transmission=.11,
                 recovery_period_human=5,
                 sexual_intercourse_day=.2,
                 share_symptomatic_humans=.2,
                 share_infected_mosquitos=0,
                 share_extreme_poverty=.2,
                 network_connectivity=2.5):
        '''
        Initialize model parameters
        '''
        self.Zika_Cases = 0

        self.human_population = human_population
        self.initial_Mosquitos = int(human_population *
                                     ratio_vectors_per_person)

        self.simultanousAct = simultanousAct
        self.network_type = network_type

        self.extrinsic_incubation_period = extrinsic_incubation_period
        self.intrinsic_incubation_period = intrinsic_incubation_period

        self.transmission_prob_human_to_vector = transmission_prob_human_to_vector
        self.transmission_prob_vector_to_human = transmission_prob_vector_to_human

        self.m_prob_reproduce = m_prob_reproduce
        self.blood_meals_per_day = blood_meals_per_day
        self.share_m_vertical_transmission = share_m_vertical_transmission

        self.recovery_period_human = recovery_period_human
        self.sexual_intercourse_day = sexual_intercourse_day
        self.share_symptomatic_humans = share_symptomatic_humans
        self.share_infected_mosquitos = share_infected_mosquitos

        number_of_links = int(network_connectivity * human_population)
        ###################
        # Agent Activation#
        ###################
        if self.simultanousAct == False:
            self.schedule = ActivationByBreed(self, False)
        else:
            self.schedule = ActivationByBreed(self, True)

        ###########
        # Network #
        ###########
        # Random Network: binomial_graph
        if network_type == 'erdos_renyi_graph':
            link_probability = (float(number_of_links) /
                                float(human_population**2)) * 1.6
            self.network = nx.erdos_renyi_graph(human_population,
                                                link_probability)

        #Scale-free network (Powerlaw)
        elif network_type == 'barabasi_albert_graph':
            self.network = nx.barabasi_albert_graph(
                human_population, number_of_links / human_population)

        # Network: small-world graph
        elif network_type == 'watts_strogatz_graph':
            link_probability = (float(number_of_links) /
                                float(human_population**2)) * 1.6
            self.network = nx.watts_strogatz_graph(human_population,
                                                   family_size,
                                                   link_probability)

        # cellular automaton
        elif network_type == 'grid_2d_graph':
            self.network = nx.grid_2d_graph(
                int(round(np.sqrt(human_population))),
                int(round(np.sqrt(human_population))),
                periodic=True)
            self.network = nx.convert_node_labels_to_integers(self.network)
            self.human_population = int(round(np.sqrt(human_population)))**2
        else:
            raise Exception(
                "Not recognized Network, please select a different network type"
            )

        self.datacollector = DataCollector(
            model_reporters={
                "m_susceptible":
                lambda m: self.count_type(m, "susceptible", Mosquito),
                "m_exposed":
                lambda m: self.count_type(m, "exposed", Mosquito),
                "m_infectious":
                lambda m: self.count_type(m, "infectious", Mosquito),
                "h_susceptible_rich":
                lambda m: self.count_type(m, "susceptible", Human) - self.
                count_poor_human(m, "susceptible"),
                "h_exposed_rich":
                lambda m: self.count_type(
                    m, "exposed", Human) - self.count_poor_human(m, "exposed"),
                "h_symptomatic_infectious_rich":
                lambda m: self.count_type(m, "infectious", Human, True) - self.
                count_poor_human(m, "infectious", True),
                "h_asymptomatic_infectious_rich":
                lambda m: self.count_type(m, "infectious", Human) - self.
                count_poor_human(m, "infectious"),
                "h_recovered_immune_rich":
                lambda m: self.count_type(m, "recovered_immune", Human) - self.
                count_poor_human(m, "recovered_immune"),
                "h_susceptible_poor":
                lambda m: self.count_poor_human(m, "susceptible"),
                "h_exposed_poor":
                lambda m: self.count_poor_human(m, "exposed"),
                "h_symptomatic_infectious_poor":
                lambda m: self.count_poor_human(m, "infectious", True),
                "h_asymptomatic_infectious_poor":
                lambda m: self.count_poor_human(m, "infectious"),
                "h_recovered_immune_poor":
                lambda m: self.count_poor_human(m, "recovered_immune"),
                "cumulative_cases":
                lambda m: m.Zika_Cases,
            })
        # Create Mosquitos:
        for i in range(self.initial_Mosquitos):
            node_ID = random.choice(self.network.nodes())
            if self.share_infected_mosquitos >= random.uniform(0., 1.0):
                M_condition = 'infected'
            else:
                M_condition = 'susceptible'
            new_mosquito = Mosquito(
                node_ID=node_ID,
                condition=
                M_condition,  # Assumes all mosquitoes are susceptible initially
                age=int(np.random.uniform(0, average_M_lifespan)),
                # age = int(np.random.triangular(0, average_M_lifespan/2.0, average_M_lifespan)),
            )
            self.schedule.add(new_mosquito)

#         print ('infected', nr_infected)
#         print ('nr_exposed', nr_exposed)
#         print ('nr_recovered_immune', nr_recovered_immune)

# Create Humans
        for i in range(self.human_population):
            node_ID = random.choice(self.network.nodes())
            if nr_infected > 0:
                condition = "infectious"
                nr_infected -= 1
            elif nr_recovered_immune > 0:
                condition = "recovered_immune"
                nr_recovered_immune -= 1
            elif nr_exposed > 0:
                condition = "exposed"
                nr_exposed -= 1
            else:
                condition = "susceptible"

            if share_extreme_poverty >= random.uniform(0., 1.0):
                income_group = 'poor'
            else:
                income_group = 'rich'
            new_person = Human(self, node_ID, condition, income_group)
            self.schedule.add(new_person)

        # Auto run until stop
        self.running = False
import networkx as nx
n = int(input("Enter #vertices: "))
p = float(input("Enter Edge probability: "))
er = nx.erdos_renyi_graph(n, p)
f_name = raw_input("Enter file name: ")
f = open(f_name, "w")
for x in er.edges():
    f.write(str(x[0]) + ' ' + str(x[1]))
    f.write('\n')
print str(er.number_of_nodes()) + ' ' + str(er.number_of_edges())
示例#56
0
WRITE("Networkx version:" + str(nx.__version__))

init_cond = {
    'N': N,
    'f': f,
    'mean_degree': mean_degree,
    'K': K,
    'steps': steps
}

WRITE("N=" + str(N) + "\nf=" + str(f) + "\nmean_degree=" + str(mean_degree) +
      "\nK=" + str(K) + "\nsteps=" + str(steps))

#np.random.seed(1)
G_undir = nx.erdos_renyi_graph(N, mean_degree / N)

G_dir = nx.DiGraph()
G_dir.add_nodes_from(range(N))

G_dir.add_edges_from(G_undir.edges())

A = nx.to_numpy_matrix(G_dir.to_undirected(), dtype=np.int)
#fig = plt.figure(figsize=(5, 5))
#plt.title("Adjacency Matrix")
#plt.imshow(A,cmap="Greys",interpolation="none")
#%matplotlib inline
#sns.heatmap(A, cmap="Greys")
#plt.show()

#storex = np.zeros((N,steps))
示例#57
0
def generate_erdos_renyi_netx(p, N):
    """ Generate random Erdos Renyi graph """
    g = networkx.erdos_renyi_graph(N, p)
    W = networkx.adjacency_matrix(g).todense()
    return torch.as_tensor(W, dtype=torch.float)
示例#58
0
__author__ = 'Bhavin.Parekh'
import networkx as nx
import random

import ndlib.models.ModelConfig as mc
import ndlib.models.CompositeModel as gc
import ndlib.models.compartments.NodeCategoricalAttribute as ns

# Network generation
g = nx.erdos_renyi_graph(1000, 0.1)

# Setting node attribute
attr = {n: {"Sex": random.choice(['male', 'female'])} for n in g.nodes()}
nx.set_node_attributes(g, attr)

# Composite Model instantiation
model = gc.CompositeModel(g)

# Model statuses
model.add_status("Susceptible")
model.add_status("Infected")
model.add_status("Removed")

# Compartment definition
c1 = na.NodeCategoricalAttribute("Sex", "male", probability=0.6)

# Rule definition
model.add_rule("Susceptible", "Infected", c1)

# Model initial status configuration
config = mc.Configuration()
示例#59
0
# Created by Filip Slazyk
# MOwNiT 2
# 2018/2019

import networkx as nx
import csv
import numpy as np

# Random graph n=30 r = 1
G = nx.erdos_renyi_graph(30, 0.2)
edges = G.edges()
with open('./graphs_csv/random_graph.csv', 'w') as writeFile:
    writer = csv.writer(writeFile)
    for edge in edges:
        writer.writerow(edge + (1, ))
writeFile.close()

# 3-regular graph n=50 r = 1
G = nx.random_regular_graph(3, 50)
edges = G.edges()
with open('./graphs_csv/3_regular_graph.csv', 'w') as writeFile:
    writer = csv.writer(writeFile)
    for edge in edges:
        writer.writerow(edge + (1, ))
writeFile.close()

# Graph with bridge n=40 r in (0,10)
G = nx.erdos_renyi_graph(20, 0.2)
edges = G.edges()
with open('./graphs_csv/graph_with_bridge.csv', 'w') as writeFile:
    writer = csv.writer(writeFile)
示例#60
0
def test_community():
    G = nx.erdos_renyi_graph(20, 0.1)
    prediction = Community(G).predict()
    assert_less_equal(len(prediction), 190)