Exemple #1
0
 def __init__(self, start, end):
     self.graph = DirectedGraph()
     self.__activities = []
     self.__sortedActivities = []
     self.__criticalActivities = []
     self.start = start
     self.end = end
     self.graph.addVertex(start)
     self.graph.addVertex(end)
Exemple #2
0
def createRandomDAGIter(n):
    newGraph = DirectedGraph()
    # Create n nodes
    for k in range(0, n):
        newGraph.addNode(k)

    # Assign each node 2 random vertices (might assign 0, 1 or 2 vertices)
    for node in newGraph.vertices:
        randomVertices = set()
        # Generate 2 random numbers which will represent direction up and right
        neighborNodeIndex1 = random.randint(node.val,
                                            len(newGraph.vertices) - 1)
        neighborNodeIndex2 = random.randint(node.val,
                                            len(newGraph.vertices) - 1)
        # If number generated is not being used yet and it doesn't represent node.val
        if node.val != neighborNodeIndex1 and neighborNodeIndex1 not in randomVertices:
            newGraph.addDirectedEdge(newGraph.vertices[node.val],
                                     newGraph.vertices[neighborNodeIndex1])
            randomVertices.add(neighborNodeIndex1)
        # If second number generated is not being used yet and it doesn't represent node.val
        if node.val != neighborNodeIndex2 and neighborNodeIndex2 not in randomVertices:
            newGraph.addDirectedEdge(newGraph.vertices[node.val],
                                     newGraph.vertices[neighborNodeIndex2])
            randomVertices.add(neighborNodeIndex2)

    return newGraph
Exemple #3
0
 def mDFS(graph: DirectedGraph) -> List[Node]:
     stack = []
     visited = set()
     for node in graph.getAllNodes():
         if node not in visited:
             TopSort.mDFSHelper(graph, node, stack, visited)
     stack.reverse()
     return stack
Exemple #4
0
def printGraph(graph: DirectedGraph):
    if verbose:
        print("Start to Print Graph")
        nodes = graph.getAllNodes()
        for node in nodes:
            print("--- Node", node.getNodeVal(), "---")
            for neighbor in node.getNeighbors():
                print("Neighbor -", neighbor.getNodeVal(), "Weight -",
                      node.getNeighbors()[neighbor])
        print("Done Printing Graph")
class CriticalPath(object):
    def __call__(self, DG):
        self.graph = DG

        topsort = TopologicSort()

        # 求正向的情况
        forwardTopSequence, forwardVe = topsort(self.graph)
        # 总时长为最后一个时间完成的最早时间
        total = forwardVe[forwardTopSequence[-1]]
        
        # 这里用了一个小技巧,教材上是写了两段不同的拓扑排序(而且写得很丑陋)
        # ,事实上,可以这么做:将所拥有边反向,正常的进行一次拓扑排序(也就是
        # 带有最早完成时间的拓扑排序),对反向图求出结果后,把 ve 数组里面的每
        # 个元素,都被正向拓扑排序时得到的总时长减去即可。
        # 这样可以节省代码量。

        # 将边反向
        self.reversedGraph = DirectedGraph() # 新图
        for u in self.graph: # 枚举点
            self.reversedGraph.addVertex(u) # 将原图所有点添加到新图
        for u in self.graph: # 枚举边
            for v in self.graph[u]:
                # 当枚举到一条边时,在新图里面插入一条同权反向边
                self.reversedGraph.insertEdge(v, u, self.graph[u][v])

        # 求反向的情况
        backwardTopSequence, backwardVe = topsort(self.reversedGraph)
        # 减总时长
        backwardVe = {key:total-backwardVe[key] for key in backwardVe}
        
        # 求关键活动
        criticalEvent = {}
        for u in forwardVe:
            if forwardVe[u] == backwardVe[u]:
                criticalEvent[u] = forwardVe[u]

        return (criticalEvent, 
                (forwardTopSequence, forwardVe),
                (backwardTopSequence, backwardVe))
