Esempio n. 1
0
def run_nc():
    with open("../resources/tinyEWDnc.txt", ) as f:
        values = "".join(f.readlines()).splitlines()
        V, E = int(values[0]), int(values[1])
        g = EdgeWeightedDigraph(V)
        for line in values[2:]:
            vertices = line.split(' ')
            v, w, weight = int(vertices[0]), int(vertices[1]), float(vertices[2])
            e = DirectedEdge(v, w, weight)
            g.add_edge(e)
    s = 0
    sp = BellmanFordSP(g, s)

    if sp.has_negative_cycle():
        print('negative cycle')
        q = sp.negative_cycle()
        while not q.empty():
            print(q.get())
    else:
        for t in range(g.get_V()):
            if sp.has_path_to(t):
                print(f'{s} to {t} ({sp.dist_to(t)}) ', end="")
                q = sp.path_to(t)
                while not q.empty():
                    print(q.get())
                print()
            else:
                print(f'{s} to {t} no path\n')
Esempio n. 2
0
    def run():
        V = 5
        names = ['USD', 'EUR', 'GBP', 'CHF', 'CAD']
        rates = [[1, 0.741, 0.657, 1.061, 1.005],
                 [1.349, 1, 0.888, 1.433, 1.366],
                 [1.521, 1.126, 1, 1.614, 1.538],
                 [0.942, 0.698, 0.619, 1, 0.953],
                 [0.995, 0.732, 0.650, 1.049, 1]]

        g = EdgeWeightedDigraph(V)

        for v in range(V):
            for w in range(V):
                e = DirectedEdge(v, w, -math.log(rates[v][w]))
                g.add_edge(e)
        # print(g)
        spt = BellmanFordSP(g, 0)
        # print(spt)
        print(spt.negative_cycle().queue)
        print(spt.has_negative_cycle())
        if spt.has_negative_cycle():
            print('hit')
            stake = 1000.0
            for e in spt.negative_cycle().queue:
                print(e)
                print(f'{stake} {names[e.tail()]}')
                stake *= math.exp(-e.weight())
                print(f'= {stake}\n {names[e.head()]}')
        else:
            print('No arbitrage opportunity')
Esempio n. 3
0
def main():
    g = EdgeWeightedDigraph(8)
    with open("../resources/tinyEWD.txt", ) as f:
        for line in f.readlines():
            vertices = " ".join(line.splitlines()).split(' ')
            if len(vertices) < 3:
                continue
            else:
                v, w, weight = int(vertices[0]), int(vertices[1]), float(
                    vertices[2])
                e = DirectedEdge(v, w, weight)
                g.add_edge(e)

    print(g)
    finder = EdgeWeightedDirectedCycle(g)
    print(finder)

    if finder.has_cycle():
        print('cycle')
        while not finder.cycle().empty():
            e = finder.cycle().get()
            print(f'{e} ')
        print()
    else:
        print('No directed cycle')
Esempio n. 4
0
    def run():
        with open("../resources/jobsPC.txt", ) as f:
            values = "".join(f.readlines()).splitlines()
            print(values)
            n = int(values[0])
            source, sink = 2 * n, 2 * n + 1
            durations = list()
            for x in values[1:]:
                durations.append(float(x.split(' ')[0]))
            precedent = list()
            print(values[1:])
            for prec in values[1:]:
                if prec.split('  ')[-1] == '0':
                    precedent.append([])
                else:
                    precedent.append("".join(prec.split('  ')[-1]).split(' '))

            print(n, durations, precedent)
            g = EdgeWeightedDigraph(2 * n + 2)
            for i in range(n):
                g.add_edge(DirectedEdge(source, i, 0.0))
                g.add_edge(DirectedEdge(i + n, sink, 0.0))
                g.add_edge(DirectedEdge(i, i + n, durations[i]))

                m = len(precedent[i])
                for j in range(m):
                    p = int(precedent[i][j])
                    g.add_edge(DirectedEdge(n + i, p, 0.0))
            print(g)
        lp = AcyclicLP(g, source)
        print('job start finish')
        print('----------------')
        for i in range(n):
            print(f'{i}, {lp.dist_to(i)}, {lp.dist_to(i+n)}')
        print(f'finish time {lp.dist_to(sink)}')
