Beispiel #1
0
def average_nearest_neighbor_distance(points, mark=None):
    if mark!=None:
        marked_points = []
        shortest_path = []
        for x in range(len(points)):
            if points[x].get_mark() == mark:
                marked_points.append(points[x].get_point())
        for num1, p_one in enumerate(marked_points):
            distance = []
            for num2, p_two in enumerate(marked_points):
                if num1 != num2:
                    distance.append(utils.euclidean_distance(p_one, p_two))
            shortest_path.append(min(distance))
        mean_d = sum(shortest_path)/len(shortest_path)
        return mean_d
    else:
        shortest_path = []
        for num1, p_one in enumerate(points):
            distance = []
            for num2, p_two in enumerate(points):
                if num1 != num2:
                    distance.append(utils.euclidean_distance(p_one, p_two))
            shortest_path.append(min(distance))
        mean_d = sum(shortest_path)/len(shortest_path)
        return mean_d
Beispiel #2
0
    def test_euclidean_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.euclidean_distance(point_a, point_b)
        self.assertAlmostEqual(2.8284271, distance, 4)

        point_a = (-1.25, 2.35)
        point_b = (4.2, -3.1)
        distance = utils.euclidean_distance(point_a, point_b)
        self.assertAlmostEqual(7.7074639, distance, 4)

        point_a = (0, 0)
        point_b = (0, 0)
        distance = utils.euclidean_distance(point_b, point_a)
        self.assertAlmostEqual(0.0, distance, 4)
Beispiel #3
0
    def search(
        self,
        maze: List[List[int]],
        start: Tuple[int, int],
        goal: Tuple[int, int],
        neighborhood: str = "N8",
        radius: float = 0,
    ) -> List[Tuple[int, int]]:
        if not self._is_free_cell(start, maze):
            return []

        open_set: PriorityQueue[Tuple[int, int]] = PriorityQueue()
        open_set.push(start, 0)

        came_from: Dict[Tuple[int, int], Optional[Tuple[int, int]]] = {
            start: None
        }
        dist: Dict[Tuple[int, int], float] = {start: 0}
        while not open_set.empty():
            current = open_set.pop()

            if euclidean_distance(current, goal) <= radius:
                return self._reconstruct_path(current, came_from)

            for node in self._get_neighbors(current, maze, neighborhood):
                new_dist = dist[current] + euclidean_distance(current, node)
                if node not in dist or new_dist < dist[node]:
                    came_from[node], dist[node] = current, new_dist
                    open_set.push(node, new_dist + self.heuristic(node, goal))

        return []
    def random_solution(self):
        cost = 0
        pending = []
        result = []
        mapped_result = []
        mapped = {}

        for i in range(0, len(self.coordinates)):
            pending.append(self.coordinates[i])
            mapped[self.coordinates[i]] = i

        while len(pending) != 0:
            pos = int(round(uniform(0, len(pending) - 1)))
            result.append(pending[pos])
            mapped_result.append(mapped[pending[pos]] + 1)
            pending.remove(pending[pos])

            if len(result) >= 2:
                cost += euclidean_distance(result[len(result) - 1],
                                           result[len(result) - 2])

        if len(result) >= 2:
            cost += euclidean_distance(result[0], result[len(result) - 1])

        return result, cost
Beispiel #5
0
def average_nearest_neighbor_distance(points,mark=None):
    mean_d = 0
    
    if(mark==None):
        for i in range(len(points)):
            dist_nearest=math.inf
            for j in range(len(points)):
                temp_p1 = (points[i].x, points[i].y)
                temp_p2 = (points[j].x, points[j].y)
                dist = utils.euclidean_distance(temp_p1, temp_p2)
                if temp_p1 == temp_p2:
                    continue
                elif dist < dist_nearest:
                    dist_nearest = dist;
                    mean_d += dist_nearest;
                    mean_d=mean_d/(len(points))
    else:
        for i in range(len(points)):
            dist_nearest=math.inf
            for j in range(len(points)):
                dist = utils.euclidean_distance((points[i].x, points[i].y), (points[j].x,points[j].y))
                if temp_p1 == temp_p2:
                    continue
                elif dist < dist_nearest and temp_p1==temp_p2:
                    dist_nearest = dist;
                    mean_d += dist_nearest;
                    mean_d=mean_d/(len(points))
        
    return mean_d
