def wall_kill(charlie, enemies, grid): """ Checks if an enemy os on the wall and attempt to cut them off\n @param charlie -> Own snake information\n @param enemies -> Array of enemy snakes\n @param grid -> Updated grid\n @return temp_path -> Path for a wall kill """ for enemy in enemies: for coords in charlie['coords'][2:]: for neighbour in neighbours(charlie['coords'][0], grid, 0, charlie['coords'][0], [SNAKE, DANGER]): if neighbour == (0, len(grid) - 1) or neighbour == (0, 0) or neighbour == ( len(grid[0]) - 1, len(grid) - 1) or neighbour == (len(grid[0]) - 1, 0): continue for neigh in neighbours(neighbour, grid, 0, neighbour, [SNAKE]): temp_path = a_star(charlie['coords'][0], neigh, grid, charlie['coords'], [SNAKE, DANGER]) if temp_path: if enemy['coords'][0][0] == 0 and enemy['coords'][0][ 1] == coords[1] - 1: if charlie['coords'][0][0] == 0: continue if neighbour[0] == 0: path = [charlie['coords'][0], neighbour] return path if enemy['coords'][0][1] == 0 and enemy['coords'][0][ 0] == coords[0] - 1: if charlie['coords'][0][1] == 0: continue if neighbour[1] == 0: path = [charlie['coords'][0], neighbour] return path if enemy['coords'][0][1] == len(grid) - 1 and enemy[ 'coords'][0][1] == coords[1] + 1: if charlie['coords'][0][1] == len(grid) - 1: continue if neighbour[1] == len(grid) - 1: path = [charlie['coords'][0], neighbour] return path if enemy['coords'][0][0] == len(grid[0]) - 1 and enemy[ 'coords'][0][0] == coords[0] + 1: if charlie['coords'][0][0] == len(grid[0]) - 1: continue if neighbour[0] == len(grid[0]) - 1: path = [charlie['coords'][0], neighbour]
def find_path(self, start, end, known_region): print 'finding path' current = Node(start, end) self.open_list.append(current) self.map = known_region while self.open_list: #find the neighbours of the last item in list self.open_list += self.neighbours(current, end) self.open_list.remove(current) self.closed_list.append(current) shortest_f = self.open_list[0] for node in self.open_list: if node.f < shortest_f.f: shortest_f = node current = shortest_f if current.position in neighbours(end): print 'target found:', end break path_nodes = [current] while path_nodes[-1].position != start: path_nodes.append(path_nodes[-1].parent) path = [] for node in path_nodes: path.append(node.position) print 'path found:', path return path
def remove_light_source(self, x, y): """ Apply light removing algorythm to given position x, y - position """ unlit_blocks = set() # Blocks which light was deleted self._unlight_block(x, y, x, y, unlit_blocks) srclight = self.world.get_light(x, y) to_light = () for x, y in unlit_blocks: for nx, ny in neighbours(x, y): #if (nx, ny) in to_light or not (nx != x or ny != y): # continue # Block already in to light list or it is source block if self.world.get_chunk( nx, ny) is not None: # Neighbor block's chunk is exists light = self.world.get_light(nx, ny) if light > srclight: to_light += ((nx, ny, light), ) for x, y, light in to_light: self._light_block(x, y, intensity=light)
def run(): data = load_data() total_flashes = 0 for step in itertools.count(): will_flash = set() for x, y in itertools.product(range(10), range(10)): data[x][y] += 1 if data[x][y] > 9: will_flash.add((x, y)) flash_queue = list(will_flash) while flash_queue: x, y = flash_queue.pop() for nx, ny in utils.neighbours((x, y), include_diagonals=True): if not ((0 <= nx < 10) and (0 <= ny < 10)): continue data[nx][ny] += 1 if data[nx][ny] > 9 and (nx, ny) not in will_flash: will_flash.add((nx, ny)) flash_queue.append((nx, ny)) for x, y in will_flash: data[x][y] = 0 total_flashes += len(will_flash) if step == 99: print(f"Part 1: {total_flashes}") if len(will_flash) == 100: print(f"Part 2: {step + 1}") break
def trouble(charlie, grid): """ Select a random available move\n @param charlie -> Own snake information\n @param grid -> Updated grid\n @return temp_path -> Random safe spot to move """ for neighbour in neighbours(charlie['coords'][0], grid, 0, charlie['coords'][-1], [SNAKE]): trouble_path = a_star(charlie['coords'][0], neighbour, grid, charlie['coords'], [SNAKE]) return trouble_path
def agent_slow(world_state, *args, **kwargs): my_position = world_state['you']['position'] my_node = world_state['world'][my_position] (next_node, _) = neighbour_profit(world_state) if next_node is None: try: next_node = max([(n, neighbour_profit(world_state, n)) for n in u.neighbours(world_state)], key=lambda a:a[1][1])[0] except ValueError: next_node = random.choice(u.neighbours(world_state)) # what is profitable at our next node? profitable = profitable_resources(my_node["resources"], world_state['world'][next_node]["resources"]) ### sell # sell everything # we need to avoid selling stuff that makes a profit next round sells = {name:q for name,q in world_state['you']['resources'].items() if name not in profitable and name in my_node["resources"].keys()} ### buy # buy as many resources that profit on the next node as possible coin_available = world_state['you']['coin'] buys = {} if not u.is_last_round(world_state): for (name, profit) in profitable: max_q_to_buy = coin_available / my_node["resources"][name]["sell"] buys[name] = min(max_q_to_buy, my_node["resources"][name]["quantity"]) coin_available -= buys[name] * my_node["resources"][name]["sell"] return { 'resources_to_sell_to_shop': sells, 'resources_to_buy_from_shop': buys, 'move': next_node }
def a_star(start, goal, grid, tail, ignore_list): """ A-Star algorithm for pathfinding\n Originally from https://github.com/noahspriggs/battlesnake-python\n @param start -> Starting point\n @param goal -> End point\n @param grid -> Updated grid\n @param tail -> Tail of snake / additional coords to ignore\n @param ignore_list -> Grid locations to avoid """ start = tuple(start) goal = tuple(goal) closed_set = [] open_set = [start] came_from = {} g_score = [[10] * len(grid[0]) for _ in xrange(len(grid))] g_score[start[0]][start[1]] = 0 f_score = [[10] * len(grid[0]) for _ in xrange(len(grid))] f_score[start[0]][start[1]] = distance(start,goal) while(len(open_set) > 0): current = min(open_set, key=lambda p: f_score[p[0]][p[1]]) if (current == goal): return reconstruct_path(came_from, goal) open_set.remove(current) closed_set.append(current) for neighbour in neighbours(current, grid, int(g_score[current[0]][current[1]]), tail, ignore_list): if neighbour in closed_set: continue tentative_g_score = g_score[current[0]][current[1]] + distance(current,neighbour) if neighbour not in open_set: open_set.append(neighbour) elif tentative_g_score == g_score[neighbour[0]][neighbour[1]]: dx1 = current[0] - goal[0] dy1 = current[1] - goal[1] dx2 = start[0] - goal[0] dy2 = start[1] - goal[1] cross = abs(dx1*dy2 - dx2*dy1) tentative_g_score += cross*0.001 elif tentative_g_score > g_score[neighbour[0]][neighbour[1]]: continue came_from[neighbour] = current g_score[neighbour[0]][neighbour[1]] = tentative_g_score f_score[neighbour[0]][neighbour[1]] = tentative_g_score + distance(neighbour,goal) return None
def reveal_tile(x, y): revealed = [] queue = [(x, y)] while len(queue) > 0: i, j = queue.pop() if not self.mine(i, j) and (i, j) not in revealed and not self.board[i][j].revealed: revealed.append((i, j)) if self.neighbours_with_mines(i, j) < 1: queue.extend(neighbours(i, j, self.size)) if (x, y) not in revealed: revealed.append((x, y)) return revealed
def part1(data=DATA) -> int: edges: dict[Coord, dict[Coord, int]] = {} size = len(data) if size != len(data[0]): raise Exception("Not a square...") for y in range(size): for x in range(size): for nx, ny in utils.neighbours((x, y), include_diagonals=False): if not ((0 <= nx < size) and (0 <= ny < size)): continue edges.setdefault((x, y), {})[(nx, ny)] = data[nx][ny] return dijkstra(edges, (0, 0), (size - 1, size - 1))
def bfs(starting_position, target_position, board, exclude, return_list): """ BFS implementation to search for path to food :param starting_position: starting position :param target_position: target position :param board: the board state example: bfs((0,0), (2,2), board) -> [(0,0), (0,1), (0,2), (1,2), (2,2)] """ def get_path_from_nodes(node): path = [] while(node != None): path.insert(0, (node[0], node[1])) # Reverse node = node[2] return return_list.append(path[1:]) x = starting_position[0] y = starting_position[1] board_copy = deepcopy(board) board_copy.set_cell((x, y), 0) for excluded_point in exclude: board_copy.set_cell(excluded_point, "B") print board_copy.format() queue = deque([(x, y, None)]) while len(queue) > 0: node = queue.popleft() x = node[0] y = node[1] if board_copy.inside((x, y)) == True: if (x, y) == target_position: # If we reach target_position return get_path_from_nodes(node) # Rebuild path if (board_copy.outside((x, y)) == True or board_copy.get_cell((x, y)) == "B" or board_copy.get_cell((x, y)) == 1) and not (x, y) == starting_position: # Snakes #print "exclude", (x, y) continue board_copy.set_cell((x, y), "B") # Mark as explored for i in neighbours(node): if board.inside((i[0], i[1])): #print "append", (x, y) queue.append((i[0], i[1], node)) return None # No path
def astar(vacant_func, start_pos, goal_pos, allow_start_in_occupied_cell=False): """ A*, a pathfinding algorithm for finding a shortest path from a start location to a goal. Returns the list of positions comprising the path, or none if no path could be found. If allow_start_in_occupied_cell is True, the search may begin from an occupied cell (a snake's head, for eg). However, if you do this, you'll probably want to trim off the first position in the resulting shortest path. """ if not allow_start_in_occupied_cell and not vacant_func(start_pos): return None closed_set = set() min_cost_to = {start_pos: 0} parent_of = {start_pos: None} todo = [(dist(start_pos, goal_pos), start_pos)] while todo: priority, current = heapq.heappop(todo) closed_set.add(current) if current == goal_pos: # Found the goal - walk up the parent chain to build the final path path = [current] while parent_of[current]: path.append(parent_of[current]) current = parent_of[current] return list(reversed(path)) for p in neighbours(current): if p in closed_set or not vacant_func(p): continue new_cost = min_cost_to[current] + 1 if p not in min_cost_to or new_cost < min_cost_to[p]: min_cost_to[p] = new_cost parent_of[p] = current priority = new_cost + dist(p, goal_pos) # Note that this is a simplification of A* where we don't reprioritize items # within the heap, we just push the same item again with a lower priority. # This is wasteful in terms of memory, but for a problem of our scope, it # doesn't really matter. heapq.heappush(todo, (priority, p)) return None
def eat_snake(charlie, enemies, grid): """ If enemy is smaller will try to kill by moving into potential spots enemy head will be if enemy nest to wall will choke into crash\n @param charlie -> Own snake information\n @param enemies -> Array of enemy snakes\n @param grid -> Updated grid\n @return temp_path -> Path to eat enemy """ for neighbour in neighbours(charlie['coords'][0], grid, 0, charlie['coords'], [SNAKE, DANGER]): if grid[neighbour[0]][neighbour[1]] == KILLABLE: kill_path = a_star(charlie['coords'][0], neighbour, grid, charlie['coords'], [SNAKE, DANGER]) # return check_ahead(kill_path, charlie, neighbour, grid) return kill_path
def adjacents(level, p): coords = [] for d, n in utils.neighbours(p): nx, ny = n if n == center: coords.extend(((level - 1), c) for c in corners[d]) continue if nx < xmin: coords.append((level + 1, (cx - 1, cy))) elif nx > xmax: coords.append((level + 1, (cx + 1, cy))) if ny < ymin: coords.append((level + 1, (cx, cy - 1))) elif ny > ymax: coords.append((level + 1, (cx, cy + 1))) if xmin <= nx <= xmax and ymin <= ny <= ymax: coords.append((level, (nx, ny))) return coords
def neighbour_profit(world_state, node_label=None): """ if we just bought all the resources at the current node and then sold them on, what is the maximum profit we could make? """ if node_label is None: node_label = world_state["you"]["position"] current_node = world_state["world"][node_label] current_resources = current_node["resources"] best_label = None highest_profit = 0 for neighbour in u.neighbours(world_state, node_label): neighbour_resources = world_state["world"][neighbour]["resources"] p = potential_profit(current_resources, neighbour_resources) if p > highest_profit: highest_profit = p best_label = neighbour return (best_label, highest_profit)
def generate_board(self): # Generate a board for Minesweeper self.board = [[Tile(j, i) for i in range(0, self.size)] for j in range(0, self.size)] # select self.numMines random fields from 0 to self.size*self.size - 1 fields_with_mines_ids = sample(range(0, self.size * self.size), self.numMines) # for a given field n select the field with coordinates (i,j) such that i*self.size + j = n fields_with_mines = map(lambda n, size=self.size: ((n - n % size) / size, n % size), fields_with_mines_ids) for field in fields_with_mines: i, j = field self.board[i][j].mine = True # add 1 to all neighbours of that field, except of the fields that already contain a bomb for (x, y) in neighbours(i, j, self.size): if not self.board[x][y].mine: self.board[x][y].neighbours_with_mines += 1
def flood_fill(board, start_pos, allow_start_in_occupied_cell=False): """ Flood fill is an algorithm that expands from a starting position into adjacent vacant cells. Returns the set of all vacant cells found. If allow_start_in_occupied_cell is True, the flood fill start position may be occupied and the start position will be included in the resulting set. """ visited = set() if not allow_start_in_occupied_cell and not board.vacant(start_pos): return visited visited.add(start_pos) todo = collections.deque([start_pos]) while todo: current = todo.popleft() for p in neighbours(current): if p not in visited and board.vacant(p): visited.add(p) todo.append(p) return visited
def adjacents(_, p): for _, n in utils.neighbours(p): nx, ny = n if xmin <= nx <= xmax and ymin <= ny <= ymax: yield 0, n
def move(self): self.step_num += 1 # if bomb in the neigbourhood if self.parent.target in neighbours((self.x, self.y), True): # The agent found the bomb self.bomb_location = self.parent.target if self.is_scout: # bomb deactivated self.parent.bomb_found = True return True else: self.color = QColor(200, 96, 109, 255) # the path is being reinitialized in # order to be show to the scout self.bomb_location = self.parent.target # if agent is scout and scout knows the bomb if self.bomb_location and self.is_scout: if self.path_to_bomb: (self.x, self.y) = self.path_to_bomb.pop() return True # create a shortcut target = self.bomb_location known_region = self.path start = (self.x, self.y) print 'calling astar' shortest_path = AStar() print 'will find the shortest path' self.path_to_bomb = shortest_path.find_path(start, target, known_region) return True # select to move randomly avoiding # to go to the last position order_list = ['u', 'r', 'd', 'l'] random.shuffle(order_list) # get the available moves moves = [] for order in order_list: if order == 'u': moves = self.up(moves) elif order == 'r': moves = self.right(moves) elif order == 'd': moves = self.down(moves) elif order == 'l': moves = self.left(moves) # if moves available if len(moves) != 0: # check if agents meet each other for agent in self.parent.agents: if (agent.x, agent.y) in neighbours((self.x, self.y)): self.exchanges += 1 agent.path += self.path self.path += agent.path self.path = list(set(self.path)) agent.path = list(set(agent.path)) if (agent.is_scout) and (self.bomb_location) and (not agent.bomb_location): agent.bomb_location = self.bomb_location return True else: if self.bomb_location and not agent.bomb_location: agent.bomb_location = self.bomb_location agent.color = QColor(200, 96, 109, 255) for m in moves: # The agent prefers to go to a # square he has not visited if m in self.path: #we put this move at the end moves.remove(m) moves.append(m) (self.x, self.y) = moves[0] if moves[0] in self.path: self.path.remove((self.x, self.y)) self.path.append((self.x, self.y)) else: print 'cannot move' return False return True
import numpy as np import utils import sys def mk_training_matrices(pairs, en_dimension, cat_dimension, semanticspace, catalan_space): en_mat = np.zeros((len(pairs),en_dimension)) cat_mat = np.zeros((len(pairs),cat_dimension)) c = 0 for p in pairs: en_word,cat_word = p.split() en_mat[c] = semanticspace[en_word] cat_mat[c] = catalan_space[cat_word] c+=1 return en_mat,cat_mat if len(sys.argv) == 4: space=sys.argv[1] if space=='reducedcolors': semanticspace=utils.readDM("data/reducedcolors.dm")s if space =='fullcolors': semanticspace=utils.readDM("data/full.dm") word = sys.argv[2] num_neighbours = int(sys.argv[3]) print(utils.neighbours(semanticspace, semanticspace[word],num_neighbours)) english_neighbours = utils.neighbours(semanticspace,semanticspace[word],num_neighbours) utils.run_PCAneighbours(semanticspace,[word]+english_neighbours,"english_neighbours"+word+".png")
def test(): img = io.imread('ex 38.png') img = img/255 img_thin = zhangSuen(img) # img_thin = cv2.resize(img_thin, (256,256)) # img_thin = zhangSuen(img_thin) # img_thin[img_thin >= 0.2] = 1 # img_thin[img_thin < 0.2] = 0 # img_thin = zhangSuen(img_thin) cross_list = [] tmp = 0 tt = 0 num_pic = 0 for x in range(512): for y in range(512): if img_thin[x,y] == 1: if sum(utils.neighbours(x,y,img_thin)) >=3: if (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[0]).all(): # FIXME: a in b # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[1]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[2]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[3]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[4]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[5]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[6]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[7]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[8]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[9]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[10]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[11]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[12]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[13]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[14]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[15]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[16]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[17]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[18]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[19]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[20]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[21]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[22]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[23]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[24]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[25]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[26]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[27]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[28]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[29]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[30]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9)) == Not_sample[31]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt+=1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1, 9)) == Not_sample[32]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt += 1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1, 9)) == Not_sample[33]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt += 1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1, 9)) == Not_sample[34]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt += 1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1, 9)) == Not_sample[35]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt += 1 elif (np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1, 9)) == Not_sample[36]).all(): # print(np.array(img_thin[x - 1:x + 2, y - 1:y + 2]).reshape((1,9))) tt += 1 else: tmp = tmp + img_thin[x, y] cross_list.append([x,y]) print(img_thin[x - 1:x + 2, y - 1:y + 2]) tm = np.copy(img_thin) cv2.rectangle(tm, (y-5, x-5), (y+6, x+6), 0.5, 1) tm[tm > 0] = 255 cv2.imwrite('bound/{}.png'.format(num_pic),tm) num_pic +=1 # cv2.rectangle(img_thin, (y-5, x-5), (y+6, x+6), 0.1, 1) # plt.imshow(tm) # plt.show() print(len(cross_list)) print('tmp', tmp) print('tt',tt)
foo = \ [ [C(1, 6), C(-2, 1), C(2, 1)], [C(-2, 1), C(-2, 1), C(2, 1)], [C(1, 1), C(1, 1), C(2, 1)] ] for i in range(3): print foo[i] for i in range(3): for j in range(3): print foo[i][j].height, print "\n" current_neighbours = neighbours(0, 0, foo) curr_min_neighb = minimal_neighbours(0, 0, foo) curr_min_neighb_diffs = [] print "NEIGHBours ", current_neighbours print "MIN NEIGHB ", curr_min_neighb for min_neighb in curr_min_neighb: min_neighb_neighb = neighbours(min_neighb[0], min_neighb[1], foo) shared_neighb = list(set.intersection(set(current_neighbours), set(min_neighb_neighb))) minimal_diff = float("inf") for shrd_nghbr in shared_neighb: if foo[shrd_nghbr[0]][shrd_nghbr[1]].height - foo[min_neighb[0]][min_neighb[1]].height < minimal_diff and foo[shrd_nghbr[0]][shrd_nghbr[1]].height - foo[min_neighb[0]][min_neighb[1]].height != 0: minimal_diff = foo[shrd_nghbr[0]][shrd_nghbr[1]].height - foo[min_neighb[0]][min_neighb[1]].height curr_min_neighb_diffs.append(minimal_diff) print "curr_min_neighb_diffs ", curr_min_neighb_diffs
def zhangSuen(image): "the Zhang-Suen Thinning Algorithm" Image_Thinned = image.copy() # deepcopy to protect the original image changing1 = changing2 = 1 # the points to be removed (set as 0) while changing1 or changing2: # iterates until no further changes occur in the image # Step 1 changing1 = [] rows, columns = Image_Thinned.shape # x for rows, y for columns for x in range(1, rows - 1): # No. of rows for y in range(1, columns - 1): # No. of columns P2,P3,P4,P5,P6,P7,P8,P9 = n = utils.neighbours(x, y, Image_Thinned) if (Image_Thinned[x][y] == 1 and # Condition 0: Point P1 in the object regions 2 <= sum(n) <= 6 and # Condition 1: 2<= N(P1) <= 6 transitions(n) == 1 and # Condition 2: S(P1)=1 P2 * P4 * P6 == 0 and # Condition 3 P4 * P6 * P8 == 0): # Condition 4 changing1.append((x,y)) for x, y in changing1: Image_Thinned[x][y] = 0 # Step 2 changing2 = [] for x in range(1, rows - 1): for y in range(1, columns - 1): P2,P3,P4,P5,P6,P7,P8,P9 = n = utils.neighbours(x, y, Image_Thinned) if (Image_Thinned[x][y] == 1 and # Condition 0 2 <= sum(n) <= 6 and # Condition 1 transitions(n) == 1 and # Condition 2 P2 * P4 * P8 == 0 and # Condition 3 P2 * P6 * P8 == 0): # Condition 4 changing2.append((x,y)) for x, y in changing2: Image_Thinned[x][y] = 0 return Image_Thinned
def _full_neighbours_groups(self, fragment_id, group_id, step=1): return (new_group_id for new_group_id in neighbours(group_id, 0, self._last_usable[fragment_id] + 1) if self._associations.is_group_full(fragment_id, new_group_id))
all_pairs.append(l) f.close() '''Make training/test fold''' training_pairs = all_pairs[:120] test_pairs = all_pairs[121:] '''Make training/test matrices''' en_mat, cat_mat = mk_training_matrices(training_pairs, 400, 300, english_space, catalan_space) params = linalg(en_mat, cat_mat) '''Test''' '''Sanity check -- is the regression matrix retrieving the training vectors?''' #print(training_pairs[0]) #en, cat = training_pairs[0].split() #predict = np.dot(params.T,english_space[en]) #print(predict[:20]) #print(catalan_space[cat][:20]) '''Loop through test pairs and evaluate translations''' score = 0 for p in test_pairs: en, cat = p.split() predicted_vector = np.dot(params.T, english_space[en]) #print(predicted_vector) nearest_neighbours = utils.neighbours(catalan_space, predicted_vector, 5) if cat in nearest_neighbours: score += 1 print(en, cat, nearest_neighbours, "1") else: print(en, cat, nearest_neighbours, "0") print("Precision:", score / len(test_pairs))
def move(): data = {} time_remaining = [150] # leave 50ms for network position = None path = None next_move = list() thread_pool = list() potential_snake_positions = list() direction = None with timing("bottle", time_remaining): data = bottle.request.json try: with timing("data parsing", time_remaining): board = Board(**data) snake = board.get_snake(data['you']) direction = general_direction(board, snake.head, snake.attributes['health_points']) move = direction # fallback for enemy_snake in board.snakes: if enemy_snake.attributes['id'] != snake.attributes[ 'id']: # and enemy_snake.attributes['health_points'] >= snake.attributes['health_points']: potential_snake_positions.extend([ position for position in enemy_snake.potential_positions() if board.inside(position) ]) number_of_squares = list() # find number of empty squares in every direction. for cell in neighbours(snake.head): if board.inside(cell): count = len(flood_fill(board, cell, False)) number_of_squares.append((cell, count)) if count <= 10: potential_snake_positions.append(cell) if number_of_squares[0][1] <= 10 and number_of_squares[1][ 1] <= 10 and number_of_squares[2][ 1] <= 10 and number_of_squares[3][1] <= 10: largest = reduce( lambda carry, direction: carry if carry[1] > direction[1] else direction, number_of_squares, number_of_squares[0]) potential_snake_positions.remove(largest[0]) print potential_snake_positions with timing("need_food", time_remaining): food = need_food(board, snake.head, snake.attributes['health_points']) if food: #if snake.attributes['health_points'] < 30: #potential_snake_positions = [] with timing("find_food", time_remaining): food_positions = find_food(snake.head, snake.attributes['health_points'], board, food) positions = [position[0] for position in food_positions] # positions = list(set([ position[0] for position in food_positions ]) - set(potential_snake_positions)) print positions print[board.get_cell(position) for position in positions] for position in positions: t = Thread( target=bfs(snake.head, position, board, potential_snake_positions, next_move)) t = Thread( target=bfs(snake.head, position, board, [], next_move)) thread_pool.append(t) for thread in thread_pool: thread.start() thread.join() next_move = filter(lambda path: not len(path) == 0, next_move) path = min(next_move, key=len) move = get_direction(snake.head, path[0]) else: #with timing("flood_fill", time_remaining): # flood_fill(board.vacant, snake.head, True) with timing("find_safest_position", time_remaining): positions = find_safest_position(snake.head, direction, board) positions = [position[0] for position in positions] # positions = list(set([position[0] for position in positions]) - set(potential_snake_positions)) print positions print[board.get_cell(position) for position in positions] for position in positions: t = Thread( target=bfs(snake.head, position, board, potential_snake_positions, next_move)) t = Thread( target=bfs(snake.head, position, board, [], next_move)) thread_pool.append(t) for thread in thread_pool: thread.start() thread.join() path = max(next_move, key=len) move = get_direction(snake.head, path[0]) except Exception as e: print "WTF", e.message print next_move print path print move if len(next_move) == 0: print "CHANGING MOVE" with timing("floodfill", time_remaining): floods = { "up": len(flood_fill(board, (snake.head[0], snake.head[1] - 1))), "down": len(flood_fill(board, (snake.head[0], snake.head[1] + 1))), "right": len(flood_fill(board, (snake.head[0] + 1, snake.head[1]))), "left": len(flood_fill(board, (snake.head[0] - 1, snake.head[1]))) } move = max(floods.iterkeys(), key=(lambda key: floods[key])) # don't be stupid m_move = add(snake.head, DIR_VECTORS[DIR_NAMES.index(move)]) if board.inside(m_move) and board.get_cell(m_move) == 1: print "CHANGING MOVE" for direction in DIR_NAMES: m_move = add(snake.head, DIR_VECTORS[DIR_NAMES.index(direction)]) if board.inside(m_move) and board.get_cell(m_move) != 1: move = direction print "moving", move return {'move': move, 'taunt': random.choice(TAUNTS)}
def main(): if len(sys.argv) == 3: # listtop500 = open('data/listtop500.txt','r') #listlast500=open('data/listlast500.txt','r') #['reykjanes','danielli','underdrawing','halichoerus','hepler','change-'] #['widgeon','colourpoint','water-lilies','kingbirds','gallinules','pebbledash'] #['flowers.','nard','hearing-aid','filsham','trumpet-shaped','crecca' ] #['kerchief', 'kingbirds','cerise','biretta','pale-blue','v-necked','pebbledash'] #['crecca','flowers.','corollas','shovelers','supercilium','crocuses'] listtop500=['village','ponk','catspaw','lycaenid','orangey-pink','saponaria'] if sys.argv[2]=='full': semanticspace1=utils.readDM("data/colorswithoutremovedtargets.dm") if sys.argv[2]=='nonzero': semanticspace1=utils.readDM("data/reducedcolors.dm") dicttop=defaultdict(list) dictlast=defaultdict(list) for line in listtop500: #word = line.strip() word=line num_neighbours = int(sys.argv[1]) neighbours1=[] for i in utils.neighbours(semanticspace1,semanticspace1[word],num_neighbours): neighbours1.append(i.strip(".")) neighbours2=[] cosinefull=[] for i in functionneighbours(word,num_neighbours): neighbours2.append(i[0]) cosinefull.append(i[1]) densityfull=(sum(cosinefull))/(len(cosinefull)) ##compare neigbours of 2 different spaces intersection = set(neighbours1) & set(neighbours2) print(word, intersection,len(intersection)) #dicttop[word]=len(intersection) # for line in listlast500: # word = line.strip() # num_neighbours = int(sys.argv[1]) # neighbours1=[] # for i in utils.neighbours(semanticspace1,semanticspace1[word],num_neighbours): # neighbours1.append(i.strip(".")) # neighbours2=[] # cosinefull=[] # for i in functionneighbours(word,num_neighbours): # neighbours2.append(i[0]) # cosinefull.append(i[1]) # densityfull=(sum(cosinefull))/(len(cosinefull)) # ##compare neigbours of 2 different spaces # intersection = set(neighbours1) & set(neighbours2) # print(intersection,len(intersection)) # dictlast[word]=len(intersection) #density color space listdensity=[] listcoherence=[] neighbours=utils.neighbours(semanticspace1,semanticspace1[word],num_neighbours) for i in neighbours: cosine=utils.cosine_similarity(semanticspace1[word],semanticspace1[i]) # if np.isnan(cosine): # pass # else: listdensity.append(cosine) density=sum(listdensity)/(len(listdensity)) print('density color space: ',density) print('density full space: ', densityfull) dicttop[word]=[len(intersection),density]