def get_sholl_parts(neuron, step_size):
    """return a dataframe including sholl frequency of apical and basal dendrites
    'step_size': the increasing radius (um)"""
    shollf1 = nm.get(
        "sholl_frequency",
        neuron,
        step_size=step_size,
        neurite_type=nm.NeuriteType.apical_dendrite,
    )
    shollf2 = nm.get(
        "sholl_frequency",
        neuron,
        step_size=step_size,
        neurite_type=nm.NeuriteType.basal_dendrite,
    )
    r1 = np.arange(len(shollf1)) * step_size
    r2 = np.arange(len(shollf2)) * step_size
    df1 = pd.DataFrame(
        {"radius": r1, "intersections": shollf1, "label": "apical", "id": neuron.name}
    )
    df2 = pd.DataFrame(
        {"radius": r2, "intersections": shollf2, "label": "basal", "id": neuron.name}
    )
    df = pd.concat([df1, df2])
    return df[df.intersections > 0]
 def f3(name):
     cur_res0=nm.get(name, neuron).sum()
     cur_res1=nm.get(name, neuron, neurite_type=nm.APICAL_DENDRITE).sum()
     cur_res2=nm.get(name, neuron, neurite_type=nm.BASAL_DENDRITE).sum()
     yield (name, cur_res0)
     yield (name+'(apical)', cur_res1)
     yield (name+'(basal)', cur_res2)
Example #3
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)
Example #4
0
def extract_stats(neurons, config):
    '''Extract stats from neurons'''

    stats = defaultdict(dict)
    for ns, modes in config['neurite'].items():
        for n in config['neurite_type']:
            n = _NEURITE_MAP[n]
            for mode in modes:
                stat_name = _stat_name(ns, mode)
                stat = eval_stats(nm.get(ns, neurons, neurite_type=n), mode)

                if stat is None or len(stat.shape) == 0:
                    stats[n.name][stat_name] = stat
                else:
                    assert stat.shape in ((3, ), ), \
                        'Statistic must create a 1x3 result'

                    for i, suffix in enumerate('XYZ'):
                        compound_stat_name = stat_name + '_' + suffix
                        stats[n.name][compound_stat_name] = stat[i]

    for ns, modes in config['neuron'].items():
        for mode in modes:
            stat_name = _stat_name(ns, mode)
            stats[stat_name] = eval_stats(nm.get(ns, neurons), mode)

    return stats
def test_segment_radial_distances_origin():
    origin = (-100, -200, -300)
    ref_segs = nf.segment_radial_distances(NEURON)
    ref_segs_origin = nf.segment_radial_distances(NEURON, origin=origin)

    rad_dists = get_feature('segment_radial_distances', NEURON)
    rad_dists_origin = get_feature('segment_radial_distances',
                                   NEURON,
                                   origin=origin)

    nt.ok_(np.all(rad_dists == ref_segs))
    nt.ok_(np.all(rad_dists_origin == ref_segs_origin))
    nt.ok_(np.all(rad_dists_origin != ref_segs))

    nrns = [
        nm.load_neuron(Path(SWC_PATH, f))
        for f in ('point_soma_single_neurite.swc',
                  'point_soma_single_neurite2.swc')
    ]
    pop = Population(nrns)
    rad_dist_nrns = []
    for nrn in nrns:
        rad_dist_nrns.extend(nm.get('segment_radial_distances', nrn))

    rad_dist_nrns = np.array(rad_dist_nrns)
    rad_dist_pop = nm.get('segment_radial_distances', pop)
    assert_allclose(rad_dist_nrns, rad_dist_pop)
Example #6
0
def extract_stats(neurons, config):
    """Extract stats from neurons."""
    stats = defaultdict(dict)

    def _fill_compoundified(data, stat_name, stat):
        """Insert the stat in the dict and eventually split it into XYZ components."""
        if stat is None or not isinstance(
                stat, np.ndarray) or stat.shape not in ((3, ), ):
            data[stat_name] = stat
        else:
            for i, suffix in enumerate('XYZ'):
                compound_stat_name = stat_name + '_' + suffix
                data[compound_stat_name] = stat[i]

    for (feature_name,
         modes), neurite_type in product(config['neurite'].items(),
                                         config['neurite_type']):
        neurite_type = _NEURITE_MAP[neurite_type]
        for mode in modes:
            stat_name = _stat_name(feature_name, mode)
            stat = eval_stats(
                nm.get(feature_name, neurons, neurite_type=neurite_type), mode)
            _fill_compoundified(stats[neurite_type.name], stat_name, stat)

    for feature_name, modes in config['neuron'].items():
        for mode in modes:
            stat_name = _stat_name(feature_name, mode)
            stat = eval_stats(nm.get(feature_name, neurons), mode)
            _fill_compoundified(stats, stat_name, stat)

    return stats
