# API Documentation¶

## Data structures¶

File contains:

B. Torben-Nielsen (from legacy code). Daniele Linaro contributed the iterators in STree2.

Bases: object

Basic container to represent and store 3D information

Constructor.

xyz : numpy.array
3D location

radius : float type : int

Type asscoiated with the segment according to SWC standards
class btmorph.btstructs2.SNode2(index)[source]

Bases: object

Simple Node for use with a simple Tree (STree)

By design, the “content” should be a dictionary. (2013-03-08)

Constructor.

index : int
Index, unique name of the SNode2

add a child to the children list of a given node

node : SNode2

children

Return the children nodes of this one (if any)

children : list SNode2
In case of a leaf an empty list is returned
content

Return the content dict of a SNode2

parent : SNode2
In case of the root, None is returned.Otherwise a SNode2 is returned
get_children()[source]

Return the children nodes of this one (if any)

children : list SNode2
In case of a leaf an empty list is returned
get_content()[source]

Return the content dict of a SNode2

parent : SNode2
In case of the root, None is returned.Otherwise a SNode2 is returned
get_index()[source]

Return the index of this node

index : int

get_parent()[source]

Return the parent node of this one.

parent : SNode2
In case of the root, None is returned.Otherwise a SNode2 is returned
index

Return the index of this node

index : int

make_empty()[source]

Clear the node. Unclear why I ever implemented this. Probably to cover up some failed garbage collection

parent

Return the parent node of this one.

parent : SNode2
In case of the root, None is returned.Otherwise a SNode2 is returned
remove_child(child)[source]

Remove a child node from the list of children of a specific node

node : SNode2
If the child doesn’t exist, you get into problems.
set_children(children)[source]

Set the children nodes of this one

children: list SNode2

set_content(content)[source]

Set the content of a node. The content must be a dict

content : dict
dict with content. For use in btmorph at least a ‘p3d’ entry should be present
set_index(index)[source]

Set the unqiue name of a node

index : int

set_parent(parent)[source]

Set the parent node of a given other node

node : SNode2

class btmorph.btstructs2.STree2[source]

Bases: object

Simple tree for use with a simple Node (SNode2).

While the class is designed to contain binary trees (for neuronal morphologies) the number of children is not limited. As such, this is a generic implementation of a tree structure as a linked list.

Default constructor. No arguments are passed.

Add a node to the tree under a specific parent node

node : SNode2
parent : SNode2
parent node of the newly added node
degree_of_node(node)[source]

Get the degree of a given node. The degree is defined as the number of leaf nodes in the subtree rooted at this node.

node : SNode2
Node of which the degree is to be computed.

degree : int

get_node_in_subtree(index, fake_root)[source]

Get a node with a specific name in a the subtree rooted at fake_root. The name is always an integer

index : int
Name of the node to be found
fake_root: SNode2
Root node of the subtree in which the node with a given index is searched for
node : SNode2
Node with the specific index
get_node_with_index(index)[source]

Get a node with a specific name. The name is always an integer

index : int
Name of the node to be found
node : SNode2
Node with the specific index
get_nodes()[source]

Obtain a list of all nodes int the tree

all_nodes : list of SNode2

get_root()[source]

Obtain the root node

root : SNode2

get_sub_tree(fake_root)[source]

Obtain the subtree starting from the given node

fake_root : SNode2
Node which becomes the new root of the subtree
sub_tree : STree2
New tree with the node from the first argument as root node
is_leaf(node)[source]

Check whether a node is a leaf node, i.e., a node without children

is_leaf : boolean
True is the queried node is a leaf, False otherwise
is_root(node)[source]

Check whether a node is the root node

is_root : boolean
True is the queried node is the root, False otherwise
order_of_node(node)[source]

Get the order of a given node. The order or centrifugal order is defined as 0 for the root and increased with any bifurcation. Hence, a node with 2 branch points on the shortest path between that node and the root has order 2.

node : SNode2
Node of which the order is to be computed.

order : int

path_between_nodes(from_node, to_node)[source]

Find the path between two nodes. The from_node needs to be of higher order than the to_node. In case there is no path between the nodes, the path from the from_node to the soma is given.

