Пример #1
0
def Compute_rhoT(fasta_input,empty_fasta, single_line = False): #fasta file and an empty fasta file
    print("Reading FASTA file...")
    if not single_line:
        single_line_fasta(fasta_input, empty_fasta)
        fasta_file = empty_fasta
    else:
        fasta_file = fasta_input
        
    lines = format_data(fasta_file,'fasta')
    print("Computing Hamming distance matrix...")
    #print(lines[0:5])
    matrix = empty_matrix(lines)
    hamm_matrix = populate_matrix(matrix, lines)
    print('Computing barcodes ...')
    dgms = ripser(hamm_matrix,  distance_matrix=True, maxdim=1)['dgms']
    Rbarc = dgms 
    Gbarc = Rips_to_GUDHI(Rbarc)
    print('Plotting persistence diagrams')
    gd.plot_persistence_diagram(Gbarc, colormap = ('navy','darkmagenta','fuchsia'))    
    gd.plot_persistence_barcode(Gbarc, colormap = ('navy','darkmagenta','fuchsia'))
    print('Computing barcode statistics...')
    avg0, var0, b1 = barstats(Rbarc)
    print('Computing estimate of rho')
    rhoT = TREErho(avg0, var0, b1)
    print('$\psi = {}, \Phi = {}, \\beta_1 = {}, \\rho_T = {}$'.format(avg0, var0, b1, rhoT))
    return hamm_matrix,Rbarc
    def bettiNumbers(self, *args, **kwargs):
        from gudhi import RipsComplex, plot_persistence_diagram, plot_persistence_barcode, sparsify_point_set
        import random as r
        import numpy as np
        import matplotlib.pyplot as plt
        targetCluster = kwargs.get('targetCluster', [1])
        threshold = kwargs.get('threshold', 0.05)
        sparsifyThreshold = kwargs.get('sparsifyThreshold', threshold/8)
        plot = kwargs.get('plot', False)
        pointList = []
        for point in self.points:
            if point.cluster in targetCluster:
                pointList.append(np.array(point.coordinates))

        pointList = sparsify_point_set(
            points=pointList, min_squared_dist=sparsifyThreshold**2)
        point_complex = RipsComplex(
            max_edge_length=threshold/2, points=pointList)
        simplex_tree = point_complex.create_simplex_tree(
            max_dimension=self.dimension)
        persistence = simplex_tree.persistence()
        if plot:
            plot_persistence_barcode(persistence)
            plt.plot()
            plot_persistence_diagram(persistence)
            plt.plot()
        return simplex_tree.betti_numbers()
Пример #3
0
def PH_diag(img, patch_side):
    cc = gd.CubicalComplex(dimensions=(patch_side, patch_side, patch_side),
                           top_dimensional_cells=1 - img.flatten())
    diag = cc.persistence()
    plt.figure(figsize=(3, 3))
    # diag_clean = diag_tidy(diag, 1e-3)
    gd.plot_persistence_barcode(diag, max_intervals=0, inf_delta=100)
    print(diag)
    plt.xlim(0, 1)
    plt.ylim(-1, len(diag))
    plt.xticks(ticks=np.linspace(0, 1, 6),
               labels=np.round(np.linspace(1, 0, 6), 2))
    plt.yticks([])
    plt.show()
Пример #4
0
def save_PH_diag(img, patch_side, outdir):
    cc = gd.CubicalComplex(dimensions=(patch_side, patch_side, patch_side),
                           top_dimensional_cells=1 - img.flatten())
    diag = cc.persistence()
    plt.figure(figsize=(3, 3))
    diag_clean = diag_tidy(diag, 1e-3)
    print(diag_clean)
    # np.savetxt(os.path.join(outdir, 'generalization.csv'), diag_clean, delimiter=",")
    with open(os.path.join(outdir, 'generalization.txt'), 'wt') as f:
        for ele in diag_clean:
            f.write(ele + '\n')
    gd.plot_persistence_barcode(diag_clean)
    plt.ylim(-1, len(diag_clean))
    plt.xticks(ticks=np.linspace(0, 1, 6), labels=np.round(np.linspace(1, 0, 6), 2))
    plt.yticks([])
    plt.savefig(os.path.join(outdir, "PH_diag.png"))
Пример #5
0
def PH_diag(img):
    z, y, x = img.shape
    cc = gd.CubicalComplex(dimensions=(z, y, x),
                           top_dimensional_cells=1 - img.flatten())
    diag = cc.persistence()
    plt.figure(figsize=(3, 3))
    gd.plot_persistence_barcode(diag, max_intervals=0, inf_delta=100)
    plt.xlim(0, 1)
    plt.ylim(-1, len(diag))
    plt.xticks(ticks=np.linspace(0, 1, 6), labels=np.round(np.linspace(1, 0, 6), 2))
    plt.yticks([])
    plt.show()
    gd.plot_persistence_diagram(diag, legend=True)
    plt.show()
    gd.plot_persistence_density(diag, legend=True)
    plt.show()
Пример #6
0
def drawPB(data):
    z, y, x = data.shape
    cpx = init_tri_complex_3d(z, y, x)
    layer = LevelSetLayer(cpx, maxdim=2, sublevel=False)
    dgminfo = layer(torch.from_numpy(data).float())
    diag = []
    diag2 = getPB(dgminfo, 2)
    diag1 = getPB(dgminfo, 1)
    diag0 = getPB(dgminfo, 0)
    if diag2 != None: diag += diag2
    if diag1 != None: diag += diag1
    if diag0 != None: diag += diag0

    diag = diag_tidy(diag, 1e-3)
    print(diag)

    plt.figure(figsize=(3, 3))
    gd.plot_persistence_barcode(diag, max_intervals=0, inf_delta=100)
    plt.xlim(0, 1)
    plt.ylim(-1, len(diag))
    plt.xticks(ticks=np.linspace(0, 1, 6), labels=np.round(np.linspace(1, 0, 6), 2))
    plt.yticks([])
Пример #7
0
def get_persistence_from_audio(audio_wave,
                               sample=22050,
                               length=5,
                               graph=False):
    simplex_up = gd.SimplexTree()  # for the upper level persistence data
    simplex_dw = gd.SimplexTree()  # for the lower level persistence data
    for i in np.arange(len(audio_wave)):
        simplex_up.insert([i, i + 1], filtration=audio_wave[i])
        simplex_dw.insert([i, i + 1], filtration=-audio_wave[i])
    for i in np.arange(len(audio_wave) - 1):
        simplex_up.insert([i, i + 1], filtration=audio_wave[i])
        simplex_dw.insert([i, i + 1], filtration=-audio_wave[i])
    simplex_up.initialize_filtration()
    simplex_dw.initialize_filtration()
    dig_up = simplex_up.persistence()
    dig_dw = simplex_dw.persistence()
    if graph:
        plt.figure()
        lr_disp.waveplot(audio_wave, sr=sample)
        plt.title("Audio Wave")
        plt.show()
        plt.figure()
        gd.plot_persistence_barcode(dig_up)
        plt.title("Upper Level Persistence Barcode")
        plt.show()
        plt.figure()
        gd.plot_persistence_barcode(dig_dw)
        plt.title("Sub Levels Persistence Barcode")
        plt.show()
        plt.figure()
        gd.plot_persistence_diagram(dig_up)
        plt.title("Upper Level Persistence Diagram")
        plt.show()
        plt.figure()
        gd.plot_persistence_diagram(dig_dw)
        plt.title("Sub Levels Persistence Diagram")
        plt.show()
    return dig_up, dig_dw  # NOTE: this does not filter out infinite values
Пример #8
0
parser.add_argument(
    "--no-barcode",
    default=False,
    action="store_true",
    help="Flag for not to display the barcodes",
)

args = parser.parse_args()

if is_file_perseus(args.file):
    print("##################################################################")
    print("PeriodicCubicalComplex creation")
    periodic_cubical_complex = gudhi.PeriodicCubicalComplex(
        perseus_file=args.file)

    print("persistence(homology_coeff_field=3, min_persistence=0)=")
    diag = periodic_cubical_complex.persistence(
        homology_coeff_field=3, min_persistence=0
    )
    print(diag)

    print("betti_numbers()=")
    print(periodic_cubical_complex.betti_numbers())
    if args.no_barcode == False:
        import matplotlib.pyplot as plot
        gudhi.plot_persistence_barcode(diag)
        plot.show()
else:
    raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT),
                            args.file)
__copyright__ = "Copyright (C) 2016 Inria"
__license__ = "MIT"

print("#####################################################################")
print("Show barcode persistence example")

persistence = [
    (2, (1.0, float("inf"))),
    (1, (1.4142135623730951, float("inf"))),
    (1, (1.4142135623730951, float("inf"))),
    (0, (0.0, float("inf"))),
    (0, (0.0, 1.0)),
    (0, (0.0, 1.0)),
    (0, (0.0, 1.0)),
]
gudhi.plot_persistence_barcode(persistence)
plot.show()

print("#####################################################################")
print("Show diagram persistence example")

gudhi.plot_persistence_diagram(persistence)
plot.show()

print("#####################################################################")
print("Show diagram persistence example with a confidence band")

gudhi.plot_persistence_diagram(persistence, band=0.2)
plot.show()

print("#####################################################################")
Пример #10
0
__author__ = "Vincent Rouvreau"
__copyright__ = "Copyright (C) 2016 Inria"
__license__ = "MIT"

print("#####################################################################")
print("Show barcode persistence example")

persistence = [
    (2, (1.0, float("inf"))),
    (1, (1.4142135623730951, float("inf"))),
    (1, (1.4142135623730951, float("inf"))),
    (0, (0.0, float("inf"))),
    (0, (0.0, 1.0)),
    (0, (0.0, 1.0)),
    (0, (0.0, 1.0)),
]
gudhi.plot_persistence_barcode(persistence)

print("#####################################################################")
print("Show diagram persistence example")

pplot = gudhi.plot_persistence_diagram(persistence)
pplot.show()

print("#####################################################################")
print("Show diagram persistence example with a confidence band")

pplot = gudhi.plot_persistence_diagram(persistence, band=0.2)
pplot.show()
Пример #11
0
def rstg(n, A):
    rp = gudhi.RipsComplex(A)
    st = rp.create_simplex_tree(max_dimension=n)
    diag = st.persistence()
    gudhi.plot_persistence_barcode(diag)
Пример #12
0
'''计算过滤后的复杂体的持久性图,默认情况下,它停在1维,使用persistence_dim_max = True
计算所有维度的同源性'''
dgm = st.persistence(persistence_dim_max=True)
""" dgm = st.persistence()"""
#print("dgm:",dgm)# 有0,1,2维,0是点 1是线段 2是三角形
#但是只有一个2维  (2, (78.57119751, inf))   其余的0,1还是正常的 (1, (7.01657343, 29.42458725))  (0, (-117.12751007, inf))
##绘制一个持久性图
gd.plot_persistence_diagram([pt for pt in dgm if pt[0] == 0])
"""plot = gd.plot_persistence_diagram(dgm)"""
plt.title('persistence diagram with point')
plt.show()
gd.plot_persistence_diagram(dgm)
plt.title('plot_persistence_diagram')
plt.show()
gd.plot_persistence_barcode(dgm)
plt.title('plot_persistence_barcode')
plt.show()


# 获取所有simplex的列表
# 注意,如果一条边不在顶点中,则插入边会自动插入其顶点
# 与之前的问题相同:手臂在普通持久性图中不生成任何点,并且连接的组件具有无限的持久性。 因此,让我们尝试扩展持久性!
############扩展持久性  extend persistence##########
st.extend_filtration()
'''将持久性同源性扩展到代数拓扑中的其他基本概念,例如同调性和相对同源性/同调性,是很自然的'''
dgms = st.extended_persistence(min_persistence=1e-5)
'''gd.plot_persistence_barcode(dgms)
plt.title('plot_extended_persistence_barcode')
plt.show()'''
#print("dgms:",dgms)# 有0,1,2维,0是点 1是线段 2是三角形
Пример #13
0
import matplotlib.pyplot as plt
from src.datasets.datasets import double_tours

