def generateNetwork(N,cnType,weighted):
    # Input:
    #   N - number of nodes
    #   cnType  - network type (i.e. scale-free, small-world, Erdos-Renyi random graph)
    #   weighted - weighted or unweighted network
    # Output:
    #   G - a network with random generated topology acoording with the input parameters

    if (cnType == "scale-free"):
        G = nx.powerlaw_cluster_graph(N, 5, 0.3)
        while (nx.is_connected(G) == False):
            G = nx.powerlaw_cluster_graph(N, 5, 0.3)
    if (cnType == "small-world"):
        G = nx.newman_watts_strogatz_graph(N, 6, 0.6)
        while (nx.is_connected(G) == False):
            G = nx.newman_watts_strogatz_graph(N, 6, 0.6)
    if (cnType == "Erdos-Renyi"):
        G = nx.fast_gnp_random_graph(N, 0.01)
        while (nx.is_connected(G) == False):
            G = nx.fast_gnp_random_graph(N, 0.01)

    if (weighted):
        G = generateWeightedNetwork(G)
    else:
        G = generateUnweightedNetwork(G)

    return G
Пример #2
0
    def __init__(self, graph_type, min_n, max_n, p, m=None, seed=None):

        cur_n = np.random.randint(max_n - min_n + 1) + min_n
        if graph_type == 'erdos_renyi':
            self.g = nx.erdos_renyi_graph(n=cur_n, p=p, seed=seed)
        elif graph_type == 'powerlaw':
            self.g = nx.powerlaw_cluster_graph(n=cur_n, m=m, p=p, seed=seed)
        elif graph_type == 'barabasi_albert':
            self.g = nx.barabasi_albert_graph(n=cur_n, m=m, seed=seed)
        elif graph_type == 'gnp_random_graph':
            self.g = nx.gnp_random_graph(n=cur_n, p=p, seed=seed)

        while self.g.number_of_edges == 0:
            if graph_type == 'erdos_renyi':
                self.g = nx.erdos_renyi_graph(n=cur_n, p=p, seed=seed)
            elif graph_type == 'powerlaw':
                self.g = nx.powerlaw_cluster_graph(n=cur_n,
                                                   m=m,
                                                   p=p,
                                                   seed=seed)
            elif graph_type == 'barabasi_albert':
                self.g = nx.barabasi_albert_graph(n=cur_n, m=m, seed=seed)
            elif graph_type == 'gnp_random_graph':
                self.g = nx.gnp_random_graph(n=cur_n, p=p, seed=seed)

        self.adj_dense = nx.to_numpy_matrix(self.g, dtype=np.int32)
Пример #3
0
def createGraphsAndCommunities():
	g = nx.scale_free_graph(500, alpha=0.40, beta=0.40, gamma=0.20)
	g1 = nx.powerlaw_cluster_graph(500, 10, 0.2)
	g2 = nx.barabasi_albert_graph(500, 10)
	g3 = nx.newman_watts_strogatz_graph(500, 10, 0.2)
	nx.write_graphml (g, direc+"sfg.graphml")
	nx.write_graphml(g1, direc+"pcg.graphml")
	nx.write_graphml(g2, direc+"bag.graphml")
	nx.write_graphml(g3, direc+"nwsg.graphml")

	graphs = {}
	graphs["sfg"] = graph_tool.load_graph(direc+"sfg.graphml")
	graphs["pcg"] = graph_tool.load_graph(direc+"pcg.graphml")
	graphs["bag"] = graph_tool.load_graph(direc+"bag.graphml")
	graphs["nwsg"] = graph_tool.load_graph(direc+"nwsg.graphml")
	graphs["price"] = graph_tool.generation.price_network(1000)
	
	for i,h in graphs.iteritems():
		s = graph_tool.community.minimize_blockmodel_dl(h)
		b = s.b
		graph_tool.draw.graph_draw(h, vertex_fill_color=b, vertex_shape=b, output=direc+"block"+str(i)+".pdf")
		
		com = graph_tool.community.community_structure(h, 10000, 20)
		graph_tool.draw.graph_draw(h, vertex_fill_color=com, vertex_shape=com, output=direc+"community"+str(i)+".pdf")

		state = graph_tool.community.minimize_nested_blockmodel_dl(h)
		graph_tool.draw.draw_hierarchy(state, output=direc+"nestedblock"+str(i)+".pdf")

		pagerank = graph_tool.centrality.pagerank(h)
		graph_tool.draw.graph_draw(h, vertex_fill_color=pagerank, vertex_size = graph_tool.draw.prop_to_size(pagerank, mi=5, ma=15), vorder=pagerank, output=direc+"pagerank"+str(i)+".pdf")
		h.set_reversed(is_reversed=True)
		pagerank = graph_tool.centrality.pagerank(h)
		graph_tool.draw.graph_draw(h, vertex_fill_color=pagerank, vertex_size = graph_tool.draw.prop_to_size(pagerank, mi=5, ma=15), vorder=pagerank, output=direc+"reversed_pagerank"+str(i)+".pdf")
def generate_powerlaw_graph(nodes, d, p, ind=1):
    graph = []
    graph.extend([(i, j, ind) for (i, j) in nx.powerlaw_cluster_graph(
        nodes, d, p, seed=np.random.randint(0, 10000000)).edges()])

    graph_edges = np.array(graph)
    return graph_edges
Пример #5
0
    def set_graph(self, graphtype, graphparams):
        if graphtype == 'hexagonal':
            self.G = nx.triangular_lattice_graph(**graphparams)

        elif graphtype == 'watts strogatz':
            self.G = nx.watts_strogatz_graph(**graphparams)

        elif graphtype == 'newman watts strogatz':
            self.G = nx.newman_watts_strogatz_graph(**graphparams)

        elif graphtype == 'square':
            self.G = nx.grid_2d_graph(**graphparams)

        elif graphtype == 'random blocks':
            self.G = nx.stochastic_block_model(**graphparams)

        elif graphtype == 'powerlaw cluster':
            self.G = nx.powerlaw_cluster_graph(**graphparams)

        elif graphtype == 'scale-free small world':
            self.G = clustered_scalefree(**graphparams)

        elif graphtype == 'barabasi-albert':
            self.G = nx.barabasi_albert_graph(**graphparams)

        else:
            print('Using complete graph')
            self.G = nx.complete_graph(**graphparams)
def initialize():
    global g
    global wr
    global f
    global initialConditions
    initialConditions=0
    # Inicialite file for saving data
    cola= dt.datetime.now().strftime('%H%M')
    outputfilename = 'competicion_01_{}.csv'.format( cola)
    fileOut = open(outputfilename, 'w')
    wr = csv.writer(fileOut,quoting = csv.QUOTE_NONE)
    wr.writerow(['Tipo 1','Tipo 2','Tipo 3','Patogeno'])
    f = open( 'competicion_01_{}.ini'.format( cola), "w")
    
 #   g = nx.karate_club_graph()
    g=nx.powerlaw_cluster_graph(100,3,0.3)
    g.pos = nx.spring_layout(g)

    for i in g.nodes_iter():
        if random() < .33:
            g.node[i]['tipo'] = 0
        elif random() < .33:
            g.node[i]['tipo'] = 1
        elif random() < .33:
            g.node[i]['tipo'] = 2
        elif random() < .33:
            g.node[i]['tipo'] = 3
        else:
            g.node[i]['tipo'] = 4
