示例#1
0
def draw(obj, mode='2d', **kwargs):
    """Draw a morphology object.

    Arguments:
        obj: morphology object to be drawn (neuron, tree, soma).
        mode (Optional[str]): drawing mode ('2d', '3d', 'dendrogram'). Defaults to '2d'.
        **kwargs: keyword arguments for underlying neurom.view.view functions.

    Raises:
        InvalidDrawModeError if mode is not valid
        NotDrawableError if obj is not drawable
        NotDrawableError if obj type and mode combination is not drawable

    Examples:
        >>> nrn = ... # load a neuron
        >>> fig, _ = viewer.draw(nrn)             # 2d plot
        >>> fig.show()
        >>> fig3d, _ = viewer.draw(nrn, mode='3d') # 3d plot
        >>> fig3d.show()
        >>> fig, _ = viewer.draw(nrn.neurites[0]) # 2d plot of neurite tree
        >>> dend, _ = viewer.draw(nrn, mode='dendrogram')
    """
    if mode not in MODES:
        raise InvalidDrawModeError('Invalid drawing mode %s' % mode)

    if 'realistic_diameters' in kwargs and mode == '3d':
        if kwargs['realistic_diameters']:
            raise NotImplementedError(
                'Option realistic_diameter not implemented for 3D plots')
        del kwargs['realistic_diameters']

    fig, ax = (common.get_figure() if mode in ('2d', 'dendrogram') else
               common.get_figure(params={'projection': '3d'}))

    if isinstance(obj, Neuron):
        tag = 'neuron'
    elif isinstance(obj, (Section, Neurite)):
        tag = 'tree'
    elif isinstance(obj, Soma):
        tag = 'soma'
    else:
        raise NotDrawableError('draw not implemented for %s' % obj.__class__)

    viewer = '%s_%s' % (tag, mode)
    try:
        plotter = _VIEWERS[viewer]
    except KeyError as e:
        raise NotDrawableError('No drawer for class %s, mode=%s' %
                               (obj.__class__, mode)) from e

    output_path = kwargs.pop('output_path', None)
    plotter(ax, obj, **kwargs)

    if mode != 'dendrogram':
        common.plot_style(fig=fig, ax=ax, **kwargs)

    if output_path:
        common.save_plot(fig=fig, output_path=output_path, **kwargs)

    return fig, ax
示例#2
0
def plot_density(population,  # pylint: disable=too-many-arguments, too-many-locals
                 bins=100, new_fig=True, subplot=111, levels=None, plane='xy',
                 colorlabel='Nodes per unit area', labelfontsize=16,
                 color_map='Reds', no_colorbar=False, threshold=0.01,
                 neurite_type=NeuriteType.basal_dendrite, **kwargs):
    '''Plots the 2d histogram of the center
       coordinates of segments in the selected plane.
    '''
    fig, ax = fig, ax = common.get_figure(new_fig=new_fig, subplot=subplot)

    H1, xedges1, yedges1 = extract_density(population, plane=plane, bins=bins,
                                           neurite_type=neurite_type)

    mask = H1 < threshold  # mask = H1==0
    H2 = np.ma.masked_array(H1, mask)

    getattr(plt.cm, color_map).set_bad(color='white', alpha=None)

    plots = ax.contourf((xedges1[:-1] + xedges1[1:]) / 2,
                        (yedges1[:-1] + yedges1[1:]) / 2,
                        np.transpose(H2), # / np.max(H2),
                        cmap=getattr(plt.cm, color_map), levels=levels)

    if not no_colorbar:
        cbar = plt.colorbar(plots)
        cbar.ax.set_ylabel(colorlabel, fontsize=labelfontsize)

    kwargs['title'] = kwargs.get('title', '')
    kwargs['xlabel'] = kwargs.get('xlabel', plane[0])
    kwargs['ylabel'] = kwargs.get('ylabel', plane[1])

    return common.plot_style(fig=fig, ax=ax, **kwargs)
示例#3
0
文件: plot_somas.py 项目: MFSY/NeuroM
def plot_somas(somas):
    """Plot set of somas on same figure as spheres, each with different color."""
    _, ax = common.get_figure(new_fig=True, subplot=111,
                              params={'projection': '3d', 'aspect': 'equal'})
    for s in somas:
        common.plot_sphere(ax, s.center, s.radius, color=random_color(), alpha=1)
    plt.show()
示例#4
0
def boxplots(data_all, new_fig=True, subplot=False,
             feature_titles=features, **kwargs):
    '''Plots a list of boxplots for each feature in feature_list for object 1.
    Then presents the value of object 2 for each feature as an colored objected
    in the same boxplot.

    Parameters:
        data_all:\
            A list of pairs of flattened data for each feature.
        new_fig (Optional[bool]):\
            Default is False, which returns the default matplotlib axes 111\
            If a subplot needs to be specified, it should be provided in xxx format.
        subplot (Optional[bool]):\
            Default is False, which returns a matplotlib figure object. If True,\
            returns a matplotlib axis object, for use as a subplot.

    Returns:
        fig:\
            A figure which contains the list of boxplots.
    '''
    from neurom.view import common

    fig, ax = common.get_figure(new_fig=new_fig, subplot=subplot)

    ax.boxplot(list(np.transpose(np.array(data_all))[0]), vert=False)

    for idata, data in enumerate(data_all):
        ax.scatter(np.median(data[1]), len(data_all) - idata, s=100, color='r', marker='s')

    ax.set_yticklabels(feature_titles)

    fig, ax = common.plot_style(fig, ax, xlabel='Normalized units (dimensionless)', ylabel='',
                                title='Summarizing features', tight=True, **kwargs)

    return fig, ax
示例#5
0
def plot_somas(somas):
    '''Plot set of somas on same figure as spheres, each with different color'''
    _, ax = common.get_figure(new_fig=True, subplot=111,
                              params={'projection': '3d', 'aspect': 'equal'})
    for s in somas:
        common.plot_sphere(ax, s.center, s.radius, color=random_color(), alpha=1)
    plt.show()
示例#6
0
def boxplot(neurons, feature, new_fig=True, subplot=False):
    '''
    Plot a histogram of the selected feature for the population of neurons.
    Plots x-axis versus y-axis on a scatter|histogram|binned values plot.

    More information about the plot and how it works.

    Parameters
    ----------
    neurons : list
        List of Neurons. Single neurons must be encapsulated in a list.

    feature : str
    The feature of interest.

    Options
    -------

    subplot : bool
        Default is False, which returns a matplotlib figure object. If True,
        returns a matplotlib axis object, for use as a subplot.

    '''
    feature_values = [getattr(neu, 'get_' + feature)() for neu in neurons]

    _, ax = common.get_figure(new_fig=new_fig, subplot=subplot)

    ax.boxplot(feature_values)

    x_labels = ['neuron_id' for _ in neurons]

    ax.set_xticklabels(x_labels)
示例#7
0
def plot_neuron_on_density(
        population,  # pylint: disable=too-many-arguments
        bins=100,
        new_fig=True,
        subplot=111,
        levels=None,
        plane='xy',
        colorlabel='Nodes per unit area',
        labelfontsize=16,
        color_map='Reds',
        no_colorbar=False,
        threshold=0.01,
        neurite_type=NeuriteType.basal_dendrite,
        **kwargs):
    """Plots the 2d histogram of the center
       coordinates of segments in the selected plane
       and superimposes the view of the first neurite of the collection.
    """
    _, ax = common.get_figure(new_fig=new_fig)

    view.plot_tree(ax, population.neurites[0])

    return plot_density(population,
                        plane=plane,
                        bins=bins,
                        new_fig=False,
                        subplot=subplot,
                        colorlabel=colorlabel,
                        labelfontsize=labelfontsize,
                        levels=levels,
                        color_map=color_map,
                        no_colorbar=no_colorbar,
                        threshold=threshold,
                        neurite_type=neurite_type,
                        **kwargs)
示例#8
0
def test_plot_cylinder():
    fig0, ax0 = get_figure(params={'projection': '3d'})
    start, end = np.array([0, 0, 0]), np.array([1, 0, 0])
    plot_cylinder(ax0, start=start, end=end,
                  start_radius=0, end_radius=10.,
                  color='black', alpha=1.)
    nt.ok_(ax0.has_data())
示例#9
0
def plot_somas(somas):
    """Plot set of somas on same figure as spheres, each with different color"""
    fig, ax = common.get_figure(new_fig=True, subplot=111, params={"projection": "3d", "aspect": "equal"})
    for s in somas:
        center = s.center
        radius = s.radius
        common.plot_sphere(fig, ax, center, radius, color=random_color(), alpha=1)
    plt.show()
