def checarSiAristaExiste(self, source, target):
     nueva_arista = Arista(self.nodos[source], self.nodos[target])
     nueva_arista2 = Arista(self.nodos[target], self.nodos[source])
     if nueva_arista.id in self.aristas:
         return True
     if (not self.dirigido):  #Si no es un grafo dirigido
         if nueva_arista2.id in self.aristas:
             return True
     return False
Example #2
0
 def cargarDesdeMatriz(self, Matriz, Demanda):
     #for fila in range(0, len(Matriz)):
     #    self._V.append(Vertice(fila+1, Demanda[fila]))    #V=[1,3,4] A=[(1,3)(3,4)] => sol 1->3->4->5->2
     for fila in range(0, len(Matriz)):
         self._V.append(Vertice(fila+1, Demanda[fila]))    #V=[1,3,4] A=[(1,3)(3,4)] => sol 1->3->4->5->2
         for columna in range(0, len(Matriz[fila])):
             aux = Arista(Vertice(fila+1, Demanda[fila]),Vertice(columna+1, Demanda[columna]),(Matriz[fila][columna]))
             aux.setId(fila, columna, len(Matriz))
             self._A.append(aux)
Example #3
0
    def add_arista(self, vertice_inicial, vertice_final, timestamp):
        arista = Arista(vertice_inicial, vertice_final, timestamp)
        arista_invertida = Arista(vertice_final, vertice_inicial, timestamp)
        self.vertices[vertice_inicial].add_arista(arista)
        self.vertices[vertice_final].add_arista(arista_invertida)

        heapq.heappush(self.aristas, [timestamp, arista])
        # Actualiza el maximo timestamp si hace falta
        if self.max_ts < timestamp:
            self.max_ts = timestamp
Example #4
0
    def cargarDesdeSecuenciaDeVertices(self, seq: list):
        self._V = seq
        self._A = []
        costo = 0
        demAcum = 0
        self._demandaAcumulada = []
        cap = 0

        for i in range(0, len(seq)):
            if (i < len(seq) - 1):
                fila = seq[i].getValue() - 1
                col = seq[i + 1].getValue() - 1
                dist = self.getMatriz()[fila][col]  #Referencias en la matriz
                new_edge = Arista(seq[i], seq[i + 1], dist)
                new_edge.setId(fila, col, len(self._matrizDistancias))
                self.getA().append(new_edge)
            else:
                fila = seq[i].getValue() - 1
                col = 0
                dist = self.getMatriz()[fila][col]
                new_edge = Arista(seq[i], seq[0], dist)
                new_edge.setId(fila, col, len(self._matrizDistancias))
                self.getA().append(new_edge)
            demAcum += new_edge.getOrigen().getDemanda()
            self._demandaAcumulada.append(demAcum)
            costo += dist
            cap += seq[i].getDemanda()
        self._costoAsociado = costo

        return cap
Example #5
0
class Cara:
    __centro = '0'
    __e1 = Esquina()
    __e2 = Esquina()
    __e3 = Esquina()
    __e4 = Esquina()
    __a1 = Arista()
    __a2 = Arista()
    __a3 = Arista()
    __a4 = Arista()

    def __init__(self, centro):
        self.__centro = centro
Example #6
0
 def __extract_edges(self, lines):
     clean_lines = self.__clean_lines(lines)
     edges = {}
     for edge in clean_lines:
         edges[edge[0]] = Arista(edge[3], edge[1], edge[2], edge[4],
                                 edge[5])
     return edges
Example #7
0
    def __str__(self):
        salida = ""
        V = self.getV()
        #Muestra la primera fila con los vertices
        if (len(self._matrizDistancias) == len(self.getV())):
            for i in range(0, len(V)):
                if (V[i] >= 10):
                    salida += "        " + str(V[i])
                else:
                    salida += "        " + str(V[i]) + " "

            salida = salida + "\n"
            for i in range(0, len(V)):
                if (V[i] >= 10):
                    salida += str(V[i]) + "    "
                else:
                    salida += str(V[i]) + "     "
                for j in range(0, len(V)):
                    if (self._matrizDistancias[i][j] == 999999999999):
                        salida += str(0) + "         "
                    else:
                        salida += str(self._matrizDistancias[i][j]) + "    "
                salida = salida + "\n"
        else:
            for i in range(0, len(V)):
                salida += str(V[i]) + "         "

            salida = salida + "\n"
            for i in V:
                salida += str(i) + "    "
                for j in V:
                    indice = self.getCostoArista(Arista(i, j, 0))
                    salida += str(self.getA()[indice].getPeso()) + "    "
                salida = salida + "\n"
        return salida