Example #7
0
def extract_stats(neurons, config):
    """Extract stats from neurons.

    Arguments:
        neurons: a neuron, population, neurite tree or list of neuron paths/str
        config (dict): configuration dict. The keys are:
            - neurite_type: a list of neurite types for which features are extracted
              If not provided, all neurite_type will be used
            - neurite: a dictionary {{neurite_feature: mode}} where:
                - neurite_feature is a string from NEURITEFEATURES
                - mode is an aggregation operation provided as a string such as:
                  ['min', 'max', 'median', 'mean', 'std', 'raw', 'total']

    Returns:
        The extracted statistics

    Note:
        An example config can be found at:

    {config_path}
    """

    def _fill_stats_dict(data, stat_name, stat):
        """Insert the stat data in the dict.

        And if the stats is a 3D array, splits it into XYZ components.
        """
        if stat is None or not isinstance(stat, np.ndarray) or stat.shape not in ((3, ), ):
            data[stat_name] = stat
        else:
            for i, suffix in enumerate('XYZ'):
                compound_stat_name = stat_name + '_' + suffix
                data[compound_stat_name] = stat[i]

    stats = defaultdict(dict)

    for (feature_name, modes), neurite_type in product(config['neurite'].items(),
                                                       config.get('neurite_type',
                                                                  _NEURITE_MAP.keys())):
        neurite_type = _NEURITE_MAP[neurite_type]
        feature = nm.get(feature_name, neurons, neurite_type=neurite_type)
        for mode in modes:
            stat_name = _stat_name(feature_name, mode)
            stat = eval_stats(feature, mode)
            _fill_stats_dict(stats[neurite_type.name], stat_name, stat)

    for feature_name, modes in config.get('neuron', {}).items():
        feature = nm.get(feature_name, neurons)
        for mode in modes:
            stat_name = _stat_name(feature_name, mode)
            stat = eval_stats(feature, mode)
            _fill_stats_dict(stats, stat_name, stat)

    return dict(stats)
 def f1_1(name,part='all'):
     if part=='all':
         cur_res = nm.get(name, neuron).mean()
         cur_key = 'mean_' + name
     elif part=='apical':
         cur_res = nm.get(name, neuron, neurite_type=nm.APICAL_DENDRITE).mean()
         cur_key = 'mean_' + name + '(apical)'
     elif part=='basal':
         cur_res = nm.get(name, neuron, neurite_type=nm.BASAL_DENDRITE).mean()
         cur_key = 'mean_' + name + '(basal)'
     yield (cur_key, cur_res)
Example #9
0
def test_section_radial_distances_endpoint():
    ref_sec_rad_dist = nf.section_radial_distances(NEURON)

    rad_dists = fst_get('section_radial_distances', NEURON)

    nt.eq_(len(rad_dists), 84)
    nt.ok_(np.all(rad_dists == ref_sec_rad_dist))

    nrns = [nm.load_neuron(os.path.join(SWC_PATH, f)) for
            f in ('point_soma_single_neurite.swc', 'point_soma_single_neurite2.swc')]
    pop = Population(nrns)
    rad_dist_nrns = [nm.get('section_radial_distances', nrn) for nrn in nrns]
    rad_dist_pop = nm.get('section_radial_distances', pop)
    assert_items_equal(rad_dist_pop, rad_dist_nrns)
Example #10
0
def test_section_radial_distances_endpoint():
    ref_sec_rad_dist = nf.section_radial_distances(NEURON)

    rad_dists = fst_get('section_radial_distances', NEURON)

    nt.eq_(len(rad_dists), 84)
    nt.ok_(np.all(rad_dists == ref_sec_rad_dist))

    nrns = [nm.load_neuron(os.path.join(SWC_PATH, f)) for
            f in ('point_soma_single_neurite.swc', 'point_soma_single_neurite2.swc')]
    pop = Population(nrns)
    rad_dist_nrns = [nm.get('section_radial_distances', nrn) for nrn in nrns]
    rad_dist_pop = nm.get('section_radial_distances', pop)
    assert_items_equal(rad_dist_pop, rad_dist_nrns)
def test_segment_radial_distances_displaced_neurite():
    nrns = [nm.load_neuron(os.path.join(SWC_PATH, f)) for
            f in ('point_soma_single_neurite.swc', 'point_soma_single_neurite2.swc')]

    pop = Population(nrns)

    rad_dist_nrns = []
    for nrn in nrns:
        rad_dist_nrns.extend( nm.get('segment_radial_distances', nrn))

    rad_dist_nrns = np.array(rad_dist_nrns)

    rad_dist_pop = nm.get('segment_radial_distances', pop)

    nt.ok_(np.alltrue(rad_dist_pop == rad_dist_nrns))
Example #12
0
def tree_asymmetry(neurite, neuron=None):
    '''
    Return the tree-assymetry of a neurite.

    Parameters
    ----------
    neurite : Neurite object or str
        Neurite to analyze.
    neuron : int, optional (default: None)
        GID of the neuron if the neurite was passed as a str and not as an
        object.
    '''
    try:
        import neurom as nm
    except ImportError:
        raise ImportError("This function requires the `neurom` package "
                          "to work, please install it through, e.g. "
                          "`pip install --user neurom`.")

    try:
        tree = neurite.get_tree().neurom_tree()
    except AttributeError:
        nrn = _pg.get_neurons(neuron)[0]
        tree = neurite.get_tree().neurom_tree()
    asyms = nm.get("partition_asymmetry", tree)
    return np.average(asyms) / _max_asym(len(neurite.get_tree().tips))