Пример #7
0
    def fromPowerLaw(cls, specs):
        '''
        :param specs: a tupple containing (n, m, p, seed, bw, delay, cpu)
        :return: a substrate
        '''
        n, m, p, seed, bw, delay, cpu = specs
        n = int(n)
        m = int(m)
        p = float(p)
        seed = int(seed)
        g = nx.powerlaw_cluster_graph(n, m, p, seed)
        session = Session()
        nodes = [Node(name=str(n), cpu_capacity=cpu) for n in g.nodes()]

        session.add_all(nodes)
        session.flush()

        edges = [Edge
                 (node_1=session.query(Node).filter(Node.name == str(e[0])).one(),
                  node_2=session.query(Node).filter(Node.name == str(e[1])).one(),
                  bandwidth=bw,
                  delay=delay
                  )
                 for e in g.edges()

                 ]
        session.add_all(edges)
        session.flush()

        return cls(edges, nodes
                   )
Пример #8
0
def add_edges_to_groups(output_graph, groups_list, edges_to_add, prob, level):
    global template_created
    total_groups = len(groups_list)
    edges_per_node = max((3 - level), 1)
    triangle_prob = 0.1*level
    if False:
        random_graph = nx.random_regular_graph(int(total_groups/3), total_groups)
    else:
        random_graph = nx.powerlaw_cluster_graph(total_groups, edges_per_node, triangle_prob, random.random()*10)

    if template_created:
        template_created = False
        plt.axis('off')
        position = nx.graphviz_layout(random_graph, prog='sfdp')
        nx.draw_networkx_nodes(random_graph, position, node_size=30, node_color='r') #output_graph.degree().values())
        nx.draw_networkx_edges(random_graph, position, alpha=0.3)
        plt.savefig(dataset_name2 +"/"+ "template_" + image_name, bbox_inches='tight', dpi=500)
        print "plot saved as ", image_name
    
    random_edges = random_graph.edges()
    
    for edge in random_edges:
        e0 = edge[0]
        e1 = edge[1]
        if random.random() > 0.3:
            e0, e1 = e1, e0
        print("adding level{} edges between group{} and group{}".format(level, e0, e1))
        add_edges_to_two_groups(output_graph, groups_list[e0], groups_list[e1], edges_to_add, prob)
Пример #9
0
	def __init__(self, N, m, p):
		self.name = 'Default Power-Law random graph SF_%i (Poisson distribution)' % N
		self.N = N
		self.G = nx.powerlaw_cluster_graph(N, m, p)

		self.params = dict()
		self.state = None
Пример #10
0
def get_graph(objects, properties):
    graph_type = properties['graph_type']
    n = len(objects) - 1
    if 'num_nodes_to_attach' in properties.keys():
        k = properties['num_nodes_to_attach']
    else:
        k = 3
    r = properties['connection_probability']

    tries = 0
    while (True):
        if graph_type == 'random':
            x = nx.fast_gnp_random_graph(n, r)
        elif graph_type == 'erdos_renyi_graph':
            x = nx.erdos_renyi_graph(n, r)
        elif graph_type == 'watts_strogatz_graph':
            x = nx.watts_strogatz_graph(n, k, r)
        elif graph_type == 'newman_watts_strogatz_graph':
            x = nx.newman_watts_strogatz_graph(n, k, r)
        elif graph_type == 'barabasi_albert_graph':
            x = nx.barabasi_albert_graph(n, k, r)
        elif graph_type == 'powerlaw_cluster_graph':
            x = nx.powerlaw_cluster_graph(n, k, r)
        elif graph_type == 'cycle_graph':
            x = nx.cycle_graph(n)
        else:  ##Star by default
            x = nx.star_graph(len(objects) - 1)
        tries += 1
        cc_conn = nx.connected_components(x)
        if len(cc_conn) == 1 or tries > 5:
            ##best effort to create a connected graph!
            break
    return x, cc_conn
Пример #11
0
 def test_pagerank(self):
     size = 1000
     g = nx.DiGraph(nx.powerlaw_cluster_graph(size, 3, 0.001))
     N = len(g.nodes())
     tmp_file = tempfile.NamedTemporaryFile(delete=False)
     for node in g.nodes():
         outlinks = g.out_edges(nbunch=[node])
         outlinks = map(str, [n2 for n1, n2 in outlinks])
         if not outlinks:
             value = 'pr_results,%s,%s' % (1.0/N, N)
             tmp_file.write('%s\t%s\n' % (node, value))
         else:
             outlinks_str = ','.join(outlinks)
             value = 'pr_results,%s,%s,' % (1.0/N, N)
             value += outlinks_str
             tmp_file.write('%s\t%s\n' % (node, value))
     tmp_file.flush()
     input_path = tmp_file.name
     job_id = 'unittest'
     sorted_ids = pagerank(job_id, self.iter_count, input_path, self.top_n)
     fs = HadoopFS()
     fs.rmr('%s/hat_results' % job_id)
     if self.top_n <= size: 
         self.assertEqual(len(sorted_ids), self.top_n, 'some ids is missing')
     id_ranges = range(0, 1000)
     for _id in sorted_ids:
         self.assertIn(int(_id), id_ranges, 'node should in graph')
Пример #12
0
    def fromPowerLaw(cls, specs):
        '''
        :param specs: a tupple containing (n, m, p, seed, bw, delay, cpu)
        :return: a substrate
        '''
        n, m, p, seed, bw, delay, cpu = specs
        n = int(n)
        m = int(m)
        p = float(p)
        seed = int(seed)
        g = nx.powerlaw_cluster_graph(n, m, p, seed)
        session = Session()
        nodes = [Node(name=str(n), cpu_capacity=cpu) for n in g.nodes()]

        session.add_all(nodes)
        session.flush()

        edges = [Edge
                 (node_1=session.query(Node).filter(Node.name == str(e[0])).one(),
                  node_2=session.query(Node).filter(Node.name == str(e[1])).one(),
                  bandwidth=bw,
                  delay=delay
                  )
                 for e in g.edges()

                 ]
        session.add_all(edges)
        session.flush()

        return cls(edges, nodes
                   )
Пример #13
0
def create_graph(num_nodes):
    """
    Creates directed graph with agents assigned to the nodes and trust values assigned to the edges

    :param num_nodes: integer, number of nodes in the graph
    :return: graph: nx.DiGraph, a directed graph representing the connections between the agents
    """
    graph = nx.powerlaw_cluster_graph(num_nodes, 3, 0.5)
    graph = graph.to_directed()

    # Set weights on edges
    for node in graph.nodes():
        # Set out-degree as weight on out-going edges
        out_degree = graph.out_degree[node]
        for edge in graph.edges(node):
            graph.edges[edge]['weight'] = out_degree

    # Normalize over in-going edges
    for node in graph.nodes():
        sum_ingoing = np.sum(attr['weight']
                             for a, b, attr in graph.in_edges(node, data=True))
        for edge in graph.in_edges(node):
            graph.edges[edge]['weight'] /= sum_ingoing

    return graph
Пример #14
0
def get_graph(objects, properties):
    graph_type = properties['graph_type']
    n = len(objects)-1
    if 'num_nodes_to_attach' in properties.keys():
        k = properties['num_nodes_to_attach']
    else:
        k = 3
    r = properties['connection_probability']

    tries = 0
    while(True):
        if graph_type == 'random':
            x = nx.fast_gnp_random_graph(n,r)
        elif graph_type == 'erdos_renyi_graph':
            x = nx.erdos_renyi_graph(n,r)
        elif graph_type == 'watts_strogatz_graph':
            x = nx.watts_strogatz_graph(n, k, r)
        elif graph_type == 'newman_watts_strogatz_graph':
            x = nx.newman_watts_strogatz_graph(n, k, r)
        elif graph_type == 'barabasi_albert_graph':
            x = nx.barabasi_albert_graph(n, k, r)
        elif graph_type == 'powerlaw_cluster_graph':
            x = nx.powerlaw_cluster_graph(n, k, r)
        elif graph_type == 'cycle_graph':
            x = nx.cycle_graph(n)
        else: ##Star by default
            x = nx.star_graph(len(objects)-1)
        tries += 1
        cc_conn = nx.connected_components(x)
        if len(cc_conn) == 1 or tries > 5: 
            ##best effort to create a connected graph!
            break
    return x, cc_conn
