def answer_value(name):
    answer = parse_answer(name + '.out')
    N, M, D, U, drivers, users = rif.parse_in(name + '.in')
    if not legal_answer(answer, D, drivers, users):
        return 0

    value = 0
    for driver in answer:
        passengers = get_driver_passengers_idx(driver)

        # driver only counts if not alone
        if passengers:
            actual_distance = driven_distance(driver)
            min_distance = manhattan_distance(drivers[driver[0][0]][1],
                                              drivers[driver[0][0]][2])
            value += MAX_DISTANCE - (actual_distance - min_distance)

        # passengers
        for passenger in passengers:
            if passenger >= D:  # passenger that's not a driver
                value += manhattan_distance(
                    users[passenger - D][1],
                    users[passenger - D][2]) + MAX_DISTANCE
            else:
                value += manhattan_distance(
                    drivers[passenger][1],
                    drivers[passenger][2]) + MAX_DISTANCE
    return value
示例#2
0
    def test_manhattan_distance(self):
        """
        A test to ensure that the distance between points
        is being properly computed.

        You do not need to make any changes to this test,
        instead, in utils.py, you must complete the
        `eucliden_distance` function so that the correct
        values are returned.

        Something to think about: Why might you want to test
        different cases, e.g. all positive integers, positive
        and negative floats, coincident points?
        """
        point_a = (3, 7)
        point_b = (1, 9)
        distance = utils.manhattan_distance(point_a, point_b)
        self.assertEqual(4.0, distance)

        point_a = (-1.25, 2.35)
        point_b = (4.2, -3.1)
        distance = utils.manhattan_distance(point_a, point_b)
        self.assertEqual(10.9, distance)

        point_a = (0, 0)
        point_b = (0, 0)
        distance = utils.manhattan_distance(point_b, point_a)
        self.assertAlmostEqual(0.0, distance, 4)
示例#3
0
def preprocess_data(couriers, orders):

    impossible_orders = 0
    filtered_orders = []
    for order in orders:
        distance = manhattan_distance(order['pickup_location_x'],
                                      order['pickup_location_y'],
                                      order['dropoff_location_x'],
                                      order['dropoff_location_y'])

        closest_courier = None
        closest_courier_distance = np.inf
        for courier in couriers:
            courier_distance = manhattan_distance(courier['location_x'],
                                                  courier['location_y'],
                                                  order['pickup_location_x'],
                                                  order['pickup_location_y'])

            if courier_distance < closest_courier_distance:
                closest_courier = courier
                closest_courier_distance = courier_distance

        max_window = order['dropoff_to'] - max(order['pickup_from'],
                                               360 + closest_courier_distance)

        if distance >= max_window:
            impossible_orders += 1
        else:
            filtered_orders.append(order)

    print(
        f"Total orders: {len(orders)}, Impossible without depot: {impossible_orders}"
    )

    # fix order's time windows
    bad_order_counter = 0
    for order in filtered_orders:
        if order['pickup_to'] < order['pickup_from']:
            print(
                f"Bad time window order: {(order['pickup_from'], order['pickup_to'])}"
            )
            #             order['pickup_to'], order['pickup_from'] = order['pickup_from'], order['pickup_to']
            order['pickup_to'] = 24 * 60
            bad_order_counter += 1

        if order['dropoff_to'] < order['dropoff_from']:
            print(
                f"Bad time window order: {(order['dropoff_from'], order['dropoff_to'])}"
            )
            #             order['dropoff_to'], order['dropoff_from'] = order['dropoff_from'], order['dropoff_to']
            order['dropoff_from'] = 6 * 60
            bad_order_counter += 1

    # courier initial time windows
    for i, courier in enumerate(couriers):
        courier['from'] = 6 * 60
        courier['to'] = 24 * 60

    return couriers, filtered_orders
