示例#1
0
def SineCosine_SCP(id,instance_file,instance_dir,population,maxIter,discretizacionScheme,repair):

    print(f'repair: {repair}')
    instance_path = workdirInstance + instance_dir + instance_file

    if not os.path.exists(instance_path):
        print(f'No se encontró la instancia: {instance_path}')
        return False

    instance = Instance.Read(instance_path)

    problemaGPU = SCPProblem.SCPProblem(instance_path)
    pondRestricciones = 1/np.sum(problemaGPU.instance.get_r(), axis=1)

    matrizCobertura = np.array(instance.get_r())
    vectorCostos = np.array(instance.get_c())

    dim = len(vectorCostos)
    pob = population
    maxIter = maxIter
    DS = discretizacionScheme #[v1,Standard]
    a = 2

    #Variables de diversidad
    diversidades = []
    maxDiversidades = np.zeros(7) #es tamaño 7 porque calculamos 7 diversidades
    PorcentajeExplor = []
    PorcentajeExplot = []
    state = []

    #Generar población inicial
    poblacion = np.random.uniform(low=-1.0, high=1.0, size=(pob,dim))
    matrixBin = np.zeros((pob,dim))
    fitness = np.zeros(pob)
    solutionsRanking = np.zeros(pob)
    matrixBin,fitness,solutionsRanking  = Problem.SCP(poblacion,matrixBin,solutionsRanking,vectorCostos,matrizCobertura,DS,repair,problemaGPU,pondRestricciones)
    diversidades, maxDiversidades, PorcentajeExplor, PorcentajeExplot, state = dv.ObtenerDiversidadYEstado(matrixBin,maxDiversidades)

    inicio = datetime.now()
    timerStartResult = time.time()
    memory = []
    for iter in range(0, maxIter):
        print(f'iter: {iter}')
        processTime = time.process_time()  

        # if iter == 0:
        #     if not connect.startEjecucion(id,datetime.now(),'ejecutando'):
        #         return False
           

        timerStart = time.time()
        
        r1 = a - iter * (a/maxIter)
        r4 = np.random.uniform(low=0.0,high=1.0, size=poblacion.shape[0])
        r2 = (2*np.pi) * np.random.uniform(low=0.0,high=1.0, size=poblacion.shape)
        r3 = np.random.uniform(low=0.0,high=2.0, size=poblacion.shape)
        bestRowAux = solutionsRanking[0]
        Best = poblacion[bestRowAux]
        BestBinary = matrixBin[bestRowAux]
        BestFitness = np.min(fitness)
        poblacion[r4<0.5] = poblacion[r4<0.5] + np.multiply(r1,np.multiply(np.sin(r2[r4<0.5]),np.abs(np.multiply(r3[r4<0.5],Best)-poblacion[r4<0.5])))
        poblacion[r4>=0.5] = poblacion[r4>=0.5] + np.multiply(r1,np.multiply(np.cos(r2[r4>=0.5]),np.abs(np.multiply(r3[r4>=0.5],Best)-poblacion[r4>=0.5])))
        # poblacion[bestRow] = Best
        
        #Binarizamos y evaluamos el fitness de todas las soluciones de la iteración t
        matrixBin,fitness,solutionsRanking = Problem.SCP(poblacion,matrixBin,solutionsRanking,vectorCostos,matrizCobertura,DS,repair,problemaGPU,pondRestricciones)


        #Conservo el Best
        if fitness[bestRowAux] > BestFitness:
            fitness[bestRowAux] = BestFitness
            matrixBin[bestRowAux] = BestBinary

        diversidades, maxDiversidades, PorcentajeExplor, PorcentajeExplot, state = dv.ObtenerDiversidadYEstado(matrixBin,maxDiversidades)
        BestFitnes = str(np.min(fitness))

        walltimeEnd = np.round(time.time() - timerStart,6)
        processTimeEnd = np.round(time.process_time()-processTime,6) 

        dataIter = {
            "id_ejecucion": id,
            "numero_iteracion":iter,
            "fitness_mejor": BestFitnes,
            "parametros_iteracion": json.dumps({
                "fitness": BestFitnes,
                "clockTime": walltimeEnd,
                "processTime": processTimeEnd,
                "DS":DS,
                "Diversidades":  str(diversidades),
                "PorcentajeExplor": str(PorcentajeExplor)
                #"PorcentajeExplot": str(PorcentajeExplot),
                #"state": str(state)
                })
                }

        memory.append(dataIter)
       

        if iter % 100 == 0:
            memory = connect.insertMemory(memory)

    # Si es que queda algo en memoria para insertar
    if(len(memory)>0):
        memory = connect.insertMemory(memory)

    #Actualizamos la tabla resultado_ejecucion, sin mejor_solucion
    memory2 = []
    fin = datetime.now()    
    dataResult = {
        "id_ejecucion": id,
        "fitness": BestFitnes,
        "inicio": inicio,
        "fin": fin
        }
    memory2.append(dataResult)
    dataResult = connect.insertMemoryBest(memory2)

    # Update ejecucion
    if not connect.endEjecucion(id,datetime.now(),'terminado'):
        return False

    return True