Пример #15
0
    def create_graph(self, params):

        # case statements on type of graph

        if self.type == 'small_world':
            self.graph = nx.watts_strogatz_graph(
                int(params[0]), int(params[1]), float(params[2]),
                None if len(params) < 4 else int(params[3]))
            cg.SWC += 1
            self.idx = cg.SWC
            self.path = 'smallWorldGraphs'
        elif self.type == 'small_world_connected':
            self.graph = nx.connected_watts_strogatz_graph(
                int(params[0]), int(params[1]), float(params[2]),
                100 if len(params) < 4 else int(params[3]),
                None if len(params) < 5 else int(params[4]))
            cg.SWCC += 1
            self.idx = cg.SWCC
            self.path = 'smallWorldConnectedGraphs'
        elif self.type == 'small_world_newman':
            self.graph = nx.newman_watts_strogatz_graph(
                int(params[0]), int(params[1]), float(params[2]),
                None if len(params) < 4 else int(params[3]))
            cg.SWNC += 1
            self.idx = cg.SWNC
            self.path = 'smallWorldNewmanGraphs'
        elif self.type == 'power_law':
            self.graph = nx.powerlaw_cluster_graph(
                int(params[0]), int(params[1]), float(params[2]),
                None if len(params) < 4 else int(params[3]))
            cg.PLC += 1
            self.idx = cg.PLC
            self.path = 'powerLawGraphs'
        elif self.type == 'power_law_tree':
            self.graph = nx.random_powerlaw_tree(
                int(params[0]), 3 if len(params) < 2 else float(params[1]),
                None if len(params) < 3 else int(params[2]),
                100 if len(params) < 4 else int(params[3]))
            cg.PLTC += 1
            self.idx = cg.PLTC
            self.path = 'powerLawTreeGraphs'
        elif self.type == 'random_graph':
            self.graph = nx.gnm_random_graph(
                int(params[0]), int(params[1]),
                None if len(params) < 3 else int(params[2]),
                False if len(params) < 4 else bool(params[3]))
            cg.RGC += 1
            self.idx = cg.RGC
            self.path = 'randomGraphs'
        elif self.type == 'erdos_renyi_random':
            self.graph = nx.erdos_renyi_graph(
                int(params[0]), float(params[1]),
                None if len(params) < 3 else int(params[2]),
                False if len(params) < 4 else bool(params[3]))
            cg.ERRC += 1
            self.idx = cg.ERRC
            self.path = 'erdosRenyiRandomGraphs'
        else:
            print 'GRAPH TYPE:', self.type
            raise Exception('Invalid Type of Graph input into argv[2]')
Пример #16
0
def generate_graph(n, m, p, seed):
    G = nx.powerlaw_cluster_graph(n, m, p, seed)
    data = json_graph.node_link_data(G)
    with open('./Working/graph.json', 'w') as f:
        json.dump(data, f)
    with open('./Working/graph_flag', mode='w', encoding='utf-8') as fh:
        fh.write("i look at you")
Пример #17
0
	def __update_structure(self):
		self.structure = nx.powerlaw_cluster_graph(
			self.num_nodes,
			self.node_degree,
			self.prob_triad,
			self.seed
		)

		if nx.is_connected(self.structure):
			return

		components = nx.connected_components(self.structure)

		biggest_comp = []
		comp_index = -1
		for i, component in enumerate(components):
			if len(component) > len(biggest_comp):
				biggest_comp = component
				comp_index = i

		if self.seed:
			random.seed(self.seed)

		del components[comp_index]
		for component in components:
			for left_node in component:
				right_node = random.choice(biggest_comp)
				self.structure.add_edge(left_node, right_node)
Пример #18
0
    def __init__(self, population_size, initial_outbreak_size, spread_chance):
        print("Beginning model setup...\n")
        self.population_size = population_size
        print("Creating graph...")
        self.graph = nx.powerlaw_cluster_graph(population_size, 100, 0.5)
        #self.graph = nx.complete_graph(population_size)
        print(len(self.graph.edges))
        print("Initializing grid...")
        self.grid = NetworkGrid(self.graph)
        self.schedule = SimultaneousActivation(self)
        self.initial_outbreak_size = initial_outbreak_size
        self.spread_chance = spread_chance

        print("Initializing data collector...")
        self.datacollector = DataCollector({
            "Infected:": count_infected,
            "Susceptible:": count_susceptible,
            "Removed:": count_removed
        })

        for i, node in enumerate(self.graph.nodes()):
            a = Person(i, self, State.SUSCEPTIBLE, spread_chance)
            self.schedule.add(a)
            self.grid.place_agent(a, i)
            if i % 100 == 0:
                print("Finished with agent ", i)

        infected_nodes = self.random.sample(self.graph.nodes(),
                                            self.initial_outbreak_size)
        for a in self.grid.get_cell_list_contents(infected_nodes):
            a.status = State.INFECTED

        self.datacollector.collect(self)
        print("Model initialized...\n")
Пример #19
0
def gen_graph(num_min, num_max, g_type, path, i, n_type='uniform'):
    cur_n = random.randint(num_max - num_min + 1) + num_min
    if g_type == 'erdos_renyi':
        g = nx.erdos_renyi_graph(n=cur_n, p=0.15)
    elif g_type == 'powerlaw':
        g = nx.powerlaw_cluster_graph(n=cur_n, m=4, p=0.05)
    elif g_type == 'small-world':
        g = nx.connected_watts_strogatz_graph(n=cur_n, k=8, p=0.1)
    elif g_type == 'barabasi_albert':
        g = nx.barabasi_albert_graph(n=cur_n, m=4)

    if n_type != 'uniform':
        if n_type == 'random':
            weights = {}
            for node in g.nodes():
                weights[node] = random.uniform(0, 1)
        else:
            degree = nx.degree_centrality(g)
            maxDegree = max(dict(degree).values())
            weights = {}
            for node in g.nodes():
                weights[node] = degree[node] / maxDegree
        nx.set_node_attributes(g, weights, 'weight')

    path = '%s/%s-%s' % (path, str(num_min), str(num_max))
    if not os.path.exists(path):
        os.mkdir(path)

    nx.write_gml(g, '%s/g_%s' % (path, str(i)))
Пример #20
0
def gen_graph(opt):
    max_n = int(opt['max_n'])
    min_n = int(opt['min_n'])
    g_type = opt['g_type']
    max_w = 10
    min_w = 1

    graph_id = np.random.randint(MAX_VAL)

    cur_n = np.random.randint(max_n - min_n + 1) + min_n
    if g_type == 'erdos_renyi':
        p = float(opt['density'])
        e_g = nx.erdos_renyi_graph(n=cur_n, p=p, seed=graph_id)
        lcc = max(nx.connected_component_subgraphs(e_g), key=len)
        g = nx.convert_node_labels_to_integers(lcc)
    elif g_type == 'powerlaw':
        g = nx.powerlaw_cluster_graph(n=cur_n, m=4, p=p, seed=graph_id)
    elif g_type == 'barabasi_albert':
        p = int(opt['density'])
        if p == 0:
            max_p = 16
            min_p = 1
            p = np.random.randint(max_p - min_p + 1) + min_p
        g = nx.barabasi_albert_graph(n=cur_n, m=p, seed=graph_id)

    for edge in nx.edges(g):
        pert = np.random.uniform(-0.5, 0.5)
        weight = np.random.randint(max_w - min_w + 1) + min_w
        g[edge[0]][edge[1]]['weight'] = (weight + pert) * w_scaling

    return g