示例#4
0
 def process(self):
     # if status is inactive, activate
     self.activate_if_inactive()
     
     # only moves (not captures) are a valid goal
     if self.owner.captures:
         self.status = self.FAILED
         return
     
     # identify player and enemy
     plr_color = self.owner.to_move
     enemy_color = self.owner.enemy
     player = self.owner.get_pieces(plr_color)[0]
     p_idx, _ = player
     p_row, p_col = self.owner.row_col_for_index(p_idx)
     enemy = self.owner.get_pieces(enemy_color)[0]
     e_idx, _ = enemy
     e_row, e_col = self.owner.row_col_for_index(e_idx)
     
     # pick DC that isn't blocked by enemy
     lowest_dist = sys.maxsize
     dc = 0 
     for i in self.dc:
         dc_row, dc_col = self.owner.row_col_for_index(i)
         pdist = manhattan_distance(dc_row, dc_col, p_row, p_col)
         edist = manhattan_distance(dc_row, dc_col, e_row, e_col)
         if pdist < lowest_dist and edist > pdist:
             lowest_dist = pdist
             dc = i
             
     # if lowest distance is 0, then goal is complete.
     if lowest_dist == 0:
         self.status = self.COMPLETED
         return
     
     # select the available move that decreases the distance
     # between the original player position and the chosen double corner.
     # If no such move exists, the goal has failed.
     dc_row, dc_col = self.owner.row_col_for_index(dc)
     good_move = None
     for m in self.owner.moves:
         # try a move and gather the new row & col for the player
         self.owner.make_move(m, False, False)
         plr_update = self.owner.get_pieces(plr_color)[0]
         pu_idx, _ = plr_update
         pu_row, pu_col = self.owner.row_col_for_index(pu_idx)
         self.owner.undo_move(m, False, False)
         new_diff = abs(pu_row - dc_row) + abs(pu_col - dc_col)
         if new_diff < lowest_dist:
             good_move = m
             break
     if good_move:
         self.owner.make_move(good_move, True, True)
     else:
         self.status = self.FAILED
示例#5
0
    def predict(self, datum):
        min_distance = manhattan_distance(self.centroid[0], datum)
        min_idx = 0

        for i in range(0, self.n_clusters):
            distance = manhattan_distance(datum, self.centroid[i])
            if (distance < min_distance):
                min_distance = distance
                min_idx = i

        return min_idx
示例#6
0
def path_cost(path):
    # return total path length
    # consecutive nodes of the path are either along x-axis or y-axis so distance = manhattan distance
    cost = 0
    for i in range(len(path) - 1):
        cost += manhattan_distance(path[i], path[i + 1])
    return cost
示例#7
0
    def update(self, color, sensor_position, model):
        """
        Update the belief distribution based on new evidence:  our agent
        detected the given color at sensor location: sensor_position.
        :param color: (string) color detected
        :param sensor_position: (tuple) position of the sensor
        :param model (Model object) models the relationship between the
             treasure location and the sensor data
        :return: None
        """
        # Iterate over ALL positions in the grid and update the
        # probability of finding the treasure at that position - given
        # the new evidence.
        # The probability of the evidence given the Manhattan distance
        # to the treasure is given by calling model.pcolorgivendist.
        # Don't forget to normalize.
        # Don't forget to update self.open since sensor_position has
        # now been observed.
        for p in self.current_distribution:
            a = utils.manhattan_distance(p, sensor_position)
            self.current_distribution[
                p] = self.current_distribution[p] * model.pcolorgivendist(
                    color, a)

        # Don't forget to normalize!
        for p in self.current_distribution:
            self.current_distribution[p] = self.current_distribution[p] / sum(
                self.current_distribution.values())
        # Don't forget to update self.open since sensor_position has now been observed.
        self.open.discard(sensor_position)
    def update(self, sensor_position, color, model):
        """
        Update the belief distribution based on new evidence:  our agent
        detected the given color at sensor location: sensor_position.
        :param sensor_position: (tuple) position of the sensor
        :param color: (string) color detected
        :param model (Model object) models the relationship between the
             treasure location and the sensor data
        :return: None
        """
        # Iterate over ALL positions in the grid and update the probability
        # of finding the treasure at that position - given the new evidence
        # The probability of the evidence given the Manhattan distance to the
        # treasure may be accessed by calling model.get_pcolorgivendist.
        # Don't forget to normalize.
        # Don't forget to update self.open since sensor_position has now been
        # observed.

        # !!! update all positions instead of open positions
        # iterate over all keys
        # ??? If updating all probabilities, why need to update self.open?  What is that for? for recommend?
        sum = 0
        for any_position in self.tprob:
            # multiply P(effect_k|cause), then normalize
            # estimate the probability of treasure in open_position given all effects
            m_dist = utils.manhattan_distance(any_position, sensor_position)
            # should be proportional to this value
            self.tprob[any_position] *= model.get_pcolorgivendist(
                color, m_dist)
            #sum(dict.values())
            sum += self.tprob[any_position]
        self.tprob = {k: v / sum for k, v in self.tprob.items()}
        self.open.discard(sensor_position)
 def update(self, color, sensor_position, model):
     """
     Update the belief distribution based on new evidence:  our agent
     detected the given color at sensor location: sensor_position.
     :param color: (string) color detected
     :param sensor_position: (tuple) position of the sensor
     :param model (Model object) models the relationship between the
          treasure location and the sensor data
     :return: None
     """
     # Iterate over ALL positions in the grid and update the
     # probability of finding the treasure at that position - given
     # the new evidence.
     # The probability of the evidence given the Manhattan distance
     # to the treasure id given by calling model.psonargivendist.
     # Don't forget to normalize.
     # Don't forget to update self.open since sensor_position has
     # now been observed.
     self.open.remove(sensor_position)
     sumProb = float(0)
     for x, y in self.current_distribution:
         dist = utils.manhattan_distance((x, y), sensor_position)
         # P(S|T), float probability
         cp = model.psonargivendist(color, dist)
         self.current_distribution[x, y] *= cp
         sumProb += self.current_distribution[x, y]
     for w, z in self.current_distribution:
         self.current_distribution[
             w, z] = self.current_distribution[w, z] / sumProb