Example #13
0
def histogram(neuron, feature, ax, bins=15, normed=True, cumulative=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.

    Parameters :

        neurons : neuron list

        feature : str
        The feature of interest.

        bins : int
        Number of bins for the histogram.

        cumulative : bool
        Sets cumulative histogram on.

        ax : axes object
            the axes in which the plot is taking place
    '''

    feature_values = nm.get(feature, neuron)
    # generate histogram
    ax.hist(feature_values, bins=bins, cumulative=cumulative, normed=normed)
Example #14
0
def histogram(neuron, feature, ax, bins=15, normed=True, cumulative=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.

    Parameters :

        neurons : neuron list

        feature : str
        The feature of interest.

        bins : int
        Number of bins for the histogram.

        cumulative : bool
        Sets cumulative histogram on.

        ax : axes object
            the axes in which the plot is taking place
    '''

    feature_values = nm.get(feature, neuron)
    # generate histogram
    ax.hist(feature_values, bins=bins, cumulative=cumulative, normed=normed)
def create_recordings(cell):
    """Create the recordings"""
    my_neuron = nm.load_neuron('morphology/C230300D1_-_Clone_5.asc')
    num_axon_sec = len(
        nm.get('section_lengths', my_neuron, neurite_type=nm.AXON))
    print('Attaching recording electrodes')
    recordings = {}
    recordings['time'] = neuron.h.Vector()
    recordings['soma(0.5)'] = neuron.h.Vector()
    #recordings['axon35'] = neuron.h.Vector()
    #recordings['axon67'] = neuron.h.Vector()
    #recordings['axon124'] = neuron.h.Vector()
    #recordings['axon106'] = neuron.h.Vector()
    #d = {}
    for i in range(num_axon_sec):  # 171
        recordings["v_vect" + str(i)] = neuron.h.Vector()
    for i in range(num_axon_sec):  # 171
        recordings["v_vect" + str(i)].record(cell.axon[i](0.5)._ref_v, 0.025)
    recordings['time'].record(neuron.h._ref_t, 0.025)
    recordings['soma(0.5)'].record(cell.soma[0](0.5)._ref_v, 0.025)
    #recordings['axon35'].record(cell.axon[35](0.5)._ref_v, 0.025)
    #recordings['axon67'].record(cell.axon[67](0.5)._ref_v, 0.025)
    #recordings['axon124'].record(cell.axon[124](0.5)._ref_v, 0.1)
    #recordings['axon106'].record(cell.axon[106](0.5)._ref_v, 0.025)
    return recordings
Example #16
0
def test_section_radial_distances_endpoint():
    ref_sec_rad_dist = nf.section_radial_distances(NEURON)

    rad_dists = get_feature('section_radial_distances', NEURON)

    assert len(rad_dists) == 84
    assert np.all(rad_dists == ref_sec_rad_dist)

    nrns = [
        nm.load_neuron(Path(SWC_PATH, f))
        for f in ('point_soma_single_neurite.swc',
                  'point_soma_single_neurite2.swc')
    ]
    pop = Population(nrns)
    rad_dist_nrns = [nm.get('section_radial_distances', nrn) for nrn in nrns]
    rad_dist_pop = nm.get('section_radial_distances', pop)
    assert_items_equal(rad_dist_pop, rad_dist_nrns)
Example #17
0
def test_neuron_not_corrupted():
    # Regression for #492: dendrogram was corrupting
    # neuron used to construct it.
    # This caused the section path distance calculation
    # to raise a KeyError exception.
    neuron = load_neuron(NEURON_PATH)
    dm.Dendrogram(neuron)
    assert get('section_path_distances', neuron).size > 0
Example #18
0
def extract_stats(neurons, config):
    '''Extract stats from neurons'''

    stats = defaultdict(dict)
    for ns, modes in config['neurite'].iteritems():
        for n in config['neurite_type']:
            n = _NEURITE_MAP[n]
            for mode in modes:
                stat_name = _stat_name(ns, mode)
                stats[n.name][stat_name] = eval_stats(nm.get(ns, neurons, neurite_type=n), mode)
                L.debug('Stat: %s, Neurite: %s, Type: %s',
                        stat_name, n, type(stats[n.name][stat_name]))

    for ns, modes in config['neuron'].iteritems():
        for mode in modes:
            stat_name = _stat_name(ns, mode)
            stats[stat_name] = eval_stats(nm.get(ns, neurons), mode)

    return stats
Example #19
0
def load_neurite_features(filepath):
    """Unpack relevant data into megadict"""
    stuff = defaultdict(lambda: defaultdict(list))
    nrns = nm.load_neurons(filepath)
    # unpack data into arrays
    for nrn in nrns:
        for t in NEURITES_:
            for feat in FEATURES:
                stuff[feat][str(t).split(".")[1]].extend(nm.get(feat, nrn, neurite_type=t))
    return stuff
Example #20
0
def neuroMAnalysisForNeurons(fullState: FullState) -> pd.DataFrame:
    result = pd.DataFrame()
    neurons = [treeToNeuroM(fullState, tree) for tree in fullState.trees]

    result['paths'] = [os.path.basename(path) for path in fullState.filePaths]
    result['tdbl'] = [
        np.sum(
            nm.get('section_lengths', neuron, neurite_type=nm.BASAL_DENDRITE))
        for neuron in neurons
    ]
    return result
Example #21
0
def load_neurite_features(filepath):
    '''Unpack relevant data into megadict'''
    stuff = defaultdict(lambda: defaultdict(list))
    nrns = nm.load_neurons(filepath)
    # unpack data into arrays
    for nrn in nrns:
        for t in NEURITES_:
            for feat in FEATURES:
                stuff[feat][str(t).split('.')[1]].extend(
                    nm.get(feat, nrn, neurite_type=t))
    return stuff
def extract_data(data_path, feature):
    '''Loads a list of neurons, extracts feature
       and transforms the fitted distribution in the correct format.
       Returns the optimal distribution, corresponding parameters,
       minimun and maximum values.
    '''
    population = nm.load_neurons(data_path)

    feature_data = [nm.get(feature, n) for n in population]
    feature_data = list(chain(*feature_data))

    return stats.optimal_distribution(feature_data)
Example #23
0
def extract_data(data_path, feature):
    '''Loads a list of neurons, extracts feature
       and transforms the fitted distribution in the correct format.
       Returns the optimal distribution, corresponding parameters,
       minimun and maximum values.
    '''
    population = nm.load_neurons(data_path)

    feature_data = [nm.get(feature, n) for n in population]
    feature_data = list(chain(*feature_data))

    return stats.optimal_distribution(feature_data)
Example #24
0
def test_segment_radial_distances_origin():
    origin = (-100, -200, -300)
    ref_segs = nf.segment_radial_distances(NEURON)
    ref_segs_origin = nf.segment_radial_distances(NEURON, origin=origin)

    rad_dists = fst_get('segment_radial_distances', NEURON)
    rad_dists_origin = fst_get('segment_radial_distances', NEURON, origin=origin)

    nt.ok_(np.all(rad_dists == ref_segs))
    nt.ok_(np.all(rad_dists_origin == ref_segs_origin))
    nt.ok_(np.all(rad_dists_origin != ref_segs))

    nrns = [nm.load_neuron(os.path.join(SWC_PATH, f)) for
            f in ('point_soma_single_neurite.swc', 'point_soma_single_neurite2.swc')]
    pop = Population(nrns)
    rad_dist_nrns = []
    for nrn in nrns:
        rad_dist_nrns.extend(nm.get('segment_radial_distances', nrn))

    rad_dist_nrns = np.array(rad_dist_nrns)
    rad_dist_pop = nm.get('segment_radial_distances', pop)
    assert_allclose(rad_dist_nrns, rad_dist_pop)
Example #25
0
def test_load_neuron_mixed_tree_swc():
    nrn_mix =  utils.load_neuron(os.path.join(SWC_ORD_PATH, 'sample_mixed_tree_sections.swc'))
    nt.assert_items_equal(get('number_of_sections_per_neurite', nrn_mix), [5, 3])

    nt.assert_items_equal(get('number_of_sections_per_neurite', nrn_mix),
                          get('number_of_sections_per_neurite', SWC_ORD_REF))

    nt.assert_items_equal(get('number_of_segments', nrn_mix),
                          get('number_of_segments', SWC_ORD_REF))

    nt.assert_items_equal(get('total_length', nrn_mix),
                          get('total_length', SWC_ORD_REF))
Example #26
0
def test_load_neuron_mixed_tree_swc():
    nrn_mix = utils.load_neuron(os.path.join(SWC_ORD_PATH, 'sample_mixed_tree_sections.swc'))
    assert_items_equal(get('number_of_sections_per_neurite', nrn_mix), [5, 3])

    assert_items_equal(get('number_of_sections_per_neurite', nrn_mix),
                       get('number_of_sections_per_neurite', SWC_ORD_REF))

    assert_items_equal(get('number_of_segments', nrn_mix),
                       get('number_of_segments', SWC_ORD_REF))

    assert_items_equal(get('total_length', nrn_mix),
                       get('total_length', SWC_ORD_REF))
Example #27
0
def extract_data(neurons, feature, params=None):
    '''Extracts feature from a list of neurons
       and transforms the fitted distribution in the correct format.
       Returns the optimal distribution and corresponding parameters.
       Normal distribution params (mean, std)
       Exponential distribution params (loc, scale)
       Uniform distribution params (min, range)
    '''
    if params is None:
        params = {}

    feature_data = [get(FEATURE_MAP[feature], n, **params) for n in neurons]
    feature_data = list(chain(*feature_data))
    return stats.optimal_distribution(feature_data)
Example #28
0
def extract_data(neurons, feature, params=None):
    '''Extracts feature from a list of neurons
       and transforms the fitted distribution in the correct format.
       Returns the optimal distribution and corresponding parameters.
       Normal distribution params (mean, std)
       Exponential distribution params (loc, scale)
       Uniform distribution params (min, range)
    '''
    if params is None:
        params = {}

    feature_data = [get(FEATURE_MAP[feature], n, **params) for n in neurons]
    feature_data = list(chain(*feature_data))
    return stats.optimal_distribution(feature_data)
Example #29
0
def test_load_neuron_section_order_break_swc():
    nrn_mix =  utils.load_neuron(os.path.join(SWC_ORD_PATH, 'sample_disordered.swc'))

    assert_items_equal(get('number_of_sections_per_neurite', nrn_mix), [5, 3])

    assert_items_equal(get('number_of_sections_per_neurite', nrn_mix),
                       get('number_of_sections_per_neurite', SWC_ORD_REF))

    assert_items_equal(get('number_of_segments', nrn_mix),
                       get('number_of_segments', SWC_ORD_REF))

    assert_items_equal(get('total_length', nrn_mix),
                       get('total_length', SWC_ORD_REF))
Example #30
0
def test_load_neuron_section_order_break_swc():
    nrn_mix = utils.load_neuron(Path(SWC_ORD_PATH, 'sample_disordered.swc'))

    assert_items_equal(get('number_of_sections_per_neurite', nrn_mix), [5, 3])

    assert_items_equal(get('number_of_sections_per_neurite', nrn_mix),
                       get('number_of_sections_per_neurite', SWC_ORD_REF))

    assert_items_equal(get('number_of_segments', nrn_mix),
                       get('number_of_segments', SWC_ORD_REF))

    assert_items_equal(get('total_length', nrn_mix),
                       get('total_length', SWC_ORD_REF))
Example #31
0
def test_multiple_distr(filepath):
    '''Runs the distribution fit for multiple distributions and returns
       the optimal distribution along with the corresponding parameters.
    '''
    #  load a neuron from an SWC file
    population = nm.load_neurons(filepath)

    # Create a list of basic distributions
    distr_to_check = ('norm', 'expon', 'uniform')

    # Get the soma radii of a population of neurons
    soma_size = nm.get('soma_radii', population)

    # Find the best fit distribution
    return st.optimal_distribution(soma_size, distr_to_check)
Example #32
0
def test_multiple_distr(filepath):
    '''Runs the distribution fit for multiple distributions and returns
       the optimal distribution along with the corresponding parameters.
    '''
    #  load a neuron from an SWC file
    population = nm.load_neurons(filepath)

    # Create a list of basic distributions
    distr_to_check = ('norm', 'expon', 'uniform')

    # Get the soma radii of a population of neurons
    soma_size = nm.get('soma_radii', population)

    # Find the best fit distribution
    return st.optimal_distribution(soma_size, distr_to_check)
Example #33
0
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

'''Compatibility between NL and H5 files'''
# pylint: disable=protected-access

import numpy as np
import neurom as nm
from neurom.fst import _neuritefunc as _nf

nrn_h5 = nm.load_neuron('test_data/h5/v1/bio_neuron-001.h5')
nrn_asc = nm.load_neuron('test_data/neurolucida/bio_neuron-001.asc')

print 'h5 number of sections: %s' % nm.get('number_of_sections', nrn_h5)[0]
print 'nl number of sections: %s\n' % nm.get('number_of_sections', nrn_asc)[0]
print 'h5 number of segments: %s' % nm.get('number_of_segments', nrn_h5)[0]
print 'nl number of segments: %s\n' % nm.get('number_of_segments', nrn_asc)[0]
print 'h5 total neurite length: %s' % np.sum(nm.get('section_lengths', nrn_h5))
print 'nl total neurite length: %s\n' % np.sum(nm.get('section_lengths', nrn_asc))
print 'h5 principal direction extents: %s' % nm.get('principal_direction_extents', nrn_h5)
print 'nl principal direction extents: %s' % nm.get('principal_direction_extents', nrn_asc)

print '\nNumber of neurites:'
for nt in nm.NeuriteType:
    print nt, _nf.n_neurites(nrn_h5, neurite_type=nt),\
        _nf.n_neurites(nrn_asc, neurite_type=nt)

print '\nNumber of segments:'
for nt in nm.NeuriteType:
Example #34
0
 def time_segment_midpoints(self):
     nm.get('segment_midpoints', self.neuron)
Example #35
0
def pprint_stats(data):
    '''Pretty print summary stats for data'''
    pprint(stats(data))


if __name__ == '__main__':

    filename = 'test_data/swc/Neuron.swc'

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

    # Get some soma information
    # Soma radius and surface area
    print("Soma radius", nm.get('soma_radii', nrn)[0])
    print("Soma surface area", nm.get('soma_surface_areas', nrn)[0])

    # Get information about neurites
    # Most neurite data can be queried for a particular type of neurite.
    # The allowed types are members of the NeuriteType enumeration.
    # NEURITE_TYPES is a list of valid neurite types.

    # We start by calling methods for different neurite types separately
    # to warm up...

    # number of neurites
    print('Number of neurites (all):', nm.get('number_of_neurites', nrn)[0])
    print('Number of neurites (axons):',
          nm.get('number_of_neurites', nrn, neurite_type=nm.NeuriteType.axon)[0])
    print('Number of neurites (apical dendrites):',
Example #36
0
 def time_number_of_terminations(self):
     nm.get('number_of_terminations', self.neuron)
Example #37
0
 def time_number_of_bifurcations(self):
     nm.get('number_of_bifurcations', self.neuron)
Example #38
0
 def time_remote_bifurcation_angles(self):
     nm.get('remote_bifurcation_angles', self.neuron)
Example #39
0
 def time_segment_lengths(self):
     nm.get('segment_lengths', self.neuron)
Example #40
0
 def time_number_of_segments(self):
     nm.get('number_of_segments', self.neuron)
Example #41
0
 def time_segment_taper_rates(self):
     nm.get('segment_taper_rates', self.neuron)
Example #42
0
 def time_segment_midpoints(self):
     nm.get('segment_midpoints', self.neuron)
Example #43
0
 def time_segment_radii(self):
     nm.get('segment_radii', self.neuron)
Example #44
0
 def time_segment_lengths(self):
     nm.get('segment_lengths', self.neuron)
Example #45
0
 def time_number_of_segments(self):
     nm.get('number_of_segments', self.neuron)
Example #46
0
 def time_partition(self):
     nm.get('partition', self.neuron)
Example #47
0
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Compatibility between NL and H5 files."""
# pylint: disable=protected-access

import numpy as np

import neurom as nm
from neurom.features import neuritefunc as _nf

nrn_h5 = nm.load_neuron('tests/data/h5/v1/bio_neuron-001.h5')
nrn_asc = nm.load_neuron('tests/data/neurolucida/bio_neuron-001.asc')

print('h5 number of sections: %s' % nm.get('number_of_sections', nrn_h5)[0])
print('nl number of sections: %s\n' % nm.get('number_of_sections', nrn_asc)[0])
print('h5 number of segments: %s' % nm.get('number_of_segments', nrn_h5)[0])
print('nl number of segments: %s\n' % nm.get('number_of_segments', nrn_asc)[0])
print('h5 total neurite length: %s' %
      np.sum(nm.get('section_lengths', nrn_h5)))
print('nl total neurite length: %s\n' %
      np.sum(nm.get('section_lengths', nrn_asc)))
print('h5 principal direction extents: %s' %
      nm.get('principal_direction_extents', nrn_h5))
print('nl principal direction extents: %s' %
      nm.get('principal_direction_extents', nrn_asc))

print('\nNumber of neurites:')
for nt in iter(nm.NeuriteType):
    print(nt, _nf.n_neurites(nrn_h5, neurite_type=nt), _nf.n_neurites(nrn_asc, neurite_type=nt))
Example #48
0
 def time_segment_radii(self):
     nm.get('segment_radii', self.neuron)
Example #49
0
 def time_remote_bifurcation_angles(self):
     nm.get('remote_bifurcation_angles', self.neuron)
Example #50
0
 def time_section_radial_distances(self):
     nm.get('section_radial_distances', self.neuron)
Example #51
0
 def time_local_bifurcation_angles(self):
     nm.get('local_bifurcation_angles', self.neuron)
Example #52
0
 def time_partition(self):
     nm.get('partition', self.neuron)
Example #53
0
 def time_number_of_neurites(self):
     nm.get('number_of_neurites', self.neuron)
Example #54
0
 def time_number_of_sections_per_neurite(self):
     nm.get('number_of_sections_per_neurite', self.neuron)
Example #55
0
 def time_segment_taper_rates(self):
     nm.get('segment_taper_rates', self.neuron)
Example #56
0
def test_load_neuron_mixed_tree_h5():
    nrn_mix = utils.load_neuron(Path(H5_PATH, 'sample_mixed_tree_sections.h5'))
    assert_items_equal(get('number_of_sections_per_neurite', nrn_mix), [5, 3])
    assert_items_equal(get('number_of_sections_per_neurite', nrn_mix),
                       get('number_of_sections_per_neurite', H5_ORD_REF))
Example #57
0
 def test_neuron_not_corrupted(self):
     # Regression for #492: dendrogram was corrupting
     # neuron used to construct it.
     # This caused the section path distance calculation
     # to raise a KeyError exception.
     get('section_path_distances', NEURON)
Example #58
0
 def time_section_branch_orders(self):
     nm.get('section_branch_orders', self.neuron)
Example #59
0
 def time_number_of_forking_points(self):
     nm.get('number_of_forking_points', self.neuron)