示例#10
0
def histogram(neurons, feature, new_fig=True, subplot=False, normed=False, **kwargs):
    '''
    Plot a histogram of the selected feature for the population of neurons.
    Plots x-axis versus y-axis on a scatter|histogram|binned values plot.

    More information about the plot and how it works.

    Parameters :

        neurons : list
            List of Neurons. Single neurons must be encapsulated in a list.

        feature : str
            The feature of interest.

        bins : int
            Number of bins for the histogram.

        cumulative : bool
            Sets cumulative histogram on.

        subplot : bool
            Default is False, which returns a matplotlib figure object. If True,
            returns a matplotlib axis object, for use as a subplot.

    Returns :

        figure_output : list
            [fig|ax, figdata, figtext]
            The first item is either a figure object (if subplot is False) or an
            axis object. The second item is an object containing the data used to
            generate the figure. The final item is text used in report generation
            as a figure legend. This text needs to be manually entered in each
            figure file.
    '''

    bins = kwargs.get('bins', 25)
    cumulative = kwargs.get('cumulative', False)

    fig, ax = common.get_figure(new_fig=new_fig, subplot=subplot)

    kwargs['xlabel'] = kwargs.get('xlabel', feature)

    kwargs['ylabel'] = kwargs.get('ylabel', feature + ' fraction')

    kwargs['title'] = kwargs.get('title', feature + ' histogram')

    feature_values = [getattr(neu, 'get_' + feature)() for neu in neurons]

    neu_labels = [neu.name for neu in neurons]

    ax.hist(feature_values, bins=bins, cumulative=cumulative, label=neu_labels, normed=normed)

    kwargs['no_legend'] = len(neu_labels) == 1

    return common.plot_style(fig=fig, ax=ax, **kwargs)
示例#11
0
def histogram(neurons, feature, new_fig=True, subplot=False, normed=False, **kwargs):
    '''
    Plot a histogram of the selected feature for the population of neurons.
    Plots x-axis versus y-axis on a scatter|histogram|binned values plot.

    More information about the plot and how it works.

    Parameters :

        neurons : list
            List of Neurons. Single neurons must be encapsulated in a list.

        feature : str
            The feature of interest.

        bins : int
            Number of bins for the histogram.

        cumulative : bool
            Sets cumulative histogram on.

        subplot : bool
            Default is False, which returns a matplotlib figure object. If True,
            returns a matplotlib axis object, for use as a subplot.

    Returns :

        figure_output : list
            [fig|ax, figdata, figtext]
            The first item is either a figure object (if subplot is False) or an
            axis object. The second item is an object containing the data used to
            generate the figure. The final item is text used in report generation
            as a figure legend. This text needs to be manually entered in each
            figure file.
    '''

    bins = kwargs.get('bins', 25)
    cumulative = kwargs.get('cumulative', False)

    fig, ax = common.get_figure(new_fig=new_fig, subplot=subplot)

    kwargs['xlabel'] = kwargs.get('xlabel', feature)

    kwargs['ylabel'] = kwargs.get('ylabel', feature + ' fraction')

    kwargs['title'] = kwargs.get('title', feature + ' histogram')

    feature_values = [getattr(neu, 'get_' + feature)() for neu in neurons]

    neu_labels = [neu.name for neu in neurons]

    ax.hist(feature_values, bins=bins, cumulative=cumulative, label=neu_labels, normed=normed)

    kwargs['no_legend'] = len(neu_labels) == 1

    return common.plot_style(fig=fig, ax=ax, **kwargs)
示例#12
0
def test_plot_cylinder():
    fig0, ax0 = get_figure(params={'projection': '3d'})
    start, end = np.array([0, 0, 0]), np.array([1, 0, 0])
    plot_cylinder(ax0,
                  start=start,
                  end=end,
                  start_radius=0,
                  end_radius=10.,
                  color='black',
                  alpha=1.)
    nt.ok_(ax0.has_data())
示例#13
0
文件: view.py 项目: wvangeit/NeuroM
def soma3d(sm, new_fig=True, new_axes=True, subplot=False, **kwargs):
    '''Generates a 3d figure of the soma.

    Parameters:
        soma: Soma
        neurom.Soma object

    Options:
        alpha: float \
            Defines throughe transparency of the tree. \
            0.0 transparent through 1.0 opaque. \
            Default value is 0.8.
        treecolor: str or None \
            Defines the color of the soma. \
            Soma : "black". \
            Default value is None.
        new_fig: boolean \
            Defines if the tree will be plotted \
            in the current figure (False) \
            or in a new figure (True) \
            Default value is True.
        subplot: matplotlib subplot value or False \
            If False the default subplot 111 will be used. \
            For any other value a matplotlib subplot \
            will be generated. \
            Default value is False.

    Returns:
        A 3D matplotlib figure with a soma view.
    '''
    treecolor = kwargs.get('treecolor', None)

    # Initialization of matplotlib figure and axes.
    fig, ax = common.get_figure(new_fig=new_fig, new_axes=new_axes,
                                subplot=subplot, params={'projection': '3d'})

    # Definition of the tree color depending on the tree type.
    treecolor = common.get_color(treecolor, tree_type=TreeType.soma)

    xs = sm.center[0]
    ys = sm.center[1]
    zs = sm.center[2]

    # Plot the soma as a circle.
    fig, ax = common.plot_sphere(fig, ax, center=[xs, ys, zs], radius=sm.radius, color=treecolor,
                                 alpha=get_default('alpha', **kwargs))

    kwargs['title'] = kwargs.get('title', 'Soma view')
    kwargs['xlabel'] = kwargs.get('xlabel', 'X')
    kwargs['ylabel'] = kwargs.get('ylabel', 'Y')
    kwargs['zlabel'] = kwargs.get('zlabel', 'Z')

    return common.plot_style(fig=fig, ax=ax, **kwargs)
示例#14
0
文件: view.py 项目: wvangeit/NeuroM
def soma3d(sm, new_fig=True, new_axes=True, subplot=False, **kwargs):
    """Generates a 3d figure of the soma.

    Parameters:
        soma: Soma
        neurom.Soma object

    Options:
        alpha: float \
            Defines throughe transparency of the tree. \
            0.0 transparent through 1.0 opaque. \
            Default value is 0.8.
        treecolor: str or None \
            Defines the color of the soma. \
            Soma : "black". \
            Default value is None.
        new_fig: boolean \
            Defines if the tree will be plotted \
            in the current figure (False) \
            or in a new figure (True) \
            Default value is True.
        subplot: matplotlib subplot value or False \
            If False the default subplot 111 will be used. \
            For any other value a matplotlib subplot \
            will be generated. \
            Default value is False.

    Returns:
        A 3D matplotlib figure with a soma view.
    """
    treecolor = kwargs.get("treecolor", None)

    # Initialization of matplotlib figure and axes.
    fig, ax = common.get_figure(new_fig=new_fig, new_axes=new_axes, subplot=subplot, params={"projection": "3d"})

    # Definition of the tree color depending on the tree type.
    treecolor = common.get_color(treecolor, tree_type=TreeType.soma)

    xs = sm.center[0]
    ys = sm.center[1]
    zs = sm.center[2]

    # Plot the soma as a circle.
    fig, ax = common.plot_sphere(
        fig, ax, center=[xs, ys, zs], radius=sm.radius, color=treecolor, alpha=get_default("alpha", **kwargs)
    )

    kwargs["title"] = kwargs.get("title", "Soma view")
    kwargs["xlabel"] = kwargs.get("xlabel", "X")
    kwargs["ylabel"] = kwargs.get("ylabel", "Y")
    kwargs["zlabel"] = kwargs.get("zlabel", "Z")

    return common.plot_style(fig=fig, ax=ax, **kwargs)
示例#15
0
def test_get_figure():
    fig_old = plt.figure()
    fig, ax = get_figure(new_fig=False, subplot=False)
    nt.ok_(fig == fig_old)
    nt.ok_(ax.colNum == 0)
    nt.ok_(ax.rowNum == 0)
    fig1, ax1 = get_figure(new_fig=True, subplot=224)
    nt.ok_(fig1 != fig_old)
    nt.ok_(ax1.colNum == 1)
    nt.ok_(ax1.rowNum == 1)
    fig = get_figure(new_fig=True, no_axes=True)
    nt.ok_(type(fig) == plt.Figure)
    fig2, ax2 = get_figure(new_fig=True, subplot=[1, 1, 1])
    nt.ok_(ax2.colNum == 0)
    nt.ok_(ax2.rowNum == 0)
    plt.close('all')
    fig = plt.figure()
    ax = fig.add_subplot(111)
    fig2, ax2 = get_figure(new_fig=False, new_axes=False)
    nt.ok_(fig2 == plt.gcf())
    nt.ok_(ax2 == plt.gca())
    plt.close('all')
示例#16
0
def test_get_figure():
    fig_old = plt.figure()
    fig, ax = get_figure(new_fig=False, subplot=False)
    nt.ok_(fig == fig_old)
    nt.ok_(ax.colNum == 0)
    nt.ok_(ax.rowNum == 0)
    fig1, ax1 = get_figure(new_fig=True, subplot=224)
    nt.ok_(fig1 != fig_old)
    nt.ok_(ax1.colNum == 1)
    nt.ok_(ax1.rowNum == 1)
    fig = get_figure(new_fig=True, no_axes=True)
    nt.ok_(type(fig) == plt.Figure)
    fig2, ax2 = get_figure(new_fig=True, subplot=[1,1,1])
    nt.ok_(ax2.colNum == 0)
    nt.ok_(ax2.rowNum == 0)
    plt.close('all')
    fig = plt.figure()
    ax  = fig.add_subplot(111)
    fig2, ax2 = get_figure(new_fig=False, new_axes=False)
    nt.ok_(fig2 == plt.gcf())
    nt.ok_(ax2 == plt.gca())
    plt.close('all')
