Generates a figure of the neuron,
    that contains a soma and a list of trees.
555188
def _plot_neuron3d(neuron, inline, **kwargs):
    '''
    
    '''
    return _plotly(neuron, plane='3d', title='neuron-3D', inline=inline, **kwargs)
846547
public Neuron[] neurons() {
        HashMap<Integer, Neuron> hash = new HashMap<>();
        Neuron[] neurons = new Neuron[nodes.size()];
        
        int i = 0;
        for (Node node : nodes) {
            Neuron[] neighbors = new Neuron[node.edges.size()];
            neurons[i] = new Neuron(node.w, neighbors);
            hash.put(node.id, neurons[i]);
            i++;
        }

        i = 0;
        for (Node node : nodes) {
            int j = 0;
            for (Edge edge : node.edges) {
                if (edge.a != node)
                    neurons[i].neighbors[j++] = hash.get(edge.a.id);
                else
                    neurons[i].neighbors[j++] = hash.get(edge.b.id);
            }
            i++;
        }
        
        return neurons;
    }
757691
def n_sections(neurites, neurite_type=NeuriteType.all, iterator_type=Tree.ipreorder):
    ''''''
    return sum(1 for _ in iter_sections(neurites,
                                        iterator_type=iterator_type,
                                        neurite_filter=is_type(neurite_type)))
1136581
def make_fig(self):
        
        self.fig = plt.figure(figsize=(8, 4))
        self._all_figures.append(self.fig)
396881
def plot(self):
    
    plt.ion()
    plt.show()
    x = numpy.linspace(0, 15, 100)
    y = numpy.zeros(x.shape)
    y = self.excite(y, x)
    plt.plot(x, y)
    plt.xlabel('Input')
    plt.ylabel('Persistence')
    plt.title('Sigmoid Activation Function')
817834
def plot_grid_to_ax(self, ax, **kwargs):
        
        all_xz = []
        for x, z in zip(self.grid['x'], self.grid['z']):
            tmp = np.vstack((x, z)).T
            all_xz.append(tmp)
        collection = mpl.collections.PolyCollection(
            all_xz,
            edgecolor='k',
            facecolor='none',
            linewidth=0.4,
        )
        ax.add_collection(collection)
        if self.electrodes is not None:
            ax.scatter(
                self.electrodes[:, 1],
                self.electrodes[:, 2],
                color=self.props['electrode_color'],
                clip_on=False,
            )
        ax.set_xlim(self.grid['x'].min(), self.grid['x'].max())
        ax.set_ylim(self.grid['z'].min(), self.grid['z'].max())
        # ax.autoscale_view()
        ax.set_aspect('equal')

        if kwargs.get('plot_electrode_numbers', False):
            for nr, xy in enumerate(self.electrodes[:, 1:3]):
                ax.text(
                    xy[0], xy[1],
                    format(nr + 1),
                    bbox=dict(boxstyle='circle', facecolor='red', alpha=0.8)
                )
397888
def draw(self):
        
        matrix = nx.to_numpy_matrix(self.graph, nodelist=self.nodes)
        self.ax.matshow(matrix, cmap=self.cmap)
240296
def n_leaves(neurites, neurite_type=NeuriteType.all):
    ''''''
    return n_sections(neurites, neurite_type=neurite_type, iterator_type=Tree.ileaf)
142770
def generate(ast_tree: ast.Tree, model_name: str):
    
    component_ref = ast.ComponentRef.from_string(model_name)
    ast_tree_new = copy.deepcopy(ast_tree)
    ast_walker = TreeWalker()
    flat_tree = flatten(ast_tree_new, component_ref)
    sympy_gen = SympyGenerator()
    ast_walker.walk(sympy_gen, flat_tree)
    return sympy_gen.src[flat_tree]
