#!/usr/bin/env python3

# kendall.py *.lendiff test_sentence_bleu_result


def cmb(n, r):
    if n - r < r:
        r = n - r
    if r == 0:
        return 1
    if r == 1:
        return n

    numerator = [n - r + k + 1 for k in range(r)]
    denominator = [k + 1 for k in range(r)]

    for p in range(2, r + 1):
        pivot = denominator[p - 1]
        if pivot > 1:
            offset = (n - r) % p
            for k in range(p - 1, r, p):
                numerator[k - offset] /= float(pivot)
                denominator[k] /= float(pivot)

    result = 1
    for k in range(r):
        if numerator[k] > 1:
            result *= int(numerator[k])

    return result


def kendall(list1, list2):
    if len(list1) != len(list2):
        print("Kendall's rank correlation coefficient can not be calculated because the file length is different.")
        sys.exit(1)
    K = L = 0
    n = len(list1)
    for i in range(n):
        for j in range(i + 1, n):
            if (list1[i] > list1[j] and list2[i] > list2[j])\
                    or (list1[i] < list1[j] and list2[i] < list2[j]):
                K += 1
            else:
                L += 1
    tau = (K - L) / float(cmb(n, 2))
    return tau


import sys

path1 = sys.argv[1]
path2 = sys.argv[2]

buff1 = []
buff2 = []
for l1, l2 in zip(open(path1), open(path2)):
    buff1.append(float(l1.strip()))
    buff2.append(float(l2.strip()))

tau = kendall(buff1, buff2)

print('kendall = ' + str(tau))
with open(path1 + '_sentBLEU.kendall', 'w') as f:
    f.write(str(tau))