Пример #21
0
    def __update_structure(self):
        self.structure = nx.powerlaw_cluster_graph(self.num_nodes,
                                                   self.node_degree,
                                                   self.prob_triad, self.seed)

        if nx.is_connected(self.structure):
            return

        components = nx.connected_components(self.structure)

        biggest_comp = []
        comp_index = -1
        for i, component in enumerate(components):
            if len(component) > len(biggest_comp):
                biggest_comp = component
                comp_index = i

        if self.seed:
            random.seed(self.seed)

        del components[comp_index]
        for component in components:
            for left_node in component:
                right_node = random.choice(biggest_comp)
                self.structure.add_edge(left_node, right_node)
Пример #22
0
    def __init__(self, graph_type, cur_n=0, p=None, m=None, seed=None):
        """
        initialize a graphing problem
        :param graph_type: type of random graph to generate
        :param cur_n: size of graph
        :param p: probability of being connected
        :param m:
        :param seed: seed used to gen graph under
        """
        self.graph_type = graph_type
        self.cur_n = cur_n
        self.seed = seed
        self.m, self.p = "_", "_"
        if m:
            self.m = m
        if p:
            self.p = p
        if graph_type == "prototype":
            pass
        elif graph_type == 'erdos_renyi':
            self.g = nx.erdos_renyi_graph(n=cur_n, p=p, seed=seed)
        elif graph_type == 'powerlaw':
            self.g = nx.powerlaw_cluster_graph(n=cur_n, m=m, p=p, seed=seed)
        elif graph_type == 'barabasi_albert':
            self.g = nx.barabasi_albert_graph(n=cur_n, m=m, seed=seed)
        elif graph_type == 'gnp_random_graph':
            self.g = nx.gnp_random_graph(n=cur_n, p=p, seed=seed)

        self.solution = None
        self.approx = None
    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
Пример #24
0
def ShowGraph():
    def RandomLetter():

        string.ascii_letters
        import random
        letter = random.choice(string.ascii_lowercase)
        return letter
    # erdos renyi graph
    # generate a graph which has n=20 nodes, probablity p = 0.2.
    ER = nx.random_graphs.erdos_renyi_graph(20, 0.2)
    PW = nx.powerlaw_cluster_graph(20,3,0)
     # the shell layout
    pos = nx.shell_layout(ER)
    NER = []
    for e in nx.to_edgelist(ER):
        T = (e[0],e[1],RandomLetter())
        NER.append(T)
    print (NER)
    nx.draw(ER, pos, with_labels = False, node_size = 30)
    plt.show()

    query = "a.b.c.d"
    querylist=query.split("+", query.count(".", 0, len(query)))
    print (querylist)

    query1 ="a[2,3].h.(b+c+d.(e+f+g+t)+u).a[2,3].(b+c+d+e.(f+g))).y.(i+9)"
Пример #25
0
def powerlaw_cluster_graph(N, deg, dia, dim, domain):
    '''
    Parameters of the graph:
    n (int) – the number of nodes
    m (int) – the number of random edges to add for each new node
    p (float,) – Probability of adding a triangle after adding a random edge
    Formula for m:  (m^2)- (Nm)/2 + avg_deg * (N/2) = 0  =>  From this equation we need to find m :
    p : Does not vary the average degree or diameter so much. : Higher value of p may cause average degree to overshoot intended average_deg
    so we give the control of average degree to parameter m: by setting a lower value of p: 0.1
    :return: Graph Object
    '''

    ## Calculating thof nodes: 10\nNumber of edges: 16\nAverage degree:   3.2000'
    strt_time = time()

    m = int(round((N - np.sqrt(N ** 2 - 4 * deg * N)) / 4))
    p = 0.2

    ## G at center:
    G = nx.powerlaw_cluster_graph(n=N, m=m, p=p)

    lcc, _ = graph_util.get_nk_lcc_undirected(G)

    best_G = lcc

    best_diam = nx.algorithms.diameter(best_G)

    best_avg_deg = np.mean(list(dict(nx.degree(best_G)).values()))


    end_time = time()
    print('Graph_Name: powerlaw_cluster_graph')
    print('Num_Nodes: ', nx.number_of_nodes(best_G), ' Avg_Deg : ', best_avg_deg, ' Diameter: ', best_diam)
    print('TIME: ', end_time - strt_time)
    return best_G, best_avg_deg, best_diam
Пример #26
0
 def init_random(self, n=200, k=10, typ='random', p=.1, weighted=False, seed=None):
     # add n nodes to the network in the start state -> S
     self.add_mult(n, state='S', traced=False)
     # initialize the rewire probability to k/n if p=None provided
     p = k / n if p is None else p
             
     links_to_create_dict = {
         # Generate random pairs (edges) without replacement
         'random': lambda: rand_pairs(n, int(n * k / 2), seed=seed),
         'binomial': lambda: list(nx.fast_gnp_random_graph(n, p, seed=seed).edges),
         # small-world network
         'ws': lambda: list(nx.watts_strogatz_graph(n, k, p, seed=seed).edges),
         'newman-ws': lambda: list(nx.newman_watts_strogatz_graph(n, k, p, seed=seed).edges),
         # scale-free network
         'barabasi': lambda: list(nx.barabasi_albert_graph(n, m=k, seed=seed).edges),
         'powerlaw-cluster': lambda: list(nx.powerlaw_cluster_graph(n, m=k, p=p, seed=seed).edges),
         # fully connected network
         'complete': lambda: list(nx.complete_graph(n).edges),
     }
     try:
         links_to_create = links_to_create_dict[typ]()
     except KeyError:
         print("The inputted network type is not supported. Default to: random", file=stderr)
         links_to_create = links_to_create_dict['random']()
         
     len_links = len(links_to_create)
         
     if weighted:
         # Create random weights from 1 to 10 and append them to the list of edge tuples
         weights = random.choices(range(1,10), k=len_links)
         links_to_create = [links_to_create[i] + (weights[i],) for i in range(len_links)]
         
     # Add the random edges with/without weights depending on 'weighted' parameter
     # we do not update the counts here because they will be updated after the infection has been seeded with first_inf
     self.add_links(links_to_create, update=False)
Пример #27
0
def RandomHolmeKim(n, m, p, seed=None):
    """
    Returns a random graph generated by the Holme and Kim algorithm for
    graphs with power law degree distribution and approximate average
    clustering.

    INPUT:


    -  ``n`` - number of vertices.

    -  ``m`` - number of random edges to add for each new
       node.

    -  ``p`` - probability of adding a triangle after
       adding a random edge.

    -  ``seed`` - for the random number generator.


    From the NetworkX documentation: The average clustering has a hard
    time getting above a certain cutoff that depends on m. This cutoff
    is often quite low. Note that the transitivity (fraction of
    triangles to possible triangles) seems to go down with network
    size. It is essentially the Barabasi-Albert growth model with an
    extra step that each random edge is followed by a chance of making
    an edge to one of its neighbors too (and thus a triangle). This
    algorithm improves on B-A in the sense that it enables a higher
    average clustering to be attained if desired. It seems possible to
    have a disconnected graph with this algorithm since the initial m
    nodes may not be all linked to a new node on the first iteration
    like the BA model.

    EXAMPLE: We show the edge list of a random graph on 8 nodes with 2
    random edges per node and a probability `p = 0.5` of
    forming triangles.

    ::

        sage: graphs.RandomHolmeKim(8, 2, 0.5).edges(labels=False)
        [(0, 2), (0, 5), (1, 2), (1, 3), (2, 3), (2, 4), (2, 6), (2, 7),
         (3, 4), (3, 6), (3, 7), (4, 5)]

    ::

        sage: G = graphs.RandomHolmeKim(12, 3, .3)
        sage: G.show()  # long time

    REFERENCE:

    - [1] Holme, P. and Kim, B.J. Growing scale-free networks with
      tunable clustering, Phys. Rev. E (2002). vol 65, no 2,
      026107.
    """
    if seed is None:
        seed = current_randstate().long_seed()
    import networkx

    return graph.Graph(networkx.powerlaw_cluster_graph(n, m, p, seed=seed))
 def powerlaw_cluster_graph(n=100, m=50, p=0.5):
     """powerlaw cluster graph
     :param n: node num
     :param m: the number of random edges to add for each new node
     :param p: prob
     :return: powerlaw_cluster_graph instance
     """
     return nx.powerlaw_cluster_graph(n, m, p)
