One Rule to Grow Them All: A General Theory of Neuronal Branching and Its Practical Application

Understanding the principles governing axonal and dendritic branching is essential for unravelling the functionality of single neurons and the way in which they connect. Nevertheless, no formalism has yet been described which can capture the general features of neuronal branching. Here we propose such a formalism, which is derived from the expression of dendritic arborizations as locally optimized graphs. Inspired by Ramón y Cajal's laws of conservation of cytoplasm and conduction time in neural circuitry, we show that this graphical representation can be used to optimize these variables. This approach allows us to generate synthetic branching geometries which replicate morphological features of any tested neuron. The essential structure of a neuronal tree is thereby captured by the density profile of its spanning field and by a single parameter, a balancing factor weighing the costs for material and conduction time. This balancing factor determines a neuron's electrotonic compartmentalization. Additions to this rule, when required in the construction process, can be directly attributed to developmental processes or a neuron's computational role within its neural circuit. The simulations presented here are implemented in an open-source software package, the “TREES toolbox,” which provides a general set of tools for analyzing, manipulating, and generating dendritic structure, including a tool to create synthetic members of any particular cell group and an approach for a model-based supervised automatic morphological reconstruction from fluorescent image stacks. These approaches provide new insights into the constraints governing dendritic architectures. They also provide a novel framework for modelling and analyzing neuronal branching structures and for constructing realistic synthetic neural networks.

Definitions a tree is a graph branch branch point (B) continuation point (C) branch As a graph, a tree is represented by a set of labelled nodes connected by edges. Since most statistics describing a neuron"s branching relate to the root (e.g. branch order, which increases after each branch point on the way from the tree root to all terminal nodes) it makes sense to attribute a directionality to the edges and to define the root as the node with the index 1. All edges lead away from the root. That defines their directionality uniquely.
the TREES toolbox -on the nature of neuronal branching 5 The directed adjacency matrix describes how nodes are directionally connected to a graph looking at trees using graph theory Definitions adjacency matrix When neuronal trees are regarded as graphs, their branching structure can be well described with the corresponding directed adjacency matrix dA (see "dA_tree"), a quadratic matrix of size NxN where N is the number of nodes in the tree. As mentioned earlier, the direction of the edges shows away from the first point, representing the arbitrary starting vertex S (= 1), the root of the tree. Note that the widely used .swc format (Cannon RC, Turner DA, Pyapali GK, Wheal HV, 1998, J Neurosci Methods 84: 49-54) for storing neuronal morphology is nothing else than a sparse representation of the adjacency matrix since it simply attributes to all nodes (row index) a parent node (column index).
Not each possible directed adjacency matrix represents a possible neuronal tree, since loops and branching points with more than two child branches are possible, but do not exist in natural dendritic trees. dA therefore never contains more than two entries in one column and no entry will lay directly on the diagonal. Also, each node has exactly one parent, apart from the root, which has none. Each row of dA therefore contains exactly one entry apart from the first, which contains none.

adjacency matrix dA
In order to derive most dendritic branching statistics using the typical descriptions, an algorithmic formulation by recursion is required to "walk" through a tree and collect statistics. Many operations for example on dendritic trees require processing with a stack and can therefore not be written analytically. With repeated matrix multiplication on the directed adjacency matrix as in dA r the (i, j)-entry represents the number of distinct r-walks from node i to node j in the graph.
the TREES toolbox -on the nature of neuronal branching 6 Further order r parents are simply obtained by applying repeated matrix multiplication (see "ipar_tree"): Where r = 0 corresponds to the node itself, r = 1 the parent, r = 2 the grand-parent etc…   T r r N dA ipar ... 2 1   Using simple multiplications of the adjacency matrix allows one to "walk" through a tree looking at trees using graph theory Definitions using graph theory Therefore, the derivation of some elementary branching properties follows directly from the graph representation of the tree. As such, the child nodes of each node i can be read out in the non-zero elements directly from dA in column i. The index of the direct parent node idpar to any node i (see "idpar_tree") is simply the i-th element of:

Definitions BCT formalism
None of the common formats for dendritic trees represent one and the same tree in a unique way. This becomes very clear for the graph representation where all permutations of labels (indices) result in the same tree: Again, the same is true for the .swc format. A more constrained representation is given by the BCT formalism (which was developed as far as we know by Rocky Nevin and implemented in the compartmental modelling software NeMoSys, Eeckman FH, Theunissen FE and Miller JP, 1994, Nemosys: a system for realistic single neuron modeling. In Neural Network Simulation Environments,ed. Skrzypek J,Dordrecht,London: Kluwer Academic Publishers). There, the node labels are sorted hierarchically so that the nodes of a sub-tree remain in sequence and within each sub-tree parent nodes always precede their respective daughter nodes. This was done in our example: the resulting BCT string can then be read out by summing over the columns of dA.
Nodes where this sum is 0 (no daughter nodes) are termed "T" for terminal. Nodes where the sum is 1 are termed "C" for continuation. Nodes where the sum is 2 are termed "B" for branch. The resulting string reads "CBBTTBTT":

"Define a root and start a branch. Continue to next node (C). Open new branch (B 1 ). Open new branch (B 2 ). Terminate last branch which is still open (T 2 ). Terminate previous branch (T 1 ). Open new branch (B 3 ). Terminate last opened branch (T 3 ). Terminate full tree (T 0 )."
The adjacency matrix is fully described by the BCT string and additionally the labelling of the nodes is now more restricted. But at each branch point permuting the sub-trees would still result in the exact same underlying tree.
A simple way to arrange the node labels to conform to BCT is to insert each node one by one directly behind its parent node and to re-label the nodes after the whole process (see "sort_tree" function of the TREES toolbox).
An important note here: If the nodes are pre-sorted beforehand (for example lexicographically or by level order and topological path length, see section "sorting a tree") a perfectly unique representation of the topology can be obtained. Note also: In BCT form, all entries in dA are strictly below the diagonal. j i  In order to find the directed adjacency matrix from a BCT string (see "BCT_tree") by maintaining the order of elements (metrics can then be directly transferred) the following algorithmic procedure can be applied: % basic algorithm: Set dA to square matrix of zeros Use a stack For i = 1:N if index exists then dA(i,index) = 1 index = i If BCT(i) == '0|T' then index = POP stack If BCT(i) == '2|B' then PUSH i to stack End If an adjacency matrix represents a correct BCT order, a pointer starting with one at the root diminishing by one for each terminal and increasing by one for each branching point should become zero exactly at the end of the string (position N, number of nodes). This can be represented by the cumulative sum C x : Note that one rough way to obtain all possible BCT strings with N nodes is by setting all numbers from 0 to 3 N -1 into base 3 and verifying whether they are BCT. the TREES toolbox -on the nature of neuronal branching 10 Even in BCT order the representation of a tree"s connectivity matrix is not unique. Sorting the labels is a solution Definitions sorted and equivalent tree

BCT order topological sorting
The labeling of the nodes of a tree should be unique if one wants to for example compare the graphs of two trees topologically or electrotonically. In principle, the labels on the nodes describing a graph can be attributed arbitrarily. As mentioned before, all permutations of labels (indices) result in the same tree by rearranging the adjacency matrix and any metric elements attributed to the nodes: In a hierarchical sorting, node label values always increase towards daughter nodes. This can constrain the otherwise arbitrary labelling. As discussed before, labelling can be constrained further in the BCT order (see introduction part "BCT formalism"). Within any sub-tree, the labelling is then continuous. A truly unique labelling arises in a topological sorting when labels additionally carry a weight according to some topological values such as the topological depth or the number of child nodes. At each branch point for example, the heavier sub-trees can then be labelled first. Rearranging the metrics of a tree based on its topologically sorted label order leads to a unique electrotonic equivalent tree.
In order to arrive to such a labelling, nodes are first sorted according to their topological depth. Each node is then inserted in that order into a one dimensional string one by one directly behind its direct parent node. Subsequently, the resulting string of labels is mapped back onto the nodes of the tree.
the TREES toolbox -on the nature of neuronal branching 11 Variants of the BCT string can be used as a "topological gene" description of a tree looking at trees using graph theory Definitions the "topological gene"

B
29 B 21 T 10 B 8 T 17 B 9 T 11 T 9 T 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Once the labels of a tree are topologically sorted (see "sort_tree"), a unique representation of the topology is given by the topological "gene" (see "gene_tree"): green segments are branches ending with a branch point, black segments are branches ending with a termination point; the order is determined by the topological sorting described on the previous page. Numbers on the "gene" branches (and also their actual length) correspond to the path length along each branch. In this case the node labels are displayed under the "gene" for descriptive purposes. Apart from the diameter mapping, the equivalent tree can be reconstructed solely from this one-dimensional string.
Because of the continuous labelling sub-trees of the original tree are continuous bits within the topological "gene" (see red contours).
Morphing a tree is the process of mapping new metric length values on an existing tree, while preserving its topology and local angles

Definitions tree morphing
Segev and colleagues derived a new representation of neuronal trees depending on electrotonic measures. The method used for this representation was called the "Morphoelectrotonic Transform" (Zador et al. 1995, J Neurosci 15(3):1669-82).
In fact, the method used in that case is very generalizable. Any Nx1 vector of length values may be mapped on a tree with N nodes. This is done by scaling the length value l i of all segments to the new segment lengths while conserving the direction of the segment indicated by the direction vector (arrow below). At each step the entire sub-tree needs to be translated accordingly.
Only in the case of 0-length segments, a direction needs to be picked arbitrarily. A TREES toolbox function (see "morph_tree") performs this type of morphing operation which can have various applications of which the morpho-electrotonic transform is just one .
On the path sum (see "Pvec_tree"), child sum (see "child_tree"), parent daughter ratio (see "ratio_tree"), segment binning (see "bin_tree") are further examples of such "meta-functions" which apply an Nx1 vector on a tree structure to result in a wide variety of applications.

Definitions Electrotonic signature
Using linear algebra in combination with Kirchhoff"s laws of current conservation, the adjacency matrix can be used directly to obtain a full signature of passive steady-state current propagation in a tree Combining Kirchhoff"s junction law for electrical circuits with simple linear algebra, a matrix can be derived which describes the equivalent circuit of a tree. If we cut the circuit at node 3 in the above example the following matrix appears: 200 mm

Definitions Electrotonic signature (II)
The electrotonic signature describes the compartmentalization of the neuronal tree Simply taking the inverse of the conductance matrix M (see previous page) results in the steady state electrotonic signature of the tree: This electrotonic signature (see "sse_tree") describes well the electrotonic compartmentalization of a neuronal tree. In this case the matrix of input currents I is simply the identity matrix. Currents of 1 (nA) are therefore injected one at a time in each node in subsequent columns or rows. The symmetrical square matrix V SSE contains in each column or row the potential distribution in all nodes following the current injection in the corresponding node (i.e. the current transfer). The diagonal therefore contains the local input resistances since there the potential change is measured in each node resulting from current injection into the same node. Red squares correspond to sub-trees with increased electrotonic inter-connectivity. The electrotonic signature therefore follows closely on the adjacency matrix (as can be seen from the relationship between M and dA).
the TREES toolbox -on the nature of neuronal branching 15

Definitions resampling a tree
By redistributing nodes on a tree structure such that segments are constant length, node locations become unique (not arbitrary) and trees can be simplified.

CCBCBBCCBCBBBCTCTCTBCTTTCCTCCTCCCTCBCBB BBBCTCTCTTCTCCTCCTBCCCTCTCBCTTCCBBBCCBB CTCTCCTTCCCTT
The direct comparison of two trees along strict criteria requires (apart from a unique label distribution) a unique distribution of node locations on the graph. The process of manual reconstruction attributes node locations in an arbitrary manner. However, nodes can be redistributed on the same tree structure assigning homogeneous inter-nodal distances, a process we term resampling (see "resample_tree"). Resampling compromises either the total length (see loss resampling) or the shape of the neuronal tree (see length conservation) when undersampling. This is because a tortuous path is simplified by a straight line (always shorter). If the length is conserved then the shape of the neuronal tree is altered (the tree spannning field becomes larger, see length conservation). A zig-zag implementation of resampling would best remediate this but would also alter the original shape of the tree (and was not implemented). The resulting electrotonic signature or BCT string will then be entirely independent of the reconstruction procedure. Furthermore, simplified tree structures, which preserve the electrotonic compartmentalization, can be obtained. Computing current flow in a corresponding model will be much faster since the number of nodes is decreased drastically (from 297 to 39 in the example on the far right).

Definitions MST rule
A greedy algorithm can be implemented which optimizes locally total wiring and path length to the root inspired by Cajal"s laws of conservation of material and conduction time. This represents an extension to the minimum spanning tree (MST) algorithm.
The figure above exemplifies the general approach to obtain a locally optimized graph. In the process, unconnected carrier points (red dots) connect one by one to the nodes of a tree (black dots). At each step, the unconnected carrier point, which is closest to the tree according to some cost function, connects to the node in the tree to which it is closest. The distance cost in this case is composed of two components inspired by Ramón y Cajal"s laws of neuronal branching: 1. the wiring cost corresponding to the Euclidean distance to the node in the tree (red dashed lines show three sample segment distances for carrier point P); 2. the conduction time cost, corresponding to the path length from the root (large black node) to the carrier point P. In the example here, even though P is closer to node 5 in Euclidean terms, the additional cost of path length (adding distance between node 4 and node 5) might tip the balance in favour of node 4. A balancing factor bf weighs these two cost functions against each other (see "MST_tree").

Definitions MST rule (II)
One parameter, the balancing factor bf, determines the formants of potential trees This approach produces realistic neuronal branching structures in all cases. The balancing factor between the two costs determines the electrotonic compartmentalization of the neuronal tree. At one extreme, one finds the pure minimum spanning tree, at the other, the entirely compartmentalized stellate structure, which connects each carrier point directly to the root.

Definitions quadratic diameter taper
Optimizing diameter values for an equal current transfer to the root (synaptic democracy) results in a quadratic taper. The latter can be mapped on a neuronal tree. in black: original tree in red: mapped quadratic diameter taper Each single triplet P corresponds to the best fit to a segment of a specific cable length l dend . In order to map a quadratic diameter to a full tree, each path from terminal to the root is compared to its closest value in a predetermined set of l dend . Then the quadratic equation parameters P are chosen according to l dend . This is done for all paths from root to terminal points and for each node the diameter is set to the average of all local diameters of all paths leading through that node (see "quaddiameter_tree"). P and l dend depend on the total leak and the minimal diameter: these have to be adjusted by the parameters scale and offset respectively (see "quadfit_tree"). The resulting tree diameter mapping compares well with the original even though it is set merely by two parameters, the scale and offset values. Here is a sample overview of the outputs of some TREES toolbox functions whose form is an Nx1 vector, attributing thereby one value to each node.

