Beispiel #1
0
def fracLac_2d(fn='tmpTree_2d.swc'):
    tree = btmorph.STree2().read_SWC_tree_from_file(fn)
    stats = btmorph.BTStats(tree)
    voxvol = max(stats.total_dimension()) / 512.0
    rng = map(lambda i: voxvol * i, range(1, 8))
    print fn
    for i in rng:
        print('VoxelSize:', i)
        print stats.fractal_dimension_lacunarity(i)
Beispiel #2
0
def standard_lacunarity():
    """
    Test if lacunarity method is working properly
    """
    tree = btmorph.STree2().read_SWC_tree_from_file(
        "tests/moto_1_outputted.swc")
    stats = btmorph.BTStats(tree)
    for vD in range(5, 40, 5):
        lac, fd = stats.fractal_dimension_lacunarity(vD)
        print("Voxel size:", vD, "tree Lac=", lac, "tree fd=", fd)
Beispiel #3
0
def test_load_swc_mcs2():
    '''
    Test whether SWC files with multiple-cylinder soma format are read correctly (ri05)
    '''
    print "\n"
    swc_tree = btmorph.STree2()
    swc_tree.read_SWC_tree_from_file('tests/soma_types/ri05.CNG.swc')
    all_nodes1 = swc_tree.get_nodes()
    print '\nlen(swc_tree1)', len(all_nodes1)
    assert (len(all_nodes1) == 8970)
    assert (503 < btmorph.BTStats(swc_tree).approx_soma() < 504)
Beispiel #4
0
def setup_func_small_tree_lac():
    """
    Setup function for tree initialization and loading
    """
    global test_trees
    global test_stats
    #0 - Only soma tree
    #test_trees.append(btmorph.STree2().read_SWC_tree_from_file("tests/soma_only.swc"))
    #1 - Wiki test tree moto_1_outputted
    #test_trees.append(btmorph.STree2().read_SWC_tree_from_file("tests/horton-strahler_test_wiki_3pointsoma.swc"))
    test_trees.append(
        btmorph.STree2().read_SWC_tree_from_file("tests/moto_1_outputted.swc"))
    test_stats = [btmorph.BTStats(test_trees[0])]
Beispiel #5
0
def setup_func_small_tree():
    """
    Setup function for Horton-Strahler number testing
    """
    global test_trees
    global test_stats
    #0 - Only soma tree
    test_trees.append(
        btmorph.STree2().read_SWC_tree_from_file("tests/soma_only.swc"))
    #1 - Wiki test tree
    test_trees.append(btmorph.STree2().read_SWC_tree_from_file(
        "tests/horton-strahler_test_wiki_3pointsoma.swc"))
    test_stats = btmorph.BTStats(test_trees[1])
def loaddata(path):
    swc_tree = btmorph.STree2()
    swc_tree.read_SWC_tree_from_file(path)
    stats = btmorph.BTStats(swc_tree)
    return swc_tree, stats
Beispiel #7
0
def test_0_load_stats():
    """
    Check whether the statitics package can be loaded
    """
    global stats
    stats = btmorph.BTStats(swc_tree)
    counter = 0
    for i in range(from_level, to_level):  # runs until the final level
        slice_begin = i
        slice_end = i + slice_size
        new_file_name = str(slice_begin)

        print(str(slice_begin) + '-' + str(slice_end))
        for fileName in os.listdir(directory):  #for each file in the directory
            if fileName.endswith(".swc"):
                counter += 1
                swc_tree = btmorph.STree2()
                filePath = str(directory) + '/' + str(fileName)
                types = [1, 3, 4, 5, 6,
                         7]  # the 2 is omited because we are not using axons
                swc_tree.read_SWC_tree_from_file(filePath, types)
                stats = btmorph.BTStats(swc_tree)
                stats.set_level_to_tree()
                # print ("tree level"+ str(swc_tree.max_height))
                tree_height = swc_tree.max_height
                print str(fileName) + "  " + str(tree_height)
                if tree_height < 0:
                    print(" -> processing " + str(fileName))
                    print("OUT OF RANGE")
                else:
                    try:
                        swc_tree = stats.write_subtree_by_slice_range(
                            slice_begin, slice_end, new_directory, fileName,
                            class_number)
                    except ValueError:
                        print("ERROR  " + str(fileName))