示例#17
0
def test_get_figure():
    fig_old = plt.figure()
    fig, ax = get_figure(new_fig=False)
    nt.eq_(fig, fig_old)
    nt.eq_(ax.get_subplotspec().colspan.start, 0)
    nt.eq_(ax.get_subplotspec().rowspan.start, 0)

    fig1, ax1 = get_figure(new_fig=True, subplot=224)
    nt.ok_(fig1 != fig_old)
    nt.eq_(ax1.get_subplotspec().colspan.start, 1)
    nt.eq_(ax1.get_subplotspec().rowspan.start, 1)

    fig2, ax2 = get_figure(new_fig=True, subplot=[1, 1, 1])
    nt.eq_(ax2.get_subplotspec().colspan.start, 0)
    nt.eq_(ax2.get_subplotspec().rowspan.start, 0)
    plt.close('all')

    fig = plt.figure()
    ax = fig.add_subplot(111)
    fig2, ax2 = get_figure(new_fig=False)
    nt.eq_(fig2, plt.gcf())
    nt.eq_(ax2, plt.gca())
    plt.close('all')
示例#18
0
def test_get_figure():
    fig_old = plt.figure()
    fig, ax = get_figure(new_fig=False)
    nt.eq_(fig, fig_old)
    nt.eq_(ax.colNum, 0)
    nt.eq_(ax.rowNum, 0)

    fig1, ax1 = get_figure(new_fig=True, subplot=224)
    nt.ok_(fig1 != fig_old)
    nt.eq_(ax1.colNum, 1)
    nt.eq_(ax1.rowNum, 1)

    fig2, ax2 = get_figure(new_fig=True, subplot=[1, 1, 1])
    nt.eq_(ax2.colNum, 0)
    nt.eq_(ax2.rowNum, 0)
    plt.close('all')

    fig = plt.figure()
    ax = fig.add_subplot(111)
    fig2, ax2 = get_figure(new_fig=False)
    nt.eq_(fig2, plt.gcf())
    nt.eq_(ax2, plt.gca())
    plt.close('all')
示例#19
0
def test_get_figure():
    fig_old = plt.figure()
    fig, ax = get_figure(new_fig=False)
    nt.eq_(fig, fig_old)
    nt.eq_(ax.colNum, 0)
    nt.eq_(ax.rowNum, 0)

    fig1, ax1 = get_figure(new_fig=True, subplot=224)
    nt.ok_(fig1 != fig_old)
    nt.eq_(ax1.colNum, 1)
    nt.eq_(ax1.rowNum, 1)

    fig2, ax2 = get_figure(new_fig=True, subplot=[1, 1, 1])
    nt.eq_(ax2.colNum, 0)
    nt.eq_(ax2.rowNum, 0)
    plt.close('all')

    fig = plt.figure()
    ax = fig.add_subplot(111)
    fig2, ax2 = get_figure(new_fig=False)
    nt.eq_(fig2, plt.gcf())
    nt.eq_(ax2, plt.gca())
    plt.close('all')
示例#20
0
def test_get_figure():
    fig_old = plt.figure()
    fig, ax = get_figure(new_fig=False)
    assert fig == fig_old
    assert ax.get_subplotspec().colspan.start == 0
    assert ax.get_subplotspec().rowspan.start == 0

    fig1, ax1 = get_figure(new_fig=True, subplot=224)
    assert fig1 != fig_old
    assert ax1.get_subplotspec().colspan.start == 1
    assert ax1.get_subplotspec().rowspan.start == 1

    fig2, ax2 = get_figure(new_fig=True, subplot=[1, 1, 1])
    assert ax2.get_subplotspec().colspan.start == 0
    assert ax2.get_subplotspec().rowspan.start == 0
    plt.close('all')

    fig = plt.figure()
    ax = fig.add_subplot(111)
    fig2, ax2 = get_figure(new_fig=False)
    assert fig2 == plt.gcf()
    assert ax2 == plt.gca()
    plt.close('all')
示例#21
0
def dendrogram(tree_object,
               show_diameters=False,
               new_fig=True,
               subplot=False,
               **kwargs):
    '''Generates the deondrogram of the input neurite

    Arguments:

        tree_object : input tree object

    Options:

        show_diameters : bool for showing segment diameters

        subplot : Default is False, which returns a matplotlib figure object. If True,
        returns a matplotlib axis object, for use as a subplot.

    Returns:

        figure_output : list
            [fig|ax, figdata, figtext]
            The first item is either a figure object (if subplot is False) or an
            axis object. The second item is an object containing the data used to
            generate the figure. The final item is text used in report generation
            as a figure legend. This text needs to be manually entered in each
            figure file.
    '''

    collection, linked_colors = _generate_segment_collection(
        tree_object, show_diameters)

    fig, ax = common.get_figure(new_fig=new_fig, subplot=subplot)

    ax.add_collection(collection)
    ax.autoscale(enable=True, tight=None)

    # dummy plots for color bar labels
    for color, label in set(linked_colors):
        ax.plot((0., 0.), (0., 0.), c=color, label=label)

    # customization settings
    kwargs['xticks'] = []
    kwargs['title'] = kwargs.get('title', 'Morphology Dendrogram')
    kwargs['xlabel'] = kwargs.get('xlabel', '')
    kwargs['ylabel'] = kwargs.get('ylabel', '')
    kwargs['no_legend'] = False

    return common.plot_style(fig=fig, ax=ax, **kwargs)
示例#22
0
def main(data_dir, mtype_file):  # pylint: disable=too-many-locals
    '''Run the stuff'''
    # data structure to store results
    stuff = load_neurite_features(data_dir)
    sim_params = json.load(open(mtype_file))

    # load histograms, distribution parameter sets and figures into arrays.
    # To plot figures, do
    # plots[i].fig.show()
    # To modify an axis, do
    # plots[i].ax.something()

    _plots = []

    for feat, d in stuff.items():
        for typ, data in d.items():
            dist = sim_params['components'][typ].get(feat, None)
            print('Type = %s, Feature = %s, Distribution = %s' %
                  (typ, feat, dist))
            # if no data available, skip this feature
            if not data:
                print("No data found for feature %s (%s)" % (feat, typ))
                continue
            # print 'DATA', data
            num_bins = 100
            limits = calc_limits(data, dist)
            bin_edges = np.linspace(limits[0], limits[1], num_bins + 1)
            histo = np.histogram(data, bin_edges, normed=True)
            print('PLOT LIMITS:', limits)
            # print 'DATA:', data
            # print 'BIN HEIGHT', histo[0]
            plot = Plot(*view_utils.get_figure(new_fig=True, subplot=111))
            view_utils.plot_limits(plot.fig,
                                   plot.ax,
                                   xlim=limits,
                                   no_ylim=True)
            plot.ax.bar(histo[1][:-1], histo[0], width=bin_widths(histo[1]))
            dp, bc = dist_points(histo[1], dist)
            # print 'BIN CENTERS:', bc, len(bc)
            if dp is not None:
                # print 'DIST POINTS:', dp, len(dp)
                plot.ax.plot(bc, dp, 'r*')
            plot.ax.set_title('%s (%s)' % (feat, typ))
            _plots.append(plot)

    return _plots
示例#23
0
def plot_neuron_on_density(population, # pylint: disable=too-many-arguments
                           bins=100, new_fig=True, subplot=111, levels=None, plane='xy',
                           colorlabel='Nodes per unit area', labelfontsize=16,
                           color_map='Reds', no_colorbar=False, threshold=0.01,
                           neurite_type=NeuriteType.basal_dendrite, **kwargs):
    '''Plots the 2d histogram of the center
       coordinates of segments in the selected plane
       and superimposes the view of the first neurite of the collection.
    '''
    _, ax = common.get_figure(new_fig=new_fig)

    view.plot_tree(ax, population.neurites[0])

    return plot_density(population, plane=plane, bins=bins, new_fig=False, subplot=subplot,
                        colorlabel=colorlabel, labelfontsize=labelfontsize, levels=levels,
                        color_map=color_map, no_colorbar=no_colorbar, threshold=threshold,
                        neurite_type=neurite_type, **kwargs)
示例#24
0
def plot_density(
        population,  # pylint: disable=too-many-arguments, too-many-locals
        bins=100,
        new_fig=True,
        subplot=111,
        levels=None,
        plane='xy',
        colorlabel='Nodes per unit area',
        labelfontsize=16,
        color_map='Reds',
        no_colorbar=False,
        threshold=0.01,
        neurite_type=NeuriteType.basal_dendrite,
        **kwargs):
    """Plots the 2d histogram of the center
       coordinates of segments in the selected plane.
    """
    fig, ax = common.get_figure(new_fig=new_fig, subplot=subplot)

    H1, xedges1, yedges1 = extract_density(population,
                                           plane=plane,
                                           bins=bins,
                                           neurite_type=neurite_type)

    mask = H1 < threshold  # mask = H1==0
    H2 = np.ma.masked_array(H1, mask)

    getattr(plt.cm, color_map).set_bad(color='white', alpha=None)

    plots = ax.contourf(
        (xedges1[:-1] + xedges1[1:]) / 2,
        (yedges1[:-1] + yedges1[1:]) / 2,
        np.transpose(H2),  # / np.max(H2),
        cmap=getattr(plt.cm, color_map),
        levels=levels)

    if not no_colorbar:
        cbar = plt.colorbar(plots)
        cbar.ax.set_ylabel(colorlabel, fontsize=labelfontsize)

    kwargs['title'] = kwargs.get('title', '')
    kwargs['xlabel'] = kwargs.get('xlabel', plane[0])
    kwargs['ylabel'] = kwargs.get('ylabel', plane[1])

    return common.plot_style(fig=fig, ax=ax, **kwargs)
示例#25
0
def dendrogram(tree_object, show_diameters=False, new_fig=True,
               subplot=False, **kwargs):
    '''Generates the deondrogram of the input neurite

    Arguments:

        tree_object : input tree object

    Options:

        show_diameters : bool for showing segment diameters

        subplot : Default is False, which returns a matplotlib figure object. If True,
        returns a matplotlib axis object, for use as a subplot.

    Returns:

        figure_output : list
            [fig|ax, figdata, figtext]
            The first item is either a figure object (if subplot is False) or an
            axis object. The second item is an object containing the data used to
            generate the figure. The final item is text used in report generation
            as a figure legend. This text needs to be manually entered in each
            figure file.
    '''

    collection, linked_colors = _generate_segment_collection(tree_object, show_diameters)

    fig, ax = common.get_figure(new_fig=new_fig, subplot=subplot)

    ax.add_collection(collection)
    ax.autoscale(enable=True, tight=None)

    # dummy plots for color bar labels
    for color, label in set(linked_colors):
        ax.plot((0., 0.), (0., 0.), c=color, label=label)

    # customization settings
    kwargs['xticks'] = []
    kwargs['title'] = kwargs.get('title', 'Morphology Dendrogram')
    kwargs['xlabel'] = kwargs.get('xlabel', '')
    kwargs['ylabel'] = kwargs.get('ylabel', '')
    kwargs['no_legend'] = False

    return common.plot_style(fig=fig, ax=ax, **kwargs)
示例#26
0
def main(data_dir, mtype_file):  # pylint: disable=too-many-locals
    '''Run the stuff'''
    # data structure to store results
    stuff = load_neurite_features(data_dir)
    sim_params = json.load(open(mtype_file))

    # load histograms, distribution parameter sets and figures into arrays.
    # To plot figures, do
    # plots[i].fig.show()
    # To modify an axis, do
    # plots[i].ax.something()

    _plots = []

    for feat, d in stuff.items():
        for typ, data in d.items():
            dist = sim_params['components'][typ].get(feat, None)
            print('Type = %s, Feature = %s, Distribution = %s' % (typ, feat, dist))
            # if no data available, skip this feature
            if not data:
                print("No data found for feature %s (%s)" % (feat, typ))
                continue
            # print 'DATA', data
            num_bins = 100
            limits = calc_limits(data, dist)
            bin_edges = np.linspace(limits[0], limits[1], num_bins + 1)
            histo = np.histogram(data, bin_edges, normed=True)
            print('PLOT LIMITS:', limits)
            # print 'DATA:', data
            # print 'BIN HEIGHT', histo[0]
            plot = Plot(*view_utils.get_figure(new_fig=True, subplot=111))
            plot.ax.set_xlim(*limits)
            plot.ax.bar(histo[1][:-1], histo[0], width=bin_widths(histo[1]))
            dp, bc = dist_points(histo[1], dist)
            # print 'BIN CENTERS:', bc, len(bc)
            if dp is not None:
                # print 'DIST POINTS:', dp, len(dp)
                plot.ax.plot(bc, dp, 'r*')
            plot.ax.set_title('%s (%s)' % (feat, typ))
            _plots.append(plot)

    return _plots
示例#27
0
文件: view.py 项目: wvangeit/NeuroM
def tree(tr, plane='xy', new_fig=True, subplot=False, **kwargs):
    '''Generates a 2d figure of the tree.

    Parameters:
        tr: Tree \
            neurom.Tree object

    Options:
        plane: str \
            Accepted values: Any pair of of xyz \
            Default value is 'xy'.treecolor
        linewidth: float \
            Defines the linewidth of the tree, \
            if diameter is set to False. \
            Default value is 1.2.
        alpha: float \
            Defines throughe transparency of the tree. \
            0.0 transparent through 1.0 opaque. \
            Default value is 0.8.
        treecolor: str or None \
            Defines the color of the tree. \
            If None the default values will be used, \
            depending on the type of tree: \
            Basal dendrite: "red" \
            Axon : "blue" \
            Apical dendrite: "purple" \
            Undefined tree: "black" \
            Default value is None.
        new_fig: boolean \
            Defines if the tree will be plotted \
            in the current figure (False) \
            or in a new figure (True) \
            Default value is True.
        subplot: matplotlib subplot value or False \
            If False the default subplot 111 will be used. \
            For any other value a matplotlib subplot \
            will be generated. \
            Default value is False.
        diameter: boolean
            If True the diameter, scaled with diameter_scale factor, \
            will define the width of the tree lines. \
            If False use linewidth to select the width of the tree lines. \
            Default value is True.
        diameter_scale: float \
            Defines the scale factor that will be multiplied \
            with the diameter to define the width of the tree line. \
            Default value is 1.
        limits: list or boolean \
            List of type: [[xmin, ymin, zmin], [xmax, ymax, zmax]] \
            If False the figure will not be scaled. \
            If True the figure will be scaled according to tree limits. \
            Default value is False.
        white_space: float \
            Defines the white space around \
            the boundary box of the morphology. \
            Default value is 1.

    Returns:
        A 2D matplotlib figure with a tree view, at the selected plane.
    '''
    if plane not in ('xy', 'yx', 'xz', 'zx', 'yz', 'zy'):
        return None, 'No such plane found! Please select one of: xy, xz, yx, yz, zx, zy.'

    # Initialization of matplotlib figure and axes.
    fig, ax = common.get_figure(new_fig=new_fig, subplot=subplot)

    # Data needed for the viewer: x,y,z,r
    bounding_box = get_bounding_box(tr)

    def _seg_2d(seg):
        '''2d coordinates needed for the plotting of a segment'''
        horz = getattr(COLS, plane[0].capitalize())
        vert = getattr(COLS, plane[1].capitalize())
        parent_point = seg[0]
        child_point = seg[1]
        horz1 = parent_point[horz]
        horz2 = child_point[horz]
        vert1 = parent_point[vert]
        vert2 = child_point[vert]
        return ((horz1, vert1), (horz2, vert2))

    segs = [_seg_2d(seg) for seg in val_iter(isegment(tr))]

    linewidth = get_default('linewidth', **kwargs)
    # Definition of the linewidth according to diameter, if diameter is True.
    if get_default('diameter', **kwargs):
        scale = get_default('diameter_scale', **kwargs)
        # TODO: This was originally a numpy array. Did it have to be one?
        linewidth = [2 * d * scale for d in i_segment_radius(tr)]

    # Plot the collection of lines.
    collection = LineCollection(segs,
                                color=common.get_color(get_default('treecolor', **kwargs),
                                                       get_tree_type(tr)),
                                linewidth=linewidth, alpha=get_default('alpha', **kwargs))

    ax.add_collection(collection)

    kwargs['title'] = kwargs.get('title', 'Tree view')
    kwargs['xlabel'] = kwargs.get('xlabel', plane[0])
    kwargs['ylabel'] = kwargs.get('ylabel', plane[1])
    kwargs['xlim'] = kwargs.get('xlim', [bounding_box[0][getattr(COLS, plane[0].capitalize())] -
                                         get_default('white_space', **kwargs),
                                         bounding_box[1][getattr(COLS, plane[0].capitalize())] +
                                         get_default('white_space', **kwargs)])
    kwargs['ylim'] = kwargs.get('ylim', [bounding_box[0][getattr(COLS, plane[1].capitalize())] -
                                         get_default('white_space', **kwargs),
                                         bounding_box[1][getattr(COLS, plane[1].capitalize())] +
                                         get_default('white_space', **kwargs)])

    return common.plot_style(fig=fig, ax=ax, **kwargs)
示例#28
0
文件: view.py 项目: wvangeit/NeuroM
def neuron3d(nrn, new_fig=True, new_axes=True, subplot=False, **kwargs):
    '''Generates a figure of the neuron,
       that contains a soma and a list of trees.

    Parameters:
        neuron: Neuron
        neurom.Neuron object

    Options:
        linewidth: float \
            Defines the linewidth of the tree, \
            if diameter is set to False. \
            Default value is 1.2.
        alpha: float \
            Defines throughe transparency of the tree. \
            0.0 transparent through 1.0 opaque. \
            Default value is 0.8.
        treecolor: str or None \
            Defines the color of the tree. \
            If None the default values will be used, \
            depending on the type of tree: \
            Basal dendrite: "red" \
            Axon : "blue" \
            Apical dendrite: "purple" \
            Undefined tree: "black" \
            Default value is None.
        new_fig: boolean \
            Defines if the tree will be plotted \
            in the current figure (False) \
            or in a new figure (True) \
            Default value is True.
        subplot: matplotlib subplot value or False \
            If False the default subplot 111 will be used. \
            For any other value a matplotlib subplot \
            will be generated. \
            Default value is False.
        diameter: boolean
            If True the diameter, scaled with diameter_scale factor, \
            will define the width of the tree lines. \
            If False use linewidth to select the width of the tree lines. \
            Default value is True.
        diameter_scale: float \
            Defines the scale factor that will be multiplied \
            with the diameter to define the width of the tree line. \
            Default value is 1.

    Returns:
        A 3D matplotlib figure with a neuron view.
    '''
    # Initialization of matplotlib figure and axes.
    fig, ax = common.get_figure(new_fig=new_fig, new_axes=new_axes,
                                subplot=subplot, params={'projection': '3d'})

    kwargs['new_fig'] = False
    kwargs['subplot'] = subplot
    kwargs['new_axes'] = False
    kwargs['title'] = kwargs.get('title', 'Neuron view')

    soma3d(nrn.soma, **kwargs)

    h = []
    v = []
    d = []

    for temp_tree in nrn.neurites:

        bounding_box = get_bounding_box(temp_tree)

        h.append([bounding_box[0][getattr(COLS, 'X')],
                  bounding_box[1][getattr(COLS, 'X')]])
        v.append([bounding_box[0][getattr(COLS, 'Y')],
                  bounding_box[1][getattr(COLS, 'Y')]])
        d.append([bounding_box[0][getattr(COLS, 'Z')],
                  bounding_box[1][getattr(COLS, 'Z')]])

        tree3d(temp_tree, **kwargs)

    if h:
        kwargs['xlim'] = kwargs.get('xlim', [np.min(h) - get_default('white_space', **kwargs),
                                             np.max(h) + get_default('white_space', **kwargs)])
    if v:
        kwargs['ylim'] = kwargs.get('ylim', [np.min(v) - get_default('white_space', **kwargs),
                                             np.max(v) + get_default('white_space', **kwargs)])
    if d:
        kwargs['zlim'] = kwargs.get('zlim', [np.min(d) - get_default('white_space', **kwargs),
                                             np.max(d) + get_default('white_space', **kwargs)])

    return common.plot_style(fig=fig, ax=ax, **kwargs)
