def calculate_threshold(sorted_predictions, purity_class, minimum_purity):
    """
    Get the threshold with the purity heuristic.

    Purity is defined as the precision metric where, where the threshold is treated as a binary classifier for the
    task of deciding whether an ngram is important or not - i.e., whether the label of the original sentence matches
    the identity class of the filter.

    :param sorted_predictions: all of the predictions of the interpretation dataset,
           sorted by the activation strength of the max-pooling layer of the filter in question
    :param purity_class: the identity class of the filter in question
    :param minimum_purity: the minimum purity value to be achieved by the threshold
    :return: the lowest threshold that satisfies the purity level
    """
    ix = len(sorted_predictions) - 1

    count = sum(sorted_predictions[:ix] == purity_class)
    purity = count / ix

    while purity < minimum_purity:
        ix -= 1
        if ix <= 0:
            return 0, 0

        if sorted_predictions[ix] == purity_class:
            count -= 1

        purity = count / ix

    return ix, purity