Beispiel #9
0
def perform_1D_population_analysis(destination,
                                   filter="*.swc",
                                   depth="Y",
                                   bar=[200, 200, 200],
                                   post_name=None,
                                   max_n=None):
    """
    Wrapper function to perform a complete analysis of a population of neuronal morphologies stored in SWC format (and three-point soma).

    Computes the following features:

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

    For each feature a list is created with all values collected from all morphologies.
    
    These vectors are saved as python Pickle objects.

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

    Parameters
    -----------
    destination : string
        string with the location of where to find the SWC files.
    filter :  string
        filter to select SWC files. Default is "*.swc". See `glob
        <https://docs.python.org/2/library/glob.html>`_ documentation for more advanced filters
    depth : string
        Dimension that indicates "depth"/distance from top. Default is "Y"; NeuroMac generated files use "Z".
    bar : array of float
        Include a scale-bar with the specified dimensions
    max_n : int
        To perform the analysis on a subset of morphologies specify a \
        number. Default is None and all morphologies will be taken \
        into account.
    post_name : string
        string appended to the file name when saving. Default None
    """
    # change to a directory of choice for I/O
    pwd = os.getcwd()
    os.chdir(destination)

    # load morphologies and initialize statistics
    all_f = glob.glob(filter)
    if not max_n == None:
        all_f = all_f[:max_n]
    swc_trees = {}
    individual_stats = {}
    for f in all_f:
        print "f: ", f
        cell_name = f.split(filter)[0]
        temp_tree = btmorph.STree2()
        temp_tree.read_SWC_tree_from_file(f)
        swc_trees[cell_name] = temp_tree
        temp_stats = btmorph.BTStats(temp_tree)
        individual_stats[cell_name] = temp_stats
        plt.clf()
        btmorph.plot_2D_SWC(f,
                            outN=cell_name + "_2D.pdf",
                            align=True,
                            depth=depth,
                            show_axis=True)
        #btmorph.true_2D_projections_equal(f,outN=f.split(".swc")[0]+"_projections.pdf",depth=depth,bar=bar)
        plt.close()
    """ 1D features, without dependencies on other quantities
        Both global (1 per neuron) and local (N per neuron) features"""

    one_d_stats = {}

    # bulk statistics of global features
    funcs = ["total_length","no_bifurcations","no_terminals","no_stems",\
             "total_volume","total_surface"]
    for cell_name in individual_stats:
        for func in funcs:
            method = getattr(individual_stats[cell_name], func)
            ret = method()
            if isinstance(ret, tuple):
                ret = ret[0]
            if func in one_d_stats:
                one_d_stats[func].append(ret)
            else:
                one_d_stats[func] = []
                one_d_stats[func].append(ret)

    # extract the max order
    for cell_name in individual_stats:
        max_order = 0
        for node in swc_trees[cell_name].get_nodes():
            order = individual_stats[cell_name].order_of_node(node)
            if order > max_order:
                max_order = order
        if "max_order" in one_d_stats:
            one_d_stats["max_order"].append(max_order)
        else:
            one_d_stats["max_order"] = []
            one_d_stats["max_order"].append(max_order)

    # extract the "inter-bifurcation segment length"
    for cell_name in individual_stats:
        bif_nodes = individual_stats[cell_name]._bif_points
        for node in bif_nodes:
            L = individual_stats[cell_name].get_segment_pathlength(node)
            if "inter_bif_L" in one_d_stats:
                one_d_stats["inter_bif_L"].append(L)
            else:
                one_d_stats["inter_bif_L"] = []
                one_d_stats["inter_bif_L"].append(L)

    # extract the terminal segment lengths
    # extract the path length / euclidean distance to terminal tips
    for cell_name in individual_stats:
        term_nodes = individual_stats[cell_name]._end_points
        for node in term_nodes:
            L = individual_stats[cell_name].get_segment_pathlength(node)
            path_L = individual_stats[cell_name].get_pathlength_to_root(node)
            eucl_L = individual_stats[cell_name].get_Euclidean_length_to_root(
                node)
            if "term_L" in one_d_stats:
                one_d_stats["term_L"].append(L)
            else:
                one_d_stats["term_L"] = []
                one_d_stats["term_L"].append(L)

            if "term_path_L" in one_d_stats:
                one_d_stats["term_path_L"].append(path_L)
            else:
                one_d_stats["term_path_L"] = []
                one_d_stats["term_path_L"].append(path_L)

            if "term_eucl_L" in one_d_stats:
                one_d_stats["term_eucl_L"].append(eucl_L)
            else:
                one_d_stats["term_eucl_L"] = []
                one_d_stats["term_eucl_L"].append(eucl_L)

    for func in one_d_stats:
        plt.figure(0)
        plt.clf()
        plt.hist(one_d_stats[func])
        plt.xlabel(func)
        plt.ylabel("#")
        if post_name == None:
            plt.savefig("pop_1D_" + func + "_hist.pdf")
            p_name = "pop_1D_" + func + "_raw.pkl"
        else:
            plt.savefig("pop_1D_" + func + "_hist" + post_name + ".pdf")
            p_name = "pop_1D_" + func + "_raw" + post_name + ".pkl"
        pickle.dump(one_d_stats[func], open(p_name, "w"))

    # and change back to the original directory where the command was given
    os.chdir(pwd)