from_node : SNode2 to_node : SNode2

path_to_root(node)[source]

Find and return the path between a node and the root.

node : SNode2
Node at which the path starts
path : list of SNode2
list of SNode2 with the provided node and the root as first and last entry, respectively.
read_SWC_tree_from_file(file_n, types=[1, 2, 3, 4, 5, 6, 7, 8, 9])[source]

Non-specific for a “tree data structure” Read and load a morphology from an SWC file and parse it into an STree2 object.

On the NeuroMorpho.org website, 5 types of somadescriptions are considered (http://neuromorpho.org/neuroMorpho/SomaFormat.html). The “3-point soma” is the standard and most files are converted to this format during a curation step. btmorph follows this default specificationand the internal structure of btmorph implements the 3-point soma.

However, two other options to describe the soma are still allowed and available, namely: - soma absent: btmorph adds a 3-point soma in between of [TO DEFINE/TODO] - multiple cylinder: [TO DEFINE/TODO]

file_n : str
name of the file to open
remove_node(node)[source]

Remove a node from the tree

node : SNode2
node to be removed
root

Obtain the root node

root : SNode2

set_root(node)[source]

Set the root node of the tree

node : SNode2
to-be-root node
write_SWC_tree_to_file(file_n)[source]

Non-specific for a tree.

Used to write an SWC file from a morphology stored in this STree2. Output uses the 3-point soma standard.

file_n : str
name of the file to open

## Morphometrics¶

class btmorph.btstats.BTStats(tree)[source]

Bases: object

Compute morphometric features and statistics of a single morphology

Assume the “3 point” soma of the curated NeuroMorpho format. (website)

1. Torben-Nielsen (legacy code)

Constructor.

tree : STree2
Neuronal tree for which to compute morphometrics
approx_soma()[source]

Scalar, global morphometric

By NeuroMorpho.org convention: soma surface ~ 4*pi*r^2, where r is the abs(y_value) of point 2 and 3 in the SWC file

surface : float
soma surface in micron squared
bifurcation_angle_vec(node, where='local')[source]

Vector, local morphometric

Only to be computed at branch points (_bif_points). Computes the angle between the two daughter branches in the plane defined by the parent and the two daughters.

cos alpha = $$(a \dot b) / (|a||b|)$$

node : btmorph.btstructs2.SNode2 where : string

either “local” or “remote”. “Local” uses the immediate daughter points while “remote” uses the point just before the next bifurcation or terminal point.
angle : float
Angle in degrees
bifurcation_rall_ratio_classic(node, where='local')[source]

Vector, local morphometric

The ratio $$\frac{ {d_1}^p + {d_2}^p }{D^p}$$ computed with $$p=1.5$$

node : btmorph.btstructs2.SNode2 where : string

either ‘local or ‘remote’. ‘Local’ uses the immediate daughter points while “remote” uses the point just before the next bifurcation or terminal point.
rr : float
Approximation of Rall’s ratio
bifurcation_ralls_power_brute(node, where='local', min_v=0, max_v=5, steps=1000)[source]

Vector, local morphometric

Approximation of Rall’s ratio. $$D^p = {d_1}^p + {d_2}^p$$, p is approximated by brute-force checking the interval [0,5] in 1000 steps (by default, but the exact search dimensions can be specified by keyworded arguments.

node : btmorph.btstructs2.SNode2 where : string

either ‘local or ‘remote’. ‘Local’ uses the immediate daughter points while “remote” uses the point just before the next bifurcation or terminal point.
rr : float
Approximation of Rall’s power, p
bifurcation_ralls_power_fmin(node, where='local')[source]

Vector, local morphometric

Approximation of Rall’s ratio using scipy.optimize.fmin. The error function is $$F={D_{d1}}^n+{D_{d2}}^n-{D_p}^n$$

node : btmorph.btstructs2.SNode2 where : string

either “local” or “remote”. “Local” uses the immediate daughter points while “remote” uses the point just before the next bifurcation or terminal point.
rr : float
Appriximation of Rall’s ratio
bifurcation_sibling_ratio(node, where='local')[source]

Vector, local morphometric

Ratio between the diameters of two siblings.

node : btmorph.btstructs2.SNode2 where : string

Toggle ‘local’ or ‘remote’
result : float
Ratio between the diameter of two siblings
degree_of_node(node)[source]

Degree of a node. (The number of leaf node in the subtree mounted at the provided node)

degree : float
degree of the subtree rooted at node
frac_dim_lac(vg=None)[source]

Compute both lacunarity and fractal dimension Calculates lacunarity based on standard fixed grid box counting method with coef. of variation See wikipedia for more information: http://en.wikipedia.org/wiki/Lacunarity#equation_1 Note: here we ignore orientations (all boxes start from (0,0,0)) and box sizes are always power of two Calculates fractal dimension of the given voxel grid by this formula: D = lim e -> 0 of (log(Ne)/log(e)) http://rsbweb.nih.gov/ij/plugins/fraclac/FLHelp/Glossary.htm#db

vg : btmorph.btstructs2.VoxelGrid

lacunarity, fractal_dimension : tuple

fractal_dimension_box_counting_core(vg)[source]

Calculates fractal dimension of the given voxel grid by this formula: D = lim e -> 0 of (log(Ne)/log(e)) http://rsbweb.nih.gov/ij/plugins/fraclac/FLHelp/Glossary.htm#db

fractal_dimension_lacunarity(voxelSize)[source]

Calculate both lacunarity and fractal dimension of a tree. Faster than calling fractal_dim_box_counting and lacunarity_standard separately

voxelSize : number
Desired voxel size, affects resolution. Both measures use voxelization of the 3D tree for calculations

(lacunarity, fractal_dimension)

get_Euclidean_length_to_root(from_node)[source]

euclidean length between the from_node and the root

from_node : btmorph.btstructs2.SNode2

length : float
length of the path between the soma and the provided node
get_diameters()[source]

Vector, local morphometric

Get the diameters of all points in the morphology

get_pathlength_to_root(from_node)[source]

Length of the path between from_node to the root. another branching point

from_node : btmorph.btstructs2.SNode2

length : float
length of the path between the soma and the provided node
get_points_of_interest()[source]

Get lists containting the “points of interest”, i.e., soma points, bifurcation points and end/terminal points.

soma_points : list bif_points : list end_points : list

get_segment_Euclidean_length(to_node)[source]

Euclidean length to the incoming segment. Between this node and the soma or another branching point

from_node : btmorph.btstructs2.SNode2

length : float
Euclidean distance to provided node (from soma or first branch point with lower order)
get_segment_pathlength(to_node)[source]

Vector, local morphometric.

Length of the incoming segment. Between this node and the soma or another branching point. A path is defined as a stretch between the soma and a bifurcation point, between bifurcation points, or in between of a bifurcation point and a terminal point

to_node : btmorph.btstructs2.SNode2
Node to which the measurement is taken
length : float
length of the incoming path in micron
global_horton_strahler()[source]

Calculate Horton-Strahler number at the root See local_horton_strahler()

Horton-Strahler number at the root

lacunarity_box_counting_core(vg)[source]

Calculate lacunarity based on standard fixed grid box counting method with coef. of variation See wikipedia for more information: http://en.wikipedia.org/wiki/Lacunarity#equation_1 Note: here we ignore orientations (all boxes start from (0,0,0)) and box sizes are always power of two

vg : btmorph.btstructs2.VoxelGrid

lacunarity : float

local_horton_strahler(node)[source]

We assign Horton-Strahler number to all nodes of a tree, in bottom-up order, as follows:

If the node is a leaf (has no children), its Strahler number is one. If the node has one child with Strahler number i, and all other children have Strahler numbers less than i, then the Strahler number of the node is i again. If the node has two or more children with Strahler number i, and no children with greater number, then the Strahler number of the node is i + 1. *If the node has only one child, the Strahler number of the node equals to the Strahler number of the child The Strahler number of a tree is the number of its root node.

node : btmorph.btstructs2.SNode2
Node of interest
hs : int
The Horton-Strahler number (Strahler number) of the node
no_bifurcations()[source]

Scalar, global morphometric

Count the number of bifurcations points in a complete moprhology

no_bifurcations : int
number of bifurcation
no_stems()[source]

Scalar, global morphometric

Count the number of stems in a complete moprhology (except the three point soma from the Neuromoprho.org standard)

no_stems : int
number of stems
no_terminals()[source]

Scalar, global morphometric

Count the number of temrinal points in a complete moprhology

no_terminals : int
number of terminals
order_of_node(node)[source]

Order of a node. (Going centrifugally away from the soma, the order increases with 1 each time a bifurcation point is passed)

order : float
order of the subtree rooted at node
partition_asymmetry(node)[source]

Vector, local morphometric

Compute the partition asymmetry for a given node.

partition_asymmetry : float
partition asymmetry of the subtree rooted at node (according to vanpelt and schierwagen 199x)
pca(A)[source]
performs principal components analysis

(PCA) on the n-by-p data matrix A Rows of A correspond to observations, columns to variables.

Returns :
coeff :

is a p-by-p matrix, each column containing coefficients for one principal component.

score :

the principal component scores; that is, the representation of A in the principal component space. Rows of SCORE correspond to observations, columns to components.

latent :

a vector containing the eigenvalues of the covariance matrix of A. source: http://glowingpython.blogspot.jp/2011/07/principal-component-analysis-with-numpy.html

total_dimension()[source]

Scalar, global morphometric Overall dimension of the morphology

dx : float
x-dimension
dy : float
y-dimension
dz : float
z-dimension
total_dimensions_verbose()[source]

Scalar, global morphometric

Overall dimension of the whole moprhology. (No translation of the moprhology according to arbitrary axes.)

dx : float
x-dimension
dy : float
y-dimension
dz : float
z-dimension
data : list
minX,maxX,minY,maxY,minZ,maxZ
total_length()[source]

Scalar, global morphometric

Calculate the total length of a complete morphology

total_length : float
total length in micron
total_surface()[source]

Scalar, global morphometric

Total neurite surface (at least, surface of all neurites excluding the soma. In accordance to the NeuroMorpho / L-Measure standard)

total_surface : float
total surface in micron squared
total_volume()[source]

Scalar, global morphometric

Total neurite volume (at least, surface of all neurites excluding the soma. In accordance to the NeuroMorpho / L-Measure standard)

total_volume : float
total volume in micron cubed

## Visualization¶

Basic visualization of neurite morphologies using matplotlib.

Usage is restricted to morphologies in the sWC format with the three-point soma standard

1. Torben-Nielsen
btmorph.btviz.pca_project_tree(tree)[source]

Returns a tree which is a projection of the original tree on the plane of most variance

tree : btmorph.btstructs2.STree2 A tree

tree : btmorph.btstructs2.STree2
New flattened tree
btmorph.btviz.plot_2D_SWC(file_name='P20-DEV139.CNG.swc', cs=None, synapses=None, syn_cs='ro', outN=None, align=True, offset=None, show_axis=False, depth='Y', filter=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], show_radius=True, bar_L=None, bar=[50, 50, 50], new_fig=True, color_scheme='default')[source]

2D matplotlib plot of a neuronal moprhology. Projection can be in XY and XZ. The SWC has to be formatted with a “three point soma”. Colors can be provided

file_name : string
File name of the SWC file to plots
cs : list of float
Raw values that will be plotted on the morphology according to a colormap
synapses : list of int
Indices of the compartments where synapses (= small circles) should be drawn
syn_c : string
Color of the synapses (‘r’,’g’, ‘b’, ...). String follows matplotlib conventions. You can include the marker style as well. Default syn_c=’ro’
outN : string
File name of the output file. Extension of this file sets the file type
align : boolean
Translate the figure so that the soma is on the origin [0,0,0].
offset : list on float
List of length 3 with X,Y and Z shift of the morphology to be plotted. Not to be used in conjunction with the “align” option
show_axis : boolean
whether or not to draw the axis
filter : list
List of integers indicating the SWC types to be included (1:soma, 2:axon, 3:basal,4:apical,...). By default, all SWC types are included
Default “True” plots the diameter; “False” will render a wire plot.
bar_L : float
Add a scale bar to the plot. Currently only works with align=True
bar : list of real
When the axis are shown (show_axis=True), ticks will be plotted according to this list. List contains 3 values for X, Y and Z ticks. Default [50,50,50]
depth : string
Default “Y” means that X represents the superficial to deep axis. Otherwise, use “Z” to conform the mathematical standard of having the Z axis.
new_fig : boolean
True if matplotlib has to plot in a new figure. False, if otherwise.
color_scheme : string
Set the color scheme used for background and neurite types. Default default. Other option neuromorpho

If the soma is not located at [0,0,0], the scale bar (bar_L) and the ticks (bar) might not work as expected

btmorph.btviz.plot_3D_SWC(file_name='P20-DEV139.CNG.swc', cs=None, synapses=None, syn_cs=None, outN=None, offset=None, align=True, filter=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9])[source]

