Ejemplo n.º 1
0
def lsf(values_filename, simplices_filename):
    # Read vertices
    vertices = []
    with open(values_filename) as f:
        for line in f:
            if line.startswith('#'): continue
            vertices.append(float(line.split()[0]))

    # Read simplices
    fltr = Filtration()
    with open(simplices_filename) as f:
        for line in f:
            if line.startswith('#'): continue
            fltr.append(Simplex(map(int, line.split())))
    fltr.sort(lambda x,y: max_vertex_cmp(x,y,vertices))

    # Compute persistence
    p = StaticPersistence(fltr)
    p.pair_simplices()
    
    # Output the persistence diagram
    smap = p.make_simplex_map(fltr)
    for i in p:
        if not i.sign(): continue

        b = smap[i]
        d = smap[i.pair()]

        if i.unpaired():
            print b.dimension(), max_vertex(b, vertices), "inf"
            continue

        print b.dimension(), max_vertex(b, vertices), max_vertex(d, vertices)
Ejemplo n.º 2
0
def main(filename, skeleton, max):
    points = np.random.rand(120, 3)  #[p for p in points_file(filename)]
    print(points)
    distances = PairwiseDistances(points)
    # distances = ExplicitDistances(distances)           # speeds up generation of the Rips complex at the expense of memory usage
    rips = Rips(distances)
    print time.asctime(), "Rips initialized"

    simplices = Filtration()
    rips.generate(skeleton, max, simplices.append)
    print time.asctime(), "Generated complex: %d simplices" % len(simplices)

    # While this step is unnecessary (Filtration below can be passed rips.cmp),
    # it greatly speeds up the running times
    for s in simplices:
        s.data = rips.eval(s)
    print time.asctime(), simplices[0], '...', simplices[-1]

    simplices.sort(
        data_dim_cmp
    )  # could be rips.cmp if s.data for s in simplices is not set
    print time.asctime(), "Set up filtration"

    p = StaticPersistence(simplices)
    print time.asctime(), "Initialized StaticPersistence"

    p.pair_simplices()
    print time.asctime(), "Simplices paired"

    print "Outputting persistence diagram"
    smap = p.make_simplex_map(simplices)
    for i in p:
        if i.sign():
            b = smap[i]

            if b.dimension() >= skeleton: continue

            if i.unpaired():
                print b.dimension(), b.data, "inf"
                continue

            d = smap[i.pair()]
            print b.dimension(), b.data, d.data
Ejemplo n.º 3
0
    def run(self):
        self.rips = Rips(self.distances)
        self.filtration = Filtration()

        self._rips_generate()
        self._filtration_sort()

        self.dynamic_persistence = DynamicPersistenceChains(self.filtration)

        self._pair_simplices()
        self._make_simplex_map()
Ejemplo n.º 4
0
def vietoris_rips(X, skeleton=5, max=10000):
    """ Generate the Vietoris-Rips complex on the given set of points in 2D.
    Only simplexes up to dimension skeleton are computed.
    The max parameter denotes the distance cut-off value.
    """
    distances = PairwiseDistances(X.tolist())
    rips = Rips(distances)
    simplices = Filtration()
    rips.generate(skeleton, max, simplices.append)
    for sx in simplices:
        sx.data = rips.eval(sx)
    return simplices
def compute_dgm_from_edges(
    all_edges_for_diagrams, astuple: bool = True, negate: bool = True
):
    _prepare_edges_for_diagram(all_edges_for_diagrams)

    # Dionysus computations (persistent diagrams)
    # logger.info(f"Before filtration")
    #logger.info(f"len all_edges_for_diagrams = {len(all_edges_for_diagrams)}")

    f = Filtration()
    for vertices, weight in all_edges_for_diagrams:
        if negate:
            timing = -weight.round(3)
        else:
            timing = weight.round(3)
        f.append(Simplex(vertices, timing))
    f.sort()
    #logger.info(f"{f}")
    m = homology_persistence(f)
    dgms = init_diagrams(m, f)
    dgm = dgms[0]

    if not astuple:
        return dgm
    else:
        ret = list()
        for pt in dgm:
            # ret.append((pt.birth, pt.death if not np.isposinf(pt.death) else 2**64))
            ret.append((round(pt.birth, 2), round(pt.death, 2)))
        return ret
