本文整理匯總了Python中networkx.all_pairs_dijkstra_path_length方法的典型用法代碼示例。如果您正苦於以下問題:Python networkx.all_pairs_dijkstra_path_length方法的具體用法?Python networkx.all_pairs_dijkstra_path_length怎麽用?Python networkx.all_pairs_dijkstra_path_length使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類networkx
的用法示例。
在下文中一共展示了networkx.all_pairs_dijkstra_path_length方法的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_all_pairs_shortest_path_length
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import all_pairs_dijkstra_path_length [as 別名]
def test_all_pairs_shortest_path_length(self):
ans = dict(nx.shortest_path_length(self.cycle))
assert_equal(ans[0], {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
assert_equal(ans, dict(nx.all_pairs_shortest_path_length(self.cycle)))
ans = dict(nx.shortest_path_length(self.grid))
assert_equal(ans[1][16], 6)
# now with weights
ans = dict(nx.shortest_path_length(self.cycle, weight='weight'))
assert_equal(ans[0], {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
assert_equal(ans, dict(nx.all_pairs_dijkstra_path_length(self.cycle)))
ans = dict(nx.shortest_path_length(self.grid, weight='weight'))
assert_equal(ans[1][16], 6)
# weights and method specified
ans = dict(nx.shortest_path_length(self.cycle, weight='weight',
method='dijkstra'))
assert_equal(ans[0], {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
assert_equal(ans, dict(nx.all_pairs_dijkstra_path_length(self.cycle)))
ans = dict(nx.shortest_path_length(self.cycle, weight='weight',
method='bellman-ford'))
assert_equal(ans[0], {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
assert_equal(ans,
dict(nx.all_pairs_bellman_ford_path_length(self.cycle)))
示例2: _compute_all_pairs
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import all_pairs_dijkstra_path_length [as 別名]
def _compute_all_pairs(self, graph, weight=None, normalize=False):
lengths = nx.all_pairs_dijkstra_path_length(graph, weight=weight)
lengths = dict(lengths)
max_length = max([max(lengths[i].values()) for i in lengths])
if normalize:
for i in lengths:
for j in lengths[i]:
lengths[i][j] = float(lengths[i][j]) / max_length
return lengths
示例3: _get_unique_path_lengths
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import all_pairs_dijkstra_path_length [as 別名]
def _get_unique_path_lengths(G, paths=None):
"""
Compute the unique path lengths.
Parameters
----------
G (nx.Graph or DiGraph):
a graph.
paths (list):
list of paths.
Returns
-------
unique_path_lengths (list):
sorted unique path lengths.
"""
if paths is None:
paths = list(nx.all_pairs_dijkstra_path_length(G))
unique_path_lengths = set()
for starting_node, dist_dict in paths:
unique_path_lengths |= set(dist_dict.values())
unique_path_lengths = sorted(list(unique_path_lengths))
return unique_path_lengths
示例4: all_pairs_dijkstra_path_length
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import all_pairs_dijkstra_path_length [as 別名]
def all_pairs_dijkstra_path_length(G, cutoff=None, weight='weight'):
""" Compute shortest path lengths between all nodes in a weighted graph.
Parameters
----------
G : NetworkX graph
weight: string, optional (default='weight')
Edge data key corresponding to the edge weight
cutoff : integer or float, optional
Depth to stop the search. Only paths of length <= cutoff are returned.
Returns
-------
distance : dictionary
Dictionary, keyed by source and target, of shortest path lengths.
Examples
--------
>>> G=nx.path_graph(5)
>>> length=nx.all_pairs_dijkstra_path_length(G)
>>> print(length[1][4])
3
>>> length[1]
{0: 1, 1: 0, 2: 1, 3: 2, 4: 3}
Notes
-----
Edge weight attributes must be numerical.
Distances are calculated as sums of weighted edges traversed.
The dictionary returned only has keys for reachable node pairs.
"""
length = single_source_dijkstra_path_length
# TODO This can be trivially parallelized.
return {n: length(G, n, cutoff=cutoff, weight=weight) for n in G}
示例5: test_all_pairs_shortest_path_length
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import all_pairs_dijkstra_path_length [as 別名]
def test_all_pairs_shortest_path_length(self):
l=nx.shortest_path_length(self.cycle)
assert_equal(l[0],{0:0,1:1,2:2,3:3,4:3,5:2,6:1})
assert_equal(l,nx.all_pairs_shortest_path_length(self.cycle))
l=nx.shortest_path_length(self.grid)
assert_equal(l[1][16],6)
# now with weights
l=nx.shortest_path_length(self.cycle,weight='weight')
assert_equal(l[0],{0:0,1:1,2:2,3:3,4:3,5:2,6:1})
assert_equal(l,nx.all_pairs_dijkstra_path_length(self.cycle))
l=nx.shortest_path_length(self.grid,weight='weight')
assert_equal(l[1][16],6)
示例6: test_all_pairs_dijkstra_path_length
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import all_pairs_dijkstra_path_length [as 別名]
def test_all_pairs_dijkstra_path_length(self):
cycle = nx.cycle_graph(7)
pl = dict(nx.all_pairs_dijkstra_path_length(cycle))
assert_equal(pl[0], {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
cycle[1][2]['weight'] = 10
pl = dict(nx.all_pairs_dijkstra_path_length(cycle))
assert_equal(pl[0], {0: 0, 1: 1, 2: 5, 3: 4, 4: 3, 5: 2, 6: 1})
示例7: test_all_pairs_dijkstra_path_length
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import all_pairs_dijkstra_path_length [as 別名]
def test_all_pairs_dijkstra_path_length(self):
cycle=nx.cycle_graph(7)
pl = dict(nx.all_pairs_dijkstra_path_length(cycle))
assert_equal(pl[0], {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
cycle[1][2]['weight'] = 10
pl = dict(nx.all_pairs_dijkstra_path_length(cycle))
assert_equal(pl[0], {0: 0, 1: 1, 2: 5, 3: 4, 4: 3, 5: 2, 6: 1})
示例8: test_all_pairs_shortest_path_length
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import all_pairs_dijkstra_path_length [as 別名]
def test_all_pairs_shortest_path_length(self):
l=dict(nx.shortest_path_length(self.cycle))
assert_equal(l[0],{0:0,1:1,2:2,3:3,4:3,5:2,6:1})
assert_equal(l, dict(nx.all_pairs_shortest_path_length(self.cycle)))
l=dict(nx.shortest_path_length(self.grid))
assert_equal(l[1][16],6)
# now with weights
l = dict(nx.shortest_path_length(self.cycle, weight='weight'))
assert_equal(l[0], {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1})
assert_equal(l, dict(nx.all_pairs_dijkstra_path_length(self.cycle)))
l = dict(nx.shortest_path_length(self.grid, weight='weight'))
assert_equal(l[1][16], 6)
示例9: define_neighborhoods
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import all_pairs_dijkstra_path_length [as 別名]
def define_neighborhoods(self, **kwargs):
# Overwriting the global settings, if required
if 'node_distance_metric' in kwargs:
self.node_distance_metric = kwargs['node_distance_metric']
if 'neighborhood_radius_type' in kwargs:
self.neighborhood_radius_type = kwargs['neighborhood_radius_type']
if 'neighborhood_radius' in kwargs:
self.neighborhood_radius = kwargs['neighborhood_radius']
# Make sure that the settings are still valid
self.validate_config()
all_shortest_paths = {}
neighborhoods = np.zeros([self.graph.number_of_nodes(), self.graph.number_of_nodes()], dtype=int)
if self.node_distance_metric == 'euclidean':
x = list(dict(self.graph.nodes.data('x')).values())
nr = self.neighborhood_radius * (np.max(x) - np.min(x))
x = np.matrix(self.graph.nodes.data('x'))[:, 1]
y = np.matrix(self.graph.nodes.data('y'))[:, 1]
node_coordinates = np.concatenate([x, y], axis=1)
node_distances = squareform(pdist(node_coordinates, 'euclidean'))
neighborhoods[node_distances < nr] = 1
else:
if self.node_distance_metric == 'shortpath_weighted_layout':
# x = np.matrix(self.graph.nodes.data('x'))[:, 1]
x = list(dict(self.graph.nodes.data('x')).values())
nr = self.neighborhood_radius * (np.max(x) - np.min(x))
all_shortest_paths = dict(nx.all_pairs_dijkstra_path_length(self.graph,
weight='length', cutoff=nr))
elif self.node_distance_metric == 'shortpath':
nr = self.neighborhood_radius
all_shortest_paths = dict(nx.all_pairs_dijkstra_path_length(self.graph, cutoff=nr))
neighbors = [(s, t) for s in all_shortest_paths for t in all_shortest_paths[s].keys()]
for i in neighbors:
neighborhoods[i] = 1
# Set diagonal to zero (a node is not part of its own neighborhood)
# np.fill_diagonal(neighborhoods, 0)
# Calculate the average neighborhood size
num_neighbors = np.sum(neighborhoods, axis=1)
if self.verbose:
print('Node distance metric: %s' % self.node_distance_metric)
print('Neighborhood definition: %.2f x %s' % (self.neighborhood_radius, self.neighborhood_radius_type))
print('Number of nodes per neighborhood (mean +/- std): %.2f +/- %.2f' % (np.mean(num_neighbors), np.std(num_neighbors)))
self.neighborhoods = neighborhoods
示例10: weighted_portrait
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import all_pairs_dijkstra_path_length [as 別名]
def weighted_portrait(G, paths=None, binedges=None):
"""Compute weighted portrait, using Dijkstra's algorithm for finding
shortest paths.
Parameters
----------
G (nx.Graph or nx.DiGraph):
a graph.
paths (list):
a list of all pairs of paths.
binedges (list):
sampled path lengths.
Returns
-------
B (np.ndarray):
a matrix :math:`B` where :math:`B_{i,j}` is the number of starting
nodes in graph with :math:`j` nodes at distance :math:`d_i < d <
d_{i+1}`.
"""
# all pairs path lengths
if paths is None:
paths = list(nx.all_pairs_dijkstra_path_length(G))
if binedges is None:
unique_path_lengths = _get_unique_path_lengths(G, paths=paths)
sampled_path_lengths = np.percentile(unique_path_lengths, np.arange(0, 101, 1))
else:
sampled_path_lengths = binedges
UPL = np.array(sampled_path_lengths)
l_s_v = []
for i, (s, dist_dict) in enumerate(paths):
distances = np.array(list(dist_dict.values()))
s_v, e = np.histogram(distances, bins=UPL)
l_s_v.append(s_v)
M = np.array(l_s_v)
B = np.zeros((len(UPL) - 1, G.number_of_nodes() + 1))
for i in range(len(UPL) - 1):
col = M[:, i] # ith col = numbers of nodes at d_i <= distance < d_i+1
for n, c in Counter(col).items():
B[i, n] += c
return B
示例11: all_pairs_dijkstra_path_length
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import all_pairs_dijkstra_path_length [as 別名]
def all_pairs_dijkstra_path_length(G, cutoff=None, weight='weight'):
"""Compute shortest path lengths between all nodes in a weighted graph.
Parameters
----------
G : NetworkX graph
cutoff : integer or float, optional
Depth to stop the search. Only return paths with length <= cutoff.
weight : string or function
If this is a string, then edge weights will be accessed via the
edge attribute with this key (that is, the weight of the edge
joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
such edge attribute exists, the weight of the edge is assumed to
be one.
If this is a function, the weight of an edge is the value
returned by the function. The function must accept exactly three
positional arguments: the two endpoints of an edge and the
dictionary of edge attributes for that edge. The function must
return a number.
Returns
-------
distance : iterator
(source, dictionary) iterator with dictionary keyed by target and
shortest path length as the key value.
Examples
--------
>>> G = nx.path_graph(5)
>>> length = dict(nx.all_pairs_dijkstra_path_length(G))
>>> for node in [0, 1, 2, 3, 4]:
... print('1 - {}: {}'.format(node, length[1][node]))
1 - 0: 1
1 - 1: 0
1 - 2: 1
1 - 3: 2
1 - 4: 3
>>> length[3][2]
1
>>> length[2][2]
0
Notes
-----
Edge weight attributes must be numerical.
Distances are calculated as sums of weighted edges traversed.
The dictionary returned only has keys for reachable node pairs.
"""
length = single_source_dijkstra_path_length
for n in G:
yield (n, length(G, n, cutoff=cutoff, weight=weight))
示例12: run
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import all_pairs_dijkstra_path_length [as 別名]
def run(self):
"""
Run the monte carlo simulation
@return:
"""
self.progress_signal.emit(0.0)
n = len(self.grid.buses)
if self.use_ptdf:
self.progress_text.emit('Analyzing PTDF...')
# the PTDF matrix will be scaled to 0, 1 to be able to train
self.X_train = Normalizer().fit_transform(self.ptdf_results.flows_sensitivity_matrix)
metric = 'euclidean'
else:
self.progress_text.emit('Exploring Dijkstra distances...')
# explore
g = self.build_weighted_graph()
k = 0
for i, distances_dict in nx.all_pairs_dijkstra_path_length(g):
for j, d in distances_dict.items():
self.X_train[i, j] = d
self.progress_signal.emit((k+1) / n * 100.0)
k += 1
metric = 'precomputed'
# compute the sample sigma
self.sigma = np.std(self.X_train)
max_distance = self.sigma * self.sigmas
# construct groups
self.progress_text.emit('Building groups with DBSCAN...')
# Compute DBSCAN
model = DBSCAN(eps=max_distance,
min_samples=self.min_group_size,
metric=metric)
db = model.fit(self.X_train)
# get the labels that are greater than -1
labels = list({i for i in db.labels_ if i > -1})
self.groups_by_name = [list() for k in labels]
self.groups_by_index = [list() for k in labels]
# fill in the groups
for i, (bus, group_idx) in enumerate(zip(self.grid.buses, db.labels_)):
if group_idx > -1:
self.groups_by_name[group_idx].append(bus.name)
self.groups_by_index[group_idx].append(i)
# display progress
self.progress_text.emit('Done')
self.progress_signal.emit(0.0)
self.done_signal.emit()