本文整理汇总了Python中networkx.to_numpy_array方法的典型用法代码示例。如果您正苦于以下问题:Python networkx.to_numpy_array方法的具体用法?Python networkx.to_numpy_array怎么用?Python networkx.to_numpy_array使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx
的用法示例。
在下文中一共展示了networkx.to_numpy_array方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: seed
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_array [as 别名]
def seed(value: Optional[int]) -> None:
"""Seed for random number generators.
Wrapper function for `numpy.random.seed <https://docs.scipy.org/doc/numpy//reference/generated
/numpy.random.seed.html>`_ to seed all NumPy-based random number generators. This allows for
repeatable sampling.
**Example usage:**
>>> g = nx.erdos_renyi_graph(5, 0.7)
>>> a = nx.to_numpy_array(g)
>>> seed(1967)
>>> sample(a, 3, 4)
[[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 0, 1, 0, 1], [0, 0, 0, 0, 0]]
>>> seed(1967)
>>> sample(a, 3, 4)
[[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 0, 1, 0, 1], [0, 0, 0, 0, 0]]
Args:
value (int): random seed
"""
np.random.seed(value)
示例2: _get_state
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_array [as 别名]
def _get_state(graph: nx.Graph, n_mean: float = 5, loss: float = 0.0) -> BaseGaussianState:
r"""Embeds the input graph into a GBS device and returns the corresponding Gaussian state.
"""
modes = graph.order()
A = nx.to_numpy_array(graph)
mean_photon_per_mode = n_mean / float(modes)
p = sf.Program(modes)
# pylint: disable=expression-not-assigned
with p.context as q:
sf.ops.GraphEmbed(A, mean_photon_per_mode=mean_photon_per_mode) | q
if loss:
for _q in q:
sf.ops.LossChannel(1 - loss) | _q
eng = sf.LocalEngine(backend="gaussian")
return eng.run(p).state
示例3: deobfuscator
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_array [as 别名]
def deobfuscator(dict_of_dicts):
#====Work backwards====
#Build graph from dict_of_dicts:
graph_from_dict = nx.DiGraph(dict_of_dicts)
#Get adjacency matrix of graph
graph_array = nx.to_numpy_array(graph_from_dict)
#Change 1's to 255's to save as an image
graph_array[graph_array == 1] = 255
image_from_array = Image.fromarray(graph_array).convert("L")
#We can send the array directly to OCR, but I like to see the image.
image_from_array.save("obfuscated.png")
#Run OCR on our image
return pytesseract.image_to_string("obfuscated.png")
示例4: __init__
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_array [as 别名]
def __init__(self, graph, rep_size=128):
self.g = graph
self.node_size = self.g.G.number_of_nodes()
self.rep_size = rep_size
self.adj_mat = nx.to_numpy_array(self.g.G)
self.vectors = {}
self.embeddings = self.get_train()
look_back = self.g.look_back_list
for i, embedding in enumerate(self.embeddings):
self.vectors[look_back[i]] = embedding
示例5: mock_batch
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_array [as 别名]
def mock_batch(batch_size):
"""construct pyG batch"""
graphs = []
while len(graphs) < batch_size:
G = nx.erdos_renyi_graph(np.random.choice([300, 500]), 0.5)
if G.number_of_edges() > 1:
graphs.append(G)
adjs = [torch.from_numpy(nx.to_numpy_array(G)) for G in graphs]
graph_data = [dense_to_sparse(A) for A in adjs]
data_list = [Data(x=x, edge_index=e) for (e, x) in graph_data]
return Batch.from_data_list(data_list)
示例6: get_edge_index
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_array [as 别名]
def get_edge_index(self):
adj = torch.Tensor(nx.to_numpy_array(self))
edge_index, _ = dense_to_sparse(adj)
return edge_index
示例7: test_real_degenerate
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_array [as 别名]
def test_real_degenerate(self):
"""Verify that the Takagi decomposition returns a matrix that is unitary and results in a
correct decomposition when input a real but highly degenerate matrix. This test uses the
adjacency matrix of a balanced tree graph."""
g = nx.balanced_tree(2, 4)
a = nx.to_numpy_array(g)
rl, U = dec.takagi(a)
assert np.allclose(U @ U.conj().T, np.eye(len(a)))
assert np.allclose(U @ np.diag(rl) @ U.T, a)
示例8: _chromatic_number_upper_bound
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_array [as 别名]
def _chromatic_number_upper_bound(G):
# tries to determine an upper bound on the chromatic number of G
# Assumes G is not complete
if not nx.is_connected(G):
return max((_chromatic_number_upper_bound(G.subgraph(c))
for c in nx.connected_components(G)))
n_nodes = len(G.nodes)
n_edges = len(G.edges)
# chi * (chi - 1) <= 2 * |E|
quad_bound = math.ceil((1 + math.sqrt(1 + 8 * n_edges)) / 2)
if n_nodes % 2 == 1 and is_cycle(G):
# odd cycle graphs need three colors
bound = 3
elif n_nodes > 2:
try:
import numpy as np
except ImportError:
# chi <= max degree, unless it is complete or a cycle graph of odd length,
# in which case chi <= max degree + 1 (Brook's Theorem)
bound = max(G.degree(node) for node in G)
else:
# Let A be the adj matrix of G (symmetric, 0 on diag). Let theta_1
# be the largest eigenvalue of A. Then chi <= theta_1 + 1 with
# equality iff G is complete or an odd cycle.
# this is strictly better than brooks theorem
bound = math.ceil(max(np.linalg.eigvals(nx.to_numpy_array(G))))
else:
# we know it's connected
bound = n_nodes
return min(quad_bound, bound)
示例9: dist
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_array [as 别名]
def dist(self, G1, G2):
r"""Frobenius distance between two graphs.
If :math:`a_{ij}` and :math:`b_{ij}` are the two adjacency matrices
we define
.. math::
d(G1, G2) = \sqrt{\sum_{i,j} |a_{ij} - b_{ij}|^2}
The results dictionary also stores a 2-tuple of the underlying
adjacency matrices in the key `'adjacency_matrices'`.
Parameters
----------
G1, G2 (nx.Graph)
two graphs to compare
Returns
-------
float
the distance between `G1` and `G2`
Notes
-----
The graphs must have the same number of nodes.
"""
adj1 = nx.to_numpy_array(G1)
adj2 = nx.to_numpy_array(G2)
dist = np.linalg.norm((adj1 - adj2))
self.results['dist'] = dist
self.results['adjacency_matrices'] = adj1, adj2
return dist
示例10: get_resistance_matrix
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_array [as 别名]
def get_resistance_matrix(G):
"""Get the resistance matrix of a networkx graph.
The resistance matrix of a graph :math:`G` is calculated as
:math:`R = \text{diag}(L_i) 1^T + 1 \text{diag}(L_i)^T - 2L_i`,
where L_i is the Moore-Penrose pseudoinverse of the Laplacian of :math:`G`.
Parameters
----------
G (nx.Graph): networkx graph from which to get its resistance matrix
Returns
-------
R (np.array): resistance matrix of G
"""
# Get adjacency matrix
n = len(G.nodes())
A = nx.to_numpy_array(G)
# Get Laplacian
D = np.diag(A.sum(axis=0))
L = D - A
# Get Moore-Penrose pseudoinverses of Laplacian
# Note: converts to dense matrix and introduces n^2 operation here
I = np.eye(n)
J = (1 / n) * np.ones((n, n))
L_i = np.linalg.solve(L + J, I) - J
# Get resistance matrix
ones = np.ones(n)
ones = ones.reshape((1, n))
L_i_diag = np.diag(L_i)
L_i_diag = L_i_diag.reshape((n, 1))
R = np.dot(L_i_diag, ones) + np.dot(ones.T, L_i_diag.T) - 2 * L_i
return R
示例11: test_tnet_to_nx
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_array [as 别名]
def test_tnet_to_nx():
df = pd.DataFrame({'i': [0, 0], 'j': [1, 2], 't': [0, 1]})
dfnx = teneto.utils.tnet_to_nx(df, t=0)
G = nx.to_numpy_array(dfnx)
if not G.shape == (2, 2):
raise AssertionError()
if not G[0, 1] == 1:
raise AssertionError()
示例12: test_graphin
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_array [as 别名]
def test_graphin(self):
G = nx.from_numpy_array(self.A)
np.testing.assert_array_equal(nx.to_numpy_array(G), gs.utils.import_graph(G))
示例13: test_graphin
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_array [as 别名]
def test_graphin(self):
G = nx.from_numpy_array(self.A)
np.testing.assert_array_equal(nx.to_numpy_array(G), gus.import_graph(G))
示例14: test_lcc_networkx
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_array [as 别名]
def test_lcc_networkx(self):
expected_lcc_matrix = np.array(
[
[0, 1, 1, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 1, 1],
[0, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
]
)
expected_nodelist = np.array([1, 2, 3, 4, 6])
g = nx.DiGraph()
[g.add_node(i) for i in range(1, 7)]
g.add_edge(1, 2)
g.add_edge(1, 3)
g.add_edge(3, 4)
g.add_edge(3, 4)
g.add_edge(3, 6)
g.add_edge(6, 3)
g.add_edge(4, 2)
lcc, nodelist = gus.get_lcc(g, return_inds=True)
lcc_matrix = nx.to_numpy_array(lcc)
np.testing.assert_array_equal(lcc_matrix, expected_lcc_matrix)
np.testing.assert_array_equal(nodelist, expected_nodelist)
lcc = gus.get_lcc(g)
lcc_matrix = nx.to_numpy_array(lcc)
np.testing.assert_array_equal(lcc_matrix, expected_lcc_matrix)
示例15: test_lcc_numpy
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import to_numpy_array [as 别名]
def test_lcc_numpy(self):
expected_lcc_matrix = np.array(
[
[0, 1, 1, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 1, 1],
[0, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
]
)
expected_nodelist = np.array([0, 1, 2, 3, 5])
g = nx.DiGraph()
[g.add_node(i) for i in range(1, 7)]
g.add_edge(1, 2)
g.add_edge(1, 3)
g.add_edge(3, 4)
g.add_edge(3, 4)
g.add_edge(3, 6)
g.add_edge(6, 3)
g.add_edge(4, 2)
g = nx.to_numpy_array(g)
lcc_matrix, nodelist = gus.get_lcc(g, return_inds=True)
np.testing.assert_array_equal(lcc_matrix, expected_lcc_matrix)
np.testing.assert_array_equal(nodelist, expected_nodelist)
lcc_matrix = gus.get_lcc(g)
np.testing.assert_array_equal(lcc_matrix, expected_lcc_matrix)