示例#29
0
def test_plot_sphere():
    fig0, ax0 = get_figure(params={'projection': '3d'})
    plot_sphere(ax0, [0, 0, 0], 10., color='black', alpha=1.)
    assert ax0.has_data()
示例#30
0
文件: view.py 项目: wvangeit/NeuroM
def tree3d(tr, new_fig=True, new_axes=True, subplot=False, **kwargs):
    '''Generates a figure of the tree in 3d.

    Parameters:
        tr: Tree
        neurom.Tree object

    Options:
        linewidth: float \
            Defines the linewidth of the tree, \
            if diameter is set to False. \
            Default value is 1.2.
        alpha: float \
            Defines throughe transparency of the tree. \
            0.0 transparent through 1.0 opaque. \
            Default value is 0.8.
        treecolor: str or None \
            Defines the color of the tree. \
            If None the default values will be used, \
            depending on the type of tree: \
            Basal dendrite: "red" \
            Axon : "blue" \
            Apical dendrite: "purple" \
            Undefined tree: "black" \
            Default value is None.
        new_fig: boolean \
            Defines if the tree will be plotted \
            in the current figure (False) \
            or in a new figure (True) \
            Default value is True.
        subplot: matplotlib subplot value or False \
            If False the default subplot 111 will be used. \
            For any other value a matplotlib subplot \
            will be generated. \
            Default value is False.
        diameter: boolean
            If True the diameter, scaled with diameter_scale factor, \
            will define the width of the tree lines. \
            If False use linewidth to select the width of the tree lines. \
            Default value is True.
        diameter_scale: float \
            Defines the scale factor that will be multiplied \
            with the diameter to define the width of the tree line. \
            Default value is 1.
        white_space: float \
            Defines the white space around \
            the boundary box of the morphology. \
            Default value is 1.

    Returns:
        A 3D matplotlib figure with a tree view.
    '''
    from mpl_toolkits.mplot3d.art3d import Line3DCollection

    # Initialization of matplotlib figure and axes.
    fig, ax = common.get_figure(new_fig=new_fig, new_axes=new_axes,
                                subplot=subplot, params={'projection': '3d'})

    # Data needed for the viewer: x,y,z,r
    bounding_box = get_bounding_box(tr)

    def _seg_3d(seg):
        '''2d coordinates needed for the plotting of a segment'''
        horz = getattr(COLS, 'X')
        vert = getattr(COLS, 'Y')
        depth = getattr(COLS, 'Z')
        parent_point = seg[0]
        child_point = seg[1]
        horz1 = parent_point[horz]
        horz2 = child_point[horz]
        vert1 = parent_point[vert]
        vert2 = child_point[vert]
        depth1 = parent_point[depth]
        depth2 = child_point[depth]
        return ((horz1, vert1, depth1), (horz2, vert2, depth2))

    segs = [_seg_3d(seg) for seg in val_iter(isegment(tr))]

    linewidth = get_default('linewidth', **kwargs)

    # Definition of the linewidth according to diameter, if diameter is True.
    if get_default('diameter', **kwargs):
        # TODO: This was originally a numpy array. Did it have to be one?
        linewidth = [2 * d * get_default('diameter_scale', **kwargs) for d in i_segment_radius(tr)]

    # Plot the collection of lines.
    collection = Line3DCollection(segs,
                                  color=common.get_color(get_default('treecolor', **kwargs),
                                                         get_tree_type(tr)),
                                  linewidth=linewidth, alpha=get_default('alpha', **kwargs))

    ax.add_collection3d(collection)

    kwargs['title'] = kwargs.get('title', 'Tree 3d-view')
    kwargs['xlabel'] = kwargs.get('xlabel', 'X')
    kwargs['ylabel'] = kwargs.get('ylabel', 'Y')
    kwargs['zlabel'] = kwargs.get('zlabel', 'Z')
    kwargs['xlim'] = kwargs.get('xlim', [bounding_box[0][0] - get_default('white_space', **kwargs),
                                         bounding_box[1][0] + get_default('white_space', **kwargs)])
    kwargs['ylim'] = kwargs.get('ylim', [bounding_box[0][1] - get_default('white_space', **kwargs),
                                         bounding_box[1][1] + get_default('white_space', **kwargs)])
    kwargs['zlim'] = kwargs.get('zlim', [bounding_box[0][2] - get_default('white_space', **kwargs),
                                         bounding_box[1][2] + get_default('white_space', **kwargs)])

    return common.plot_style(fig=fig, ax=ax, **kwargs)
示例#31
0
def test_plot_sphere():
    fig0, ax0 = get_figure(params={'projection':'3d'})
    fig1, ax1 = plot_sphere(fig0, ax0, [0,0,0], 10., color='black', alpha=1.)
    nt.ok_(ax1.has_data() == True)
示例#32
0
def test_plot_sphere():
    fig0, ax0 = get_figure(params={'projection': '3d'})
    fig1, ax1 = plot_sphere(fig0, ax0, [0, 0, 0], 10., color='black', alpha=1.)
    nt.ok_(ax1.has_data() == True)
示例#33
0
def tree(tr, plane='xy', new_fig=True, subplot=False, **kwargs):
    '''
    Generates a 2d figure of the tree's segments. \
    If the tree contains one single point the plot will be empty \
    since no segments can be constructed.

    Parameters:
        tr: Tree \
            neurom.Tree object
        plane: str \
            Accepted values: Any pair of of xyz \
            Default value is 'xy'.treecolor
        linewidth: float \
            Defines the linewidth of the tree, \
            if diameter is set to False. \
            Default value is 1.2.
        alpha: float \
            Defines throughe transparency of the tree. \
            0.0 transparent through 1.0 opaque. \
            Default value is 0.8.
        treecolor: str or None \
            Defines the color of the tree. \
            If None the default values will be used, \
            depending on the type of tree: \
            Basal dendrite: "red" \
            Axon : "blue" \
            Apical dendrite: "purple" \
            Undefined tree: "black" \
            Default value is None.
        new_fig: boolean \
            Defines if the tree will be plotted \
            in the current figure (False) \
            or in a new figure (True) \
            Default value is True.
        subplot: matplotlib subplot value or False \
            If False the default subplot 111 will be used. \
            For any other value a matplotlib subplot \
            will be generated. \
            Default value is False.
        diameter: boolean
            If True the diameter, scaled with diameter_scale factor, \
            will define the width of the tree lines. \
            If False use linewidth to select the width of the tree lines. \
            Default value is True.
        diameter_scale: float \
            Defines the scale factor that will be multiplied \
            with the diameter to define the width of the tree line. \
            Default value is 1.
        limits: list or boolean \
            List of type: [[xmin, ymin, zmin], [xmax, ymax, zmax]] \
            If False the figure will not be scaled. \
            If True the figure will be scaled according to tree limits. \
            Default value is False.
        white_space: float \
            Defines the white space around \
            the boundary box of the morphology. \
            Default value is 1.

    Returns:
        A 2D matplotlib figure with a tree view, at the selected plane.
    '''
    if plane not in ('xy', 'yx', 'xz', 'zx', 'yz', 'zy'):
        return None, 'No such plane found! Please select one of: xy, xz, yx, yz, zx, zy.'

    # Initialization of matplotlib figure and axes.
    fig, ax = common.get_figure(new_fig=new_fig, subplot=subplot)

    # Data needed for the viewer: x,y,z,r
    bounding_box = get_bounding_box(tr)

    def _seg_2d(seg):
        '''2d coordinates needed for the plotting of a segment'''
        horz = getattr(COLS, plane[0].capitalize())
        vert = getattr(COLS, plane[1].capitalize())
        parent_point = seg[0]
        child_point = seg[1]
        horz1 = parent_point[horz]
        horz2 = child_point[horz]
        vert1 = parent_point[vert]
        vert2 = child_point[vert]
        return ((horz1, vert1), (horz2, vert2))

    segs = [_seg_2d(seg) for seg in val_iter(isegment(tr))]

    linewidth = get_default('linewidth', **kwargs)
    # Definition of the linewidth according to diameter, if diameter is True.
    if get_default('diameter', **kwargs):
        scale = get_default('diameter_scale', **kwargs)
        # TODO: This was originally a numpy array. Did it have to be one?
        linewidth = [2 * d * scale for d in iter_neurites(tr, segment_radius)]
        if len(linewidth) == 0:
            linewidth = get_default('linewidth', **kwargs)

    # Plot the collection of lines.
    collection = LineCollection(segs,
                                color=common.get_color(get_default('treecolor', **kwargs),
                                                       get_tree_type(tr)),
                                linewidth=linewidth, alpha=get_default('alpha', **kwargs))

    ax.add_collection(collection)

    kwargs['title'] = kwargs.get('title', 'Tree view')
    kwargs['xlabel'] = kwargs.get('xlabel', plane[0])
    kwargs['ylabel'] = kwargs.get('ylabel', plane[1])
    kwargs['xlim'] = kwargs.get('xlim', [bounding_box[0][getattr(COLS, plane[0].capitalize())] -
                                         get_default('white_space', **kwargs),
                                         bounding_box[1][getattr(COLS, plane[0].capitalize())] +
                                         get_default('white_space', **kwargs)])
    kwargs['ylim'] = kwargs.get('ylim', [bounding_box[0][getattr(COLS, plane[1].capitalize())] -
                                         get_default('white_space', **kwargs),
                                         bounding_box[1][getattr(COLS, plane[1].capitalize())] +
                                         get_default('white_space', **kwargs)])

    return common.plot_style(fig=fig, ax=ax, **kwargs)
