本文整理匯總了Python中networkx.Graph方法的典型用法代碼示例。如果您正苦於以下問題:Python networkx.Graph方法的具體用法?Python networkx.Graph怎麽用?Python networkx.Graph使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類networkx
的用法示例。
在下文中一共展示了networkx.Graph方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import Graph [as 別名]
def __init__(self, model_nm, logfile=None, props=None,
loglevel=logging.INFO):
self.model_nm = model_nm
self.graph = nx.Graph()
if props is None:
self.props = {}
else:
self.props = props
logfile = self.get("log_fname")
self.logger = Logger(self, model_name=model_nm,logfile=logfile)
self.graph.add_edge(self, self.logger)
self["OS"] = platform.system()
self["model"] = model_nm
# process command line args and set them as properties:
prop_nm = None
for arg in sys.argv:
# the first arg (-prop) names the property
if arg.startswith(SWITCH):
prop_nm = arg.lstrip(SWITCH)
# the second arg is the property value
elif prop_nm is not None:
self[prop_nm] = arg
prop_nm = None
示例2: form_cliques
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import Graph [as 別名]
def form_cliques(p_values, nnames):
"""
This method forms the cliques
"""
# first form the numpy matrix data
m = len(nnames)
g_data = np.zeros((m, m), dtype=np.int64)
for p in p_values:
if p[3] == False:
i = np.where(nnames == p[0])[0][0]
j = np.where(nnames == p[1])[0][0]
min_i = min(i, j)
max_j = max(i, j)
g_data[min_i, max_j] = 1
g = networkx.Graph(g_data)
return networkx.find_cliques(g)
示例3: __init_unrestorables
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import Graph [as 別名]
def __init_unrestorables(self):
# anything that can't be restored from JSON file init here
pop_name = ""
if self.model_nm:
pop_name += self.model_nm + " "
pop_name += "Agents"
self.agents = ap.AgentPop(pop_name)
self.womb = []
self.graph = nx.Graph()
self.graph.add_edge(self, self.agents)
if self.props is not None:
self.graph.add_edge(self, self.props)
self.graph.add_edge(self, self.user)
self.graph.add_edge(self, self.menu)
self.graph.add_edge(self, node.universals)
示例4: convert_to_graph_tool
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx 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
示例5: setUp
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import Graph [as 別名]
def setUp(self):
# Create the graph for testing
G = nx.Graph()
G.add_edge('a',2)
G.add_edge(2,'c')
G.add_edge('a','c')
G.add_edge('a',4)
G.add_edge(4,'c')
G.add_edge('out','c')
G.add_edge('c','d')
G.add_edge('d',2)
# Growth edges
G.add_edge('out',11)
G.add_edge('out',12)
G.add_edge(12, 'd')
G.add_edge('TTTTT',11)
G.add_edge('qqqq', 'TTTTT')
G.add_node('alone')
self.input_G = G.copy()
# Viewer under test
self.a = nxv.GraphCanvas(G)
示例6: _radial_behind
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import Graph [as 別名]
def _radial_behind(self, home_node, behind_node):
"""Detect what nodes create a radial string behind the edge from
home_node to behind_node"""
base_islands = nx.number_connected_components(self.dispG)
# If we remove the edge in question, it should radialize the system
# and we can then detect the side to remove
G = nx.Graph()
G.add_nodes_from(self.dispG.nodes())
G.add_edges_from(self.dispG.edges())
G.remove_edge(home_node, behind_node)
node_sets = list(nx.connected_components(G))
if len(node_sets) == base_islands:
# There is no radial path behind this node
return None
else:
for ns in node_sets:
if behind_node in ns:
# We know know what nodes to remove from the display graph
# to remove the radial string
return ns
示例7: text_to_graph
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import Graph [as 別名]
def text_to_graph(text):
import networkx as nx
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.neighbors import kneighbors_graph
# use tfidf to transform texts into feature vectors
vectorizer = TfidfVectorizer()
vectors = vectorizer.fit_transform(text)
# build the graph which is full-connected
N = vectors.shape[0]
mat = kneighbors_graph(vectors, N, metric='cosine', mode='distance', include_self=True)
mat.data = 1 - mat.data # to similarity
g = nx.from_scipy_sparse_matrix(mat, create_using=nx.Graph())
return g
示例8: mol_to_graph
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import Graph [as 別名]
def mol_to_graph(mol):
"""Convert RDKit Mol to NetworkX graph
Convert mol into a graph representation atoms are nodes, and bonds
are vertices stored as graph
Parameters
----------
mol: rdkit Mol
The molecule to convert into a graph.
Returns
-------
graph: networkx.Graph
Contains atoms indices as nodes, edges as bonds.
"""
import networkx as nx
G = nx.Graph()
num_atoms = mol.GetNumAtoms()
G.add_nodes_from(range(num_atoms))
for i in range(mol.GetNumBonds()):
from_idx = mol.GetBonds()[i].GetBeginAtomIdx()
to_idx = mol.GetBonds()[i].GetEndAtomIdx()
G.add_edge(from_idx, to_idx)
return G
示例9: calculate_max_depth_over_max_width
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import Graph [as 別名]
def calculate_max_depth_over_max_width(comment_tree):
comment_tree_nx = nx.from_scipy_sparse_matrix(comment_tree, create_using=nx.Graph())
if len(comment_tree_nx) == 0:
max_depth_over_max_width = 0.0
else:
node_to_depth = nx.shortest_path_length(comment_tree_nx, 0)
depth_to_nodecount = collections.defaultdict(int)
for k, v in node_to_depth.items():
depth_to_nodecount[v] += 1
max_depth = max(node_to_depth.values())
max_width = max(depth_to_nodecount.values())
max_depth_over_max_width = max_depth/max_width
return max_depth_over_max_width
示例10: calculate_comment_tree_hirsch
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import Graph [as 別名]
def calculate_comment_tree_hirsch(comment_tree):
comment_tree_nx = nx.from_scipy_sparse_matrix(comment_tree, create_using=nx.Graph())
if len(comment_tree_nx) == 0:
comment_tree_hirsch = 0.0
else:
node_to_depth = nx.shortest_path_length(comment_tree_nx, 0)
depth_to_nodecount = collections.defaultdict(int)
for k, v in node_to_depth.items():
depth_to_nodecount[v] += 1
comment_tree_hirsch = max(node_to_depth.values())
while True:
if depth_to_nodecount[comment_tree_hirsch] >= comment_tree_hirsch:
break
else:
comment_tree_hirsch -= 1
return comment_tree_hirsch
示例11: load_equivalences
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import Graph [as 別名]
def load_equivalences(paths):
"""Loads equivalences from a text file.
Args:
paths: sequence of paths to the text files of equivalences; id0,id1 per
line, or id0,id1,x,y,z.
Returns:
NX graph object representing the equivalences
"""
equiv_graph = nx.Graph()
for path in paths:
with open(path, "r") as f:
reader = pd.read_csv(
f, sep=",", engine="c", comment="#", chunksize=4096, header=None)
for chunk in reader:
if len(chunk.columns) not in (2, 5):
logging.critical("Unexpected # of columns (%d), want 2 or 5",
len(chunk.columns))
edges = chunk.values[:, :2]
equiv_graph.add_edges_from(edges)
return equiv_graph
示例12: test_no_cheapest_neighbor_first
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import Graph [as 別名]
def test_no_cheapest_neighbor_first():
# Example demonstrating that we should not always visit the cheapest
# neighbor first
# Visit order should be
# C B F D E
global G
G = nx.Graph()
G.add_edge('A', 'B', cost=3)
G.add_edge('A', 'C', cost=1)
G.add_edge('B', 'F', cost=1)
G.add_edge('C', 'E', cost=5)
G.add_edge('C', 'D', cost=4)
visited = init('A')
print('Visited : ', visited)
assert visited == ['A', 'C', 'B', 'F', 'D', 'E']
print('\n\n')
示例13: test_one_loop_2
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import Graph [as 別名]
def test_one_loop_2():
global G
G = nx.Graph()
G.add_edge('A', 'B', cost=2)
G.add_edge('B', 'C', cost=1)
G.add_edge('B', 'D', cost=2)
G.add_edge('C', 'E', cost=2)
G.add_edge('D', 'E', cost=2)
G.add_edge('E', 'F', cost=5)
G.add_edge('D', 'G', cost=1)
visited = init('A')
print('Visited : ', visited)
# order between E and G does not matter, the cost of the path from A to
# them is the same (5)
assert visited == ['A', 'B', 'C', 'D', 'E', 'G', 'F'] or \
visited == ['A', 'B', 'C', 'D', 'G', 'E', 'F']
print('\n\n')
示例14: generate_scalefree_graph
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import Graph [as 別名]
def generate_scalefree_graph(variables_count, m_edge, allow_subgraph):
if not allow_subgraph:
graph = nx.barabasi_albert_graph(variables_count, m_edge)
is_connected = nx.is_connected(graph)
while not is_connected:
graph = nx.barabasi_albert_graph(variables_count, m_edge)
is_connected = nx.is_connected(graph)
else:
graph = nx.barabasi_albert_graph(variables_count, m_edge)
# In the obtained graph, low rank nodes will have a much higher edge count
# than high rank nodes. We shuffle the nodes names to avoid this effect:
new_nodes = list(range(variables_count))
random.shuffle(new_nodes)
node_mapping = {n: nn for n, nn in zip(graph.nodes, new_nodes)}
new_graph = nx.Graph((node_mapping[e1], node_mapping[e2]) for e1, e2 in graph.edges)
return new_graph
示例15: generate_binary_constraints
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import Graph [as 別名]
def generate_binary_constraints(
grid_graph: nx.Graph, variables, bin_range: float, extensive: bool
) -> Dict[str, Constraint]:
constraints: Dict[str, Constraint] = {}
for nodes in grid_graph.edges:
(r1, c1), (r2, c2) = sorted(nodes)
name1 = f"v_{r1}_{c1}"
name2 = f"v_{r2}_{c2}"
v1 = variables[name1]
v2 = variables[name2]
if extensive:
constraint = generate_binary_extensive_constraint(v1, v2, bin_range)
else:
constraint = generate_binary_intentional_constraint(v1, v2, bin_range)
constraints[constraint.name] = constraint
return constraints