Exemplo n.º 1
0
def compute_Betti_bumbers(img, th=0.5):
    z, y, x = img.shape
    img_v = img.flatten()
    cc = gd.CubicalComplex(dimensions=(z, y, x),
                           top_dimensional_cells=1 - img_v)
    cc.persistence(min_persistence=th)
    return cc.persistent_betti_numbers(0, th)
Exemplo n.º 2
0
def compute_dgm(f, card, hom_dim):
    """
    Computes the persistence diagram of an image.
    :param f: image
    :param card: maximum number of bars kept
    :param hom_dim: dimension of homology
    :return: persistence diagram, critical pixels
    """
    dgm = np.zeros([card, 2], dtype=np.float32)
    cof = np.zeros([card, 2], dtype=np.int32)
    cc = gd.CubicalComplex(dimensions=f.shape, top_dimensional_cells=f.ravel())
    cc.compute_persistence()
    # Return zero arrays if no finite bars
    num_bars = len(cc.persistence_intervals_in_dimension(hom_dim))
    if ((hom_dim == 0) and (num_bars == 1)) or ((hom_dim > 0) and
                                                (num_bars == 0)):
        return dgm, cof
    # These are all the critical pixels
    all_cof = cc.cofaces_of_persistence_pairs()[0][hom_dim]
    # Generate the persistence diagram
    birth_times, death_times = f.flat[all_cof[:, 0]], f.flat[all_cof[:, 1]]
    # Return at most param:card bars
    min_card = min(len(birth_times), card)
    dgm[:min_card, 0], dgm[:min_card,
                           1] = birth_times[:min_card], death_times[:min_card]
    cof[:min_card, :] = all_cof[:min_card, :]
    return dgm, cof
Exemplo n.º 3
0
def compute_thresh_dgm(f, card, hom_dim, pers_region=None):
    """
    Computes thresholded persistent homology of an image.
    :param f: input image
    :param card: max cardinality of persistence diagram
    :param hom_dim: degree of homology
    :param pers_region: np.array([birth_low, birth_high, lifetime_low, lifetime_high])
    :return: persistence diagram and associated critical pixels
    """
    dgm = np.zeros([card, 2], dtype=np.float32)
    cof = np.zeros([card, 2], dtype=np.int32)
    cc = gd.CubicalComplex(dimensions=f.shape, top_dimensional_cells=f.ravel())
    cc.compute_persistence()
    # Return zero arrays if no finite bars
    num_bars = len(cc.persistence_intervals_in_dimension(hom_dim))
    if ((hom_dim == 0) and (num_bars == 1)) or ((hom_dim > 0) and
                                                (num_bars == 0)):
        return dgm, cof
    # These are all the critical pixels
    all_cof = cc.cofaces_of_persistence_pairs()[0][hom_dim]
    # Generate the persistence diagram
    birth_times, death_times = f.flat[all_cof[:, 0]], f.flat[all_cof[:, 1]]
    # Threshold by persistence region if one was provided
    if pers_region is not None:
        lifetimes = death_times - birth_times
        rel_ind = (pers_region[0] < birth_times) & (birth_times < pers_region[1]) & \
                  (pers_region[2] < lifetimes) & (lifetimes < pers_region[3])
        birth_times, death_times, all_cof = birth_times[rel_ind], death_times[
            rel_ind], all_cof[rel_ind, :]
    min_card = min(len(birth_times), card)
    dgm[:min_card, 0], dgm[:min_card,
                           1] = birth_times[:min_card], death_times[:min_card]
    cof[:min_card, :] = all_cof[:min_card, :]
    return dgm, cof
Exemplo n.º 4
0
def barcode(filt):

    cplx = gudhi.CubicalComplex(dimensions=filt.shape,
                                top_dimensional_cells=filt.flatten(order="F"))
    pd = cplx.persistence(homology_coeff_field=2, min_persistence=0)

    return pd
Exemplo n.º 5
0
def getCriticalPoints(likelihood):

    lh = 1 - likelihood
    lh_vector = np.asarray(lh).flatten()

    lh_cubic = gd.CubicalComplex(dimensions=[lh.shape[0], lh.shape[1]],
                                 top_dimensional_cells=lh_vector)

    Diag_lh = lh_cubic.persistence(homology_coeff_field=2, min_persistence=0)
    pairs_lh = lh_cubic.cofaces_of_persistence_pairs()

    # if(torch.min(lh_patch) == 1 or torch.max(lh_patch) == 0): continue
    # if(torch.min(gt_patch) == 1 or torch.max(gt_patch) == 0): continue

    # return persistence diagram, birth/death critical points
    pd_lh = numpy.array(
        [[lh_vector[pairs_lh[0][0][i][0]], lh_vector[pairs_lh[0][0][i][1]]]
         for i in range(len(pairs_lh[0][0]))])
    bcp_lh = numpy.array([[
        pairs_lh[0][0][i][0] // lh.shape[1], pairs_lh[0][0][i][0] % lh.shape[1]
    ] for i in range(len(pairs_lh[0][0]))])
    dcp_lh = numpy.array([[
        pairs_lh[0][0][i][1] // lh.shape[1], pairs_lh[0][0][i][1] % lh.shape[1]
    ] for i in range(len(pairs_lh[0][0]))])

    return pd_lh, bcp_lh, dcp_lh
Exemplo n.º 6
0
def Cubical(X, dim, card):
    # Parameters: X (image),
    #             dim (homological dimension),
    #             card (number of persistence diagram points, sorted by distance-to-diagonal)

    # Compute the persistence pairs with Gudhi
    cc = gd.CubicalComplex(dimensions=X.shape,
                           top_dimensional_cells=X.flatten())
    cc.persistence()
    try:
        cof = cc.cofaces_of_persistence_pairs()[0][dim]
    except IndexError:
        cof = np.array([])

    Xs = X.shape

    if len(cof) > 0:
        # Sort points with distance-to-diagonal
        pers = [
            X[np.unravel_index(cof[idx, 1], Xs)] -
            X[np.unravel_index(cof[idx, 0], Xs)] for idx in range(len(cof))
        ]
        perm = np.argsort(pers)
        cof = cof[perm[::-1]]

    # Retrieve and ouput image indices/pixels corresponding to positive and negative simplices
    D = len(Xs)
    ocof = np.array([0 for _ in range(D * card * 2)])
    count = 0
    for idx in range(0, min(2 * card, 2 * cof.shape[0]), 2):
        ocof[D * idx:D * (idx + 1)] = np.unravel_index(cof[count, 0], Xs)
        ocof[D * (idx + 1):D * (idx + 2)] = np.unravel_index(cof[count, 1], Xs)
        count += 1
    return list(np.array(ocof, dtype=np.int32))
Exemplo n.º 7
0
def get_persistence_image(img,
                          thresh=128,
                          C=0.5,
                          p=1,
                          size=51,
                          sigma=0.5,
                          win={
                              'xmin': -10.5,
                              'xmax': 60.5,
                              'ymin': -10.5,
                              'ymax': 70.5
                          }):
    arr = np.array(img)
    for i in range(arr.shape[0]):
        for j in range(arr.shape[1]):
            if arr[i, j] > thresh:
                arr[i, j] = 1
            else:
                arr[i, j] = 0

    fil = manhattan(arr)

    cp = gudhi.CubicalComplex(dimensions=fil.shape,
                              top_dimensional_cells=[
                                  fil[i, j]
                                  for i in range(fil.shape[0] - 1, -1, -1)
                                  for j in range(fil.shape[1])
                              ])

    pers = cp.persistence()

    h0 = [p[1] for p in pers if p[0] == 0]
    h1 = [p[1] for p in pers if p[0] == 1]

    def rho(x, y, points):
        somme = 0
        for p in points:
            we = 1
            if p[1] == math.inf:
                we = 1.
                a = np.exp(-((p[0] - x)**2 + (win["ymax"] - y)**2) /
                           (2 * sigma**2))
            else:
                we = w(p[0], p[1])
                a = np.exp(-((p[0] - x)**2 + (p[1] - y)**2) / (2 * sigma**2))
            somme += we * a
        return somme

    xx = np.linspace(win['xmin'], win['xmax'], size)
    yy = np.linspace(win['ymax'], win['ymin'], size)
    image0 = np.zeros((size, size))
    image1 = np.zeros((size, size))
    for j, x in enumerate(xx):
        for i, y in enumerate(yy):
            if (y >= x):
                image0[i, j] = rho(x, y, h0)
                image1[i, j] = rho(x, y, h1)

    return image0, image1
    def _cubical_complex(self, points):
        shape = [points.shape[0]] * 2
        bitmap = np.zeros(shape)
        #  You can do other calculations for the bitmap values,
        # this is just an example I found.
        for i, p1 in enumerate(points):
            for j, p2 in enumerate(points):
                norm = np.linalg.norm(p1 - p2)
                bitmap[i, j] = norm

        cube = gd.CubicalComplex(top_dimensional_cells=bitmap.flatten(),
                                 dimensions=shape)
        diag = cube.persistence()
        return diag
Exemplo n.º 9
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()
Exemplo n.º 10
0
def image_persistence(flare_obj,
                      threshold,
                      SHARP,
                      timeline,
                      intensity,
                      frametime,
                      ftype,
                      hour,
                      PIL=True):
    mask = np.array(flare_obj["PIL_MASK"])
    index = timeline.index(frametime[6:])
    flare_intensity = intensity[index]
    p_feature = [flare_intensity]

    for ch in SHARP:
        image = np.array(flare_obj[ch])

        # preprocess the image for cubical complex construction
        if PIL == True:
            check = np.logical_or(np.isnan(image), mask == 0)
        else:
            check = np.isnan(image)

        image[check] = np.inf
        if (ch in ['Br', 'TOTUSJZ', 'TOTUSJH']):
            image = np.abs(image)

        fname = "./Penseus/" + ch + "_" + ftype + str(hour) + ".txt"
        perseus_gen(image, fname=fname)
        cubical_complex = gudhi.CubicalComplex(perseus_file=fname)
        cubical_complex.compute_persistence()
        cubical_complex.persistence()
        q = threshold[ch]

        for q_value in q.values:
            q_value = float(q_value)
            p_feature.append(
                cubical_complex.persistent_betti_numbers(
                    from_value=q_value, to_value=q_value)[1])  # number
            # of live holes

    for SHARP_feature in [
            'USFLUX', 'MEANGAM', 'MEANGBT', 'MEANGBH', 'MEANGBZ', 'MEANJZD',
            'TOTUSJZ', 'MEANALP', 'TOTUSJH', 'SAVNCPP', 'MEANPOT', 'MEANSHR'
    ]:
        p_feature.append(flare_obj.attrs[SHARP_feature])

    return np.array(p_feature)
Exemplo n.º 11
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"))
Exemplo n.º 12
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()
Exemplo n.º 13
0
def calculate_diagram_gudhi(image):

    reshaped = np.reshape(image, [image.shape[0] * image.shape[1]], order='F')
    # reshapes image to a single vector

    Complex = gudhi.CubicalComplex(dimensions=image.shape,
                                   top_dimensional_cells=reshaped)
    # creates the cubical complex from the image

    Complex.persistence()

    Dgm0 = Complex.persistence_intervals_in_dimension(0)
    # compute oth dimensional persistence diagram

    Dgm1 = Complex.persistence_intervals_in_dimension(1)

    return Dgm0, Dgm1
Exemplo n.º 14
0
def cube_hom(name, array):
    cubical = gd.CubicalComplex(dimensions=array.shape,
                                top_dimensional_cells=array.flatten())

    #Calculate the persistent homology of the filtered cubical complex
    phom = cubical.persistence()

    #Persistence homology per dimension
    phom_0 = cubical.persistence_intervals_in_dimension(0)
    phom_1 = cubical.persistence_intervals_in_dimension(1)
    phom_2 = cubical.persistence_intervals_in_dimension(2)

    #Creating a third column listing dim number
    if len(phom_0) != 0:
        phom_0_form = (np.append(phom_0, np.zeros([len(phom_0), 1]), 1) +
                       np.array([0, 0, 0]))
    else:
        phom_0_form = phom_0

    if len(phom_1) != 0:
        phom_1_form = (np.append(phom_1, np.zeros([len(phom_1), 1]), 1) +
                       np.array([0, 0, 1]))
    else:
        phom_1_form = phom_1

    if len(phom_2) != 0:
        phom_2_form = (np.append(phom_2, np.zeros([len(phom_2), 1]), 1) +
                       np.array([0, 0, 2]))
    else:
        phom_2_form = phom_2

    file_name = str(path) + '/Python_Hom/' + name + ".csv"

    # opening the csv file in 'w+' mode
    file = open(file_name, 'w+', newline='')

    # writing the data into the file
    with file:
        write = csv.writer(file)
        write.writerows(phom_0_form)
        write.writerows(phom_1_form)
        write.writerows(phom_2_form)
Exemplo n.º 15
0
def getCriticalPoints(likelihood):
    """
    Compute the critical points of the image (Value range from 0 -> 1)

    Args:
        likelihood: Likelihood image from the output of the neural networks

    Returns:
        pd_lh:  persistence diagram.
        bcp_lh: Birth critical points.
        dcp_lh: Death critical points.
        Bool:   Skip the process if number of matching pairs is zero.

    """
    lh = 1 - likelihood
    lh_vector = np.asarray(lh).flatten()

    lh_cubic = gd.CubicalComplex(dimensions=[lh.shape[0], lh.shape[1]],
                                 top_dimensional_cells=lh_vector)

    Diag_lh = lh_cubic.persistence(homology_coeff_field=2, min_persistence=0)
    pairs_lh = lh_cubic.cofaces_of_persistence_pairs()

    # If the paris is 0, return False to skip
    if (len(pairs_lh[0]) == 0): return 0, 0, 0, False

    # return persistence diagram, birth/death critical points
    pd_lh = numpy.array(
        [[lh_vector[pairs_lh[0][0][i][0]], lh_vector[pairs_lh[0][0][i][1]]]
         for i in range(len(pairs_lh[0][0]))])
    bcp_lh = numpy.array([[
        pairs_lh[0][0][i][0] // lh.shape[1], pairs_lh[0][0][i][0] % lh.shape[1]
    ] for i in range(len(pairs_lh[0][0]))])
    dcp_lh = numpy.array([[
        pairs_lh[0][0][i][1] // lh.shape[1], pairs_lh[0][0][i][1] % lh.shape[1]
    ] for i in range(len(pairs_lh[0][0]))])

    return pd_lh, bcp_lh, dcp_lh, True
Exemplo n.º 16
0
def compute_persistence_diagram(matrix, min_pers=0, i=5):
    """
        Given a matrix representing a nii image compute the persistence diagram by using the Gudhi library (link)

        :param matrix: matrix encoding the nii image
        :type matrix: np.array

        :param min_pers: minimum persistence interval to be included in the persistence diagram
        :type min_pers: Integer

        :returns: Persistence diagram encoded as a list of tuples [d,x,y]=p where

            * d: indicates the dimension of the d-cycle p

            * x: indicates the birth of p

            * y: indicates the death of p
    """
    #save the dimenions of the matrix
    dims = matrix.shape
    size = reduce(lambda x, y: x * y, dims, 1)

    #create the cubica complex from the image
    cubical_complex = gudhi.CubicalComplex(dimensions=dims,
                                           top_dimensional_cells=np.reshape(
                                               matrix.T, size))
    #compute the persistence diagram
    if i == 5:
        pd = cubical_complex.persistence(homology_coeff_field=2,
                                         min_persistence=min_pers)
        return np.array(map(lambda row: [row[1][0], row[1][1]], pd))
    else:
        pd = cubical_complex.persistence(homology_coeff_field=2,
                                         min_persistence=min_pers)
        pd = cubical_complex.persistence_intervals_in_dimension(i)
        return np.array(list(map(lambda row: [row[0], row[1]], pd)))