示例#34
0
def neuron3d(nrn, new_fig=True, new_axes=True, subplot=False, **kwargs):
    '''
    Generates a figure of the neuron,
    that contains a soma and a list of trees.

    Parameters:
        neuron: Neuron \
        neurom.Neuron object
        linewidth: float \
            Defines the linewidth of the tree, \
            if diameter is set to False. \
            Default value is 1.2.
        alpha: float \
            Defines throughe transparency of the tree. \
            0.0 transparent through 1.0 opaque. \
            Default value is 0.8.
        treecolor: str or None \
            Defines the color of the tree. \
            If None the default values will be used, \
            depending on the type of tree: \
            Basal dendrite: "red" \
            Axon : "blue" \
            Apical dendrite: "purple" \
            Undefined tree: "black" \
            Default value is None.
        new_fig: boolean \
            Defines if the tree will be plotted \
            in the current figure (False) \
            or in a new figure (True) \
            Default value is True.
        subplot: matplotlib subplot value or False \
            If False the default subplot 111 will be used. \
            For any other value a matplotlib subplot \
            will be generated. \
            Default value is False.
        diameter: boolean
            If True the diameter, scaled with diameter_scale factor, \
            will define the width of the tree lines. \
            If False use linewidth to select the width of the tree lines. \
            Default value is True.
        diameter_scale: float \
            Defines the scale factor that will be multiplied \
            with the diameter to define the width of the tree line. \
            Default value is 1.

    Returns:
        A 3D matplotlib figure with a neuron view.
    '''
    # Initialization of matplotlib figure and axes.
    fig, ax = common.get_figure(new_fig=new_fig, new_axes=new_axes,
                                subplot=subplot, params={'projection': '3d'})

    kwargs['new_fig'] = False
    kwargs['subplot'] = subplot
    kwargs['new_axes'] = False
    kwargs['title'] = kwargs.get('title', 'Neuron view')

    soma3d(nrn.soma, **kwargs)

    h = []
    v = []
    d = []

    for temp_tree in nrn.neurites:

        bounding_box = get_bounding_box(temp_tree)

        h.append([bounding_box[0][getattr(COLS, 'X')],
                  bounding_box[1][getattr(COLS, 'X')]])
        v.append([bounding_box[0][getattr(COLS, 'Y')],
                  bounding_box[1][getattr(COLS, 'Y')]])
        d.append([bounding_box[0][getattr(COLS, 'Z')],
                  bounding_box[1][getattr(COLS, 'Z')]])

        tree3d(temp_tree, **kwargs)

    if h:
        kwargs['xlim'] = kwargs.get('xlim', [np.min(h) - get_default('white_space', **kwargs),
                                             np.max(h) + get_default('white_space', **kwargs)])
    if v:
        kwargs['ylim'] = kwargs.get('ylim', [np.min(v) - get_default('white_space', **kwargs),
                                             np.max(v) + get_default('white_space', **kwargs)])
    if d:
        kwargs['zlim'] = kwargs.get('zlim', [np.min(d) - get_default('white_space', **kwargs),
                                             np.max(d) + get_default('white_space', **kwargs)])

    return common.plot_style(fig=fig, ax=ax, **kwargs)
示例#35
0
def soma(sm, plane='xy', new_fig=True, subplot=False, **kwargs):
    '''
    Generates a 2d figure of the soma.

    Parameters:
        soma: Soma \
        neurom.Soma object
        plane: str \
            Accepted values: Any pair of of xyz \
            Default value is 'xy'.treecolor
        linewidth: float \
            Defines the linewidth of the tree, \
            if diameter is set to False. \
            Default value is 1.2.
        alpha: float \
            Defines throughe transparency of the tree. \
            0.0 transparent through 1.0 opaque. \
            Default value is 0.8.
        treecolor: str or None \
            Defines the color of the soma. \
            Soma: black" \
            Default value is None.
        new_fig: boolean \
            Defines if the tree will be plotted \
            in the current figure (False) \
            or in a new figure (True) \
            Default value is True.
        subplot: matplotlib subplot value or False \
            If False the default subplot 111 will be used. \
            For any other value a matplotlib subplot \
            will be generated. \
            Default value is False.
        limits: list or boolean \
            List of type: [[xmin, ymin, zmin], [xmax, ymax, zmax]] \
            If False the figure will not be scaled. \
            If True the figure will be scaled according to tree limits. \
            Default value is False.

    Returns:
        A 2D matplotlib figure with a soma view, at the selected plane.
    '''
    treecolor = kwargs.get('treecolor', None)
    outline = kwargs.get('outline', True)

    if plane not in ('xy', 'yx', 'xz', 'zx', 'yz', 'zy'):
        return None, 'No such plane found! Please select one of: xy, xz, yx, yz, zx, zy.'

    # Initialization of matplotlib figure and axes.
    fig, ax = common.get_figure(new_fig=new_fig, subplot=subplot)

    # Definition of the tree color depending on the tree type.
    treecolor = common.get_color(treecolor, tree_type=TreeType.soma)

    # Plot the outline of the soma as a circle, is outline is selected.
    if not outline:
        soma_circle = common.plt.Circle(sm.center, sm.radius, color=treecolor,
                                        alpha=get_default('alpha', **kwargs))
        ax.add_artist(soma_circle)
    else:
        horz = []
        vert = []

        for s_point in sm.iter():
            horz.append(s_point[getattr(COLS, plane[0].capitalize())])
            vert.append(s_point[getattr(COLS, plane[1].capitalize())])

        horz.append(horz[0]) # To close the loop for a soma viewer. This might be modified!
        vert.append(vert[0]) # To close the loop for a soma viewer. This might be modified!

        common.plt.plot(horz, vert, color=treecolor,
                        alpha=get_default('alpha', **kwargs),
                        linewidth=get_default('linewidth', **kwargs))

    kwargs['title'] = kwargs.get('title', 'Soma view')
    kwargs['xlabel'] = kwargs.get('xlabel', plane[0])
    kwargs['ylabel'] = kwargs.get('ylabel', plane[1])

    return common.plot_style(fig=fig, ax=ax, **kwargs)