def perform_2D_analysis(destination, filter="*.swc", max_n=None):
    """
    Wrapper function to perform an analysis of the vector features of one neuronal morphology (in the SWC format and with 3-point soma)

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

    - Order of the node
    - degree of the node
    - Euclidean distance to the soma
    - path length to the soma
    - pathlength of the segment (coming in to a node)
    - Euclidean distance of the segment (coming in the a node)
    - branch angle amplitude [branch points only]
    
    Two text files are generated, for terminal and branching points. Each row corresponds to a node (point) and the six
    columns correspond to the features above.

    Parameters
    -----------
    destination : string
        string with the location of where to find the SWC files.
    """

    # change to a directory of choice for I/O
    os.chdir(destination)

    # load morphologies and initialize statistics
    all_f = glob.glob(filter)
    if not max_n == None:
        all_f = all_f[:max_n]
    swc_trees = {}
    individual_stats = {}
    for f in all_f:
        print(("f: ", f))
        cell_name = f.split(filter)[0]
        temp_tree = btmorph.STree2()
        temp_tree.read_SWC_tree_from_file(f)
        swc_trees[cell_name] = temp_tree
        temp_stats = btmorph.BTStats(temp_tree)
        individual_stats[cell_name] = temp_stats
    """ 2D features calculated per neuron and for the whole population.
        For each bifurcation and terminal point, the following features \
        at that location will be recorded: order, degree, asymmetry_index, \
        path length, euclidean distance,(bifurcation angle, local)"""

    for cell_name in individual_stats:
        print(("analyzing cell %s" % cell_name))
        bif_nodes = individual_stats[cell_name]._bif_points
        term_nodes = individual_stats[cell_name]._end_points

        term_to_write = ""
        for node in term_nodes:
            O,D,ED,PL,SPL,SED= \
              _get_node_features(individual_stats[cell_name],node,term=True)
            term_to_write += "%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\n" % (
                O, D, ED, PL, SPL, SED)

        term_writer = open(cell_name + "_terms_multivariate.txt", "w")
        term_writer.write(term_to_write)
        term_writer.flush()
        term_writer.close()

        bif_to_write = ""
        for node in bif_nodes:
            O,D,ED,PL,SPL,SED,PA,AMP= \
              _get_node_features(individual_stats[cell_name],node)
            bif_to_write += "%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\n" % (
                O, D, ED, PL, SPL, SED, PA, AMP)
        bif_writer = open(cell_name + "_bifs_multivariate.txt", "w")
        bif_writer.write(bif_to_write)
        bif_writer.flush()
        bif_writer.close()