Esempio n. 5
0
    def __find_negative_cycle(self):
        V = len(self._edge_to)
        spt = EdgeWeightedDigraph(V)

        for v in range(V):
            if self._edge_to[v] is not None:
                spt.add_edge(self._edge_to[v])

        finder = EdgeWeightedDirectedCycle(spt)
        self._cycle = finder.cycle()
def main():
    with open("../resources/tinyEWD.txt", ) as f:
        values = "".join(f.readlines()).splitlines()
        V, E = int(values[0]), int(values[1])
        g = EdgeWeightedDigraph(V)
        for line in values[2:]:
            vertices = line.split(' ')
            v, w, weight = int(vertices[0]), int(vertices[1]), float(
                vertices[2])
            e = DirectedEdge(v, w, weight)
            g.add_edge(e)

    dijkstra = DijkstraAllPairsSP(g)
    print(dijkstra)
Esempio n. 7
0
    def __init__(self, g: EdgeWeightedDigraph, s: int):
        self._dist_to = [-math.inf] * g.get_V()  # -inf not inf
        self._edge_to = [None] * g.get_V()
        self._g = g
        self.__validate_vertex(s)
        self._s = s
        self._dist_to[s] = 0.0

        top_order = Topological(g)
        if not top_order.has_order():
            raise ValueError('Digraph is not acyclic')
        else:
            for v in top_order.order():
                for e in g.adj_vertices(v):
                    self.__relax(e)
Esempio n. 8
0
    def __init__(self, g: EdgeWeightedDigraph, s: int):
        self._dist_to = [math.inf] * g.get_V()
        self._edge_to = [None] * g.get_V()
        self._g = g
        self._s = s
        self._cycle = None
        self.__validate_vertex(s)
        self._on_queue = [False] * g.get_V()
        self._dist_to[s] = 0.0

        # Bellman-Ford Algorithm
        self._queue = Queue()
        self._queue.enqueue(s)
        self._on_queue[s] = True

        while not self._queue.is_empty() and not self.has_negative_cycle():
            v = self._queue.dequeue()
            self._on_queue[v] = False
            self.__relax(g, v)

        assert self.__check(g, s)
Esempio n. 9
0
def main():
    with open("../resources/tinyEWDAG.txt", ) as f:
        values = "".join(f.readlines()).splitlines()
        V, E = int(values[0]), int(values[1])
        g = EdgeWeightedDigraph(V)
        for line in values[2:]:
            vertices = line.split(' ')
            v, w, weight = int(vertices[0]), int(vertices[1]), float(vertices[2])
            e = DirectedEdge(v, w, weight)
            g.add_edge(e)
    s = 5
    asp = AcyclicSP(g, s)
    for t in range(g.get_V()):
        if asp.has_path_to(t):
            print(f'{s} to {t} ({asp.dist_to(t)}) ', end="")
            q = asp.path_to(t)
            while not q.empty():
                print(q.get())
            print()
        else:
            print(f'{s} to {t} no path\n')
Esempio n. 10
0
    def __dfs(self, g: EdgeWeightedDigraph, v):
        self._on_stack[v] = True
        self._marked[v] = True
        for e in g.adj_vertices(v):
            w = e.item.head()
            # short circuit if directed cycle found
            if self._cycle is not None:
                return
            # found new vertex so recur
            elif not self._marked[w]:
                self._edge_to[w] = e
                self.__dfs(g, w)
            # trace back directed cycle
            elif self._on_stack[w]:
                self._cycle = LifoQueue()
                f = e
                while f.item.tail() != w:
                    self._cycle.put(f.item)
                    f = self._edge_to[f.item.tail()]
                self._cycle.put(f.item)
                return

        self._on_stack[v] = False
Esempio n. 11
0
    def __init__(self, g: EdgeWeightedDigraph, s: int):
        for e in g.edges():
            edge_weight = e.item.item.weight()
            if edge_weight < 0:
                raise ValueError(f'edge {e} has negative weight')
        self._g = g
        self._s = s
        self._edge_to = [None] * g.get_V()
        self._dist_to = [math.inf] * g.get_V()
        self._dist_to[s] = 0.0
        self._spt = [False] * g.get_V()
        self._on_queue = [False] * g.get_V()
        self.__validate_vertex(s)

        self._pq = list()
        heapq.heappush(self._pq, (self._dist_to[s], s))
        self._on_queue[s] = True

        while len(self._pq) > 0:
            current_distance, v = heapq.heappop(self._pq)
            self._on_queue[v] = False
            for e in g.adj_vertices(v):
                self.__relax(e)