data_double, labels = double_tours()

rips_complex_double = gd.RipsComplex(points = data_double,max_edge_length=2)
rips_simplex_tree_double = rips_complex_double.create_simplex_tree(max_dimension=4)


persistence_double = rips_simplex_tree_double.persistence()
persistence_double_filtered = [x for x in persistence_double if x[0]>1]


gd.plot_persistence_diagram(persistence_double_filtered)
plt.show()
gd.plot_persistence_barcode(persistence_double_filtered)
plt.show()

from src.datasets.shapes import torus
data_single, label = torus(n=500, c=6, a=4, label=0)
rips_complex_single = gd.RipsComplex(points = data_single,max_edge_length=2)
rips_simplex_tree_single = rips_complex_single.create_simplex_tree(max_dimension=4)

persistence_single = rips_simplex_tree_single.persistence()
print(persistence_single)
persistence_single_filtered = [x for x in persistence_single if x[0]>1]
print(persistence_single_filtered)
gd.plot_persistence_diagram(persistence_single_filtered)
plt.show()
gd.plot_persistence_barcode(persistence_single_filtered)
plt.show()
Пример #14
0
import gudhi as gd

cplx = gd.RipsComplex(points=[[0, 0], [1, 2], [2, 1], [4, 3], [4, -3]])
stree = cplx.create_simplex_tree(max_dimension=5)

for x in stree.get_filtration():
    print(x)

diag = stree.persistence(min_persistence=0.01)
plot = gd.plot_persistence_barcode(diag)
plot.show()
Пример #15
0
    return Gbarc


def descriptives(Gbarc):
    #finds the number of features, birth times, death times,
    #and lifespans for a set of GUDHI barcodes
    num = len(Gbarc)
    birth, death, length = [], [], []

    for i in Gbarc:
        b = i[1][0]
        d = i[1][1]
        birth.append(b)
        death.append(d)
        length.append(d - b)

    return num, birth, death, length


# print(tree_sequence.get_num_mutations())

D = Hamming_mat(tree_sequence)
dgms = ripser(D, distance_matrix=True)['dgms']  #computes PH with ripser
barcode = Rips_to_GUDHI(dgms)

#plot barcode and persistence plot with GUDHI
gd.plot_persistence_diagram(barcode,
                            colormap=('navy', 'darkmagenta', 'fuchsia'))
gd.plot_persistence_barcode(barcode,
                            colormap=('navy', 'darkmagenta', 'fuchsia'))
Пример #16
0
''' Record spiking activity of Layer 1 while showing it a bunch of images '''
print("Recording Spikes")
num_images = 1
time_step = 50
spikes = []
for i in tqdm(range(num_images)):
    network.populations[0].set_input(x_train[i])
    spikes.append(network.run(time_step, learning=False, record_spikes=True, pop_index=1).get("spikes"))
    network.rest()
spikes = np.reshape(spikes, (num_neurons, time_step*num_images))


''' Calculate correlation matrix from spiking activity '''
corr = np.zeros((len(spikes), len(spikes)))

print("Calculating correlation matrix")
for i in tqdm(range(len(spikes)-1)):
    for j in range(i+1,len(spikes)):
        corr[i,j] = correlation(spikes[i,:], spikes[j,:], len(spikes[j,:])-50)
        corr[i,j] = 1/(corr[i,j]+.01)

corr = corr + np.transpose(corr)

''' Compute and plot barcodes based on correlation matrix '''
print("Computing Barcodes")
rips_complex = gudhi.RipsComplex(distance_matrix=corr)
simplex_tree = rips_complex.create_simplex_tree(max_dimension=2)
diag_Rips = simplex_tree.persistence()
plt = gudhi.plot_persistence_barcode(diag_Rips)
plt.show()