Search is not available for this dataset
text
stringlengths
75
104k
def section_term_radial_distances(neurites, neurite_type=NeuriteType.all, origin=None): '''Get the radial distances of the termination sections for a collection of neurites''' return section_radial_distances(neurites, neurite_type=neurite_type, origin=origin, iterator_type=Tr...
def section_bif_radial_distances(neurites, neurite_type=NeuriteType.all, origin=None): '''Get the radial distances of the bifurcation sections for a collection of neurites''' return section_radial_distances(neurites, neurite_type=neurite_type, origin=origin, iterator_type=Tre...
def number_of_sections_per_neurite(neurites, neurite_type=NeuriteType.all): '''Get the number of sections per neurite in a collection of neurites''' return list(sum(1 for _ in n.iter_sections()) for n in iter_neurites(neurites, filt=is_type(neurite_type)))
def total_length_per_neurite(neurites, neurite_type=NeuriteType.all): '''Get the path length per neurite in a collection''' return list(sum(s.length for s in n.iter_sections()) for n in iter_neurites(neurites, filt=is_type(neurite_type)))
def terminal_path_lengths_per_neurite(neurites, neurite_type=NeuriteType.all): '''Get the path lengths to each terminal point per neurite in a collection''' return list(sectionfunc.section_path_length(s) for n in iter_neurites(neurites, filt=is_type(neurite_type)) for s in iter_s...
def total_volume_per_neurite(neurites, neurite_type=NeuriteType.all): '''Get the volume per neurite in a collection''' return list(sum(s.volume for s in n.iter_sections()) for n in iter_neurites(neurites, filt=is_type(neurite_type)))
def neurite_volume_density(neurites, neurite_type=NeuriteType.all): '''Get the volume density per neurite The volume density is defined as the ratio of the neurite volume and the volume of the neurite's enclosing convex hull ''' def vol_density(neurite): '''volume density of a single neurit...
def section_volumes(neurites, neurite_type=NeuriteType.all): '''section volumes in a collection of neurites''' return map_sections(sectionfunc.section_volume, neurites, neurite_type=neurite_type)
def section_areas(neurites, neurite_type=NeuriteType.all): '''section areas in a collection of neurites''' return map_sections(sectionfunc.section_area, neurites, neurite_type=neurite_type)
def section_tortuosity(neurites, neurite_type=NeuriteType.all): '''section tortuosities in a collection of neurites''' return map_sections(sectionfunc.section_tortuosity, neurites, neurite_type=neurite_type)
def section_end_distances(neurites, neurite_type=NeuriteType.all): '''section end to end distances in a collection of neurites''' return map_sections(sectionfunc.section_end_distance, neurites, neurite_type=neurite_type)
def principal_direction_extents(neurites, neurite_type=NeuriteType.all, direction=0): '''Principal direction extent of neurites in neurons''' def _pde(neurite): '''Get the PDE of a single neurite''' # Get the X, Y,Z coordinates of the points in each section points = neurite.points[:, :3]...
def section_strahler_orders(neurites, neurite_type=NeuriteType.all): '''Inter-segment opening angles in a section''' return map_sections(sectionfunc.strahler_order, neurites, neurite_type)
def _plane2col(plane): '''take a string like 'xy', and return the indices from COLS.*''' planes = ('xy', 'yx', 'xz', 'zx', 'yz', 'zy') assert plane in planes, 'No such plane found! Please select one of: ' + str(planes) return (getattr(COLS, plane[0].capitalize()), getattr(COLS, plane[1].capi...
def _get_linewidth(tree, linewidth, diameter_scale): '''calculate the desired linewidth based on tree contents If diameter_scale exists, it is used to scale the diameter of each of the segments in the tree If diameter_scale is None, the linewidth is used. ''' if diameter_scale is not None and t...
def plot_tree(ax, tree, plane='xy', diameter_scale=_DIAMETER_SCALE, linewidth=_LINEWIDTH, color=None, alpha=_ALPHA): '''Plots a 2d figure of the tree's segments Args: ax(matplotlib axes): on what to plot tree(neurom.core.Tree or neurom.core.Neurite): plotted tree ...
def plot_soma(ax, soma, plane='xy', soma_outline=True, linewidth=_LINEWIDTH, color=None, alpha=_ALPHA): '''Generates a 2d figure of the soma. Args: ax(matplotlib axes): on what to plot soma(neurom.core.Soma): plotted soma plane(str): Any pair of...
def plot_neuron(ax, nrn, neurite_type=NeuriteType.all, plane='xy', soma_outline=True, diameter_scale=_DIAMETER_SCALE, linewidth=_LINEWIDTH, color=None, alpha=_ALPHA): '''Plots a 2D figure of the neuron, that contains a soma and the neur...
def _update_3d_datalim(ax, obj): '''unlike w/ 2d Axes, the dataLim isn't set by collections, so it has to be updated manually''' min_bounding_box, max_bounding_box = geom.bounding_box(obj) xy_bounds = np.vstack((min_bounding_box[:COLS.Z], max_bounding_box[:COLS.Z])) ax.xy_data...
def plot_tree3d(ax, tree, diameter_scale=_DIAMETER_SCALE, linewidth=_LINEWIDTH, color=None, alpha=_ALPHA): '''Generates a figure of the tree in 3d. If the tree contains one single point the plot will be empty \ since no segments can be constructed. Args: ax(matp...
def plot_soma3d(ax, soma, color=None, alpha=_ALPHA): '''Generates a 3d figure of the soma. Args: ax(matplotlib axes): on what to plot soma(neurom.core.Soma): plotted soma color(str or None): Color of plotted values, None corresponds to default choice alpha(float): Transparency o...
def plot_neuron3d(ax, nrn, neurite_type=NeuriteType.all, diameter_scale=_DIAMETER_SCALE, linewidth=_LINEWIDTH, color=None, alpha=_ALPHA): ''' Generates a figure of the neuron, that contains a soma and a list of trees. Args: ax(matplotlib axes): on what to plo...
def _generate_collection(group, ax, ctype, colors): '''Render rectangle collection''' color = TREE_COLOR[ctype] # generate segment collection collection = PolyCollection(group, closed=False, antialiaseds=True, edgecolors='face', facecolors=color) # add it to the axe...
def _render_dendrogram(dnd, ax, displacement): '''Renders dendrogram''' # set of unique colors that reflect the set of types of the neurites colors = set() for n, (indices, ctype) in enumerate(zip(dnd.groups, dnd.types)): # slice rectangles array for the current neurite group = dnd.dat...
def plot_dendrogram(ax, obj, show_diameters=True): '''Dendrogram of `obj` Args: obj: Neuron or tree \ neurom.Neuron, neurom.Tree show_diameters : boolean \ Determines if node diameters will \ be show or not. ''' # create dendrogram and generate rectangle ...
def make_neurites(rdw): '''Build neurite trees from a raw data wrapper''' post_action = _NEURITE_ACTION[rdw.fmt] trunks = rdw.neurite_root_section_ids() if not trunks: return [], [] # One pass over sections to build nodes nodes = tuple(Section(section_id=i, poi...
def _remove_soma_initial_point(tree): '''Remove tree's initial point if soma''' if tree.points[0][COLS.TYPE] == POINT_TYPE.SOMA: tree.points = tree.points[1:]
def _check_soma_topology_swc(points): '''check if points form valid soma Currently checks if there are bifurcations within a soma with more than three points. ''' if len(points) == 3: return parents = tuple(p[COLS.P] for p in points if p[COLS.P] != ROOT_ID) if len(parents) > len(se...
def points(self): '''Return unordered array with all the points in this neuron''' if self._points is None: _points = self.soma.points.tolist() for n in self.neurites: _points.extend(n.points.tolist()) self._points = np.array(_points) return se...
def transform(self, trans): '''Return a copy of this neuron with a 3D transformation applied''' _data = deepcopy(self._data) _data.data_block[:, 0:3] = trans(_data.data_block[:, 0:3]) return FstNeuron(_data, self.name)
def vector(p1, p2): '''compute vector between two 3D points Args: p1, p2: indexable objects with indices 0, 1, 2 corresponding to 3D cartesian coordinates. Returns: 3-vector from p1 - p2 ''' return np.subtract(p1[COLS.XYZ], p2[COLS.XYZ])
def linear_interpolate(p1, p2, fraction): '''Returns the point p satisfying: p1 + fraction * (p2 - p1)''' return np.array((p1[0] + fraction * (p2[0] - p1[0]), p1[1] + fraction * (p2[1] - p1[1]), p1[2] + fraction * (p2[2] - p1[2])))
def interpolate_radius(r1, r2, fraction): '''Calculate the radius that corresponds to a point P that lies at a fraction of the length of a cut cone P1P2 where P1, P2 are the centers of the circles that bound the shape with radii r1 and r2 respectively. Args: r1: float Radius of the ...
def path_fraction_id_offset(points, fraction, relative_offset=False): '''Find the segment which corresponds to the fraction of the path length along the piecewise linear curve which is constructed from the set of points. Args: points: an iterable of indexable objects with indices 0, 1, ...
def path_fraction_point(points, fraction): '''Computes the point which corresponds to the fraction of the path length along the piecewise linear curve which is constructed from the set of points. Args: points: an iterable of indexable objects with indices 0, 1, 2 correspoding to 3D cart...
def scalar_projection(v1, v2): '''compute the scalar projection of v1 upon v2 Args: v1, v2: iterable indices 0, 1, 2 corresponding to cartesian coordinates Returns: 3-vector of the projection of point p onto the direction of v ''' return np.dot(v1, v2) / np.linalg.norm(v2)
def vector_projection(v1, v2): '''compute the vector projection of v1 upon v2 Args: v1, v2: iterable indices 0, 1, 2 corresponding to cartesian coordinates Returns: 3-vector of the projection of point p onto the direction of v ''' return scalar_projection(v1, v2) * v2 / np....
def dist_point_line(p, l1, l2): '''compute the orthogonal distance between from the line that goes through the points l1, l2 and the point p Args: p, l1, l2 : iterable point indices 0, 1, 2 corresponding to cartesian coordinates ''' cross_prod = np.cross(l2 - l1, p - l1) ...
def point_dist2(p1, p2): '''compute the square of the euclidian distance between two 3D points Args: p1, p2: indexable objects with indices 0, 1, 2 corresponding to 3D cartesian coordinates. Returns: The square of the euclidian distance between the points. ''' v = vector(p1,...
def angle_3points(p0, p1, p2): ''' compute the angle in radians between three 3D points Calculated as the angle between p1-p0 and p2-p0. Args: p0, p1, p2: indexable objects with indices 0, 1, 2 corresponding to 3D cartesian coordinates. Returns: Angle in radians between (p1-p...
def angle_between_vectors(p1, p2): """ Computes the angle in radians between vectors 'p1' and 'p2' Normalizes the input vectors and computes the relative angle between them. >>> angle_between((1, 0), (0, 1)) 1.5707963267948966 >>> angle_between((1, 0), (1, 0)) 0.0 >>...
def polygon_diameter(points): ''' Compute the maximun euclidian distance between any two points in a list of points ''' return max(point_dist(p0, p1) for (p0, p1) in combinations(points, 2))
def average_points_dist(p0, p_list): """ Computes the average distance between a list of points and a given point p0. """ return np.mean(list(point_dist(p0, p1) for p1 in p_list))
def path_distance(points): """ Compute the path distance from given set of points """ vecs = np.diff(points, axis=0)[:, :3] d2 = [np.dot(p, p) for p in vecs] return np.sum(np.sqrt(d2))
def segment_radial_dist(seg, pos): '''Return the radial distance of a tree segment to a given point The radial distance is the euclidian distance between the mid-point of the segment and the point in question. Parameters: seg: tree segment pos: origin to which distances are measured. ...
def segment_area(seg): '''Compute the surface area of a segment. Approximated as a conical frustum. Does not include the surface area of the bounding circles. ''' r0 = seg[0][COLS.R] r1 = seg[1][COLS.R] h2 = point_dist2(seg[0], seg[1]) return math.pi * (r0 + r1) * math.sqrt((r0 - r1) **...
def segment_volume(seg): '''Compute the volume of a segment. Approximated as a conical frustum. ''' r0 = seg[0][COLS.R] r1 = seg[1][COLS.R] h = point_dist(seg[0], seg[1]) return math.pi * h * ((r0 * r0) + (r0 * r1) + (r1 * r1)) / 3.0
def taper_rate(p0, p1): '''Compute the taper rate between points p0 and p1 Args: p0, p1: iterables with first 4 components containing (x, y, z, r) Returns: The taper rate, defined as the absolute value of the difference in the diameters of p0 and p1 divided by the euclidian distanc...
def principal_direction_extent(points): '''Calculate the extent of a set of 3D points. The extent is defined as the maximum distance between the projections on the principal directions of the covariance matrix of the points. Parameter: points : a 2D numpy array of points Returns: ext...
def stylize(ax, name, feature): '''Stylization modifications to the plots ''' ax.set_ylabel(feature) ax.set_title(name, fontsize='small')
def histogram(neuron, feature, ax, bins=15, normed=True, cumulative=False): ''' Plot a histogram of the selected feature for the population of neurons. Plots x-axis versus y-axis on a scatter|histogram|binned values plot. Parameters : neurons : neuron list feature : str The fe...
def plot_feature(feature, cell): '''Plot a feature ''' fig = pl.figure() ax = fig.add_subplot(111) if cell is not None: try: histogram(cell, feature, ax) except ValueError: pass stylize(ax, cell.name, feature) return fig
def path_end_to_end_distance(neurite): '''Calculate and return end-to-end-distance of a given neurite.''' trunk = neurite.root_node.points[0] return max(morphmath.point_dist(l.points[-1], trunk) for l in neurite.root_node.ileaf())
def make_end_to_end_distance_plot(nb_segments, end_to_end_distance, neurite_type): '''Plot end-to-end distance vs number of segments''' plt.figure() plt.plot(nb_segments, end_to_end_distance) plt.title(neurite_type) plt.xlabel('Number of segments') plt.ylabel('End-to-end distance') plt.show(...
def calculate_and_plot_end_to_end_distance(neurite): '''Calculate and plot the end-to-end distance vs the number of segments for an increasingly larger part of a given neurite. Note that the plots are not very meaningful for bifurcating trees.''' def _dist(seg): '''Distance between segmenr end ...
def tree_type_checker(*ref): '''Tree type checker functor Returns: Functor that takes a tree, and returns true if that tree matches any of NeuriteTypes in ref Ex: >>> from neurom.core.types import NeuriteType, tree_type_checker >>> tree_filter = tree_type_checker(NeuriteTyp...
def dendrite_filter(n): '''Select only dendrites''' return n.type == NeuriteType.basal_dendrite or n.type == NeuriteType.apical_dendrite
def plot_somas(somas): '''Plot set of somas on same figure as spheres, each with different color''' _, ax = common.get_figure(new_fig=True, subplot=111, params={'projection': '3d', 'aspect': 'equal'}) for s in somas: common.plot_sphere(ax, s.center, s.radius, color=rand...
def _max_recursion_depth(obj): ''' Estimate recursion depth, which is defined as the number of nodes in a tree ''' neurites = obj.neurites if hasattr(obj, 'neurites') else [obj] return max(sum(1 for _ in neu.iter_sections()) for neu in neurites)
def _total_rectangles(tree): ''' Calculate the total number of segments that are required for the dendrogram. There is a vertical line for each segment and two horizontal line at each branching point ''' return sum(len(sec.children) + sec.points.shape[0] - 1 for sec in tree.iter_s...
def _n_rectangles(obj): ''' Calculate the total number of rectangles with respect to the type of the object ''' return sum(_total_rectangles(neu) for neu in obj.neurites) \ if hasattr(obj, 'neurites') else _total_rectangles(obj)
def _square_segment(radius, origin): '''Vertices for a square ''' return np.array(((origin[0] - radius, origin[1] - radius), (origin[0] - radius, origin[1] + radius), (origin[0] + radius, origin[1] + radius), (origin[0] + radius, origin[1] - rad...
def _vertical_segment(old_offs, new_offs, spacing, radii): '''Vertices for a vertical rectangle ''' return np.array(((new_offs[0] - radii[0], old_offs[1] + spacing[1]), (new_offs[0] - radii[1], new_offs[1]), (new_offs[0] + radii[1], new_offs[1]), ...
def _horizontal_segment(old_offs, new_offs, spacing, diameter): '''Vertices of a horizontal rectangle ''' return np.array(((old_offs[0], old_offs[1] + spacing[1]), (new_offs[0], old_offs[1] + spacing[1]), (new_offs[0], old_offs[1] + spacing[1] - diameter), ...
def _spacingx(node, max_dims, xoffset, xspace): '''Determine the spacing of the current node depending on the number of the leaves of the tree ''' x_spacing = _n_terminations(node) * xspace if x_spacing > max_dims[0]: max_dims[0] = x_spacing return xoffset - x_spacing / 2.
def _update_offsets(start_x, spacing, terminations, offsets, length): '''Update the offsets ''' return (start_x + spacing[0] * terminations / 2., offsets[1] + spacing[1] * 2. + length)
def _max_diameter(tree): '''Find max diameter in tree ''' return 2. * max(max(node.points[:, COLS.R]) for node in tree.ipreorder())
def _generate_soma(self): '''soma''' radius = self._obj.soma.radius return _square_segment(radius, (0., -radius))
def generate(self): '''Generate dendrogram ''' offsets = (0., 0.) n_previous = 0 # set recursion limit with respect to # the max number of nodes on the trees old_depth = sys.getrecursionlimit() max_depth = old_depth if old_depth > self._max_rec_depth els...
def _generate_dendro(self, current_section, spacing, offsets): '''Recursive function for dendrogram line computations ''' max_dims = self._max_dims start_x = _spacingx(current_section, max_dims, offsets[0], spacing[0]) for child in current_section.children: segments...
def types(self): ''' Returns an iterator over the types of the neurites in the object. If the object is a tree, then one value is returned. ''' neurites = self._obj.neurites if hasattr(self._obj, 'neurites') else (self._obj,) return (neu.type for neu in neurites)
def register_neurite_feature(name, func): '''Register a feature to be applied to neurites Parameters: name: name of the feature, used for access via get() function. func: single parameter function of a neurite. ''' if name in NEURITEFEATURES: raise NeuroMError('Attempt to hide r...
def get(feature, obj, **kwargs): '''Obtain a feature from a set of morphology objects Parameters: feature(string): feature to extract obj: a neuron, population or neurite tree **kwargs: parameters to forward to underlying worker functions Returns: features as a 1D or 2D num...
def _indent(string, count): '''indent `string` by `count` * INDENT''' indent = _INDENT * count ret = indent + string.replace('\n', '\n' + indent) return ret.rstrip()
def _get_doc(): '''Get a description of all the known available features''' def get_docstring(func): '''extract doctstring, if possible''' docstring = ':\n' if func.__doc__: docstring += _indent(func.__doc__, 2) return docstring ret = ['\nNeurite features (neurit...
def read(filename, remove_duplicates=False, data_wrapper=DataWrapper): '''Read a file and return a `data_wrapper'd` data * Tries to guess the format and the H5 version. * Unpacks the first block it finds out of ('repaired', 'unraveled', 'raw') Parameters: remove_duplicates: boolean, If True re...
def _remove_duplicate_points(points, groups): ''' Removes the duplicate points from the beginning of a section, if they are present in points-groups representation. Returns: points, groups with unique points. ''' group_initial_ids = groups[:, GPFIRST] to_be_reduced = np.zeros(len(gro...
def _unpack_v1(h5file): '''Unpack groups from HDF5 v1 file''' points = np.array(h5file['points']) groups = np.array(h5file['structure']) return points, groups
def _unpack_v2(h5file, stage): '''Unpack groups from HDF5 v2 file''' points = np.array(h5file['neuron1/%s/points' % stage]) # from documentation: The /neuron1/structure/unraveled reuses /neuron1/structure/raw groups_stage = stage if stage != 'unraveled' else 'raw' groups = np.array(h5file['neuron1/s...
def fit_results_to_dict(fit_results, min_bound=None, max_bound=None): '''Create a JSON-comparable dict from a FitResults object Parameters: fit_results (FitResults): object containing fit parameters,\ errors and type min_bound: optional min value to add to dictionary if min isn't\ ...
def fit(data, distribution='norm'): '''Calculate the parameters of a fit of a distribution to a data set Parameters: data: array of data points to be fitted Options: distribution (str): type of distribution to fit. Default 'norm'. Returns: FitResults object with fitted paramet...
def optimal_distribution(data, distr_to_check=('norm', 'expon', 'uniform')): '''Calculate the parameters of a fit of different distributions to a data set and returns the distribution of the minimal ks-distance. Parameters: data: array of data points to be fitted Options: distr_to_c...
def scalar_stats(data, functions=('min', 'max', 'mean', 'std')): '''Calculate the stats from the given numpy functions Parameters: data: array of data points to be used for the stats Options: functions: tuple of numpy stat functions to apply on data Returns: Dictionary with th...
def compare_two(data1, data2, test=StatTests.ks): '''Compares two distributions of data and assess two scores: a distance between them and a probability they are drawn from the same distribution. Parameters: data1: numpy array of dataset 1 data2: numpy array of dataset 2 ...
def total_score(paired_dats, p=2, test=StatTests.ks): '''Calculates the p-norm of the distances that have been calculated from the statistical test that has been applied on all the paired datasets. Parameters: paired_dats: a list of tuples or where each tuple contains the p...
def iter_neurites(obj, mapfun=None, filt=None, neurite_order=NeuriteIter.FileOrder): '''Iterator to a neurite, neuron or neuron population Applies optional neurite filter and mapping functions. Parameters: obj: a neurite, neuron or neuron population. mapfun: optional neurite mapping functi...
def iter_sections(neurites, iterator_type=Tree.ipreorder, neurite_filter=None, neurite_order=NeuriteIter.FileOrder): '''Iterator to the sections in a neurite, neuron or neuron population. Parameters: neurites: neuron, population, neurite, or iterabl...
def iter_segments(obj, neurite_filter=None, neurite_order=NeuriteIter.FileOrder): '''Return an iterator to the segments in a collection of neurites Parameters: obj: neuron, population, neurite, section, or iterable containing neurite objects neurite_filter: optional top level filter on properti...
def graft_neuron(root_section): '''Returns a neuron starting at root_section''' assert isinstance(root_section, Section) return Neuron(soma=Soma(root_section.points[:1]), neurites=[Neurite(root_section)])
def points(self): '''Return unordered array with all the points in this neurite''' # add all points in a section except the first one, which is a duplicate _pts = [v for s in self.root_node.ipreorder() for v in s.points[1:, COLS.XYZR]] # except for the very first point, w...
def transform(self, trans): '''Return a copy of this neurite with a 3D transformation applied''' clone = deepcopy(self) for n in clone.iter_sections(): n.points[:, 0:3] = trans(n.points[:, 0:3]) return clone
def iter_sections(self, order=Tree.ipreorder, neurite_order=NeuriteIter.FileOrder): '''iteration over section nodes Parameters: order: section iteration order within a given neurite. Must be one of: Tree.ipreorder: Depth-first pre-order iteration of tree nodes Tree.ipreorder...
def eval_stats(values, mode): '''Extract a summary statistic from an array of list of values Parameters: values: numpy array of values mode: summary stat to extract. One of ['min', 'max', 'median', 'mean', 'std', 'raw'] Note: fails silently if values is empty, and None is returned ''' ...
def _stat_name(feat_name, stat_mode): '''Set stat name based on feature name and stat mode''' if feat_name[-1] == 's': feat_name = feat_name[:-1] if feat_name == 'soma_radii': feat_name = 'soma_radius' if stat_mode == 'raw': return feat_name return '%s_%s' % (stat_mode, feat...
def extract_stats(neurons, config): '''Extract stats from neurons''' stats = defaultdict(dict) for ns, modes in config['neurite'].items(): for n in config['neurite_type']: n = _NEURITE_MAP[n] for mode in modes: stat_name = _stat_name(ns, mode) ...
def get_header(results): '''Extracts the headers, using the first value in the dict as the template''' ret = ['name', ] values = next(iter(results.values())) for k, v in values.items(): if isinstance(v, dict): for metric in v.keys(): ret.append('%s:%s' % (k, metric)) ...
def generate_flattened_dict(headers, results): '''extract from results the fields in the headers list''' for name, values in results.items(): row = [] for header in headers: if header == 'name': row.append(name) elif ':' in header: neurite_...
def add_child(self, tree): '''Add a child to the list of this tree's children This tree becomes the added tree's parent ''' tree.parent = self self.children.append(tree) return tree
def ipreorder(self): '''Depth-first pre-order iteration of tree nodes''' children = deque((self, )) while children: cur_node = children.pop() children.extend(reversed(cur_node.children)) yield cur_node
def ipostorder(self): '''Depth-first post-order iteration of tree nodes''' children = [self, ] seen = set() while children: cur_node = children[-1] if cur_node not in seen: seen.add(cur_node) children.extend(reversed(cur_node.childr...