def get_radius(self): # faster BBs can move with greater radius # return self._spd * 1.0 / MAX_ATTRIBUTE * MAX_RADIUS - self._image_surf_rect.width # TODO: need to fix this! return calc_distance(self._image_surf_rect.centerx, self._image_surf_rect.centery, int(WIDTH / 2.0), int(HEIGHT / 2.0))
def check_obstacles(self, vehicles): minimumDistance = 1000 for vehicle in vehicles: if self.vehicle_type == "Pedrestian": # and vehicle.vehicle_type == "Pedrestian": continue elif vehicle.RightOfPassage == 0 and self.RightOfPassage == 1 and self.vehicle_type != "Pedrestian": # The vehicle doesn't have right of passage (not in roundabout) continue elif self.position == vehicle.position: # It's our vehicle continue else: distance = utils.calc_distance(self.position, vehicle.position) angle = abs(utils.calc_angle(self.position, vehicle.position) - self.direction) current_vision = self.vision_angle if ( self.RightOfPassage == 0 and self.velocity < 0.75 * self.max_velocity and vehicle.RightOfPassage == 1 ): current_vision = self.vision_angle_entrance if distance <= self.range_of_sight and angle < current_vision: stopDistance = ( utils.calc_stopDistance(distance, angle) - self.length * 2 - vehicle.length ) # 3 times radius if stopDistance < minimumDistance: minimumDistance = stopDistance return minimumDistance
def recommendation(): json_data = request.get_json(silent=True) df_hotels_return = df_hotels df_tour_return = df_tours if "city_id" in json_data: df_hotels_return = df_hotels_return[df_hotels_return["city_id"] == int(json_data["city_id"])] df_tour_return = df_tour_return[df_tour_return["city_id"] == int(json_data["city_id"])] if "type_price_hotel" in json_data and json_data["type_price_hotel"] != "-1": df_hotels_return = filter_by_price_hotel( df_hotels_return, type_price=json_data["type_price_hotel"]) if "type_price_tour" in json_data and json_data["type_price_tour"] != "-1": df_tour_return = filter_by_price_tour( df_tour_return, type_price=json_data["type_price_tour"]) center_location = LIST_CENTER_CITY[json_data["city_id"]] if len(df_hotels_return) > 0: df_hotels_return["distance_calc"] = df_hotels_return["distance"].apply( lambda x: calc_distance(x, center_location)) prob_hotels, hotel_idxes = ranking_topsis( df_hotels_return, type_topsis="hotel") df_hotels_return = df_hotels_return.iloc[hotel_idxes] if len(df_tour_return) > 0: prob_tours, tour_idxes = ranking_topsis( df_tour_return, type_topsis="tour") df_tour_return = df_tour_return.iloc[tour_idxes] return jsonify({"hotels": eval(df_hotels_return.to_json(orient="records")), "tours": eval(df_tour_return.to_json(orient="records"))})
def getNearestMainNode(pos, node_list): min_dist = 1000 for node in node_list: dist = utils.calc_distance(pos, node) if dist < min_dist: min_dist = dist end_pos = node return (pos,end_pos)
def getNearestNodeInList(pos, any_list): min_dist = 1000 for node in any_list: dist = utils.calc_distance(pos, node) if dist < min_dist: min_dist = dist index = any_list.index(node) return any_list[index]
def getNearestNodeIndex(pos, node_list): min_dist = 1000 for node in node_list: dist = utils.calc_distance(pos, node) if dist < min_dist: min_dist = dist index = node_list.index(node) return index
def getObservation(self): sensors = Pa10Task.getObservation(self) # Calculate the straightline distance from the arm to the target [m] self.distance_to_target = utils.calc_distance(self.tooltip_position, self.target_position) return sensors
def GetDistanceToBusStop(self,position,direction): deltaX=self.roads[2][0]-self.roads[1][0] deltaY=self.roads[2][1]-self.roads[1][1] busStopX=self.roads[1][0]+deltaX*0.5 busStopY=self.roads[1][1]+deltaY*0.5 dist=utils.calc_distance((busStopX,busStopY),position) if (abs(utils.calc_angle(position, (busStopX,busStopY)) - direction)>math.pi/2): dist=-dist return dist
def calc_reward(self): """ Calculate the agent score, which is a linear combination of the distance between the agent and the target and the time elapsed since the beginning of the simulation :return: the reward """ r1 = -utils.calc_distance(self.agent_xyz, self.tgt_xyz) r2 = -self.time * self.time_reward_factor return r1 + r2
def test_works_as_expected(self): '''utils.calc_distance correctly calculates the distance between two points''' pairs = [[[0, 0], [1, 1]], [[0, 0], [0, 1]], [[5, 2], [2, 5]], [[-1, 3], [10, 0]]] for pair in pairs: distance = utils.calc_distance(*pair) expected_distance = math.sqrt((pair[1][0] - pair[0][0])**2 + (pair[1][1] - pair[0][1])**2) self.assertEqual(distance, expected_distance)
def getObservation(self): sensors = Pa10Task.getObservation(self) # Calculate the straightline distance from the arm to the target [m] self.distance_to_target = utils.calc_distance( self.tooltip_position, self.target_position ) return sensors
def recalculate_info(currentLat, currentLong, altitude): """ Recalculate target heading """ heading = utils.calc_heading(currentLat, currentLong, this.targetLat.get(), this.targetLong.get()) overlay.show_heading(heading) if this.planetRadius.get() > 0: distance = utils.calc_distance(currentLat, currentLong, this.targetLat.get(), this.targetLong.get(), this.planetRadius.get(), altitude) overlay.show_distance(distance)
def knn(all_stations, sugg_station, nearest_stations=[], nearest_stations_distances=None, nearest_stations_names=None, index=0): nearest_station = '' minimum_distance = float('inf') for station in all_stations: diff = calc_distance(station[1], sugg_station[1]) if diff < minimum_distance: minimum_distance = diff nearest_station = station[0] nearest_stations.append((nearest_station, minimum_distance)) if nearest_stations_distances: nearest_stations_distances[index] = minimum_distance if nearest_stations_names: nearest_stations_names[index] = nearest_station return (nearest_station, minimum_distance)
def test_can_see_an_object_if_angle_does_not_pass_through_center_but_passes_through_some_of_object( self): '''if the angle of the eye and the angle between the snake's head and the object are not equal but close enough (depending on obj size & distance) then the eye can see the object''' ''' example: ( ) - object; x - snake; ( ) | | x ''' expected_seen_object = MockObject([0.5, 5], 1, visual_encoding=[1, 1]) other_objects = [expected_seen_object] output = self.snake.look(other_objects) snake_head = self.snake.body[0] expected_output = expected_seen_object.visual_encoding + [ utils.calc_distance(snake_head.position, expected_seen_object.position) ] self.assertListEqual(output, expected_output)
def __init__(self, agent_xyz_init, agent_acc, tgt_xyz_init, tgt_traj, max_time, time_reward_factor=0.01): """ Initialize the trajectory environment :param agent_xyz_init: the initial agent position :param agent_acc: the acceleration available to the agent :param tgt_xyz_init: the target initial position :param tgt_traj: function defining the target trajectory parametrically vs. time :param max_time: the maximum trajectory time """ # define the initial separation between target/agent and how close they need to be to terminate the env self.init_sep = utils.calc_distance(agent_xyz_init, tgt_xyz_init) self.done_sep_threshold = 0.001 # set the time equal to 0, identify max time, and define the time step, which works out to 50 Hz if the time # is in seconds self.time = 0 self.time_step = 0.02 self.max_time = max_time # the time factor is a weight that determines how much the agent cares about time progressing # Higher scores <-> lower times self.time_reward_factor = time_reward_factor # the agent characteristics self.agent_xyz = agent_xyz_init self.agent_vxyz = np.zeros(3) self.agent_axyz = np.zeros(3) self.agent_acc = agent_acc # the target characteristics self.tgt_xyz = tgt_xyz_init self.tgt_xyz_next = self.tgt_position_calc(self.time_step) self.tgt_traj = tgt_traj
def evaluate_possible_movement_targets(self, possible_targets): """The value of a story location is highest when its distance from its author is 40, so determine the value of all possible target locations accordingly.""" result = [] # find the goal location - near either the author of the story, or its recipient (in case there's no author) if self.authors.all().count() > 0: author = self.authors.all()[0] goal_location = (author.x, author.y) elif self.recipients.all().count() > 0: recipient = self.recipients.all()[0] goal_location = (recipient.x, recipient.y) else: goal_location = None # move toward the goal location if goal_location != None: goal_location = near_by_location(goal_location, min_distance=20, max_distance=40, limit=LAYER_SIZE) for loc in possible_targets: value = -calc_distance(goal_location, loc) result.append( (value, loc) ) else : result = [ (0, i) for i in possible_targets] return result
def step(self, thrust_vector): """ Move the agent forward one step forward in time :param thrust_vector: the direction the agent moves :return: the current state (the acceleration, agent position, target position, and next target position), the reward the agent receives for its action, and whether or not the simulation is finished """ # get the unit vector representation of the thrust vector thrust_vector = utils.norm_vector(thrust_vector) # increment time by one step self.time += self.time_step # update the target position self.tgt_xyz = self.tgt_xyz_next self.tgt_xyz_next = self.tgt_position_calc() # update the agent position self.agent_position_update(thrust_vector) # calculate the reward reward = self.calc_reward() # determine if the simulation is finished or not. It finishes if the distance between the two is less # than the threshold or if the time is greater than the maximum time if utils.calc_distance(self.agent_xyz, self.tgt_xyz) < self.done_sep_threshold * self.init_sep \ or self.time > self.max_time: done = True reward = 0 else: done = False # concatenate the important information to feed into the DQN for the next prediction cur_state = np.concatenate(self.agent_acc, self.agent_xyz, self.tgt_xyz, self.tgt_xyz_next) return cur_state, reward, done
def location_analysis(): reviews_path = config.Project_CONFIG['user_folder_path'] city_values = [] state_values = [] distance_values = [] std_dist_values = [] std_dist_city_values = [] city_distance_values = [] b_data = read_business_info() files = os.listdir(reviews_path) for user_file in files: if not os.path.isdir(user_file): file_json_data = open(reviews_path + user_file, 'r', encoding="utf8") city_stat = {} state_stat = {} points = [] city_points = [] for line in enumerate(file_json_data): temp_json_data = json.loads(line[1]) b_id = temp_json_data['business_id'] b_info = b_data[b_id] city = b_info['city'] state = b_info['state'] lat = b_info['lat'] lon = b_info['lon'] points.append((lat, lon)) if city in city_stat: city_stat[city] += 1 else: city_stat[city] = 1 if state in state_stat: state_stat[state] += 1 else: state_stat[state] = 1 max_num = city_stat[max(city_stat, key=city_stat.get)] city_num = sum(city_stat.values()) city_values.append(max_num * 1.00 / city_num) file_json_data = open(reviews_path + user_file, 'r', encoding="utf8") city_name = max(city_stat, key=city_stat.get) for line in enumerate(file_json_data): temp_json_data = json.loads(line[1]) b_id = temp_json_data['business_id'] b_info = b_data[b_id] if b_info['city'] == city_name: lat = b_info['lat'] lon = b_info['lon'] city_points.append((lat, lon)) max_num_state = state_stat[max(state_stat, key=state_stat.get)] state_num = sum(state_stat.values()) state_values.append(max_num_state * 1.00 / state_num) x = [p[0] for p in points] y = [p[1] for p in points] centroid = (sum(x) / len(points), sum(y) / len(points)) distance = 0 dist_list = [] for p in points: distance += calc_distance(centroid[0], centroid[1], p[0], p[1]) dist_list.append( calc_distance(centroid[0], centroid[1], p[0], p[1])) avg_distance = distance / len(points) distance_values.append(avg_distance) std_dist_values.append(np.std(dist_list, ddof=1)) c_x = [c_p[0] for c_p in city_points] c_y = [c_p[1] for c_p in city_points] c_centroid = (sum(c_x) / len(city_points), sum(c_y) / len(city_points)) c_distance = 0 c_dist_list = [] for c_p in city_points: c_distance += calc_distance(c_centroid[0], c_centroid[1], c_p[0], c_p[1]) c_dist_list.append( calc_distance(c_centroid[0], c_centroid[1], c_p[0], c_p[1])) c_avg_distance = c_distance / len(city_points) city_distance_values.append(c_avg_distance) std_dist_city_values.append(np.std(c_dist_list, ddof=1)) print(city_values) # the proportion that the business is in the same city print( state_values) # the proportion that the business is in the same state print(distance_values) # business distance print(std_dist_values) # business distance standard deviation print(city_distance_values) # business distance in the same city print(std_dist_city_values ) # business distance in the same city standard deviation
def update_next_node(self,delta_t): next_pos = self.road.GetNodePosition(self.nextNode) if utils.calc_distance(self.position, next_pos) < self.velocity*delta_t: #We arrive at the next node self.nextNode=self.road.GetNextNode(self.nextNode) if self.nextNode == -1: self.active=False
def touches(self, other): return utils.calc_distance(self.x, self.y, other.x, other.y) <= 27
else: print "Main bus road needed" elif state == 2 and BusRoadStates == 3: if len(buses['Main']) != 0: buses['End'].append((event.pos, getNearestNodeIndex(event.pos, buses['Main']))) busExit_list.append(getNearestMainNode(event.pos, buses['Main'])) else: print "Main bus road needed" elif state == 3: alter = 0 dist = 1000 if len(roads['Main']) != 0: nearestMainNode = getNearestNodeInList(event.pos, roads['Main']) distMainNode = utils.calc_distance(event.pos, nearestMainNode) if distMainNode < dist: dist = distMainNode alter = 1 if len(roads['Start']) != 0: nearestStartNode = getNearestNodeInList(event.pos, [x[0] for x in roads['Start']]) distStartNode = utils.calc_distance(event.pos, nearestStartNode) if distStartNode < dist: dist = distStartNode alter = 2 if len(roads['End']) != 0: nearestEndNode = getNearestNodeInList(event.pos, [x[0] for x in roads['End']]) distEndNode = utils.calc_distance(event.pos, nearestEndNode) if distEndNode < dist: dist = distEndNode