def applyHungarian(quick_scores_matrix):
    """ 

    Function to use the hangarian matrix after the quick scores matrix is ready
    
    Parameters: 
       (nxm list)  quick_scores_matrix:  a matrix containing the quick scores of 
                                          the players.
        
    Returns: 
       (tuple): result_index the index of the the optimal results in the matrix
       (tuple): heroes_index the location of the optimal hero in the matrix
       (tuple): scores_index the location of the optimal score in the matrix

    """

    # Now the Hungarian part
    hungarian = h.Hungarian(quick_scores_matrix, is_profit_matrix=False)
    hungarian.calculate()
    result_index = hungarian.get_results()

    result_index.sort()
    heroes_index = []
    scores_index = []

    for item in result_index:
        heroes_index.append(item[0])
        scores_index.append(item[1])

    return result_index, heroes_index, scores_index
예제 #2
0
 def better_hungarian(self, piece_index, valid_directions, pos):
     '''
     Get the hungarian arrangement around a piece
     :param piece_index: the piece's index
     :param valid_directions: direction with empty cells as list [T, R, L, B]
     :return: list of tuples (index, direction) where index is the index of the matching piece 
         and the direction is the direction relative to the piece
     '''
     # Get i * unassigned
     D = self.board.get_distance_matrix()
     # row_distance_matrix = get_row
     # print(row_distance_matrix)
     # Convert to 2d array
     H = self.get_H_matrix(
         pos)  # row_distance_matrix#.reshape(row_distance_matrix.shape[1], row_distance_matrix.shape[2])
     # Take only valid directions
     H = H[:, valid_directions]
     # Calculate hungarian
     hungarian = Hungarian.Hungarian(H)
     hungarian.calculate()
     # Get the correct indexes of unassigned cells and valid directions
     result = [(self.board.get_unassigned_cells()[index],
                valid_directions[direction]) for (index, direction) in
               hungarian.get_results()]
     cost = hungarian.get_total_potential()
     return result, cost
예제 #3
0
 def gnnsf(self, xk_1, position, H, th=10000000000000000000000):
     pos = np.matmul(H, xk_1).T
     n = xk_1.shape[1]
     m = position.shape[0]
     p = np.expand_dims(pos, axis=1)
     p = np.repeat(p, m, axis=1)
     mea = np.expand_dims(position, axis=1)
     mea = np.repeat(mea, n, axis=1)
     mea = mea.transpose((1, 0, 2))
     s = p - mea
     s = sum([np.square(s[:, :, i]) for i in range(self.dimension)])
     # arg_min = np.argmin(s, axis=1)
     # print(arg_min)
     solver = hungarian.Hungarian(s)
     solver.calculate()
     res = solver.get_results()
     arg_min = [i[0] for i in res]
     s_min = np.min(s, axis=1)
     min_dis = s_min
     l = np.less(min_dis, th)
     wl = np.where(l == False)[0]
     z = position[arg_min]
     z = np.delete(z, wl, axis=0).T
     z_min = np.min(s, axis=0)
     l1 = np.greater(z_min, 625)
     wl1 = np.where(l1 == True)[0]
     new_x = position[wl1, :]
     return z, wl, new_x
예제 #4
0
def associate(first,next,method="greedy"): # take first and next position and return pair of index associated
    thresh = 50
    first = [(first[i],i) for i in range(len(first))]
    next = [(next[i],i) for i in range(len(next))]
    # print("first",first)
    # print("next",next)
    if method == "greedy":
        first = sorted(first, key=lambda x: np.sum(np.power(x[0][1],2)),reverse=True)
        pair = []
        for i in first:
            if len(next) != 0:
                distance = [np.sqrt(np.sum(np.power(n[0]-i[0],2))) for n in next]
                if np.min(distance) <= thresh:
                    pair.append([i[1],next[np.argmin(distance)][1]])
                    remove_by_key(next,next[np.argmin(distance)][1])
        return pair
    if method == "hungarian":
        k = max(len(first),len(next))
        dis_mat = np.zeros(shape=(k,k))
        for i in range(len(first)):
            for j in range(len(next)):
                dis_mat[i][j] = np.sqrt(np.sum(np.power(first[i][0] - next[j][0],2)))
        dis_mat[dis_mat>=thresh] = 10000
        solver = hungarian.Hungarian(dis_mat)
        solver.calculate()
        res = solver.get_results()
        ret = [i for i in res if dis_mat[i[0]][i[1]] < thresh]
        if len(first) > len(next):
            ret = [i for i in ret if i[1] < len(next)]
        if len(first) < len(next):
            ret = [i for i in ret if i[0] < len(first)]
        return ret
