def test_gaussian_random_partition_graph(): G = nx.gaussian_random_partition_graph(100, 10, 10, 0.3, 0.01) assert len(G) == 100 G = nx.gaussian_random_partition_graph(100, 10, 10, 0.3, 0.01, directed=True) assert len(G) == 100 G = nx.gaussian_random_partition_graph(100, 10, 10, 0.3, 0.01, directed=False, seed=42) assert len(G) == 100 G = nx.gaussian_random_partition_graph(100, 10, 10, 0.3, 0.01, directed=True, seed=42) assert len(G) == 100 pytest.raises(nx.NetworkXError, nx.gaussian_random_partition_graph, 100, 101, 10, 1, 0)
def __init__(self, n, seed): if seed == 0: # 空网络 self.net = nx.empty_graph() elif seed == 1: # ER随机图 self.net = nx.gnp_random_graph(n, 0.012) elif seed == 2: # ER随机图 self.net = nx.gnp_random_graph(n, 0.1) elif seed == 3: # ER随机图 self.net = nx.gnp_random_graph(n, 0.3) elif seed == 4: # 规则图 self.net = nx.watts_strogatz_graph(n, 4, 0) elif seed == 5: # 规则图 self.net = nx.watts_strogatz_graph(n, 8, 0) elif seed == 6: # 规则图 self.net = nx.watts_strogatz_graph(n, 16, 0) elif seed == 7: # WS小世界网络 self.net = nx.connected_watts_strogatz_graph(n, 4, 0.1) elif seed == 8: # WS小世界网络 self.net = nx.connected_watts_strogatz_graph(n, 8, 0.1) elif seed == 9: # WS小世界网络 self.net = nx.connected_watts_strogatz_graph(n, 16, 0.1) elif seed == 10: # 无标度网络 self.net = nx.barabasi_albert_graph(n, 4) elif seed == 11: # 无标度网络 self.net = nx.barabasi_albert_graph(n, 8) elif seed == 12: # 无标度网络 self.net = nx.barabasi_albert_graph(n, 16) elif seed == 13: # 高斯随机分块网络 self.net = nx.gaussian_random_partition_graph(n, 100, 10, 1, 0.01) elif seed == 14: # 高斯随机分块网络 self.net = nx.gaussian_random_partition_graph(n, 100, 10, 1, 0.01) elif seed == 15: # 高斯随机分块网络 self.net = nx.gaussian_random_partition_graph(n, 100, 10, 1, 0.01) else: self.net = nx.empty_graph()
def test_gaussian_random_partition_graph(): G = nx.gaussian_random_partition_graph(100, 10, 10, 0.3, 0.01) assert_equal(len(G), 100) G = nx.gaussian_random_partition_graph(100, 10, 10, 0.3, 0.01, directed=True) assert_equal(len(G), 100) G = nx.gaussian_random_partition_graph(100, 10, 10, 0.3, 0.01, directed=False, seed=42) assert_equal(len(G), 100) G = nx.gaussian_random_partition_graph(100, 10, 10, 0.3, 0.01, directed=True, seed=42) assert_equal(len(G), 100) assert_raises(nx.NetworkXError, nx.gaussian_random_partition_graph, 100, 101, 10, 1, 0)
def main(sourceFile, destinationFile, k, epsilon): if (sourceFile != ""): G = nx.read_weighted_edgelist( sourceFile, delimiter=' ', nodetype=str ) #read the graph from file(adjacency list) graph.csv is an example of format else: G = nx.gaussian_random_partition_graph( 100, 2, 0.1, 0.6, 0.6) #select and generate the intial graph #G = nx.connected_watts_strogatz_graph(15,2,0.1) #G = nx.dorogovtsev_goltsev_mendes_graph(3) for (u, v ) in G.edges(): # initialize the weight of the edges of the graph G.edge[u][v]['weight'] = 1 #random.randint(0, 10) for n in G.nodes(): # initialize the weight of the nodes of the graph G.node[n]['weight'] = 1 #random.random() * 100 n = G.number_of_nodes() if (nx.is_connected(G) and k <= n): print("Avvio trasformazione di grafo in albero") partitor = GraphPartitioning( epsilon, n, k, G) # create the object and pass it the intial graph bestP = partitor.run( ) # run the algorithm and return the best paritition print("The best parition is:") partitor.printPartition(bestP) # print textually the best partition print("The cost of the parition is:") print(partitor.getCostPartition( bestP)) # calculate and print the cost of the best partition partitor.printGraphWithPartitions( bestP) # render graphically the best partitions partitor.savePartitionToFile( bestP, destinationFile) # save the best partition to file
def createRandomGraph(nodes, numOfCommunity, shape=10, pIn=0.5, pOut=0.25): return gaussian_random_partition_graph(nodes, numOfCommunity, shape, pIn, pOut, directed=True)
def main(): #G = nx.read_weighted_edgelist("graph.csv", delimiter=' ', nodetype=str) G = nx.gaussian_random_partition_graph(20,2,0.1,0.6,0.6) #G = nx.connected_watts_strogatz_graph(20,2,0.1) #G = nx.dorogovtsev_goltsev_mendes_graph(2) for (u, v) in G.edges(): G.edge[u][v]['weight'] = 1 testEpsilon(5,[0.3,0.5],G,3)
def main(): #initialize a guassian randomly partitioned graph to represent a clustered social network G = nx.gaussian_random_partition_graph(100, 10, 10, 0.98, 0.02) commIndex = 0 nodeToComm = dict() for x in G.graph['partition']: for y in x: nodeToComm[y] = commIndex commIndex += 1 pos = community_layout(G, nodeToComm) plt.figure(figsize=(8, 8)) plt.axis('off') nx.draw_networkx_nodes(G, pos, node_size=100) nx.draw_networkx_edges(G, pos, width=0.2, alpha=0.5) plt.show(G)
def execute(self, size, type, t_nums, strengths, seed=None, degree=3): net = Network(size) if type == 'RANDOM': net.generate(nx.erdos_renyi_graph(size, degree / size, seed=seed)) elif type == 'SCALE_FREE': net.generate(nx.barabasi_albert_graph(size, degree, seed=seed)) elif type == 'CLUSTERED': net.generate( nx.gaussian_random_partition_graph(100, 20, 5, 0.1, 0.03)) net.introduce_contagion(Contagion(c_id=0, t_num=t_nums[0], color=(0.8, 0.2, 0.2), strength=strengths[0]), method='RANDOM') net.introduce_contagion(Contagion(c_id=1, t_num=t_nums[1], color=(0.2, 0.8, 0.2), strength=strengths[1]), method='RANDOM') return net.infect()[1][-1]
def __init__(self, params): self.params = params self.generators = { 'powerlaw_cluster': lambda: nx.powerlaw_cluster_graph(params["n"], params["m"], params[ "p"]), 'grid': lambda: nx.convert_node_labels_to_integers( nx.grid_2d_graph(params['n'], params['n'])), 'path': lambda: nx.path_graph(params["n"]), 'binomial': lambda: nx.fast_gnp_random_graph(params['n'], params['p']), 'watts_strogatz': lambda: nx.watts_strogatz_graph(params['n'], params['k'], params[ 'p']), 'karate': lambda: nx.karate_club_graph(), 'gaussian_random_partition': lambda: nx.gaussian_random_partition_graph(params['n'], params[ 's'], params['v'], params['p_in'], params['p_out']) }
def community_graphs(): print("Community graphs for social networks") print("Caveman graph") G = nx.caveman_graph(2, 13) draw_graph(G) print(" Connected Caveman graph") G = nx.connected_caveman_graph(2, 3) draw_graph(G) print("Relaxed caveman") G = nx.relaxed_caveman_graph(2, 5, 0.2) draw_graph(G) print("Random partition graph") G = nx.random_partition_graph([10, 10, 10], .25, .01) draw_graph(G) print(len(G)) partition = G.graph['partition'] print(len(partition)) print("Planted partition graph") G = nx.planted_partition_graph(4, 3, 0.5, 0.1, seed=42) draw_graph(G) print("Gaussian random partition graph") G = nx.gaussian_random_partition_graph(40, 10, 10, .25, .1) print(len(G)) draw_graph(G)
) else: if layout_parameters is not None: pos = nx.spring_layout(g, **layout_parameters) else: pos = nx.spring_layout(g) print( "Using standard layout algorithm, fa2 not present on the system.") ## return positions return pos def compute_random_layout(g): coordinates = tuple(np.random.rand(1, 2)) pos = { n: np.array(tuple(np.random.rand(1, 2).tolist()[0])) for n in g.nodes() } return pos if __name__ == "__main__": G = nx.gaussian_random_partition_graph(1000, 10, 10, .25, .1) print(nx.info(G)) compute_force_directed_layout(G) print("Finished..")
def createRandomGraph(nodes,numOfCommunity,shape=10,pIn=0.5,pOut=0.25): return gaussian_random_partition_graph(nodes,numOfCommunity,shape,pIn,pOut, directed=True);
def test_gaussian_random_partition_graph(): G = nx.gaussian_random_partition_graph(100, 10, 10, 0.3, 0.01) assert_equal(len(G),100) assert_raises(nx.NetworkXError, nx.gaussian_random_partition_graph, 100, 101, 10, 1, 0)
def generateGaussian( n_nodes, avg_cluster_size, var_cluster_size, p_in, p_out): #generates a synthetic graph using the barabasi-albert model return nx.gaussian_random_partition_graph(n_nodes, avg_cluster_size, var_cluster_size, p_in, p_out)
def test_gaussian_random_partition_graph(): G = nx.gaussian_random_partition_graph(100, 10, 10, 0.3, 0.01) assert_equal(len(G), 100) assert_raises(nx.NetworkXError, nx.gaussian_random_partition_graph, 100, 101, 10, 1, 0)
# ============================================================================= # A Gaussian random partition graph is created by creating k partitions each with a size drawn from a normal distribution with mean s and variance s/v. Nodes are connected within clusters with probability p_in and between clusters with probability p_out[1] # n (int) – Number of nodes in the graph # s (float) – Mean cluster size # v (float) – Shape parameter. The variance of cluster size distribution is s/v. # p_in (float) – Probabilty of intra cluster connection. # p_out (float) – Probability of inter cluster connection. n = number_nodes s = 60 v = 0.3 p_in = 0.02 p_out = 0.01 G = nx.gaussian_random_partition_graph(n, s, v, p_in, p_out, directed=False, seed=10) # pos = nx.kamada_kawai_layout(G,scale=210) pos1 = nx.kamada_kawai_layout(G) pos = nx.spring_layout(G, k=1.2, pos=pos1, scale=2.0) nx.draw(G, pos) plt.show() # Better vis. with Gephi nx.write_gexf(G, "sample.gexf") # ============================================================================= # 2
specGW_avg_amis = [] specGW_avg_times = [] GWL_avg_amis = [] GWL_avg_times = [] infoMap_avg_amis = [] infoMap_avg_times = [] for pn in range(len(ps_out)): print('Starting p_out index = ',pn) ############################################## # Training specGW ############################################## G = nx.gaussian_random_partition_graph(n=num_nodes, s=clique_size, v=8, p_in=p_in, p_out=ps_out[pn], directed=True) p_s, cost_s, idx2node = DataIO.extract_graph_info(G) p_s = (p_s + 1) ** 0.01 p_s /= np.sum(p_s) start = time.time() t = 10 cost = sgw.directed_heat_kernel(G,t) modularities = [] for j in num_clusts: p_t = GwGt.estimate_target_distribution({0: p_s}, dim_t=j) sub_costs, sub_probs, sub_idx2nodes, coup, d_gw = graph_partition_gd2(cost,
nc = np.zeros((len(num_nodes), 4, len(graph_types), num_trials)) runtime = np.zeros((len(num_nodes), 4, len(graph_types), num_trials)) for tn in range(num_trials): for nn in range(len(num_nodes)): for gn in range(len(graph_types)): # generate synthetic graph if gn == 0: G_src = nx.powerlaw_cluster_graph(n=num_nodes[nn], m=int(clique_size * p_in), p=p_out * clique_size / num_nodes[nn]) # int(np.log(num_nodes[nn]) + 1)) else: G_src = nx.gaussian_random_partition_graph(n=num_nodes[nn], s=clique_size, v=5, p_in=p_in, p_out=p_out, directed=True) G_dst = DataIO.add_noisy_edges(G_src, noise) # G_src = G_src.to_undirected() # G_dst = G_dst.to_undirected() print('Trial {}, #nodes {}, graph type: {}'.format(tn + 1, num_nodes[nn], graph_types[gn])) print('#edges: {}, {}'.format(len(G_src.edges), len(G_dst.edges))) # weights = np.random.rand(num_nodes[nn], num_nodes[nn]) + 1 p_s, cost_s, idx2node_s = DataIO.extract_graph_info(G_src, weights=None) p_s /= np.sum(p_s) p_t, cost_t, idx2node_t = DataIO.extract_graph_info(G_dst, weights=None) p_t /= np.sum(p_t) for mn in range(4):
import networkx as nx train_graph = nx.random_geometric_graph(1000, 0.1, seed=1) nx.write_gpickle(train_graph, "train_graph") test_graph = nx.gaussian_random_partition_graph(5000, 5, 1, 0.1, 0.005, seed=1) nx.write_gpickle(test_graph, "test_graph")
def generateGaussian(n_nodes,avg_cluster_size, var_cluster_size, p_in, p_out): #generates a synthetic graph using the barabasi-albert model return nx.gaussian_random_partition_graph(n_nodes, avg_cluster_size, var_cluster_size, p_in, p_out);
def init(): global edges, socNet, pos global storyPtx, ptxLeanings, agents global interactRate, spreadingRate global wStory, wTeller RD.seed() #initialize variables dependent on command line arguments parser = argparse.ArgumentParser( description= 'Simulate information propagation in a social network with adjustable considerations' ) parser.add_argument('nAgents_', type=int) parser.add_argument('clustSize_', type=int) parser.add_argument('intRate_', type=float) parser.add_argument('sprRate_', type=float) parser.add_argument('storyPtx_', type=float) parser.add_argument('--wStory_', action='store_true') parser.add_argument('--wTeller_', action='store_false') args = vars(parser.parse_args()) numAgents = args['nAgents_'] clusterSize = args['clustSize_'] interactRate = args['intRate_'] spreadingRate = args['sprRate_'] storyPtx = args['storyPtx_'] wStory = args['wStory_'] wTeller = args['wTeller_'] #initialize a clustered graph socNet = nx.gaussian_random_partition_graph(numAgents, clusterSize, 0.1 * clusterSize, 0.85, 0.05) #initialize the positioning of the graph nodes commIndex = 0 nodeToComm = dict() for x in socNet.graph['partition']: for y in x: nodeToComm[y] = commIndex commIndex += 1 pos = community_layout(socNet, nodeToComm) #initialize average political leaning for each cluster #todo: make normal distribution perhaps commPtx = dict() for i in range(0, commIndex + 1): commPtx[i] = NP.random.normal(scale=0.45) #initialize politican leanings ptxLeanings = list() for key, _ in nodeToComm.iteritems(): ptx = commPtx[nodeToComm[key]] ptx += NP.random.normal(scale=0.15) if ptx < -1: ptx = -1 elif ptx > 1: ptx = 1 ptxLeanings.append(ptx) #initialize list of agent objects agents = list() for key, _ in nodeToComm.iteritems(): agents.append(Agent(ptxLeanings[key], key)) print(storyPtx) #pick a story seed agents[RD.sample(xrange(socNet.number_of_nodes()), 1)[0]].type = AgentTypes.Spreader #initialize edgelist edges = list(socNet.edges())