Skip to content

Commit

Permalink
Black examples and lint
Browse files Browse the repository at this point in the history
  • Loading branch information
adrien-berchet committed Feb 2, 2023
1 parent 4927385 commit 84f177a
Show file tree
Hide file tree
Showing 19 changed files with 268 additions and 191 deletions.
3 changes: 1 addition & 2 deletions examples/boxplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,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
86 changes: 60 additions & 26 deletions examples/density_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,39 +44,53 @@

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])]
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)
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)
Expand All @@ -89,27 +103,47 @@ def plot_density(population, # pylint: disable=too-many-arguments, too-many-loc
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)

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)
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
37 changes: 23 additions & 14 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 @@ -59,21 +58,23 @@ def make_end_to_end_distance_plot(nb_segments, end_to_end_distance, neurite_type
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():
Expand All @@ -82,21 +83,29 @@ def main():
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(
'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__':
Expand Down
13 changes: 5 additions & 8 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,16 +60,13 @@ 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__':
Expand Down
11 changes: 4 additions & 7 deletions examples/features_graph_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,7 @@


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')

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,8 +99,8 @@ 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=".",
)


Expand Down
77 changes: 46 additions & 31 deletions examples/get_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,14 @@ def stats(data):
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)}
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 pprint_stats(data):
Expand All @@ -64,7 +66,6 @@ def pprint_stats(data):


def main():

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

# load a neuron from an SWC file
Expand All @@ -85,34 +86,48 @@ def main():

# number of neurites
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))
print('Number of neurites (apical dendrites):',
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))
print(
'Number of neurites (axons):',
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),
)
print(
'Number of neurites (basal dendrites):',
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))
print('Number of sections (axons):',
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))
print('Number of sections (basal dendrites):',
nm.get('number_of_sections', m, neurite_type=nm.NeuriteType.basal_dendrite))
print('Number of sections:', nm.get('number_of_sections', m))
print(
'Number of sections (axons):',
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),
)
print(
'Number of sections (basal dendrites):',
nm.get('number_of_sections', m, neurite_type=nm.NeuriteType.basal_dendrite),
)

# number of sections per neurite
print('Number of sections per neurite:',
nm.get('number_of_sections_per_neurite', m))
print('Number of sections per neurite (axons):',
nm.get('number_of_sections_per_neurite', m, neurite_type=nm.NeuriteType.axon))
print('Number of sections per neurite (apical dendrites):',
nm.get('number_of_sections_per_neurite',
m, neurite_type=nm.NeuriteType.apical_dendrite))
print('Number of sections per neurite (basal dendrites):',
nm.get('number_of_sections_per_neurite',
m, neurite_type=nm.NeuriteType.apical_dendrite))
print('Number of sections per neurite:', nm.get('number_of_sections_per_neurite', m))
print(
'Number of sections per neurite (axons):',
nm.get('number_of_sections_per_neurite', m, neurite_type=nm.NeuriteType.axon),
)
print(
'Number of sections per neurite (apical dendrites):',
nm.get('number_of_sections_per_neurite', m, neurite_type=nm.NeuriteType.apical_dendrite),
)
print(
'Number of sections per neurite (basal dendrites):',
nm.get('number_of_sections_per_neurite', m, neurite_type=nm.NeuriteType.apical_dendrite),
)

# OK, this is getting repetitive, so lets loop over valid neurite types.
# The following methods return arrays of measurements. We will gather some
Expand Down
Loading

0 comments on commit 84f177a

Please sign in to comment.