402522
def draw_tree(ax, tx, rmargin=.3,
              treecolor="k", leafcolor="k", supportcolor="k",
              outgroup=None, reroot=True, gffdir=None, sizes=None,
              trunc_name=None, SH=None, scutoff=0, barcodefile=None,
              leafcolorfile=None, leaffont=12):
    

    t = Tree(tx)
    if reroot:
        if outgroup:
            R = t.get_common_ancestor(*outgroup)
        else:
            # Calculate the midpoint node
            R = t.get_midpoint_outgroup()

        if R != t:
            t.set_outgroup(R)

    farthest, max_dist = t.get_farthest_leaf()

    margin = .05
    xstart = margin
    ystart = 1 - margin
    canvas = 1 - rmargin - 2 * margin
    tip = .005
    # scale the tree
    scale = canvas / max_dist

    num_leaves = len(t.get_leaf_names())
    yinterval = canvas / (num_leaves + 1)

    # get exons structures, if any
    structures = {}
    if gffdir:
        gffiles = glob("{0}/*.gff*".format(gffdir))
        setups, ratio = get_setups(gffiles, canvas=rmargin / 2, noUTR=True)
        structures = dict((a, (b, c)) for a, b, c in setups)

    if sizes:
        sizes = Sizes(sizes).mapping

    if barcodefile:
        barcodemap = DictFile(barcodefile, delimiter="\t")

    if leafcolorfile:
        leafcolors = DictFile(leafcolorfile, delimiter="\t")

    coords = {}
    i = 0
    for n in t.traverse("postorder"):
        dist = n.get_distance(t)
        xx = xstart + scale * dist

        if n.is_leaf():
            yy = ystart - i * yinterval
            i += 1

            if trunc_name:
                name = truncate_name(n.name, rule=trunc_name)
            else:
                name = n.name

            if barcodefile:
                name = decode_name(name, barcodemap)

            sname = name.replace("_", "-")

            try:
                lc = leafcolors[n.name]
            except Exception:
                lc = leafcolor
            else:
                # if color is given as "R,G,B"
                if "," in lc:
                    lc = map(float, lc.split(","))

            ax.text(xx + tip, yy, sname, va="center",
                    fontstyle="italic", size=leaffont, color=lc)

            gname = n.name.split("_")[0]
            if gname in structures:
                mrnabed, cdsbeds = structures[gname]
                ExonGlyph(ax, 1 - rmargin / 2, yy, mrnabed, cdsbeds,
                          align="right", ratio=ratio)
            if sizes and gname in sizes:
                size = sizes[gname]
                size = size / 3 - 1  # base pair converted to amino acid
                size = "{0}aa".format(size)
                ax.text(1 - rmargin / 2 + tip, yy, size, size=leaffont)

        else:
            children = [coords[x] for x in n.get_children()]
            children_x, children_y = zip(*children)
            min_y, max_y = min(children_y), max(children_y)
            # plot the vertical bar
            ax.plot((xx, xx), (min_y, max_y), "-", color=treecolor)
            # plot the horizontal bar
            for cx, cy in children:
                ax.plot((xx, cx), (cy, cy), "-", color=treecolor)
            yy = sum(children_y) * 1. / len(children_y)
            support = n.support
            if support > 1:
                support = support / 100.
            if not n.is_root():
                if support > scutoff / 100.:
                    ax.text(xx, yy+.005, "{0:d}".format(int(abs(support * 100))),
                            ha="right", size=leaffont, color=supportcolor)

        coords[n] = (xx, yy)

    # scale bar
    br = .1
    x1 = xstart + .1
    x2 = x1 + br * scale
    yy = ystart - i * yinterval
    ax.plot([x1, x1], [yy - tip, yy + tip], "-", color=treecolor)
    ax.plot([x2, x2], [yy - tip, yy + tip], "-", color=treecolor)
    ax.plot([x1, x2], [yy, yy], "-", color=treecolor)
    ax.text((x1 + x2) / 2, yy - tip, "{0:g}".format(br),
            va="top", ha="center", size=leaffont, color=treecolor)

    if SH is not None:
        xs = x1
        ys = (margin + yy) / 2.
        ax.text(xs, ys, "SH test against ref tree: {0}"
                .format(SH), ha="left", size=leaffont, color="g")

    normalize_axes(ax)
145290
def do_tree(self, line):
        """"""
        opts = self.TREE_OPTS
        line = line.split()
        _pattern = ""

        if not self.current:
            self._help_noontology()
            return

        if len(line) == 0:
            # default contextual behaviour [2016-03-01]
            line = ["classes"]

        if line[0] not in opts:
            self.help_tree()
            return

        elif line[0] == "classes":
            g = self.current['graph']
            if g.all_classes:
                g.printClassTree(showids=False, labels=False, showtype=True)
                self._print("----------------", "TIP")
            else:
                self._print("No classes available.")

        elif line[0] == "properties":
            g = self.current['graph']
            if g.all_properties:
                g.printPropertyTree(showids=False, labels=False, showtype=True)
            else:
                self._print("No properties available.")

        elif line[0] == "concepts":
            g = self.current['graph']
            if g.all_skos_concepts:
                g.printSkosTree(showids=False, labels=False, showtype=True)
            else:
                self._print("No concepts available.")

        else:  # should never arrive here
            pass
