Esempio n. 1
0
    def save_morph_data(self, morph_stats_filename):

        if not os.path.exists(morph_stats_filename):

            #  load a neuron from an SWC file
            nrn = nm.load_neuron(self.morph_file)

            morph_stats = {}

            morph_stats['cell_id'] = self.cell_id
            morph_stats['soma_suface'] = nm.get('soma_surface_areas', nrn)[0]
            morph_stats['soma_radius'] = np.mean(nm.get('soma_radii', nrn))

            # Morph stats
            for nrn_type_ in NEURITES:

                morph_stats['length' + '.' +
                            str(nrn_type_).split('.')[1]] = np.sum(
                                nm.get('segment_lengths',
                                       nrn,
                                       neurite_type=nrn_type_))
                morph_stats['area' + '.' + str(nrn_type_).split('.')[1]] = sum(
                    mm.segment_area(s) for s in nm.iter_segments(
                        nrn, neurite_filter=tree_type_checker(nrn_type_)))
                morph_stats[
                    'volume' + '.' + str(nrn_type_).split('.')[1]] = sum(
                        mm.segment_volume(s) for s in nm.iter_segments(
                            nrn, neurite_filter=tree_type_checker(nrn_type_)))
                morph_stats['taper_rate' + '.' + str(nrn_type_).split('.')[1]] = \
                    np.mean([mm.segment_taper_rate(s) for s in nm.iter_segments(
                        nrn, neurite_filter=tree_type_checker(nrn_type_))])

            utility.save_json(morph_stats_filename, morph_stats)
Esempio n. 2
0
def neurite_centre_of_mass(neurite):
    '''Calculate and return centre of mass of a neurite.'''
    centre_of_mass = np.zeros(3)
    total_volume = 0

    seg_vol = np.array(map(mm.segment_volume, nm.iter_segments(neurite)))
    seg_centre_of_mass = np.array(map(segment_centre_of_mass, nm.iter_segments(neurite)))

    # multiply array of scalars with array of arrays
    # http://stackoverflow.com/questions/5795700/multiply-numpy-array-of-scalars-by-array-of-vectors
    seg_centre_of_mass = seg_centre_of_mass * seg_vol[:, np.newaxis]
    centre_of_mass = np.sum(seg_centre_of_mass, axis=0)
    total_volume = np.sum(seg_vol)
    return centre_of_mass / total_volume
Esempio n. 3
0
def neurite_centre_of_mass(neurite):
    """Calculate and return centre of mass of a neurite."""
    centre_of_mass = np.zeros(3)
    total_volume = 0

    seg_vol = np.array(map(mm.segment_volume, nm.iter_segments(neurite)))
    seg_centre_of_mass = np.array(map(segment_centre_of_mass, nm.iter_segments(neurite)))

    # multiply array of scalars with array of arrays
    # http://stackoverflow.com/questions/5795700/multiply-numpy-array-of-scalars-by-array-of-vectors
    seg_centre_of_mass = seg_centre_of_mass * seg_vol[:, np.newaxis]
    centre_of_mass = np.sum(seg_centre_of_mass, axis=0)
    total_volume = np.sum(seg_vol)
    return centre_of_mass / total_volume
Esempio n. 4
0
def radius_of_gyration(neurite):
    """Calculate and return radius of gyration of a given neurite."""
    centre_mass = neurite_centre_of_mass(neurite)
    sum_sqr_distance = 0
    N = 0
    dist_sqr = [distance_sqr(centre_mass, s) for s in nm.iter_segments(neurite)]
    sum_sqr_distance = np.sum(dist_sqr)
    N = len(dist_sqr)
    return np.sqrt(sum_sqr_distance / N)
Esempio n. 5
0
def radius_of_gyration(neurite):
    '''Calculate and return radius of gyration of a given neurite.'''
    centre_mass = neurite_centre_of_mass(neurite)
    sum_sqr_distance = 0
    N = 0
    dist_sqr = [distance_sqr(centre_mass, s) for s in nm.iter_segments(neurite)]
    sum_sqr_distance = np.sum(dist_sqr)
    N = len(dist_sqr)
    return np.sqrt(sum_sqr_distance / N)
