def jarvis(points, cutoff=False): if cutoff: points = interior_elimination(points) #removing duplicate points pts = list(set(points)) P0 = min(pts, key=lambda p: (p[1], p[0])) H = [P0] # Since 'for loops' works as generators, 'H' is gonna be # populated within the loop and 'h' will always be # the most recent added. In the last iteration, 'H' won't # be updated (case when P0 is reached again) # and the 'for loop' ends. for h in H: a = h for b in pts: if ccw(h, a, b) < 0 or (ccw(h, a, b) == 0 and \ distance(h, b) > distance(h, a)): a = b if a is not P0: H.append(a) assert is_convex(H) return H
def start_vk(): for event in longpoll.listen(): if event.type == VkEventType.MESSAGE_NEW and event.to_me: user_res=vk_session.method("users.get",{'user_ids':[event.user_id],'fields':['id','first_name','last_name']}) insert_user(user_res[0]['id'],user_res[0]['first_name'],user_res[0]['last_name'],'vk') result = vk_session.method("messages.getById", {"message_ids": [event.message_id],"group_id": 192738048}) if result['items'][0]['geo']: geo = result['items'][0]['geo']['coordinates'] latitude, longitude = geo['latitude'], geo['longitude'] print(latitude, longitude) my_location={'latitude':latitude,'longitude':longitude} places = select_places() dist={p['id']:distance(my_location['longitude'],my_location['latitude'],p['loc_lon'],p['loc_lat']) for p in places} min_dist=min(dist.keys(), key=(lambda k: dist[k])) db_place = select_place_param(min_dist) image_url = 'https://ecoukhta.herokuapp.com/images/?img='+str(db_place['id']) image = session.get(image_url, stream=True) photo = upload.photo_messages(photos=image.raw)[0] attachments='photo{}_{}'.format(photo['owner_id'], photo['id']) vk.messages.send( user_id=event.user_id, attachment=attachments, random_id=get_random_id(), lat=db_place['loc_lat'], long=db_place['loc_lon'], message=db_place['info'] ) insert_log(select_userid_by_name(str(user_res[0]['id'])),db_place['id']) return 'ok' else: return 'ok'
def checkifpayload(self): if (distance(self.__pos[0], self.__pos[1], self.__droplocation[0], self.__droplocation[1])) <= 9: print("payload dropped") self.__payload = -1 self.__droplocation = [0, 0, 0]
def inter_uav_collsion(self, vel, GlobalUavData): """ """ for friend in GlobalUavData: if self.id != friend: friend_location = GlobalUavData[friend]['GPS'] current_location = self.get_pos() if len(friend_location): dist = distance(friend_location[0], friend_location[1], current_location[0], current_location[1]) if dist < 30: print(dist, self.id, friend) if dist < 7: print("inter uav collision aviodance triggered") vel[0] += 10000 * (-friend_location[0] + current_location[0]) vel[1] += 10000 * (-friend_location[1] + current_location[1]) vel[2] = 0 if dist < 4: print("collision") return vel
def get_reward(self, reset_reason, i): pre_potential = helper.dipole_potential(self.pre_ball[X], self.pre_ball[Y], 2.1, 7) cur_potential = helper.dipole_potential(self.cur_ball[X], self.cur_ball[Y], 2.1, 7) reward = cur_potential - pre_potential # Reset if (reset_reason != NONE): reward = 0 reward -= 0.1 * helper.distance( self.cur_ball[X], self.cur_my_posture[i][X], self.cur_ball[Y], self.cur_my_posture[i][Y]) for k in range(self.number_of_robots): if self.cur_my_posture[k][TOUCH]: reward += 30 if (reset_reason == SCORE_MYTEAM): self.score_sum += 1 reward += 200 # minimum 25 self.printConsole("my team goal") if (reset_reason == SCORE_OPPONENT): self.score_sum -= 1 reward -= 200 # maxmimum -25 self.printConsole("op team goal") # self.printConsole("reward: " + str(reward)) return reward
def _arcade_grow_explosions(self): """ Grow explosions. """ explosion_remove_list = [] asteroid_remove_list = [] new_explosions = [] for explosion in self._explosions: if explosion.update(): self._evman.Post(ExplosionGrowEvent(explosion)) # check for collisions with asteroids for asteroid in self._asteroids: if asteroid.y > ASTEROID_SAFE_ZONE: dist = helper.distance(* asteroid.position + explosion.position) if (dist < explosion.radius * 4): self.asteroids_destroyed += 1 asteroid_remove_list.append(asteroid) new_explosions.append(asteroid) else: explosion_remove_list.append(explosion) self._arcade_remove_asteroids(asteroid_remove_list) for explosion in explosion_remove_list: self._explosions.remove(explosion) self._evman.Post(ExplosionDestroyEvent(explosion)) for asteroid in new_explosions: self._arcade_spawn_explosion(asteroid.position)
def find_closest_robot_2(self): for i in range(self.number_of_robots): self.distances[i] = helper.distance(self.cur_ball[X], self.cur_my_posture[i][X], self.cur_ball[Y], self.cur_my_posture[i][Y]) self.idxs = sorted(range(len(self.distances)), key=lambda k: self.distances[k])
def midfielder(self, robot_id, idx, offset_y): ox = 0.1 oy = 0.075 ball_dist = helper.distance(self.cur_my_posture[robot_id][X], self.cur_ball[X], self.cur_my_posture[robot_id][Y], self.cur_ball[Y]) goal_dist = helper.distance(self.cur_my_posture[robot_id][X], self.field[X] / 2, self.cur_my_posture[robot_id][Y], 0) if (robot_id == idx): if (ball_dist < 0.04): # if near the ball and near the opposite team goal if (goal_dist < 1.0): self.position(robot_id, self.field[X] / 2, 0) else: # if near and in front of the ball if (self.cur_ball[X] < self.cur_my_posture[robot_id][X] - 0.044): x_suggest = self.cur_ball[X] - 0.044 self.position(robot_id, x_suggest, self.cur_ball[Y]) # if near and behind the ball else: self.position(robot_id, self.field[X] + self.goal[X], -self.goal[Y] / 2) else: if (self.cur_ball[X] < self.cur_my_posture[robot_id][X]): if (self.cur_ball[Y] > 0): self.position( robot_id, self.cur_ball[X] - ox, min(self.cur_ball[Y] - oy, 0.45 * self.field[Y])) else: self.position( robot_id, self.cur_ball[X] - ox, min(self.cur_ball[Y] + oy, -0.45 * self.field[Y])) else: self.position(robot_id, self.cur_ball[X], self.cur_ball[Y]) else: self.position(robot_id, self.cur_ball[X] - 0.1, self.cur_ball[Y] + offset_y)
def attracting_neighbours(self, agent: agent.Agent) -> List[agent.Agent]: attractors = [] if len(agents := agent.model.agents) > 1: for a in [other for other in agents if agent is not other]: distance = self.strength + agent.radius + a.radius if helper.distance(agent, a) <= distance: if any([isinstance(b, type(self)) for b in a.behaviours]): attractors.append(a)
def next_point(self, vector, point): new_point = (round2(vector[0] + point[0]), round2(vector[1] + point[1])) nearest = self._nearest_to(new_point) if helper.distance(new_point, self.nodes[nearest]['pos']) < 0.1: return nearest else: self.add_nonterminal(new_point) return new_point
def pick_up(self, time, ride): """increases time to show the distance travelled""" distance_to_ride = helper.distance(self.currentLocation, ride.start) self.willNextBeFree = time + distance_to_ride + ride.distance() self.currentLocation = ride.finish self.rides.append(ride.id)
def get_idxs(self): # sort according to distant to the ball # my team for i in range(self.number_of_robots): self.dist_ball[MY_TEAM][i] = helper.distance( self.cur_ball[X], self.cur_my[i][X], self.cur_ball[Y], self.cur_my[i][Y]) # opponent team for i in range(self.number_of_robots): self.dist_ball[OP_TEAM][i] = helper.distance( self.cur_ball[X], self.cur_op[i][X], self.cur_ball[Y], self.cur_op[i][Y]) # my team distance index idxs = sorted(range(len(self.dist_ball[MY_TEAM])), key=lambda k: self.dist_ball[MY_TEAM][k]) return idxs
def midfielder(self, robot_id, idx, offset_y): ox = 0.1 oy = 0.075 ball_dist = helper.distance(self.cur_my_posture[robot_id][X], self.cur_ball[X], self.cur_my_posture[robot_id][Y], self.cur_ball[Y]) goal_dist = helper.distance(self.cur_my_posture[robot_id][X], self.field[X] / 2, self.cur_my_posture[robot_id][Y], 0) if (ball_dist < 0.04): # if near the ball and near the opposite team goal if (goal_dist < 1.0): self.position(robot_id, self.field[X] / 2, 0) self.printConsole("shoot") else: # if near and in front of the ball if (self.cur_ball[X] < self.cur_my_posture[robot_id][X] - 0.044): x_suggest = self.cur_ball[X] - 0.044 self.position(robot_id, x_suggest, self.cur_ball[Y]) self.printConsole(" near front") # if near and behind the ball else: self.position(robot_id, self.field[X] + self.goal[X], -self.goal[Y] / 2) self.printConsole(" near behind") else: if (self.cur_ball[X] < self.cur_my_posture[robot_id][X]): if (self.cur_ball[Y] > 0): self.position(robot_id, self.cur_ball[X] - ox, min(self.cur_ball[Y] - oy, 1.2)) #self.printConsole(" far front +") else: self.position(robot_id, self.cur_ball[X] - ox, max(self.cur_ball[Y] + oy, -1.2)) #self.printConsole(" far front -") else: if (self.cur_ball[Y] > 0): self.position(robot_id, self.cur_ball[X], min(self.cur_ball[Y], 2)) #self.printConsole(" far behind +") else: self.position(robot_id, self.cur_ball[X], max(self.cur_ball[Y], -2))
def sort_by_distance_to_ball(self, received_frame, team): # sort according to distant to the ball for i in range(self.number_of_robots): self.distances[team][i] = helper.distance( self.cur_ball[X], received_frame.coordinates[team][i][X], self.cur_ball[Y], received_frame.coordinates[team][i][Y]) self.idxs[MY_TEAM] = sorted(range(len(self.distances[team])), key=lambda k: self.distances[team][k])
def go_fast(self, robot_id): distance2ball = helper.distance(self.cur_ball[X], self.cur_posture[robot_id][X], self.cur_ball[Y], self.cur_posture[robot_id][Y]) d_bg = helper.distance(self.cur_ball[X], 3.9, self.cur_ball[Y], 0) d_rg = helper.distance(3.9, self.cur_posture[robot_id][X], 0, self.cur_posture[robot_id][Y]) if (distance2ball < 0.25 and d_rg > d_bg): if (self.cur_ball[X] > 3.7 and abs(self.cur_ball[Y]) > 0.5 and abs(self.cur_posture[robot_id][TH]) < 30 * math.pi / 180): return False else: return True else: return False
def find_closest_robot(self): min_idx = 0 min_distance = 9999.99 for i in range(self.number_of_robots-1): measured_distance = helper.distance(self.cur_ball[X], self.cur_my_posture[i][X], self.cur_ball[Y], self.cur_my_posture[i][Y]) if (measured_distance < min_distance): min_distance = measured_distance min_idx = i self.idx = min_idx
def change_velocities_2(p1, p2) -> None: dist = helper.distance(p1, p2) distance_vec = np.array(p1.pos) - np.array(p2.pos) norm = distance_vec / (dist) k = np.array(p1.v) - np.array(p2.v) p = 2 * (norm * k) / (p1.radius + p2.radius) p1.v = np.array(p1.v) + p * p2.radius * norm * 0.1 p2.v = np.array(p2.v) - p * p1.radius * norm * 0.1
def count_deadlock(self): # delta of ball delta_b = helper.distance(self.cur_ball[X], self.prev_ball[X], \ self.cur_ball[Y], self.prev_ball[Y]) if (abs(self.cur_ball[Y]) > 0.65) and (delta_b < 0.02): self.dlck_cnt += 1 else: self.dlck_cnt = 0 self.avoid_dlck_cnt = 0
def select_enemy(self): battle_field_image = get_battle_field_image() enemy_locs = self.list_enemy(battle_field_image) enemy_dict = {} for loc in enemy_locs: dis = distance(settings.CROSSHAIR, loc) enemy_dict[dis] = loc return enemy_dict
def payload_drop(self, GlobalUavData, loc, fol): """ """ print("dropping payload...") print("...") friend_distances = { i: sys.maxsize for i in range(1, 1 + len(GlobalUavData)) } temp = [] for friend in GlobalUavData: friend_location = GlobalUavData[friend]["GPS"] if len(friend_location) > 0: dist = distance(loc[0], loc[1], friend_location[0], friend_location[1]) if self.__payload == 1: # set flag if dist <= 2.5 * fol: friend_distances[friend] = dist if self.__payload == 0: if dist <= 2.5 * fol and distance( self.__droplocation[0], self.__droplocation[1], self.get_pos()[0], self.get_pos()[1]) > distance( loc[0], loc[1], self.get_pos()[0], self.get_pos()[1]): friend_distances[friend] = dist min_dist = min(friend_distances.values()) if min_dist != sys.maxsize: y = list(friend_distances.items()) critical_key = min(y, key=lambda y: y[1])[0] if critical_key == self.id: # drop payload using the current uav if self.__payload == 1: self.__droplocation = [loc[0], loc[1], 5] self.__payload = 0 else: newloc = self.__droplocation self.__droplocation = [loc[0], loc[1], 5] self.payload_drop(GlobalUavData, newloc, fol) else: self.__futurepayload.append(loc)
def count_deadlock(self): d_ball = helper.distance(self.cur_ball[X], self.prev_ball[X], self.cur_ball[Y], self.prev_ball[Y]) # delta of ball #self.printConsole("boal delta: " + str(d_ball)) if (abs(self.cur_ball[Y]) > 0.65) and (d_ball < 0.02): #self.printConsole("boal stop") self.deadlock_cnt += 1 else: self.deadlock_cnt = 0
def get_idxs(self): # sort according to distant to the ball for i in range(self.number_of_robots): self.dist_ball[i] = helper.distance(self.cur_ball[X], self.cur_my[i][X], self.cur_ball[Y], self.cur_my[i][Y]) idxs = sorted(range(len(self.dist_ball)), key=lambda k: self.dist_ball[k]) return idxs
def solve(self, grid, start, goal): visited = set() prev = dict() dist = defaultdict(lambda: float('inf')) pq = [] prev[start] = None dist[start] = 0 # Need to put (cost, pos) into priority queue so that pq is ordered by cost h.heappush(pq, (0, start)) while len(pq) != 0: current_cost, current_pos = h.heappop(pq) self._animate_visited.append(current_pos) # Check we havent visited this point before if current_pos not in visited: visited.add(current_pos) else: continue # If we have reached the end get the path if current_pos == goal: return self.get_path(prev, goal) # print(pq) for nbr in hlp.nhood8(grid, *current_pos): new_cost = dist[current_pos] + hlp.distance(current_pos, nbr) heuristic = hlp.distance(nbr, goal) # If we havent visited if nbr not in visited: if new_cost < dist[nbr]: dist[nbr] = new_cost prev[nbr] = current_pos h.heappush(pq, (dist[nbr] + heuristic, nbr))
def loc_message(message): user=str(message.from_user.id) insert_user(user,message.from_user.first_name, message.from_user.last_name,'telegram') my_location={'latitude':message.location.latitude,'longitude':message.location.longitude} places = select_places() #red_get(str(message.from_user.id)+'_type')) dist={p['id']:distance(my_location['longitude'],my_location['latitude'],p['loc_lon'],p['loc_lat']) for p in places} min_dist=min(dist.keys(), key=(lambda k: dist[k])) db_place = select_place_param(min_dist) bot.send_location(message.chat.id, db_place['loc_lat'], db_place['loc_lon']) bot.send_photo(message.chat.id, db_place['photo'],caption=db_place['info']) insert_log(select_userid_by_name(str(message.from_user.id)),db_place['id'])
def get_reward(self, reset_reason, i): pre_potential = helper.dipole_potential(self.pre_ball[X], self.pre_ball[Y], 2.1, 30) cur_potential = helper.dipole_potential(self.cur_ball[X], self.cur_ball[Y], 2.1, 30) potential_rew = cur_potential - pre_potential # Reset if (reset_reason != NONE): potential_rew = 0 self.printConsole(' potential reward ' + str(i) + ': ' + str(potential_rew)) dist_rew = -0.1 * helper.distance( self.cur_ball[X], self.cur_my_posture[i][X], self.cur_ball[Y], self.cur_my_posture[i][Y]) self.printConsole(' distance reward ' + str(i) + ': ' + str(dist_rew)) touch_rew = 0 touch_case = 0 if (abs(self.cur_ball[X]) < 1.85) and (abs(self.cur_ball[Y]) < 1.3): if self.cur_my_posture[i][TOUCH]: touch_rew += 20 touch_case = 1 elif (self.cur_ball[X] > 0) and (abs(self.cur_ball[Y]) < 0.3): if self.cur_my_posture[i][TOUCH]: touch_rew += 20 touch_case = 2 elif (self.cur_ball[X] < 0) and (abs(self.cur_ball[Y]) < 0.3): pass else: if self.cur_my_posture[i][TOUCH]: touch_rew -= 0.01 touch_case = 3 self.printConsole(' touch reward ' + str(i) + ': ' + str(touch_rew) + ' (case: ' + str(touch_case) + ')') goal_rew = 0 if (reset_reason == SCORE_MYTEAM): self.score_sum += 1 goal_rew += 500 # minimum 25 self.printConsole("my team goal") if (reset_reason == SCORE_OPPONENT): self.score_sum -= 1 goal_rew -= 500 # maxmimum -25 self.printConsole("op team goal") rew = potential_rew + dist_rew + touch_rew + goal_rew self.printConsole(' reward ' + str(i) + ': ' + str(rew)) return rew
def attraction_constraints(self, agent: agent.Agent) -> None: bound_others = [ x for x in agent.model.agents if x is not agent and helper.distance(agent, x) <= (x.radius + agent.radius + self.strength) and any([isinstance(b, type(self)) for b in x.behaviours]) ] # Kinda works, for now while len(bound_others) > 2: repelled_agent = bound_others.pop() move_vec = -repelled_agent.v repelled_agent.pos += move_vec # If distance is less than diameter of agent and radius of x, y then we want them to move away from each other # Works but attraction ruins things try: x, y = bound_others if helper.distance( x, y) < (agent.radius * 2 + x.radius + y.radius - 5): third_point = agent.pos + np.array([0, agent.radius]) x_angle = helper.angle_on_cirumfrance(np.array(agent.pos), np.array(x.pos), np.array(third_point)) y_angle = helper.angle_on_cirumfrance(np.array(agent.pos), np.array(y.pos), np.array(third_point)) # Now they all circulate, but need to make them repel each other such that only two can be bound x_move_vec = x.pos + np.array([ np.sin(x_angle + (np.pi / 2)), np.cos(x_angle + (np.pi / 2)) ]) y_move_vec = y.pos + -np.array([ np.sin(x_angle + (np.pi / 2)), np.cos(x_angle + (np.pi / 2)) ]) x.pos = x_move_vec y.pos = y_move_vec except: return
def link(self, agent: agent.Agent) -> None: if not self.right and (linking_neighs := [ x for x in agent.model.agents if helper.distance_pos( x.pos, right_link := self.right_link(agent)) < x.radius ]): print('Am here') linking_neigh = linking_neighs.pop() distance_vector = np.array(agent.pos) - np.array(right_link) move_vector = 0.1 * distance_vector agent.pos = agent.pos - move_vector if (dist := helper.distance( agent, linking_neigh)) <= (agent.radius + linking_neigh.radius): overlap = 0.5 * (dist - agent.radius - linking_neigh.radius) agent.pos[0] -= overlap * (agent.pos[0] - linking_neigh.pos[0]) / dist agent.pos[1] -= overlap * (agent.pos[1] - linking_neigh.pos[1]) / dist linking_neigh.pos[0] += overlap * (agent.pos[0] - linking_neigh.pos[0]) / dist linking_neigh.pos[1] += overlap * (agent.pos[1] - linking_neigh.pos[1]) / dist
def density_sorter(pos_list, patients): density_block = [0] * len(pos_list) gap = distance(pos_list[0], pos_list[1]) xnum = pos_list.xnum xmin, ymin = pos_list.xmin, pos_list.ymin for pat in patients: pat_x, pat_y = pat.x - xmin, pat.y - ymin pat_block = int(pat_x / gap) + int(pat_y / gap) * xnum density_block[pat_block] += 1 for i in range(len(density_block)): pos_list[i].density = density_block[i] pos_list.sort(key = lambda x: x.density, reverse=True) return pos_list
def get_reward(self, reset_reason, i): dist_rew = -0.1 * helper.distance(self.cur_ball[X], self.cur_my[i][X], self.cur_ball[Y], self.cur_my[i][Y]) # self.printConsole(' distance reward ' + str(i) + ': ' + str(dist_rew)) touch_rew = 0 if self.cur_my[i][TOUCH]: touch_rew += 10 rew = dist_rew + touch_rew # self.printConsole(' reward ' + str(i) + ': ' + str(rew)) return rew
def circulate(self, agent: agent.Agent) -> None: bound_others = [ x for x in agent.model.agents if x is not agent and helper.distance(agent, x) <= (x.radius + agent.radius + self.strength) ] for x in bound_others: third_point = agent.pos + np.array([0, agent.radius]) x_angle = helper.angle_on_cirumfrance(np.array(agent.pos), np.array(x.pos), np.array(third_point)) x_move_vec = x.pos + np.array( [np.sin(x_angle + (np.pi / 2)), np.cos(x_angle + (np.pi / 2))]) x.pos = x_move_vec
def minimumdistance(self, GlobalUavData): """ """ friend_distances = [] current_position = self.get_pos() for friends in GlobalUavData: friend_location = GlobalUavData[friends]["GPS"] friend_distances.append((distance(current_position[0],current_position[1],friend_location[0],friend_location[1]), friends)) friend_distances.sort() for element in friend_distances[:5]: pso_friends.append(element[1]) return pso_friends # list of uav ids
def step(self, agent: agent.Agent) -> None: """ Move agent that this instance belong to by a random vector, scaled by step size """ move_vector = np.array(random.sample([-0.5, 0, 0.5], 2)) # Idea to scale velocity by agent 'weight' (radius) scaled_vel = move_vector * (1 / agent.radius) agent.v = scaled_vel + agent.v agent.pos = agent.v + agent.pos if shared_pos := [ x for x in agent.model.agents if x is not agent and helper.distance(agent, x) < agent.radius ]: self.collide(agent, shared_pos) agent.pos = agent.v + agent.pos
def closest_ready_turret(self, arcade_position): """ Returns the closest, charged turret to a position. Position is in ARCADE measurements (ARCADE _WIDTH / _HEIGHT). """ # do not allow targeting positions below the boundary. if (arcade_position[1] >= ARCADE_HEIGHT - ((BASE_HEIGHT + 4) * BLOCK_PADDING)): return chosen_one = None chosen_dist = ARCADE_HEIGHT for key, base in self._moonbase.items(): if isinstance(base, Turret): if base.ready: distance = helper.distance(* arcade_position + base.position) if distance < chosen_dist: chosen_dist = distance chosen_one = base return chosen_one