Python networkx.diameter() Examples
The following are 19
code examples of networkx.diameter().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
networkx
, or try the search function
.
Example #1
Source File: utils.py From GraphRNN with MIT License | 7 votes |
def decode_graph(adj, prefix): adj = np.asmatrix(adj) G = nx.from_numpy_matrix(adj) # G.remove_nodes_from(nx.isolates(G)) print('num of nodes: {}'.format(G.number_of_nodes())) print('num of edges: {}'.format(G.number_of_edges())) G_deg = nx.degree_histogram(G) G_deg_sum = [a * b for a, b in zip(G_deg, range(0, len(G_deg)))] print('average degree: {}'.format(sum(G_deg_sum) / G.number_of_nodes())) if nx.is_connected(G): print('average path length: {}'.format(nx.average_shortest_path_length(G))) print('average diameter: {}'.format(nx.diameter(G))) G_cluster = sorted(list(nx.clustering(G).values())) print('average clustering coefficient: {}'.format(sum(G_cluster) / len(G_cluster))) cycle_len = [] cycle_all = nx.cycle_basis(G, 0) for item in cycle_all: cycle_len.append(len(item)) print('cycles', cycle_len) print('cycle count', len(cycle_len)) draw_graph(G, prefix=prefix)
Example #2
Source File: utils.py From graph-generation with MIT License | 6 votes |
def decode_graph(adj, prefix): adj = np.asmatrix(adj) G = nx.from_numpy_matrix(adj) # G.remove_nodes_from(nx.isolates(G)) print('num of nodes: {}'.format(G.number_of_nodes())) print('num of edges: {}'.format(G.number_of_edges())) G_deg = nx.degree_histogram(G) G_deg_sum = [a * b for a, b in zip(G_deg, range(0, len(G_deg)))] print('average degree: {}'.format(sum(G_deg_sum) / G.number_of_nodes())) if nx.is_connected(G): print('average path length: {}'.format(nx.average_shortest_path_length(G))) print('average diameter: {}'.format(nx.diameter(G))) G_cluster = sorted(list(nx.clustering(G).values())) print('average clustering coefficient: {}'.format(sum(G_cluster) / len(G_cluster))) cycle_len = [] cycle_all = nx.cycle_basis(G, 0) for item in cycle_all: cycle_len.append(len(item)) print('cycles', cycle_len) print('cycle count', len(cycle_len)) draw_graph(G, prefix=prefix)
Example #3
Source File: main.py From scTDA with GNU General Public License v3.0 | 6 votes |
def dendritic_graph(self): """ Builds skeleton of the topological representation (used internally) """ diam = networkx.diameter(self.gl) g3 = networkx.Graph() dicdend = {} for n in range(diam-1): nodedist = [] for k in self.pl: dil = networkx.shortest_path_length(self.gl, self.root, k) if dil == n: nodedist.append(str(k)) g2 = self.gl.subgraph(nodedist) dicdend[n] = sorted(networkx.connected_components(g2)) for n2, yu in enumerate(dicdend[n]): g3.add_node(str(n) + '_' + str(n2)) if n > 0: for n3, yu2 in enumerate(dicdend[n-1]): if networkx.is_connected(self.gl.subgraph(list(yu)+list(yu2))): g3.add_edge(str(n) + '_' + str(n2), str(n-1) + '_' + str(n3)) return g3, dicdend
Example #4
Source File: network_analysis.py From ditto with BSD 3-Clause "New" or "Revised" License | 5 votes |
def split_network_into_feeders(self): """ This function splits the network into subnetworks corresponding to the feeders. .. note:: add_feeder_information should be called first """ if self.feeder_names is None or self.feeder_nodes is None: raise ValueError( "Cannot split the network into feeders because feeders are unknown. Call add_feeder_information first." ) for cpt, feeder_name in enumerate(self.feeder_names): feeder_node_list = self.feeder_nodes[cpt] self.feeder_networks[feeder_name] = self.G.graph.subgraph(feeder_node_list) # If the feeder information is perfect, that is the end of the story. # But, most of the time, some nodes are missing from the feeder information. # This means that we get disconnected feeder networks which will cause some # issues later (when computing the diameter for example) # For this reason, the following code is trying to infer the missing nodes # and edges such that the feeder networks are all connected in the end. while not nx.is_connected(self.feeder_networks[feeder_name]): self.connect_disconnected_components(feeder_name) feeder_node_list = self.feeder_nodes[cpt] self.feeder_networks[feeder_name] = self.G.graph.subgraph( feeder_node_list ) # Build the node_feeder_mapping # for node in self.feeder_nodes[cpt]: for node in self.feeder_networks[feeder_name].nodes(): self.node_feeder_mapping[node] = feeder_name
Example #5
Source File: test_distance_measures.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def test_radius_exception(self): G = networkx.Graph() G.add_edge(1, 2) G.add_edge(3, 4) assert_raises(networkx.NetworkXError, networkx.diameter, G)
Example #6
Source File: test_distance_measures.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def test_bound_diameter(self): assert_equal(networkx.diameter(self.G, usebounds=True), 6)
Example #7
Source File: test_distance_measures.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def test_diameter(self): assert_equal(networkx.diameter(self.G), 6)
Example #8
Source File: test_distance_measures.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_radius_exception(self): G = networkx.Graph() G.add_edge(1, 2) G.add_edge(3, 4) assert_raises(networkx.NetworkXError, networkx.diameter, G)
Example #9
Source File: test_distance_measures.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_bound_diameter(self): assert_equal(networkx.diameter(self.G, usebounds=True), 6)
Example #10
Source File: test_distance_measures.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_diameter(self): assert_equal(networkx.diameter(self.G), 6)
Example #11
Source File: test_distance_measures.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def test_radius_exception(self): G=networkx.Graph() G.add_edge(1,2) G.add_edge(3,4) assert_raises(networkx.NetworkXError, networkx.diameter, G)
Example #12
Source File: test_distance_measures.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def test_diameter(self): assert_equal(networkx.diameter(self.G),6)
Example #13
Source File: network_analysis.py From ditto with BSD 3-Clause "New" or "Revised" License | 5 votes |
def diameter(self, *args): """Returns the diameter of the network.""" if args: return nx.diameter(args[0]) else: return nx.diameter(self.G.graph)
Example #14
Source File: graphs.py From pyDcop with BSD 3-Clause "New" or "Revised" License | 5 votes |
def calc_diameter(nodes): """ Warning : this only works on tree graphs !! For arbitrary graphs, we need to compute the shortest path between any two vertices and take the length of the greatest of these paths :param nodes: :return: """ # Calculate the diameter of a graph made of variables and relations # first pick a random node in the tree and use a BFS to find the furthest # node in the graph root = random.choice(nodes) node, distance = find_furthest_node(root, nodes) _, distance = find_furthest_node(node, nodes) return distance
Example #15
Source File: dmeasure.py From netrd with MIT License | 5 votes |
def network_node_dispersion(G): """ This function calculates the network node dispersion of a graph G. This function also returns the average of the each node-distance distribution. Parameters ---------- G (nx.Graph): the graph in question. Returns ------- nnd (float): the nearest node dispersion nd_vec (np.ndarray): a vector of averages of the node-distance distributions """ N = G.number_of_nodes() nd = node_distance(G) pdfm = np.mean(nd, axis=0) # NOTE: the paper says that the normalization is the diameter plus one, # but the previous implementation uses the number of nonzero entries in the # node-distance matrix. This number should typically be the diameter plus # one anyway. norm = np.log(nx.diameter(G) + 1) ndf = nd.flatten() # calculate the entropy, with the convention that 0/0 = 0 entr = -1 * sum(ndf * np.log(ndf, out=np.zeros_like(ndf), where=(ndf != 0))) nnd = max([0, entropy(pdfm) - entr / N]) / norm return nnd, pdfm
Example #16
Source File: statistics.py From generative-graph-transformer with MIT License | 5 votes |
def get_diameters(graph): r""" Compute histogram of connected components diameters for a graph. :param graph: graph representation in networkx format: nx.from_numpy_matrix(A) :return: list of connected components diameters """ diams = [] for g in nx.connected_component_subgraphs(graph): diams.append(nx.diameter(g)) diams = list(filter(lambda a: a != 0, diams)) return np.array(diams)
Example #17
Source File: graphs.py From pyDcop with BSD 3-Clause "New" or "Revised" License | 5 votes |
def graph_diameter(variables, relations): """ Compute the graph diameter(s). If the graph contains several independent sub graph, returns a list the diamater of each of the subgraphs. :param variables: :param relations: :return: """ diams = [] g = as_networkx_graph(variables, relations) components = (g.subgraph(c).copy() for c in nx.connected_components(g)) for c in components: diams.append(nx.diameter(c)) return diams
Example #18
Source File: data.py From GraphRNN with MIT License | 4 votes |
def Graph_synthetic(seed): G = nx.Graph() np.random.seed(seed) base = np.repeat(np.eye(5), 20, axis=0) rand = np.random.randn(100, 5) * 0.05 node_features = base + rand # # print('node features') # for i in range(node_features.shape[0]): # print(np.around(node_features[i], decimals=4)) node_distance_l1 = np.ones((node_features.shape[0], node_features.shape[0])) node_distance_np = np.zeros((node_features.shape[0], node_features.shape[0])) for i in range(node_features.shape[0]): for j in range(node_features.shape[0]): if i != j: node_distance_l1[i,j] = np.sum(np.abs(node_features[i] - node_features[j])) # print('node distance', node_distance_l1[i,j]) node_distance_np[i, j] = 1 / np.sum(np.abs(node_features[i] - node_features[j]) ** 2) print('node distance max', np.max(node_distance_l1)) print('node distance min', np.min(node_distance_l1)) node_distance_np_sum = np.sum(node_distance_np, axis=1, keepdims=True) embedding_dist = node_distance_np / node_distance_np_sum # generate the graph average_degree = 9 for i in range(node_features.shape[0]): for j in range(i + 1, embedding_dist.shape[0]): p = np.random.rand() if p < embedding_dist[i, j] * average_degree: G.add_edge(i, j) G.remove_nodes_from(nx.isolates(G)) print('num of nodes', G.number_of_nodes()) print('num of edges', G.number_of_edges()) G_deg = nx.degree_histogram(G) G_deg_sum = [a * b for a, b in zip(G_deg, range(0, len(G_deg)))] print('average degree', sum(G_deg_sum) / G.number_of_nodes()) print('average path length', nx.average_shortest_path_length(G)) print('diameter', nx.diameter(G)) G_cluster = sorted(list(nx.clustering(G).values())) print('average clustering coefficient', sum(G_cluster) / len(G_cluster)) print('Graph generation complete!') # node_features = np.concatenate((node_features, np.zeros((1,node_features.shape[1]))),axis=0) return G, node_features # G = Graph_synthetic(10) # return adj and features from a single graph
Example #19
Source File: data.py From graph-generation with MIT License | 4 votes |
def Graph_synthetic(seed): G = nx.Graph() np.random.seed(seed) base = np.repeat(np.eye(5), 20, axis=0) rand = np.random.randn(100, 5) * 0.05 node_features = base + rand # # print('node features') # for i in range(node_features.shape[0]): # print(np.around(node_features[i], decimals=4)) node_distance_l1 = np.ones((node_features.shape[0], node_features.shape[0])) node_distance_np = np.zeros((node_features.shape[0], node_features.shape[0])) for i in range(node_features.shape[0]): for j in range(node_features.shape[0]): if i != j: node_distance_l1[i,j] = np.sum(np.abs(node_features[i] - node_features[j])) # print('node distance', node_distance_l1[i,j]) node_distance_np[i, j] = 1 / np.sum(np.abs(node_features[i] - node_features[j]) ** 2) print('node distance max', np.max(node_distance_l1)) print('node distance min', np.min(node_distance_l1)) node_distance_np_sum = np.sum(node_distance_np, axis=1, keepdims=True) embedding_dist = node_distance_np / node_distance_np_sum # generate the graph average_degree = 9 for i in range(node_features.shape[0]): for j in range(i + 1, embedding_dist.shape[0]): p = np.random.rand() if p < embedding_dist[i, j] * average_degree: G.add_edge(i, j) G.remove_nodes_from(nx.isolates(G)) print('num of nodes', G.number_of_nodes()) print('num of edges', G.number_of_edges()) G_deg = nx.degree_histogram(G) G_deg_sum = [a * b for a, b in zip(G_deg, range(0, len(G_deg)))] print('average degree', sum(G_deg_sum) / G.number_of_nodes()) print('average path length', nx.average_shortest_path_length(G)) print('diameter', nx.diameter(G)) G_cluster = sorted(list(nx.clustering(G).values())) print('average clustering coefficient', sum(G_cluster) / len(G_cluster)) print('Graph generation complete!') # node_features = np.concatenate((node_features, np.zeros((1,node_features.shape[1]))),axis=0) return G, node_features # G = Graph_synthetic(10) # return adj and features from a single graph