def test_silhouette_transform(n_jobs):
    sht = Silhouette(n_bins=31, power=1., n_jobs=n_jobs)
    X_sht_res = np.array([0., 0.05, 0.1, 0.15, 0.2, 0.25, 0.2, 0.15, 0.1,
                          0.05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0., 0.05,
                          0.1, 0.15, 0.2, 0.25, 0.2, 0.15, 0.1, 0.05, 0.])

    assert_almost_equal(sht.fit_transform(X)[0][0], X_sht_res)
def test_silhouette_transform():
    sht = Silhouette(n_bins=31, order=1.)
    X_sht_res = np.array([0., 0.05, 0.1, 0.15, 0.2, 0.25, 0.2, 0.15, 0.1,
                          0.05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0., 0.05,
                          0.1, 0.15, 0.2, 0.25, 0.2, 0.15, 0.1, 0.05, 0.])

    assert_almost_equal(sht.fit_transform(diagram)[0][0], X_sht_res)
def test_silhouette_big_order():
    diagrams = np.array([[[0, 2, 0], [1, 4, 0]]])
    sht_10 = Silhouette(n_bins=41, power=10.)
    X_sht_res = np.array([
        0., 0.00170459, 0.00340919, 0.00511378, 0.00681837, 0.00852296,
        0.01022756, 0.01193215, 0.01363674, 0.01534133, 0.01704593, 0.11363674,
        0.21022756, 0.30681837, 0.40340919, 0.5, 0.59659081, 0.69318163,
        0.78977244, 0.88636326, 0.98295407, 1.08124948, 1.17954489, 1.27784029,
        1.3761357, 1.47443111, 1.3761357, 1.27784029, 1.17954489, 1.08124948,
        0.98295407, 0.88465867, 0.78636326, 0.68806785, 0.58977244, 0.49147704,
        0.39318163, 0.29488622, 0.19659081, 0.09829541, 0.
    ])

    assert_almost_equal(sht_10.fit_transform(diagrams)[0][0], X_sht_res)
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)
Example #5
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_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)
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,
        plotly_params=plotly_params
        )
               [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,
                                   plotly_params=plotly_params)