示例#10
0
    def update(self, color, sensor_position, model):
        """
        Update the belief distribution based on new evidence:  our agent
        detected the given color at sensor location: sensor_position.
        :param color: (string) color detected
        :param sensor_position: (tuple) position of the sensor
        :param model (Model object) models the relationship between the
             treasure location and the sensor data
        :return: None
        """
        # Iterate over ALL positions in the grid and update the probability
        # of finding the treasure at that position - given the new evidence
        # The probability of the evidence given the Manhattan distance to the
        # treasure may be accessed by calling model.pcolorgivendist.
        # Don't forget to normalize.
        # Don't forget to update self.open since sensor_position has now been
        # observed

        # Iterate over All positions in the grid and update the probability of finding treasure
        for p in self.current_distribution:
            self.current_distribution[p] *= model.pcolorgivendist(color, utils.manhattan_distance(p, sensor_position))

        # Normalize
        for p in self.current_distribution:
            self.current_distribution[p] = self.current_distribution[p]/sum(self.current_distribution.values())

        # Quick check that the values are normalized
        # print('CHECK',  sum(self.current_distribution.values()))

        # Remove sensor_position from the open set
        self.open.discard(sensor_position)
示例#11
0
def part2(instructions):
    ship = Ant(0, 0, 90)
    waypoint = Ant(10, 1)
    for ins in instructions:
        i, value = ins[0], int(ins[1:])
        if i == "F":
            x, y = waypoint.pos()
            ship.x += value * x
            ship.y += value * y
        elif i == "N":
            waypoint.north(value)
        elif i == "S":
            waypoint.south(value)
        elif i == "E":
            waypoint.east(value)
        elif i == "W":
            waypoint.west(value)
        elif i in "LR":
            dist = waypoint.dist()
            angle = waypoint.angle()
            waypoint.x = 0
            waypoint.y = 0
            if i == "L":
                waypoint.heading = angle + value
            else:
                waypoint.heading = angle - value
            waypoint.forward(dist)
    return manhattan_distance((0, 0), ship.pos())
示例#12
0
def distance_intra_cluster(transformed_df, main_df, centroids):
    zones = ["D1", "D2", "D3", "D4", "D5", "D6"]
    centroids_map = dict(zip(zones, centroids))
    centroids_df = pd.DataFrame.from_dict(
        centroids_map,
        orient="index",
        columns=["lat_centroids", "lon_centroids"])
    centroids_df = centroids_df.reset_index().rename(
        columns={"index": "zones"})

    unpivoted_df = pd.melt(transformed_df,
                           id_vars=['Id_Cliente'],
                           var_name="zones")
    unpivoted_df = unpivoted_df[unpivoted_df.value > 0]
    joined_df = unpivoted_df.merge(main_df[["Id_Cliente", "lat", "lon"]], on="Id_Cliente", how = "left")\
                            .merge(centroids_df,  on="zones", how = "left")
    joined_df["manhattan"] = manhattan_distance(joined_df["lat"],
                                                joined_df["lon"],
                                                joined_df["lat_centroids"],
                                                joined_df["lon_centroids"])
    joined_df["haversine"] = haversine_distance(joined_df["lat"],
                                                joined_df["lon"],
                                                joined_df["lat_centroids"],
                                                joined_df["lon_centroids"])
    print("Manhattan Distance")
    print(joined_df.groupby("zones")["manhattan"].sum())
    print("Haversine Distance")
    print(joined_df.groupby("zones")["haversine"].sum())
    return (joined_df["manhattan"].sum(), joined_df["haversine"].sum())