First steps starting with TREES
Simply unzip the TREES package obtained from www.treestoolbox.org unto your computer and change directory to its parent folder after opening Matlab. Set the path and create a global empty cell array called "trees" by typing "start_trees" in the command window.
By default, most functions append new trees to this cell array "trees". Try out:

>> load_tree
which opens a fileselect. You can find some sample trees in ".\sample\mtr\". We will start by loading the tree called "sample2.mtr".
the TREES toolbox -on the nature of neuronal branching 23

First steps exploration of a tree
The tree was appended to the cell array "trees": It contains the NxN adjacency matrix "dA" in sparse form which describes the edges between the N nodes of the graph. A few Nx1 vectors attribute individual values to all nodes (e.g. "X", "Y", "Z" coordinates; "R" region index; "D" diameter values). A cell array of strings "rnames" attributes a name to each region. A few single values describe homogenously distributed features, here the passive electrotonic parameters. A string "name" attributes a name to the given tree.

First steps visual exploration
Many ways were implemented to explore the tree visually, for example:
But the most common function will be: In order to get more information about a function check out the reference (in the end of this manual) or type "help function-name", for example here we might want to know what "BO_tree" does:

BO_TREE
Branch order values in a tree.  The reference general remarks The suffix "_tree" is usually appended to indicate that a function belongs directly to the TREES toolbox. An input tree intree is generally the first argument which is passed on (this proved to be more comfortable in most cases). This first argument intree can be a tree structure or an index (single value) to the global cell array trees. If the first input is omitted (or "[]") the last entry in the trees array is used.
In general, omitting an input argument by typing in the empty vector "[]" or by simply sending out too few arguments to a function will result in replacing the input arguments by default values. These default values are indicated precisely in the headers of each function (simply typing "help function_name" will retrieve the header) and in the code. For most functions only a subset of the full tree definition is used (e.g. only the diameter values, only the X and Y coordinates or only the topology). In those cases the functions will not complain if the tree is not complete but the required fields are existent in the tree structure. Missing fields might even be replaced: the "plot_tree" function for example will attribute sensible fake metrics if real ones are missing.
In most cases the last input argument to a TREES function is the options string. This string contains concatenated flags starting with "-". Examples of typical options are: show the result, this is mostly for demo purposes ‚-m" demonstration movie in very few cases ‚-w" waitbar to indicate the progress of long-lasting calculations ‚-e" echo changes made to the tree Note that if options is left empty (‚") default options will be used rather than all flags off. To be sure that all flags are off set options string to ‚none". Note also that when demo flags are on, features of a tree as well as other TREES toolbox functions might be required which are not required when the flags are off.
Meta-functions are generalized functions whose input of an Nx1 vector can vary their application greatly (see introductary explanation of morphing a tree for one such example).
Examples are not necessarily useful but try to also exemplify typically more unintuitive applications. Output values and resulting plots are formatted and do not always correspond to the correct output (e.g. At each branch point of tree intree, node values of Nx1 vector v get summed up in each sub-tree to S 1 and S 2 . asym, an Nx1 vector, contains the ratio of S 1 / (S 1 + S 2 ) for S 1 < S 2 at branch points (but NaN otherwise).
By default, number of terminal child nodes are compared in both sub-trees at a branch point: v is a vector of 1 when termination point and 0 else (see "T_tree"). For the example branch point on the right (at node 3), S 1 =2 terminals are divided by S 1 + S 2 = 2+3 terminals (= 0.4). Returns for tree intree an Nx1 vector B which is one if a given node is a branch point (more than 1 daughter node) and zero else.  C_tree continuation points graphtheory edit metrics graphical construct electrotonics IO

C = C_tree (intree, options)
Returns for tree intree an Nx1 vector C which is one if a given node is a continuation point (exactly 1 daughter node) and zero else.
dissect_tree group nodes to branches graphtheory edit metrics graphical construct electrotonics IO

[sect vec] = dissect_tree (intree, options)
Groups segments of tree intree together when they belong to the same branch. Can be used as sections in NEURON-like compartmental modelling (see "neuron_tree"). Branches are delimited by either branching or termination points or region-defined borders.
Output matrix sect of size nx2 where n is the number of branches contains starting and end nodes of each branch. Nx2 matrix vec attributes a branch to each node and a fractional path length along this branch.
(Note that in the example below, nodes 14 and 15 form a separate region called "1", which reflects in the NEURON code below. Returns a binary Nx1 vector dist indicating the nodes of tree intree, whose segments cross path distance l from the root. If l is a vector of length n, dist becomes an Nxn matrix. Returns for a cell array of cell arrays of trees intrees, a cell array of cell arrays of topological genes genes (for each tree one). The two-depth of the input/output arrays allows the comparison between different groups of neuronal trees. The topological gene (see introduction section "topological gene") returns for a sorted labelling of a tree (see "sort_tree") for all branches (delimited by topological points) the metric length and the ending point type (termination or branch).

HSE cells HSN cells VS2 cells VS3 cells VS4 cells
branch length values in mm branch ending topological point descriptor (0: terminal, 2: branch) (this might take some time, 1 min) the TREES toolbox -on the nature of neuronal branching 39 idpar_tree index to direct parent node graphtheory edit metrics graphical construct electrotonics IO

idpar = idpar_tree (intree, options)
Returns for tree intree an Nx1 vector idpar containing the direct parent indices for each node. Parent node of root is "1" by default. Use "-0" option to set root parent to "0".

ipar = ipar_tree (intree, options)
Returns for tree intree a matrix ipar of indices to the parent of individual nodes following the path against the direction of the adjacency matrix towards the root of the tree. This function is crucial to many other functions based on graph theory in the TREES package.

LO = LO_tree (intree, options)
Returns for tree intree the Nx1 vector LO with summed topological path distance (see "PL_tree") of all child branches to the root. We call the function level order and it is useful to classify rooted trees into isomorphic classes, i.e to sort the node labels (see introduction section "sorted and equivalent tree"). when v contains just ones the output is 1+PL the topological path length: >> Pvec_tree (sample2_tree, ones (N, 1))" [1 2 3 4 5 6 7 8 7 4 5 6 7 7 5] when v contains the branch points the output is an alternative formulation of the branch order which increases at the branch point itself: >> Pvec_tree (sample2_tree, B_tree (sample2_tree))" [0 0 1 1 1 2 2 2 2 2 2 3 3 3 2] By default, "Pvec_tree" sums up the length values of the segments in the tree: v is then len the vector of segment lengths (see "len_tree"). Pvec then corresponds to the metric path length to the root [in mm].
the TREES toolbox -on the nature of neuronal branching 44 ratio_tree parent to daughter ratio graphtheory edit metrics graphical construct electrotonics IO

ratio = ratio_tree (intree, v, options)
Returns for tree intree an Nx1 vector ratio which takes the ratios of values of Nx1 vector v at the node itself and its direct parent idpar. the TREES toolbox -on the nature of neuronal branching 45 redirect_tree set root to new node graphtheory edit metrics graphical construct electrotonics IO

[tree, order] = redirect_tree (intree, istart, options)
Sets the root to a different node. This changes in tree intree the direction of the adjacency matrix so that arrows show away from node istart (which becomes the first element).

Example:
>> redirect_tree (sample2_tree, 5, "-s"); in black: old node index in red: new node index, after redirect the TREES toolbox -on the nature of neuronal branching 46 rindex_tree region specific indexation graphtheory edit metrics graphical construct electrotonics IO

rindex = rindex_tree (intree, options)
Returns for tree intree an Nx1 vector rindex attributing to each node a region specific index increasing for each region individually in order of appearance within that region.

[tree, order] = sort_tree (intree, options)
Sorts the labels (indices) of nodes of tree intree to conform to BCT, an order in which elements are arranged according to their hierarchy keeping the sub-tree structure intact (see introduction section "sorted and equivalent trees"). Many isomorphic BCT order structures exist, this one is created by switching the location of each node one at a time to the right neighbour position of their parent node. For a unique sorting use '-LO' or "-LEX' options.
'-LO' orders the indices using path length and level order. This results in a relatively unique equivalence relation.
'-LEX" orders the BCT elements lexicographically. This makes less sense but results in a purely unique equivalence relation.
"sort_tree" affects all vectors of form Nx1 attributed to the tree accordingly.. Example: after redirecting the tree from a different root (see "redirect_tree") the nodes are scrambled. Try out: >> rtree = redirect_tree (sample2_tree, 5); >> sort_tree (rtree, "-s"); hierarchical sorting BCT order after sorting with "sort_tree" topological sorting "sort_tree" with option "-LO" in black: old node index in red: new node index, after sorting the TREES toolbox -on the nature of neuronal branching 48 sub_tree child nodes forming sub-tree graphtheory edit metrics graphical construct electrotonics IO

[sub subtree] = sub_tree (intree, inode, options)
Returns for tree intree, an Nx1 vector sub, where the elements corresponding to a sub-tree defined by its starting node inode are "1", and all other elements are "0". An optional output subtree is a structure containing the tree structure corresponding to the sub-tree. Example:

T = T_tree (intree, options)
Returns for tree intree an Nx1 vector T which is one if a given node is a termination point (exactly 0 daughter nodes) and zero else.
Example: Returns for tree intree an Nx1 vector typeN which attributes to each node either 0: termination, 1: continuation, 2: branch point. If the tree is sorted (see "sort_tree"), this is the BCT string description of the topology of the tree (see introduction section "BCT formalism"). This function simply takes the vertical sum over the adjacency matrix with 2 as an upper bound.
Examples: Concatenates two trees intree2 onto intree1 at respective nodes inode2 and inode1 within the branching structure. Sorts the indices topologically (see "sort_tree" with option '-LO'). Fields are preferably taken from intree1, all vectors (X, Y, Z, D etc...) must exist in both trees if they exist in one tree and are concatenated as well. Region fields R and rnames are updated.
By default, intree2 is connected at its root to the closest node of intree1.
Examples: Move the sample tree (see "tran_tree") and concatenate it with itself Eliminates trifurcation or multifurcations present in the adjacency matrix of tree intree by adding tiny (x-deflected) compartments.
Example: A trifurcation occurs for example when a tree is redirected to a branch point (see "redirect_tree").

[tree indx] = insertp_tree (intree, inode, plens, options)
Inserts nodes into tree intree at path-lengths plens on the path from the root to node inode. All Nx1 vectors are interpolated linearly but regions are taken from child nodes.

tree = recon_tree (intree, ichilds, ipars, options)
Reconnects within tree intree a set of sub-trees, given by node indices ichilds to new respective parent nodes defined by indices ipars.
By default the sub-trees are moved directly to their new parent nodes (option "-h"). Without options this can be avoided (see below). the TREES toolbox -on the nature of neuronal branching 59 repair_tree restore full BCT conformity graphtheory edit metrics graphical construct electrotonics IO

>> repair_tree (tree)
the TREES toolbox -on the nature of neuronal branching 60 resample_tree redistributes nodes graphtheory edit metrics graphical construct electrotonics IO tree = resample_tree (intree, sr, options) Resamples a tree intree to equidistant nodes of distance sr in mm. See introduction section "resampling a tree" for the details on the abstraction principles.  Displays some statistics of sets of trees. stats can be a structure obtained from "stats_tree" or can be read out from an ".sts" file. vcolor is a numx3 matrix attributing to each of all num groups of trees an RGB 3-tupel colour. Options are showing only global statistics "-g", only distributions "-d" and smoothen the distributions "-c". Example: >> dLPTCs = load_tree ("dLPTCs.mtr"); >> dstats_tree (stats_tree (dLPTCs)); the TREES toolbox -on the nature of neuronal branching 67 eucl_tree euclidean distances graphtheory edit metrics graphical construct electrotonics IO

eucl = eucl_tree (intree, inode, options)
Returns Nx1 vector eucl containing the Euclidean (as the bird flies) distance [in mm] between all points on the tree intree and the root (by default) or any other node defined by its index inode. inode can also be a 3-tupel of XYZ coordinates. Morphs the metrics of tree intree without changing angles or topology (see introduction section "morphing a tree"). Attributes length values from Nx1 vector v to the individual segments but keeps the branching structure otherwise intact. This can result in overlap between previously non-overlapping segments or extreme sparseness depending on intree and v. This function provides universal application to all possible morpho-electrotonic transforms and much more. If the original lengths of segments are backed up in a vector len, the original tree can simply be recovered by: originaltree = morph_tree (morphedtree, len); However of course, 0-length segments cannot be regrown. Rotates tree intree by multiplying each point in space with a simple 3x3 (3D) or 2x2 (2D) rotation-matrix. Rotation along principal components is also possible (option "-pc2d" or "-pc3d"). Then first pc is in x, second pc is in y, third pc is in z. intree should be first centred with "tran_tree" except if rotation around a different point is required. Scales the entire tree intree by factor fac. If fac is a 3-tupel, the scaling factor can be different for X, Y and Z. With equal scaling, diameter is scaled by default. Option "-d" can prevent this. Collects typical statistics on trees intrees. Input trees can be organized as: .single tree .one group of trees: {tree 1 , tree 2 ,... tree n } .many groups of trees: {{tree i1 ,...,tree in },{tree j1 ,...,tree jm },...} With s a cell array of names defining the individual groups of trees can be passed on, option "-f" saves statistics to file with name name. option "-x" avoids time consuming statistics (use that!!) and option "-s" shows the result (see "dstats_tree"). This function will shortly be greatly enhanced.   While reconstructing neuronal trees sudden shifts in the z-axis may occur. This function automatically corrects these effects in a given input tree intree. Any jump in the z-axis > tZ, a threshold difference in z, is subtracted from the entire subtree. Before applying this function, check that this is really the adequate way to process these jumps in z.

Example:
After introducing a fake jump in the z values of the sub-tree of node #5, "zcorr_tree" is applied >> tree = sample2_tree; isub = find (sub_tree (tree, 5)); Plots a convex hull around nodes with index ipart of tree intree (intree can also simply be an Nx3 matrix of XYZ points). Hull patch is offset by XYZ 3-tupel DD and coloured with RGB 3-tupel color. alpha sets the transparency of the patch (by default .2). Option "-2d" restricts the hull patch to two dimensions. HP is the handle to the graphical object. Set options to "none" to avoid graphical output. Output hull is a structure containing in hull.XY(Z) the coordinates and in hull.ch the indices to the convex hull (see Matlab function "convhull").
If the tree is 100% flat 3D convex hull doesn't work. If selected nodes are two draws a straight line. If selected nodes are one plots a point. Displays the adjacency matrix of tree intree in the colour defined by RGB 3-tupel color, displaced by XY/Z 2/3-tupel DD and scaled by scaling factor xyscale. Fills in an NxN square with 1s (where there is a connection between two nodes, against 0s elsewhere) if N<50 and with black dots if tree is bigger. HP is the handle to the graphical object.
Example 1: adjacency plot of a small tree

>> dA_tree (sample_tree)
the TREES toolbox -on the nature of neuronal branching 83 dendrogram_tree plots a dendrogram graphtheory edit metrics graphical construct electrotonics IO

HP = dendrogram_tree (intree, diam, yvec, color, DD, wscale, options)
Plots a dendrogram of the tree intree (must conform to BCT). HP is the handle to the graphical object. Nx1 vector yvec simply assigns a y-value to each node (metric path length by default, see "Pvec_tree"), while Nx1 vector diam attributes a diameter (single value = constant diameter). The dendrogram is offset by XYZ 3tupel DD and coloured with RGB 3-tupel color.
Single value wscale determines the spacing between two terminals.

[M dX dY dZ HP] = gdens_tree (intree, sr, ipart, options)
Calculates a density matrix of the nodes in the tree intree. Uses Matlab function "isosurface" to display the resulting gradient and increases opacity with density. sr determines the bin size for the matrix. ipart, a set of indices into intree, allows to use only a subset of nodes, for example only the topological points. Outputs are the density matrix M and dX, dY and dZ are the X-, Y-and Z-dimension labels of M. HP is the handle to the graphical object. Set options to "none" to avoid graphical output.
Example: Density of topological points (only termination and branch points)

[c M HP] = hull_tree (intree, thr, bx, by, bz, options)
Calculates a space-filling 3D isosurface around the tree intree with a threshold distance of thr [in mm]. In order to do this it creates a grid defined by the vectors bx, by and bz and calculates the closest point of the tree to any of the points on the grid. Higher resolution requires more computer power but results in higher accuracy of contour. Note that for smaller threshold distances thr, a better spatial resolution is required! Outputs are c, a structure containing the polygon point coordinates, and the distance matrix M. In the 2D case (with option "-2d"), c is a contour (see Matlab function "contourc" Uses "gdens_tree" to plot the bins of a density matrix M of points in a tree intree. sr sets the resolution (size of the bins) and thr a threshold for the transparency. Opacity and colours increase with density. The individual bins are shaped like lego pieces. Example: >> tree = resample_tree (sample_tree, 1);

>> lego_tree (tree, 5)
without the resampling, most bins along the tree will be empty since no nodes exist there plot_tree plots a tree graphtheory edit metrics graphical construct electrotonics IO

HP = plot_tree (intree, color, DD, ipart, res, options)
Plots a directed graph contained in tree structure intree. Many settings allow to play with the output results. Colour handling is different on line plots than on patchy '-b' or '-p'. Even if metrics are nonexistent "plot_tree" will plot its best guess for a reasonable tree (see "xdend_tree"). Line plots are always slower than any patch display. Plot is offset by XYZ 3-tupel DD and coloured with RGB 3-tupel (or Nx1 vector, a colour value per node) color. ipart is an optional index for a sub-set of nodes whose segements are to be plotted. res determines the resolution of the cylinders, with 8 points as a default. options are "-2l" or "-3l" for 2D or 3D line plots, "-2q" or "-3q" for 2D or 3D arrow plots (quiver); see comments in "plot_tree" for more details. HP is the handle to the graphical object.
Example 1 (map branch order to colour):

[HP, indy] = plotsect_tree (intree, sect, color, DD, options, ipar)
Draws a line through a section (or path) out of a tree intree. The section must be a directed path away from the root as obtained by "dissect_tree" for example (or "ipar_tree"). Plot is offset by XYZ 3-tupel DD and coloured with RGB 3-tupel color.
Providing parental paths matrix ipar (see "ipar_tree") speeds up the plotting significantly. HP is the handle to the graphical object. indy outputs the nodes on the path.

HP = pointer_tree (intree, inodes, llen, color, DD, options)
Draws pointers away at random positive deflections of length~llen from nodes inodes in tree intree. Pointer are offset by XYZ 3-tupel DD and coloured with RGB 3-tupel color. By default these are simple spheres. With options "-l" or "-v" the pointers look a bit like thin or thick electrodes respectively. HP is the handle to the graphical object. the TREES toolbox -on the nature of neuronal branching 90 spread_tree spreads out trees graphtheory edit metrics graphical construct electrotonics IO

[DD trees] = spread_tree (intrees, dX, dY, options)
Creates a cell array DD of same organization as 2(or 1)-depth cell array intrees with X-, Y-and Z-coordinates to display trees spread over the XY-surface of a figure. DD is then an input to most functions in the "graphical" folder of the TREES toolbox (see "plot_tree" for example). If nesting level is 2 deep, trees are separated in groups additionally. dX and dY determine the minimal distance in X and Y respectively between two trees. trees output contains all trees in intrees translated according to DD.

[HP VO KK vol] = vhull_tree (intree, v, points, ipart, DD, options)
Subdivides a tree intree in convex polygons using the voronoi-algorithm. Returns one patch around each node. Patches can be coloured with Nx1 vector v. Boundary voronoi patches would go ad infinitum. Therefore a set of boundary points prevents this, by default these are calculated according to the isosurface from "hull_tree". vhull plot is offset by XYZ 3-tupel DD and ipart is an optional index for using a sub-set of nodes only. HP is the handle to the graphical object.

HP = vtext_tree (intree, v, color, DD, crange, ipart, options)
Displays text numbers or text in the Nx1 vector v at the coordinates of the nodes of tree intree. By default v contains the numbers 1 to N, a way to display node indices. Plot is offset by XYZ 3-tupel DD and coloured with RGB 3-tupel (or Nx1 vector, a colour value per node) color. ipart is an optional index for a subset of nodes to be plotted. crange restricts the colour limits. HP is the handle to the text object. Example:

[xdend tree] = xdend_tree (intree, options)
Returns an Nx1 vector xdend of x-values useful for constructing the dendrogram of tree intree. Each element's x-value is set in the middle of the labelled terminal children (maximum index + minimum index)/2. Optional output is a correlate (equivalent) tree to intree with same branch lengths and topology but with standard and sorted metrics. Branch overlap is also avoided if possible. intree must be conform to BCT format. If unsure just apply "repair_tree" beforehand. Example:

[HT HP] = xplore_tree (intree, options, color, DD)
Plots different representative exploration plots for a tree intree. Three options exist (see below). When it makes sense, plot is offset by XYZ 3-tupel DD and coloured with RGB 3-tupel (or Nx1 vector, a colour value per node) color as in "plot_tree". HT contains handles to font objects while HP contains the handles to the graphical objects. Outputs in BCTs all possible non-isomorphic BCT strings with N nodes (see introduction section "BCT formalism"). On demand, cell array of trees BCTtrees is calculated whose trees correspond to the BCT strings using sensible metrics. This uses the equivalent tree method from "BCT_tree". Finds the directed adjacency matrix from BCT a horizontal vector (0: terminal, 1: continuation, 2: branch). The algorithm uses a stack (see introduction section on "BCT formalism"). Proposes artificial metrics according to a circular dendrogram (see "xdend_tree", but used as angles). This can be seen as an equivalent tree (electrotonically) to any real tree whose BCT string is known.
Examples: the TREES toolbox -on the nature of neuronal branching 98 clean_tree deletes improbable nodes graphtheory edit metrics graphical construct electrotonics IO

tree = clean_tree (intree, radius, options)
Cleans tree intree of improbable nodes (after e.g. automated reconstruction or artificial generation of a tree structure). Termination points in close vicinity of other nodes on a different branch will be deleted and very short terminal branches as well. The "close vicinity" depends on the radius of the "other node" and on the input parameter radius. Consecutive calls of this function can be useful. Example: >> clean_tree (sample2_tree, 20); in gray: original tree in black: cleaned tree clone_tree MST-based cloning graphtheory edit metrics graphical construct electrotonics IO

trees = clone_tree (intrees, num, bf, options)
Creates as set of num trees trees similar to an input set of trees intrees by distributing points randomly in the spanning fields of the average intrees, scaling them within the variance of intrees and connecting them with "MST_tree", the minimum spanning tree constructor. "MST_tree" requires the balancing factor bf between minimization of path length and total wire length.

>> trees = clone_tree (dLPTCs{5})
This is a good opportunity to mention that specific cloning should be adapted to the individual properties of the trees to be cloned. In this case much better results can be obtained (just out of reasons of computation) by using the fact that the trees are flat or by fitting the amount of jitter or taper in more sophisticated ways (not implemented in clone_tree for speed reasons). clone_tree uses "gscale_tree" to fit these parameters, a very primitive but computationally efficient way to obtain them.
the TREES toolbox -on the nature of neuronal branching 100 cplotter plots a contour graphtheory edit metrics graphical construct electrotonics IO

HP = cplotter (c, color, DD)
Plots a 2D contour c obtained e.g. from "contourc" (see Matlab function). A contour c is defined by: #number_of_pairs y1 y2 y3 ... #number_of_pairs y1 y2 y3 ...]' "hull_tree" can for example produce such a contour and this can be used to describe the spanning field of a neuronal tree in the construction process. The contour plot is offset by XYZ 3-tupel DD and coloured with RGB 3-tupel color. HP is the handle to the graphical object. "hull_tree" can for example produce such a contour and this can be used to describe the spanning field of a neuronal tree in the construction process. Example:

[spanning ctrees] = gscale_tree (intrees, options)
Extracts region by region features from a group of trees intrees which are sufficient to constrain the artificial generation of trees similar to the original group. Is based on the assumption that the density of topological points on the trees are more or less scalable. The result is a structure spanning with some info about the spanning fields of the individual regions throughout the trees. ctrees contains the scaled trees.
Example: "hull_tree" can for example produce such a contour and this can be used to describe the spanning field of a neuronal tree in the construction process.

isBCT = isBCT_tree (intree)
Checks if tree intree (or a BCT vector of terminals (0), continuations (1) and branches (2)) is conform to BCT order (see introduction section "BCT formalism"). Examples: >> isBCT_tree ([1 2 1 0 2 0 0 Adds spatial noise to the coordinates of the nodes of tree intree. The amplitude of the spatial noise is such that its standard deviation is stde and it is filtered with length constant lambda (not in mm but in nodes on the path...).

[tree indx] = MST_tree (msttrees, X, Y, Z, bf, thr, mplen, DIST, options)
Connects points defined by coordinates X, Y and Z in a competitive manner to starting trees msttrees (alternatively: starting positions as index into X, Y and Z) using a greedy algorithm which minimizes locally the total amount of wiring and the path length to the root (with balancing factor bf). A threshold connection distance thr and a maximal path length in the tree mplen constrain the resulting tree size. A sparse distance matrix DIST between nodes is added to the cost function. Don't forget to include input tree nodes into the distance matrix DIST! Option "-b" forbids trifurcations during the process, option "-t" outputs timelapse trees, see option "-s" for a movie. Maps quadratic diameter tapering on a given tree structure intree. P and ldend are derived in (Cuntz, Borst and Segev 2007, Theor Biol Med Model, 4:21). P is an numx3 matrix containing the parameters to put in the quadratic equation y = P(1)x 2 + P(2)x + P(3). Each single triplet corresponds to the best fit to a segment of length ldend (numx1) vector. When the quadratic diameter is added, the path from each terminal to the root is compared to its closest in ldend. Then the quadratic equation is chosen according to the index in ldend. This is done for all paths from root to terminal point and for each node the diameter is an average of all local diameters of all paths leading through that node. Choosing parameters (P and ldend) by hand here is tempting but very hard. P and ldend depend on the total leak and the minimal diameter: these have to be adjust by the parameters scale and offset respectively (see "quadfit_tree").
resampling is better for a homogeneous quadratic diameter tapering the TREES toolbox -on the nature of neuronal branching 108 quadfit_tree fit quadratic diameter taper graphtheory edit metrics graphical construct electrotonics IO

[P0 tree] = quadfit_tree (intree, options)
To a given tree intree with diameter values, this fits a quadratic tapering using "quaddiameter_tree" to best fit the original diameters. The output is a scaling and an offset value in P0 for direct input to "quaddiameter_tree". See below how well two parameters simply describe the dendritic quadratic tapering nearly perfectly.
Examples: Distributes N random points in accordance with the density matrix M. Only points within the sharp boundaries of a 2d contour c are selected (see below). Note that the number of resulting points is therefore typically smaller than N.
The boundary can be further reduced by a distance thr, minimal distance that a point needs to be away from any point on the contour. This makes particularly sense if the contour was obtained using "hull_tree" in 2D. The contour (see "contourc") is defined by: #number_of_pairs y1 y2 y3 ... #number_of_pairs y1 y2 y3 ...]' see "hull_tree" to check out how such a contour can be produced.

Examples:
As an example, let"s get some points which are similarly distributed as an underlying hsn cell: Smoothens a tree intree along its longest paths. This changes (shortens) the total length of the branch significantly. First finds the heavier sub-branches (thresholded by .5 to 1 value pwchild) and puts them together to longest paths. Then a smoothing step is applied on the branches individually using p, proportion smoothing (0 to 1, default .9), and n, number of iterations (default 10). "smooth_tree" calls "smoothbranch" but this sub-function can be replaced by any other one of a similar type. Smoothens a branch given by consecutive 3D coordinates X, Y and Z, in usage by "smooth_tree". This changes (shortens) the total length of the branch significantly. The amount of smoothing is parameterized by p, proportion smoothing (0 to 1, default .9), and n, number of iterations (default 10). Method: in each triplet of consecutive points, approach the middle point toward the center of the triangle formed by the three points. (this is rather arbitrary and can be improved) Changes the diameter in tree intree in all locations smaller than path length x=l/2 [in mm] away from the root. Diameters become a sort of circular (cosine) soma shape of maximal diameter mD: If the original diameter at that location in the tree is larger, it remains unchanged! resampling is better for a homogeneous result the TREES toolbox -on the nature of neuronal branching 113 spines_tree add spines graphtheory edit metrics graphical construct electrotonics IO tree = spines_tree (intree, XYZ, dneck, dhead, mlneck, stdlneck, ipart,

options)
Attaches cylinders with diameter dhead to closest node on an existing tree intree, introducing a neck with diameter dneck. If XYZ coordinates XYZ are not defined, the spines are attached to a randomly picked node with distance mlneck+-stdlneck. XYZ parameter becomes the number of spines (default: 100). If region with name "spines" exists then nodes are appended to that region otherwise new nodes are attributed to new region named "spines". ipart is an optional index for attaching spines only to a sub-set of nodes. 119 loop_tree conductance matrix incl. loops graphtheory edit metrics graphical construct electrotonics IO

M = loop_tree (intree, inodes1, inodes2, gelsyn, options)
Creates loops in the neuronal conductance matrix of tree intree. Since conventional trees cannot be used (they are not supposed to have loops), a conductance matrix M is calculated directly extending on M from "M_tree". Set of num nodes inodes1 are connected to the set of num nodes inodes2 with gap junction conductances given by numx1 vector gelsyn.

>> inv (M)
the TREES toolbox -on the nature of neuronal branching 120 M_tree conductance matrix graphtheory edit metrics graphical construct electrotonics IO

M = M_tree (intree, options)
Calculates the matrix containing the conductances in the equivalent circuit of the neuron in the tree structure intree. To be used in "sse_tree" and other electrotonic analysis of trees. See introduction section "electrotonic signature" for more details: Example:

sse = sse_tree (intree, I, options)
Calculates the steady state electrotonic (sse) matrix describing the electrotonic properties of the neuron in the tree structure intree. Each column j is the potential distribution in all nodes during injection of current into node j. The diagonal contains therefore the local input resistances of each node. sse, NxN matrix, is therefore symmetric. If input current I is not identity matrix then columns in sse correspond to potential distributions in separate experiments corresponding to the input current distribution in that column. Note that NxN sse is obtained by inverse matrix calculation and therefore goes very quickly but takes memory. In special cases it is advisable to split calls in several input matrices I. the TREES toolbox -on the nature of neuronal branching 122 ssecat_tree sse signature incl. gap junctions graphtheory edit metrics graphical construct electrotonics IO
Example: we reproduce a simplified dendritic network similar as in (Cuntz H, Haag J, Borst A 2003 PNAS 100(19):11082-5). Connect all nodes from one tree to another one and inject a current in the dendrite of one tree: The resulting potential spread is smaller in the tree where the current was injected, than in the neighbour: the dendritic network leads to spatial blurring, as is used in some fly interneurons to process motion-based images: 2. cell 1. cell the TREES toolbox -on the nature of neuronal branching 123 syn_tree synaptic electrotonic signature graphtheory edit metrics graphical construct electrotonics IO syn = syn_tree (intree, ge, Ee, gi, Ei, I, options) Calculates the steady state potentials matrix syn resulting from a current injection I (see "sse_tree") and synaptic inputs defined by Nx1 vectors ge and gi, conductance values for each node (or alternatively: node location of unit conductances), and reversal potential values Ee and Ei into tree intree.
Examples: Impact of on-path location of inhibition, compare:

I, options)
Concatenates trees in cell array of trees intrees with electrical synapses and calculates the steady state electrotonic matrix just as does "ssecat_tree". Additionally, synaptic inputs (as in "syn_tree") can be defined by conductance values ge and gi and by reversal potentials Ee and Ei. Loads the metrics and the corresponding directed adjacency matrix of tree from file name to create the tree structure. Input files can be in TREES internal .mtr format (which is just a matlab workspace file), in .swc format (see "swc_tree") or in an export format .neu for trees created in the software NEURON package (http://www.neuron.yale.edu/neuron/) with the function "neu_tree" provided in the TREES toolbox. Make sure to realize that most imported trees are originally encoded as connected frusta instead of cylinders whereas the TREES toolbox assumes that they are cylinders. This can be changed by adding the field "frustum=1" to the tree structure. Loads the metrics and the corresponding directed adjacency matrix to create a tree directly from an ASCII neurolucida description file called name. NOTE! For example to infer the cylinder-representation of the soma we chose arbitrary algorithms similar but not equal to the NEURON neurolucida import. Sub-trees are attributed to somata by who-is-closest. This function can be much further optimized or just rewritten. The TREES toolbox function however has additional features to the NEURON neurolucida import. For example spines are imported (as cylinders with region named "spines"). Furthermore, imported markers can be added as spines via "spines_tree". Examples:

>> neurolucida_tree
the TREES toolbox -on the nature of neuronal branching 128 neuron_tree export tree as NEURON file graphtheory edit metrics graphical construct electrotonics IO

[name path] = neuron_tree (intree, name, res, options)
Saves a complete tree intree into the file called name in the section based NEURON (http://www.neuron.yale.edu/neuron/) .hoc format. res determines the resolution at which NEURON samples a segment (nseg). Alternatively, the tree can also be stored as .nrn file in which each segment from the tree graph becomes an independent section in NEURON. Option "-e" incorporates electrotonic properties if existent, "->" starts NEURON immediately if it is installed and the TREES toolbox runs in windows.
Examples: Current injection in section dendrite [5] and spatial potential distribution.

[name path] = pov_tree (intree, name, v, options)
Writes POV-ray (http://www.povray.org/) files using the anatomy-data contained in intree. intree can be a single tree structure or a cell array of trees or just XYZD coordinates of points (plotted as spheres). With v, an Nx1 vector or cell array of vectors (corresponding to intree), values for each node can be mapped to the colours of the segments. options involve different styles and for example option "-c" for brainbow random colours and "-v" option which conserves the viewpoint of the active Matlab figure. "->" starts POV-Ray immediately if it is installed and the TREES toolbox runs in windows. Saves tree intree into a TREES internal .mtr format using a Matlab type workspace file. intree can be a structured tree or a cell array of structured tree or a cell array of cell array of structured trees (2-depth). This type of file can be read directly by the GUI (see below) and the 2-depth in that case allows to arrange in groups of trees. Examples:

[name path] = swc_tree (intree, name)
Exports tree intree to the .swc format, a matrix with 7 columns: node index inode is usually from 1..N and idpar is the direct parent index. The root has an idpar of - Exports a tree intree as a set of cylinders in the .x3d html format. A viewer is necessary to use these files. Blender (http://www.blender.org/) and BS Contact (http://www.bitmanagement.com/) can for example load .x3d files. As opposed to POV-Ray (see "pov_tree", http://www.povray.org/), these programs can only deal with polygons. As such, the output trees are sets of polygons. Object is offset by XYZ 3-tupel DD and coloured with RGB 3-tupel color (or Nx1 vector, attributing one value per node). ipart, a set of indices into intree, allows to use only a subset of nodes, for example only a sub-tree. If a viewer is installed and TREES runs on windows Matlab can call the viewer directly with the option "->". This is a NEURON .hoc file which exports a tree into a .neu format which the TREES toolbox can read using "load_tree". Works only for basic trees and sometimes scrambles the graph (use "cgui_tree" for editing). Make sure to realize that most imported trees are originally encoded as connected frusta instead of cylinders whereas the TREES toolbox assumes that they are cylinders. This can be changed by adding the field "frustum=1" to the tree structure.

code in NEURON hoc
After having loaded one single cell in the NEURON environment (make sure that the file neu_tree.hoc is in the current directory). Examples: >> load_file("neu_tree.hoc") >> neu_tree("tree.neu") "load_tree" in the Matlab environment is then able to load the .neu file.
the TREES toolbox -on the nature of neuronal branching

2D Euclidean distances btw. 2 sets of points
Calculates a distance matrix M between two sets of points described by their x and y coordinates.

a 3D round show of a plot
a 3D round show, simply changes the view in regular intervals.
add a scalebar to a plot add some effects on current axis polishes the graphical output. By default simply adds a camera light (therefore the name "shine"), which typically sets the figure renderer to opengl as a side effect.   From Watt , Cuntz, Mori, Nusser, Sjöström, Häusser 2009, Nat Neurosci 12: 463-473. the TREES toolbox -on the nature of neuronal branching 146 The GUI starting the GUI Calling:

>> cgui_tree
opens up a user interface window. With it the user can browse through directories of trees, edit them, explore their properties. The individual buttons typically link to one function of the TREES toolbox. The GUI is therefore practical to explore the possibilities of the toolbox before starting a research project with the more flexible command line interaction. Aside of that, the user interface allows the automated reconstruction of neuronal branching structures directly from image stacks. The following passages will attempt to familiarize the user with the axis, the multiple panels, the menu etc.. of the GUI.
All the GUI is divided into three parts, one common axis, a menu and a number of control panels. The control panels on the right are there to control the axis, the graphical output and to browse through trees or individual nodes or properties of a tree. The control panels to the left are associated with the process of reconstruction, artificial generation and editing of tree structures. To each of the panels on the left special "edit" modes are associated. The GUI the vis_ panel

2D views
The vis_ panel (visualization) controls the one common axis. To each control panel a prefix is attributed (here "vis_") and all computer code related to this control panel uses this prefix in the core program of the GUI, "cgui_tree". The GUI the vis_ panel The grid button toggles on/off the grid. It settles in the plane corresponding to the active view at the coordinate given by the slicer field. Grid field coordinates are set according to the two dimensions of the active plane. The slicer coordinate becomes important later for image stack representation and manual editing of a tree.
If the plotted image contains color-coded values (e.g. the brightness values in an image stack or in this case the mapping of branch orders on the sample tree), a colorbar can be summoned up using the colorbar controls. By default the limits are set automatically. However, these can be manually adjusted using the two edit fields.
The colormap can be chosen in the menu. Also, by default, the colormap is transparent but it can be switched back to opaque in the same menu. This also affects the image stack representations (but not the trees).

The GUI the stk_ panel
For reconstruction purposes or just to compare a tree with its underlying image stack, load image stacks or single images using the menu. The TREES internal .stk format stacks are just binary Matlab workspaces and can be read out in comand line using the matlab "load" function (but see also "load_stack"). In the following we will assume that the first goal is a reconstruction of a tree present in tiled image stacks. The stk_ panel is then the first editing panel required. The image stacks are loaded sequentially and the last stack in the popup control is the active stack. With the thr_ panel a set of binary matrices is constructed by thresholding the original image stacks. If the "dyn." toggle is pressed down a local (or dynamic) threshold is taken. This is particularly advantageous to capture small branches. The edit value is an offset to the local mean brightness necessary to be part of the binary matrix. Without dyn. thresholding the edit value indicates the actual absolute threshold value. The vis_ panel displays the percentage of voxels which fall in the binary matrix. That should typically not exceed 2-3%. When the third radio button is switched on, the maximum intensity projections of the stk_ panel show the index of thresholded maximum values, which in the XY view for example corresponds to the z values (between 0 and 1), at which the brightness is maximal in the original image stack.
With the first radio button switched on, little blue transparent tiles are drawn on the maximum intensity projections to show which voxels will be kept in the binary matrices.
Cleaning the binary matrix involves linking voxels by neighborhood relationships. When a set of linked voxels is smaller than the cleaning size in the edit field, it is removed. This is an efficient way to remove noisy bits off of the thresholded image (see Matlab function "bwareaopen"). Finally, in order to check the integrity of the binary matrix and its flow between the tiled image stacks, the second radio button can be activated (this can be very slow). This shows a 3D box representation of the binary matrices at a reduced resolution (2x2 voxels in the XY plane). The skl_ panel is there to reduce the binary matrices to a set of individual carrier points and some starting nodes to be subsequently connected to trees. The 3D skeletonization is a process which carves off binary voxels one by one in dependence of their neighborhood (a method introduced by Palagyi and Kuba), ideally leaving only the carrier nodes of the branched structure (see "skel_stack"). Pressing the "skel" button performs the morphological operation. If toggle "D" is pressed, a diameter value is obtained for each node from the neighborhood relationships of the binary matrix: D is the distance of the closest zero value in the binary matrix (see "bwdist" from the image processing toolbox in Matlab). If toggle "L" is pressed, a labeling is performed on the binary matrix: two nodes are connected if walking on non-zero voxels from one to the other without gaps is possible. This is helpful for calculating the connnectivity matrix later. Also it helps to chose starting points: two starting points should never show up on the same "label" (see "bwlabeln" from the image processing toolbox in matlab).
The skl_panel is equipped with a very basic soma finding function. This takes the threshold value (thr) in the edit field and finds either all nodes whose diameters were calculated to be higher than thr. If none falls in that category the node with the highest diameter is chosen (as in this case). If more than one node falls in that category then smaller starting nodes which appear in distance smaller than thr of larger starting nodes are cleaned away. Starting nodes which appear on the same label are also deleted. Pressing [v] in the edit2 mode previews the result of cleaning. This process reduces the number of nodes by preventing neighboring nodes within a distance limit in mm indicated in the edit field. Pressing [V] or the "clean" key finalizes the sparsening of the nodes.
The nodes and starting nodes are then ready for the tree constructor. However to improve the result further the MST tree constructor with "RST" option accepts a distance matrix between the nodes to increase the probability of connection. Thresholdlinking is a standard way to do this. The resulting connectivity graph of increased connection probability is shown when the third radio button is active. The mtr_ panel is the most intricate panel and also the core panel in the TREES toolbox GUI. Artificial trees can be constructed using different methods such as automated reconstruction, cloning or fully manually. The trees can be remodelled in many different ways including smoothing, introducing jitter, resampling, diameter tapering, addition of spines and somata or manual remodelling. Equivalent trees can be obtained, trees can be morphed or flattened or cut to pieces, etc.. The edit modes in this panel have multiple sub-modes allowing the editing of single nodes, selected nodes, sub-trees etc... In the automated reconstruction process the first step is to connect the skeletonized points obtained by the skl_ panel to a graph. This is done in the TREES toolbox using the MST constructor (see "MST rule" in the introductary part) following a greedy algorithm to obtain an extended minimum spanning tree. The constructor is launched with the "MST" button in the mtr_ panel.
the TREES toolbox -on the nature of neuronal branching 159 The GUI the mtr_ panel Because of the central role of the mtr_ panel a number of different representations exist. By default (first radio button), a tree is represented as rectangular pieces between two connected nodes corresponding to the cylinder or frustum. The rectangular pieces are mapped to the active vis_ plane, in this case in the XY-plane. A green circle indicates the last activated node (here the root).
Additionally, the second radio button allows a 3D visualization of the tree. The last radio button toggles transparency. In order to set higher or lower cylinder resolution go to the "Visualize" menu.
As an alternative to the second option a graph representing the edges between nodes as arrows can be selected using the third radio buttion.
If an Nx1 vector has been selected with the slt_ panel (see later), this can be mapped on the colour values of the tree again as an alternative to the second option. This happens when toggling ON the fourth radio button.
the TREES toolbox -on the nature of neuronal branching Cleaning a tree (see "clean_tree") is a process in which improbable nodes are eliminated. Termination points in close vicinity of other nodes on a different branch and very short terminal branches are deleted. Consecutive calls of this function can be useful.

Resample a tree
Resampling a tree (see "resample_tree") redistributes nodes such that segments are constant length. This is required to get a unique graph representation, and to apply functions such as adding a spatial jitter or a number of spines homogeneously.
The resulting tree from the reconstruction process is ready for manual editing (see later) but can also simply be cleaned up with different cleaning algorithms

Smoothing a tree
Smoothing a tree (see "smooth_tree") along its longest paths.

Add spatial jitter
If additional jitter is desired it can be applied here (see "jitter_tree").

The GUI the plt_ panel
The examples on this page and the next are different plotting options provided by the TREES toolbox. For the purpose of illustration, the branch order was mapped onto the nodes (BO Nx1 vector in the slt_ panel) and a sub-tree was selected (using the subtree function of the slt_ panel). Each plotting function creates a handle package. These handle packages can then be browsed post hoc, altered or deleted.
plot maps BO on colour but disregards sub-tree selection.

patch plot
2D patches in XY-plane. Maps BO on colour plots only selected sub-tree.

quiver plot
Arrows along edges of graph. Disregards BO mapping, but plots only selected sub-tree.

text plot
Plots the BO values as 2D or 3D text and maps BO on colour. Covers only selected indices.