Skip to content

Commit

Permalink
Add testing of example scripts (#1041)
Browse files Browse the repository at this point in the history
eleftherioszisis authored May 24, 2022
1 parent ed338f3 commit 0f3b8d0
Showing 16 changed files with 254 additions and 557 deletions.
26 changes: 23 additions & 3 deletions examples/boxplot.py
Original file line number Diff line number Diff line change
@@ -28,11 +28,17 @@
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""Box Plot function for multiple morphs."""
from pathlib import Path

from neurom import load_morphologies
from neurom.view import matplotlib_utils
from neurom.features import get


def boxplot(neurons, feature, new_fig=True, subplot=False):
PACKAGE_DIR = Path(__file__).resolve().parent.parent


def boxplot(neurons, feature, new_fig=True, subplot=111):
"""Plot a histogram of the selected feature for the population of morphologies.
Plots x-axis versus y-axis on a scatter|histogram|binned values plot.
@@ -53,12 +59,26 @@ def boxplot(neurons, feature, new_fig=True, subplot=False):
Default is False, which returns a matplotlib figure object. If True,
returns a matplotlib axis object, for use as a subplot.
"""
feature_values = [getattr(neu, 'get_' + feature)() for neu in neurons]
feature_values = [get(feature, neuron) for neuron in neurons]

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

ax.boxplot(feature_values)

x_labels = ['neuron_id' for _ in neurons]
x_labels = [neuron.name for neuron in neurons]

ax.set_xticklabels(x_labels)

# uncomment below to show image
# pylab.show()


def main():

morphology_directory = Path(PACKAGE_DIR, "tests/data/valid_set")
neurons = load_morphologies(morphology_directory)
boxplot(neurons, "section_lengths")


if __name__ == "__main__":
main()
30 changes: 26 additions & 4 deletions examples/density_plot.py
Original file line number Diff line number Diff line change
@@ -27,20 +27,28 @@
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""Example for generating density plots."""
from pathlib import Path

import pylab as plt
import matplotlib as mpl
import numpy as np

from neurom import get as get_feat
from neurom.view import matplotlib_utils, matplotlib_impl
from neurom.core.types import NeuriteType

from neurom import load_morphologies

PACKAGE_DIR = Path(__file__).resolve().parent.parent


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)
segment_midpoints = np.array(
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))
@@ -62,12 +70,13 @@ def plot_density(population, # pylint: disable=too-many-arguments, too-many-loc
mask = H1 < threshold # mask = H1==0
H2 = np.ma.masked_array(H1, mask)

getattr(plt.cm, color_map).set_bad(color='white', alpha=None)
colormap = mpl.cm.get_cmap(color_map).copy()
colormap.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)
cmap=colormap, levels=levels)