示例#13
0
文件: map.py 项目: sumitsk/algp
    def distance_between_nodes_with_headings(self, start, start_heading, goal,
                                             goal_heading):
        dist, final_heading = self.distance_between_nodes(
            start, goal, start_heading)
        if not opposite_headings(final_heading, goal_heading):
            return dist

        # Goal heading is opposite of final_heading
        perimeter = 4 + 2 * (self.corridor_len + 1)

        if start_heading in [(1, 0), (-1, 0)]:
            start_junc = self.get_junction(start, start_heading)
            gj = self.get_junction(goal, start_heading)
            goal_junc = self.get_junction(goal,
                                          (-goal_heading[0], goal_heading[1]))
            # the agent has to move atleast this distance
            min_dist = manhattan_distance(
                start, start_junc) + manhattan_distance(
                    start_junc, goal_junc) + manhattan_distance(
                        goal_junc, goal)

            # if start and goal are in the same column
            if start[1] == goal[1]:
                # same block
                if start_junc[0] == gj[0]:
                    # top or bottom block
                    if start_junc[0] == 0 or start_junc[0] == self.shape[0] - 1:
                        extra = perimeter + 4
                    else:
                        extra = perimeter
                # different blocks
                else:
                    extra = 4

            # start and goal are in adjacent sampling columns
            elif abs(start[1] - goal[1]) == 2:
                if start_heading == goal_heading:
                    extra = 4
                else:
                    extra = 0

            else:
                extra = 0
        else:
            raise NotImplementedError

        return min_dist + extra
示例#14
0
    def complete_link(cls, cluster_a, cluster_b):
        max_distance = -1

        for a in cluster_a:
            for b in cluster_b:
                distance = manhattan_distance(a, b)
                min_distance = max(distance, min_distance)

        return max_distance
示例#15
0
    def avg_group_link(cls, cluster_a, cluster_b):
        total_a = reduce(lambda a, b: [x[0] + x[1] for x in zip(a, b)],
                         cluster_a, [0 for x in range(len(cluster_a[0]))])
        total_b = reduce(lambda a, b: [x[0] + x[1] for x in zip(a, b)],
                         cluster_b, [0 for x in range(len(cluster_b[0]))])
        avg_a = list(map(lambda x: x / len(cluster_a), total_a))
        avg_b = list(map(lambda x: x / len(cluster_b), total_b))

        return manhattan_distance(avg_a, avg_b)
示例#16
0
    def single_link(cls, cluster_a, cluster_b):
        min_distance = 9999999999999

        for a in cluster_a:
            for b in cluster_b:
                distance = manhattan_distance(a, b)
                min_distance = min(distance, min_distance)

        return min_distance
示例#17
0
    def avg_link(cls, cluster_a, cluster_b):
        total_distance = 0
        counter = 0

        for a in cluster_a:
            for b in cluster_b:
                total_distance += manhattan_distance(a, b)
                counter += 1

        return total_distance / counter
示例#18
0
def calc_dist(wires):
    p0 = points_from_wire(wires[0])
    p1 = points_from_wire(wires[1])

    dist = 2**32
    for point in set(p0).intersection(set(p1)):
        d = manhattan_distance((0, 0), point)
        if d < dist:
            dist = d
    return dist
示例#19
0
 def observe(self, pos, problem):
     """
     Return the color returned when the sonar is aimed at the given location
     :param pos:  (tuple) sonar position
     :param problem: (Problem object)
     :return:
     color (string) : sensor reading
     """
     dist = utils.manhattan_distance(pos, problem.treasure)
     color = self.sample(dist)
     return color