Example #8
0
 def addPeso(self):
     '''
     Metodo que permite ingresar una arista, cuando se tiene referenciados
     dos puntos en el widget se podra digitar el peso, solo si se clickea en el boton
     aceptar la arista sera guardada, por lo cual, aqui se instacia
     un objeto de tipo Arista, y se adiciona un enlace en el grafo
     '''
     if self.lienzo.textPeso.text() != '0' and self.lienzo.textPeso.text(
     ) != '':
         peso = float(self.lienzo.textPeso.text())
         if peso > 0:
             arista = Arista(self.lienzo.puntoDuo[0],
                             self.lienzo.puntoDuo[1], peso)
             self.lienzo.aristas.append(arista)
             self.lienzo.grafo.adicionarEnlace(
                 self.lienzo.puntoDuo[0].getNombre(),
                 self.lienzo.puntoDuo[1].getNombre(), float(peso))
             self.lienzo.puntoDuo[1].setColorPunto(QBrush(Qt.blue))
             self.lienzo.textPeso.setText('')
             self.lienzo.widgetPeso.setEnabled(False)
             self.lienzo.contador = 0
             self.lienzo.puntoDuo[0].setColorPunto(QBrush(Qt.blue))
             self.lienzo.puntoDuo[1].setColorPunto(QBrush(Qt.blue))
             self.puntoenable = False
             self.lienzo.puntoDuo[0] = None
             self.lienzo.puntoDuo[1] = None
             self.repaint()
             self.lienzo.labelMessage.setText('Se adiciono una arista')
         else:
             self.lienzo.labelMessage.setText(
                 'Digite valores mayores a cero')
     else:
         self.lienzo.labelMessage.setText(
             'No deje el espacio de peso en blanco')
    def cargarDesdeSecuenciaDeVertices(self,seq:list):
        self._V = seq
        self._A = []
        costo = 0
        cap = 0
        
        for i in range(0,len(seq)):
            if(i< len(seq)-1):
                dist = self.getMatriz()[seq[i].getValue()-1][seq[i+1].getValue()-1] #Referencias en la matriz
                self.getA().append(Arista(seq[i], seq[i+1], dist))
            else:
                dist = self.getMatriz()[seq[i].getValue()-1][0]
                self.getA().append(Arista(seq[i], seq[0], dist))
            costo+=dist
            cap += seq[i].getDemanda()
        self._costoAsociado = costo

        return cap
 def agregar_arista(self, source, target):
     try:
         nueva_arista = Arista(self.nodos[source], self.nodos[target])
         self.aristas[nueva_arista.id] = nueva_arista
         self.nodos[source].grado += 1  #aumentar el grado del nodo
         self.nodos[target].grado += 1  #aumentar el grado del nodo
     except:
         print(
             '***Error - Checar que los nodos se hayan decalarado previamente!***'
         )
Example #11
0
    def cargaAristas(self):
        A = []
        cantV = len(self._V)
        for row in range(1, cantV):
            for col in range(1, cantV):
                arista_aux = Arista(row, col, self._matrizDistancias[row][col])
                A.append(arista_aux)

        #print("Aristas: \n",A)
        return A
Example #12
0
    def cargaGrafoDesdeSec(self, secuencia):
        V = []
        self._A = []
        costo = 0
        demAcum = 0
        self._demandaAcumulada = []
        cap = 0

        #for x in secuencia:
        for i in range(0, len(secuencia)):
            x = secuencia[i]
            V.append(Vertice(int(x), self._demanda[x - 1]))

            if i > 0:
                Vfila = V[i - 1]
                Vcol = V[i]
                fila = Vfila.getValue() - 1
                col = Vcol.getValue() - 1
                dist = self.getMatriz()[fila][col]  #Referencias en la matriz
                new_edge = Arista(Vfila, Vcol, dist)
                new_edge.setId(fila, col, len(self._matrizDistancias))
                self._A.append(new_edge)
                demAcum += new_edge.getOrigen().getDemanda()
                self._demandaAcumulada.append(demAcum)
                costo += dist
                cap += Vfila.getDemanda()

        self.setV(V)
        Vfila = V[-1]
        Vcol = V[0]
        fila = Vfila.getValue() - 1
        col = 0
        dist = self.getMatriz()[fila][col]
        new_edge = Arista(Vfila, Vcol, dist)
        new_edge.setId(fila, col, len(self._matrizDistancias))
        self._A.append(new_edge)
        demAcum += new_edge.getOrigen().getDemanda()
        self._demandaAcumulada.append(demAcum)
        costo += dist
        cap += Vfila.getDemanda()
        self._costoAsociado = costo

        return cap
 def insertarA(self, origen, destino):
     ''' Metodo para insertar una arista dentro de la lista de
         Aristas
         Args:
             origen(objeto): el valor del vertice de origen. 
             destino(objeto): el valor del vertice de destino. 
     '''
     origen_aux = self.buscarV(origen)
     destino_aux = self.buscarV(destino)
     if( (origen_aux != None) and (destino_aux != None) ):
         self.__Aristas.append(Arista(origen_aux, destino_aux))