if not no_colorbar:
cbar = plt.colorbar(plots)
@@ -91,9 +100,22 @@ def plot_neuron_on_density(population, # pylint: disable=too-many-arguments
"""
_, ax = matplotlib_utils.get_figure(new_fig=new_fig)

matplotlib_impl.plot_tree(population.neurites[0], ax)
matplotlib_impl.plot_tree(list(population)[0].neurites[0], ax)

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 main():

morphology_directory = Path(PACKAGE_DIR, "tests/data/valid_set")
neurons = load_morphologies(morphology_directory)

plot_density(neurons)
plot_neuron_on_density(neurons)


if __name__ == "__main__":
main()
15 changes: 12 additions & 3 deletions examples/end_to_end_distance.py
Original file line number Diff line number Diff line change
@@ -28,13 +28,17 @@
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""Calculate and plot end-to-end distance of neurites."""
from pathlib import Path

import neurom as nm
from neurom import morphmath
import numpy as np
import matplotlib.pyplot as plt


PACKAGE_DIR = Path(__file__).resolve().parent.parent


def path_end_to_end_distance(neurite):
"""Calculate and return end-to-end-distance of a given neurite."""
trunk = neurite.root_node.points[0]
@@ -54,7 +58,8 @@ def make_end_to_end_distance_plot(nb_segments, end_to_end_distance, neurite_type
plt.title(neurite_type)
plt.xlabel('Number of segments')
plt.ylabel('End-to-end distance')
plt.show()
# uncomment to show
#plt.show()


def calculate_and_plot_end_to_end_distance(neurite):
@@ -71,9 +76,9 @@ def _dist(seg):
end_to_end_distance, neurite.type)


if __name__ == '__main__':
def main():
# load a neuron from an SWC file
filename = 'tests/data/swc/Neuron_3_random_walker_branches.swc'
filename = Path(PACKAGE_DIR, 'tests/data/swc/Neuron_3_random_walker_branches.swc')
m = nm.load_morphology(filename)

# print mean end-to-end distance per neurite type
@@ -92,3 +97,7 @@ def _dist(seg):
# print (number of segments, end-to-end distance, neurite type)
print(sum(len(s.points) - 1 for s in nrte.root_node.ipreorder()),
path_end_to_end_distance(nrte), nrte.type)


if __name__ == '__main__':
main()
38 changes: 16 additions & 22 deletions examples/extract_distribution.py
Original file line number Diff line number Diff line change
@@ -31,52 +31,46 @@
"""Extract a distribution for the selected feature of the population of morphologies among
the exponential, normal and uniform distribution, according to the minimum ks distance.
"""
from pathlib import Path

from itertools import chain
import argparse
import json

import neurom as nm
from neurom import stats
from neurom.utils import NeuromJSON


def parse_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(
description='Morphology fit distribution extractor',
epilog='Note: Outputs json of the optimal distribution \
and corresponding parameters.')
PACKAGE_DIR = Path(__file__).resolve().parent.parent

parser.add_argument('datapath',
help='Path to morphology data directory')

parser.add_argument('feature',
help='Feature to be extracted with neurom.get')

return parser.parse_args()


def extract_data(data_path, feature):
def find_optimal_distribution(population_directory, feature):
"""Loads a list of morphologies, extracts feature
and transforms the fitted distribution in the correct format.
Returns the optimal distribution, corresponding parameters,
minimun and maximum values.
"""
population = nm.load_morphologies(data_path)
population = nm.load_morphologies(population_directory)

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

return stats.optimal_distribution(feature_data)


if __name__ == '__main__':
args = parse_args()
def main():

population_directory = Path(PACKAGE_DIR, "tests/data/valid_set")

d_path = args.datapath
result = stats.fit_results_to_dict(
find_optimal_distribution(population_directory, "section_lengths")
)

feat = args.feature
print(json.dumps(
result, indent=2, separators=(',', ': '), cls=NeuromJSON
))

_result = stats.fit_results_to_dict(extract_data(d_path, feat))

print(json.dumps(_result, indent=2, separators=(',', ': ')))
if __name__ == '__main__':
main()
48 changes: 20 additions & 28 deletions examples/features_graph_table.py
Original file line number Diff line number Diff line change
@@ -28,33 +28,14 @@
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""Example for comparison of the same feature of multiple cells."""
import argparse
from pathlib import Path

import pylab as pl
import neurom as nm
from neurom.io.utils import get_morph_files


def parse_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(description='Feature Comparison Between Different Cells')

parser.add_argument('-d',
'--datapath',
help='Data directory')

parser.add_argument('-o',
'--odir',
default='.',
help='Output path')

parser.add_argument('-f',
'--features',
nargs='+',
help='List features separated by spaces')

return parser.parse_args()
PACKAGE_DIR = Path(__file__).resolve().parent.parent


def stylize(ax, name, feature):
@@ -88,7 +69,7 @@ def histogram(neuron, feature, ax, bins=15, normed=True, cumulative=False):

feature_values = nm.get(feature, neuron)
# generate histogram
ax.hist(feature_values, bins=bins, cumulative=cumulative, normed=normed)
ax.hist(feature_values, bins=bins, cumulative=cumulative, density=normed)


def plot_feature(feature, cell):
@@ -106,14 +87,25 @@ def plot_feature(feature, cell):
return fig


if __name__ == '__main__':
args = parse_args()
def create_feature_plots(morphologies_dir, feature_list, output_dir):

for morph_file in get_morph_files(args.datapath):
for morph_file in get_morph_files(morphologies_dir):
m = nm.load_morphology(morph_file)

for _feature in args.features:
f = plot_feature(_feature, m)
figname = "{0}_{1}.eps".format(_feature, m.name)
f.savefig(Path(args.odir, figname))
for feature_name in feature_list:
f = plot_feature(feature_name, m)
figname = f"{feature_name}_{m.name}.eps"
f.savefig(Path(output_dir, figname))
pl.close(f)


def main():
create_feature_plots(
morphologies_dir=Path(PACKAGE_DIR, "tests/data/valid_set"),
feature_list=["section_lengths"],
output_dir=".",
)


if __name__ == '__main__':
main()
33 changes: 20 additions & 13 deletions examples/get_features.py
Original file line number Diff line number Diff line change
@@ -33,13 +33,16 @@
morphometrics functionality.
"""
from pathlib import Path

from __future__ import print_function
from pprint import pprint
import numpy as np
import neurom as nm


PACKAGE_DIR = Path(__file__).resolve().parent.parent


def stats(data):
"""Dictionary with summary stats for data
@@ -60,17 +63,17 @@ def pprint_stats(data):
pprint(stats(data))


if __name__ == '__main__':
def main():

filename = 'tests/data/swc/Neuron.swc'
filename = Path(PACKAGE_DIR, 'tests/data/swc/Neuron.swc')

# load a neuron from an SWC file
m = nm.load_morphology(filename)

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

# Get information about neurites
# Most neurite data can be queried for a particular type of neurite.
@@ -81,23 +84,23 @@ def pprint_stats(data):
# to warm up...

# number of neurites
print('Number of neurites (all):', nm.get('number_of_neurites', m)[0])
print('Number of neurites (all):', nm.get('number_of_neurites', m))
print('Number of neurites (axons):',
nm.get('number_of_neurites', m, neurite_type=nm.NeuriteType.axon)[0])
nm.get('number_of_neurites', m, neurite_type=nm.NeuriteType.axon))
print('Number of neurites (apical dendrites):',
nm.get('number_of_neurites', m, neurite_type=nm.NeuriteType.apical_dendrite)[0])
nm.get('number_of_neurites', m, neurite_type=nm.NeuriteType.apical_dendrite))
print('Number of neurites (basal dendrites):',
nm.get('number_of_neurites', m, neurite_type=nm.NeuriteType.basal_dendrite)[0])
nm.get('number_of_neurites', m, neurite_type=nm.NeuriteType.basal_dendrite))

# number of sections
print('Number of sections:',
nm.get('number_of_sections', m)[0])
nm.get('number_of_sections', m))
print('Number of sections (axons):',
nm.get('number_of_sections', m, neurite_type=nm.NeuriteType.axon)[0])
nm.get('number_of_sections', m, neurite_type=nm.NeuriteType.axon))
print('Number of sections (apical dendrites):',
nm.get('number_of_sections', m, neurite_type=nm.NeuriteType.apical_dendrite)[0])
nm.get('number_of_sections', m, neurite_type=nm.NeuriteType.apical_dendrite))
print('Number of sections (basal dendrites):',
nm.get('number_of_sections', m, neurite_type=nm.NeuriteType.basal_dendrite)[0])
nm.get('number_of_sections', m, neurite_type=nm.NeuriteType.basal_dendrite))

# number of sections per neurite
print('Number of sections per neurite:',
@@ -152,3 +155,7 @@ def pprint_stats(data):
rem_bifangles = nm.get('remote_bifurcation_angles', m, neurite_type=ttype)
print('Local bifurcation angles (', ttype, '):', sep='')
pprint_stats(rem_bifangles)


if __name__ == '__main__':
main()
30 changes: 24 additions & 6 deletions examples/histogram.py
Original file line number Diff line number Diff line change
@@ -28,13 +28,20 @@
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""Simple Histogram function for multiple morphologies."""
from pathlib import Path

from itertools import chain

import numpy as np
import neurom.features
from neurom.view import matplotlib_utils
from neurom import load_morphologies


PACKAGE_DIR = Path(__file__).resolve().parent.parent

def histogram(neurons, feature, new_fig=True, subplot=False, normed=False, **kwargs):

def histogram(neurons, feature, new_fig=True, subplot=111, normed=False, **kwargs):
"""
Plot a histogram of the selected feature for the population of morphologies.
Plots x-axis versus y-axis on a scatter|histogram|binned values plot.
@@ -81,11 +88,11 @@ def histogram(neurons, feature, new_fig=True, subplot=False, normed=False, **kwa

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

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

neu_labels = [neu.name for neu in neurons]

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

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

@@ -99,7 +106,7 @@ def population_feature_values(pops, feature):

for pop in pops:

feature_values = [getattr(neu, 'get_' + feature)() for neu in pop.morphologies]
feature_values = [neurom.features.get(feature, neu) for neu in pop]

# ugly hack to chain in case of list of lists
if any([isinstance(p, (list, np.ndarray)) for p in feature_values]):
@@ -111,7 +118,7 @@ def population_feature_values(pops, feature):
return pops_feature_values


def population_histogram(pops, feature, new_fig=True, normed=False, subplot=False, **kwargs):
def population_histogram(pops, feature, new_fig=True, normed=False, subplot=111, **kwargs):
"""
Plot a histogram of the selected feature for the population of morphologies.
Plots x-axis versus y-axis on a scatter|histogram|binned values plot.
@@ -161,8 +168,19 @@ def population_histogram(pops, feature, new_fig=True, normed=False, subplot=Fals

pops_labels = [pop.name for pop in pops]

ax.hist(pops_feature_values, bins=bins, cumulative=cumulative, label=pops_labels, normed=normed)
ax.hist(pops_feature_values, bins=bins, cumulative=cumulative, label=pops_labels, density=normed)

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

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


def main():

pop1 = load_morphologies(Path(PACKAGE_DIR, "tests/data/valid_set"))
pop2 = load_morphologies(Path(PACKAGE_DIR, "tests/data/valid_set"))
population_histogram([pop1, pop2], "section_lengths")


if __name__ == "__main__":
main()
12 changes: 9 additions & 3 deletions examples/iteration_analysis.py
Original file line number Diff line number Diff line change
@@ -33,8 +33,8 @@
morphometrics functionality using iterators.
"""
from pathlib import Path

from __future__ import print_function
from neurom.core.dataformat import COLS
import neurom as nm
from neurom import geom
@@ -44,10 +44,12 @@
from neurom import morphmath as mm
import numpy as np

PACKAGE_DIR = Path(__file__).resolve().parent.parent

if __name__ == '__main__':

filename = 'tests/data/swc/Neuron.swc'
def main():

filename = Path(PACKAGE_DIR, 'tests/data/swc/Neuron.swc')

# load a neuron from an SWC file
m = nm.load_morphology(filename)
@@ -142,3 +144,7 @@ def n_points(sec):
# Morphology's bounding box
# Note: does not account for soma radius
print('Bounding box ((min x, y, z), (max x, y, z))', geom.bounding_box(m))


if __name__ == '__main__':
main()
57 changes: 32 additions & 25 deletions examples/nl_fst_compat.py
Original file line number Diff line number Diff line change
@@ -28,32 +28,39 @@
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Compatibility between NL and H5 files."""
# pylint: disable=protected-access
from pathlib import Path

import numpy as np

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

m_h5 = nm.load_morphology('tests/data/h5/v1/bio_neuron-001.h5')
m_asc = nm.load_morphology('tests/data/neurolucida/bio_neuron-001.asc')

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

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

print('\nNumber of segments:')
for nt in iter(nm.NeuriteType):
print(nt, _nf.n_segments(m_h5, neurite_type=nt), _nf.n_segments(m_asc, neurite_type=nt))
from neurom.features import neurite as nf
from neurom.features import morphology as mf

PACKAGE_DIR = Path(__file__).resolve().parent.parent


def main():

m_h5 = nm.load_morphology(Path(PACKAGE_DIR, 'tests/data/h5/v1/bio_neuron-001.h5'))
m_asc = nm.load_morphology(Path(PACKAGE_DIR, 'tests/data/neurolucida/bio_neuron-001.asc'))

print('h5 number of sections:', nm.get('number_of_sections', m_h5))
print('nl number of sections:', nm.get('number_of_sections', m_asc))
print('h5 number of segments:', nm.get('number_of_segments', m_h5))
print('nl number of segments:', nm.get('number_of_segments', m_asc))
print('h5 total neurite length:', np.sum(nm.get('section_lengths', m_h5)))
print('nl total neurite length:', np.sum(nm.get('section_lengths', m_asc)))
print('h5 principal direction extents:', nm.get('principal_direction_extents', m_h5))
print('nl principal direction extents:', nm.get('principal_direction_extents', m_asc))

print('\nNumber of neurites:')
for nt in iter(nm.NeuriteType):
print(nt, mf.number_of_neurites(m_h5, neurite_type=nt), mf.number_of_neurites(m_asc, neurite_type=nt))

print('\nNumber of segments:')
for nt in iter(nm.NeuriteType):
print(nt, nf.number_of_segments(m_h5.neurites[0]), nf.number_of_segments(m_asc.neurites[0]))


if __name__ == "__main__":
main()
202 changes: 0 additions & 202 deletions examples/plot_features.py

This file was deleted.

18 changes: 11 additions & 7 deletions examples/plot_somas.py
Original file line number Diff line number Diff line change
@@ -36,30 +36,34 @@
import matplotlib.pyplot as plt
import numpy as np

DATA_PATH = Path(__file__).parent.parent / 'tests/data'
SWC_PATH = Path(DATA_PATH, 'swc')
DATA_PATH = Path(__file__).resolve().parent.parent / 'tests/data/swc'


def random_color():
"""Random color generation."""
return np.random.rand(3, 1)
return np.random.rand(4)


def plot_somas(somas):
"""Plot set of somas on same figure as spheres, each with different color."""
_, ax = matplotlib_utils.get_figure(new_fig=True, subplot=111,
params={'projection': '3d', 'aspect': 'equal'})
params={'projection': '3d', 'aspect': 'auto'})
for s in somas:
matplotlib_utils.plot_sphere(ax, s.center, s.radius, color=random_color(), alpha=1)
plt.show()

# uncomment to show
# plt.show()

if __name__ == '__main__':

def main():
# define set of files containing relevant morphs
file_nms = [Path(SWC_PATH, file_nm) for file_nm in ['Soma_origin.swc',
file_nms = [Path(DATA_PATH, file_nm) for file_nm in ['Soma_origin.swc',
'Soma_translated_1.swc',
'Soma_translated_2.swc']]

# load from file and plot
sms = [load_morphology(file_nm).soma for file_nm in file_nms]
plot_somas(sms)

if __name__ == '__main__':
main()
17 changes: 13 additions & 4 deletions examples/radius_of_gyration.py
Original file line number Diff line number Diff line change
@@ -28,13 +28,17 @@
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""Calculate radius of gyration of neurites."""
from pathlib import Path

import neurom as nm
from neurom import morphmath as mm
from neurom.core.dataformat import COLS
import numpy as np


PACKAGE_DIR = Path(__file__).resolve().parent.parent


def segment_centre_of_mass(seg):
"""Calculate and return centre of mass of a segment.
@@ -53,8 +57,8 @@ def neurite_centre_of_mass(neurite):
centre_of_mass = np.zeros(3)
total_volume = 0

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

# multiply array of scalars with array of arrays
# http://stackoverflow.com/questions/5795700/multiply-numpy-array-of-scalars-by-array-of-vectors
@@ -87,9 +91,10 @@ def mean_rad_of_gyration(neurites):
return np.mean([radius_of_gyration(n) for n in neurites])


if __name__ == '__main__':
def main():

# load a neuron from an SWC file
filename = 'tests/data/swc/Neuron.swc'
filename = Path(PACKAGE_DIR, 'tests/data/swc/Neuron.swc')
m = nm.load_morphology(filename)

# for every neurite, print (number of segments, radius of gyration, neurite type)
@@ -104,3 +109,7 @@ def mean_rad_of_gyration(neurites):
print('Mean radius of gyration for apical dendrites: ',
mean_rad_of_gyration(n for n in m.neurites
if n.type == nm.APICAL_DENDRITE))


if __name__ == '__main__':
main()
12 changes: 10 additions & 2 deletions examples/section_ids.py
Original file line number Diff line number Diff line change
@@ -28,12 +28,16 @@
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""Get sections and segments by ID."""
from pathlib import Path

import neurom as nm
from neurom import morphmath as mm
from neurom.core.dataformat import COLS


PACKAGE_DIR = Path(__file__).resolve().parent.parent


def get_segment(neuron, section_id, segment_id):
"""Get a segment given a section and segment id
@@ -44,11 +48,15 @@ def get_segment(neuron, section_id, segment_id):
return sec.points[segment_id:segment_id + 2][:, COLS.XYZR]


if __name__ == '__main__':
def main():

m = nm.load_morphology('tests/data/h5/v1/Neuron.h5')
m = nm.load_morphology(Path(PACKAGE_DIR, 'tests/data/h5/v1/Neuron.h5'))

seg = get_segment(m, 3, 2)
print('Segment:\n', seg)
print('Mid-point (x, y, z):\n', mm.linear_interpolate(seg[0], seg[1], 0.5))
print('Mid-point R:\n', mm.interpolate_radius(seg[0][COLS.R], seg[1][COLS.R], 0.5))


if __name__ == '__main__':
main()
30 changes: 11 additions & 19 deletions examples/soma_radius_fit.py
Original file line number Diff line number Diff line change
@@ -31,23 +31,13 @@
"""Extract a distribution for the soma radii of the population (list) of morphologies.
for the soma radii of the population (list) of morphologies.
"""

import argparse
from pathlib import Path

import neurom as nm
from neurom import stats as st


def parse_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(
description='Morphology fit distribution extractor',
epilog='Note: Prints the optimal distribution and corresponding parameters.')

parser.add_argument('datapath',
help='Path to morphology data file or directory')

return parser.parse_args()
PACKAGE_DIR = Path(__file__).resolve().parent.parent


def test_multiple_distr(filepath):
@@ -61,17 +51,19 @@ def test_multiple_distr(filepath):
distr_to_check = ('norm', 'expon', 'uniform')

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

# Find the best fit distribution
return st.optimal_distribution(soma_size, distr_to_check)


if __name__ == '__main__':
args = parse_args()
def main():

data_path = args.datapath
morphology_path = Path(PACKAGE_DIR, "tests/data/swc/Neuron.swc")

result = test_multiple_distr(data_path)
print("Optimal distribution fit for soma radius is: %s with parameters %s" %
(result.type, result.params))
result = test_multiple_distr(morphology_path)
print(f"Optimal distribution fit for soma radius is: {result.type} with parameters {result.params}")


if __name__ == '__main__':
main()
216 changes: 0 additions & 216 deletions examples/synthesis_json.py

This file was deleted.

27 changes: 27 additions & 0 deletions tests/test_examples.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import os
import tempfile
import importlib.util
from pathlib import Path

import pytest

TESTS_DIR = Path(__file__).resolve().parent

EXAMPLES_DIR = TESTS_DIR.parent / "examples"
print(EXAMPLES_DIR)

@pytest.mark.parametrize("filepath", EXAMPLES_DIR.glob("*.py"))
def test_example(filepath):

spec = importlib.util.spec_from_file_location(filepath.stem, filepath)
module = spec.loader.load_module()

with tempfile.TemporaryDirectory() as tempdir:

# change directory to avoid creating files in the root folder
try:
cwd = os.getcwd()
os.chdir(tempdir)
module.main()
finally:
os.chdir(cwd)

0 comments on commit 0f3b8d0

Please sign in to comment.