本文整理汇总了Python中networkx.bfs_tree函数的典型用法代码示例。如果您正苦于以下问题:Python bfs_tree函数的具体用法?Python bfs_tree怎么用?Python bfs_tree使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了bfs_tree函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
def run(self, G, O, mi, sigma2):
"""
Main
:param G: graph
:param O: list of observers <<<< ACTIVE observers !
:param mi: mean
:param sigma2: variance
:return:
"""
# TODO : consider only active observers !
first_node = O[0]
# Compute the delay vector d relative to first_node
d = self.observed_delay(G, O)
# calculates F for the first node: fulfills max
max = self.main_function(first_node, O, d, nx.bfs_tree(G, source=first_node), mi, sigma2)
source = first_node # SEE HOW WE CAN DO IT
# calculates the maximum F
for s in G: # FIXME is this G_a ?
# Compute the spanning tree rooted at s
T = nx.bfs_tree(G, source=s)
F = self.main_function(s, O, d, T, mi, sigma2)
if F > max:
max = F
source = s
return source
示例2: relations
def relations(self, sty1, sty2, rela, source_vocab=[]):
"""Return set of relations between provided semantic types"""
# collect descendant/child types for each semantic type
network = self.semantic_network.graph("isa")
sty1 = [node for node in nx.bfs_tree(network, sty1)]
sty2 = [node for node in nx.bfs_tree(network, sty2)]
sty1 = " OR ".join(map(lambda x:"STY='%s'" % x, sty1))
sty2 = " OR ".join(map(lambda x:"STY='%s'" % x, sty2))
# override object default source vocabulary?
if source_vocab:
sab = self._source_vocab_sql(source_vocab)
else:
sab = self._source_vocab_sql(self.source_vocab)
sab = "" if not sab else sab + " AND"
sql = """
SELECT DISTINCT CUI2,CUI1 FROM
(SELECT * FROM MRREL WHERE RELA='%s') AS R,
(SELECT L.CUI FROM MRCONSO AS L, MRSTY AS LS WHERE (%s) AND L.CUI=LS.CUI) AS LARG,
(SELECT R.CUI FROM MRCONSO AS R, MRSTY AS RS WHERE (%s) AND R.CUI=RS.CUI) AS RARG
WHERE %s ((LARG.CUI=CUI2) AND (RARG.CUI=CUI1));"""
sql = sql % (rela,sty1,sty2,sab)
results = self.conn.query(sql)
return results
示例3: family_tree
def family_tree(digraph, target):
"""
Subsets graph to return predecessors and successors with a blood relation
to the target node
"""
all_successors = nx.bfs_tree(digraph, target, reverse=False)
all_predecessors = nx.bfs_tree(digraph, target, reverse=True)
subdig = digraph.subgraph(itertools.chain(
[target], all_successors, all_predecessors)).copy()
return subdig
示例4: Algorithm
def Algorithm(self, G, O, mi, sigma2):
d = self.observed_delay(G, O)
first_node = O[0]
# calculates F for the first node: fulfills max
MAX = self.main_function(first_node, O, d, nx.bfs_tree(G, source=first_node), mi, sigma2)
source = first_node # SEE HOW WE CAN DO IT
# calculates the maximum F
for s in G:
T = nx.bfs_tree(G, source=s)
F = self.main_function(s, d, T, mi)
if F > MAX:
MAX = F
source = s
return source
示例5: bfs_heur
def bfs_heur(graph, query_nodes, a = 1, include_solution = False):
""" Approximately maximize discrepancy on graph. """
best_root = None
best_d = -1
for root in query_nodes:
sys.stderr.write('.')
tree = nx.bfs_tree(graph, root)
d, solution_graph = tree_offline(tree, query_nodes, root, a, False)
if d > best_d:
best_d = d
best_root = root
tree = nx.bfs_tree(graph, best_root)
sys.stderr.write('\n')
return tree_offline(tree, query_nodes, best_root, a, include_solution)
示例6: objecttree_get_all_skeletons
def objecttree_get_all_skeletons(request, project_id=None, node_id=None):
""" Retrieve all skeleton ids for a given node in the object tree. """
g = get_annotation_graph( project_id )
potential_skeletons = nx.bfs_tree(g, int(node_id)).nodes()
result = tuple(nid for nid in potential_skeletons if 'skeleton' == g.node[nid]['class'])
json_return = json.dumps({'skeletons': result}, sort_keys=True, indent=4)
return HttpResponse(json_return, content_type='text/json')
示例7: get_spanning_tree
def get_spanning_tree(self, node, use_infectors = False):
''' Returns a networkx spanning tree of the adjacency matrix
rooted at node'''
G = nx.bfs_tree(self.graph, node).to_undirected()
if not nx.is_connected(G):
return None
return G
示例8: test_bfs_tree_isolates
def test_bfs_tree_isolates(self):
G = nx.Graph()
G.add_node(1)
G.add_node(2)
T = nx.bfs_tree(G, source=1)
assert_equal(sorted(T.nodes()), [1])
assert_equal(sorted(T.edges()), [])
示例9: _get_node_to_pset_same_transition_matrix
def _get_node_to_pset_same_transition_matrix(T, root, P,
node_to_allowed_states=None):
T_bfs = nx.bfs_tree(T, root)
preorder_nodes = list(nx.dfs_preorder_nodes(T, root))
sorted_states = sorted(P)
# Put the tree into sparse boolean csr form.
tree_csr_indices, tree_csr_indptr = _digraph_to_bool_csr(
T_bfs, preorder_nodes)
# Put the transition matrix into sparse boolean csr form.
trans_csr_indices, trans_csr_indptr = _digraph_to_bool_csr(
P, sorted_states)
# Define the state mask.
state_mask = _define_state_mask(
node_to_allowed_states, preorder_nodes, sorted_states)
# Update the state mask.
pyfelscore.mcy_get_node_to_pset(
tree_csr_indices,
tree_csr_indptr,
trans_csr_indices,
trans_csr_indptr,
state_mask)
# Convert the updated state mask into a node_to_pset dict.
node_to_pset = _state_mask_to_dict(
state_mask, preorder_nodes, sorted_states)
# Return the node_to_pset dict.
return node_to_pset
示例10: graph
def graph(ttl):
T = nx.bfs_tree(G,ttl)
edgeAccuracy = 0
years = []
for e in T.edges():
t1 = e[0]
t2 = e[1]
y1 = 0
y2 = 0
for d in Data:
if(d['title'] == t1):
y1 = d['year']
if(d['title'] == t2):
y2 = d['year']
#print e
#print str(y1) + " | " + str(y2)
if(y1 > y2):
edgeAccuracy += 1
if(years == []):
years.append(y1)
years.append(y2)
else:
years.append(y2)
yearsAccuracy = 0
for y in range(1,len(years)):
if( years[y] > years[y-1]):
yearsAccuracy +=1
print(T.edges())
#print years
#print "edge Accuracy = " + str(edgeAccuracy)
print ttl + " = " + str(yearsAccuracy)
示例11: get_graph_compressed
def get_graph_compressed(graph_data):
"""
Getting the Compressed Graph. A Compressed Graph is a DAG, after removing
unreachable graph nodes, and getting bfs tree.
"""
# Creating the directed graphs, for graph1.
dgraph = nx.DiGraph(graph_data)
if not dgraph.has_node(0): # adding root node, on one node case.
dgraph.add_node(0)
# First, remove non reachable nodes, from the root.
# assuming node 0 is the function root node.
bfsy = nx.bfs_tree(dgraph, 0).nodes()
if 0 not in bfsy:
bfsy.append(0)
for i in dgraph.nodes():
if i not in bfsy:
dgraph.remove_node(i)
# Second, _collapse some vertices together...
dgraph = _collapse(dgraph)
# create DAG's (computing scc) from digraph before.
compressed_graph = nx.condensation(dgraph)
return compressed_graph.edges()
示例12: all_dag_covers
def all_dag_covers(_graph, condenseg, final_sccs, tree_type):
initial_scc = _graph.node[_graph.graph["initial"]]["scc_index"]
if tree_type=="bfs":
condense_tree = networkx.bfs_tree(condenseg, initial_scc)
elif tree_type=="dfs":
condense_tree = networkx.dfs_tree(condenseg, initial_scc)
rest_edges = [edge for edge in condenseg.edges() if edge not in condense_tree.edges()]
all_tree_branch(_graph, condenseg, final_sccs, tree_type, condense_tree)
dag_paths = condenseg.graph["condense_paths"]
for rest_edge in rest_edges:
path = networkx.shortest_path(condense_tree, initial_scc, rest_edge[0])
_node = rest_edge[1]
while True:
if condense_tree.out_degree(_node)==0 and condense_tree.in_degree(_node)==1:
if "_final" in str(_node):
path.append(_node)
else:
path = path + condense_tree.node[_node]["continue_path"]
break
else:
path.append(_node)
_node = condense_tree.edge[_node].keys()[0]
dag_paths.append(path)
condenseg.graph["condense_paths"] = dag_paths
return dag_paths
示例13: keep
def keep(self, areas=['all'], sexes=['male', 'female', 'total'], start_year=-pl.inf, end_year=pl.inf):
""" Modify model to feature only desired area/sex/year(s)
:Parameters:
- `areas` : list of str, optional
- `sexes` : list of str, optional
- `start_year` : int, optional
- `end_year` : int, optional
"""
if 'all' not in areas:
self.hierarchy.remove_node('all')
for area in areas:
self.hierarchy.add_edge('all', area)
self.hierarchy = nx.bfs_tree(self.hierarchy, 'all')
def relevant_row(i):
area = self.input_data['area'][i]
return (area in self.hierarchy) or (area == 'all')
self.input_data = self.input_data.select(relevant_row)
self.nodes_to_fit = set(self.hierarchy.nodes()) & set(self.nodes_to_fit)
self.input_data = self.input_data.select(lambda i: self.input_data['sex'][i] in sexes)
self.input_data = self.input_data.select(lambda i: self.input_data['year_end'][i] >= start_year)
self.input_data = self.input_data.select(lambda i: self.input_data['year_start'][i] <= end_year)
print 'kept %d rows of data' % len(self.input_data.index)
示例14: main
def main(args):
# read and validate the rate matrix info from the sqlite3 database file
conn = sqlite3.connect(args.rates)
cursor = conn.cursor()
states, distn, Q = get_rate_matrix_info(cursor)
conn.close()
# Get a more convenient form of the rate matrix for forward simulation.
rates, P = cmedbutil.decompose_rates(Q)
# extract the unrooted tree from the tree db file
conn = sqlite3.connect(args.tree)
cursor = conn.cursor()
G = get_unrooted_tree(cursor)
conn.close()
# Pick the smallest vertex of G as an arbitrary root for sampling.
# This choice can be made arbitrarily
# because the rate matrix is currently defined to be time-reversible.
root = min(G.nodes())
# Build a directed breadth first tree starting at the distinguished vertex.
# Note that the tree built by nx.bfs_tree and the edges yielded
# by nx.bfs_edges do not retain the edge attributes.
G_dag = nx.bfs_tree(G, root)
for a, b in G_dag.edges():
G_dag[a][b]['blen'] = G[a][b]['blen']
# sample the unconditional columns of the alignment
conn = sqlite3.connect(args.outfile)
build_alignment_table(
args.length, args.only_leaves,
conn, root, G_dag, distn, states, rates, P)
conn.close()
示例15: chiral_order
def chiral_order(atoms, chiral_atom, depth=6):
# Create a list of ordered atoms to be passed back
ordered = []
# Do a quick check whether there are multiple hydrogens
neighbors = atoms.neighbors(chiral_atom)
hydrogens = [atom for atom in neighbors if atom.element == "H"]
if len(hydrogens) < 2:
tree = nx.bfs_tree(atoms, chiral_atom)
# Generate the list of shortest paths in the molecule, neglecting the trivial path [chiral_atom]
paths = sorted(nx.single_source_shortest_path(tree, chiral_atom, depth).values(), reverse = True)[:-1]
while paths:
# Pop the first element (highest priority path) from the list of paths and remove any duplicates.
path = paths.pop(0)
paths_no_dups = [unpruned for unpruned in paths if unpruned != path]
# If there are any duplicates, the paths list will be smaller and we can't resolve a highest priority yet.
if len(paths_no_dups) != len(paths):
paths = paths_no_dups
# Otherwise, the path is higher priority than all the other paths, so its second atom is the neighbour with
# highest priority.
else:
ranked_atom = path[1]
ordered.append(ranked_atom)
# Drop all the paths containing our ranked atom.
paths = [unpruned for unpruned in paths if unpruned[1] is not ranked_atom]
return ordered