Beispiel #1
0
def LandscapePnorm(ts,
                   p,
                   ts2=None,
                   dim=1,
                   maxrad=1,
                   t_min=None,
                   t_max=None,
                   n_points=100):
    # compute L^p norm of all landscapes from multidimensional timeseries (or just set of points)
    # input:
    # ts - m x d numpy array, one timeseries (or just point coordinates) per column (d series), m samples per series
    # p - integer (type of L^p norm to compute)
    # ts2 - m x d numpy array, one timeseries (or just point coordinates) per column (d series), m samples per series
    #     if this is set, then the L^p distance will be returned
    # dim - dimension of the persistence diagram from which to derive the landscape
    # maxrad - max distance between pairwise points to consider for the Rips complex
    # t_min, t_max (int or None) - same as inputs to dgm2landscape; if universal start/stop radii are desired for computing landscapes
    #                              setting these to fixed values might reduce computation time a little bit
    # n_points (int) - same as input to dgm2landscape; number of data points for landscape functions
    # output:
    # float32 - the L^p norm of the landscapes or difference
    # need to go one dim up, above the one we want, as otherwise get free hom group at the top of the chains.
    frips = d.fill_rips(np.array(ts, dtype='float32'), dim + 1, maxrad)
    mrips = d.homology_persistence(frips)
    dgms = d.init_diagrams(mrips, frips)
    # acquire birth/death pairs
    if len(dgms) <= dim:
        # set the only birth/death pair to (0.0,0.0) if no gens found
        bd = np.zeros((1, 2))
    else:
        bd = dgm2array(dgms[dim])
    # acquire landscape functions
    landscapes, rstart, rend = dgm2landscape(bd,
                                             t_min=t_min,
                                             t_max=t_max,
                                             n_points=n_points)
    if ts2 is not None:
        frips2 = d.fill_rips(np.array(ts2, dtype='float32'), dim + 1, maxrad)
        mrips2 = d.homology_persistence(frips2)
        dgms2 = d.init_diagrams(mrips2, frips2)
        if len(dgms2) <= dim:
            # set the only birth/death pair to (0.0,0.0) if no gens found
            bd2 = np.zeros((1, 2))
        else:
            bd2 = dgm2array(dgms2[dim])
        landscapes2, rstart2, rend2 = dgm2landscape(bd2,
                                                    t_min=t_min,
                                                    t_max=t_max,
                                                    n_points=n_points)
        # compute L^p distances
        lpnorms = LpNorms(landscapes,
                          min(rstart, rstart2),
                          max(rend, rend2),
                          landscapes2=landscapes2,
                          p=p)
    else:
        # compute L^p norms
        lpnorms = LpNorms(landscapes, rstart, rend, p=p)
    normie = LandscapeLpNorm(lpnorms, p=p)
    return (normie)
Beispiel #2
0
    def fit(self, data):
        """ Generate Rips filtration and cycles for data.
        """

        # Generate rips filtration 
        maxeps = np.max(data.std(axis=0)) # TODO: is this the best choice?
        cpx = dionysus.fill_rips(data, self.order+1, maxeps)

        # Add cone point to force homology to finite length; Dionysus only gives out cycles of finite intervals
        spxs = [dionysus.Simplex([-1])] + [c.join(-1) for c in cpx]
        for spx in spxs:
            spx.data = 1
            cpx.append(spx)

        # Compute persistence diagram
        persistence = dionysus.homology_persistence(cpx)
        diagrams = dionysus.init_diagrams(persistence, cpx)

        # Set all the results
        self._filtration = cpx
        self._diagram = diagrams[self.order]
        self._persistence = persistence
        self.barcode = np.array([(d.birth, d.death) for d in self._diagram])

        self._build_cycles()
Beispiel #3
0
def computePD(i):
    # print('Process %s' % i)
    # np.random.seed(42)
    f1 = d.fill_rips(np.random.random((i + 10, 2)), 2, 1)
    m1 = d.homology_persistence(f1)
    dgms1 = d.init_diagrams(m1, f1)
    # return [(p.birth, p.death) for p in dgms1[1]]  # advice from Dmitriy
    return dgms1[1]
Beispiel #4
0
 def get_rips_diagram(pcpds_obj):
     f = d.fill_rips(pcpds_obj.get_point_cloud().astype('f4'),
                     pcpds_obj.get_skeleton(), pcpds_obj.get_distance())
     m = d.homology_persistence(f)
     diagram = d.init_diagrams(m, f)
     pcpds_obj.set_persistance_diagram(diagram)
     pcpds_obj.set_filtration_used(Filtration.get_rips_diagram, "rips")
     return pcpds_obj
def generate_rv_complex(PointsArray, Dimension):
    dists = pdist(PointsArray)
    # adjacentDist = [norm(PointsArray[i,:] - PointsArray[i+1,:]) for i in range(len(PointsArray)-1)]
    Alpha = max(dists)
    rips = d.fill_rips(dists, Dimension, Alpha)
    m = d.homology_persistence(rips)
    dgms = d.init_diagrams(m, rips)
    return rips, m, dgms
Beispiel #6
0
def PersistentDiagram(nparray,dim=1,skeletondim=2):
    stime=timer()
    DisM=distance.pdist(nparray,'euclidean')
    M=DisM.max()
    VRC=d.fill_rips(nparray,skeletondim,M)
    ph=d.homology_persistence(VRC)
    dgms=d.init_diagrams(ph,VRC)
    timer(stime)
    return dgms[dim]
Beispiel #7
0
    def fit(self, data):
        """ Generate Rips filtration and cycles for data.
        """

       # Generate rips filtration 
        maxeps = np.max(data.std(axis=0)) # TODO: is this the best choice?
        simplices = dionysus.fill_rips(data, self.order+1 , maxeps)
        
        self.from_simplices(simplices)
Beispiel #8
0
def test_rips(n=100, dim=2):
    # dionysus version
    t0 = time.time()
    points = np.random.random((n, dim))
    f = d.fill_rips(points, 2, 0.3)
    print(f)
    # for s in f:
    #     print(s)
    print('Computing rips of %s nodes at dim %s takes %s' %
          (n, dim, pf(time.time() - t0)))
Beispiel #9
0
        def get_tris(A, labels):
            A_u = make_undirected(A)

            A_u[A_u != 0] = 0.1
            A_u[A_u == 0] = 10
            np.fill_diagonal(A_u, 0)

            f = dio.fill_rips(squareform(A_u), k=2, r=1)
            tris = [fix_vert_nums(i, labels) for i in f if i.dimension() == 2]

            return tris
Beispiel #10
0
def compute_diagrams(data, k_filt=3, to_return=2):

    diagrams = []
    for i in range(len(data)):
        # print("Processing data: " + str(i) + "\n")
        filtration = dion.fill_rips(data[i], k_filt, 3.0)
        homology = dion.homology_persistence(filtration)
        diagram = dion.init_diagrams(homology, filtration)

        diagrams.append(diagram[to_return])

    return diagrams
Beispiel #11
0
def geomill(arr,dim=1,cutoff=2,elevation=45,azimuth=30):
    #E3view(arr,elevation,azimuth)
    #VR complex
    stime=timer()
    skeletondim=dim+1
    filtration = d.fill_rips(arr, skeletondim, cutoff)
    #persistent homology
    ph = d.homology_persistence(filtration)
    dgms = d.init_diagrams(ph, filtration)
    d.plot.plot_bars(dgms[dim], show = True)
    timer(stime)
    return dgms
def compute_diagrams(data):

    diagrams = []
    for i in range(len(data)):
        # print("Processing data: " + str(i))
        filtration = dion.fill_rips(data[i], 2, 3.0)
        homology = dion.homology_persistence(filtration)
        diagram = dion.init_diagrams(homology, filtration)
        diagrams.append(diagram[1])
    # print()

    return diagrams
Beispiel #13
0
def geomill(arr, skeletondim=2, elevation=45, azimuth=30):
    #3D illustration
    fig = pyplot.figure()
    ax = Axes3D(fig)
    ax.view_init(elev=elevation, azim=azimuth)
    ax.scatter(arr[:, 0], arr[:, 1], arr[:, 2])
    pyplot.show()
    #VR complex
    filtration = d.fill_rips(circ, skeletondim, 2)
    #persistent homology
    ph = d.homology_persistence(filtration)
    dgms = d.init_diagrams(ph, filtration)
    d.plot.plot_bars(dgms[1], show=True)
    return ax, dgms
Beispiel #14
0
def RipsFiltration(neuron_file, k=2, r=.5):
    """
    Compute the rips filtration of a neuron with dionysus.
    Requires dionysus library
    :param neuron_file:
    :param k: max skeleton dimension
    :param r: compute the Ribs Filtration with max value = r * max distance between points, r \in [0, 1]
    :return:
    """
    nrn = tmd.io.load_neuron(neuron_file)

    points = np.concatenate(
        [[np.array([x, y, z]) for x, y, z in zip(t.x, t.y, t.z)]
         for t in nrn.neurites])
    D = pdist(points)

    return di.fill_rips(squareform(D), k, r * D.max())
    def forward(ctx, x, saturation=None, maxdim=1, verbose=False):
        MAX_DIMENSION = maxdim + 1  # maximal simplex dimension
        if verbose: print("*** dgm start")
        if saturation == None:
            SATURATION_VALUE = 3.1
            print("==== WARNING: NO SATURATION VALUE GIVEN, {}".format(
                SATURATION_VALUE))
        else:
            SATURATION_VALUE = saturation

        start_time = time.time()
        function_values = x
        # list of function values on vertices, and maximal dimension it will return 0,1,2,3
        function_useable = function_values.data.numpy()
        ''' 2 is max homology dimension '''
        ''' returns (sorted) filtration filled with the k-skeleton of the clique complex built on the points at distance at most r from each other '''
        F = d.fill_rips(function_useable, MAX_DIMENSION, SATURATION_VALUE)
        # F.sort() # this is done in computePersistence

        dgms, Tbl = computePersistence(F)
        max_pts = np.max([len(dgms[i]) for i in range(maxdim + 1)])
        num_dgm_pts = max_pts
        ''' -1 is used later '''
        dgms_inds = -1 * np.ones([maxdim + 1, num_dgm_pts, 4])
        dgms_values = -np.inf * np.ones([
            maxdim + 1, num_dgm_pts, 2
        ])  # -1.0 * np.ones([3, num_dgm_pts, 2])
        for dim in range(maxdim + 1):
            if len(dgms[dim]) > 0:
                dgm = np.array(dgms[dim])
                dgm[dgm == np.inf] = SATURATION_VALUE
                l = np.min([num_dgm_pts, len(dgm)])
                arg_sort = np.argsort(np.abs(dgm[:, 1] - dgm[:, 0]))[::-1]
                dgms_inds[dim][:l] = dgm[arg_sort[:l], 2:6]
                dgms_values[dim][:l] = dgm[arg_sort[:l], 0:2]

        dgms_inds = dgms_inds.reshape([maxdim + 1, num_dgm_pts, 2, 2])
        #print dgms_values
        #dgms_values[dgms_values == np.inf] = SATURATION_VALUE #-1.0, Won't show up as inifinite, but good enough
        output = torch.tensor(dgms_values).type(dtype)
        ctx.save_for_backward(x,
                              torch.tensor(dgms_inds).type(dtype), output,
                              torch.tensor(verbose))
        if verbose: print("*** dgm done", time.time() - start_time)
        return output
Beispiel #16
0
def fpd_cluster(data, c, verbose=False, max_iter=5, p=1, max_range=10, T=100):
    # Compute topological fuzzy clusters of a collection of point clouds
    #
    # inputs: list of datasets data, number of cluster centres c,
    #         verbose True/False, maximum iterations max_iter,
    #         dimension p-PH  p, Rips parameter max_range, hyper-parameter T
    #         (if unsure of value for max_range or T, set as the furthest distance between two points)
    # outputs: membership values r, cluster centres M

    diagrams = []
    for i in range(len(data)):
        filtration = dion.fill_rips(data[i], p + 1, max_range)
        homology = dion.homology_persistence(filtration)
        diagram = dion.init_diagrams(homology, filtration)
        diagrams.append(diagram[p])

    diagrams = reformat_diagrams(diagrams, T)
    r, M = pd_fuzzy(diagrams, c, verbose, max_iter)

    return r, M
Beispiel #17
0
    def compute_persistence(self, max_epsilon):
        '''
        Computes persistence of self.points up to max_epsilon and returns
        persistence diagrams
        :param max_epsilon: max epsilon for persistence
        :return: class Diagram
        '''
        # fill rips complex up to distance max_epsilon using self.points
        filtration = d.fill_rips(self.points, self.k_skeleton, max_epsilon)

        # before computing persistence we sort the filtration
        filtration.sort()

        # compute persistence and return ReducedMatrix
        matrix = d.homology_persistence(filtration, prime = 2)

        # initialize diagrams with ReducedMatrix and filtration
        diagrams = d.init_diagrams(matrix, filtration)

        return diagrams
 def __init__(self,
              Win_or_Lose_kihus,
              dim=2,
              radius=2 * np.sqrt(2),
              step=10):
     ##initializing parameter
     self.radius = radius
     self.dim = dim
     self.step = step
     self.kihus = Win_or_Lose_kihus
     ##making filltration
     self.dim2_fill_list = []
     for kihu in self.kihus:
         remainder = len(kihu) % step
         turns = np.arange(step, len(kihu), step)
         if remainder >= step / 2:
             turns = np.append(turns, len(kihu))
         else:
             turns[-1] = len(kihu)
         self.dim2_fill_list.append(
             [d.fill_rips(pdist(kihu[:t]), dim, radius) for t in turns])
Beispiel #19
0
    dgm_denoise_0 = bars_0
    dgm_denoise_1 = bars_1
    #print(type(dgm_denoise_0))
    #dionysus.plot.plot_diagram(dgm_denoise_0, show=False)
    #dionysus.plot.plot_diagram(dgm_denoise_1, show=False)
    return ([dgm_denoise_0, dgm_denoise_1])


#Let us compute the bottle-neck distance between full dataset and k-PCA dataset. k denotes the number of principal components.
prime = 23
D = 20
#Here is the data insertion part
mean = np.repeat(0, D)
cov = np.identity(D)
dat1 = np.random.multivariate_normal(mean, cov, 100)
vr = dionysus.fill_rips(dat1, 2, 10)  #Vietoris-Rips complex
cp = dionysus.cohomology_persistence(vr, prime,
                                     True)  #Create the persistent cohomology
dgms = dionysus.init_diagrams(
    cp, vr
)  #Calculate the persistent diagram using the designated coefficient field.
#record for plottings..
A = np.array([0, 0, 1, 1])

for thres in [0, 0.025, 0.05, 0.1, 0.2]:
    #######Thresholding the features on the persistent diagrams describing persistent cohomology of VR complex(CC)
    dgms_tmp = denoise_dgm(dgms, thres)  #thresholding CC diagrams
    dgms_base_0 = dionysus._dionysus.Diagram(
    )  #take persistent points of dim 0
    dgms_base_1 = dionysus._dionysus.Diagram(
    )  #take persistent points of dim 1
    plt.gca().set_aspect('equal', 'datalim')
    ax = fig.add_subplot(111, projection='3d')
    ax.set_xlim([-2, 2])
    ax.set_ylim([-2, 2])
    ax.set_zlim([-2, 2])
    ax.scatter(xs=X[:, 0], ys=X[:, 1], zs=X[:, 2], s=10, c='b')
    plt.title('Scatter plot of data points')
    pdf.savefig(fig)

# The persistent cohomology of $X$ is in the plot. As expected from the dataset, the $1$-dimensional persistent cohomology
# of $X$ has one prominent topological feature.

# In[5]:

prime = 23  #choose the prime base for the coefficient field that we use to construct the persistence cohomology.
vr = dionysus.fill_rips(X, 2, 2.)  #Vietoris-Rips complex
cp = dionysus.cohomology_persistence(
    vr, prime,
    True)  #Create the persistent cohomology based on the chosen parameters.
dgms = dionysus.init_diagrams(
    cp, vr
)  #Calculate the persistent diagram using␣ the designated coefficient field and complex.

# In[6]:

with PdfPages('fig_cc-pca_dataset_ph.pdf') as pdf:
    fig = plt.figure(figsize=(4, 4), dpi=100)
    plt.xlim([0, 2])
    plt.yticks([])
    plt.title('Barcode(dim 1) of data points')
    dionysus.plot.plot_bars(dgms[1], show=True)
Beispiel #21
0
import scipy.io

# The followings are input data
filename = "Point.txt"  # input a point cloud dataset;
data = np.genfromtxt(filename, delimiter=' ')
tK = 1
# threshold for simplicial complex K
tL = 1.5
# threshold for simplicial complex L
end = 1.5
# largest threshold for building the Vietoris-Rips complex
q = 2
# dimension for the persistent Laplacian

# Building a Vietoris-Rips complex
f = d.fill_rips(data, q + 1, end)
print(f)

count = 0
for s in f:
    count = count + 1
print(count)
shape = (count, count)
Bw = np.zeros(shape, dtype=int)

if q == 0:  # If q=0, returns only the 1-boundary matrix of L
    q1_column_index = []
    q1_row_index = []
    Kind = 0

    for s in f:
Beispiel #22
0
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.set_xlim(dims[0][0],dims[0][1])
ax.set_ylim(dims[1][0],dims[1][1])
ax.set_zlim(dims[2][0],dims[2][1])
ax.scatter(sphere_data[:,0],sphere_data[:,1],sphere_data[:,2])
ax.set_aspect("equal")

plt.show()


"""
computing homology
"""
#VR filtration TDA
test_f = d.fill_rips(TDA_data, 2, 10.)
p = d.homology_persistence(test_f)
dgms = d.init_diagrams(p, test_f)

#scatters
d.plot.plot_diagram(dgms[0])
d.plot.plot_diagram(dgms[1])
plt.show()

#bars
d.plot.plot_bars(dgms[0])
plt.show()

d.plot.plot_bars(dgms[1])
plt.show()
Beispiel #23
0
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn import manifold, datasets

n_points = 100
Y, color = datasets.make_circles(n_points, random_state=1, factor=0.5, noise=0)

fig, ax = plt.subplots()
ax.scatter(Y[:,0], Y[:,1], c=color, cmap=plt.cm.Spectral)
# plt.show()

import dionysus as d

max_epsilon = 1
k_skeleton = 3

f = d.fill_rips(Y, k_skeleton, max_epsilon)
p = d.homology_persistence(f)
dgms = d.init_diagrams(p, f)

fig, axes = plt.subplots(nrows=2, ncols=2)
d.plot.plot_diagram(dgms[0], ax=axes[0,0], show=False)
d.plot.plot_diagram(dgms[1], ax=axes[0,1], show=False)
d.plot.plot_bars(dgms[0], ax=axes[1,0], show=False)
d.plot.plot_bars(dgms[1], ax=axes[1,1], show=False)

axes[0,0].set_title("Dimension 0")
axes[0,1].set_title("Dimension 1")

plt.show()
    plt.ylabel('Y')
    plt.gca().set_aspect('equal', 'datalim')
    plt.scatter(X[:, 0], X[:, 1], s=10, c='b')
    plt.axis('equal')
    plt.title('Scatter plot of data points')
    pdf.savefig(fig)


# The persistent cohomology of $X$ is in the plot. As expected from the dataset, the $1$-dimensional persistent cohomology
# of $X$ has one prominent topological feature.

# In[13]:


prime = 23 #choose the prime base for the coefficient field that we use to construct the persistence cohomology.
vr = dionysus.fill_rips(X, 2, 2.) #Vietoris-Rips complex
cp = dionysus.cohomology_persistence(vr, prime, True) #Create the persistent cohomology based on the chosen parameters.
dgms = dionysus.init_diagrams(cp, vr) #Calculate the persistent diagram using␣ the designated coefficient field and complex.


# In[14]:


with PdfPages('fig_cp-cp_dataset_ph.pdf') as pdf:
    fig = plt.figure(figsize=(4,4), dpi=100)
    plt.xlim([0, 2])
    plt.yticks([])
    plt.title('Barcode(dim 1) of data points')
    dionysus.plot.plot_bars(dgms[1], show=True)
    #dionysus.plot.plot_diagram(dgms[1], show=True)
    #dionysus.plot.plot_diagram(dgms[0], show=True)