示例#2
0
def HHO_SCP(id, instance_file, instance_dir, population, maxIter,
            discretizacionScheme, repair):

    print(f'repair: {repair}')
    instance_path = workdirInstance + instance_dir + instance_file

    if not os.path.exists(instance_path):
        print(f'No se encontró la instancia: {instance_path}')
        return False

    instance = Instance.Read(instance_path)

    problemaGPU = SCPProblem.SCPProblem(instance_path)
    pondRestricciones = 1 / np.sum(problemaGPU.instance.get_r(), axis=1)

    matrizCobertura = np.array(instance.get_r())
    vectorCostos = np.array(instance.get_c())

    dim = len(vectorCostos)
    pob = population
    maxIter = maxIter
    DS = discretizacionScheme  #[v1,Standard]

    #Variables de diversidad
    diversidades = []
    maxDiversidades = np.zeros(
        7)  #es tamaño 7 porque calculamos 7 diversidades
    PorcentajeExplor = []
    PorcentajeExplot = []
    state = []

    #Generar población inicial
    poblacion = np.random.uniform(low=-1.0, high=1.0, size=(pob, dim))
    matrixBin = np.zeros((pob, dim))
    fitness = np.zeros(pob)
    solutionsRanking = np.zeros(pob)
    matrixBin, fitness, solutionsRanking = Problem.SCP(
        poblacion, matrixBin, solutionsRanking, vectorCostos, matrizCobertura,
        DS, repair, problemaGPU, pondRestricciones)
    diversidades, maxDiversidades, PorcentajeExplor, PorcentajeExplot, state = dv.ObtenerDiversidadYEstado(
        matrixBin, maxDiversidades)

    #Parámetros fijos de HHO
    beta = 1.5  #Escalar según paper
    sigma = (math.gamma(1 + beta) * math.sin(math.pi * beta / 2) / (math.gamma(
        (1 + beta) / 2) * beta * 2**((beta - 1) / 2)))**(1 / beta)  #Escalar
    LB = -10  #Limite inferior de los valores continuos
    UB = 10  #Limite superior de los valores continuos

    inicio = datetime.now()
    timerStartResult = time.time()
    memory = []

    for iter in range(0, maxIter):
        #print(iter)
        processTime = time.process_time()

        timerStart = time.time()

        #HHO
        E0 = np.random.uniform(low=-1.0, high=1.0,
                               size=pob)  #vector de tam Pob
        E = 2 * E0 * (1 - (iter / maxIter))  #vector de tam Pob
        Eabs = np.abs(E)

        q = np.random.uniform(low=0.0, high=1.0, size=pob)  #vector de tam Pob
        r = np.random.uniform(low=0.0, high=1.0, size=pob)  #vector de tam Pob

        Xm = np.mean(poblacion, axis=0)

        bestRowAux = solutionsRanking[0]
        Best = poblacion[bestRowAux]
        BestBinary = matrixBin[bestRowAux]
        BestFitness = np.min(fitness)

        #print(f'Eabs: {Eabs}')

        #ecu 1.1
        indexCond1_1 = np.intersect1d(
            np.argwhere(Eabs >= 1), np.argwhere(q >= 0.5)
        )  #Nos entrega los index de las soluciones a las que debemos aplicar la ecu 1.1
        #print("indexCond1_1")
        if indexCond1_1.shape[0] != 0:
            Xrand = poblacion[np.random.randint(
                low=0, high=pob, size=indexCond1_1.shape[0]
            )]  #Me entrega un conjunto de soluciones rand de tam indexCond1_1.shape[0] (osea los que cumplen la cond11)

            poblacion[indexCond1_1] = Xrand - np.multiply(
                np.random.uniform(
                    low=0.0, high=1.0, size=indexCond1_1.shape[0]),
                np.abs(Xrand - (2 * np.multiply(
                    np.random.uniform(
                        low=0.0, high=1.0, size=indexCond1_1.shape[0]),
                    poblacion[indexCond1_1].T).T)).T
            ).T  #Aplico la ecu 1.1 solamente a las que cumplen las condiciones np.argwhere(Eabs>=1),np.argwhere(q>=0.5)

        #ecu 1.2
        indexCond1_2 = np.intersect1d(
            np.argwhere(Eabs >= 1), np.argwhere(q < 0.5)
        )  #Nos entrega los index de las soluciones a las que debemos aplicar la ecu 1.2
        #print("indexCond1_2")
        if indexCond1_2.shape[0] != 0:

            array_Xm = np.zeros(poblacion[indexCond1_2].shape)
            array_Xm = array_Xm + Xm

            poblacion[indexCond1_2] = ((Best - array_Xm).T - np.multiply(
                np.random.uniform(
                    low=0.0, high=1.0, size=indexCond1_2.shape[0]),
                (LB + np.random.uniform(
                    low=0.0, high=1.0, size=indexCond1_2.shape[0]) *
                 (UB - LB)))).T

        #ecu 4
        indexCond4 = np.intersect1d(
            np.argwhere(Eabs >= 0.5), np.argwhere(r >= 0.5)
        )  #Nos entrega los index de las soluciones a las que debemos aplicar la ecu 4
        #print("indexCond4")
        if indexCond4.shape[0] != 0:

            array_Xm = np.zeros(poblacion[indexCond4].shape)
            array_Xm = array_Xm + Xm

            poblacion[indexCond4] = (
                (array_Xm - poblacion[indexCond4]) - np.multiply(
                    E[indexCond4],
                    np.abs(
                        np.multiply(
                            2 * (1 - np.random.uniform(
                                low=0.0, high=1.0, size=indexCond4.shape[0])),
                            array_Xm.T).T - poblacion[indexCond4]).T).T)

        #ecu 10
        indexCond10 = np.intersect1d(
            np.argwhere(Eabs >= 0.5), np.argwhere(r < 0.5)
        )  #Nos entrega los index de las soluciones a las que debemos aplicar la ecu 10
        if indexCond10.shape[0] != 0:
            #print("indexCond10")
            y10 = poblacion
            #ecu 7

            Array_y10 = np.zeros(poblacion[indexCond10].shape)
            Array_y10 = Array_y10 + y10[bestRowAux]

            y10[indexCond10] = Array_y10 - np.multiply(
                E[indexCond10],
                np.abs(
                    np.multiply(
                        2 * (1 - np.random.uniform(
                            low=0.0, high=1.0, size=indexCond10.shape[0])),
                        Array_y10.T).T - Array_y10).T).T

            #ecu 8
            z10 = y10
            S = np.random.uniform(low=0.0,
                                  high=1.0,
                                  size=(y10[indexCond10].shape))
            LF = np.divide(
                (0.01 * np.random.uniform(
                    low=0.0, high=1.0, size=(y10[indexCond10].shape)) * sigma),
                np.power(
                    np.abs(
                        np.random.uniform(low=0.0,
                                          high=1.0,
                                          size=(y10[indexCond10].shape))),
                    (1 / beta)))

            z10[indexCond10] = y10[indexCond10] + np.multiply(LF, S)

            #evaluar fitness de ecu 7 y 8
            Fy10 = solutionsRanking
            Fy10[indexCond10] = Problem.SCP(y10[indexCond10],
                                            matrixBin[indexCond10],
                                            solutionsRanking[indexCond10],
                                            vectorCostos, matrizCobertura, DS,
                                            repair, problemaGPU,
                                            pondRestricciones)[1]

            Fz10 = solutionsRanking
            Fz10[indexCond10] = Problem.SCP(z10[indexCond10],
                                            matrixBin[indexCond10],
                                            solutionsRanking[indexCond10],
                                            vectorCostos, matrizCobertura, DS,
                                            repair, problemaGPU,
                                            pondRestricciones)[1]

            #ecu 10.1
            indexCond101 = np.intersect1d(
                indexCond10, np.argwhere(Fy10 < solutionsRanking)
            )  #Nos entrega los index de las soluciones a las que debemos aplicar la ecu 10.1
            if indexCond101.shape[0] != 0:
                #print("indexCond101")
                poblacion[indexCond101] = y10[indexCond101]

            #ecu 10.2
            indexCond102 = np.intersect1d(
                indexCond10, np.argwhere(Fz10 < solutionsRanking)
            )  #Nos entrega los index de las soluciones a las que debemos aplicar la ecu 10.2
            if indexCond102.shape[0] != 0:
                #print("indexCond102")
                poblacion[indexCond102] = z10[indexCond102]

            # ecu 6
            indexCond6 = np.intersect1d(
                np.argwhere(Eabs < 0.5), np.argwhere(r >= 0.5)
            )  #Nos entrega los index de las soluciones a las que debemos aplicar la ecu 6
            if indexCond6.shape[0] != 0:
                #print("indexCond6")
                poblacion[indexCond6] = Best - np.multiply(
                    E[indexCond6],
                    np.abs(Best - poblacion[indexCond6]).T).T

            #ecu 11
            indexCond11 = np.intersect1d(
                np.argwhere(Eabs < 0.5), np.argwhere(r < 0.5)
            )  #Nos entrega los index de las soluciones a las que debemos aplicar la ecu 11
            if indexCond11.shape[0] != 0:
                #print("indexCond11")
                #ecu 12
                y11 = poblacion
                array_Xm = np.zeros(poblacion[indexCond11].shape)
                array_Xm = array_Xm + Xm

                y11[indexCond11] = y11[bestRowAux] - np.multiply(
                    E[indexCond11],
                    np.abs(
                        np.multiply(
                            2 *
                            (1 - np.random.uniform(low=0.0,
                                                   high=1.0,
                                                   size=poblacion[indexCond11].
                                                   shape)), y11[bestRowAux]) -
                        array_Xm).T).T

                #ecu 13
                z11 = y11
                S = np.random.uniform(low=0.0, high=1.0, size=(y11.shape))
                LF = np.divide(
                    (0.01 *
                     np.random.uniform(low=0.0, high=1.0, size=(y11.shape)) *
                     sigma),
                    np.power(
                        np.abs(
                            np.random.uniform(low=0.0,
                                              high=1.0,
                                              size=(y11.shape))), (1 / beta)))
                z11[indexCond11] = y11[indexCond11] + np.multiply(
                    S[indexCond11], LF[[indexCond11]])

                #evaluar fitness de ecu 12 y 13
                if solutionsRanking is None:
                    solutionsRanking = np.ones(pob) * 999999

                Fy11 = solutionsRanking
                Fy11[indexCond11] = Problem.SCP(y11[indexCond11],
                                                matrixBin[indexCond11],
                                                solutionsRanking[indexCond11],
                                                vectorCostos, matrizCobertura,
                                                DS, repair, problemaGPU,
                                                pondRestricciones)[1]

                Fz11 = solutionsRanking
                Fz11[indexCond11] = Problem.SCP(z11[indexCond11],
                                                matrixBin[indexCond11],
                                                solutionsRanking[indexCond11],
                                                vectorCostos, matrizCobertura,
                                                DS, repair, problemaGPU,
                                                pondRestricciones)[1]

                #ecu 11.1
                indexCond111 = np.intersect1d(
                    indexCond11, np.argwhere(Fy11 < solutionsRanking)
                )  #Nos entrega los index de las soluciones a las que debemos aplicar la ecu 11.1
                if indexCond111.shape[0] != 0:
                    poblacion[indexCond111] = y11[indexCond111]

                #ecu 11.2
                indexCond112 = np.intersect1d(
                    indexCond11, np.argwhere(Fz11 < solutionsRanking)
                )  #Nos entrega los index de las soluciones a las que debemos aplicar la ecu 11.2
                if indexCond112.shape[0] != 0:
                    poblacion[indexCond112] = z11[indexCond112]

        #Binarizamos y evaluamos el fitness de todas las soluciones de la iteración t
        matrixBin, fitness, solutionsRanking = Problem.SCP(
            poblacion, matrixBin, solutionsRanking, vectorCostos,
            matrizCobertura, DS, repair, problemaGPU, pondRestricciones)

        #Conservo el Best
        if fitness[bestRowAux] > BestFitness:
            fitness[bestRowAux] = BestFitness
            matrixBin[bestRowAux] = BestBinary

        diversidades, maxDiversidades, PorcentajeExplor, PorcentajeExplot, state = dv.ObtenerDiversidadYEstado(
            matrixBin, maxDiversidades)
        BestFitnes = str(np.min(fitness))

        walltimeEnd = np.round(time.time() - timerStart, 6)
        processTimeEnd = np.round(time.process_time() - processTime, 6)

        dataIter = {
            "id_ejecucion":
            id,
            "numero_iteracion":
            iter,
            "fitness_mejor":
            BestFitnes,
            "parametros_iteracion":
            json.dumps({
                "fitness": BestFitnes,
                "clockTime": walltimeEnd,
                "processTime": processTimeEnd,
                "DS": DS,
                "Diversidades": str(diversidades),
                "PorcentajeExplor": str(PorcentajeExplor)
                #"PorcentajeExplot": str(PorcentajeExplot),
                #"state": str(state)
            })
        }

        memory.append(dataIter)

        if iter % 100 == 0:
            memory = connect.insertMemory(memory)

    # Si es que queda algo en memoria para insertar
    if (len(memory) > 0):
        memory = connect.insertMemory(memory)

    #Actualizamos la tabla resultado_ejecucion, sin mejor_solucion
    memory2 = []
    fin = datetime.now()
    dataResult = {
        "id_ejecucion": id,
        "fitness": BestFitnes,
        "inicio": inicio,
        "fin": fin
    }
    memory2.append(dataResult)
    dataResult = connect.insertMemoryBest(memory2)

    # Update ejecucion
    if not connect.endEjecucion(id, datetime.now(), 'terminado'):
        return False

    return True
    def HH(self):

        for iter in range(0,self.iterMax):

            #print("----------- iter "+str(iter)+" -----------------------")

            timerStart = time.time()

            for ant in range(0,self.ants):

                #Update pheromona
                self.Pheromona(iter)

                #Seleccion esquema segun Probs
                esquema = self.seleccionRuleta(iter,ant)


                ############################### GWO #######################################################

                for lobo in range(0, self.Lobos):

                    # F.O por cada lobo
                    self.posLobos[lobo, :], fitness = SCP.SCP(self.posLobos[lobo, :], self.vectorCostos, self.matrizCobertura, self.DS_actions[esquema])

                    # Actualizamos alpha,beta, delta
                    if fitness < self.Alpha_score:
                        self.Alpha_score = fitness;
                        self.Alpha_pos = self.posLobos[lobo, :].copy()

                    if (fitness > self.Alpha_score and fitness < self.Beta_score):
                        self.Beta_score = fitness
                        self.Beta_pos = self.posLobos[lobo, :].copy()

                    if (fitness > self.Alpha_score and fitness > self.Beta_score and fitness < self.Delta_score):
                        self.Delta_score = fitness
                        self.Delta_pos = self.posLobos[lobo, :].copy()

                    # parametro linealmente decreciente  2->0
                a = 2 - iter * ((2) / self.iterMax);

                # Lobos
                for lobo in range(0, self.Lobos):
                    for j in range(0, self.dim):
                        r1 = np.random.uniform(0, 1)  # random [0,1]
                        r2 = np.random.uniform(0, 1)  # random [0,1]

                        A1 = 2 * a * r1 - a;  # Equation (3.3)
                        C1 = 2 * r2;  # Equation (3.4)

                        D_alpha = abs(C1 * self.Alpha_pos[j] - self.posLobos[lobo, j]);
                        X1 = self.Alpha_pos[j] - A1 * D_alpha;

                        r1 = np.random.uniform(0, 1)  # random [0,1]
                        r2 = np.random.uniform(0, 1)  # random [0,1]

                        A2 = 2 * a * r1 - a;
                        C2 = 2 * r2;

                        D_beta = abs(C2 * self.Beta_pos[j] - self.posLobos[lobo, j]);
                        X2 = self.Beta_pos[j] - A2 * D_beta;

                        r1 = np.random.uniform(0, 1)  # random [0,1]
                        r2 = np.random.uniform(0, 1)  # random [0,1]

                        A3 = 2 * a * r1 - a;
                        C3 = 2 * r2;

                        D_delta = abs(C3 * self.Delta_pos[j] - self.posLobos[lobo, j]);
                        X3 = self.Delta_pos[j] - A3 * D_delta;

                        self.posLobos[lobo, j] = (X1 + X2 + X3) / 3

                #solucion_bin, fitness = SCP.SCP(solucion_random, self.vectorCostos, self.matrizCobertura, self.DS_actions[esquema])

                if self.Metric_k[ant] > self.Alpha_score:
                    self.Metric_k[ant] = self.Alpha_score
                    self.X_tk[iter][ant][esquema] = 1


                if self.Alpha_score < self.bestMetric:
                    self.bestMetric = self.Alpha_score

            timeEnd = time.time()
            execution = round(timeEnd - timerStart, 2)

            linea_r = "SCP|AntHH-GWO|" \
                      + str(self.instancia) + "|" \
                      + str(self.Lobos) + "|" \
                      + str(self.run) + "|" \
                      + str(iter) + "|" \
                      + str(self.DS_actions[esquema]) + "|" \
                      + str(self.bestMetric) + "|" \
                      + str(execution)+ "|" \
                      + str(self.ants)

            if iter % 100 == 0:
                print(linea_r)

            f = open(self.rootdir + self.resultado, 'a')
            f.write(linea_r)
            f.write('\n')
            f.close();

        try:
            pushGithub.pushGithub(self.repo, self.resultado, 'Resultado final corrida ' + str(self.run))
        except:
            print("No se logró hacer push a github")

        return True