Example #14
0
 def add_edge(self, u, v, weight=0):
     try:
         if v > self.V() - 1:
             print 'Vertice no valido'
             return
         aristas = self.aristas[u]
         for arista in aristas:
             if arista.dst == v:
                 ## si ya existe actualizo el peso
                 arista.weight = weight
                 return
         nueva_arista = Arista(u, v, weight)
         self.aristas[u].append(nueva_arista)
     except:
         print 'Vertice no valido'
Example #15
0
    def swap_2opt(self, lista_permitidos, ind_random, rutas_orig):
        sol_factible = False
        costo_solucion = self.getCostoAsociado()
        rutas = rutas_orig
        ADD = []
        DROP = []
            
        while(not sol_factible and len(ind_random)>=1):
            ADD = []
            DROP = []
            costo_solucion = self.getCostoAsociado()
            arista_ini = lista_permitidos[ind_random[-1]]
            ind_random.pop()
            
            V_origen = arista_ini.getOrigen()
            V_destino = arista_ini.getDestino()
            
            ADD.append(arista_ini)
            
            rutas = copy.deepcopy(rutas_orig)

            ind_rutas, ind_A = self.getPosiciones(V_origen, V_destino, rutas_orig)
            #En distintas rutas
            if(ind_rutas[0]!=ind_rutas[1]):
                r1 = rutas[ind_rutas[0]]
                r2 = rutas[ind_rutas[1]]
                costo_solucion -= r1.getCostoAsociado() + r2.getCostoAsociado()
                
                A_r1_left = r1.getA()[:ind_A[0]]
                A_r1_right = r1.getA()[ind_A[0]+1:]
                
                A_r2_left = r2.getA()[:ind_A[1]]
                A_r2_right = r2.getA()[ind_A[1]+1:]
                
                if(A_r1_right==[] and A_r2_left==[]):
                    continue

                A_r1_drop = r1.getA()[ind_A[0]]
                A_r2_drop = r2.getA()[ind_A[1]]
                
                if(A_r2_left!=[]):
                    V_origen = A_r2_left[-1].getDestino()    # => (6, )
                #En caso de que la arista al azar se encuentra al principio
                else:
                    V_origen = Vertice(1,0)
                if(A_r1_right!=[]):
                    V_destino = A_r1_right[0].getOrigen()   # => ( ,4)
                #En caso de que la arista al azar se encuentra al final
                else:
                    V_destino = Vertice(1,0)
                peso = self._matrizDistancias[V_origen.getValue()-1][V_destino.getValue()-1]
                A_r_add = Arista(V_origen,V_destino, peso)   # => (6,4, peso)
                
                ADD.append(A_r_add)
                DROP.append(A_r1_drop)
                DROP.append(A_r2_drop)
                
                A_r1_left.append(ADD[0])
                A_r1_left.extend(A_r2_right)
                A_r2_left.append(ADD[1])
                A_r2_left.extend(A_r1_right)
                
                cap_r1 = r1.cargaDesdeAristas(A_r1_left)
                cap_r2 = r2.cargaDesdeAristas(A_r2_left)
                r1.setCapacidad(cap_r1)
                r2.setCapacidad(cap_r2)

                if(cap_r1 > self.__capacidadMax or cap_r2 > self.__capacidadMax):
                    rutas = []
                else:
                    sol_factible = True
                    costo_solucion += r1.getCostoAsociado() + r2.getCostoAsociado()
            #En la misma ruta
            else:
                r = rutas[ind_rutas[0]]
                costo_solucion -= r.getCostoAsociado()
                V_r = r.getV()
                V_r.append(Vertice(1,0))
                V_r_left = V_r[:ind_A[0]+1]
                V_r_middle = V_r[ind_A[0]+1:ind_A[1]+1]
                V_r_middle = V_r_middle[::-1]               #invierto el medio
                V_r_right = V_r[ind_A[1]+2:]
                
                A_r_drop1 = r.getA()[ind_A[0]]
                A_r_drop2 = r.getA()[ind_A[1]+1]

                try:
                    V_origen = V_r_middle[-1]    # => (6, )
                except ValueError:
                    print("error")    
                    print("arista_ini: "+str(arista_ini))    
                    print("lista de perm: "+str(lista_permitidos))
                        
                V_destino = V_r_right[0]
                peso = self._matrizDistancias[V_origen.getValue()-1][V_destino.getValue()-1]
                A_r_add = Arista(V_origen,V_destino, peso)   # => (6,4, peso)
                
                ADD.append(A_r_add)                
                DROP.append(A_r_drop1)
                DROP.append(A_r_drop2)
                
                V_r_left.append(r.getV()[ind_A[1]+1])
                V_r_left.extend(V_r_middle)
                V_r_left.extend(V_r_right)
                V_r = V_r_left[:-1]
                
                cap = r.cargarDesdeSecuenciaDeVertices(V_r)
                r.setCapacidad(cap)
                if(cap > self.__capacidadMax):
                    rutas = []
                else:
                    sol_factible = True
                    costo_solucion += r.getCostoAsociado()
        #Fin del while (se encontro una solucion factible)
        if (not sol_factible):
            return rutas_orig, [], [], self.getCostoAsociado()

        return rutas, ADD[:1], DROP, costo_solucion