Beispiel #6
0
def complete_linkage(subcluster_1, subcluster_2):
    flattened_1 = flatten(subcluster_1)
    flattened_2 = flatten(subcluster_2)

    best_max = float("-inf")
    for x1 in flattened_1:
        for x2 in flattened_2:
            if best_max < euclidean_distance(x1, x2):
                best_max = euclidean_distance(x1, x2)
    return best_max
Beispiel #7
0
def single_linkage(subcluster_1, subcluster_2):
    flattened_1 = flatten(subcluster_1)
    flattened_2 = flatten(subcluster_2)

    best_min = float("inf")
    for x1 in flattened_1:
        for x2 in flattened_2:
            if best_min > euclidean_distance(x1, x2):
                best_min = euclidean_distance(x1, x2)
    return best_min
    def test_euclidean_distance(self):
        p2D = [0.3, 0.5]
        q2D = [1.3, 1.2]
        self.assertAlmostEqual(utl.euclidean_distance(p2D, q2D), 1.220656, 6)

        p3D = [0.3, 0.5, 0.8]
        q3D = [1.3, 0.4, 1.2]
        self.assertAlmostEqual(utl.euclidean_distance(p3D, q3D), 1.081665, 6)

        p0 = [0.0] * 40
        q0 = [0.0] * 40
        self.assertEqual(utl.euclidean_distance(p0, q0), 0)
Beispiel #9
0
    def calculate(self, individuals, membership_matrix, centers):
        """ fuzzy_membership should be ELEMENTSxCLUSTERS matrix
        """
        min_cluster_distance = min(euclidean_distance(first, second) ** 2 for first, second in combinations(centers, 2))

        clusterization_scattering = 0
        for cluster_index in xrange(len(centers)):
            for individual_index in xrange(len(individuals)):
                membership = membership_matrix[individual_index][cluster_index] ** self._m
                distance   = euclidean_distance(individuals[individual_index], centers[cluster_index]) ** 2
                clusterization_scattering += membership * distance

        return clusterization_scattering / min_cluster_distance * self._c
Beispiel #10
0
    def attaction_force(self, agent, myx, myy, fromx, fromy):
        # TODO - clean this up
        nx, ny = ((agent.position.y - fromy) / euclidean_distance((agent.position.x, agent.position.y), (fromx, fromy))), \
                ((agent.position.x - fromx) / euclidean_distance((agent.x, agent.position.y), (fromx, fromy)))
        oc11, oc12 = agent.position.x + self.radius * nx, agent.position.y - self.radius * ny
        oc21, oc22 = agent.position.x - self.radius * nx, agent.position.y + self.radius * ny

        pn = self.normal_point(myx, myy, oc11, oc12, oc21, oc22)
        pdist = euclidean_distance((myx, myy), (pn[0],pn[1]))

        if pdist == 0:
            return (0, 0, 0)

        return ((pn[0]-myx)/pdist, (pn[1]-myy)/pdist, 0 )
Beispiel #11
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())
Beispiel #12
0
 def _get_distance_matrix(self, sorted_locs: List[Location]) -> List[List[float]]:
     n = len(sorted_locs)
     matrix = [[0.0 for _ in range(n)] for _ in range(n)]
     for i in range(n):
         for j in range(n):
             matrix[i][j] = euclidean_distance(sorted_locs[i], sorted_locs[j])
     return matrix
Beispiel #13
0
 def h(self, node):
     """The heuristic h(n) function: here it's used the straight distance."""
     locs = self.locations
     if locs:
         return int(euclidean_distance(locs[node.state], locs[self.goal]))
     else:
         return math.inf
    def classify_one(self, test_example: Examples) -> int:
        committee = []
        for train_example in self._train_examples:
            insort(committee, CommitteeWrapper(train_example[0], euclidean_distance(test_example, train_example)))

        votes_num, vote_for, vote_against, under_bound = 0, 0, 0, (0, 0)
        for vote in committee:
            if vote.distance < self._bound:
                under_bound = (vote_for, vote_against)
            if votes_num >= self._k:
                break
            if vote == 1:
                vote_for += 1
            else:
                vote_against += 1
            votes_num += 1

        if vote_for >= vote_against:
            return 1

        # KNN wants to classify as Negative to disease (healthy), let's get a second opinion
        if self._id3_classifier is None:
            self._id3_classifier = ID3ContinuousFeatures(self._train_examples)

        if self._id3_classifier.classify_one(test_example):
            return 1

        # Both KNN and ID3 want to classify as Negative to disease (healthy), let's get a third final opinion
        return under_bound[0] > under_bound[1]