3D matplotlib plot of a neuronal morphology. The SWC has to be formatted with a “three point soma”. Colors can be provided and synapse location marked

file_name : string
File name of the SWC file to plots
cs : list of float
Raw values that will be plotted on the morphology according to a colormap
synapses : list of int
Indices of the compartments where synapses (= small circles) should be drawn
syn_cs : string
Color of the synapses (‘r’,’g’, ‘b’, ...)
outN : string
File name of the output file. Extension of this file sets the file type
offset : list on float
List of length 3 with X,Y and Z shift of the morphology to be plotted. Not to be used in conjunction with the “align” option
show_axis : boolean
whether or not to draw the axis
filter : list
List of integers indicating the SWC types to be included (1:soma, 2:axon, 3:basal,4:apical,...). By default, all SWC types are included
btmorph.btviz.plot_dendrogram(file_name, transform='plain', shift=0, c='k', radius=True, rm=20000.0, ra=200, outN=None)[source]

Generate a dendrogram from an SWC file. The SWC has to be formatted with a “three point soma”

file_name : string
File name of the SWC file to plots
transform : string
Either ‘plain’ or ‘lambda’. Plain means no transform while ‘lambda’ performs an elecotrtonic transform
shift : float
Offset in the x-direction
c : string
Color (‘r’,’g’, ‘b’, ...)
Plot a wire (False) dendrogram or one with the thickness of the processes (True)
rm : float
Membrane resistance. Only needed when transform = ‘lambda’
rm : float
Axial resistance. Only needed when transform = ‘lambda’
outN : string
File name of the output file. Extension of this file sets the file type
btmorph.btviz.true_2D_projections(file_name='P20-DEV139.CNG.swc', align=True, outN=None, bar=None, depth='Z')[source]