Example #16
0
    def swap_4opt(self, lista_permitidos, ind_random, rutas_orig):
        sol_factible = False
        rutas = rutas_orig
        costo_solucion = self.getCostoAsociado()
        ADD = []
        DROP = []
        while(not sol_factible and len(ind_random)>=1):
            ADD = []
            DROP = []
            costo_solucion = self.getCostoAsociado()
            arista_ini = lista_permitidos[ind_random[-1]]
            ind_random.pop()
            ADD.append(arista_ini)

            V_origen = arista_ini.getOrigen()
            V_destino = arista_ini.getDestino()
            
            rutas = copy.deepcopy(rutas_orig)
            
            ind_rutas, ind_A = self.getPosiciones(V_origen, V_destino, rutas_orig)
            
            #Cada ruta de al menos 4 aristas o 3 clientes. Si a o b estan al final: los intercambio
            if(ind_rutas[0]!=ind_rutas[1]):
                r1 = rutas[ind_rutas[0]]
                r2 = rutas[ind_rutas[1]]
                costo_solucion -= r1.getCostoAsociado()+r2.getCostoAsociado()
                #Sol: 1-2-3-a-4   1-5-6-7-8-b
                #1-2-3-a-b    1-5-6-7-8-4   ADD (a,b)(8,4) DROP (a,4)(8,b)
                #Sol: 1-2-3-4-a   1-5-6-7-8-b
                #1-2-3-4-a-b    1-5-6-7-8   ADD (a,b)(8,1) DROP (a,1)(8,b)
                #Sol: 1-2-3-4-a   1-5-6-7-b-8
                #1-2-3-4-a-b    1-5-6-7-8   ADD (a,b)(7,8) DROP (a,1)(7,b)(b,8)
                #Sol: 1-a-2-3-4   1-5-6-7-8-b
                #(a,b)
                #Sol_nueva:    1-a-b-3-4         1-5-6-7-8-2
                #=>   DROP                ADD
                #     (a,2) que ahora es (a,b)
                #     (2,3) que ahora es (b,3)
                #     (8,b) que ahora es (8,2)
                #     (b,1) que ahora es (2,1)
                #ind_A[0]=1    ind_A[1]=4
                #Descompongo las aristas con respecto al vertice "a"
                #Ruta 1 y 2
                #1 y 3-4         1-5-6-7-8 y 1
                V_r1 = r1.getV()
                V_r1.append(Vertice(1,0))
                if(V_origen == V_r1[-2]):
                    V_r1 = V_r1[::-1]
                    ind_A[0] = 1
                
                V_r2 = r2.getV()
                V_r2.append(Vertice(1,0))
                if(V_destino == V_r2[-2]):
                    V_r2 = V_r2[::-1]
                    ind_A[1] = 0
                
                V_r1_left = V_r1[:ind_A[0]+1]
                V_r1_right = V_r1[ind_A[0]+2:]
                V_r2_left = V_r2[:ind_A[1]+1]
                V_r2_right = V_r2[ind_A[1]+2:]
                
                #Obtengo las aristas que se eliminan y las que se añaden
                #3 ADD's y 4 DROP's
                #1er DROP
                V_origen = V_r1[ind_A[0]]
                V_destino = V_r1[ind_A[0]+1]
                peso = self._matrizDistancias[V_origen.getValue()-1][V_destino.getValue()-1]
                A_r1_drop1 = Arista(V_origen, V_destino, peso)
                #2do DROP
                V_origen = V_destino
                V_destino = V_r1[ind_A[0]+2]
                peso = self._matrizDistancias[V_origen.getValue()-1][V_destino.getValue()-1]
                A_r1_drop2 = Arista(V_origen, V_destino, peso)
                
                #2do ADD
                V_origen = ADD[0].getDestino()
                peso = self._matrizDistancias[V_origen.getValue()-1][V_destino.getValue()-1]
                A_r1_add2 = Arista(V_origen, V_destino, peso)
                
                #3er DROP
                V_origen = V_r2[ind_A[1]]
                V_destino = V_r2[ind_A[1]+1]
                peso = self._matrizDistancias[V_origen.getValue()-1][V_destino.getValue()-1]
                A_r2_drop1 = Arista(V_origen, V_destino, peso)
                #3er ADD
                V_destino = V_r1[ind_A[0]+1]
                peso = self._matrizDistancias[V_origen.getValue()-1][V_destino.getValue()-1]
                A_r2_add1 = Arista(V_origen, V_destino, peso)
                
                #4to DROP
                V_origen = V_r2[ind_A[1]+1]
                V_destino = V_r2[ind_A[1]+2]
                peso = self._matrizDistancias[V_origen.getValue()-1][V_destino.getValue()-1]
                A_r2_drop2 = Arista(V_origen, V_destino, peso)
                #4to ADD
                V_origen = A_r2_add1.getDestino()
                peso = self._matrizDistancias[V_origen.getValue()-1][V_destino.getValue()-1]
                A_r2_add2 = Arista(V_origen, V_destino, peso)
                
                DROP.append(A_r1_drop1)
                DROP.append(A_r1_drop2)
                DROP.append(A_r2_drop1)
                DROP.append(A_r2_drop2)

                ADD.append(A_r1_add2)
                ADD.append(A_r2_add1)
                ADD.append(A_r2_add2)

                V_r1_left.append(ADD[0].getDestino())
                V_r1_left.extend(V_r1_right)
                V_r2_left.append(ADD[2].getDestino())
                V_r2_left.extend(V_r2_right)
                
                cap_r1 = r1.cargarDesdeSecuenciaDeVertices(V_r1_left[:-1])
                cap_r2 = r2.cargarDesdeSecuenciaDeVertices(V_r2_left[:-1])
                
                r1.setCapacidad(cap_r1)
                r2.setCapacidad(cap_r2)
                
                if(cap_r1 > self.__capacidadMax or cap_r2 > self.__capacidadMax):
                    rutas = []
                else:
                    sol_factible = True
                    costo_solucion += r1.getCostoAsociado() + r2.getCostoAsociado()
            #4-opt en la misma ruta. Condicion: Deben haber 4 aristas de separacion entre a y b, si no se realiza 2-opt
            else:
                #1-2-a-3-4-5-6-b-7
                #(a,b)  1-2-a-b-4-5-6-3-7
                #=>  ADD     DROP
                #   (a,b)   (a,3)
                #   (b,4)   (3,4)
                #   (6,3)   (6,b)
                #   (3,7)   (b,7)
                r = rutas[ind_rutas[0]]
                costo_solucion -= r.getCostoAsociado()

                V_r = r.getV()
                V_r.append(Vertice(1,0))
                
                #Descompongo la ruta
                V_r_left = V_r[:ind_A[0]+1]                #1-2-a
                V_r_middle = V_r[ind_A[0]+2:ind_A[1]+1]    #3-4
                V_r_right = V_r[ind_A[1]+2:]               #b-5-6-7
                
                A_r_drop1 = r.getA()[ind_A[0]]
                A_r_drop2 = r.getA()[ind_A[0]+1]
                A_r_drop3 = r.getA()[ind_A[1]]
                A_r_drop4 = r.getA()[ind_A[1]+1]
                
                #Obtengo las otras aristas ADD
                V_origen = V_destino
                V_destino = A_r_drop1.getDestino()
                peso = self._matrizDistancias[V_origen.getValue()-1][V_destino.getValue()-1]
                A_r_add1 = Arista(V_origen,V_destino, peso)
                
                V_origen = A_r_drop3.getOrigen()
                V_destino = A_r_drop1.getDestino()
                peso = self._matrizDistancias[V_origen.getValue()-1][V_destino.getValue()-1]
                A_r_add2 = Arista(V_origen,V_destino, peso)
                
                V_origen = V_destino
                V_destino = V_r_right[0]
                peso = self._matrizDistancias[V_origen.getValue()-1][V_destino.getValue()-1]
                A_r_add3 = Arista(V_origen,V_destino, peso)
                
                if(len(V_r_middle)>=2):
                    ADD.append(A_r_add1)
                    ADD.append(A_r_add2)
                    ADD.append(A_r_add3)
                    DROP.append(A_r_drop1)
                    DROP.append(A_r_drop2)
                    DROP.append(A_r_drop3)
                    DROP.append(A_r_drop4)
                else:
                    #print("Se aplica 2-opt ya que solo existe una arista intermedia para hacer el swap")
                    ADD.append(A_r_add3)
                    DROP.append(A_r_drop1)
                    DROP.append(A_r_drop4)

                V_r_left.append(A_r_drop4.getOrigen())
                V_r_left.extend(V_r_middle)
                V_r_left.append(A_r_add3.getOrigen())
                V_r_left.extend(V_r_right)
                V_r = V_r_left[:-1]
                
                cap = r.cargarDesdeSecuenciaDeVertices(V_r)
                r.setCapacidad(cap)
                if(cap > self.__capacidadMax):
                    rutas = []
                else:
                    sol_factible = True
                    costo_solucion += r.getCostoAsociado()
        #Fin del while (se encontro una solucion factible)
        if (not sol_factible):
            return rutas_orig, [], [], self.getCostoAsociado()

        return rutas, ADD[:1], DROP, costo_solucion
