Esempio n. 1
0
def _get_heuristic_value(chunk: str, mapper: Dict[str, str],
                         tf_idf_values: Dict[str,
                                             float], path: List[str]) -> float:
    processed_chunk = mapper.get(chunk)
    if processed_chunk is None:
        raise UndefinedChunkError('Chunk omitted during pre-processing.')

    vectorized_chunk = vectorize_sentence(processed_chunk)[0]
    avg_tf_idf = sum(tf_idf_values.values()) / len(tf_idf_values)

    tf_idf_score = 0
    for word in word_tokenize(processed_chunk):
        if tf_idf_values.get(word) is None:
            tf_idf_score += avg_tf_idf
        else:
            tf_idf_score += tf_idf_values[word]

    distances = []
    for prev_chunk in path:
        vectorized_prev_chunk = vectorize_sentence(prev_chunk)[0]
        distance = find_distance(vectorized_chunk, vectorized_prev_chunk)
        distances.append(distance)

    heuristic_val = tf_idf_score + min(distances)

    return heuristic_val
def guess_key_size(ciphertext):
    average_distances = []
    for keysize in range(2, 41):
        distances_list = []

        chunks = [ciphertext[i:i+keysize] for i in range(0, len(ciphertext), keysize)]

        while True:
            try:
                chunk_1 = chunks[0]
                chunk_2 = chunks[1]

                new_distance = find_distance(chunk_1, chunk_2)

                distances_list.append(new_distance/keysize)

                del chunks[0]
                del chunks[1]
            except Exception as e:
                break

        result = {
            'key': keysize,
            'avg distance': sum(distances_list) / len(distances_list)
        }
        average_distances.append(result)

    possible_keys = sorted(average_distances, key=lambda x: x['avg distance'])[:1]

    return [possible_key["key"] for possible_key in possible_keys]
Esempio n. 3
0
    def create_dataset(self, data_dict, business_names, date_range):
        for name in business_names:
            business_dict = self.gen_json_data(name)
            for date in date_range:
                data_dict[date].append(business_dict)

        # Add in random availabilities
        for date in date_range:  # each date key
            # each dict in the date key val array
            for i in range(len(data_dict[date])):
                # each stylist in stylist arr
                for j in range(len(data_dict[date][i]["stylists"])):
                    # iterate the dicts
                    for key, value in data_dict[date][i]["stylists"][j][
                            "availability"].items():
                        data_dict[date][i]["stylists"][j]["availability"][
                            key] = random.randint(0, 1)

        image_urls = self.query_photos(num=20, query='salon')
        addresses = self.gen_random_addresses(num=20,
                                              city="San Francisco",
                                              state="CA")

        for date in date_range:
            for i in range(len(data_dict[date])):
                data_dict[date][i]["imageurl"] = image_urls[i]
                data_dict[date][i]["location"] = addresses[i]
                latlong_coords = address_to_latlong(
                    data_dict[date][i]["location"])
                data_dict[date][i]["distance"] = find_distance(self.location,
                                                               latlong_coords,
                                                               unit='mi')

        self.output_data = data_dict
Esempio n. 4
0
def basic(collection, k, threshold):
    clusters: List[List[Tuple[str, tuple]]] = [[collection[0]]]

    for x in collection[1:]:
        arg_min_index = arg_min(x, clusters)

        if find_distance(
                x, clusters[arg_min_index]) > threshold and len(clusters) < k:
            clusters.append([x])
        else:
            clusters[arg_min_index].append(x)

    return clusters
Esempio n. 5
0
def main():
    graph = input.get_graph()

    # Test Input:
    # 1.
    print(utils.find_distance(graph, ['A', 'B', 'C']))

    # 2.
    print(utils.find_distance(graph, ['A', 'D']))

    # 3.
    print(utils.find_distance(graph, ['A', 'D', 'C']))

    # 4.
    print(utils.find_distance(graph, ['A', 'E', 'B', 'C', 'D']))

    # 5.
    print(utils.find_distance(graph, ['A', 'E', 'D']))

    # 6.
    print(utils.find_routes_max_stops(graph, 'C', 'C', 3))

    # 7.
    print(utils.find_routes_equal_stops(graph, 'A', 'C', 4))
Esempio n. 6
0
 def process_odom(self, odom_data: Odometry) -> None:
     """
     Receive an odometry reading and check if the robot is in the center of the map.
     """
     if not self.initialized:
         # Set the starting pose when the bot first spawns in
         self.starting_pose = odom_data.pose.pose
         self.initialized = True
     else:
         # If the starting pose exists, check whether the bot is within
         # a certain radius of the starting position
         distance = find_distance(self.starting_pose, odom_data.pose.pose)
         if distance < C.CENTER_RADIUS:
             self.conditions["IN_CENTER"] = True
         else:
             self.conditions["IN_CENTER"] = False
         self.update_controller_states(self.get_next_state())
Esempio n. 7
0
    def calculate_velocity_odom(self, odom_data: Odometry) -> Twist:
        """
        Calculate a velocity for the robot to navigate to the center of the map.
        """
        bot_vel = Twist()

        # Calculate the angular displacement from the bot's current orientation
        # to where its original spawn point was
        angle_offset = find_angle_offset(odom_data.pose.pose,
                                         self.starting_pose)
        bot_vel.angular.z = C.KP_ANG * angle_offset

        if abs(angle_offset) < (np.pi / 4):
            # Only move forward if the bot is facing the spawn point
            distance = find_distance(odom_data.pose.pose, self.starting_pose)
            bot_vel.linear.x = C.KP_LIN * distance

        return bot_vel
Esempio n. 8
0
def two_pass(collection, k, threshold):
    clusters: List[List[Tuple[str, tuple]]] = [[collection[0]]]
    Y = []

    for x in collection[1:]:
        arg_min_index = arg_min(x, clusters)

        if find_distance(
                x, clusters[arg_min_index]) > threshold and len(clusters) < k:
            clusters.append([x])
        else:
            Y.append(x)

    for y in Y:
        arg_min_index = arg_min(y, clusters)
        clusters[arg_min_index].append(y)

    return clusters