def _betmap(G_normalized_weight_sources_tuple): """Pool for multiprocess only accepts functions with one argument. This function uses a tuple as its only argument. We use a named tuple for python 3 compatibility, and then unpack it when we send it to `betweenness_centrality_source` """ return nx.betweenness_centrality_source(*G_normalized_weight_sources_tuple)
def test_K5(self): """Betweenness Centrality Sources: K5""" G = nx.complete_graph(5) b = nx.betweenness_centrality_source(G, weight=None, normalized=False) b_answer = {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0} for n in sorted(G): assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
def _btwn_pool(G_tuple): """ Wrapper for the method nx.betweenness_centrality_source. :param G_tuple: nodes of graph G :return dict: nodes with their betweenness centrality """ return nx.betweenness_centrality_source(*G_tuple)
def test_P3(self): """Betweenness Centrality Sources: P3""" G = nx.path_graph(3) b_answer = {0: 0.0, 1: 1.0, 2: 0.0} b = nx.betweenness_centrality_source(G, weight=None, normalized=True) for n in sorted(G): assert almost_equal(b[n], b_answer[n])
def test_P3(self): """Betweenness Centrality Sources: P3""" G = nx.path_graph(3) b_answer = {0: 0.0, 1: 1.0, 2: 0.0} b = nx.betweenness_centrality_source(G, weight=None, normalized=True) for n in sorted(G): assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
def test_K5(self): """Betweenness Centrality Sources: K5""" G = nx.complete_graph(5) b = nx.betweenness_centrality_source(G, weight=None, normalized=False) b_answer = {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0} for n in sorted(G): assert almost_equal(b[n], b_answer[n])
def test_K5(self): """Betweenness centrality: K5""" G = nx.complete_graph(5) b = nx.betweenness_centrality_source(G, weight=None, normalized=False) b_answer = {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0} for n in sorted(G): assert_almost_equal(b[n], b_answer[n])
def test_P3(self): """Betweenness centrality: P3""" G = nx.path_graph(3) b_answer = {0: 0.0, 1: 1.0, 2: 0.0} b = nx.betweenness_centrality_source(G, weight=None, normalized=True) for n in sorted(G): assert_almost_equal(b[n], b_answer[n])
def test_P3(self): """Betweenness centrality: P3""" G = networkx.path_graph(3) b_answer = {0: 0.0, 1: 1.0, 2: 0.0} b = networkx.betweenness_centrality_source(G, weighted_edges=False, normalized=True) for n in sorted(G): assert_almost_equal(b[n], b_answer[n])
def __init__(self, df, node_columns): self.df = df self.node_columns = node_columns self.nodes = self.get_nodes() self.edges = self.get_edges() self.graph = self.get_graph() self.colors = self.get_colors() self.igraph = self.get_igraph() self.betweenness = nx.betweenness_centrality_source(self.graph, normalized=True, weight='weight', sources=self.nodes)
def function(sample): pnm_params = { 'data_path': r"Z:\Robert_TOMCAT_3_netcdf4_archives\for_PNM", # 'data_path': r"A:\Robert_TOMCAT_3_netcdf4_archives\processed_1200_dry_seg_aniso_sep", 'sample': sample # 'sample': 'T3_100_7_III', # 'sample': 'T3_025_3_III', # 'sample': 'T3_300_8_III', } pnm = PNM(**pnm_params) graph = pnm.graph sourcesraw = np.unique(pnm.data['label_matrix'][:, :, 0])[1:] targetsraw = np.unique(pnm.data['label_matrix'][:, :, -1])[1:] sources = [] targets = [] for k in sourcesraw: if k in graph.nodes(): sources.append(k) for k in targetsraw: if k in graph.nodes(): targets.append(k) centrality = np.array(list(nx.betweenness_centrality(graph).values())) centrality2 = np.array( list( nx.betweenness_centrality_subset(graph, sources, targets, normalized=True).values())) centrality5 = np.array( list( nx.betweenness_centrality_source(graph, sources=sources).values())) waiting_times = np.zeros(len(centrality)) vx = pnm.data.attrs['voxel'] V = pnm.data['volume'].sum(dim='label') V0 = 0.95 * V.max() ref = V[V < V0].argmax() meanflux = (V0 * vx**3 / pnm.data['time'][ref]) # meanflux = V[-1]*vx**3/pnm.data['time'][-1] meanflux = meanflux.data i = 0 for node in graph.nodes(): wt = 0 nb = list(nx.neighbors(graph, node)) if len(nb) > 0: t0 = pnm.data['sig_fit_data'].sel(label=node, sig_fit_var='t0 [s]') t0nb = pnm.data['sig_fit_data'].sel(label=nb, sig_fit_var='t0 [s]') upstream_nb = np.where(t0nb < t0) if len(upstream_nb[0]) > 0: wt = t0 - t0nb[upstream_nb].max() waiting_times[i] = wt i += 1 return centrality, waiting_times, meanflux, centrality5, centrality2, sample
def get_betweenness_centrality(network_file, gene_file): G = read_network(network_file) gene_set = read_gene_list(gene_file) g = nx.subgraph(G, gene_set) betweenness_centarlity_sum = 0 betweenness_centarlity = list(nx.betweenness_centrality_source(g).values()) for i in range(0, len(betweenness_centarlity)): betweenness_centarlity_sum = betweenness_centarlity_sum + betweenness_centarlity[ i] betweenness_centarlity_result = betweenness_centarlity_sum / len( betweenness_centarlity) # print("clustering_coefficient的结果为:%s" % betweenness_centarlity_result) return betweenness_centarlity_result
def btwn_pool(G_tuple): return nx.betweenness_centrality_source(*G_tuple)
def core_function(samples, timesteps, i, peak_fun=peak_fun, inlet_count=2, diff_data=None): prng3 = np.random.RandomState(i) sample = prng3.choice(samples) pnm_params = { 'data_path': r"Z:\Robert_TOMCAT_3_netcdf4_archives\for_PNM", # 'data_path': r"A:\Robert_TOMCAT_3_netcdf4_archives\processed_1200_dry_seg_aniso_sep", 'sample': sample, 'graph': nx.watts_strogatz_graph(400, 8, 0.1, seed=i + 1), # 'sample': 'T3_100_7_III', # 'sample': 'T3_025_3_III', # 'sample': 'T3_300_8_III', 'inlet_count': inlet_count + 2, 'randomize_pore_data': True, 'seed': (i + 3)**3 } pnm = PNM(**pnm_params) graph = pnm.graph.copy() R0 = 1 #E17#4E15 # print('inlet R '+str(R0)) # ####fixed inlets for validation samples############## # inlet_nodes = [162,171,207] # if pnm.sample == 'T3_100_7_III': inlet_nodes = [86, 89, 90, 52] # if pnm.sample == 'T3_300_8_III': inlet_nodes = [ 13, 63, 149] # inlets = [] # found_inlets = [] # for inlet in inlet_nodes: # inlet = int(inlet) # if inlet in pnm.label_dict: # inlets.append(pnm.label_dict[inlet]) # found_inlets.append(inlet) # else: # print('Failed to find node named', inlet) # print('Got inlet labels:', inlets) # pnm.inlets = inlets # pnm.build_inlets() ############# if diff_data is None: diff_data = pnm.pore_diff_data sourcesraw = np.unique(pnm.data['label_matrix'][:, :, 0])[1:] targetsraw = np.unique(pnm.data['label_matrix'][:, :, -1])[1:] sources = [] targets = [] for k in sourcesraw: if k in graph.nodes(): sources.append(k) for k in targetsraw: if k in graph.nodes(): targets.append(k) sources2 = sources.copy() inlets = pnm.inlets.copy() # prng7 = np.random.RandomState(i+3) # # inlets = prng7.choice(sources, 2) # sources = prng7.choice(sources, 4) # inlets = sources found_inlets = [] for inlet in inlets: found_inlets.append(pnm.nodes[inlet]) v_inlets = -1 * (np.arange(len(inlets)) + 1) for k in range(len(inlets)): graph.add_edge(found_inlets[k], v_inlets[k]) inlets = v_inlets sources = inlets inlet_radii = np.zeros(len(inlets)) inlet_heights = np.zeros(len(inlets)) r_i = pnm.radi.copy() lengths = pnm.volumes.copy() / np.pi / r_i**2 r_i = np.concatenate([r_i, inlet_radii]) lengths = np.concatenate([lengths, inlet_heights]) adj_matrix = nx.to_numpy_array(graph) result_sim = core_simulation(r_i, lengths, adj_matrix, inlets, timesteps, pnm_params, peak_fun, i, pnm, diff_data, R0=R0) centrality = np.array(list(nx.betweenness_centrality(graph).values())) centrality3 = np.array( list( nx.betweenness_centrality_source(graph, sources=sources2).values())) centrality2 = np.array( list( nx.betweenness_centrality_subset(graph, sources, targets, normalized=True).values())) centrality4 = np.array( list( nx.betweenness_centrality_subset(graph, sources2, targets, normalized=True).values())) centrality5 = np.array( list( nx.betweenness_centrality_source(graph, sources=sources).values())) result_sim = result_sim + (centrality5, ) result_sim = result_sim + (centrality4, ) result_sim = result_sim + (centrality3, ) result_sim = result_sim + (centrality2, ) result_sim = result_sim + (pnm.data.attrs['tension'], centrality) # V0 = result_sim[2] time = result_sim[0] V = result_sim[1] ref = np.argmax(V) mean_flux = V[ref] / time[ref] result_sim = result_sim + (mean_flux, ) result_sim = result_sim + (graph, ) return result_sim
def parpro(MAP_normalized_weight_source_tuple): return net.betweenness_centrality_source( *MAP_normalized_weight_source_tuple)
# node_partitions = list(partitions(G.nodes(), int(len(G)/part_generator))) # num_partitions = len(node_partitions) # # bet_map = p.map(btwn_pool, # zip([G]*num_partitions, # [True]*num_partitions, # [None]*num_partitions, # node_partitions)) # # bt_c = bet_map[0] # for bt in bet_map[1:]: # for n in bt: # bt_c[n] += bt[n] # return bt_c bt = nx.betweenness_centrality_source(G_fb) top = 10 max_nodes = sorted(bt.iteritems(), key=lambda v: -v[1])[:top] bt_values = [5] * len(G_fb.nodes()) bt_colors = [0] * len(G_fb.nodes()) for max_key, max_val in max_nodes: bt_values[max_key] = 150 bt_colors[max_key] = 2 plt.axis("off") print('Plotting') nx.draw_networkx(G_fb, pos=spring_pos, cmap=plt.get_cmap("rainbow"), node_color=bt_colors,
def _betmap((G,normalized,weight,sources)): """Pool for multiprocess only accepts functions with one argument. This function uses a tuple as its only argument. """ return nx.betweenness_centrality_source(G,normalized,weight,sources)