Example #17
0
 def __init__(self, origen, destino, peso):
     Arista.__init__(self, origen, destino)
     self.peso = peso
Example #18
0
from Grafo import Grafo
from Nodo import Nodo
from Arista import Arista

grafo = Grafo()

A = Nodo("A")
B = Nodo("B")
C = Nodo("C")
D = Nodo("D")
E = Nodo("E")
F = Nodo("F")

AB = Arista(A, B)
AC = Arista(A, C)
AD = Arista(A, D)
CE = Arista(C, E)
DF = Arista(D, F)
FC = Arista(F, C)

A.add_edge(AB)
A.add_edge(AC)
A.add_edge(AD)
C.add_edge(CE)
D.add_edge(DF)
F.add_edge(FC)

grafo.add_node(A)
grafo.add_node(B)
grafo.add_node(C)
grafo.add_node(D)
Example #19
0
from Grafo import Grafo
from Nodo import Nodo
from Arista import Arista

grafo = Grafo()

A = Nodo("A")
B = Nodo("B")
C = Nodo("C")
D = Nodo("D")
E = Nodo("E")

AB = Arista(A, B, 2)
AC = Arista(A, C, 5)
AE = Arista(A, E, 6)
BC = Arista(B, C, 5)
BD = Arista(B, D, 3)
BE = Arista(B, E, 2)
EC = Arista(E, C, 4)
DE = Arista(D, E, 4)