示例#20
0
 def closest_point(x, y, points):
     dist = 1000000000000
     point = -1
     for i in range(len(points)):
         dist_ = manhattan_distance((x, y), points[i])
         if dist_ < dist:
             dist = dist_
             point = i
         elif dist_ == dist:
             point = -1
     return point
示例#21
0
def manhatten_freq(vectorizer, text1, text2):
    try:
        tfidf = vectorizer.fit_transform([text1, text2])
    except:
        vectorizer = TfidfVectorizer(stop_words=None,
                                     use_idf=True,
                                     tokenizer=tokenize_and_stem)
        tfidf = vectorizer.fit_transform([text1, text2])
    return float(
        manhattan_distance(list(tfidf[0].toarray()[0]),
                           list(tfidf[1].toarray()[0])))
示例#22
0
    def execute_search(self):
        """
        Corre el algoritmo A* sobre la cuadrícula
        para encontrar el objetivo.
        """
        path = []
        self.color[self.start[0]][self.start[1]] =\
            'GRAY'
        self.distance[self.start[0]][self.start[1]] = 0
        self.parent[self.start[0]][self.start[1]] = None
        self.open_list.put((0, self.start))
        self.f_score[self.start[0]][self.start[1]] =\
            manhattan_distance(self.start, self.goal)

        while not self.open_list.empty():
            current_square = self.open_list.get()
            current_square_coordinates =\
                current_square[1]
            if current_square_coordinates == self.goal:
                break
            if self.parent[current_square_coordinates[0]][
                    current_square_coordinates[1]]:
                current_path = self.get_path(current_square_coordinates)
                path += current_path
                path += self.get_reverse_path(current_path)
            up_square = self.move_up(current_square_coordinates)
            left_square = self.move_to_the_left(current_square_coordinates)
            right_square = self.move_to_the_right(current_square_coordinates)
            down_square = self.move_down(current_square_coordinates)

            successors = [up_square, left_square, right_square, down_square]

            for successor in successors:
                if successor:
                    f = self.distance[successor[0]][successor[1]] +\
                        manhattan_distance(successor, self.goal)
                    if self.f_score[successor[0]][successor[1]] >= f:
                        self.f_score[successor[0]][successor[1]] = f
                        self.open_list.put((f, successor))
        return path
示例#23
0
    def execute_search(self):
        """
        Realiza la búsqueda primero en anchura.

        :return: una lista con la trayectoria más corta del inicio al objetivo.
        :return type: list
        """
        path = []
        self.color[self.start[0]][self.start[1]] =\
            'GRAY'
        self.distance[self.start[0]][self.start[1]] = 0
        self.parent[self.start[0]][self.start[1]] = None
        self.my_bests.put((manhattan_distance(self.start, self.goal),\
            self.start))

        while not self.my_bests.empty():
            current_square = self.my_bests.get()
            current_square = current_square[1]
            if current_square == self.goal:
                break
            if self.parent[current_square[0]][current_square[1]]:
                current_path = self.get_path(current_square)
                path += current_path
                path += self.get_reverse_path(current_path)

            up_square = self.move_up(current_square)
            if up_square:
                self.my_bests.put((manhattan_distance(up_square, self.goal), up_square))
            left_square = self.move_to_the_left(current_square)
            if left_square:
                self.my_bests.put((manhattan_distance(left_square, self.goal), left_square))
            right_square = self.move_to_the_right(current_square)
            if right_square:
                self.my_bests.put((manhattan_distance(right_square, self.goal), right_square))
            down_square = self.move_down(current_square)
            if down_square:
                self.my_bests.put((manhattan_distance(down_square, self.goal), down_square))

            self.color[current_square[0]][current_square[1]] = 'BLACK'
        return path