Beispiel #15
0
def compute_dbi(embs, clus_map, center_map):

    n_clus = len(center_map)

    c_centers = {}
    for c_center in center_map:
        cid = center_map[c_center]
        c_centers[int(cid)] = embs[c_center]

    M = [[0 for x in range(n_clus)] for y in range(n_clus)]
    R = [[0 for x in range(n_clus)] for y in range(n_clus)]
    S = [0 for x in range(n_clus)]
    D = [0 for x in range(n_clus)]

    for i in range(n_clus):
        c_embs = [embs[x] for x in clus_map[i]]
        S[i] = utils.euclidean_cluster(c_embs, c_centers[i])

    for i in range(n_clus):
        for j in range(n_clus):
            if i != j:
                M[i][j] = utils.euclidean_distance(c_centers[i], c_centers[j])
                R[i][j] = (S[i] + S[j]) / M[i][j]

    for i in range(n_clus):
        for j in range(n_clus):
            if i != j and R[i][j] > D[i]:
                D[i] = R[i][j]

    return sum(D) / len(D)
    def _search_tree(self, root, x):
        """搜索kd树
        Args:
            root: 开始搜索的树节点
            x: 需要判定类别的样本
        """
        if root is None:
            return

        split_axis = root['split_axis']
        if x[split_axis] < root['data'][split_axis]:
            self._search_tree(root['left'], x)
        else:
            self._search_tree(root['right'], x)

        heapq.heappush(self.neighbors, (-1 * euclidean_distance(x, root['data'][1:]), next(counter), root['data']))
        if len(self.neighbors) > self.k:
            heapq.heappop(self.neighbors)

        split_dist = abs(x[split_axis] - root['data'][split_axis])
        neighbor_max = -1 * heapq.nsmallest(1, self.neighbors)[0][0]
        if split_dist > neighbor_max:
            return

        if x[split_axis] < root['data'][split_axis]:
            self._search_tree(root['right'], x)
        else:
            self._search_tree(root['left'], x)
 def predict(self, X_train, y_train, X_test, kd_tree=False):
     """用训练集来预测测试集
     Args:
         X_train: 训练特征数据
         y_train: 训练标签数据
         X_test: 测试特征数据
         kd_tree: True代表使用kd树搜索,False代表使用线性扫描
     Returns
         pred: 针对X_test的预测结果
     """
     pred = np.empty(X_test.shape[0])
     if kd_tree:
         data = np.insert(X_train, 0, y_train, axis=1)
         n_features = np.array(data).shape[1]
         self.split_order = random.sample(range(1, n_features), n_features - 1)
         root = self._build_kd_tree(data, 0)
         for i, sample in enumerate(X_test):
             # print(f'processing sample {i + 1} / {len(X_test)}')
             self.neighbors.clear()
             self._search_tree(root, sample)
             neighbors = np.array([x[0] for d, c, x in self.neighbors])
             pred[i] = self._vote(neighbors)
     else:
         for i, sample in enumerate(X_test):
             # print(f'processing sample {i + 1} / {len(X_test)}')
             idx = np.argsort([euclidean_distance(x, sample) for x in X_train])[:self.k]
             neighbors = np.array([y_train[j] for j in idx])
             pred[i] = self._vote(neighbors)
     return pred
Beispiel #18
0
def test_arange():
    a = np.arange(4).reshape(2, 2)
    print(a)
    print(np.diag(a))
    print(np.einsum('i...i', a))
    print(euclidean_distance(p1_array, p2_array))
    print(f1_score(p1_array, p2_array))
