def _analyze_lsdb_graph(self): for ns in self.nses: for name in [srv.name for srv in self.services if nx.get_edge_attributes(self.graphs[ns], srv.name)]: G = nx.Graph([(s, d, data) for s, d, data in self.graphs[ns].edges(data=True) if data[name] == True]) if G.nodes: self.ns[ns][f'{name}_number_of_nodes'] = len(G.nodes) self.ns[ns][f'{name}_number_of_edges'] = len(G.edges) if not nx.is_connected(G): self.ns[ns][f'{name}_is_fully_connected'] = False self.ns[ns][f'{name}_center'] = False else: self.ns[ns][f'{name}_is_fully_connected'] = True self.ns[ns][f'{name}_center'] = nx.barycenter(G) self.ns[ns][f'{name}_self_loops'] = list(nx.nodes_with_selfloops(G)) self.ns[ns][f'{name}_number_of_disjoint_sets'] = len(list(nx.connected_components(G))) self.ns[ns][f'{name}_degree_histogram'] = nx.degree_histogram(G) # if there are too many degrees than the column gets too big if len(self.ns[ns][f'{name}_degree_histogram']) > 6: self.ns[ns][f'{name}_degree_histogram'] = '...' else: for k in [f'{name}_is_fully_connected', f'{name}_center', f'{name}_self_loops', f'{name}_number_of_disjoint_sets', f'{name}_degree_histogram', f'{name}_number_of_nodes', f'{name}_number_of_edges']: self.ns[ns][k] = None
def analyze_distance(): center = nx.center(G) barycenter = nx.barycenter(G) diameter = nx.diameter(G) table = prettytable.PrettyTable(['center', 'barycenter', 'diameter']) table.add_row([center, barycenter, diameter]) print(table)
def test_sp_kwarg(self): # Complete graph K_5. Normally it works... K_5 = nx.complete_graph(5) sp = dict(nx.shortest_path_length(K_5)) assert_equal(nx.barycenter(K_5, sp=sp), list(K_5)) # ...but not with the weight argument for u, v, data in K_5.edges.data(): data['weight'] = 1 assert_raises(ValueError, nx.barycenter, K_5, sp=sp, weight='weight') # ...and a corrupted sp can make it seem like K_5 is disconnected del sp[0][1] assert_raises(nx.NetworkXNoPath, nx.barycenter, K_5, sp=sp)
def compute_features(self): # barycenter self.add_feature( "barycenter_size", lambda graph: len(nx.barycenter(ensure_connected(graph))), "The barycenter is the subgraph which minimises a distance function", InterpretabilityScore(4), ) # center self.add_feature( "center_size", lambda graph: len(nx.center(ensure_connected(graph))), "The center is the subgraph of nodes with eccentricity equal to radius", InterpretabilityScore(3), ) # extrema bounding self.add_feature( "center_size", lambda graph: nx.extrema_bounding(ensure_connected(graph)), "The largest distance in the graph", InterpretabilityScore(4), ) # periphery self.add_feature( "periphery", lambda graph: len(nx.periphery(ensure_connected(graph))), "The number of peripheral nodes in the graph", InterpretabilityScore(4), ) # eccentricity self.add_feature( "eccentricity", lambda graph: list( nx.eccentricity(ensure_connected(graph)).values()), "The distribution of node eccentricity across the network", InterpretabilityScore(3), statistics="centrality", )
def barycenter_as_subgraph(self, g, **kwargs): """Return the subgraph induced on the barycenter of g""" b = nx.barycenter(g, **kwargs) assert_is_instance(b, list) assert_less_equal(set(b), set(g)) return g.subgraph(b)
def barycenter_as_subgraph(self, g, **kwargs): """Return the subgraph induced on the barycenter of g""" b = nx.barycenter(g, **kwargs) assert isinstance(b, list) assert set(b) <= set(g) return g.subgraph(b)
def _compute_links(self, gr, conn_weigths, parts, partitioning_kwargs): total_connect(gr, [b.id for b in self.downloaded_buildings], {b.id: str(b.id) + '_a' for b in self.downloaded_buildings}, connection_type_weigths=conn_weigths, phases=1, type='link', logger=self.logger) street_nodes = [n for n in gr.nodes if gr.nodes[n]['type'] in ('street', 'street_link')] self.logger.debug('Minimum spanning tree calculation...') tc = deepcopy(gr) # clustering self.logger.debug('Cluster elaboration...') valid_nodes = [n for n in gr.nodes if gr.nodes[n]['type'] == 'load'] for n in tc.nodes: if tc.nodes[n]['type'] == 'load': tc.nodes[n]['pwr'] = tc.nodes[n]['building']['area'] * 0.01 else: tc.nodes[n]['pwr'] = 0.01 tot_pwr = sum(nx.get_node_attributes(tc, 'pwr').values()) start_time = time() clusters = partition_grid(tc, [x * tot_pwr for x in parts], 'virtual_length', 'pwr', partitioning_kwargs) end_time = time() self.logger.info(f'Clustering step completed in {end_time - start_time:.2f} seconds') loads_in_clusters = [len([n for n in cluster if gr.nodes[n]['type'] == 'load']) for cluster in clusters] self.logger.debug('{} clusters created of cardinality: {}'.format(len(clusters), loads_in_clusters)) # knowing the clusters, now we make n copies of the original graph and we generate the clustered subgraph # by clipping away what's unneeded subcoms = [] for clno, cluster in enumerate(clusters): self.logger.debug('Subgraph #{} creation and clipping...'.format(clno)) gr_part = deepcopy(tc) relabel = {x: str(x) + '_' + str(clno) for x in street_nodes} # each cluster must have its own street nodes, because it's possible that the street paths overlap partially nx.relabel_nodes(gr_part, relabel, copy=False) # calculating best traf position no = deepcopy(gr_part.nodes) realnodes = [n for n in no if gr_part.nodes[n]['type'] == 'load' and n in cluster] gro_part = nxs.steiner_tree(gr_part, realnodes) barycenter = nx.barycenter(gro_part, weight='virtual_length')[0] gr_part.add_edge('trmain' + str(clno), barycenter, phases=3, type='entry') gr_part.nodes['trmain' + str(clno)]['type'] = 'source' gr_part.nodes['trmain' + str(clno)]['pos'] = [x+0.000005 for x in gr_part.nodes[barycenter]['pos']] # removing loads not pertaining to this cluster (refines input) gr_part.remove_nodes_from([n for n in no if gr_part.nodes[n]['type'] == 'load' and n not in cluster]) # steiner # gr_part = nxs.steiner_tree(gr_part, realnodes, weight='virtual_length') # mst gr_part = nx.minimum_spanning_tree(gr_part, weight='virtual_length') # remove street nodes that are not used by this cluster sps = nx.shortest_path(gr_part, 'trmain' + str(clno), weight='virtual_length') sps = {k: v for k, v in sps.items() if k in valid_nodes and k in cluster} used_nodes = set() for target, path in sps.items(): if gr_part.nodes[target]['type'] in ('street', 'street_link'): raise ValueError else: used_nodes.update(set(path)) unused_nodes = set(gr_part.nodes) - used_nodes gr_part.remove_nodes_from(unused_nodes) assert nx.number_connected_components(gr_part) <= 1 assert nx.is_tree(gr_part) subcoms.append(gr_part) # union of the subgraphs try: self.g = nx.union_all(subcoms) except nx.NetworkXError: from itertools import combinations ls = [(n, set(x.nodes)) for n, x in enumerate(subcoms)] for n1x, n2y in combinations(ls, 2): n1, x = n1x n2, y = n2y print('{},{} : {}'.format(n1, n2, x.intersection(y))) raise self.logger.info('Grid created')
#12. Знайдіть медіану графа, тобто таку його вершину, що сума відстаней від неї до інших вершин мінімальна. import networkx as nx import matplotlib.pyplot as plt G = nx.gnm_random_graph(6, 6) plt.subplot(121) nx.draw(G, with_labels=True, font_weight='bold') print("Медіана: ", nx.barycenter(G)) plt.show()
def barycenter_size(graph): """barycenter_size""" return len(nx.barycenter(ensure_connected(graph)))
def barycenter_size_weighted(graph): """barycenter_size_weighted""" return len(nx.barycenter(ensure_connected(graph), weight="weight"))
# block_cut_tree.view(filename='block_cut_tree') print("m", file=main) for i in nx.algorithms.connectivity.k_edge_components(Full_graph, 2): for j in i: print(j, end=",", file=main) print('', file=main) print("o", file=main) minimum_spanning_tree = ( nx.algorithms.tree.minimum_spanning_tree(Main_graph)).edges minimum_spanning_tree_graph = gv.Graph() print("Minimum spanning tree:", minimum_spanning_tree, file=main) print("minimum_spanning_tree.size =", len(minimum_spanning_tree), file=main) color_the_edges(minimum_spanning_tree_graph, minimum_spanning_tree) # minimum_spanning_tree_graph.view(filename='minimum_spanning_tree', quiet_view=True) print("p", file=main) print(nx.barycenter(nx.algorithms.tree.minimum_spanning_tree(Main_graph)), file=main) print("q", file=main) prufer_minimum_spanning_tree = nx.algorithms.tree.minimum_spanning_tree( Main_graph) Prufer_graph = nx.Graph() prufer_graph_edges = [] for index, vertex in enumerate(Main_graph.nodes): print(vertex, ":", index, file=fout) for edge in Main_graph.edges(data=True): for index, vertex in enumerate(Main_graph.nodes): if vertex == edge[0]: first_index = index if vertex == edge[1]: second_index = index if index not in Prufer_graph.nodes: