示例#1
0
def cubical_persistence(images,
                        title,
                        plot_diagrams=False,
                        betti_curves=False,
                        scaled=False):
    homology_dimensions = (0, 1, 2)
    cp = CubicalPersistence(
        homology_dimensions=homology_dimensions,
        coeff=2,
        periodic_dimensions=None,
        infinity_values=None,
        reduced_homology=True,
        n_jobs=N_JOBS,
    )
    diagrams_cubical_persistence = cp.fit_transform(images)
    if scaled:
        sc = Scaler(metric="bottleneck")
        diagrams_cubical_persistence = sc.fit_transform(
            diagrams_cubical_persistence)
    else:
        scaled_diagrams_cubical_persistence = diagrams_cubical_persistence

    if plot_diagrams:
        fig = cp.plot(diagrams_cubical_persistence)
        fig.update_layout(title=title)
        fig.show()
    if betti_curves:
        BC = BettiCurve()
        X_betti_curves = BC.fit_transform(diagrams_cubical_persistence)
        fig = BC.plot(X_betti_curves)
        fig.update_layout(title=title)
        fig.show()
    if title is not None:
        print(f"Computed CP for {title}")
    return diagrams_cubical_persistence
示例#2
0
def vr_persistent_homology(patch_pc):
    homology_dimensions = (0, 1, 2)
    VR = VietorisRipsPersistence(
        metric="euclidean",
        max_edge_length=5,
        homology_dimensions=homology_dimensions,
        n_jobs=N_JOBS,
    )
    diagrams_VietorisRips = VR.fit_transform(np.asarray(patch_pc))
    VR.plot(diagrams_VietorisRips).show()
    BC = BettiCurve()
    X_betti_curves = BC.fit_transform(diagrams_VietorisRips)
    BC.plot(X_betti_curves).show()
    return diagrams_VietorisRips
 def extract_feature_(self, persistence_diagram):
     betti_curve = BettiCurve(n_jobs=-1).fit_transform(
         [persistence_diagram])[0]
     return np.array([
         np.sum(betti_curve[i, :])
         for i in range(int(np.max(persistence_diagram[:, 2])) + 1)
     ])
 def extract_feature_(self, persistence_diagram, n_bins=100):
     betti_curve = BettiCurve(n_jobs=-1, n_bins=n_bins).fit_transform(
         [persistence_diagram])[0]
     max_dim = int(np.max(persistence_diagram[:, 2])) + 1
     max_bettis = np.array(
         [np.max(betti_curve[i, :]) for i in range(max_dim)])
     return np.array([
         np.where(betti_curve[i, :] == max_bettis[i])[0][0] /
         (n_bins * max_dim) for i in range(max_dim)
     ])
示例#5
0
def bettiCurve_pipe2(img_file):
    """
    Pipeline 2: Cubical Perisitance --> Betti Curve
    """
    img = cv2.imread(img_file)
    img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    # blur the image to reduce noise
    figure_size = 9  # the dimension of the x and y axis of the kernal.
    # img = cv2.blur(img,(figure_size, figure_size))

    shape = img.shape
    images = np.zeros((1, *shape))
    images[0] = img
    p = make_pipeline(CubicalPersistence(), BettiCurve(n_bins=50))
    return p.fit_transform(images)
def test_not_fitted():
    with pytest.raises(NotFittedError):
        PersistenceEntropy().transform(X)

    with pytest.raises(NotFittedError):
        BettiCurve().transform(X)

    with pytest.raises(NotFittedError):
        PersistenceLandscape().transform(X)

    with pytest.raises(NotFittedError):
        HeatKernel().transform(X)

    with pytest.raises(NotFittedError):
        PersistenceImage().transform(X)

    with pytest.raises(NotFittedError):
        Silhouette().transform(X)
示例#7
0
def bettiCurve_pipe1(img_file):
    """
    Pipeline 1: Binarizer --> Height Filtration --> Cubical Persistance --> Betti Curve
    """
    img = cv2.imread(img_file)
    img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    # blur the image to reduce noise
    figure_size = 9  # the dimension of the x and y axis of the kernal.
    img = cv2.blur(img, (figure_size, figure_size))

    shape = img.shape
    images = np.zeros((1, *shape))
    images[0] = img
    bz = Binarizer(threshold=40 / 255)
    binned = bz.fit_transform(images)
    p = make_pipeline(HeightFiltration(direction=np.array([1, 1])),
                      CubicalPersistence(), BettiCurve(n_bins=50))
    return p.fit_transform(binned)