示例#36
0
def tree3d(tr, new_fig=True, new_axes=True, subplot=False, **kwargs):
    '''
    Generates a figure of the tree in 3d.
    If the tree contains one single point the plot will be empty \
    since no segments can be constructed.


    Parameters:
        tr: Tree \
        neurom.Tree object
        linewidth: float \
            Defines the linewidth of the tree, \
            if diameter is set to False. \
            Default value is 1.2.
        alpha: float \
            Defines throughe transparency of the tree. \
            0.0 transparent through 1.0 opaque. \
            Default value is 0.8.
        treecolor: str or None \
            Defines the color of the tree. \
            If None the default values will be used, \
            depending on the type of tree: \
            Basal dendrite: "red" \
            Axon : "blue" \
            Apical dendrite: "purple" \
            Undefined tree: "black" \
            Default value is None.
        new_fig: boolean \
            Defines if the tree will be plotted \
            in the current figure (False) \
            or in a new figure (True) \
            Default value is True.
        subplot: matplotlib subplot value or False \
            If False the default subplot 111 will be used. \
            For any other value a matplotlib subplot \
            will be generated. \
            Default value is False.
        diameter: boolean \
            If True the diameter, scaled with diameter_scale factor, \
            will define the width of the tree lines. \
            If False use linewidth to select the width of the tree lines. \
            Default value is True.
        diameter_scale: float \
            Defines the scale factor that will be multiplied \
            with the diameter to define the width of the tree line. \
            Default value is 1.
        white_space: float \
            Defines the white space around \
            the boundary box of the morphology. \
            Default value is 1.

    Returns:
        A 3D matplotlib figure with a tree view.
    '''
    from mpl_toolkits.mplot3d.art3d import Line3DCollection

    # Initialization of matplotlib figure and axes.
    fig, ax = common.get_figure(new_fig=new_fig, new_axes=new_axes,
                                subplot=subplot, params={'projection': '3d'})

    # Data needed for the viewer: x,y,z,r
    bounding_box = get_bounding_box(tr)

    def _seg_3d(seg):
        '''2d coordinates needed for the plotting of a segment'''
        horz = getattr(COLS, 'X')
        vert = getattr(COLS, 'Y')
        depth = getattr(COLS, 'Z')
        parent_point = seg[0]
        child_point = seg[1]
        horz1 = parent_point[horz]
        horz2 = child_point[horz]
        vert1 = parent_point[vert]
        vert2 = child_point[vert]
        depth1 = parent_point[depth]
        depth2 = child_point[depth]
        return ((horz1, vert1, depth1), (horz2, vert2, depth2))

    segs = [_seg_3d(seg) for seg in val_iter(isegment(tr))]

    linewidth = get_default('linewidth', **kwargs)

    # Definition of the linewidth according to diameter, if diameter is True.
    if get_default('diameter', **kwargs):
        # TODO: This was originally a numpy array. Did it have to be one?
        linewidth = [2 * d * get_default('diameter_scale', **kwargs)
                     for d in iter_neurites(tr, segment_radius)]
        if len(linewidth) == 0:
            linewidth = get_default('linewidth', **kwargs)

    # Plot the collection of lines.
    collection = Line3DCollection(segs,
                                  color=common.get_color(get_default('treecolor', **kwargs),
                                                         get_tree_type(tr)),
                                  linewidth=linewidth, alpha=get_default('alpha', **kwargs))

    ax.add_collection3d(collection)

    kwargs['title'] = kwargs.get('title', 'Tree 3d-view')
    kwargs['xlabel'] = kwargs.get('xlabel', 'X')
    kwargs['ylabel'] = kwargs.get('ylabel', 'Y')
    kwargs['zlabel'] = kwargs.get('zlabel', 'Z')
    kwargs['xlim'] = kwargs.get('xlim', [bounding_box[0][0] - get_default('white_space', **kwargs),
                                         bounding_box[1][0] + get_default('white_space', **kwargs)])
    kwargs['ylim'] = kwargs.get('ylim', [bounding_box[0][1] - get_default('white_space', **kwargs),
                                         bounding_box[1][1] + get_default('white_space', **kwargs)])
    kwargs['zlim'] = kwargs.get('zlim', [bounding_box[0][2] - get_default('white_space', **kwargs),
                                         bounding_box[1][2] + get_default('white_space', **kwargs)])

    return common.plot_style(fig=fig, ax=ax, **kwargs)
示例#37
0
文件: view.py 项目: wvangeit/NeuroM
def tree3d(tr, new_fig=True, new_axes=True, subplot=False, **kwargs):
    """Generates a figure of the tree in 3d.

    Parameters:
        tr: Tree
        neurom.Tree object

    Options:
        linewidth: float \
            Defines the linewidth of the tree, \
            if diameter is set to False. \
            Default value is 1.2.
        alpha: float \
            Defines throughe transparency of the tree. \
            0.0 transparent through 1.0 opaque. \
            Default value is 0.8.
        treecolor: str or None \
            Defines the color of the tree. \
            If None the default values will be used, \
            depending on the type of tree: \
            Basal dendrite: "red" \
            Axon : "blue" \
            Apical dendrite: "purple" \
            Undefined tree: "black" \
            Default value is None.
        new_fig: boolean \
            Defines if the tree will be plotted \
            in the current figure (False) \
            or in a new figure (True) \
            Default value is True.
        subplot: matplotlib subplot value or False \
            If False the default subplot 111 will be used. \
            For any other value a matplotlib subplot \
            will be generated. \
            Default value is False.
        diameter: boolean
            If True the diameter, scaled with diameter_scale factor, \
            will define the width of the tree lines. \
            If False use linewidth to select the width of the tree lines. \
            Default value is True.
        diameter_scale: float \
            Defines the scale factor that will be multiplied \
            with the diameter to define the width of the tree line. \
            Default value is 1.
        white_space: float \
            Defines the white space around \
            the boundary box of the morphology. \
            Default value is 1.

    Returns:
        A 3D matplotlib figure with a tree view.
    """
    from mpl_toolkits.mplot3d.art3d import Line3DCollection

    # Initialization of matplotlib figure and axes.
    fig, ax = common.get_figure(new_fig=new_fig, new_axes=new_axes, subplot=subplot, params={"projection": "3d"})

    # Data needed for the viewer: x,y,z,r
    bounding_box = get_bounding_box(tr)

    def _seg_3d(seg):
        """2d coordinates needed for the plotting of a segment"""
        horz = getattr(COLS, "X")
        vert = getattr(COLS, "Y")
        depth = getattr(COLS, "Z")
        parent_point = seg[0]
        child_point = seg[1]
        horz1 = parent_point[horz]
        horz2 = child_point[horz]
        vert1 = parent_point[vert]
        vert2 = child_point[vert]
        depth1 = parent_point[depth]
        depth2 = child_point[depth]
        return ((horz1, vert1, depth1), (horz2, vert2, depth2))

    segs = [_seg_3d(seg) for seg in val_iter(isegment(tr))]

    linewidth = get_default("linewidth", **kwargs)

    # Definition of the linewidth according to diameter, if diameter is True.
    if get_default("diameter", **kwargs):
        # TODO: This was originally a numpy array. Did it have to be one?
        linewidth = [2 * d * get_default("diameter_scale", **kwargs) for d in i_segment_radius(tr)]

    # Plot the collection of lines.
    collection = Line3DCollection(
        segs,
        color=common.get_color(get_default("treecolor", **kwargs), get_tree_type(tr)),
        linewidth=linewidth,
        alpha=get_default("alpha", **kwargs),
    )

    ax.add_collection3d(collection)

    kwargs["title"] = kwargs.get("title", "Tree 3d-view")
    kwargs["xlabel"] = kwargs.get("xlabel", "X")
    kwargs["ylabel"] = kwargs.get("ylabel", "Y")
    kwargs["zlabel"] = kwargs.get("zlabel", "Z")
    kwargs["xlim"] = kwargs.get(
        "xlim",
        [
            bounding_box[0][0] - get_default("white_space", **kwargs),
            bounding_box[1][0] + get_default("white_space", **kwargs),
        ],
    )
    kwargs["ylim"] = kwargs.get(
        "ylim",
        [
            bounding_box[0][1] - get_default("white_space", **kwargs),
            bounding_box[1][1] + get_default("white_space", **kwargs),
        ],
    )
    kwargs["zlim"] = kwargs.get(
        "zlim",
        [
            bounding_box[0][2] - get_default("white_space", **kwargs),
            bounding_box[1][2] + get_default("white_space", **kwargs),
        ],
    )

    return common.plot_style(fig=fig, ax=ax, **kwargs)
示例#38
0
文件: view.py 项目: wvangeit/NeuroM
def soma(sm, plane='xy', new_fig=True, subplot=False, **kwargs):
    '''Generates a 2d figure of the soma.

    Parameters:
        soma: Soma
        neurom.Soma object

    Options:
        plane: str \
            Accepted values: Any pair of of xyz \
            Default value is 'xy'.treecolor
        linewidth: float \
            Defines the linewidth of the tree, \
            if diameter is set to False. \
            Default value is 1.2.
        alpha: float \
            Defines throughe transparency of the tree. \
            0.0 transparent through 1.0 opaque. \
            Default value is 0.8.
        treecolor: str or None \
            Defines the color of the soma. \
            Soma: black" \
            Default value is None.
        new_fig: boolean \
            Defines if the tree will be plotted \
            in the current figure (False) \
            or in a new figure (True) \
            Default value is True.
        subplot: matplotlib subplot value or False \
            If False the default subplot 111 will be used. \
            For any other value a matplotlib subplot \
            will be generated. \
            Default value is False.
        limits: list or boolean \
            List of type: [[xmin, ymin, zmin], [xmax, ymax, zmax]] \
            If False the figure will not be scaled. \
            If True the figure will be scaled according to tree limits. \
            Default value is False.

    Returns:
        A 2D matplotlib figure with a soma view, at the selected plane.
    '''
    treecolor = kwargs.get('treecolor', None)
    outline = kwargs.get('outline', True)

    if plane not in ('xy', 'yx', 'xz', 'zx', 'yz', 'zy'):
        return None, 'No such plane found! Please select one of: xy, xz, yx, yz, zx, zy.'

    # Initialization of matplotlib figure and axes.
    fig, ax = common.get_figure(new_fig=new_fig, subplot=subplot)

    # Definition of the tree color depending on the tree type.
    treecolor = common.get_color(treecolor, tree_type=TreeType.soma)

    # Plot the outline of the soma as a circle, is outline is selected.
    if not outline:
        soma_circle = common.plt.Circle(sm.center, sm.radius, color=treecolor,
                                        alpha=get_default('alpha', **kwargs))
        ax.add_artist(soma_circle)
    else:
        horz = []
        vert = []

        for s_point in sm.iter():
            horz.append(s_point[getattr(COLS, plane[0].capitalize())])
            vert.append(s_point[getattr(COLS, plane[1].capitalize())])

        horz.append(horz[0]) # To close the loop for a soma viewer. This might be modified!
        vert.append(vert[0]) # To close the loop for a soma viewer. This might be modified!

        common.plt.plot(horz, vert, color=treecolor,
                        alpha=get_default('alpha', **kwargs),
                        linewidth=get_default('linewidth', **kwargs))

    kwargs['title'] = kwargs.get('title', 'Soma view')
    kwargs['xlabel'] = kwargs.get('xlabel', plane[0])
    kwargs['ylabel'] = kwargs.get('ylabel', plane[1])

    return common.plot_style(fig=fig, ax=ax, **kwargs)