Exemplo n.º 17
0
def fractional_lifespancurve(image, height, width, pixel):
    """ Returns a window (needs height h, weight w)
    based on input dimensions and pixel location

    Args
    --------
    image: numpy array
        image to be sliced casted as numpy array
    
    height: int
        desired height for the window image
        
    width: int
        desired width for the window image
    
    pixel: numpy array
        coordinates of where the window will be created

    Returns
    --------
    padded_window: numpy array
        the window sliced from the original image;
        pads the image with 0's if indexing goes
        beyond the image dimensions
        
    """

    # convert image if not numpy array
    if type(image) is not np.array:
        image = np.array(image)

    h = height
    w = width

    n, m = image.shape
    x, y = pixel
    window = np.zeros([h, w])
    for i in range(x, x + h):
        for j in range(y, y + w):
            if i >= n - 1 and j >= m - 1:
                window[i - x, j - y] = 0
            else:
                window[i - x,
                       j - y] = image[i,
                                      j]  #padding out of bounds entry with 0s
    fraction_image = window

    reshaped = np.reshape(fraction_image,
                          [fraction_image.shape[0] * fraction_image.shape[1]],
                          order='F')
    # reshapes image to a single vector

    Complex = gudhi.CubicalComplex(dimensions=fraction_image.shape,
                                   top_dimensional_cells=reshaped)
    # creates the cubical complex from the image

    Complex.persistence()
    Dgm0 = Complex.persistence_intervals_in_dimension(0)
    # compute oth dimensional persistence diagram

    Dgm1 = Complex.persistence_intervals_in_dimension(1)
    # computes 1st dimensional persistenence diagram

    return Dgm0, fraction_image
Exemplo n.º 18
0
from IPython.display import Image
from sklearn.neighbors.kde import KernelDensity

f = open("crater_tuto")
#For python 3
#crater = pickle.load(f,encoding='latin1')
#For python 2
crater = pickle.load(f)
f.close()

plt.scatter(crater[:, 0], crater[:, 1], s=0.1)
plt.show()

#create 10 by 10 cubical complex:
xval = np.arange(0, 10, 0.05)
yval = np.arange(0, 10, 0.05)
nx = len(xval)
ny = len(yval)

#Now we compute the values of the kernel density estimator on the center of each point of our grid.
#The values will be stored in the array scores.
kde = KernelDensity(kernel='gaussian', bandwidth=0.3).fit(crater)
positions = np.array([[u, v] for u in xval for v in yval])
scores = -np.exp(kde.score_samples(X=positions))

#And subsequently construct a cubical complex based on the scores.
cc_density_crater = gd.CubicalComplex(dimensions=[nx, ny],
                                      top_dimensional_cells=scores)
# OPTIONAL
pers_density_crater = cc_density_crater.persistence()
plt = gd.plot_persistence_diagram(pers_density_crater).show()
Exemplo n.º 19
0
#    print(j)
for i in range(0, numwinB):
    #    print (i)
    #    print(windowsA[i,::10])
    V_x = -1.0 * windowsB[i, ::10] / 2
    V_y = (-1.0 / np.sqrt(2)) * windowsB[i, ::10] / 2
    V_z = -0.5 * windowsB[i, ::10] / 2
    V_w = (-1.0 / np.sqrt(5)) * windowsB[i, ::10] / 2
    fieldB[:, i] = 0.5 * (-1.0 * np.kron(np.kron(V_x, V_y), V_z) -
                          1.0 * np.kron(np.kron(V_y, V_z), V_w))
print(np.shape(fieldB))

L_a = np.empty([numwinA, 5000])
for i in range(0, numwinA):
    cubical_complex = gd.CubicalComplex(
        dimensions=[30, 30, 30],
        top_dimensional_cells=fieldA[:, i],
    )
    diag = cubical_complex.persistence(homology_coeff_field=2,
                                       min_persistence=10)
    #gd.plot_persistence_diagram(diag)
    #print(cubical_complex.betti_numbers())

    LS = gd.representations.Landscape(resolution=1000)
    L_a[i, :] = LS.fit_transform(
        [cubical_complex.persistence_intervals_in_dimension(2)])
    print(np.shape(L_a))
