def test_hk_shape(n_jobs, pts, dims):
    n_bins = 10
    X = get_input(pts, dims)
    sigma = (np.max(X[:, :, :2]) - np.min(X[:, :, :2])) / 2

    hk = HeatKernel(sigma=sigma, n_bins=n_bins, n_jobs=n_jobs)
    num_dimensions = len(np.unique(dims))
    X_t = hk.fit_transform(X)

    assert X_t.shape == (X.shape[0], num_dimensions, n_bins, n_bins)
Пример #2
0
def test_hk_positive(pts, dims):
    """ We expect the points above the PD-diagonal to be non-negative,
    (up to a numerical error)"""
    n_bins = 10
    hk = HeatKernel(sigma=1, n_bins=n_bins)

    x = get_input(pts, dims)
    x_t = hk.fit(x).transform(x)

    assert np.all((np.tril(x_t[:, :, ::-1, :]) + 1e-13) >= 0.)
Пример #3
0
def test_hk_big_sigma(pts, dims):
    """ We expect that with a huge sigma, the diagrams are so diluted that
    they are almost 0. Effectively, verifies that the smoothing is applied."""
    n_bins = 10
    x = get_input(pts, dims)

    hk = HeatKernel(sigma=100*np.max(np.abs(x)), n_bins=n_bins)
    x_t = hk.fit(x).transform(x)

    assert np.all(np.abs(x_t) <= 1e-4)
def test_hk_positive(pts, dims):
    """We expect the points above the PD-diagonal to be non-negative (up to a
    numerical error)"""
    n_bins = 10
    X = get_input(pts, dims)
    sigma = (np.max(X[:, :, :2]) - np.min(X[:, :, :2])) / 2

    hk = HeatKernel(sigma=sigma, n_bins=n_bins)
    X_t = hk.fit_transform(X)

    assert np.all((np.tril(X_t[:, :, ::-1, :]) + 1e-13) >= 0.)
def test_large_hk_shape_parallel():
    """Test that HeatKernel returns something of the right shape when the input
    array is at least 1MB and more than 1 process is used, triggering joblib's
    use of memmaps"""
    X = np.linspace(0, 100, 300000)
    n_bins = 10
    diagrams = np.expand_dims(np.stack([X, X, np.zeros(len(X))]).transpose(),
                              axis=0)

    hk = HeatKernel(sigma=1, n_bins=n_bins, n_jobs=2)
    num_dimensions = 1
    x_t = hk.fit_transform(diagrams)

    assert x_t.shape == (diagrams.shape[0], num_dimensions, n_bins, n_bins)
def test_hk_with_diag_points(pts):
    """Add points on the diagonal, and verify that we have the same results
    (on the same fitted values)."""
    n_bins = 10
    hk = HeatKernel(sigma=1, n_bins=n_bins)

    X = get_input(pts, np.zeros((pts.shape[0], pts.shape[1], 1)))
    diag_points = np.array([[[2, 2, 0], [3, 3, 0], [7, 7, 0]]])
    X_with_diag_points = np.concatenate([X, diag_points], axis=1)

    hk = hk.fit(X_with_diag_points)

    X_t, X_with_diag_points_t = [hk.transform(X_)
                                 for X_ in [X, X_with_diag_points]]

    assert_almost_equal(X_with_diag_points_t, X_t, decimal=13)
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)
Пример #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")
Пример #9
0
def test_all_pts_the_same():
    X = np.zeros((1, 4, 3))
    hk = HeatKernel(sigma=1)
    with pytest.raises(IndexError):
        _ = hk.fit(X).transform(X)
def get_heat_kernel(persistence_diagram):
    pi = HeatKernel(sigma=0.001, n_bins=N_BINS, n_jobs=N_JOBS)
    print("Computed heat kernel")
    return pi.fit_transform(persistence_diagram)
    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,
        plotly_params=plotly_params
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,