def get_costs_matrix(actual_blobs, detections, threshold):
    # the costs matrix width has to be larger or equal than height
    rows_count = len(actual_blobs)

    if rows_count > len(detections):
        columns_count = rows_count
        for i in range(0, len(actual_blobs) - len(detections)):
            detections = np.append(detections, Detection())
    else:
        columns_count = len(detections)

    costs_matrix = np.zeros(shape=(rows_count, columns_count), dtype=float)

    for i, blob in enumerate(actual_blobs):
        for j, detection in enumerate(detections):
            if detection.position is None:
                costs_matrix[i][j] = INFINITE
            else:
                distance = euclidean_distance(
                    blob_center(blob), blob_center(detection.position)
                )

                costs_matrix[i][j] = \
                    distance if distance <= threshold else INFINITE

    return costs_matrix, detections
Beispiel #20
0
    def assign_label(self):
        all_labeled_y, all_labeled_x = read_input('./datas/all_label.p')
        all_labeled_imgs = self.encoder.predict(all_labeled_x)
        all_unlabeled_x = read_input('./datas/all_unlabel.p')
        all_unlabeled_imgs = self.encoder.predict(all_unlabeled_x)
        index = -1
        for unlabeled_img in tqdm(all_unlabeled_imgs):
            index += 1
            target_img = all_unlabeled_x[index]
            target_img = target_img.reshape((1,) + target_img.shape)

            all_distance = [euclidean_distance(unlabeled_img, labeled_img) for labeled_img in all_labeled_imgs]
            index_of_max = min(range(len(all_distance)), key = lambda i: all_distance[i])
            assigned_label = all_labeled_y[index_of_max]
            all_labeled_x = np.concatenate((all_labeled_x, target_img), axis=0)
            all_labeled_y = np.concatenate((all_labeled_y, np.array([assigned_label])), axis=0)

            # # for debug
            # origin_img = all_labeled_x[index_of_max]
            # target_img = np.reshape(target_img, (3, 32, 32))
            # origin_img = np.reshape(origin_img, (3, 32, 32))
            # pyplot.figure(figsize=[4, 4])
            # pyplot.subplot(2, 2, 1)
            # pyplot.imshow(toimage(origin_img))
            # pyplot.subplot(2, 2, 2)
            # pyplot.imshow(toimage(target_img))
            # pyplot.show()

        output_dict = dict({'data': all_labeled_x, 'labels': all_labeled_y})
        output_path = 'datas/relabeled_img.p'
        import pickle
        with open(output_path, 'wb') as handle:
            print("Save output at %s " % output_path)
            pickle.dump(output_dict, handle, protocol=pickle.HIGHEST_PROTOCOL)
def batch_hard(axs, ays):
    """ Returns hard positives and hard negatives for anchors (axs argument).

    Computes euclidean distance using numpy functionalities (W/O CUDA).
    Then, for each embedding finds farthest embedding as hard positive from the same class.
    As hard negatives it chooses nearest embedding from different class.

    :param axs: ndarray (N, EMBEDDING_SIZE)
    :param ays: ndarray (N,)
    :return: tuple, (hard_positives: ndarray (N, EMBEDDING_SIZE) , hard_negatives: ndarray (N, EMBEDDING_SIZE))
    """
    distance_matrix = euclidean_distance(axs, axs)
    # matrix side size
    ays = ays.reshape(-1, 1)
    num = ays.shape[0]
    diagonal_idxs = np.diag_indices(num)
    # mask items where labels are equal
    y_equals = ays == ays.T
    # let's find HARD POSITIVES
    y_equals[diagonal_idxs] = False
    d2p = distance_matrix.copy()
    # we are going to find hard positive - the most distant positive
    # therefore set -infinity distance to the same items
    d2p[y_equals == False] = -np.inf
    p_idxs = np.argmax(d2p, axis=1)
    hard_positives = axs[p_idxs]
    # let's find HARD NEGATIVES
    d2n = distance_matrix.copy()
    y_equals[diagonal_idxs] = True
    d2n[y_equals == True] = np.inf
    n_idxs = np.argmin(d2n, axis=1)
    hard_negatives = axs[n_idxs]
    return hard_positives, hard_negatives