L_hatA = np.mean(L_a, axis=0)

L_b = np.empty([numwinB, 5000])
for i in range(0, numwinB):
    cubical_complex = gd.CubicalComplex(
    epilog="Example: "
    "./random_cubical_complex_persistence_example.py"
    " 10 10 10 - Constructs a random cubical "
    "complex in a dimension [10, 10, 10] (aka. "
    "1000 random top dimensional cells).",
)
parser.add_argument("dimension",
                    type=int,
                    nargs="*",
                    help="Cubical complex dimensions")

args = parser.parse_args()
dimension_multiplication = reduce(operator.mul, args.dimension, 1)

if dimension_multiplication > 1:
    print(
        "#####################################################################"
    )
    print("CubicalComplex creation")
    cubical_complex = gudhi.CubicalComplex(
        dimensions=args.dimension,
        top_dimensional_cells=numpy.random.rand(dimension_multiplication),
    )

    print("persistence(homology_coeff_field=2, min_persistence=0)=")
    print(
        cubical_complex.persistence(homology_coeff_field=2, min_persistence=0))

    print("betti_numbers()=")
    print(cubical_complex.betti_numbers())
Exemplo n.º 21
0
import matplotlib.pyplot as plt
import numpy as np
import random as rd
from mpl_toolkits.mplot3d import Axes3D
import csv
from sklearn import decomposition
import math
import gudhi as gd
from PIL import Image

#in this example we are considering two dimensional complexes
N = 100

#this is where you set the probability:
p = 0.6

bitmap = []
for i in range(0,N*N):
	x = rd.uniform(0, 1)
	if ( x < p ): bitmap.append(1)
	else: bitmap.append(0)

bcc = gd.CubicalComplex(top_dimensional_cells = bitmap, dimensions=[N,N])
diag = bcc.persistence()
#now we can check how many generators in dimension 0 and in dimension 1 we have:
dim0 = bcc.persistence_intervals_in_dimension(0)
dim1 = bcc.persistence_intervals_in_dimension(1)

print "Here is the first Betti number: ", len(dim0)
print "Here is the second Betti number: ", len(dim1)
Exemplo n.º 22
0
    img_arr = np.squeeze(np.stack(images,axis=-1))
    if args.distance_transform:
        img_arr = dt(img_arr)
    print("input shape: ",img_arr.shape)

    start = time.time()
    if args.software=="gudhi":
        try:
            import gudhi
        except:
            print("Install pydicom first by: conda install -c conda-forge gudhi")
            exit()
        
        print("Computing PH with GUDHI (T-construction)")
        gd = gudhi.CubicalComplex(top_dimensional_cells=img_arr)
    #    gd.compute_persistence()
        res = np.array(gd.persistence(2,0)) # coeff = 2
        print("Betti numbers: ", gd.persistent_betti_numbers(np.inf,-np.inf))

    else:
        if args.filtration=='V':
            res = cripser.computePH(img_arr,maxdim=args.maxdim,top_dim=args.top_dim,embedded=args.embedded)
        else:
            res = tcripser.computePH(img_arr,maxdim=args.maxdim,top_dim=args.top_dim,embedded=args.embedded)
        print("Betti numbers: ", [res[res[:,0]==i].shape[0] for i in range(3)])
    #    print(res[:10])

    print ("computation took:{} [sec]".format(time.time() - start))

    if args.output is not None:
