本文整理汇总了Python中networkx.Graph.remove_node方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.remove_node方法的具体用法?Python Graph.remove_node怎么用?Python Graph.remove_node使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx.Graph
的用法示例。
在下文中一共展示了Graph.remove_node方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: polygon_skeleton
# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import remove_node [as 别名]
def polygon_skeleton(polygon, density=10):
""" Given a buffer polygon, return a skeleton graph.
"""
skeleton = Graph()
points = []
for ring in polygon_rings(polygon):
points.extend(densify_line(list(ring.coords), density))
if len(points) <= 4:
# don't bother with this one
return skeleton
print >> stderr, ' ', len(points), 'perimeter points',
rbox = '\n'.join( ['2', str(len(points))] + ['%.2f %.2f' % (x, y) for (x, y) in points] + [''] )
qvoronoi = Popen('qvoronoi o'.split(), stdin=PIPE, stdout=PIPE)
output, error = qvoronoi.communicate(rbox)
voronoi_lines = output.splitlines()
if qvoronoi.returncode:
raise _QHullFailure('Failed with code %s' % qvoronoi.returncode)
vert_count, poly_count = map(int, voronoi_lines[1].split()[:2])
for (index, line) in enumerate(voronoi_lines[2:2+vert_count]):
point = Point(*map(float, line.split()[:2]))
if point.within(polygon):
skeleton.add_node(index, dict(point=point))
for line in voronoi_lines[2+vert_count:2+vert_count+poly_count]:
indexes = map(int, line.split()[1:])
for (v, w) in zip(indexes, indexes[1:] + indexes[:1]):
if v not in skeleton.node or w not in skeleton.node:
continue
v1, v2 = skeleton.node[v]['point'], skeleton.node[w]['point']
line = LineString([(v1.x, v1.y), (v2.x, v2.y)])
if line.within(polygon):
skeleton.add_edge(v, w, dict(line=line, length=line.length))
removing = True
while removing:
removing = False
for index in skeleton.nodes():
if skeleton.degree(index) == 1:
depth = skeleton.node[index].get('depth', 0)
if depth < 20:
other = skeleton.neighbors(index)[0]
skeleton.node[other]['depth'] = depth + skeleton.edge[index][other]['line'].length
skeleton.remove_node(index)
removing = True
print >> stderr, 'contain', len(skeleton.edge), 'internal edges.'
return skeleton
示例2: remove_node
# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import remove_node [as 别名]
def remove_node(self, node):
""" Remove node from network. """
if node not in self.nodes():
logger.error("Node not in network")
return
Graph.remove_node(self, node)
del self.pos[node]
del self.labels[node]
node.network = None
logger.debug('Node with id %d is removed.' % node.id)
示例3: polygon_dots_skeleton
# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import remove_node [as 别名]
def polygon_dots_skeleton(polygon, points):
'''
'''
skeleton = Graph()
rbox = '\n'.join( ['2', str(len(points))] + ['%.2f %.2f' % (x, y) for (x, y) in points] + [''] )
qvoronoi = Popen('qvoronoi o'.split(), stdin=PIPE, stdout=PIPE)
output, error = qvoronoi.communicate(rbox)
voronoi_lines = output.splitlines()
if qvoronoi.returncode:
raise _QHullFailure('Failed with code %s' % qvoronoi.returncode)
vert_count, poly_count = map(int, voronoi_lines[1].split()[:2])
for (index, line) in enumerate(voronoi_lines[2:2+vert_count]):
point = Point(*map(float, line.split()[:2]))
if point.within(polygon):
skeleton.add_node(index, dict(point=point))
for line in voronoi_lines[2+vert_count:2+vert_count+poly_count]:
indexes = map(int, line.split()[1:])
for (v, w) in zip(indexes, indexes[1:] + indexes[:1]):
if v not in skeleton.node or w not in skeleton.node:
continue
v1, v2 = skeleton.node[v]['point'], skeleton.node[w]['point']
line = LineString([(v1.x, v1.y), (v2.x, v2.y)])
if line.within(polygon):
skeleton.add_edge(v, w, dict(line=line, length=line.length))
removing = True
while removing:
removing = False
for index in skeleton.nodes():
if skeleton.degree(index) == 1:
depth = skeleton.node[index].get('depth', 0)
if depth < 20:
other = skeleton.neighbors(index)[0]
skeleton.node[other]['depth'] = depth + skeleton.edge[index][other]['line'].length
skeleton.remove_node(index)
removing = True
logging.debug('found %d skeleton edges' % len(skeleton.edge))
return skeleton
示例4: solve
# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import remove_node [as 别名]
def solve():
from networkx import Graph, number_connected_components
from heap.heap import heap
def up(p):
r, c = divmod(p,C)
return (R-1 if r==0 else r-1)*C + c
def down(p):
r, c = divmod(p,C)
return (0 if r==R-1 else r+1)*C + c
def left(p):
r, c = divmod(p,C)
return r*C + (C-1 if c==0 else c-1)
def right(p):
r, c = divmod(p,C)
return r*C + (0 if c==C-1 else c+1)
def link(a,b):
G.add_edge(('start',a),('end',b))
H[b] += 1
R, C = map(int,input().split())
N = R*C
G = Graph()
H = heap({n:0 for n in range(N)})
for p in range(N):
G.add_node(('start',p))
G.add_node(('end',p))
for p, x in enumerate(x for _ in range(R) for x in input().strip()):
if x == '|':
link(p,up(p))
link(p,down(p))
elif x == '-':
link(p,left(p))
link(p,right(p))
elif x == '/':
link(p,down(left(p)))
link(p,up(right(p)))
elif x == '\\':
link(p,up(left(p)))
link(p,down(right(p)))
while H[H.peek()] <= 1:
p, ins = H.popitem()
if ins == 0:
# There is a sqaure such that no other square points to it.
# It's impossible for a lemming to get here.
# So there are no proper ways to arrange this.
return 0
else:
# There is exactly one edge leading into p.
# Remove the relevant nodes.
_, q = next(iter(G['end',p]))
r = next(r for _, r in G['start',q] if r != p)
G.remove_node(('end',p))
G.remove_node(('start',q))
# If q now points to p, the other square that q points to
# has one fewer square pointing to it.
H[r] -= 1
# Now all remaining nodes are cycles, and there are exatly two ways
# to choose the directions for each cycle.
return pow(2,number_connected_components(G),1000003)
示例5: remove_node
# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import remove_node [as 别名]
def remove_node(self,n):
Graph.remove_node(self,n)
self.fh.write("Remove node: %s\n"%n)
示例6: Network
# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import remove_node [as 别名]
#.........这里部分代码省略.........
def show_surface(self):
""" Shows the surface for the selected network nodes """
if self.rendermanager is None:
raise Exception('No RenderManager. You have to first activate the network and render it.')
self.rendermanager._show_surface()
def load_pickled_graphml(self, graph):
""" Loads a pickled GraphML file
Parameters
----------
graph : NetworkX Graph instance
A graph instance
"""
# setting the graph
self.graph = graph
if self.graph.has_node('n0'):
if self.graph.node['n0'].has_key('nodekeys'):
# extracting the node keys from the first node
self.nodekeys = self.graph.node['n0']['nodekeys']
# extracting the edge keys from the first edge (without explanation)
if self.graph.node['n0'].has_key('edgekeys'):
self.edgekeys = self.graph.node['n0']['edgekeys']
if self.graph.node['n0'].has_key('graphid'):
self.networkid = self.graph.node['n0']['graphid']
# remove node
self.graph.remove_node('n0')
def _return_default_edgevalue(self, edgekeys, key):
""" Looks up if there is a default value defined, otherwise
return zero """
if edgekeys[key].has_key('default'):
return float(edgekeys[key]['default'])
else:
return 0.0
def parse_network_graphml(self, path):
""" Read network in GraphML format from a path.
Parameters
----------
path : string
path the the GraphML file
Returns
-------
graph : NetworkX `Graph`
"""
import networkx as nx
from networkx.utils import _get_fh
from lxml import etree
# Return a file handle for given path.
# Path can be a string or a file handle.
# Attempt to uncompress/compress files ending in .gz and .bz2.
fh=_get_fh(path,mode='r')
示例7: print
# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import remove_node [as 别名]
utm_zone_number = pos[2]
graph.add_node(item.id, lat=item.lat, lon=item.lon, pos=pos[:2])
#nodes += 1
items += 1
print('{0} items processed'.format(items), end='\r')
print('{0} items processed'.format(items))
if shape_file:
n = graph.number_of_nodes()
i = 0
print('Apply shapefile')
for node in graph.nodes():
p = Point(graph.node[node]['lon'], graph.node[node]['lat'])
if not shape_file.contains(p):
graph.remove_node(node)
i += 1
print('{0}/{1} nodes processed'.format(i, n), end='\r')
print('{0}/{1} nodes processed'.format(i, n))
print('Search for orphaned nodes')
orphaned = set()
n = graph.number_of_nodes()
i = 0
for node in graph.nodes_iter():
if graph.degree(node) == 0:
orphaned.add(node)
i += 1
print('{0}/{1} nodes processed'.format(i, n), end='\r')
print('{0}/{1} nodes processed'.format(i, n))
示例8: LangGraph
# 需要导入模块: from networkx import Graph [as 别名]
# 或者: from networkx.Graph import remove_node [as 别名]
#.........这里部分代码省略.........
Returns the words in narrative order
"""
return [t.word for t in self.tokens()]
def tokens(self):
"""
Returns the tokens in narrative order
"""
return [i.token for i in self.temporal]
def labels(self):
"""
Returns the sequence of labels for the instances
"""
return [i.event.type for i in self.temporal]
def removeAny(self, blackList):
"""
Removes any nodes/tokens/instances that match the words in the blacklist
"""
#if a token or its lemma match any of the words in the blacklist
#mark it for removal
toRemove = {inst.token for inst in self.temporal
if inst.token.word.lower() in blackList
or inst.token.lemma.lower() in blackList}
self.removeNodes(toRemove)
def removeNodes(self, tokens):
"""
Removes the token from the graph
"""
startLen = len(self)
#mark all the instances/indexes to remove
instances = {inst:i for inst,i in self.temporalMap.items()
if inst.token in tokens}
#determine the remaining nodes
remaining = sorted(list(set(range(startLen)) - {i for i in instances.values()}))
#add in all the bypasses
for startIndex, endIndex in iterPairs(remaining):
start = self.temporal[startIndex]
end = self.temporal[endIndex]
self.addEdge(start, end, WORD_EDGE)
#remove the edges
for inst in instances:
self.graph.remove_node(inst)
#if there are remaining nodes then reset the temporal mapping
if remaining:
startIndex = min(remaining)
self.start = self.temporal[startIndex]
#redo narrative order
self.temporal = self.narrativeOrder()
self.temporalMap = self.narrativeMapping()
else:
self.start = None
self.temporal = []
self.temporalMap = {}
def copy(self):
"""
Performs a shallow copy of the graph
"""
newGraph = LangGraph(self.isDirected, self.entEdges)
#create new instances
newInst = {i:me.Instance(copy(i.token), i.event) for i in self.temporal}
#add in all the edges
for start, end in self.graph.edges():
for eType in self.edgeTypes(start, end):
newGraph.addEdge(newInst[start], newInst[end], eType)
newGraph.setStart(newInst[self.start])
return newGraph
def graphString(self):
"""
Returns the graph as a string
"""
return " ".join([t.word for t in self.tokens()])
def __len__(self):
"""
Returns the number of nodes (tokens) in the graph
"""
return len(self.graph)
def __repr__(self):
"""
Returns a summary string of the graph
"""
return "LangGraph {} nodes, {} edges".format(len(self.graph.nodes()), len(self.graph.edges()))