示例#4
0
def WOA_SCP(id,instance_file,instance_dir,population,maxIter,discretizacionScheme,repair):

    print(f'repair: {repair}')
    instance_path = workdirInstance + instance_dir + instance_file

    if not os.path.exists(instance_path):
        print(f'No se encontró la instancia: {instance_path}')
        return False

    instance = Instance.Read(instance_path)
    
    #RepairGPU
    problemaGPU = SCPProblem.SCPProblem(instance_path)
    pondRestricciones = 1/np.sum(problemaGPU.instance.get_r(), axis=1)

    matrizCobertura = np.array(instance.get_r())
    vectorCostos = np.array(instance.get_c())

    dim = len(vectorCostos)
    pob = population
    maxIter = maxIter
    DS = discretizacionScheme #[v1,Standard]

    #Variables de diversidad
    diversidades = []
    maxDiversidades = np.zeros(7) #es tamaño 7 porque calculamos 7 diversidades
    PorcentajeExplor = []
    PorcentajeExplot = []
    state = []

    #Generar población inicial
    poblacion = np.random.uniform(low=-1.0, high=1.0, size=(pob,dim))
    matrixBin = np.zeros((pob,dim))
    fitness = np.zeros(pob)
    solutionsRanking = np.zeros(pob)
    matrixBin,fitness,solutionsRanking  = Problem.SCP(poblacion,matrixBin,solutionsRanking,vectorCostos,matrizCobertura,DS,repair,problemaGPU,pondRestricciones)
    diversidades, maxDiversidades, PorcentajeExplor, PorcentajeExplot, state = dv.ObtenerDiversidadYEstado(matrixBin,maxDiversidades)

    #Parámetros fijos de WOA
    LB = -10 #Limite inferior de los valores continuos
    UB = 10 #Limite superior de los valores continuos
    b = 1 #Según código

    inicio = datetime.now()
    timerStartResult = time.time()
    memory = []

    for iter in range(0, maxIter):
        #print(iter)
        processTime = time.process_time()  
        timerStart = time.time()
        
        #WOA
        a = 2 - ((2*iter)/maxIter)
        A = np.random.uniform(low=-a,high=a,size=(pob,dim)) #vector rand de tam (pob,dim)
        Aabs = np.abs(A[0]) # Vector de A absoluto en tam pob
        C = np.random.uniform(low=0,high=2,size=(pob,dim)) #vector rand de tam (pob,dim)
        l = np.random.uniform(low=-1,high=1,size=(pob,dim)) #vector rand de tam (pob,dim)
        p = np.random.uniform(low=0,high=0.4,size=pob) #vector rand de tam pob ***

        bestRowAux = solutionsRanking[0]
        Best = poblacion[bestRowAux]
        BestBinary = matrixBin[bestRowAux]
        BestFitness = np.min(fitness)

        #ecu 2.1 Pero el movimiento esta en 2.2
        indexCond2_2 = np.intersect1d(np.argwhere(p<0.5),np.argwhere(Aabs<1)) #Nos entrega los index de las soluciones a las que debemos aplicar la ecu 2.2
        if indexCond2_2.shape[0] != 0:
            poblacion[indexCond2_2] = Best - np.multiply(A[indexCond2_2],np.abs(np.multiply(C[indexCond2_2],Best)-poblacion[indexCond2_2]))

        #ecu 2.8
        indexCond2_8 = np.intersect1d(np.argwhere(p<0.5),np.argwhere(Aabs>=1)) #Nos entrega los index de las soluciones a las que debemos aplicar la ecu 2.1
        if indexCond2_8.shape[0] != 0:
            Xrand = poblacion[np.random.randint(low=0, high=pob, size=indexCond2_8.shape[0])] #Me entrega un conjunto de soluciones rand de tam indexCond2_2.shape[0] (osea los que cumplen la cond11)

            poblacion[indexCond2_8] = Xrand - np.multiply(A[indexCond2_8],np.abs(np.multiply(C[indexCond2_8],Xrand)-poblacion[indexCond2_8]))

        #ecu 2.5
        indexCond2_5 = np.intersect1d(np.argwhere(p>=0.5),np.argwhere(p>=0.5)) #Nos entrega los index de las soluciones a las que debemos aplicar la ecu 2.1
        if indexCond2_5.shape[0] != 0:
            poblacion[indexCond2_5] = np.multiply(np.multiply(np.abs(Best - poblacion[indexCond2_5]),np.exp(b*l)),np.cos(2*np.pi*l)) + Best

        #Binarizamos y evaluamos el fitness de todas las soluciones de la iteración t
        matrixBin,fitness,solutionsRanking = Problem.SCP(poblacion,matrixBin,solutionsRanking,vectorCostos,matrizCobertura,DS,repair,problemaGPU,pondRestricciones)


        #Conservo el Best
        if fitness[bestRowAux] > BestFitness:
            fitness[bestRowAux] = BestFitness
            matrixBin[bestRowAux] = BestBinary

        diversidades, maxDiversidades, PorcentajeExplor, PorcentajeExplot, state = dv.ObtenerDiversidadYEstado(matrixBin,maxDiversidades)
        BestFitnes = str(np.min(fitness))

        walltimeEnd = np.round(time.time() - timerStart,6)
        processTimeEnd = np.round(time.process_time()-processTime,6) 

        dataIter = {
            "id_ejecucion": id,
            "numero_iteracion":iter,
            "fitness_mejor": BestFitnes,
            "parametros_iteracion": json.dumps({
                "fitness": BestFitnes,
                "clockTime": walltimeEnd,
                "processTime": processTimeEnd,
                "DS":str(DS),
                "Diversidades":  str(diversidades),
                "PorcentajeExplor": str(PorcentajeExplor)
                #"PorcentajeExplot": str(PorcentajeExplot),
                #"state": str(state)
                })
                }

        memory.append(dataIter)
       

        if iter % 100 == 0:
            memory = connect.insertMemory(memory)

    # Si es que queda algo en memoria para insertar
    if(len(memory)>0):
        memory = connect.insertMemory(memory)

    #Actualizamos la tabla resultado_ejecucion, sin mejor_solucion
    memory2 = []
    fin = datetime.now()
    dataResult = {
        "id_ejecucion": id,
        "fitness": BestFitnes,
        "inicio": inicio,
        "fin": fin
        }
    memory2.append(dataResult)
    dataResult = connect.insertMemoryBest(memory2)

    # Update ejecucion
    if not connect.endEjecucion(id,datetime.now(),'terminado'):
        return False

    return True