Exemplo n.º 23
0
def Persistence_windows(image, height, width , pixel):
    """ Returns a window (needs height h, weight w)
    based on input dimensions and pixel location

    Args
    --------
    image: numpy array
        image to be sliced casted as numpy array
    
    height: int
        desired height for the window image
        
    width: int
        desired width for the window image
    
    pixel: numpy array
        coordinates of where the window will be created

    Returns
    --------
    padded_window: numpy array
        the window sliced from the original image;
        pads the image with 0's if indexing goes
        beyond the image dimensions
        
    """

    # convert image if not numpy array
    if type(image) is not np.array:
        image = np.array(image)

    h = height
    w = width

    n, m = image.shape
    x,y = pixel
    window = np.zeros([h,w])
    diskwindow = np.zeros([h,w])

    for i in range(x, x+h):
        for j in range(y, y+w):
            if i >= n-1 or j >= m-1: 

                #we discuss this earlier but afterwards
                #I realize the "and" statement is justified 
                #since we start with an array of 0 and later 
                #add values.  Hence the "or" case would be zeroed out 
                #regardless.

                window[i-x,j-y]= float('inf')
            else:
                window[i-x,j-y] = image[i,j] #padding out of bounds entry with 256s
    test = window
    fraction_image = disk_window(test) 

    reshaped = np.reshape(fraction_image, [fraction_image.shape[0]*fraction_image.shape[1]], order = 'F')
    # reshapes image to a single vector

    Complex = gudhi.CubicalComplex(dimensions=fraction_image.shape, top_dimensional_cells=reshaped)
    # creates the cubical complex from the image

    Complex.persistence()
    Dgm0=Complex.persistence_intervals_in_dimension(0)
    # compute oth dimensional persistence diagram

    Dgm1=Complex.persistence_intervals_in_dimension(1)
    # computes 1st dimensional persistenence diagram

    return Dgm0,Dgm1, fraction_image
Exemplo n.º 24
0
from matplotlib import pyplot as plt

N = 100
array = np.zeros((2*N+1,2*N+1))
xExtrem = 2;
yExtrem = 2;

bitmap = []
for i in range(0,2*N+1):
	for j in range (0,2*N+1):
		x = i/(2*float(N)+1)*2*float(xExtrem)-xExtrem
		y = j/(2*float(N)+1)*2*float(xExtrem)-xExtrem
		norm = math.sqrt( x*x + y*y )
		norm =  math.fabs(norm-1)
		array[i][j] = norm
		bitmap.append(norm)


#Here we will display our creation:
plt.imshow(array, cmap='gray', interpolation='nearest', vmin=np.amin(array), vmax=np.amax(array))
#plt.savefig('circle.png')
plt.show()

#Given the input data we can buld a Gudhi btmap cubical complex:
bcc = gd.CubicalComplex(top_dimensional_cells = bitmap, dimensions=[2*N+1,2*N+1])
#optional computation of persistence
#persistence = bcc.persistence()
#plt = gd.plot_persistence_diagram(persistence)
#plt.show()

Exemplo n.º 25
0
    else:
        IMG = [X[0][0][j] for j in range(len(X[0][0]))][::step] + [X[1][0][j] for j in range(len(X[1][0]))][::step]
        LAB = [X[0][1][j] for j in range(len(X[0][0]))][::step] + [X[1][1][j] for j in range(len(X[1][0]))][::step]
        ntrain = len(np.arange(len(X[0][0]))[::step])
        train_idxs, test_idxs = np.arange(0, ntrain), np.arange(ntrain, len(IMG))

    DGMb = []
    for pdi in range(num_filts):
        DGMi = []
        for j, img in enumerate(IMG):
            inds = np.argwhere(img > 0)
            I = np.inf * np.ones(img.shape)
            for i in range(len(inds)):
                val = np.cos(Cinit[pdi])*inds[i,0] + np.sin(Cinit[pdi])*inds[i,1]
                I[inds[i,0], inds[i,1]] = val
            ccb = gd.CubicalComplex(top_dimensional_cells=I)
            ccb.persistence()
            dgmb = ccb.persistence_intervals_in_dimension(hdim)
            DGMi.append(dgmb)

            if j == -1:
                vm, vM = min(list(I[I!=np.inf].flatten())), max(list(I[I!=np.inf].flatten()))
                plt.figure()
                plt.imshow(I, vmin=vm, vmax=vM)
                plt.colorbar()
                plt.savefig(str(j) + '_' + '{:.2f}'.format(Cinit[pdi]) + '.png')

        DGMb.append(DGMi)

elif data_type == 'GRAPHS':