示例#24
0
def pair_triplet_accuracy(y_true: TensorLike,
                          y_pred: TensorLike,
                          margin: FloatTensorLike = 1.0,
                          distance_metric: Union[str, Callable] = "L2"):
    """
        Calculates how often predictions matches the cut/non cut labels.
        Convert two embeddings into label `labels_pred` by calculating 
        distance and threshold using margin.
        It computes the frequency with which `labels_pred` matches `y_true`. 
        This frequency is ultimately returned as `pair accuracy`.
        Args:
            y_true: Integer ground truth values.
            y_pred: 3-D float `Tensor` of representational embedding of
                RNA and gRNA. [batch, 2, embedding_dim]
            margin: Float, threshold distance.
            distance_metric: String, distance metric in use.
        Returns:
            Float, accuracy values.
    """
    embeddings = ops.convert_to_tensor_v2_with_dispatch(y_pred)
    labels = ops.convert_to_tensor_v2_with_dispatch(y_true)

    convert_to_float32 = (
        embeddings.dtype == tf.dtypes.float16 or \
            embeddings.dtype == tf.dtypes.bfloat16
    )
    precise_embeddings = (
        tf.cast(embeddings, tf.dtypes.float32) \
            if convert_to_float32 else embeddings
    )

    if distance_metric == "L2":
        dist = euclidean_distance(precise_embeddings[:, 0],
                                  precise_embeddings[:, 1])
    elif distance_metric == "squared-L2":
        dist = tf.square(
            euclidean_distance(precise_embeddings[:, 0],
                               precise_embeddings[:, 1]))
    elif distance_metric == "L1":
        dist = manhattan_distance(precise_embeddings[:, 0],
                                  precise_embeddings[:, 1])
    else:  # Callable
        dist = distance_metric(precise_embeddings[:, 0], precise_embeddings[:,
                                                                            1])

    labels_pred = dist <= margin

    return math_ops.cast(
        math_ops.equal(tf.cast(tf.math.floormod(y_true, 2), tf.dtypes.bool),
                       labels_pred), K.floatx())
示例#25
0
 def select_element(self, cell):
     contained = list(cell.contained)
     is_selected = False
     selected = None
     while not is_selected:
         if not contained:
             return
         selected = random.choice(contained)
         destination = self.get_destination_cell(selected)
         distance = manhattan_distance(cell.index, destination)
         if distance != 0:
             is_selected = True
         else:
             contained.remove(selected)
     return selected
示例#26
0
def get_user_shop_distance(result):
    result['feature_user_shop_lon_sub'] = (result['user_longitude'] -
                                           result['shop_longitude'])
    result['feature_user_shop_lat_sub'] = (result['user_latitude'] -
                                           result['shop_latitude'])
    result['feature_user_shop_lon_sub_abs'] = abs(
        result['feature_user_shop_lon_sub'])
    result['feature_user_shop_lat_sub_abs'] = abs(
        result['feature_user_shop_lat_sub'])
    result['feature_user_shop_uclidean_dis'] = euclidean_distance(
        result['user_latitude'], result['user_longitude'],
        result['shop_latitude'], result['shop_longitude'])
    result['feature_user_shop_haversine_dis'] = haversine_distance(
        result['user_latitude'], result['user_longitude'],
        result['shop_latitude'], result['shop_longitude'])
    result['feature_user_shop_manhattan_dis'] = manhattan_distance(
        result['user_latitude'], result['user_longitude'],
        result['shop_latitude'], result['shop_longitude'])
    return result
示例#27
0
def part1(instructions):
    ship = Ant(0, 0, heading=0)
    for ins in instructions:
        i, value = ins[0], int(ins[1:])
        if i == "F":
            ship.forward(value)
        elif i == "N":
            ship.north(value)
        elif i == "S":
            ship.south(value)
        elif i == "E":
            ship.east(value)
        elif i == "W":
            ship.west(value)
        elif i == "L":
            ship.turn(value)
        elif i == "R":
            ship.turn(-value)
    return manhattan_distance((0, 0), ship.pos())
示例#28
0
def get_user_shop_average_distance(refer, result):
    shop_longitude = refer.groupby(['shop_id'],
                                   as_index=False)['longitude'].agg(
                                       {'shop_average_longitude': 'mean'})
    shop_latitude = refer.groupby(['shop_id'], as_index=False)['latitude'].agg(
        {'shop_average_latitude': 'mean'})
    result = pd.merge(result, shop_longitude, on=['shop_id'], how='left')
    result = pd.merge(result, shop_latitude, on=['shop_id'], how='left')
    result['feature_user_shop_aver_uclidean_dis'] = euclidean_distance(
        result['user_latitude'], result['user_longitude'],
        result['shop_average_latitude'], result['shop_average_longitude'])
    result['feature_user_shop_aver_haversine_dis'] = haversine_distance(
        result['user_latitude'], result['user_longitude'],
        result['shop_average_latitude'], result['shop_average_longitude'])
    result['feature_user_shop_aver_manhattan_dis'] = manhattan_distance(
        result['user_latitude'], result['user_longitude'],
        result['shop_average_latitude'], result['shop_average_longitude'])
    del result['shop_average_longitude']
    del result['shop_average_latitude']
    return result
