def findPath(net, startnode, finalnode): # a path longer than max_len must contain # loops max_len = len(net.get_nodes()) # Gamma is temporary list of instances if Path, # Pi contains only the paths from startnode to finalnode Gamma = [] Pi = [] # initialize the first paths as Path from startnode # to starnode.get_childen() for edge in startnode.get_edges_out(): temp_path = Path.Path(edge.get_parent(), edge.get_child(), edge) if temp_path.get_last() == finalnode: Pi.append(temp_path) else: Gamma.append(temp_path) # this happens if startnode.get_children()=finalnode if len(Gamma) == 0: return (Pi) i = 0 while True: i = i + 1 # only for emergency break # Gamma gets updated by remove Gamma[0] and Gamma.append path = Gamma[0] temp_node = path.get_last() # in each iteration, take the last node and append # the child of each edge in edges_out for edge in temp_node.get_edges_out(): temp_path = Path.concatenate( path, Path.Path(edge.get_parent(), edge.get_child(), edge)) #print('temp_path') #temp_path.show() if temp_path.get_last() == finalnode: Pi.append(temp_path) #print('added') elif not temp_path.get_last() in path.get_nodes(): Gamma.append(temp_path) #print('appended') Gamma.remove(path) if len(Gamma) == 0: #print('Empty Gamma') break elif Gamma[-1].len() > max_len: print('max_len reached') break # arbitrary emergency break to avoid unexpectedly long # computation times elif i > 10000: print('findPath stopped after ' + str(i) + ' combinations') break return (Pi)
def carrinheiro(id_user, date): user_carrinheiro = User.get_user(id_user, DATABASE_DIRECTORY) path = Path.Path(user_carrinheiro, date, DATABASE_DIRECTORY) stop_points = scenario_stop_points(path) # download the osm file (scenario) file_name_osm = OpenSteetMap.file_osm(MAPS_DIRECTORY, stop_points) # download the GeoTiff file (scenario) geotiff_name = GeoTiff.geotiff(MAPS_DIRECTORY, stop_points) G, nodes_coordinates, nodes_mass_increment = graph_scenario( stop_points, geotiff_name, path.material_weights, file_name_osm) H = Graph_Collect.create_graph_route(nodes_coordinates, nodes_mass_increment) index_coordinate_start = list(nodes_coordinates.values()).index( path.start_point) node_source = list(nodes_coordinates.keys())[index_coordinate_start] index_coordinate_end = list(nodes_coordinates.values()).index( path.end_point) node_target = list(nodes_coordinates.keys())[index_coordinate_end] cost_total, paths = closest_insertion_path(G, H, node_source, node_target) for i in paths: fig, ax = ox.plot_graph_route(G, i, route_linewidth=6, node_size=0, bgcolor='w') return paths
def initialize_columns(instance): """ Se inicializan las columnas: cada cliente es atendido exclusivamente por un vehículo con la capacidad mínima entre todos los vehículos que pueden satisfacerlo. """ routes = [] clients = set(instance.demand) clients.remove(0) for i in clients: # Entre los vehículos que pueden satisface la demanda de i, elegimos al de menor capacidad k = min((v for v, c in instance.cap.items() if c >= instance.demand[i]), key=lambda v: instance.cap[v]) path = Path(k) path.add_node(i, instance) routes.append(Route.from_path(path, instance)) return routes
def find_paths(city1, city2, city_edges, max_cost, scoring, player=None, edge_claims=None): """ Find all paths that connect two cities for less than the max_cost. :param city1: The first city to connect. :param city2: The second city to connect. :param city_edges: All of the edges that make up the map. :param max_cost: The maximum cost of all paths returned. :param scoring: The scoring dictionary for the game. :param player: Optional parameter for a player. If included, all edges owned by the player have 0 cost. :param edge_claims: Optional parameter for edge_claims. If included, all edges owned by the player have 0 cost. :return: A list of paths. """ queue = deque() result = [] # Put the first city into the queue. queue.append((city1, set(city1), Path(set(), scoring, player, edge_claims))) iteration = 0 while queue and iteration < MAX_PATH_ITER and len(result) < MAX_NUM_PATH: city, visited, path = queue.popleft() iteration += 1 # Add all neighbors to the queue. for outgoing_edge in city_edges[city]: other_city = outgoing_edge.other_city(city) # First line makes sure the edge isn't already in the path and it's below max cost. # Second and third line make sure it's not claimed by another player, if that matters. if other_city not in visited and path.cost + outgoing_edge.cost <= max_cost \ and ((edge_claims is None and player is None) or edge_claims[outgoing_edge] is None or edge_claims[outgoing_edge] == player.name): # Create a copy of the path thus far with the new edge added. updated_path = deepcopy(path) updated_path.add_edge(outgoing_edge, scoring, player, edge_claims) if other_city == city2: # The updated path is a valid path between the two cities. result.append(updated_path) else: # Add the updated path and new city to the queue. queue.append((other_city, visited.union(set(other_city)), updated_path)) return result
def find_paths_for_destinations(destinations, city_edges, max_cost, scoring=get_scoring(), player=None, edge_claims=None, sort_paths=True): """ Finds all paths that connect all destinations for less than the max_cost. :param destinations: A list of the destinations to connect. :param city_edges: All of the edges that make up the map. :param max_cost: The maximum cost of all paths returned. :param scoring: The scoring dictionary for the game. :param player: Optional parameter for a player. If included, all edges owned by the player have 0 cost. :param edge_claims: Optional parameter for edge_claims. If included, all edges owned by the player have 0 cost. :param sort_paths: Optional boolean to sort the paths. By default, will sort paths by cost. :return: A list of paths, ordered with sort method. Paths may not be continuous. """ dest_paths = {} all_paths = [] # First step: get candidate paths. for dest in destinations: # Perform breadth first search to get all paths below the max_cost. dest_paths[dest] = find_paths(dest.city1, dest.city2, city_edges, max_cost, scoring, player, edge_claims) # Second step: Combine paths to get a list of all possible paths that hit everything for less than the max_cost. for dest in dest_paths: # For the first destination, just dump in all the paths currently found. if not all_paths: all_paths = dest_paths[dest] # For any destination past the first, combine with the existing paths to create new ones, only counting # duplicates once in the new path, thus possibly reducing cost. else: working_paths = all_paths all_paths = [] for path1 in working_paths: for path2 in dest_paths[dest]: # Combine the paths and add them to all_paths if they're still below max_cost. combined_path = Path(path1.edges.union(path2.edges), scoring, player, edge_claims) if combined_path.cost <= max_cost: all_paths.append(combined_path) # Third step: Sort by path cost in ascending order. if sort_paths: return sorted(all_paths, key=Path.default_sort_method) else: return all_paths
def get_paths(height: int, lines: List[str], width: int) -> List[Path]: paths: List[Path] = [] # standard format implies width % 3 == 1 number_of_paths = int(1 + (width - 1) / 3) # removing spaces to work on values ranks top_values_line = lines[1].replace(" ", "") bottom_values_line = lines[height].replace(" ", "") check_line(top_values_line, number_of_paths) check_line(bottom_values_line, number_of_paths) paths = [ Path(top_values_line[i], bottom_values_line[i]) for i in range(number_of_paths) ] return paths
def game_loop(game_level): room = pygame.image.load("Living RoomWithStuff.png").convert() # Living Room.jpg") menu = pygame.image.load("BoxWithElements.png").convert_alpha() # Menu is 1025 x 196 timer_offset = 0 menu_timer_fill = pygame.image.load("Timer.png").convert() menu_timer_background = pygame.image.load("WhiteBox.png").convert() menu_objective = pygame.image.load("Controls.png").convert() start_time = pygame.time.get_ticks() # Time from the beginning of execution cycle_time = pygame.time.get_ticks() # Time of each cycle or loop iteration time_counter = 0 #ghost_guy = ghost("boo.png") # Player Sprite declaration ############## player_position = vector2(352, 114) player_sprite = Player("WalkingSheet.png", player_position) # Object declaration, spray ID = 01, tape ID = 02, dog_toy ID = 03 spray = Objects("SprayDarkLine.png", vector2(820, 444), 01) tape = Objects("Object_Tape.png", vector2(630, 280), 02) dog_toy = Objects("Object_DogToy.png", vector2(400, 530), 03) dog_bags = Objects("Object_DogBag.png", vector2(160, 308), 04) trash_can = Objects("Object_TrashCan.png", vector2(0, 450), 05) # Stores all objects into object_list #object_list = [spray, tape, dog_toy, dog_bags, trash_can] object_list = [spray, dog_bags] # Path declaration, 6 points for dog to travel too path_list = [Path(vector2(750, 510), vector2(60, 40)), Path(vector2(160, 528), vector2(60, 40)), Path(vector2(350, 400), vector2(60, 40)), Path(vector2(550, 340), vector2(60, 40)), Path(vector2(620, 500), vector2(60, 40)), Path(vector2(250, 340), vector2(60, 40))] # Puppy declaration and setup puppy_position = path_list[0].pos puppy_speed = vector2(0, 0) puppy_sprite = Puppy("dogresized.png", puppy_position, puppy_speed) # Pup clone: Better to start together or sep? puppy_position2 = path_list[2].pos puppy_speed2 = vector2(0, 0) puppy_sprite2 = Puppy("dogresized.png", puppy_position, puppy_speed2) pup_list = [puppy_sprite] if game_level >= 2: pup_list.append(puppy_sprite2) # Sets object status as active for first puppy path for pup in pup_list: pup.change_path(path_list) # Game loop setup frame_clock = pygame.time.Clock() FPS = 60 game_running = True while game_running: frame_clock.tick(FPS) # get user events pygame.event.pump() for evt in pygame.event.get(): # print(evt) # Prints all key and mouse events if evt.type == pygame.QUIT: pygame.quit() sys.exit() sprinting = False # Not sure if this is correct ######## if evt.type == pygame.KEYDOWN: if evt.key == pygame.K_ESCAPE: pygame.quit sys.exit() if evt.key == pygame.K_w: # Up player_sprite.moving = True elif evt.key == pygame.K_s: player_sprite.moving = True elif evt.key == pygame.K_a: player_sprite.moving = True elif evt.key == pygame.K_d: player_sprite.moving = True elif evt.key == pygame.K_SPACE: sprinting = True # Equip items tree if evt.key == pygame.K_j: player_sprite.looking_for_item = True else: player_sprite.looking_for_item = False else: player_sprite.moving = False # Pressed keys are assigned an action keys_pressed = pygame.key.get_pressed() # Movement speed increase with 'sprint' if keys_pressed[pygame.K_w]: player_sprite.moving = True player_sprite.timer = 0 player_sprite.side = 3 player_sprite.move(0, -4, sprinting) if keys_pressed[pygame.K_s]: player_sprite.moving = True player_sprite.timer = 0 player_sprite.side = 0 player_sprite.move(0, 4, sprinting) if keys_pressed[pygame.K_a]: player_sprite.moving = True player_sprite.timer = 0 player_sprite.side = 2 player_sprite.move(-4, 0, sprinting) if keys_pressed[pygame.K_d]: player_sprite.moving = True player_sprite.timer = 0 player_sprite.side = 1 player_sprite.move(4, 0, sprinting) if keys_pressed[pygame.K_k]: player_sprite.cleanup = True else: player_sprite.cleanup = False # SIMULATION --------------------------- # UPDATE end = pygame.time.get_ticks() delta_time = end - cycle_time cycle_time = end # Game Timer functions counting_time = pygame.time.get_ticks() - start_time counting_seconds = int(counting_time % 60000 / 1000) # print(counting_seconds) # Using get_ticks, counting seconds currently times game if counting_seconds != time_counter: time_counter += 1 timer_offset += 5 # If the timer has exceeded 59 seconds, game over screen if counting_seconds == 59: game_running = False return path_list # Checks if player is touching any objects, works for obj in object_list: player_sprite.update(obj, delta_time) for pup in pup_list: # Moves towards active target, returns True if reached if pup.move(delta_time): # Set new active area when destination reached print("Reached point, in Main loop") for path in path_list: path.update(pup) pup.change_path(path_list) # Is the player in the path area for cleanup for path in path_list: if path.status == 'warning': path.update(player_sprite) # DRAW SECTION (from back to front) Room, paths, player, Pup, menu, objects################## screen.blit(room, (0, 0)) # Draws each object to room for path in path_list: path.draw(screen) # draws the unequipped items for obj in object_list: if not obj.item_held: obj.draw(screen) player_sprite.draw(screen) for pup in pup_list: pup.draw(screen) screen.blit(menu_timer_background, (5, 584)) screen.blit(menu_timer_fill, (5 - timer_offset, 594)) # 305 x 146 # 1 sec 5 pixel screen.blit(menu, (0, 572)) screen.blit(menu_objective, (782, 628)) #draws equipped items for obj in object_list: if obj.item_held: obj.draw(screen) pygame.display.flip()
N = Net.Network() for i in range(1, 10): N.add_node('x' + str(i), 0) N.add_error_node('x1') N.add_error_node('x2') N.add_observed_node('x6') N.add_observed_node('x7') N.add_dynamic_equation('x1', '-x1 + 0.5 * x9 ') for i in range(2, 10): N.add_dynamic_equation('x' + str(i), '-x' + str(i) + ' + 0.5 * x' + str(i - 1)) ############################# print(N.children('x2')) print(N.parents('x2')) ############################# P = Path.Path('x1') P.append_node('x2') print(P.get_sequence()) print(P.children('x1')) print(P.parents('x2')) print(P.len())
def solve_SPk(pi, lamb, k, instance): """ Se resulve el problema \bar{SP} restringido al tipo de vehículo k. Se utiliza el procedimiento de etiquetas detallada en la tercera sección del informe. :param pi: diccionario con los valores óptimos de las variables del dual correspondiente al primer conjunto de restricciones de CLP :type pi: dict :param lamb: diccionario con los valores óptimos de las variables del dual correspondiente al primer conjunto de restricciones de CLP :type lamb: dict :param k: tipo de vehículo :type k: int :param instance: datos del problema :type instance: Instance :return: ruta con menor costo reducido para el tipo de vehículo k y su costo reducido :rtype: Route, float """ pi[0] = lamb[k] bk = instance.cap[k] # Removemos a los clientes cuya demanda supera a bk nodes = set(filter(lambda c: instance.demand[c] <= bk, instance.demand)) clients = nodes.difference({0}) # Se define la matriz de costos del subgrafo \bar{G}_k cost_matrix = make_cost_matrix(pi, k, instance) # Se inicializa el estado del depósito warehouse_label = Label.warehouse_label() # Se crean los conjuntos de estados cuya cota superior coincide con su cota inferior P = {j: [] for j in clients} P[0] = [warehouse_label] L = deque([warehouse_label]) while L: label = L.popleft() for j in filter(lambda c: label.q + instance.demand[c] <= bk and c != label.pred and c != label.node, clients): new_label = Label(label.q + instance.demand[j], j) new_label.path = label.path + [j] new_label.pred = label.node new_label.reduced_cost = get_reduced_cost(new_label, cost_matrix, instance, k) dominates = [] dominated = False # Se chequea si la nueva etiqueta no está dominada for s in P[j]: if s.reduced_cost > new_label.reduced_cost: dominates.append(s) elif s.reduced_cost < new_label.reduced_cost: dominated = True break if not dominated: # Se encola la nueva etiqueta L.append(new_label) P[j].append(new_label) # Se eliminan todas las etiquetas dominadas por la nueva for s in dominates: P[j].remove(s) try: L.remove(s) except ValueError: pass best_state = min((s for s in chain.from_iterable(P.values())), key=lambda s: getattr(s, 'reduced_cost')) best_path = Path.from_sequence(best_state.path, instance, k) return Route.from_path(best_path, instance), get_reduced_cost(best_state, cost_matrix, instance, k)
def pulling_algorithm(pi, lamb, k, instance): """ Método para resolver \bar{SP} restringido al tipo de vehículo k desarrollado por Desrochers. No utilizado para resolver las instancias. :param pi: diccionario con los valores óptimos de las variables del dual correspondiente al primer conjunto de restricciones de CLP :type pi: dict :param lamb: diccionario con los valores óptimos de las variables del dual correspondiente al primer conjunto de restricciones de CLP :type lamb: dict :param k: tipo de vehículo :type k: int :param instance: datos del problema :type instance: Instance :return: ruta con menor costo reducido para el tipo de vehículo k y su costo reducido :rtype: Route, float """ pi[0] = lamb[k] bk = instance.cap[k] # Removemos a los clientes cuya demanda supera a bk nodes = set(filter(lambda c: instance.demand[c] <= bk, instance.demand)) clients = nodes.difference({0}) # Se define la matriz de costos del subgrafo \bar{G}_k cost_matrix = make_cost_matrix(pi, k, instance) # Se inicilizan los estados de los nodos correspondientes a los clientes states = [State(q, j) for j in clients for q in range(instance.demand[j], bk + 1)] # Se inicializa el estado del depósito depo_state = State.warehouse_state() states.append(depo_state) # Se crean los conjuntos de estados cuya cota superior coincide con su cota inferior P = {j: [] for j in clients} P[0] = [depo_state] # Consideramos el conjunto W de estados cuyas cotas no coinciden W = deque(sorted([s for s in states if s.ub != s.lb], key=lambda s: (s.q, s.node))) best_state = None best_rc = 1e6 while W: # Entre los estados de cada j cuya cotas no coinciden, elegimos el que tiene menor q. Ante empates, elegimos el # que tiene menor j state = W.popleft() # Actualizamos la cota superior del estado. Primero calculamos el estado previo a (q,j) para el cual se realiza # el mínimo demand_bound = state.q - instance.demand[state.node] candidate_states = [s for s in states if s.node != state.node and s.q <= demand_bound] candidate_phis = [phi(s, state.node, cost_matrix) for s in candidate_states] prev_state, prev_phi = get_prev_state(candidate_states, candidate_phis) state.pred = prev_state.node state.ub = prev_phi state.path = prev_state.path + [state.node] # Se actualiza la cota superior del segundo mejor camino. Si el conjunto sobre el que se toma el mínimo es # vacío, la cota no se altera state.sub = get_secondary_ub(candidate_states, candidate_phis, state.pred) # Se actualiza la cota inferior del estado state.lb = min(map(lambda s: s.lb + cost_matrix[s.node][state.node], candidate_states)) # Actualizamos Pj de ser necesario: if isclose(state.lb, state.ub): P[state.node].append(state) state_rc = get_reduced_cost(state, cost_matrix, instance, k) if state_rc < best_rc: best_rc = state_rc best_state = state best_path = Path.from_sequence(best_state.path, instance, k) return Route.from_path(best_path, instance), get_reduced_cost(best_state, cost_matrix, instance, k)
def game_loop(): room = pygame.image.load("Living RoomWithStuff.png") # Living Room.jpg") menu = pygame.image.load("BoxWithElements.png").convert_alpha() # Menu is 1025 x 196 ########################### start_time = pygame.time.get_ticks( ) # Time from the beginning of execution cycle_time = pygame.time.get_ticks( ) # Time of each cycle or loop iteration time_counter = 0 # Player Sprite declaration ############## player_position = vector2(352, 114) player_sprite = Player("WalkingSheet.png", player_position) # Object declaration spray = Objects("Object_Spray.png", vector2(200, 430)) tape = Objects("Object_Tape.png", vector2(300, 330)) dog_toy = Objects("Object_DogToy.png", vector2(400, 530)) # Stores all objects into object_list object_list = [spray, tape, dog_toy] # Path declaration, 6 points for dog to travel too path_list = [ Path(vector2(750, 300), vector2(40, 40)), Path(vector2(110, 370), vector2(40, 40)), Path(vector2(304, 420), vector2(40, 40)), Path(vector2(750, 300), vector2(40, 40)), Path(vector2(620, 100), vector2(40, 40)), Path(vector2(250, 250), vector2(40, 40)) ] # Sets object status as active for first puppy path change_point(path_list) # Puppy declaration and setup puppy_position = path_list[0].pos puppy_speed = vector2(0, 0) puppy_sprite = Puppy("DogSpriteSpreadfinal.png", puppy_position, puppy_speed) # Game loop setup frame_clock = pygame.time.Clock() FPS = 60 game_running = True while game_running: frame_clock.tick(FPS) # get user events pygame.event.pump() for evt in pygame.event.get(): # print(evt) # Prints all key and mouse events if evt.type == pygame.QUIT: pygame.quit() sys.exit() elif evt.type == pygame.KEYDOWN and evt.key == pygame.K_ESCAPE: pygame.quit sys.exit() sprinting = False player_sprite.moving = False # Not sure if this is correct ######## if evt.type == pygame.KEYDOWN: if evt.key == pygame.K_w: # Up player_sprite.moving = True elif evt.key == pygame.K_s: player_sprite.moving = True elif evt.key == pygame.K_a: player_sprite.moving = True elif evt.key == pygame.K_d: player_sprite.moving = True elif evt.key == pygame.K_SPACE: sprinting = True # Pressed keys are assigned an action keys_pressed = pygame.key.get_pressed() # Movement speed increase with 'sprint' if keys_pressed[pygame.K_w]: player_sprite.timer = 0 player_sprite.side = 3 player_sprite.move(0, -4, sprinting) if keys_pressed[pygame.K_s]: player_sprite.timer = 0 player_sprite.side = 0 player_sprite.move(0, 4, sprinting) if keys_pressed[pygame.K_a]: player_sprite.timer = 0 player_sprite.side = 2 player_sprite.move(-4, 0, sprinting) if keys_pressed[pygame.K_d]: player_sprite.timer = 0 player_sprite.side = 1 player_sprite.move(4, 0, sprinting) # SIMULATION --------------------------- # UPDATE simulation end = pygame.time.get_ticks() delta_time = end - cycle_time cycle_time = end # Checks if player is touching any objects for obj in object_list: player_sprite.update(obj, delta_time) # Finds active spot for puppy to travel too for path in path_list: if path.status == 'active': puppy_sprite.target = path.pos path.status = 'idle' path.color = object_color_idle break # Moves towards active target if puppy_sprite.move(delta_time): # Set new active area when destination reached print("Reached point") change_point(path_list) # Game Timer functions counting_time = pygame.time.get_ticks() - start_time counting_seconds = int(counting_time % 60000 / 1000) # print(counting_seconds) # Using get_ticks, counting seconds currently times game if counting_seconds != time_counter: time_counter += 1 # If the timer has exceeded 59 seconds, game over screen if counting_seconds == 59: game_running = False game_over(path_list) # DRAW SECTION (from back to front)################## screen.blit(room, (0, 0)) # Draws each object to room for path in path_list: path.draw(screen) for obj in object_list: obj.draw(screen) # Puppy sprite is not allowing the room to be redrawn puppy_sprite.draw(screen) player_sprite.draw(screen) screen.blit(menu, (0, 572)) pygame.display.flip()