import heapq


def produce_tng_blosum(seq_file, blosum_dict, n):
    """Generate top-n-gram by blosum62 matrix.
    :param seq_file: the sequence file containing one sequence.
    :param blosum_dict: the dict which stores the blosum62 matrix.
    :param n: the n most frequent amino acids in the amino acid frequency profiles.
    """
    tng_list = []
    with open(seq_file, 'r') as f:
        for line in f:
            if line.strip().startswith('>'):
                continue
            else:
                line = line.strip()
                for amino in line:
                    amino_blosum = blosum_dict[amino]
                    data = heapq.nlargest(n, enumerate(amino_blosum), key=lambda x:x[1])
                    if n == 1:
                        index = data[0][0]
                        new_alpha = blosum_dict['alphas'][index]
                    else:
                        new_alpha = ''
                        indices, val = zip(*data)
                        for i in indices:
                            new_alpha += blosum_dict['alphas'][i]
                    tng_list.append(new_alpha)
    return tng_list