Пример #29
0
def generate_topo(n):
    topo = nx.powerlaw_cluster_graph(n,2,0.08)
    # topo = fnss.waxman_1_topology(n=50,alpha=0.6,beta=0.3)
    # topo = fnss.fat_tree_topology(n)
    fnss.set_weights_constant(topo,1)
    fnss.set_delays_constant(topo, 1, 'ms')
    fnss.set_capacities_edge_betweenness(topo,[100,500,1000],'Mbps')
    fnss.write_topology(topo,'topo_pl_50.xml')
Пример #30
0
def generate_graph():
    # Try these included graphs! Play around with the constants!
    # Feel free to define your own graph for testing.

    #return nx.random_regular_graph(5, GRAPH_SIZE, seed=GRAPH_SEED)
    #return nx.barabasi_albert_graph(GRAPH_SIZE, 5)
    #return grid_graph()
    return nx.powerlaw_cluster_graph(GRAPH_SIZE, 5, 0.7)
Пример #31
0
def clusterGraph(nodes,edges,p):
    """Holme and Kim algorithm for growing graphs with powerlaw degree distribution and approximate average clustering.
    p is a ptobability of adding a triangle after adding a random edge.
    edges = number of random edges to add for each new node
    https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.generators.random_graphs.powerlaw_cluster_graph.html#networkx.generators.random_graphs.powerlaw_cluster_graph
    """
    g = nx.powerlaw_cluster_graph(nodes,edges,p)
    return g
Пример #32
0
def RandomHolmeKim(n, m, p, seed=None):
    """
    Returns a random graph generated by the Holme and Kim algorithm for
    graphs with power law degree distribution and approximate average
    clustering.

    INPUT:


    -  ``n`` - number of vertices.

    -  ``m`` - number of random edges to add for each new
       node.

    -  ``p`` - probability of adding a triangle after
       adding a random edge.

    -  ``seed`` - for the random number generator.


    From the NetworkX documentation: The average clustering has a hard
    time getting above a certain cutoff that depends on m. This cutoff
    is often quite low. Note that the transitivity (fraction of
    triangles to possible triangles) seems to go down with network
    size. It is essentially the Barabasi-Albert growth model with an
    extra step that each random edge is followed by a chance of making
    an edge to one of its neighbors too (and thus a triangle). This
    algorithm improves on B-A in the sense that it enables a higher
    average clustering to be attained if desired. It seems possible to
    have a disconnected graph with this algorithm since the initial m
    nodes may not be all linked to a new node on the first iteration
    like the BA model.

    EXAMPLE: We show the edge list of a random graph on 8 nodes with 2
    random edges per node and a probability `p = 0.5` of
    forming triangles.

    ::

        sage: graphs.RandomHolmeKim(8, 2, 0.5).edges(labels=False)
        [(0, 2), (0, 5), (1, 2), (1, 3), (2, 3), (2, 4), (2, 6), (2, 7),
         (3, 4), (3, 6), (3, 7), (4, 5)]

    ::

        sage: G = graphs.RandomHolmeKim(12, 3, .3)
        sage: G.show()  # long time

    REFERENCE:

    - [1] Holme, P. and Kim, B.J. Growing scale-free networks with
      tunable clustering, Phys. Rev. E (2002). vol 65, no 2,
      026107.
    """
    if seed is None:
        seed = current_randstate().long_seed()
    import networkx
    return graph.Graph(networkx.powerlaw_cluster_graph(n, m, p, seed=seed))
Пример #33
0
def graph_space_iter():
    i = 20
    n = 0
    while n < 1000000:
        G = nx.powerlaw_cluster_graph(i, 10, 0.1)
        G = nx.convert_node_labels_to_integers(G)
        n = G.number_of_edges()
        i *= 2
        yield G.number_of_nodes(), G
Пример #34
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)
Пример #35
0
def setup_network(alpha,
                  beta,
                  gamma,
                  infected,
                  directory=None,
                  name=None,
                  size=None,
                  edge_p=None,
                  knn=None,
                  rewire_p=None,
                  drop=None,
                  m=None,
                  n_edges=None,
                  triangle_p=None):

    # Network topology

    # Create Graph
    if edge_p != None:
        print("Making ER Graph")
        g = nx.erdos_renyi_graph(size, edge_p)

    elif knn != None:
        print("Making NWS Graph with drops")
        g = nx.newman_watts_strogatz_graph(size, knn, rewire_p)

        # drop random edges
        for i in range(drop):
            e = random.choice(list(g.edges))
            g.remove_edge(e[0], e[1])

    elif m != None:
        print("Making BA Graph")
        g = nx.barabasi_albert_graph(size, m)

    elif triangle_p != None:
        print("Making Powerlaw Cluster Graph")
        g = nx.powerlaw_cluster_graph(n=size, m=n_edges, p=triangle_p)

    else:
        print("Loading custom Graph")
        g = nx.read_adjlist(os.path.join(directory, name),
                            delimiter='\t',
                            nodetype=int)

    # Model selection
    m = ep.SEIRModel(g)

    # Model Configuration
    cfg = mc.Configuration()
    cfg.add_model_parameter('beta', beta)
    cfg.add_model_parameter('gamma', gamma)
    cfg.add_model_parameter('alpha', alpha)
    cfg.add_model_parameter("fraction_infected", infected)
    m.set_initial_status(cfg)

    return m
Пример #36
0
def save_syn():
    clustering_bins = np.linspace(0.3, 0.6, 7)
    print(clustering_bins)
    path_bins = np.linspace(1.8, 3.0, 7)
    print(path_bins)

    powerlaw_k = np.arange(2, 12)
    powerlaw_p = np.linspace(0, 1, 101)
    ws_k = np.arange(4, 23, 2)
    ws_p = np.linspace(0, 1, 101)

    counts = np.zeros((8, 8))
    thresh = 4
    graphs = []
    n = 64
    while True:
        k, p = np.random.choice(powerlaw_k), np.random.choice(powerlaw_p)
        g = nx.powerlaw_cluster_graph(n, k, p)
        clustering = nx.average_clustering(g)
        path = nx.average_shortest_path_length(g)
        clustering_id = np.digitize(clustering, clustering_bins)
        path_id = np.digitize(path, path_bins)
        if counts[clustering_id, path_id] < thresh:
            counts[clustering_id, path_id] += 1
            default_feature = torch.ones(1)
            nx.set_node_attributes(g, default_feature, 'node_feature')
            graphs.append(g)
            print(np.sum(counts))
        if np.sum(counts) == 8 * 8 * thresh:
            break

    with open('scalefree.pkl', 'wb') as file:
        pickle.dump(graphs, file)

    counts = np.zeros((8, 8))
    thresh = 4
    graphs = []
    n = 64
    while True:
        k, p = np.random.choice(ws_k), np.random.choice(ws_p)
        g = nx.watts_strogatz_graph(n, k, p)
        clustering = nx.average_clustering(g)
        path = nx.average_shortest_path_length(g)
        clustering_id = np.digitize(clustering, clustering_bins)
        path_id = np.digitize(path, path_bins)
        if counts[clustering_id, path_id] < thresh:
            counts[clustering_id, path_id] += 1
            default_feature = torch.ones(1)
            nx.set_node_attributes(g, default_feature, 'node_feature')
            graphs.append(g)
            print(np.sum(counts))
        if np.sum(counts) == 8 * 8 * thresh:
            break

    with open('smallworld.pkl', 'wb') as file:
        pickle.dump(graphs, file)
