本文整理汇总了Python中graph_tool.Graph方法的典型用法代码示例。如果您正苦于以下问题:Python graph_tool.Graph方法的具体用法?Python graph_tool.Graph怎么用?Python graph_tool.Graph使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类graph_tool
的用法示例。
在下文中一共展示了graph_tool.Graph方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: convert_to_graph_tool
# 需要导入模块: import graph_tool [as 别名]
# 或者: from graph_tool import Graph [as 别名]
def convert_to_graph_tool(G):
timer = utils.Timer()
timer.tic()
gtG = gt.Graph(directed=G.is_directed())
gtG.ep['action'] = gtG.new_edge_property('int')
nodes_list = G.nodes()
nodes_array = np.array(nodes_list)
nodes_id = np.zeros((nodes_array.shape[0],), dtype=np.int64)
for i in range(nodes_array.shape[0]):
v = gtG.add_vertex()
nodes_id[i] = int(v)
# d = {key: value for (key, value) in zip(nodes_list, nodes_id)}
d = dict(itertools.izip(nodes_list, nodes_id))
for src, dst, data in G.edges_iter(data=True):
e = gtG.add_edge(d[src], d[dst])
gtG.ep['action'][e] = data['action']
nodes_to_id = d
timer.toc(average=True, log_at=1, log_str='src.graph_utils.convert_to_graph_tool')
return gtG, nodes_array, nodes_to_id
示例2: get_graph_tool_from_adjacency
# 需要导入模块: import graph_tool [as 别名]
# 或者: from graph_tool import Graph [as 别名]
def get_graph_tool_from_adjacency(adjacency, directed=None):
"""Get graph_tool graph from adjacency matrix."""
import graph_tool as gt
adjacency_edge_list = adjacency
if not directed:
from scipy.sparse import tril
adjacency_edge_list = tril(adjacency)
g = gt.Graph(directed=directed)
g.add_vertex(adjacency.shape[0]) # this adds adjacency.shap[0] vertices
g.add_edge_list(np.transpose(adjacency_edge_list.nonzero()))
weights = g.new_edge_property('double')
for e in g.edges():
# graph_tool uses the following convention,
# which is opposite to the rest of scanpy
weights[e] = adjacency[int(e.source()), int(e.target())]
g.edge_properties['weight'] = weights
return g
示例3: get_igraph_from_adjacency
# 需要导入模块: import graph_tool [as 别名]
# 或者: from graph_tool import Graph [as 别名]
def get_igraph_from_adjacency(adjacency, directed=None):
"""Get igraph graph from adjacency matrix."""
import igraph as ig
sources, targets = adjacency.nonzero()
weights = adjacency[sources, targets]
if isinstance(weights, np.matrix):
weights = weights.A1
g = ig.Graph(directed=directed)
g.add_vertices(adjacency.shape[0]) # this adds adjacency.shap[0] vertices
g.add_edges(list(zip(sources, targets)))
try:
g.es['weight'] = weights
except:
pass
if g.vcount() != adjacency.shape[0]:
logg.warn('The constructed graph has only {} nodes. '
'Your adjacency matrix contained redundant nodes.'
.format(g.vcount()))
return g
示例4: __from_nx_to_graph_tool
# 需要导入模块: import graph_tool [as 别名]
# 或者: from graph_tool import Graph [as 别名]
def __from_nx_to_graph_tool(g, directed=None):
"""
:param g:
:param directed:
:return:
"""
if directed is None:
directed = g.is_directed()
if gt is None:
raise ModuleNotFoundError(
"Optional dependency not satisfied: install igraph to use the selected feature.")
gt_g = gt.Graph(directed=directed)
node_map = {v: i for i, v in enumerate(g.nodes())}
gt_g.add_vertex(len(node_map))
gt_g.add_edge_list([(node_map[u], node_map[v]) for u, v in g.edges()])
return gt_g, {v: k for k, v in node_map.items()}
示例5: __from_graph_tool_to_nx
# 需要导入模块: import graph_tool [as 别名]
# 或者: from graph_tool import Graph [as 别名]
def __from_graph_tool_to_nx(graph, node_map=None, directed=None):
if directed is None:
directed = graph.is_directed()
if directed:
tp = nx.DiGraph()
else:
tp = nx.Graph()
tp.add_nodes_from([int(v) for v in graph.vertices()])
tp.add_edges_from([(int(e.source()), int(e.target()))
for e in graph.edges()])
if node_map:
nx.relabel_nodes(tp, node_map, copy=False)
return tp
示例6: __from_igraph_to_nx
# 需要导入模块: import graph_tool [as 别名]
# 或者: from graph_tool import Graph [as 别名]
def __from_igraph_to_nx(ig, directed=None):
"""
:param ig:
:param directed:
:return:
"""
if ig is None:
raise ModuleNotFoundError(
"Optional dependency not satisfied: install igraph to use the selected feature.")
if directed is None:
directed = ig.is_directed()
if directed:
tp = nx.DiGraph()
else:
tp = nx.Graph()
for e in ig.es:
tp.add_edge(ig.vs[e.source]["name"], ig.vs[e.target]["name"], **e.attributes())
return tp
示例7: convert_graph_formats
# 需要导入模块: import graph_tool [as 别名]
# 或者: from graph_tool import Graph [as 别名]
def convert_graph_formats(graph, desired_format, directed=None):
"""Converts from/to networkx/igraph
:param graph: original graph object
:param desired_format: desired final type. Either nx.Graph or ig.Graph
:param directed: boolean, default **False**
:return: the converted graph
:raises TypeError: if input graph is neither an instance of nx.Graph nor ig.Graph
"""
if isinstance(graph, desired_format):
return graph
elif desired_format is nx.Graph:
return __from_igraph_to_nx(graph, directed)
elif ig is not None and desired_format is ig.Graph:
return __from_nx_to_igraph(graph, directed)
else:
raise TypeError(
"The graph object should be either a networkx or an igraph one.")
示例8: test_degree
# 需要导入模块: import graph_tool [as 别名]
# 或者: from graph_tool import Graph [as 别名]
def test_degree(self):
graph = graphs.Graph([
[0, 1, 0],
[1, 0, 2],
[0, 2, 0],
])
self.assertEqual(graph.is_directed(), False)
np.testing.assert_allclose(graph.d, [1, 2, 1])
np.testing.assert_allclose(graph.dw, [1, 3, 2])
graph = graphs.Graph([
[0, 1, 0],
[0, 0, 2],
[0, 2, 0],
])
self.assertEqual(graph.is_directed(), True)
np.testing.assert_allclose(graph.d, [0.5, 1.5, 1])
np.testing.assert_allclose(graph.dw, [0.5, 2.5, 2])
示例9: test_is_directed
# 需要导入模块: import graph_tool [as 别名]
# 或者: from graph_tool import Graph [as 别名]
def test_is_directed(self):
graph = graphs.Graph([
[0, 3, 0, 0],
[3, 0, 4, 0],
[0, 4, 0, 2],
[0, 0, 2, 0],
])
assert graph.W.nnz == 6
self.assertEqual(graph.is_directed(), False)
# In-place modification is not allowed anymore.
# graph.W[0, 1] = 0
# assert graph.W.nnz == 6
# self.assertEqual(graph.is_directed(recompute=True), True)
# graph.W[1, 0] = 0
# assert graph.W.nnz == 6
# self.assertEqual(graph.is_directed(recompute=True), False)
示例10: test_differential_operator
# 需要导入模块: import graph_tool [as 别名]
# 或者: from graph_tool import Graph [as 别名]
def test_differential_operator(self, n_vertices=98):
r"""The Laplacian must always be the divergence of the gradient,
whether the Laplacian is combinatorial or normalized, and whether the
graph is directed or weighted."""
def test_incidence_nx(graph):
r"""Test that the incidence matrix corresponds to NetworkX."""
incidence_pg = np.sign(graph.D.toarray())
G = nx.OrderedDiGraph if graph.is_directed() else nx.OrderedGraph
graph_nx = nx.from_scipy_sparse_matrix(graph.W, create_using=G)
incidence_nx = nx.incidence_matrix(graph_nx, oriented=True)
np.testing.assert_equal(incidence_pg, incidence_nx.toarray())
for graph in [graphs.Graph(np.zeros((n_vertices, n_vertices))),
graphs.Graph(np.identity(n_vertices)),
graphs.Graph([[0, 0.8], [0.8, 0]]),
graphs.Graph([[1.3, 0], [0.4, 0.5]]),
graphs.ErdosRenyi(n_vertices, directed=False, seed=42),
graphs.ErdosRenyi(n_vertices, directed=True, seed=42)]:
for lap_type in ['combinatorial', 'normalized']:
graph.compute_laplacian(lap_type)
graph.compute_differential_operator()
L = graph.D.dot(graph.D.T)
np.testing.assert_allclose(L.toarray(), graph.L.toarray())
test_incidence_nx(graph)
示例11: test_adjacency_types
# 需要导入模块: import graph_tool [as 别名]
# 或者: from graph_tool import Graph [as 别名]
def test_adjacency_types(self, n_vertices=10):
rs = np.random.RandomState(42)
W = 10 * np.abs(rs.normal(size=(n_vertices, n_vertices)))
W = W + W.T
W = W - np.diag(np.diag(W))
def test(adjacency):
G = graphs.Graph(adjacency)
G.compute_laplacian('combinatorial')
G.compute_laplacian('normalized')
G.estimate_lmax()
G.compute_fourier_basis()
G.compute_differential_operator()
test(W)
test(W.astype(np.float32))
test(W.astype(np.int))
test(sparse.csr_matrix(W))
test(sparse.csr_matrix(W, dtype=np.float32))
test(sparse.csr_matrix(W, dtype=np.int))
test(sparse.csc_matrix(W))
test(sparse.coo_matrix(W))
示例12: test_graphtool_multiedge_import
# 需要导入模块: import graph_tool [as 别名]
# 或者: from graph_tool import Graph [as 别名]
def test_graphtool_multiedge_import(self):
# Manualy create a graph with multiple edges
g_gt = gt.Graph()
g_gt.add_vertex(n=10)
# connect edge (3,6) three times
for i in range(3):
g_gt.add_edge(g_gt.vertex(3), g_gt.vertex(6))
g = graphs.Graph.from_graphtool(g_gt)
self.assertEqual(g.W[3, 6], 3.0)
eprop_double = g_gt.new_edge_property("double")
# Set the weight of 2 out of the 3 edges. The last one has a default weight of 0
e = g_gt.edge(3, 6, all_edges=True)
eprop_double[e[0]] = 8.0
eprop_double[e[1]] = 1.0
g_gt.edge_properties["weight"] = eprop_double
g3 = graphs.Graph.from_graphtool(g_gt)
self.assertEqual(g3.W[3, 6], 9.0)
示例13: test_graphtool_import_export
# 需要导入模块: import graph_tool [as 别名]
# 或者: from graph_tool import Graph [as 别名]
def test_graphtool_import_export(self):
# Import to PyGSP and export again to graph tool directly
# create a random graphTool graph that does not contain multiple edges and no signal
graph_gt = gt.generation.random_graph(100, lambda : (np.random.poisson(4), np.random.poisson(4)))
eprop_double = graph_gt.new_edge_property("double")
for e in graph_gt.edges():
eprop_double[e] = random.random()
graph_gt.edge_properties["weight"] = eprop_double
graph2_gt = graphs.Graph.from_graphtool(graph_gt).to_graphtool()
self.assertEqual(graph_gt.num_edges(), graph2_gt.num_edges(),
"the number of edges does not correspond")
def key(edge): return str(edge.source()) + ":" + str(edge.target())
for e1, e2 in zip(sorted(graph_gt.edges(), key=key), sorted(graph2_gt.edges(), key=key)):
self.assertEqual(e1.source(), e2.source())
self.assertEqual(e1.target(), e2.target())
for v1, v2 in zip(graph_gt.vertices(), graph2_gt.vertices()):
self.assertEqual(v1, v2)
示例14: test_graphtool_signal_import
# 需要导入模块: import graph_tool [as 别名]
# 或者: from graph_tool import Graph [as 别名]
def test_graphtool_signal_import(self):
g_gt = gt.Graph()
g_gt.add_vertex(10)
g_gt.add_edge(g_gt.vertex(3), g_gt.vertex(6))
g_gt.add_edge(g_gt.vertex(4), g_gt.vertex(6))
g_gt.add_edge(g_gt.vertex(7), g_gt.vertex(2))
vprop_double = g_gt.new_vertex_property("double")
vprop_double[g_gt.vertex(0)] = 5
vprop_double[g_gt.vertex(1)] = -3
vprop_double[g_gt.vertex(2)] = 2.4
g_gt.vertex_properties["signal"] = vprop_double
g = graphs.Graph.from_graphtool(g_gt)
self.assertEqual(g.signals["signal"][0], 5.0)
self.assertEqual(g.signals["signal"][1], -3.0)
self.assertEqual(g.signals["signal"][2], 2.4)
示例15: test_break_join_signals
# 需要导入模块: import graph_tool [as 别名]
# 或者: from graph_tool import Graph [as 别名]
def test_break_join_signals(self):
"""Multi-dim signals are broken on export and joined on import."""
graph1 = graphs.Sensor(20, seed=42)
graph1.set_signal(graph1.coords, 'coords')
# networkx
graph2 = graph1.to_networkx()
graph2 = graphs.Graph.from_networkx(graph2)
np.testing.assert_allclose(graph2.signals['coords'], graph1.coords)
# graph-tool
graph2 = graph1.to_graphtool()
graph2 = graphs.Graph.from_graphtool(graph2)
np.testing.assert_allclose(graph2.signals['coords'], graph1.coords)
# save and load (need ordered dicts)
if sys.version_info >= (3, 6):
filename = 'graph.graphml'
graph1.save(filename)
graph2 = graphs.Graph.load(filename)
np.testing.assert_allclose(graph2.signals['coords'], graph1.coords)
os.remove(filename)