Beispiel #22
0
def average_nearest_neighbor_distance(points_list, mark = None):
   
    points = None
    if mark is None:
        
        points = points_list
    else:
        points = list(filter(lambda current_point: current_point.mark['color'] == mark, points_list))

    mean_d = 0
    temp_nearest_neighbor = None
    
    for i, point in enumerate(points):
        for j, otherPoint in enumerate(points):
            if i == j:
                continue
            current_distance = utils.euclidean_distance((point.x, point.y), (otherPoint.x, otherPoint.y))
            if temp_nearest_neighbor is None:
                temp_nearest_neighbor = current_distance
            elif temp_nearest_neighbor > current_distance:
                temp_nearest_neighbor = current_distance
        mean_d += temp_nearest_neighbor
        temp_nearest_neighbor = None
    mean_d /= len(points)

    return mean_d
    def get_torso_subimage(self):
        """
        Extract a subimage of just a torso for given person view.
        Should be better for histograms since contains less surroundings than the whole person box.
        :return: subimage containing only the torso
        """
        image_width = self.original_image.shape[1]
        body_height = int(
            euclidean_distance(self.pose_top_coordinate,
                               self.pose_bottom_coordinate))
        # an average body's width from side is about one third of the height (half of the height from front)
        half_body_width = int(body_height / 6)

        pose_top_left = (min(self.pose_top_coordinate[0],
                             self.pose_bottom_coordinate[0]),
                         min(self.pose_top_coordinate[1],
                             self.pose_bottom_coordinate[1]))
        pose_bottom_right = (max(self.pose_top_coordinate[0],
                                 self.pose_bottom_coordinate[0]),
                             max(self.pose_top_coordinate[1],
                                 self.pose_bottom_coordinate[1]))

        roi_top_left = (max(0, pose_top_left[0] - half_body_width),
                        pose_top_left[1])
        roi_bottom_right = (min(image_width,
                                pose_bottom_right[0] + half_body_width),
                            pose_bottom_right[1])

        return self.original_image[roi_top_left[1]:roi_bottom_right[1] + 1,
                                   roi_top_left[0]:roi_bottom_right[0] + 1]
Beispiel #24
0
 def calculate_scatter(cls, cluster_individuals, center):
     """ Calculates the scatter of cluster.
     """
     return (sum(
         euclidean_distance(individual, center)
         for individual in cluster_individuals) +
             0.) / len(cluster_individuals)
Beispiel #25
0
def enumerate_states(player_model, start_state, graph, action_set):
    start_state_str = start_state.to_str()
    graph.add_node(start_state_str)

    unexplored_states = set([start_state_str])
    explored_states = set()

    while len(unexplored_states) > 0:
        cur_state_str = unexplored_states.pop()
        explored_states.add(cur_state_str)

        cur_state = State.from_str(cur_state_str)

        for action in action_set:
            next_state = player_model.next_state(state=cur_state,
                                                 action=action)
            next_state_str = next_state.to_str()
            if next_state_str not in explored_states and next_state_str not in unexplored_states:
                graph.add_node(next_state_str)
                unexplored_states.add(next_state_str)

            if not graph.has_edge(cur_state_str, next_state_str):
                distance = euclidean_distance((cur_state.x, cur_state.y),
                                              (next_state.x, next_state.y))
                graph.add_edge(cur_state_str,
                               next_state_str,
                               weight=distance,
                               action=[action.to_str()])
            else:
                graph.get_edge_data(cur_state_str,
                                    next_state_str)["action"].append(
                                        action.to_str())

    print('graph size:', len(graph.nodes), len(graph.edges))
    return graph
Beispiel #26
0
def main():
    players = Player.random_player_set(NUMBER_PLAYERS)

    # players = []
    # players.append(Player(Personality(0., 0., 0.)))
    # players.append(Player(Personality(1., 0., 0.)))
    # players.append(Player(Personality(0., 1., 0.)))
    # players.append(Player(Personality(0., 0., 1.)))
    # players.append(Player(Personality(1., 0., 1.)))
    # players.append(Player(Personality(0., 1., 1.)))
    # players.append(Player(Personality(1., 1., 0.)))
    # players.append(Player(Personality(1., 1., 1.)))
    # players.append(Player(Personality(1., 1., 1.)))

    player_vectors = []
    player_favourite_level_map = {}

    levels = Level.random_level_set(NUMBER_LEVELS)
    level_vectors = {level: level.to_vector() for level in levels}

    for player in players:
        player_vector, favourite_level = player.play_levels(levels, level_vectors)
        player_vectors.append(player_vector)
        player_favourite_level_map[player] = favourite_level

    # pprint.pprint(player_vectors)
    # pprint.pprint(level_vectors)
    # pprint.pprint(player_favourite_level_map)

    actual_player_vectors = [player.to_vector() for player in players]

    x_coordinates = []
    x2_coordinates = []
    y_coordinates = []
    for i in range(len(players)):
        for j in range(i + 1, len(players)):
            x = euclidean_distance(player_vectors[i].values(), player_vectors[j].values())
            x2 = euclidean_distance(actual_player_vectors[i].values(), actual_player_vectors[j].values())

            y = euclidean_distance(level_vectors[player_favourite_level_map[players[i]]].values(),
                                   level_vectors[player_favourite_level_map[players[j]]].values())

            x_coordinates.append(x)
            x2_coordinates.append(x2)
            y_coordinates.append(y)

    return x_coordinates, y_coordinates, x2_coordinates