A.add_edge(AB)
A.add_edge(AC)
A.add_edge(AE)

B.add_edge(BD)
B.add_edge(BE)
B.add_edge(BC)

E.add_edge(EC)
D.add_edge(DE)
Example #20
0
def duplicar_camino(mst):
    return_mst = set(mst)
    for arista in mst:
        nueva_arista = Arista(arista.dst, arista.src, arista.weight)
        return_mst.add(nueva_arista)
    return return_mst
Example #21
0
from Esquina import Esquina
from Arista import Arista

#e = Esquina('0', '1', '2')
#a = Arista('3', '6')
e1 = Esquina()
a1 = Arista()
#print("La arista ejemplo tiene los colores: " + a.getColor1() + ' ' + a.getColor2())
#print("La esquina ejemplo tiene los colores: " + e.getColor1() + ' ' + e.getColor2() + ' ' + e.getColor3())
print("Esquina por defecto: " + e1.getColor1() + ' ' + e1.getColor2() + ' ' + e1.getColor3())
print("Arista por defecto: " + e1.getColor1() + ' ' + e1.getColor2())
Example #22
0
from Grafo import Grafo
from Nodo import Nodo
from Arista import Arista

grafo = Grafo()

A = Nodo("A")
B = Nodo("B")
C = Nodo("C")
D = Nodo("D")
E = Nodo("E")
F = Nodo("F")


AB = Arista(A,B)
AC = Arista(A,C)
AD = Arista(A,D)
CE = Arista(C,E)
CF = Arista(C,F)
DF = Arista(D,F)



A.add_edge(AB)
A.add_edge(AC)
A.add_edge(AD)
C.add_edge(CE)
D.add_edge(CF)
F.add_edge(DF)
	def __init__(self, origen, destino, peso):
		Arista.__init__(self, origen, destino)
		self.peso = peso