示例#29
0
def main(puzzle_input):
    points = []

    for line in puzzle_input:
        points.append(tuple(get_numbers((line))))

    # compute the distance between every pair of points
    distances = {
        p: {q: manhattan_distance(p, q)
            for q in points}
        for p in points
    }

    # for each point, find the constellation of points that it contains
    constellations = 0
    points_in_constellation = set()
    points_remaining = set(points)
    # basically we pick a point that isn't in a constellation, and then keep working
    # away from that point until we've found the entire constellation
    while True:
        # no more points remaining!
        if len(points_remaining) == 0:
            break

        p = points_remaining.pop()
        to_process = set([p])
        points_in_constellation.add(p)

        while len(to_process) > 0:
            p = to_process.pop()

            # get all the points that are within a distance of 3 of our current processing points
            qs = {q for q in points_remaining if distances[p][q] <= 3}

            points_remaining = points_remaining.difference(qs)
            points_in_constellation = points_in_constellation.union(qs)
            to_process = to_process.union(qs)

        constellations += 1

    return constellations
示例#30
0
def dirt_heuristic(state, problem):
    """
    Heuristic to search all locations in the map
    Uses distance to furthest dirt as heuristic
    :param state: Current state of the robot/world (RobotState)
    :param problem: Search problem to be completed (e.g., MapEnvironmentProblem)
    :return: Heuristic value of the current state (RobotState, Grid)
    """

    unvisited = state.getDirt()
    cell_costs = []
    for cell in unvisited:
        cell_costs.append(
            utils.manhattan_distance(state.getRobotPosition(), cell))
    if len(cell_costs) > 0:
        max_cost = max(cell_costs)
        min_cost = min(cell_costs)
    else:
        max_cost = 0
        min_cost = 0
    return min_cost + (len(unvisited) * len(unvisited))
示例#31
0
    def dfs_visit(self, current_square):
        if current_square == self.goal or self.done:
            self.done = True
            return
        self.distance[current_square[0]][current_square[1]] = self.time
        self.time += 1
        self.color[current_square[0]][current_square[1]] = 'GRAY'
        up_square = self.move_up(current_square)
        left_square = self.move_to_the_left(current_square)
        right_square = self.move_to_the_right(current_square)
        down_square = self.move_down(current_square)
        candidates = [up_square, left_square, right_square, down_square]
        candidates = [(manhattan_distance(candidates[idx], self.goal), idx)\
            for idx in range(4) if candidates[idx]]
        for candidate in sorted(candidates):
            if self.done:
                break
            if candidate[1] == 0:
                self.path.append('U')
                self.dfs_visit(up_square)
                # if not self.done:
                self.path.append('D')
            if candidate[1] == 2:
                self.path.append('R')
                self.dfs_visit(right_square)
                # if not self.done:
                self.path.append('L')
            if candidate[1] == 1:
                self.path.append('L')
                self.dfs_visit(left_square)
                # if not self.done:
                self.path.append('R')
            if candidate[1] == 3:
                self.path.append('D')
                self.dfs_visit(down_square)
                # if not self.done:
                self.path.append('U')

        self.color[current_square[0]][current_square[1]] = 'BLACK'
示例#32
0
文件: q2_q3.py 项目: babingto/IT3708
from scenarios import flatland_from_file
from utils import manhattan_distance

ITERATIONS = 5000

TEMPERATURE = 1.0

N = 1

if __name__ == '__main__':
    times = {
        2: [],
        3: []
    }
    flatland = flatland_from_file('../scenarios/5-even-bigger.txt')
    backup_x = int(sqrt(manhattan_distance((0, 0), (flatland.w, flatland.h))))

    for i in xrange(N):
        print(2, i)
        agent = FlatlandAgent(
            world=deepcopy(flatland),
            step_limit=flatland.w * flatland.h,
            backup_x=backup_x,
            temperature=TEMPERATURE,
            delta_t=TEMPERATURE / ITERATIONS
        )
        agent.Q = Q2()

        start = time()
        agent.train()
        finish = time()
	def get_h_val(self, node):
		return manhattan_distance(node.xy, self.goal_node.xy)