本文整理汇总了Python中Graph.getDistance方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.getDistance方法的具体用法?Python Graph.getDistance怎么用?Python Graph.getDistance使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Graph
的用法示例。
在下文中一共展示了Graph.getDistance方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: labelNodes
# 需要导入模块: import Graph [as 别名]
# 或者: from Graph import getDistance [as 别名]
def labelNodes(dRails, dAllLabels, optLabelDistance):
dLabels = dict()
for curNode in dRails.iterkeys():
dPossibleLabels = dict( [ (Graph.getDistance(curNode,x), y[0]) for x, y in dAllLabels.iteritems() ] )
if not dPossibleLabels: continue
minDist = min( dPossibleLabels.iterkeys() )
if minDist > optLabelDistance: continue
dLabels[curNode] = dPossibleLabels[minDist]
return dLabels
示例2: generateDot
# 需要导入模块: import Graph [as 别名]
# 或者: from Graph import getDistance [as 别名]
def generateDot( dGraph, sEndings, sClusterNodes, dLabels, bSwitchAsEndpoint = False, bLabelEdges = False, dWeighEdges = False ):
dAttrIntersection = { "shape":"point", "style":"filled", "fillcolor":"black", "label":"\"\"", "height":0.1, "width":0.1 }
dAttrStation = { "shape":"doublecircle", "style":"filled", "fillcolor":"\"#7BF4FF\"", "label":"\"STATION\\n{0},{1},{2}\"" }
dAttrSwitch = { "shape" : "doublecircle", "style" : "filled", "fillcolor":"\"#FFB879\"", "label":"\"\"", "height":0.2, "width":0.2 }
dAttrEndpoint = { "shape" : "box", "style":"filled", "fillcolor": "\"#BDFF79\"", "label":"\"{0},{1},{2}\""}
dEdge = dict()
dNode = dict()
lLines = [ "strict graph {" ]
for curNode, sAdjacent in dGraph.iteritems():
if curNode in dNode: continue
bLabelNode = False
if curNode in sClusterNodes:
# Station
if len(sAdjacent) > 2:
dNode[curNode] = dAttrStation
bLabelNode = True
# Switch
elif len(sAdjacent) == 2:
if curNode in dLabels or bSwitchAsEndpoint:
bLabelNode = True
dNode[curNode] = dAttrEndpoint
else:
dNode[curNode] = dAttrSwitch
# Madness
else:
raise RuntimeError("Non-standard clusternode, should not exist.")
else:
if len(sAdjacent) > 1:
dNode[curNode] = dAttrIntersection
elif len(sAdjacent) == 1:
dNode[curNode] = dAttrEndpoint
bLabelNode = True
else:
raise RuntimeError("Single node, should not exist.")
# Copy template
dNode[curNode] = dNode[curNode].copy()
# Label node
if curNode in dLabels and bLabelNode:
dNode[curNode]["label"] = "\"" + dLabels[curNode] + "\""
elif dNode[curNode].get("label", "\"\"") != "\"\"":
dNode[curNode]["label"] = dNode[curNode]["label"].format( *curNode )
for curAdjacent in sAdjacent:
tEdge = (curAdjacent, curNode)
if tEdge in dEdge: continue
dEdge[ (curNode, curAdjacent) ] = dict()
if bLabelEdges: dEdge[ (curNode, curAdjacent) ]["label"] = "\"{0}\"".format( int(Graph.getDistance(curNode, curAdjacent) ) )
edgeLenMax = max([ Graph.getDistance(x,y) for (x,y) in dEdge.iterkeys() ])
for curNode, dAttributes in dNode.iteritems():
if dAttributes:
lLines.append( "\"" + str(curNode) + "\" [" + ",".join( [ x + "=" + str(y) for x,y in dAttributes.items() ] ) + "];" )
else:
lLines.append( "\"" + str(curNode) + "\";" )
for (edgeStart, edgeEnd), dAttributes in dEdge.iteritems():
if dAttributes:
if dWeighEdges: dAttributes["penwidth"] = ( Graph.getDistance(edgeStart, edgeEnd) / edgeLenMax ) * dWeighEdges + 1.0
lLines.append( "\"" + str(edgeStart) + "\" -- \"" + str(edgeEnd) + "\" [" + ",".join( [ x + "=" + str(y) for x,y in dAttributes.items() ] ) + "];" )
else:
lLines.append( "\"" + str(edgeStart) + "\" -- \"" + str(edgeEnd) + "\";" )
lLines.append( "}" )
return "\n".join(lLines)
示例3: main
# 需要导入模块: import Graph [as 别名]
# 或者: from Graph import getDistance [as 别名]
def main():
global args
argParser = argparse.ArgumentParser( add_help=True,
epilog="Don't have any expections on this piece of software. It's an ugly mess of a hack mainly for personal use.",
usage="%(prog)s [options] regionFile [regionFile ...]")
curGroup = argParser.add_argument_group("cache")
curGroup.add_argument("--cache", dest="strCache", type=str, metavar="<str>", default=False, help="Path to cache, unique to the region-files specified")
curGroup.add_argument("--only-cache", dest="bOnlyCache", action="store_true", default=False, help="Don't read region-files, use only the cache")
curGroup = argParser.add_argument_group("generic")
curGroup.add_argument("--distance-label", dest="distanceLabel", type=float, metavar="<float>", default=False, help="Distance to look for a sign labeling a node")
curGroup.add_argument("--component-rail", dest="componentRail", type=int, metavar="<int>", default=30, help="Disregard components comprised of too little rail (default: 30)")
curGroup = argParser.add_argument_group("second pass")
curGroup.add_argument("--distance-cluster", dest="distanceCluster", type=float, metavar="<float>", default=False, help="Distance used for clustering nodes")
curGroup = argParser.add_argument_group("dividing components")
curGroup.add_argument("--component-divide", dest="bComponentDivide", action="store_true", default=False, help="Divide graph into connected components <required>")
curGroup.add_argument("--combine-pairs", dest="bCombinePairs", action="store_true", default=False, help="Combine all pairs of nodes into one graph")
curGroup.add_argument("--distance-min", dest="distanceMin", type=float, metavar="<float>", default=False, help="Disregard components where the longest distance between end-nodes are too short")
curGroup = argParser.add_argument_group("drawing")
curGroup.add_argument("--switch-as-endpoint", dest="bSwitchAsEndpoint", action="store_true", default=False, help="Draw switches as endpoints")
curGroup.add_argument("--label-edges", dest="bLabelEdges", action="store_true", default=False, help="Label edges according to geometric distance")
curGroup.add_argument("--edge-weight", dest="edgeWeight", type=float, metavar="<float>", default=False, help="Draw geometrically longer edges as thicker")
curGroup = argParser.add_argument_group("regions")
curGroup.add_argument("regionFile", type=str, nargs="+", help="Region files (.mca) that the graph should be generated from")
args = argParser.parse_args()
dLabels = dict()
sClusterNodes = set()
print "Fetching rail data..."
timeStart = time.time()
dRails, dAllLabels = dict(), dict()
lenRegionsLeft = len(args.regionFile)
with ProcessPoolExecutor() as executor:
for dRegionRails, dRegionLabels in executor.map( railLoaderHelper, args.regionFile ):
lenRegionsLeft -= 1
print "\r\tReading regions: {0:>6}".format(lenRegionsLeft),
sys.stdout.flush()
for x, y in dRegionRails.items() : dRails[x] = y
for x, y in dRegionLabels.items() : dAllLabels[x] = y
print ""
# Prune non-existant edges and add edge back if it doesn't exist, for example in intersections
# This will create some illegal intersections if they exist in the map. Tough luck.
print "\tAdding bidirectionality..."
for curPos, sEdges in dRails.iteritems():
sEdges = set([x for x in sEdges if x in dRails])
for edge in sEdges: dRails[edge].add(curPos)
dRails[curPos] = sEdges
timePerRegion = (time.time() - timeStart) / len(args.regionFile)
print "\tSeconds per region: {0:.2}s".format(timePerRegion)
print "\tNodes = {0}, Labels = {1}".format( len(dRails), len(dAllLabels) )
print "Generating first pass rudimentary graph..."
print "\tRemoving nodes not used in any shortest path and small components..."
Graph.filterPathsAndComponents(dRails, set([x for x in dRails if len(dRails[x]) == 1]), args.componentRail)
print "\tMerging nodes with only two edges..."
Graph.minimizeNodes(dRails)
print "\tNodes = {0}".format( len(dRails) )
if args.distanceCluster:
print "Generating second pass graph based on distance..."
print "\tClustering neighbouring nodes..."
sClusterNodes = Graph.distanceClusterNodes(dRails, args.distanceCluster)
print "\tRemoving nodes not used in any shortest path..."
Graph.filterPathsAndComponents( dRails, sClusterNodes.union( [x for x in dRails if len(dRails[x]) == 1] ), None )
sClusterNodes = set( [x for x in sClusterNodes if len(dRails[x]) > 1 ] )
print "\tMerging nodes with only two edges..."
Graph.minimizeNodes(dRails, sClusterNodes)
print "\tNodes = {0}".format( len(dRails) )
if args.distanceLabel: dLabels = labelNodes(dRails, dAllLabels, args.distanceLabel)
if args.bComponentDivide:
lGraphs = Graph.componentDivide(dRails, sClusterNodes)
else:
lGraphs = [(dRails, None, sClusterNodes)]
if args.distanceMin:
if not args.bComponentDivide:
print "warning: min distance filter need components to be divided"
else:
print "Removing components with distance < {0}".format(args.distanceMin)
lGraphDistances = []
for (curGraph, curEndings, sClusterNodes) in lGraphs:
maxDistance = 0
for curEnding in curEndings:
lDistances = [ Graph.getDistance(curEnding, x) for x in curEndings ]
curMax = max(lDistances)
if curMax > maxDistance: maxDistance = curMax
lGraphDistances.append(maxDistance)
#.........这里部分代码省略.........
示例4: generateGML
# 需要导入模块: import Graph [as 别名]
# 或者: from Graph import getDistance [as 别名]
def generateGML( dGraph, sEndings, sClusterNodes, dLabels, bSwitchAsEndpoint = False, bLabelEdges = False, dWeighEdges = False ):
dAttrIntersection = { "shape":"ellipse", "style":"filled", "fillcolor":"#000000", "label":"", "height":14, "width":14 }
dAttrStation = { "shape":"ellipse", "style":"filled", "fillcolor":"#7BF4FF", "label":"STATION\\n{0},{1},{2}" }
dAttrSwitch = { "shape" : "ellipse", "style" : "filled", "fillcolor":"#FFB879", "label":"", "height":16, "width":16 }
dAttrEndpoint = { "shape" : "rectangle", "style":"filled", "fillcolor": "#BDFF79", "label":"{0},{1},{2}"}
dEdge = dict()
dNode = dict()
lLines = []
lLines.append(r'<?xml version="1.0" encoding="UTF-8" standalone="no"?>')
lLines.append(r'<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:y="http://www.yworks.com/xml/graphml" xmlns:yed="http://www.yworks.com/xml/yed/3" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd">')
lLines.append(r'<key for="edge" id="d9" yfiles.type="edgegraphics"/>')
lLines.append(r'<key for="node" id="d6" yfiles.type="nodegraphics"/>')
lLines.append(r'<graph edgedefault="undirected" id="G">')
for curNode, sAdjacent in dGraph.iteritems():
if curNode in dNode: continue
bLabelNode = False
if curNode in sClusterNodes:
# Station
if len(sAdjacent) > 2:
dNode[curNode] = dAttrStation
bLabelNode = True
# Switch
elif len(sAdjacent) == 2:
if curNode in dLabels or bSwitchAsEndpoint:
bLabelNode = True
dNode[curNode] = dAttrEndpoint
else:
dNode[curNode] = dAttrSwitch
# Madness
else:
raise RuntimeError("Non-standard clusternode, should not exist.")
else:
if len(sAdjacent) > 1:
dNode[curNode] = dAttrIntersection
elif len(sAdjacent) == 1:
dNode[curNode] = dAttrEndpoint
bLabelNode = True
else:
raise RuntimeError("Single node, should not exist.")
# Copy template
dNode[curNode] = dNode[curNode].copy()
# Label node
if curNode in dLabels and bLabelNode:
dNode[curNode]["label"] = dLabels[curNode]
elif dNode[curNode].get("label", ""):
dNode[curNode]["label"] = dNode[curNode]["label"].format( *curNode )
for curAdjacent in sAdjacent:
tEdge = (curAdjacent, curNode)
if tEdge in dEdge: continue
dEdge[ (curNode, curAdjacent) ] = dict()
if bLabelEdges: dEdge[ (curNode, curAdjacent) ]["label"] = "{0}".format( int(Graph.getDistance(curNode, curAdjacent) ) )
edgeLenMax = max([ Graph.getDistance(x,y) for (x,y) in dEdge.iterkeys() ])
for curNode, dAttributes in dNode.iteritems():
lLines.append(r'<node id="{0}">'.format(curNode))
if dAttributes:
lLines.append(r'<data key="d6">'.format(curNode))
lLines.append(r'<y:ShapeNode>'.format(curNode))
if "width" in dAttributes and "height" in dAttributes: lLines.append(r'<y:Geometry height="{0}" width="{1}" />'.format( dAttributes["height"], dAttributes["width"] ) )
if "fillcolor" in dAttributes: lLines.append(r'<y:Fill color="{0}" />'.format(dAttributes["fillcolor"]) )
if "label" in dAttributes: lLines.append(r'<y:NodeLabel>{0}</y:NodeLabel>'.format(xml.sax.saxutils.escape(dAttributes["label"].replace("\\n", "\n")) ) )
if "shape" in dAttributes: lLines.append(r'<y:Shape type="{0}"/>'.format(dAttributes["shape"]) )
lLines.append(r'</y:ShapeNode>')
lLines.append(r'</data>')
lLines.append(r'</node>')
for (edgeStart, edgeEnd), dAttributes in dEdge.iteritems():
lLines.append( r'<edge id="{0}" source="{1}" target="{2}">'.format( (edgeStart, edgeEnd), edgeStart, edgeEnd ) )
lLines.append( r'<data key="d9"><y:PolyLineEdge><y:Arrows source="none" target="none"/></y:PolyLineEdge></data>' )
lLines.append( r'</edge>' )
lLines.append(r'</graph>')
lLines.append(r'</graphml>')
return "\n".join(lLines)