def handleToolEvent(self, event): radius = int(self.palette_data[self.palette_data_type]['radius']) link_length = \ self.palette_data[self.palette_data_type]['link_length'] Tool.handleToolEvent(self, event) if event.type == MOUSEBUTTONDOWN and event.button == 1: self.vertices = [tuple_to_int(event.pos)] self.safe = False elif event.type == MOUSEBUTTONUP and event.button == 1: if not self.vertices: return if len(self.vertices) == 1 and self.previous_vertices is not None: last_x_y = self.previous_vertices[-1] delta_x = last_x_y[0] - tuple_to_int(event.pos)[0] delta_y = last_x_y[1] - tuple_to_int(event.pos)[1] self.vertices = [[i[0] - delta_x, i[1] - delta_y] for i in self.previous_vertices] self.safe = True if self.vertices and self.safe: self.constructor(self.vertices, link_length, radius) self.previous_vertices = self.vertices[:] self.vertices = None elif event.type == MOUSEMOTION and self.vertices: last_x_y = self.vertices[-1] if distance(tuple_to_int(event.pos), last_x_y) >= link_length: self.vertices.append(tuple_to_int(event.pos)) if not self.vertices: return if distance(tuple_to_int(event.pos), self.vertices[0]) >= link_length * 5 and \ len(self.vertices) > 3: self.safe = True
def swordFightA(self, player, rocks, enemyGroup): enemy = enemyGroup.sprites() target = enemy[0] for x in range(len(enemy)): if helpers.distance(self.rect.topleft, enemy[x].rect.topleft) < helpers.distance(self.rect.topleft, target.rect.topleft): target = enemy[x] if self.clock == 0: self.__chase(target.rect.topleft, rocks, target) if self.walking_timer <=0: self.__walk(target) self.walking_timer = 5 else: self.walking_timer -= 1 if helpers.distance(self.rect.topleft, target.rect.topleft) < 9 and self.cool_down <= 0: self.attacking = True self.attack_group.add(self.attack) self.cool_down = 20 elif self.cool_down > 0: self.cool_down -=1 if self.attacking: self.attack.use(self, self.follow_direction) if self.attack.is_done(): self.attacking = False self.attack.kill() hit_enemy = pygame.sprite.spritecollide(target, self.attack_group, False) if hit_enemy: target.get_hit("none", 1) self.attack_group.update() self.attack_group.draw(self.windowSurface)
def expLoss(output, target, m, centers, class_num, c_points=None, center_distance=None): loss = 0. for i, out in enumerate(output): classId = target[i].item() if c_points is not None: if classId not in c_points: c_points[classId] = out.unsqueeze(0).data else: c_points[classId] = torch.cat( (c_points[classId], out.unsqueeze(0).data), dim=0) D_xc = distance(out, centers[classId]).sum() min_D_xj = distance(out, center_distance[classId]).sum() loss = loss + torch.exp(-min_D_xj / (D_xc + 1e-8)) return loss / target.size()[0]
def update(self, player, rocks): distance = abs(helpers.distance(player.rect.topleft, self.rect.topleft)) old_position = self.rect.topleft """ Above checks the distance from enemy to player, according to that, the enemy either chases directly or patrols """ if distance < 15 or self.id == 3: self.follow = True else: self.follow = False if self.follow: if self.clock == 0: target = player if player.hasFriend: freind = player.passComp() if helpers.distance(player.rect.topleft, self.rect.topleft) > helpers.distance(freind.rect.topleft, self.rect.topleft): target = freind self.__chase(target.rect.topleft, rocks) if self.walking_timer <=0: self.__walk(player) self.walking_timer = 5 else: self.walking_timer -= 1 else: self.clock -= 1 else: self.__patrol() if not self.__check_collision(rocks, player, old_position): self.blocked_direction = "nope"
def test_helper(self): self.assertTrue( abs(helpers.distance((-4, 6.5), (-7, 17)) - 10.920164833920778) < 0.001) self.assertTrue( abs( helpers.distance((50.67, -4.006), (-3.345, 36.98)) - 67.80466371128169) < 0.001)
def update_weights(self, sensor_range, std_landmark_x, std_landmark_y, observations, map_landmarks): # print(map_landmarks) # print(std_landmark_x, std_landmark_y) # TODO: For each particle, do the following: for particle in self.particles: # 1. Select the set of landmarks that are visible # (within the sensor range). landmarks = [] for key in map_landmarks.keys(): dist = distance(map_landmarks[key], particle) if dist <= sensor_range: temp_dict = map_landmarks[key] temp_dict['id'] = key landmarks.append(temp_dict) if len(landmarks) == 0: continue # 2. Transform each observed landmark's coordinates from the # particle's coordinate system to the map's coordinates. p_x = particle['x'] p_y = particle['y'] p_t = particle['t'] transformed_observations = [] for observation in observations: m_x = p_x + observation['x'] * np.cos( p_t) - observation['y'] * np.sin(p_t) m_y = p_y + observation['x'] * np.sin( p_t) + observation['y'] * np.cos(p_t) transformed_observations.append({'x': m_x, 'y': m_y}) # 3. Associate each transformed observation to one of the # predicted (selected in Step 1) landmark positions. # Use self.associate() for this purpose - it receives # the predicted landmarks and observations; and returns # the list of landmarks by implementing the nearest-neighbour # association algorithm. associate_results = self.associate(landmarks, transformed_observations) # 4. Calculate probability of this set of observations based on # a multi-variate Gaussian distribution (two variables being # the x and y positions with means from associated positions # and variances from std_landmark_x and std_landmark_y). # The resulting probability is the product of probabilities # for all the observations. # 5. Update the particle's weight by the calculated probability. particle['w'] = 1.0 particle['assoc'] = [] for i, associate_result in enumerate(associate_results): dist = distance(associate_result, particle) observation_distance = np.sqrt( (observations[i]['x']**2 + observations[i]['y']**2)) particle['w'] *= norm_pdf( dist, observation_distance, np.sqrt(std_landmark_x**2 + std_landmark_y**2)) + 1e-9 particle['assoc'].append(associate_result['id'])
def assignCluster(vectors, clusters): for i in vectors: for y in clusters: if i.cluster is None or helpers.distance(i, y) < helpers.distance( i, i.cluster): i.cluster = y for x in vectors: for z in clusters: if x.cluster == z: z.vectors.append(x) return moveClusters(clusters)
def update_weights(self, sensor_range, std_landmark_x, std_landmark_y, observations, map_landmarks): # TODO: For each particle, do the following: # 1. Select the set of landmarks that are visible # (within the sensor range). in_range = [] associations = [] for p in self.particles: for k, v in map_landmarks.items(): if distance(p, v) < sensor_range: in_range.append({'id': k, 'x': v['x'], 'y': v['y']}) # 2. Transform each observed landmark's coordinates from the # particle's coordinate system to the map's coordinates. trans_observation = [] for obs in observations: x = p['x'] + (obs['x'] * np.cos(p['t'])) - (obs['y'] * np.sin(p['t'])) y = p['y'] + (obs['x'] * np.sin(p['t'])) + (obs['y'] * np.cos(p['t'])) trans_observation.append({'x': x, 'y': y}) # 3. Associate each transformed observation to one of the # predicted (selected in Step 1) landmark positions. # Use self.associate() for this purpose - it receives # the predicted landmarks and observations; and returns # the list of landmarks by implementing the nearest-neighbour # association algorithm. if not in_range: continue association_temp = self.associate(in_range, trans_observation) # 4. Calculate probability of this set of observations based on # a multi-variate Gaussian distribution (two variables being # the x and y positions with means from associated positions # and variances from std_landmark_x and std_landmark_y). # The resulting probability is the product of probabilities # for all the observations. p['w'] = 1 p['assoc'] = [] for i in range(len(association_temp)): p['w'] *= ( 1 / np.sqrt(2 * np.pi) / np.sqrt(std_landmark_x**2 + std_landmark_y**2) ) * np.exp(-1 / 2 * ( (distance(association_temp[i], p) - np.sqrt(observations[i]['x']**2 + observations[i]['y']**2) ) / np.sqrt(std_landmark_x**2 + std_landmark_y**2))**2) # 5. Update the particle's weight by the calculated probability. p['assoc'].append(association_temp[i]['id'])
def handleToolEvent(self, event): Tool.handleToolEvent(self, event) if hasattr(event, 'button') and event.button == 1: if event.type == MOUSEBUTTONDOWN and self.vertices is None: self.vertices = [tuple_to_int(event.pos)] self.safe = False if not self.vertices: return if event.type == MOUSEBUTTONUP and self.vertices is not None and \ len(self.vertices) == 1 and \ tuple_to_int(event.pos)[0] == self.vertices[0][0] and \ tuple_to_int(event.pos)[1] == self.vertices[0][1]: if self.previous_vertices is not None: last_x_y = self.previous_vertices[-1] delta_x = last_x_y[0] - tuple_to_int(event.pos)[0] delta_y = last_x_y[1] - tuple_to_int(event.pos)[1] self.vertices = [[i[0] - delta_x, i[1] - delta_y] for i in self.previous_vertices] self.safe = True self.constructor( self.vertices, density=self.palette_data['density'], restitution=self.palette_data['restitution'], friction=self.palette_data['friction']) self.vertices = None elif (event.type == MOUSEBUTTONUP or event.type == MOUSEBUTTONDOWN): if self.vertices is None or (tuple_to_int(event.pos)[0] == self.vertices[-1][0] and tuple_to_int(event.pos)[1] == self.vertices[-1][1]): # Skip if coordinate is same as last one return if distance(tuple_to_int(event.pos), self.vertices[0]) < 15 \ and self.safe: self.vertices.append(self.vertices[0]) # Connect polygon self.constructor( self.vertices, density=self.palette_data['density'], restitution=self.palette_data['restitution'], friction=self.palette_data['friction']) self.previous_vertices = self.vertices[:] self.vertices = None elif distance(tuple_to_int(event.pos), self.vertices[0]) < 15: self.vertices = None else: self.vertices.append(tuple_to_int(event.pos)) if distance(tuple_to_int(event.pos), self.vertices[0]) > 54: self.safe = True
def handleToolEvent(self, event): Tool.handleToolEvent(self, event) if hasattr(event, 'button') and event.button == 1: if event.type == MOUSEBUTTONDOWN and self.vertices is None: self.vertices = [tuple_to_int(event.pos)] self.safe = False if not self.vertices: return if event.type == MOUSEBUTTONUP and self.vertices is not None and \ len(self.vertices) == 1 and \ tuple_to_int(event.pos)[0] == self.vertices[0][0] and \ tuple_to_int(event.pos)[1] == self.vertices[0][1]: if self.previous_vertices is not None: last_x_y = self.previous_vertices[-1] delta_x = last_x_y[0] - tuple_to_int(event.pos)[0] delta_y = last_x_y[1] - tuple_to_int(event.pos)[1] self.vertices = [[i[0] - delta_x, i[1] - delta_y] for i in self.previous_vertices] self.safe = True self.constructor( self.vertices, density=self.palette_data['density'], restitution=self.palette_data['restitution'], friction=self.palette_data['friction']) self.vertices = None elif (event.type == MOUSEBUTTONUP or event.type == MOUSEBUTTONDOWN): if self.vertices is None or (tuple_to_int( event.pos)[0] == self.vertices[-1][0] and tuple_to_int( event.pos)[1] == self.vertices[-1][1]): # Skip if coordinate is same as last one return if distance(tuple_to_int(event.pos), self.vertices[0]) < 15 \ and self.safe: self.vertices.append(self.vertices[0]) # Connect polygon self.constructor( self.vertices, density=self.palette_data['density'], restitution=self.palette_data['restitution'], friction=self.palette_data['friction']) self.previous_vertices = self.vertices[:] self.vertices = None elif distance(tuple_to_int(event.pos), self.vertices[0]) < 15: self.vertices = None else: self.vertices.append(tuple_to_int(event.pos)) if distance(tuple_to_int(event.pos), self.vertices[0]) > 54: self.safe = True
def _get_Ce(self, side, boundary): sigma = self.conds[boundary]['Sigma'] beta = self.conds[boundary]['Beta'] gamma = distance(side[0], side[1]) Uc = self.conds[boundary]['Uc'] return np.array([[1], [1]]) * sigma * gamma * Uc / (beta * 2)
def update(self, player, rocks): if self.decided and self.tele_done: self.direction = direction = helpers.checkOrient(player, self) if self.attack_timer <= 0: self.__loadShot(player) self.attack_timer = 130 elif self.attack_timer <15: self.attack_timer -=1 self.image = self.tele1 else: self.__move(player) self.attack_timer -=1 if self.immortal_timer > 0: self.immortal_timer -=1 self.attack_timer -= 1 elif self.decided and (not self.tele_done): self.__teleport() elif (not self.decided) and (helpers.distance(player.rect.topleft, self.rect.topleft) < 12): self.__decide() self.attack_group.update(player, rocks) self.attack_group.draw(self.screen) hit_player = pygame.sprite.spritecollide(player, self.attack_group, False) if hit_player: player.getHit("none", 1) hit_player[0].kill()
def handleToolEvent(self, event): Tool.handleToolEvent(self, event) if event.type == MOUSEBUTTONDOWN and event.button == 1: self.vertices = [tuple_to_int(event.pos)] self.safe = False elif event.type == MOUSEBUTTONUP and event.button == 1: if not self.vertices: return if len(self.vertices) == 1 and self.previous_vertices is not None: last_x_y = self.previous_vertices[-1] delta_x = last_x_y[0] - tuple_to_int(event.pos)[0] delta_y = last_x_y[1] - tuple_to_int(event.pos)[1] self.vertices = [[i[0] - delta_x, i[1] - delta_y] for i in self.previous_vertices] self.safe = True if self.vertices and self.safe: self.constructor( self.vertices, density=self.palette_data['density'], restitution=self.palette_data['restitution'], friction=self.palette_data['friction']) self.previous_vertices = self.vertices[:] self.vertices = None elif event.type == MOUSEMOTION and self.vertices: self.vertices.append(tuple_to_int(event.pos)) if not self.vertices: return if distance(tuple_to_int(event.pos), self.vertices[0]) >= 55 and \ len(self.vertices) > 3: self.safe = True
def constructor(self, pos1, pos2, density, restitution, friction, share=True): if pos2[0] == pos1[0] and pos2[1] == pos1[1]: pos1 = [pos2[0] - self.line_delta[0], pos2[1] - self.line_delta[1]] else: self.line_delta = [pos2[0] - pos1[0], pos2[1] - pos1[1]] # Use minimum sized triangle if user input too small minimum_size_check = float(distance(pos1, pos2)) if minimum_size_check < 20: middle_x = (pos1[0] + pos2[0]) / 2.0 pos1[0] = middle_x - (((middle_x - pos1[0]) / minimum_size_check) * 20) pos2[0] = middle_x - (((middle_x - pos2[0]) / minimum_size_check) * 20) middle_y = (pos1[1] + pos2[1]) / 2.0 pos1[1] = middle_y - (((middle_y - pos1[1]) / minimum_size_check) * 20) pos2[1] = middle_y - (((middle_y - pos2[1]) / minimum_size_check) * 20) self.vertices = constructTriangleFromLine(pos1, pos2) self.game.world.add.convexPoly(self.vertices, dynamic=True, density=density, restitution=restitution, friction=friction) if share: data = json.dumps([pos1, pos2, density, restitution, friction]) self.game.activity.send_event('T:' + data) self.vertices = None
def update_weights(self, sensor_range, std_landmark_x, std_landmark_y, observations, map_landmarks): # TODO: For each particle, do the following: # 1. Select the set of landmarks that are visible # (within the sensor range). associations = [] tran_obs = [] for p in self.particles: px = p['x'] py = p['y'] pt = p['t'] vis_landmark = [] for i, l in map_landmarks.items(): if distance(p, l) < sensor_range: vis_id = i vis_x = l['x'] vis_y = l['y'] vis_landmark.append({'id': vis_id, 'x': vis_x, 'y': vis_y}) # 2. Transform each observed landmark's coordinates from the # particle's coordinate system to the map's coordinates. temp = [] for obs in observations: temp_x = px + obs['x'] * np.cos(pt) - obs['y'] * np.sin(pt) temp_y = py + obs['x'] * np.sin(pt) + obs['y'] * np.cos(pt) temp = { 'x': temp_x, 'y': temp_y, } tran_obs.append(temp) if not vis_landmark: continue # 3. Associate each transformed observation to one of the # predicted (selected in Step 1) landmark positions. # Use self.associate() for this purpose - it receives # the predicted landmarks and observations; and returns # the list of landmarks by implementing the nearest-neighbour # association algorithm. near_landmark = self.associate(vis_landmark, tran_obs) # 4. Calculate probability of this set of observations based on # a multi-variate Gaussian distribution (two variables being # the x and y positions with means from associated positions # and variances from std_landmark_x and std_landmark_y). # The resulting probability is the product of probabilities # for all the observations. p['w'] = 1.0 for n in near_landmark: norm = 1 / (2 * math.pi * std_landmark_x * std_landmark_y) power = ((p['x']-n['x'])**2) / (std_landmark_x**2) \ +((p['y']-n['y'])**2)/(std_landmark_y**2) \ - 2*((p['x']-n['x'])*(p['y']-n['y'])/(std_landmark_x*std_landmark_y)) # 5. Update the particle's weight by the calculated probability. weight = norm * np.exp(-0.5 * power) p['w'] *= weight associations.append(n['id']) p['assoc'] = associations
def make_chain(self, body1, body2, pos1, pos2, link_length, radius): dist = int(distance(pos1, pos2) + 0.5) x1, y1 = pos1 x2, y2 = pos2 bearing = math.atan2((y2 - y1), (x2 - x1)) if dist < link_length: # Too short to make a chain self.game.world.add.joint(body1, body2, pos1, pos2) return # Draw circles along the path and join them together prev_circle = body1 prev_pos = tuple_to_int((x1, y1)) for current_point in range(int(link_length / 2.), dist, int(link_length)): x = x1 + (current_point) * math.cos(bearing) y = y1 + (current_point) * math.sin(bearing) circle = self.game.world.add.ball(tuple_to_int((x, y)), radius, dynamic=True, density=1.0, restitution=0.16, friction=0.1) circle.userData['color'] = (0, 0, 0) self.game.world.add.joint( prev_circle, circle, prev_pos, tuple_to_int((x, y)), False) if (current_point + link_length) >= dist: self.game.world.add.joint( circle, body2, tuple_to_int((x, y)), pos2, False) prev_circle = circle prev_pos = tuple_to_int((x, y))
def constructor(self, vertices, link_length, radius, share=True): pos1 = vertices[0][:] body1 = find_body(self.game.world, pos1) if body1 is None: body1 = self.game.world.add.ball( pos1, radius, dynamic=True, density=1.0, restitution=0.16, friction=0.1) body1.userData['color'] = (0, 0, 0) for i, pos2 in enumerate(vertices): if i == 0: continue body2 = find_body(self.game.world, pos2) if body2 is None: body2 = self.game.world.add.ball( pos2, radius, dynamic=True, density=1.0, restitution=0.16, friction=0.1) body2.userData['color'] = (0, 0, 0) self.make_chain(body1, body2, pos1, pos2, link_length, radius) body1 = body2 pos1 = pos2[:] # Close the chain if the start and end were near each other if distance(vertices[0], vertices[-1]) < link_length * 2: pos1 = vertices[0][:] body1 = find_body(self.game.world, pos1) pos2 = vertices[-1][:] body2 = find_body(self.game.world, pos2) if body1 != body2: self.make_chain(body1, body2, pos1, pos2, link_length, radius) if share: data = json.dumps([vertices, link_length, radius]) self.game.activity.send_event('c:' + data)
def handleEvents(self, event, bridge): # look for default events, and if none are # handled then try the custom events if not super(GirderTool, self).handleEvents(event, bridge): if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: self.pt1 = pygame.mouse.get_pos() elif event.type == pygame.MOUSEBUTTONUP: if event.button == 1: if self.pt2 is not None: self.game.world.set_color( (self.red, self.green, self.blue)) self.red += self.colordiff self.green += self.colordiff self.blue += self.colordiff if self.red > 200: self.colordiff *= -1 elif self.red < 20: self.colordiff *= -1 print(self.theta, math.degrees(self.theta)) self.game.world.add.rect(((self.pt1[0] + self.pt2[0]) / 2, (self.pt1[1] + self.pt2[1]) / 2), helpers.distance( self.pt1, self.pt2) / 2, self.thickness / 2, angle=math.degrees( self.theta), dynamic=True, density=1.0, restitution=0.16, friction=0.5) self.game.bridge.box_added() self.game.world.reset_color() self.pt1 = None
def distance(self, bus_stop: BusStop = None, user_loc: UserLoc = None): if not bus_stop and not user_loc: return 10000 (lat, lon) = (bus_stop.LAT_, bus_stop.LON_) if bus_stop else (user_loc.lat, user_loc.lon) return distance(lat, lon, self.last_lat_, self.last_lon_)
def fingerprinting(): with open('LocTest_v2.csv', 'r') as testloc: csvreader = csv.reader(testloc, delimiter=',') next(csvreader) # csvreader = [[-8.07752, -34.899162, -67.3, -24.7, -73.4, -67.2, -79.2666666666667, -80.6], ] errors = [] prediction_locs = [] point_targets = [] for row in csvreader: point_target = (float(row[0]), float(row[1])) rssis = [float(rssi) for rssi in row[2:]] pathlosses = np.subtract(EIRP, rssis) # print('Pathloss Point: {}'.format(pathlosses)) with open('map.csv', 'r') as mapgrid_file: # mapreader = csv.reader(maploc, delimiter=',') # nearest_100 = get_n_nearest(mapreader, pathlosses[0], 100000) map_grid = np.loadtxt(mapgrid_file, delimiter=',') prediction_on_grid = get_most_similar(map_grid, pathlosses) prediction_locs.append(prediction_on_grid[:2]) point_targets.append(point_target) # print('Prediction on Grid: {}'.format(prediction_on_grid)) point_prediction = prediction_on_grid[:2] error = distance(point_prediction, point_target) errors.append(error) print("Media: {}".format((sum(errors)/len(errors)))) print('Melhor: {}'.format(min(errors))) return
def make_chain(self, body1, body2, pos1, pos2, link_length, radius): dist = int(distance(pos1, pos2) + 0.5) x1, y1 = pos1 x2, y2 = pos2 bearing = math.atan2((y2 - y1), (x2 - x1)) if dist < link_length: # Too short to make a chain self.game.world.add.joint(body1, body2, pos1, pos2) return # Draw circles along the path and join them together prev_circle = body1 prev_pos = tuple_to_int((x1, y1)) for current_point in range(int(link_length / 2.), dist, int(link_length)): x = x1 + (current_point) * math.cos(bearing) y = y1 + (current_point) * math.sin(bearing) circle = self.game.world.add.ball(tuple_to_int((x, y)), radius, dynamic=True, density=1.0, restitution=0.16, friction=0.1) circle.userData['color'] = (0, 0, 0) self.game.world.add.joint(prev_circle, circle, prev_pos, tuple_to_int((x, y)), False) if (current_point + link_length) >= dist: self.game.world.add.joint(circle, body2, tuple_to_int((x, y)), pos2, False) prev_circle = circle prev_pos = tuple_to_int((x, y))
def handleToolEvent(self, event): Tool.handleToolEvent(self, event) if event.type == MOUSEBUTTONDOWN and event.button == 1: self.vertices = [tuple_to_int(event.pos)] self.safe = False elif event.type == MOUSEBUTTONUP and event.button == 1: if not self.vertices: return if len(self.vertices) == 1 and self.previous_vertices is not None: last_x_y = self.previous_vertices[-1] delta_x = last_x_y[0] - tuple_to_int(event.pos)[0] delta_y = last_x_y[1] - tuple_to_int(event.pos)[1] self.vertices = [[i[0] - delta_x, i[1] - delta_y] for i in self.previous_vertices] self.safe = True if self.vertices and self.safe: self.constructor(self.vertices, density=self.palette_data['density'], restitution=self.palette_data['restitution'], friction=self.palette_data['friction']) self.previous_vertices = self.vertices[:] self.vertices = None elif event.type == MOUSEMOTION and self.vertices: self.vertices.append(tuple_to_int(event.pos)) if not self.vertices: return if distance(tuple_to_int(event.pos), self.vertices[0]) >= 55 and \ len(self.vertices) > 3: self.safe = True
def update(self, gamestate): if self.invulnerable: self.framecount += 1 self._player.color(self.invuln_color) if self.framecount == self.invuln_frames: self.invulnerable = False self.framecount = 0 else: self._player.color(self.outline_color) # if you hit the border, back up if check_border_collision(self._player.pos(), self.radius, gamestate): self._player.backward(25) # check for enemy collisions. for coord in gamestate['enemies']: if check_object_collision( self._player.pos(), coord, self.radius, gamestate['enemy_radius']): self.enemy_collision_handler() # check for food collisions. if check_object_collision( self._player.pos(), gamestate['food'], self.radius, gamestate['food_radius']): self.food_pickup_handler() # tell the _player where to go! # if you haven't reached the destination, set your direction # towards that point and move forwards. if distance(self._player.pos(), self.dest) > self.radius: self._player.setheading(self._player.towards(*self.dest)) self._player.forward(self.move_speed)
def associate(self, predicted, observations): associations = [] # For each observation, find the nearest landmark and associate it. # You might want to devise and implement a more efficient algorithm. for o in observations: min_dist = -1.0 for p in predicted: dist = distance(o, p) # print(p) if (min_dist < 0.0) or (dist < min_dist): min_dist = dist min_id = p['id'] min_x = p['x'] min_y = p['y'] association = { 'id': min_id, 'x': min_x, 'y': min_y, } associations.append(association) # Return a list of associated landmarks that corresponds to # the list of (coordinates transformed) predictions. return associations
def update_weights(self, sensor_range, std_landmark_x, std_landmark_y, observations, map_landmarks): # TODO: For each particle, do the following: # 1. Select the set of landmarks that are visible # (within the sensor range). for p in self.particles: visible_landmarks = [] for id, landmark in map_landmarks.items(): if distance(p, landmark) <= sensor_range: landmark['id'] = id visible_landmarks.append(landmark) # 2. Transform each observed landmark's coordinates from the # particle's coordinate system to the map's coordinates. transformed_observations = [] for obs in observations: obs['x'] = obs['x'] + p['x'] * np.cos(p['t']) - \ p['y'] * np.sin(p['t']) obs['y'] = obs['y'] + p['x'] * np.sin(p['t']) + \ p['y'] * np.cos(p['t']) transformed_observations.append(obs) # 3. Associate each transformed observation to one of the # predicted (selected in Step 1) landmark positions. # Use self.associate() for this purpose - it receives # the predicted landmarks and observations; and returns # the list of landmarks by implementing the nearest-neighbour # association algorithm. assoc_landmarks = self.associate(visible_landmarks, transformed_observations) p['accoc'] = [landmark['id'] for landmark in assoc_landmarks] # 4. Calculate probability of this set of observations based on # a multi-variate Gaussian distribution (two variables being # the x and y positions with means from associated positions # and variances from std_landmark_x and std_landmark_y). # The resulting probability is the product of probabilities # for all the observations. particle_loc = np.array([p['x'], p['y']]) landmark_x = np.array( [landmark['x'] for landmark in assoc_landmarks]) landmark_y = np.array( [landmark['y'] for landmark in assoc_landmarks]) print(landmark_x) print(landmark_y) mean_x = landmark_x.mean(axis=0) mean_y = landmark_y.mean(axis=0) mean = np.array([mean_x, mean_y]) corr = np.correlate(landmark_x, landmark_y)[0] cov = np.array( [[std_landmark_x**2, corr * std_landmark_x * std_landmark_y], [corr * std_landmark_x * std_landmark_y, std_landmark_y**2]]) particle_prob = multivariate_normal.pdf(particle_loc, mean=mean, cov=cov) # 5. Update the particle's weight by the calculated probability. p['w'] = particle_prob
def test_distance(): a = [2, 3] b = [5, 7] d = distance(a, b) expected = 5 assert (expected == d)
def test_distance_3d(): b = [2, -3, 9] a = [1, -5, 7] d = distance(a, b) expected = 3 assert (expected == d)
def test_distance_negatives(): a = [-2, -3] b = [-5, -7] d = distance(a, b) expected = 5 assert (expected == d)
def test_distance_flipped(): b = [2, 3] a = [5, 7] d = distance(a, b) expected = 5 assert (expected == d)
def distance(self, bus_stop: BusStop = None, user_loc: UserLoc = None): if not bus_stop and not user_loc: return QUICK_FIX_DIST (lat, lon) = (bus_stop.LAT_, bus_stop.LON_) if bus_stop else (user_loc.lat, user_loc.lon) if lat is None or lon is None: return QUICK_FIX_DIST return distance(lat, lon, self.lat, self.lon)
def update_weights(self, sensor_range, std_landmark_x, std_landmark_y, observations, map_landmarks): # TODO: For each particle, do the following: for p in self.particles: # 1. Select the set of landmarks that are visible # (within the sensor range). # 50미터 이내에 존재하는 landmark들만 뽑아냄 visible_landmarks = [] for i in map_landmarks.keys(): if distance(map_landmarks[i], p) < sensor_range: visible_landmarks.append({ 'id': i, 'x': map_landmarks[i]['x'], 'y': map_landmarks[i]['y'] }) transform_obs = [] # 2. Transform each observed landmark's coordinates from the # particle's coordinate system to the map's coordinates. for obs in observations: obs_xm = p['x'] + obs['x'] * np.cos( p['t']) - obs['y'] * np.sin(p['t']) obs_ym = p['y'] + obs['x'] * np.sin( p['t']) + obs['y'] * np.cos(p['t']) transform_obs.append({'x': obs_xm, 'y': obs_ym}) # 3. Associate each transformed observation to one of the # predicted (selected in Step 1) landmark positions. # Use self.associate() for this purpose - it receives # the predicted landmarks and observations; and returns # the list of landmarks by implementing the nearest-neighbour # association algorithm. associations = self.associate( visible_landmarks, transform_obs) # 현재 p에서 보이는 landmarks for assoc in associations: p['assoc'].append(assoc['id']) # 4. Calculate probability of this set of observations based on # a multi-variate Gaussian distribution (two variables being # the x and y positions with means from associated positions # and variances from std_landmark_x and std_landmark_y). # The resulting probability is the product of probabilities # for all the observations. # 5. Update the particle's weight by the calculated probability. # landmark mean # multivariate gaussian distribution pdf for i in range(len(transform_obs)): ex = (transform_obs[i]['x'] - associations[i]['x'])**2 / (std_landmark_x**2) ey = (transform_obs[i]['y'] - associations[i]['y'])**2 / (std_landmark_y**2) c = 2. * pi * std_landmark_x * std_landmark_y pdf = exp(-0.5 * (ex + ey)) / c pdf += 0.000000000000001 p['w'] *= pdf
def get_visible_vessels(self, shipstate): tmp = [] for vessel in vesselService.vessels: if vessel.id != self.id: if helpers.distance(vessel.shipstate.position, shipstate.position) < config.visibility: tmp.append(vessel) return tmp
def update(self, player, rocks): if helpers.distance(player.rect.topleft, self.rect.topleft) < 15 and self.reset_complete: self.image = self.fist self.__slam(player, rocks) self.cool_down = 60 else: self.image = self.hand self.__bob() if self.cool_down > 0: self.cool_down -=1
def bowFightA(self, player, rocks, enemyGroup): enemy = enemyGroup.sprites() target = enemy[0] for x in range(len(enemy)): if helpers.distance(self.rect.topleft, enemy[x].rect.topleft) < helpers.distance(self.rect.topleft, target.rect.topleft): target = enemy[x] lazor_sight = Lazor(self.rect.center, target.rect.center) self.lazor_group.add(lazor_sight) self.lazor_group.update() lazor_player = pygame.sprite.spritecollide(player, self.lazor_group, False) if lazor_player: #STRAFE if self.clock > 0: self.clock -= 1 if self.cool_down >0: self.cool_down -=1 self.__strafe() else: if self.clock > 0: self.clock -= 1 self.__strafe() if self.clock == 0: if self.cool_down == 0: attack = R_Attack(self.rect.center, target.rect.center, self.direction) self.attack_group.add(attack) self.cool_down = 80 else: self.cool_down -= 1 else: self.clock -= 1 hit_player = pygame.sprite.spritecollide(player, self.attack_group, False) if hit_player: player.getHit("none", 1) hit_player[0].kill() hit_enemy = pygame.sprite.spritecollide(target, self.attack_group, False) if hit_enemy: target.get_hit("none", 10) hit_enemy[0].kill() self.attack_group.update() self.attack_group.draw(self.windowSurface)
def update_weights(self, sensor_range, std_landmark_x, std_landmark_y, observations, map_landmarks): # TODO: For each particle, do the following: for p in self.particles: # 1. Select the set of landmarks that are visible # (within the sensor range). valid_id = [] valid_x = [] valid_y = [] for l in map_landmarks: dist = distance(p, map_landmarks[l]) if dist <= sensor_range: valid_id.append(l) valid_x.append(map_landmarks[l]['x']) valid_y.append(map_landmarks[l]['y']) prediction = [{'id': L, 'x': x, 'y': y} for (L, x, y) in \ zip (valid_id, valid_x, valid_y)] # 2. Transform each observed landmark's coordinates from the # particle's coordinate system to the map's coordinates. transformed_obs = [] for o in observations: temp = {} temp['x'] = (o['x'] * np.cos(p['t'])) - ( o['y'] * np.sin(p['t'])) + p['x'] temp['y'] = (o['x'] * np.sin(p['t'])) + ( o['y'] * np.cos(p['t'])) + p['y'] transformed_obs.append(temp) # 3. Associate each transformed observation to one of the # predicted (selected in Step 1) landmark positions. # Use self.associate() for this purpose - it receives # the predicted landmarks and observations; and returns # the list of landmarks by implementing the nearest-neighbour # association algorithm. assoc_total = self.associate(prediction, transformed_obs) p['assoc'] = [assoc['id'] for assoc in assoc_total] # 4. Calculate probability of this set of observations based on # a multi-variate Gaussian distribution (two variables being # the x and y positions with means from associated positions # and variances from std_landmark_x and std_landmark_y). # The resulting probability is the product of probabilities # for all the observations. z = 1 for a, o in zip(assoc_total, transformed_obs): z_a_x = norm_pdf(o['x'], a['x'], std_landmark_x) z_a_y = norm_pdf(o['y'], a['y'], std_landmark_y) z_a = z_a_x * z_a_y z *= z_a # 5. Update the particle's weight by the calculated probability. p['w'] = z
def draw(self): Tool.draw(self) # Draw a circle from pt1 to mouse if self.pt1 is not None: delta = distance(self.pt1, tuple_to_int(pygame.mouse.get_pos())) if delta > 0: self.radius = max(delta, 5) pygame.draw.circle(self.game.screen, (100, 180, 255), self.pt1, int(self.radius), 3) pygame.draw.line(self.game.screen, (100, 180, 255), self.pt1, tuple_to_int(pygame.mouse.get_pos()), 1)
def __chase(self, spot, rocks, target): my_x = self.rect.topleft[0] my_y = self.rect.topleft[1] x = spot[0] y = spot[1] if helpers.distance(spot, self.rect.topleft) > 10 and not self.defensive: if self.tick ==0: #Increase up to 30 if y < my_y +30 and y > my_y -30: y -= self.sway *2 if x < my_x +30 and x > my_x -30: x -= self.sway *2 self.sway +=1 if self.sway > 30: self.tick = 1 if self.tick == 1: #Decrease to -30 if y < my_y +30 and y > my_y -30: y -= abs(self.sway *2) if x < my_x +30 and x > my_x -30: x -= abs(self.sway *2) self.sway -=1 if self.sway < -30: self.tick = 0 spot = (x, y) canShift = True self.follow_direction = helpers.checkOrient(target, self) self.lazor_group.add(LazorStick(self.rect.center, spot)) self.lazor_group.add(LazorStick(self.rect.topleft, spot)) #These two are the lazors from mid and top self.lazor_group.update() self.lazor_group.draw(pygame.display.get_surface()) #shown only for tests lazor_rock = pygame.sprite.groupcollide(self.lazor_group, rocks, False, False) lazor_target = pygame.sprite.spritecollide(target, self.lazor_group, True) if lazor_rock and not lazor_target: for rock in pygame.sprite.groupcollide(self.lazor_group, rocks, True, False).keys(): if canShift == True: if self.follow_direction == "up" or self.follow_direction == "down": self.rect.topleft = (self.rect.topleft[0]+2, self.rect.topleft[1]) else: self.rect.topleft = (self.rect.topleft[0], self.rect.topleft[1]+2) canShift = False else: if x+10 >= self.rect.topleft[0] and not self.blocked_direction == "right": my_x += 2 if x-10 < self.rect.topleft[0] and not self.blocked_direction == "left": my_x -= 2 if y+10 >= self.rect.topleft[1] and not self.blocked_direction == "up": my_y += 2 if y-10 < self.rect.topleft[1] and not self.blocked_direction == "down": my_y -= 2 self.rect.topleft = (my_x, my_y)
def drive(self): start_time = time.time() if self.waypoints is not None: # rospy.loginfo("curyaw: {}".format(yaw)) # start = time.time() self.cur_wp = self.get_closest_waypoint(self.pose) # end = time.time() # self.sum_wp_time += (end - start) # self.count_wp_time += 1 # avg_wp_time = self.sum_wp_time / self.count_wp_time # rospy.loginfo("m_id time: {}".format(avg_wp_time)) lane = Lane() first_wp_obj = self.waypoints[self.cur_wp] rl_is_visible = self.redlight_is_visible() redlight_wp = self.redlight_wp rospy.loginfo("redlight_visible: {}, cur: {}, rl: {}({}m)".format( rl_is_visible, self.cur_wp, redlight_wp, None if redlight_wp is None else \ (distance(self.waypoints[redlight_wp].pose.pose.position, self.waypoints[self.cur_wp].pose.pose.position)) )) if rl_is_visible: # if False: # stopline waypoint sl_wp = self.dist2wp(redlight_wp, -self.tl_config["offset"]) wps = self.wps_behind_wp(sl_wp, self.tl_config["brake_start"]) self.full_brake(wps) rospy.loginfo("wps v: {}".format( list(map(lambda x: self.waypoints[x].twist.twist.linear.x, wps)))) if self.distance_to_wp(sl_wp) > self.tl_config["brake_start"]: self.set_waypoint_velocity(first_wp_obj, self.config["v"]) else: self.set_waypoint_velocity(first_wp_obj, self.config["v"]) rospy.loginfo("v was set to: {}".format( self.waypoints[self.cur_wp].twist.twist.linear.x)) for i, wp in enumerate(self.waypoints[ self.cur_wp:(self.cur_wp+LOOKAHEAD_WPS)]): lane.waypoints.append(wp) # rospy.loginfo("(p) next_wp angular: {}".format(lane.waypoints[0].twist.twist.angular)) self.final_waypoints_pub.publish(lane) elapsed_time = time.time() - start_time rospy.loginfo('drive() time = %0.1fus\n' % (1000.0*1000*elapsed_time))
def update_weights(self, sensor_range, std_landmark_x, std_landmark_y, observations, map_landmarks): # 각각의 particle에 대해서... for particle in self.particles: # 1. 해당 particle의 위치에서 sensor_range 이내에 있는 # landmarks들의 목록을 구한다. visible_landmarks = [] landmark_id = 0 for landmark_id in map_landmarks: dist = distance(map_landmarks[landmark_id], particle) if dist <= sensor_range: visible_landmarks.append({'x' : map_landmarks[landmark_id]['x'], 'y' : map_landmarks[landmark_id]['y'], 'id' : landmark_id}) # 2. 관측된 landmarks(observations)의 좌표를 map 기준 좌표계로 변환한다. observed_in_map = [] for observation in observations: x = (particle['x'] + observation['x']*np.cos(particle['t']) - observation['y']*np.sin(particle['t'])) y = (particle['x'] + observation['x']*np.sin(particle['t']) - observation['y']*np.cos(particle['t'])) observed_in_map.append({'x': x, 'y' : y}) # 3. (1)에서 계산한 센서 범위 내의 landmarks와 # (2)에서 map 좌표계로 변환한 관측된 landmarks 중 같은 것끼리 짝지음. # 아래 함수는 가장 가까운 landmarks list를 리턴한다. assoc = self.associate(visible_landmarks, observed_in_map) # 4. assoc에 포함된 각 landmark와 차량 사이의 거리만큼 떨어진 위치에서, # 우리가 얻은 observation이 관측된 확률을 1.0부터 시작하여 누적하여 곱한다. # 5. 하나의 particle에서 계산한 (4)의 최종 값이 해당 particle의 weight가 된다. particle['w'] = 1.0 particle['assoc'] = [] for i in range(len(assoc)): dist = distance(assoc[i], particle) observ_dist = np.sqrt(observations[i]['x']**2 + observations[i]['y']**2) s = np.sqrt(std_landmark_x**2 + std_landmark_y**2) particle['w'] *= self.norm_pdf(dist, observ_dist, s) + 0.001 particle['assoc'].append(assoc[i]['id'])
def calculate_distance(channel): logger.info("calculating distance") logger.info(channel.queue) global farthest_racer_current_cordinates, race_sent_message_log, lap_no logger.info(farthest_racer) logger.info(farthest_racer_current_cordinates) x1 = farthest_racer_current_cordinates[0][0] y1 = farthest_racer_current_cordinates[0][1] x2 = farthest_racer_current_cordinates[1][0] y2 = farthest_racer_current_cordinates[1][1] dis = distance(x1, y1, x2, y2) logger.info("check_distnace %d" % dis) # send new lap message if not already sent and dis is greater than allowed if (dis > max_distance): # dis = 0 farthest_racer_current_cordinates = [[0, 0], [0, 0]] logger.info("Sending message for lap no --> {}".format(lap_no)) race_msg = generate_msg() race_sent_message_log[lap_no] = race_msg logger.info(race_msg) if lap_no < total_number_of_laps: logger.info("distance complete, sent new lap info ") yield from channel.publish(json.dumps(race_msg), exchange_name="race-exchange", routing_key="race") else: logger.info("Race is completed") yield from channel.publish("exit", exchange_name="race-exchange", routing_key="race") while True: choice = input("Press L to see stats, anyother to quit") if choice == "Q" or choice == "q": logger.info(race_sent_message_log) else: logger.info(" *--* ") exit() yield from asyncio.sleep(slow_down_factor)
def draw(self): # draw a circle from pt1 to mouse if self.pt1 is not None: mouse_pos = pygame.mouse.get_pos() self.radius = helpers.distance(self.pt1, mouse_pos) if self.radius > 3: thick = 3 else: thick = 0 pygame.draw.circle(self.game.screen, (100, 180, 255), self.pt1, int(self.radius), thick) pygame.draw.line(self.game.screen, (100, 180, 255), self.pt1, mouse_pos, 1)
def update(self, player, rocks): old_position = self.rect.topleft x = player.rect.topleft[0] y = player.rect.topleft[1] if self.clock == 0: if self.cool_down == 0: target = player if player.hasFriend: freind = player.passComp() if helpers.distance(player.rect.topleft, self.rect.topleft) > helpers.distance(freind.rect.topleft, self.rect.topleft): target = freind attack = R_Attack(self.rect.center, target.rect.center, helpers.checkOrient(target, self)) self.attack_group.add(attack) self.cool_down = 80 else: self.cool_down -= 1 else: self.clock -= 1 self.attack_group.update() self.attack_group.draw(self.windowSurface) self.__face(player) hit_player = pygame.sprite.spritecollide(player, self.attack_group, False) if hit_player: player.getHit("none", 1) hit_player[0].kill() if player.hasFriend: friend = player.passComp() hit_friend = pygame.sprite.spritecollide(friend, self.attack_group, False) if hit_friend: friend.getHit("none", 1) hit_friend[0].kill() if friend.health <= 0: friend.getDead() player.hasFriend = False self.__check_collision(rocks, player, old_position)
def update(self, player, rocks, enemyGroup): if self.invul > 0: self.invul -= 1 if self.health <= 0: self.kill() self.alive = False player.hasFreind = False self.dialogHandle.companionDeath(self.windowSurface, self) old_position = self.rect.topleft if len(enemyGroup) > 0: if self.recall_timer == 0: if self.weapon == 1: if self.defensive == True: self.bowFightD(player, rocks, enemyGroup) else: self.bowFightA(player, rocks, enemyGroup) else: if self.defensive == True: self.swordFightD(player, rocks, enemyGroup) else: self.swordFightA(player, rocks, enemyGroup) else: self.__chase(player.rect.topleft, rocks, player) self.recall_timer -= 1 else: # print helpers.distance(self.rect.topleft, player.rect.topleft) if helpers.distance(self.rect.topleft, player.rect.topleft) > 6 : self.__chase(player.rect.topleft, rocks, player) if self.walking_timer <=0: self.__walk(player) self.walking_timer = 5 else: self.walking_timer -= 1 if not self.__check_collision(rocks, player, old_position): self.blocked_direction = "nope" self.collide = True self.rect.topleft = helpers.checkBoundry(self.rect.topleft) if old_position == self.rect.topleft and self.weapon ==0 and not self.defensive: self.stayed_still +=1 if self.stayed_still > 25: self.stayed_still = 0 self.__chase(player.rect.topleft, rocks, player) self.recall_timer = 60
def button_release(self, evt): if not evt.inaxes is self.fig.ax_main: return if evt.button == 1: if self.fig.ax_main is self.fig.ax_3d: # Rotation or zoom self.update_fig() if self.anim_running.get(): return release_loc = evt.x, evt.y d = helpers.distance(self.press_loc, release_loc) if d > 5: return x, y, z = evt.xdata, evt.ydata, 0.0 if self.fig.ax_main is self.fig.ax_3d: s = evt.inaxes.format_coord(evt.xdata, evt.ydata) x, y, z = [float(c.split('=')[-1]) for c in s.split(',')] pos = x, y, z #logging.debug("Position: %s" % str(pos)) #logging.debug("Limits: %s" % str(self.fig.get_limits())) #if not helpers.is_inside(pos, self.fig.get_limits()): # logging.warning("Position outside limits.") # return self.add_location(pos)
def _plane_preset_old(self, direction = None): elevs = [0.0, 0.0, 90.0] azims = [0.0, 90.0, 0.0] limits = self.ax.get_xlim(), self.ax.get_ylim(), self.ax.get_zlim() if direction is None: #From screen elev = np.radians(self.ax.elev) azim = np.radians(self.ax.azim) else: elev = np.radians(elevs[direction]) azim = np.radians(azims[direction]) center = [sum(limits[i])/2.0 for i in range(3)] c1 = [l[0] for l in limits] c2 = [l[1] for l in limits] r = 0.5 * helpers.distance(c1, c2) dz = r * np.sin(elev) dy = r * np.sin(azim)*np.cos(elev) dx = r * np.cos(azim)*np.cos(elev) p0 = [center[0]-dx, center[1]-dy, center[2]-dz] p1 = [center[0]+dx, center[1]+dy, center[2]+dz] self.p0_str.set(point_to_str(p0)) self.p1_str.set(point_to_str(p1)) self.factor.set(0.5) self._update()
def __leash(self, old_position, player, rocks): if helpers.distance(player.rect.topleft, self.rect.topleft) > 10: self.rect.topleft = old_position self.__chase(player.rect.topleft, rocks, player)
# would be dynamically loaded in an app current_address = "5000 Forbes" current_position = [40.4433, -79.9436] destination = "PNC Park" destination_position = [40.4469, -80.0058] customer = 9 # 1. Find the closest car helpers.cur.execute( """ SELECT * from Cars; """ ) distance = helpers.distance(current_position, destination_position) base_fee = 5 fare = distance * 2 + base_fee # assuming 30mph in cities rows = helpers.cur.fetchall() class car: pass closest = car() min_distance = ( math.pi * 3959 ) # start with half the circumference of the earth, because no uber trip is further that that min_car = -1