id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
2,700 | BlueBrain/NeuroM | neurom/view/_dendrogram.py | _vertical_segment | def _vertical_segment(old_offs, new_offs, spacing, radii):
'''Vertices for a vertical rectangle
'''
return np.array(((new_offs[0] - radii[0], old_offs[1] + spacing[1]),
(new_offs[0] - radii[1], new_offs[1]),
(new_offs[0] + radii[1], new_offs[1]),
(new_offs[0] + radii[0], old_offs[1] + spacing[1]))) | python | def _vertical_segment(old_offs, new_offs, spacing, radii):
'''Vertices for a vertical rectangle
'''
return np.array(((new_offs[0] - radii[0], old_offs[1] + spacing[1]),
(new_offs[0] - radii[1], new_offs[1]),
(new_offs[0] + radii[1], new_offs[1]),
(new_offs[0] + radii[0], old_offs[1] + spacing[1]))) | [
"def",
"_vertical_segment",
"(",
"old_offs",
",",
"new_offs",
",",
"spacing",
",",
"radii",
")",
":",
"return",
"np",
".",
"array",
"(",
"(",
"(",
"new_offs",
"[",
"0",
"]",
"-",
"radii",
"[",
"0",
"]",
",",
"old_offs",
"[",
"1",
"]",
"+",
"spacing",
"[",
"1",
"]",
")",
",",
"(",
"new_offs",
"[",
"0",
"]",
"-",
"radii",
"[",
"1",
"]",
",",
"new_offs",
"[",
"1",
"]",
")",
",",
"(",
"new_offs",
"[",
"0",
"]",
"+",
"radii",
"[",
"1",
"]",
",",
"new_offs",
"[",
"1",
"]",
")",
",",
"(",
"new_offs",
"[",
"0",
"]",
"+",
"radii",
"[",
"0",
"]",
",",
"old_offs",
"[",
"1",
"]",
"+",
"spacing",
"[",
"1",
"]",
")",
")",
")"
] | Vertices for a vertical rectangle | [
"Vertices",
"for",
"a",
"vertical",
"rectangle"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/_dendrogram.py#L80-L86 |
2,701 | BlueBrain/NeuroM | neurom/view/_dendrogram.py | _horizontal_segment | def _horizontal_segment(old_offs, new_offs, spacing, diameter):
'''Vertices of a horizontal rectangle
'''
return np.array(((old_offs[0], old_offs[1] + spacing[1]),
(new_offs[0], old_offs[1] + spacing[1]),
(new_offs[0], old_offs[1] + spacing[1] - diameter),
(old_offs[0], old_offs[1] + spacing[1] - diameter))) | python | def _horizontal_segment(old_offs, new_offs, spacing, diameter):
'''Vertices of a horizontal rectangle
'''
return np.array(((old_offs[0], old_offs[1] + spacing[1]),
(new_offs[0], old_offs[1] + spacing[1]),
(new_offs[0], old_offs[1] + spacing[1] - diameter),
(old_offs[0], old_offs[1] + spacing[1] - diameter))) | [
"def",
"_horizontal_segment",
"(",
"old_offs",
",",
"new_offs",
",",
"spacing",
",",
"diameter",
")",
":",
"return",
"np",
".",
"array",
"(",
"(",
"(",
"old_offs",
"[",
"0",
"]",
",",
"old_offs",
"[",
"1",
"]",
"+",
"spacing",
"[",
"1",
"]",
")",
",",
"(",
"new_offs",
"[",
"0",
"]",
",",
"old_offs",
"[",
"1",
"]",
"+",
"spacing",
"[",
"1",
"]",
")",
",",
"(",
"new_offs",
"[",
"0",
"]",
",",
"old_offs",
"[",
"1",
"]",
"+",
"spacing",
"[",
"1",
"]",
"-",
"diameter",
")",
",",
"(",
"old_offs",
"[",
"0",
"]",
",",
"old_offs",
"[",
"1",
"]",
"+",
"spacing",
"[",
"1",
"]",
"-",
"diameter",
")",
")",
")"
] | Vertices of a horizontal rectangle | [
"Vertices",
"of",
"a",
"horizontal",
"rectangle"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/_dendrogram.py#L89-L95 |
2,702 | BlueBrain/NeuroM | neurom/view/_dendrogram.py | _spacingx | def _spacingx(node, max_dims, xoffset, xspace):
'''Determine the spacing of the current node depending on the number
of the leaves of the tree
'''
x_spacing = _n_terminations(node) * xspace
if x_spacing > max_dims[0]:
max_dims[0] = x_spacing
return xoffset - x_spacing / 2. | python | def _spacingx(node, max_dims, xoffset, xspace):
'''Determine the spacing of the current node depending on the number
of the leaves of the tree
'''
x_spacing = _n_terminations(node) * xspace
if x_spacing > max_dims[0]:
max_dims[0] = x_spacing
return xoffset - x_spacing / 2. | [
"def",
"_spacingx",
"(",
"node",
",",
"max_dims",
",",
"xoffset",
",",
"xspace",
")",
":",
"x_spacing",
"=",
"_n_terminations",
"(",
"node",
")",
"*",
"xspace",
"if",
"x_spacing",
">",
"max_dims",
"[",
"0",
"]",
":",
"max_dims",
"[",
"0",
"]",
"=",
"x_spacing",
"return",
"xoffset",
"-",
"x_spacing",
"/",
"2."
] | Determine the spacing of the current node depending on the number
of the leaves of the tree | [
"Determine",
"the",
"spacing",
"of",
"the",
"current",
"node",
"depending",
"on",
"the",
"number",
"of",
"the",
"leaves",
"of",
"the",
"tree"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/_dendrogram.py#L98-L107 |
2,703 | BlueBrain/NeuroM | neurom/view/_dendrogram.py | _update_offsets | def _update_offsets(start_x, spacing, terminations, offsets, length):
'''Update the offsets
'''
return (start_x + spacing[0] * terminations / 2.,
offsets[1] + spacing[1] * 2. + length) | python | def _update_offsets(start_x, spacing, terminations, offsets, length):
'''Update the offsets
'''
return (start_x + spacing[0] * terminations / 2.,
offsets[1] + spacing[1] * 2. + length) | [
"def",
"_update_offsets",
"(",
"start_x",
",",
"spacing",
",",
"terminations",
",",
"offsets",
",",
"length",
")",
":",
"return",
"(",
"start_x",
"+",
"spacing",
"[",
"0",
"]",
"*",
"terminations",
"/",
"2.",
",",
"offsets",
"[",
"1",
"]",
"+",
"spacing",
"[",
"1",
"]",
"*",
"2.",
"+",
"length",
")"
] | Update the offsets | [
"Update",
"the",
"offsets"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/_dendrogram.py#L110-L114 |
2,704 | BlueBrain/NeuroM | neurom/view/_dendrogram.py | _max_diameter | def _max_diameter(tree):
'''Find max diameter in tree
'''
return 2. * max(max(node.points[:, COLS.R]) for node in tree.ipreorder()) | python | def _max_diameter(tree):
'''Find max diameter in tree
'''
return 2. * max(max(node.points[:, COLS.R]) for node in tree.ipreorder()) | [
"def",
"_max_diameter",
"(",
"tree",
")",
":",
"return",
"2.",
"*",
"max",
"(",
"max",
"(",
"node",
".",
"points",
"[",
":",
",",
"COLS",
".",
"R",
"]",
")",
"for",
"node",
"in",
"tree",
".",
"ipreorder",
"(",
")",
")"
] | Find max diameter in tree | [
"Find",
"max",
"diameter",
"in",
"tree"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/_dendrogram.py#L117-L120 |
2,705 | BlueBrain/NeuroM | neurom/view/_dendrogram.py | Dendrogram._generate_dendro | def _generate_dendro(self, current_section, spacing, offsets):
'''Recursive function for dendrogram line computations
'''
max_dims = self._max_dims
start_x = _spacingx(current_section, max_dims, offsets[0], spacing[0])
for child in current_section.children:
segments = child.points
# number of leaves in child
terminations = _n_terminations(child)
# segement lengths
seg_lengths = np.linalg.norm(np.subtract(segments[:-1, COLS.XYZ],
segments[1:, COLS.XYZ]), axis=1)
# segment radii
radii = np.vstack((segments[:-1, COLS.R], segments[1:, COLS.R])).T \
if self._show_diameters else np.zeros((seg_lengths.shape[0], 2))
y_offset = offsets[1]
for i, slen in enumerate(seg_lengths):
# offset update for the vertical segments
new_offsets = _update_offsets(start_x, spacing, terminations,
(offsets[0], y_offset), slen)
# segments are drawn vertically, thus only y_offset changes from init offsets
self._rectangles[self._n] = _vertical_segment((offsets[0], y_offset),
new_offsets, spacing, radii[i, :])
self._n += 1
y_offset = new_offsets[1]
if y_offset + spacing[1] * 2 + sum(seg_lengths) > max_dims[1]:
max_dims[1] = y_offset + spacing[1] * 2. + sum(seg_lengths)
self._max_dims = max_dims
# recursive call to self.
self._generate_dendro(child, spacing, new_offsets)
# update the starting position for the next child
start_x += terminations * spacing[0]
# write the horizontal lines only for bifurcations, where the are actual horizontal
# lines and not zero ones
if offsets[0] != new_offsets[0]:
# horizontal segment. Thickness is either 0 if show_diameters is false
# or 1. if show_diameters is true
self._rectangles[self._n] = _horizontal_segment(offsets, new_offsets, spacing, 0.)
self._n += 1 | python | def _generate_dendro(self, current_section, spacing, offsets):
'''Recursive function for dendrogram line computations
'''
max_dims = self._max_dims
start_x = _spacingx(current_section, max_dims, offsets[0], spacing[0])
for child in current_section.children:
segments = child.points
# number of leaves in child
terminations = _n_terminations(child)
# segement lengths
seg_lengths = np.linalg.norm(np.subtract(segments[:-1, COLS.XYZ],
segments[1:, COLS.XYZ]), axis=1)
# segment radii
radii = np.vstack((segments[:-1, COLS.R], segments[1:, COLS.R])).T \
if self._show_diameters else np.zeros((seg_lengths.shape[0], 2))
y_offset = offsets[1]
for i, slen in enumerate(seg_lengths):
# offset update for the vertical segments
new_offsets = _update_offsets(start_x, spacing, terminations,
(offsets[0], y_offset), slen)
# segments are drawn vertically, thus only y_offset changes from init offsets
self._rectangles[self._n] = _vertical_segment((offsets[0], y_offset),
new_offsets, spacing, radii[i, :])
self._n += 1
y_offset = new_offsets[1]
if y_offset + spacing[1] * 2 + sum(seg_lengths) > max_dims[1]:
max_dims[1] = y_offset + spacing[1] * 2. + sum(seg_lengths)
self._max_dims = max_dims
# recursive call to self.
self._generate_dendro(child, spacing, new_offsets)
# update the starting position for the next child
start_x += terminations * spacing[0]
# write the horizontal lines only for bifurcations, where the are actual horizontal
# lines and not zero ones
if offsets[0] != new_offsets[0]:
# horizontal segment. Thickness is either 0 if show_diameters is false
# or 1. if show_diameters is true
self._rectangles[self._n] = _horizontal_segment(offsets, new_offsets, spacing, 0.)
self._n += 1 | [
"def",
"_generate_dendro",
"(",
"self",
",",
"current_section",
",",
"spacing",
",",
"offsets",
")",
":",
"max_dims",
"=",
"self",
".",
"_max_dims",
"start_x",
"=",
"_spacingx",
"(",
"current_section",
",",
"max_dims",
",",
"offsets",
"[",
"0",
"]",
",",
"spacing",
"[",
"0",
"]",
")",
"for",
"child",
"in",
"current_section",
".",
"children",
":",
"segments",
"=",
"child",
".",
"points",
"# number of leaves in child",
"terminations",
"=",
"_n_terminations",
"(",
"child",
")",
"# segement lengths",
"seg_lengths",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"np",
".",
"subtract",
"(",
"segments",
"[",
":",
"-",
"1",
",",
"COLS",
".",
"XYZ",
"]",
",",
"segments",
"[",
"1",
":",
",",
"COLS",
".",
"XYZ",
"]",
")",
",",
"axis",
"=",
"1",
")",
"# segment radii",
"radii",
"=",
"np",
".",
"vstack",
"(",
"(",
"segments",
"[",
":",
"-",
"1",
",",
"COLS",
".",
"R",
"]",
",",
"segments",
"[",
"1",
":",
",",
"COLS",
".",
"R",
"]",
")",
")",
".",
"T",
"if",
"self",
".",
"_show_diameters",
"else",
"np",
".",
"zeros",
"(",
"(",
"seg_lengths",
".",
"shape",
"[",
"0",
"]",
",",
"2",
")",
")",
"y_offset",
"=",
"offsets",
"[",
"1",
"]",
"for",
"i",
",",
"slen",
"in",
"enumerate",
"(",
"seg_lengths",
")",
":",
"# offset update for the vertical segments",
"new_offsets",
"=",
"_update_offsets",
"(",
"start_x",
",",
"spacing",
",",
"terminations",
",",
"(",
"offsets",
"[",
"0",
"]",
",",
"y_offset",
")",
",",
"slen",
")",
"# segments are drawn vertically, thus only y_offset changes from init offsets",
"self",
".",
"_rectangles",
"[",
"self",
".",
"_n",
"]",
"=",
"_vertical_segment",
"(",
"(",
"offsets",
"[",
"0",
"]",
",",
"y_offset",
")",
",",
"new_offsets",
",",
"spacing",
",",
"radii",
"[",
"i",
",",
":",
"]",
")",
"self",
".",
"_n",
"+=",
"1",
"y_offset",
"=",
"new_offsets",
"[",
"1",
"]",
"if",
"y_offset",
"+",
"spacing",
"[",
"1",
"]",
"*",
"2",
"+",
"sum",
"(",
"seg_lengths",
")",
">",
"max_dims",
"[",
"1",
"]",
":",
"max_dims",
"[",
"1",
"]",
"=",
"y_offset",
"+",
"spacing",
"[",
"1",
"]",
"*",
"2.",
"+",
"sum",
"(",
"seg_lengths",
")",
"self",
".",
"_max_dims",
"=",
"max_dims",
"# recursive call to self.",
"self",
".",
"_generate_dendro",
"(",
"child",
",",
"spacing",
",",
"new_offsets",
")",
"# update the starting position for the next child",
"start_x",
"+=",
"terminations",
"*",
"spacing",
"[",
"0",
"]",
"# write the horizontal lines only for bifurcations, where the are actual horizontal",
"# lines and not zero ones",
"if",
"offsets",
"[",
"0",
"]",
"!=",
"new_offsets",
"[",
"0",
"]",
":",
"# horizontal segment. Thickness is either 0 if show_diameters is false",
"# or 1. if show_diameters is true",
"self",
".",
"_rectangles",
"[",
"self",
".",
"_n",
"]",
"=",
"_horizontal_segment",
"(",
"offsets",
",",
"new_offsets",
",",
"spacing",
",",
"0.",
")",
"self",
".",
"_n",
"+=",
"1"
] | Recursive function for dendrogram line computations | [
"Recursive",
"function",
"for",
"dendrogram",
"line",
"computations"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/_dendrogram.py#L219-L270 |
2,706 | BlueBrain/NeuroM | neurom/view/_dendrogram.py | Dendrogram.types | def types(self):
''' Returns an iterator over the types of the neurites in the object.
If the object is a tree, then one value is returned.
'''
neurites = self._obj.neurites if hasattr(self._obj, 'neurites') else (self._obj,)
return (neu.type for neu in neurites) | python | def types(self):
''' Returns an iterator over the types of the neurites in the object.
If the object is a tree, then one value is returned.
'''
neurites = self._obj.neurites if hasattr(self._obj, 'neurites') else (self._obj,)
return (neu.type for neu in neurites) | [
"def",
"types",
"(",
"self",
")",
":",
"neurites",
"=",
"self",
".",
"_obj",
".",
"neurites",
"if",
"hasattr",
"(",
"self",
".",
"_obj",
",",
"'neurites'",
")",
"else",
"(",
"self",
".",
"_obj",
",",
")",
"return",
"(",
"neu",
".",
"type",
"for",
"neu",
"in",
"neurites",
")"
] | Returns an iterator over the types of the neurites in the object.
If the object is a tree, then one value is returned. | [
"Returns",
"an",
"iterator",
"over",
"the",
"types",
"of",
"the",
"neurites",
"in",
"the",
"object",
".",
"If",
"the",
"object",
"is",
"a",
"tree",
"then",
"one",
"value",
"is",
"returned",
"."
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/_dendrogram.py#L292-L297 |
2,707 | BlueBrain/NeuroM | neurom/fst/__init__.py | register_neurite_feature | def register_neurite_feature(name, func):
'''Register a feature to be applied to neurites
Parameters:
name: name of the feature, used for access via get() function.
func: single parameter function of a neurite.
'''
if name in NEURITEFEATURES:
raise NeuroMError('Attempt to hide registered feature %s' % name)
def _fun(neurites, neurite_type=_ntype.all):
'''Wrap neurite function from outer scope and map into list'''
return list(func(n) for n in _ineurites(neurites, filt=_is_type(neurite_type)))
NEURONFEATURES[name] = _fun | python | def register_neurite_feature(name, func):
'''Register a feature to be applied to neurites
Parameters:
name: name of the feature, used for access via get() function.
func: single parameter function of a neurite.
'''
if name in NEURITEFEATURES:
raise NeuroMError('Attempt to hide registered feature %s' % name)
def _fun(neurites, neurite_type=_ntype.all):
'''Wrap neurite function from outer scope and map into list'''
return list(func(n) for n in _ineurites(neurites, filt=_is_type(neurite_type)))
NEURONFEATURES[name] = _fun | [
"def",
"register_neurite_feature",
"(",
"name",
",",
"func",
")",
":",
"if",
"name",
"in",
"NEURITEFEATURES",
":",
"raise",
"NeuroMError",
"(",
"'Attempt to hide registered feature %s'",
"%",
"name",
")",
"def",
"_fun",
"(",
"neurites",
",",
"neurite_type",
"=",
"_ntype",
".",
"all",
")",
":",
"'''Wrap neurite function from outer scope and map into list'''",
"return",
"list",
"(",
"func",
"(",
"n",
")",
"for",
"n",
"in",
"_ineurites",
"(",
"neurites",
",",
"filt",
"=",
"_is_type",
"(",
"neurite_type",
")",
")",
")",
"NEURONFEATURES",
"[",
"name",
"]",
"=",
"_fun"
] | Register a feature to be applied to neurites
Parameters:
name: name of the feature, used for access via get() function.
func: single parameter function of a neurite. | [
"Register",
"a",
"feature",
"to",
"be",
"applied",
"to",
"neurites"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/__init__.py#L108-L122 |
2,708 | BlueBrain/NeuroM | neurom/fst/__init__.py | get | def get(feature, obj, **kwargs):
'''Obtain a feature from a set of morphology objects
Parameters:
feature(string): feature to extract
obj: a neuron, population or neurite tree
**kwargs: parameters to forward to underlying worker functions
Returns:
features as a 1D or 2D numpy array.
'''
feature = (NEURITEFEATURES[feature] if feature in NEURITEFEATURES
else NEURONFEATURES[feature])
return _np.array(list(feature(obj, **kwargs))) | python | def get(feature, obj, **kwargs):
'''Obtain a feature from a set of morphology objects
Parameters:
feature(string): feature to extract
obj: a neuron, population or neurite tree
**kwargs: parameters to forward to underlying worker functions
Returns:
features as a 1D or 2D numpy array.
'''
feature = (NEURITEFEATURES[feature] if feature in NEURITEFEATURES
else NEURONFEATURES[feature])
return _np.array(list(feature(obj, **kwargs))) | [
"def",
"get",
"(",
"feature",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"feature",
"=",
"(",
"NEURITEFEATURES",
"[",
"feature",
"]",
"if",
"feature",
"in",
"NEURITEFEATURES",
"else",
"NEURONFEATURES",
"[",
"feature",
"]",
")",
"return",
"_np",
".",
"array",
"(",
"list",
"(",
"feature",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
")",
")"
] | Obtain a feature from a set of morphology objects
Parameters:
feature(string): feature to extract
obj: a neuron, population or neurite tree
**kwargs: parameters to forward to underlying worker functions
Returns:
features as a 1D or 2D numpy array. | [
"Obtain",
"a",
"feature",
"from",
"a",
"set",
"of",
"morphology",
"objects"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/__init__.py#L125-L141 |
2,709 | BlueBrain/NeuroM | neurom/fst/__init__.py | _get_doc | def _get_doc():
'''Get a description of all the known available features'''
def get_docstring(func):
'''extract doctstring, if possible'''
docstring = ':\n'
if func.__doc__:
docstring += _indent(func.__doc__, 2)
return docstring
ret = ['\nNeurite features (neurite, neuron, neuron population):']
ret.extend(_INDENT + '- ' + feature + get_docstring(func)
for feature, func in sorted(NEURITEFEATURES.items()))
ret.append('\nNeuron features (neuron, neuron population):')
ret.extend(_INDENT + '- ' + feature + get_docstring(func)
for feature, func in sorted(NEURONFEATURES.items()))
return '\n'.join(ret) | python | def _get_doc():
'''Get a description of all the known available features'''
def get_docstring(func):
'''extract doctstring, if possible'''
docstring = ':\n'
if func.__doc__:
docstring += _indent(func.__doc__, 2)
return docstring
ret = ['\nNeurite features (neurite, neuron, neuron population):']
ret.extend(_INDENT + '- ' + feature + get_docstring(func)
for feature, func in sorted(NEURITEFEATURES.items()))
ret.append('\nNeuron features (neuron, neuron population):')
ret.extend(_INDENT + '- ' + feature + get_docstring(func)
for feature, func in sorted(NEURONFEATURES.items()))
return '\n'.join(ret) | [
"def",
"_get_doc",
"(",
")",
":",
"def",
"get_docstring",
"(",
"func",
")",
":",
"'''extract doctstring, if possible'''",
"docstring",
"=",
"':\\n'",
"if",
"func",
".",
"__doc__",
":",
"docstring",
"+=",
"_indent",
"(",
"func",
".",
"__doc__",
",",
"2",
")",
"return",
"docstring",
"ret",
"=",
"[",
"'\\nNeurite features (neurite, neuron, neuron population):'",
"]",
"ret",
".",
"extend",
"(",
"_INDENT",
"+",
"'- '",
"+",
"feature",
"+",
"get_docstring",
"(",
"func",
")",
"for",
"feature",
",",
"func",
"in",
"sorted",
"(",
"NEURITEFEATURES",
".",
"items",
"(",
")",
")",
")",
"ret",
".",
"append",
"(",
"'\\nNeuron features (neuron, neuron population):'",
")",
"ret",
".",
"extend",
"(",
"_INDENT",
"+",
"'- '",
"+",
"feature",
"+",
"get_docstring",
"(",
"func",
")",
"for",
"feature",
",",
"func",
"in",
"sorted",
"(",
"NEURONFEATURES",
".",
"items",
"(",
")",
")",
")",
"return",
"'\\n'",
".",
"join",
"(",
"ret",
")"
] | Get a description of all the known available features | [
"Get",
"a",
"description",
"of",
"all",
"the",
"known",
"available",
"features"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/__init__.py#L154-L171 |
2,710 | BlueBrain/NeuroM | neurom/io/hdf5.py | read | def read(filename, remove_duplicates=False, data_wrapper=DataWrapper):
'''Read a file and return a `data_wrapper'd` data
* Tries to guess the format and the H5 version.
* Unpacks the first block it finds out of ('repaired', 'unraveled', 'raw')
Parameters:
remove_duplicates: boolean, If True removes duplicate points
from the beginning of each section.
'''
with h5py.File(filename, mode='r') as h5file:
version = get_version(h5file)
if version == 'H5V1':
points, groups = _unpack_v1(h5file)
elif version == 'H5V2':
stg = next(s for s in ('repaired', 'unraveled', 'raw')
if s in h5file['neuron1'])
points, groups = _unpack_v2(h5file, stage=stg)
if remove_duplicates:
points, groups = _remove_duplicate_points(points, groups)
neuron_builder = BlockNeuronBuilder()
points[:, POINT_DIAMETER] /= 2 # Store radius, not diameter
for id_, row in enumerate(zip_longest(groups,
groups[1:, GPFIRST],
fillvalue=len(points))):
(point_start, section_type, parent_id), point_end = row
neuron_builder.add_section(id_, int(parent_id), int(section_type),
points[point_start:point_end])
return neuron_builder.get_datawrapper(version, data_wrapper=data_wrapper) | python | def read(filename, remove_duplicates=False, data_wrapper=DataWrapper):
'''Read a file and return a `data_wrapper'd` data
* Tries to guess the format and the H5 version.
* Unpacks the first block it finds out of ('repaired', 'unraveled', 'raw')
Parameters:
remove_duplicates: boolean, If True removes duplicate points
from the beginning of each section.
'''
with h5py.File(filename, mode='r') as h5file:
version = get_version(h5file)
if version == 'H5V1':
points, groups = _unpack_v1(h5file)
elif version == 'H5V2':
stg = next(s for s in ('repaired', 'unraveled', 'raw')
if s in h5file['neuron1'])
points, groups = _unpack_v2(h5file, stage=stg)
if remove_duplicates:
points, groups = _remove_duplicate_points(points, groups)
neuron_builder = BlockNeuronBuilder()
points[:, POINT_DIAMETER] /= 2 # Store radius, not diameter
for id_, row in enumerate(zip_longest(groups,
groups[1:, GPFIRST],
fillvalue=len(points))):
(point_start, section_type, parent_id), point_end = row
neuron_builder.add_section(id_, int(parent_id), int(section_type),
points[point_start:point_end])
return neuron_builder.get_datawrapper(version, data_wrapper=data_wrapper) | [
"def",
"read",
"(",
"filename",
",",
"remove_duplicates",
"=",
"False",
",",
"data_wrapper",
"=",
"DataWrapper",
")",
":",
"with",
"h5py",
".",
"File",
"(",
"filename",
",",
"mode",
"=",
"'r'",
")",
"as",
"h5file",
":",
"version",
"=",
"get_version",
"(",
"h5file",
")",
"if",
"version",
"==",
"'H5V1'",
":",
"points",
",",
"groups",
"=",
"_unpack_v1",
"(",
"h5file",
")",
"elif",
"version",
"==",
"'H5V2'",
":",
"stg",
"=",
"next",
"(",
"s",
"for",
"s",
"in",
"(",
"'repaired'",
",",
"'unraveled'",
",",
"'raw'",
")",
"if",
"s",
"in",
"h5file",
"[",
"'neuron1'",
"]",
")",
"points",
",",
"groups",
"=",
"_unpack_v2",
"(",
"h5file",
",",
"stage",
"=",
"stg",
")",
"if",
"remove_duplicates",
":",
"points",
",",
"groups",
"=",
"_remove_duplicate_points",
"(",
"points",
",",
"groups",
")",
"neuron_builder",
"=",
"BlockNeuronBuilder",
"(",
")",
"points",
"[",
":",
",",
"POINT_DIAMETER",
"]",
"/=",
"2",
"# Store radius, not diameter",
"for",
"id_",
",",
"row",
"in",
"enumerate",
"(",
"zip_longest",
"(",
"groups",
",",
"groups",
"[",
"1",
":",
",",
"GPFIRST",
"]",
",",
"fillvalue",
"=",
"len",
"(",
"points",
")",
")",
")",
":",
"(",
"point_start",
",",
"section_type",
",",
"parent_id",
")",
",",
"point_end",
"=",
"row",
"neuron_builder",
".",
"add_section",
"(",
"id_",
",",
"int",
"(",
"parent_id",
")",
",",
"int",
"(",
"section_type",
")",
",",
"points",
"[",
"point_start",
":",
"point_end",
"]",
")",
"return",
"neuron_builder",
".",
"get_datawrapper",
"(",
"version",
",",
"data_wrapper",
"=",
"data_wrapper",
")"
] | Read a file and return a `data_wrapper'd` data
* Tries to guess the format and the H5 version.
* Unpacks the first block it finds out of ('repaired', 'unraveled', 'raw')
Parameters:
remove_duplicates: boolean, If True removes duplicate points
from the beginning of each section. | [
"Read",
"a",
"file",
"and",
"return",
"a",
"data_wrapper",
"d",
"data"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/hdf5.py#L67-L98 |
2,711 | BlueBrain/NeuroM | neurom/io/hdf5.py | _remove_duplicate_points | def _remove_duplicate_points(points, groups):
''' Removes the duplicate points from the beginning of a section,
if they are present in points-groups representation.
Returns:
points, groups with unique points.
'''
group_initial_ids = groups[:, GPFIRST]
to_be_reduced = np.zeros(len(group_initial_ids))
to_be_removed = []
for ig, g in enumerate(groups):
iid, typ, pid = g[GPFIRST], g[GTYPE], g[GPID]
# Remove first point from sections that are
# not the root section, a soma, or a child of a soma
if pid != -1 and typ != 1 and groups[pid][GTYPE] != 1:
# Remove duplicate from list of points
to_be_removed.append(iid)
# Reduce the id of the following sections
# in groups structure by one
to_be_reduced[ig + 1:] += 1
groups[:, GPFIRST] = groups[:, GPFIRST] - to_be_reduced
points = np.delete(points, to_be_removed, axis=0)
return points, groups | python | def _remove_duplicate_points(points, groups):
''' Removes the duplicate points from the beginning of a section,
if they are present in points-groups representation.
Returns:
points, groups with unique points.
'''
group_initial_ids = groups[:, GPFIRST]
to_be_reduced = np.zeros(len(group_initial_ids))
to_be_removed = []
for ig, g in enumerate(groups):
iid, typ, pid = g[GPFIRST], g[GTYPE], g[GPID]
# Remove first point from sections that are
# not the root section, a soma, or a child of a soma
if pid != -1 and typ != 1 and groups[pid][GTYPE] != 1:
# Remove duplicate from list of points
to_be_removed.append(iid)
# Reduce the id of the following sections
# in groups structure by one
to_be_reduced[ig + 1:] += 1
groups[:, GPFIRST] = groups[:, GPFIRST] - to_be_reduced
points = np.delete(points, to_be_removed, axis=0)
return points, groups | [
"def",
"_remove_duplicate_points",
"(",
"points",
",",
"groups",
")",
":",
"group_initial_ids",
"=",
"groups",
"[",
":",
",",
"GPFIRST",
"]",
"to_be_reduced",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"group_initial_ids",
")",
")",
"to_be_removed",
"=",
"[",
"]",
"for",
"ig",
",",
"g",
"in",
"enumerate",
"(",
"groups",
")",
":",
"iid",
",",
"typ",
",",
"pid",
"=",
"g",
"[",
"GPFIRST",
"]",
",",
"g",
"[",
"GTYPE",
"]",
",",
"g",
"[",
"GPID",
"]",
"# Remove first point from sections that are",
"# not the root section, a soma, or a child of a soma",
"if",
"pid",
"!=",
"-",
"1",
"and",
"typ",
"!=",
"1",
"and",
"groups",
"[",
"pid",
"]",
"[",
"GTYPE",
"]",
"!=",
"1",
":",
"# Remove duplicate from list of points",
"to_be_removed",
".",
"append",
"(",
"iid",
")",
"# Reduce the id of the following sections",
"# in groups structure by one",
"to_be_reduced",
"[",
"ig",
"+",
"1",
":",
"]",
"+=",
"1",
"groups",
"[",
":",
",",
"GPFIRST",
"]",
"=",
"groups",
"[",
":",
",",
"GPFIRST",
"]",
"-",
"to_be_reduced",
"points",
"=",
"np",
".",
"delete",
"(",
"points",
",",
"to_be_removed",
",",
"axis",
"=",
"0",
")",
"return",
"points",
",",
"groups"
] | Removes the duplicate points from the beginning of a section,
if they are present in points-groups representation.
Returns:
points, groups with unique points. | [
"Removes",
"the",
"duplicate",
"points",
"from",
"the",
"beginning",
"of",
"a",
"section",
"if",
"they",
"are",
"present",
"in",
"points",
"-",
"groups",
"representation",
"."
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/hdf5.py#L101-L129 |
2,712 | BlueBrain/NeuroM | neurom/io/hdf5.py | _unpack_v1 | def _unpack_v1(h5file):
'''Unpack groups from HDF5 v1 file'''
points = np.array(h5file['points'])
groups = np.array(h5file['structure'])
return points, groups | python | def _unpack_v1(h5file):
'''Unpack groups from HDF5 v1 file'''
points = np.array(h5file['points'])
groups = np.array(h5file['structure'])
return points, groups | [
"def",
"_unpack_v1",
"(",
"h5file",
")",
":",
"points",
"=",
"np",
".",
"array",
"(",
"h5file",
"[",
"'points'",
"]",
")",
"groups",
"=",
"np",
".",
"array",
"(",
"h5file",
"[",
"'structure'",
"]",
")",
"return",
"points",
",",
"groups"
] | Unpack groups from HDF5 v1 file | [
"Unpack",
"groups",
"from",
"HDF5",
"v1",
"file"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/hdf5.py#L132-L136 |
2,713 | BlueBrain/NeuroM | neurom/io/hdf5.py | _unpack_v2 | def _unpack_v2(h5file, stage):
'''Unpack groups from HDF5 v2 file'''
points = np.array(h5file['neuron1/%s/points' % stage])
# from documentation: The /neuron1/structure/unraveled reuses /neuron1/structure/raw
groups_stage = stage if stage != 'unraveled' else 'raw'
groups = np.array(h5file['neuron1/structure/%s' % groups_stage])
stypes = np.array(h5file['neuron1/structure/sectiontype'])
groups = np.hstack([groups, stypes])
groups[:, [1, 2]] = groups[:, [2, 1]]
return points, groups | python | def _unpack_v2(h5file, stage):
'''Unpack groups from HDF5 v2 file'''
points = np.array(h5file['neuron1/%s/points' % stage])
# from documentation: The /neuron1/structure/unraveled reuses /neuron1/structure/raw
groups_stage = stage if stage != 'unraveled' else 'raw'
groups = np.array(h5file['neuron1/structure/%s' % groups_stage])
stypes = np.array(h5file['neuron1/structure/sectiontype'])
groups = np.hstack([groups, stypes])
groups[:, [1, 2]] = groups[:, [2, 1]]
return points, groups | [
"def",
"_unpack_v2",
"(",
"h5file",
",",
"stage",
")",
":",
"points",
"=",
"np",
".",
"array",
"(",
"h5file",
"[",
"'neuron1/%s/points'",
"%",
"stage",
"]",
")",
"# from documentation: The /neuron1/structure/unraveled reuses /neuron1/structure/raw",
"groups_stage",
"=",
"stage",
"if",
"stage",
"!=",
"'unraveled'",
"else",
"'raw'",
"groups",
"=",
"np",
".",
"array",
"(",
"h5file",
"[",
"'neuron1/structure/%s'",
"%",
"groups_stage",
"]",
")",
"stypes",
"=",
"np",
".",
"array",
"(",
"h5file",
"[",
"'neuron1/structure/sectiontype'",
"]",
")",
"groups",
"=",
"np",
".",
"hstack",
"(",
"[",
"groups",
",",
"stypes",
"]",
")",
"groups",
"[",
":",
",",
"[",
"1",
",",
"2",
"]",
"]",
"=",
"groups",
"[",
":",
",",
"[",
"2",
",",
"1",
"]",
"]",
"return",
"points",
",",
"groups"
] | Unpack groups from HDF5 v2 file | [
"Unpack",
"groups",
"from",
"HDF5",
"v2",
"file"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/hdf5.py#L139-L148 |
2,714 | BlueBrain/NeuroM | neurom/stats.py | fit_results_to_dict | def fit_results_to_dict(fit_results, min_bound=None, max_bound=None):
'''Create a JSON-comparable dict from a FitResults object
Parameters:
fit_results (FitResults): object containing fit parameters,\
errors and type
min_bound: optional min value to add to dictionary if min isn't\
a fit parameter.
max_bound: optional max value to add to dictionary if max isn't\
a fit parameter.
Returns:
JSON-compatible dictionary with fit results
Note:
Supported fit types: 'norm', 'expon', 'uniform'
'''
type_map = {'norm': 'normal', 'expon': 'exponential', 'uniform': 'uniform'}
param_map = {'uniform': lambda p: [('min', p[0]), ('max', p[0] + p[1])],
'norm': lambda p: [('mu', p[0]), ('sigma', p[1])],
'expon': lambda p: [('lambda', 1.0 / p[1])]}
d = OrderedDict({'type': type_map[fit_results.type]})
d.update(param_map[fit_results.type](fit_results.params))
if min_bound is not None and 'min' not in d:
d['min'] = min_bound
if max_bound is not None and 'max' not in d:
d['max'] = max_bound
return d | python | def fit_results_to_dict(fit_results, min_bound=None, max_bound=None):
'''Create a JSON-comparable dict from a FitResults object
Parameters:
fit_results (FitResults): object containing fit parameters,\
errors and type
min_bound: optional min value to add to dictionary if min isn't\
a fit parameter.
max_bound: optional max value to add to dictionary if max isn't\
a fit parameter.
Returns:
JSON-compatible dictionary with fit results
Note:
Supported fit types: 'norm', 'expon', 'uniform'
'''
type_map = {'norm': 'normal', 'expon': 'exponential', 'uniform': 'uniform'}
param_map = {'uniform': lambda p: [('min', p[0]), ('max', p[0] + p[1])],
'norm': lambda p: [('mu', p[0]), ('sigma', p[1])],
'expon': lambda p: [('lambda', 1.0 / p[1])]}
d = OrderedDict({'type': type_map[fit_results.type]})
d.update(param_map[fit_results.type](fit_results.params))
if min_bound is not None and 'min' not in d:
d['min'] = min_bound
if max_bound is not None and 'max' not in d:
d['max'] = max_bound
return d | [
"def",
"fit_results_to_dict",
"(",
"fit_results",
",",
"min_bound",
"=",
"None",
",",
"max_bound",
"=",
"None",
")",
":",
"type_map",
"=",
"{",
"'norm'",
":",
"'normal'",
",",
"'expon'",
":",
"'exponential'",
",",
"'uniform'",
":",
"'uniform'",
"}",
"param_map",
"=",
"{",
"'uniform'",
":",
"lambda",
"p",
":",
"[",
"(",
"'min'",
",",
"p",
"[",
"0",
"]",
")",
",",
"(",
"'max'",
",",
"p",
"[",
"0",
"]",
"+",
"p",
"[",
"1",
"]",
")",
"]",
",",
"'norm'",
":",
"lambda",
"p",
":",
"[",
"(",
"'mu'",
",",
"p",
"[",
"0",
"]",
")",
",",
"(",
"'sigma'",
",",
"p",
"[",
"1",
"]",
")",
"]",
",",
"'expon'",
":",
"lambda",
"p",
":",
"[",
"(",
"'lambda'",
",",
"1.0",
"/",
"p",
"[",
"1",
"]",
")",
"]",
"}",
"d",
"=",
"OrderedDict",
"(",
"{",
"'type'",
":",
"type_map",
"[",
"fit_results",
".",
"type",
"]",
"}",
")",
"d",
".",
"update",
"(",
"param_map",
"[",
"fit_results",
".",
"type",
"]",
"(",
"fit_results",
".",
"params",
")",
")",
"if",
"min_bound",
"is",
"not",
"None",
"and",
"'min'",
"not",
"in",
"d",
":",
"d",
"[",
"'min'",
"]",
"=",
"min_bound",
"if",
"max_bound",
"is",
"not",
"None",
"and",
"'max'",
"not",
"in",
"d",
":",
"d",
"[",
"'max'",
"]",
"=",
"max_bound",
"return",
"d"
] | Create a JSON-comparable dict from a FitResults object
Parameters:
fit_results (FitResults): object containing fit parameters,\
errors and type
min_bound: optional min value to add to dictionary if min isn't\
a fit parameter.
max_bound: optional max value to add to dictionary if max isn't\
a fit parameter.
Returns:
JSON-compatible dictionary with fit results
Note:
Supported fit types: 'norm', 'expon', 'uniform' | [
"Create",
"a",
"JSON",
"-",
"comparable",
"dict",
"from",
"a",
"FitResults",
"object"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/stats.py#L60-L91 |
2,715 | BlueBrain/NeuroM | neurom/stats.py | fit | def fit(data, distribution='norm'):
'''Calculate the parameters of a fit of a distribution to a data set
Parameters:
data: array of data points to be fitted
Options:
distribution (str): type of distribution to fit. Default 'norm'.
Returns:
FitResults object with fitted parameters, errors and distribution type
Note:
Uses Kolmogorov-Smirnov test to estimate distance and p-value.
'''
params = getattr(_st, distribution).fit(data)
return FitResults(params, _st.kstest(data, distribution, params), distribution) | python | def fit(data, distribution='norm'):
'''Calculate the parameters of a fit of a distribution to a data set
Parameters:
data: array of data points to be fitted
Options:
distribution (str): type of distribution to fit. Default 'norm'.
Returns:
FitResults object with fitted parameters, errors and distribution type
Note:
Uses Kolmogorov-Smirnov test to estimate distance and p-value.
'''
params = getattr(_st, distribution).fit(data)
return FitResults(params, _st.kstest(data, distribution, params), distribution) | [
"def",
"fit",
"(",
"data",
",",
"distribution",
"=",
"'norm'",
")",
":",
"params",
"=",
"getattr",
"(",
"_st",
",",
"distribution",
")",
".",
"fit",
"(",
"data",
")",
"return",
"FitResults",
"(",
"params",
",",
"_st",
".",
"kstest",
"(",
"data",
",",
"distribution",
",",
"params",
")",
",",
"distribution",
")"
] | Calculate the parameters of a fit of a distribution to a data set
Parameters:
data: array of data points to be fitted
Options:
distribution (str): type of distribution to fit. Default 'norm'.
Returns:
FitResults object with fitted parameters, errors and distribution type
Note:
Uses Kolmogorov-Smirnov test to estimate distance and p-value. | [
"Calculate",
"the",
"parameters",
"of",
"a",
"fit",
"of",
"a",
"distribution",
"to",
"a",
"data",
"set"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/stats.py#L94-L110 |
2,716 | BlueBrain/NeuroM | neurom/stats.py | optimal_distribution | def optimal_distribution(data, distr_to_check=('norm', 'expon', 'uniform')):
'''Calculate the parameters of a fit of different distributions to a data set
and returns the distribution of the minimal ks-distance.
Parameters:
data: array of data points to be fitted
Options:
distr_to_check: tuple of distributions to be checked
Returns:
FitResults object with fitted parameters, errors and distribution type\
of the fit with the smallest fit distance
Note:
Uses Kolmogorov-Smirnov test to estimate distance and p-value.
'''
fit_results = [fit(data, d) for d in distr_to_check]
return min(fit_results, key=lambda fit: fit.errs[0]) | python | def optimal_distribution(data, distr_to_check=('norm', 'expon', 'uniform')):
'''Calculate the parameters of a fit of different distributions to a data set
and returns the distribution of the minimal ks-distance.
Parameters:
data: array of data points to be fitted
Options:
distr_to_check: tuple of distributions to be checked
Returns:
FitResults object with fitted parameters, errors and distribution type\
of the fit with the smallest fit distance
Note:
Uses Kolmogorov-Smirnov test to estimate distance and p-value.
'''
fit_results = [fit(data, d) for d in distr_to_check]
return min(fit_results, key=lambda fit: fit.errs[0]) | [
"def",
"optimal_distribution",
"(",
"data",
",",
"distr_to_check",
"=",
"(",
"'norm'",
",",
"'expon'",
",",
"'uniform'",
")",
")",
":",
"fit_results",
"=",
"[",
"fit",
"(",
"data",
",",
"d",
")",
"for",
"d",
"in",
"distr_to_check",
"]",
"return",
"min",
"(",
"fit_results",
",",
"key",
"=",
"lambda",
"fit",
":",
"fit",
".",
"errs",
"[",
"0",
"]",
")"
] | Calculate the parameters of a fit of different distributions to a data set
and returns the distribution of the minimal ks-distance.
Parameters:
data: array of data points to be fitted
Options:
distr_to_check: tuple of distributions to be checked
Returns:
FitResults object with fitted parameters, errors and distribution type\
of the fit with the smallest fit distance
Note:
Uses Kolmogorov-Smirnov test to estimate distance and p-value. | [
"Calculate",
"the",
"parameters",
"of",
"a",
"fit",
"of",
"different",
"distributions",
"to",
"a",
"data",
"set",
"and",
"returns",
"the",
"distribution",
"of",
"the",
"minimal",
"ks",
"-",
"distance",
"."
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/stats.py#L113-L131 |
2,717 | BlueBrain/NeuroM | neurom/stats.py | scalar_stats | def scalar_stats(data, functions=('min', 'max', 'mean', 'std')):
'''Calculate the stats from the given numpy functions
Parameters:
data: array of data points to be used for the stats
Options:
functions: tuple of numpy stat functions to apply on data
Returns:
Dictionary with the name of the function as key and the result
as the respective value
'''
stats = {}
for func in functions:
stats[func] = getattr(np, func)(data)
return stats | python | def scalar_stats(data, functions=('min', 'max', 'mean', 'std')):
'''Calculate the stats from the given numpy functions
Parameters:
data: array of data points to be used for the stats
Options:
functions: tuple of numpy stat functions to apply on data
Returns:
Dictionary with the name of the function as key and the result
as the respective value
'''
stats = {}
for func in functions:
stats[func] = getattr(np, func)(data)
return stats | [
"def",
"scalar_stats",
"(",
"data",
",",
"functions",
"=",
"(",
"'min'",
",",
"'max'",
",",
"'mean'",
",",
"'std'",
")",
")",
":",
"stats",
"=",
"{",
"}",
"for",
"func",
"in",
"functions",
":",
"stats",
"[",
"func",
"]",
"=",
"getattr",
"(",
"np",
",",
"func",
")",
"(",
"data",
")",
"return",
"stats"
] | Calculate the stats from the given numpy functions
Parameters:
data: array of data points to be used for the stats
Options:
functions: tuple of numpy stat functions to apply on data
Returns:
Dictionary with the name of the function as key and the result
as the respective value | [
"Calculate",
"the",
"stats",
"from",
"the",
"given",
"numpy",
"functions"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/stats.py#L134-L152 |
2,718 | BlueBrain/NeuroM | neurom/stats.py | total_score | def total_score(paired_dats, p=2, test=StatTests.ks):
'''Calculates the p-norm of the distances that have been calculated from the statistical
test that has been applied on all the paired datasets.
Parameters:
paired_dats: a list of tuples or where each tuple
contains the paired data lists from two datasets
Options:
p : integer that defines the order of p-norm
test: Stat_tests\
Defines the statistical test to be used, based\
on the scipy available modules.\
Accepted tests: ks_2samp, wilcoxon, ttest
Returns:
A float corresponding to the p-norm of the distances that have
been calculated. 0 corresponds to high similarity while 1 to low.
'''
scores = np.array([compare_two(fL1, fL2, test=test).dist for fL1, fL2 in paired_dats])
return np.linalg.norm(scores, p) | python | def total_score(paired_dats, p=2, test=StatTests.ks):
'''Calculates the p-norm of the distances that have been calculated from the statistical
test that has been applied on all the paired datasets.
Parameters:
paired_dats: a list of tuples or where each tuple
contains the paired data lists from two datasets
Options:
p : integer that defines the order of p-norm
test: Stat_tests\
Defines the statistical test to be used, based\
on the scipy available modules.\
Accepted tests: ks_2samp, wilcoxon, ttest
Returns:
A float corresponding to the p-norm of the distances that have
been calculated. 0 corresponds to high similarity while 1 to low.
'''
scores = np.array([compare_two(fL1, fL2, test=test).dist for fL1, fL2 in paired_dats])
return np.linalg.norm(scores, p) | [
"def",
"total_score",
"(",
"paired_dats",
",",
"p",
"=",
"2",
",",
"test",
"=",
"StatTests",
".",
"ks",
")",
":",
"scores",
"=",
"np",
".",
"array",
"(",
"[",
"compare_two",
"(",
"fL1",
",",
"fL2",
",",
"test",
"=",
"test",
")",
".",
"dist",
"for",
"fL1",
",",
"fL2",
"in",
"paired_dats",
"]",
")",
"return",
"np",
".",
"linalg",
".",
"norm",
"(",
"scores",
",",
"p",
")"
] | Calculates the p-norm of the distances that have been calculated from the statistical
test that has been applied on all the paired datasets.
Parameters:
paired_dats: a list of tuples or where each tuple
contains the paired data lists from two datasets
Options:
p : integer that defines the order of p-norm
test: Stat_tests\
Defines the statistical test to be used, based\
on the scipy available modules.\
Accepted tests: ks_2samp, wilcoxon, ttest
Returns:
A float corresponding to the p-norm of the distances that have
been calculated. 0 corresponds to high similarity while 1 to low. | [
"Calculates",
"the",
"p",
"-",
"norm",
"of",
"the",
"distances",
"that",
"have",
"been",
"calculated",
"from",
"the",
"statistical",
"test",
"that",
"has",
"been",
"applied",
"on",
"all",
"the",
"paired",
"datasets",
"."
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/stats.py#L182-L202 |
2,719 | BlueBrain/NeuroM | neurom/core/_neuron.py | iter_neurites | def iter_neurites(obj, mapfun=None, filt=None, neurite_order=NeuriteIter.FileOrder):
'''Iterator to a neurite, neuron or neuron population
Applies optional neurite filter and mapping functions.
Parameters:
obj: a neurite, neuron or neuron population.
mapfun: optional neurite mapping function.
filt: optional neurite filter function.
neurite_order (NeuriteIter): order upon which neurites should be iterated
- NeuriteIter.FileOrder: order of appearance in the file
- NeuriteIter.NRN: NRN simulator order: soma -> axon -> basal -> apical
Examples:
Get the number of points in each neurite in a neuron population
>>> from neurom.core import iter_neurites
>>> n_points = [n for n in iter_neurites(pop, lambda x : len(x.points))]
Get the number of points in each axon in a neuron population
>>> import neurom as nm
>>> from neurom.core import iter_neurites
>>> filter = lambda n : n.type == nm.AXON
>>> mapping = lambda n : len(n.points)
>>> n_points = [n for n in iter_neurites(pop, mapping, filter)]
'''
neurites = ((obj,) if isinstance(obj, Neurite) else
obj.neurites if hasattr(obj, 'neurites') else obj)
if neurite_order == NeuriteIter.NRN:
last_position = max(NRN_ORDER.values()) + 1
neurites = sorted(neurites, key=lambda neurite: NRN_ORDER.get(neurite.type, last_position))
neurite_iter = iter(neurites) if filt is None else filter(filt, neurites)
return neurite_iter if mapfun is None else map(mapfun, neurite_iter) | python | def iter_neurites(obj, mapfun=None, filt=None, neurite_order=NeuriteIter.FileOrder):
'''Iterator to a neurite, neuron or neuron population
Applies optional neurite filter and mapping functions.
Parameters:
obj: a neurite, neuron or neuron population.
mapfun: optional neurite mapping function.
filt: optional neurite filter function.
neurite_order (NeuriteIter): order upon which neurites should be iterated
- NeuriteIter.FileOrder: order of appearance in the file
- NeuriteIter.NRN: NRN simulator order: soma -> axon -> basal -> apical
Examples:
Get the number of points in each neurite in a neuron population
>>> from neurom.core import iter_neurites
>>> n_points = [n for n in iter_neurites(pop, lambda x : len(x.points))]
Get the number of points in each axon in a neuron population
>>> import neurom as nm
>>> from neurom.core import iter_neurites
>>> filter = lambda n : n.type == nm.AXON
>>> mapping = lambda n : len(n.points)
>>> n_points = [n for n in iter_neurites(pop, mapping, filter)]
'''
neurites = ((obj,) if isinstance(obj, Neurite) else
obj.neurites if hasattr(obj, 'neurites') else obj)
if neurite_order == NeuriteIter.NRN:
last_position = max(NRN_ORDER.values()) + 1
neurites = sorted(neurites, key=lambda neurite: NRN_ORDER.get(neurite.type, last_position))
neurite_iter = iter(neurites) if filt is None else filter(filt, neurites)
return neurite_iter if mapfun is None else map(mapfun, neurite_iter) | [
"def",
"iter_neurites",
"(",
"obj",
",",
"mapfun",
"=",
"None",
",",
"filt",
"=",
"None",
",",
"neurite_order",
"=",
"NeuriteIter",
".",
"FileOrder",
")",
":",
"neurites",
"=",
"(",
"(",
"obj",
",",
")",
"if",
"isinstance",
"(",
"obj",
",",
"Neurite",
")",
"else",
"obj",
".",
"neurites",
"if",
"hasattr",
"(",
"obj",
",",
"'neurites'",
")",
"else",
"obj",
")",
"if",
"neurite_order",
"==",
"NeuriteIter",
".",
"NRN",
":",
"last_position",
"=",
"max",
"(",
"NRN_ORDER",
".",
"values",
"(",
")",
")",
"+",
"1",
"neurites",
"=",
"sorted",
"(",
"neurites",
",",
"key",
"=",
"lambda",
"neurite",
":",
"NRN_ORDER",
".",
"get",
"(",
"neurite",
".",
"type",
",",
"last_position",
")",
")",
"neurite_iter",
"=",
"iter",
"(",
"neurites",
")",
"if",
"filt",
"is",
"None",
"else",
"filter",
"(",
"filt",
",",
"neurites",
")",
"return",
"neurite_iter",
"if",
"mapfun",
"is",
"None",
"else",
"map",
"(",
"mapfun",
",",
"neurite_iter",
")"
] | Iterator to a neurite, neuron or neuron population
Applies optional neurite filter and mapping functions.
Parameters:
obj: a neurite, neuron or neuron population.
mapfun: optional neurite mapping function.
filt: optional neurite filter function.
neurite_order (NeuriteIter): order upon which neurites should be iterated
- NeuriteIter.FileOrder: order of appearance in the file
- NeuriteIter.NRN: NRN simulator order: soma -> axon -> basal -> apical
Examples:
Get the number of points in each neurite in a neuron population
>>> from neurom.core import iter_neurites
>>> n_points = [n for n in iter_neurites(pop, lambda x : len(x.points))]
Get the number of points in each axon in a neuron population
>>> import neurom as nm
>>> from neurom.core import iter_neurites
>>> filter = lambda n : n.type == nm.AXON
>>> mapping = lambda n : len(n.points)
>>> n_points = [n for n in iter_neurites(pop, mapping, filter)] | [
"Iterator",
"to",
"a",
"neurite",
"neuron",
"or",
"neuron",
"population"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/core/_neuron.py#L54-L90 |
2,720 | BlueBrain/NeuroM | neurom/core/_neuron.py | iter_sections | def iter_sections(neurites,
iterator_type=Tree.ipreorder,
neurite_filter=None,
neurite_order=NeuriteIter.FileOrder):
'''Iterator to the sections in a neurite, neuron or neuron population.
Parameters:
neurites: neuron, population, neurite, or iterable containing neurite objects
iterator_type: section iteration order within a given neurite. Must be one of:
Tree.ipreorder: Depth-first pre-order iteration of tree nodes
Tree.ipreorder: Depth-first post-order iteration of tree nodes
Tree.iupstream: Iterate from a tree node to the root nodes
Tree.ibifurcation_point: Iterator to bifurcation points
Tree.ileaf: Iterator to all leaves of a tree
neurite_filter: optional top level filter on properties of neurite neurite objects.
neurite_order (NeuriteIter): order upon which neurites should be iterated
- NeuriteIter.FileOrder: order of appearance in the file
- NeuriteIter.NRN: NRN simulator order: soma -> axon -> basal -> apical
Examples:
Get the number of points in each section of all the axons in a neuron population
>>> import neurom as nm
>>> from neurom.core import ites_sections
>>> filter = lambda n : n.type == nm.AXON
>>> n_points = [len(s.points) for s in iter_sections(pop, neurite_filter=filter)]
'''
return chain.from_iterable(
iterator_type(neurite.root_node) for neurite in
iter_neurites(neurites, filt=neurite_filter, neurite_order=neurite_order)) | python | def iter_sections(neurites,
iterator_type=Tree.ipreorder,
neurite_filter=None,
neurite_order=NeuriteIter.FileOrder):
'''Iterator to the sections in a neurite, neuron or neuron population.
Parameters:
neurites: neuron, population, neurite, or iterable containing neurite objects
iterator_type: section iteration order within a given neurite. Must be one of:
Tree.ipreorder: Depth-first pre-order iteration of tree nodes
Tree.ipreorder: Depth-first post-order iteration of tree nodes
Tree.iupstream: Iterate from a tree node to the root nodes
Tree.ibifurcation_point: Iterator to bifurcation points
Tree.ileaf: Iterator to all leaves of a tree
neurite_filter: optional top level filter on properties of neurite neurite objects.
neurite_order (NeuriteIter): order upon which neurites should be iterated
- NeuriteIter.FileOrder: order of appearance in the file
- NeuriteIter.NRN: NRN simulator order: soma -> axon -> basal -> apical
Examples:
Get the number of points in each section of all the axons in a neuron population
>>> import neurom as nm
>>> from neurom.core import ites_sections
>>> filter = lambda n : n.type == nm.AXON
>>> n_points = [len(s.points) for s in iter_sections(pop, neurite_filter=filter)]
'''
return chain.from_iterable(
iterator_type(neurite.root_node) for neurite in
iter_neurites(neurites, filt=neurite_filter, neurite_order=neurite_order)) | [
"def",
"iter_sections",
"(",
"neurites",
",",
"iterator_type",
"=",
"Tree",
".",
"ipreorder",
",",
"neurite_filter",
"=",
"None",
",",
"neurite_order",
"=",
"NeuriteIter",
".",
"FileOrder",
")",
":",
"return",
"chain",
".",
"from_iterable",
"(",
"iterator_type",
"(",
"neurite",
".",
"root_node",
")",
"for",
"neurite",
"in",
"iter_neurites",
"(",
"neurites",
",",
"filt",
"=",
"neurite_filter",
",",
"neurite_order",
"=",
"neurite_order",
")",
")"
] | Iterator to the sections in a neurite, neuron or neuron population.
Parameters:
neurites: neuron, population, neurite, or iterable containing neurite objects
iterator_type: section iteration order within a given neurite. Must be one of:
Tree.ipreorder: Depth-first pre-order iteration of tree nodes
Tree.ipreorder: Depth-first post-order iteration of tree nodes
Tree.iupstream: Iterate from a tree node to the root nodes
Tree.ibifurcation_point: Iterator to bifurcation points
Tree.ileaf: Iterator to all leaves of a tree
neurite_filter: optional top level filter on properties of neurite neurite objects.
neurite_order (NeuriteIter): order upon which neurites should be iterated
- NeuriteIter.FileOrder: order of appearance in the file
- NeuriteIter.NRN: NRN simulator order: soma -> axon -> basal -> apical
Examples:
Get the number of points in each section of all the axons in a neuron population
>>> import neurom as nm
>>> from neurom.core import ites_sections
>>> filter = lambda n : n.type == nm.AXON
>>> n_points = [len(s.points) for s in iter_sections(pop, neurite_filter=filter)] | [
"Iterator",
"to",
"the",
"sections",
"in",
"a",
"neurite",
"neuron",
"or",
"neuron",
"population",
"."
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/core/_neuron.py#L93-L126 |
2,721 | BlueBrain/NeuroM | neurom/core/_neuron.py | iter_segments | def iter_segments(obj, neurite_filter=None, neurite_order=NeuriteIter.FileOrder):
'''Return an iterator to the segments in a collection of neurites
Parameters:
obj: neuron, population, neurite, section, or iterable containing neurite objects
neurite_filter: optional top level filter on properties of neurite neurite objects
neurite_order: order upon which neurite should be iterated. Values:
- NeuriteIter.FileOrder: order of appearance in the file
- NeuriteIter.NRN: NRN simulator order: soma -> axon -> basal -> apical
Note:
This is a convenience function provided for generic access to
neuron segments. It may have a performance overhead WRT custom-made
segment analysis functions that leverage numpy and section-wise iteration.
'''
sections = iter((obj,) if isinstance(obj, Section) else
iter_sections(obj,
neurite_filter=neurite_filter,
neurite_order=neurite_order))
return chain.from_iterable(zip(sec.points[:-1], sec.points[1:])
for sec in sections) | python | def iter_segments(obj, neurite_filter=None, neurite_order=NeuriteIter.FileOrder):
'''Return an iterator to the segments in a collection of neurites
Parameters:
obj: neuron, population, neurite, section, or iterable containing neurite objects
neurite_filter: optional top level filter on properties of neurite neurite objects
neurite_order: order upon which neurite should be iterated. Values:
- NeuriteIter.FileOrder: order of appearance in the file
- NeuriteIter.NRN: NRN simulator order: soma -> axon -> basal -> apical
Note:
This is a convenience function provided for generic access to
neuron segments. It may have a performance overhead WRT custom-made
segment analysis functions that leverage numpy and section-wise iteration.
'''
sections = iter((obj,) if isinstance(obj, Section) else
iter_sections(obj,
neurite_filter=neurite_filter,
neurite_order=neurite_order))
return chain.from_iterable(zip(sec.points[:-1], sec.points[1:])
for sec in sections) | [
"def",
"iter_segments",
"(",
"obj",
",",
"neurite_filter",
"=",
"None",
",",
"neurite_order",
"=",
"NeuriteIter",
".",
"FileOrder",
")",
":",
"sections",
"=",
"iter",
"(",
"(",
"obj",
",",
")",
"if",
"isinstance",
"(",
"obj",
",",
"Section",
")",
"else",
"iter_sections",
"(",
"obj",
",",
"neurite_filter",
"=",
"neurite_filter",
",",
"neurite_order",
"=",
"neurite_order",
")",
")",
"return",
"chain",
".",
"from_iterable",
"(",
"zip",
"(",
"sec",
".",
"points",
"[",
":",
"-",
"1",
"]",
",",
"sec",
".",
"points",
"[",
"1",
":",
"]",
")",
"for",
"sec",
"in",
"sections",
")"
] | Return an iterator to the segments in a collection of neurites
Parameters:
obj: neuron, population, neurite, section, or iterable containing neurite objects
neurite_filter: optional top level filter on properties of neurite neurite objects
neurite_order: order upon which neurite should be iterated. Values:
- NeuriteIter.FileOrder: order of appearance in the file
- NeuriteIter.NRN: NRN simulator order: soma -> axon -> basal -> apical
Note:
This is a convenience function provided for generic access to
neuron segments. It may have a performance overhead WRT custom-made
segment analysis functions that leverage numpy and section-wise iteration. | [
"Return",
"an",
"iterator",
"to",
"the",
"segments",
"in",
"a",
"collection",
"of",
"neurites"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/core/_neuron.py#L129-L150 |
2,722 | BlueBrain/NeuroM | neurom/core/_neuron.py | graft_neuron | def graft_neuron(root_section):
'''Returns a neuron starting at root_section'''
assert isinstance(root_section, Section)
return Neuron(soma=Soma(root_section.points[:1]), neurites=[Neurite(root_section)]) | python | def graft_neuron(root_section):
'''Returns a neuron starting at root_section'''
assert isinstance(root_section, Section)
return Neuron(soma=Soma(root_section.points[:1]), neurites=[Neurite(root_section)]) | [
"def",
"graft_neuron",
"(",
"root_section",
")",
":",
"assert",
"isinstance",
"(",
"root_section",
",",
"Section",
")",
"return",
"Neuron",
"(",
"soma",
"=",
"Soma",
"(",
"root_section",
".",
"points",
"[",
":",
"1",
"]",
")",
",",
"neurites",
"=",
"[",
"Neurite",
"(",
"root_section",
")",
"]",
")"
] | Returns a neuron starting at root_section | [
"Returns",
"a",
"neuron",
"starting",
"at",
"root_section"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/core/_neuron.py#L153-L156 |
2,723 | BlueBrain/NeuroM | neurom/core/_neuron.py | Neurite.points | def points(self):
'''Return unordered array with all the points in this neurite'''
# add all points in a section except the first one, which is a duplicate
_pts = [v for s in self.root_node.ipreorder()
for v in s.points[1:, COLS.XYZR]]
# except for the very first point, which is not a duplicate
_pts.insert(0, self.root_node.points[0][COLS.XYZR])
return np.array(_pts) | python | def points(self):
'''Return unordered array with all the points in this neurite'''
# add all points in a section except the first one, which is a duplicate
_pts = [v for s in self.root_node.ipreorder()
for v in s.points[1:, COLS.XYZR]]
# except for the very first point, which is not a duplicate
_pts.insert(0, self.root_node.points[0][COLS.XYZR])
return np.array(_pts) | [
"def",
"points",
"(",
"self",
")",
":",
"# add all points in a section except the first one, which is a duplicate",
"_pts",
"=",
"[",
"v",
"for",
"s",
"in",
"self",
".",
"root_node",
".",
"ipreorder",
"(",
")",
"for",
"v",
"in",
"s",
".",
"points",
"[",
"1",
":",
",",
"COLS",
".",
"XYZR",
"]",
"]",
"# except for the very first point, which is not a duplicate",
"_pts",
".",
"insert",
"(",
"0",
",",
"self",
".",
"root_node",
".",
"points",
"[",
"0",
"]",
"[",
"COLS",
".",
"XYZR",
"]",
")",
"return",
"np",
".",
"array",
"(",
"_pts",
")"
] | Return unordered array with all the points in this neurite | [
"Return",
"unordered",
"array",
"with",
"all",
"the",
"points",
"in",
"this",
"neurite"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/core/_neuron.py#L211-L218 |
2,724 | BlueBrain/NeuroM | neurom/core/_neuron.py | Neurite.transform | def transform(self, trans):
'''Return a copy of this neurite with a 3D transformation applied'''
clone = deepcopy(self)
for n in clone.iter_sections():
n.points[:, 0:3] = trans(n.points[:, 0:3])
return clone | python | def transform(self, trans):
'''Return a copy of this neurite with a 3D transformation applied'''
clone = deepcopy(self)
for n in clone.iter_sections():
n.points[:, 0:3] = trans(n.points[:, 0:3])
return clone | [
"def",
"transform",
"(",
"self",
",",
"trans",
")",
":",
"clone",
"=",
"deepcopy",
"(",
"self",
")",
"for",
"n",
"in",
"clone",
".",
"iter_sections",
"(",
")",
":",
"n",
".",
"points",
"[",
":",
",",
"0",
":",
"3",
"]",
"=",
"trans",
"(",
"n",
".",
"points",
"[",
":",
",",
"0",
":",
"3",
"]",
")",
"return",
"clone"
] | Return a copy of this neurite with a 3D transformation applied | [
"Return",
"a",
"copy",
"of",
"this",
"neurite",
"with",
"a",
"3D",
"transformation",
"applied"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/core/_neuron.py#L247-L253 |
2,725 | BlueBrain/NeuroM | neurom/core/_neuron.py | Neurite.iter_sections | def iter_sections(self, order=Tree.ipreorder, neurite_order=NeuriteIter.FileOrder):
'''iteration over section nodes
Parameters:
order: section iteration order within a given neurite. Must be one of:
Tree.ipreorder: Depth-first pre-order iteration of tree nodes
Tree.ipreorder: Depth-first post-order iteration of tree nodes
Tree.iupstream: Iterate from a tree node to the root nodes
Tree.ibifurcation_point: Iterator to bifurcation points
Tree.ileaf: Iterator to all leaves of a tree
neurite_order: order upon which neurites should be iterated. Values:
- NeuriteIter.FileOrder: order of appearance in the file
- NeuriteIter.NRN: NRN simulator order: soma -> axon -> basal -> apical
'''
return iter_sections(self, iterator_type=order, neurite_order=neurite_order) | python | def iter_sections(self, order=Tree.ipreorder, neurite_order=NeuriteIter.FileOrder):
'''iteration over section nodes
Parameters:
order: section iteration order within a given neurite. Must be one of:
Tree.ipreorder: Depth-first pre-order iteration of tree nodes
Tree.ipreorder: Depth-first post-order iteration of tree nodes
Tree.iupstream: Iterate from a tree node to the root nodes
Tree.ibifurcation_point: Iterator to bifurcation points
Tree.ileaf: Iterator to all leaves of a tree
neurite_order: order upon which neurites should be iterated. Values:
- NeuriteIter.FileOrder: order of appearance in the file
- NeuriteIter.NRN: NRN simulator order: soma -> axon -> basal -> apical
'''
return iter_sections(self, iterator_type=order, neurite_order=neurite_order) | [
"def",
"iter_sections",
"(",
"self",
",",
"order",
"=",
"Tree",
".",
"ipreorder",
",",
"neurite_order",
"=",
"NeuriteIter",
".",
"FileOrder",
")",
":",
"return",
"iter_sections",
"(",
"self",
",",
"iterator_type",
"=",
"order",
",",
"neurite_order",
"=",
"neurite_order",
")"
] | iteration over section nodes
Parameters:
order: section iteration order within a given neurite. Must be one of:
Tree.ipreorder: Depth-first pre-order iteration of tree nodes
Tree.ipreorder: Depth-first post-order iteration of tree nodes
Tree.iupstream: Iterate from a tree node to the root nodes
Tree.ibifurcation_point: Iterator to bifurcation points
Tree.ileaf: Iterator to all leaves of a tree
neurite_order: order upon which neurites should be iterated. Values:
- NeuriteIter.FileOrder: order of appearance in the file
- NeuriteIter.NRN: NRN simulator order: soma -> axon -> basal -> apical | [
"iteration",
"over",
"section",
"nodes"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/core/_neuron.py#L255-L270 |
2,726 | BlueBrain/NeuroM | neurom/apps/morph_stats.py | eval_stats | def eval_stats(values, mode):
'''Extract a summary statistic from an array of list of values
Parameters:
values: numpy array of values
mode: summary stat to extract. One of ['min', 'max', 'median', 'mean', 'std', 'raw']
Note: fails silently if values is empty, and None is returned
'''
if mode == 'raw':
return values.tolist()
if mode == 'total':
mode = 'sum'
try:
return getattr(np, mode)(values, axis=0)
except ValueError:
pass
return None | python | def eval_stats(values, mode):
'''Extract a summary statistic from an array of list of values
Parameters:
values: numpy array of values
mode: summary stat to extract. One of ['min', 'max', 'median', 'mean', 'std', 'raw']
Note: fails silently if values is empty, and None is returned
'''
if mode == 'raw':
return values.tolist()
if mode == 'total':
mode = 'sum'
try:
return getattr(np, mode)(values, axis=0)
except ValueError:
pass
return None | [
"def",
"eval_stats",
"(",
"values",
",",
"mode",
")",
":",
"if",
"mode",
"==",
"'raw'",
":",
"return",
"values",
".",
"tolist",
"(",
")",
"if",
"mode",
"==",
"'total'",
":",
"mode",
"=",
"'sum'",
"try",
":",
"return",
"getattr",
"(",
"np",
",",
"mode",
")",
"(",
"values",
",",
"axis",
"=",
"0",
")",
"except",
"ValueError",
":",
"pass",
"return",
"None"
] | Extract a summary statistic from an array of list of values
Parameters:
values: numpy array of values
mode: summary stat to extract. One of ['min', 'max', 'median', 'mean', 'std', 'raw']
Note: fails silently if values is empty, and None is returned | [
"Extract",
"a",
"summary",
"statistic",
"from",
"an",
"array",
"of",
"list",
"of",
"values"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/apps/morph_stats.py#L40-L59 |
2,727 | BlueBrain/NeuroM | neurom/apps/morph_stats.py | _stat_name | def _stat_name(feat_name, stat_mode):
'''Set stat name based on feature name and stat mode'''
if feat_name[-1] == 's':
feat_name = feat_name[:-1]
if feat_name == 'soma_radii':
feat_name = 'soma_radius'
if stat_mode == 'raw':
return feat_name
return '%s_%s' % (stat_mode, feat_name) | python | def _stat_name(feat_name, stat_mode):
'''Set stat name based on feature name and stat mode'''
if feat_name[-1] == 's':
feat_name = feat_name[:-1]
if feat_name == 'soma_radii':
feat_name = 'soma_radius'
if stat_mode == 'raw':
return feat_name
return '%s_%s' % (stat_mode, feat_name) | [
"def",
"_stat_name",
"(",
"feat_name",
",",
"stat_mode",
")",
":",
"if",
"feat_name",
"[",
"-",
"1",
"]",
"==",
"'s'",
":",
"feat_name",
"=",
"feat_name",
"[",
":",
"-",
"1",
"]",
"if",
"feat_name",
"==",
"'soma_radii'",
":",
"feat_name",
"=",
"'soma_radius'",
"if",
"stat_mode",
"==",
"'raw'",
":",
"return",
"feat_name",
"return",
"'%s_%s'",
"%",
"(",
"stat_mode",
",",
"feat_name",
")"
] | Set stat name based on feature name and stat mode | [
"Set",
"stat",
"name",
"based",
"on",
"feature",
"name",
"and",
"stat",
"mode"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/apps/morph_stats.py#L62-L71 |
2,728 | BlueBrain/NeuroM | neurom/apps/morph_stats.py | extract_stats | 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 not stat.shape:
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 | python | 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 not stat.shape:
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",
"extract_stats",
"(",
"neurons",
",",
"config",
")",
":",
"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",
"not",
"stat",
".",
"shape",
":",
"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"
] | Extract stats from neurons | [
"Extract",
"stats",
"from",
"neurons"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/apps/morph_stats.py#L74-L100 |
2,729 | BlueBrain/NeuroM | neurom/apps/morph_stats.py | get_header | def get_header(results):
'''Extracts the headers, using the first value in the dict as the template'''
ret = ['name', ]
values = next(iter(results.values()))
for k, v in values.items():
if isinstance(v, dict):
for metric in v.keys():
ret.append('%s:%s' % (k, metric))
else:
ret.append(k)
return ret | python | def get_header(results):
'''Extracts the headers, using the first value in the dict as the template'''
ret = ['name', ]
values = next(iter(results.values()))
for k, v in values.items():
if isinstance(v, dict):
for metric in v.keys():
ret.append('%s:%s' % (k, metric))
else:
ret.append(k)
return ret | [
"def",
"get_header",
"(",
"results",
")",
":",
"ret",
"=",
"[",
"'name'",
",",
"]",
"values",
"=",
"next",
"(",
"iter",
"(",
"results",
".",
"values",
"(",
")",
")",
")",
"for",
"k",
",",
"v",
"in",
"values",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"for",
"metric",
"in",
"v",
".",
"keys",
"(",
")",
":",
"ret",
".",
"append",
"(",
"'%s:%s'",
"%",
"(",
"k",
",",
"metric",
")",
")",
"else",
":",
"ret",
".",
"append",
"(",
"k",
")",
"return",
"ret"
] | Extracts the headers, using the first value in the dict as the template | [
"Extracts",
"the",
"headers",
"using",
"the",
"first",
"value",
"in",
"the",
"dict",
"as",
"the",
"template"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/apps/morph_stats.py#L103-L113 |
2,730 | BlueBrain/NeuroM | neurom/apps/morph_stats.py | generate_flattened_dict | def generate_flattened_dict(headers, results):
'''extract from results the fields in the headers list'''
for name, values in results.items():
row = []
for header in headers:
if header == 'name':
row.append(name)
elif ':' in header:
neurite_type, metric = header.split(':')
row.append(values[neurite_type][metric])
else:
row.append(values[header])
yield row | python | def generate_flattened_dict(headers, results):
'''extract from results the fields in the headers list'''
for name, values in results.items():
row = []
for header in headers:
if header == 'name':
row.append(name)
elif ':' in header:
neurite_type, metric = header.split(':')
row.append(values[neurite_type][metric])
else:
row.append(values[header])
yield row | [
"def",
"generate_flattened_dict",
"(",
"headers",
",",
"results",
")",
":",
"for",
"name",
",",
"values",
"in",
"results",
".",
"items",
"(",
")",
":",
"row",
"=",
"[",
"]",
"for",
"header",
"in",
"headers",
":",
"if",
"header",
"==",
"'name'",
":",
"row",
".",
"append",
"(",
"name",
")",
"elif",
"':'",
"in",
"header",
":",
"neurite_type",
",",
"metric",
"=",
"header",
".",
"split",
"(",
"':'",
")",
"row",
".",
"append",
"(",
"values",
"[",
"neurite_type",
"]",
"[",
"metric",
"]",
")",
"else",
":",
"row",
".",
"append",
"(",
"values",
"[",
"header",
"]",
")",
"yield",
"row"
] | extract from results the fields in the headers list | [
"extract",
"from",
"results",
"the",
"fields",
"in",
"the",
"headers",
"list"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/apps/morph_stats.py#L116-L128 |
2,731 | BlueBrain/NeuroM | neurom/core/tree.py | Tree.add_child | def add_child(self, tree):
'''Add a child to the list of this tree's children
This tree becomes the added tree's parent
'''
tree.parent = self
self.children.append(tree)
return tree | python | def add_child(self, tree):
'''Add a child to the list of this tree's children
This tree becomes the added tree's parent
'''
tree.parent = self
self.children.append(tree)
return tree | [
"def",
"add_child",
"(",
"self",
",",
"tree",
")",
":",
"tree",
".",
"parent",
"=",
"self",
"self",
".",
"children",
".",
"append",
"(",
"tree",
")",
"return",
"tree"
] | Add a child to the list of this tree's children
This tree becomes the added tree's parent | [
"Add",
"a",
"child",
"to",
"the",
"list",
"of",
"this",
"tree",
"s",
"children"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/core/tree.py#L41-L48 |
2,732 | BlueBrain/NeuroM | neurom/core/tree.py | Tree.ipreorder | def ipreorder(self):
'''Depth-first pre-order iteration of tree nodes'''
children = deque((self, ))
while children:
cur_node = children.pop()
children.extend(reversed(cur_node.children))
yield cur_node | python | def ipreorder(self):
'''Depth-first pre-order iteration of tree nodes'''
children = deque((self, ))
while children:
cur_node = children.pop()
children.extend(reversed(cur_node.children))
yield cur_node | [
"def",
"ipreorder",
"(",
"self",
")",
":",
"children",
"=",
"deque",
"(",
"(",
"self",
",",
")",
")",
"while",
"children",
":",
"cur_node",
"=",
"children",
".",
"pop",
"(",
")",
"children",
".",
"extend",
"(",
"reversed",
"(",
"cur_node",
".",
"children",
")",
")",
"yield",
"cur_node"
] | Depth-first pre-order iteration of tree nodes | [
"Depth",
"-",
"first",
"pre",
"-",
"order",
"iteration",
"of",
"tree",
"nodes"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/core/tree.py#L66-L72 |
2,733 | BlueBrain/NeuroM | neurom/core/tree.py | Tree.ipostorder | def ipostorder(self):
'''Depth-first post-order iteration of tree nodes'''
children = [self, ]
seen = set()
while children:
cur_node = children[-1]
if cur_node not in seen:
seen.add(cur_node)
children.extend(reversed(cur_node.children))
else:
children.pop()
yield cur_node | python | def ipostorder(self):
'''Depth-first post-order iteration of tree nodes'''
children = [self, ]
seen = set()
while children:
cur_node = children[-1]
if cur_node not in seen:
seen.add(cur_node)
children.extend(reversed(cur_node.children))
else:
children.pop()
yield cur_node | [
"def",
"ipostorder",
"(",
"self",
")",
":",
"children",
"=",
"[",
"self",
",",
"]",
"seen",
"=",
"set",
"(",
")",
"while",
"children",
":",
"cur_node",
"=",
"children",
"[",
"-",
"1",
"]",
"if",
"cur_node",
"not",
"in",
"seen",
":",
"seen",
".",
"add",
"(",
"cur_node",
")",
"children",
".",
"extend",
"(",
"reversed",
"(",
"cur_node",
".",
"children",
")",
")",
"else",
":",
"children",
".",
"pop",
"(",
")",
"yield",
"cur_node"
] | Depth-first post-order iteration of tree nodes | [
"Depth",
"-",
"first",
"post",
"-",
"order",
"iteration",
"of",
"tree",
"nodes"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/core/tree.py#L74-L85 |
2,734 | BlueBrain/NeuroM | neurom/utils.py | deprecated | def deprecated(fun_name=None, msg=""):
'''Issue a deprecation warning for a function'''
def _deprecated(fun):
'''Issue a deprecation warning for a function'''
@wraps(fun)
def _wrapper(*args, **kwargs):
'''Issue deprecation warning and forward arguments to fun'''
name = fun_name if fun_name is not None else fun.__name__
_warn_deprecated('Call to deprecated function %s. %s' % (name, msg))
return fun(*args, **kwargs)
return _wrapper
return _deprecated | python | def deprecated(fun_name=None, msg=""):
'''Issue a deprecation warning for a function'''
def _deprecated(fun):
'''Issue a deprecation warning for a function'''
@wraps(fun)
def _wrapper(*args, **kwargs):
'''Issue deprecation warning and forward arguments to fun'''
name = fun_name if fun_name is not None else fun.__name__
_warn_deprecated('Call to deprecated function %s. %s' % (name, msg))
return fun(*args, **kwargs)
return _wrapper
return _deprecated | [
"def",
"deprecated",
"(",
"fun_name",
"=",
"None",
",",
"msg",
"=",
"\"\"",
")",
":",
"def",
"_deprecated",
"(",
"fun",
")",
":",
"'''Issue a deprecation warning for a function'''",
"@",
"wraps",
"(",
"fun",
")",
"def",
"_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"'''Issue deprecation warning and forward arguments to fun'''",
"name",
"=",
"fun_name",
"if",
"fun_name",
"is",
"not",
"None",
"else",
"fun",
".",
"__name__",
"_warn_deprecated",
"(",
"'Call to deprecated function %s. %s'",
"%",
"(",
"name",
",",
"msg",
")",
")",
"return",
"fun",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"_wrapper",
"return",
"_deprecated"
] | Issue a deprecation warning for a function | [
"Issue",
"a",
"deprecation",
"warning",
"for",
"a",
"function"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/utils.py#L86-L99 |
2,735 | BlueBrain/NeuroM | neurom/check/__init__.py | check_wrapper | def check_wrapper(fun):
'''Decorate a checking function'''
@wraps(fun)
def _wrapper(*args, **kwargs):
'''Sets the title property of the result of running a checker'''
title = fun.__name__.replace('_', ' ').capitalize()
result = fun(*args, **kwargs)
result.title = title
return result
return _wrapper | python | def check_wrapper(fun):
'''Decorate a checking function'''
@wraps(fun)
def _wrapper(*args, **kwargs):
'''Sets the title property of the result of running a checker'''
title = fun.__name__.replace('_', ' ').capitalize()
result = fun(*args, **kwargs)
result.title = title
return result
return _wrapper | [
"def",
"check_wrapper",
"(",
"fun",
")",
":",
"@",
"wraps",
"(",
"fun",
")",
"def",
"_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"'''Sets the title property of the result of running a checker'''",
"title",
"=",
"fun",
".",
"__name__",
".",
"replace",
"(",
"'_'",
",",
"' '",
")",
".",
"capitalize",
"(",
")",
"result",
"=",
"fun",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"result",
".",
"title",
"=",
"title",
"return",
"result",
"return",
"_wrapper"
] | Decorate a checking function | [
"Decorate",
"a",
"checking",
"function"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/__init__.py#L34-L44 |
2,736 | BlueBrain/NeuroM | neurom/check/runner.py | CheckRunner.run | def run(self, path):
'''Test a bunch of files and return a summary JSON report'''
SEPARATOR = '=' * 40
summary = {}
res = True
for _f in utils.get_files_by_path(path):
L.info(SEPARATOR)
status, summ = self._check_file(_f)
res &= status
if summ is not None:
summary.update(summ)
L.info(SEPARATOR)
status = 'PASS' if res else 'FAIL'
return {'files': summary, 'STATUS': status} | python | def run(self, path):
'''Test a bunch of files and return a summary JSON report'''
SEPARATOR = '=' * 40
summary = {}
res = True
for _f in utils.get_files_by_path(path):
L.info(SEPARATOR)
status, summ = self._check_file(_f)
res &= status
if summ is not None:
summary.update(summ)
L.info(SEPARATOR)
status = 'PASS' if res else 'FAIL'
return {'files': summary, 'STATUS': status} | [
"def",
"run",
"(",
"self",
",",
"path",
")",
":",
"SEPARATOR",
"=",
"'='",
"*",
"40",
"summary",
"=",
"{",
"}",
"res",
"=",
"True",
"for",
"_f",
"in",
"utils",
".",
"get_files_by_path",
"(",
"path",
")",
":",
"L",
".",
"info",
"(",
"SEPARATOR",
")",
"status",
",",
"summ",
"=",
"self",
".",
"_check_file",
"(",
"_f",
")",
"res",
"&=",
"status",
"if",
"summ",
"is",
"not",
"None",
":",
"summary",
".",
"update",
"(",
"summ",
")",
"L",
".",
"info",
"(",
"SEPARATOR",
")",
"status",
"=",
"'PASS'",
"if",
"res",
"else",
"'FAIL'",
"return",
"{",
"'files'",
":",
"summary",
",",
"'STATUS'",
":",
"status",
"}"
] | Test a bunch of files and return a summary JSON report | [
"Test",
"a",
"bunch",
"of",
"files",
"and",
"return",
"a",
"summary",
"JSON",
"report"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/runner.py#L53-L71 |
2,737 | BlueBrain/NeuroM | neurom/check/runner.py | CheckRunner._do_check | def _do_check(self, obj, check_module, check_str):
'''Run a check function on obj'''
opts = self._config['options']
if check_str in opts:
fargs = opts[check_str]
if isinstance(fargs, list):
out = check_wrapper(getattr(check_module, check_str))(obj, *fargs)
else:
out = check_wrapper(getattr(check_module, check_str))(obj, fargs)
else:
out = check_wrapper(getattr(check_module, check_str))(obj)
try:
if out.info:
L.debug('%s: %d failing ids detected: %s',
out.title, len(out.info), out.info)
except TypeError: # pragma: no cover
pass
return out | python | def _do_check(self, obj, check_module, check_str):
'''Run a check function on obj'''
opts = self._config['options']
if check_str in opts:
fargs = opts[check_str]
if isinstance(fargs, list):
out = check_wrapper(getattr(check_module, check_str))(obj, *fargs)
else:
out = check_wrapper(getattr(check_module, check_str))(obj, fargs)
else:
out = check_wrapper(getattr(check_module, check_str))(obj)
try:
if out.info:
L.debug('%s: %d failing ids detected: %s',
out.title, len(out.info), out.info)
except TypeError: # pragma: no cover
pass
return out | [
"def",
"_do_check",
"(",
"self",
",",
"obj",
",",
"check_module",
",",
"check_str",
")",
":",
"opts",
"=",
"self",
".",
"_config",
"[",
"'options'",
"]",
"if",
"check_str",
"in",
"opts",
":",
"fargs",
"=",
"opts",
"[",
"check_str",
"]",
"if",
"isinstance",
"(",
"fargs",
",",
"list",
")",
":",
"out",
"=",
"check_wrapper",
"(",
"getattr",
"(",
"check_module",
",",
"check_str",
")",
")",
"(",
"obj",
",",
"*",
"fargs",
")",
"else",
":",
"out",
"=",
"check_wrapper",
"(",
"getattr",
"(",
"check_module",
",",
"check_str",
")",
")",
"(",
"obj",
",",
"fargs",
")",
"else",
":",
"out",
"=",
"check_wrapper",
"(",
"getattr",
"(",
"check_module",
",",
"check_str",
")",
")",
"(",
"obj",
")",
"try",
":",
"if",
"out",
".",
"info",
":",
"L",
".",
"debug",
"(",
"'%s: %d failing ids detected: %s'",
",",
"out",
".",
"title",
",",
"len",
"(",
"out",
".",
"info",
")",
",",
"out",
".",
"info",
")",
"except",
"TypeError",
":",
"# pragma: no cover",
"pass",
"return",
"out"
] | Run a check function on obj | [
"Run",
"a",
"check",
"function",
"on",
"obj"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/runner.py#L73-L92 |
2,738 | BlueBrain/NeuroM | neurom/check/runner.py | CheckRunner._check_loop | def _check_loop(self, obj, check_mod_str):
'''Run all the checks in a check_module'''
check_module = self._check_modules[check_mod_str]
checks = self._config['checks'][check_mod_str]
result = True
summary = OrderedDict()
for check in checks:
ok = self._do_check(obj, check_module, check)
summary[ok.title] = ok.status
result &= ok.status
return result, summary | python | def _check_loop(self, obj, check_mod_str):
'''Run all the checks in a check_module'''
check_module = self._check_modules[check_mod_str]
checks = self._config['checks'][check_mod_str]
result = True
summary = OrderedDict()
for check in checks:
ok = self._do_check(obj, check_module, check)
summary[ok.title] = ok.status
result &= ok.status
return result, summary | [
"def",
"_check_loop",
"(",
"self",
",",
"obj",
",",
"check_mod_str",
")",
":",
"check_module",
"=",
"self",
".",
"_check_modules",
"[",
"check_mod_str",
"]",
"checks",
"=",
"self",
".",
"_config",
"[",
"'checks'",
"]",
"[",
"check_mod_str",
"]",
"result",
"=",
"True",
"summary",
"=",
"OrderedDict",
"(",
")",
"for",
"check",
"in",
"checks",
":",
"ok",
"=",
"self",
".",
"_do_check",
"(",
"obj",
",",
"check_module",
",",
"check",
")",
"summary",
"[",
"ok",
".",
"title",
"]",
"=",
"ok",
".",
"status",
"result",
"&=",
"ok",
".",
"status",
"return",
"result",
",",
"summary"
] | Run all the checks in a check_module | [
"Run",
"all",
"the",
"checks",
"in",
"a",
"check_module"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/runner.py#L94-L105 |
2,739 | BlueBrain/NeuroM | neurom/check/runner.py | CheckRunner._check_file | def _check_file(self, f):
'''Run tests on a morphology file'''
L.info('File: %s', f)
full_result = True
full_summary = OrderedDict()
try:
data = load_data(f)
except Exception as e: # pylint: disable=W0703
L.error('Failed to load data... skipping tests for this file')
L.error(e.args)
return False, {f: OrderedDict([('ALL', False)])}
try:
result, summary = self._check_loop(data, 'structural_checks')
full_result &= result
full_summary.update(summary)
nrn = fst_core.FstNeuron(data)
result, summary = self._check_loop(nrn, 'neuron_checks')
full_result &= result
full_summary.update(summary)
except Exception as e: # pylint: disable=W0703
L.error('Check failed: %s', str(type(e)) + str(e.args))
full_result = False
full_summary['ALL'] = full_result
for m, s in full_summary.items():
self._log_msg(m, s)
return full_result, {f: full_summary} | python | def _check_file(self, f):
'''Run tests on a morphology file'''
L.info('File: %s', f)
full_result = True
full_summary = OrderedDict()
try:
data = load_data(f)
except Exception as e: # pylint: disable=W0703
L.error('Failed to load data... skipping tests for this file')
L.error(e.args)
return False, {f: OrderedDict([('ALL', False)])}
try:
result, summary = self._check_loop(data, 'structural_checks')
full_result &= result
full_summary.update(summary)
nrn = fst_core.FstNeuron(data)
result, summary = self._check_loop(nrn, 'neuron_checks')
full_result &= result
full_summary.update(summary)
except Exception as e: # pylint: disable=W0703
L.error('Check failed: %s', str(type(e)) + str(e.args))
full_result = False
full_summary['ALL'] = full_result
for m, s in full_summary.items():
self._log_msg(m, s)
return full_result, {f: full_summary} | [
"def",
"_check_file",
"(",
"self",
",",
"f",
")",
":",
"L",
".",
"info",
"(",
"'File: %s'",
",",
"f",
")",
"full_result",
"=",
"True",
"full_summary",
"=",
"OrderedDict",
"(",
")",
"try",
":",
"data",
"=",
"load_data",
"(",
"f",
")",
"except",
"Exception",
"as",
"e",
":",
"# pylint: disable=W0703",
"L",
".",
"error",
"(",
"'Failed to load data... skipping tests for this file'",
")",
"L",
".",
"error",
"(",
"e",
".",
"args",
")",
"return",
"False",
",",
"{",
"f",
":",
"OrderedDict",
"(",
"[",
"(",
"'ALL'",
",",
"False",
")",
"]",
")",
"}",
"try",
":",
"result",
",",
"summary",
"=",
"self",
".",
"_check_loop",
"(",
"data",
",",
"'structural_checks'",
")",
"full_result",
"&=",
"result",
"full_summary",
".",
"update",
"(",
"summary",
")",
"nrn",
"=",
"fst_core",
".",
"FstNeuron",
"(",
"data",
")",
"result",
",",
"summary",
"=",
"self",
".",
"_check_loop",
"(",
"nrn",
",",
"'neuron_checks'",
")",
"full_result",
"&=",
"result",
"full_summary",
".",
"update",
"(",
"summary",
")",
"except",
"Exception",
"as",
"e",
":",
"# pylint: disable=W0703",
"L",
".",
"error",
"(",
"'Check failed: %s'",
",",
"str",
"(",
"type",
"(",
"e",
")",
")",
"+",
"str",
"(",
"e",
".",
"args",
")",
")",
"full_result",
"=",
"False",
"full_summary",
"[",
"'ALL'",
"]",
"=",
"full_result",
"for",
"m",
",",
"s",
"in",
"full_summary",
".",
"items",
"(",
")",
":",
"self",
".",
"_log_msg",
"(",
"m",
",",
"s",
")",
"return",
"full_result",
",",
"{",
"f",
":",
"full_summary",
"}"
] | Run tests on a morphology file | [
"Run",
"tests",
"on",
"a",
"morphology",
"file"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/runner.py#L107-L138 |
2,740 | BlueBrain/NeuroM | neurom/check/runner.py | CheckRunner._log_msg | def _log_msg(self, msg, ok):
'''Helper to log message to the right level'''
if self._config['color']:
CGREEN, CRED, CEND = '\033[92m', '\033[91m', '\033[0m'
else:
CGREEN = CRED = CEND = ''
LOG_LEVELS = {False: logging.ERROR, True: logging.INFO}
# pylint: disable=logging-not-lazy
L.log(LOG_LEVELS[ok],
'%35s %s' + CEND, msg, CGREEN + 'PASS' if ok else CRED + 'FAIL') | python | def _log_msg(self, msg, ok):
'''Helper to log message to the right level'''
if self._config['color']:
CGREEN, CRED, CEND = '\033[92m', '\033[91m', '\033[0m'
else:
CGREEN = CRED = CEND = ''
LOG_LEVELS = {False: logging.ERROR, True: logging.INFO}
# pylint: disable=logging-not-lazy
L.log(LOG_LEVELS[ok],
'%35s %s' + CEND, msg, CGREEN + 'PASS' if ok else CRED + 'FAIL') | [
"def",
"_log_msg",
"(",
"self",
",",
"msg",
",",
"ok",
")",
":",
"if",
"self",
".",
"_config",
"[",
"'color'",
"]",
":",
"CGREEN",
",",
"CRED",
",",
"CEND",
"=",
"'\\033[92m'",
",",
"'\\033[91m'",
",",
"'\\033[0m'",
"else",
":",
"CGREEN",
"=",
"CRED",
"=",
"CEND",
"=",
"''",
"LOG_LEVELS",
"=",
"{",
"False",
":",
"logging",
".",
"ERROR",
",",
"True",
":",
"logging",
".",
"INFO",
"}",
"# pylint: disable=logging-not-lazy",
"L",
".",
"log",
"(",
"LOG_LEVELS",
"[",
"ok",
"]",
",",
"'%35s %s'",
"+",
"CEND",
",",
"msg",
",",
"CGREEN",
"+",
"'PASS'",
"if",
"ok",
"else",
"CRED",
"+",
"'FAIL'",
")"
] | Helper to log message to the right level | [
"Helper",
"to",
"log",
"message",
"to",
"the",
"right",
"level"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/runner.py#L140-L151 |
2,741 | BlueBrain/NeuroM | neurom/check/runner.py | CheckRunner._sanitize_config | def _sanitize_config(config):
'''check that the config has the correct keys, add missing keys if necessary'''
if 'checks' in config:
checks = config['checks']
if 'structural_checks' not in checks:
checks['structural_checks'] = []
if 'neuron_checks' not in checks:
checks['neuron_checks'] = []
else:
raise ConfigError('Need to have "checks" in the config')
if 'options' not in config:
L.debug('Using default options')
config['options'] = {}
if 'color' not in config:
config['color'] = False
return config | python | def _sanitize_config(config):
'''check that the config has the correct keys, add missing keys if necessary'''
if 'checks' in config:
checks = config['checks']
if 'structural_checks' not in checks:
checks['structural_checks'] = []
if 'neuron_checks' not in checks:
checks['neuron_checks'] = []
else:
raise ConfigError('Need to have "checks" in the config')
if 'options' not in config:
L.debug('Using default options')
config['options'] = {}
if 'color' not in config:
config['color'] = False
return config | [
"def",
"_sanitize_config",
"(",
"config",
")",
":",
"if",
"'checks'",
"in",
"config",
":",
"checks",
"=",
"config",
"[",
"'checks'",
"]",
"if",
"'structural_checks'",
"not",
"in",
"checks",
":",
"checks",
"[",
"'structural_checks'",
"]",
"=",
"[",
"]",
"if",
"'neuron_checks'",
"not",
"in",
"checks",
":",
"checks",
"[",
"'neuron_checks'",
"]",
"=",
"[",
"]",
"else",
":",
"raise",
"ConfigError",
"(",
"'Need to have \"checks\" in the config'",
")",
"if",
"'options'",
"not",
"in",
"config",
":",
"L",
".",
"debug",
"(",
"'Using default options'",
")",
"config",
"[",
"'options'",
"]",
"=",
"{",
"}",
"if",
"'color'",
"not",
"in",
"config",
":",
"config",
"[",
"'color'",
"]",
"=",
"False",
"return",
"config"
] | check that the config has the correct keys, add missing keys if necessary | [
"check",
"that",
"the",
"config",
"has",
"the",
"correct",
"keys",
"add",
"missing",
"keys",
"if",
"necessary"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/runner.py#L154-L172 |
2,742 | BlueBrain/NeuroM | neurom/io/swc.py | read | def read(filename, data_wrapper=DataWrapper):
'''Read an SWC file and return a tuple of data, format.'''
data = np.loadtxt(filename)
if len(np.shape(data)) == 1:
data = np.reshape(data, (1, -1))
data = data[:, [X, Y, Z, R, TYPE, ID, P]]
return data_wrapper(data, 'SWC', None) | python | def read(filename, data_wrapper=DataWrapper):
'''Read an SWC file and return a tuple of data, format.'''
data = np.loadtxt(filename)
if len(np.shape(data)) == 1:
data = np.reshape(data, (1, -1))
data = data[:, [X, Y, Z, R, TYPE, ID, P]]
return data_wrapper(data, 'SWC', None) | [
"def",
"read",
"(",
"filename",
",",
"data_wrapper",
"=",
"DataWrapper",
")",
":",
"data",
"=",
"np",
".",
"loadtxt",
"(",
"filename",
")",
"if",
"len",
"(",
"np",
".",
"shape",
"(",
"data",
")",
")",
"==",
"1",
":",
"data",
"=",
"np",
".",
"reshape",
"(",
"data",
",",
"(",
"1",
",",
"-",
"1",
")",
")",
"data",
"=",
"data",
"[",
":",
",",
"[",
"X",
",",
"Y",
",",
"Z",
",",
"R",
",",
"TYPE",
",",
"ID",
",",
"P",
"]",
"]",
"return",
"data_wrapper",
"(",
"data",
",",
"'SWC'",
",",
"None",
")"
] | Read an SWC file and return a tuple of data, format. | [
"Read",
"an",
"SWC",
"file",
"and",
"return",
"a",
"tuple",
"of",
"data",
"format",
"."
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/swc.py#L47-L53 |
2,743 | BlueBrain/NeuroM | neurom/io/datawrapper.py | _merge_sections | def _merge_sections(sec_a, sec_b):
'''Merge two sections
Merges sec_a into sec_b and sets sec_a attributes to default
'''
sec_b.ids = list(sec_a.ids) + list(sec_b.ids[1:])
sec_b.ntype = sec_a.ntype
sec_b.pid = sec_a.pid
sec_a.ids = []
sec_a.pid = -1
sec_a.ntype = 0 | python | def _merge_sections(sec_a, sec_b):
'''Merge two sections
Merges sec_a into sec_b and sets sec_a attributes to default
'''
sec_b.ids = list(sec_a.ids) + list(sec_b.ids[1:])
sec_b.ntype = sec_a.ntype
sec_b.pid = sec_a.pid
sec_a.ids = []
sec_a.pid = -1
sec_a.ntype = 0 | [
"def",
"_merge_sections",
"(",
"sec_a",
",",
"sec_b",
")",
":",
"sec_b",
".",
"ids",
"=",
"list",
"(",
"sec_a",
".",
"ids",
")",
"+",
"list",
"(",
"sec_b",
".",
"ids",
"[",
"1",
":",
"]",
")",
"sec_b",
".",
"ntype",
"=",
"sec_a",
".",
"ntype",
"sec_b",
".",
"pid",
"=",
"sec_a",
".",
"pid",
"sec_a",
".",
"ids",
"=",
"[",
"]",
"sec_a",
".",
"pid",
"=",
"-",
"1",
"sec_a",
".",
"ntype",
"=",
"0"
] | Merge two sections
Merges sec_a into sec_b and sets sec_a attributes to default | [
"Merge",
"two",
"sections"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/datawrapper.py#L89-L100 |
2,744 | BlueBrain/NeuroM | neurom/io/datawrapper.py | _section_end_points | def _section_end_points(structure_block, id_map):
'''Get the section end-points'''
soma_idx = structure_block[:, TYPE] == POINT_TYPE.SOMA
soma_ids = structure_block[soma_idx, ID]
neurite_idx = structure_block[:, TYPE] != POINT_TYPE.SOMA
neurite_rows = structure_block[neurite_idx, :]
soma_end_pts = set(id_map[id_]
for id_ in soma_ids[np.in1d(soma_ids, neurite_rows[:, PID])])
# end points have either no children or more than one
# ie: leaf or multifurcation nodes
n_children = defaultdict(int)
for row in structure_block:
n_children[row[PID]] += 1
end_pts = set(i for i, row in enumerate(structure_block)
if n_children[row[ID]] != 1)
return end_pts.union(soma_end_pts) | python | def _section_end_points(structure_block, id_map):
'''Get the section end-points'''
soma_idx = structure_block[:, TYPE] == POINT_TYPE.SOMA
soma_ids = structure_block[soma_idx, ID]
neurite_idx = structure_block[:, TYPE] != POINT_TYPE.SOMA
neurite_rows = structure_block[neurite_idx, :]
soma_end_pts = set(id_map[id_]
for id_ in soma_ids[np.in1d(soma_ids, neurite_rows[:, PID])])
# end points have either no children or more than one
# ie: leaf or multifurcation nodes
n_children = defaultdict(int)
for row in structure_block:
n_children[row[PID]] += 1
end_pts = set(i for i, row in enumerate(structure_block)
if n_children[row[ID]] != 1)
return end_pts.union(soma_end_pts) | [
"def",
"_section_end_points",
"(",
"structure_block",
",",
"id_map",
")",
":",
"soma_idx",
"=",
"structure_block",
"[",
":",
",",
"TYPE",
"]",
"==",
"POINT_TYPE",
".",
"SOMA",
"soma_ids",
"=",
"structure_block",
"[",
"soma_idx",
",",
"ID",
"]",
"neurite_idx",
"=",
"structure_block",
"[",
":",
",",
"TYPE",
"]",
"!=",
"POINT_TYPE",
".",
"SOMA",
"neurite_rows",
"=",
"structure_block",
"[",
"neurite_idx",
",",
":",
"]",
"soma_end_pts",
"=",
"set",
"(",
"id_map",
"[",
"id_",
"]",
"for",
"id_",
"in",
"soma_ids",
"[",
"np",
".",
"in1d",
"(",
"soma_ids",
",",
"neurite_rows",
"[",
":",
",",
"PID",
"]",
")",
"]",
")",
"# end points have either no children or more than one",
"# ie: leaf or multifurcation nodes",
"n_children",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"row",
"in",
"structure_block",
":",
"n_children",
"[",
"row",
"[",
"PID",
"]",
"]",
"+=",
"1",
"end_pts",
"=",
"set",
"(",
"i",
"for",
"i",
",",
"row",
"in",
"enumerate",
"(",
"structure_block",
")",
"if",
"n_children",
"[",
"row",
"[",
"ID",
"]",
"]",
"!=",
"1",
")",
"return",
"end_pts",
".",
"union",
"(",
"soma_end_pts",
")"
] | Get the section end-points | [
"Get",
"the",
"section",
"end",
"-",
"points"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/datawrapper.py#L103-L120 |
2,745 | BlueBrain/NeuroM | neurom/io/datawrapper.py | _extract_sections | def _extract_sections(data_block):
'''Make a list of sections from an SWC-style data wrapper block'''
structure_block = data_block[:, COLS.TYPE:COLS.COL_COUNT].astype(np.int)
# SWC ID -> structure_block position
id_map = {-1: -1}
for i, row in enumerate(structure_block):
id_map[row[ID]] = i
# end points have either no children, more than one, or are the start
# of a new gap
sec_end_pts = _section_end_points(structure_block, id_map)
# a 'gap' is when a section has part of it's segments interleaved
# with those of another section
gap_sections = set()
sections = []
def new_section():
'''new_section'''
sections.append(DataBlockSection())
return sections[-1]
curr_section = new_section()
parent_section = {-1: -1}
for row in structure_block:
row_id = id_map[row[ID]]
parent_id = id_map[row[PID]]
if not curr_section.ids:
# first in section point is parent
curr_section.ids.append(parent_id)
curr_section.ntype = row[TYPE]
gap = parent_id != curr_section.ids[-1]
# If parent is not the previous point, create a section end-point.
# Else add the point to this section
if gap:
sec_end_pts.add(row_id)
else:
curr_section.ids.append(row_id)
if row_id in sec_end_pts:
parent_section[curr_section.ids[-1]] = len(sections) - 1
# Parent-child discontinuity section
if gap:
curr_section = new_section()
curr_section.ids.extend((parent_id, row_id))
curr_section.ntype = row[TYPE]
gap_sections.add(len(sections) - 2)
elif row_id != len(data_block) - 1:
# avoid creating an extra DataBlockSection for last row if it's a leaf
curr_section = new_section()
for sec in sections:
# get the section parent ID from the id of the first point.
if sec.ids:
sec.pid = parent_section[sec.ids[0]]
# join gap sections and "disable" first half
if sec.pid in gap_sections:
_merge_sections(sections[sec.pid], sec)
# TODO find a way to remove empty sections. Currently they are
# required to maintain tree integrity.
return sections | python | def _extract_sections(data_block):
'''Make a list of sections from an SWC-style data wrapper block'''
structure_block = data_block[:, COLS.TYPE:COLS.COL_COUNT].astype(np.int)
# SWC ID -> structure_block position
id_map = {-1: -1}
for i, row in enumerate(structure_block):
id_map[row[ID]] = i
# end points have either no children, more than one, or are the start
# of a new gap
sec_end_pts = _section_end_points(structure_block, id_map)
# a 'gap' is when a section has part of it's segments interleaved
# with those of another section
gap_sections = set()
sections = []
def new_section():
'''new_section'''
sections.append(DataBlockSection())
return sections[-1]
curr_section = new_section()
parent_section = {-1: -1}
for row in structure_block:
row_id = id_map[row[ID]]
parent_id = id_map[row[PID]]
if not curr_section.ids:
# first in section point is parent
curr_section.ids.append(parent_id)
curr_section.ntype = row[TYPE]
gap = parent_id != curr_section.ids[-1]
# If parent is not the previous point, create a section end-point.
# Else add the point to this section
if gap:
sec_end_pts.add(row_id)
else:
curr_section.ids.append(row_id)
if row_id in sec_end_pts:
parent_section[curr_section.ids[-1]] = len(sections) - 1
# Parent-child discontinuity section
if gap:
curr_section = new_section()
curr_section.ids.extend((parent_id, row_id))
curr_section.ntype = row[TYPE]
gap_sections.add(len(sections) - 2)
elif row_id != len(data_block) - 1:
# avoid creating an extra DataBlockSection for last row if it's a leaf
curr_section = new_section()
for sec in sections:
# get the section parent ID from the id of the first point.
if sec.ids:
sec.pid = parent_section[sec.ids[0]]
# join gap sections and "disable" first half
if sec.pid in gap_sections:
_merge_sections(sections[sec.pid], sec)
# TODO find a way to remove empty sections. Currently they are
# required to maintain tree integrity.
return sections | [
"def",
"_extract_sections",
"(",
"data_block",
")",
":",
"structure_block",
"=",
"data_block",
"[",
":",
",",
"COLS",
".",
"TYPE",
":",
"COLS",
".",
"COL_COUNT",
"]",
".",
"astype",
"(",
"np",
".",
"int",
")",
"# SWC ID -> structure_block position",
"id_map",
"=",
"{",
"-",
"1",
":",
"-",
"1",
"}",
"for",
"i",
",",
"row",
"in",
"enumerate",
"(",
"structure_block",
")",
":",
"id_map",
"[",
"row",
"[",
"ID",
"]",
"]",
"=",
"i",
"# end points have either no children, more than one, or are the start",
"# of a new gap",
"sec_end_pts",
"=",
"_section_end_points",
"(",
"structure_block",
",",
"id_map",
")",
"# a 'gap' is when a section has part of it's segments interleaved",
"# with those of another section",
"gap_sections",
"=",
"set",
"(",
")",
"sections",
"=",
"[",
"]",
"def",
"new_section",
"(",
")",
":",
"'''new_section'''",
"sections",
".",
"append",
"(",
"DataBlockSection",
"(",
")",
")",
"return",
"sections",
"[",
"-",
"1",
"]",
"curr_section",
"=",
"new_section",
"(",
")",
"parent_section",
"=",
"{",
"-",
"1",
":",
"-",
"1",
"}",
"for",
"row",
"in",
"structure_block",
":",
"row_id",
"=",
"id_map",
"[",
"row",
"[",
"ID",
"]",
"]",
"parent_id",
"=",
"id_map",
"[",
"row",
"[",
"PID",
"]",
"]",
"if",
"not",
"curr_section",
".",
"ids",
":",
"# first in section point is parent",
"curr_section",
".",
"ids",
".",
"append",
"(",
"parent_id",
")",
"curr_section",
".",
"ntype",
"=",
"row",
"[",
"TYPE",
"]",
"gap",
"=",
"parent_id",
"!=",
"curr_section",
".",
"ids",
"[",
"-",
"1",
"]",
"# If parent is not the previous point, create a section end-point.",
"# Else add the point to this section",
"if",
"gap",
":",
"sec_end_pts",
".",
"add",
"(",
"row_id",
")",
"else",
":",
"curr_section",
".",
"ids",
".",
"append",
"(",
"row_id",
")",
"if",
"row_id",
"in",
"sec_end_pts",
":",
"parent_section",
"[",
"curr_section",
".",
"ids",
"[",
"-",
"1",
"]",
"]",
"=",
"len",
"(",
"sections",
")",
"-",
"1",
"# Parent-child discontinuity section",
"if",
"gap",
":",
"curr_section",
"=",
"new_section",
"(",
")",
"curr_section",
".",
"ids",
".",
"extend",
"(",
"(",
"parent_id",
",",
"row_id",
")",
")",
"curr_section",
".",
"ntype",
"=",
"row",
"[",
"TYPE",
"]",
"gap_sections",
".",
"add",
"(",
"len",
"(",
"sections",
")",
"-",
"2",
")",
"elif",
"row_id",
"!=",
"len",
"(",
"data_block",
")",
"-",
"1",
":",
"# avoid creating an extra DataBlockSection for last row if it's a leaf",
"curr_section",
"=",
"new_section",
"(",
")",
"for",
"sec",
"in",
"sections",
":",
"# get the section parent ID from the id of the first point.",
"if",
"sec",
".",
"ids",
":",
"sec",
".",
"pid",
"=",
"parent_section",
"[",
"sec",
".",
"ids",
"[",
"0",
"]",
"]",
"# join gap sections and \"disable\" first half",
"if",
"sec",
".",
"pid",
"in",
"gap_sections",
":",
"_merge_sections",
"(",
"sections",
"[",
"sec",
".",
"pid",
"]",
",",
"sec",
")",
"# TODO find a way to remove empty sections. Currently they are",
"# required to maintain tree integrity.",
"return",
"sections"
] | Make a list of sections from an SWC-style data wrapper block | [
"Make",
"a",
"list",
"of",
"sections",
"from",
"an",
"SWC",
"-",
"style",
"data",
"wrapper",
"block"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/datawrapper.py#L142-L210 |
2,746 | BlueBrain/NeuroM | neurom/io/datawrapper.py | DataWrapper.neurite_root_section_ids | def neurite_root_section_ids(self):
'''Get the section IDs of the intitial neurite sections'''
sec = self.sections
return [i for i, ss in enumerate(sec)
if ss.pid > -1 and (sec[ss.pid].ntype == POINT_TYPE.SOMA and
ss.ntype != POINT_TYPE.SOMA)] | python | def neurite_root_section_ids(self):
'''Get the section IDs of the intitial neurite sections'''
sec = self.sections
return [i for i, ss in enumerate(sec)
if ss.pid > -1 and (sec[ss.pid].ntype == POINT_TYPE.SOMA and
ss.ntype != POINT_TYPE.SOMA)] | [
"def",
"neurite_root_section_ids",
"(",
"self",
")",
":",
"sec",
"=",
"self",
".",
"sections",
"return",
"[",
"i",
"for",
"i",
",",
"ss",
"in",
"enumerate",
"(",
"sec",
")",
"if",
"ss",
".",
"pid",
">",
"-",
"1",
"and",
"(",
"sec",
"[",
"ss",
".",
"pid",
"]",
".",
"ntype",
"==",
"POINT_TYPE",
".",
"SOMA",
"and",
"ss",
".",
"ntype",
"!=",
"POINT_TYPE",
".",
"SOMA",
")",
"]"
] | Get the section IDs of the intitial neurite sections | [
"Get",
"the",
"section",
"IDs",
"of",
"the",
"intitial",
"neurite",
"sections"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/datawrapper.py#L76-L81 |
2,747 | BlueBrain/NeuroM | neurom/io/datawrapper.py | DataWrapper.soma_points | def soma_points(self):
'''Get the soma points'''
db = self.data_block
return db[db[:, COLS.TYPE] == POINT_TYPE.SOMA] | python | def soma_points(self):
'''Get the soma points'''
db = self.data_block
return db[db[:, COLS.TYPE] == POINT_TYPE.SOMA] | [
"def",
"soma_points",
"(",
"self",
")",
":",
"db",
"=",
"self",
".",
"data_block",
"return",
"db",
"[",
"db",
"[",
":",
",",
"COLS",
".",
"TYPE",
"]",
"==",
"POINT_TYPE",
".",
"SOMA",
"]"
] | Get the soma points | [
"Get",
"the",
"soma",
"points"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/datawrapper.py#L83-L86 |
2,748 | BlueBrain/NeuroM | neurom/io/datawrapper.py | BlockNeuronBuilder.add_section | def add_section(self, id_, parent_id, section_type, points):
'''add a section
Args:
id_(int): identifying number of the section
parent_id(int): identifying number of the parent of this section
section_type(int): the section type as defined by POINT_TYPE
points is an array of [X, Y, Z, R]
'''
# L.debug('Adding section %d, with parent %d, of type: %d with count: %d',
# id_, parent_id, section_type, len(points))
assert id_ not in self.sections, 'id %s already exists in sections' % id_
self.sections[id_] = BlockNeuronBuilder.BlockSection(parent_id, section_type, points) | python | def add_section(self, id_, parent_id, section_type, points):
'''add a section
Args:
id_(int): identifying number of the section
parent_id(int): identifying number of the parent of this section
section_type(int): the section type as defined by POINT_TYPE
points is an array of [X, Y, Z, R]
'''
# L.debug('Adding section %d, with parent %d, of type: %d with count: %d',
# id_, parent_id, section_type, len(points))
assert id_ not in self.sections, 'id %s already exists in sections' % id_
self.sections[id_] = BlockNeuronBuilder.BlockSection(parent_id, section_type, points) | [
"def",
"add_section",
"(",
"self",
",",
"id_",
",",
"parent_id",
",",
"section_type",
",",
"points",
")",
":",
"# L.debug('Adding section %d, with parent %d, of type: %d with count: %d',",
"# id_, parent_id, section_type, len(points))",
"assert",
"id_",
"not",
"in",
"self",
".",
"sections",
",",
"'id %s already exists in sections'",
"%",
"id_",
"self",
".",
"sections",
"[",
"id_",
"]",
"=",
"BlockNeuronBuilder",
".",
"BlockSection",
"(",
"parent_id",
",",
"section_type",
",",
"points",
")"
] | add a section
Args:
id_(int): identifying number of the section
parent_id(int): identifying number of the parent of this section
section_type(int): the section type as defined by POINT_TYPE
points is an array of [X, Y, Z, R] | [
"add",
"a",
"section"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/datawrapper.py#L234-L246 |
2,749 | BlueBrain/NeuroM | neurom/io/datawrapper.py | BlockNeuronBuilder._make_datablock | def _make_datablock(self):
'''Make a data_block and sections list as required by DataWrapper'''
section_ids = sorted(self.sections)
# create all insertion id's, this needs to be done ahead of time
# as some of the children may have a lower id than their parents
id_to_insert_id = {}
row_count = 0
for section_id in section_ids:
row_count += len(self.sections[section_id].points)
id_to_insert_id[section_id] = row_count - 1
datablock = np.empty((row_count, COLS.COL_COUNT), dtype=np.float)
datablock[:, COLS.ID] = np.arange(len(datablock))
datablock[:, COLS.P] = datablock[:, COLS.ID] - 1
sections = []
insert_index = 0
for id_ in section_ids:
sec = self.sections[id_]
points, section_type, parent_id = sec.points, sec.section_type, sec.parent_id
idx = slice(insert_index, insert_index + len(points))
datablock[idx, COLS.XYZR] = points
datablock[idx, COLS.TYPE] = section_type
datablock[idx.start, COLS.P] = id_to_insert_id.get(parent_id, ROOT_ID)
sections.append(DataBlockSection(idx, section_type, parent_id))
insert_index = idx.stop
return datablock, sections | python | def _make_datablock(self):
'''Make a data_block and sections list as required by DataWrapper'''
section_ids = sorted(self.sections)
# create all insertion id's, this needs to be done ahead of time
# as some of the children may have a lower id than their parents
id_to_insert_id = {}
row_count = 0
for section_id in section_ids:
row_count += len(self.sections[section_id].points)
id_to_insert_id[section_id] = row_count - 1
datablock = np.empty((row_count, COLS.COL_COUNT), dtype=np.float)
datablock[:, COLS.ID] = np.arange(len(datablock))
datablock[:, COLS.P] = datablock[:, COLS.ID] - 1
sections = []
insert_index = 0
for id_ in section_ids:
sec = self.sections[id_]
points, section_type, parent_id = sec.points, sec.section_type, sec.parent_id
idx = slice(insert_index, insert_index + len(points))
datablock[idx, COLS.XYZR] = points
datablock[idx, COLS.TYPE] = section_type
datablock[idx.start, COLS.P] = id_to_insert_id.get(parent_id, ROOT_ID)
sections.append(DataBlockSection(idx, section_type, parent_id))
insert_index = idx.stop
return datablock, sections | [
"def",
"_make_datablock",
"(",
"self",
")",
":",
"section_ids",
"=",
"sorted",
"(",
"self",
".",
"sections",
")",
"# create all insertion id's, this needs to be done ahead of time",
"# as some of the children may have a lower id than their parents",
"id_to_insert_id",
"=",
"{",
"}",
"row_count",
"=",
"0",
"for",
"section_id",
"in",
"section_ids",
":",
"row_count",
"+=",
"len",
"(",
"self",
".",
"sections",
"[",
"section_id",
"]",
".",
"points",
")",
"id_to_insert_id",
"[",
"section_id",
"]",
"=",
"row_count",
"-",
"1",
"datablock",
"=",
"np",
".",
"empty",
"(",
"(",
"row_count",
",",
"COLS",
".",
"COL_COUNT",
")",
",",
"dtype",
"=",
"np",
".",
"float",
")",
"datablock",
"[",
":",
",",
"COLS",
".",
"ID",
"]",
"=",
"np",
".",
"arange",
"(",
"len",
"(",
"datablock",
")",
")",
"datablock",
"[",
":",
",",
"COLS",
".",
"P",
"]",
"=",
"datablock",
"[",
":",
",",
"COLS",
".",
"ID",
"]",
"-",
"1",
"sections",
"=",
"[",
"]",
"insert_index",
"=",
"0",
"for",
"id_",
"in",
"section_ids",
":",
"sec",
"=",
"self",
".",
"sections",
"[",
"id_",
"]",
"points",
",",
"section_type",
",",
"parent_id",
"=",
"sec",
".",
"points",
",",
"sec",
".",
"section_type",
",",
"sec",
".",
"parent_id",
"idx",
"=",
"slice",
"(",
"insert_index",
",",
"insert_index",
"+",
"len",
"(",
"points",
")",
")",
"datablock",
"[",
"idx",
",",
"COLS",
".",
"XYZR",
"]",
"=",
"points",
"datablock",
"[",
"idx",
",",
"COLS",
".",
"TYPE",
"]",
"=",
"section_type",
"datablock",
"[",
"idx",
".",
"start",
",",
"COLS",
".",
"P",
"]",
"=",
"id_to_insert_id",
".",
"get",
"(",
"parent_id",
",",
"ROOT_ID",
")",
"sections",
".",
"append",
"(",
"DataBlockSection",
"(",
"idx",
",",
"section_type",
",",
"parent_id",
")",
")",
"insert_index",
"=",
"idx",
".",
"stop",
"return",
"datablock",
",",
"sections"
] | Make a data_block and sections list as required by DataWrapper | [
"Make",
"a",
"data_block",
"and",
"sections",
"list",
"as",
"required",
"by",
"DataWrapper"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/datawrapper.py#L248-L277 |
2,750 | BlueBrain/NeuroM | neurom/io/datawrapper.py | BlockNeuronBuilder._check_consistency | def _check_consistency(self):
'''see if the sections have obvious errors'''
type_count = defaultdict(int)
for _, section in sorted(self.sections.items()):
type_count[section.section_type] += 1
if type_count[POINT_TYPE.SOMA] != 1:
L.info('Have %d somas, expected 1', type_count[POINT_TYPE.SOMA]) | python | def _check_consistency(self):
'''see if the sections have obvious errors'''
type_count = defaultdict(int)
for _, section in sorted(self.sections.items()):
type_count[section.section_type] += 1
if type_count[POINT_TYPE.SOMA] != 1:
L.info('Have %d somas, expected 1', type_count[POINT_TYPE.SOMA]) | [
"def",
"_check_consistency",
"(",
"self",
")",
":",
"type_count",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"_",
",",
"section",
"in",
"sorted",
"(",
"self",
".",
"sections",
".",
"items",
"(",
")",
")",
":",
"type_count",
"[",
"section",
".",
"section_type",
"]",
"+=",
"1",
"if",
"type_count",
"[",
"POINT_TYPE",
".",
"SOMA",
"]",
"!=",
"1",
":",
"L",
".",
"info",
"(",
"'Have %d somas, expected 1'",
",",
"type_count",
"[",
"POINT_TYPE",
".",
"SOMA",
"]",
")"
] | see if the sections have obvious errors | [
"see",
"if",
"the",
"sections",
"have",
"obvious",
"errors"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/datawrapper.py#L279-L286 |
2,751 | BlueBrain/NeuroM | neurom/io/datawrapper.py | BlockNeuronBuilder.get_datawrapper | def get_datawrapper(self, file_format='BlockNeuronBuilder', data_wrapper=DataWrapper):
'''returns a DataWrapper'''
self._check_consistency()
datablock, sections = self._make_datablock()
return data_wrapper(datablock, file_format, sections) | python | def get_datawrapper(self, file_format='BlockNeuronBuilder', data_wrapper=DataWrapper):
'''returns a DataWrapper'''
self._check_consistency()
datablock, sections = self._make_datablock()
return data_wrapper(datablock, file_format, sections) | [
"def",
"get_datawrapper",
"(",
"self",
",",
"file_format",
"=",
"'BlockNeuronBuilder'",
",",
"data_wrapper",
"=",
"DataWrapper",
")",
":",
"self",
".",
"_check_consistency",
"(",
")",
"datablock",
",",
"sections",
"=",
"self",
".",
"_make_datablock",
"(",
")",
"return",
"data_wrapper",
"(",
"datablock",
",",
"file_format",
",",
"sections",
")"
] | returns a DataWrapper | [
"returns",
"a",
"DataWrapper"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/datawrapper.py#L288-L292 |
2,752 | BlueBrain/NeuroM | neurom/io/utils.py | _is_morphology_file | def _is_morphology_file(filepath):
""" Check if `filepath` is a file with one of morphology file extensions. """
return (
os.path.isfile(filepath) and
os.path.splitext(filepath)[1].lower() in ('.swc', '.h5', '.asc')
) | python | def _is_morphology_file(filepath):
""" Check if `filepath` is a file with one of morphology file extensions. """
return (
os.path.isfile(filepath) and
os.path.splitext(filepath)[1].lower() in ('.swc', '.h5', '.asc')
) | [
"def",
"_is_morphology_file",
"(",
"filepath",
")",
":",
"return",
"(",
"os",
".",
"path",
".",
"isfile",
"(",
"filepath",
")",
"and",
"os",
".",
"path",
".",
"splitext",
"(",
"filepath",
")",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"in",
"(",
"'.swc'",
",",
"'.h5'",
",",
"'.asc'",
")",
")"
] | Check if `filepath` is a file with one of morphology file extensions. | [
"Check",
"if",
"filepath",
"is",
"a",
"file",
"with",
"one",
"of",
"morphology",
"file",
"extensions",
"."
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/utils.py#L50-L55 |
2,753 | BlueBrain/NeuroM | neurom/io/utils.py | get_morph_files | def get_morph_files(directory):
'''Get a list of all morphology files in a directory
Returns:
list with all files with extensions '.swc' , 'h5' or '.asc' (case insensitive)
'''
lsdir = (os.path.join(directory, m) for m in os.listdir(directory))
return list(filter(_is_morphology_file, lsdir)) | python | def get_morph_files(directory):
'''Get a list of all morphology files in a directory
Returns:
list with all files with extensions '.swc' , 'h5' or '.asc' (case insensitive)
'''
lsdir = (os.path.join(directory, m) for m in os.listdir(directory))
return list(filter(_is_morphology_file, lsdir)) | [
"def",
"get_morph_files",
"(",
"directory",
")",
":",
"lsdir",
"=",
"(",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"m",
")",
"for",
"m",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
")",
"return",
"list",
"(",
"filter",
"(",
"_is_morphology_file",
",",
"lsdir",
")",
")"
] | Get a list of all morphology files in a directory
Returns:
list with all files with extensions '.swc' , 'h5' or '.asc' (case insensitive) | [
"Get",
"a",
"list",
"of",
"all",
"morphology",
"files",
"in",
"a",
"directory"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/utils.py#L92-L99 |
2,754 | BlueBrain/NeuroM | neurom/io/utils.py | get_files_by_path | def get_files_by_path(path):
'''Get a file or set of files from a file path
Return list of files with path
'''
if os.path.isfile(path):
return [path]
if os.path.isdir(path):
return get_morph_files(path)
raise IOError('Invalid data path %s' % path) | python | def get_files_by_path(path):
'''Get a file or set of files from a file path
Return list of files with path
'''
if os.path.isfile(path):
return [path]
if os.path.isdir(path):
return get_morph_files(path)
raise IOError('Invalid data path %s' % path) | [
"def",
"get_files_by_path",
"(",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"return",
"[",
"path",
"]",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"return",
"get_morph_files",
"(",
"path",
")",
"raise",
"IOError",
"(",
"'Invalid data path %s'",
"%",
"path",
")"
] | Get a file or set of files from a file path
Return list of files with path | [
"Get",
"a",
"file",
"or",
"set",
"of",
"files",
"from",
"a",
"file",
"path"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/utils.py#L102-L112 |
2,755 | BlueBrain/NeuroM | neurom/io/utils.py | load_neuron | def load_neuron(handle, reader=None):
'''Build section trees from an h5 or swc file'''
rdw = load_data(handle, reader)
if isinstance(handle, StringType):
name = os.path.splitext(os.path.basename(handle))[0]
else:
name = None
return FstNeuron(rdw, name) | python | def load_neuron(handle, reader=None):
'''Build section trees from an h5 or swc file'''
rdw = load_data(handle, reader)
if isinstance(handle, StringType):
name = os.path.splitext(os.path.basename(handle))[0]
else:
name = None
return FstNeuron(rdw, name) | [
"def",
"load_neuron",
"(",
"handle",
",",
"reader",
"=",
"None",
")",
":",
"rdw",
"=",
"load_data",
"(",
"handle",
",",
"reader",
")",
"if",
"isinstance",
"(",
"handle",
",",
"StringType",
")",
":",
"name",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"handle",
")",
")",
"[",
"0",
"]",
"else",
":",
"name",
"=",
"None",
"return",
"FstNeuron",
"(",
"rdw",
",",
"name",
")"
] | Build section trees from an h5 or swc file | [
"Build",
"section",
"trees",
"from",
"an",
"h5",
"or",
"swc",
"file"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/utils.py#L115-L122 |
2,756 | BlueBrain/NeuroM | neurom/io/utils.py | load_neurons | def load_neurons(neurons,
neuron_loader=load_neuron,
name=None,
population_class=Population,
ignored_exceptions=()):
'''Create a population object from all morphologies in a directory\
of from morphologies in a list of file names
Parameters:
neurons: directory path or list of neuron file paths
neuron_loader: function taking a filename and returning a neuron
population_class: class representing populations
name (str): optional name of population. By default 'Population' or\
filepath basename depending on whether neurons is list or\
directory path respectively.
Returns:
neuron population object
'''
if isinstance(neurons, (list, tuple)):
files = neurons
name = name if name is not None else 'Population'
elif isinstance(neurons, StringType):
files = get_files_by_path(neurons)
name = name if name is not None else os.path.basename(neurons)
ignored_exceptions = tuple(ignored_exceptions)
pop = []
for f in files:
try:
pop.append(neuron_loader(f))
except NeuroMError as e:
if isinstance(e, ignored_exceptions):
L.info('Ignoring exception "%s" for file %s',
e, os.path.basename(f))
continue
raise
return population_class(pop, name=name) | python | def load_neurons(neurons,
neuron_loader=load_neuron,
name=None,
population_class=Population,
ignored_exceptions=()):
'''Create a population object from all morphologies in a directory\
of from morphologies in a list of file names
Parameters:
neurons: directory path or list of neuron file paths
neuron_loader: function taking a filename and returning a neuron
population_class: class representing populations
name (str): optional name of population. By default 'Population' or\
filepath basename depending on whether neurons is list or\
directory path respectively.
Returns:
neuron population object
'''
if isinstance(neurons, (list, tuple)):
files = neurons
name = name if name is not None else 'Population'
elif isinstance(neurons, StringType):
files = get_files_by_path(neurons)
name = name if name is not None else os.path.basename(neurons)
ignored_exceptions = tuple(ignored_exceptions)
pop = []
for f in files:
try:
pop.append(neuron_loader(f))
except NeuroMError as e:
if isinstance(e, ignored_exceptions):
L.info('Ignoring exception "%s" for file %s',
e, os.path.basename(f))
continue
raise
return population_class(pop, name=name) | [
"def",
"load_neurons",
"(",
"neurons",
",",
"neuron_loader",
"=",
"load_neuron",
",",
"name",
"=",
"None",
",",
"population_class",
"=",
"Population",
",",
"ignored_exceptions",
"=",
"(",
")",
")",
":",
"if",
"isinstance",
"(",
"neurons",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"files",
"=",
"neurons",
"name",
"=",
"name",
"if",
"name",
"is",
"not",
"None",
"else",
"'Population'",
"elif",
"isinstance",
"(",
"neurons",
",",
"StringType",
")",
":",
"files",
"=",
"get_files_by_path",
"(",
"neurons",
")",
"name",
"=",
"name",
"if",
"name",
"is",
"not",
"None",
"else",
"os",
".",
"path",
".",
"basename",
"(",
"neurons",
")",
"ignored_exceptions",
"=",
"tuple",
"(",
"ignored_exceptions",
")",
"pop",
"=",
"[",
"]",
"for",
"f",
"in",
"files",
":",
"try",
":",
"pop",
".",
"append",
"(",
"neuron_loader",
"(",
"f",
")",
")",
"except",
"NeuroMError",
"as",
"e",
":",
"if",
"isinstance",
"(",
"e",
",",
"ignored_exceptions",
")",
":",
"L",
".",
"info",
"(",
"'Ignoring exception \"%s\" for file %s'",
",",
"e",
",",
"os",
".",
"path",
".",
"basename",
"(",
"f",
")",
")",
"continue",
"raise",
"return",
"population_class",
"(",
"pop",
",",
"name",
"=",
"name",
")"
] | Create a population object from all morphologies in a directory\
of from morphologies in a list of file names
Parameters:
neurons: directory path or list of neuron file paths
neuron_loader: function taking a filename and returning a neuron
population_class: class representing populations
name (str): optional name of population. By default 'Population' or\
filepath basename depending on whether neurons is list or\
directory path respectively.
Returns:
neuron population object | [
"Create",
"a",
"population",
"object",
"from",
"all",
"morphologies",
"in",
"a",
"directory",
"\\",
"of",
"from",
"morphologies",
"in",
"a",
"list",
"of",
"file",
"names"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/utils.py#L125-L164 |
2,757 | BlueBrain/NeuroM | neurom/io/utils.py | _get_file | def _get_file(handle):
'''Returns the filename of the file to read
If handle is a stream, a temp file is written on disk first
and its filename is returned'''
if not isinstance(handle, IOBase):
return handle
fd, temp_file = tempfile.mkstemp(str(uuid.uuid4()), prefix='neurom-')
os.close(fd)
with open(temp_file, 'w') as fd:
handle.seek(0)
shutil.copyfileobj(handle, fd)
return temp_file | python | def _get_file(handle):
'''Returns the filename of the file to read
If handle is a stream, a temp file is written on disk first
and its filename is returned'''
if not isinstance(handle, IOBase):
return handle
fd, temp_file = tempfile.mkstemp(str(uuid.uuid4()), prefix='neurom-')
os.close(fd)
with open(temp_file, 'w') as fd:
handle.seek(0)
shutil.copyfileobj(handle, fd)
return temp_file | [
"def",
"_get_file",
"(",
"handle",
")",
":",
"if",
"not",
"isinstance",
"(",
"handle",
",",
"IOBase",
")",
":",
"return",
"handle",
"fd",
",",
"temp_file",
"=",
"tempfile",
".",
"mkstemp",
"(",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
",",
"prefix",
"=",
"'neurom-'",
")",
"os",
".",
"close",
"(",
"fd",
")",
"with",
"open",
"(",
"temp_file",
",",
"'w'",
")",
"as",
"fd",
":",
"handle",
".",
"seek",
"(",
"0",
")",
"shutil",
".",
"copyfileobj",
"(",
"handle",
",",
"fd",
")",
"return",
"temp_file"
] | Returns the filename of the file to read
If handle is a stream, a temp file is written on disk first
and its filename is returned | [
"Returns",
"the",
"filename",
"of",
"the",
"file",
"to",
"read"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/utils.py#L167-L180 |
2,758 | BlueBrain/NeuroM | neurom/io/utils.py | load_data | def load_data(handle, reader=None):
'''Unpack data into a raw data wrapper'''
if not reader:
reader = os.path.splitext(handle)[1][1:].lower()
if reader not in _READERS:
raise NeuroMError('Do not have a loader for "%s" extension' % reader)
filename = _get_file(handle)
try:
return _READERS[reader](filename)
except Exception as e:
L.exception('Error reading file %s, using "%s" loader', filename, reader)
raise RawDataError('Error reading file %s:\n%s' % (filename, str(e))) | python | def load_data(handle, reader=None):
'''Unpack data into a raw data wrapper'''
if not reader:
reader = os.path.splitext(handle)[1][1:].lower()
if reader not in _READERS:
raise NeuroMError('Do not have a loader for "%s" extension' % reader)
filename = _get_file(handle)
try:
return _READERS[reader](filename)
except Exception as e:
L.exception('Error reading file %s, using "%s" loader', filename, reader)
raise RawDataError('Error reading file %s:\n%s' % (filename, str(e))) | [
"def",
"load_data",
"(",
"handle",
",",
"reader",
"=",
"None",
")",
":",
"if",
"not",
"reader",
":",
"reader",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"handle",
")",
"[",
"1",
"]",
"[",
"1",
":",
"]",
".",
"lower",
"(",
")",
"if",
"reader",
"not",
"in",
"_READERS",
":",
"raise",
"NeuroMError",
"(",
"'Do not have a loader for \"%s\" extension'",
"%",
"reader",
")",
"filename",
"=",
"_get_file",
"(",
"handle",
")",
"try",
":",
"return",
"_READERS",
"[",
"reader",
"]",
"(",
"filename",
")",
"except",
"Exception",
"as",
"e",
":",
"L",
".",
"exception",
"(",
"'Error reading file %s, using \"%s\" loader'",
",",
"filename",
",",
"reader",
")",
"raise",
"RawDataError",
"(",
"'Error reading file %s:\\n%s'",
"%",
"(",
"filename",
",",
"str",
"(",
"e",
")",
")",
")"
] | Unpack data into a raw data wrapper | [
"Unpack",
"data",
"into",
"a",
"raw",
"data",
"wrapper"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/utils.py#L183-L196 |
2,759 | BlueBrain/NeuroM | neurom/io/utils.py | _load_h5 | def _load_h5(filename):
'''Delay loading of h5py until it is needed'''
from neurom.io import hdf5
return hdf5.read(filename,
remove_duplicates=False,
data_wrapper=DataWrapper) | python | def _load_h5(filename):
'''Delay loading of h5py until it is needed'''
from neurom.io import hdf5
return hdf5.read(filename,
remove_duplicates=False,
data_wrapper=DataWrapper) | [
"def",
"_load_h5",
"(",
"filename",
")",
":",
"from",
"neurom",
".",
"io",
"import",
"hdf5",
"return",
"hdf5",
".",
"read",
"(",
"filename",
",",
"remove_duplicates",
"=",
"False",
",",
"data_wrapper",
"=",
"DataWrapper",
")"
] | Delay loading of h5py until it is needed | [
"Delay",
"loading",
"of",
"h5py",
"until",
"it",
"is",
"needed"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/utils.py#L199-L204 |
2,760 | BlueBrain/NeuroM | neurom/io/utils.py | NeuronLoader._filepath | def _filepath(self, name):
""" File path to `name` morphology file. """
if self.file_ext is None:
candidates = glob.glob(os.path.join(self.directory, name + ".*"))
try:
return next(filter(_is_morphology_file, candidates))
except StopIteration:
raise NeuroMError("Can not find morphology file for '%s' " % name)
else:
return os.path.join(self.directory, name + self.file_ext) | python | def _filepath(self, name):
""" File path to `name` morphology file. """
if self.file_ext is None:
candidates = glob.glob(os.path.join(self.directory, name + ".*"))
try:
return next(filter(_is_morphology_file, candidates))
except StopIteration:
raise NeuroMError("Can not find morphology file for '%s' " % name)
else:
return os.path.join(self.directory, name + self.file_ext) | [
"def",
"_filepath",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"file_ext",
"is",
"None",
":",
"candidates",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"directory",
",",
"name",
"+",
"\".*\"",
")",
")",
"try",
":",
"return",
"next",
"(",
"filter",
"(",
"_is_morphology_file",
",",
"candidates",
")",
")",
"except",
"StopIteration",
":",
"raise",
"NeuroMError",
"(",
"\"Can not find morphology file for '%s' \"",
"%",
"name",
")",
"else",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"directory",
",",
"name",
"+",
"self",
".",
"file_ext",
")"
] | File path to `name` morphology file. | [
"File",
"path",
"to",
"name",
"morphology",
"file",
"."
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/utils.py#L75-L84 |
2,761 | BlueBrain/NeuroM | neurom/viewer.py | draw | def draw(obj, mode='2d', **kwargs):
'''Draw a morphology object
Parameters:
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 mode in ('2d', 'dendrogram'):
fig, ax = common.get_figure()
else:
fig, ax = common.get_figure(params={'projection': '3d'})
if isinstance(obj, Neuron):
tag = 'neuron'
elif isinstance(obj, (Tree, 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:
raise NotDrawableError('No drawer for class %s, mode=%s' % (obj.__class__, mode))
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 | python | def draw(obj, mode='2d', **kwargs):
'''Draw a morphology object
Parameters:
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 mode in ('2d', 'dendrogram'):
fig, ax = common.get_figure()
else:
fig, ax = common.get_figure(params={'projection': '3d'})
if isinstance(obj, Neuron):
tag = 'neuron'
elif isinstance(obj, (Tree, 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:
raise NotDrawableError('No drawer for class %s, mode=%s' % (obj.__class__, mode))
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 | [
"def",
"draw",
"(",
"obj",
",",
"mode",
"=",
"'2d'",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"mode",
"not",
"in",
"MODES",
":",
"raise",
"InvalidDrawModeError",
"(",
"'Invalid drawing mode %s'",
"%",
"mode",
")",
"if",
"mode",
"in",
"(",
"'2d'",
",",
"'dendrogram'",
")",
":",
"fig",
",",
"ax",
"=",
"common",
".",
"get_figure",
"(",
")",
"else",
":",
"fig",
",",
"ax",
"=",
"common",
".",
"get_figure",
"(",
"params",
"=",
"{",
"'projection'",
":",
"'3d'",
"}",
")",
"if",
"isinstance",
"(",
"obj",
",",
"Neuron",
")",
":",
"tag",
"=",
"'neuron'",
"elif",
"isinstance",
"(",
"obj",
",",
"(",
"Tree",
",",
"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",
":",
"raise",
"NotDrawableError",
"(",
"'No drawer for class %s, mode=%s'",
"%",
"(",
"obj",
".",
"__class__",
",",
"mode",
")",
")",
"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"
] | Draw a morphology object
Parameters:
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') | [
"Draw",
"a",
"morphology",
"object"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/viewer.py#L77-L134 |
2,762 | BlueBrain/NeuroM | examples/histogram.py | population_feature_values | def population_feature_values(pops, feature):
'''Extracts feature values per population
'''
pops_feature_values = []
for pop in pops:
feature_values = [getattr(neu, 'get_' + feature)() for neu in pop.neurons]
# ugly hack to chain in case of list of lists
if any([isinstance(p, (list, np.ndarray)) for p in feature_values]):
feature_values = list(chain(*feature_values))
pops_feature_values.append(feature_values)
return pops_feature_values | python | def population_feature_values(pops, feature):
'''Extracts feature values per population
'''
pops_feature_values = []
for pop in pops:
feature_values = [getattr(neu, 'get_' + feature)() for neu in pop.neurons]
# ugly hack to chain in case of list of lists
if any([isinstance(p, (list, np.ndarray)) for p in feature_values]):
feature_values = list(chain(*feature_values))
pops_feature_values.append(feature_values)
return pops_feature_values | [
"def",
"population_feature_values",
"(",
"pops",
",",
"feature",
")",
":",
"pops_feature_values",
"=",
"[",
"]",
"for",
"pop",
"in",
"pops",
":",
"feature_values",
"=",
"[",
"getattr",
"(",
"neu",
",",
"'get_'",
"+",
"feature",
")",
"(",
")",
"for",
"neu",
"in",
"pop",
".",
"neurons",
"]",
"# ugly hack to chain in case of list of lists",
"if",
"any",
"(",
"[",
"isinstance",
"(",
"p",
",",
"(",
"list",
",",
"np",
".",
"ndarray",
")",
")",
"for",
"p",
"in",
"feature_values",
"]",
")",
":",
"feature_values",
"=",
"list",
"(",
"chain",
"(",
"*",
"feature_values",
")",
")",
"pops_feature_values",
".",
"append",
"(",
"feature_values",
")",
"return",
"pops_feature_values"
] | Extracts feature values per population | [
"Extracts",
"feature",
"values",
"per",
"population"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/examples/histogram.py#L96-L112 |
2,763 | BlueBrain/NeuroM | examples/section_ids.py | get_segment | def get_segment(neuron, section_id, segment_id):
'''Get a segment given a section and segment id
Returns:
array of two [x, y, z, r] points defining segment
'''
sec = neuron.sections[section_id]
return sec.points[segment_id:segment_id + 2][:, COLS.XYZR] | python | def get_segment(neuron, section_id, segment_id):
'''Get a segment given a section and segment id
Returns:
array of two [x, y, z, r] points defining segment
'''
sec = neuron.sections[section_id]
return sec.points[segment_id:segment_id + 2][:, COLS.XYZR] | [
"def",
"get_segment",
"(",
"neuron",
",",
"section_id",
",",
"segment_id",
")",
":",
"sec",
"=",
"neuron",
".",
"sections",
"[",
"section_id",
"]",
"return",
"sec",
".",
"points",
"[",
"segment_id",
":",
"segment_id",
"+",
"2",
"]",
"[",
":",
",",
"COLS",
".",
"XYZR",
"]"
] | Get a segment given a section and segment id
Returns:
array of two [x, y, z, r] points defining segment | [
"Get",
"a",
"segment",
"given",
"a",
"section",
"and",
"segment",
"id"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/examples/section_ids.py#L37-L44 |
2,764 | BlueBrain/NeuroM | examples/extract_distribution.py | extract_data | 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) | python | 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) | [
"def",
"extract_data",
"(",
"data_path",
",",
"feature",
")",
":",
"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",
")"
] | 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. | [
"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",
"."
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/examples/extract_distribution.py#L59-L70 |
2,765 | BlueBrain/NeuroM | neurom/fst/_bifurcationfunc.py | bifurcation_partition | def bifurcation_partition(bif_point):
'''Calculate the partition at a bifurcation point
We first ensure that the input point has only two children.
The number of nodes in each child tree is counted. The partition is
defined as the ratio of the largest number to the smallest number.'''
assert len(bif_point.children) == 2, 'A bifurcation point must have exactly 2 children'
n = float(sum(1 for _ in bif_point.children[0].ipreorder()))
m = float(sum(1 for _ in bif_point.children[1].ipreorder()))
return max(n, m) / min(n, m) | python | def bifurcation_partition(bif_point):
'''Calculate the partition at a bifurcation point
We first ensure that the input point has only two children.
The number of nodes in each child tree is counted. The partition is
defined as the ratio of the largest number to the smallest number.'''
assert len(bif_point.children) == 2, 'A bifurcation point must have exactly 2 children'
n = float(sum(1 for _ in bif_point.children[0].ipreorder()))
m = float(sum(1 for _ in bif_point.children[1].ipreorder()))
return max(n, m) / min(n, m) | [
"def",
"bifurcation_partition",
"(",
"bif_point",
")",
":",
"assert",
"len",
"(",
"bif_point",
".",
"children",
")",
"==",
"2",
",",
"'A bifurcation point must have exactly 2 children'",
"n",
"=",
"float",
"(",
"sum",
"(",
"1",
"for",
"_",
"in",
"bif_point",
".",
"children",
"[",
"0",
"]",
".",
"ipreorder",
"(",
")",
")",
")",
"m",
"=",
"float",
"(",
"sum",
"(",
"1",
"for",
"_",
"in",
"bif_point",
".",
"children",
"[",
"1",
"]",
".",
"ipreorder",
"(",
")",
")",
")",
"return",
"max",
"(",
"n",
",",
"m",
")",
"/",
"min",
"(",
"n",
",",
"m",
")"
] | Calculate the partition at a bifurcation point
We first ensure that the input point has only two children.
The number of nodes in each child tree is counted. The partition is
defined as the ratio of the largest number to the smallest number. | [
"Calculate",
"the",
"partition",
"at",
"a",
"bifurcation",
"point"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_bifurcationfunc.py#L80-L91 |
2,766 | BlueBrain/NeuroM | neurom/fst/_bifurcationfunc.py | partition_pair | def partition_pair(bif_point):
'''Calculate the partition pairs at a bifurcation point
The number of nodes in each child tree is counted. The partition
pairs is the number of bifurcations in the two daughter subtrees
at each branch point.'''
n = float(sum(1 for _ in bif_point.children[0].ipreorder()))
m = float(sum(1 for _ in bif_point.children[1].ipreorder()))
return (n, m) | python | def partition_pair(bif_point):
'''Calculate the partition pairs at a bifurcation point
The number of nodes in each child tree is counted. The partition
pairs is the number of bifurcations in the two daughter subtrees
at each branch point.'''
n = float(sum(1 for _ in bif_point.children[0].ipreorder()))
m = float(sum(1 for _ in bif_point.children[1].ipreorder()))
return (n, m) | [
"def",
"partition_pair",
"(",
"bif_point",
")",
":",
"n",
"=",
"float",
"(",
"sum",
"(",
"1",
"for",
"_",
"in",
"bif_point",
".",
"children",
"[",
"0",
"]",
".",
"ipreorder",
"(",
")",
")",
")",
"m",
"=",
"float",
"(",
"sum",
"(",
"1",
"for",
"_",
"in",
"bif_point",
".",
"children",
"[",
"1",
"]",
".",
"ipreorder",
"(",
")",
")",
")",
"return",
"(",
"n",
",",
"m",
")"
] | Calculate the partition pairs at a bifurcation point
The number of nodes in each child tree is counted. The partition
pairs is the number of bifurcations in the two daughter subtrees
at each branch point. | [
"Calculate",
"the",
"partition",
"pairs",
"at",
"a",
"bifurcation",
"point"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_bifurcationfunc.py#L110-L118 |
2,767 | BlueBrain/NeuroM | neurom/io/neurolucida.py | _match_section | def _match_section(section, match):
'''checks whether the `type` of section is in the `match` dictionary
Works around the unknown ordering of s-expressions in each section.
For instance, the `type` is the 3-rd one in for CellBodies
("CellBody"
(Color Yellow)
(CellBody)
(Set "cell10")
)
Returns:
value associated with match[section_type], None if no match
'''
# TODO: rewrite this so it is more clear, and handles sets & dictionaries for matching
for i in range(5):
if i >= len(section):
return None
if isinstance(section[i], StringType) and section[i] in match:
return match[section[i]]
return None | python | def _match_section(section, match):
'''checks whether the `type` of section is in the `match` dictionary
Works around the unknown ordering of s-expressions in each section.
For instance, the `type` is the 3-rd one in for CellBodies
("CellBody"
(Color Yellow)
(CellBody)
(Set "cell10")
)
Returns:
value associated with match[section_type], None if no match
'''
# TODO: rewrite this so it is more clear, and handles sets & dictionaries for matching
for i in range(5):
if i >= len(section):
return None
if isinstance(section[i], StringType) and section[i] in match:
return match[section[i]]
return None | [
"def",
"_match_section",
"(",
"section",
",",
"match",
")",
":",
"# TODO: rewrite this so it is more clear, and handles sets & dictionaries for matching",
"for",
"i",
"in",
"range",
"(",
"5",
")",
":",
"if",
"i",
">=",
"len",
"(",
"section",
")",
":",
"return",
"None",
"if",
"isinstance",
"(",
"section",
"[",
"i",
"]",
",",
"StringType",
")",
"and",
"section",
"[",
"i",
"]",
"in",
"match",
":",
"return",
"match",
"[",
"section",
"[",
"i",
"]",
"]",
"return",
"None"
] | checks whether the `type` of section is in the `match` dictionary
Works around the unknown ordering of s-expressions in each section.
For instance, the `type` is the 3-rd one in for CellBodies
("CellBody"
(Color Yellow)
(CellBody)
(Set "cell10")
)
Returns:
value associated with match[section_type], None if no match | [
"checks",
"whether",
"the",
"type",
"of",
"section",
"is",
"in",
"the",
"match",
"dictionary"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/neurolucida.py#L64-L84 |
2,768 | BlueBrain/NeuroM | neurom/io/neurolucida.py | _parse_section | def _parse_section(token_iter):
'''take a stream of tokens, and create the tree structure that is defined
by the s-expressions
'''
sexp = []
for token in token_iter:
if token == '(':
new_sexp = _parse_section(token_iter)
if not _match_section(new_sexp, UNWANTED_SECTIONS):
sexp.append(new_sexp)
elif token == ')':
return sexp
else:
sexp.append(token)
return sexp | python | def _parse_section(token_iter):
'''take a stream of tokens, and create the tree structure that is defined
by the s-expressions
'''
sexp = []
for token in token_iter:
if token == '(':
new_sexp = _parse_section(token_iter)
if not _match_section(new_sexp, UNWANTED_SECTIONS):
sexp.append(new_sexp)
elif token == ')':
return sexp
else:
sexp.append(token)
return sexp | [
"def",
"_parse_section",
"(",
"token_iter",
")",
":",
"sexp",
"=",
"[",
"]",
"for",
"token",
"in",
"token_iter",
":",
"if",
"token",
"==",
"'('",
":",
"new_sexp",
"=",
"_parse_section",
"(",
"token_iter",
")",
"if",
"not",
"_match_section",
"(",
"new_sexp",
",",
"UNWANTED_SECTIONS",
")",
":",
"sexp",
".",
"append",
"(",
"new_sexp",
")",
"elif",
"token",
"==",
"')'",
":",
"return",
"sexp",
"else",
":",
"sexp",
".",
"append",
"(",
"token",
")",
"return",
"sexp"
] | take a stream of tokens, and create the tree structure that is defined
by the s-expressions | [
"take",
"a",
"stream",
"of",
"tokens",
"and",
"create",
"the",
"tree",
"structure",
"that",
"is",
"defined",
"by",
"the",
"s",
"-",
"expressions"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/neurolucida.py#L114-L128 |
2,769 | BlueBrain/NeuroM | neurom/io/neurolucida.py | _parse_sections | def _parse_sections(morph_fd):
'''returns array of all the sections that exist
The format is nested lists that correspond to the s-expressions
'''
sections = []
token_iter = _get_tokens(morph_fd)
for token in token_iter:
if token == '(': # find top-level sections
section = _parse_section(token_iter)
if not _match_section(section, UNWANTED_SECTIONS):
sections.append(section)
return sections | python | def _parse_sections(morph_fd):
'''returns array of all the sections that exist
The format is nested lists that correspond to the s-expressions
'''
sections = []
token_iter = _get_tokens(morph_fd)
for token in token_iter:
if token == '(': # find top-level sections
section = _parse_section(token_iter)
if not _match_section(section, UNWANTED_SECTIONS):
sections.append(section)
return sections | [
"def",
"_parse_sections",
"(",
"morph_fd",
")",
":",
"sections",
"=",
"[",
"]",
"token_iter",
"=",
"_get_tokens",
"(",
"morph_fd",
")",
"for",
"token",
"in",
"token_iter",
":",
"if",
"token",
"==",
"'('",
":",
"# find top-level sections",
"section",
"=",
"_parse_section",
"(",
"token_iter",
")",
"if",
"not",
"_match_section",
"(",
"section",
",",
"UNWANTED_SECTIONS",
")",
":",
"sections",
".",
"append",
"(",
"section",
")",
"return",
"sections"
] | returns array of all the sections that exist
The format is nested lists that correspond to the s-expressions | [
"returns",
"array",
"of",
"all",
"the",
"sections",
"that",
"exist"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/neurolucida.py#L131-L143 |
2,770 | BlueBrain/NeuroM | neurom/io/neurolucida.py | _flatten_subsection | def _flatten_subsection(subsection, _type, offset, parent):
'''Flatten a subsection from its nested version
Args:
subsection: Nested subsection as produced by _parse_section, except one level in
_type: type of section, ie: AXON, etc
parent: first element has this as it's parent
offset: position in the final array of the first element
Returns:
Generator of values corresponding to [X, Y, Z, R, TYPE, ID, PARENT_ID]
'''
for row in subsection:
# TODO: Figure out what these correspond to in neurolucida
if row in ('Low', 'Generated', 'High', ):
continue
elif isinstance(row[0], StringType):
if len(row) in (4, 5, ):
if len(row) == 5:
assert row[4][0] == 'S', \
'Only known usage of a fifth member is Sn, found: %s' % row[4][0]
yield (float(row[0]), float(row[1]), float(row[2]), float(row[3]) / 2.,
_type, offset, parent)
parent = offset
offset += 1
elif isinstance(row[0], list):
split_parent = offset - 1
start_offset = 0
slices = []
start = 0
for i, value in enumerate(row):
if value == '|':
slices.append(slice(start + start_offset, i))
start = i + 1
slices.append(slice(start + start_offset, len(row)))
for split_slice in slices:
for _row in _flatten_subsection(row[split_slice], _type, offset,
split_parent):
offset += 1
yield _row | python | def _flatten_subsection(subsection, _type, offset, parent):
'''Flatten a subsection from its nested version
Args:
subsection: Nested subsection as produced by _parse_section, except one level in
_type: type of section, ie: AXON, etc
parent: first element has this as it's parent
offset: position in the final array of the first element
Returns:
Generator of values corresponding to [X, Y, Z, R, TYPE, ID, PARENT_ID]
'''
for row in subsection:
# TODO: Figure out what these correspond to in neurolucida
if row in ('Low', 'Generated', 'High', ):
continue
elif isinstance(row[0], StringType):
if len(row) in (4, 5, ):
if len(row) == 5:
assert row[4][0] == 'S', \
'Only known usage of a fifth member is Sn, found: %s' % row[4][0]
yield (float(row[0]), float(row[1]), float(row[2]), float(row[3]) / 2.,
_type, offset, parent)
parent = offset
offset += 1
elif isinstance(row[0], list):
split_parent = offset - 1
start_offset = 0
slices = []
start = 0
for i, value in enumerate(row):
if value == '|':
slices.append(slice(start + start_offset, i))
start = i + 1
slices.append(slice(start + start_offset, len(row)))
for split_slice in slices:
for _row in _flatten_subsection(row[split_slice], _type, offset,
split_parent):
offset += 1
yield _row | [
"def",
"_flatten_subsection",
"(",
"subsection",
",",
"_type",
",",
"offset",
",",
"parent",
")",
":",
"for",
"row",
"in",
"subsection",
":",
"# TODO: Figure out what these correspond to in neurolucida",
"if",
"row",
"in",
"(",
"'Low'",
",",
"'Generated'",
",",
"'High'",
",",
")",
":",
"continue",
"elif",
"isinstance",
"(",
"row",
"[",
"0",
"]",
",",
"StringType",
")",
":",
"if",
"len",
"(",
"row",
")",
"in",
"(",
"4",
",",
"5",
",",
")",
":",
"if",
"len",
"(",
"row",
")",
"==",
"5",
":",
"assert",
"row",
"[",
"4",
"]",
"[",
"0",
"]",
"==",
"'S'",
",",
"'Only known usage of a fifth member is Sn, found: %s'",
"%",
"row",
"[",
"4",
"]",
"[",
"0",
"]",
"yield",
"(",
"float",
"(",
"row",
"[",
"0",
"]",
")",
",",
"float",
"(",
"row",
"[",
"1",
"]",
")",
",",
"float",
"(",
"row",
"[",
"2",
"]",
")",
",",
"float",
"(",
"row",
"[",
"3",
"]",
")",
"/",
"2.",
",",
"_type",
",",
"offset",
",",
"parent",
")",
"parent",
"=",
"offset",
"offset",
"+=",
"1",
"elif",
"isinstance",
"(",
"row",
"[",
"0",
"]",
",",
"list",
")",
":",
"split_parent",
"=",
"offset",
"-",
"1",
"start_offset",
"=",
"0",
"slices",
"=",
"[",
"]",
"start",
"=",
"0",
"for",
"i",
",",
"value",
"in",
"enumerate",
"(",
"row",
")",
":",
"if",
"value",
"==",
"'|'",
":",
"slices",
".",
"append",
"(",
"slice",
"(",
"start",
"+",
"start_offset",
",",
"i",
")",
")",
"start",
"=",
"i",
"+",
"1",
"slices",
".",
"append",
"(",
"slice",
"(",
"start",
"+",
"start_offset",
",",
"len",
"(",
"row",
")",
")",
")",
"for",
"split_slice",
"in",
"slices",
":",
"for",
"_row",
"in",
"_flatten_subsection",
"(",
"row",
"[",
"split_slice",
"]",
",",
"_type",
",",
"offset",
",",
"split_parent",
")",
":",
"offset",
"+=",
"1",
"yield",
"_row"
] | Flatten a subsection from its nested version
Args:
subsection: Nested subsection as produced by _parse_section, except one level in
_type: type of section, ie: AXON, etc
parent: first element has this as it's parent
offset: position in the final array of the first element
Returns:
Generator of values corresponding to [X, Y, Z, R, TYPE, ID, PARENT_ID] | [
"Flatten",
"a",
"subsection",
"from",
"its",
"nested",
"version"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/neurolucida.py#L146-L187 |
2,771 | BlueBrain/NeuroM | neurom/io/neurolucida.py | _extract_section | def _extract_section(section):
'''Find top level sections, and get their flat contents, and append them all
Returns a numpy array with the row format:
[X, Y, Z, R, TYPE, ID, PARENT_ID]
Note: PARENT_ID starts at -1 for soma and 0 for neurites
'''
# sections with only one element will be skipped,
if len(section) == 1:
assert section[0] == 'Sections', \
('Only known usage of a single Section content is "Sections", found %s' %
section[0])
return None
# try and detect type
_type = WANTED_SECTIONS.get(section[0][0], None)
start = 1
# CellBody often has [['"CellBody"'], ['CellBody'] as its first two elements
if _type is None:
_type = WANTED_SECTIONS.get(section[1][0], None)
if _type is None: # can't determine the type
return None
start = 2
parent = -1 if _type == POINT_TYPE.SOMA else 0
subsection_iter = _flatten_subsection(section[start:], _type, offset=0,
parent=parent)
ret = np.array([row for row in subsection_iter])
return ret | python | def _extract_section(section):
'''Find top level sections, and get their flat contents, and append them all
Returns a numpy array with the row format:
[X, Y, Z, R, TYPE, ID, PARENT_ID]
Note: PARENT_ID starts at -1 for soma and 0 for neurites
'''
# sections with only one element will be skipped,
if len(section) == 1:
assert section[0] == 'Sections', \
('Only known usage of a single Section content is "Sections", found %s' %
section[0])
return None
# try and detect type
_type = WANTED_SECTIONS.get(section[0][0], None)
start = 1
# CellBody often has [['"CellBody"'], ['CellBody'] as its first two elements
if _type is None:
_type = WANTED_SECTIONS.get(section[1][0], None)
if _type is None: # can't determine the type
return None
start = 2
parent = -1 if _type == POINT_TYPE.SOMA else 0
subsection_iter = _flatten_subsection(section[start:], _type, offset=0,
parent=parent)
ret = np.array([row for row in subsection_iter])
return ret | [
"def",
"_extract_section",
"(",
"section",
")",
":",
"# sections with only one element will be skipped,",
"if",
"len",
"(",
"section",
")",
"==",
"1",
":",
"assert",
"section",
"[",
"0",
"]",
"==",
"'Sections'",
",",
"(",
"'Only known usage of a single Section content is \"Sections\", found %s'",
"%",
"section",
"[",
"0",
"]",
")",
"return",
"None",
"# try and detect type",
"_type",
"=",
"WANTED_SECTIONS",
".",
"get",
"(",
"section",
"[",
"0",
"]",
"[",
"0",
"]",
",",
"None",
")",
"start",
"=",
"1",
"# CellBody often has [['\"CellBody\"'], ['CellBody'] as its first two elements",
"if",
"_type",
"is",
"None",
":",
"_type",
"=",
"WANTED_SECTIONS",
".",
"get",
"(",
"section",
"[",
"1",
"]",
"[",
"0",
"]",
",",
"None",
")",
"if",
"_type",
"is",
"None",
":",
"# can't determine the type",
"return",
"None",
"start",
"=",
"2",
"parent",
"=",
"-",
"1",
"if",
"_type",
"==",
"POINT_TYPE",
".",
"SOMA",
"else",
"0",
"subsection_iter",
"=",
"_flatten_subsection",
"(",
"section",
"[",
"start",
":",
"]",
",",
"_type",
",",
"offset",
"=",
"0",
",",
"parent",
"=",
"parent",
")",
"ret",
"=",
"np",
".",
"array",
"(",
"[",
"row",
"for",
"row",
"in",
"subsection_iter",
"]",
")",
"return",
"ret"
] | Find top level sections, and get their flat contents, and append them all
Returns a numpy array with the row format:
[X, Y, Z, R, TYPE, ID, PARENT_ID]
Note: PARENT_ID starts at -1 for soma and 0 for neurites | [
"Find",
"top",
"level",
"sections",
"and",
"get",
"their",
"flat",
"contents",
"and",
"append",
"them",
"all"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/neurolucida.py#L190-L222 |
2,772 | BlueBrain/NeuroM | neurom/io/neurolucida.py | _sections_to_raw_data | def _sections_to_raw_data(sections):
'''convert list of sections into the `raw_data` format used in neurom
This finds the soma, and attaches the neurites
'''
soma = None
neurites = []
for section in sections:
neurite = _extract_section(section)
if neurite is None:
continue
elif neurite[0][COLS.TYPE] == POINT_TYPE.SOMA:
assert soma is None, 'Multiple somas defined in file'
soma = neurite
else:
neurites.append(neurite)
assert soma is not None, 'Missing CellBody element (ie. soma)'
total_length = len(soma) + sum(len(neurite) for neurite in neurites)
ret = np.zeros((total_length, 7,), dtype=np.float64)
pos = len(soma)
ret[0:pos, :] = soma
for neurite in neurites:
end = pos + len(neurite)
ret[pos:end, :] = neurite
ret[pos:end, COLS.P] += pos
ret[pos:end, COLS.ID] += pos
# TODO: attach the neurite at the closest point on the soma
ret[pos, COLS.P] = len(soma) - 1
pos = end
return ret | python | def _sections_to_raw_data(sections):
'''convert list of sections into the `raw_data` format used in neurom
This finds the soma, and attaches the neurites
'''
soma = None
neurites = []
for section in sections:
neurite = _extract_section(section)
if neurite is None:
continue
elif neurite[0][COLS.TYPE] == POINT_TYPE.SOMA:
assert soma is None, 'Multiple somas defined in file'
soma = neurite
else:
neurites.append(neurite)
assert soma is not None, 'Missing CellBody element (ie. soma)'
total_length = len(soma) + sum(len(neurite) for neurite in neurites)
ret = np.zeros((total_length, 7,), dtype=np.float64)
pos = len(soma)
ret[0:pos, :] = soma
for neurite in neurites:
end = pos + len(neurite)
ret[pos:end, :] = neurite
ret[pos:end, COLS.P] += pos
ret[pos:end, COLS.ID] += pos
# TODO: attach the neurite at the closest point on the soma
ret[pos, COLS.P] = len(soma) - 1
pos = end
return ret | [
"def",
"_sections_to_raw_data",
"(",
"sections",
")",
":",
"soma",
"=",
"None",
"neurites",
"=",
"[",
"]",
"for",
"section",
"in",
"sections",
":",
"neurite",
"=",
"_extract_section",
"(",
"section",
")",
"if",
"neurite",
"is",
"None",
":",
"continue",
"elif",
"neurite",
"[",
"0",
"]",
"[",
"COLS",
".",
"TYPE",
"]",
"==",
"POINT_TYPE",
".",
"SOMA",
":",
"assert",
"soma",
"is",
"None",
",",
"'Multiple somas defined in file'",
"soma",
"=",
"neurite",
"else",
":",
"neurites",
".",
"append",
"(",
"neurite",
")",
"assert",
"soma",
"is",
"not",
"None",
",",
"'Missing CellBody element (ie. soma)'",
"total_length",
"=",
"len",
"(",
"soma",
")",
"+",
"sum",
"(",
"len",
"(",
"neurite",
")",
"for",
"neurite",
"in",
"neurites",
")",
"ret",
"=",
"np",
".",
"zeros",
"(",
"(",
"total_length",
",",
"7",
",",
")",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"pos",
"=",
"len",
"(",
"soma",
")",
"ret",
"[",
"0",
":",
"pos",
",",
":",
"]",
"=",
"soma",
"for",
"neurite",
"in",
"neurites",
":",
"end",
"=",
"pos",
"+",
"len",
"(",
"neurite",
")",
"ret",
"[",
"pos",
":",
"end",
",",
":",
"]",
"=",
"neurite",
"ret",
"[",
"pos",
":",
"end",
",",
"COLS",
".",
"P",
"]",
"+=",
"pos",
"ret",
"[",
"pos",
":",
"end",
",",
"COLS",
".",
"ID",
"]",
"+=",
"pos",
"# TODO: attach the neurite at the closest point on the soma",
"ret",
"[",
"pos",
",",
"COLS",
".",
"P",
"]",
"=",
"len",
"(",
"soma",
")",
"-",
"1",
"pos",
"=",
"end",
"return",
"ret"
] | convert list of sections into the `raw_data` format used in neurom
This finds the soma, and attaches the neurites | [
"convert",
"list",
"of",
"sections",
"into",
"the",
"raw_data",
"format",
"used",
"in",
"neurom"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/neurolucida.py#L225-L257 |
2,773 | BlueBrain/NeuroM | neurom/io/neurolucida.py | read | def read(morph_file, data_wrapper=DataWrapper):
'''return a 'raw_data' np.array with the full neuron, and the format of the file
suitable to be wrapped by DataWrapper
'''
msg = ('This is an experimental reader. '
'There are no guarantees regarding ability to parse '
'Neurolucida .asc files or correctness of output.')
warnings.warn(msg)
L.warning(msg)
with open(morph_file, encoding='utf-8', errors='replace') as morph_fd:
sections = _parse_sections(morph_fd)
raw_data = _sections_to_raw_data(sections)
return data_wrapper(raw_data, 'NL-ASCII') | python | def read(morph_file, data_wrapper=DataWrapper):
'''return a 'raw_data' np.array with the full neuron, and the format of the file
suitable to be wrapped by DataWrapper
'''
msg = ('This is an experimental reader. '
'There are no guarantees regarding ability to parse '
'Neurolucida .asc files or correctness of output.')
warnings.warn(msg)
L.warning(msg)
with open(morph_file, encoding='utf-8', errors='replace') as morph_fd:
sections = _parse_sections(morph_fd)
raw_data = _sections_to_raw_data(sections)
return data_wrapper(raw_data, 'NL-ASCII') | [
"def",
"read",
"(",
"morph_file",
",",
"data_wrapper",
"=",
"DataWrapper",
")",
":",
"msg",
"=",
"(",
"'This is an experimental reader. '",
"'There are no guarantees regarding ability to parse '",
"'Neurolucida .asc files or correctness of output.'",
")",
"warnings",
".",
"warn",
"(",
"msg",
")",
"L",
".",
"warning",
"(",
"msg",
")",
"with",
"open",
"(",
"morph_file",
",",
"encoding",
"=",
"'utf-8'",
",",
"errors",
"=",
"'replace'",
")",
"as",
"morph_fd",
":",
"sections",
"=",
"_parse_sections",
"(",
"morph_fd",
")",
"raw_data",
"=",
"_sections_to_raw_data",
"(",
"sections",
")",
"return",
"data_wrapper",
"(",
"raw_data",
",",
"'NL-ASCII'",
")"
] | return a 'raw_data' np.array with the full neuron, and the format of the file
suitable to be wrapped by DataWrapper | [
"return",
"a",
"raw_data",
"np",
".",
"array",
"with",
"the",
"full",
"neuron",
"and",
"the",
"format",
"of",
"the",
"file",
"suitable",
"to",
"be",
"wrapped",
"by",
"DataWrapper"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/neurolucida.py#L260-L275 |
2,774 | BlueBrain/NeuroM | examples/get_features.py | stats | def stats(data):
'''Dictionary with summary stats for data
Returns:
dicitonary with length, mean, sum, standard deviation,\
min and max of data
'''
return {'len': len(data),
'mean': np.mean(data),
'sum': np.sum(data),
'std': np.std(data),
'min': np.min(data),
'max': np.max(data)} | python | def stats(data):
'''Dictionary with summary stats for data
Returns:
dicitonary with length, mean, sum, standard deviation,\
min and max of data
'''
return {'len': len(data),
'mean': np.mean(data),
'sum': np.sum(data),
'std': np.std(data),
'min': np.min(data),
'max': np.max(data)} | [
"def",
"stats",
"(",
"data",
")",
":",
"return",
"{",
"'len'",
":",
"len",
"(",
"data",
")",
",",
"'mean'",
":",
"np",
".",
"mean",
"(",
"data",
")",
",",
"'sum'",
":",
"np",
".",
"sum",
"(",
"data",
")",
",",
"'std'",
":",
"np",
".",
"std",
"(",
"data",
")",
",",
"'min'",
":",
"np",
".",
"min",
"(",
"data",
")",
",",
"'max'",
":",
"np",
".",
"max",
"(",
"data",
")",
"}"
] | Dictionary with summary stats for data
Returns:
dicitonary with length, mean, sum, standard deviation,\
min and max of data | [
"Dictionary",
"with",
"summary",
"stats",
"for",
"data"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/examples/get_features.py#L43-L55 |
2,775 | BlueBrain/NeuroM | neurom/apps/__init__.py | get_config | def get_config(config, default_config):
'''Load configuration from file if in config, else use default'''
if not config:
logging.warning('Using default config: %s', default_config)
config = default_config
try:
with open(config, 'r') as config_file:
return yaml.load(config_file)
except (yaml.reader.ReaderError,
yaml.parser.ParserError,
yaml.scanner.ScannerError) as e:
raise ConfigError('Invalid yaml file: \n %s' % str(e)) | python | def get_config(config, default_config):
'''Load configuration from file if in config, else use default'''
if not config:
logging.warning('Using default config: %s', default_config)
config = default_config
try:
with open(config, 'r') as config_file:
return yaml.load(config_file)
except (yaml.reader.ReaderError,
yaml.parser.ParserError,
yaml.scanner.ScannerError) as e:
raise ConfigError('Invalid yaml file: \n %s' % str(e)) | [
"def",
"get_config",
"(",
"config",
",",
"default_config",
")",
":",
"if",
"not",
"config",
":",
"logging",
".",
"warning",
"(",
"'Using default config: %s'",
",",
"default_config",
")",
"config",
"=",
"default_config",
"try",
":",
"with",
"open",
"(",
"config",
",",
"'r'",
")",
"as",
"config_file",
":",
"return",
"yaml",
".",
"load",
"(",
"config_file",
")",
"except",
"(",
"yaml",
".",
"reader",
".",
"ReaderError",
",",
"yaml",
".",
"parser",
".",
"ParserError",
",",
"yaml",
".",
"scanner",
".",
"ScannerError",
")",
"as",
"e",
":",
"raise",
"ConfigError",
"(",
"'Invalid yaml file: \\n %s'",
"%",
"str",
"(",
"e",
")",
")"
] | Load configuration from file if in config, else use default | [
"Load",
"configuration",
"from",
"file",
"if",
"in",
"config",
"else",
"use",
"default"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/apps/__init__.py#L36-L48 |
2,776 | BlueBrain/NeuroM | neurom/fst/_neuronfunc.py | soma_surface_area | def soma_surface_area(nrn, neurite_type=NeuriteType.soma):
'''Get the surface area of a neuron's soma.
Note:
The surface area is calculated by assuming the soma is spherical.
'''
assert neurite_type == NeuriteType.soma, 'Neurite type must be soma'
return 4 * math.pi * nrn.soma.radius ** 2 | python | def soma_surface_area(nrn, neurite_type=NeuriteType.soma):
'''Get the surface area of a neuron's soma.
Note:
The surface area is calculated by assuming the soma is spherical.
'''
assert neurite_type == NeuriteType.soma, 'Neurite type must be soma'
return 4 * math.pi * nrn.soma.radius ** 2 | [
"def",
"soma_surface_area",
"(",
"nrn",
",",
"neurite_type",
"=",
"NeuriteType",
".",
"soma",
")",
":",
"assert",
"neurite_type",
"==",
"NeuriteType",
".",
"soma",
",",
"'Neurite type must be soma'",
"return",
"4",
"*",
"math",
".",
"pi",
"*",
"nrn",
".",
"soma",
".",
"radius",
"**",
"2"
] | Get the surface area of a neuron's soma.
Note:
The surface area is calculated by assuming the soma is spherical. | [
"Get",
"the",
"surface",
"area",
"of",
"a",
"neuron",
"s",
"soma",
"."
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuronfunc.py#L46-L53 |
2,777 | BlueBrain/NeuroM | neurom/fst/_neuronfunc.py | soma_surface_areas | def soma_surface_areas(nrn_pop, neurite_type=NeuriteType.soma):
'''Get the surface areas of the somata in a population of neurons
Note:
The surface area is calculated by assuming the soma is spherical.
Note:
If a single neuron is passed, a single element list with the surface
area of its soma member is returned.
'''
nrns = neuron_population(nrn_pop)
assert neurite_type == NeuriteType.soma, 'Neurite type must be soma'
return [soma_surface_area(n) for n in nrns] | python | def soma_surface_areas(nrn_pop, neurite_type=NeuriteType.soma):
'''Get the surface areas of the somata in a population of neurons
Note:
The surface area is calculated by assuming the soma is spherical.
Note:
If a single neuron is passed, a single element list with the surface
area of its soma member is returned.
'''
nrns = neuron_population(nrn_pop)
assert neurite_type == NeuriteType.soma, 'Neurite type must be soma'
return [soma_surface_area(n) for n in nrns] | [
"def",
"soma_surface_areas",
"(",
"nrn_pop",
",",
"neurite_type",
"=",
"NeuriteType",
".",
"soma",
")",
":",
"nrns",
"=",
"neuron_population",
"(",
"nrn_pop",
")",
"assert",
"neurite_type",
"==",
"NeuriteType",
".",
"soma",
",",
"'Neurite type must be soma'",
"return",
"[",
"soma_surface_area",
"(",
"n",
")",
"for",
"n",
"in",
"nrns",
"]"
] | Get the surface areas of the somata in a population of neurons
Note:
The surface area is calculated by assuming the soma is spherical.
Note:
If a single neuron is passed, a single element list with the surface
area of its soma member is returned. | [
"Get",
"the",
"surface",
"areas",
"of",
"the",
"somata",
"in",
"a",
"population",
"of",
"neurons"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuronfunc.py#L56-L67 |
2,778 | BlueBrain/NeuroM | neurom/fst/_neuronfunc.py | soma_radii | def soma_radii(nrn_pop, neurite_type=NeuriteType.soma):
''' Get the radii of the somata of a population of neurons
Note:
If a single neuron is passed, a single element list with the
radius of its soma member is returned.
'''
assert neurite_type == NeuriteType.soma, 'Neurite type must be soma'
nrns = neuron_population(nrn_pop)
return [n.soma.radius for n in nrns] | python | def soma_radii(nrn_pop, neurite_type=NeuriteType.soma):
''' Get the radii of the somata of a population of neurons
Note:
If a single neuron is passed, a single element list with the
radius of its soma member is returned.
'''
assert neurite_type == NeuriteType.soma, 'Neurite type must be soma'
nrns = neuron_population(nrn_pop)
return [n.soma.radius for n in nrns] | [
"def",
"soma_radii",
"(",
"nrn_pop",
",",
"neurite_type",
"=",
"NeuriteType",
".",
"soma",
")",
":",
"assert",
"neurite_type",
"==",
"NeuriteType",
".",
"soma",
",",
"'Neurite type must be soma'",
"nrns",
"=",
"neuron_population",
"(",
"nrn_pop",
")",
"return",
"[",
"n",
".",
"soma",
".",
"radius",
"for",
"n",
"in",
"nrns",
"]"
] | Get the radii of the somata of a population of neurons
Note:
If a single neuron is passed, a single element list with the
radius of its soma member is returned. | [
"Get",
"the",
"radii",
"of",
"the",
"somata",
"of",
"a",
"population",
"of",
"neurons"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuronfunc.py#L70-L79 |
2,779 | BlueBrain/NeuroM | neurom/fst/_neuronfunc.py | trunk_section_lengths | def trunk_section_lengths(nrn, neurite_type=NeuriteType.all):
'''list of lengths of trunk sections of neurites in a neuron'''
neurite_filter = is_type(neurite_type)
return [morphmath.section_length(s.root_node.points)
for s in nrn.neurites if neurite_filter(s)] | python | def trunk_section_lengths(nrn, neurite_type=NeuriteType.all):
'''list of lengths of trunk sections of neurites in a neuron'''
neurite_filter = is_type(neurite_type)
return [morphmath.section_length(s.root_node.points)
for s in nrn.neurites if neurite_filter(s)] | [
"def",
"trunk_section_lengths",
"(",
"nrn",
",",
"neurite_type",
"=",
"NeuriteType",
".",
"all",
")",
":",
"neurite_filter",
"=",
"is_type",
"(",
"neurite_type",
")",
"return",
"[",
"morphmath",
".",
"section_length",
"(",
"s",
".",
"root_node",
".",
"points",
")",
"for",
"s",
"in",
"nrn",
".",
"neurites",
"if",
"neurite_filter",
"(",
"s",
")",
"]"
] | list of lengths of trunk sections of neurites in a neuron | [
"list",
"of",
"lengths",
"of",
"trunk",
"sections",
"of",
"neurites",
"in",
"a",
"neuron"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuronfunc.py#L82-L86 |
2,780 | BlueBrain/NeuroM | neurom/fst/_neuronfunc.py | trunk_origin_radii | def trunk_origin_radii(nrn, neurite_type=NeuriteType.all):
'''radii of the trunk sections of neurites in a neuron'''
neurite_filter = is_type(neurite_type)
return [s.root_node.points[0][COLS.R] for s in nrn.neurites if neurite_filter(s)] | python | def trunk_origin_radii(nrn, neurite_type=NeuriteType.all):
'''radii of the trunk sections of neurites in a neuron'''
neurite_filter = is_type(neurite_type)
return [s.root_node.points[0][COLS.R] for s in nrn.neurites if neurite_filter(s)] | [
"def",
"trunk_origin_radii",
"(",
"nrn",
",",
"neurite_type",
"=",
"NeuriteType",
".",
"all",
")",
":",
"neurite_filter",
"=",
"is_type",
"(",
"neurite_type",
")",
"return",
"[",
"s",
".",
"root_node",
".",
"points",
"[",
"0",
"]",
"[",
"COLS",
".",
"R",
"]",
"for",
"s",
"in",
"nrn",
".",
"neurites",
"if",
"neurite_filter",
"(",
"s",
")",
"]"
] | radii of the trunk sections of neurites in a neuron | [
"radii",
"of",
"the",
"trunk",
"sections",
"of",
"neurites",
"in",
"a",
"neuron"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuronfunc.py#L89-L92 |
2,781 | BlueBrain/NeuroM | neurom/fst/_neuronfunc.py | trunk_origin_azimuths | def trunk_origin_azimuths(nrn, neurite_type=NeuriteType.all):
'''Get a list of all the trunk origin azimuths of a neuron or population
The azimuth is defined as Angle between x-axis and the vector
defined by (initial tree point - soma center) on the x-z plane.
The range of the azimuth angle [-pi, pi] radians
'''
neurite_filter = is_type(neurite_type)
nrns = neuron_population(nrn)
def _azimuth(section, soma):
'''Azimuth of a section'''
vector = morphmath.vector(section[0], soma.center)
return np.arctan2(vector[COLS.Z], vector[COLS.X])
return [_azimuth(s.root_node.points, n.soma)
for n in nrns
for s in n.neurites if neurite_filter(s)] | python | def trunk_origin_azimuths(nrn, neurite_type=NeuriteType.all):
'''Get a list of all the trunk origin azimuths of a neuron or population
The azimuth is defined as Angle between x-axis and the vector
defined by (initial tree point - soma center) on the x-z plane.
The range of the azimuth angle [-pi, pi] radians
'''
neurite_filter = is_type(neurite_type)
nrns = neuron_population(nrn)
def _azimuth(section, soma):
'''Azimuth of a section'''
vector = morphmath.vector(section[0], soma.center)
return np.arctan2(vector[COLS.Z], vector[COLS.X])
return [_azimuth(s.root_node.points, n.soma)
for n in nrns
for s in n.neurites if neurite_filter(s)] | [
"def",
"trunk_origin_azimuths",
"(",
"nrn",
",",
"neurite_type",
"=",
"NeuriteType",
".",
"all",
")",
":",
"neurite_filter",
"=",
"is_type",
"(",
"neurite_type",
")",
"nrns",
"=",
"neuron_population",
"(",
"nrn",
")",
"def",
"_azimuth",
"(",
"section",
",",
"soma",
")",
":",
"'''Azimuth of a section'''",
"vector",
"=",
"morphmath",
".",
"vector",
"(",
"section",
"[",
"0",
"]",
",",
"soma",
".",
"center",
")",
"return",
"np",
".",
"arctan2",
"(",
"vector",
"[",
"COLS",
".",
"Z",
"]",
",",
"vector",
"[",
"COLS",
".",
"X",
"]",
")",
"return",
"[",
"_azimuth",
"(",
"s",
".",
"root_node",
".",
"points",
",",
"n",
".",
"soma",
")",
"for",
"n",
"in",
"nrns",
"for",
"s",
"in",
"n",
".",
"neurites",
"if",
"neurite_filter",
"(",
"s",
")",
"]"
] | Get a list of all the trunk origin azimuths of a neuron or population
The azimuth is defined as Angle between x-axis and the vector
defined by (initial tree point - soma center) on the x-z plane.
The range of the azimuth angle [-pi, pi] radians | [
"Get",
"a",
"list",
"of",
"all",
"the",
"trunk",
"origin",
"azimuths",
"of",
"a",
"neuron",
"or",
"population"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuronfunc.py#L95-L113 |
2,782 | BlueBrain/NeuroM | neurom/fst/_neuronfunc.py | trunk_origin_elevations | def trunk_origin_elevations(nrn, neurite_type=NeuriteType.all):
'''Get a list of all the trunk origin elevations of a neuron or population
The elevation is defined as the angle between x-axis and the
vector defined by (initial tree point - soma center)
on the x-y half-plane.
The range of the elevation angle [-pi/2, pi/2] radians
'''
neurite_filter = is_type(neurite_type)
nrns = neuron_population(nrn)
def _elevation(section, soma):
'''Elevation of a section'''
vector = morphmath.vector(section[0], soma.center)
norm_vector = np.linalg.norm(vector)
if norm_vector >= np.finfo(type(norm_vector)).eps:
return np.arcsin(vector[COLS.Y] / norm_vector)
raise ValueError("Norm of vector between soma center and section is almost zero.")
return [_elevation(s.root_node.points, n.soma)
for n in nrns
for s in n.neurites if neurite_filter(s)] | python | def trunk_origin_elevations(nrn, neurite_type=NeuriteType.all):
'''Get a list of all the trunk origin elevations of a neuron or population
The elevation is defined as the angle between x-axis and the
vector defined by (initial tree point - soma center)
on the x-y half-plane.
The range of the elevation angle [-pi/2, pi/2] radians
'''
neurite_filter = is_type(neurite_type)
nrns = neuron_population(nrn)
def _elevation(section, soma):
'''Elevation of a section'''
vector = morphmath.vector(section[0], soma.center)
norm_vector = np.linalg.norm(vector)
if norm_vector >= np.finfo(type(norm_vector)).eps:
return np.arcsin(vector[COLS.Y] / norm_vector)
raise ValueError("Norm of vector between soma center and section is almost zero.")
return [_elevation(s.root_node.points, n.soma)
for n in nrns
for s in n.neurites if neurite_filter(s)] | [
"def",
"trunk_origin_elevations",
"(",
"nrn",
",",
"neurite_type",
"=",
"NeuriteType",
".",
"all",
")",
":",
"neurite_filter",
"=",
"is_type",
"(",
"neurite_type",
")",
"nrns",
"=",
"neuron_population",
"(",
"nrn",
")",
"def",
"_elevation",
"(",
"section",
",",
"soma",
")",
":",
"'''Elevation of a section'''",
"vector",
"=",
"morphmath",
".",
"vector",
"(",
"section",
"[",
"0",
"]",
",",
"soma",
".",
"center",
")",
"norm_vector",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"vector",
")",
"if",
"norm_vector",
">=",
"np",
".",
"finfo",
"(",
"type",
"(",
"norm_vector",
")",
")",
".",
"eps",
":",
"return",
"np",
".",
"arcsin",
"(",
"vector",
"[",
"COLS",
".",
"Y",
"]",
"/",
"norm_vector",
")",
"raise",
"ValueError",
"(",
"\"Norm of vector between soma center and section is almost zero.\"",
")",
"return",
"[",
"_elevation",
"(",
"s",
".",
"root_node",
".",
"points",
",",
"n",
".",
"soma",
")",
"for",
"n",
"in",
"nrns",
"for",
"s",
"in",
"n",
".",
"neurites",
"if",
"neurite_filter",
"(",
"s",
")",
"]"
] | Get a list of all the trunk origin elevations of a neuron or population
The elevation is defined as the angle between x-axis and the
vector defined by (initial tree point - soma center)
on the x-y half-plane.
The range of the elevation angle [-pi/2, pi/2] radians | [
"Get",
"a",
"list",
"of",
"all",
"the",
"trunk",
"origin",
"elevations",
"of",
"a",
"neuron",
"or",
"population"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuronfunc.py#L116-L139 |
2,783 | BlueBrain/NeuroM | neurom/fst/_neuronfunc.py | trunk_vectors | def trunk_vectors(nrn, neurite_type=NeuriteType.all):
'''Calculates the vectors between all the trunks of the neuron
and the soma center.
'''
neurite_filter = is_type(neurite_type)
nrns = neuron_population(nrn)
return np.array([morphmath.vector(s.root_node.points[0], n.soma.center)
for n in nrns
for s in n.neurites if neurite_filter(s)]) | python | def trunk_vectors(nrn, neurite_type=NeuriteType.all):
'''Calculates the vectors between all the trunks of the neuron
and the soma center.
'''
neurite_filter = is_type(neurite_type)
nrns = neuron_population(nrn)
return np.array([morphmath.vector(s.root_node.points[0], n.soma.center)
for n in nrns
for s in n.neurites if neurite_filter(s)]) | [
"def",
"trunk_vectors",
"(",
"nrn",
",",
"neurite_type",
"=",
"NeuriteType",
".",
"all",
")",
":",
"neurite_filter",
"=",
"is_type",
"(",
"neurite_type",
")",
"nrns",
"=",
"neuron_population",
"(",
"nrn",
")",
"return",
"np",
".",
"array",
"(",
"[",
"morphmath",
".",
"vector",
"(",
"s",
".",
"root_node",
".",
"points",
"[",
"0",
"]",
",",
"n",
".",
"soma",
".",
"center",
")",
"for",
"n",
"in",
"nrns",
"for",
"s",
"in",
"n",
".",
"neurites",
"if",
"neurite_filter",
"(",
"s",
")",
"]",
")"
] | Calculates the vectors between all the trunks of the neuron
and the soma center. | [
"Calculates",
"the",
"vectors",
"between",
"all",
"the",
"trunks",
"of",
"the",
"neuron",
"and",
"the",
"soma",
"center",
"."
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuronfunc.py#L142-L151 |
2,784 | BlueBrain/NeuroM | neurom/fst/_neuronfunc.py | trunk_angles | def trunk_angles(nrn, neurite_type=NeuriteType.all):
'''Calculates the angles between all the trunks of the neuron.
The angles are defined on the x-y plane and the trees
are sorted from the y axis and anticlock-wise.
'''
vectors = trunk_vectors(nrn, neurite_type=neurite_type)
# In order to avoid the failure of the process in case the neurite_type does not exist
if not vectors.size:
return []
def _sort_angle(p1, p2):
"""Angle between p1-p2 to sort vectors"""
ang1 = np.arctan2(*p1[::-1])
ang2 = np.arctan2(*p2[::-1])
return (ang1 - ang2)
# Sorting angles according to x-y plane
order = np.argsort(np.array([_sort_angle(i / np.linalg.norm(i), [0, 1])
for i in vectors[:, 0:2]]))
ordered_vectors = vectors[order][:, [COLS.X, COLS.Y]]
return [morphmath.angle_between_vectors(ordered_vectors[i], ordered_vectors[i - 1])
for i, _ in enumerate(ordered_vectors)] | python | def trunk_angles(nrn, neurite_type=NeuriteType.all):
'''Calculates the angles between all the trunks of the neuron.
The angles are defined on the x-y plane and the trees
are sorted from the y axis and anticlock-wise.
'''
vectors = trunk_vectors(nrn, neurite_type=neurite_type)
# In order to avoid the failure of the process in case the neurite_type does not exist
if not vectors.size:
return []
def _sort_angle(p1, p2):
"""Angle between p1-p2 to sort vectors"""
ang1 = np.arctan2(*p1[::-1])
ang2 = np.arctan2(*p2[::-1])
return (ang1 - ang2)
# Sorting angles according to x-y plane
order = np.argsort(np.array([_sort_angle(i / np.linalg.norm(i), [0, 1])
for i in vectors[:, 0:2]]))
ordered_vectors = vectors[order][:, [COLS.X, COLS.Y]]
return [morphmath.angle_between_vectors(ordered_vectors[i], ordered_vectors[i - 1])
for i, _ in enumerate(ordered_vectors)] | [
"def",
"trunk_angles",
"(",
"nrn",
",",
"neurite_type",
"=",
"NeuriteType",
".",
"all",
")",
":",
"vectors",
"=",
"trunk_vectors",
"(",
"nrn",
",",
"neurite_type",
"=",
"neurite_type",
")",
"# In order to avoid the failure of the process in case the neurite_type does not exist",
"if",
"not",
"vectors",
".",
"size",
":",
"return",
"[",
"]",
"def",
"_sort_angle",
"(",
"p1",
",",
"p2",
")",
":",
"\"\"\"Angle between p1-p2 to sort vectors\"\"\"",
"ang1",
"=",
"np",
".",
"arctan2",
"(",
"*",
"p1",
"[",
":",
":",
"-",
"1",
"]",
")",
"ang2",
"=",
"np",
".",
"arctan2",
"(",
"*",
"p2",
"[",
":",
":",
"-",
"1",
"]",
")",
"return",
"(",
"ang1",
"-",
"ang2",
")",
"# Sorting angles according to x-y plane",
"order",
"=",
"np",
".",
"argsort",
"(",
"np",
".",
"array",
"(",
"[",
"_sort_angle",
"(",
"i",
"/",
"np",
".",
"linalg",
".",
"norm",
"(",
"i",
")",
",",
"[",
"0",
",",
"1",
"]",
")",
"for",
"i",
"in",
"vectors",
"[",
":",
",",
"0",
":",
"2",
"]",
"]",
")",
")",
"ordered_vectors",
"=",
"vectors",
"[",
"order",
"]",
"[",
":",
",",
"[",
"COLS",
".",
"X",
",",
"COLS",
".",
"Y",
"]",
"]",
"return",
"[",
"morphmath",
".",
"angle_between_vectors",
"(",
"ordered_vectors",
"[",
"i",
"]",
",",
"ordered_vectors",
"[",
"i",
"-",
"1",
"]",
")",
"for",
"i",
",",
"_",
"in",
"enumerate",
"(",
"ordered_vectors",
")",
"]"
] | Calculates the angles between all the trunks of the neuron.
The angles are defined on the x-y plane and the trees
are sorted from the y axis and anticlock-wise. | [
"Calculates",
"the",
"angles",
"between",
"all",
"the",
"trunks",
"of",
"the",
"neuron",
".",
"The",
"angles",
"are",
"defined",
"on",
"the",
"x",
"-",
"y",
"plane",
"and",
"the",
"trees",
"are",
"sorted",
"from",
"the",
"y",
"axis",
"and",
"anticlock",
"-",
"wise",
"."
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuronfunc.py#L154-L177 |
2,785 | BlueBrain/NeuroM | neurom/fst/_neuronfunc.py | sholl_crossings | def sholl_crossings(neurites, center, radii):
'''calculate crossings of neurites
Args:
nrn(morph): morphology on which to perform Sholl analysis
radii(iterable of floats): radii for which crossings will be counted
Returns:
Array of same length as radii, with a count of the number of crossings
for the respective radius
'''
def _count_crossings(neurite, radius):
'''count_crossings of segments in neurite with radius'''
r2 = radius ** 2
count = 0
for start, end in iter_segments(neurite):
start_dist2, end_dist2 = (morphmath.point_dist2(center, start),
morphmath.point_dist2(center, end))
count += int(start_dist2 <= r2 <= end_dist2 or
end_dist2 <= r2 <= start_dist2)
return count
return np.array([sum(_count_crossings(neurite, r)
for neurite in iter_neurites(neurites))
for r in radii]) | python | def sholl_crossings(neurites, center, radii):
'''calculate crossings of neurites
Args:
nrn(morph): morphology on which to perform Sholl analysis
radii(iterable of floats): radii for which crossings will be counted
Returns:
Array of same length as radii, with a count of the number of crossings
for the respective radius
'''
def _count_crossings(neurite, radius):
'''count_crossings of segments in neurite with radius'''
r2 = radius ** 2
count = 0
for start, end in iter_segments(neurite):
start_dist2, end_dist2 = (morphmath.point_dist2(center, start),
morphmath.point_dist2(center, end))
count += int(start_dist2 <= r2 <= end_dist2 or
end_dist2 <= r2 <= start_dist2)
return count
return np.array([sum(_count_crossings(neurite, r)
for neurite in iter_neurites(neurites))
for r in radii]) | [
"def",
"sholl_crossings",
"(",
"neurites",
",",
"center",
",",
"radii",
")",
":",
"def",
"_count_crossings",
"(",
"neurite",
",",
"radius",
")",
":",
"'''count_crossings of segments in neurite with radius'''",
"r2",
"=",
"radius",
"**",
"2",
"count",
"=",
"0",
"for",
"start",
",",
"end",
"in",
"iter_segments",
"(",
"neurite",
")",
":",
"start_dist2",
",",
"end_dist2",
"=",
"(",
"morphmath",
".",
"point_dist2",
"(",
"center",
",",
"start",
")",
",",
"morphmath",
".",
"point_dist2",
"(",
"center",
",",
"end",
")",
")",
"count",
"+=",
"int",
"(",
"start_dist2",
"<=",
"r2",
"<=",
"end_dist2",
"or",
"end_dist2",
"<=",
"r2",
"<=",
"start_dist2",
")",
"return",
"count",
"return",
"np",
".",
"array",
"(",
"[",
"sum",
"(",
"_count_crossings",
"(",
"neurite",
",",
"r",
")",
"for",
"neurite",
"in",
"iter_neurites",
"(",
"neurites",
")",
")",
"for",
"r",
"in",
"radii",
"]",
")"
] | calculate crossings of neurites
Args:
nrn(morph): morphology on which to perform Sholl analysis
radii(iterable of floats): radii for which crossings will be counted
Returns:
Array of same length as radii, with a count of the number of crossings
for the respective radius | [
"calculate",
"crossings",
"of",
"neurites"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuronfunc.py#L180-L206 |
2,786 | BlueBrain/NeuroM | neurom/fst/_neuronfunc.py | sholl_frequency | def sholl_frequency(nrn, neurite_type=NeuriteType.all, step_size=10):
'''perform Sholl frequency calculations on a population of neurites
Args:
nrn(morph): nrn or population
neurite_type(NeuriteType): which neurites to operate on
step_size(float): step size between Sholl radii
Note:
Given a neuron, the soma center is used for the concentric circles,
which range from the soma radii, and the maximum radial distance
in steps of `step_size`. When a population is given, the concentric
circles range from the smallest soma radius to the largest radial neurite
distance. Finally, each segment of the neuron is tested, so a neurite that
bends back on itself, and crosses the same Sholl radius will get counted as
having crossed multiple times.
'''
nrns = neuron_population(nrn)
neurite_filter = is_type(neurite_type)
min_soma_edge = float('Inf')
max_radii = 0
neurites_list = []
for neuron in nrns:
neurites_list.extend(((neurites, neuron.soma.center)
for neurites in neuron.neurites
if neurite_filter(neurites)))
min_soma_edge = min(min_soma_edge, neuron.soma.radius)
max_radii = max(max_radii, np.max(np.abs(bounding_box(neuron))))
radii = np.arange(min_soma_edge, max_radii + step_size, step_size)
ret = np.zeros_like(radii)
for neurites, center in neurites_list:
ret += sholl_crossings(neurites, center, radii)
return ret | python | def sholl_frequency(nrn, neurite_type=NeuriteType.all, step_size=10):
'''perform Sholl frequency calculations on a population of neurites
Args:
nrn(morph): nrn or population
neurite_type(NeuriteType): which neurites to operate on
step_size(float): step size between Sholl radii
Note:
Given a neuron, the soma center is used for the concentric circles,
which range from the soma radii, and the maximum radial distance
in steps of `step_size`. When a population is given, the concentric
circles range from the smallest soma radius to the largest radial neurite
distance. Finally, each segment of the neuron is tested, so a neurite that
bends back on itself, and crosses the same Sholl radius will get counted as
having crossed multiple times.
'''
nrns = neuron_population(nrn)
neurite_filter = is_type(neurite_type)
min_soma_edge = float('Inf')
max_radii = 0
neurites_list = []
for neuron in nrns:
neurites_list.extend(((neurites, neuron.soma.center)
for neurites in neuron.neurites
if neurite_filter(neurites)))
min_soma_edge = min(min_soma_edge, neuron.soma.radius)
max_radii = max(max_radii, np.max(np.abs(bounding_box(neuron))))
radii = np.arange(min_soma_edge, max_radii + step_size, step_size)
ret = np.zeros_like(radii)
for neurites, center in neurites_list:
ret += sholl_crossings(neurites, center, radii)
return ret | [
"def",
"sholl_frequency",
"(",
"nrn",
",",
"neurite_type",
"=",
"NeuriteType",
".",
"all",
",",
"step_size",
"=",
"10",
")",
":",
"nrns",
"=",
"neuron_population",
"(",
"nrn",
")",
"neurite_filter",
"=",
"is_type",
"(",
"neurite_type",
")",
"min_soma_edge",
"=",
"float",
"(",
"'Inf'",
")",
"max_radii",
"=",
"0",
"neurites_list",
"=",
"[",
"]",
"for",
"neuron",
"in",
"nrns",
":",
"neurites_list",
".",
"extend",
"(",
"(",
"(",
"neurites",
",",
"neuron",
".",
"soma",
".",
"center",
")",
"for",
"neurites",
"in",
"neuron",
".",
"neurites",
"if",
"neurite_filter",
"(",
"neurites",
")",
")",
")",
"min_soma_edge",
"=",
"min",
"(",
"min_soma_edge",
",",
"neuron",
".",
"soma",
".",
"radius",
")",
"max_radii",
"=",
"max",
"(",
"max_radii",
",",
"np",
".",
"max",
"(",
"np",
".",
"abs",
"(",
"bounding_box",
"(",
"neuron",
")",
")",
")",
")",
"radii",
"=",
"np",
".",
"arange",
"(",
"min_soma_edge",
",",
"max_radii",
"+",
"step_size",
",",
"step_size",
")",
"ret",
"=",
"np",
".",
"zeros_like",
"(",
"radii",
")",
"for",
"neurites",
",",
"center",
"in",
"neurites_list",
":",
"ret",
"+=",
"sholl_crossings",
"(",
"neurites",
",",
"center",
",",
"radii",
")",
"return",
"ret"
] | perform Sholl frequency calculations on a population of neurites
Args:
nrn(morph): nrn or population
neurite_type(NeuriteType): which neurites to operate on
step_size(float): step size between Sholl radii
Note:
Given a neuron, the soma center is used for the concentric circles,
which range from the soma radii, and the maximum radial distance
in steps of `step_size`. When a population is given, the concentric
circles range from the smallest soma radius to the largest radial neurite
distance. Finally, each segment of the neuron is tested, so a neurite that
bends back on itself, and crosses the same Sholl radius will get counted as
having crossed multiple times. | [
"perform",
"Sholl",
"frequency",
"calculations",
"on",
"a",
"population",
"of",
"neurites"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/_neuronfunc.py#L209-L245 |
2,787 | BlueBrain/NeuroM | examples/plot_features.py | dist_points | def dist_points(bin_edges, d):
"""Return an array of values according to a distribution
Points are calculated at the center of each bin
"""
bc = bin_centers(bin_edges)
if d is not None:
d = DISTS[d['type']](d, bc)
return d, bc | python | def dist_points(bin_edges, d):
"""Return an array of values according to a distribution
Points are calculated at the center of each bin
"""
bc = bin_centers(bin_edges)
if d is not None:
d = DISTS[d['type']](d, bc)
return d, bc | [
"def",
"dist_points",
"(",
"bin_edges",
",",
"d",
")",
":",
"bc",
"=",
"bin_centers",
"(",
"bin_edges",
")",
"if",
"d",
"is",
"not",
"None",
":",
"d",
"=",
"DISTS",
"[",
"d",
"[",
"'type'",
"]",
"]",
"(",
"d",
",",
"bc",
")",
"return",
"d",
",",
"bc"
] | Return an array of values according to a distribution
Points are calculated at the center of each bin | [
"Return",
"an",
"array",
"of",
"values",
"according",
"to",
"a",
"distribution"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/examples/plot_features.py#L70-L78 |
2,788 | BlueBrain/NeuroM | examples/plot_features.py | calc_limits | def calc_limits(data, dist=None, padding=0.25):
"""Calculate a suitable range for a histogram
Returns:
tuple of (min, max)
"""
dmin = sys.float_info.max if dist is None else dist.get('min',
sys.float_info.max)
dmax = sys.float_info.min if dist is None else dist.get('max',
sys.float_info.min)
_min = min(min(data), dmin)
_max = max(max(data), dmax)
padding = padding * (_max - _min)
return _min - padding, _max + padding | python | def calc_limits(data, dist=None, padding=0.25):
"""Calculate a suitable range for a histogram
Returns:
tuple of (min, max)
"""
dmin = sys.float_info.max if dist is None else dist.get('min',
sys.float_info.max)
dmax = sys.float_info.min if dist is None else dist.get('max',
sys.float_info.min)
_min = min(min(data), dmin)
_max = max(max(data), dmax)
padding = padding * (_max - _min)
return _min - padding, _max + padding | [
"def",
"calc_limits",
"(",
"data",
",",
"dist",
"=",
"None",
",",
"padding",
"=",
"0.25",
")",
":",
"dmin",
"=",
"sys",
".",
"float_info",
".",
"max",
"if",
"dist",
"is",
"None",
"else",
"dist",
".",
"get",
"(",
"'min'",
",",
"sys",
".",
"float_info",
".",
"max",
")",
"dmax",
"=",
"sys",
".",
"float_info",
".",
"min",
"if",
"dist",
"is",
"None",
"else",
"dist",
".",
"get",
"(",
"'max'",
",",
"sys",
".",
"float_info",
".",
"min",
")",
"_min",
"=",
"min",
"(",
"min",
"(",
"data",
")",
",",
"dmin",
")",
"_max",
"=",
"max",
"(",
"max",
"(",
"data",
")",
",",
"dmax",
")",
"padding",
"=",
"padding",
"*",
"(",
"_max",
"-",
"_min",
")",
"return",
"_min",
"-",
"padding",
",",
"_max",
"+",
"padding"
] | Calculate a suitable range for a histogram
Returns:
tuple of (min, max) | [
"Calculate",
"a",
"suitable",
"range",
"for",
"a",
"histogram"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/examples/plot_features.py#L81-L95 |
2,789 | BlueBrain/NeuroM | examples/plot_features.py | load_neurite_features | 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 | python | 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",
"load_neurite_features",
"(",
"filepath",
")",
":",
"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"
] | Unpack relevant data into megadict | [
"Unpack",
"relevant",
"data",
"into",
"megadict"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/examples/plot_features.py#L112-L123 |
2,790 | BlueBrain/NeuroM | examples/plot_features.py | main | 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 | python | 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 | [
"def",
"main",
"(",
"data_dir",
",",
"mtype_file",
")",
":",
"# pylint: disable=too-many-locals",
"# 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"
] | Run the stuff | [
"Run",
"the",
"stuff"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/examples/plot_features.py#L150-L191 |
2,791 | BlueBrain/NeuroM | examples/density_plot.py | extract_density | def extract_density(population, plane='xy', bins=100, neurite_type=NeuriteType.basal_dendrite):
'''Extracts the 2d histogram of the center
coordinates of segments in the selected plane.
'''
segment_midpoints = get_feat('segment_midpoints', population, neurite_type=neurite_type)
horiz = segment_midpoints[:, 'xyz'.index(plane[0])]
vert = segment_midpoints[:, 'xyz'.index(plane[1])]
return np.histogram2d(np.array(horiz), np.array(vert), bins=(bins, bins)) | python | def extract_density(population, plane='xy', bins=100, neurite_type=NeuriteType.basal_dendrite):
'''Extracts the 2d histogram of the center
coordinates of segments in the selected plane.
'''
segment_midpoints = get_feat('segment_midpoints', population, neurite_type=neurite_type)
horiz = segment_midpoints[:, 'xyz'.index(plane[0])]
vert = segment_midpoints[:, 'xyz'.index(plane[1])]
return np.histogram2d(np.array(horiz), np.array(vert), bins=(bins, bins)) | [
"def",
"extract_density",
"(",
"population",
",",
"plane",
"=",
"'xy'",
",",
"bins",
"=",
"100",
",",
"neurite_type",
"=",
"NeuriteType",
".",
"basal_dendrite",
")",
":",
"segment_midpoints",
"=",
"get_feat",
"(",
"'segment_midpoints'",
",",
"population",
",",
"neurite_type",
"=",
"neurite_type",
")",
"horiz",
"=",
"segment_midpoints",
"[",
":",
",",
"'xyz'",
".",
"index",
"(",
"plane",
"[",
"0",
"]",
")",
"]",
"vert",
"=",
"segment_midpoints",
"[",
":",
",",
"'xyz'",
".",
"index",
"(",
"plane",
"[",
"1",
"]",
")",
"]",
"return",
"np",
".",
"histogram2d",
"(",
"np",
".",
"array",
"(",
"horiz",
")",
",",
"np",
".",
"array",
"(",
"vert",
")",
",",
"bins",
"=",
"(",
"bins",
",",
"bins",
")",
")"
] | Extracts the 2d histogram of the center
coordinates of segments in the selected plane. | [
"Extracts",
"the",
"2d",
"histogram",
"of",
"the",
"center",
"coordinates",
"of",
"segments",
"in",
"the",
"selected",
"plane",
"."
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/examples/density_plot.py#L39-L46 |
2,792 | BlueBrain/NeuroM | examples/density_plot.py | plot_density | 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) | python | 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) | [
"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",
")",
":",
"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",
")"
] | Plots the 2d histogram of the center
coordinates of segments in the selected plane. | [
"Plots",
"the",
"2d",
"histogram",
"of",
"the",
"center",
"coordinates",
"of",
"segments",
"in",
"the",
"selected",
"plane",
"."
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/examples/density_plot.py#L49-L80 |
2,793 | BlueBrain/NeuroM | examples/density_plot.py | plot_neuron_on_density | 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) | python | 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) | [
"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",
")",
":",
"_",
",",
"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",
")"
] | 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. | [
"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",
"."
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/examples/density_plot.py#L83-L99 |
2,794 | BlueBrain/NeuroM | neurom/check/morphtree.py | is_monotonic | def is_monotonic(neurite, tol):
'''Check if neurite tree is monotonic
If each child has smaller or equal diameters from its parent
Args:
neurite(Neurite): neurite to operate on
tol(float): tolerance
Returns:
True if neurite monotonic
'''
for node in neurite.iter_sections():
# check that points in section satisfy monotonicity
sec = node.points
for point_id in range(len(sec) - 1):
if sec[point_id + 1][COLS.R] > sec[point_id][COLS.R] + tol:
return False
# Check that section boundary points satisfy monotonicity
if(node.parent is not None and
sec[0][COLS.R] > node.parent.points[-1][COLS.R] + tol):
return False
return True | python | def is_monotonic(neurite, tol):
'''Check if neurite tree is monotonic
If each child has smaller or equal diameters from its parent
Args:
neurite(Neurite): neurite to operate on
tol(float): tolerance
Returns:
True if neurite monotonic
'''
for node in neurite.iter_sections():
# check that points in section satisfy monotonicity
sec = node.points
for point_id in range(len(sec) - 1):
if sec[point_id + 1][COLS.R] > sec[point_id][COLS.R] + tol:
return False
# Check that section boundary points satisfy monotonicity
if(node.parent is not None and
sec[0][COLS.R] > node.parent.points[-1][COLS.R] + tol):
return False
return True | [
"def",
"is_monotonic",
"(",
"neurite",
",",
"tol",
")",
":",
"for",
"node",
"in",
"neurite",
".",
"iter_sections",
"(",
")",
":",
"# check that points in section satisfy monotonicity",
"sec",
"=",
"node",
".",
"points",
"for",
"point_id",
"in",
"range",
"(",
"len",
"(",
"sec",
")",
"-",
"1",
")",
":",
"if",
"sec",
"[",
"point_id",
"+",
"1",
"]",
"[",
"COLS",
".",
"R",
"]",
">",
"sec",
"[",
"point_id",
"]",
"[",
"COLS",
".",
"R",
"]",
"+",
"tol",
":",
"return",
"False",
"# Check that section boundary points satisfy monotonicity",
"if",
"(",
"node",
".",
"parent",
"is",
"not",
"None",
"and",
"sec",
"[",
"0",
"]",
"[",
"COLS",
".",
"R",
"]",
">",
"node",
".",
"parent",
".",
"points",
"[",
"-",
"1",
"]",
"[",
"COLS",
".",
"R",
"]",
"+",
"tol",
")",
":",
"return",
"False",
"return",
"True"
] | Check if neurite tree is monotonic
If each child has smaller or equal diameters from its parent
Args:
neurite(Neurite): neurite to operate on
tol(float): tolerance
Returns:
True if neurite monotonic | [
"Check",
"if",
"neurite",
"tree",
"is",
"monotonic"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/morphtree.py#L40-L64 |
2,795 | BlueBrain/NeuroM | neurom/check/morphtree.py | is_flat | def is_flat(neurite, tol, method='tolerance'):
'''Check if neurite is flat using the given method
Args:
neurite(Neurite): neurite to operate on
tol(float): tolerance
method(string): the method of flatness estimation:
'tolerance' returns true if any extent of the tree is smaller
than the given tolerance
'ratio' returns true if the ratio of the smallest directions
is smaller than tol. e.g. [1,2,3] -> 1/2 < tol
Returns:
True if neurite is flat
'''
ext = principal_direction_extent(neurite.points[:, COLS.XYZ])
assert method in ('tolerance', 'ratio'), "Method must be one of 'tolerance', 'ratio'"
if method == 'ratio':
sorted_ext = np.sort(ext)
return sorted_ext[0] / sorted_ext[1] < float(tol)
return any(ext < float(tol)) | python | def is_flat(neurite, tol, method='tolerance'):
'''Check if neurite is flat using the given method
Args:
neurite(Neurite): neurite to operate on
tol(float): tolerance
method(string): the method of flatness estimation:
'tolerance' returns true if any extent of the tree is smaller
than the given tolerance
'ratio' returns true if the ratio of the smallest directions
is smaller than tol. e.g. [1,2,3] -> 1/2 < tol
Returns:
True if neurite is flat
'''
ext = principal_direction_extent(neurite.points[:, COLS.XYZ])
assert method in ('tolerance', 'ratio'), "Method must be one of 'tolerance', 'ratio'"
if method == 'ratio':
sorted_ext = np.sort(ext)
return sorted_ext[0] / sorted_ext[1] < float(tol)
return any(ext < float(tol)) | [
"def",
"is_flat",
"(",
"neurite",
",",
"tol",
",",
"method",
"=",
"'tolerance'",
")",
":",
"ext",
"=",
"principal_direction_extent",
"(",
"neurite",
".",
"points",
"[",
":",
",",
"COLS",
".",
"XYZ",
"]",
")",
"assert",
"method",
"in",
"(",
"'tolerance'",
",",
"'ratio'",
")",
",",
"\"Method must be one of 'tolerance', 'ratio'\"",
"if",
"method",
"==",
"'ratio'",
":",
"sorted_ext",
"=",
"np",
".",
"sort",
"(",
"ext",
")",
"return",
"sorted_ext",
"[",
"0",
"]",
"/",
"sorted_ext",
"[",
"1",
"]",
"<",
"float",
"(",
"tol",
")",
"return",
"any",
"(",
"ext",
"<",
"float",
"(",
"tol",
")",
")"
] | Check if neurite is flat using the given method
Args:
neurite(Neurite): neurite to operate on
tol(float): tolerance
method(string): the method of flatness estimation:
'tolerance' returns true if any extent of the tree is smaller
than the given tolerance
'ratio' returns true if the ratio of the smallest directions
is smaller than tol. e.g. [1,2,3] -> 1/2 < tol
Returns:
True if neurite is flat | [
"Check",
"if",
"neurite",
"is",
"flat",
"using",
"the",
"given",
"method"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/morphtree.py#L67-L88 |
2,796 | BlueBrain/NeuroM | neurom/check/morphtree.py | is_back_tracking | def is_back_tracking(neurite):
''' Check if a neurite process backtracks to a previous node. Back-tracking takes place
when a daughter of a branching process goes back and either overlaps with a previous point, or
lies inside the cylindrical volume of the latter.
Args:
neurite(Neurite): neurite to operate on
Returns:
True Under the following scenaria:
1. A segment endpoint falls back and overlaps with a previous segment's point
2. The geometry of a segment overlaps with a previous one in the section
'''
def pair(segs):
''' Pairs the input list into triplets'''
return zip(segs, segs[1:])
def coords(node):
''' Returns the first three values of the tree that correspond to the x, y, z coordinates'''
return node[COLS.XYZ]
def max_radius(seg):
''' Returns maximum radius from the two segment endpoints'''
return max(seg[0][COLS.R], seg[1][COLS.R])
def is_not_zero_seg(seg):
''' Returns True if segment has zero length'''
return not np.allclose(coords(seg[0]), coords(seg[1]))
def is_in_the_same_verse(seg1, seg2):
''' Checks if the vectors face the same direction. This
is true if their dot product is greater than zero.
'''
v1 = coords(seg2[1]) - coords(seg2[0])
v2 = coords(seg1[1]) - coords(seg1[0])
return np.dot(v1, v2) >= 0
def is_seg2_within_seg1_radius(dist, seg1, seg2):
''' Checks whether the orthogonal distance from the point at the end of
seg1 to seg2 segment body is smaller than the sum of their radii
'''
return dist <= max_radius(seg1) + max_radius(seg2)
def is_seg1_overlapping_with_seg2(seg1, seg2):
'''Checks if a segment is in proximity of another one upstream'''
# get the coordinates of seg2 (from the origin)
s1 = coords(seg2[0])
s2 = coords(seg2[1])
# vector of the center of seg2 (from the origin)
C = 0.5 * (s1 + s2)
# endpoint of seg1 (from the origin)
P = coords(seg1[1])
# vector from the center C of seg2 to the endpoint P of seg1
CP = P - C
# vector of seg2
S1S2 = s2 - s1
# projection of CP upon seg2
prj = mm.vector_projection(CP, S1S2)
# check if the distance of the orthogonal complement of CP projection on S1S2
# (vertical distance from P to seg2) is smaller than the sum of the radii. (overlap)
# If not exit early, because there is no way that backtracking can feasible
if not is_seg2_within_seg1_radius(np.linalg.norm(CP - prj), seg1, seg2):
return False
# projection lies within the length of the cylinder. Check if the distance between
# the center C of seg2 and the projection of the end point of seg1, P is smaller than
# half of the others length plus a 5% tolerance
return np.linalg.norm(prj) < 0.55 * np.linalg.norm(S1S2)
def is_inside_cylinder(seg1, seg2):
''' Checks if seg2 approximately lies within a cylindrical volume of seg1.
Two conditions must be satisfied:
1. The two segments are not facing the same direction (seg2 comes back to seg1)
2. seg2 is overlaping with seg1
'''
return not is_in_the_same_verse(seg1, seg2) and is_seg1_overlapping_with_seg2(seg1, seg2)
# filter out single segment sections
section_itr = (snode for snode in neurite.iter_sections() if snode.points.shape[0] > 2)
for snode in section_itr:
# group each section's points intro triplets
segment_pairs = list(filter(is_not_zero_seg, pair(snode.points)))
# filter out zero length segments
for i, seg1 in enumerate(segment_pairs[1:]):
# check if the end point of the segment lies within the previous
# ones in the current sectionmake
for seg2 in segment_pairs[0: i + 1]:
if is_inside_cylinder(seg1, seg2):
return True
return False | python | def is_back_tracking(neurite):
''' Check if a neurite process backtracks to a previous node. Back-tracking takes place
when a daughter of a branching process goes back and either overlaps with a previous point, or
lies inside the cylindrical volume of the latter.
Args:
neurite(Neurite): neurite to operate on
Returns:
True Under the following scenaria:
1. A segment endpoint falls back and overlaps with a previous segment's point
2. The geometry of a segment overlaps with a previous one in the section
'''
def pair(segs):
''' Pairs the input list into triplets'''
return zip(segs, segs[1:])
def coords(node):
''' Returns the first three values of the tree that correspond to the x, y, z coordinates'''
return node[COLS.XYZ]
def max_radius(seg):
''' Returns maximum radius from the two segment endpoints'''
return max(seg[0][COLS.R], seg[1][COLS.R])
def is_not_zero_seg(seg):
''' Returns True if segment has zero length'''
return not np.allclose(coords(seg[0]), coords(seg[1]))
def is_in_the_same_verse(seg1, seg2):
''' Checks if the vectors face the same direction. This
is true if their dot product is greater than zero.
'''
v1 = coords(seg2[1]) - coords(seg2[0])
v2 = coords(seg1[1]) - coords(seg1[0])
return np.dot(v1, v2) >= 0
def is_seg2_within_seg1_radius(dist, seg1, seg2):
''' Checks whether the orthogonal distance from the point at the end of
seg1 to seg2 segment body is smaller than the sum of their radii
'''
return dist <= max_radius(seg1) + max_radius(seg2)
def is_seg1_overlapping_with_seg2(seg1, seg2):
'''Checks if a segment is in proximity of another one upstream'''
# get the coordinates of seg2 (from the origin)
s1 = coords(seg2[0])
s2 = coords(seg2[1])
# vector of the center of seg2 (from the origin)
C = 0.5 * (s1 + s2)
# endpoint of seg1 (from the origin)
P = coords(seg1[1])
# vector from the center C of seg2 to the endpoint P of seg1
CP = P - C
# vector of seg2
S1S2 = s2 - s1
# projection of CP upon seg2
prj = mm.vector_projection(CP, S1S2)
# check if the distance of the orthogonal complement of CP projection on S1S2
# (vertical distance from P to seg2) is smaller than the sum of the radii. (overlap)
# If not exit early, because there is no way that backtracking can feasible
if not is_seg2_within_seg1_radius(np.linalg.norm(CP - prj), seg1, seg2):
return False
# projection lies within the length of the cylinder. Check if the distance between
# the center C of seg2 and the projection of the end point of seg1, P is smaller than
# half of the others length plus a 5% tolerance
return np.linalg.norm(prj) < 0.55 * np.linalg.norm(S1S2)
def is_inside_cylinder(seg1, seg2):
''' Checks if seg2 approximately lies within a cylindrical volume of seg1.
Two conditions must be satisfied:
1. The two segments are not facing the same direction (seg2 comes back to seg1)
2. seg2 is overlaping with seg1
'''
return not is_in_the_same_verse(seg1, seg2) and is_seg1_overlapping_with_seg2(seg1, seg2)
# filter out single segment sections
section_itr = (snode for snode in neurite.iter_sections() if snode.points.shape[0] > 2)
for snode in section_itr:
# group each section's points intro triplets
segment_pairs = list(filter(is_not_zero_seg, pair(snode.points)))
# filter out zero length segments
for i, seg1 in enumerate(segment_pairs[1:]):
# check if the end point of the segment lies within the previous
# ones in the current sectionmake
for seg2 in segment_pairs[0: i + 1]:
if is_inside_cylinder(seg1, seg2):
return True
return False | [
"def",
"is_back_tracking",
"(",
"neurite",
")",
":",
"def",
"pair",
"(",
"segs",
")",
":",
"''' Pairs the input list into triplets'''",
"return",
"zip",
"(",
"segs",
",",
"segs",
"[",
"1",
":",
"]",
")",
"def",
"coords",
"(",
"node",
")",
":",
"''' Returns the first three values of the tree that correspond to the x, y, z coordinates'''",
"return",
"node",
"[",
"COLS",
".",
"XYZ",
"]",
"def",
"max_radius",
"(",
"seg",
")",
":",
"''' Returns maximum radius from the two segment endpoints'''",
"return",
"max",
"(",
"seg",
"[",
"0",
"]",
"[",
"COLS",
".",
"R",
"]",
",",
"seg",
"[",
"1",
"]",
"[",
"COLS",
".",
"R",
"]",
")",
"def",
"is_not_zero_seg",
"(",
"seg",
")",
":",
"''' Returns True if segment has zero length'''",
"return",
"not",
"np",
".",
"allclose",
"(",
"coords",
"(",
"seg",
"[",
"0",
"]",
")",
",",
"coords",
"(",
"seg",
"[",
"1",
"]",
")",
")",
"def",
"is_in_the_same_verse",
"(",
"seg1",
",",
"seg2",
")",
":",
"''' Checks if the vectors face the same direction. This\n is true if their dot product is greater than zero.\n '''",
"v1",
"=",
"coords",
"(",
"seg2",
"[",
"1",
"]",
")",
"-",
"coords",
"(",
"seg2",
"[",
"0",
"]",
")",
"v2",
"=",
"coords",
"(",
"seg1",
"[",
"1",
"]",
")",
"-",
"coords",
"(",
"seg1",
"[",
"0",
"]",
")",
"return",
"np",
".",
"dot",
"(",
"v1",
",",
"v2",
")",
">=",
"0",
"def",
"is_seg2_within_seg1_radius",
"(",
"dist",
",",
"seg1",
",",
"seg2",
")",
":",
"''' Checks whether the orthogonal distance from the point at the end of\n seg1 to seg2 segment body is smaller than the sum of their radii\n '''",
"return",
"dist",
"<=",
"max_radius",
"(",
"seg1",
")",
"+",
"max_radius",
"(",
"seg2",
")",
"def",
"is_seg1_overlapping_with_seg2",
"(",
"seg1",
",",
"seg2",
")",
":",
"'''Checks if a segment is in proximity of another one upstream'''",
"# get the coordinates of seg2 (from the origin)",
"s1",
"=",
"coords",
"(",
"seg2",
"[",
"0",
"]",
")",
"s2",
"=",
"coords",
"(",
"seg2",
"[",
"1",
"]",
")",
"# vector of the center of seg2 (from the origin)",
"C",
"=",
"0.5",
"*",
"(",
"s1",
"+",
"s2",
")",
"# endpoint of seg1 (from the origin)",
"P",
"=",
"coords",
"(",
"seg1",
"[",
"1",
"]",
")",
"# vector from the center C of seg2 to the endpoint P of seg1",
"CP",
"=",
"P",
"-",
"C",
"# vector of seg2",
"S1S2",
"=",
"s2",
"-",
"s1",
"# projection of CP upon seg2",
"prj",
"=",
"mm",
".",
"vector_projection",
"(",
"CP",
",",
"S1S2",
")",
"# check if the distance of the orthogonal complement of CP projection on S1S2",
"# (vertical distance from P to seg2) is smaller than the sum of the radii. (overlap)",
"# If not exit early, because there is no way that backtracking can feasible",
"if",
"not",
"is_seg2_within_seg1_radius",
"(",
"np",
".",
"linalg",
".",
"norm",
"(",
"CP",
"-",
"prj",
")",
",",
"seg1",
",",
"seg2",
")",
":",
"return",
"False",
"# projection lies within the length of the cylinder. Check if the distance between",
"# the center C of seg2 and the projection of the end point of seg1, P is smaller than",
"# half of the others length plus a 5% tolerance",
"return",
"np",
".",
"linalg",
".",
"norm",
"(",
"prj",
")",
"<",
"0.55",
"*",
"np",
".",
"linalg",
".",
"norm",
"(",
"S1S2",
")",
"def",
"is_inside_cylinder",
"(",
"seg1",
",",
"seg2",
")",
":",
"''' Checks if seg2 approximately lies within a cylindrical volume of seg1.\n Two conditions must be satisfied:\n 1. The two segments are not facing the same direction (seg2 comes back to seg1)\n 2. seg2 is overlaping with seg1\n '''",
"return",
"not",
"is_in_the_same_verse",
"(",
"seg1",
",",
"seg2",
")",
"and",
"is_seg1_overlapping_with_seg2",
"(",
"seg1",
",",
"seg2",
")",
"# filter out single segment sections",
"section_itr",
"=",
"(",
"snode",
"for",
"snode",
"in",
"neurite",
".",
"iter_sections",
"(",
")",
"if",
"snode",
".",
"points",
".",
"shape",
"[",
"0",
"]",
">",
"2",
")",
"for",
"snode",
"in",
"section_itr",
":",
"# group each section's points intro triplets",
"segment_pairs",
"=",
"list",
"(",
"filter",
"(",
"is_not_zero_seg",
",",
"pair",
"(",
"snode",
".",
"points",
")",
")",
")",
"# filter out zero length segments",
"for",
"i",
",",
"seg1",
"in",
"enumerate",
"(",
"segment_pairs",
"[",
"1",
":",
"]",
")",
":",
"# check if the end point of the segment lies within the previous",
"# ones in the current sectionmake",
"for",
"seg2",
"in",
"segment_pairs",
"[",
"0",
":",
"i",
"+",
"1",
"]",
":",
"if",
"is_inside_cylinder",
"(",
"seg1",
",",
"seg2",
")",
":",
"return",
"True",
"return",
"False"
] | Check if a neurite process backtracks to a previous node. Back-tracking takes place
when a daughter of a branching process goes back and either overlaps with a previous point, or
lies inside the cylindrical volume of the latter.
Args:
neurite(Neurite): neurite to operate on
Returns:
True Under the following scenaria:
1. A segment endpoint falls back and overlaps with a previous segment's point
2. The geometry of a segment overlaps with a previous one in the section | [
"Check",
"if",
"a",
"neurite",
"process",
"backtracks",
"to",
"a",
"previous",
"node",
".",
"Back",
"-",
"tracking",
"takes",
"place",
"when",
"a",
"daughter",
"of",
"a",
"branching",
"process",
"goes",
"back",
"and",
"either",
"overlaps",
"with",
"a",
"previous",
"point",
"or",
"lies",
"inside",
"the",
"cylindrical",
"volume",
"of",
"the",
"latter",
"."
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/morphtree.py#L91-L187 |
2,797 | BlueBrain/NeuroM | neurom/check/morphtree.py | get_flat_neurites | def get_flat_neurites(neuron, tol=0.1, method='ratio'):
'''Check if a neuron has neurites that are flat within a tolerance
Args:
neurite(Neurite): neurite to operate on
tol(float): the tolerance or the ratio
method(string): 'tolerance' or 'ratio' described in :meth:`is_flat`
Returns:
Bool list corresponding to the flatness check for each neurite
in neuron neurites with respect to the given criteria
'''
return [n for n in neuron.neurites if is_flat(n, tol, method)] | python | def get_flat_neurites(neuron, tol=0.1, method='ratio'):
'''Check if a neuron has neurites that are flat within a tolerance
Args:
neurite(Neurite): neurite to operate on
tol(float): the tolerance or the ratio
method(string): 'tolerance' or 'ratio' described in :meth:`is_flat`
Returns:
Bool list corresponding to the flatness check for each neurite
in neuron neurites with respect to the given criteria
'''
return [n for n in neuron.neurites if is_flat(n, tol, method)] | [
"def",
"get_flat_neurites",
"(",
"neuron",
",",
"tol",
"=",
"0.1",
",",
"method",
"=",
"'ratio'",
")",
":",
"return",
"[",
"n",
"for",
"n",
"in",
"neuron",
".",
"neurites",
"if",
"is_flat",
"(",
"n",
",",
"tol",
",",
"method",
")",
"]"
] | Check if a neuron has neurites that are flat within a tolerance
Args:
neurite(Neurite): neurite to operate on
tol(float): the tolerance or the ratio
method(string): 'tolerance' or 'ratio' described in :meth:`is_flat`
Returns:
Bool list corresponding to the flatness check for each neurite
in neuron neurites with respect to the given criteria | [
"Check",
"if",
"a",
"neuron",
"has",
"neurites",
"that",
"are",
"flat",
"within",
"a",
"tolerance"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/morphtree.py#L190-L202 |
2,798 | BlueBrain/NeuroM | neurom/check/morphtree.py | get_nonmonotonic_neurites | def get_nonmonotonic_neurites(neuron, tol=1e-6):
'''Get neurites that are not monotonic
Args:
neurite(Neurite): neurite to operate on
tol(float): the tolerance or the ratio
Returns:
list of neurites that do not satisfy monotonicity test
'''
return [n for n in neuron.neurites if not is_monotonic(n, tol)] | python | def get_nonmonotonic_neurites(neuron, tol=1e-6):
'''Get neurites that are not monotonic
Args:
neurite(Neurite): neurite to operate on
tol(float): the tolerance or the ratio
Returns:
list of neurites that do not satisfy monotonicity test
'''
return [n for n in neuron.neurites if not is_monotonic(n, tol)] | [
"def",
"get_nonmonotonic_neurites",
"(",
"neuron",
",",
"tol",
"=",
"1e-6",
")",
":",
"return",
"[",
"n",
"for",
"n",
"in",
"neuron",
".",
"neurites",
"if",
"not",
"is_monotonic",
"(",
"n",
",",
"tol",
")",
"]"
] | Get neurites that are not monotonic
Args:
neurite(Neurite): neurite to operate on
tol(float): the tolerance or the ratio
Returns:
list of neurites that do not satisfy monotonicity test | [
"Get",
"neurites",
"that",
"are",
"not",
"monotonic"
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/morphtree.py#L205-L215 |
2,799 | BlueBrain/NeuroM | examples/radius_of_gyration.py | segment_centre_of_mass | def segment_centre_of_mass(seg):
'''Calculate and return centre of mass of a segment.
C, seg_volalculated as centre of mass of conical frustum'''
h = mm.segment_length(seg)
r0 = seg[0][COLS.R]
r1 = seg[1][COLS.R]
num = r0 * r0 + 2 * r0 * r1 + 3 * r1 * r1
denom = 4 * (r0 * r0 + r0 * r1 + r1 * r1)
centre_of_mass_z_loc = num / denom
return seg[0][COLS.XYZ] + (centre_of_mass_z_loc / h) * (seg[1][COLS.XYZ] - seg[0][COLS.XYZ]) | python | def segment_centre_of_mass(seg):
'''Calculate and return centre of mass of a segment.
C, seg_volalculated as centre of mass of conical frustum'''
h = mm.segment_length(seg)
r0 = seg[0][COLS.R]
r1 = seg[1][COLS.R]
num = r0 * r0 + 2 * r0 * r1 + 3 * r1 * r1
denom = 4 * (r0 * r0 + r0 * r1 + r1 * r1)
centre_of_mass_z_loc = num / denom
return seg[0][COLS.XYZ] + (centre_of_mass_z_loc / h) * (seg[1][COLS.XYZ] - seg[0][COLS.XYZ]) | [
"def",
"segment_centre_of_mass",
"(",
"seg",
")",
":",
"h",
"=",
"mm",
".",
"segment_length",
"(",
"seg",
")",
"r0",
"=",
"seg",
"[",
"0",
"]",
"[",
"COLS",
".",
"R",
"]",
"r1",
"=",
"seg",
"[",
"1",
"]",
"[",
"COLS",
".",
"R",
"]",
"num",
"=",
"r0",
"*",
"r0",
"+",
"2",
"*",
"r0",
"*",
"r1",
"+",
"3",
"*",
"r1",
"*",
"r1",
"denom",
"=",
"4",
"*",
"(",
"r0",
"*",
"r0",
"+",
"r0",
"*",
"r1",
"+",
"r1",
"*",
"r1",
")",
"centre_of_mass_z_loc",
"=",
"num",
"/",
"denom",
"return",
"seg",
"[",
"0",
"]",
"[",
"COLS",
".",
"XYZ",
"]",
"+",
"(",
"centre_of_mass_z_loc",
"/",
"h",
")",
"*",
"(",
"seg",
"[",
"1",
"]",
"[",
"COLS",
".",
"XYZ",
"]",
"-",
"seg",
"[",
"0",
"]",
"[",
"COLS",
".",
"XYZ",
"]",
")"
] | Calculate and return centre of mass of a segment.
C, seg_volalculated as centre of mass of conical frustum | [
"Calculate",
"and",
"return",
"centre",
"of",
"mass",
"of",
"a",
"segment",
"."
] | 254bb73535b20053d175bc4725bade662177d12b | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/examples/radius_of_gyration.py#L38-L48 |
Subsets and Splits