Beispiel #27
0
def set_edges(graph, threshold):
    for v in graph.nodes(data=True):
        for u in (n for n in graph.nodes(data=True) if (n != v)):
            if (v[1]['long'] - threshold < u[1]['long'] < v[1]['long'] + threshold) \
                    and (v[1]['lat'] - threshold < u[1]['lat'] < v[1]['lat'] + threshold):
                graph.add_edge(v[0], u[0], a=v[1]['city'], b=u[1]['city'],
                               weight=utils.euclidean_distance(v[1]['long'], v[1]['lat'], u[1]['long'], u[1]['lat']))
    return graph
Beispiel #28
0
    def count_close_point(self, x, cluster):
        close_point_count = 0

        for j in range(len(cluster)):
            if (euclidean_distance(x, cluster[j]) <= self.epsilon):
                close_point_count += 1

        return close_point_count
Beispiel #29
0
    def find_marker(query, image):
        """
        Searches for the marker object in the image

        Parameters:
                query: picture of the object to search for, also called the query image
                image: image to search within, also called the train image

        return: list containing top left and top right coordinate of rectangle around object
        rtype: list
        """

        orb = cv2.ORB_create()

        kp_q, des_q = orb.detectAndCompute(query, None)
        kp_i, des_i = orb.detectAndCompute(image, None)

        bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)

        matches = bf.match(des_q, des_i)
        matches = sorted(matches, key=lambda x: x.distance)
        top_half = matches[:(int(len(matches) / 2))]

        points = {}

        for match in top_half:
            idx = match.trainIdx
            points[idx] = kp_i[idx].pt

        x = 0
        y = 0
        cnt = 0

        # accumulation for center
        for pair in points.values():
            x += pair[0]
            y += pair[1]
            cnt += 1

        center = (x / cnt, y / cnt)
        top_half = sorted(
            top_half,
            key=lambda x: utils.euclidean_distance(center[0], center[
                1], points[x.trainIdx][0], points[x.trainIdx][1]))
        good_matches = top_half[:(int(len(top_half) / 2))]

        # find bounding rectangle coords
        left = bottom = sys.maxsize
        right = top = -sys.maxsize - 1
        for match in good_matches:
            idx = match.trainIdx
            pt = kp_i[idx].pt
            top = int(max(top, pt[1]))
            left = int(min(left, pt[0]))
            bottom = int(min(bottom, pt[1]))
            right = int(max(right, pt[0]))

        return [(top, left), (bottom, right)]
Beispiel #30
0
 def test_euclidean_distance(self, xs, ys):
     """ Tests equivalence RMSE and computed distance."""
     distance_matrix = euclidean_distance(xs, xs)
     is_ok = True
     for i in range(distance_matrix.shape[0]):
         rmse = np.sqrt(np.mean(np.square(xs[i:i+1] - xs), 1))
         dm_1st_row = distance_matrix[i, :]
         is_ok = is_ok and np.array_equal(dm_1st_row, rmse)
     self.assertEqual(is_ok, True)
Beispiel #31
0
    def init_distance_matrix(self):
        self.distance_matrix = [[0 for x in range(self.data_length)]
                                for x in range(self.data_length)]

        for i in range(self.data_length):
            for j in range(i, self.data_length):
                self.distance_matrix[i][j] = euclidean_distance(
                    self.data[i], self.data[j])
                self.distance_matrix[j][i] = self.distance_matrix[i][j]
