def Scale_free(N, gamma, wseed): s = nx.utils.powerlaw_sequence(N, gamma) #100 nodes, power-law exponent 2.5 if wseed == 1: G = nx.expected_degree_graph(s, seed=123, selfloops=False) else: G = nx.expected_degree_graph(s, selfloops=False) return G
def test_expected_degree_graph(): # test that fixed seed delivers the same graph deg_seq = [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3] G1 = nx.expected_degree_graph(deg_seq, seed=1000) G2 = nx.expected_degree_graph(deg_seq, seed=1000) assert_true(nx.is_isomorphic(G1, G2)) G1 = nx.expected_degree_graph(deg_seq, seed=10) G2 = nx.expected_degree_graph(deg_seq, seed=10) assert_true(nx.is_isomorphic(G1, G2))
def gen_delta_graph(n, ks, ps, simple=False, model='conf'): ''' Generate a graph whose degree distribution is of finite support. Parameters ---------- n : number of nodes ks : list Degrees the nodes can have ps : list Probability for each edge, must have same length as ks and sum to 1 ''' # the following function generates a degree sequence of length n pkmap = choicemap(ks,ps) dseqfun = lambda n: [ nx.utils.weighted_choice(pkmap) for i in range(n) ] success = False while not success: dseq = dseqfun(n) if nx.is_valid_degree_sequence(dseq): success = True if model == 'conf': G = nx.configuration_model(dseq) elif model == 'chung-lu': G = nx.expected_degree_graph(dseq) else: raise Exception('wrong graph model requested') if simple: G = nx.Graph(G) # removes multi-edges G.remove_edges_from( G.selfloop_edges() ) # remove self loop return G
def synth_plots(): num_nodes = 100 samples = 5 chunglu_M = [] kron_M = [] HRG_M = [] pHRG_M = [] G_M = [] for i in range(0, samples): ##BA Graph G = nx.erdos_renyi_graph(num_nodes, .1) G_M.append(G) for i in range(0, samples): chunglu_M.append(nx.expected_degree_graph(G.degree().values())) HRG_M_s, degree = HRG.stochastic_hrg(G, samples) HRG_M = HRG_M + HRG_M_s pHRG_M_s = PHRG.probabilistic_hrg(G, samples) pHRG_M = pHRG_M + pHRG_M_s for i in range(0, samples): P = kronfit(G) k = math.log(num_nodes, 2) kron_M.append( product.kronecker_random_graph(int(math.floor(k)), P, directed=False)) metrics.draw_network_value(G_M, chunglu_M, HRG_M, pHRG_M, kron_M)
def DegreeSequenceExpected(deg_sequence, seed=None): """ Returns a random graph with expected given degree sequence. Raises a NetworkX error if the proposed degree sequence cannot be that of a graph. One requirement is that the sum of the degrees must be even, since every edge must be incident with two vertices. INPUT: - ``deg_sequence`` - a list of integers with each entry corresponding to the expected degree of a different vertex. - ``seed`` - a ``random.Random`` seed or a Python ``int`` for the random number generator (default: ``None``). EXAMPLES:: sage: G = graphs.DegreeSequenceExpected([1,2,3,2,3]) sage: G Looped graph on 5 vertices sage: G.show() # long time REFERENCE: [CL2002]_ """ if seed is None: seed = int(current_randstate().long_seed() % sys.maxsize) import networkx return Graph(networkx.expected_degree_graph([int(i) for i in deg_sequence], seed=seed), loops=True)
def DegreeSequenceExpected(deg_sequence, seed=None): """ Returns a random graph with expected given degree sequence. Raises a NetworkX error if the proposed degree sequence cannot be that of a graph. One requirement is that the sum of the degrees must be even, since every edge must be incident with two vertices. INPUT: - ``deg_sequence`` - a list of integers with each entry corresponding to the expected degree of a different vertex. - ``seed`` - for the random number generator. EXAMPLES:: sage: G = graphs.DegreeSequenceExpected([1,2,3,2,3]) sage: G.edges(labels=False) [(0, 2), (0, 3), (1, 1), (1, 4), (2, 3), (2, 4), (3, 4), (4, 4)] sage: G.show() # long time REFERENCE: .. [ChungLu2002] Chung, Fan and Lu, L. Connected components in random graphs with given expected degree sequences. Ann. Combinatorics (6), 2002 pp. 125-145. """ if seed is None: seed = current_randstate().long_seed() import networkx return Graph(networkx.expected_degree_graph([int(i) for i in deg_sequence], seed=seed), loops=True)
def _random_poisson_graph(self, n=10, mu=2.5, ratio=0.9, remove_unconnected=True, remove_self_loops=True, Nsignals=5, Nstimuli=5): from scipy.stats import poisson z = [poisson.rvs(mu) for i in range(0,n)] G = nx.expected_degree_graph(z) self.clear() # converts to strings edges = [(unicode(e[0]), unicode(e[1])) for e in G.edges()] assert ratio >= 0 assert ratio <= 1 N = int(len(edges)* ratio) edges_pos = edges[0:N] edges_neg = edges[N:] self.add_edges_from(edges_pos, link="+") self.add_edges_from(edges_neg, link="-") # remove self loop first if remove_self_loops: self.remove_self_loops() if remove_unconnected == False: # add all nodes (even though they me be unconnected self.add_nodes_from(G.nodes()) ranks = self.get_same_rank() sources = ranks[0] sinks = ranks[max(ranks.keys())] Nstim = min(len(sources), Nstimuli) Nsignals = min(len(sinks), Nsignals) self._stimuli = sources[0:Nstim] self._signals = sinks[0:Nsignals] self.set_default_node_attributes()
def transform_all(filenames, party_ids, min_gateways, max_gateways, edges): comments = [] all_gateways = [] graphs, gateways_map = {}, {} for i in range(len(filenames)): fname, p = filenames[i], party_ids[i] g = random.randint(min_gateways, max_gateways) graph, gateways, comment = transform_one_to_local(fname, p, g) graphs[p] = graph gateways_map[p] = gateways all_gateways = all_gateways + gateways comments.append(comment) # Generate the public graph using scale-free distribution s = nx.utils.powerlaw_sequence(len(all_gateways), 1.7) G = nx.expected_degree_graph(s, selfloops=False) public_edges = [] for n1, n2 in G.edges(): g1, g2 = all_gateways[n1], all_gateways[n2] if get_party(g1) == get_party(g2): continue public_edges.append((g1, g2)) print len(all_gateways), len(public_edges) return graphs, gateways_map, (all_gateways, compute_diameter(all_gateways, public_edges), public_edges), comments
def DegreeSequenceExpected(deg_sequence, seed=None): """ Returns a random graph with expected given degree sequence. Raises a NetworkX error if the proposed degree sequence cannot be that of a graph. One requirement is that the sum of the degrees must be even, since every edge must be incident with two vertices. INPUT: - ``deg_sequence`` - a list of integers with each entry corresponding to the expected degree of a different vertex. - ``seed`` - for the random number generator. EXAMPLE:: sage: G = graphs.DegreeSequenceExpected([1,2,3,2,3]) sage: G.edges(labels=False) [(0, 2), (0, 3), (1, 1), (1, 4), (2, 3), (2, 4), (3, 4), (4, 4)] sage: G.show() # long time REFERENCE: - [1] Chung, Fan and Lu, L. Connected components in random graphs with given expected degree sequences. Ann. Combinatorics (6), 2002 pp. 125-145. """ if seed is None: seed = current_randstate().long_seed() import networkx return graph.Graph(networkx.expected_degree_graph( [int(i) for i in deg_sequence], seed=seed), loops=True)
def graph_generator(): import networkx as nx s = nx.utils.powerlaw_sequence(1000, 2.5) G = nx.expected_degree_graph(s, selfloops=False) pos = nx.spring_layout( G ) #this command makes a layout of position of all nodes (instead of spring_layout you can use fruchterman_reingold_layout or other layouts so you will have different figures for graph) ,since we want to have different color for different states of nodes so we have to first make a layout then in graph draw function we make node by different colores,in fact ( I seperated this command and also above command (G=nx.Graph()) from the function of graph draw for two reasons : 1- seperating pos command causes we have a fixed layout for all graph draw (for example if initial node is located in south west of picture of graph(in graph draw plot)then for any time we plot graph again (for example for different timesteps) then the initial infected node is still in south west of graph plot, so we can see spread of rumor and its expand from south west of graph during different timesteps 2- by seperating graph generator function (G = nx.Graph command) we save time because we perform this command only one time and for any times that we plot graph we would not use this command again, so plots will be made fastly adjacency = G.adjacency_list() return G, pos, adjacency
def log_normal_config(N, mu, sigma): """ Builds a configuration model with the given graph size and log-normal parameters """ samples = np.random.lognormal(mean=mu, sigma=sigma, size=N) # Maybe there's a better way to do this: return nx.expected_degree_graph(samples, selfloops=False) rounded_w = [int(round(_)) for _ in w] option_2 = nx.configuration_model(rounded_w)
def create_powerlaw_graph(N, gamma=1.6, path=None, version=''): seq = nx.utils.powerlaw_sequence(N, gamma) graph = nx.expected_degree_graph(seq, selfloops=False) graph = sorted(nx.connected_component_subgraphs(graph), key=len, reverse=True)[0] if path is not None: nx.write_gpickle(graph, f'{path}/SF_gamma={gamma}_N={N}{version}.gpickle') return graph
def main(argsD): runs = argsD['runs'] print print 'dataset: {}\nruns: {},'.format(argsD['orig'][0], runs), G = read_load_graph(argsD['orig'][0]) print "(V,E): {},{}".format(G.number_of_nodes(), G.number_of_edges()) ## if metrix if argsD['netstats']: compute_netstats(G, G.name) exit(0) if argsD['peek']: compute_netstats_peek(G, G.name, piikshl=True) exit(0) ofname = "Results/" + G.name + ".shl" # if argsD['rods']: ofname = ofname.split(".")[0] + "_rods.shl" database = shelve.open(ofname) if argsD['rods']: print '% --> Control Rods' start_time = time.time() HRG_M, degree = HRG.stochastic_hrg(G, runs) print(" %d, %s seconds ---" % (G.number_of_nodes(), time.time() - start_time)) database['rods_hstars'] = HRG_M else: print '% --> PHRG' start_time = time.time() A = PHRG.probabilistic_hrg(G, runs) # returns a list of Hstar graphs # print(" --- Total %s seconds ---" % (time.time() - start_time)) print(" %d, %s seconds ---" % (G.number_of_nodes(), time.time() - start_time)) database['prob_hstars'] = A print start_time = time.time() print '% --> CHLU' clgs = [] z = G.degree().values() for i in range(runs): clgs.append(nx.expected_degree_graph(z)) database['clgs'] = clgs print(" %d, %s seconds ---" % (G.number_of_nodes(), time.time() - start_time)) # -- Kron Prod Graphs print '% --> Kron' start_time = time.time() database['kpgs'] = grow_graphs_using_krongen(G, gn=G.name, nbr_runs=runs) print(" %d, %s seconds ---" % (G.number_of_nodes(), time.time() - start_time)) database.close() return
def poissongraph(n, mu): z = np.zeros(n) #n is number of nodes for i in range(n): z[i] = poisson.rvs(mu) #mu is the expected value G = nx.expected_degree_graph(z) H = G.to_directed() #print(G.edges()) #for (fr, to) in list(G.edges()): # G.add_edge(to,fr) # print(to,fr) return H
def chung_lu_graphs(g, n=5): graphs = [] for _ in range(n): print('Starting Chung-Lu....') start_time = time() degree_seq = sorted(g.degree().values()) g_chung_lu = nx.expected_degree_graph(degree_seq, selfloops=False) graphs.append(g_chung_lu) print('Chung-Lu ran in {} secs'.format(round(time() - start_time, 3))) return graphs
def get_clgm_graph_recurrence(graph,recurrence_nbr=1): """ Returns ------- output file of the x,y values """ for r in range(recurrence_nbr): z = graph.degree().values() cl_grph = nx.expected_degree_graph(z) graph = cl_grph print '\tChung-Lu -> run:', r, graph.number_of_nodes(),graph.number_of_edges() return graph
def _generate_cl(qubo, seed): """Generate a Chung-Lu graph that matches a graph's degree distriubtion""" # Compute the parameters needed for CL degree_distribution = sorted([qubo.degree(node) for node in qubo.nodes()]) # Generate graph graph = nx.expected_degree_graph(w=degree_distribution, selfloops=False, seed=seed) # Name the graph graph.graph['name'] = '{}-{}-{}'.format(qubo.graph['name'], 'cl', seed) # Sanitize the graph and return graph = reset_labels(graph) return graph
def SimExpDeg2(G, sim): res = [] deg_to_sim = [i[1] for i in G.degree_iter()] for j in range(1, sim + 1): Gtemp = nx.expected_degree_graph( w=deg_to_sim, seed=j, selfloops=False) #maybe try ?nx.powerlaw_cluster_graph()? Whe1 = domSet_Whe(G=Gtemp) Whe2 = domSet_Whe2(G=Gtemp) MinMy = min([len(Whe1), len(Whe2)]) MinSet = MinMy res.append([j, len(Whe1), len(Whe2), MinSet]) return res
def county_graph(degree_sequence, l, p, verbose=True): #Generate the first clique county_graph = nx.expected_degree_graph(degree_sequence, selfloops=False) #Add l-1 additional cliques to the existing graph if(verbose): print("Generating cliques") for _ in range(0, l-1): #Generate a clique to add to the existing county addition = nx.expected_degree_graph(degree_sequence, selfloops=False) #Force a disjoint union in the network county_graph = nx.disjoint_union(county_graph, addition) nodes = list(county_graph) #Loop over all edges and randomly rewire them with probability p if(verbose): print("Rewiring Edges") for (u,v) in county_graph.edges(): #Choose whether to rewire with probability p if(np.random.rand(1)[0] < p): new_end = np.random.choice(nodes) if(county_graph.has_edge(u, new_end)): continue county_graph.remove_edge(u, v) county_graph.add_edge(u, new_end) if(verbose): print("Removing Disconnected Components") for component in list(nx.connected_components(county_graph)): if(len(component)<5): for node in component: county_graph.remove_node(node) return county_graph
def initGraphMod(N, k, niter, alpha=None): """ Init graph, assets are drawn from a power law distribution, other information are chosen at random in ranged specified in the paper N: number of nodes alpha: power law exponent, if None is drawn at random in [1.5,5.0] returns: list of nodes information sorted by decreasing assets """ nodes = {} if alpha == None: alpha = np.random.uniform(1.5, 5) sample = Statistics.powerlaw_sample(100, 10**10, alpha, N) for i in range(N): equity = np.random.uniform(0, 0.25) cash = np.random.uniform(0, 0.25) # node information nodes[i] = { 'ASSET': sample[i], 'EQUITY': equity, 'DEPOSITS': np.random.uniform(0, 1 - equity), 'CASH': cash, #'LOANS': np.random.uniform(k*(1-cash)/niter,(1-cash)), 'LOANS': np.random.uniform(k * (1 - cash) / niter, (k + 1) * (1 - cash) / niter), # 'LOANS': np.random.uniform(0, 1-cash), # 0: False, 1: default, 2: failure, 3: exogenous 'BANKRUPT': 0 } # sorting sort = sorted(nodes.values(), key=lambda n: n['ASSET'], reverse=True) # nodes as dictionary nodes = {i: sort[i] for i in range(len(sort))} # undirected edges exp_degree = map(lambda x: nodes[x]['ASSET'], nodes.keys()) exp_degree = exp_degree / max(exp_degree) exp_degree = exp_degree * N g = nx.expected_degree_graph(exp_degree, selfloops=False) # remove cycles #g = nx.bfs_tree(g,0) for i in g.nodes(): g.node[i] = nodes[i] return g
def gen_SF(nodes, gam, name): # Generate Graph s = nx.utils.powerlaw_sequence(nodes, gam) s = [6*i for i in s] G = nx.expected_degree_graph(s, selfloops=False) # Transform into dataframe of edges source, target = [], [] for edge in G.edges(): source.append(edge[0]) target.append(edge[1]) d = pd.DataFrame({'source': source,'target': target}) # Save to file d.to_csv('./network_data/SF/' + name +'.csv', index=False)
def sample_event_network(self): # sample subset of nodes, by sampling a degree sequence with several zeros degrees = np.zeros(self.node_number, dtype=np.int16) for n in self.network.nodes: if rnd.rand() <= self.network.nodes[n]['event_prob']: degrees[n] = self.event_degree_distribution.sample() else: degrees[n] = 0 # sample network self.event_network = nx.expected_degree_graph(degrees, seed=None, selfloops=False) for e in self.event_network.edges: self.event_network[e[0]][ e[1]]['p'] = self.infection_probability_distribution.sample() self.event_network[e[0]][e[1]]['mlogp'] = -np.log( self.event_network[e[0]][e[1]]['p'])
def build_chunglu_graph(N, exp_val, fn_edges=[ lambda G, x, y: npr.exponential(2), lambda G, x, y: np.abs(npr.normal(0, 1)) ], directed=True, self=False): A = nx.expected_degree_graph( [np.round(v) for v in truncated_power_law(N, exp_val)], selfloops=self) A.remove_nodes_from(list(nx.isolates(A))) A = nx.relabel_nodes(A, {k: v for k, v in zip(A.nodes, range(len(A.nodes)))}) A = nx.DiGraph(A) return networkx_wrapper(A, self=self, directed=directed, fn_edges=fn_edges)
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 generate_random_network(self): """ Generates a random network with given degree distribution """ degrees = self.main_degree_distribution.sample_sequence( self.node_number) self.network = nx.expected_degree_graph(degrees, seed=None, selfloops=False) for n in self.network.nodes: self.network.nodes[n]['state'] = State(self.model) self.network.nodes[n][ 'event_prob'] = self.event_probability.sample() for e in self.network.edges: self.network[e[0]][ e[1]]['p'] = self.infection_probability_distribution.sample() self.network[e[0]][e[1]]['mlogp'] = -np.log( self.network[e[0]][e[1]]['p'])
def get_random_graphs(temporal_graphs): random_graphs = dict() # generate random graphs from temporal_graphs for k, v in temporal_graphs.iteritems(): egraph = v rgraph = nx.expected_degree_graph(egraph.degree().values(), selfloops=False) # mapping = dict(zip( # sorted(rgraph.nodes()), # sorted(egraph.nodes()) # )) # nx.relabel_nodes(rgraph, mapping, copy=False) random_graphs[k] = rgraph # print "generated random graph for timestep: {} - # edges: {}/{}".format(k, len(rgraph.edges()), len(egraph.edges()) ) return random_graphs
def initGraphMod(N,k,niter,alpha=None): """ Init graph, assets are drawn from a power law distribution, other information are chosen at random in ranged specified in the paper N: number of nodes alpha: power law exponent, if None is drawn at random in [1.5,5.0] returns: list of nodes information sorted by decreasing assets """ nodes = {} if alpha == None: alpha = np.random.uniform(1.5,5) sample = Statistics.powerlaw_sample(100, 10**10, alpha,N) for i in range(N): equity = np.random.uniform(0, 0.25) cash = np.random.uniform(0, 0.25) # node information nodes[i] = { 'ASSET': sample[i], 'EQUITY': equity, 'DEPOSITS': np.random.uniform(0,1-equity), 'CASH': cash, #'LOANS': np.random.uniform(k*(1-cash)/niter,(1-cash)), 'LOANS': np.random.uniform(k*(1-cash)/niter,(k+1)*(1-cash)/niter), # 'LOANS': np.random.uniform(0, 1-cash), # 0: False, 1: default, 2: failure, 3: exogenous 'BANKRUPT': 0 } # sorting sort = sorted(nodes.values(), key=lambda n: n['ASSET'], reverse=True) # nodes as dictionary nodes = {i: sort[i] for i in range(len(sort))} # undirected edges exp_degree = map(lambda x:nodes[x]['ASSET'],nodes.keys()) exp_degree = exp_degree / max(exp_degree) exp_degree = exp_degree * N g = nx.expected_degree_graph(exp_degree,selfloops=False) # remove cycles #g = nx.bfs_tree(g,0) for i in g.nodes(): g.node[i] = nodes[i] return g
def SimExpDeg(G, sim): res = [] deg_to_sim = [i[1] for i in G.degree_iter()] for j in range(1, sim + 1): Gtemp = nx.expected_degree_graph( w=deg_to_sim, seed=j, selfloops=False) #maybe try ?nx.powerlaw_cluster_graph()? Whe1 = domSet_Whe(G=Gtemp) Whe2 = domSet_Whe2(G=Gtemp) MinMy = min([len(Whe1), len(Whe2)]) #This searches 2 below, then if 2 below is found searches 4 below MinSet = domCheckFirst2(G=Gtemp, max=MinMy - 1, min=MinMy - 2) if MinSet == None: MinSet = MinMy elif MinSet == (MinMy - 2): MinSet2 = domCheckFirst(G=Gtemp, max=MinMy - 3, min=MinMy - 4) if MinSet2 != None: MinSet = MinSet2 res.append([j, len(Whe1), len(Whe2), MinSet]) return res
def check_small_world_bias(corr, dmin=3, dmax=30, dnum=10, randomizations=20, seed=1): """ Test to see if a method for defining edges produces networks with excess clustering This is based on Zalesky et al. Neuroimage 60:2096 2012 which demonstrated that standard correlation applied to random time series resulted in networks with unexpectedly high clustering. The cause is the observation that if A is correlated with B and B is correlated with C, there is a high probability that A is correlated with C """ np.fill_diagonal(corr, 0) # no self connections # L_null = np.zeros(10) C_null = np.zeros(10) # L_rand = np.zeros(10) C_test = np.zeros(10) thresholds = np.zeros(10) densities = np.linspace(3, 30, 10) for i, density in enumerate(densities): graph, threshold = corr_matrix_to_graph(corr, density, tol=0.0001) if len(graph) > 1: # L_test[i] = nx.average_shortest_path_length(graph) C_test[i] = nx.average_clustering(graph) thresholds[i] = threshold # L = np.zeros(randomizations) C = np.zeros(randomizations) for r in range(randomizations): random = nx.expected_degree_graph(graph.degree().values(), selfloops=False, seed=seed + density + 100*r) # L[r] = nx.average_shortest_path_length(random) C[r] = nx.average_clustering(random) # L_null[i] = np.average(L) C_null[i] = np.average(C) return C_test, C_null, densities
def __init__(self, input_file=None, prob=1.0, sample_type=None, nodes=None, edges=None, degree=None, shrink_ratio=1.0): """ the function is used to generate graph according different kinds of input requirements :param input_file: input file as string "foo.txt" :param prob: probability value for sampling process :param sample_type: two types: "karate_club" and "random_graph" :param nodes: if sample_type is "random_graph", here number of nodes must be declared :param edges: if sample_type is "random_graph", here number of edges can be declared :param degree: if sample_type is "random_graph", here degree of each node can be declared :param shrink_ratio: the ratio used to be randomly shrink the input file for large input file :return: None """ self.G = nx.Graph() if input_file: self.edges = self.import_file(input_file, shrink_ratio) self.G.add_edges_from(self.edges) self.edges = self.G.edges() if sample_type: if sample_type == "karate_club": self.G = nx.karate_club_graph() self.edges = self.G.edges() elif sample_type == "random_graph": if nodes and edges: self.G = nx.gnm_random_graph(nodes, edges) self.edges = self.G.edges() elif nodes and degree: w = [nodes*degree for i in range(nodes)] # w = p*n for all nodes self.G = nx.expected_degree_graph(w) # configuration model self.edges = self.G.edges() else: raise Exception('Wrong: ' + "nodes/edges/degree is None!") else: raise Exception("Wrong: please give input file name!") self.random_select_edge_at(prob) self.prob = prob
def test_expected_degree_graph_selfloops(): deg_seq = [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3] G1 = nx.expected_degree_graph(deg_seq, seed=1000, selfloops=False) G2 = nx.expected_degree_graph(deg_seq, seed=1000, selfloops=False) assert_true(nx.is_isomorphic(G1, G2)) assert_equal(len(G1), 12)
def test_expected_degree_graph_empty(): # empty graph has empty degree sequence deg_seq = [] G = nx.expected_degree_graph(deg_seq) assert_equal(dict(G.degree()), {})
def test_expected_degree_graph_skew(): deg_seq = [10, 2, 2, 2, 2] G1 = nx.expected_degree_graph(deg_seq, seed=1000) G2 = nx.expected_degree_graph(deg_seq, seed=1000) assert_true(nx.is_isomorphic(G1, G2)) assert_equal(len(G1), 5)
def create_expected_degree_graph(degseq,selfloops=True): g = nx.expected_degree_graph(degseq,int(time.time()),selfloops); alist = g.degree().values(); blist = create_blist(alist); return nx.bipartite.configuration_model(alist,blist);
n_community, 'grid': nx.generators. grid_2d_graph, # grid_2d_graph(m, n, periodic=False, create_using=None) 'gnp': nx.generators. fast_gnp_random_graph, # fast_gnp_random_graph(n, p, seed=None, directed=False) 'ba': nx.generators. barabasi_albert_graph, # barabasi_albert_graph(n, m, seed=None) 'pow_law': lambda **kwargs: nx.configuration_model( nx.generators.random_powerlaw_tree_sequence( **kwargs, gamma=3, tries=2000)), 'except_deg': lambda **kwargs: nx.expected_degree_graph(**kwargs, selfloops=False), 'cycle': nx.cycle_graph, 'c_l': nx.circular_ladder_graph, 'lobster': nx.random_lobster # 'ego': nx.generators.ego_graph # ego_graph(G, n, radius=1, center=True, undirected=False, distance=None) } class GraphGenerator: def __init__(self, graph_type='grid', possible_params_dict=None, corrupt_func=None):
def get_random_graph_g(B): G = nx.from_numpy_matrix(B) degree_seq = nx.degree(G).values() RG = nx.expected_degree_graph(degree_seq, seed=None, selfloops=False) return RG
def gen_graph(mu, num_nodes): expected_degrees = poisson.rvs(mu, size=num_nodes) return expected_degree_graph(expected_degrees)