Пример #37
0
def pl_cluster_new(n, m, p, random_seed=None):
	Gw=nx.powerlaw_cluster_graph(n, m, p, seed=random_seed)
	
	Gs=nx.Graph()
	Gs.add_nodes_from(Gw.nodes(),state=1.0)
	Gs.add_edges_from(Gw.edges(),weight=1.0)
	##remove self-edges
	Gs.remove_edges_from(Gs.selfloop_edges())
	
	return Gs
Пример #38
0
def pl_cluster_new(n, m, p, random_seed=None):
    Gw = nx.powerlaw_cluster_graph(n, m, p, seed=random_seed)

    Gs = nx.Graph()
    Gs.add_nodes_from(Gw.nodes(), state=1.0)
    Gs.add_edges_from(Gw.edges(), weight=1.0)
    ##remove self-edges
    Gs.remove_edges_from(Gs.selfloop_edges())

    return Gs
Пример #39
0
    def __init__(self, graph_type, cur_n, p, m=None, seed=None):

        if graph_type == 'erdos_renyi':
            self.g = nx.erdos_renyi_graph(n=cur_n, p=p, seed=seed)
        elif graph_type == 'powerlaw':
            self.g = nx.powerlaw_cluster_graph(n=cur_n, m=m, p=p, seed=seed)
        elif graph_type == 'barabasi_albert':
            self.g = nx.barabasi_albert_graph(n=cur_n, m=m, seed=seed)
        elif graph_type == 'gnp_random_graph':
            self.g = nx.gnp_random_graph(n=cur_n, p=p, seed=seed)
Пример #40
0
def create_scale_free_graph(N_nodes,p_edge,n_infected):
    #scale free and small world
    #Growing Scale-Free Networks with Tunable Clustering
    n = N_nodes
    m = int(0.5*p_edge*N_nodes)
    p = 1.0
    #Random graph
    #p_coop is the fraction of cooperators
    G = nx.powerlaw_cluster_graph(n,m,p)
    return set_graph_strategies(G, n_infected)
Пример #41
0
def topo_pl(nodes):
    bws = [1,2,3,4,5,6,7,8,9]
    network = nx.powerlaw_cluster_graph(nodes,2,0.13)
    g = nx.Graph()
    g.add_nodes_from(network.nodes())
    for link in network.edges():
        bw = random.choice(bws)
        g.add_edge(link[0],link[1],{'weight':bw})
        g.add_edge(link[1],link[0],{'weight':bw})
    return g
Пример #42
0
 def gen_graph(self, num_min, num_max):
     cur_n = np.random.randint(num_max - num_min + 1) + num_min
     if self.g_type == 'erdos_renyi':
         g = nx.erdos_renyi_graph(n=cur_n, p=0.15)
     elif self.g_type == 'small-world':
         g = nx.connected_watts_strogatz_graph(n=cur_n, k=8, p=0.1)
     elif self.g_type == 'barabasi_albert':
         g = nx.barabasi_albert_graph(n=cur_n, m=4)
     elif self.g_type == 'powerlaw':
         g = nx.powerlaw_cluster_graph(n=cur_n, m=4, p=0.05)
     return g
Пример #43
0
def gen_graph(opt):
    max_n = int(opt['max_n'])
    min_n = int(opt['min_n'])
    cur_n = np.random.randint(max_n - min_n + 1) + min_n
    if opt['g_type'] == 'erdos_renyi':
        g = nx.erdos_renyi_graph(n = cur_n, p = 0.15)
    elif opt['g_type'] == 'powerlaw':
        g = nx.powerlaw_cluster_graph(n = cur_n, m = 4, p = 0.05)
    elif opt['g_type'] == 'barabasi_albert':
        g = nx.barabasi_albert_graph(n = cur_n, m = 4)
    return g
Пример #44
0
 def gen_graph(self):
     cur_n = np.random.randint(self.min_nodes, self.max_nodes)
     if self.graph_type == 'erdos_renyi':
         return nx.erdos_renyi_graph(n=cur_n, p=0.15)
     elif self.graph_type == 'small-world':
         return nx.connected_watts_strogatz_graph(n=cur_n, k=8, p=0.1)
     elif self.graph_type == 'barabasi_albert':
         return nx.barabasi_albert_graph(n=cur_n, m=4)
     elif self.graph_type == 'powerlaw':
         return nx.powerlaw_cluster_graph(n=cur_n, m=4, p=0.05)
     raise ValueError(f'{self.graph_type} graph type is not supported yet')
def initialize():
    global g
 #   g = nx.karate_club_graph()
    g=nx.powerlaw_cluster_graph(100,3,0.3)
    g.pos = nx.spring_layout(g)
    for i in g.nodes_iter():
        if random() < .3:
            g.node[i]['state'] = 1
        elif random() < .3:
            g.node[i]['state'] = 2
        elif random() < .3:
            g.node[i]['state'] = 3
        else:
            g.node[i]['state'] = 0
Пример #46
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--input', help="Input file path", default=None)
    parser.add_argument(
        '-o', '--output', help="Output file path",
        default=None)
    parser.add_argument(
        '--page-rank',
        help="Adds page rank to the output network",
        action='store_const', default=False, const=True)
    parser.add_argument(
        '--eigenvector',
        help="Adds eigenvector centrality to the output network",
        action='store_const', default=False, const=True)
    parser.add_argument(
        '--betweenness',
        help="Adds betweenness centrality to the output network",
        action='store_const', default=False, const=True)

    namespace = parser.parse_args()

    if namespace.input is None:
        graph = nx.powerlaw_cluster_graph(100, 8, 0.1)
    else:
        graph = read_network(namespace.input)

    if namespace.page_rank:
        page_rank_dictionary = nx.pagerank(graph)
        for node, rank in page_rank_dictionary.iteritems():
            graph.add_node(node, pagerank=rank)

    if namespace.eigenvector:
        eig_dictionary = nx.eigenvector_centrality(graph)
        for node, rank in eig_dictionary.iteritems():
            graph.add_node(node, eigenvector_centrality=rank)

    if namespace.betweenness:
        betw_dictionary = nx.betweenness_centrality(graph)
        for node, rank in betw_dictionary.iteritems():
            graph.add_node(node, betweenness=rank)

    graph_dict = convert_network(graph)

    if namespace.output is None:
        out = sys.stdout
    else:
        out = file(namespace.output, 'w')

    json.dump(graph_dict, out)
Пример #47
0
    def __init__(self, vertices, m, c, seed = int(time.time())):
        """
        Construct a Powerlaw Clustered network. The vertices argument contains 
        objects of type Vertex representing the vertices of the network. The 
        m argument specifies the number of attachments made from the 
        new vertex to the existing vertices during the network construction 
        process. The c argument specifies the desired level of clustering. 
        The seed argument is the seed for the random number generator used to 
        build the network.

        Note that the desired level of clustering may not always be achievable.
        """

        self.vertices = vertices
        self.m = m
        self.c = c
        self.seed = seed
        p = 0.0
        g = networkx.powerlaw_cluster_graph(len(vertices), m, p, seed = seed)
        while p < 1 and networkx.average_clustering(g) < c:
            g = networkx.powerlaw_cluster_graph(len(vertices), m, p)
            p += 0.01
        self.g = g
        self.__adj_list_map__ = {}