Beispiel #32
0
 def reached_waypoint(self, waypoint):
     """ Check if the agent has reached the given waypoint so we 
         advance to the next one. Reaching means being in the 
         waypoint circle
     """
     if euclidean_distance((self._position.x, self._position.y), waypoint.position) <= waypoint.radius:
         return True
     else:
         return False
Beispiel #33
0
def avg_group_linkage(subcluster_1, subcluster_2):
    flattened_1 = flatten(subcluster_1)
    flattened_2 = flatten(subcluster_2)
    
    # find mean / centroid
    avg_1 = tuple(sum(elements)/len(flattened_1) for elements in zip(*flattened_1))
    avg_2 = tuple(sum(elements)/len(flattened_2) for elements in zip(*flattened_2))
    # calculate distance between centroid
    return euclidean_distance(avg_1, avg_2)
Beispiel #34
0
 def reached_waypoint(self, waypoint):
     """ Check if the agent has reached the given waypoint so we 
         advance to the next one. Reaching means being in the 
         waypoint circle
     """
     if euclidean_distance((self._position.x, self._position.y), waypoint.position) <= waypoint.radius:
         return True
     else:
         return False
Beispiel #35
0
 def find_neighbors(self) -> list:
     n_rows, n_col = self.S.shape
     neighbors_list = [None for i in range(0, n_rows)]
     for i in range(0, n_rows):
         distance_vector = euclidean_distance(self.S[i, :], self.S)
         distance_vector[i] = np.inf  # So that point isn't his own neighbor
         neighbors_list[i] = np.where(
             distance_vector <= self.nbr_max_distance)
     return neighbors_list
Beispiel #36
0
 def _closest_centroid(self, sample, centroids):
     """ Return the index of the closest centroid to the sample """
     closest_i = 0
     closest_dist = float('inf')
     for i, centroid in enumerate(centroids):
         distance = euclidean_distance(sample, centroid)
         if distance < closest_dist:
             closest_i = i
             closest_dist = distance
     return closest_i
Beispiel #37
0
    def calculate_distances(self):
        """Calculate distance between nodes and save it to a matrix."""

        distances = np.zeros((self.n, self.n))

        for i, node_i in enumerate(self.nodes):
            for j, node_j in enumerate(self.nodes):
                distances[i][j] = utils.euclidean_distance(node_i, node_j)

        return distances
Beispiel #38
0
    def _circle_intersection(self, circle, point):
        """ Compute the distance and point on the boundary of the circle
            intersected by a line from its center to the point
        """
        dist = euclidean_distance((circle[0], circle[1]), point) - circle[2]
        vun = vec2d((circle[0] - point[0]), (circle[1] - point[1]))
        v = vun.normalized()

        x, y = (point[0] + dist * v.x), (point[0] + dist * v.x)

        return dist, (x, y)
Beispiel #39
0
def average_nearest_neighbor_distance(points):
    mean_d = 0
    for i in points:
        dist_nearest=1e9
        for j in points:
            dist = utils.euclidean_distance(i, j)
            if i==j:
                continue
            elif dist < dist_nearest:
                dist_nearest = dist;
        mean_d += dist_nearest;
    mean_d=mean_d/(len(points))
    return mean_d
Beispiel #40
0
    def _line_intersection(self, line, point):
        """ Fine the point of intersetion of a line and a point 
            Line is given as (x1,y1, x2,y2), point (x,y)

            based on http://paulbourke.net/geometry/pointlineplane/
        """
        den = euclidean_distance((line[0],line[1]), (line[2],line[3]))
        x1, y1, x2, y2 = line[0], line[1], line[2], line[3]
        x3, y3 = point[0], point[1]

        u = ( ((x3-x1) * (x2-x1)) + ((y3-y1) * (y2-y1)) ) / den

        x, y = (x1 + u * (x2-x1)), (y1 + u * (y2-y1))
        dist = euclidean_distance((x,y), point)

        # pygame.draw.circle(self.screen, SIM_COLORS['aqua'], 
        #         (int(x*SCALE), int(y*SCALE)), 
        #         int(40), 
        #         0)
        # print dist*SCALE, (x*SCALE,y*SCALE)

        return dist, (x, y)