Beispiel #25
0
    def setup_Zigzag_fixed(self, r, k=2, verbose=False):
        '''
        Helper function for ``run_Zigzag`` that sets up inputs needed for Dionysus' zigzag persistence function.
        This only works for a fixed radius r.

        Parameters
        ----------

        r: float
            Radius for rips complex

        k: int, optional
            Max dimension for rips complex (default is 2)

        verbose: bool, optional
            If true, prints updates when running code

        Returns
        -------
        filtration: dio.Filtration
            Dionysis filtration containing all simplices that exist in zigzag sequence

        times: list
            List of times, where times[i] is a list containing [a,b] where simplex i appears at time a, and disappears at time b

        '''

        lst = list(self.ptclouds['PtCloud'])

        # simps_df = pd.DataFrame(columns = ['Simp','B,D'])
        simps_list = []
        times_list = []

        # Vertex counter
        vertind = 0

        init_st = time.time()
        # Initialize A with R(X_0)
        rips = dio.fill_rips(lst[0], k=2, r=r)
        rips.sort()
        rips_set = set(rips)

        # Initialize A with set of simplices with verts in X_0
        A = rips_set

        # # Add all simps to the list with birth,death=[0,1]
        simps_list = simps_list + [s for s in A]
        times_list = times_list + [[0, 1] for j in range(len(A))]

        # Initialize with vertices for X_0
        verts = set(
            [dio.Simplex([j + vertind], 0) for j, pc in enumerate(lst[0])])

        init_end = time.time()
        if verbose:
            print(f'Initializing done in {init_end-init_st} seconds...')

        loop_st = time.time()
        # Loop over the rest of the point clouds
        for i in range(1, len(lst)):

            # Calculate rips of X_{i-1} \cup X_i
            rips = dio.fill_rips(np.vstack([lst[i - 1], lst[i]]), k=2, r=r)

            # Adjust vertex numbers, sort, and make into a set
            rips = fix_dio_vert_nums(rips, vertind)
            rips.sort()
            rips_set = set(rips)

            # Increment vertex counter
            vertind = vertind + len(verts)

            # Set of vertices in R(X_i)
            verts_next = set(
                [dio.Simplex([j + vertind], 0) for j, pc in enumerate(lst[i])])

            # Set of simplices with verts in X_{i}
            B = set(verts_next.intersection(rips_set))

            # Set of simplices with verts in X_{i-1} AND X_{i}
            M = set()

            # Loop over vertices in R(X_{i-1} \cup R_i)
            for simp in rips:

                # Get list of vertices of simp
                bdy = get_verts(simp)

                # If it has no boundary and its in B, its a vertex in B and has been handled
                if not bdy:
                    continue

                # If all of its verts are in A, it's been handled in the initialization or the previous iteration
                if bdy.intersection(A) == bdy:
                    continue

                # If all of its verts are in B, add it to B
                elif bdy.intersection(B) == bdy:
                    B.add(simp)

                # If it has some verts in A and some in B, it only exists in the union
                # Add it to M
                else:
                    M.add(simp)

            # Add simplices in B with the corresponding birth,death times
            simps_list = simps_list + [s for s in B]
            times_list = times_list + [[i - 0.5, i + 1] for j in range(len(B))]

            # Add simplicies in M with corresponding birth,death times
            simps_list = simps_list + [s for s in M]
            times_list = times_list + [[i - 0.5, i] for j in range(len(M))]

            # Reinitialize for next iteration
            verts = verts_next
            A = B

        loop_end = time.time()
        if verbose:
            print(f'Preprocessing done in {loop_end-loop_st} seconds...')

        f_st = time.time()
        filtration = dio.Filtration(simps_list)
        f_end = time.time()

        return filtration, times_list