544303
def vt2esofspy(vesseltree, outputfilename="tracer.txt", axisorder=[0, 1, 2]):
    

    if (type(vesseltree) == str) and os.path.isfile(vesseltree):
        import io3d
        vt = io3d.misc.obj_from_file(vesseltree)
    else:
        vt = vesseltree
    print(vt['general'])
    print(vt.keys())
    vtgm = vt['graph']['microstructure']
    lines = []
    vs = vt['general']['voxel_size_mm']
    sh = vt['general']['shape_px']

    # switch axis
    ax = axisorder

    lines.append("#Tracer+\n")
    lines.append("#voxelsize mm %f %f %f\n" % (vs[ax[0]], vs[ax[1]], vs[ax[2]]))
    lines.append("#shape %i %i %i\n" % (sh[ax[0]], sh[ax[1]], sh[ax[2]]))
    lines.append(str(len(vtgm) * 2)+"\n")

    i = 1
    for id in vtgm:
        # edge['']
        try:
            nda = vtgm[id]['nodeA_ZYX']
            ndb = vtgm[id]['nodeB_ZYX']
            lines.append("%i\t%i\t%i\t%i\n" % (nda[ax[0]], nda[ax[1]], nda[ax[2]], i))
            lines.append("%i\t%i\t%i\t%i\n" % (ndb[ax[0]], ndb[ax[1]], ndb[ax[2]], i))
            i += 1
        except:
            pass


    lines.append("%i\t%i\t%i\t%i" % (0, 0, 0, 0))
    lines[3] = str(i - 1) + "\n"
    with open(outputfilename, 'wt') as f:
        f.writelines(lines)
504630
def plot_memory(calc_id=-1):
    
    dstore = util.read(calc_id)
    plots = []
    for task_name in dstore['task_info']:
        mem = dstore['task_info/' + task_name]['mem_gb']
        plots.append((task_name, mem))
    plt = make_figure(plots)
    plt.show()
467196
def local_bifurcation_angles(neurites, neurite_type=NeuriteType.all):
    ''''''
    return map_sections(_bifurcationfunc.local_bifurcation_angle,
                        neurites,
                        neurite_type=neurite_type,
                        iterator_type=Tree.ibifurcation_point)
1048508
def info(cls, obj, ansi=True, backend='matplotlib', visualization=True,
             recursive=False, pattern=None, elements=[]):
        
        parameterized_object = isinstance(obj, param.Parameterized)
        parameterized_class = (isinstance(obj,type)
                               and  issubclass(obj,param.Parameterized))
        info = None
        if parameterized_object or parameterized_class:
            info = InfoPrinter.info(obj, ansi=ansi, backend=backend,
                                    visualization=visualization,
                                    pattern=pattern, elements=elements)

        if parameterized_object and recursive:
            hierarchy = obj.traverse(lambda x: type(x))
            listed = []
            for c in hierarchy[1:]:
                if c not in listed:
                    inner_info = InfoPrinter.info(c, ansi=ansi, backend=backend,
                                                  visualization=visualization,
                                                  pattern=pattern)
                    black = '\x1b[1;30m%s\x1b[0m' if ansi else '%s'
                    info +=  '\n\n' + (black % inner_info)
                    listed.append(c)
        return info
702721
def partition_asymmetries(neurites, neurite_type=NeuriteType.all):
    ''''''
    return map(_bifurcationfunc.partition_asymmetry,
               iter_sections(neurites,
                             iterator_type=Tree.ibifurcation_point,
                             neurite_filter=is_type(neurite_type)))
970708
def _section_end_points(structure_block, id_map):
    ''''''
    soma_idx = structure_block[:, TYPE] == POINT_TYPE.SOMA
    soma_ids = structure_block[soma_idx, ID]
    neurite_idx = structure_block[:, TYPE] != POINT_TYPE.SOMA
    neurite_rows = structure_block[neurite_idx, :]
    soma_end_pts = set(id_map[id_]
                       for id_ in soma_ids[np.in1d(soma_ids, neurite_rows[:, PID])])

    # end points have either no children or more than one
    # ie: leaf or multifurcation nodes
    n_children = defaultdict(int)
    for row in structure_block:
        n_children[row[PID]] += 1
    end_pts = set(i for i, row in enumerate(structure_block)
                  if n_children[row[ID]] != 1)

    return end_pts.union(soma_end_pts)