Пример #48
0
def emulate(tmp_file, size=1000):
    g = nx.DiGraph(nx.powerlaw_cluster_graph(size, 3, 0.001))
    N = len(g.nodes())
    for node in g.nodes():
        outlinks = g.out_edges(nbunch=[node])
        outlinks = map(str, [n2 for n1, n2 in outlinks])
        if not outlinks:
            value = 'pr_results,%s,%s' % (1.0/N, N)
            tmp_file.write('%s\t%s\n' % (node, value))
        else:
            outlinks_str = ','.join(outlinks)
            value = 'pr_results,%s,%s,' % (1.0/N, N)
            value += outlinks_str
            tmp_file.write('%s\t%s\n' % (node, value))
    return tmp_file
Пример #49
0
    def __init__(self, vertices, m, p, seed = int(time.time())):
        """
        Construct a Powerlaw Clustered network. The vertices argument contains 
        objects of type Vertex representing the vertices of the network. The 
        m argument specifies the number of attachments made from the 
        new vertex to the existing vertices during the network construction 
        process. The p argument specifies the probability of adding a triangle 
        after adding a random edge. The seed argument is the seed for 
        the random number generator used to build the network.
        """

        self.vertices = vertices
        self.m = m
        self.p = p
        self.seed = seed
        self.g = networkx.powerlaw_cluster_graph(len(vertices), m, p, seed = seed)
        self.__adj_list_map__ = {}
Пример #50
0
def add_edges_to_groups(output_graph, groups_list, edges_to_add, prob, level):
    total_groups = len(groups_list)
    edges_per_node = max((3 - level), 1)
    triangle_prob = 0.1*level
    if False:
        random_graph = nx.random_regular_graph(int(total_groups/3), total_groups)
    else:
        random_graph = nx.powerlaw_cluster_graph(total_groups, edges_per_node, triangle_prob, random.random()*10)
    random_edges = random_graph.edges()
    
    for edge in random_edges:
        e0 = edge[0]
        e1 = edge[1]
        if random.random() > 0.3:
            e0, e1 = e1, e0
        print("adding level{} edges between group{} and group{}".format(level, e0, e1))
        add_edges_to_two_groups(output_graph, groups_list[e0], groups_list[e1], edges_to_add, prob)
def GraphType(num_nodes, str, p=0.05, m=3):
    """
    :param num_nodes: the number of nodes of the graph (if that option is available)
    :param str: the type of graph that is used. We have
                'erdos'         an erdos renyi graph
                'powerlaw'      a graph with powerlaw degree distribution
                'enron'         a social network graph loaded from
                                http://snap.stanford.edu/data/email-Enron.html. (36692 nodes)
                'karateclub'    some karate club graph
                'women'         women social network
    :return: the graph
    """
    if str == 'erdos':
        graph = nx.erdos_renyi_graph(num_nodes, p)
    elif str == 'powerlaw':
        graph = nx.powerlaw_cluster_graph(num_nodes, m, p)
    elif str == 'enron':
        graph = nx.Graph()
        edges = np.loadtxt('Enron.txt',skiprows=4)
        graph.add_edges_from(edges)
    elif str == 'karateclub':
        graph = nx.karate_club_graph()
    elif str == 'women':
        graph = nx.davis_southern_women_graph()
    elif str == 'pair':
        graph = nx.DiGraph()
        graph.add_edge(0,1)
        graph.add_edge(1,0)
    elif str == 'star':
        graph = nx.star_graph(num_nodes)
    elif str == 'cycle':
        graph = nx.cycle_graph(num_nodes)
    elif str == 'config':
        max_degree = int(num_nodes/5)
        #Create some degrees
        degrees = np.asarray(np.round(np.exp(np.log(max_degree) * np.random.uniform(size=num_nodes))), np.int)
        #Ensure the total number of degrees is even
        if sum(degrees) % 2 != 0:
            degrees[np.random.randint(num_nodes)] += 2 * np.random.randint(2) - 1
        #Create a graph and apply the configuration model
        graph = nx.Graph()
        graph = nx.configuration_model(degrees, graph)
        graph = graph.to_directed()

    return graph
    def create_graph(self, params):

        # case statements on type of graph

        if self.type == 'small_world':
            self.graph = nx.watts_strogatz_graph(int(params[0]), int(params[1]), float(params[2]), None if len(params) < 4 else int(params[3]))
            cg.SWC += 1
            self.idx = cg.SWC
            self.path = 'smallWorldGraphs'
        elif self.type == 'small_world_connected':
            self.graph = nx.connected_watts_strogatz_graph(int(params[0]), int(params[1]), float(params[2]), 100 if len(params) < 4 else int(params[3]), None if len(params) < 5 else int(params[4]))
            cg.SWCC += 1
            self.idx = cg.SWCC
            self.path = 'smallWorldConnectedGraphs'
        elif self.type == 'small_world_newman':
            self.graph = nx.newman_watts_strogatz_graph(int(params[0]), int(params[1]), float(params[2]), None if len(params) < 4 else int(params[3]))
            cg.SWNC += 1
            self.idx = cg.SWNC
            self.path = 'smallWorldNewmanGraphs'
        elif self.type == 'power_law':
            self.graph = nx.powerlaw_cluster_graph(int(params[0]), int(params[1]), float(params[2]), None if len(params) < 4 else int(params[3]))
            cg.PLC += 1
            self.idx = cg.PLC
            self.path = 'powerLawGraphs'
        elif self.type == 'power_law_tree':
            self.graph = nx.random_powerlaw_tree(int(params[0]), 3 if len(params) < 2 else float(params[1]), None if len(params) < 3 else int(params[2]), 100 if len(params) < 4 else int(params[3]))
            cg.PLTC += 1
            self.idx = cg.PLTC
            self.path = 'powerLawTreeGraphs'
        elif self.type == 'random_graph':
            self.graph = nx.gnm_random_graph(int(params[0]), int(params[1]), None if len(params) < 3 else int(params[2]), False if len(params) < 4 else bool(params[3]))
            cg.RGC += 1
            self.idx = cg.RGC
            self.path = 'randomGraphs'
        elif self.type == 'erdos_renyi_random':
            self.graph = nx.erdos_renyi_graph(int(params[0]), float(params[1]), None if len(params) < 3 else int(params[2]), False if len(params) < 4 else bool(params[3]))
            cg.ERRC += 1
            self.idx = cg.ERRC
            self.path = 'erdosRenyiRandomGraphs'
        else:
            print 'GRAPH TYPE:', self.type
            raise Exception('Invalid Type of Graph input into argv[2]')
Пример #53
0
dataset_name = "output"
if len(sys.argv) == 6:
    dataset_name = sys.argv[5];
image_name = dataset_name + ".png"
dot_name = dataset_name + ".dot"
pckl_name = dataset_name + ".pckl"
neo4j_data = dataset_name + "-neo4j.txt"

total_edges = 0
nodes_per_group = int(sys.argv[1])
random_edges_per_node = int(sys.argv[2])
triangle_prob = float(sys.argv[3])
edge_addition_prob = float(sys.argv[4]) 

G = nx.powerlaw_cluster_graph(nodes_per_group, random_edges_per_node, triangle_prob,10)
Gnode_count = G.number_of_nodes()
Gnodes = G.nodes()
print "Edges in group G: ", G.number_of_edges()