Beispiel #26
0
    def setup_Zigzag_changing(self, r, k=2, verbose=False):
        '''
        Helper function for ``run_Zigzag`` that sets up inputs needed for Dionysus' zigzag persistence function.
        This one allows r to be a list of radii, rather than one fixed value

        Parameters
        ----------

        r: list
            List of radii for rips complex of each X_i

        k: int, optional
            Max dimension for rips complex (default is 2)

        verbose: bool, optional
            If true, prints updates when running code

        Returns
        -------
        filtration: dio.Filtration
            Dionysis filtration containing all simplices that exist in zigzag sequence

        times: list
            List of times, where times[i] is a list containing [a,b] where simplex i appears at time a, and disappears at time b

        '''

        lst = list(self.ptclouds['PtCloud'])

        # If you haven't input enough r values, just append extra of the last
        # list entry to make it the right number
        if len(r) < len(lst):
            if verbose:
                print('Warning: too few radii given, duplicating last entry')
            r = r + ([r[-1]] * (len(lst) - len(r)))
        elif len(r) > len(lst):
            if verbose:
                print('Warning: too many radii given, only using first ',
                      len(lst))
            r = r[:len(lst)]
        self.r = r

        # simps_df = pd.DataFrame(columns = ['Simp','B,D'])
        simps_list = []
        times_list = []

        # Vertex counter
        vertind = 0

        init_st = time.time()

        # Initialize A with R(X_0)
        rips = dio.fill_rips(lst[0], k=2, r=r[0])
        rips.sort()
        rips_set = set(rips)

        # Initialize A with set of simplices with verts in X_0
        # In the loop, this will store simplices with verts in X_{i-1}
        A = rips_set

        # Add all simps to the list with birth,death=[0,1]
        simps_list = simps_list + [s for s in A]
        times_list = times_list + [[0, 1] for j in range(len(A))]

        # Initialize with vertices for X_0
        # In the loop, this will store vertices in X_{i-1}
        verts = set(
            [dio.Simplex([j + vertind], 0) for j, pc in enumerate(lst[0])])

        init_end = time.time()
        if verbose:
            print(f'Initializing done in {init_end-init_st} seconds...')

        loop_st = time.time()
        # Loop over the rest of the point clouds
        for i in range(1, len(lst)):

            # Calculate rips of X_{i-1} \cup X_i
            rips = dio.fill_rips(np.vstack([lst[i - 1], lst[i]]),
                                 k=2,
                                 r=max(r[i - 1], r[i]))

            # Adjust vertex numbers, sort, and make into a set
            rips = fix_dio_vert_nums(rips, vertind)
            rips.sort()
            rips_set = set(rips)

            # Increment vertex counter
            vertind = vertind + len(verts)

            # Set of vertices in X_{i}
            verts_next = set(
                [dio.Simplex([j + vertind], 0) for j, pc in enumerate(lst[i])])

            # Set of simplices with verts in X_{i}
            B = set(verts_next.intersection(rips_set))

            # Set of simplices with verts in X_{i-1} AND X_{i}
            # And simplicies in X_{i-1} \cup X_{i} that are not in X_{i-1} or X_i
            M = set()

            # Loop over vertices in R(X_{i-1} \cup R_i)
            for simp in rips:

                # Get list of vertices of simp
                bdy = get_verts(simp)  #set([s for s in simp.boundary()])

                # If it has no boundary and its in B, its a vertex in B and has been handled
                if not bdy:
                    continue

                # If all of its verts are in A, it's been handled in the initialization or the previous iteration
                if bdy.intersection(A) == bdy:
                    if r[i - 1] < r[i]:
                        if simp.data > r[i - 1]:
                            # If we haven't seen it before, add it to M
                            if simp not in simps_list:
                                M.add(simp)

                            # If we've already added it to the list...
                            else:
                                # Edit the lists to include new birth,death times
                                simps_list, times_list = edit_Simp_Times(
                                    simp, [i - 0.5, i], simps_list, times_list)

                # If all of its verts are in B...
                elif bdy.intersection(B) == bdy:

                    # If r[i-1] <= r[i], anything with verts in B should also be in B
                    if r[i - 1] <= r[i]:
                        B.add(simp)

                    # If r[i-1] > r[i], we need to check if it should go in M or B
                    else:
                        # If simplex's birth time is greater than the radius, it goes in M
                        if simp.data > r[i]:
                            M.add(simp)

                        # If it's <= then it goes in B
                        else:
                            B.add(simp)

                # If it has some verts in A and some in B, it only exists in the union
                else:
                    # If we haven't seen it before, add it to M
                    if simp not in simps_list:
                        M.add(simp)

                    # If we've already added it to the list...
                    else:
                        # Edit the lists to include new birth,death times
                        simps_list, times_list = edit_Simp_Times(
                            simp, [i - 0.5, i], simps_list, times_list)

            # Add simps and times that are in B
            simps_list = simps_list + [simp for simp in B]
            times_list = times_list + [[i - 0.5, i + 1] for j in range(len(B))]

            # Add simps and times that are in M
            simps_list = simps_list + [simp for simp in M]
            times_list = times_list + [[i - 0.5, i] for j in range(len(M))]

            # Reinitialize for next iteration
            verts = verts_next
            A = B

        loop_end = time.time()
        if verbose:
            print(f'Preprocessing done in {loop_end-loop_st} seconds...')

        # Put list of simplices into Filtration format
        filtration = dio.Filtration(simps_list)

        return filtration, times_list
