Beispiel #1
0
def test_colorscale_asymmetric_cmap_vmax():
    cmap = 'jet'
    values = np.arange(15)
    colors = js_plotting_utils.colorscale(cmap, values, vmax=7,
                                          symmetric_cmap=False)
    assert (colors['vmin'], colors['vmax']) == (0, 7)
    assert colors['cmap'].N == 256
    assert (colors['norm'].vmax, colors['norm'].vmin) == (7, 0)
    assert not colors['symmetric_cmap']
    values = np.arange(15) + 3
    colors = js_plotting_utils.colorscale(cmap, values, vmax=7,
                                          symmetric_cmap=False)
    assert (colors['vmin'], colors['vmax']) == (3, 7)
    assert (colors['norm'].vmax, colors['norm'].vmin) == (7, 3)
    colors = js_plotting_utils.colorscale(
        cmap, values, vmax=7, symmetric_cmap=False, vmin=1)
    assert (colors['vmin'], colors['vmax']) == (1, 7)
    assert (colors['norm'].vmax, colors['norm'].vmin) == (7, 1)
    colors = js_plotting_utils.colorscale(
        cmap, values, vmax=10, symmetric_cmap=False, vmin=6, threshold=5)
    assert (colors['vmin'], colors['vmax']) == (0, 10)
    assert (colors['norm'].vmax, colors['norm'].vmin) == (10, 0)
    colors = js_plotting_utils.colorscale(
        cmap, values, vmax=10, symmetric_cmap=False, vmin=None, threshold=5)
    assert (colors['vmin'], colors['vmax']) == (0, 10)
    assert (colors['norm'].vmax, colors['norm'].vmin) == (10, 0)
def test_colorscale_asymmetric_cmap_vmax():
    cmap = 'jet'
    values = np.arange(15)
    colors = js_plotting_utils.colorscale(cmap, values, vmax=7,
                                          symmetric_cmap=False)
    assert (colors['vmin'], colors['vmax']) == (0, 7)
    assert colors['cmap'].N == 256
    assert (colors['norm'].vmax, colors['norm'].vmin) == (7, 0)
    assert not colors['symmetric_cmap']
    values = np.arange(15) + 3
    colors = js_plotting_utils.colorscale(cmap, values, vmax=7,
                                          symmetric_cmap=False)
    assert (colors['vmin'], colors['vmax']) == (3, 7)
    assert (colors['norm'].vmax, colors['norm'].vmin) == (7, 3)
    colors = js_plotting_utils.colorscale(
        cmap, values, vmax=7, symmetric_cmap=False, vmin=1)
    assert (colors['vmin'], colors['vmax']) == (1, 7)
    assert (colors['norm'].vmax, colors['norm'].vmin) == (7, 1)
    colors = js_plotting_utils.colorscale(
        cmap, values, vmax=10, symmetric_cmap=False, vmin=6, threshold=5)
    assert (colors['vmin'], colors['vmax']) == (0, 10)
    assert (colors['norm'].vmax, colors['norm'].vmin) == (10, 0)
    colors = js_plotting_utils.colorscale(
        cmap, values, vmax=10, symmetric_cmap=False, vmin=None, threshold=5)
    assert (colors['vmin'], colors['vmax']) == (0, 10)
    assert (colors['norm'].vmax, colors['norm'].vmin) == (10, 0)
Beispiel #3
0
def test_colorscale_no_threshold():
    cmap = 'jet'
    values = np.linspace(-13, -1.5, 20)
    threshold = None
    colors = js_plotting_utils.colorscale(cmap, values, threshold)
    check_colors(colors['colors'])
    assert (colors['vmin'], colors['vmax']) == (-13, 13)
    assert colors['cmap'].N == 256
    assert (colors['norm'].vmax, colors['norm'].vmin) == (13, -13)
    assert colors['abs_threshold'] is None
    colors = js_plotting_utils.colorscale(cmap, values > 0, .5)
def test_colorscale_asymmetric_cmap():
    cmap = 'jet'
    values = np.arange(15)
    colors = js_plotting_utils.colorscale(cmap, values, symmetric_cmap=False)
    assert (colors['vmin'], colors['vmax']) == (0, 14)
    assert colors['cmap'].N == 256
    assert (colors['norm'].vmax, colors['norm'].vmin) == (14, 0)
    assert not colors['symmetric_cmap']
    values = np.arange(15) + 3
    colors = js_plotting_utils.colorscale(cmap, values, symmetric_cmap=False)
    assert (colors['vmin'], colors['vmax']) == (3, 17)
    assert (colors['norm'].vmax, colors['norm'].vmin) == (17, 3)
