def __init__(self, formData): self.timeNow = formData['timeNow'] conn = Db.Connect(self.cdata) self.N_SHOVELS = conn.getShovelNumber() -1 self.N_TRUCKS = conn.getTruckNumber() - 1 self.TRUCK_TYPES = conn.getTruckTypes() conn.disconnect()
def checkAssignment(simulation_name_truck): #truck askingTruck = simulation_name_truck.split(".")[0] conn = Db.Connect() truckId = conn.findTruckByName(askingTruck) assignment = conn.hasAssignment(truckId) if assignment: conn.updateAssignment(truckId) assignment = conn.getLoadName(assignment[0][0])[0] conn.disconnect() return assignment
def createGA(self): #individual structure #define fitness function, minimize in this case, weight negative stands for minimizing fitness creator.create("FitnessMin", base.Fitness, weights=(-1.0,)) creator.create("Individual", list, fitness = creator.FitnessMin) #trucks to create (6 in this test) '''conn = Db.Connect(self.cdata) self.TRUCK_TYPES = conn.getTruckTypes() for tt in self.TRUCK_TYPES: self.N_TRUCKS += tt[5]''' #population config toolbox = base.Toolbox() toolbox.register("attr_int", random.randint, self.MIN, self.N_SHOVELS) # define los tipos de un individuo toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_int, self.N_TRUCKS) # define individuo toolbox.register("population", tools.initRepeat, list, toolbox.individual) #crea la poblacion toolbox.register("evaluate", self.evalMin) toolbox.register("mate", tools.cxTwoPoint) toolbox.register("mutate", tools.mutUniformInt, low=1, up=self.N_SHOVELS, indpb=0.05) toolbox.register("select", tools.selTournament, tournsize=3) #conn.disconnect() print("creando poblacion") pop = toolbox.population(n=10) hof = tools.HallOfFame(1) '''stats = tools.Statistics(lambda ind: ind.fitness.values) stats.register("avg", numpy.mean) stats.register("sum", numpy.sum) stats.register("std", numpy.std) stats.register("min", numpy.min) stats.register("max", numpy.max)''' print("ejecutando AG") #pop, log = algorithms.eaSimple(pop, toolbox, cxpb=0.5, mutpb=0.2, ngen=10, stats=stats, halloffame=hof, verbose=False) pop, log = algorithms.eaSimple(pop, toolbox, cxpb=0.5, mutpb=0.2, ngen=10, halloffame=hof, verbose=True) bestSolution = hof[0] print("mejor solucion: %s" % bestSolution) conn = Db.Connect(self.cdata) conn.truncGAInit() #en esta linea insertar el tiempo estimado de llegada #obtenido de hof[0].fitness.values for row in bestSolution: conn.insertGA(row) conn.disconnect() #clear toolbox for next ussage of deap self.clear(toolbox) return bestSolution
def __init__(self, formData): #sets actual simulation time self.tCurrent = formData['timeNow'] conn = Db.Connect(self.cdata) self.TRUCK_STATES = conn.getTruckStates() self.TRUCK_TYPES = conn.getTruckTypes() self.N_TRUCKS = conn.getTruckNumber() self.N_SHOVELS = conn.getShovelNumber() conn.disconnect() #assign trucks to shovels arrays for t in self.TRUCK_STATES: if "Pala" in t[3]: i = t[3].split('Pala') if (i[1] == '0'): self.SHOVEL_0.append(t) if (i[1] == '1'): self.SHOVEL_1.append(t)
def main(current_simulation_time, simulation_name_truck): tiempo_total_ag = time.time() tiempo_inicio_ag = time.time() #truck askingTruck = simulation_name_truck.split(".")[0] #set current simlation time tCurrent = float(current_simulation_time.replace(',','.')) creator.create("FitnessMin", base.Fitness, weights=(-1.0,)) creator.create("Individual", list, fitness=creator.FitnessMin) toolbox = base.Toolbox() conn = Db.Connect() SHOVEL_NUMBER = conn.getShovelNumber() TRUCK_STATES = conn.getTruckStates() TRUCKS_NUMBER = conn.getTruckNumber() unloadStations = conn.getAllUnloadStations() # Attribute generator # define 'attr_bool' to be an attribute ('gene') # which corresponds to integers sampled uniformly # from the range [0,1] (i.e. 0 or 1 with equal # probability) #Genera valor de attr_bool de forma aleatoria esto en mi ag va desde 0 hasta el numero maximo de palas-1 toolbox.register("no_shovel", random.randint, 1, SHOVEL_NUMBER) # Structure initializers # define 'individual' to be an individual # consisting of 100 'attr_bool' elements ('genes') # en mi ga el individuo consiste de valores enteros hasta el numero de camiones utilizados o registrados en la bd toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.no_shovel, TRUCKS_NUMBER) # define the population to be a list of individuals #igual en mi AG toolbox.register("population", tools.initRepeat, list, toolbox.individual) #FUNCIONES DE UTILIDAD # # # def findTruck(id): my_truck = '' for truck in TRUCK_STATES: if id == truck[1]: my_truck = truck return my_truck def calcTA(truckstate): #calcta es llamada cada vez que se realiza la evaluacion del individuo #shovel assignment sera el numero generado aleatoriamente por el cromosoma del individuo #ts[4] == "vc" or ts[4] == "vd" no realizan cambios ya que no son observados estimatedarrivaltime = 0 #si el camion se encuentra en viaje se asigna valor 0 if truckstate: if str(truckstate[6]) == "v": #0 no se puede determinar u observar estimatedarrivaltime = 0 elif str(truckstate[6]) == "d": #se encuentra en descarga #unload = conn.getUnloadStation(truckstate[3]) deltatime = abs(tCurrent - float(truckstate[7].replace(",", "."))) #resultado = (tiempo en descargar completo) + tiempo maniobra de camion - (tiempo actual simulacion -> timeNow - tiempo inicio -> tiempo en el que llego a d) estimatedarrivaltime = (truckstate[12] + truckstate[14])/60000 - deltatime elif str(truckstate[6]) == "cd": unload = conn.getUnloadStation(truckstate[2]) trucksinunload = conn.getTrucksInStation(truckstate[2]) queuearrivaltime = 0 #busca posicion de camion actual en cola y calcula tiempo de descarga de camion que se encuentre descargando for truckinunload in trucksinunload: if truckinunload[6] == "cd": #buscar posicion camion en cola if truckstate[1] == truckinunload[1]: #obtener indice queuearrivaltime = float(truckinunload[7].replace(',','.')) elif truckinunload[6] == "d": #usar formula de camion cargando que se encuentra en la estacion de descarga deltatime = abs(tCurrent - float(truckinunload[7].replace(",", "."))) estimatedarrivaltime = (truckinunload[12] + truckinunload[14])/60000 - deltatime for truckinunload in trucksinunload: #si el tiempo de llegada del camion que esta en el array es menor o = al tiempo de llegada del camion para calc ta sumar if float(truckinunload[7].replace(',','.')) <= queuearrivaltime: deltatime = abs(tCurrent - float(truckinunload[7].replace(",", "."))) estimatedarrivaltime = estimatedarrivaltime + (truckinunload[12] + truckinunload[14])/6000 - deltatime elif str(truckstate[6]) == "c": #camion se encuentra cargando: capacidad camion * vel descarga + tiempo maniobra + tiempo actual - tiempo inicial #nueva forma: camion.capacidad * pala.palasMinuto + camion.spottingtime + tiempoactual - tiempo inicial + tiempo estimado en cola si lo tiene shovel = conn.getShovel(truckstate[2]) unloadroute = conn.getRoutesToDestination(shovel[2], shovel[8]) unload = conn.getUnloadStation(shovel[8]) trucksinunload = conn.getTrucksInStation(unload[3]) #shortest path not mean meanunloadroute = unloadroute[4] queuetime = 0 #calcula tiempo de espera en descarga for truckinunload in trucksinunload: deltatime = abs(tCurrent - float(truckinunload[7].replace(",", "."))) queuetime = queuetime + (truckinunload[12] * unload[14]/60000) + truckinunload[11] - deltatime #resultado = (capacidad camion * vel. descarga pala) + tiempo maniobra de camion + (distancia de viaje * vel camion cargado) + tiempo de camiones que estan en la zona de descarga) # - (tiempo actual simulacion -> timeNow - tiempo inicio -> tiempo en el que llego a d) #estimatedarrivaltime = (truckstate[12] * shovel[2]) + truckstate[11] + (meanunloadroute * truckstate[11]) + queuetime - deltatime # paladas necesarias para llenar camion = capacidad camion / cantidad por palada # nro paladas * LOAD_RATE * (tiempo de carga por una palada en milisegundos / 6000) # tiempo en recorrer camino = (meanunloadroute * truckstate[17]) (se asume ambos estan en km - distancia (km), velocidad cargado (km/h)) estimatedarrivaltime = (truckstate[13] / shovel[3]) * ((shovel[4] * shovel[5])/60000) + (meanunloadroute * truckstate[17])/60000 + queuetime - deltatime elif str(truckstate[6]) == "cc": #camion se encuentra esperando carga shovel = conn.getShovel(truckstate[2]) trucksinshovel = conn.getTrucksInStation(shovel[2]) unloadroute = conn.getRoutesToDestination(shovel[2], shovel[8]) unload = conn.getUnloadStation(shovel[8]) trucksinunload = conn.getTrucksInStation(unload[3]) meanunloadroute = 0 queuearrivaltime = 0 queuetime = 0 estimatedarrivaltime = 0 #calcula tiempos aprox para que el camion salga de la pala for truckinshovel in trucksinshovel: if truckinshovel[6] == "cc": if truckstate[1] == truckinshovel[1]: queuearrivaltime = truckinshovel[7] elif truckinshovel[6] == "c": deltatime = abs(tCurrent - float(truckinshovel[7].replace(",", "."))) #estimatedarrivaltime = (truckinshovel[9] * shovel[2]) + truckinshovel[8] - deltatime estimatedarrivaltime = (truckinshovel[13] / shovel[3]) * (shovel[4]/60000) - deltatime for truckinshovel in trucksinshovel: if float(truckinshovel[7].replace(',','.')) <= queuearrivaltime: deltatime = abs(tCurrent - float(truckinshovel[7].replace(",", "."))) estimatedarrivaltime = estimatedarrivaltime + (truckinshovel[12] + truckinshovel[14] )/60000 - deltatime #calcula tiempo de viaje estimado y lo adiciona al estimatedarrivaltime meanunloadroute = unloadroute #suma tiempos de los camiones que se encuentran en destino (descarga) for truckinunload in trucksinunload: deltatime = abs(tCurrent - float(truckinunload[7].replace(",", "."))) #(truckinunload[12] + truckinunload[14])/6000 - deltatime queuetime = queuetime + (truckinunload[12] + truckinunload[14])/60000 - deltatime # en cola descarga o en carga (truckstate[12] * shovel[2]) #estimatedarrivaltime = estimatedarrivaltime + (truckstate[12] * shovel[2]) + truckstate[11] + (meanunloadroute * truckstate[11]) + queuetime - deltatime estimatedarrivaltime = estimatedarrivaltime + (truckstate[13] / shovel[3]) * ((shovel[4] * shovel[5])/60000) + ((meanunloadroute * truckstate[17])/60000) + queuetime - deltatime elif str(truckstate[7]) == "sag": # sag: solicita algoritmo genetico # ya se encuentra en el ultimo estado estimatedarrivaltime = 0 return estimatedarrivaltime # the goal ('fitness') function to be maximized #en mi ag necesito qud se minimize def evalOneMin(individual): #calcular como en TA segun trucksCycleTime = 0 listshovel = individual #recorre cada indice de la lista del individuo for index,value in enumerate(listshovel,1): truck = findTruck(index) if type(truck) is list: if truck[6] != "v" or '': shovel = conn.getShovelById(value) shovelname = str(shovel[2]) #datos obligatorios # shovel[2], shovel[8] #unload = conn.getUnloadStation(shovel[8]) for sublist in unloadStations: if sublist[3] == shovel[8]: unload = sublist break loadroutes = conn.getRoutesToDestination(unload[3], shovelname) trucksinshovel = conn.getTrucksInStation(shovelname) #unloadroutes = conn.getRoutesToDestination(shovel[2], shovel[8]) #trucksinunload = conn.getTrucksInStation(shovel[8]) # distancia mas corta ruta viaje a carga loadtraveltime = loadroutes[4] * truck[12] #suma camiones en carga sumtrucksinshovel = 0 for truckinshovel in trucksinshovel: deltatime = abs(float(tCurrent) -float(truckinshovel[7].replace(",", "."))) #sumtrucksinshovel = sumtrucksinshovel + (truckinshovel[9] * shovel[2]) + truckinshovel[8] - deltatime sumtrucksinshovel = sumtrucksinshovel + (truckinshovel[13] / shovel[3]) * ((shovel[4] * shovel[5])/60000) + truckinshovel[17]/60000 - deltatime #distancia prom ruta viaje a descarga #unloadtraveltime = unloadroutes[4] * truck[16] #suma camiones en descarga #sumtrucksinunload = 0 '''for truckinunload in trucksinunload: deltatime = abs(tCurrent - float(truckinunload[7].replace(",", ".")))''' #sumtrucksinunload = sumtrucksinunload + (truckinunload[9] * unload[2]) + truckinunload[8] - deltatime #sumtrucksinunload = sumtrucksinunload + (truckinunload[15]/60000) + (truckinunload[17]/60000) - deltatime #trucksCycleTime = loadtraveltime + sumtrucksinshovel + unloadtraveltime + sumtrucksinunload trucksCycleTime = loadtraveltime + sumtrucksinshovel #se agrega el TA trucksCycleTime = trucksCycleTime + individual[index-1] #calcular TGA return trucksCycleTime, #return sum(individual), #---------- # Operator registration #---------- # register the goal / fitness function toolbox.register("evaluate", evalOneMin) # register the crossover operator toolbox.register("mate", tools.cxTwoPoint) # register a mutation operator with a probability to # flip each attribute/gene of 0.05 toolbox.register("mutate", tools.mutUniformInt, low = 1, up = SHOVEL_NUMBER, indpb=50) # operator for selecting individuals for breeding the next # generation: each individual of the current generation # is replaced by the 'fittest' (best) of three individuals # drawn randomly from the current generation. toolbox.register("select", tools.selTournament, tournsize=3) #print("Termino fase 1: ", time.time()-tiempo_inicio_ag) tiempo_inicio_ag = time.time() # create an initial population of 300 individuals (where # each individual is a list of integers) pop = toolbox.population(n=5) #print("Termino fase 2: ", time.time()-tiempo_inicio_ag) tiempo_inicio_ag = time.time() # CXPB is the probability with which two individuals # are crossed # # MUTPB is the probability for mutating an individual CXPB, MUTPB = 0.5, 0.08 #convergence list results = [] genetic_algorithm_initial_time = time.time() # Evaluate the entire population fitnesses = list(map(toolbox.evaluate, pop)) for ind, fit in zip(pop, fitnesses): ind.fitness.values = fit #print("Termino evaluacion inicial: ", time.time()-genetic_algorithm_initial_time) genetic_algorithm_initial_time = time.time() #print("evaluacion primera poblacion") # Extracting all the fitnesses of # Variable keeping track of the number of generations g = 0 # Begin the evolution #tiempo maximo de ejecucion 1 minuto time_current = time.time() + 7 converge = 0 #while converge < 3 or (int(time.time()/60) - time_current) < 1: #while converge < 3 or (int(time.time()) - time_current) < 1: while time.time() <= time_current: variable_tiempo=time.time() variable_tiempo_final=time.time() # A new generation #time_current = int(time.time()/60) g = g + 1 #print("-- Generation %i --" % g) #print("cantidad de individuos: ", len(pop)) # Select the next generation individuals offspring = toolbox.select(pop, len(pop)) #print("Individuos seleccionados: ", len(offspring)) # Clone the selected individuals offspring = list(map(toolbox.clone, offspring)) # Apply crossover and mutation on the offspring for child1, child2 in zip(offspring[::2], offspring[1::2]): # cross two individuals with probability CXPB if random.random() < CXPB: toolbox.mate(child1, child2) # fitness values of the children # must be recalculated later del child1.fitness.values del child2.fitness.values for mutant in offspring: # mutate an individual with probability MUTPB if random.random() < MUTPB: toolbox.mutate(mutant) del mutant.fitness.values # Evaluate the individuals with an invalid fitness #print(" Evaluated %i individuals" % len(invalid_ind)) fitnesses = list(map(toolbox.evaluate, offspring)) for ind, fit in zip(offspring, fitnesses): ind.fitness.values = fit total = 0 for fitness in fitnesses: total = total + fitness[0] results.append(total) #fin prueba # The population is entirely replaced by the offspring pop[:] = offspring # Gather all the fitnesses in one list and print the stats #converge = convergence(results, converge) #print("converge: ", converge) print("generations: %i" % g) print("-- End of (successful) evolution --") tiempo_inicio_ag = time.time() #print("individuos candidatos") #print(pop) best_ind = tools.selBest(pop, 1)[0] #print("mejor individuo seleccionado") #print(best_ind) #print("fitness mejor individuo sleeccionado") #print(best_ind.fitness) #print("Best individual is %s, %s" % (best_ind, best_ind.fitness.values)) # find truck index tiempo_inicio_ag = time.time() truck_index = conn.getTruckIndex(askingTruck)[0] trucks_index = conn.getTrucksIndex() assignments = [(trucks_index[i], best_ind[i]) for i in range(0, len(trucks_index))] # find unload index (resulting data), name shovel_index = best_ind[truck_index-1] shovel_name = conn.getLoadName(shovel_index)[0] # insert asssignment #conn.insertAssignment(truck_index, unload_index) conn.updateAssignments() conn.insertAssignments(assignments) # return results to SIMIO #print("mejor individuo, tiempo estimado, fitness") conn.disconnect() estimated_arrival_time= 0 return best_ind, estimated_arrival_time, best_ind.fitness.values, shovel_name
ConnectfileData = File.Read(ConnectfileObject, empty) if (ConnectfileData != empty): ConnectfileDataList = ConnectfileData.split(',') else: Errormessage = 'No data in ' + Connectfilename File.Logerror(ErrorfileObject, module, Errormessage, error) Errormessage = 'Could not close' + Connectfilename if (File.Close(ConnectfileObject, failure) == failure): File.Logerror(ErrorfileObject, module, Errormessage, error) # Progress update File.Logerror(ErrorfileObject, module, 'Read database connection data', info) # Open database connection. DbObject = Db.Connect(ConnectfileDataList[0], ConnectfileDataList[1], ConnectfileDataList[2], ConnectfileDataList[3], invalid) Errormessage = 'Could not connect to database' if (DbObject == invalid): File.Logerror(ErrorfileObject, module, Errormessage, error) # Prepare a database cursor object. DbCursor = Db.Initcursor(DbObject, invalid) Errormessage = 'Unable to create database cursor' if (DbCursor == invalid): File.Logerror(ErrorfileObject, module, Errormessage, error) # Progress update File.Logerror(ErrorfileObject, module, 'Connected to database', info) # Killing outlook process if it exists. Interface.KillProcess(Outlook, Delay, empty)
def createGA(self): conn = Db.Connect(self.cdata) #calcular TA ta = self.getTA(conn) #AG creator.create("FitnessMin", base.Fitness, weights=(-1.0, )) creator.create("Individual", list, fitness=creator.FitnessMin) #operators toolbox = base.Toolbox() toolbox.register("individual", self.InitMatrix, creator.Individual, ta) # define individuo toolbox.register("population", tools.initRepeat, list, toolbox.individual) #crea la poblacion pop = toolbox.population(n=4) toolbox.register("evaluate", self.evalMin, conn, list) #toolbox.register("mate", tools.cxTwoPoint) toolbox.register("mate", self.CxFunction) toolbox.register("mutate", self.MutFunction) toolbox.register("select", self.Selection) #crear poblacion # Evaluate the entire population fitnesses = [] for individual in pop: fitnesses.append(self.evalMin(conn, individual)) for ind, fit in zip(pop, fitnesses): ind.fitness.values = fit, ind[2] = fit hof = tools.HallOfFame(1) generation = 0 GEN_LIMIT = 100 """ evaluate(population) LISTO for g in range(ngen): LISTO population = select(population, len(population)) LISTO offspring = varAnd(population, toolbox, cxpb, mutpb) X evaluate(offspring) population = offspring """ for generation in range(GEN_LIMIT): # A new generation generation = generation + 1 print("-- Generation %i --" % generation) # Select the next generation individuals offspring = toolbox.select(pop) #offspring = algorithms.varAnd(pop, toolbox, self.CXPB, self.MUTPB) """ seccion varAnd """ offspring = [toolbox.clone(ind) for ind in pop] print("descendencia") for i in offspring: print(i) print("fin descendencia") # Apply crossover and mutation on the offspring for i in range(1, len(offspring), 2): if random.random() < self.CXPB: offspring[i - 1], offspring[i] = toolbox.mate( conn, offspring[i - 1], offspring[i]) del offspring[ i - 1].fitness.values, offspring[i].fitness.values for i in range(len(offspring)): if random.random() < self.MUTPB: offspring[i] = toolbox.mutate(conn, offspring[i]) del offspring[i].fitness.values """ fin seccion varAnd """ #evaluar # Evaluate the individuals with an invalid fitness invalid_ind = [ind for ind in offspring if not ind.fitness.valid] fitnesses = toolbox.map(self.evalMinWrapper(conn, invalid_ind)) for ind, fit in zip(invalid_ind, fitnesses): ind.fitness.values = fit #1. eaSimple => pop, log = algorithms.eaSimple(pop, toolbox, cxpb=0.5, mutpb=0.2, ngen=2500, halloffame=hof, verbose=False) #2. varAnd # Clone the selected individuals, creo que el clone no me sirve #offspring = list(map(toolbox.clone, offspring)) #cruce y mutacion # Apply crossover and mutation on the offspring #selecciona parejas '''for child1, child2 in zip(offspring[::2], offspring[1::2]): obtiene probabilidad de mutacion if random.random() < self.CXPB: offspring = toolbox.mate(conn, child1, child2) print('resultado cruce') print(offspring) del child1.fitness.values del child2.fitness.values for mutant in offspring: if random.random() < self.MUTPB: offspring = toolbox.mutate(conn, mutant) del mutant.fitness.values''' # Update the hall of fame with the generated individuals hof.update(offspring) # Replace the current population by the offspring pop[:] = offspring '''fitness_points = [] fo'r ind in pop: fitness_points.append(ind[2]) best_ind = [] for fitness_point in fitness_points: if(fitness_point == min(fitness_points)): best_ind = fitness_point''' print(hof) return pop
def main(current_simulation_time): # # # # # # # # # #random.seed(64) -> nose para que es xd #set current simlation time tCurrent = float(current_simulation_time.replace(',','.')) creator.create("FitnessMin", base.Fitness, weights=(-1.0,)) creator.create("Individual", list, fitness=creator.FitnessMin) toolbox = base.Toolbox() conn = Db.Connect() SHOVEL_NUMBER = conn.getShovelNumber()-1 #tCurrent = formData['timeNow'] TRUCK_STATES = conn.getTruckStates() TRUCKS_NUMBER = conn.getTruckNumber() # Attribute generator # define 'attr_bool' to be an attribute ('gene') # which corresponds to integers sampled uniformly # from the range [0,1] (i.e. 0 or 1 with equal # probability) #Genera valor de attr_bool de forma aleatoria esto en mi ag va desde 0 hasta el numero maximo de palas-1 toolbox.register("no_shovel", random.randint, 0, SHOVEL_NUMBER) # Structure initializers # define 'individual' to be an individual # consisting of 100 'attr_bool' elements ('genes') # en mi ga el individuo consiste de valores enteros hasta el numero de camiones utilizados o registrados en la bd toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.no_shovel, TRUCKS_NUMBER) # define the population to be a list of individuals #igual en mi AG toolbox.register("population", tools.initRepeat, list, toolbox.individual) #FUNCIONES DE UTILIDAD # # # def findTruck(id): my_truck = '' for truck in TRUCK_STATES: if id == truck[10]: my_truck = truck return my_truck def calcTA(truckstate): #calcta es llamada cada vez que se realiza la evaluacion del individuo #shovel assignment sera el numero generado aleatoriamente por el cromosoma del individuo #ts[7] == "vc" or ts[7] == "vd" no realizan cambios ya que no son observados estimatedarrivaltime = 0 #si el camion se encuentra en viaje se asigna valor 0 if truckstate: if str(truckstate[7]) == "v": #0 no se puede determinar u observar estimatedarrivaltime = 0 elif str(truckstate[7]) == "d": #se encuentra en descarga unload = conn.getUnloadStation(truckstate[3]) deltatime = abs(tCurrent - float(truckstate[8].replace(",", "."))) #resultado = (capacidad camion * vel. descarga pala) + tiempo maniobra de camion - (tiempo actual simulacion -> timeNow - tiempo inicio -> tiempo en el que llego a d) estimatedarrivaltime = (truckstate[13] * unload[2]) + truckstate[12] - deltatime elif str(truckstate[7]) == "cd": unload = conn.getUnloadStation(truckstate[3]) trucksinunload = conn.getTrucksInStation(truckstate[3]) queuearrivaltime = 0 #busca posicion de camion actual en cola y calcula tiempo de descarga de camion que se encuentre descargando for truckinunload in trucksinunload: if truckinunload[3] == "cd": #buscar posicion camion en cola if truckstate[1] == truckinunload[1]: #obtener indice queuearrivaltime = truckinunload[4] elif truckinunload[3] == "d": #usar formula de camion cargando que se encuentra en la estacion de descarga deltatime = abs(tCurrent - float(truckinunload[4].replace(",", "."))) estimatedarrivaltime = (truckinunload[9] * unload[2]) + truckinunload[8] - deltatime for truckinunload in trucksinunload: #si el tiempo de llegada del camion que esta en el array es menor o = al tiempo de llegada del camion para calc ta sumar if truckinunload[4] <= queuearrivaltime: deltatime = abs(tCurrent - float(truckinunload[4].replace(",", "."))) estimatedarrivaltime = estimatedarrivaltime + (truckinunload[9] * unload[2]) + truckinunload[8] - deltatime elif str(truckstate[7]) == "c": #camion se encuentra cargando: capacidad camion * vel descarga + tiempo maniobra + tiempo actual - tiempo inicial shovel = conn.getShovel(truckstate[3]) unloadroutes = conn.getRoutesToDestination(truckstate[3], shovel[3]) unload = conn.getUnloadStation(shovel[3]) trucksinunload = conn.getTrucksInStation(shovel[3]) meanunloadroute = 0 queuetime = 0 #calcula distancia promedio de rutas hacia descarga for unloadroute in unloadroutes: meanunloadroute = meanunloadroute + unloadroute[3] meanunloadroute = meanunloadroute/len(unloadroutes) #calcula tiempo de espera en descarga for truckinunload in trucksinunload: deltatime = abs(tCurrent - float(truckinunload[4].replace(",", "."))) queuetime = queuetime + (truckinunload[12] * unload[2]) + truckinunload[11] - deltatime #resultado = (capacidad camion * vel. descarga pala) + tiempo maniobra de camion + (distancia de viaje * vel camion cargado) + tiempo de camiones que estan en la zona de descarga) # - (tiempo actual simulacion -> timeNow - tiempo inicio -> tiempo en el que llego a d) estimatedarrivaltime = (truckstate[12] * shovel[2]) + truckstate[11] + (meanunloadroute * truckstate[11]) + queuetime - deltatime elif str(truckstate[7]) == "cc": #camion se encuentra esperando carga shovel = conn.getShovel(truckstate[3]) trucksinshovel = conn.getTrucksInStation(truckstate[3]) unloadroutes = conn.getRoutesToDestination(truckstate[3], shovel[3]) trucksinunload = conn.getTrucksInStation(shovel[3]) meanunloadroute = 0 queuearrivaltime = 0 queuetime = 0 estimatedarrivaltime = 0 #calcula tiempos aprox para que el camion salga de la pala for truckinshovel in trucksinshovel: if truckinshovel[3] == "cc": if truckstate[1] == truckinshovel[1]: queuearrivaltime = truckinshovel[4] elif truckinshovel[3] == "c": deltatime = abs(tCurrent - float(truckinshovel[4].replace(",", "."))) estimatedarrivaltime = (truckinshovel[9] * shovel[2]) + truckinshovel[8] - deltatime for truckinshovel in trucksinshovel: if truckinshovel[4] <= queuearrivaltime: deltatime = abs(tCurrent - float(truckinshovel[4].replace(",", "."))) estimatedarrivaltime = estimatedarrivaltime + (truckinshovel[9] * shovel[2]) + truckinshovel[8] - deltatime #calcula tiempo de viaje estimado y lo adiciona al estimatedarrivaltime for unloadroute in unloadroutes: meanunloadroute = meanunloadroute + unloadroute[3] meanunloadroute = meanunloadroute/len(unloadroutes) #suma tiempos de los camiones que se encuentran en destino (descarga) for truckinunload in trucksinunload: deltatime = abs(tCurrent - float(truckinunload[4].replace(",", "."))) queuetime = queuetime + (truckinunload[12] * unload[2]) + truckinunload[11] - deltatime estimatedarrivaltime = estimatedarrivaltime + (truckstate[12] * shovel[2]) + truckstate[11] + (meanunloadroute * truckstate[11]) + queuetime - deltatime elif str(truckstate[7]) == "sag": #ya se encuentra en el ultimo estado estimatedarrivaltime = 0 return estimatedarrivaltime # the goal ('fitness') function to be maximized #en mi ag necesito qud se minimize def evalOneMin(individual): #calcular como en TA segun trucksCycleTime = 0 listshovel = individual #recorre cada indice de la lista del individuo for index,value in enumerate(listshovel,1): truck = findTruck(index) if truck[7] != "v": shovelname = "Pala"+str(value) shovel = conn.getShovel(shovelname) #datos obligatorios loadroutes = conn.getRoutesToDestination(truck[3], shovelname) trucksinshovel = conn.getTrucksInStation(shovelname) unloadroutes = conn.getRoutesToDestination(shovel[1], shovel[3]) unload = conn.getUnloadStation(shovel[3]) trucksinunload = conn.getTrucksInStation(shovel[3]) # distancia prom ruta viaje a carga loadmeandistance = 0 for loadroute in loadroutes: loadmeandistance = loadmeandistance + loadroute[3] loadmeandistance = loadmeandistance / len(loadroutes) loadtraveltime = loadmeandistance * truck[12] #suma camiones en carga sumtrucksinshovel = 0 for truckinshovel in trucksinshovel: deltatime = abs(float(tCurrent) -float(truckinshovel[4].replace(",", "."))) sumtrucksinshovel = sumtrucksinshovel + (truckinshovel[9] * shovel[2]) + truckinshovel[8] - deltatime #distancia prom ruta viaje a descarga unloadmeandistance = 0 for unloadroute in unloadroutes: unloadmeandistance = unloadmeandistance + unloadroute[3] unloadmeandistance = unloadmeandistance / len(unloadroutes) unloadtraveltime = unloadmeandistance * truck[12] #suma camiones en descarga sumtrucksinunload = 0 for truckinunload in trucksinunload: deltatime = abs(tCurrent - float(truckinunload[4].replace(",", "."))) sumtrucksinunload = sumtrucksinunload + (truckinunload[9] * unload[2]) + truckinunload[8] - deltatime trucksCycleTime = loadtraveltime + sumtrucksinshovel + unloadtraveltime + sumtrucksinunload #se agrega el TA trucksCycleTime = trucksCycleTime + individual[index-1] #calcular TGA return trucksCycleTime, #return sum(individual), #---------- # Operator registration #---------- # register the goal / fitness function toolbox.register("evaluate", evalOneMin) # register the crossover operator toolbox.register("mate", tools.cxTwoPoint) # register a mutation operator with a probability to # flip each attribute/gene of 0.05 toolbox.register("mutate", tools.mutFlipBit, indpb=0.05) # operator for selecting individuals for breeding the next # generation: each individual of the current generation # is replaced by the 'fittest' (best) of three individuals # drawn randomly from the current generation. toolbox.register("select", tools.selTournament, tournsize=3) # create an initial population of 300 individuals (where # each individual is a list of integers) pop = toolbox.population(n=300) # CXPB is the probability with which two individuals # are crossed # # MUTPB is the probability for mutating an individual CXPB, MUTPB = 0.5, 0.2 print("Start of evolution") # Evaluate the entire population fitnesses = list(map(toolbox.evaluate, pop)) for ind, fit in zip(pop, fitnesses): ind.fitness.values = fit print(" Evaluated %i individuals" % len(pop)) # Extracting all the fitnesses of fits = [ind.fitness.values[0] for ind in pop] # Variable keeping track of the number of generations g = 0 # Begin the evolution #tiempo maximo de ejecucion 1 minuto time_current = int(time.time()/60) while (int(time.time()/60) - time_current) < 1 and g < 500: # A new generation time_current = int(time.time()/60) g = g + 1 print("-- Generation %i --" % g) # Select the next generation individuals offspring = toolbox.select(pop, len(pop)) # Clone the selected individuals offspring = list(map(toolbox.clone, offspring)) # Apply crossover and mutation on the offspring for child1, child2 in zip(offspring[::2], offspring[1::2]): # cross two individuals with probability CXPB if random.random() < CXPB: toolbox.mate(child1, child2) # fitness values of the children # must be recalculated later del child1.fitness.values del child2.fitness.values for mutant in offspring: # mutate an individual with probability MUTPB if random.random() < MUTPB: toolbox.mutate(mutant) del mutant.fitness.values # Evaluate the individuals with an invalid fitness invalid_ind = [ind for ind in offspring if not ind.fitness.valid] fitnesses = map(toolbox.evaluate, invalid_ind) for ind, fit in zip(invalid_ind, fitnesses): ind.fitness.values = fit print(" Evaluated %i individuals" % len(invalid_ind)) # The population is entirely replaced by the offspring pop[:] = offspring # Gather all the fitnesses in one list and print the stats fits = [ind.fitness.values[0] for ind in pop] length = len(pop) mean = sum(fits) / length sum2 = sum(x*x for x in fits) std = abs(sum2 / length - mean**2)**0.5 print(" Min %s" % min(fits)) print(" Max %s" % max(fits)) print(" Avg %s" % mean) print(" Std %s" % std) print("-- End of (successful) evolution --") best_ind = tools.selBest(pop, 1)[0] print("Best individual is %s, %s" % (best_ind, best_ind.fitness.values)) estimated_arrival_time = [] for index, val in enumerate(best_ind, start = 1): ta = calcTA(findTruck(index)) estimated_arrival_time.append(ta) print("mejor individuo, tiempo estimado, fitness") return best_ind, estimated_arrival_time, best_ind.fitness.values
def evalMin(individual): mtct = list() #por cada gen del individuo (camion en posicion 0 del array o lista) for truck, shovel in enumerate(individual): tType = "" #truck type mTime = "" #tiempo maniobra #1. que tipo de camion es? y tiempo de maniobra if 0 <= truck <= truckTypes[0][5]-1: tType = truckTypes[0][0] mTime = truckTypes[0][3] truckEmptySpeed = truckTypes[0][1] if truckTypes[0][5] <= truck <= truckTypes[0][5]+truckTypes[1][5]-1: tType = truckTypes[1][0] mTime = truckTypes[1][3] truckEmptySpeed = truckTypes[1][1] if truck == truckTypes[0][5]+truckTypes[1][5]+truckTypes[2][5]-1: tType = truckTypes[2][0] mTime = truckTypes[2][3] truckEmptySpeed = truckTypes[1][1] #3. tiempo carga = ton/min x capacidad camion #obtener posicion en mapa gen (camion) actual -> se obtiene al comienzo por c# var home #obtener posibles rutas hasta el destino conn = Db.Connect(cdata) #cambiar a ingles todo al final destinationNode = str('Pala'+str(shovel)) routesToDestination = conn.getRoutesToDestination(home, destinationNode) conn.disconnect() route = random.choice(routesToDestination) distance = route[3] estimatedTravelTime = distance * truckEmptySpeed #obtener tiempo espera estimado en cola (para ello consultar camiones que se encuentran en la cola y el tiempo estimado de los que se encuentran camino al mismo destino) conn = Db.Connect(cdata) #buscar cuantos y que tipos de camion se encuentran en cola TrucksInShovel = conn.getTrucksInShovel(destinationNode) #buscar si hay un camion que esta siendo cargado inputTrucksWaitTime = 0 processingTruckLoadTime = 0 totalWaitingTime = 0 shovelData = conn.getShovel(destinationNode) #calcular tiempo aproximado espera antes de que el camion comience a ser cargado por la pala if len(TrucksInShovel) > 0: for truck in TrucksInShovel: truckCapacity = conn.getTruckCapacity(truck[2]) if truck[5] == 'Processing': #tiempo carga = tiempo carga pala x espacio disponible camion processingTruckLoadTime = (shovelData[2] * truckCapacity) elif truck[5] == 'Input': #sumar tiempo carga sgte camion inputTrucksWaitTime = inputTrucksWaitTime + shovelData[0][2] * truckCapacity[4] + mTime #tiempo carga camion processing + tiempo carga camion input totalWaitingTime = processingTruckLoadTime + inputTrucksWaitTime conn.disconnect() #obtener tiempo carga #lista de mtct en i0 guardar: #tiempo de ciclo estimado (tiempo de viaje) + tiempo espera estimado en cola + tiempo maniobra + tiempo carga estimatedcycletime = mTime + estimatedTravelTime + totalWaitingTime mtct.append(estimatedcycletime) #resultado mtct individuo actual mctc1 = list() mctc1.append(sum(mtct)) return mctc1 #suma todos los elementos de la lista devolver como iterable
return mctc1 #suma todos los elementos de la lista devolver como iterable #connection configuration cdata = { "host": "localhost", "username": "******", "password": "", "database": "simio" } #individual structure #define fitness function, minimize in this case, weight negative stands for minimizing fitness creator.create("FitnessMin", base.Fitness, weights=(-1.0,)) creator.create("Individual", list, fitness = creator.FitnessMin) #trucks to create (6 in this test) conn = Db.Connect(cdata) truckTypes = conn.getTruckTypes() for tt in truckTypes: N_TRUCKS += tt[5] #population config toolbox = base.Toolbox() toolbox.register("attr_int", random.randint, MIN, N_SHOVELS) # define los tipos de un individuo toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_int, N_TRUCKS) # define individuo toolbox.register("population", tools.initRepeat, list, toolbox.individual) #crea la poblacion toolbox.register("evaluate", evalMin) toolbox.register("mate", tools.cxTwoPoint) toolbox.register("mutate", tools.mutUniformInt, low=1, up=N_SHOVELS, indpb=0.05) toolbox.register("select", tools.selTournament, tournsize=3)