本文整理汇总了Python中graphs.Graph.from_edge_pairs方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.from_edge_pairs方法的具体用法?Python Graph.from_edge_pairs怎么用?Python Graph.from_edge_pairs使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类graphs.Graph
的用法示例。
在下文中一共展示了Graph.from_edge_pairs方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_circular_layout
# 需要导入模块: from graphs import Graph [as 别名]
# 或者: from graphs.Graph import from_edge_pairs [as 别名]
def test_circular_layout(self):
G = Graph.from_edge_pairs([], num_vertices=4)
expected = np.array([[1,0],[0,1],[-1,0],[0,-1]])
assert_array_almost_equal(G.layout_circle(), expected)
# edge cases
for nv in (0, 1):
G = Graph.from_edge_pairs([], num_vertices=nv)
X = G.layout_circle()
self.assertEqual(X.shape, (nv, 2))
示例2: setUp
# 需要导入模块: from graphs import Graph [as 别名]
# 或者: from graphs.Graph import from_edge_pairs [as 别名]
def setUp(self):
pairs = np.array([[0,1],[0,2],[1,2],[3,4]])
adj = [[0,1,2,0,0],
[0,0,3,0,0],
[0,0,0,0,0],
[0,0,0,0,4],
[0,0,0,0,0]]
self.graphs = [
Graph.from_edge_pairs(pairs),
Graph.from_edge_pairs(pairs, symmetric=True),
Graph.from_adj_matrix(adj),
Graph.from_adj_matrix(csr_matrix(adj)),
]
self.coords = np.random.random((5, 3))
示例3: concat_trajectories
# 需要导入模块: from graphs import Graph [as 别名]
# 或者: from graphs.Graph import from_edge_pairs [as 别名]
def concat_trajectories(traj_lengths, directed=False):
P = []
last_idx = 0
for tl in traj_lengths:
P.append(last_idx + _traj_pair_idxs(tl))
last_idx += tl
return Graph.from_edge_pairs(np.vstack(P), num_vertices=last_idx,
symmetric=(not directed))
示例4: delaunay_graph
# 需要导入模块: from graphs import Graph [as 别名]
# 或者: from graphs.Graph import from_edge_pairs [as 别名]
def delaunay_graph(X, weighted=False):
'''Delaunay triangulation graph.
'''
e1, e2 = _delaunay_edges(X)
pairs = np.column_stack((e1, e2))
w = paired_distances(X[e1], X[e2]) if weighted else None
return Graph.from_edge_pairs(pairs, num_vertices=X.shape[0], symmetric=True,
weights=w)
示例5: gabriel_graph
# 需要导入模块: from graphs import Graph [as 别名]
# 或者: from graphs.Graph import from_edge_pairs [as 别名]
def gabriel_graph(X, metric='euclidean'):
a,b = np.triu_indices(X.shape[0], k=1)
midpoints = (X[a] + X[b]) / 2
Dmid = pairwise_distances(midpoints, X, metric=metric).min(axis=1)
Dedge = paired_distances(X[a], X[b], metric=metric)
mask = (Dedge - Dmid * 2) < 1e-10
pairs = np.transpose((a[mask],b[mask]))
return Graph.from_edge_pairs(pairs, num_vertices=X.shape[0], symmetric=True)
示例6: gabriel_graph
# 需要导入模块: from graphs import Graph [as 别名]
# 或者: from graphs.Graph import from_edge_pairs [as 别名]
def gabriel_graph(X, metric='euclidean', weighted=False):
n = X.shape[0]
a, b = np.triu_indices(n, k=1)
midpoints = (X[a] + X[b]) / 2
_, Dmid = pairwise_distances_argmin_min(midpoints, X, metric=metric)
Dedge = paired_distances(X[a], X[b], metric=metric)
mask = (Dedge - Dmid * 2) < 1e-10
pairs = np.column_stack((a[mask], b[mask]))
w = Dedge[mask] if weighted else None
return Graph.from_edge_pairs(pairs, num_vertices=n, symmetric=True, weights=w)
示例7: test_connected_subgraphs
# 需要导入模块: from graphs import Graph [as 别名]
# 或者: from graphs.Graph import from_edge_pairs [as 别名]
def test_connected_subgraphs(self):
G = Graph.from_edge_pairs(PAIRS)
subgraphs = list(G.connected_subgraphs(directed=False, ordered=False))
self.assertEqual(len(subgraphs), 2)
assert_array_equal(subgraphs[0].pairs(), PAIRS[:6])
assert_array_equal(subgraphs[1].pairs(), [[0,1],[1,0]])
G = neighbor_graph(X, k=2)
subgraphs = list(G.connected_subgraphs(directed=True, ordered=True))
self.assertEqual(len(subgraphs), 3)
self.assertEqual([g.num_vertices() for g in subgraphs], [9,6,5])
示例8: test_kernelize
# 需要导入模块: from graphs import Graph [as 别名]
# 或者: from graphs.Graph import from_edge_pairs [as 别名]
def test_kernelize(self):
graphs = [
Graph.from_edge_pairs(PAIRS),
Graph.from_adj_matrix(ADJ),
Graph.from_adj_matrix(coo_matrix(ADJ)),
Graph.from_adj_matrix(csr_matrix(ADJ)),
]
for G in graphs:
for kernel in ('none', 'binary'):
K = G.kernelize(kernel)
assert_array_equal(K.matrix('dense'), ADJ)
self.assertRaises(ValueError, G.kernelize, 'foobar')
示例9: urquhart_graph
# 需要导入模块: from graphs import Graph [as 别名]
# 或者: from graphs.Graph import from_edge_pairs [as 别名]
def urquhart_graph(X, weighted=False):
'''Urquhart graph: made from the 2 shortest edges of each Delaunay triangle.
'''
e1, e2 = _delaunay_edges(X)
w = paired_distances(X[e1], X[e2])
mask = np.ones_like(w, dtype=bool)
bad_inds = w.reshape((-1, 3)).argmax(axis=1) + np.arange(0, len(e1), 3)
mask[bad_inds] = False
weights = w[mask] if weighted else None
pairs = np.column_stack((e1[mask], e2[mask]))
return Graph.from_edge_pairs(pairs, num_vertices=X.shape[0], symmetric=True,
weights=weights)
示例10: test_bicolor_spectral
# 需要导入模块: from graphs import Graph [as 别名]
# 或者: from graphs.Graph import from_edge_pairs [as 别名]
def test_bicolor_spectral(self):
pairs = np.array([[0,1],[0,2],[1,0],[1,2],[2,0],[2,1],[2,3],[3,2]])
adj = [[0,1,1,0],
[1,0,1,0],
[1,1,0,1],
[0,0,1,0]]
test_cases = [
Graph.from_edge_pairs(pairs),
Graph.from_adj_matrix(adj),
Graph.from_adj_matrix(coo_matrix(adj)),
]
expected = np.array([1,1,0,1], dtype=bool)
for G in test_cases:
assert_array_equal(expected, G.bicolor_spectral())
示例11: test_greedy_coloring
# 需要导入模块: from graphs import Graph [as 别名]
# 或者: from graphs.Graph import from_edge_pairs [as 别名]
def test_greedy_coloring(self):
pairs = np.array([[0,1],[0,2],[1,0],[1,2],[2,0],[2,1],[3,4],[4,3]])
adj = [[0,1,1,0,0],
[1,0,1,0,0],
[1,1,0,0,0],
[0,0,0,0,1],
[0,0,0,1,0]]
test_cases = [
Graph.from_edge_pairs(pairs),
Graph.from_adj_matrix(adj),
Graph.from_adj_matrix(coo_matrix(adj)),
]
for G in test_cases:
assert_array_equal([1,2,3,1,2], G.color_greedy())
示例12: relative_neighborhood_graph
# 需要导入模块: from graphs import Graph [as 别名]
# 或者: from graphs.Graph import from_edge_pairs [as 别名]
def relative_neighborhood_graph(X, metric='euclidean'):
n = X.shape[0]
a,b = np.triu_indices(n, k=1)
D = pairwise_distances(X, metric=metric)
# Naive algorithm, but it's generic to any D (doesn't depend on delaunay).
pairs = []
for pair in zip(a,b):
d = D[pair]
for i in range(n):
if i in pair:
continue
if (D[pair,i] < d).all():
break # Point in lune, this is not an edge
else:
pairs.append(pair)
return Graph.from_edge_pairs(pairs, num_vertices=X.shape[0], symmetric=True)
示例13: test_spring_layout
# 需要导入模块: from graphs import Graph [as 别名]
# 或者: from graphs.Graph import from_edge_pairs [as 别名]
def test_spring_layout(self):
np.random.seed(1234)
w = np.array([1,2,0.1,1,1,2,0.1,1])
p = [[0,1],[1,2],[2,3],[3,4],[1,0],[2,1],[3,2],[4,3]]
G = Graph.from_edge_pairs(p, weights=w, num_vertices=5)
expected = np.array([
[-1.12951518, 0.44975598],
[-0.42574481, 0.51702804],
[0.58946761, 0.61403187],
[0.96513010, 0.64989485],
[1.67011322, 0.71714073]])
assert_array_almost_equal(G.layout_spring(), expected)
# Test initial_layout kwarg
X = np.arange(10).reshape((5,2))
expected = np.array([
[1.837091, 2.837091],
[2.996882, 3.996882],
[4.472791, 5.472791],
[5.014210, 6.014210],
[6.162909, 7.162909]])
assert_array_almost_equal(G.layout_spring(initial_layout=X), expected)
示例14: setUp
# 需要导入模块: from graphs import Graph [as 别名]
# 或者: from graphs.Graph import from_edge_pairs [as 别名]
def setUp(self):
self.graphs = [
Graph.from_edge_pairs(PAIRS),
Graph.from_adj_matrix(ADJ),
Graph.from_adj_matrix(coo_matrix(ADJ)),
]
示例15: b_matching
# 需要导入模块: from graphs import Graph [as 别名]
# 或者: from graphs.Graph import from_edge_pairs [as 别名]
def b_matching(D, k, max_iter=1000, damping=1, conv_thresh=1e-4, verbose=False):
"""
"Belief-Propagation for Weighted b-Matchings on Arbitrary Graphs
and its Relation to Linear Programs with Integer Solutions"
Bayati et al.
Finds the minimal weight perfect b-matching using min-sum loopy-BP.
@param D pairwise distance matrix
@param k number of neighbors per vertex (scalar or array-like)
Based on the code at http://www.cs.columbia.edu/~bert/code/bmatching/bdmatch
"""
INTERVAL = 2
oscillation = 10
cbuff = np.zeros(100, dtype=float)
cbuffpos = 0
N = D.shape[0]
assert D.shape[1] == N, "Input distance matrix must be square"
mask = ~np.eye(N, dtype=bool) # Assume all nonzero except for diagonal
W = -D[mask].reshape((N, -1)).astype(float)
degrees = np.clip(np.atleast_1d(k), 0, N - 1)
if degrees.size == 1: # broadcast scalar up to length-N array
degrees = np.repeat(degrees, N)
else:
assert degrees.shape == (N,), "Input degrees must have length N"
# TODO: remove these later
inds = np.tile(np.arange(N), (N, 1))
backinds = inds.copy()
inds = inds[mask].reshape((N, -1))
backinds = backinds.T.ravel()[: (N * (N - 1))].reshape((N, -1))
# Run Belief Revision
change = 1.0
B = W.copy()
for n_iter in range(1, max_iter + 1):
oldB = B.copy()
updateB(oldB, B, W, degrees, damping, inds, backinds)
# check for convergence
if n_iter % INTERVAL == 0:
# track changes
c = np.abs(B[:, 0]).sum()
# c may be infinite here, and that's ok
with np.errstate(invalid="ignore"):
if np.any(np.abs(c - cbuff) < conv_thresh):
oscillation -= 1
cbuff[cbuffpos] = c
cbuffpos = (cbuffpos + 1) % len(cbuff)
change = update_change(B, oldB)
if np.isnan(change):
warnings.warn(
"change is NaN! " "BP will quit but solution could be invalid. " "Problem may be infeasible."
)
break
if change < conv_thresh or oscillation < 1:
break
else:
warnings.warn("Hit iteration limit (%d) before converging" % max_iter)
if verbose: # pragma: no cover
if change < conv_thresh:
print("Converged to stable beliefs in %d iterations" % n_iter)
elif oscillation < 1:
print("Stopped after reaching oscillation in %d iterations" % n_iter)
print("No feasible solution found or there are multiple maxima.")
print("Outputting best approximate solution. Try damping.")
# recover result from B
thresholds = np.zeros(N)
for i, d in enumerate(degrees):
Brow = B[i]
if d >= N - 1:
thresholds[i] = -np.inf
elif d < 1:
thresholds[i] = np.inf
else:
thresholds[i] = Brow[quickselect(Brow, d - 1)]
ii, jj = np.where(B >= thresholds[:, None])
pairs = np.column_stack((ii, inds[ii, jj]))
return Graph.from_edge_pairs(pairs, num_vertices=N)