예제 #1
0
def get_persistence_images(persistence_diagram):
    pi = PersistenceImage(sigma=0.001,
                          n_bins=N_BINS,
                          weight_function=None,
                          n_jobs=N_JOBS)
    print("Computed persistence images")
    return pi.fit_transform(persistence_diagram)
def test_pi_positive(pts):
    pi = PersistenceImage(sigma=1)
    diagrams = np.expand_dims(np.concatenate(
        [np.sort(pts, axis=1),
         np.zeros((pts.shape[0], 1))], axis=1),
                              axis=0)
    assert np.all(pi.fit_transform(diagrams) >= 0.)
def test_pi_positive(pts):
    diagrams = np.expand_dims(np.concatenate(
        [np.sort(pts, axis=1),
         np.zeros((pts.shape[0], 1))], axis=1),
                              axis=0)
    sigma = (np.max(diagrams[:, :, 1] - np.min(diagrams[:, :, 0]))) / 2
    pi = PersistenceImage(sigma=sigma)
    assert np.all(pi.fit_transform(diagrams) >= 0.)
예제 #4
0
def persistence_image(persistence_diagram, sigma, title):
    pi = PersistenceImage(sigma=sigma,
                          n_bins=100,
                          weight_function=None,
                          n_jobs=N_JOBS)
    persistence_image = pi.fit_transform(persistence_diagram)
    fig = pi.plot(persistence_image)
    fig.update_layout(title=title).show()
    return persistence_image
def test_large_pi_null_parallel():
    """Test that pi is computed correctly 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)
    pi = PersistenceImage(sigma=1, n_bins=10, n_jobs=2)
    diagrams = np.expand_dims(np.stack([X, X, np.zeros(len(X))]).transpose(),
                              axis=0)
    diagrams = np.repeat(diagrams, 2, axis=0)
    diagrams[1, :, 1] += 1

    assert_almost_equal(pi.fit_transform(diagrams)[0], 0)
def test_pi_null(X):
    """Test that, if one trivial diagram (all pts on the diagonal) is provided,
    (along with a non-trivial one), then its pi is null"""
    pi = PersistenceImage(sigma=1, n_bins=10)
    X = np.append(X, 1 + X[-1])
    diagrams = np.expand_dims(np.stack(
        [X, X, np.zeros((X.shape[0], ), dtype=int)]).transpose(),
                              axis=0)
    diagrams = np.repeat(diagrams, 2, axis=0)
    diagrams[1, :, 1] += 1

    assert_almost_equal(pi.fit_transform(diagrams)[0], 0)
def test_pi_null(X):
    """Test that, if one trivial diagram (all pts on the diagonal) is provided,
    along with a non-trivial one, then its persistence image is null"""
    n_bins = 10
    X = np.append(X, 1 + X[-1])
    diagrams = np.expand_dims(np.stack([X, X, np.zeros(len(X))]).transpose(),
                              axis=0)
    diagrams = np.repeat(diagrams, 2, axis=0)
    diagrams[1, :, 1] += 1

    sigma = (np.max(diagrams[:, :, 1] - np.min(diagrams[:, :, 0]))) / 2
    pi = PersistenceImage(sigma=sigma, n_bins=n_bins)

    assert_almost_equal(pi.fit_transform(diagrams)[0], 0)
def test_fit_transform_plot_one_hom_dim(hom_dim_ix):
    HeatKernel().fit_transform_plot(X,
                                    sample=0,
                                    homology_dimension_ix=hom_dim_ix)
    PersistenceImage().fit_transform_plot(X,
                                          sample=0,
                                          homology_dimension_ix=hom_dim_ix)
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)
예제 #10
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")
예제 #11
0
def test_pi_not_fitted():
    pi = PersistenceImage(sigma=1)
    with pytest.raises(NotFittedError):
        pi.transform(diagram)
def test_pi_zero_weight_function(n_jobs):
    pi = PersistenceImage(weight_function=lambda x: x * 0., n_jobs=n_jobs)
    X_res = pi.fit_transform(X)
    assert np.array_equal(X_res, np.zeros_like(X_res))
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,
                                   homology_dimension_idx=hom_dim_idx,