def test_stop_at_obstacle( command, position): obstacle1_coordinate = Coordinate(0, 4) obstacle2_coordinate = Coordinate(2 ,0) grid = Grid([obstacle1_coordinate, obstacle2_coordinate]) rover_obj = Rover(grid) assert rover_obj.execute(command) == position
def test_vehicle_collision_on_same_grid(self): grid = Grid(5, 5) vehicle1 = basic_vehicle(grid) vehicle2 = Vehicle(grid, [Coordinate(1, 1), Coordinate(1, 2)]) assert vehicle1.collides_with(vehicle2) assert vehicle2.collides_with(vehicle1)
def agglomerate(setup, iteration, sample, thresholds, output_basenames, *args, **kwargs): thresholds = list(thresholds) aff_data_dir = os.path.join(os.getcwd(), 'processed', setup, str(iteration)) affs_filename = os.path.join(aff_data_dir, sample + '.hdf') gt_data_dir = os.path.join(os.getcwd(), '../01_data') gt_filename = os.path.join(gt_data_dir, sample + '.hdf') print "Agglomerating " + sample + " with " + setup + ", iteration " + str( iteration) + " at thresholds " + str(thresholds) print "Reading affinities..." with h5py.File(affs_filename, 'r') as affs_file: affs = np.array(affs_file['volumes/predicted_affs']) affs_offset_nm = Coordinate( affs_file['volumes/predicted_affs'].attrs['offset']) resolution = Coordinate( affs_file['volumes/predicted_affs'].attrs['resolution']) affs_roi = Roi(affs_offset_nm, resolution * affs.shape[1:]) print "affs ROI: " + str(affs_roi) print "Reading ignore mask..." with h5py.File(gt_filename, 'r') as gt_file: ignore_mask = np.array(gt_file['volumes/labels/ignore']) start = time.time() agglomerate_lineages(affs, ignore_mask, thresholds, affs_roi, resolution, output_basenames, **kwargs) print "Finished agglomeration in " + str(time.time() - start) + "s"
def new_game(self, mazesize): """New game, takes maze dimensions as input""" self.__field = Maze(mazesize) self.__field.carve_maze(Coordinate(0, 0, 0)) self.__player = Player(Coordinate(0, 0, 0)) self.__won = False self.__time = 0
def test_next_position(self): next_position = self.valid_position.next_position( 2, Coordinate((0, 0, 1))) coordinates = next_position.occupied_coordinates self.assertTrue(coordinates.__contains__(Coordinate((1, 1, 2)))) self.assertTrue(coordinates.__contains__(Coordinate((1, 1, 1)))) self.assertEqual(len(coordinates), 5)
def eta_at_goal(self, drone_id): ''' :returns: amount of seconds until the drone hits the goal ''' speed = self.active_drone_info[drone_id].ground_speed_setpoint current_position = Coordinate( GPS_data=self.active_drone_info[drone_id].position) if self.active_drone_info[ drone_id].mission_index >= self.active_drone_info[ drone_id].mission_length: # next waypoint is goal. goal_position = Coordinate( GPS_data=self.active_drone_paths[drone_id][-1]) dist = self.pythagoras(current_position, goal_position) eta = dist / speed return int(eta) else: next_position = Coordinate( GPS_data=self.active_drone_info[drone_id].next_waypoint) dist_to_next = self.pythagoras(current_position, next_position) eta = dist_to_next / speed for dist in self.dist_between_mission_points[drone_id][ self.active_drone_info[drone_id]. mission_index:]: #TODO check that mission index refers to the right position #range(self.active_drone_info[drone_id].mission_index, self.active_drone_info[drone_id].mission_length-1): eta += dist / speed return int(eta)
def is_clear_to_take_of(self, drone_id, position): start_position = Coordinate(lon=position.longitude, lat=position.latitude) current_time = time.time() for int_id, dnfz in self.dynamic_no_flight_zones.items(): if dnfz["geometry"] == "circle": coord = dnfz["coordinates"] coord = coord.split(',') dist = self.pythagoras(start_position, Coordinate(lon=coord[1], lat=coord[0])) if (int(dnfz["valid_from_epoch"]) - self.safety_extra_time) < current_time < (int( dnfz["valid_to_epoch"]) + self.safety_extra_time): if dist <= (float(coord[2]) + self.safety_dist_to_dnfz): return False, int(dnfz["valid_to_epoch"]) elif dnfz["geometry"] == "polygon": dist = dnfz["polygon"].distance( geometry.Point(start_position.easting, start_position.northing)) if (int(dnfz["valid_from_epoch"]) - self.safety_extra_time) < current_time < (int( dnfz["valid_to_epoch"]) + self.safety_extra_time): if dist <= self.safety_dist_to_dnfz: return False, int(dnfz["valid_to_epoch"]) return True, time.time()
def __init__(self, pos, screen_dims): self.initial_pos = pos self.screen_dims = screen_dims self.displacement = Coordinate(pos, vel=Coordinate.get_empty_coord()) self.origin = Coordinate(Coordinate.get_empty_coord(), Coordinate.get_empty_coord()) self.displacement = Coordinate(Coordinate.get_empty_coord(), Coordinate.get_empty_coord()) self.pitch = math.pi / 2 self.yaw = math.pi / 2 self.facing = None self.up = None self.right = None self.screen_diagonal = math.sqrt(screen_dims[0] ** 2 + screen_dims[1] ** 2) / 2 self.field_of_view = math.pi / 3.0 self.projection_plane_distance = self.screen_diagonal / math.atan(self.field_of_view) self.get_direction_vectors() self.zoom_rate = 200 self.zoom_multiplier = 1.0 self.degrees_per_turn = 5 self.camera_is_moving = False self.initial_mouse_pos = None self.update_background = False self.key_mappings = { pygame.K_DOWN: self.look_down, pygame.K_UP: self.look_up, pygame.K_LEFT: self.look_left, pygame.K_RIGHT: self.look_right, pygame.K_a: self.strafe_left, pygame.K_d: self.strafe_right, pygame.K_w: self.move_forward, pygame.K_s: self.move_backward, pygame.K_z: self.move_up, pygame.K_x: self.move_down }
def expand_ra(self): """ uses agent position to expand the (n, s, e, w) nodes and returns the associated coordinate objects if the space is empty return:: the surrounding, traversible coordinates/nodes [] """ n = Coordinate(self.position.get_x(), self.position.get_y(), self.position.get_z() - 1) s = Coordinate(self.position.get_x(), self.position.get_y(), self.position.get_z() + 1) w = Coordinate(self.position.get_x() - 1, self.position.get_y(), self.position.get_z()) e = Coordinate(self.position.get_x() + 1, self.position.get_y(), self.position.get_z()) #empty_neighbors = set() empty_neighbors = [] if self.get_block_type(n) == 0: empty_neighbors.append(n) if self.get_block_type(s) == 0: empty_neighbors.append(s) if self.get_block_type(e) == 0: empty_neighbors.append(e) if self.get_block_type(w) == 0: empty_neighbors.append(w) return empty_neighbors
def dist_from_cc(df): """ Helper function to create a new column in a DataFrame with dist to city center """ coordinate = Coordinate(df['dest_lat'], df['dest_lon']) city_center = Coordinate(cn.CITY_CENTER[0], cn.CITY_CENTER[1]) return city_center.haversine_distance(coordinate)
def solve(self): # The starting point self.push(Coordinate(0, 0, 1), self.sequence[0], 0) # Symmetrical first moves for c in ((0, 0, 0), (0, 1, 1)): self._solve(Coordinate(*c), 1) return self.solutions, self.steps
def generate_possible_moves(self, board, check_check=False): possible_movement_coords = [] x = self.coordinate.x y = self.coordinate.y d = self.direction indeterminate_coords = [] one_space = Coordinate(x, y + d) two_space = Coordinate(x, y + d + d) left_space = Coordinate(x - 1, y + d) right_space = Coordinate(x + 1, y + d) if one_space.is_valid() and not board.is_occupied(one_space): indeterminate_coords.append(one_space) if two_space.is_valid( ) and not board.is_occupied(two_space) and self.first_move: indeterminate_coords.append(two_space) if left_space.is_valid() and board.is_occupied_by_opponent( left_space, self.color): indeterminate_coords.append(left_space) if right_space.is_valid() and board.is_occupied_by_opponent( right_space, self.color): indeterminate_coords.append(right_space) indeterminate_coords = self.filter_invalid_coords( indeterminate_coords, board.movement_coord_validity) if not check_check: indeterminate_coords = self.filter_invalid_coords( indeterminate_coords, board.does_not_put_king_in_check) possible_movement_coords.extend(indeterminate_coords) return possible_movement_coords
def parseInput(self, resp): info = {} info['timeLeft'] = resp[0] info['gameNum'] = resp[1] info['tickNum'] = resp[2] info['maxWalls'] = int(resp[3]) info['wallPlacementDelay'] = resp[4] info['boardSizeX'] = int(resp[5]) info['boardSizeY'] = int(resp[6]) info['currentWallTimer'] = resp[7] info['hunter'] = Coordinate(resp[8], resp[9], resp[10], resp[11]) info['prey'] = Coordinate(resp[12], resp[13]) info['numWalls'] = int(resp[14]) info['walls'] = [] for i in range(0, info['numWalls']): info['walls'].append( Wall(int(resp[15 + i * 4]), int(resp[16 + i * 4]), int(resp[17 + i * 4]), int(resp[18 + i * 4]))) return info
def starting_points(self): """ All distinct starting coordinates Every class of coordinate has sysmmetrical solutions """ return (Coordinate(0, 0, 0), Coordinate(0, 0, 1), Coordinate(0, 1, 1), Coordinate(1, 1, 1))
def test_add_two_horizontal_cars(): grid = make_normal_grid() grid.add_car(t.basic_horizontal_car(grid, coor=Coordinate(0, 0))) grid.add_car(t.basic_horizontal_car(grid, coor=Coordinate(0, 1))) assert len(grid.cars.keys()) == 2
def handle_getPathPlan(req): #TODO add boolean for dynamic and start time in the requested message global path_planner_dict,plannum start = Coordinate(GPS_data=req.start) theend = Coordinate(GPS_data=req.end) map_padding = 2500 if req.drone_id in path_planner_dict: map, old_start = path_planner_dict[req.drone_id] if (old_start.easting - map_padding > start.easting or old_start.northing - map_padding > start.northing or old_start.easting + map_padding < start.easting or old_start.northing + map_padding < start.northing): map = make_static_map(start) path_planner_dict[req.drone_id] = map, start else: map = make_static_map(start) path_planner_dict[req.drone_id] = map, start map, old_start = path_planner_dict[req.drone_id] print("[Path planner]: Planning from: " + start.str() + " - to: " + theend.str()) planner = PathPlanner(start, theend, map) planner.compute_path(req.useDNFZ, req.velocity, req.startTime, map_padding) plan = planner.path #planner.export_kml_path("Path"+str(plannum)) plannum = plannum +1 GPSPlan = [] for point in plan: GPSPlan.append(point.GPS_data) return pathPlanResponse(GPSPlan)
def setHardTerrain(self, numhardcenters): #keeps track of centers being used hardTerrainList = [] #holds terrain to be changed to HARD #iterate to find 8 center cells for i in range(numhardcenters): #get center cell coordinate while True: centerCoord = self.getRandomCoord() #breaks loop if center coordinate is not already being used if centerCoord not in self.hardCenterList: #add to list as being used self.hardCenterList.append(centerCoord) break #iterate through 31 x 31 block of cells around center #start at row 15 up from center, end 15 below center for irow in range(centerCoord.row - 15, centerCoord.row + 15): #start at col 15 left of center, end 15 right of center for icol in range(centerCoord.col - 15, centerCoord.col + 15): #verify that given coordinate is legal if self.verifyCoordInBounds(Coordinate(irow, icol)): #randomly set cell at coordinate to 'hard to pass' if random.random() > 0.5: hardTerrainList.append(Coordinate(irow, icol)) #update terrain self.changeTerrain(hardTerrainList, "2")
def update_dnfz(self): # Update the dynamic no flight zones in the final map! currentTime = int(time.time()) for key, val in self.dynamic_no_flight_zones.items(): #print(key, "=>", val) if int(val["valid_from_epoch"]) > currentTime or int( val["valid_to_epoch"]) < currentTime: # then don't plot it #print("Discard dnfz - not active right now!") continue if val["geometry"] == "polygon": #print("drawing a polygon") # first, draw a point: # coord[0] --> easting # coord[1] --> northing #print(list(val["polygon"].exterior.coords)) coordinateString = val["coordinates"] coordinateArray = coordinateString.split(' ') first = True for coordinatePair in coordinateArray: coord = coordinatePair.split(',') (east, north) = self.getPixelCoordinate( Coordinate(lat=coord[1], lon=coord[0])) toAppend = np.array([[east, north]]) if first: pts = np.array(toAppend) #print("Polygon here:", pts) first = False else: pts = np.concatenate([pts, toAppend]) pts = pts.reshape((-1, 1, 2)) #print(pts) with self.protection: cv2.polylines(self.final_dnfz_map, [pts], True, 1.0, 10) elif val["geometry"] == "circle": #print("drawing a circle") coordinateString = val["coordinates"] coordinateArray = coordinateString.split(',') (east, north) = self.getPixelCoordinate( Coordinate(lon=coordinateArray[0], lat=coordinateArray[1])) #print("Circle here:", (east,north)) with self.protection: cv2.circle(self.final_dnfz_map, (east, north), int(coordinateArray[2]), 1.0, 2)
def test_moves(self): coordinate = Coordinate((1, 0, 0)) moves = coordinate.moves() self.assertTrue(not moves.__contains__(coordinate)) self.assertEqual(len(moves), 4) self.assertTrue(moves.__contains__(Coordinate((0, 1, 0)))) self.assertTrue(moves.__contains__(Coordinate((0, -1, 0))))
def set_start_and_goal(self, start, goal, start_time=0): temp_start = Coordinate(GPS_data=start) temp_goal = Coordinate(GPS_data=goal) self.start = TimeCoord(easting=temp_start.easting, northing=temp_start.northing, time=start_time) self.goal = TimeCoord(easting=temp_goal.easting, northing=temp_goal.northing)
def test_shift_group_of_coordinates(): coor = make_zero_coordinate() coors = coor.extend_down(3) for coor in coors: coor.shift_down() assert coors == [Coordinate(0, 1), Coordinate(0, 2), Coordinate(0, 3)]
def __init__(self): self.numrows = 100 self.numcols = 100 self.startCoordinate = Coordinate(0, self.numcols - 1) self.goalCoordinate = Coordinate(self.numrows - 1, self.numcols - 1) self.cells = [[Cell(i, j) for j in range(self.numcols)] for i in range(self.numrows)] self.setBlockedTerrain(30)
def test_eq(self): a = Coordinate(0, 0) b = Coordinate(1, 2) c = Coordinate(0, 0) self.assertEqual(a, c) self.assertNotEqual(a, b) self.assertNotEqual(b, c)
def list_neighbors(self): result = [] for i in (Coordinate(0, -1), Coordinate(1, 0), Coordinate(0, 1), Coordinate(-1, 0)): result = update_list( result, self.dijkstra.give_element(self.coordinates + i)) return result
def move(self): # try to move! judge in the world direction = self.GetRandomDirection() if direction == Direction.up(): return Coordinate(self.coor.x, self.coor.y+1) elif direction == Direction.down(): return Coordinate(self.coor.x, self.coor.y-1) elif direction == Direction.left(): return Coordinate(self.coor.x-1, self.coor.y) else: return Coordinate(self.coor.x+1, self.coor.y)
def jump(self): if self._pos.x < 100: self._velocity += Coordinate(500, 500) elif self._pos.x > 600: self._velocity += Coordinate(-500, 500) elif self._pos.y < 100: self._velocity += Coordinate(0, 250) self._pos.y += 10
def __init__(self, offset=None, shape=None): self.__offset = None if offset is None else Coordinate(offset) self.__shape = None if shape is None else Coordinate(shape) if self.__offset is not None and self.__shape is not None: assert self.__offset.dims() == self.__shape.dims( ), "offset dimension %d != shape dimension %d" % ( self.__offset.dims(), self.__shape.dims())
def test_get_neighbouring_coordinates_4_0(self): coordinate = Coordinate(4, 0) actual_neighbouring_coordinates = coordinate.get_neighbouring_cordinates(4, 4) assert len(actual_neighbouring_coordinates) == 3 assert Coordinate(3, 0) in actual_neighbouring_coordinates assert Coordinate(3, 1) in actual_neighbouring_coordinates assert Coordinate(4, 1) in actual_neighbouring_coordinates
def move(self, stones): num = 0 i = 0 j = 0 if (len(stones[0]) == 0 and len(stones[1]) == 0): return self.grid.center() # Get last stone of opponent opponentLastStone = stones[1][-1] if opponentLastStone.x + 66 < self.grid.WIDTH: finalCoord = Coordinate(opponentLastStone.x + 66, opponentLastStone.y) else: finalCoord = Coordinate(opponentLastStone.x - 66, opponentLastStone.y) for i in range(0, len(self.coordList), self.JUMP): coord = self.coordList[i] x = opponentLastStone.x + coord.x y = opponentLastStone.y + coord.y if x < 0 or y < 0 or x > self.grid.WIDTH or y > self.grid.HEIGHT: continue currStone = Stone(x, y) flag = 0 if not opponentLastStone.getFeasible(currStone): continue for l in range(0, 2): for stone in stones[l]: if not stone.getFeasible(currStone): flag = 1 break if flag == 1: break if flag == 1: continue stones[0].append(currStone) self.grid.setColor(stones) ret = self.grid.getColorDist() stones[0].pop() if (ret[0] > num): num = ret[0] finalCoord = Coordinate(currStone.x, currStone.y) return finalCoord
def test_get_neighbouring_coordinates_0_4(self): coordinate = Coordinate(0, 4) actual_neighbouring_coordinates = coordinate.get_neighbouring_cordinates(4, 4) assert len(actual_neighbouring_coordinates) == 3 assert Coordinate(0, 3) in actual_neighbouring_coordinates assert Coordinate(1, 3) in actual_neighbouring_coordinates assert Coordinate(1, 4) in actual_neighbouring_coordinates