#!/usr/bin/python3

import numpy as np
import subprocess

def parse_output(s):
    ret = []
    current_dim = None
    for line in s.splitlines():
        if line.startswith("persistence intervals in dim"):
            splitline = line.rstrip().rstrip(":").split(" ")
            assert(len(splitline) == 5)
            current_dim = int(splitline[-1])
            while len(ret) < current_dim + 1:
                ret.append(([], []))
        elif line.startswith(" ["):
            splitline = line.lstrip(" [").rstrip().rstrip(")").split(",")
            assert(len(splitline) == 2)
            if splitline[1].strip() == "":
                ret[current_dim][1].append(float(splitline[0]))
            else:
                ret[current_dim][0].append((float(splitline[0]), float(splitline[1])))

    return ret

def main():
    tests = [(None, "lower-distance", 2, "sphere_3_192.lower_distance_matrix"),
             (None, "distance", 2, "projective_plane.csv"),
             (None, "dipha", 2, "projective_plane.dipha"),
             (None, "lower-distance", 2, "projective_plane.lower_distance_matrix"),
             (2, "lower-distance", 2, "sphere_3_192.lower_distance_matrix"),
             (2, "distance", 2, "projective_plane.csv"),
             (2, "dipha", 2, "projective_plane.dipha"),
             (2, "lower-distance", 2, "projective_plane.lower_distance_matrix")]
             
    for (coeff, format, dim, prefix) in tests:
        if coeff is None:
            print("Running test %s." %(prefix))
            proc = subprocess.Popen(["/usr/bin/ripser", "--dim", str(dim), "--format", format, "examples/%s" %(prefix)], stdout=subprocess.PIPE)
        else:
            print("Running test %s with coefficients in Z/%dZ." %(prefix, coeff))
            proc = subprocess.Popen(["/usr/bin/ripser-coeff", "--modulus", str(coeff), "--dim", str(dim), "--format", format, "examples/%s" %(prefix)], stdout=subprocess.PIPE)
            
        output = proc.communicate()[0].decode("utf-8")
        assert(proc.returncode == 0)
        pd = parse_output(output)

        with open("debian/tests/reference/%s.txt" %(prefix), "r") as f:
            pd_ref = parse_output(f.read())

        assert(len(pd) == len(pd_ref))

        for d in range(0, len(pd)):
            fin = np.array(sorted(pd[d][0]))
            inf = np.array(sorted(pd[d][1]))
            print("Finite bars in dimension %d:" %(d))
            print(fin)
            print("Infinite bars in dimension %d:" %(d))
            print(inf)
            
            fin_ref = np.array(sorted(pd_ref[d][0]))
            inf_ref = np.array(sorted(pd_ref[d][1]))

            assert(fin.shape == fin_ref.shape)
            assert(inf.shape == inf_ref.shape)

            np.testing.assert_allclose(fin, fin_ref)
            np.testing.assert_allclose(inf, inf_ref)

            print("------")

        print("-------------------------------------------------")
        

if __name__ == "__main__":
    main()
