import math


def ppmi_similarity(target_word, context_word, co_occurrences, word_id, word_frequency, count):
    """
    Compute PPMI as log2(P(word1,word2)/(P(word1)*P(word2)))

    :param target_word: the target word
    :param context_word: the context word
    :param co_occurrences: the number of co-occurrences between each pair of words in the corpus
    :param word_id: the word to wordID mapping used in co_occurrences
    :param word_frequency: the frequency of each word in the corpus
    :param count: the number of word occurrences in the corpus
    :return:
    """
    target_id = word_id[target_word]
    context_id = word_id[context_word]
    target_occurrences = word_frequency[target_word]
    context_occurrences = word_frequency[context_word]
    if context_id not in co_occurrences[target_id]:
        return 0
    cooccurrence_prob = co_occurrences[target_id][context_id]/target_occurrences
    target_occurrence_prob = target_occurrences/count
    context_occurrence_prob = context_occurrences/count
    pmi = math.log2(cooccurrence_prob/(target_occurrence_prob*context_occurrence_prob))
    if pmi < 0:
        return 0
    else:
        return pmi