def test_colorscale_asymmetric_cmap():
    cmap = 'jet'
    values = np.arange(15)
    colors = js_plotting_utils.colorscale(cmap, values, symmetric_cmap=False)
    assert (colors['vmin'], colors['vmax']) == (0, 14)
    assert colors['cmap'].N == 256
    assert (colors['norm'].vmax, colors['norm'].vmin) == (14, 0)
    assert not colors['symmetric_cmap']
    values = np.arange(15) + 3
    colors = js_plotting_utils.colorscale(cmap, values, symmetric_cmap=False)
    assert (colors['vmin'], colors['vmax']) == (3, 17)
    assert (colors['norm'].vmax, colors['norm'].vmin) == (17, 3)
def test_colorscale_vmin_vmax():
    cmap = 'jet'
    values = np.arange(15)
    colors = js_plotting_utils.colorscale(cmap, values, vmax=7)
    assert (colors['vmin'], colors['vmax']) == (-7, 7)
    assert colors['cmap'].N == 256
    assert (colors['norm'].vmax, colors['norm'].vmin) == (7, -7)
    assert colors['symmetric_cmap']
    colors = js_plotting_utils.colorscale(cmap, values, vmax=7, vmin=-5)
    assert (colors['vmin'], colors['vmax']) == (-7, 7)
    assert colors['cmap'].N == 256
    assert (colors['norm'].vmax, colors['norm'].vmin) == (7, -7)
    assert colors['symmetric_cmap']
def test_colorscale_vmin_vmax():
    cmap = 'jet'
    values = np.arange(15)
    colors = js_plotting_utils.colorscale(cmap, values, vmax=7)
    assert (colors['vmin'], colors['vmax']) == (-7, 7)
    assert colors['cmap'].N == 256
    assert (colors['norm'].vmax, colors['norm'].vmin) == (7, -7)
    assert colors['symmetric_cmap']
    colors = js_plotting_utils.colorscale(
        cmap, values, vmax=7, vmin=-5)
    assert (colors['vmin'], colors['vmax']) == (-7, 7)
    assert colors['cmap'].N == 256
    assert (colors['norm'].vmax, colors['norm'].vmin) == (7, -7)
    assert colors['symmetric_cmap']
Beispiel #8
0
def test_colorscale_asymmetric_cmap_negative_values():
    cmap = 'jet'
    values = np.linspace(-15, 4)
    with pytest.warns(UserWarning):
        js_plotting_utils.colorscale(cmap, values, symmetric_cmap=False)

    colors = js_plotting_utils.colorscale(cmap,
                                          values,
                                          vmax=7,
                                          symmetric_cmap=False)
    assert (colors['vmin'], colors['vmax']) == (-7, 7)
    assert colors['cmap'].N == 256
    assert (colors['norm'].vmax, colors['norm'].vmin) == (7, -7)
    assert colors['symmetric_cmap']
Beispiel #9
0
def test_colorscale_symmetric_cmap(vmin, vmax):
    """Test colorscale with symmetric cmap and positive values."""
    colors = colorscale('jet', np.arange(15), vmin=vmin, vmax=vmax)
    assert (colors['vmin'], colors['vmax']) == (-7, 7)
    assert colors['cmap'].N == 256
    assert (colors['norm'].vmax, colors['norm'].vmin) == (7, -7)
    assert colors['symmetric_cmap']
Beispiel #10
0
def one_mesh_info(surf_map,
                  surf_mesh,
                  threshold=None,
                  cmap=cm.cold_hot,
                  black_bg=False,
                  bg_map=None,
                  symmetric_cmap=True,
                  vmax=None,
                  vmin=None):
    """Prepare info for plotting one surface map on a single mesh.

    This computes the dictionary that gets inserted in the web page,
    which contains the encoded mesh, colors, min and max values, and
    background color.

    """
    info = {}
    colors = colorscale(cmap,
                        surf_map,
                        threshold,
                        symmetric_cmap=symmetric_cmap,
                        vmax=vmax,
                        vmin=vmin)
    info['inflated_left'] = mesh_to_plotly(surf_mesh)
    info['vertexcolor_left'] = _get_vertexcolor(surf_map, colors['cmap'],
                                                colors['norm'],
                                                colors['abs_threshold'],
                                                bg_map)
    info["cmin"], info["cmax"] = float(colors['vmin']), float(colors['vmax'])
    info['black_bg'] = black_bg
    info['full_brain_mesh'] = False
    info['colorscale'] = colors['colors']
    return info
def test_colorscale_asymmetric_cmap():
    cmap = 'jet'
    values = np.arange(15)
    (colors, vmin, vmax, new_cmap, norm, abs_threshold
     ) = js_plotting_utils.colorscale(cmap, values, symmetric_cmap=False)
    assert (vmin, vmax) == (0, 14)
    assert new_cmap.N == 256
    assert (norm.vmax, norm.vmin) == (14, 0)
def test_colorscale_vmax():
    cmap = 'jet'
    values = np.arange(15)
    (colors, vmin, vmax, new_cmap, norm, abs_threshold
     ) = js_plotting_utils.colorscale(cmap, values, vmax=7)
    assert (vmin, vmax) == (-7, 7)
    assert new_cmap.N == 256
    assert (norm.vmax, norm.vmin) == (7, -7)
def test_colorscale_asymmetric_cmap_vmax():
    cmap = 'jet'
    values = np.arange(15)
    colors = js_plotting_utils.colorscale(cmap, values, vmax=7,
                                          symmetric_cmap=False)
    assert (colors['vmin'], colors['vmax']) == (0, 7)
    assert colors['cmap'].N == 256
    assert (colors['norm'].vmax, colors['norm'].vmin) == (7, 0)
    assert not colors['symmetric_cmap']
Beispiel #14
0
def test_colorscale_no_threshold():
    """Test colorscale with no thresholding."""
    values = np.linspace(-13, -1.5, 20)
    colors = colorscale('jet', values, None)
    check_colors(colors['colors'])
    assert (colors['vmin'], colors['vmax']) == (-13, 13)
    assert colors['cmap'].N == 256
    assert (colors['norm'].vmax, colors['norm'].vmin) == (13, -13)
    assert colors['abs_threshold'] is None
Beispiel #15
0
def test_colorscale_threshold(threshold, expected_abs_threshold):
    """Test colorscale with different threshold values."""
    colors = colorscale('jet', np.linspace(-13, -1.5, 20), threshold=threshold)
    _, cstring = check_colors(colors['colors'])
    assert cstring[50] == 'rgb(127, 127, 127)'
    assert (colors['vmin'], colors['vmax']) == (-13, 13)
    assert colors['cmap'].N == 256
    assert (colors['norm'].vmax, colors['norm'].vmin) == (13, -13)
    assert np.allclose(colors['abs_threshold'], expected_abs_threshold, 2)
    assert colors['symmetric_cmap']
def test_colorscale_no_threshold():
    cmap = 'jet'
    values = np.linspace(-13, -1.5, 20)
    threshold = None
    colors = js_plotting_utils.colorscale(cmap, values, threshold)
    check_colors(colors['colors'])
    assert (colors['vmin'], colors['vmax']) == (-13, 13)
    assert colors['cmap'].N == 256
    assert (colors['norm'].vmax, colors['norm'].vmin) == (13, -13)
    assert colors['abs_threshold'] is None
def test_colorscale_threshold_99():
    cmap = 'jet'
    values = np.linspace(-13, -1.5, 20)
    threshold = '99%'
    colors = js_plotting_utils.colorscale(cmap, values, threshold)
    check_colors(colors['colors'])
    assert (colors['vmin'], colors['vmax']) == (-13, 13)
    assert colors['cmap'].N == 256
    assert (colors['norm'].vmax, colors['norm'].vmin) == (13, -13)
    assert colors['abs_threshold'] == 13
    assert colors['symmetric_cmap']
