Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Format long lists in tests #1057

Merged
merged 4 commits into from
Apr 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions examples/boxplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,7 @@ def boxplot(neurons, feature, new_fig=True, subplot=111):


def main():

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

Expand Down
102 changes: 68 additions & 34 deletions examples/density_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,75 +42,109 @@
PACKAGE_DIR = Path(__file__).resolve().parent.parent


def extract_density(population, plane='xy', bins=100, neurite_type=NeuriteType.basal_dendrite):
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.
coordinates of segments in the selected plane.
"""
segment_midpoints = np.array(
get_feat('segment_midpoints', population, neurite_type=neurite_type)
get_feat("segment_midpoints", population, neurite_type=neurite_type)
)
horiz = segment_midpoints[:, 'xyz'.index(plane[0])]
vert = segment_midpoints[:, 'xyz'.index(plane[1])]
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 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):
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.
coordinates of segments in the selected plane.
"""
fig, ax = matplotlib_utils.get_figure(new_fig=new_fig, subplot=subplot)

H1, xedges1, yedges1 = extract_density(population, plane=plane, bins=bins,
neurite_type=neurite_type)
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)

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=colormap, levels=levels)
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=colormap,
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])
kwargs["title"] = kwargs.get("title", "")
kwargs["xlabel"] = kwargs.get("xlabel", plane[0])
kwargs["ylabel"] = kwargs.get("ylabel", plane[1])

return matplotlib_utils.plot_style(fig=fig, ax=ax, **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):
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.
coordinates of segments in the selected plane
and superimposes the view of the first neurite of the collection.
"""
_, ax = matplotlib_utils.get_figure(new_fig=new_fig)

ref_neuron = population[0]
matplotlib_impl.plot_tree(ref_neuron.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)
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)

Expand Down
49 changes: 29 additions & 20 deletions examples/end_to_end_distance.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,7 @@
def path_end_to_end_distance(neurite):
"""Calculate and return end-to-end-distance of a given neurite."""
trunk = neurite.root_node.points[0]
return max(morphmath.point_dist(l.points[-1], trunk)
for l in neurite.root_node.ileaf())
return max(morphmath.point_dist(l.points[-1], trunk) for l in neurite.root_node.ileaf())


def mean_end_to_end_dist(neurites):
Expand All @@ -56,48 +55,58 @@ def make_end_to_end_distance_plot(nb_segments, end_to_end_distance, neurite_type
plt.figure()
plt.plot(nb_segments, end_to_end_distance)
plt.title(neurite_type)
plt.xlabel('Number of segments')
plt.ylabel('End-to-end distance')
plt.xlabel("Number of segments")
plt.ylabel("End-to-end distance")
# uncomment to show
#plt.show()
# plt.show()


def calculate_and_plot_end_to_end_distance(neurite):
"""Calculate and plot the end-to-end distance vs the number of segments for
an increasingly larger part of a given neurite.

Note that the plots are not very meaningful for bifurcating trees."""

def _dist(seg):
"""Distance between segmenr end and trunk."""
return morphmath.point_dist(seg[1], neurite.root_node.points[0])

end_to_end_distance = [_dist(s) for s in nm.iter_segments(neurite)]
make_end_to_end_distance_plot(np.arange(len(end_to_end_distance)) + 1,
end_to_end_distance, neurite.type)
make_end_to_end_distance_plot(
np.arange(len(end_to_end_distance)) + 1, end_to_end_distance, neurite.type
)


def main():
# load a neuron from an SWC file
filename = Path(PACKAGE_DIR, '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
print('Mean end-to-end distance for axons: ',
mean_end_to_end_dist(n for n in m.neurites if n.type == nm.AXON))
print('Mean end-to-end distance for basal dendrites: ',
mean_end_to_end_dist(n for n in m.neurites if n.type == nm.BASAL_DENDRITE))
print('Mean end-to-end distance for apical dendrites: ',
mean_end_to_end_dist(n for n in m.neurites
if n.type == nm.APICAL_DENDRITE))

print('End-to-end distance per neurite (nb segments, end-to-end distance, neurite type):')
print(
"Mean end-to-end distance for axons: ",
mean_end_to_end_dist(n for n in m.neurites if n.type == nm.AXON),
)
print(
"Mean end-to-end distance for basal dendrites: ",
mean_end_to_end_dist(n for n in m.neurites if n.type == nm.BASAL_DENDRITE),
)
print(
"Mean end-to-end distance for apical dendrites: ",
mean_end_to_end_dist(n for n in m.neurites if n.type == nm.APICAL_DENDRITE),
)

print("End-to-end distance per neurite (nb segments, end-to-end distance, neurite type):")
for nrte in m.neurites:
# plot end-to-end distance for increasingly larger parts of neurite
calculate_and_plot_end_to_end_distance(nrte)
# 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)
print(
sum(len(s.points) - 1 for s in nrte.root_node.ipreorder()),
path_end_to_end_distance(nrte),
nrte.type,
)


if __name__ == '__main__':
if __name__ == "__main__":
main()
15 changes: 6 additions & 9 deletions examples/extract_distribution.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,9 @@

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.
and transforms the fitted distribution in the correct format.
Returns the optimal distribution, corresponding parameters,
minimun and maximum values.
"""
population = nm.load_morphologies(population_directory)

Expand All @@ -60,17 +60,14 @@ def find_optimal_distribution(population_directory, feature):


def main():

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

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

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


if __name__ == '__main__':
if __name__ == "__main__":
main()
15 changes: 6 additions & 9 deletions examples/features_graph_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,9 @@


def stylize(ax, name, feature):
"""Stylization modifications to the plots
"""
"""Stylization modifications to the plots"""
ax.set_ylabel(feature)
ax.set_title(name, fontsize='small')
ax.set_title(name, fontsize="small")


def histogram(neuron, feature, ax, bins=15, normed=True, cumulative=False):
Expand Down Expand Up @@ -73,8 +72,7 @@ def histogram(neuron, feature, ax, bins=15, normed=True, cumulative=False):


def plot_feature(feature, cell):
"""Plot a feature
"""
"""Plot a feature"""
fig = pl.figure()
ax = fig.add_subplot(111)

Expand All @@ -88,7 +86,6 @@ def plot_feature(feature, cell):


def create_feature_plots(morphologies_dir, feature_list, output_dir):

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

Expand All @@ -102,10 +99,10 @@ def create_feature_plots(morphologies_dir, feature_list, output_dir):
def main():
create_feature_plots(
morphologies_dir=Path(PACKAGE_DIR, "tests/data/valid_set"),
feature_list=["section_lengths"],
output_dir=".",
feature_list=["section_lengths"],
output_dir=".",
)


if __name__ == '__main__':
if __name__ == "__main__":
main()
Loading
Loading