H = nx.powerlaw_cluster_graph(nodes_per_group, random_edges_per_node, triangle_prob,10)
H = nx.convert_node_labels_to_integers(H,first_label=nodes_per_group)
Hnodes = H.nodes()
Hnode_count = H.number_of_nodes()
print "Edges in group H: ", H.number_of_edges()

I = nx.powerlaw_cluster_graph(nodes_per_group, random_edges_per_node, triangle_prob,10)
I = nx.convert_node_labels_to_integers(I,first_label=nodes_per_group*2)
Inodes = I.nodes()
Inode_count = I.number_of_nodes()
print "Edges in group I: ", I.number_of_edges()
Пример #54
0
#!/usr/bin/env python

import networkx as nx

N = 100
E = int(round((N**2)/1.5))

dense = nx.dense_gnm_random_graph(N, E)
nx.write_edgelist(dense, 'dense.dat', data=False)

karate = nx.karate_club_graph()
nx.write_edgelist(karate, 'karate.dat', data=False)

plaw = nx.powerlaw_cluster_graph(N * 10, N/10, 0.3)
nx.write_edgelist(plaw, 'plaw.dat', data=False)
Пример #55
0
# Convert to networkx graph object
G = network_gen.import_weights_to_graph(W_net_dict)

N = len(G.nodes())

# These are the new params, derived from adjusting the proverbial knobs
G_ER = nx.erdos_renyi_graph(N,0.087)
G_WS = nx.watts_strogatz_graph(N,36,0.159)

#G_BA = standard_graphs.symmetric_BA_graph(N,20,0.52)
G_BA = nx.barabasi_albert_graph(N,20)
G_BA = standard_graphs.symmetric_BA_graph(N,20,0.52)
#G_BA = nx.barabasi_albert_graph(N,19)

G_PWC = nx.powerlaw_cluster_graph(N,19,1)
print 'Generating biophysical graph...'
G_BIO,A,D = aux_random_graphs.biophysical_graph(N=426,N_edges=7804,L=1.,power=1.5,mode=0)

if plot_functions:
    
    # Here you can specify which plotting function you want to run.
    # It needs to take a single graph as input!
    plotfunction = plot_net.plot_clustering_coeff_pdf
        
    Fig, axs = plt.subplots(2,2, facecolor=[1,1,1])
    
    plotfunction(axs[0,0],G)
    #plotfunction(axs[0,1],G_PWC)
    plotfunction(axs[0,1],G_ER)
    plotfunction(axs[1,0],G_BA)
Пример #56
0
class Node(Node):
    def activate(self):
        pass

class Simulation(simulation.Simulation):
    class configurator_type(configurators.NXGraphConfigurator):
        node_type = Node
        node_options = {}


# trck.track_class(core.Agent, resolution_level=5)
# trck.track_class(Node, resolution_level=5)

st.print_diff()
g = nx.powerlaw_cluster_graph(5000, 20, 0.1)
# trck.track_object(g, resolution_level=5)
# trck.create_snapshot('Graph only')

st.print_diff()

sim = Simulation()
sim.run(starting_graph=g)
st.print_diff()
# trck.create_snapshot('With agents')
# trck.stats.print_summary()


from pympler import refbrowser
import types
Пример #57
0
    row_labels = range(n)
    col_labels = range(n)
    G, W_net, _ = aux_random_graphs.biophysical_graph(n, N_edges=7804,
                                                      L=1, power=1.5, mode=0)

    # Put everything in a dictionary
    net_dict = {'row_labels': row_labels, 'col_labels': col_labels,
                'data': W_net}
else:
    n = 426
    row_labels = range(n)
    col_labels = range(n)

    # Create networkx graph
    if network_type == 'powerlaw_cluster':
        temp_G = nx.powerlaw_cluster_graph(n=n, m=19, p=1)
    elif network_type == 'scale_free':
        temp_G = nx.barabasi_albert_graph(n=n, m=19)
    elif network_type == 'random':
        temp_G = nx.erdos_renyi_graph(n, 0.123)
    elif network_type == 'small_world':  # small_world
        temp_G = nx.watts_strogatz_graph(n, 36, 0.159)
    else:
        print 'Network type not recognized'

    # Set weights for all the egdes
    wts = {}
    for e in temp_G.edges():
        wts[e] = 1.
    nx.set_edge_attributes(temp_G, 'weight', wts)
Пример #58
0
with open(combined_dir, 'rb') as f:
    adj, features = pickle.load(f)
    fb_graphs['combined'] = (adj, features)



### ---------- Create Random NetworkX Graphs ---------- ###
# Dictionary to store all nx graphs
nx_graphs = {}

# Small graphs
N_SMALL = 200
nx_graphs['er-small'] = nx.erdos_renyi_graph(n=N_SMALL, p=.02, seed=RANDOM_SEED) # Erdos-Renyi
nx_graphs['ws-small'] = nx.watts_strogatz_graph(n=N_SMALL, k=5, p=.1, seed=RANDOM_SEED) # Watts-Strogatz
nx_graphs['ba-small'] = nx.barabasi_albert_graph(n=N_SMALL, m=2, seed=RANDOM_SEED) # Barabasi-Albert
nx_graphs['pc-small'] = nx.powerlaw_cluster_graph(n=N_SMALL, m=2, p=.02, seed=RANDOM_SEED) # Powerlaw Cluster
nx_graphs['sbm-small'] = nx.random_partition_graph(sizes=[N_SMALL/10]*10, p_in=.1, p_out=.01, seed=RANDOM_SEED) # Stochastic Block Model

# Larger graphs
N_LARGE = 1000
nx_graphs['er-large'] = nx.erdos_renyi_graph(n=N_LARGE, p=.01, seed=RANDOM_SEED) # Erdos-Renyi
nx_graphs['ws-large'] = nx.watts_strogatz_graph(n=N_LARGE, k=3, p=.1, seed=RANDOM_SEED) # Watts-Strogatz
nx_graphs['ba-large'] = nx.barabasi_albert_graph(n=N_LARGE, m=2, seed=RANDOM_SEED) # Barabasi-Albert
nx_graphs['pc-large'] = nx.powerlaw_cluster_graph(n=N_LARGE, m=2, p=.02, seed=RANDOM_SEED) # Powerlaw Cluster
nx_graphs['sbm-large'] = nx.random_partition_graph(sizes=[N_LARGE/10]*10, p_in=.05, p_out=.005, seed=RANDOM_SEED) # Stochastic Block Model

# Remove isolates from random graphs
for g_name, nx_g in nx_graphs.iteritems():
    isolates = nx.isolates(nx_g)
    if len(isolates) > 0:
        for isolate_node in isolates:
Пример #59
0
#!/usr/bin/env python

import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
from math import sqrt
from operator import itemgetter
import random

import Network_solve as ns
import sfg as sfg
from functions import *
import timeit


nodes = 30
steps = 20000
G = nx.powerlaw_cluster_graph(nodes, 3, 0.2)
np.savetxt("./settings/adjacency.txt", nx.adjacency_matrix(G).todense())
np.savetxt("./settings/mismatch.txt", np.random.randn(steps, nodes))

start = timeit.default_timer()
ns.networkSolver(nodes)
end = timeit.default_timer()
print "time to solve %d timesteps: %2.2f" % (steps, (end - start))
print "average %f sec per step" % ((end - start) / steps)
Пример #60
0
def generate_PL_graph(N, m, p, filename, directed=True):
    G = nx.powerlaw_cluster_graph(N, m, p, None, directed)
    nx.write_edgelist(G, filename, '#', '\t', False, 'utf-8')