def test_colorscale_threshold_99():
    cmap = 'jet'
    values = np.linspace(-13, -1.5, 20)
    threshold = '99%'
    (colors, vmin, vmax, new_cmap, norm, abs_threshold
     ) = js_plotting_utils.colorscale(cmap, values, threshold)
    check_colors(colors)
    assert (vmin, vmax) == (-13, 13)
    assert new_cmap.N == 256
    assert (norm.vmax, norm.vmin) == (13, -13)
    assert abs_threshold == 13
def test_colorscale_threshold_99():
    cmap = 'jet'
    values = np.linspace(-13, -1.5, 20)
    threshold = '99%'
    colors = js_plotting_utils.colorscale(cmap, values, threshold)
    check_colors(colors['colors'])
    assert (colors['vmin'], colors['vmax']) == (-13, 13)
    assert colors['cmap'].N == 256
    assert (colors['norm'].vmax, colors['norm'].vmin) == (13, -13)
    assert colors['abs_threshold'] == 13
    assert colors['symmetric_cmap']
def test_colorscale_threshold_50():
    cmap = 'jet'
    values = np.linspace(-13, -1.5, 20)
    threshold = '50%'
    colors = js_plotting_utils.colorscale(cmap, values, threshold)
    val, cstring = check_colors(colors['colors'])
    assert cstring[50] == 'rgb(127, 127, 127)'
    assert (colors['vmin'], colors['vmax']) == (-13, 13)
    assert colors['cmap'].N == 256
    assert (colors['norm'].vmax, colors['norm'].vmin) == (13, -13)
    assert np.allclose(colors['abs_threshold'], 7.55, 2)
    assert colors['symmetric_cmap']
def test_colorscale_asymmetric_cmap_negative_values():
    cmap = 'jet'
    values = np.linspace(-15, 4)
    assert_warns(UserWarning, js_plotting_utils.colorscale, cmap,
                 values, symmetric_cmap=False)

    (colors, vmin, vmax, new_cmap, norm, abs_threshold
     ) = js_plotting_utils.colorscale(cmap, values, vmax=7,
                                      symmetric_cmap=False)
    assert (vmin, vmax) == (-7, 7)
    assert new_cmap.N == 256
    assert (norm.vmax, norm.vmin) == (7, -7)
def test_colorscale_absolute_threshold():
    cmap = 'jet'
    values = np.linspace(-13, -1.5, 20)
    threshold = 7.25
    (colors, vmin, vmax, new_cmap, norm, abs_threshold
     ) = js_plotting_utils.colorscale(cmap, values, threshold)
    val, cstring = check_colors(colors)
    assert cstring[50] == 'rgb(127, 127, 127)'
    assert (vmin, vmax) == (-13, 13)
    assert new_cmap.N == 256
    assert (norm.vmax, norm.vmin) == (13, -13)
    assert np.allclose(abs_threshold, 7.25)
def test_colorscale_asymmetric_cmap_negative_values():
    cmap = 'jet'
    values = np.linspace(-15, 4)
    assert_warns(UserWarning, js_plotting_utils.colorscale, cmap,
                 values, symmetric_cmap=False)

    colors = js_plotting_utils.colorscale(cmap, values, vmax=7,
                                          symmetric_cmap=False)
    assert (colors['vmin'], colors['vmax']) == (-7, 7)
    assert colors['cmap'].N == 256
    assert (colors['norm'].vmax, colors['norm'].vmin) == (7, -7)
    assert colors['symmetric_cmap']
def test_colorscale_absolute_threshold():
    cmap = 'jet'
    values = np.linspace(-13, -1.5, 20)
    threshold = 7.25
    colors = js_plotting_utils.colorscale(cmap, values, threshold)
    val, cstring = check_colors(colors['colors'])
    assert cstring[50] == 'rgb(127, 127, 127)'
    assert (colors['vmin'], colors['vmax']) == (-13, 13)
    assert colors['cmap'].N == 256
    assert (colors['norm'].vmax, colors['norm'].vmin) == (13, -13)
    assert np.allclose(colors['abs_threshold'], 7.25)
    assert colors['symmetric_cmap']
Beispiel #25
0
def test_colorscale_asymmetric_cmap(values, vmax, vmin, threshold,
                                    expected_vmin_vmax):
    """Test colorscale with asymmetric cmap."""
    colors = colorscale('jet',
                        values,
                        vmax=vmax,
                        vmin=vmin,
                        threshold=threshold,
                        symmetric_cmap=False)
    assert (min(values) < 0) | (not colors['symmetric_cmap'])
    assert colors['cmap'].N == 256
    assert (int(colors['vmin']), int(colors['vmax'])) == expected_vmin_vmax
    assert ((colors['norm'].vmax,
             colors['norm'].vmin) == expected_vmin_vmax[::-1])
