本文整理汇总了Python中networkx.DiGraph.out_degree方法的典型用法代码示例。如果您正苦于以下问题:Python DiGraph.out_degree方法的具体用法?Python DiGraph.out_degree怎么用?Python DiGraph.out_degree使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx.DiGraph
的用法示例。
在下文中一共展示了DiGraph.out_degree方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: contract_chains
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import out_degree [as 别名]
def contract_chains(g:nx.DiGraph, blockname='block'):
'''Contract chains with indegree=outdegree=1:
i.e. turns > - - - <
into [>---<]
The label of the chain is the label of its first element.
g.node[n][blockname] will hold list of dictionaries.
'''
from itertools import chain
starts = set(chain((n for n in g if g.in_degree(n) != 1),
chain.from_iterable(g.successors_iter(n) for n in g
if g.out_degree(n) > 1)))
blocks = nx.DiGraph()
for label in starts:
n = label
block = []
while True:
block.append(g.node[n])
if g.out_degree(n) != 1:
break
next_n = next(g.successors_iter(n))
if g.in_degree(next_n) != 1:
break
n = next_n
if label not in blocks:
blocks.add_node(label)
blocks.add_edges_from((label, suc) for suc in g.successors_iter(n))
blocks.node[label][blockname] = block
return blocks
示例2: filter_edges
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import out_degree [as 别名]
def filter_edges(self,thresh):
edges=DiGraph.edges(self,data='weight')
for edge in edges:
if edge[2]<thresh:
DiGraph.remove_edge(self,edge[0],edge[1])
if DiGraph.in_degree(self,edge[0])==0 and DiGraph.out_degree(self,edge[0])==0:
DiGraph.remove_node(self,edge[0])
if DiGraph.in_degree(self,edge[1])==0 and DiGraph.out_degree(self,edge[1])==0:
DiGraph.remove_node(self,edge[1])
示例3: splitG
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import out_degree [as 别名]
def splitG(self,minN):
contcmp=[]
ct_cliq=[]
cncp=list(strongly_connected_components(self))
for item in cncp:
#print(len(item))
if len(item)<=minN and len(item)>1:
#print("topic")
tmp=set()
tmp_cliq=[]
for each in item:
tmp=tmp.union(set(self.node[each]["keywords"]))
tmp_cliq.append(each)
DiGraph.remove_node(self,each)
contcmp.append(tmp)
ct_cliq.append(tmp_cliq)
if len(item)==1:
DiGraph.remove_node(self,list(item)[0])
nodes=DiGraph.nodes(self)
for node in nodes:
if DiGraph.in_degree(self,node)==0 and DiGraph.out_degree(self,node)==0:
DiGraph.remove_node(self,node)
return contcmp,ct_cliq
示例4: filter_nodes
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import out_degree [as 别名]
def filter_nodes(self,thresh):
nodes=DiGraph.nodes(self)
for node in nodes:
if DiGraph.in_degree(self,node)<thresh:
DiGraph.remove_node(self,node)
nodes=DiGraph.nodes(self)
for node in nodes:
if DiGraph.in_degree(self,node)==0 and DiGraph.out_degree(self,node)==0:
DiGraph.remove_node(self,node)
示例5: maximal_non_branching_paths
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import out_degree [as 别名]
def maximal_non_branching_paths(graph: nx.DiGraph) -> list:
paths = []
for node in graph:
if not is_in_1_out_1(graph, node) and graph.out_degree(node) > 0:
for v, w in graph.edges(node):
non_branching_path = [v, w]
while is_in_1_out_1(graph, w):
u = graph.edges(w)[0][1]
non_branching_path.append(u)
w = u
paths.append(non_branching_path)
return paths + isolated_cycles(graph)
示例6: TermGraph
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import out_degree [as 别名]
#.........这里部分代码省略.........
"""
Return a topologically-sorted iterator over the terms in ``self`` which
need to be computed.
"""
return iter(topological_sort(
self.graph.subgraph(
{term for term, refcount in refcounts.items() if refcount > 0},
),
))
def ordered(self):
return iter(topological_sort(self.graph))
@lazyval
def loadable_terms(self):
return tuple(
term for term in self.graph if isinstance(term, LoadableTerm)
)
@lazyval
def jpeg(self):
return display_graph(self, 'jpeg')
@lazyval
def png(self):
return display_graph(self, 'png')
@lazyval
def svg(self):
return display_graph(self, 'svg')
def _repr_png_(self):
return self.png.data
def initial_refcounts(self, initial_terms):
"""
Calculate initial refcounts for execution of this graph.
Parameters
----------
initial_terms : iterable[Term]
An iterable of terms that were pre-computed before graph execution.
Each node starts with a refcount equal to its outdegree, and output
nodes get one extra reference to ensure that they're still in the graph
at the end of execution.
"""
refcounts = self.graph.out_degree()
for t in self.outputs.values():
refcounts[t] += 1
for t in initial_terms:
self._decref_depencies_recursive(t, refcounts, set())
return refcounts
def _decref_depencies_recursive(self, term, refcounts, garbage):
"""
Decrement terms recursively.
Notes
-----
This should only be used to build the initial workspace, after that we
should use:
:meth:`~zipline.pipeline.graph.TermGraph.decref_dependencies`
"""
# Edges are tuple of (from, to).
for parent, _ in self.graph.in_edges([term]):
refcounts[parent] -= 1
# No one else depends on this term. Remove it from the
# workspace to conserve memory.
if refcounts[parent] == 0:
garbage.add(parent)
self._decref_depencies_recursive(parent, refcounts, garbage)
def decref_dependencies(self, term, refcounts):
"""
Decrement in-edges for ``term`` after computation.
Parameters
----------
term : zipline.pipeline.Term
The term whose parents should be decref'ed.
refcounts : dict[Term -> int]
Dictionary of refcounts.
Return
------
garbage : set[Term]
Terms whose refcounts hit zero after decrefing.
"""
garbage = set()
# Edges are tuple of (from, to).
for parent, _ in self.graph.in_edges([term]):
refcounts[parent] -= 1
# No one else depends on this term. Remove it from the
# workspace to conserve memory.
if refcounts[parent] == 0:
garbage.add(parent)
return garbage
示例7: load
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import out_degree [as 别名]
#.........这里部分代码省略.........
If True, the graph is returned (False by default).
Returns:
--------
The graph is saved internally in self.graph.
"""
delimiter = kwargs["delimiter"] if "delimiter" in kwargs.keys() else " "
data = np.genfromtxt(fname, delimiter=delimiter, dtype=int, unpack=False)
source, target = data[:,0], data[:,1]
if data.shape[1] > 2:
flux = data[:,2]
else:
flux = np.ones_like(source)
nodes = set(source) | set(target)
self.nodes = len(nodes)
lines = len(flux)
if set(range(self.nodes)) != nodes:
new_node_ID = {old:new for new,old in enumerate(nodes)}
map_new_node_ID = np.vectorize(new_node_ID.__getitem__)
source = map_new_node_ID(source)
target = map_new_node_ID(target)
if verbose:
print "\nThe node IDs have to run continuously from 0 to Number_of_nodes-1."
print "Node IDs have been changed according to the requirement.\n-----------------------------------\n"
print 'Lines: ',lines , ', Nodes: ', self.nodes
print '-----------------------------------\nData Structure:\n\nsource, target, weight \n'
for ii in range(7):
print "%i, %i, %1.2e" %(source[ii], target[ii], flux[ii])
print '-----------------------------------\n'
G = DiGraph() # Empty, directed Graph
G.add_nodes_from(range(self.nodes))
for ii in xrange(lines):
u, v, w = int(source[ii]), int(target[ii]), float(flux[ii])
if u != v: # ignore self loops
assert not G.has_edge(u,v), "Edge appeared twice - not supported"
G.add_edge(u,v,weight=w)
else:
if verbose:
print "ignore self loop at node", u
symmetric = True
for s,t,w in G.edges(data=True):
w1 = G[s][t]["weight"]
try:
w2 = G[t][s]["weight"]
except KeyError:
symmetric = False
G.add_edge(t,s,weight=w1)
w2 = w1
if w1 != w2:
symmetric = False
G[s][t]["weight"] += G[t][s]["weight"]
G[s][t]["weight"] /= 2
G[t][s]["weight"] = G[s][t]["weight"]
if verbose:
if not symmetric:
print "The network has been symmetricised."
ccs = strongly_connected_component_subgraphs(G)
ccs = sorted(ccs, key=len, reverse=True)
G_GSCC = ccs[0]
if G_GSCC.number_of_nodes() != G.number_of_nodes():
G = G_GSCC
if verbose:
print "\n--------------------------------------------------------------------------"
print "The network has been restricted to the giant strongly connected component."
self.nodes = G.number_of_nodes()
for u, v, data in G.edges(data=True):
weight = G.out_degree(u,weight='weight')
data['transition_rate'] = 1.*data['weight']/weight
for u, v, data in G.edges(data=True):
data['effective_distance'] = 1. - log(data['transition_rate'])
if verbose:
print "\n--------------------------------------------------------------------------"
print "\nnode ID, out-weight, normalized out-weight, sum of effective distances \n "
for ii in range(7):
out_edges = G.out_edges(ii, data=True)
out_weight, effective_distance, transition_rate = 0, 0, 0
for u, v, data in out_edges:
out_weight += data["weight"]
effective_distance += data["effective_distance"]
transition_rate += data["transition_rate"]
print " %i %1.2e %2.3f %1.2e " %(ii,out_weight, transition_rate, effective_distance)
print "\n ... graph is saved in self.graph"
return G
示例8: is_in_1_out_1
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import out_degree [as 别名]
def is_in_1_out_1(graph: nx.DiGraph, node: object) -> bool:
in_degree = graph.in_degree(node)
out_degree = graph.out_degree(node)
return in_degree == 1 and out_degree == 1
示例9: in_out_balance
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import out_degree [as 别名]
def in_out_balance(graph: nx.DiGraph, node: object):
return graph.in_degree(node) - graph.out_degree(node)
示例10: GraphManager
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import out_degree [as 别名]
class GraphManager(object):
""" Generates and processes the graph based on packets
"""
def __init__(self, packets, layer=3, geo_ip=os.path.expanduser('~/GeoIP.dat')):
self.graph = DiGraph()
self.layer = layer
self.geo_ip = None
self.data = {}
try:
self.geo_ip = GeoIP(geo_ip)
except:
logging.warning("could not load GeoIP data")
if self.layer == 2:
edges = map(self._layer_2_edge, packets)
elif self.layer == 3:
edges = map(self._layer_3_edge, packets)
elif self.layer == 4:
edges = map(self._layer_4_edge, packets)
else:
raise ValueError("Other layers than 2,3 and 4 are not supported yet!")
for src, dst, packet in filter(lambda x: not (x is None), edges):
if src in self.graph and dst in self.graph[src]:
self.graph[src][dst]['packets'].append(packet)
else:
self.graph.add_edge(src, dst, {'packets': [packet]})
for node in self.graph.nodes():
self._retrieve_node_info(node)
for src, dst in self.graph.edges():
self._retrieve_edge_info(src, dst)
def get_in_degree(self, print_stdout=True):
unsorted_degrees = self.graph.in_degree()
return self._sorted_results(unsorted_degrees, print_stdout)
def get_out_degree(self, print_stdout=True):
unsorted_degrees = self.graph.out_degree()
return self._sorted_results(unsorted_degrees, print_stdout)
@staticmethod
def _sorted_results(unsorted_degrees, print_stdout):
sorted_degrees = OrderedDict(sorted(unsorted_degrees.items(), key=lambda t: t[1], reverse=True))
for i in sorted_degrees:
if print_stdout:
print(sorted_degrees[i], i)
return sorted_degrees
def _retrieve_node_info(self, node):
self.data[node] = {}
if self.layer >= 3 and self.geo_ip:
if self.layer == 3:
self.data[node]['ip'] = node
elif self.layer == 4:
self.data[node]['ip'] = node.split(':')[0]
node_ip = self.data[node]['ip']
country = self.geo_ip.country_name_by_addr(node_ip)
self.data[node]['country'] = country if country else 'private'
#TODO layer 2 info?
def _retrieve_edge_info(self, src, dst):
edge = self.graph[src][dst]
if edge:
packets = edge['packets']
edge['layers'] = set(list(itertools.chain(*[set(GraphManager.get_layers(p)) for p in packets])))
edge['transmitted'] = sum(len(p) for p in packets)
edge['connections'] = len(packets)
@staticmethod
def get_layers(packet):
return list(GraphManager.expand(packet))
@staticmethod
def expand(x):
yield x.name
while x.payload:
x = x.payload
yield x.name
@staticmethod
def _layer_2_edge(packet):
return packet[0].src, packet[0].dst, packet
@staticmethod
def _layer_3_edge(packet):
if packet.haslayer(IP):
return packet[1].src, packet[1].dst, packet
@staticmethod
def _layer_4_edge(packet):
if any(map(lambda p: packet.haslayer(p), [TCP, UDP])):
src = packet[1].src
dst = packet[1].dst
_ = packet[2]
return "%s:%i" % (src, _.sport), "%s:%i" % (dst, _.dport), packet
#.........这里部分代码省略.........