Three 2D projections

file_name : string
File name of the SWC file to plots
depth : string
Set which axis represents “depth”. In experimental work, the Z-axis is depth (as in my PPNeurMorphC) but in NeuroMorpho the Y-axis is the depth. (Depth is used to denote the axis from deep to superficial)
align : boolean
Translate the figure so that the soma is on the origin [0,0,0].
outN : string
File name of the output file. Extension of this file sets the file type
bar : list of int or real
Three values to set the thicks and marks on the plot in X,Y and Z-dimension
depth : string
Set the axis representing the depth (= axis from superficial to deep). In most SWC files this is ‘Y’. The other option is ‘Z’, that is more consistent with the usual Cartesian coordinate systems
btmorph.population_density_plots.population_2D_density_projections(destination='.', filter='*.swc', outN=None, depth='Z', limits=None, precision=[10, 10, 10])[source]

Plot a pseudo-3D heat-map of all neurites in a population by means of three 2D plots. A population can be sepcified by setting the destination and filter arguments.

destination : string
Set the directory in which the population is located. Default ”.” sets the current working directory.
filter : string
Filter the file-names to constrain the population. Default “*.swc” will select all SWC files in one directory. The filter uses the glob module so make sure glob understands your filter!
outN : string
File name to save the figure to. Default is None and the figure will not be saved by default.
depth : string
Indicate the axis from superficial to deep. In most files this is “Y”. Default, however, is set to the mathematical standard “Z”.
precision : list of ints
Set the bin size of the heatmap. Default [10,10,10] (in micron)
btmorph.population_density_plots.population_density_projection(destination='.', filter='*.swc', outN=None, depth='Z', precision=[10, 10, 10])[source]

Plot a 2D heat-map of all neurites in a population. A population can be sepcified by setting the destination and filter arguments. Parameters ———- destination : string

Set the directory in which the population is located. Default ”.” sets the current working directory.
filter : string
Filter the file-names to constrain the population. Default “*.swc” will select all SWC files in one directory. The filter uses the glob module so make sure glob understands your filter!
outN : string
File name to save the figure to. Default is None and the figure will not be saved by default.
depth : string
Indicate the axis from superficial to deep. In most files this is “Y”. Default, however, is set to the mathematical standard “Z”.
precision : list of ints
Set the bin size of the heatmap. Default [10,10,10] (in micron)

Generate animation of morphologies using matplotlib.

Usage is restricted to morphologies in the sWC format with the three-point soma standard

btmorph.btviz_dynamic.animate_SWC_rotation(file_name, offset=None, align=True, color_scheme='neuromorpho', filter=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], depth='Y', out_n='rotate_animation')[source]

Rotate illustration of a neuronal morphology over 360 degrees.

file_n : string
Filename of SWC description. Must be using the 3-point soma description. If the file is not in this format, use btmorph.btstructs2.STree2.read_SWC_tree_from_file() followed by btmorph.btstructs2.STree2.write_SWC_tree_to_file(), which will convert the description to three-point soma.
offset : array_like
Move the structure by the specified [x,y,z]
color_scheme : string
Default or “neuromorpho”
filter_range : array_like
List of integers indicating the SWC types to be included (1:soma, 2:axon, 3:basal,4:apical,...). By default, all SWC types are included
depth : string
Specify which direction (axis) represents “depth”. On NeuroMorpho.org this is the Y-axis (and is used here by default). In NeuroMaC, depth is on the Z-axis.
out_n : string
File name of the generated gif file. The ”.gif” extension is added automatically.