Beispiel #26
0
def full_brain_info(volume_img,
                    mesh='fsaverage5',
                    threshold=None,
                    cmap=cm.cold_hot,
                    black_bg=False,
                    symmetric_cmap=True,
                    vmax=None,
                    vmin=None,
                    vol_to_surf_kwargs={}):
    """
    Project 3D map on cortex; prepare info to plot both hemispheres.


    This computes the dictionary that gets inserted in the web page,
    which contains encoded meshes, colors, min and max values, and
    background color.

    """
    info = {}
    mesh = surface.surface._check_mesh(mesh)
    surface_maps = {
        h: surface.vol_to_surf(volume_img,
                               mesh['pial_{}'.format(h)],
                               inner_mesh=mesh.get('white_{}'.format(h), None),
                               **vol_to_surf_kwargs)
        for h in ['left', 'right']
    }
    colors = colorscale(cmap,
                        np.asarray(list(surface_maps.values())).ravel(),
                        threshold,
                        symmetric_cmap=symmetric_cmap,
                        vmax=vmax,
                        vmin=vmin)

    for hemi, surf_map in surface_maps.items():
        bg_map = surface.load_surf_data(mesh['sulc_{}'.format(hemi)])
        info['pial_{}'.format(hemi)] = mesh_to_plotly(
            mesh['pial_{}'.format(hemi)])
        info['inflated_{}'.format(hemi)] = mesh_to_plotly(
            mesh['infl_{}'.format(hemi)])

        info['vertexcolor_{}'.format(hemi)] = _get_vertexcolor(
            surf_map, colors['cmap'], colors['norm'], colors['abs_threshold'],
            bg_map)
    info["cmin"], info["cmax"] = float(colors['vmin']), float(colors['vmax'])
    info['black_bg'] = black_bg
    info['full_brain_mesh'] = True
    info['colorscale'] = colors['colors']
    return info
Beispiel #27
0
def plot_surf(mesh, data, view="right", threshold="85%", output_file=None):
    coords, triangles = surface.load_surf_mesh(mesh)
    x, y, z = coords.T
    i, j, k = triangles.T
    colors = colorscale(cold_hot, data, threshold)
    vertexcolor = _get_vertexcolor(
        data,
        colors["cmap"],
        colors["norm"],
        colors["abs_threshold"],
        surface.load_surf_data(fsaverage["sulc_right"]),
    )
    mesh_3d = go.Mesh3d(x=x, y=y, z=z, i=i, j=j, k=k, vertexcolor=vertexcolor)
    fig = go.Figure(data=[mesh_3d])
    fig.update_layout(scene_camera=CAMERAS[view], **LAYOUT)
    if output_file is not None:
        fig.write_image(output_file)
    return fig
Beispiel #28
0
    def fit(self, stat_map_img, bg_img="MNI152"):
        """
        Generate sprite and meta-data from a brain volume. Also optionally
        incorporate a background image.

        :param stat_map_img: The statistical map image. Can be either a 3D volume
            or a 4D volume with exactly one time point.
        :type stat_map_img: stasNiimg-like object, See
            http://nilearn.github.io/manipulating_images/input_output.html
        :param bg_img: The background image that the stat map will be plotted on top of.
            If nothing is specified, the MNI152 template will be used.
            To turn off background image, just pass "bg_img=False".
        :type bg_img: Niimg-like object, optional
            See http://nilearn.github.io/manipulating_images/input_output.html
        """
        # Prepare the color map and thresholding
        mask_img, stat_map_img, data, self.threshold = _mask_stat_map(
            stat_map_img, self.threshold)

        self.colors_ = colorscale(
            self.cmap,
            data.ravel(),
            threshold=self.threshold,
            symmetric_cmap=self.symmetric_cmap,
            vmax=self.vmax,
            vmin=self.vmin,
        )

        if self.black_bg:
            cfont = "#FFFFFF"
            cbg = "#000000"
        else:
            cfont = "#000000"
            cbg = "#FFFFFF"

        # Prepare the data for the cuts
        bg_img, self.bg_min_, self.bg_max_, self.black_bg_ = _load_bg_img(
            stat_map_img, bg_img, self.black_bg, self.dim)
        stat_map_img, mask_img = _resample_stat_map(
            stat_map_img, bg_img, mask_img, self.resampling_interpolation)
        self.cut_slices_ = _get_cut_slices(stat_map_img, self.cut_coords,
                                           self.threshold)

        # Now create the viewer, and populate the sprite data
        self.html_ = self._brainsprite_html(bg_img, stat_map_img, mask_img)

        # Add the javascript snippet
        self.javascript_ = self._brainsprite_js(
            shape=stat_map_img.shape,
            affine=stat_map_img.affine,
            colorFont=cfont,
            colorBackground=cbg,
        )

        # Add the brainsprite.min.js library
        js_dir = os.path.join(os.path.dirname(__file__), "data", "js")
        with open(os.path.join(js_dir, "brainsprite.min.js")) as f:
            self.library_ = f.read()
            f.close()

        # Suggest a size for the viewer
        # width x height, in pixels
        self.width_, self.height_ = _viewer_size(stat_map_img.shape)