Exemple #6
0
def createRandomDAGIter(node_count=10):
    self = DirectedGraph()
    # Create the nodes:
    for n in range(node_count):
        self.addNode(n)

    for node in self.nodes:
        connect = node
        while connect is node:  # Keeps going if it tries to connect to itself.
            connect = random.choice(self.nodes)

        self.addDirectedEdge(node.val, connect.val)

    return self
Exemple #7
0
def createRandomDAGIter(n: int) -> DirectedGraph:
    graph = DirectedGraph()
    for i in range(n):
        graph.addNode(i)
    for node in graph.nodes:
        for _node in graph.nodes:
            if node is not _node and bool(getrandbits(1)):
                if not hasCycle(graph, node, _node):
                    graph.addDirectedEdge(node, _node)
    return graph
    def createRandomDAGIter(n):
        graph = DirectedGraph()
        nums = list(range(n))
        for num in nums:
            graph.addNode(num)

        for node in graph.getAllNodes():
            numNodes = random.randint(0, n - node)
            numsAdded = set()
            while len(numsAdded) != numNodes:
                num = random.randint(node + 1, n)
                if num not in numsAdded:
                    numsAdded.add(num)
                    graph.addDirectedEdge(node, num)

        return graph
Exemple #9
0
 def Kahns(graph: DirectedGraph) -> List[Node]:
     nodes = graph.getAllNodes()
     inDegreeMap = {node:0 for node in nodes}
     for node in nodes:
         for neighbor in node.getNeighbors():
             inDegreeMap[neighbor] += 1
     topSort = []
     queue = deque()
     for node in inDegreeMap:
         if inDegreeMap[node] == 0:
             queue.append(node)
     count = 0
     while len(queue) != 0:
         node = queue.popleft()
         topSort.append(node)
         count += 1
         for neighbor in node.getNeighbors():
             inDegreeMap[neighbor] -= 1
             if inDegreeMap[neighbor] == 0:
                 queue.append(neighbor)
     if count != len(graph.nodes):
         return None
     return topSort
u'''
测试拓扑排序的一个演示程序。
程序的第一个参数是个文件名,程序会从该文件中读取图,对其进行拓扑排序,并打印在
屏幕上。

用法:
$ ./topologicSortDemo.py graph.json
'''

import sys

from directedGraph import DirectedGraph
from topologicSort import TopologicSort

if __name__ == '__main__':

    if len(sys.argv) == 2:
        filename = sys.argv[1]
    else:
        raise Exception, "需要参数"

    g = DirectedGraph()
    g.loadFromFile(filename)

    topsort = TopologicSort()
    ret, ve = topsort(g)

    print u"拓扑序 ", ret
    print u"时间最早发生的时间 ", ve

Exemple #11
0
class ActivityGraph:
    def __init__(self, start, end):
        self.graph = DirectedGraph()
        self.__activities = []
        self.__sortedActivities = []
        self.__criticalActivities = []
        self.start = start
        self.end = end
        self.graph.addVertex(start)
        self.graph.addVertex(end)

    def addActivity(self, a):
        self.__activities.append(a)

    def DepthFirst(self, sortedVertices, inStack, x):
        inStack.append(x)
        for y in self.graph.getOutboundVertices(x):
            if y not in inStack:
                if self.DepthFirst(sortedVertices, inStack, y) == False:
                    return False
            elif y in inStack and y not in sortedVertices:
                return False
        sortedVertices.append(x)
        
        return True

    def CheckIfDAG(self):
        inStack = []
        isDag = self.DepthFirst(self.__sortedActivities, inStack, self.start)
        if isDag == False:
            return isDag

        print(self.__sortedActivities)
        self.ComputeCriticalActivities()
            
        return isDag
    
    def ComputeCriticalActivities(self):
        for a in reversed(self.__sortedActivities):
            maxVal = 0
            inbound = []
            for v in self.graph.getInboundVertices(a):
                V = Activity(v, 0)
                inbound.append(V)
            for A in self.__activities:
                if A in inbound:
                    maxVal = max(maxVal, A.earliestEnd)
            A = Activity(a, 0)
            for activity in self.__activities:
                if activity == A:
                    activity.earliestStart = maxVal
                    activity.earliestEnd = maxVal + activity.duration

        for a in self.__sortedActivities:
            minVal = 99999999
            outbound = []
            for v in self.graph.getOutboundVertices(a):
                V = Activity(v, 0)
                outbound.append(V)
            for A in self.__activities:
                if A in outbound:
                    minVal = min(minVal, A.latestStart)
            A = Activity(a, 0)
            for activity in self.__activities:
                if activity == A:
                    activity.latestEnd = minVal
                    activity.latestStart = minVal - activity.duration
                    if activity.activityID == 'Y':
                        activity.latestEnd = activity.earliestEnd
                        activity.latestStart = activity.earliestStart
                    if activity.latestStart == activity.earliestStart:
                        self.__criticalActivities.append(activity)

    
    def GetActivities(self):
        return self.__activities
    
    def GetCriticalActivities(self):
        return self.__criticalActivities
