def main(): np.random.seed(7890) # recebendo instâncias r = ReadingDatas("dat/p01") r.readFile() # adicionando clientes Customers.addCustomers(r) # for cst in Customers.get_customersList().values(): # print(cst) # adicionando depósitos Depots.addDepots(r) # print("\n\n\n\") # for dpt in Depots.get_depotsList().values(): # print(dpt) # cálculo das distâncias Distances.euclidianDistanceAll(Customers.get_customersList(), Depots.get_depotsList()) # for cst in Customers.get_customersList(): # print(cst) # print(Customers.get_customersList()[cst].get_depotsDistances()) # print("\n\n\n") # for cst in Customers.get_customersList(): # print(cst) # print(Customers.get_customersList()[cst].get_neighborsDistances()) ga = GA() ga.GA()
def definePopulation(self, size): LS = ls() # Heurística do vizinho mais próximo customers = list(csts.get_customersList().values()) cst0 = customers[np.random.randint(len(customers)-1)] tour = NearestNeighbor.nearestNeighbor(cst0) cluster = SplitDepots.splitByDepot(tour) # criação de rotas por depósitos, individual é um Solution individual = split.splitLinear(cluster) # print(individual) # print(individual.get_routes()) rand = np.random.random() if rand < config.PROB_LS_POP: individual = LS.LS(individual) self.addIndividual(individual) # print(individual) # exit(1) # print(individual.get_routes()) # exit(1) # “cluster first and then route” cluster = SplitDepots.GilletJohnson() # divisão por depósitos # criação de rotas por depósitos, individual é um Solution individual = split.splitLinear(cluster) # print(individual) # print(individual.get_routes()) rand = np.random.random() if rand < config.PROB_LS_POP: individual = LS.LS(individual) # print(individual) # print(individual.get_routes()) if individual is not None and self.is_different(individual): self.addIndividual(individual) # for i in self._population: # print(i) # self.verifyNodes(i) # exit(1) # formação de rotas aleatórias self.formRandomPopulation(size) self.sortPopulation() # for i in self._population: # print(i) print(len(self._population)) return self._population
def nearestNeighbor(startCustomer): NearestNeighbor._path = [] NearestNeighbor._availableCsts = {} NearestNeighbor._availableCsts = copy.deepcopy(cst.get_customersList()) NearestNeighbor._path.append(startCustomer) del NearestNeighbor._availableCsts[str( startCustomer.get_id())] #remover da lista currentCst = startCustomer for i in range(len(NearestNeighbor._availableCsts)): nextCst = NearestNeighbor.findNeighbor(currentCst) if nextCst is not None: NearestNeighbor._path.append(nextCst) currentCst = nextCst return NearestNeighbor._path
def GilletJohnson(): SplitDepots._individual = Solution() SplitDepots._availableDepots = [] customersList = copy.deepcopy(csts.get_customersList()) # dicionário for dpt in dpts.get_depotsList(): SplitDepots._availableDepots.append( [dpt, dpts.get_depotsList()[dpt].get_loadTotal(), 0.0, 0] ) # depósito, carga totaL,demanda total atendida,clientes alocados unallocatedCustomers = SplitDepots.GilletJohnsonProcedure( customersList, len(SplitDepots._availableDepots)) # print("verificando") # print(SplitDepots._individual) return SplitDepots._individual
def main(SEED, POP, DESC, PROB_MUT, PROB_LS_POP, PROB_LS, PROB_LSB, PROB_LSBP, GEN_ILS, GEN_ILSA, DATFILE, INSTANCE): # redefinindo variáveis conforme Package Irace # config.FRAC_MAX_DISTRIBUTION = FRAC config.SIZE_POP = POP config.SIZE_DESC = DESC config.PROB_MUTATION = PROB_MUT config.PROB_LS_POP = PROB_LS_POP config.PROB_LS = PROB_LS config.PROB_LS_BEST = PROB_LSB config.PROB_LS_BEST_P = PROB_LSBP config.GEN_ILS = GEN_ILS config.GEN_ILSA = GEN_ILSA seed = SEED timeIni = time.time() # exit(0) # recebendo instâncias r = ReadingDatas(INSTANCE) r.readFile() # adicionando clientes Customers.addCustomers(r) # adicionando depósitos Depots.addDepots(r) # cálculo das distâncias Distances.euclidianDistanceAll(Customers.get_customersList(), Depots.get_depotsList()) ga = GA() best = ga.GA(seed) cost = best.get_cost() timeEnd = (time.time() - timeIni) / 60.0 logging.debug("Melhor indivíduo: %s" % best) logging.debug("tempo total: " + str(timeEnd) + " minutos.") logging.debug("------------fim algoritmo genético-----------") with open(DATFILE, 'w') as f: f.write(str(cost))
def randomDistribution(): #print('Entrou aqui') #np.random.seed(idum) SplitDepots._individual = Solution() customersList = copy.deepcopy(csts.get_customersList()) # dicionário # lista com as chaves dos clientes keysCst = list(customersList.keys()) depots = dpts.get_depotsList() # dicionário nDepots = len(depots) base = len(customersList) / float(nDepots) maxCustomers = round(config.FRAC_MAX_DISTRIBUTION * base) nCustomers = len(keysCst) solution = {} # (depósito, [total de demanda, número de clientes alocados] control = {} for depot in depots: control[depot] = [0, 0] while nCustomers > 0: # enquanto tiver cliente não alocado # cliente aleatório idCst = np.random.randint(0, len(keysCst)) customer = customersList[keysCst[idCst]] # depósito mais próximo i = 0 dpt = customer.get_depotsDistances()[i] cont = len(customer.get_depotsDistances()) aux = 0 while (control[str(dpt[0])][0] >= depots[str(dpt[0])].get_loadTotal() + 0.0001 or (cont > 1 and control[str(dpt[0])][1] > maxCustomers)) and cont > 0: if cont == 1: aux = 1 # indica que todos os depósitos anteriores estão lotados i += 1 dpt = customer.get_depotsDistances()[i] cont -= 1 depot = depots[str(dpt[0])] control[str( dpt[0])][0] = control[str(dpt[0])][0] + customer.get_demand() control[str(dpt[0])][1] = control[str(dpt[0])][1] + 1 # adicionar cliente ao depósito SplitDepots._individual.addGiantTour(customer, depot) del keysCst[idCst] # atualizar lista nCustomers -= 1 # escolher três clientes aleatórios if len(keysCst) > 0: idcst1 = np.random.randint(0, len(keysCst)) neighbor1 = customersList[keysCst[idcst1]] dist1 = dist.euclidianDistance(customer.get_x_coord(), customer.get_y_coord(), neighbor1.get_x_coord(), neighbor1.get_y_coord()) idcst2 = np.random.randint(0, len(keysCst)) neighbor2 = customersList[keysCst[idcst2]] dist2 = dist.euclidianDistance(customer.get_x_coord(), customer.get_y_coord(), neighbor2.get_x_coord(), neighbor2.get_y_coord()) idcst3 = np.random.randint(0, len(keysCst)) neighbor3 = customersList[keysCst[idcst3]] dist3 = dist1 = dist.euclidianDistance(customer.get_x_coord(), customer.get_y_coord(), neighbor3.get_x_coord(), neighbor3.get_y_coord()) # ver o mais próximo ao cliente if dist1 <= dist2 and dist1 <= dist3: close = neighbor1 id = idcst1 elif dist2 <= dist1 and dist2 <= dist3: close = neighbor2 id = idcst2 else: close = neighbor3 id = idcst3 control[str( dpt[0])][0] = control[str(dpt[0])][0] + close.get_demand() control[str(dpt[0])][1] = control[str(dpt[0])][1] + 1 if (control[str(dpt[0])][0] <= depot.get_loadTotal() + 0.0001 and control[str(dpt[0])][1] <= maxCustomers) or aux == 1: # adicionar vizinho mais próximo a solução SplitDepots._individual.addGiantTour(close, depot) del keysCst[id] # atualizar lista nCustomers -= 1 else: control[str(dpt[0])][0] = control[str( dpt[0])][0] - close.get_demand() control[str(dpt[0])][1] = control[str(dpt[0])][1] - 1 # print(self._individual.get_giantTour()) # print(SplitDepots._individual.get_depots()) return SplitDepots._individual
def GilletJohnsonProcedure(customersList, nDepotsAvailable): unallocatedCustomers = customersList numberDepotsAvailable = nDepotsAvailable depots = dpts.get_depotsList() auxiliar = [] base = len(csts.get_customersList()) / float(len(depots)) maxCustomers = round(config.FRAC_MAX_DISTRIBUTION * base) # print("maxCustomers:") # print(maxCustomers) # print(unallocatedCustomers) for cst in unallocatedCustomers: depotsDistances = unallocatedCustomers[cst].get_depotsDistances() depotsAvailable = [] # recuperar apenas depósitos com vagas for dptDist in depotsDistances: for adpts in SplitDepots._availableDepots: if str(dptDist[0]) == adpts[0]: depotsAvailable.append(dptDist) break # print("saiu do for") # print(depotsAvailable) if len(depotsAvailable) > 1: fstDepot = depotsAvailable[0] # primeiro depósito mais próximo sndDepot = depotsAvailable[1] # segundo depósito mais próximo fstDistance = fstDepot[1] # distância do primeiro depósito sndDistance = sndDepot[1] # distância do segundo depósito ratio = fstDistance / float(sndDistance) auxiliar.append( [unallocatedCustomers[cst], ratio, str(fstDepot[0])]) elif len(depotsAvailable) == 1: fstDepot = depotsAvailable[0] # primeiro depósito mais próximo ratio = 1.0 auxiliar.append( [unallocatedCustomers[cst], ratio, str(fstDepot[0])]) # print("check") # print(unallocatedCustomers[cst]) # ordenar lista auxiliar em ordem decrescente pts = sorted(auxiliar, key=lambda x: x[1], reverse=True) # print("pts:") # print(pts) # print(SplitDepots._individual) for dpt in SplitDepots._availableDepots: control = 0 for pt in pts: # print(pt) if dpt[0] == pt[2]: dpt[2] = dpt[2] + pt[0].get_demand() dpt[3] = dpt[3] + 1 # demanda total > carga total (considera cheio) if (dpt[2] > dpt[1] or dpt[3] > maxCustomers): if numberDepotsAvailable > 1: dpt[2] = dpt[2] - pt[0].get_demand() dpt[3] = dpt[3] - 1 dpt[0] = "-1" numberDepotsAvailable -= 1 #print("é menor") else: # se ainda faltarem clientes para serem alocados e restar apenas 1 depósito, a carga total será desrespeitada #print("último depósito disponível") # print(SplitDepots._availableDepots) # adiciona o cliente no depósito mais próximo SplitDepots._individual.addGiantTour( pt[0], depots[dpt[0]]) # remove da lista de unallocatedCustomers unallocatedCustomers.pop(str(pt[0].get_id()), -1) control += 1 else: # adiciona o cliente no depósito mais próximo SplitDepots._individual.addGiantTour( pt[0], depots[dpt[0]]) # remove da lista de unallocatedCustomers unallocatedCustomers.pop(str(pt[0].get_id()), -1) control += 1 # print(":") # print(SplitDepots._availableDepots) # print(unallocatedCustomers) # print(SplitDepots._availableDepots) if len(unallocatedCustomers) > 0: return SplitDepots.GilletJohnsonProcedure(unallocatedCustomers, numberDepotsAvailable) else: return unallocatedCustomers
def definePopulation(self, size): LS = ls() # Heurística do vizinho mais próximo for cst in csts.get_customersList(): tour = NearestNeighbor.nearestNeighbor( csts.get_customersList()[cst]) break cluster = SplitDepots.splitByDepot(tour) # criação de rotas por depósitos, individual é um Solution individual = split.splitLinear(cluster) # print(individual) # print(individual.get_routes()) rand = np.random.random() if rand < config.PROB_LS_POP: individual = LS.LS(individual) self.addIndividual(individual) # print(individual) # exit(1) # print(individual.get_routes()) # exit(1) # “cluster first and then route” cluster = SplitDepots.GilletJohnson() # divisão por depósitos # criação de rotas por depósitos, individual é um Solution individual = split.splitLinear(cluster) # print(individual) # print(individual.get_routes()) rand = np.random.random() if rand < config.PROB_LS_POP: individual = LS.LS(individual) # print(individual) # print(individual.get_routes()) if individual is not None and self.is_different(individual): self.addIndividual(individual) # formação de rotas aleatórias for i in range(2 * size): if len(self._population) >= size: break seed = i + int(500 * np.random.random()) cluster = SplitDepots.randomDistribution(seed) # criação de rotas por depósitos, individual é um Solution individual = split.splitLinear(cluster) # print(individual) # print(individual.get_routes()) rand = np.random.random() if rand < config.PROB_LS_POP: individual = LS.LS(individual) if individual is not None and self.is_different(individual): self.addIndividual(individual) # print(individual) # print(individual.get_routes()) # exit(1) # exit(1) self.sortPopulation() # for i in self._population: # print(i) # self.verifyNodes(i) print(len(self._population)) return self._population
def definePopulation(self, size): timeI = time.time() LS = ls() split = splitAlg() # Heurística do vizinho mais próximo customers = list(csts.get_customersList().values()) cst0 = customers[np.random.randint(len(customers) - 1)] # cst0 = customers[0] tour = NearestNeighbor.nearestNeighbor(cst0) cluster = SplitDepots.splitByDepot(tour) # criação de rotas por depósitos, individual é um Solution individual = split.splitLinear(cluster, True) # individual = split.mountRoutes(cluster) # print(individual) # print(individual.get_routes()) # rand = np.random.random_sample() # if rand < config.PROB_LS_POP: # individual = LS.LS(individual) individual = self.localSearch(individual, timeI) self.addIndividual(individual) # print(individual) # exit(1) # print(individual.get_routes()) # exit(1) # “cluster first and then route” cluster = SplitDepots.GilletJohnson() # divisão por depósitos # criação de rotas por depósitos, individual é um Solution individual = split.splitLinear(cluster, True) # individual = split.mountRoutes(cluster) # print(individual) # print(individual.get_routes()) # rand = np.random.random_sample() # if rand < config.PROB_LS_POP: # individual = LS.LS(individual) individual = self.localSearch(individual, timeI) # print(individual) # print(individual.get_routes()) if individual is not None and self.is_different(individual): self.addIndividual(individual) # for i in self._population: # print(i) # self.verifyNodes(i) # exit(1) # formação de rotas aleatórias self.formRandomPopulation(size, timeI) # individual = np.random.choice(self._population, 1)[0] # individual = self.localSearch(individual, timeI) self.sortPopulation() # print(self.showBestSolution()) # individual = self.localSearch(self.showBestSolution(), timeI) # self._population[len(self._population)-1] = individual # print(self.showBestSolution()) # self.sortPopulation() # for i in self._population: # print(i) # print(i.get_routes()) # print(i.get_cost()) # print(i.get_nRoutesByDepot()) # print(self.showBestSolution().get_routes()) # print(self.showBestSolution().get_cost()) # print(self.showBestSolution().get_nRoutesByDepot()) # self.test(self.showBestSolution()) # exit(1) # print(len(self._population)) print("Tempo população: {} minutos".format((time.time() - timeI) / 60)) return self._population