Example #24
0
    def swap_3opt(self, lista_permitidos, ind_random, rutas_orig):
        sol_factible = False
        costo_solucion = self.getCostoAsociado()
        rutas = rutas_orig
        ADD = []
        DROP = []
        
        while(not sol_factible and len(ind_random)>=1):
            ADD = []
            DROP = []
            costo_solucion = self.getCostoAsociado()
            arista_ini = lista_permitidos[ind_random[-1]]
            ind_random.pop()
            ADD.append(arista_ini)

            V_origen = arista_ini.getOrigen()
            V_destino = arista_ini.getDestino()
            
            rutas = copy.deepcopy(rutas_orig)

            ind_rutas, ind_A = self.getPosiciones(V_origen, V_destino, rutas_orig)
            if(ind_rutas[0]!=ind_rutas[1]):
                r1 = rutas[ind_rutas[0]]
                r2 = rutas[ind_rutas[1]]
                costo_solucion -= r1.getCostoAsociado() + r2.getCostoAsociado()
                #Descompongo las aristas con respecto al vertice "a"
                # 1-2 y 3-4         1-5 y 6-7-8
                A_r1_left = r1.getA()[:ind_A[0]-1]
                A_r1_right = r1.getA()[ind_A[0]+1:]
                
                #Obtengo las aristas que se eliminan y las que se añaden
                #DROP 1 y 2
                A_r1_drop1 = r1.getA()[ind_A[0]-1]
                A_r1_drop2 = r1.getA()[ind_A[0]]
                
                #ADD 1
                V_origen = r1.getA()[ind_A[0]-1].getOrigen()
                V_destino = r1.getA()[ind_A[0]].getDestino()
                peso = self._matrizDistancias[V_origen.getValue()-1][V_destino.getValue()-1]
                A_r1_add = Arista(V_origen, V_destino, peso)
                
                #Ruta 2
                A_r2_left = r2.getA()[:ind_A[1]]
                A_r2_drop = r2.getA()[ind_A[1]]
                A_r2_right = r2.getA()[ind_A[1]+1:]
                
                V_origen = r2.getA()[ind_A[1]].getOrigen()
                V_destino = r1.getA()[ind_A[0]-1].getDestino()
                peso = self._matrizDistancias[V_origen.getValue()-1][V_destino.getValue()-1]
                A_r2_add = Arista(V_origen, V_destino, peso)
                
                DROP.append(A_r1_drop1)
                DROP.append(A_r1_drop2)
                DROP.append(A_r2_drop)

                ADD.append(A_r1_add)
                ADD.append(A_r2_add)

                A_r1_left.append(ADD[1])
                A_r1_left.extend(A_r1_right)
                A_r2_left.append(ADD[2])
                A_r2_left.append(ADD[0])
                A_r2_left.extend(A_r2_right)
                
                cap_r1 = r1.cargaDesdeAristas(A_r1_left)
                cap_r2 = r2.cargaDesdeAristas(A_r2_left)
                r1.setCapacidad(cap_r1)
                r2.setCapacidad(cap_r2)
                
                if(cap_r1 > self.__capacidadMax or cap_r2 > self.__capacidadMax):
                    rutas = []
                else:
                    sol_factible = True
                    costo_solucion += r1.getCostoAsociado() + r2.getCostoAsociado()
            #3-opt en la misma ruta
            else:
                #1-2-a-3-4-b-5-6-7
                #(a,b)  1-2-a-b-3-4-5-6-7
                #=>  ADD     DROP
                #   (a,b)   (4,b)
                #   (4,5)   (5,b)
                #   (b,3)   (a,3)
                r = rutas[ind_rutas[0]]
                costo_solucion -= r.getCostoAsociado()
                
                #Descompongo la ruta
                V_r_left = r.getV()[:ind_A[0]+1]                #1-2-a
                V_r_middle = r.getV()[ind_A[0]+1:ind_A[1]+1]    #3-4
                V_r_right = r.getV()[ind_A[1]+1:]               #b-5-6-7
                V_r_right = V_r_right[1:]                       #5-6-7   *No puedo hacer r.getV()[ind_A[1]+2:] xq el indice podria exceder el tam 
                V_r_right.append(Vertice(1,0))                  #5-6-7-1

                A_r_drop1 = r.getA()[ind_A[0]]
                A_r_drop2 = r.getA()[ind_A[1]+1]
                A_r_drop3 = r.getA()[ind_A[1]]

                #Obtengo las otra arista ADD
                try:
                    V_origen = V_r_middle[-1]
                except ValueError:
                    print("error: "+str(arista_ini))
                    print(str(r))
                    print(str(V_r_middle))
                V_destino = V_r_right[0]
                peso = self._matrizDistancias[V_origen.getValue()-1][V_destino.getValue()-1]
                A_r_add1 = Arista(V_origen,V_destino, peso)
                
                V_origen = r.getV()[ind_A[1]+1]
                V_destino = V_r_middle[0]
                peso = self._matrizDistancias[V_origen.getValue()-1][V_destino.getValue()-1]
                A_r_add2 = Arista(V_origen,V_destino, peso)
                if(peso>=999999999999):
                    print("\n"+str(ind_A))
                    print("distintas rutas")
                    print("A_r_add2. Arista azar: "+str(arista_ini))
                    print("rutas: "+str(rutas))
                    print("V_origen: "+str(V_origen))
                    print(V_origen.getValue()-1)
                    print("V_destino: "+str(V_destino))
                    print(V_destino.getValue()-1)
                    print("Matriz: "+str(self._matrizDistancias[V_origen.getValue()-1][V_destino.getValue()-1]))

                ADD.append(A_r_add1)                
                DROP.append(A_r_drop1)
                DROP.append(A_r_drop2)

                if(len(V_r_middle)>1):
                    ADD.append(A_r_add2)
                    DROP.append(A_r_drop3)
                #else:
                #    print("Se aplica 2-opt ya que solo existe una arista intermedia para hacer el swap")

                #print("DROP: "+str(DROP))
                #print("ADD: "+str(ADD))

                V_r_left.append(r.getV()[ind_A[1]+1])
                V_r_left.extend(V_r_middle)
                V_r_left.extend(V_r_right)
                V_r = V_r_left[:-1]
                
                cap = r.cargarDesdeSecuenciaDeVertices(V_r)
                r.setCapacidad(cap)
                if(cap > self.__capacidadMax):
                    rutas = []
                else:
                    sol_factible = True 
                    costo_solucion += r.getCostoAsociado()
        #Fin del while (se encontro una solucion factible)
        if (not sol_factible):
            return rutas_orig, [], [], self.getCostoAsociado()

        return rutas, ADD[:1], DROP, costo_solucion