Ejemplo n.º 6
0
def lsf(values_filename, simplices_filename):
    # Read vertices
    vertices = []
    with open(values_filename) as f:
        for line in f:
            if line.startswith('#'): continue
            vertices.append(float(line.split()[0]))

    # Read simplices
    fltr = Filtration()
    with open(simplices_filename) as f:
        for line in f:
            if line.startswith('#'): continue
            fltr.append(Simplex(map(int, line.split())))
    fltr.sort(lambda x, y: max_vertex_cmp(x, y, vertices))

    # Compute persistence
    p = StaticPersistence(fltr)
    p.pair_simplices()

    # Output the persistence diagram
    smap = p.make_simplex_map(fltr)
    for i in p:
        if not i.sign(): continue

        b = smap[i]
        d = smap[i.pair()]

        if i.unpaired():
            print b.dimension(), max_vertex(b, vertices), "inf"
            continue

        print b.dimension(), max_vertex(b, vertices), max_vertex(d, vertices)
Ejemplo n.º 7
0
def persistence_diagram(cx, max_r, X=[], n_intervals=10, max_dim=2):
    """ Compute persistence diagrams for cx, given max_r as the maximum
    distance between two points upto max_dim dimensions.
    """
    cx.sort(data_dim_cmp)
    print "Current X:"
    print X
    if n_intervals:
        cx = fix_data(cx, max_r, n_intervals=n_intervals)
    f = Filtration(cx, data_dim_cmp)
    p = StaticPersistence(f)
    p.pair_simplices()
    return to_dict(p, f, max_dim)
Ejemplo n.º 8
0
def main(filename, skeleton, max):
    points = [p for p in points_file(filename)]
    distances = PairwiseDistances(points)
    # distances = ExplicitDistances(distances)           # speeds up generation of the Rips complex at the expense of memory usage
    rips = Rips(distances)
    print time.asctime(), "Rips initialized"

    simplices = Filtration()
    rips.generate(skeleton, max, simplices.append)
    print time.asctime(), "Generated complex: %d simplices" % len(simplices)

    # While this step is unnecessary (Filtration below can be passed rips.cmp), 
    # it greatly speeds up the running times
    for s in simplices: s.data = rips.eval(s)
    print time.asctime(), simplices[0], '...', simplices[-1]

    simplices.sort(data_dim_cmp)             # could be rips.cmp if s.data for s in simplices is not set
    print time.asctime(), "Set up filtration"

    p = StaticPersistence(simplices)
    print time.asctime(), "Initialized StaticPersistence"

    p.pair_simplices()
    print time.asctime(), "Simplices paired"

    print "Outputting persistence diagram"
    smap = p.make_simplex_map(simplices)
    for i in p:
        if i.sign():
            b = smap[i]

            if b.dimension() >= skeleton: continue

            if i.unpaired():
                print b.dimension(), b.data, "inf"
                continue

            d = smap[i.pair()]
            print b.dimension(), b.data, d.data
Ejemplo n.º 9
0
def compute_rips_diagram(points, max_hom, max_death):
    """Workflow to construct a Persistence Diagram object from the level sets
    of the given function.

    Arguments
        1.

    Returns
        1.

    Raises
        None

    """

    # get pairwise distances
    distances = PairwiseDistances(points)

    rips = Rips(distances)
    simplices = Filtration()
    rips.generate(int(max_hom + 1), float(max_death), simplices.append)

    # step to speed up computation
    for s in simplices:
        s.data = rips.eval(s)

    # compute persistence
    simplices.sort(data_dim_cmp)
    p = StaticPersistence(simplices)
    p.pair_simplices()

    # construct persistence diagram
    smap = p.make_simplex_map(simplices)
    pd = _persistence_diagram_rips(smap, p, max_hom, max_death)

    return (dg.PersistenceDiagram(PD=pd))
