本文整理汇总了Python中networkx.DiGraph.add_nodes_from方法的典型用法代码示例。如果您正苦于以下问题:Python DiGraph.add_nodes_from方法的具体用法?Python DiGraph.add_nodes_from怎么用?Python DiGraph.add_nodes_from使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx.DiGraph
的用法示例。
在下文中一共展示了DiGraph.add_nodes_from方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: add_nodes_from
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_nodes_from [as 别名]
def add_nodes_from(self, nodes, **attr):
H=copy.deepcopy(self)
self.clear()
if not H.nodes():
DiGraph.add_nodes_from(self, nodes, **attr)
self.names=names=sorted(nodes)
for i, n in enumerate(self.names):
self.node[i]={'name': n, 'pmf': Pmf()}
self.node[i]['pmf'].Set(1,self.p)
self.node[i]['pmf'].Set(0, 1-self.p)
self.remove_node(n)
self.edge[i]={}
self.indep_vars+=[i]
self.SetProbs()
return
DiGraph.add_nodes_from(self, nodes, **attr)
#ind_vars=[var for var in H.indep_vars]
#DiGraph.add_nodes_from(self, ind_vars)
self.names=names=sorted(set(H.names + nodes))
for i, n in enumerate(names):
try:
self.node[i], self.edge[i]=H.node[i], H.edge[i]
except:
self.node[i]={'name': n, 'pmf': Pmf()}
self.node[i]['pmf'].Set(1,self.p)
self.node[i]['pmf'].Set(0, 1-self.p)
self.remove_node(n)
self.edge[i]={}
self.indep_vars+=[i]
self.SetProbs()
示例2: filter_non_dependencies
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_nodes_from [as 别名]
def filter_non_dependencies(nodes, get_deps_func):
node_set = set(nodes)
G = DiGraph()
G.add_nodes_from(nodes)
# process the edges based on the dependency function
for n in G:
deps = get_deps_func(n)
logging.info('%s depends on %s' % (n, deps))
for d in deps:
if d in G:
G.add_edge(n, d)
# now filter the nodes and return them
filtered_pkgs = {node for node, in_degree in G.in_degree_iter() if in_degree == 0}
# now find any strongly connected components with size greater than 1
# these will all have in degree > 0, but should still be included
glist = [g for g in strongly_connected_component_subgraphs(G, copy=False) if g.number_of_nodes() > 1]
for g in glist:
# only counts if it was the original list
nodes = [n for n in g.nodes() if n in node_set]
if len(nodes) > 0:
logging.debug('Strongly connected component: %s' % repr(nodes))
for n in nodes:
filtered_pkgs.add(n)
return filtered_pkgs
示例3: init_graph
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_nodes_from [as 别名]
def init_graph(self):
#Represent the graph using adjacency lists
g = DiGraph()
g.add_nodes_from(self.vocabulary) #The keys (terms) become nodes in the graph
for x in self.vocabulary:
for y in self.vocabulary:
if self.conditional_probability(x,y) >= 0.8 and self.conditional_probability(y,x) < 0.8:
g.add_edge(x,y)
return g
示例4: example_tree
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_nodes_from [as 别名]
def example_tree():
"""creates a tree/networkx.DiGraph of a syntactic parse tree"""
tree = DiGraph()
tree.add_nodes_from(['S', 'NP-1', 'N-1', 'Jeff', 'VP', 'V', 'ate', 'NP-2', 'D',
'the', 'N-2', 'apple'])
tree.add_edges_from([('S', 'NP-1'), ('NP-1', 'N-1'), ('N-1', 'Jeff'),
('S', 'VP'), ('VP', 'V'), ('V', 'ate'),
('VP', 'NP-2'), ('NP-2', 'D'), ('D', 'the'),
('NP-2', 'N-2'), ('N-2', 'apple')])
return tree
示例5: build_digraph
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_nodes_from [as 别名]
def build_digraph(fasta_dict, k):
"""Build a digraph from the data given by the fasta dict, using k and our
is_edge predicate.
"""
d = DiGraph()
d.add_nodes_from(fasta_dict.items())
for (s, t) in permutations(fasta_dict.items(), 2):
if is_edge(s, t, k):
d.add_edge(s, t)
return d
示例6: test_get_coord_dict
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_nodes_from [as 别名]
def test_get_coord_dict():
g = DiGraph()
g.add_nodes_from(['1', '23X', 'X', 'OX', 'A', 'TU'])
coord_dict, leftovers = get_coord_dict(g,
'cocotools/coords/pht00_rhesus.tsv')
nt.assert_equal(coord_dict, {'1': [20.31, -10.8],
'23X': [2.41, -30.15],
'OX': [1.57, -1.8],
'TU': [5.21, 1.8]})
nt.assert_equal(leftovers, ['A', 'X'])
示例7: render_trees
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_nodes_from [as 别名]
def render_trees(parsed_dir_path: Path, target_dir_path: Path,
work_distribution: list):
for ecli in work_distribution:
parsed_files_glob = parsed_dir_path.joinpath(ecli).glob('*.xml')
for parsed_file_path in parsed_files_glob:
if parsed_file_path.is_file() and parsed_file_path.stat(
).st_size != 0:
json_dir_path = target_dir_path.joinpath(ecli)
if not json_dir_path.is_dir():
mkdir(str(json_dir_path))
json_file_name = parsed_file_path.name + '.json'
json_file_path = json_dir_path.joinpath(json_file_name)
# draw_spring(tree)
if not json_file_path.is_file() or json_file_path.stat(
).st_size != 0:
tree = DiGraph()
xml_tree = parse(str(parsed_file_path))
sentence = SENTENCE_XPATH(xml_tree)[0].text
nodes = []
edges = []
for xml_node in XML_NODES(xml_tree):
lemma = xml_node.get('lemma')
pos = xml_node.get('pos')
if lemma is None:
lemma = '...'
node_id = int(xml_node.attrib['id'])
node_attributes = {'name': lemma, 'pos': pos}
node = (node_id, node_attributes)
nodes.append(node)
parent_node_id = int(xml_node.getparent().get('id'))
edges.append((parent_node_id, node_id))
tree.add_nodes_from(nodes)
tree.add_edges_from(edges)
tree_json = json_graph.tree_data(tree, root=0)
wrapper_json = {'origin': parsed_file_path.as_uri(),
'sentence': sentence,
'tree': tree_json}
with json_file_path.open(mode='wt') as json_file:
dump(wrapper_json, json_file, indent=True)
info("Rendered parse tree to '{json_file_path}'. ".format(
json_file_path=json_file_path))
else:
error("Empty or non-existent XML parse tree file at "
"'{parsed_file_path}'. ".format(
parsed_file_path=parsed_file_path))
示例8: to_directed
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_nodes_from [as 别名]
def to_directed(self):
from networkx import DiGraph
G = DiGraph()
G.name = self.name
G.add_nodes_from(self.n)
G.add_edges_from(((u, v, deepcopy(data))
for u, nbrs in self.a
for v, data in nbrs.items()))
G.graph = deepcopy(self.data)
G._nodedata = deepcopy(self._nodedata)
G.node = G._nodedata # hack to pass test
return G
示例9: to_directed
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_nodes_from [as 别名]
def to_directed(self):
from networkx import DiGraph
G=DiGraph()
G.name=self.name
G.add_nodes_from(self)
G.add_edges_from( ((u,v,deepcopy(data))
for u,nbrs in self.adjacency_iter()
for v,data in nbrs.iteritems()) )
G.graph=deepcopy(self.graph)
G.node=deepcopy(self.node)
return G
示例10: update_from_db
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_nodes_from [as 别名]
def update_from_db(self, session):
# Only allow one thread at a time to construct a fresh graph.
with self.update_lock:
checkpoint, checkpoint_time = self._get_checkpoint(session)
if checkpoint == self.checkpoint:
self.logger.debug("Checkpoint hasn't changed. Not Updating.")
return
self.logger.debug("Checkpoint changed; updating!")
new_graph = DiGraph()
new_graph.add_nodes_from(self._get_nodes_from_db(session))
new_graph.add_edges_from(self._get_edges_from_db(session))
rgraph = new_graph.reverse()
users = set()
groups = set()
for (node_type, node_name) in new_graph.nodes():
if node_type == "User":
users.add(node_name)
elif node_type == "Group":
groups.add(node_name)
user_metadata = self._get_user_metadata(session)
permission_metadata = self._get_permission_metadata(session)
service_account_permissions = all_service_account_permissions(session)
group_metadata = self._get_group_metadata(session, permission_metadata)
group_service_accounts = self._get_group_service_accounts(session)
permission_tuples = self._get_permission_tuples(session)
group_tuples = self._get_group_tuples(session)
disabled_group_tuples = self._get_group_tuples(session, enabled=False)
with self.lock:
self._graph = new_graph
self._rgraph = rgraph
self.checkpoint = checkpoint
self.checkpoint_time = checkpoint_time
self.users = users
self.groups = groups
self.permissions = {perm.permission
for perm_list in permission_metadata.values()
for perm in perm_list}
self.user_metadata = user_metadata
self.group_metadata = group_metadata
self.group_service_accounts = group_service_accounts
self.permission_metadata = permission_metadata
self.service_account_permissions = service_account_permissions
self.permission_tuples = permission_tuples
self.group_tuples = group_tuples
self.disabled_group_tuples = disabled_group_tuples
示例11: add_nodes_from
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_nodes_from [as 别名]
def add_nodes_from(self, nodes, **attr):
H=DiGraph()
H.add_nodes_from(self.names)
h_names=sorted(H.nodes())
H.add_edges_from([(h_names[e[0]], h_names[e[1]], self.edge[e[0]][e[1]]) for e in self.edges()])
causes={h_names[v]: {h_names[item]: self.node[v]['causes'][item] for item in self.node[v]['causes']} for v in self.dep_vars}
self.clear()
self.indep_vars=[]
self.dep_vars=[]
if not H.nodes():
DiGraph.add_nodes_from(self, nodes, **attr)
self.names=names=sorted(nodes)
for i, n in enumerate(self.names):
self.node[i]={'name': n, 'pmf': Pmf()}
self.node[i]['pmf'].Set(1,self.p)
self.node[i]['pmf'].Set(0, 1-self.p)
self.remove_node(n)
self.edge[i]={}
self.indep_vars+=[i]
self.SetProbs()
return
#DiGraph.add_nodes_from(self, nodes, **attr)
#ind_vars=[var for var in H.indep_vars]
#DiGraph.add_nodes_from(self, ind_vars)
self.names=names=sorted(set(H.nodes() + nodes))
for i, n in enumerate(names):
if n in H.nodes():
self.node[i], self.edge[i]=H.node[n], {names.index(item): H.edge[n][item] for item in H.edge[n]}
self.node[i]['causes']={names.index(item): causes[n][item] for item in causes[n]} if n in causes else {}
self.node[i]['name']=n
self.node[i]['pmf']=Pmf()
if not self.node[i]['causes']:
self.node[i]['pmf'].Set(1,self.p)
self.node[i]['pmf'].Set(0, 1-self.p)
self.indep_vars+=[i]
else: self.dep_vars+=[i]
else:
self.node[i]={'name': n, 'pmf': Pmf()}
self.node[i]['pmf'].Set(1,self.p)
self.node[i]['pmf'].Set(0, 1-self.p)
#self.remove_node(n)
self.edge[i]={}
self.indep_vars+=[i]
self.SetProbs()
示例12: to_directed
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_nodes_from [as 别名]
def to_directed(self):
"""Return a directed representation of the graph.
A new directed graph is returned with the same name, same nodes,
and with each edge (u,v,data) replaced by two directed edges
(u,v,data) and (v,u,data).
"""
from networkx import DiGraph
G=DiGraph()
G.add_nodes_from(self)
G.add_edges_from( ((u,v,data)
for u,nbrs in self.adjacency_iter()
for v,data in nbrs.iteritems()) )
return G
示例13: update_from_db
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_nodes_from [as 别名]
def update_from_db(self, session):
# type: (Session) -> None
# Only allow one thread at a time to construct a fresh graph.
with self._update_lock:
checkpoint, checkpoint_time = self._get_checkpoint(session)
if checkpoint == self.checkpoint:
self._logger.debug("Checkpoint hasn't changed. Not Updating.")
return
self._logger.debug("Checkpoint changed; updating!")
start_time = datetime.utcnow()
user_metadata = self._get_user_metadata(session)
groups, disabled_groups = self._get_groups(session, user_metadata)
permissions = self._get_permissions(session)
group_grants = self._get_group_grants(session)
group_service_accounts = self._get_group_service_accounts(session)
service_account_grants = all_service_account_permissions(session)
graph = DiGraph()
graph.add_nodes_from(self._get_nodes(groups, user_metadata))
graph.add_edges_from(self._get_edges(session))
rgraph = graph.reverse()
grants_by_permission = self._get_grants_by_permission(
graph, group_grants, service_account_grants
)
with self.lock:
self._graph = graph
self._rgraph = rgraph
self.checkpoint = checkpoint
self.checkpoint_time = checkpoint_time
self.user_metadata = user_metadata
self._groups = groups
self._disabled_groups = disabled_groups
self._permissions = permissions
self._group_grants = group_grants
self._group_service_accounts = group_service_accounts
self._service_account_grants = service_account_grants
self._grants_by_permission = grants_by_permission
duration = datetime.utcnow() - start_time
stats.log_rate("graph_update_ms", int(duration.total_seconds() * 1000))
示例14: update_from_db
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_nodes_from [as 别名]
def update_from_db(self, session):
checkpoint, checkpoint_time = self._get_checkpoint(session)
if checkpoint == self.checkpoint:
logging.debug("Checkpoint hasn't changed. Not Updating.")
return
logging.debug("Checkpoint changed; updating!")
new_graph = DiGraph()
new_graph.add_nodes_from(self._get_nodes_from_db(session))
new_graph.add_edges_from(self._get_edges_from_db(session))
rgraph = new_graph.reverse()
users = set()
groups = set()
for (node_type, node_name) in new_graph.nodes():
if node_type == "User":
users.add(node_name)
elif node_type == "Group":
groups.add(node_name)
user_metadata = self._get_user_metadata(session)
permission_metadata = self._get_permission_metadata(session)
group_metadata = self._get_group_metadata(session, permission_metadata)
with self.lock:
self._graph = new_graph
self._rgraph = rgraph
self.checkpoint = checkpoint
self.checkpoint_time = checkpoint_time
self.users = users
self.groups = groups
self.permissions = {perm.permission
for perm_list in permission_metadata.values()
for perm in perm_list}
self.user_metadata = user_metadata
self.group_metadata = group_metadata
self.permission_metadata = permission_metadata
示例15: deterministic_topological_ordering
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_nodes_from [as 别名]
def deterministic_topological_ordering(nodes, links, start_node):
"""
Topological sort that is deterministic because it sorts (alphabetically)
candidates to check
"""
graph = DiGraph()
graph.add_nodes_from(nodes)
for link in links:
graph.add_edge(*link)
if not is_directed_acyclic_graph(graph):
raise NetworkXUnfeasible
task_names = sorted(graph.successors(start_node))
task_set = set(task_names)
graph.remove_node(start_node)
result = [start_node]
while task_names:
for name in task_names:
if graph.in_degree(name) == 0:
result.append(name)
# it is OK to modify task_names because we break out
# of loop below
task_names.remove(name)
new_successors = [t for t in graph.successors(name)
if t not in task_set]
task_names.extend(new_successors)
task_names.sort()
task_set.update(set(new_successors))
graph.remove_node(name)
break
return result