Esempio n. 6
0
def calculate_and_plot_end_to_end_distance(neurite):
    '''Calculate and plot the end-to-end distance vs the number of segments for
    an increasingly larger part of a given neurite.

    Note that the plots are not very meaningful for bifurcating trees.'''
    def _dist(seg):
        '''Distance between segmenr end and trunk'''
        return morphmath.point_dist(seg[1], neurite.root_node.points[0])

    end_to_end_distance = [_dist(s) for s in nm.iter_segments(neurite)]
    make_end_to_end_distance_plot(np.arange(len(end_to_end_distance)) + 1,
                                  end_to_end_distance, neurite.type)
Esempio n. 7
0
def calculate_and_plot_end_to_end_distance(neurite):
    """Calculate and plot the end-to-end distance vs the number of segments for
    an increasingly larger part of a given neurite.

    Note that the plots are not very meaningful for bifurcating trees."""
    def _dist(seg):
        """Distance between segmenr end and trunk."""
        return morphmath.point_dist(seg[1], neurite.root_node.points[0])

    end_to_end_distance = [_dist(s) for s in nm.iter_segments(neurite)]
    make_end_to_end_distance_plot(np.arange(len(end_to_end_distance)) + 1,
                                  end_to_end_distance, neurite.type)
Esempio n. 8
0
def _make_trace(neuron,
                plane,
                prefix='',
                opacity=1.,
                visible=True,
                style=None,
                line_width=2):
    '''Create the trace to be plotted'''
    names = defaultdict(int)
    lines = list()
    for neurite in iter_neurites(neuron):
        names[neurite.type] += 1

        coords = dict(x=list(), y=list(), z=list())
        colors = list()

        try:
            default_color = style[neurite]['color']
        except KeyError:
            default_color = TREE_COLOR.get(neurite.root_node.type, 'black')

        for section in iter_sections(neurite):
            segs = [(s[0][COLS.XYZ], s[1][COLS.XYZ])
                    for s in iter_segments(section)]

            section_style = style.get(section, {
                'range': slice(0, len(segs)),
                'color': default_color
            })
            range_ = section_style['range']
            colors += list(repeat(default_color, 3 * range_.start))
            colors += list(
                repeat(section_style['color'],
                       3 * (range_.stop - range_.start)))
            colors += list(repeat(default_color,
                                  3 * (len(segs) - range_.stop)))

            for i, coord in enumerate('xyz'):
                coords[coord] += list(
                    chain.from_iterable(
                        (p1[i], p2[i], None) for p1, p2 in segs) if coord in
                    plane else chain.from_iterable((0, 0, None) for _ in segs))

        lines.append(
            go.Scatter3d(name=_neurite_name(neurite, prefix, names),
                         showlegend=False,
                         visible=visible,
                         opacity=opacity,
                         line=dict(color=colors, width=line_width),
                         mode='lines',
                         **coords))
    return lines
Esempio n. 9
0
def _make_trace2d(neuron,
                  plane,
                  prefix='',
                  opacity=1.,
                  visible=True,
                  style=None,
                  line_width=2):
    '''Create the trace to be plotted'''
    names = defaultdict(int)
    lines = list()
    for neurite in iter_neurites(neuron):
        names[neurite.type] += 1

        try:
            neurite_color = style[neurite]['color']
        except KeyError:
            neurite_color = TREE_COLOR.get(neurite.root_node.type, 'black')

        name = _neurite_name(neurite, prefix, names)

        for section in iter_sections(neurite):
            segs = [(s[0][COLS.XYZ], s[1][COLS.XYZ])
                    for s in iter_segments(section)]

            try:
                colors = style[section]['color']
            except KeyError:
                colors = neurite_color

            coords = dict()
            for i, coord in enumerate('xyz'):
                coords[coord] = list(
                    chain.from_iterable(
                        (p1[i], p2[i], None) for p1, p2 in segs))

            coords = dict(x=coords[plane[0]], y=coords[plane[1]])
            lines.append(
                go.Scattergl(name=name,
                             visible=visible,
                             opacity=opacity,
                             showlegend=False,
                             line=dict(color=colors, width=line_width),
                             mode='lines',
                             **coords))
    return lines