Beispiel #27
0
def get_dgms(dists):
    f = d.fill_rips(dists, 1, np.amax(dists) + 1)
    m = d.homology_persistence(f)
    dgms = d.init_diagrams(m, f)
    return dgms[0]
Beispiel #28
0
    plt.axis('equal')
    plt.title('Scatter plot of data points')
    pdf.savefig(fig)
    #                            #
    ##############################
    ##############################
    #Compute Persistence Diagrams#
    prime = 23
    maxscale = float(sys.argv[3])
    #Choose the prime base for the coefficient field that we use to construct the persistence cohomology.
    threshold = float(sys.argv[2])
    print('Base coefficient field: Z/', prime ,'Z',sep='')
    print('Maximal scale:', float(sys.argv[3]))
    print('Persistence threshold for selecting significant cocycles:',threshold)

    vr = dionysus.fill_rips(dataset, 2, float(sys.argv[3]))
    #Vietoris-Rips complex
    cp = dionysus.cohomology_persistence(vr, prime, True)
    #Create the persistent cohomology based on the chosen parameters.
    dgms = dionysus.init_diagrams(cp, vr)
    #Calculate the persistent diagram using the designated coefficient field and complex.
    now = datetime.datetime.now()
    print('>>>>>>End Time (VR-computation):',now.strftime("%Y-%m-%d %H:%M:%S"))
    ###Plot the barcode and diagrams using matplotlib incarnation within Dionysus2. This mechanism is different in Dionysus.
    #Plots of persistence barcodes of Vietoris-Rips complex for dimension 0 and 1.
    fig = plt.figure(figsize=(5,5), dpi=100)
    plt.title('Persistence Barcode for dim 0')
    dionysus.plot.plot_bars(dgms[0], show=True)
    pdf.savefig(fig)
    fig = plt.figure(figsize=(5,5), dpi=100)
    plt.title('Persistence Barcode for dim 1')
Beispiel #29
0
        [3 * i + 1 | 1 for i in range(1, n // 3 - correction) if sieve[i]])


n_max = 10**3
n_list = rwh_primes(n_max)
print(n_max)
m_list = np.sqrt(n_list).astype(int)
k_list = n_list - m_list**2
zero_list = 0 * n_list
a_list = np.maximum(zero_list, k_list - m_list)
b_list = np.minimum(k_list, m_list)

odd_m_indices = np.where(m_list % 2 == 1)
even_m_indices = np.where(m_list % 2 == 0)

Ux_odd_m = (m_list[odd_m_indices] + 1) // 2 - a_list[odd_m_indices]
Uy_odd_m = (-m_list[odd_m_indices] + 1) // 2 + b_list[odd_m_indices]
U_odd_m = np.array((Ux_odd_m, Uy_odd_m)).T  #, n_list[odd_m_indices])).T

Ux_even_m = -m_list[even_m_indices] // 2 + a_list[even_m_indices]
Uy_even_m = m_list[even_m_indices] // 2 - b_list[even_m_indices]
U_even_m = np.array((Ux_even_m, Uy_even_m)).T  #, n_list[even_m_indices])).T

U_all = np.vstack((U_odd_m, U_even_m)).astype(float)

f = d.fill_rips(U_all, 2, 20.)
p = d.homology_persistence(f)
dgms = d.init_diagrams(p, f)

d.plot.plot_diagram_density(dgms[1], show=True)
    vertex1 = 0
    vertex2 = 1
    vertex3 = 2

    print('Making simplex from verts: ', vertex1, vertex2, vertex3)


    s=d.Simplex([vertex1,vertex2,vertex3])
    print("Here is the simplex: ", s)

    print("Its dimension is: ", s.dimension())

    print("And its boundary...")
    for sb in s.boundary():
        print(sb)

    


    print("Great - So we can work with simplecies, but we can also work with points")
    print("Here is an array (Must be numpy)")
    points = np.array([[0.0,1.0],[2.0,0.0],[0.0,0.0]])
    print(points)

    #Computes rips filtration up to 2 skeleton and up to radius 5
    f = d.fill_rips(points, 2, 5)
    print("Here is the Rips filtration of the points: ", f)
    for x in f:
        print("Simplex :", x)