Ejemplo n.º 10
0
def compute_grid_diagram(f, sublevel=True, max_death=None):
    """Workflow to construct a Persistence Diagram object from the level sets
    of the given function.

    Arguments
        1.

    Returns
        1.

    Raises
        1.

    """

    # assume kernel methods are used here
    if sublevel == False and max_death is None:
        max_death = 0

    # construct list of times the simplicies are
    # added to the simplicial complex
    filtration = levelset_filtration_2d(f=f, sublevel=sublevel)

    # construct a simplex list for Dionysus
    scomplex = [Simplex(a, b) for (a, b) in filtration]

    # construct Dionysus filtration object
    filt = Filtration(scomplex, data_cmp)

    # compute persistent homology
    p = StaticPersistence(filt)
    p.pair_simplices(True)
    smap = p.make_simplex_map(filt)

    # generate numpy persistence diagram
    pd = _persistence_diagram_grid(smap, p, max_death)

    if not sublevel:
        pd[:, 1:] *= -1
        pd = pd[:, (0, 2, 1)]

    return (dg.PersistenceDiagram(PD=pd))
Ejemplo n.º 11
0
# Computes the persistence diagram of the alpha shapes in both 2D and 3D 
# (decided dynamically based on the input file)

from    dionysus        import Filtration, StaticPersistence, data_dim_cmp, vertex_cmp, \
                               fill_alpha3D_complex, fill_alpha2D_complex, points_file
from    sys             import argv, exit
from    math            import sqrt


if len(argv) < 2:
    print "Usage: %s POINTS" % argv[0]
    exit()

points = [p for p in points_file(argv[1])]
f = Filtration()
if   len(points[0]) == 2:           # 2D
    fill_alpha2D_complex(points, f)
elif len(points[1]) == 3:           # 3D
    fill_alpha3D_complex(points, f)

print "Total number of simplices:", len(f)

f.sort(data_dim_cmp)
print "Filtration initialized"

p = StaticPersistence(f)
print "StaticPersistence initialized" 

p.pair_simplices()
print "Simplices paired"
Ejemplo n.º 12
0
                     vertex_cmp, data_cmp, data_dim_cmp \

complex = [Simplex((0,),        0),                 # A
           Simplex((1,),        1),                 # B
           Simplex((2,),        2),                 # C
           Simplex((0,1),       2.5),               # AB
           Simplex((1,2),       2.9),               # BC
           Simplex((0,2),       3.5),               # CA
           Simplex((0,1,2),     5)]                 # ABC

print "Complex:", complex
print "Vertex: ", sorted(complex, vertex_cmp)
print "Data:   ", sorted(complex, data_cmp)
print "DataDim:", sorted(complex, data_dim_cmp)

f = Filtration(complex, data_cmp)
print "Complex in the filtration order:", ', '.join((str(s) for s in f))

p = StaticPersistence(f)
print "Persistence initialized"
p.pair_simplices(True)
print "Simplices paired"

smap = p.make_simplex_map(f)
for i in p:
    print i.sign(), i.pair().sign()
    print "%s (%d) - %s (%d)" % (smap[i], i.sign(), smap[i.pair()], i.pair().sign())
    print "Cycle (%d):" % len(i.cycle), " + ".join((str(smap[ii]) for ii in i.cycle))

print "Number of unpaired simplices:", len([i for i in p if i.unpaired()])
Ejemplo n.º 13
0
from    math        import fabs
from    dionysus    import Rips, Filtration, StaticPersistence #, enable_log

# Simple minded pairwise distance functor distance
class Distances:
    def __len__(self):
        return 5

    def __call__(self, x, y):
        return fabs(y-x)

dist = Distances()
r = Rips(dist)
lst = Filtration()
lst2 = Filtration()

#enable_log('rips')

r.generate(1, 3, lst.append)
r.generate(1, 3, lst2.append, [0,2,4])

print "Rips complex on all vertices:", lst
print "Rips complex on vertices [0,2,4]):", lst2

print "Values:", [map(r.eval, lst)]
print "Sorted:", sorted(lst, r.cmp)

cofaces = []
r.vertex_cofaces(2, 1, 3, cofaces.append)
print "Cofaces of vertex 2:", cofaces