Beispiel #29
0
def _plot_surf_plotly(coords, faces, surf_map=None, bg_map=None,
                      hemi='left', view='lateral', cmap=None,
                      symmetric_cmap=True, colorbar=False,
                      threshold=None, vmin=None, vmax=None,
                      cbar_vmin=None, cbar_vmax=None,
                      cbar_tick_format=".1f", title=None,
                      title_font_size=18, output_file=None):
    """Helper function for plot_surf.

    .. versionadded:: 0.8.2

    This function handles surface plotting when the selected
    engine is plotly.

    .. note::
        This function assumes that plotly and kaleido are
        installed.

    .. warning::
        This function is new and experimental. Please report
        bugs that you may encounter.

    """
    try:
        import plotly.graph_objects as go
        from nilearn.plotting.displays import PlotlySurfaceFigure
    except ImportError:
        msg = "Using engine='plotly' requires that ``plotly`` is installed."
        raise ImportError(msg)  # noqa
    x, y, z = coords.T
    i, j, k = faces.T
    if cmap is None:
        cmap = cold_hot
    bg_data = None
    if bg_map is not None:
        bg_data = load_surf_data(bg_map)
        if bg_data.shape[0] != coords.shape[0]:
            raise ValueError('The bg_map does not have the same number '
                             'of vertices as the mesh.')
    if surf_map is not None:
        _check_surf_map(surf_map, coords.shape[0])
        colors = colorscale(
            cmap, surf_map, threshold, vmax=vmax, vmin=vmin,
            symmetric_cmap=symmetric_cmap
        )
        vertexcolor = _get_vertexcolor(
            surf_map, colors["cmap"], colors["norm"],
            colors["abs_threshold"], bg_data
        )
    else:
        if bg_data is None:
            bg_data = np.zeros(coords.shape[0])
        colors = colorscale('Greys', bg_data, symmetric_cmap=False)
        vertexcolor = _get_vertexcolor(
            bg_data, colors["cmap"], colors["norm"],
            colors["abs_threshold"]
        )
    mesh_3d = go.Mesh3d(x=x, y=y, z=z, i=i, j=j, k=k, vertexcolor=vertexcolor)
    fig_data = [mesh_3d]
    if colorbar:
        dummy = _get_cbar_plotly(
            colors["colors"], float(colors["vmin"]), float(colors["vmax"]),
            cbar_tick_format
        )
        fig_data.append(dummy)
    cameras_view = _set_view_plot_surf_plotly(hemi, view)
    fig = go.Figure(data=fig_data)
    fig.update_layout(scene_camera=CAMERAS[cameras_view],
                      title=_configure_title_plotly(title, title_font_size),
                      **LAYOUT)
    if output_file is not None:
        try:
            import kaleido  # noqa: F401
        except ImportError:
            msg = ("Saving figures to file with engine='plotly' requires "
                   "that ``kaleido`` is installed.")
            raise ImportError(msg)  # noqa
    plotly_figure = PlotlySurfaceFigure(figure=fig, output_file=output_file)
    if output_file is not None:
        plotly_figure.savefig()
    return plotly_figure