本文整理汇总了Python中Graph.Graph.getVertex方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.getVertex方法的具体用法?Python Graph.getVertex怎么用?Python Graph.getVertex使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Graph.Graph
的用法示例。
在下文中一共展示了Graph.getVertex方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testGraph
# 需要导入模块: from Graph import Graph [as 别名]
# 或者: from Graph.Graph import getVertex [as 别名]
class testGraph(unittest.TestCase):
def setUp(self):
self.graph = Graph()
# @unittest.skip("jeszcze nie mamb")
def testCreateSpecyficGraphFromFile(self):
readFromFileMock = mock.Mock(return_value = """
0 1 3\n
0 4 3\n
1 2 1\n
2 3 3\n
2 5 1\n
3 1 3\n
4 5 2\n
5 3 1\n
5 1 6""") #zakladanie werifikatora
readFromFileMock("testGraf.txt") #gen
readFromFileMock.assert_called_once_with("testGraf.txt") #sciaganie werifikatora
self.graph.createGraphFromStr(readFromFileMock.return_value)
self.assertEqual(6, self.graph.getNumberOfVertex())
self.assertEqual(9, self.graph.getNumberOfEdges())
# @unittest.skip("jeszcze nie mamb")
def testAddEdge(self):
s = [1, 2, 3]
self.graph.addEdge(s)
self.assertEqual([1], self.graph.getVertex())
self.assertEqual([[2]], self.graph.getConnectFromVertex(1))
self.assertEqual([3], self.graph.getEdgeFromVToVx(1, 2))
示例2: Graph
# 需要导入模块: from Graph import Graph [as 别名]
# 或者: from Graph.Graph import getVertex [as 别名]
G1 = Graph()
G1.addVertex('a')
G1.addVertex('b')
G1.addVertex('c')
G1.addVertex('d')
G1.addVertex('e')
G1.addVertex('f')
G1.addEdge("a","b",1)
G1.addEdge("a","f",1)
G1.addEdge("f","e",1)
G1.addEdge("e","d",1)
G1.addEdge("d","c",1)
G1.addEdge("c","b",1)
print is_bipartite(G1,G1.getVertex('a'))
G2 = Graph()
G2.addVertex('a')
G2.addVertex('b')
G2.addVertex('c')
G2.addVertex('d')
G2.addVertex('e')
G2.addVertex('f')
G2.addVertex('g')
G2.addEdge("a","b",1)
G2.addEdge("a","f",1)
G2.addEdge("f","e",1)
G2.addEdge("e","d",1)
G2.addEdge("d","c",1)
开发者ID:dxmahata,项目名称:elements-of-programming-interviews-python-solutions,代码行数:33,代码来源:DetectingBipartiteGraphUsingBFS.py
示例3: print
# 需要导入模块: from Graph import Graph [as 别名]
# 或者: from Graph.Graph import getVertex [as 别名]
g.addEdge(0,5,2)
g.addEdge(1,2,4)
g.addEdge(2,3,9)
g.addEdge(3,4,7)
g.addEdge(3,5,3)
g.addEdge(4,0,1)
g.addEdge(5,4,8)
g.addEdge(5,2,1)
#print all the edges of the graph
for v in g:
for w in v.getConnections():
print("( %s , %s )" % (v.getId(), w.getId()))
#print the BFS traversal of the graph
print BFS(g, g.getVertex(0))
#print the DFS traversal of the graph
print DFS(g, g.getVertex(0))
#recursive DFS
for vertex in g:
vertex.setColor("white")
vertex.setPredecessor(None)
vertex.setDistance(sys.maxint)
vertex.setEntryTime(0)
vertex.setExitTime(0)
time = 0
dfsTraverse = []
DFSRecursive(g,g.getVertex(0),time,dfsTraverse)
开发者ID:dxmahata,项目名称:elements-of-programming-interviews-python-solutions,代码行数:33,代码来源:GraphTraversals.py
示例4: Graph
# 需要导入模块: from Graph import Graph [as 别名]
# 或者: from Graph.Graph import getVertex [as 别名]
[2, 1], [2, 3], [2, 4], [2, 10],
[3, 0], [3, 1], [3, 2], [3, 4], [3, 5],
[4, 2], [4, 3], [4, 5], [4, 7], [4, 8], [4, 10],
[5, 0], [5, 3], [5, 4], [5, 6], [5, 7],
[6, 5], [6, 7],
[7, 4], [7, 5], [7, 6], [7, 8],
[8, 4], [8, 7], [8, 9], [8, 10], [8, 11],
[9, 8], [9, 11],
[10, 2], [10, 4], [10, 8], [10, 11],
[11, 8], [11, 9], [11, 10]
]
graph1 = Graph(vertices, edges)
print("The vertices in graph1: " + str(graph1.getVertices()))
print("The number of vertices in graph1: " + str(graph1.getSize()))
print("The vertex with index 1 is " + graph1.getVertex(1))
print("The index for Miami is " + str(graph1.getIndex("Miami")))
print("The degree for Miami is " + str(graph1.getDegree("Miami")))
print("The edges for graph1:")
graph1.printEdges()
graph1.addVertex("Savannah")
graph1.addEdge("Atlanta", "Savannah")
graph1.addEdge("Savannah", "Atlanta")
print("\nThe edges for graph1 after adding a new vertex and edges:")
graph1.printEdges()
# List of Edge objects for graph in Figure 16.3(a)
names = ["Peter", "Jane", "Mark", "Cindy", "Wendy"]
edges = [[0, 2], [1, 2], [2, 4], [3, 4]]
示例5: print
# 需要导入模块: from Graph import Graph [as 别名]
# 或者: from Graph.Graph import getVertex [as 别名]
print(">> Blasting backwards from subject genome to query genome.")
# Run backwards BLAST towards query proteome.
BLASTBackward = runBLAST("tempQuery.faa", queryBLASTDBFile)
BLASTBackward = filterBLASTCSV(BLASTBackward) # Filters BLAST results by percent identity.
print(">> Creating Graph...")
for hit in BLASTForward:
BLASTGraph.addEdge(hit[0], hit[1], hit[5])
for hit in BLASTBackward:
BLASTGraph.addEdge(hit[0], hit[1], hit[5])
BackBlastOutput = list(BLASTForward)
print(">> Checking if forward hit subjects have better reciprocal hits than query.")
for hit in BLASTForward:
queryProtein = BLASTGraph.getVertex(hit[0])
subjectProtein = BLASTGraph.getVertex(hit[1])
topBackHitScore = 0
# Find the top score of the best reciprocal BLAST hit.
for backHit in subjectProtein.getConnections():
backHitScore = subjectProtein.getWeight(
backHit) # The edge weight between the subject and its reciprocal BLAST hit is the BLAST score.
if backHitScore >= topBackHitScore:
topBackHitScore = backHitScore
# Check if the query is the best reciprocal BLAST hit for the subject.
deleteHit = False
if queryProtein in subjectProtein.getConnections():
BackHitToQueryScore = subjectProtein.getWeight(
queryProtein) # The edge weight between the subject and the query is the reciprocal BLAST score.
示例6: __init__
# 需要导入模块: from Graph import Graph [as 别名]
# 或者: from Graph.Graph import getVertex [as 别名]
class NaiveHananSolver:
__slots__ = ("_graph", "_startingVerts", "_startingVertCoords", "_stationWeightFunc")
def __init__(self, startingVerts):
self._graph = Graph()
Xs = Ys = set()
self._startingVerts = []
self._stationWeightFunc = lambda g,v: 0
self._startingVertCoords = startingPts = [(vert.X, vert.Y) for vert in startingVerts]
for vert in startingVerts:
self._startingVerts.append(self._graph.addVertex(Vertex(vert.X, vert.Y, vert.name)))
Xs = Xs.union([vert.X])
Ys = Ys.union([vert.Y])
hananPts = product(*(zip(*startingPts)))
for (hananID, (vertX, vertY)) in enumerate(set(hananPts).difference(startingPts)):
self._graph.addVertex(Vertex(vertX, vertY, "h"+str(hananID)))
## NB: Make sure these all are in-scope, as we'll need their end-of-loop values below.
x = rightX = y = upY = thisVertID = rightVertID = upVertID = rightUpVertID = None
Xs = sorted(Xs)
Ys = sorted(Ys)
XsCurr, XsRight = tee(Xs)
next(XsRight, None)
for (x, rightX) in zip(XsCurr, XsRight):
YsCurr, YsUp = tee(Ys)
next(YsUp, None)
for (y, upY) in zip(YsCurr, YsUp):
thisVertID = self._graph.getVertexID(x, y)
rightVertID = self._graph.getVertexID(rightX, y)
upVertID = self._graph.getVertexID(x, upY)
self._graph.addEdgeWithVertsAndWeight(thisVertID, rightVertID, abs(rightX-x))
self._graph.addEdgeWithVertsAndWeight(thisVertID, upVertID, abs(upY-y))
rightUpVertID = self._graph.getVertexID(rightX, upY)
self._graph.addEdgeWithVertsAndWeight(rightVertID, rightUpVertID, abs(upY-y))
self._graph.addEdgeWithVertsAndWeight(upVertID, rightUpVertID, abs(rightX-x))
## stationWeightFunc should accept the graph object as the first parameter and the vertex ID
## as the second.
def addStationWeightFunc(self, stationWeightFunc):
self._stationWeightFunc = stationWeightFunc
def solve(self):
def _areVerticesColinear(theGraph, vertIDs):
assert len(vertIDs) == 3, "Expected 3 vertex IDs."
(vert1, vert2, vert3) = (theGraph.getVertex(vertID) for vertID in vertIDs)
if vert1.X == vert2.X == vert3.X:
return "Y"
if vert1.Y == vert2.Y == vert3.Y:
return "X"
return False
def _removePassthroughPoints(theGraph, distFunc):
## Each pass will remove all 2-order points that are not starting vertices,
## where the points are essentially unneeded. For example, if there are
## edges A-->B and B-->C, and B is not a starting vertex and has no other
## neighbors, and A, B, and C are all colinear, replaces both of these
## edges with a single edge A-->C and removes B from the graph.
nothingRemoved = False
while not nothingRemoved:
nothingRemoved = True
for (vertID, vertObj) in theGraph.getVerts():
if theGraph.getDegreeOfVertex(vertID) == 2:
nbrs = theGraph.getNeighborhood(vertID)
if (_areVerticesColinear(theGraph, [vertID] + nbrs)
and vertID not in self._startingVerts):
(otherVert1ID, otherVert1Obj), (otherVert2ID, otherVert2Obj) = [
(vertID, theGraph.getVertex(vertID)) for vertID in nbrs]
theGraph.removeVertex(vertID)
theGraph.addEdgeWithVertsAndWeight(otherVert1ID, otherVert2ID,
distFunc(otherVert1Obj, otherVert2Obj))
nothingRemoved = False
def _removeUselessPoints(theGraph, maxOrder, removeNearStartingVerts=False):
## Remove all n-order or less Hanan points until grid unchanged.
nothingRemoved = False
for vertID in self._startingVerts:
print ("DEBUG: solve: startingVerts is: ({ID}) {name}".format(ID=vertID, name=theGraph._verts[vertID].name))
while not nothingRemoved:
print("DEBUG: solve: Starting a {n}-order removal pass.".format(n=maxOrder))
nothingRemoved = True
for (vertID, vertObj) in theGraph.getVerts():
print("DEBUG: solve: deg = {deg} @vertex {name}".format(name=vertObj.name,
deg=theGraph.getDegreeOfVertex(vertID)))
isAdjStartVert = len(set(theGraph.getNeighborhood(vertID)).intersection(self._startingVerts)) > 0
if (theGraph.getDegreeOfVertex(vertID) <= maxOrder
and vertID not in self._startingVerts
and (isAdjStartVert if removeNearStartingVerts else True)):
print("DEBUG: solve: @vertex ({ID}) {name}".format(ID=vertID, name=theGraph._verts[vertID].name))
theGraph.removeVertex(vertID)
nothingRemoved = False
#.........这里部分代码省略.........
示例7: Graph
# 需要导入模块: from Graph import Graph [as 别名]
# 或者: from Graph.Graph import getVertex [as 别名]
# Create an edge list for graph in Figure 16.1
edges = [
[0, 1], [0, 3], [0, 5],
[1, 0], [1, 2], [1, 3],
[2, 1], [2, 3], [2, 4], [2, 10],
[3, 0], [3, 1], [3, 2], [3, 4], [3, 5],
[4, 2], [4, 3], [4, 5], [4, 7], [4, 8], [4, 10],
[5, 0], [5, 3], [5, 4], [5, 6], [5, 7],
[6, 5], [6, 7],
[7, 4], [7, 5], [7, 6], [7, 8],
[8, 4], [8, 7], [8, 9], [8, 10], [8, 11],
[9, 8], [9, 11],
[10, 2], [10, 4], [10, 8], [10, 11],
[11, 8], [11, 9], [11, 10]
]
graph = Graph(vertices, edges)
dfs = graph.dfs(graph.getIndex("Chicago"))
searchOrders = dfs.getSearchOrders()
print(str(dfs.getNumberOfVerticesFound()) +
" vertices are searched in this DFS order:")
for i in range(len(searchOrders)):
print(graph.getVertex(searchOrders[i]), end = " ")
print();
for i in range(len(searchOrders)):
if dfs.getParent(i) != -1:
print("parent of " + graph.getVertex(i) +
" is " + graph.getVertex(dfs.getParent(i)))
示例8: GraphTest
# 需要导入模块: from Graph import Graph [as 别名]
# 或者: from Graph.Graph import getVertex [as 别名]
class GraphTest(unittest.TestCase):
def setUp(self):
self.graph = Graph()
self.graph.addVertex(vertexid='v1')
self.graph.addVertex(vertexid='v2')
self.graph.addVertex(vertexid='v3')
self.graph.addVertex(vertexid='v4')
self.graph.addVertex(vertexid='v5')
self.graph.connect(vertexid1='v1', vertexid2='v2', cost=None)
self.graph.connect(vertexid1='v1', vertexid2='v3', cost=None)
self.graph.connect(vertexid1='v1', vertexid2='v4', cost=None)
self.graph.connect(vertexid1='v1', vertexid2='v5', cost=None)
self.graph.connect(vertexid1='v2', vertexid2='v1', cost=None)
self.graph.connect(vertexid1='v2', vertexid2='v3', cost=None)
self.graph.connect(vertexid1='v2', vertexid2='v4', cost=None)
self.graph.connect(vertexid1='v2', vertexid2='v5', cost=None)
# for node in self.graph.graph:
# print('sucessor: {}\n'.format(self.graph.graph.get(node).sucessor),
# 'predecessor: {}\n'.format(self.graph.graph.get(node).predecessor))
def tearDown(self):
del self.graph
def testWhenAddVertexShouldHaveId(self):
self.assertEqual(self.graph.getVertex(vertexid='v1').vertexid,
'v1',
'should have the same id')
def testDiferentVertexesShouldHaveDiferentIds(self):
self.assertNotEqual(self.graph.getVertex(vertexid='v1').vertexid,
self.graph.getVertex(vertexid='v2').vertexid,
'should have diferent ids')
def testWeigth(self):
self.graph.addVertex(vertexid='v6')
self.graph.addVertex(vertexid='v7')
self.graph.connect('v6', 'v7', cost=1290)
self.assertEquals(self.graph.vertexAdjacencies('v6').get('v7').getcost(), 1290,
'v6 should have weigth equal to 1290 linked to v7')
self.assertEquals(self.graph.vertexAdjacencies('v7').get('v6').getcost(), 1290,
'v7 should have weigth equal to 1290 linked to v6')
def testSizeShouldBeEqualToGraphLength(self):
self.assertEqual(self.graph.size, len(self.graph.graph),
'size must be equal to length(self.graph.graph)')
def testShouldConnectUsingNumbers(self):
self.graph.addVertex(vertexid=1)
self.graph.addVertex(vertexid=2)
self.graph.connect(vertexid1=1, vertexid2=2, cost=None)
self.assertTrue(2 in self.graph.vertexAdjacencies(vertexid=1),
'after insertion and connection 2 must be \"sucessor\" of 1')
def testAddVertexObjectInsteadOfId(self):
#with self.assertRaises(GraphValidationError):
self.assertEqual(self.graph.addVertex(vertexid=Vertex('v1')),
None, 'should get None after trying to input another \"v1\" in the graph')
def testMakeDisconnectOfVertexes(self):
self.graph.disconnect(vertexid1='v1', vertexid2='v5')
self.assertTrue('v5' not in self.graph.vertexAdjacencies('v1'),
'should not have a connection in between v1 and v5')
self.assertTrue('v1' not in self.graph.vertexAdjacencies('v5'),
'should not have a connection in between v1 and v5')
self.assertTrue(self.graph.size == len(self.graph.graph) == self.graph.graphMagnitude(),
'should return true for all ways to get the graph size')
def testVertexRemoval(self):
self.graph.removeVertex(vertexid='v1')
self.assertFalse('v1' in self.graph.vertexAdjacencies('v3'),
'should return nothing because v1 was removed before this')
self.assertFalse('v1' in self.graph.vertexAdjacencies('v4'),
'should return nothing because v1 was removed before this')
#with self.assertRaises(GraphValidationError):
self.assertEquals(self.graph.vertexAdjacencies(vertexid='v1'), None,
'should return nothign because it has been already deleted')
self.assertTrue(self.graph.size == len(self.graph.graph) == self.graph.graphMagnitude(),
'should return true for all ways to get the graph size')
def testGraphMagnitude(self):
self.assertFalse(self.graph.graphMagnitude() == 7,
'should have take the number of nodes already inserted in')
self.graph.disconnect(vertexid1='v1', vertexid2='v5')
self.assertEquals(self.graph.graphMagnitude(), 5,
'should have take the number of nodes already inserted in')
self.assertFalse(self.graph.size == 3,
'should return true by just getting size property')
def testVertexMagnitude(self):
self.assertEquals(self.graph.vertexMagnitude('v1'), 4,
'should have a vertex with a number of adjacencies')
def testIfItIsRegularGraph(self):
"""
The great thing about graphs is that you can save a lot of cpu power
by just connecting nodes right, when we have a regular graph we dont
need to waste cpu power to connect a lot of nodes in a case where the
edges dont have direction of course, and we can come and go through
the same edge, the connections do the heuristic job of anticipating
#.........这里部分代码省略.........