Python networkx.minimum_spanning_edges() Examples
The following are 16
code examples of networkx.minimum_spanning_edges().
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: test_mst.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_nan_weights(self): # Edge weights NaN never appear in the spanning tree. see #2164 G = self.G G.add_edge(0, 12, weight=float('nan')) edges = nx.minimum_spanning_edges(G, algorithm=self.algo, data=False, ignore_nan=True) actual = sorted((min(u, v), max(u, v)) for u, v in edges) expected = [(u, v) for u, v, d in self.minimum_spanning_edgelist] assert_edges_equal(actual, expected) # Now test for raising exception edges = nx.minimum_spanning_edges(G, algorithm=self.algo, data=False, ignore_nan=False) assert_raises(ValueError, list, edges) # test default for ignore_nan as False edges = nx.minimum_spanning_edges(G, algorithm=self.algo, data=False) assert_raises(ValueError, list, edges)
Example #2
Source File: cycles.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _min_cycle_basis(comp, weight): cb = [] # We extract the edges not in a spanning tree. We do not really need a # *minimum* spanning tree. That is why we call the next function with # weight=None. Depending on implementation, it may be faster as well spanning_tree_edges = list(nx.minimum_spanning_edges(comp, weight=None, data=False)) edges_excl = [frozenset(e) for e in comp.edges() if e not in spanning_tree_edges] N = len(edges_excl) # We maintain a set of vectors orthogonal to sofar found cycles set_orth = [set([edge]) for edge in edges_excl] for k in range(N): # kth cycle is "parallel" to kth vector in set_orth new_cycle = _min_cycle(comp, set_orth[k], weight=weight) cb.append(list(set().union(*new_cycle))) # now update set_orth so that k+1,k+2... th elements are # orthogonal to the newly found cycle, as per [p. 336, 1] base = set_orth[k] set_orth[k + 1:] = [orth ^ base if len(orth & new_cycle) % 2 else orth for orth in set_orth[k + 1:]] return cb
Example #3
Source File: test_mst.py From aws-kube-codesuite with Apache License 2.0 | 6 votes |
def test_nan_weights(self): # Edge weights NaN never appear in the spanning tree. see #2164 G = self.G G.add_edge(0, 12, weight=float('nan')) edges = nx.minimum_spanning_edges(G, algorithm=self.algo, data=False, ignore_nan=True) actual = sorted((min(u, v), max(u, v)) for u, v in edges) expected = [(u, v) for u, v, d in self.minimum_spanning_edgelist] assert_edges_equal(actual, expected) # Now test for raising exception edges = nx.minimum_spanning_edges(G, algorithm=self.algo, data=False, ignore_nan=False) assert_raises(ValueError, list, edges) # test default for ignore_nan as False edges = nx.minimum_spanning_edges(G, algorithm=self.algo, data=False) assert_raises(ValueError, list, edges)
Example #4
Source File: spanning_tree.py From complex_network with GNU General Public License v2.0 | 5 votes |
def main(): # build up a graph filename = '../../florentine_families_graph.gpickle' G = nx.read_gpickle(filename) # Spanning tree mst = nx.minimum_spanning_tree(G) out_file = 'florentine_families_graph_minimum_spanning_tree.png' PlotGraph.plot_graph(G, filename=out_file, colored_edges=mst.edges()) edges = nx.minimum_spanning_edges(G, weight='weight', data=True) list_edges = list(edges) print(list_edges)
Example #5
Source File: test_mst.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def test_mst_edges(self): edgelist=sorted(nx.minimum_spanning_edges(self.G)) assert_equal(edgelist,self.tree_edgelist)
Example #6
Source File: test_mst.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_minimum_edges(self): edges = nx.minimum_spanning_edges(self.G, algorithm=self.algo) # Edges from the spanning edges functions don't come in sorted # orientation, so we need to sort each edge individually. actual = sorted((min(u, v), max(u, v), d) for u, v, d in edges) assert_edges_equal(actual, self.minimum_spanning_edgelist)
Example #7
Source File: test_mst.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_without_data(self): edges = nx.minimum_spanning_edges(self.G, algorithm=self.algo, data=False) # Edges from the spanning edges functions don't come in sorted # orientation, so we need to sort each edge individually. actual = sorted((min(u, v), max(u, v)) for u, v in edges) expected = [(u, v) for u, v, d in self.minimum_spanning_edgelist] assert_edges_equal(actual, expected)
Example #8
Source File: test_mst.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_unicode_name(self): """Tests that using a Unicode string can correctly indicate Borůvka's algorithm. """ edges = nx.minimum_spanning_edges(self.G, algorithm=u'borůvka') # Edges from the spanning edges functions don't come in sorted # orientation, so we need to sort each edge individually. actual = sorted((min(u, v), max(u, v), d) for u, v, d in edges) assert_edges_equal(actual, self.minimum_spanning_edgelist)
Example #9
Source File: test_mst.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_multigraph_keys_min(self): """Tests that the minimum spanning edges of a multigraph preserves edge keys. """ G = nx.MultiGraph() G.add_edge(0, 1, key='a', weight=2) G.add_edge(0, 1, key='b', weight=1) min_edges = nx.minimum_spanning_edges mst_edges = min_edges(G, algorithm=self.algo, data=False) assert_edges_equal([(0, 1, 'b')], list(mst_edges))
Example #10
Source File: test_mst.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def test_minimum_edges(self): edges = nx.minimum_spanning_edges(self.G, algorithm=self.algo) # Edges from the spanning edges functions don't come in sorted # orientation, so we need to sort each edge individually. actual = sorted((min(u, v), max(u, v), d) for u, v, d in edges) assert_edges_equal(actual, self.minimum_spanning_edgelist)
Example #11
Source File: test_mst.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def test_without_data(self): edges = nx.minimum_spanning_edges(self.G, algorithm=self.algo, data=False) # Edges from the spanning edges functions don't come in sorted # orientation, so we need to sort each edge individually. actual = sorted((min(u, v), max(u, v)) for u, v in edges) expected = [(u, v) for u, v, d in self.minimum_spanning_edgelist] assert_edges_equal(actual, expected)
Example #12
Source File: test_mst.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def test_unicode_name(self): """Tests that using a Unicode string can correctly indicate Borůvka's algorithm. """ edges = nx.minimum_spanning_edges(self.G, algorithm=u'borůvka') # Edges from the spanning edges functions don't come in sorted # orientation, so we need to sort each edge individually. actual = sorted((min(u, v), max(u, v), d) for u, v, d in edges) assert_edges_equal(actual, self.minimum_spanning_edgelist)
Example #13
Source File: test_mst.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def test_multigraph_keys_min(self): """Tests that the minimum spanning edges of a multigraph preserves edge keys. """ G = nx.MultiGraph() G.add_edge(0, 1, key='a', weight=2) G.add_edge(0, 1, key='b', weight=1) min_edges = nx.minimum_spanning_edges mst_edges = min_edges(G, algorithm=self.algo, data=False) assert_edges_equal([(0, 1, 'b')], list(mst_edges))
Example #14
Source File: minimum_spanning_tree.py From CityEnergyAnalyst with MIT License | 4 votes |
def calc_minimum_spanning_tree(input_network_shp, output_network_folder, building_nodes_shp, output_edges, output_nodes, weight_field, type_mat_default, pipe_diameter_default): # read shapefile into networkx format into a directed graph graph = nx.read_shp(input_network_shp) # transform to an undirected graph iterator_edges = graph.edges(data=True) G = nx.Graph() # plant = (11660.95859999981, 37003.7689999986) for (x, y, data) in iterator_edges: G.add_edge(x, y, weight=data[weight_field]) # calculate minimum spanning tree of undirected graph mst_non_directed = nx.minimum_spanning_edges(G, data=False) # transform back directed graph and save: mst_directed = nx.DiGraph() mst_directed.add_edges_from(mst_non_directed) nx.write_shp(mst_directed, output_network_folder) # populate fields Type_mat, Name, Pipe_Dn mst_edges = gdf.from_file(output_edges) mst_edges['Type_mat'] = type_mat_default mst_edges['Pipe_DN'] = pipe_diameter_default mst_edges['Name'] = ["PIPE" + str(x) for x in mst_edges['FID']] mst_edges.drop("FID", axis=1, inplace=True) mst_edges.crs = gdf.from_file(input_network_shp).crs # to add coordinate system mst_edges.to_file(output_edges, driver='ESRI Shapefile') # populate fields Building, Type, Name mst_nodes = gdf.from_file(output_nodes) buiding_nodes_df = gdf.from_file(building_nodes_shp) mst_nodes.crs = buiding_nodes_df.crs # to add same coordinate system buiding_nodes_df['coordinates'] = buiding_nodes_df['geometry'].apply( lambda x: (round(x.coords[0][0], 4), round(x.coords[0][1], 4))) mst_nodes['coordinates'] = mst_nodes['geometry'].apply( lambda x: (round(x.coords[0][0], 4), round(x.coords[0][1], 4))) names_temporary = ["NODE" + str(x) for x in mst_nodes['FID']] new_mst_nodes = mst_nodes.merge(buiding_nodes_df, suffixes=['', '_y'], on="coordinates", how='outer') new_mst_nodes.fillna(value="NONE", inplace=True) new_mst_nodes['Building'] = new_mst_nodes['Name'] new_mst_nodes['Name'] = names_temporary new_mst_nodes['Type'] = new_mst_nodes['Building'].apply(lambda x: 'CONSUMER' if x != "NONE" else x) new_mst_nodes.drop(["FID", "coordinates", 'floors_bg', 'floors_ag', 'height_bg', 'height_ag', 'geometry_y'], axis=1, inplace=True) new_mst_nodes.to_file(output_nodes, driver='ESRI Shapefile')
Example #15
Source File: minimum_spanning_tree.py From CityEnergyAnalyst with MIT License | 4 votes |
def calc_minimum_spanning_tree(input_network_shp, output_network_folder, building_nodes_shp, output_edges, output_nodes, weight_field, type_mat_default, pipe_diameter_default): # read shapefile into networkx format into a directed graph graph = nx.read_shp(input_network_shp) # transform to an undirected graph iterator_edges = graph.edges(data=True) G = nx.Graph() # plant = (11660.95859999981, 37003.7689999986) for (x, y, data) in iterator_edges: G.add_edge(x, y, weight=data[weight_field]) # calculate minimum spanning tree of undirected graph mst_non_directed = nx.minimum_spanning_edges(G, data=False) # transform back directed graph and save: mst_directed = nx.DiGraph() mst_directed.add_edges_from(mst_non_directed) nx.write_shp(mst_directed, output_network_folder) # populate fields Type_mat, Name, Pipe_Dn mst_edges = gdf.from_file(output_edges) mst_edges['Type_mat'] = type_mat_default mst_edges['Pipe_DN'] = pipe_diameter_default mst_edges['Name'] = ["PIPE" + str(x) for x in mst_edges['FID']] mst_edges.drop("FID", axis=1, inplace=True) mst_edges.crs = gdf.from_file(input_network_shp).crs # to add coordinate system mst_edges.to_file(output_edges, driver='ESRI Shapefile') # populate fields Building, Type, Name mst_nodes = gdf.from_file(output_nodes) buiding_nodes_df = gdf.from_file(building_nodes_shp) mst_nodes.crs = buiding_nodes_df.crs # to add same coordinate system buiding_nodes_df['coordinates'] = buiding_nodes_df['geometry'].apply( lambda x: (round(x.coords[0][0], 4), round(x.coords[0][1], 4))) mst_nodes['coordinates'] = mst_nodes['geometry'].apply( lambda x: (round(x.coords[0][0], 4), round(x.coords[0][1], 4))) names_temporary = ["NODE" + str(x) for x in mst_nodes['FID']] new_mst_nodes = mst_nodes.merge(buiding_nodes_df, suffixes=['', '_y'], on="coordinates", how='outer') new_mst_nodes.fillna(value="NONE", inplace=True) new_mst_nodes['Building'] = new_mst_nodes['Name'] new_mst_nodes['Name'] = names_temporary new_mst_nodes['Type'] = new_mst_nodes['Building'].apply(lambda x: 'CONSUMER' if x != "NONE" else x) new_mst_nodes.drop(["FID", "coordinates", 'floors_bg', 'floors_ag', 'height_bg', 'height_ag', 'geometry_y'], axis=1, inplace=True) new_mst_nodes.to_file(output_nodes, driver='ESRI Shapefile')
Example #16
Source File: mst.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 4 votes |
def minimum_spanning_tree(G, weight='weight'): """Return a minimum spanning tree or forest of an undirected weighted graph. A minimum spanning tree is a subgraph of the graph (a tree) with the minimum sum of edge weights. If the graph is not connected a spanning forest is constructed. A spanning forest is a union of the spanning trees for each connected component of the graph. Parameters ---------- G : NetworkX Graph weight : string Edge data key to use for weight (default 'weight'). Returns ------- G : NetworkX Graph A minimum spanning tree or forest. Examples -------- >>> G=nx.cycle_graph(4) >>> G.add_edge(0,3,weight=2) # assign weight 2 to edge 0-3 >>> T=nx.minimum_spanning_tree(G) >>> print(sorted(T.edges(data=True))) [(0, 1, {}), (1, 2, {}), (2, 3, {})] Notes ----- Uses Kruskal's algorithm. If the graph edges do not have a weight attribute a default weight of 1 will be used. """ T = nx.Graph(nx.minimum_spanning_edges(G, weight=weight, data=True)) # Add isolated nodes if len(T) != len(G): T.add_nodes_from([n for n, d in G.degree().items() if d == 0]) # Add node and graph attributes as shallow copy for n in T: T.node[n] = G.node[n].copy() T.graph = G.graph.copy() return T