示例#8
0
def generate_sample_representations(paths_to_patches, labels):
    sample_rep_dir = DOTENV_KEY2VAL["GEN_FIGURES_DIR"] + "/sample_rep/"
    try:
        os.mkdir(sample_rep_dir)
    except OSError:
        print("Creation of the directory %s failed" % sample_rep_dir)
    else:
        print("Successfully created the directory %s " % sample_rep_dir)
    for i, path in enumerate(paths_to_patches):
        patch = np.load(path)

        cp = CubicalPersistence(
            homology_dimensions=(0, 1, 2),
            coeff=2,
            periodic_dimensions=None,
            infinity_values=None,
            reduced_homology=True,
            n_jobs=N_JOBS,
        )
        diagrams_cubical_persistence = cp.fit_transform(
            patch.reshape(1, 30, 36, 30)
        )
        for h_dim in HOMOLOGY_DIMENSIONS:
            cp.plot(
                diagrams_cubical_persistence,
                homology_dimensions=[h_dim],
            ).update_traces(
                marker=dict(size=10, color=HOMOLOGY_CMAP[h_dim]),
            ).write_image(
                sample_rep_dir
                + f"persistence_diagram_{labels[i]}_H_{h_dim}.png",
                scale=SCALE,
            )

        representation_names = [
            "Persistence landscape",
            "Betti curve",
            "Persistence image",
            "Heat kernel",
            "Silhouette",
        ]

        for j, rep in enumerate(representation_names):
            # Have not found a better way of doing this yet.
            if rep == "Persistence landscape":
                rep = PersistenceLandscape(
                    n_layers=N_LAYERS, n_bins=VEC_SIZE, n_jobs=N_JOBS
                )
            elif rep == "Betti curve":
                rep = BettiCurve()
            elif rep == "Persistence image":
                rep = PersistenceImage(
                    sigma=0.001, n_bins=VEC_SIZE, n_jobs=N_JOBS
                )
            elif rep == "Heat kernel":
                rep = HeatKernel(sigma=0.001, n_bins=VEC_SIZE, n_jobs=N_JOBS)
            elif rep == "Silhouette":
                rep = Silhouette(power=1.0, n_bins=VEC_SIZE, n_jobs=N_JOBS)

            vectorial_representation = rep.fit_transform(
                diagrams_cubical_persistence
            )

            if representation_names[j] in ["Persistence image", "Heat kernel"]:
                for h_dim in range(vectorial_representation.shape[1]):
                    plt.imshow(
                        vectorial_representation[0:, h_dim, :, :].reshape(
                            VEC_SIZE, VEC_SIZE
                        ),
                        cmap=(HOMOLOGY_CMAP[h_dim] + "s").capitalize(),
                    )
                    # plt.title(
                    #     f"{representation_names[j]} representation of a "
                    #     f"{labels[i]} patient in h_{image}"
                    # )
                    plt.savefig(
                        sample_rep_dir
                        + f"{representation_names[j].replace(' ', '_')}"
                        f"_{labels[i]}_h_{h_dim}.png",
                        bbox_inches="tight",
                    )
            else:
                rep.plot(vectorial_representation).update_layout(
                    title=None,
                    margin=dict(l=0, r=0, b=0, t=0, pad=4),
                ).write_image(
                    sample_rep_dir
                    + f"{representation_names[j].replace(' ', '_')}"
                    f"_{labels[i]}.png",
                    scale=SCALE,
                )
        print(f"Done plotting {labels[i]} sample")
def test_bc_transform_shape(n_bins):
    bc = BettiCurve(n_bins=n_bins)
    X_res = bc.fit_transform(X)
    assert X_res.shape == (1, bc._n_dimensions, n_bins)
def test_fit_transform_plot_many_hom_dims(hom_dims):
    BettiCurve().fit_transform_plot(X, sample=0, homology_dimensions=hom_dims)
    PersistenceLandscape().fit_transform_plot(X,
                                              sample=0,
                                              homology_dimensions=hom_dims)
    Silhouette().fit_transform_plot(X, sample=0, homology_dimensions=hom_dims)
    ComplexPolynomial, BettiCurve, PersistenceLandscape, HeatKernel, \
    PersistenceImage, Silhouette

pio.renderers.default = 'plotly_mimetype'

X = np.array([[[0., 0., 0.], [0., 1., 0.], [2., 3., 0.],
               [4., 6., 1.], [2., 6., 1.]]])

line_plots_traces_params = {"mode": "lines+markers"}
heatmap_trace_params = {"colorscale": "viridis"}
layout_params = {"title": "New title"}


@pytest.mark.parametrize('transformer',
                         [PersistenceEntropy(), NumberOfPoints(),
                          ComplexPolynomial(), BettiCurve(),
                          PersistenceLandscape(), HeatKernel(),
                          PersistenceImage(), Silhouette()])
def test_not_fitted(transformer):
    with pytest.raises(NotFittedError):
        transformer.transform(X)


@pytest.mark.parametrize('transformer',
                         [HeatKernel(), PersistenceImage()])
@pytest.mark.parametrize('hom_dim_idx', [0, 1])
def test_fit_transform_plot_one_hom_dim(transformer, hom_dim_idx):
    plotly_params = \
        {"trace": heatmap_trace_params, "layout": layout_params}
    transformer.fit_transform_plot(
        X, sample=0, homology_dimension_idx=hom_dim_idx,
pio.renderers.default = 'plotly_mimetype'

X = np.array([[[0., 0., 0.], [0., 1., 0.], [2., 3., 0.], [4., 6., 1.],
               [2., 6., 1.]]])

line_plots_traces_params = {"mode": "lines+markers"}
heatmap_trace_params = {"colorscale": "viridis"}
layout_params = {"title": "New title"}


@pytest.mark.parametrize('transformer', [
    PersistenceEntropy(),
    NumberOfPoints(),
    ComplexPolynomial(),
    BettiCurve(),
    PersistenceLandscape(),
    HeatKernel(),
    PersistenceImage(),
    Silhouette()
])
def test_not_fitted(transformer):
    with pytest.raises(NotFittedError):
        transformer.transform(X)


@pytest.mark.parametrize('transformer', [HeatKernel(), PersistenceImage()])
@pytest.mark.parametrize('hom_dim_idx', [0, 1])
def test_fit_transform_plot_one_hom_dim(transformer, hom_dim_idx):
    plotly_params = \
        {"trace": heatmap_trace_params, "layout": layout_params}