def regular_boolean_network(N=10, K=2, bias=0.5, bias_constraint='soft', keep_constants=True, remove_multiedges=True, niter_remove=1000): din = [K] * N # in-degree distrubtion dout = [K] * N # out-degree distrubtion regular_graph = nx.directed_configuration_model(din, dout) # the configuration graph creates a multigraph with self loops # the self loops are OK, but we should only have one copy of each edge if remove_multiedges: regular_graph = _remove_duplicate_edges(graph=regular_graph, niter_remove=niter_remove) # A dict that contains the network logic {<id>:{'name':<string>,'in':<list-input-node-id>,'out':<list-output-transitions>},..} bn_dict = { node: { 'name': str(node), 'in': sorted([n for n in regular_graph.predecessors(node)]), 'out': random_automata_table(regular_graph.in_degree(node), bias, bias_constraint) } for node in range(N) } return BooleanNetwork.from_dict(bn_dict)
def multiplex_configuration_independent(mg,seed=None): """Run configuration model independently for each layer. Parameters ---------- mg : Multinet Multiplex network to be configured. seed : object Seed for the configuration model. Return ------ A new Multinet instance. """ layers = mg.layers() nl = len(layers) seeds = _random_int_list(nl,seed=seed) nmg = Multinet() for layer in layers: sg = mg.sub_layer(layer,remove_isolates=True) nodes = sg.in_degree().keys() in_degs = sg.in_degree().values() out_degs = sg.out_degree().values() rsg = nx.directed_configuration_model(in_degs,out_degs,create_using=nx.DiGraph(),seed=seeds.pop()) rnodes = rsg.nodes() mapping = dict(zip(rnodes,nodes)) nrsg = nx.relabel_nodes(rsg,mapping) nmg.add_layer(nrsg,layer) return nmg
def custom_graph(N, gamma, in_scale_free, out_scale_free, k=3., same_deg = True, verbose = False): """Create scale free pseudograph, with scale free in or/and out.""" if in_scale_free: in_seq = np.random.zipf(gamma, N) else: in_seq = np.random.binomial(N-1, k/(N-1),N) if same_deg: out_seq = in_seq else: if out_scale_free: out_seq = np.random.zipf(gamma, N) else: out_seq = np.random.binomial(N-1, k/(N-1),N) diff = sum(out_seq) - sum(in_seq) for k in range(np.abs(diff)): out_seq[random.randint(0,N-1)] -= np.sign(diff) if verbose: print 'Generated graph', print 'in scale free:',str(in_scale_free), print 'out scale free:',str(out_scale_free) print '<kin> =',np.mean(in_seq), print '<kout> =',np.mean(out_seq) g = nx.directed_configuration_model(list(in_seq), list(out_seq)) return g
def random_stats_NX(g, n): """Return mean and SD clustering and char. path length for random graphs. Parameters ---------- g : NetworkX DiGraph n : number of random graphs to generate Returns ------- clusts charpaths Notes ----- The random graphs created are pseudo-graphs in that parallel edges and self-loops are allowed. """ clusts = [] charpaths = [] in_seq = g.in_degree().values() out_seq = g.out_degree().values() for i in range(n): r = nx.directed_configuration_model(in_seq, out_seq, create_using=nx.DiGraph()) clusts.append(directed_clustering(r)) charpaths.append(directed_char_path_length(r)) return clusts, charpaths
def randomGraph2(inDegrees, outDegrees): G = nx.directed_configuration_model(inDegrees, outDegrees) total = 0 for (u, v, w) in G.edges(data=True): w['weight'] = rd.random() ut.normalizeGraph(G) return G
def running_time(network: nx.DiGraph): num_tests = 3 n_nodes = 10**4 k5net = nx.directed_configuration_model(n_nodes * [5], n_nodes * [5], create_using=nx.DiGraph()) # Print results: how many seconds were taken for the test network of 10**4 nodes, # how many hours would a 26*10**6 nodes network take? result = timeit.timeit(lambda: pagerank_poweriter(k5net, 0.85, 10), number=num_tests) print(result) # Investigating the running time of the random walker function n_steps = 1000 * n_nodes # each node gets visited on average 1000 times # Print results: how many seconds were taken for the test network of 10**4 nodes, # how many hours would a 26*10**6 nodes network take? result = timeit.timeit(lambda: page_rank(k5net, 0.85, n_steps), number=num_tests) print(result) # Investigating effects of d: ds = np.arange(0, 1.2, 0.2) colors = ['b', 'r', 'g', 'm', 'k', 'c'] d_figure_path = 'graphs/page_rank/d_effect.pdf' investigate_d(network, ds, colors, n_steps, d_figure_path) # Wikipedia network: network_wp = nx.DiGraph( nx.read_edgelist("wikipedia_network.edg", create_using=nx.DiGraph())) # nx.read_edgelist. page_rank_wp = nx.pagerank(network_wp) indegree_wp = network_wp.in_degree() outdegree_wp = network_wp.out_degree() if page_rank_wp is not {}: highest_pr = sorted(page_rank_wp, key=lambda k: page_rank_wp[k])[::-1][0:5] print('---Highest PageRank:---') for p in highest_pr: print(page_rank_wp[p], ":", p) if indegree_wp is not {}: highest_id = sorted(indegree_wp, key=lambda k: indegree_wp[k])[::-1][0:5] print('---Highest In-degree:---') for p in highest_id: print(indegree_wp[p], ":", p) if outdegree_wp is not {}: highest_od = sorted(outdegree_wp, key=lambda k: outdegree_wp[k])[::-1][0:5] print('---Highest Out-degree:---') for p in highest_od: print(outdegree_wp[p], ":", p)
def __config(self, G): """ Takes in graph and returns directed configuration model """ d_in = [G.in_degree[node] for node in G.nodes] d_out = [G.out_degree[node] for node in G.nodes] C = nx.directed_configuration_model(d_in, d_out) C = nx.DiGraph(C) return C
def config_network(network): in_seq = network.in_degree().values() out_seq = network.out_degree().values() config = nx.directed_configuration_model(in_seq, out_seq, nx.DiGraph()) # Remove self loops and parallel edges config = nx.DiGraph(config) config.remove_edges_from(config.selfloop_edges()) return config
def rand_graph_uniform_degree(nodes, edges): """Create a random graph representing the transition graph for a random MDP.""" # need din/dout -- degree sequences # dout is easy...every node gets a constant number of outbound edges # equal to the number actions in the MDP. din is tougher...we want # the in-degree of each node to be random, subject to the constraints # that every node must be reachable by at least one edge and the total # in-degree over the entire graph must equal the total out-degree. dout = [edges] * nodes # to compute din, we generate a random sequence of N+1 random numbers, # take the difference between adjacent pairs, and scale up to the # desired target sum (with rounding) xs = np.sort(np.asarray([random.random() for i in range(nodes + 1)])) diffs = xs[1:] - xs[:nodes] diffs = sum(dout) / sum(diffs) * diffs din = [int(round(x)) for x in diffs] # at this point, din contains random fan-ins for each node, but we # may have nodes with 0 edges, and due to rounding, we may be off # by one in the sum as well. So walk the list, bumping any zero values # up to one, and then randomly remove any excess we have by decrementing # some of the nodes with larger fan-ins total_in = sum(din) for index, degree in enumerate(din): if degree < 1: din[index] = 1 total_in += 1 # now remove edges randomly until the degrees match while total_in > sum(dout): node = random.randint(0, nodes - 1) if din[node] > 1: din[node] -= 1 total_in -= 1 # finally, a last sanity check...if we don't have enough inbound # edges, add some more. Note that I'm not sure this ever happens, # but it's easy enough to handle. while total_in < sum(dout): node = random.randint(0, nodes - 1) din[node] += 1 total_in += 1 # if we did this right, the sums should be guaranteed to match assert(sum(din) == sum(dout)) # generate a random directed multigraph with the specified degree # sequences tgraph = nx.directed_configuration_model(din, dout) # make sure all nodes have the correct number of outgoing edges for node in tgraph: assert(edges == len(tgraph.out_edges(node))) return tgraph
def directed_config_ensemble(G): assert (type(G) == nx.DiGraph) indeg = [G.in_degree(x) for x in sorted(G)] outdeg = [G.out_degree(x) for x in sorted(G)] while True: Gnew = nx.directed_configuration_model(indeg, outdeg, create_using=nx.DiGraph) # remove multiedges Gnew = nx.DiGraph(Gnew) yield Gnew
def generate_graph_max_neighbors(n_nodes, max_degree): degrees = [] for _ in range(n_nodes): degrees.append(random.randint(0, max_degree)) network = nx.directed_configuration_model(degrees, np.random.permutation(degrees)) network = nx.DiGraph(network) network.remove_edges_from(nx.selfloop_edges(network)) return network
def generate_conf_model(G, seed=0): din = [x[1] for x in G.in_degree()] dout = [x[1] for x in G.out_degree()] GNoisy = nx.directed_configuration_model(din, dout, create_using=nx.DiGraph(), seed=seed) keys = [x[0] for x in G.in_degree()] G_mapping = dict(zip(range(len(G.nodes())), keys)) G_rev_mapping = dict(zip(keys, range(len(G.nodes())))) GNoisy = nx.relabel_nodes(GNoisy, G_mapping) return GNoisy
def pLaw(n,exp): rank=True while rank: z=nx.utils.create_degree_sequence(n,nx.utils.powerlaw_sequence,exponent=exp) #y=nx.utils.create_degree_sequence(10,nx.utils.powerlaw_sequence,exponent=1.5) G=nx.directed_configuration_model(z,z) Q=np.array(nx.adj_matrix(G.to_directed()).todense()) Q[Q>0]=1 for i in xrange(n): Q[i,i]=0 if rankL(Q)==n-1 and rankL(Q.T)==n-1 and sum(Q.sum(0)==0)==0 and sum(Q.sum(1)==0)==0: rank=False return Q
def random_directed_deg_seq(in_sequence, out_sequence, simplify, brain_size=[7., 7., 7.], create_using=None, seed=None): '''Wrapper function to get a MULTIGRAPH (parallel or self-loop edges may exist) given degree sequence. Chance of parallel/multiedges diminish as graph has more nodes. This graph is used conventionally as a control because it yields a random graph that accounts for degree distribution. Parameters: ----------- in_sequence: list of int In degree of each node to be added to the graph. out_sequence: list of int Out degree of each node to be added to the graph. simplify: bool Whether or not to remove self-loops and parallel edges. Will change degree sequence slightly, but effect diminishes with increasing size of graphs. brain_size: list of 3 floats Size of the brain to use when distributing node locations. create_using: graph, optional Return graph of this type. The instance will be cleared. seed: hashable object for random seed Seed for the random number generator. Returns: -------- Networkx graph object, adjacency matrix, and random distances''' # Create configuration model using specified properties G = nx.directed_configuration_model(in_sequence, out_sequence, create_using=create_using, seed=seed) if simplify: G = nx.DiGraph(G) # Remove parallel edges G.remove_edges_from(G.selfloop_edges()) # Remove self loops # Get adjacency info and create random spatial locations A = nx.adjacency_matrix(G) N = len(in_sequence) centroids = np.random.uniform([0, 0, 0], brain_size, (N, 3)) D = aux_tools.dist_mat(centroids) return G, A, D
def pLaw(n, exp): rank = True while rank: z = nx.utils.create_degree_sequence(n, nx.utils.powerlaw_sequence, exponent=exp) #y=nx.utils.create_degree_sequence(10,nx.utils.powerlaw_sequence,exponent=1.5) G = nx.directed_configuration_model(z, z) Q = np.array(nx.adj_matrix(G.to_directed()).todense()) Q[Q > 0] = 1 for i in xrange(n): Q[i, i] = 0 if rankL(Q) == n - 1 and rankL(Q.T) == n - 1 and sum( Q.sum(0) == 0) == 0 and sum(Q.sum(1) == 0) == 0: rank = False return Q
def gen_graph(l): din, dout = setStartAndEndStateForGraphGen(l) while (sum(dout) - sum(din) < 0): din, dout = setStartAndEndStateForGraphGen(l) diff = sum(dout) - sum(din) while (diff > 0): i = random.randint(0, l - 1) if (din[i] < l): diff -= 1 din[i] = din[i] + 1 D = nx.directed_configuration_model(din, dout) D = nx.DiGraph(D) return D
def degree_sequence_graphs(): print("Degree sequence") print("Configuration model") z = nx.utils.create_degree_sequence(30, powerlaw_sequence) G = nx.configuration_model(z) draw_graph(G) # to remove paralel edges G = nx.Graph(G) draw_graph(G) # to remove self loops G.remove_edges_from(G.selfloop_edges()) draw_graph(G) print("Directed configuration model") D = nx.DiGraph([(0, 1), (1, 2), (2, 3), (1, 3)]) # directed path graph din = list(D.in_degree().values()) dout = list(D.out_degree().values()) din.append(1) dout[0] = 2 D = nx.directed_configuration_model(din, dout) D = nx.DiGraph(D) # to remove paralell edges D.remove_edges_from(D.selfloop_edges()) # to remove self loops draw_graph(D) print("Expected degree graphs") z = [i for i in range(10)] G = nx.expected_degree_graph(z) draw_graph(G) print("Havel Hakimi graphs") z = [2, 4, 5, 6, 7, 3] G = nx.havel_hakimi_graph(z) draw_graph(G) print("Directed Havel Hakimi graphs") inds = [2, 4, 5, 6, 7, 3] outds = [2, 4, 5, 6, 7, 3] G = nx.directed_havel_hakimi_graph(in_deg_sequence=inds, out_deg_sequence=outds) draw_graph(G) print("Degree Sequence Tree") dg = [1, 2, 3, 4, 2, 3] G = nx.degree_sequence_tree(dg) draw_graph(G) print("Random Degree Sequence") sequence = [1, 2, 2, 3] G = nx.random_degree_sequence_graph(sequence) sorted(G.degree().values()) draw_graph(G)
def oper_num(num): mp_dic = {} g1 = nx.directed_configuration_model(in_degree_sequence, out_degree_sequence) tmp_dic = nx.triadic_census(g1) recip_ratio = nx.overall_reciprocity(g1) total_nodes = g1.number_of_nodes() total_edges = g1.number_of_edges() double_link = recip_ratio * total_edges sigle_dyad = total_edges - double_link mutual_dyad = double_link / 2 null_dyad = total_nodes * (total_nodes - 1) / 2 - sigle_dyad - mutual_dyad tmp_dic['null_dyad'] = null_dyad tmp_dic['sigle_dyad'] = sigle_dyad tmp_dic['mutual_dyad'] = mutual_dyad return tmp_dic
def random_once(g, kmax): rg = nx.DiGraph( nx.directed_configuration_model(list(d for n, d in g.in_degree()), list(d for n, d in g.out_degree()), create_using=nx.DiGraph())) #rg = g.copy() #Q = 100 #rg = DG_connected_double_edge_swap(rg, (Q * g.number_of_edges())) rg = compute_link_property(rg, kmax) #rgs.append(rg) meas = { str(i + 1): rg.graph[GRAPH_KEY_AVG_COMMON_NODES + str(i + 1)] for i in range(kmax) } stds = { str(i + 1): rg.graph[GRAPH_KEY_STD_COMMON_NODES + str(i + 1)] for i in range(kmax) } return meas, stds
def triadSignificanceProfile(G, triad_cfg): """ Compute the significance profile of the patterns mapped in triad_cfg, inside directed graph G. - G : directed graph representing the network; - triads_cfg : dict mapping interesting triadic patterns codes, as in nx.triadic_census(), with explicit names. (e.g. triad_cfg = {'003' : 'Null', '012' : 'Single-edge'}) """ census = nx.triadic_census(G) in_degree_sequence = [d for n, d in G.in_degree()] # in degree sequence out_degree_sequence = [d for n, d in G.out_degree()] # out degree sequence #print("In_degree sequence %s" % in_degree_sequence) #print("Out_degree sequence %s" % out_degree_sequence) random_nets_census = [] for i in range(100): rand_G = nx.directed_configuration_model(in_degree_sequence, out_degree_sequence, create_using=nx.DiGraph, seed=i) random_nets_census.append(nx.triadic_census(rand_G)) real_census, random_census = mapTriadCodes(census,random_nets_census,triad_cfg) #print(real_census) #print(random_census) z_score = [] for p in real_census.keys(): print(p) N_real_p = real_census[p] N_rand_p = np.mean(random_census[p]) std = np.std(random_census[p]) z_p = ((N_real_p - N_rand_p)/std if std != 0 else 0) z_score.append(z_p) SP = [] for i in range(len(z_score)): z_norm = np.linalg.norm(z_score) norm_z_score = (z_score[i]/z_norm if z_norm != 0 else z_score[i]) SP.append(round(norm_z_score,4)) #print(SP) return SP
def __graphlet_configuration_model(self, G_in): """ Converts network input network into graph sequence and generates new configuration graph. Number of edges is not conserved! """ if G_in.is_directed(): inseq = G_in.in_degree().values() outseq = G_in.out_degree().values() H = nx.directed_configuration_model(inseq, outseq) H = nx.DiGraph(H) H.remove_edges_from(H.selfloop_edges()) else: seq = G_in.degree().values() H = nx.configuration_model(seq) H = nx.Graph(H) H.remove_edges_from(H.selfloop_edges()) return H.edges()
def k5net(power): return nx.directed_configuration_model( in_degree_sequence=10**power * [5], out_degree_sequence=10**power * [5], create_using=nx.DiGraph())
#k5net = nx.DiGraph() # TODO: replace with a test network of suitable size # TODO: Print results: how many seconds were taken for the test network of # 10**4 nodes, how many hours would a 26*10**6 nodes network take? # Run num_tests times and use the average or minimum running time in your calculations. # for i in range(1,5): # net=k5net(power=i) # print(f'Number of Nodes: {10**i}') # start=time.time() # pagerank_poweriter(net,d=0.85,iterations=10) # end=time.time() # escape = end - start # print(f'Time spent: {escape}') escapes = [] for i in range(num_tests): k5_net = nx.directed_configuration_model( in_degree_sequence=10**4 * [5], out_degree_sequence=10**4 * [5], create_using=nx.DiGraph()) start = time.time() pagerank_poweriter(k5_net, d=0.85, iterations=10) end = time.time() escape = end - start escapes.append(escape) print( f'Mean time spent for pageranking a network with {n_nodes} nodes using pagerank_poweriter(): {np.mean(escapes)}s' ) target = 26 * (10**6) print( f'Estimated time for a network with {target} nodes using pagerank_poweriter(): {np.mean(escapes)/n_nodes*target/3600} hours' ) # Investigating the running time of the random walker function
def generatenetwork(N, k, mode=0, kcutoff=0, m_mode=0, m_dist=3): # generate a network of N nodes with k edges # mode=0: constant k; mode1: degrees following a power law distribution with exponent k # m_mode: # output: a list of 3 items: # I0. a list of nodenames (string). # I1: a sub-list of inputs for eachnode. Each item in this sub-list is a node name (string) # I2: graph G of the network, in networkx format nodes = [] nodeinputs = [] # ith item is the inputnodes towards node i G = nx.DiGraph() nodestates = [] ## print nodestates if mode == 0: for i in range(0, N): nodename = 'N' + str(i) nodes.append(nodename) G.add_nodes_from(nodes) # generate edges: k inputs for each node for i in range(0, N): nodeinput = [] # randomly select k different nodes from all nodes except node i A = range(0, N) del A[i] B = random.sample(A, k) for j in B: nodeinput.append(nodes[j]) G.add_edge(nodes[j], nodes[i]) nodeinputs.append(nodeinput) if mode == 1: z1 = nx.utils.create_degree_sequence(N, nx.utils.powerlaw_sequence, exponent=k) if kcutoff > 0: for index in range(0, len(z1)): if z1[index] > kcutoff: z1[index] = kcutoff # outdegree dist, s.t. the sum of degrees are the same as z1 z2 = [] ## print z1, sum(z1) while sum(z1) != sum(z2): ## print sum(z2) z2 = nx.utils.create_degree_sequence(N, nx.utils.powerlaw_sequence, exponent=k) if kcutoff > 0: for index in range(0, len(z2)): if z2[index] > kcutoff: z2[index] = kcutoff ## print z2 G1 = nx.directed_configuration_model(z1, z2, create_using=nx.DiGraph()) def mapping(x): return 'N' + str(x) G = nx.relabel_nodes(G1, mapping) nodes = list(G.nodes()) for node in nodes: nodeinputs.append(G.predecessors(node)) if m_mode == 1: # TBD: generate distribution for node in nodes: ## max1 = 2 max1 = numpy.random.choice(numpy.arange(2, 4), p=[0.5, 0.5]) ## max1 = numpy.random.choice(numpy.arange(2, 5), p=[0.34, 0.33,0.33]) ## max1 = numpy.random.choice(numpy.arange(2, 6), p=[0.6, 0.25,0.1,0.05]) ## max1 = numpy.random.choice(numpy.arange(2, 7), p=[0.55, 0.25, 0.1, 0.05, 0.05]) ## max1 = numpy.random.choice(numpy.arange(2, 8), p=[0.5, 0.25, 0.125, 0.0625, 0.03125, 0.03125]) states = [] for i in range(0, max1): states.append(i) nodestates.append(states) # check all nodes to make sure # nodestates < total input minterms. If not, cutoff higher states in target node Flag = 1 while Flag == 1: Flag = 0 for node in nodes: inputcombi = 1 for input in nodeinputs[nodes.index(node)]: ## print input inputcombi *= len(nodestates[nodes.index(input)]) if len(nodestates[nodes.index(node)]) > inputcombi: ## print 'exceeding',node nodestates[nodes.index(node)] = range(0, inputcombi) Flag = 1 return [nodes, nodeinputs, G, nodestates]
def generateDirectedConfigurationModel(graph): in_degrees = graph.in_degree() out_degrees = graph.out_degree() in_degrees_list = [x[1] for x in list(in_degrees)] out_degrees_list = [x[1] for x in list(out_degrees)] return nx.directed_configuration_model(in_degrees_list, out_degrees_list, create_using=nx.DiGraph(), seed=random.seed())
print "Reciprocity: " + str(np.mean(modelReciprocity[:,n])) + "(" + str(np.std(modelReciprocity[:,n])) + ")" meanReciprocity = np.mean(modelReciprocity,axis=1) G,A,labels = brain_graph() brainReciprocity = reciprocity(A) configReciprocity = np.zeros([20,1]) nodes = G.nodes() inDeg = G.in_degree(); inDeg = [inDeg[node] for node in nodes] outDeg = G.out_degree(); outDeg = [outDeg[node] for node in nodes] for j in range(20): G_config = nx.directed_configuration_model(inDeg,outDeg) A_config = nx.adjacency_matrix(G_config) A_configInt = np.zeros(A_config.shape,dtype=int) A_configInt[A_config < 0.5] = 0 A_configInt[A_config > 0.5] = 1 configReciprocity[j] = reciprocity(A_configInt) from extract.brain_graph import binary_directed as brain_graph from network_plot.change_settings import set_all_text_fontsizes as set_fontsize import matplotlib #matplotlib.rc('axes',edgecolor='white')
def test_directed_configuation_mode(): G = nx.directed_configuration_model([], [], seed=0) assert_equal(len(G), 0)
G = nx.read_adjlist(args.graph_type, create_using=nx.DiGraph, nodetype=int) G = nx.DiGraph(G) remove_self_loops(G) bidirected = 0.0 connections = 0.0 for edge in G.edges(): connections += 1.0 if edge[0] < edge[1] and ((edge[1], edge[0]) in G.edges()): bidirected += 1.0 connections -= 1.0 print("Percent of connections that are bidirected: %s" % (100.0 * bidirected / connections)) if args.r is not None: rewire_graph(G, args.r) if args.degree_copy: node_list = list(G.nodes()) in_degs = [G.in_degree(node) for node in node_list] out_degs = [G.out_degree(node) for node in node_list] G = nx.DiGraph(nx.directed_configuration_model(in_degs, out_degs)) remove_self_loops(G) if args.export_edge_list: nx.write_adjlist(G, args.export_edge_list) while not rm.done(): best_rule = rm.determine_best_rule() rm.contract_valid_tuples(best_rule) rm.cost_comparison()
for kappa in kappa_set: for i in range(N_ITER): print i arr_gamma = np.linspace(0,5,30) arr_kappa = np.logspace(0,3,30) for k in range (nbins): ##Get the degree sequence## degree_seq = gen_rand_powerlaw(N,arr_gamma[k], kappa) if (sum(degree_seq)%2!=0): degree_seq[0]+=1 G = nx.directed_configuration_model(degree_seq, degree_seq) ##Construct equivalent bipartite graph## bi = nx.Graph() bi.add_nodes_from(G.nodes(), bipartite = 0) bi.add_nodes_from([x+N for x in G.nodes()],bipartite = 1) bi.add_edges_from([(x[0],x[1]+N) for x in G.edges()]) matching[k] = len(nx.max_weight_matching(bi))/2.0 ##Fraction of driver nodes## nd = (N-matching[k])/N test[k] += nd ##Plotting## test/=N_ITER plt.plot()
return M #---------------------------------------------------------- if __name__ == "__main__": multiplier, input_file, output_file = get_params() input_network = load_network(input_file) print("sum-in =" + str(sum(list(input_network.in_degree().values())))) print("sum-out =" + str(sum(list(input_network.out_degree().values())))) if multiplier > 0: indegree_sequence = [ int(d * multiplier) for d in list(input_network.in_degree().values()) ] outdegree_sequence = [ int(d * multiplier) for d in list(input_network.out_degree().values()) ] elif multiplier < 0: print("Only positive multipliers accepted ") print("original: " + str(len(input_network.nodes())) + " nodes, " + str(len(input_network.edges())) + " edges") #http://networkx.github.io/documentation/networkx-1.7/reference/generated/networkx.generators.degree_seq.directed_configuration_model.html#networkx.generators.degree_seq.directed_configuration_model M = nx.directed_configuration_model(indegree_sequence, outdegree_sequence, create_using=input_network) #remove parallel edges print( str(multiplier) + "X analog: " + str(len(M.nodes())) + " nodes", str(len(M.edges())) + " edges")
node_colors = [pageRank_pi[node] for node in nodes] fig = visualize_network(network, node_positions, cmap=cmap, node_size=node_size, node_colors=node_colors, title="PageRank power iteration") fig.savefig('./network_visualization_pagerank_pi.pdf') # Investigating th of the power iteration fuction num_tests = 3 # YOUR CODE HERE k5net = nx.directed_configuration_model(10**3 * [5], 10**3 * [5], create_using=nx.DiGraph) # TODO: Print results: how many seconds were taken for the test network of # 10**4 nodes, how many hours would a 26*10**6 nodes network take? # Run num_tests times and use the average or minimum running time in your calculations. t0 = time.clock() # Investigating the running time of the random walker function n_nodes = 10**3 # YOUR CODE HERE n_steps = 1000 * n_nodes # TODO: set such number of steps that each node gets visited on average 1000 times pageRank_rw = pageRank(k5net, d, n_steps) print('time elapsed for random : ', (time.clock() - t0)) t0 = time.clock() pageRank_pi = pagerank_poweriter(k5net, d, n_nodes * 10) print('time elapsed for power iteration : ', (time.clock() - t0))
def test_directed_configuation_raise_unequal(): zin = [5, 3, 3, 3, 3, 2, 2, 2, 1, 1] zout = [5, 3, 3, 3, 3, 2, 2, 2, 1, 2] nx.directed_configuration_model(zin, zout)
def test_directed_configuation_raise_unequal(): with pytest.raises(nx.NetworkXError): zin = [5, 3, 3, 3, 3, 2, 2, 2, 1, 1] zout = [5, 3, 3, 3, 3, 2, 2, 2, 1, 2] nx.directed_configuration_model(zin, zout)
def test_directed_configuation_model(): G = nx.directed_configuration_model([], [], seed=0) assert len(G) == 0
def test_simple_directed_configuation_model(): G = nx.directed_configuration_model([1, 1], [1, 1], seed=0) assert len(G) == 2
def test_simple_directed_configuation_model(): G = nx.directed_configuration_model([1, 1], [1, 1], seed=0) assert_equal(len(G), 2)
def test_directed_configuation_model(): G = nx.directed_configuration_model([], [], seed=0) assert_equal(len(G), 0)
return list(influences) p_edges = [0.1, 0.2] alpha = [0.1, 0.2, 0.3, 0.4, 0.5] mc_greedy = 100 k = 5 # n = 100 # z=random_powerlaw_tree_sequence(5, gamma=3, seed=None, tries=1000) din = np.random.randint(low=0, high=5, size=7) dout = np.random.permutation(din) # We now expect an edge from node 0 to a new node, node 3. D = nx.directed_configuration_model(din, dout) D = nx.DiGraph(D) print(din) print([d for n, d in D.in_degree]) print() print(dout) print([d for n, d in D.out_degree]) print() print(list(filter(lambda x: x[0] == x[1], D.edges))) nx.draw(D, with_labels=True) plt.show()
def getEnsambleBowTieNetworkValues(gx, samples=5, model="configuration", debug=False): """ Returns an object BowTieEnsembleNetworkValues for the ensamble of graphs created based on the network topology of the given graph under a certain model. Parameters ---------- gx : Networkx DiGraph Networkx DiGraph samples : number of graph in the ensamble Name of the model : "configuration", "ER", default: "configuration", Model with wich the graphs will be created, valid modesl are: "configuration" : directed_configuration_model "ER" : Erdős-Rényi Gnp graph fast_gnp_random_graph "configuration" will be used if no other valid name is given. Returns ------- R : BowTieEnsembleNetworkValues TODO """ def __printDebug(*val): if debug: print(list(val)) din = list(d for n, d in gx.in_degree()) dout = list(d for n, d in gx.out_degree()) n = gx.order() m = nx.number_of_edges(gx) p = m / (n * (n - 1)) resultsNodesAllGraph = [] reusltNodesWeaklyLCC = [] resultNodesTubes = [] resultNodesTendrilsIn = [] resultsNodesIn = [] resultNodesSCC = [] resultNodesOut = [] resultNodesTendrilsOut = [] resultNodesOCC = [] if (model == "ER"): print("Gnp values. n:", n, ", p:", p) # add the values for each realization for i in range(samples): if (model == "ER"): g = nx.fast_gnp_random_graph(n=n, p=p, directed=True) else: g = nx.directed_configuration_model(din, dout) btV = getBowTieNetworkValues(g) resultsNodesAllGraph.append(btV.nrNodesAllGraph) reusltNodesWeaklyLCC.append(btV.nrNodesWeaklyLCC) resultNodesTubes.append(btV.nrNodesTubes) resultNodesTendrilsIn.append(btV.nrNodesTendrilsIn) resultsNodesIn.append(btV.nrNodesIn) resultNodesSCC.append(btV.nrNodesSCC) resultNodesOut.append(btV.nrNodesOut) resultNodesTendrilsOut.append(btV.nrNodesTendrilsOut) resultNodesOCC.append(btV.nrNodesOCC) __printDebug("Result Nodes All Graph: ", resultsNodesAllGraph) # create dictionary bowTieEnsembleNetworkValues = BowTieEnsembleNetworkValues( meanNrNodesAllGraph=np.mean(resultsNodesAllGraph, dtype=np.float64), meanNrNodesWeaklyLCC=np.mean(reusltNodesWeaklyLCC, dtype=np.float64), meanNrNodesTubes=np.mean(resultNodesTubes, dtype=np.float64), meanNrNodesTendrilsIn=np.mean(resultNodesTendrilsIn, dtype=np.float64), meanNrNodesIn=np.mean(resultsNodesIn, dtype=np.float64), meanNrNodesSCC=np.mean(resultNodesSCC, dtype=np.float64), meanNrNodesOut=np.mean(resultNodesOut, dtype=np.float64), meanNrNodesTendrilsOut=np.mean(resultNodesTendrilsOut, dtype=np.float64), meanNrNodesOCC=np.mean(resultNodesOCC, dtype=np.float64), stdNrNodesAllGraph=np.std(resultsNodesAllGraph, dtype=np.float64), stdNrNodesWeaklyLCC=np.std(reusltNodesWeaklyLCC, dtype=np.float64), stdNrNodesTubes=np.std(resultNodesTubes, dtype=np.float64), stdNrNodesTendrilsIn=np.std(resultNodesTendrilsIn, dtype=np.float64), stdNrNodesIn=np.std(resultsNodesIn, dtype=np.float64), stdNrNodesSCC=np.std(resultNodesSCC, dtype=np.float64), stdNrNodesOut=np.std(resultNodesOut, dtype=np.float64), stdNrNodesTendrilsOut=np.std(resultNodesTendrilsOut, dtype=np.float64), stdNrNodesOCC=np.std(resultNodesOCC, dtype=np.float64)) return bowTieEnsembleNetworkValues