Esempio n. 10
0
def _make_trace(neuron, plane):
    """Create the trace to be plotted."""
    for neurite in iter_neurites(neuron):
        segments = list(iter_segments(neurite))

        segs = [(s[0][COLS.XYZ], s[1][COLS.XYZ]) for s in segments]

        coords = dict(
            x=list(chain.from_iterable(
                (p1[0], p2[0], None) for p1, p2 in segs)),
            y=list(chain.from_iterable(
                (p1[1], p2[1], None) for p1, p2 in segs)),
            z=list(chain.from_iterable(
                (p1[2], p2[2], None) for p1, p2 in segs)))

        color = TREE_COLOR.get(neurite.root_node.type, 'black')
        if plane.lower() == '3d':
            plot_fun = go.Scatter3d
        else:
            plot_fun = go.Scatter
            coords = dict(x=coords[plane[0]], y=coords[plane[1]])
        yield plot_fun(line=dict(color=color, width=2), mode='lines', **coords)
Esempio n. 11
0
def _make_trace(neuron, plane):
    '''Create the trace to be plotted'''
    for neurite in iter_neurites(neuron):
        segments = list(iter_segments(neurite))

        segs = [(s[0][COLS.XYZ], s[1][COLS.XYZ]) for s in segments]

        coords = dict(x=list(chain.from_iterable((p1[0], p2[0], None) for p1, p2 in segs)),
                      y=list(chain.from_iterable((p1[1], p2[1], None) for p1, p2 in segs)),
                      z=list(chain.from_iterable((p1[2], p2[2], None) for p1, p2 in segs)))

        color = TREE_COLOR.get(neurite.root_node.type, 'black')
        if plane.lower() == '3d':
            plot_fun = go.Scatter3d
        else:
            plot_fun = go.Scatter
            coords = dict(x=coords[plane[0]], y=coords[plane[1]])
        yield plot_fun(
            line=dict(color=color, width=2),
            mode='lines',
            **coords
        )
Esempio n. 12
0
    # any function that takes a segment or section.

    # Get of all neurites in cell by iterating over sections,
    # and summing the section lengths
    def sec_len(sec):
        """Return the length of a section."""
        return mm.section_length(sec.points)

    print('Total neurite length (sections):',
          sum(sec_len(s) for s in nm.iter_sections(nrn)))

    # Get length of all neurites in cell by iterating over segments,
    # and summing the segment lengths.
    # This should yield the same result as iterating over sections.
    print('Total neurite length (segments):',
          sum(mm.segment_length(s) for s in nm.iter_segments(nrn)))

    # get volume of all neurites in cell by summing over segment
    # volumes
    print('Total neurite volume:',
          sum(mm.segment_volume(s) for s in nm.iter_segments(nrn)))

    # get area of all neurites in cell by summing over segment
    # areas
    print('Total neurite surface area:',
          sum(mm.segment_area(s) for s in nm.iter_segments(nrn)))

    # get total number of neurite points in cell.
    def n_points(sec):
        """number of points in a section."""
        n = len(sec.points)
    # any function that takes a segment or section.

    # Get of all neurites in cell by iterating over sections,
    # and summing the section lengths
    def sec_len(sec):
        '''Return the length of a section'''
        return mm.section_length(sec.points)

    print('Total neurite length (sections):',
          sum(sec_len(s) for s in nm.iter_sections(nrn)))

    # Get length of all neurites in cell by iterating over segments,
    # and summing the segment lengths.
    # This should yield the same result as iterating over sections.
    print('Total neurite length (segments):',
          sum(mm.segment_length(s) for s in nm.iter_segments(nrn)))

    # get volume of all neurites in cell by summing over segment
    # volumes
    print('Total neurite volume:',
          sum(mm.segment_volume(s) for s in nm.iter_segments(nrn)))

    # get area of all neurites in cell by summing over segment
    # areas
    print('Total neurite surface area:',
          sum(mm.segment_area(s) for s in nm.iter_segments(nrn)))

    # get total number of neurite points in cell.
    def n_points(sec):
        '''number of points in a section'''
        n = len(sec.points)