def main():
    keyString = f.readline().rstrip()
    defragmenter = Defragmenter(keyString)
    grid = defragmenter.getGrid()
    expandedGrid = [list(row) for row in grid]

    graph = DirectedGraph()
    for rowIdx, row in enumerate(expandedGrid):
        for columnIdx, column in enumerate(row):
            if column == '1':
                coordinate = (rowIdx, columnIdx)
                graph.addNode(coordinate)

                if (rowIdx > 0 and expandedGrid[rowIdx - 1][columnIdx] == '1'):
                    graph.addEdge(coordinate, (rowIdx - 1, columnIdx))
                if (columnIdx + 1 < 128
                        and expandedGrid[rowIdx][columnIdx + 1] == '1'):
                    graph.addEdge(coordinate, (rowIdx, columnIdx + 1))
                if (rowIdx + 1 < 128
                        and expandedGrid[rowIdx + 1][columnIdx] == '1'):
                    graph.addEdge(coordinate, (rowIdx + 1, columnIdx))
                if (columnIdx > 0
                        and expandedGrid[rowIdx][columnIdx - 1] == '1'):
                    graph.addEdge(coordinate, (rowIdx, columnIdx - 1))

    graph.findRegions()
    print(graph.getRegionCount())
Exemple #13
0
from directedGraph import DirectedGraph
from controller import Controller
from UI import Console

graph = DirectedGraph()
graph.loadFromFile("graph1k.txt")

controller = Controller(graph)
console = Console(controller)

console.run()
Exemple #14
0
    def createRandomDAGIter(n):
        graph = DirectedGraph()
        i=1
        nodeVal=1
        graph.addNode(1)
        while nodeVal<=n:
            if nodeVal+1<=n:
                graph.addNode(nodeVal+1)
            if nodeVal+2<=n:
                graph.addNode(nodeVal+2)
            if nodeVal+3<=n:
                graph.addNode(nodeVal+3)
            for l in range(3):
                nodeVal = nodeVal + 1
                if nodeVal<=n:
                    graph.addDirectedEdge(i,nodeVal)

            i=i+1
        return graph
Exemple #15
0
def test_directedGraph():
    defragmenter = Defragmenter('flqrgnkx')
    grid = defragmenter.getGrid()
    expandedGrid = [list(row) for row in grid]

    graph = DirectedGraph()
    for rowIdx, row in enumerate(expandedGrid):
        for columnIdx, column in enumerate(row):
            if column == '1':
                coordinate = (rowIdx, columnIdx)
                graph.addNode(coordinate)

                if (rowIdx > 0 and expandedGrid[rowIdx - 1][columnIdx] == '1'):
                    graph.addEdge(coordinate, (rowIdx - 1, columnIdx))
                if (columnIdx + 1 < 128
                        and expandedGrid[rowIdx][columnIdx + 1] == '1'):
                    graph.addEdge(coordinate, (rowIdx, columnIdx + 1))
                if (rowIdx + 1 < 128
                        and expandedGrid[rowIdx + 1][columnIdx] == '1'):
                    graph.addEdge(coordinate, (rowIdx + 1, columnIdx))
                if (columnIdx > 0
                        and expandedGrid[rowIdx][columnIdx - 1] == '1'):
                    graph.addEdge(coordinate, (rowIdx, columnIdx - 1))

    graph.findRegions()
    assert graph.getRegionCount() == 1242