def _mate_parents(self,p1,p2): size = self.graph.vcount child_tour = np.zeros(self.graph.vcount) + p2.tour while(1) : a = np.random.randint(0, size, 2) if(a[0]!=a[1]): temp = min(a[0],a[1]) a[1] = a[0]+a[1] - temp a[0] = temp break; index_list = [] for i in range(a[0],a[1] + 1): temp = nonzero(p2.tour == p1.tour[i] ) index_list.append(temp[0][0]) index_list.sort() for i in range(index_list.__len__()): temp = a[0] + i child_tour[index_list[i]] = p1.tour[temp] child = Tour() child.tour = child_tour child.tour_cost = self.graph._get_tour_cost(child_tour) return child
def create_netwok(df): network = Network() for tour_id in df[ID].unique(): rows = df[df[ID] == tour_id] if check_tour_data(tour_id, rows) is False: continue general_info = rows.iloc[0] outlet = network.get_outlet(general_info[OUTLET]) inlet = network.get_inlet(general_info[INLET]) if outlet is None: outlet = create_place(general_info, Outlet) if inlet is None: inlet = create_place(general_info, Inlet) if inlet and outlet: new_tour = Tour(tour_id=tour_id, inlet=inlet, outlet=outlet, date=general_info[DATE], driver=general_info[DRIVER], material=general_info[MATERIAL], licence_plate=general_info[DRIPLATE]) else: continue for _, row in rows.iterrows(): client = create_place(row, Client) if client: network.add_client(client) new_tour.add_client(client) network.add_tour(new_tour) return network
def buy_tours(): while True: try: tours = input(''' Tours: 1. Tour en el Puerto 2. Degustacion de comida local 3. Trotar por el pueblo o ciudad 4. Visita a Lugares historicos 5. Regresar a la pagina principal Ingrese la opcion que desee >>> ''') print() tour = Tour(tours) if tours == '1': tour.op1() elif tours == '2': tour.op2() elif tours == '3': tour.op3() elif tours == '4': tour.op4() else: break except: print('Uno de los datos ingresados es invalido')
def __init__(self, tourManager, populationSize, initialise): self.tours = [] for i in range(0, populationSize): self.tours.append(None) if initialise: for i in range(populationSize): newTour = Tour(tourManager) newTour.generateIndividual() self.saveTour(i, newTour)
def choose_tour(): #se le pide el DNI al cliente y se le muestran los tours que provee el crucero while True: try: dni = int(input('DNI: ')) for i, tour in enumerate(Tour.create(), 1): print(f'''\n {i}. {tour.name} - Precio por persona: {tour.price_per_person} - Hasta {tour.group_capacity} personas - Descuento del {tour.discount} % para la tercera y cuarta persona - Empieza a las {tour.time} - Capacidad total: {tour.total_capacity} ''') choice = int(input('Cuál tour desea reservar?: ')) if choice == 1: quantity_of_people = int(input('Cuántas personas son?: ')) #gc = group capacity gc = Tour.create()[0].group_capacity #si su grupo de personas es mayor a la capacidad por grupos del tour, no podrá reservar if quantity_of_people > gc: print(f'No se pueden grupos mayores a {gc} personas') else: print(reserve_tour(quantity_of_people, dni, choice)) #lo mismo que en el 1 elif choice == 2: quantity_of_people = int(input('Cuántas personas son?: ')) gc = Tour.create()[1].group_capacity if quantity_of_people > gc: print(f'No se pueden grupos mayores a {gc} personas') else: print(reserve_tour(quantity_of_people, dni, choice)) elif choice == 3: #aquí no se pide cantidad del grupo de personas porque este tour no tiene límite quantity_of_people = int(input('Cuántas personas son?: ')) print(reserve_tour(quantity_of_people, dni, choice)) #lo mismo que en el 1 elif choice == 4: quantity_of_people = int(input('Cuántas personas son?: ')) gc = Tour.create()[0].group_capacity if quantity_of_people > gc: print(f'No se pueden grupos mayores a {gc} personas') else: print(reserve_tour(quantity_of_people, dni, choice)) else: raise Exception break except: print('Ingrese una opción válida')
def reserve_tour(quantity_of_people, dni, choice): #si aplican descuentos #4 porque los tours que tienen descuento es en la 3ra y 4ta persona if quantity_of_people == 4: #variable que va a indicar cual tour i = choice - 1 final_price = Tour.apply_discount(Tour.create()[i].price_per_person, Tour.create()[i].discount, quantity_of_people) tour_reservation = TourReservation(dni, Tour.create()[i].name, Tour.create()[i].time, final_price) #si no hay ningun descuento else: #variable que va a indicar cual tour i = choice - 1 final_price = Tour.create()[i].price_per_person * quantity_of_people tour_reservation = TourReservation(dni, Tour.create()[i].name, Tour.create()[i].time, final_price) #con Tour.vacancy() chequeo si todavia queda espacio para el tour elegido if Tour.vacancy(i, quantity_of_people): #si queda espacio, se hace la reserva tour_reservation.tour_reservation_file('tour_reservations.txt') tour_reservation.show(quantity_of_people) else: # si no, se le avisa al cliente que no es posible print(f'No quedan suficientes cupos disponibles para el tour {tour_reservation.name}, disculpe.') #retorno esto para que no salga 'none' lol return ''
def _create_init_pop(self): var = [] for i in range(0,self.npop): temp_tour = Tour() temp = np.random.permutation(self.graph.vcount) temp_tour.tour = temp temp_tour.tour_cost = self.graph._get_tour_cost(temp_tour.tour) var.append(temp_tour) self.pop =var; self._modify_costs() self._sort_tours(self.pop)
def __init__(self, populationSize, initialize, numCities): self.tours = [] for i in range(0, populationSize): self.tours.append(None) #*populationSize if (initialize == True): for i in range(0, populationSize): #print "generating tour " + str(i) + "..." newTour = Tour(numCities, i) # pass i as id of this tour newTour.generateIndividual() self.saveTour(i, newTour)
def exhaustiveSearch(points): p0 = points[0] points.remove(p0) permutations = itertools.permutations(points) bestTour = Tour() for perm in permutations: dist = calculatePermutationCost(p0, perm) if (dist < bestTour.pathLength): bestTour.path = perm bestTour.pathLength = dist bestTour.path = list(bestTour.path) bestTour.path.insert(0, p0) return bestTour
def __init__(self, populationSize, initialize, numCities): self.tours = [] for i in range(0, populationSize): self.tours.append(None)#*populationSizeIf anyone remembers what our consensus was on Tyler Pollitt if (initialize == True): for i in range(0, populationSize): #print "generating tour " + str(i) + "..." newTour = Tour(numCities, i) # pass i as id of this tour, only for parent generation newTour.generateIndividual() self.saveTour(i, newTour)
def fill_tours(file_name): tours = [] with open(file_name) as f: for line in f: tour = line[:-1].split(',') new_tour = Tour(int(tour[0]),int(tour[1]),int(tour[2]),float(tour[3]),tour[4]) tours.append(new_tour) return tours
def cross(self, tourParent1, tourParent2): tour_size = tourParent1.getTourSize() parent1 = deepcopy(tourParent1.getTour()) parent2 = deepcopy(tourParent2.getTour()) child = [None] * tour_size index1 = 0 index2 = 0 while index1 == index2: index1 = randint(0, tour_size - 1) index2 = randint(0, tour_size - 1) start_index = min(index1, index2) end_index = max(index1, index2) for i in range(start_index, end_index + 1): child[i] = parent1[i] for i in range(tour_size): if not self.list_contains(child, parent2[i]): for j in range(tour_size): if not child[j]: child[j] = parent2[i] break if None in child: print(child) print('f**k') sys.exit() Child = Tour() Child.set_by_list(child) return Child
def tour(): """[Se encagar de ejecutar cada una de las funcionalidades disponibles para los tours del crucero] """ tour1 = Tour("Tour en el puerto", 30, '3ra y 4ta persona: 10', 4, 10, '7:00 A.M.', 10) tour2 = Tour("Degustación de comida local", 100, 0, 4, 100, '12:00 P.M.', 100) tour3 = Tour("Trotar por el pueblo/ciudad", 0, 0, 'No hay límite', 'No hay límite/', '6:00 A.M.', '') tour4 = Tour("Visita a lugares históricos", 40, '3ra y 4ta persona: 10', 4, 15, '10:00 A.M.', 15) tours = [tour1, tour2, tour3, tour4] if not file_existence("tours_information.txt"): with open("tours_information.txt", 'wb') as file: pickle.dump(tours, file) print("\n¡Bienvenido a Tours del Saman Caribbean!") while True: while True: try: tour_choice = int(input("\n¿Qué función quiere realizar? \n1. Mostrar tours \n2. Vender tour \n3. Salir \n>>> ")) if tour_choice not in range(1,4): raise ValueError break except ValueError: print("\nError: Dato ingresado no forma parte de las opciones dadas\n") if tour_choice==1: tour_information() elif tour_choice==2: if file_existence("clients_information.txt"): purchase_tour() else: print("No se pudo realizar la operación porque no hay clientes registrados") else: print("¡Hasta luego!") break
def main(): menu = [] cruceros = [] #Tours: tour_puerto = Tour("Tour en el puerto", 30, 4, "7:00 AM", 10) tour_degustacion = Tour("Degustacion de comida local", 100, 2, "12:00 PM", 100) tour_trotar = Tour("Tour trotar por el pueblo/ciudad", 0, 0, "6:00 AM", 0) tour_visita = Tour("Visita lugares historicos", 40, 4, "10:00 AM", 15) # Creamos cruceros en el background cruceros = crear_cruceros(cruceros) while True: #Menu para poder escojer que se desea hacer en el sistema opcion = input(''' 🛳 Bienvenidos a Saman Caribbean ¿Qué desea realizar?: 1. Ver cruceros 2. Venta de habitaciónes 3. Compra de tours 4. Restaurante 5. Mostrar estadisticas 6. Salir > ''') if opcion == '1': ver_cruceros(cruceros) elif opcion == '2': gestion_habitacion(cruceros) elif opcion == '3': seleccion_barco_tour(cruceros, clientes) elif opcion == '4': seleccion_barco_restaurante(cruceros) elif opcion == '5': estadisticas() elif opcion == '6': print("Adios 👋!") break else: print("Has ingresado un dato incorrecto!")
def nearestNeighbor(points): p0 = p = points[0] points[0].visited = True i = 0 tour = Tour(list(), 0) tour.path.append(p0) while i < len(points) - 1: i += 1 nextPoint = p.findNearestPoint(points) tour.pathLength += p.distance(nextPoint) p = nextPoint tour.path.append(p) tour.pathLength += p.distance(p0) return tour
def displayOption(): firstTour = Tour("New York, NY", "Lansing, MI") secondTour = Tour("Oakland, CA") thirdTour = Tour("Sacramento, CA", "Oakland, CA") print("""\nFirst Tour:{0} Second Tour:{1} Third Tour:{2}\n""".format(firstTour, secondTour, thirdTour)) print("First tour distances:\n\tDriving: {0} km;\n\tBiking: {1} km;\n\tWalking: {2} km".format( round(firstTour.getDistance("driving")/1000), round(firstTour.getDistance('bicycling')/1000), round(firstTour.getDistance('walking')/1000))) print("\nSecond tour distances:\n\tDriving: {0} km;\n\tBiking: {1} km;\n\tWalking: {2} km".format( round(secondTour.getDistance("driving")/1000), round(secondTour.getDistance('bicycling')/1000), round(secondTour.getDistance('walking')/1000))) print("\nThird tour distances:\n\tDriving: {0} km;\n\tBiking: {1} km;\n\tWalking: {2} km".format( round(thirdTour.getDistance("driving")/1000), round(thirdTour.getDistance('bicycling')/1000), round(thirdTour.getDistance('walking')/1000)))
def evolve_new_pop(self, iteration): """Step algorithm using 'New population' method.""" new_tours = [] # Save best tour _, best_tuple = self.get_best_tours(self.tours) best = self.tours[best_tuple[0]] new_tours.append(best) for i in range(1, len(self.tours)): parent1 = self.tournament_selection() parent2 = self.tournament_selection() child1, child2 = self.crossover(parent1.cities, parent2.cities) t = Tour(self.lx, self.ly) t.set_tour(child1) new_tours.append(t) self.tours = new_tours for i in range(1, len(self.tours)): self.tours[i] = self.mutate(self.tours[i]) _, best_tuple = self.get_best_tours(self.tours) best = self.tours[best_tuple[0]]
def evolve_same_pop(self, iteration): """Step algorithm using 'Sampe population' method.""" bestTwo = self.get_best_tours(self.tours) worstTwo = self.get_worst_tours(self.tours) children1, children2 = self.crossover(self.tours[bestTwo[0][0]].cities, self.tours[bestTwo[1][0]].cities) child1 = Tour(self.lx, self.ly) child2 = Tour(self.lx, self.ly) child1.set_tour(children1) child2.set_tour(children2) if self.tours[worstTwo[0][0]].get_cost() > child1.get_cost(): self.tours[worstTwo[0][0]] = child1 if self.tours[worstTwo[1][0]].get_cost() > child2.get_cost(): self.tours[worstTwo[1][0]] = child2 for i in range(len(self.tours)): self.tours[i] = self.mutate(self.tours[i])
G.add_edge(str(tour[i]),str(tour[i+1])) G.add_edge(str(tour[-1]),str(tour[0])) G.layout("neato") G.write("fuckthis.dot") G.draw(output) def __len__(self): return len(self.matrix) if __name__ == "__main__": #random.seed(1337) mapinfo = Parser().parse(sys.argv[1]) tour = Tour(mapinfo, use_best=True) print "Starting tour:" tour.printTour() #mapinfo.graphvizify(tour.tour, "start.png") print print tour.score lscore = tour.score deltaE = -0.01 iterationsOfNoChange = 0 reheat = False
def user(): next = 0 action = True while action: # loop to quitting the program print( "Please print in the format of the two digits like 44 for 4d, 3d for 44, 11 for 1a \n" ) value = input( "Enter the value of the function\nstart: 1 \nposition: " # prompt of choice "2\nundo: 3\nsave: 4\nrestore: 5\nquit: 6\n") if value == "1": # clear # start position = input( "Please type the positon of the knight on the chess board: ") assert 11 <= int(position) <= 88 and int( position) % 10 != 0, "Not a valid position" # condition t = Tour(position) # initializing the class next = t.next_moves(position) chess_board = t.chess_board() print("\nValid Next movements: ") # Giving direction for the print(next[1]) # first time to the user # new_chess = t.show_move() # for i in range ((new_chess[0])): # print(new_chess[1][i][1]) elif (value == "2"): # position stop = False while not stop: # Loop till valid point by user print( "Please print in the format of the two digits like 44 for 4d, 3d for 44, 11 for 1a \n" ) position = input( "Please print the positon of the knight on the chess board: " ) assert 11 <= int(position) <= 88 and int(position) and int( position) % 10 != 0, "Not a valid position" if next == None: # No next move print("Please execute start") # print(next) # checking for the valid move for knight bool = t.valid_moves(position, next) # checking next move is valid if bool: # print("Valid Position\n") # generating new chess board with positon of the knight next = t.next_moves(position) t.move_knight(position) t.show_move() stop = True else: print("Not valid point. Retry please!") elif value == "3": # undo try: pos = t.undo() next = t.next_moves( pos ) # recalculating the moves of knight from the undo position except: print("Move the knight, can't Undo now") elif value == "4": t.copy() elif value == "5": pos = t.restore() next = t.next_moves( pos ) # recalculating the position of the knight from the restore copy t.show_move() elif value == "6": action = False
def onClick(self): 'Event handler tied to the "Get Distance" button' # Gets the entry fields origin = self.orEntry.get() destination = self.desEntry.get() mode = self.mdEntry.get() #self.showUrl.delete(0.0, END) # List of allowed modes modeList = ['driving', 'biking', 'walking', ''] # An error message pops up if either or both of the entry fields are empty if (origin == '' or destination == ''): showinfo(title = 'Error: Empty Fields!', message = 'Either or both of the Origin or Destination fields are empty.') # An error message pops up if the mode is either of the three types or empty elif (mode not in modeList): showinfo(title = 'Error: Invalid Mode!', message = 'Invalid mode. Valid modes are \'driving\', \'biking\', or \'walking\'.') # If neither of the errors are encountered, then proceeds to calculated distance else: # Builds an instance of the Tour class and calls its distance method aTour = Tour(origin, destination) retVal = aTour.distance(mode) # Separates the distance and the duration distance = retVal[0] duration = retVal[1] # Checks if distance is a number, and then inserts its value into distEntry if (distance.isdigit()): distance = int(distance) self.distEntry.delete(0, END) self.distEntry.insert(INSERT, '{:,}'.format(distance)) # Inserts the url and automatically opens the map on the web browser if (self.zmEntry.get().isdigit() and self.szEntry.get().isdigit() and self.sclEntry.get().isdigit()): zmLevel = int(self.zmEntry.get()) szLevel = int(self.szEntry.get()) sclLevel = int(self.sclEntry.get()) if (zmLevel < 1): self.zmEntry.delete(0, END) self.zmEntry.insert(0, '1') zmLevel = 1 elif (zmLevel > 20): self.zmEntry.delete(0, END) self.zmEntry.insert(0, '20') zmLevel = 20 if (szLevel < 320): self.szEntry.delete(0, END) self.szEntry.insert(0, '320') szLevel = 320 elif (szLevel > 640): self.szEntry.delete(0, END) self.szEntry.insert(0, '640') szLevel = 640 if (sclLevel < 1): self.sclEntry.delete(0, END) self.sclEntry.insert(0, '1') sclLevel = 1 elif (sclLevel > 2): self.sclEntry.delete(0, END) self.sclEntry.insert(0, '2') sclLevel = 2 #self.showUrl.insert(0.0, aTour.map(zoom = zmLevel, size = szLevel, scale = sclLevel)) webbrowser.open_new(aTour.map(zoom = zmLevel, size = szLevel, scale = sclLevel)) else: showinfo(title = 'Error: Invalid Settings!', message = 'Please enter valid values in each of the settings.') # Here it inserts the duration into the durEntry after converting it if (duration.isdigit()): duration = int(duration) m, s = divmod(duration, 60) h, m = divmod(m, 60) d, h = divmod(h, 24) duration = ("%dd %dh %02dm %02ds" % (d, h, m, s)) else: duration = 0 self.durEntry.delete(0, END) self.durEntry.insert(INSERT, duration) # If the value that is returned is a string, it prints it as an error message instead else: showinfo(title = 'Error: Distance not found!', message = distance)
from Tour import Tour import StdDraw filename = sys.argv[1] with open(filename, 'r') as file: lines = file.read().split() file.close() # get dimensions w = int(lines[0]) h = int(lines[1]) StdDraw.setCanvasSize(w, h) StdDraw.setXscale(0, w) StdDraw.setYscale(0, h) tour = Tour() tourList = [] for i in range(2, len(lines), 2): x = float(lines[i]) y = float(lines[i + 1]) p = Point(x, y) tourList = tour.list(p, tourList) tour.farthestInsertion(tourList) # draw to standard draw tour.draw() check = True while check: StdDraw.show(5000) if StdDraw.hasNextKeyTyped():
with open(filename, 'r') as file: lines = file.read().split() file.close() # get dimensions w = int(lines[0]) h = int(lines[1]) StdDraw.setCanvasSize(w, h) StdDraw.setXscale(0, w) StdDraw.setYscale(0, h) # turn on animation mode StdDraw.show(0) # run nearest insertion heuristic tour = Tour() for i in range(2, len(lines), 2): x = float(lines[i]) y = float(lines[i + 1]) p = Point(x, y) tour.insertNearest(p) if delay > -1: StdDraw.clear() tour.draw() StdDraw.show(delay) # draw to standard draw tour.draw() StdDraw.show(5000) # print tour to standard output
def initia_pop(self, tourmanager): for i in range(self.pop_size): tour = Tour() tour.generate_one_tour(tourmanager) self.pop.append(tour)
class GA_TSP: #object to hold graph graph = TSP_Graph("",0) #size of the population npop = 0 #max number of generation max_g = 100; #current population pop = [] #mating pool mating_pool = [] #store the average cost of each generation average_cost = [] #min cost of each generation min_cost = [] modified_pop_cost = 0 best_tour = Tour() def __init__(self, filename): self.graph = TSP_Graph(filename, 15) self.graph._read_data() self.npop = self.graph.vcount * 2 def _create_init_pop(self): var = [] for i in range(0,self.npop): temp_tour = Tour() temp = np.random.permutation(self.graph.vcount) temp_tour.tour = temp temp_tour.tour_cost = self.graph._get_tour_cost(temp_tour.tour) var.append(temp_tour) self.pop =var; self._modify_costs() self._sort_tours(self.pop) def _sort_tours(self, pop): self.pop = sorted(pop, key=lambda x: x.tour_cost) def _modify_costs(self): sum_cost = 0; min_cost = sys.maxint self.modified_pop_cost = 0 for i in range(0,self.npop): sum_cost = sum_cost + self.pop[i].tour_cost if(min_cost > self.pop[i].tour_cost): min_cost = self.pop[i].tour_cost self.best_tour = self.pop[i] for i in range(0,self.npop): self.pop[i].tour_cost = sum_cost - self.pop[i].tour_cost self.modified_pop_cost = self.modified_pop_cost + self.pop[i].tour_cost self.average_cost.append(sum_cost/self.npop) self.min_cost.append(min_cost) def _create_mating_pool(self): for i in range(self.npop): rand = np.random.randint(0, self.modified_pop_cost + 1) for t in self.pop : rand = rand - t.tour_cost if(rand <= 0): self.mating_pool.append(t) break #print("printing pop") #self._print_pool(self.pop) #print("print mate pop") #self._print_pool(self.mating_pool) def _get_next_gen(self): self._create_mating_pool() new_pop = [] temp = self.npop/2 for i in range(0,temp): a,b = np.random.randint(0, self.npop, 2) #print(i,a,b) child1 = self._get_child(self.mating_pool[a], self.mating_pool[b] ) child2 = self._get_child(self.mating_pool[b], self.mating_pool[a] ) new_pop.append(child1) new_pop.append(child2) self.pop = new_pop self._modify_costs() self._sort_tours(self.pop) self.mating_pool = [] def _get_child(self, p1,p2): child = self._mate_parents(p1,p2) return child def _mate_parents(self,p1,p2): size = self.graph.vcount child_tour = np.zeros(self.graph.vcount) + p2.tour while(1) : a = np.random.randint(0, size, 2) if(a[0]!=a[1]): temp = min(a[0],a[1]) a[1] = a[0]+a[1] - temp a[0] = temp break; index_list = [] for i in range(a[0],a[1] + 1): temp = nonzero(p2.tour == p1.tour[i] ) index_list.append(temp[0][0]) index_list.sort() for i in range(index_list.__len__()): temp = a[0] + i child_tour[index_list[i]] = p1.tour[temp] child = Tour() child.tour = child_tour child.tour_cost = self.graph._get_tour_cost(child_tour) return child def _run(self): self._create_init_pop(); for i in range(0,self.max_g): #print(self.npop,self.pop.__len__(),self.mating_pool.__len__()) self._get_next_gen() print("generation " , i ) return self.best_tour def _print_pool(self, pool): for t in pool: print(t.tour.tolist(), t.tour_cost)
def crossover(self, parent1, parent2, numCities): child = Tour(numCities) startPos = int(random.random() * parent1.tourSize()) endPos = int(random.random() * parent1.tourSize()) # parent 1 for i in range(0, child.tourSize()): # add city to child tour from parent1 that is between startPos and endPos if ((startPos < endPos) and (i > startPos) and (i < endPos)): child.setCity(i, parent1.getCity(i)) elif (startPos > endPos): if not((i < startPos) and (i > endPos)): child.setCity(i, parent1.getCity(i)) # parent 2 for i in range(0, parent2.tourSize()): if not(child.containsCity(parent2.getCity(i))): for j in range(0, child.tourSize()): try: if (child.getCity(j) == None): child.setCity(j, parent2.getCity(i)) break except IndexError: a = raw_input("IndexError in crossover mutation.") child.setCity(j, parent2.getCity(i)) return child
except: print("Output file does not exist") return distance, x, y totalScore = 0.0 # Create an empty Tour object score = 0.0 try: # define 4 points forming a square a = Point(100.0, 100.0) b = Point(500.0, 100.0) c = Point(500.0, 500.0) d = Point(100.0, 500.0) tour = Tour() # Create an empty tour score += 2.0 # Compiles and runs score += 2.0 # __init__() works totalScore = score except: print("Tour class not implemented according to instructions") finally: print("Score for program compilation and execution: " + str(score) + "/4.0") # Test each method # 1. insertInOrder() score = 0.0 try: # first check to see if it is implemented
from Point import Point from Tour import Tour import StdDraw filename = sys.argv[1] with open(filename, 'r') as file: lines = file.read().split() file.close() w = int(lines[0]) h = int(lines[1]) StdDraw.setCanvasSize(w, h) StdDraw.setXscale(0, w) StdDraw.setYscale(0, h) tourList = Tour() tour = Tour() for i in range(2, len(lines), 2): x = float(lines[i]) y = float(lines[i + 1]) p = Point(x, y) tourList.insertInOrder(p) tour.insertInOrder(p) print("Tour distance = " + str(tour.distance())) tour.draw() StdDraw.show(1) tour.cyclePoints(tourList) tour.draw()
def crossover(self, parent1, parent2): #New child tour child = Tour(self.tourmanager) #Get start and end sub-tour positions ofr parent1's tour startPos = int(random.random() * parent1.tourSize()) endPos = int(random.random() * parent1.tourSize()) #Loop and add the subtour from parent1 to the child for i in range(0, child.tourSize()): #If the start position is less than the end position if startPos < endPos and i > startPos and i < endPos: child.setCity(i, parent1.getCity(i)) #If the start position is larger elif startPos > endPos: if not (i < startPos and i > endPos): child.setCity(i, parent1.getCity(i)) #Loop through parent2's city tour for i in range(0, parent2.tourSize()): #If the child doesn't have the city, add it if not child.containsCity(parent2.getCity(i)): #Find an open spot in the child's tour for ii in range(0, child.tourSize()): #When an open spot is found, add city if child.getCity(ii) == None: child.setCity(ii, parent2.getCity(i)) break return child
with open(filename, 'r') as file: lines = file.read().split() file.close() # get dimensions w = int(lines[0]) h = int(lines[1]) StdDraw.setCanvasSize(w, h) StdDraw.setXscale(0, w) StdDraw.setYscale(0, h) # turn on animation mode StdDraw.show(0) # run in order insertion heuristic tour = Tour() for i in range(2, len(lines), 2): x = float(lines[i]) y = float(lines[i + 1]) p = Point(x, y) tour.insertInOrder(p) if delay > -1: StdDraw.clear() tour.draw() StdDraw.show(delay) # draw to standard draw tour.draw() StdDraw.show(5000) # print tour to standard output
def crossover(self, parenti, parentii): child = Tour(self.tourManager) startPos = int(random.random() * parenti.tourSize()) endPos = int(random.random() * parentii.tourSize()) for i in range(child.tourSize()): if startPos < endPos and startPos < i < endPos: child.setCity(i, parenti.getCity(i)) elif startPos > endPos: if not startPos < i < endPos: child.setCity(i, parenti.getCity(i)) for i in range(parentii.tourSize()): if not child.containsCity(parentii.getCity(i)): for j in range(child.tourSize()): if child.getCity(j) is None: child.setCity(j, parentii.getCity(i)) break return child
def sell_tours(cruise, cruise_answer): """ Funcion que permite vender tours a los clientes hospedados en un respectivo crucero, ademas de almacenar los datos de dichas ventas """ #Primero se valida si existe un archivo con los datos de tours comprados en el crucero, de ser asi se llena una lista con los datos guardados en el mismo, de lo contrario se crea la lista vacía tours_file = "tours_cruise" + str(cruise_answer) + ".txt" count_tours = fm.check_empty(tours_file) if count_tours: tours = [] else: tours = fm.fill_tours(tours_file) #Primero se valida si existe un archivo con los datos de clientes hospedados en el crucero, de ser asi se llena una lista con los datos guardados en el mismo, de lo contrario se crea la lista vacía clients_file = "clients_cruise" + str(cruise_answer) + ".txt" count_clients = fm.check_empty(clients_file) if count_clients: clients = [] else: clients = fm.fill_clients(clients_file) while True: try: dni = int(input('Por favor ingrese su dni:')) break except: print('Valor invalido. Intente nuevamente') #Se valida si la lista clientes no esta vacia, de estarlo se indica que no hay clientes hospedados en el crucero especificado if len(clients) != 0: #Se busca la cedula ingresada en la base de datos para validar si se encuentra registrado. De no estarlo no podrá comprar un tour search_dni = search_available(clients, 0, dni, 2) if search_dni != "No encontrado" and clients[ search_dni].room_id != "Salió": tour_answer = select_tour() people_quantity = input_people_quantity() payment = tour_price(tour_answer, people_quantity) time = tour_time(tour_answer) limit = tour_limit(tour_answer) if len(tours) == 0: #Si payment es igual a none, significa que no se pudo comprar el tour ya que se exedio la cantidad de personas if payment != None: new_tour = Tour(dni, tour_answer, people_quantity, payment, time) #Se crea un archivo que contenga los datos del Tour comprado tours.append(new_tour) fm.create_tour_txt(tours, tours_file) #Se actualiza la base de datos de clientes indicando lo que pago en el tour clients[search_dni].tour = payment fm.create_client_txt(clients, clients_file) tour_bill(clients[search_dni], payment) print("Compra de tour exitosa") else: dni_tours = [] search_dni_tours = search_available(tours, 0, dni, 2) first_tour_index = 0 while first_tour_index < len(tours): found_tour_index = search_available( tours, first_tour_index, tour_answer, 5) if found_tour_index != "No encontrado": dni_tours.append(found_tour_index) first_tour_index = found_tour_index first_tour_index += 1 else: first_tour_index += 1 print(dni_tours) if search_dni_tours != "No encontrado" and tours[ search_dni_tours].tour_id == tour_answer: print("No puede comprar el mismo tour varias veces") else: if payment != None: total_people = 0 if len(dni_tours) != 0: for i in dni_tours: total_people += tours[i].people_quantity print(limit) print(total_people + people_quantity) #Se valida que no se exceda el cupo admitido de personas para el Tour if (total_people + people_quantity) > limit and limit != False: print( f"Lo sentimos, no hay cupos suficientes para {people_quantity} personas" ) else: new_tour = Tour(dni, tour_answer, people_quantity, payment, time) tours.append(new_tour) fm.create_tour_txt(tours, tours_file) clients[search_dni].tour += payment fm.create_client_txt(clients, clients_file) tour_bill(clients[search_dni], payment) print("Compra de tour exitosa") else: print( "El numero de cedula ingresado no se encuentra en la base de datos" ) else: print("No hay clientes hospedados en este crucero")
def __init__(self): for i in xrange(20): city = City() add_city(city) temp = 10000 cooling_rate = 0.003 current_solution = Tour() current_solution.generate_individual() print "Initial distance:", current_solution.get_distance() best = Tour(current_solution.get_tour()) while temp > 1: new_solution = Tour(current_solution.get_tour()) tour_pos1 = int(new_solution.tour_size() * random()) tour_pos2 = int(new_solution.tour_size() * random()) city_swap1 = new_solution.get_city(tour_pos1) city_swap2 = new_solution.get_city(tour_pos2) new_solution.set_city(tour_pos2, city_swap1) new_solution.set_city(tour_pos1, city_swap2) current_energy = current_solution.get_distance() neighbour_energy = new_solution.get_distance() if self.acceptance_probability(current_energy, neighbour_energy, temp) > random(): current_solution = Tour(new_solution.get_tour()) if current_solution.get_distance() < best.get_distance(): best = Tour(current_solution.get_tour()) temp *= 1 - cooling_rate print 'Final distance:', best.get_distance() print 'Tour:', best self.plot_graph(best)