from dionysus import Simplex, Filtration, StaticPersistence, \
                     vertex_cmp, data_cmp, data_dim_cmp, \
                     DynamicPersistenceChains
from math import sqrt

"""
Explanation: Persistent homology
This demo explains how to use Dionysus for persistent homology computation. First necessary imports.
End of explanation
"""


scx = [Simplex((2,),        0),                 # C
       Simplex((0,),        1),                 # A
       Simplex((1,),        1),                 # B
       Simplex((0,1),       2),                 # AB
       Simplex((1,2),       3),                 # BC
       Simplex((0,2),       3),                 # AC
       Simplex((0,1,2),     4),                 # ABC
]

"""
Explanation: We will compute persistent homology of a 2-simplex (triangle) ABC. The filtration is as follows: first the top vertex (C) of the triangle is added, then the rest of vertices (A and B) followed by the the bottom edge (AB), then the rest of the edges (AC and BC) and finally the triangle is filled in (ABC).
End of explanation
"""


f = Filtration(scx, data_cmp)            
p = DynamicPersistenceChains(f)
p.pair_simplices()
smap = p.make_simplex_map(f)

"""
Explanation: Now the persistent homology is computed.
End of explanation
"""


print "{:>10}{:>10}{:>10}{:>10}".format("First", "Second", "Birth", "Death")
for i in (i for i in p if i.sign()):
    b = smap[i]
    if i.unpaired():
        print "{:>10}{:>10}{:>10}{:>10}".format(b, '', b.data, "inf")
    else:
        d = smap[i.pair()]
        print "{:>10}{:>10}{:>10}{:>10}".format(b, d, b.data, d.data)

"""
Explanation: Now output the computed persistence diagram. For each critical cell that appears in the filtration the time of Birth and Death is given as well as the cell that kills it (its pair). The features that persist forever have Death value set to inf.
End of explanation
"""


