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)
def test_tree_type_checker_broken(): tree_filter = tree_type_checker(NeuriteType.all) assert tree_filter('fake_tree') mock_tree = Mock() mock_tree.type = NeuriteType.axon tree_filter = tree_type_checker(*NEURITES) assert tree_filter(mock_tree) tree_filter = tree_type_checker(NeuriteType.axon, NeuriteType.apical_dendrite, NeuriteType.basal_dendrite) mock_tree.type = NeuriteType.soma assert not tree_filter(mock_tree)
def plot_neuron(ax, nrn, neurite_type=NeuriteType.all, plane='xy', soma_outline=True, diameter_scale=_DIAMETER_SCALE, linewidth=_LINEWIDTH, color=None, alpha=_ALPHA): '''Plots a 2D figure of the neuron, that contains a soma and the neurites Args: ax(matplotlib axes): on what to plot neurite_type(NeuriteType): an optional filter on the neurite type nrn(neuron): neuron to be plotted soma_outline(bool): should the soma be drawn as an outline plane(str): Any pair of 'xyz' diameter_scale(float): Scale factor multiplied with segment diameters before plotting linewidth(float): all segments are plotted with this width, but only if diameter_scale=None color(str or None): Color of plotted values, None corresponds to default choice alpha(float): Transparency of plotted values ''' plot_soma(ax, nrn.soma, plane=plane, soma_outline=soma_outline, linewidth=linewidth, color=color, alpha=alpha) for neurite in iter_neurites(nrn, filt=tree_type_checker(neurite_type)): plot_tree(ax, neurite, plane=plane, diameter_scale=diameter_scale, linewidth=linewidth, color=color, alpha=alpha) ax.set_title(nrn.name) ax.set_xlabel(plane[0]) ax.set_ylabel(plane[1])
def _iter_neurites(self, iterator_type, mapping=None, neurite_type=TreeType.all): '''Iterate over collection of neurites applying iterator_type Parameters: iterator_type: Type of iterator with which to perform the iteration.\ (e.g. isegment, isection) mapping: mapping function to be applied to the target of iteration.\ (e.g. segment_length). Must be compatible with the iterator_type. neurite_type: TreeType object. Neurites of incompatible type are\ filtered out. Returns: Iterator of mapped iteration targets. Example: Get the total volume of all neurites in the cell and the total\ length or neurites from their segments. >>> from neurom import ezy >>> from neurom.analysis import morphmath as mm >>> from neurom.core import tree as tr >>> nrn = ezy.load_neuron('test_data/swc/Neuron.swc') >>> v = sum(nrn.iter_neurites(tr.isegment, mm.segment_volume)) >>> tl = sum(nrn.iter_neurites(tr.isegment, mm.segment_length))) ''' return self.i_neurites(iterator_type, mapping, tree_filter=tree_type_checker(neurite_type))
def plot_neuron3d(ax, nrn, neurite_type=NeuriteType.all, diameter_scale=_DIAMETER_SCALE, linewidth=_LINEWIDTH, color=None, alpha=_ALPHA): """Generates a figure of the neuron, that contains a soma and a list of trees. Args: ax(matplotlib axes): on what to plot nrn(neuron): neuron to be plotted neurite_type(NeuriteType): an optional filter on the neurite type diameter_scale(float): Scale factor multiplied with segment diameters before plotting linewidth(float): all segments are plotted with this width, but only if diameter_scale=None color(str or None): Color of plotted values, None corresponds to default choice alpha(float): Transparency of plotted values """ plot_soma3d(ax, nrn.soma, color=color, alpha=alpha) for neurite in iter_neurites(nrn, filt=tree_type_checker(neurite_type)): plot_tree3d(ax, neurite, diameter_scale=diameter_scale, linewidth=linewidth, color=color, alpha=alpha) ax.set_title(nrn.name)
def test_tree_type_checker_broken(): tree_filter = tree_type_checker(NeuriteType.all) mock_tree = Mock() mock_tree.type = NeuriteType.soma nt.ok_(not tree_filter(mock_tree)) mock_tree.type = NeuriteType.undefined nt.ok_(not tree_filter(mock_tree))
def _pkg(self, magic_iter, neurite_type=TreeType.all): '''Return an iterable built from magic_iter''' stuff = list( iter_neurites(self, magic_iter, tree_type_checker(neurite_type)) ) return self._iterable_type(stuff)
def test_tree_type_checker(): #check that when NeuriteType.all, we accept all trees, w/o checking type tree_filter = tree_type_checker(NeuriteType.all) nt.ok_(tree_filter('fake_tree')) mock_tree = Mock() mock_tree.type = NeuriteType.axon #single arg tree_filter = tree_type_checker(NeuriteType.axon) nt.ok_(tree_filter(mock_tree)) mock_tree.type = NeuriteType.basal_dendrite nt.ok_(not tree_filter(mock_tree)) #multiple args tree_filter = tree_type_checker(NeuriteType.axon, NeuriteType.basal_dendrite) nt.ok_(tree_filter(mock_tree)) tree_filter = tree_type_checker(*NEURITES) nt.ok_(tree_filter('fake_tree'))
def test_tree_type_checker(): # check that when NeuriteType.all, we accept all trees, w/o checking type tree_filter = tree_type_checker(NeuriteType.all) assert tree_filter('fake_tree') mock_tree = Mock() mock_tree.type = NeuriteType.axon # single arg tree_filter = tree_type_checker(NeuriteType.axon) assert tree_filter(mock_tree) mock_tree.type = NeuriteType.basal_dendrite assert not tree_filter(mock_tree) # multiple args tree_filter = tree_type_checker(NeuriteType.axon, NeuriteType.basal_dendrite) assert tree_filter(mock_tree) tree_filter = tree_type_checker( (NeuriteType.axon, NeuriteType.basal_dendrite)) assert tree_filter(mock_tree) tree_filter = tree_type_checker(*NEURITES) assert tree_filter('fake_tree') assert tree_filter(mock_tree) tree_filter = tree_type_checker(NEURITES) assert tree_filter('fake_tree') assert tree_filter(mock_tree)
def plot_neuron3d(ax, nrn, neurite_type=NeuriteType.all, diameter_scale=_DIAMETER_SCALE, linewidth=_LINEWIDTH, color=None, alpha=_ALPHA): ''' Generates a figure of the neuron, that contains a soma and a list of trees. Args: ax(matplotlib axes): on what to plot nrn(neuron): neuron to be plotted neurite_type(NeuriteType): an optional filter on the neurite type diameter_scale(float): Scale factor multiplied with segment diameters before plotting linewidth(float): all segments are plotted with this width, but only if diameter_scale=None color(str or None): Color of plotted values, None corresponds to default choice alpha(float): Transparency of plotted values ''' plot_soma3d(ax, nrn.soma, color=color, alpha=alpha) for neurite in iter_neurites(nrn, filt=tree_type_checker(neurite_type)): plot_tree3d(ax, neurite, diameter_scale=diameter_scale, linewidth=linewidth, color=color, alpha=alpha) ax.set_title(nrn.name)
def sections(self, neurite_type=TreeType.all): '''Returns sections ''' return i_neurites(self.neurites, lambda n: n.sections(), neu_filter=tree_type_checker(neurite_type))
def get_n_sections(self, neurite_type=TreeType.all): '''Get the number of sections of a given type''' tree_filter = tree_type_checker(neurite_type) return _sec.count(self, tree_filter)
def test_tree_type_checker_error(): with pytest.raises(ValueError, match='is not a valid NeuriteType'): tree_type_checker('all')
def get_n_sections_per_neurite(self, neurite_type=TreeType.all): '''Get an iterable with the number of sections for a given neurite type''' tree_filter = tree_type_checker(neurite_type) return self._iterable_type( [_sec.count(n) for n in self.neurites if tree_filter(n)] )
print('Total number of points:', sum(1 for _ in iter_neurites(nrn, pts.identity))) # get mean radius of points in cell. # p[COLS.R] yields the radius for point p. print('Mean radius of points:', np.mean([r for r in iter_neurites(nrn, pts.radius)])) # get mean radius of segments print('Mean radius of segments:', np.mean(list(iter_neurites(nrn, seg.radius)))) # get stats for the segment taper rate, for different types of neurite for ttype in ezy.NEURITE_TYPES: ttt = ttype seg_taper_rate = list(iter_neurites(nrn, seg.taper_rate, tree_type_checker(ttt))) print('Segment taper rate (', ttype, '):\n mean=', np.mean(seg_taper_rate), ', std=', np.std(seg_taper_rate), ', min=', np.min(seg_taper_rate), ', max=', np.max(seg_taper_rate), sep='') # Number of bifurcation points. print('Number of bifurcation points:', bif.count(nrn)) # Number of bifurcation points for apical dendrites print('Number of bifurcation points (apical dendrites):', sum(1 for _ in iter_neurites(nrn, bif.identity, tree_type_checker(ezy.TreeType.apical_dendrite))))
# Note: this includes duplicated points at beginning of # non-trunk sections pts = [p[COLS.R] for s in nrn.sections[1:] for p in s.points] print('Mean radius of points:', np.mean(pts)) # get mean radius of segments print('Mean radius of segments:', np.mean(list(mm.segment_radius(s) for s in nm.iter_segments(nrn)))) # get stats for the segment taper rate, for different types of neurite for ttype in NEURITES: ttt = ttype seg_taper_rate = [ mm.segment_taper_rate(s) for s in nm.iter_segments(nrn, neurite_filter=tree_type_checker(ttt)) ] print('Segment taper rate (', ttype, '):\n mean=', np.mean(seg_taper_rate), ', std=', np.std(seg_taper_rate), ', min=', np.min(seg_taper_rate), ', max=', np.max(seg_taper_rate), sep='') # Number of bifurcation points.
# p[COLS.R] yields the radius for point p. # Note: this includes duplicated points at beginning of # non-trunk sections pts = [p[COLS.R] for s in nrn.sections[1:] for p in s.points] print('Mean radius of points:', np.mean(pts)) # get mean radius of segments print('Mean radius of segments:', np.mean(list(mm.segment_radius(s) for s in nm.iter_segments(nrn)))) # get stats for the segment taper rate, for different types of neurite for ttype in NEURITES: ttt = ttype seg_taper_rate = [ mm.segment_taper_rate(s) for s in nm.iter_segments(nrn, neurite_filter=tree_type_checker(ttt)) ] print('Segment taper rate (', ttype, '):\n mean=', np.mean(seg_taper_rate), ', std=', np.std(seg_taper_rate), ', min=', np.min(seg_taper_rate), ', max=', np.max(seg_taper_rate), sep='') # Number of bifurcation points.
def get_n_neurites(self, neurite_type=TreeType.all): '''Get the number of neurites of a given type in a neuron''' tree_filter = tree_type_checker(neurite_type) return sum(1 for n in self.neurites if tree_filter(n))
def get_trunk_origin_radii(self, neurite_type=TreeType.all): '''Get the trunk origin radii of a given type in a neuron''' tree_filter = tree_type_checker(neurite_type) return self._iterable_type( [_pts.radius(t) for t in self.neurites if tree_filter(t)] )
def get_trunk_section_lengths(self, neurite_type=TreeType.all): '''Get the trunk section lengths of a given type in a neuron''' tree_filter = tree_type_checker(neurite_type) return self._iterable_type( [trunk_section_length(t) for t in self.neurites if tree_filter(t)] )
def _fun(neurites, neurite_type=NeuriteType.all): """Wrap neurite function from outer scope and map into list.""" return list( func(n) for n in iter_neurites(neurites, filt=tree_type_checker(neurite_type)))
# p[COLS.R] yields the radius for point p. # Note: this includes duplicated points at beginning of # non-trunk sections pts = [p[COLS.R] for s in nrn.sections[1:] for p in s.points] print('Mean radius of points:', np.mean(pts)) # get mean radius of segments print('Mean radius of segments:', np.mean(list(mm.segment_radius(s) for s in nm.iter_segments(nrn)))) # get stats for the segment taper rate, for different types of neurite for ttype in NEURITES: ttt = ttype seg_taper_rate = [mm.segment_taper_rate(s) for s in nm.iter_segments(nrn, neurite_filter=tree_type_checker(ttt))] print('Segment taper rate (', ttype, '):\n mean=', np.mean(seg_taper_rate), ', std=', np.std(seg_taper_rate), ', min=', np.min(seg_taper_rate), ', max=', np.max(seg_taper_rate), sep='') # Number of bifurcation points. print('Number of bifurcation points:', sum(1 for _ in nm.iter_sections(nrn, iterator_type=Tree.ibifurcation_point))) # Number of bifurcation points for apical dendrites print('Number of bifurcation points (apical dendrites):',