def __init__(self, name): """Initialize the map.""" self.__startLocation = None self.__exitLocation = None map = Map.__createEmptyMap() y = 0 with open(os.path.join(self.MAP_DIR, f"{name}.map"), "r", encoding="utf8") as f: for line in f: x = 0 for ch in line.rstrip(os.linesep): map[y][x] = ch if ch == "S": self.__startLocation = Coordinates(x, y) elif ch == "E": self.__exitLocation = Coordinates(x, y) x += 1 y += 1 self.__map = map f.close()
def _position2coordinates(self, pos): p = pos[...,0] / 180 * np.pi t = (90 - pos[...,1]) / 180 * np.pi r = pos[...,2] c = Coordinates() c.sph = np.vstack((r,t,p)).T return c
def loadMap(self): filename = self.level + ".txt" file = open(filename, "r") map = [] mapline = [] idcount = 1 xcount = 0 ycount = 0 for line in file: line = line.rstrip("\n") for c in line: if c == "X": newsquare = Square(self.squareSize, True, xcount, ycount) else: newsquare = Square(self.squareSize, False, xcount, ycount) if c == "1": self.start = Coordinates(xcount, ycount) elif c == "2": self.end = Coordinates(xcount, ycount) idcount += 1 xcount += 1 mapline.append(newsquare) xcount = 0 map.append(mapline) mapline = [] ycount += 1 file.close() return map
def get_coordinate_of_city(self, city_name: str) -> Coordinates: geocode = self._client.pelias_search(text=city_name) if geocode is None: raise ValueError('Could not collect data from OpenRouteService. Maybe wrong api key?') coordinates = Coordinates() if len(geocode['features']) > 0: coordinates.longitude = geocode['features'][0]['geometry']['coordinates'][0] coordinates.latitude = geocode['features'][0]['geometry']['coordinates'][1] return coordinates
def get_coordinates_from_city(self, city: str) -> Coordinates: self._connect_if_not_connected() sql_string = "SELECT longitude, latitude FROM cities WHERE city = ?" self._cursor.execute(sql_string, (city, )) answer = self._cursor.fetchone() coordinates = Coordinates() if answer: coordinates.longitude = answer[0] coordinates.latitude = answer[1] return coordinates
def new_coordinates(self, direction): if direction == 'up': new_coordinates = Coordinates(self.hero_coords.row + 1, self.hero_coords.column) elif direction == 'down': new_coordinates = Coordinates(self.hero_coords.row - 1, self.hero_coords.column) elif direction == 'left': new_coordinates = Coordinates(self.hero_coords.row, self.hero_coords.column - 1) else: new_coordinates = Coordinates(self.hero_coords.row, self.hero_coords.column + 1) return new_coordinates
def test_movements(self): origin = Coordinates(0,0,0) north = Direction.NORTH bot = GroundBot(origin, north) step_size_map = {Commands.FORWARD: 5} bot1 = GroundBot(origin, north, step_sizes_map=step_size_map) bot.navigate('FFR') self.assertTrue(bot.current_position == Coordinates(0,2,0)) self.assertTrue(bot.current_direction == Direction.EAST) bot1.navigate('FFR') self.assertTrue(bot1.current_position == Coordinates(0,10,0)) self.assertTrue(bot1.current_direction == Direction.EAST)
def __chooseBestMarker(self, query, markers, listLength): for marker in markers: marker.setAttribute( "soundex_diff", self.__diffsoundex(marker.getAttribute("name"), query)) listLength = min(listLength, markers.__len__()) markers = sorted(markers, cmp=lambda x, y: cmp(x.getAttribute("soundex_diff"), y.getAttribute("soundex_diff"))) coordinates = [] q_u = query.upper() for marker in markers[:listLength]: try: coordinates.append( Coordinates(lat=marker.getAttribute("lat"), lng=marker.getAttribute("lng"), name=marker.getAttribute("name").upper(), state=marker.getAttribute("state_ut"), district=marker.getAttribute("district"), sub_district=marker.getAttribute("tahsil"), level=marker.getAttribute("level"), quality="Taken_Help_Of_Phones", given_query=q_u)) except ValueError: pass return coordinates
def __chooseBestMarker(self, query, markers): lat = None lng = None quality = "Not_Available" name = None state = None district = None sub_district = None level = None names = [marker.getAttribute("name") for marker in markers] diffs = [self.__diffsoundex(name, query) for name in names] try: min_index, min_value = min(enumerate(diffs), key=operator.itemgetter(1)) marker = markers[min_index] lat = marker.getAttribute("lat") lng = marker.getAttribute("lng") name = marker.getAttribute("name") state = marker.getAttribute("state_ut") district = marker.getAttribute("district") sub_district = marker.getAttribute("tahsil") level = marker.getAttribute("level") quality = "Taken_Help_Of_Phones" except ValueError: pass return Coordinates(lat=lat, lng=lng, quality=quality, name=name.upper(), state=state, district=district, sub_district=sub_district, level=level, given_query=query.upper())
def __init__(self, squareSize, isWall, x, y): MapObject.__init__(self, squareSize*x, squareSize*y) self.coord = Coordinates(x,y) self.isWall = isWall self.size = squareSize self.cameFrom = None self.shape = None
def testMumbai(self): lc = Location() mumbai_cord = lc.getCoordinates(query="Mumbai", listLength=1)[0] mumbai_expected = Coordinates(lat=19.017587, lng=72.856248, state="Maharashtra", sub_district="Mumbai", district="Mumbai", level="Town", name="MUMBAI") self.assertTrue( (float(mumbai_cord.lat) - float(mumbai_expected.lat)) < 0.00001, "Latitude didnot Match for Mumbai") self.assertTrue( (float(mumbai_cord.lng) - float(mumbai_expected.lng)) < 0.00001, "Longitude didnot Match for Mumbai") self.assertEqual(mumbai_cord.state, mumbai_expected.state, "States didnot Match for Mumbai") self.assertEqual(mumbai_cord.district, mumbai_expected.district, "District didnot Match for Mumbai") self.assertEqual(mumbai_cord.sub_district, mumbai_expected.sub_district, "SUB District didnot Match for Mumbai") self.assertEqual(mumbai_cord.level, mumbai_expected.level, "Levels didnot Match for Mumbai")
def get_random_coordinates(self): height_coord = np.random.randint(0, self.field.shape[0] - 1) width_coord = np.random.randint(0, self.field.shape[1] - 1) coordinates = Coordinates(height_coord, width_coord) if not self.is_cell_empty(coordinates): return self.get_random_coordinates() return coordinates
def contourmethod(self, edges): hull = None contours, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours(self.source_color, contours, -1, (0, 0, 255), 1) #cv2.imshow("contours", self.source_color) print hierarchy c = max(contours, key=cv2.contourArea) cv2.drawContours(self.source_color, c, -1, (0, 0, 0), 3) #cv2.imshow("max_contour", self.source_color) cv2.waitKey(0) for i, cnt in enumerate(contours): if hierarchy[ 0, i, 3] == -1 and cv2.contourArea(cnt) >= cv2.contourArea(c): hull = cv2.convexHull(cnt, returnPoints=True) break print hull cv2.drawContours(self.source_color, [hull], -1, (255, 255, 0), 1) #cv2.imshow("hull", self.source_color) cv2.waitKey(0) length = len(hull) M = cv2.moments(hull) if M['m00'] == 0: M['m00'] = 0.01 self.cx = int(M['m10'] / M['m00']) self.cy = int(M['m01'] / M['m00']) center = [self.cx, self.cy] #cv2.circle(self.source_color, (self.cx, self.cy), 5, (0, 255, 255), 2) print length coord = Coordinates() for i in xrange(0, length): if (i + 3) < length: [x, y] = coord.intersection( (hull[i][0][0], hull[i][0][1]), (hull[i + 1][0][0], hull[i + 1][0][1]), (hull[i + 2][0][0], hull[i + 2][0][1]), (hull[i + 3][0][0], hull[i + 3][0][1])) coord.append(x, y) cv2.circle(self.source_color, (x, y), 6, (255, 255, 255), 2) #cv2.imshow("coordinates", self.source_color) #cv2.waitKey(0) return coord, center
def get_coordinates_houghP(self, edges): constant = 100 minLineLength = 10 maxLineGap = 5 coord = Coordinates() lines = cv2.HoughLinesP(edges, 1, np.pi / 180, constant, minLineLength, maxLineGap) print lines, type(lines) points = [] for x1, y1, x2, y2 in lines[0]: points.append([x1, y1]) points.append([x2, y2]) [x, y] = coord.intersection(points[0], points[1], points[2], points[3]) coord.append(x, y) # cv2.line(edges, (x1, y1), (x2, y2), (0, 255, 0), 2) # cv2.imshow("line", edges) # cv2.waitKey(0) return coord
def initial_spawn(self, hero): self.hero = hero for i in range(len(self.map)): for j in range(len(self.map[i])): if self.map[i][j] == self.dict_['start']: self.change_coordinates_in_map(i, j, Dungeon.dict_['hero']) self.hero_coords = Coordinates(i, j) return True
def move_forward(self, step_size): movement_map = self.DIRECTION_MOVEMENT_MAP[self.current_direction] point1 = [0, 0, 0] index = movement_map['index'] point1[index] = step_size coordinates1 = Coordinates(*point1) operation = movement_map['operation'] self.current_position = operation(self.current_position, coordinates1)
def spawn(self, hero): if self.hero_coords.row is None: self.initial_spawn(hero) for i in range(len(self.map)): for j in range(len(self.map[i])): if self.map[i][j] == self.dict_['walkable']: self.change_coordinates_in_map(i, j, Dungeon.dict_['hero']) self.hero_coords = Coordinates(i, j) yield True
def __init__(self, x, y): self.coordinates = Coordinates(x, y) self.alive = True self.xspeed = 0 self.xacceleration = 1 self.yspeed = 0 self.yacceleration = 2 self.maxspeed = 3 self.offset = Coordinates(0, 0) self.movingleft = False # Signaali GUI:n näppäinpainalluksesta self.movingright = False # Signaali GUI:n näppäinpainalluksesta self.jumpcond = 0 # Hypyn "ajastin" self.jumping = False # Signaali GUI:n näppäinpainalluksesta
def get_sensor_position(self, sensor_id): # front sensors are numbered from left to right, with `sensors_pitch` distance between them # they are positioned in a line perpendicular to track direction and `sensors_dist` apart from robot's position #calculate sensor position without considering heading sensor_x = self.sensors_dist sensor_y = ((self.n_sensors - 1)/2 - sensor_id) * self.sensors_pitch #transform into polar coordinates r, theta = coord.xy2polar(sensor_x, sensor_y) #sum heading to theta to calculate sensor position in reference to robot position new_theta = theta + self.heading new_x, new_y = coord.polar2xy(r, new_theta) #calculate final position in reference to track's origin final_sensor_x = self.pos.x + new_x final_sensor_y = self.pos.y - new_y #inverted sign due to inverted Y axis direction return point.Point(final_sensor_x, final_sensor_y)
def __init__(self): Tk.__init__(self) container = self.create_main_container() self.set_window_properties() self.data = Data(pd.DataFrame()) self.coordinates = Coordinates() self.heatmap = Heatmap() self.initialize_pages(container) self.show_frame(FirstPage) self.protocol("WM_DELETE_WINDOW", self.on_closing)
def testNehdaiJaisalmerRajasthan(self): lc = Location(state="Rajasthan", district="Jaisalmer") nehdai_cord = lc.getCoordinates(query="Nehdai", listLength=1)[0] nehdai_expected = Coordinates(lat=27.402876, lng=70.995243, state="Rajasthan", district="Jaisalmer", sub_district="Jaisalmer", level="Village", name="NEHDAI") self.assertEqual( nehdai_cord, nehdai_expected, "Cordinates didnot Match for Nehdai, (JSM) Rajasthan")
def can_attack_by_spell(self): if self.hero.current_spell.cast_range < 1: return False move = [[0, 1], [1, 0], [0, -1], [-1, 0]] for i in range(1, self.hero.current_spell.cast_range): for j in move: coords = Coordinates(j[0] * i, j[1] * i) if self.is_inside_map(coords) and self.map[coords.row][coords.column] ==\ Dungeon.dict_['enemy']: return True return False
def contourmethod(self, edges): hull = None contours, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) print hierarchy for i, cnt in enumerate(contours): if hierarchy[0, i, 3] == -1 and cv2.contourArea(cnt) > 5000: hull = cv2.convexHull(cnt, returnPoints=True) break print hull length = len(hull) print length coord = Coordinates() for i in xrange(0, length): if (i + 3) < length: [x, y] = coord.intersection( (hull[i][0][0], hull[i][0][1]), (hull[i + 1][0][0], hull[i + 1][0][1]), (hull[i + 2][0][0], hull[i + 2][0][1]), (hull[i + 3][0][0], hull[i + 3][0][1]), ) coord.append(x, y) return coord
def contourmethod(self, edges): hull = None contours, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) print hierarchy for i, cnt in enumerate(contours): if hierarchy[0, i, 3] == -1 and cv2.contourArea(cnt) > 5000: hull = cv2.convexHull(cnt, returnPoints=True) break print hull length = len(hull) print length coord = Coordinates() for i in xrange(0, length): if (i + 3) < length: [x, y] = coord.intersection( (hull[i][0][0], hull[i][0][1]), (hull[i + 1][0][0], hull[i + 1][0][1]), (hull[i + 2][0][0], hull[i + 2][0][1]), (hull[i + 3][0][0], hull[i + 3][0][1])) coord.append(x, y) return coord
def update(self, data): if data: if (self.coordinates) and (self.speed > MN.STOP) : if not (self.lastpos.count(self.coordinates)) : self.lastpos.append(self.coordinates) if len(self.lastpos)>MN.LASTPOSLEN: self.lastpos.pop(0)# = self.lastpos[-MN.LASTPOSLEN:] self.speed = data[0] self.course = data[1] self.coordinates = Coordinates(data[2][0], data[2][1]) self.status = ship_status.ONLINE else: self.reset() status = ship_status.OFFLINE
def deserialize_acte(xml): date = str(find_text(xml, "./data/data_proper_acte")) date_format = "%d/%m/%Y %H.%M" return Acte.Builder() \ .name(find_text(xml, "./nom")) \ .address( Address.Builder().name(find_text(xml, "./lloc_simple/nom")) \ .street(find_text(xml, address_path + "/carrer")) \ .number(find_text(xml, address_path + "/numero")) \ .zip_code(find_text(xml, address_path + "/codi_postal")) \ .district(find_text(xml, address_path + "/districte")) \ .city(find_text(xml, address_path + "/municipi")) \ .build()) \ .coordinates(Coordinates.Builder() .lat(get_float(xml, "lat")) \ .lon(get_float(xml, "lon")) \ .build()) \ .date(datetime.datetime.strptime(date, date_format)) \ .build()
def getDestinationInDirectionFromLocation(self, originLocation, direction): """Get the location that is adjacent to the direction's location.""" originTile = self.__getTileAtCoordinates(originLocation) if originTile == Map.TILE_OUTSIDE_MAP: return None x = originLocation.x y = originLocation.y if direction == Direction.NORTH: y -= 1 elif direction == Direction.EAST: x += 1 elif direction == Direction.SOUTH: y += 1 elif direction == Direction.WEST: x -= 1 destinationLocation = Coordinates(x, y) destinationTile = self.__getTileAtCoordinates( coordinates=destinationLocation) return None if destinationTile == Map.TILE_OUTSIDE_MAP else destinationLocation
def guessed_coordinates(self) -> Coordinates: return Coordinates(self.lat_guessed, self.lng_guessed)
def actual_coordinates(self) -> Coordinates: return Coordinates(self.lat, self.lng)
import sys import time import traceback from coordinates import Coordinates from databaceclient import MongoDbClient if __name__ == '__main__': argvs = sys.argv host = '127.0.0.1' port = 27017 mclient = MongoDbClient(host,port) str_line = None try: mclient.connection() db = mclient.get_db('snmfl') coordinates = Coordinates({'db':db}) coordinates.drop() coordinates.create_index_geo2d('location') cnt = 0 for line in open(argvs[1],'r'): ''' if cnt == 0: cnt = cnt + 1 continue ''' #str_line = line.rstrip("\r\n").replace('"','') # 改行コードと引用符を取っ払う str_line = line.rstrip("\r\n") coordinates.set_list_to_data(str_line) # 配列からdict作成 coordinates.insert(coordinates.data) # INSERT print str_line
class Ship: ''' A Ship class ''' def __init__(self, name, speed=None, course=None, coordinates=None): # TODO: Add last_update time if isinstance(name, list): self.name = name[0] self.nick = unicode(name[1], "UTF-8")[:-1] # \n Kill else: self.name = self.nick = name self.coordinates = coordinates self.speed = speed self.status = ship_status.OFFLINE self.lastpos = [] self.lastpierindex = None self.route = None self.alive = False self.printedpos = None def reset(self): #self.coordinates = None #self.course = None #self.speed = None self.lastpos = [] self.lastpierindex = None self.route = None #self.status = ship_status.OFFLINE def msg(self): res = message.PASS #print self if self.alive and (self.status == ship_status.ONLINE) : self.printedpos = self.coordinates if (self.speed < MN.STOP): res = message.STAND else : res = message.UNDERWAY return message.reverse_mapping[res] def msgupdate(self, data, zone): res = message.PASS A = self.status #aCoord = self.coordinates self.update(data) self.deadend(zone) B = self.status #bCoord = self.coordinates if self.printedpos and self.coordinates: self.alive = ((self.printedpos - self.coordinates).length() > MN.DELTA) else: self.alive = ((not self.printedpos) and (self.coordinates)) #if aCoord and bCoord: # print self.name, aCoord, bCoord, self.alive if (A == ship_status.ONLINE) : if (B == ship_status.ONLINE) : res = message.PASS elif (B == ship_status.OFFLINE) or (B == ship_status.INDEADEND) : res = message.GOODBYE elif (A == ship_status.OFFLINE) : if (B == ship_status.ONLINE) : res = message.HELLO elif (B == ship_status.OFFLINE) or (B == ship_status.INDEADEND) : res = message.PASS elif (A == ship_status.INDEADEND) : if (B == ship_status.ONLINE) : res = message.HELLO elif (B == ship_status.OFFLINE) : res = message.GOODBYE elif (B == ship_status.INDEADEND) : res = message.PASS return message.reverse_mapping[res] def update(self, data): if data: if (self.coordinates) and (self.speed > MN.STOP) : if not (self.lastpos.count(self.coordinates)) : self.lastpos.append(self.coordinates) if len(self.lastpos)>MN.LASTPOSLEN: self.lastpos.pop(0)# = self.lastpos[-MN.LASTPOSLEN:] self.speed = data[0] self.course = data[1] self.coordinates = Coordinates(data[2][0], data[2][1]) self.status = ship_status.ONLINE else: self.reset() status = ship_status.OFFLINE def update_from_ais(self): scrapper = Scrapper() data = scrapper.scrape_ship(self.name) return self.update(data) def __str__(self): if self.status == ship_status.ONLINE: res = "name: {0}; speed: {1}; course: {2}; coordinates: {3}; route: {4};".format(self.name, self.speed, self.course, self.coordinates, self.route) else: res = "name: {0}; ais status: {1}".format(self.name, self.ais_status()) return res def ais_status(self): return ship_status.reverse_mapping[self.status] def angle (self, point): ''' Easy use for Coordinates.angle() ''' return self.coordinates.angle(self.course, point) def viewangle(self, point): return self.angle(point) < MN.VIEWANGLE def collinear(self, point): ''' Easy use for Coordinates.collinear() ''' return self.coordinates.collinear(self.course, point) def length(self, point): ''' Easy use for Coordinates.length() ''' return (self.coordinates - point).length() def deadend(self, zone): if self.status == ship_status.OFFLINE: return False if (zone.area.is_inside(self.coordinates)): if (self.speed < MN.STOP) or (self.length(zone.mark) < MN.DEADEND) (self.viewangle(zone.mark)): self.status = ship_status.INDEADEND self.reset() return True return False
from bot import GroundBot, AirBot from direction import Direction from coordinates import Coordinates origin = Coordinates(0, 0, 0) north = Direction.NORTH bot1 = GroundBot(origin, north) bot2 = AirBot(origin, north) bot1.navigate('FFRFFLFFLFRLF') print 'BOT1--->', bot1.report_position() bot2.navigate('FFUF') print 'BOT2--->', bot2.report_position()
def setUp(self): self.snake = Snake(Coordinates(50, 50))
def test_check_self_collision(self): self.assertFalse(self.snake.check_self_collision()) self.snake.coordinates += [Coordinates(50, 50)] self.assertTrue(self.snake.check_self_collision())
def test_get_next_head_coordinates(self): self.assertEqual(self.snake.get_next_head_coordinates(), Coordinates(50, 49)) self.assertEqual(self.snake.get_next_head_coordinates(), Coordinates(50, 49))