本文整理匯總了Python中networkx.minimum_spanning_tree方法的典型用法代碼示例。如果您正苦於以下問題:Python networkx.minimum_spanning_tree方法的具體用法?Python networkx.minimum_spanning_tree怎麽用?Python networkx.minimum_spanning_tree使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類networkx
的用法示例。
在下文中一共展示了networkx.minimum_spanning_tree方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: ensure_names_are_connected
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import minimum_spanning_tree [as 別名]
def ensure_names_are_connected(graph, aids_list):
aug_graph = graph.copy().to_undirected()
orig_edges = aug_graph.edges()
unflat_edges = [list(itertools.product(aids, aids)) for aids in aids_list]
aid_pairs = [tup for tup in ut.iflatten(unflat_edges) if tup[0] != tup[1]]
new_edges = ut.setdiff_ordered(aid_pairs, aug_graph.edges())
preweighted_edges = nx.get_edge_attributes(aug_graph, 'weight')
if preweighted_edges:
orig_edges = ut.setdiff(orig_edges, list(preweighted_edges.keys()))
aug_graph.add_edges_from(new_edges)
# Ensure the largest possible set of original edges is in the MST
nx.set_edge_attributes(aug_graph, name='weight', values=dict([(edge, 1.0) for edge in new_edges]))
nx.set_edge_attributes(aug_graph, name='weight', values=dict([(edge, 0.1) for edge in orig_edges]))
for cc_sub_graph in nx.connected_component_subgraphs(aug_graph):
mst_sub_graph = nx.minimum_spanning_tree(cc_sub_graph)
for edge in mst_sub_graph.edges():
redge = edge[::-1]
if not (graph.has_edge(*edge) or graph.has_edge(*redge)):
graph.add_edge(*redge, attr_dict={})
示例2: get_tree_schedule
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import minimum_spanning_tree [as 別名]
def get_tree_schedule(frcs, graph):
"""
Find the most constrained tree in the graph and returns which messages to compute
it. This is the minimum spanning tree of the perturb_radius edge attribute.
See forward_pass for parameters.
Returns
-------
tree_schedules : numpy.ndarray of numpy.int
Describes how to compute the max marginal for the most constrained tree.
Nx3 2D array of (source pool_idx, target pool_idx, perturb radius), where
each row represents a single outgoing factor message computation.
"""
min_tree = nx.minimum_spanning_tree(graph, 'perturb_radius')
return np.array([(target, source, graph.edge[source][target]['perturb_radius'])
for source, target in nx.dfs_edges(min_tree)])[::-1]
示例3: createSteinerTree
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import minimum_spanning_tree [as 別名]
def createSteinerTree(graph, distances, inner_nodes):
"""
Computes a steiner tree with minimal sum of pipeline lengths;
updates distances such that only arcs of the spanning tree are contained with corresponding length
:param graph: an undirected networkx graph: Its edges have the attribute length which is the pipeline length in [m]
:type graph: networkx graph object
:param distances: pipeline distances in the length unit specified in the esM object
:type distances: pandas series
:return spanning tree with sum of lengths of pipelines is minimal
:rtype: graph object of networkx
"""
from networkx.algorithms import approximation
# type and value check
isNetworkxGraph(graph)
isPandasSeriesPositiveNumber(distances)
# compute spanning tree with minimal sum of pipeline lengths
S = approximation.steiner_tree(graph, terminal_nodes=inner_nodes, weight='length')
# TODO check why function fails when MST function is not called here
S = nx.minimum_spanning_tree(S, weight='length')
# delete edges that are in graph but not in the tree from the distance matrix
edgesToDelete = []
for edge in distances.index:
# check if edge or its reversed edge are contained in the tree
# you have to check both directions because we have an undirected graph
if edge not in S.edges and (edge[1], edge[0]) not in S.edges:
edgesToDelete.append(edge)
distances = distances.drop(edgesToDelete)
return S, distances
示例4: get_clique_tree
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import minimum_spanning_tree [as 別名]
def get_clique_tree(nodes, edges):
"""Given a set of int nodes i and edges (i,j), returns an nx.Graph object G
which is a clique tree, where:
- G.node[i]['members'] contains the set of original nodes in the ith
maximal clique
- G[i][j]['members'] contains the set of original nodes in the seperator
set between maximal cliques i and j
Note: This method is currently only implemented for chordal graphs; TODO:
add a step to triangulate non-chordal graphs.
"""
# Form the original graph G1
G1 = nx.Graph()
G1.add_nodes_from(nodes)
G1.add_edges_from(edges)
# Check if graph is chordal
# TODO: Add step to triangulate graph if not
if not nx.is_chordal(G1):
raise NotImplementedError("Graph triangulation not implemented.")
# Create maximal clique graph G2
# Each node is a maximal clique C_i
# Let w = |C_i \cap C_j|; C_i, C_j have an edge with weight w if w > 0
G2 = nx.Graph()
for i, c in enumerate(nx.chordal_graph_cliques(G1)):
G2.add_node(i, members=c)
for i in G2.nodes:
for j in G2.nodes:
S = G2.node[i]["members"].intersection(G2.node[j]["members"])
w = len(S)
if w > 0:
G2.add_edge(i, j, weight=w, members=S)
# Return a minimum spanning tree of G2
return nx.minimum_spanning_tree(G2)
示例5: weighted_one_edge_augmentation
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import minimum_spanning_tree [as 別名]
def weighted_one_edge_augmentation(G, avail, weight=None, partial=False):
"""Finds the minimum weight set of edges to connect G if one exists.
This is a variant of the weighted MST problem.
Example
-------
>>> G = nx.Graph([(1, 2), (2, 3), (4, 5)])
>>> G.add_nodes_from([6, 7, 8])
>>> # any edge not in avail has an implicit weight of infinity
>>> avail = [(1, 3), (1, 5), (4, 7), (4, 8), (6, 1), (8, 1), (8, 2)]
>>> sorted(weighted_one_edge_augmentation(G, avail))
[(1, 5), (4, 7), (6, 1), (8, 1)]
>>> # find another solution by giving large weights to edges in the
>>> # previous solution (note some of the old edges must be used)
>>> avail = [(1, 3), (1, 5, 99), (4, 7, 9), (6, 1, 99), (8, 1, 99), (8, 2)]
>>> sorted(weighted_one_edge_augmentation(G, avail))
[(1, 5), (4, 7), (6, 1), (8, 2)]
"""
avail_uv, avail_w = _unpack_available_edges(avail, weight=weight, G=G)
# Collapse CCs in the original graph into nodes in a metagraph
# Then find an MST of the metagraph instead of the original graph
C = collapse(G, nx.connected_components(G))
mapping = C.graph['mapping']
# Assign each available edge to an edge in the metagraph
candidate_mapping = _lightest_meta_edges(mapping, avail_uv, avail_w)
# nx.set_edge_attributes(C, name='weight', values=0)
C.add_edges_from(
(mu, mv, {'weight': w, 'generator': uv})
for (mu, mv), uv, w in candidate_mapping
)
# Find MST of the meta graph
meta_mst = nx.minimum_spanning_tree(C)
if not partial and not nx.is_connected(meta_mst):
raise nx.NetworkXUnfeasible(
'Not possible to connect G with available edges')
# Yield the edge that generated the meta-edge
for mu, mv, d in meta_mst.edges(data=True):
if 'generator' in d:
edge = d['generator']
yield edge
示例6: augment_graph_mst
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import minimum_spanning_tree [as 別名]
def augment_graph_mst(ibs, graph):
import plottool_ibeis as pt
#spantree_aids1_ = []
#spantree_aids2_ = []
# Add edges between all names
aid_list = list(graph.nodes())
aug_digraph = graph.copy()
# Change all weights in initial graph to be small (likely to be part of mst)
nx.set_edge_attributes(aug_digraph, name='weight', values=.0001)
aids1, aids2 = get_name_rowid_edges_from_aids(ibs, aid_list)
if False:
# Weight edges in the MST based on tenative distances
# Get tentative node positions
initial_pos = pt.get_nx_layout(graph.to_undirected(), 'graphviz')['node_pos']
#initial_pos = pt.get_nx_layout(graph.to_undirected(), 'agraph')['node_pos']
edge_pts1 = ut.dict_take(initial_pos, aids1)
edge_pts2 = ut.dict_take(initial_pos, aids2)
edge_pts1 = vt.atleast_nd(np.array(edge_pts1, dtype=np.int32), 2)
edge_pts2 = vt.atleast_nd(np.array(edge_pts2, dtype=np.int32), 2)
edge_weights = vt.L2(edge_pts1, edge_pts2)
else:
edge_weights = [1.0] * len(aids1)
# Create implicit fully connected (by name) graph
aug_edges = [(a1, a2, {'weight': w})
for a1, a2, w in zip(aids1, aids2, edge_weights)]
aug_digraph.add_edges_from(aug_edges)
# Determine which edges need to be added to
# make original graph connected by name
aug_graph = aug_digraph.to_undirected()
for cc_sub_graph in nx.connected_component_subgraphs(aug_graph):
mst_sub_graph = nx.minimum_spanning_tree(cc_sub_graph)
mst_edges = mst_sub_graph.edges()
for edge in mst_edges:
redge = edge[::-1]
#attr_dict = {'color': pt.DARK_ORANGE[0:3]}
attr_dict = {'color': pt.BLACK[0:3]}
if not (graph.has_edge(*edge) or graph.has_edge(*redge)):
graph.add_edge(*redge, attr_dict=attr_dict)
示例7: find_tree
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import minimum_spanning_tree [as 別名]
def find_tree(sub_network, weight='x_pu'):
"""Get the spanning tree of the graph, choose the node with the
highest degree as a central "tree slack" and then see for each
branch which paths from the slack to each node go through the
branch.
"""
branches_bus0 = sub_network.branches()["bus0"]
branches_i = branches_bus0.index
buses_i = sub_network.buses_i()
graph = sub_network.graph(weight=weight, inf_weight=1.)
sub_network.tree = nx.minimum_spanning_tree(graph)
#find bus with highest degree to use as slack
tree_slack_bus, slack_degree = max(degree(sub_network.tree), key=itemgetter(1))
logger.debug("Tree slack bus is %s with degree %d.", tree_slack_bus, slack_degree)
#determine which buses are supplied in tree through branch from slack
#matrix to store tree structure
sub_network.T = dok_matrix((len(branches_i),len(buses_i)))
for j,bus in enumerate(buses_i):
path = nx.shortest_path(sub_network.tree,bus,tree_slack_bus)
for i in range(len(path)-1):
branch = next(iterkeys(graph[path[i]][path[i+1]]))
branch_i = branches_i.get_loc(branch)
sign = +1 if branches_bus0.iat[branch_i] == path[i] else -1
sub_network.T[branch_i,j] = sign
示例8: main
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import minimum_spanning_tree [as 別名]
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)
示例9: test_mst
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import minimum_spanning_tree [as 別名]
def test_mst(self):
T=nx.minimum_spanning_tree(self.G)
assert_equal(T.edges(data=True),self.tree_edgelist)
示例10: test_mst_disconnected
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import minimum_spanning_tree [as 別名]
def test_mst_disconnected(self):
G=nx.Graph()
G.add_path([1,2])
G.add_path([10,20])
T=nx.minimum_spanning_tree(G)
assert_equal(sorted(map(sorted,T.edges())),[[1, 2], [10, 20]])
assert_equal(sorted(T.nodes()),[1, 2, 10, 20])
示例11: test_mst_isolate
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import minimum_spanning_tree [as 別名]
def test_mst_isolate(self):
G=nx.Graph()
G.add_nodes_from([1,2])
T=nx.minimum_spanning_tree(G)
assert_equal(sorted(T.nodes()),[1, 2])
assert_equal(sorted(T.edges()),[])
示例12: test_mst_attributes
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import minimum_spanning_tree [as 別名]
def test_mst_attributes(self):
G=nx.Graph()
G.add_edge(1,2,weight=1,color='red',distance=7)
G.add_edge(2,3,weight=1,color='green',distance=2)
G.add_edge(1,3,weight=10,color='blue',distance=1)
G.add_node(13,color='purple')
G.graph['foo']='bar'
T=nx.minimum_spanning_tree(G)
assert_equal(T.graph,G.graph)
assert_equal(T.node[13],G.node[13])
assert_equal(T.edge[1][2],G.edge[1][2])
示例13: test_unknown_algorithm
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import minimum_spanning_tree [as 別名]
def test_unknown_algorithm():
nx.minimum_spanning_tree(nx.Graph(), algorithm='random')
示例14: test_minimum_tree
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import minimum_spanning_tree [as 別名]
def test_minimum_tree(self):
T = nx.minimum_spanning_tree(self.G, algorithm=self.algo)
actual = sorted(T.edges(data=True))
assert_edges_equal(actual, self.minimum_spanning_edgelist)
示例15: test_disconnected
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import minimum_spanning_tree [as 別名]
def test_disconnected(self):
G = nx.Graph([(0, 1, dict(weight=1)), (2, 3, dict(weight=2))])
T = nx.minimum_spanning_tree(G, algorithm=self.algo)
assert_nodes_equal(list(T), list(range(4)))
assert_edges_equal(list(T.edges()), [(0, 1), (2, 3)])