Beispiel #41
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('img', help=('Path of the image to perform the'
                        ' transform'))
    parser.add_argument('--rmin', type=int, help='rmin parameter', default=23)
    parser.add_argument('--rmax', type=int, help='rmax parameter', default=48)

    args = parser.parse_args()

    try:
        with open(args.img, 'rb'):
            pass
    except IOError:
        print >> sys.stderr, "%s could not be opened" % args.img
        return 1

    rmin_range = (0, 100)
    if not (rmin_range[0] < args.rmin < rmin_range[1]):
        print >> sys.stderr, "rmin should be between %d and %d" % rmin_range
        return 2

    if not (rmin_range[0] < args.rmax < rmin_range[1]):
        print >> sys.stderr, "rmax should be between %d and %d" % rmin_range
        return 2

    if args.rmin >= args.rmax:
        print >> sys.stderr, 'rmin should be less than rmax'
        return 3

    aimg = image2array(args.img)
    freq_ = fft(aimg)
    shift_freq = fftshift(freq_)

    center = (shift_freq.shape[0] / 2, shift_freq.shape[1] / 2)

    distance_array = euclidean_distance(shift_freq, center)

    mask = (distance_array < args.rmin) != (distance_array > args.rmax)

    shift_freq_cpy = shift_freq.copy()

    shift_freq_cpy[mask] = 0

    output = fft(fftshift(shift_freq_cpy, True), True)

    plot([aimg, prepare_show(shift_freq), prepare_show(shift_freq_cpy),
          prepare_show(output, False)])

    return 0
Beispiel #42
0
def average_nearest_neighbor_distance_marks(points,mark=None):
    mean_d = 0
    for i in range(len(points)):
        dist_nearest=1e9
        for j in range(len(points)):
            temp_p1 = (points[i].x, points[i].y)
            temp_p2 = (points[j].x, points[j].y)
            dist = utils.euclidean_distance(temp_p1, temp_p2)
            if temp_p1 == temp_p2:
                continue
            elif dist < dist_nearest:
                dist_nearest = dist;
        mean_d += dist_nearest;
    mean_d=mean_d/(len(points))
    return mean_d
    def _calculate_distances_to_points(self):
        """
            Method calculates the distance of each point to the neighbouring points (closed loop assumed)

            returns:
                distance matrix of dimensions (num_images, num_landmarks)
        """
        distances = np.zeros((len(self.points), len(self.points[0]) / 2))
        collector = DataManipulations.DataCollector(None)

        for img in range(len(self.points)):
            collector.read_vector(self.points[img, :])
            points = collector.as_matrix()

            for ref_point_ind in range(len(points)):
                distances[img, ref_point_ind] = sum([utils.euclidean_distance(points[ref_point_ind, :], x) for x in points])

        return distances
Beispiel #44
0
 def write_your_own(gj):


 def mean_center(points):
     """
     Given a set of points, compute the mean center

     Parameters
     ----------
     points : list
          A list of points in the form (x,y)

     Returns
     -------
     x : float
         Mean x coordinate

     y : float
         Mean y coordinate
     """


     sums = map(sum,zip(*points))
     sumsL = list(sums)
     avgs = map(lambda xy: xy/len(points),sumsL)
     avgsL = list(avgs)
     x = avgsL[0]
     y = avgsL[1]

     return x,y

 def average_nearest_neighbor_distance(points):
     """
     Given a set of points, compute the average nearest neighbor.

     Parameters
     ----------
     points : list
              A list of points in the form (x,y)

     Returns
     -------
     mean_d : float
              Average nearest neighbor distance

     References
     ----------
     Clark and Evan (1954 Distance to Nearest Neighbor as a
      Measure of Spatial Relationships in Populations. Ecology. 35(4)
      p. 445-453.
     """

      shDistL =[]
     mean_sum = 0
     for point in points:
         shortestDistance = 9999999999
         for dpoint in points:
             if point != dpoint:
                 dist = euclidean_distance(point, dpoint)
                 if(shortestDistance > dist):
                     shortestDistance = dist

         shDistL.append(shortestDistance)
         mean_sum = shortestDistance + mean_sum

     print(shDistL)
     sums = sum(shDistL)
     mean_d = mean_sum/len(shDistL)
     return mean_d