## Wrappers / Tools¶

btmorph.tools.analyze_1D_population.perform_1D_population_analysis(destination, filter='*.swc', depth='Y', bar=[200, 200, 200], post_name=None, max_n=None)[source]

Wrapper function to perform a complete analysis of a population of neuronal morphologies stored in SWC format (and three-point soma).

Computes the following features:

• # bifurcations
• # terminals
• # stems
• total length
• total volume
• total surface
• max centrifugal order
• inter bifurcation length
• terminal segment length
• euclidean distance between terminal tips and soma
• path legth between terminal tips and soma

For each feature a list is created with all values collected from all morphologies.

These vectors are saved as python Pickle objects.

At the same time a histogram is generated to display the data.

destination : string
string with the location of where to find the SWC files.
filter : string
filter to select SWC files. Default is “*.swc”. See glob documentation for more advanced filters
depth : string
Dimension that indicates “depth”/distance from top. Default is “Y”; NeuroMac generated files use “Z”.
bar : array of float
Include a scale-bar with the specified dimensions
max_n : int
To perform the analysis on a subset of morphologies specify a number. Default is None and all morphologies will be taken into account.
post_name : string
string appended to the file name when saving. Default None
btmorph.tools.analyze_2D_per_neuron.perform_2D_analysis(destination, filter='*.swc', max_n=None)[source]

Wrapper function to perform an analysis of the vector features of one neuronal morphology (in the SWC format and with 3-point soma)

For both the terminal points and the branching points the following features are recorded

• Order of the node
• degree of the node
• Euclidean distance to the soma
• path length to the soma
• pathlength of the segment (coming in to a node)
• Euclidean distance of the segment (coming in the a node)
• branch angle amplitude [branch points only]

Two text files are generated, for terminal and branching points. Each row corresponds to a node (point) and the six columns correspond to the features above.

destination : string
string with the location of where to find the SWC files.
btmorph.tools.filter_and_save_swc.filter_and_save_SWC(destination, filter, types=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], prefix='_filtered')[source]

Removes points from a SWC structure and saves the new SWC to a file.

Can be used to remove unwanted structures that are identifiable by the type-field in the SWC description. Specification of (standard) SWC type fields can be found here.

To select the basal dendrites only, use the argument types=[1,3]: 1 to select the soma and 3 for the basal dendrites themselves.

destination : string
string with the location of where to find the SWC files.
types : list of int
types that are to be remained in the SWC file.