Example #25
0
    def openbinDialog(self):
        '''
        Funcion que permite abrir un archivo de texto
        con formato del programa Rutas Maritimas, el metodo
        permite cargar un archivo de tipos *txt o *bin  cuando
        se carga un archivo, el grafo que se haya trabajado
        hasta el momento se eliminara, y solamente aparecera el nuevo grafo
        con el que se podra seguir trabajando normalmente
         '''
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        filename, _ = QFileDialog.getOpenFileName(
            self,
            "QFileDialog.getOpenFileName()",
            "",
            "Archivos Binarios (*.bin)",
            options=options)
        if filename:
            self.limpiarLienzo()
            regTree = open(filename, "rb")
            self.numerodenodos = regTree.readline()
            self.numerodenodos = int(self.numerodenodos.replace('\n', ''))
            i = 1
            for line in regTree:
                line = line.replace("\n", "")
                if line != '':
                    line = line.split("|")
                    if i <= self.numerodenodos + 1:
                        if len(line) == 3:
                            x = int(line[0])
                            y = int(line[1])
                            nombre = line[2]
                            punto = Punto(x, y, nombre)
                            self.grafo.ingresarNodo(nombre)
                            self.puntos.append(punto)
                    if self.numerodenodos < i:
                        x1 = int(line[0])
                        y1 = int(line[1])
                        x2 = int(line[2])
                        y2 = int(line[3])
                        peso = float(line[4])
                        nombre1 = line[5]
                        nombre2 = line[6]
                        punto1 = Punto(x1, y1, nombre1)
                        punto2 = Punto(x2, y2, nombre2)
                        arista = Arista(punto1, punto2, peso)
                        self.aristas.append(arista)
                        self.grafo.adicionarEnlace(nombre1, nombre2, peso)
                i = i + 1
            regTree.close()
            self.labelMessage.setText('Grafo abierto correctamente')
            self.nombrePuerto.clear()
            nuevalista = listaPuertos([])
            for n in self.puntos:
                if n.nombre in nuevalista:
                    del nuevalista[nuevalista.index(n.nombre)]
            self.nombrePuerto.addItems(nuevalista)

        self.lienzoGraphic.repaint()
        self.aplicarKruskal.setEnabled(True)
        if len(self.puntos) > 1:
            self.crearArista.setEnabled(True)
        self.nuevoGrafo.setEnabled(True)