예제 #5
0
def matching_preference(class_size, associate_dict, manager_dict):

    profit_matrix = [[0 for i in range(class_size)] for j in range(class_size)]

    for each_associate in associate_dict.keys():

        matrix_associate_position = each_associate - 101
        associate_preference_list = associate_dict[each_associate]

        for manager in associate_preference_list:

            cost_associated = associate_preference_list.index(manager) + 1
            matrix_manager_position = manager - 201

            profit_matrix[matrix_associate_position][matrix_manager_position] += cost_associated
        """
        total_manager_list = list(range(201,class_size+201))
        remaining_manager_set = set(total_manager_list) - set(associate_preference_list)
        remaining_manager_list = list(remaining_manager_set)

        for remaining_manager in remaining_manager_list:
            matrix_manager_position = remaining_manager - 201

            profit_matrix[matrix_associate_position][matrix_manager_position] += class_size
        """
    for each_manager in manager_dict.keys():

        matrix_manager_position = each_manager - 201
        manager_preference_list = manager_dict[each_manager]

        for associate in manager_preference_list:

            cost_associated = manager_preference_list.index(associate) + 1
            matrix_associate_position = associate - 101

            profit_matrix[matrix_associate_position][matrix_manager_position] += cost_associated
        """
        total_associate_list = list(range(101, class_size + 101))
        remaining_associate_set = set(total_associate_list) - set(manager_preference_list)
        remaining_associate_list = list(remaining_associate_set)

        for remaining_associate in remaining_associate_list:
            matrix_associate_position = remaining_associate - 101

            profit_matrix[matrix_associate_position][matrix_manager_position] += class_size
        """
    hungarian_result = hungarian.Hungarian(profit_matrix, is_profit_matrix=True)
    hungarian_result.calculate()

    print("Calculated value:\t", hungarian_result.get_total_potential())  # = 543
    print("Results:\n\t", hungarian_result.get_results())

    return profit_matrix
예제 #6
0
 def get_hungarian(self, piece_index, valid_directions):
     '''
     Get the hungarian arrangement around a piece
     :param piece_index: the piece's index
     :return: list of tuples (index, direction) where index is the index of the matching piece 
         and the direction is the direction relative to the piece
     '''
     H = HF.tuple_list_to_2d(self.D[piece_index, self.indexes])
     hungarian = Hungarian.Hungarian(H)
     hungarian.calculate()
     results = [(self.indexes[index], direction)
                for (index, direction) in hungarian.get_results()]
     return self.take_valid_direction(results, valid_directions)
예제 #7
0
    def hungarian_matching(self):
        """
		Solve the Hungarian matching problem to find the best matches between columns and rows based on
		values in the specified similarity matrix.
		"""
        # apply hungarian matching
        h = hungarian.Hungarian()
        C = h.make_cost_matrix(self.S)
        h.calculate(C)
        results = h.get_results()
        # compute score based on similarities
        score = 0.0
        for (row, col) in results:
            score += self.S[row, col]
        score /= len(results)
        return (score, results)
예제 #8
0
파일: gmm.py 프로젝트: kbu929/PRML-1
def compute_statistics(clusters, ref_clusters, K):
    mat = make_ce_matrix(clusters, ref_clusters, K)
    hung_solver = hg.Hungarian()
    rs = hung_solver.compute(mat, False)

    tmp_clusters = np.array(clusters)
    for old, new in rs:
        clusters[np.where(tmp_clusters == old)] = new
        #print old, new

    #print clusters, ref_clusters
    nbrIts = 0
    for k in range(K):
        ref = np.where(ref_clusters == k)[0]
        clust = np.where(clusters == k)[0]
        nbrIts += len(np.intersect1d(ref, clust))
        print len(np.intersect1d(ref, clust))
    return nbrIts
예제 #9
0
	def score(self, clusts1, clusts2, format='array', format1=None, format2=None):

		if format1 == None:
			format1 = format

		if format2 == None:
			format2 = format

		if format1=='list':
			clusts1_=convertIndexToPos(clusts=clusts1,N=self.N)
		elif format1=='array':
			clusts1_=convertClusterStringToPos(clusts=clusts1,N=self.N)
		elif format1 == 'bin':
			clusts1_ = clusts1
		else:
			raise ValueError("Format not accepted: {}".format(format1))


		if format2=='list':
			clusts2_=convertIndexToPos(clusts=clusts2, N=self.N)
		elif format2=='array':
			clusts2_=convertClusterStringToPos(clusts=clusts2, N=self.N)
		elif format2 == 'bin':
			clusts2_ = clusts2			
		else:
			raise ValueError("Format not accepted: {}".format(format2))

		nclusts1_ = clusts1_.shape[0]
		nclusts2_ = clusts2_.shape[0]

		match_matrix = clusts1_.dot(clusts2_.T)

		self.clusts1_=clusts1_
		self.clusts2_=clusts2_

		# cost/profit matrix is automatically padded to be square with this module
		hungAcc = hungarian.Hungarian(match_matrix, is_profit_matrix=True)
		hungAcc.calculate()

		self.match_count = hungAcc.get_total_potential()
		self.accuracy = np.float(self.match_count) / self.N
예제 #10
0
def get_emotions(bboxes, images):

    cur = get_emotions.current_faces
    m, n = len(cur), len(bboxes)
    new = [FaceBBox(bboxes[i]) for i in range(n)]
    dist_matrix = numpy.ones((m, n)) * 1e10

    for i in range(m):
        for j in range(n):
            dist_matrix[i, j] = numpy.linalg.norm(cur[i].center() -
                                                  new[j].center())

    solver = hungarian.Hungarian()
    solver.calculate(dist_matrix)

    cur_prime = [None for i in range(n)]
    for edge in solver.get_results():
        cur_prime[edge[1]] = cur[edge[0]]
    cur = get_emotions.current_faces = cur_prime
    for j in range(n):
        if cur[j] == None:
            new[j].id = get_emotions.next_face_id
            get_emotions.next_face_id += 1
            cur[j] = new[j]

    assert n == len(cur), "Some bounding box was lost"

    if not feedforward.running:
        if feedforward.result != None:
            for result in feedforward.result:
                for face in cur:
                    if face.id == result[0]:
                        face.emotion = result[1]
            feedforward.result = None
        if len(images) != 0:
            thread = threading.Thread(target=feedforward, args=(cur, images))
            thread.start()

    return [face.emotion for face in cur]