本文整理汇总了Python中igraph.Graph方法的典型用法代码示例。如果您正苦于以下问题:Python igraph.Graph方法的具体用法?Python igraph.Graph怎么用?Python igraph.Graph使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类igraph
的用法示例。
在下文中一共展示了igraph.Graph方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: nearest_neighbors
# 需要导入模块: import igraph [as 别名]
# 或者: from igraph import Graph [as 别名]
def nearest_neighbors(X, neighbors=16, threads=1):
# initialize HNSW index on Cosine Similarity
nn_index = nmslib.init(method='hnsw', space='cosinesimil')
nn_index.addDataPointBatch(X)
nn_index.createIndex({'post': 2}, print_progress=True)
# get nearest neighbours
Xn = nn_index.knnQueryBatch(X, k=(neighbors+1), num_threads=threads)
# extract graph edges
sources = []
targets = []
for i, neigh in enumerate(Xn):
sources += [i]*(neighbors-1)
targets += list(neigh[0][1:])
# construct igraph
nn_graph = igraph.Graph(directed=True)
nn_graph.add_vertices(X.shape[0])
nn_graph.add_edges(list(zip(sources, targets)))
return nn_graph
示例2: _make_dataset
# 需要导入模块: import igraph [as 别名]
# 或者: from igraph import Graph [as 别名]
def _make_dataset(self, edges, nodes, name, description, mode):
try:
if len(edges) == 0:
util.warn('Graph has no edges, may have rendering issues')
except:
1
if mode == 'json':
edges_df = self._table_to_pandas(edges)
nodes_df = self._table_to_pandas(nodes)
return self._make_json_dataset(edges_df, nodes_df, name)
elif mode == 'vgraph':
edges_df = self._table_to_pandas(edges)
nodes_df = self._table_to_pandas(nodes)
return self._make_vgraph_dataset(edges_df, nodes_df, name)
elif mode == 'arrow':
edges_arr = self._table_to_arrow(edges)
nodes_arr = self._table_to_arrow(nodes)
return self._make_arrow_dataset(edges_arr, nodes_arr, name, description)
#token=None, dataset_id=None, url_params = None)
else:
raise ValueError('Unknown mode: ' + mode)
# Main helper for creating ETL1 payload
示例3: decode_ENAS_to_igraph
# 需要导入模块: import igraph [as 别名]
# 或者: from igraph import Graph [as 别名]
def decode_ENAS_to_igraph(row):
if type(row) == str:
row = eval(row) # convert string to list of lists
n = len(row)
g = igraph.Graph(directed=True)
g.add_vertices(n+2)
g.vs[0]['type'] = 0 # input node
for i, node in enumerate(row):
g.vs[i+1]['type'] = node[0] + 2 # assign 2, 3, ... to other types
g.add_edge(i, i+1) # always connect from last node
for j, edge in enumerate(node[1:]):
if edge == 1:
g.add_edge(j, i+1)
g.vs[n+1]['type'] = 1 # output node
g.add_edge(n, n+1)
# note that the nodes 0, 1, ... n+1 are in a topological order
return g, n+2
示例4: decode_BN_to_igraph
# 需要导入模块: import igraph [as 别名]
# 或者: from igraph import Graph [as 别名]
def decode_BN_to_igraph(row):
if type(row) == str:
row = eval(row) # convert string to list of lists
n = len(row)
g = igraph.Graph(directed=True)
g.add_vertices(n+2)
g.vs[0]['type'] = 0 # input node
for i, node in enumerate(row):
cur_type = node[0] + 2
g.vs[i+1]['type'] = cur_type
if sum(node[1:]) == 0: # if no connections from previous nodes, connect from input
g.add_edge(0, i+1)
else:
for j, edge in enumerate(node[1:]):
if edge == 1:
g.add_edge(j+1, i+1)
g.vs[n+1]['type'] = 1 # output node
end_vertices = [v.index for v in g.vs.select(_outdegree_eq=0) if v.index != n+1]
for j in end_vertices: # connect all loose-end vertices to the output node
g.add_edge(j, n+1)
return g, n+2
示例5: _check_array_function_arguments
# 需要导入模块: import igraph [as 别名]
# 或者: from igraph import Graph [as 别名]
def _check_array_function_arguments(**kwargs):
"""Checks for invalid arguments when an array is passed.
Helper for functions that work on either AnnData objects or array-likes.
"""
# TODO: Figure out a better solution for documenting dispatched functions
invalid_args = [k for k, v in kwargs.items() if v is not None]
if len(invalid_args) > 0:
raise TypeError(
f"Arguments {invalid_args} are only valid if an AnnData object is passed."
)
# --------------------------------------------------------------------------------
# Graph stuff
# --------------------------------------------------------------------------------
示例6: get_igraph_from_adjacency
# 需要导入模块: import igraph [as 别名]
# 或者: from igraph 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.shape[0] vertices
g.add_edges(list(zip(sources, targets)))
try:
g.es['weight'] = weights
except:
pass
if g.vcount() != adjacency.shape[0]:
logg.warning(
f'The constructed graph has only {g.vcount()} nodes. '
'Your adjacency matrix contained redundant nodes.'
)
return g
示例7: forceatlas2_networkx_layout
# 需要导入模块: import igraph [as 别名]
# 或者: from igraph import Graph [as 别名]
def forceatlas2_networkx_layout(self, G, pos=None, iterations=100, weight_attr=None):
import networkx
try:
import cynetworkx
except ImportError:
cynetworkx = None
assert (
isinstance(G, networkx.classes.graph.Graph)
or (cynetworkx and isinstance(G, cynetworkx.classes.graph.Graph))
), "Not a networkx graph"
assert isinstance(pos, dict) or (pos is None), "pos must be specified as a dictionary, as in networkx"
M = networkx.to_scipy_sparse_matrix(G, dtype='f', format='lil', weight=weight_attr)
if pos is None:
l = self.forceatlas2(M, pos=None, iterations=iterations)
else:
poslist = numpy.asarray([pos[i] for i in G.nodes()])
l = self.forceatlas2(M, pos=poslist, iterations=iterations)
return dict(zip(G.nodes(), l))
# A layout for igraph.
#
# This function returns an igraph layout
示例8: test_kertesz_model
# 需要导入模块: import igraph [as 别名]
# 或者: from igraph import Graph [as 别名]
def test_kertesz_model(self):
for g in get_graph():
model = epd.KerteszThresholdModel(g)
config = mc.Configuration()
config.add_model_parameter('adopter_rate', 0.4)
config.add_model_parameter('percentage_blocked', 0.1)
config.add_model_parameter('fraction_infected', 0.1)
threshold = 0.2
if isinstance(g, nx.Graph):
nodes = g.nodes
else:
nodes = g.vs['name']
for i in nodes:
config.add_node_configuration("threshold", i, threshold)
model.set_initial_status(config)
iterations = model.iteration_bunch(10)
self.assertEqual(len(iterations), 10)
iterations = model.iteration_bunch(10, node_status=False)
self.assertEqual(len(iterations), 10)
示例9: test_threshold_model
# 需要导入模块: import igraph [as 别名]
# 或者: from igraph import Graph [as 别名]
def test_threshold_model(self):
for g in get_graph(True):
model = epd.ThresholdModel(g)
config = mc.Configuration()
config.add_model_parameter('fraction_infected', 0.1)
threshold = 0.2
if isinstance(g, nx.Graph):
nodes = g.nodes
else:
nodes = g.vs['name']
for i in nodes:
config.add_node_configuration("threshold", i, threshold)
model.set_initial_status(config)
iterations = model.iteration_bunch(10)
self.assertEqual(len(iterations), 10)
iterations = model.iteration_bunch(10, node_status=False)
self.assertEqual(len(iterations), 10)
示例10: test_generalisedthreshold_model
# 需要导入模块: import igraph [as 别名]
# 或者: from igraph import Graph [as 别名]
def test_generalisedthreshold_model(self):
for g in get_graph(True):
model = epd.GeneralisedThresholdModel(g)
config = mc.Configuration()
config.add_model_parameter('fraction_infected', 0.1)
config.add_model_parameter('tau', 5)
config.add_model_parameter('mu', 5)
threshold = 0.2
if isinstance(g, nx.Graph):
nodes = g.nodes
else:
nodes = g.vs['name']
for i in nodes:
config.add_node_configuration("threshold", i, threshold)
model.set_initial_status(config)
iterations = model.iteration_bunch(50)
self.assertEqual(len(iterations), 50)
iterations = model.iteration_bunch(50, node_status=False)
self.assertEqual(len(iterations), 50)
示例11: test_independent_cascade_model
# 需要导入模块: import igraph [as 别名]
# 或者: from igraph import Graph [as 别名]
def test_independent_cascade_model(self):
for g in get_graph(True):
model = epd.IndependentCascadesModel(g)
config = mc.Configuration()
config.add_model_parameter('percentage_infected', 0.1)
threshold = 0.1
if isinstance(g, nx.Graph):
for e in g.edges:
config.add_edge_configuration("threshold", e, threshold)
else:
edges = [(g.vs[e.tuple[0]]['name'], g.vs[e.tuple[1]]['name']) for e in g.es]
for e in edges:
config.add_edge_configuration("threshold", e, threshold)
model.set_initial_status(config)
iterations = model.iteration_bunch(10)
self.assertEqual(len(iterations), 10)
iterations = model.iteration_bunch(10, node_status=False)
self.assertEqual(len(iterations), 10)
示例12: test_ICE
# 需要导入模块: import igraph [as 别名]
# 或者: from igraph import Graph [as 别名]
def test_ICE(self):
for g in get_graph(True):
model = epd.ICEModel(g)
config = mc.Configuration()
config.add_model_parameter('percentage_infected', 0.1)
if isinstance(g, nx.Graph):
node_to_com = {n: random.choice([0, 1])for n in g.nodes()}
for i in g.nodes():
config.add_node_configuration("com", i, node_to_com[i])
else:
node_to_com = {n: random.choice([0, 1]) for n in g.vs['name']}
for i in g.vs['name']:
config.add_node_configuration("com", i, node_to_com[i])
model.set_initial_status(config)
iterations = model.iteration_bunch(10)
self.assertEqual(len(iterations), 10)
iterations = model.iteration_bunch(10, node_status=False)
self.assertEqual(len(iterations), 10)
示例13: test_kertesz_model_predefined_blocked
# 需要导入模块: import igraph [as 别名]
# 或者: from igraph import Graph [as 别名]
def test_kertesz_model_predefined_blocked(self):
for g in get_graph(True):
model = epd.KerteszThresholdModel(g)
config = mc.Configuration()
config.add_model_parameter('adopter_rate', 0.4)
predefined_blocked = [0, 1, 2, 3, 4, 5]
config.add_model_initial_configuration("Blocked", predefined_blocked)
config.add_model_parameter('percentage_infected', 0.1)
threshold = 0.2
if isinstance(g, nx.Graph):
nodes = g.nodes
else:
nodes = g.vs['name']
for i in nodes:
config.add_node_configuration("threshold", i, threshold)
model.set_initial_status(config)
iteration = model.iteration()
blocked = [x for x, v in future.utils.iteritems(iteration['status']) if v == -1]
self.assertEqual(blocked, predefined_blocked)
示例14: get_graph_tool_from_adjacency
# 需要导入模块: import igraph [as 别名]
# 或者: from igraph 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
示例15: get_igraph_from_adjacency
# 需要导入模块: import igraph [as 别名]
# 或者: from igraph 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