示例#39
0
文件: view.py 项目: wvangeit/NeuroM
def neuron(nrn, plane='xy', new_fig=True, subplot=False, **kwargs):
    '''Generates a 2d figure of the neuron,
       that contains a soma and a list of trees.

    Parameters:
        neuron: Neuron
        neurom.Neuron object

    Options:
        plane: str \
            Accepted values: Any pair of of xyz \
            Default value is 'xy'.treecolor
        linewidth: float \
            Defines the linewidth of the tree, \
            if diameter is set to False. \
            Default value is 1.2.
        alpha: float \
            Defines throughe transparency of the tree. \
            0.0 transparent through 1.0 opaque. \
            Default value is 0.8.
        treecolor: str or None \
            Defines the color of the tree. \
            If None the default values will be used, \
            depending on the type of tree: \
            Basal dendrite: "red" \
            Axon : "blue" \
            Apical dendrite: "purple" \
            Undefined tree: "black" \
            Default value is None.
        new_fig: boolean \
            Defines if the tree will be plotted \
            in the current figure (False) \
            or in a new figure (True) \
            Default value is True.
        subplot: matplotlib subplot value or False \
            If False the default subplot 111 will be used. \
            For any other value a matplotlib subplot \
            will be generated. \
            Default value is False.
        diameter: boolean
            If True the diameter, scaled with diameter_scale factor, \
            will define the width of the tree lines. \
            If False use linewidth to select the width of the tree lines. \
            Default value is True.
        diameter_scale: float \
            Defines the scale factor that will be multiplied \
            with the diameter to define the width of the tree line. \
            Default value is 1.
        limits: list or boolean \
            List of type: [[xmin, ymin, zmin], [xmax, ymax, zmax]] \
            If False the figure will not be scaled. \
            If True the figure will be scaled according to tree limits. \
            Default value is False.

    Returns:
        A 3D matplotlib figure with a tree view, at the selected plane.
    '''
    if plane not in ('xy', 'yx', 'xz', 'zx', 'yz', 'zy'):
        return None, 'No such plane found! Please select one of: xy, xz, yx, yz, zx, zy.'

    # Initialization of matplotlib figure and axes.
    fig, ax = common.get_figure(new_fig=new_fig, subplot=subplot)

    kwargs['new_fig'] = False
    kwargs['subplot'] = subplot

    soma(nrn.soma, plane=plane, **kwargs)

    kwargs['title'] = kwargs.get('title', 'Neuron view')
    kwargs['xlabel'] = kwargs.get('xlabel', plane[0])
    kwargs['ylabel'] = kwargs.get('ylabel', plane[1])

    h = []
    v = []

    for temp_tree in nrn.neurites:

        bounding_box = get_bounding_box(temp_tree)

        h.append([bounding_box[0][getattr(COLS, plane[0].capitalize())],
                  bounding_box[1][getattr(COLS, plane[0].capitalize())]])
        v.append([bounding_box[0][getattr(COLS, plane[1].capitalize())],
                  bounding_box[1][getattr(COLS, plane[1].capitalize())]])

        tree(temp_tree, plane=plane, **kwargs)

    if h:
        kwargs['xlim'] = kwargs.get('xlim', [np.min(h) - get_default('white_space', **kwargs),
                                             np.max(h) + get_default('white_space', **kwargs)])
    if v:
        kwargs['ylim'] = kwargs.get('ylim', [np.min(v) - get_default('white_space', **kwargs),
                                             np.max(v) + get_default('white_space', **kwargs)])

    return common.plot_style(fig=fig, ax=ax, **kwargs)
示例#40
0
def dendrogram(obj, show_diameters=True, new_fig=True, new_axes=True, subplot=False, **kwargs):
    '''
    Generates a figure of the neuron,
    that contains a soma and a list of trees.

    Parameters:
        obj: Neuron or tree \
        neurom.Neuron, neurom.Tree
        show_diameters : boolean \
            Determines if node diameters will \
            be show or not.
        linewidth: float \
            Defines the linewidth of the tree, \
            if diameter is set to False. \
            Default value is 1.2.
        alpha: float \
            Defines throughe transparency of the tree. \
            0.0 transparent through 1.0 opaque. \
            Default value is 0.8.
        treecolor: str or None \
            Defines the color of the tree. \
            If None the default values will be used, \
            depending on the type of tree: \
            Basal dendrite: "red" \
            Axon : "blue" \
            Apical dendrite: "purple" \
            Undefined tree: "black" \
            Default value is None.
        new_fig: boolean \
            Defines if the tree will be plotted \
            in the current figure (False) \
            or in a new figure (True) \
            Default value is True.
        subplot: matplotlib subplot value or False \
            If False the default subplot 111 will be used. \
            For any other value a matplotlib subplot \
            will be generated. \
            Default value is False.

    Returns:
        A 2D matplotlib figure with a dendrogram view.
    '''
    from neurom.analysis.dendrogram import Dendrogram

    # create dendrogram and generate rectangle collection
    dnd = Dendrogram(obj, show_diameters=show_diameters)
    dnd.generate()

    fig, ax = common.get_figure(new_fig=new_fig, new_axes=new_axes, subplot=subplot)

    # render dendrogram and take into account neurite displacement which
    # starts as zero. It is important to avoid overlapping of neurites
    # and to determine tha limits of the figure.

    displacement = _render_dendrogram(dnd, ax, 0.)

    # customization settings
    kwargs['xlim'] = [- dnd.dims[0][0] * 0.5, dnd.dims[-1][0] * 0.5 + displacement]

    kwargs['title'] = kwargs.get('title', 'Morphology Dendrogram')
    kwargs['xlabel'] = kwargs.get('xlabel', 'micrometers (um)')
    kwargs['ylabel'] = kwargs.get('ylabel', 'micrometers (um)')
    kwargs['no_legend'] = False

    return common.plot_style(fig=fig, ax=ax, **kwargs)
示例#41
0
def neuron(nrn, plane='xy', new_fig=True, subplot=False, **kwargs):
    '''
    Generates a 2d figure of the neuron, \
    that contains a soma and a list of trees.

    Parameters:
        neuron: Neuron \
        neurom.Neuron object
        plane: str \
            Accepted values: Any pair of of xyz \
            Default value is 'xy'.treecolor
        linewidth: float \
            Defines the linewidth of the tree, \
            if diameter is set to False. \
            Default value is 1.2.
        alpha: float \
            Defines throughe transparency of the tree. \
            0.0 transparent through 1.0 opaque. \
            Default value is 0.8.
        treecolor: str or None \
            Defines the color of the tree. \
            If None the default values will be used, \
            depending on the type of tree: \
            Basal dendrite: "red" \
            Axon : "blue" \
            Apical dendrite: "purple" \
            Undefined tree: "black" \
            Default value is None.
        new_fig: boolean \
            Defines if the tree will be plotted \
            in the current figure (False) \
            or in a new figure (True) \
            Default value is True.
        subplot: matplotlib subplot value or False \
            If False the default subplot 111 will be used. \
            For any other value a matplotlib subplot \
            will be generated. \
            Default value is False.
        diameter: boolean
            If True the diameter, scaled with diameter_scale factor, \
            will define the width of the tree lines. \
            If False use linewidth to select the width of the tree lines. \
            Default value is True.
        diameter_scale: float \
            Defines the scale factor that will be multiplied \
            with the diameter to define the width of the tree line. \
            Default value is 1.
        limits: list or boolean \
            List of type: [[xmin, ymin, zmin], [xmax, ymax, zmax]] \
            If False the figure will not be scaled. \
            If True the figure will be scaled according to tree limits. \
            Default value is False.

    Returns:
        A 3D matplotlib figure with a tree view, at the selected plane.
    '''
    if plane not in ('xy', 'yx', 'xz', 'zx', 'yz', 'zy'):
        return None, 'No such plane found! Please select one of: xy, xz, yx, yz, zx, zy.'

    # Initialization of matplotlib figure and axes.
    fig, ax = common.get_figure(new_fig=new_fig, subplot=subplot)

    kwargs['new_fig'] = False
    kwargs['subplot'] = subplot

    soma(nrn.soma, plane=plane, **kwargs)

    kwargs['title'] = kwargs.get('title', 'Neuron view')
    kwargs['xlabel'] = kwargs.get('xlabel', plane[0])
    kwargs['ylabel'] = kwargs.get('ylabel', plane[1])

    h = []
    v = []

    for temp_tree in nrn.neurites:

        bounding_box = get_bounding_box(temp_tree)

        h.append([bounding_box[0][getattr(COLS, plane[0].capitalize())],
                  bounding_box[1][getattr(COLS, plane[0].capitalize())]])
        v.append([bounding_box[0][getattr(COLS, plane[1].capitalize())],
                  bounding_box[1][getattr(COLS, plane[1].capitalize())]])

        tree(temp_tree, plane=plane, **kwargs)

    if h:
        kwargs['xlim'] = kwargs.get('xlim', [np.min(h) - get_default('white_space', **kwargs),
                                             np.max(h) + get_default('white_space', **kwargs)])
    if v:
        kwargs['ylim'] = kwargs.get('ylim', [np.min(v) - get_default('white_space', **kwargs),
                                             np.max(v) + get_default('white_space', **kwargs)])

    return common.plot_style(fig=fig, ax=ax, **kwargs)