def LoboGris_SCP(instancia, resultado, lobos, maxIter, run_start, run_end,
                 QL_alpha, QL_gamma):

    rootdir = str(Path().cwd()) + '/'

    pathInstance = rootdir + 'Problem/Instances/SCP/'
    repo = 'MagisterMHML'

    if not pathcheck.exists(pathInstance + instancia):
        print("No se encontró la instancia: " + pathInstance + instancia)
        return False

    instance = Instance.Read(pathInstance + instancia)

    matrizCobertura = np.array(instance.get_r())
    vectorCostos = np.array(instance.get_c())

    dim = len(vectorCostos)
    Lobos = lobos
    maxIter = maxIter

    # Main loop

    f = open(rootdir + resultado, 'w')
    linea = 'problem|solver|instance|population|run|iter|ds|metric|executionTime|QL_alpha|QL_gamma'
    f.write(linea)
    f.write('\n')
    f.close()

    for run in range(run_start, run_end + 1):

        #alpha, beta, and delta_pos
        Alpha_pos = np.zeros(dim)
        Alpha_score = float("inf")

        Beta_pos = np.zeros(dim)
        Beta_score = float("inf")

        Delta_pos = np.zeros(dim)
        Delta_score = float("inf")

        # iniciamos poblacion
        posLobos = np.zeros((Lobos, dim))
        for i in range(dim):
            posLobos[:, i] = np.random.uniform(0, 1, Lobos)

        convergencia = np.zeros(maxIter)

        #QLEARNING DECISION

        transferFunction = ['V1', 'V2', 'V3', 'V4', 'S1', 'S2', 'S3', 'S4']
        operatorBinarization = ['Standard']

        DS_actions = [
            tf + "," + ob for tf in transferFunction
            for ob in operatorBinarization
        ]

        qualityMetric = 0
        agente = QLearning.QAgent(QL_alpha, QL_gamma, DS_actions, maxIter)
        actionDS = agente.getAccion(0)

        for iter in range(0, maxIter):

            timerStart = time.time()

            # Seleccion de Esquema desde DS
            if iter > 0:
                agente.Qnuevo(qualityMetric, actionDS, iter)
                actionDS = agente.getAccion(iter)

            for lobo in range(0, Lobos):

                # F.O por cada lobo
                posLobos[lobo, :], fitness = SCP.SCP(posLobos[lobo, :],
                                                     vectorCostos,
                                                     matrizCobertura,
                                                     DS_actions[actionDS])

                # Actualizamos alpha,beta, delta
                if fitness < Alpha_score:
                    Alpha_score = fitness
                    Alpha_pos = posLobos[lobo, :].copy()

                if (fitness > Alpha_score and fitness < Beta_score):
                    Beta_score = fitness
                    Beta_pos = posLobos[lobo, :].copy()

                if (fitness > Alpha_score and fitness > Beta_score
                        and fitness < Delta_score):
                    Delta_score = fitness
                    Delta_pos = posLobos[lobo, :].copy()

            #parametro linealmente decreciente  2->0
            a = 2 - iter * ((2) / maxIter)

            # Lobos
            for lobo in range(0, Lobos):
                for j in range(0, dim):
                    r1 = np.random.uniform(0, 1)  #random [0,1]
                    r2 = np.random.uniform(0, 1)  #random [0,1]

                    A1 = 2 * a * r1 - a
                    # Equation (3.3)
                    C1 = 2 * r2
                    # Equation (3.4)

                    D_alpha = abs(C1 * Alpha_pos[j] - posLobos[lobo, j])
                    X1 = Alpha_pos[j] - A1 * D_alpha

                    r1 = np.random.uniform(0, 1)  # random [0,1]
                    r2 = np.random.uniform(0, 1)  # random [0,1]

                    A2 = 2 * a * r1 - a
                    C2 = 2 * r2

                    D_beta = abs(C2 * Beta_pos[j] - posLobos[lobo, j])
                    X2 = Beta_pos[j] - A2 * D_beta

                    r1 = np.random.uniform(0, 1)  # random [0,1]
                    r2 = np.random.uniform(0, 1)  # random [0,1]

                    A3 = 2 * a * r1 - a
                    C3 = 2 * r2

                    D_delta = abs(C3 * Delta_pos[j] - posLobos[lobo, j])
                    X3 = Delta_pos[j] - A3 * D_delta

                    posLobos[lobo, j] = (X1 + X2 + X3) / 3

            timeEnd = time.time()
            execution = round(timeEnd - timerStart, 2)

            linea_r = "SCP|GWO-Q|" \
                      + str(instancia) + "|" \
                      + str(len(posLobos)) + "|" \
                      + str(run) + "|" \
                      + str(iter) + "|" \
                      + str(DS_actions[actionDS]) + "|" \
                      + str(Alpha_score) + "|" \
                      + str(execution) + "|" \
                      + str(QL_alpha) + "|" \
                      + str(QL_gamma)

            #update Metrica calidad
            qualityMetric = Alpha_score

            if iter % 100 == 0:
                print(linea_r)

            f = open(rootdir + resultado, 'a')
            f.write(linea_r)
            f.write('\n')
            f.close()
            '''
            #Push a Github cada 500 iteraciones
            if iter%500 == 0:
                try:
                    pushGithub.pushGithub(repo,resultado,'Resultado intermedio iteración '+str(iter)+' corrida '+str(run))
                except:
                    print("No se hizo push")
            '''

            convergencia[iter] = Alpha_score

        try:
            pushGithub.pushGithub(
                repo, resultado,
                'Resultado final corrida ' + str(run) + ' de ' + str(run_end))
        except:
            print("Error al hacer push")

    return convergencia