コード例 #1
0
ファイル: pareto_steiner.py プロジェクト: arjunc12/Plants
def pareto_analysis(G, plant, fronts_dir=FRONTS_DIR, output_dir=OUTPUT_DIR,\
                    figs_dir=FIGS_DIR, output=True, viz_trees=VIZ_TREES):

    assert G.number_of_nodes() > 0
    assert is_tree(G)

    print plant

    input_points = G.graph['input points']
    point_graph = G.subgraph(input_points)
    print point_graph.number_of_nodes(), 'points'

    # ---------------------------------------
    tree_costs_fname = '%s/tree_costs.csv' % fronts_dir

    models_fname = '%s/models_%s.csv' % (output_dir, plant)
    output_fname = '%s/pareto_steiner_%s.csv' % (output_dir, plant)
    tradeoff_fname = '%s/tradeoff_%s.csv' % (output_dir, plant)

    # ---------------------------------------
    alphas, mcosts, scosts, first_time = pareto_front(G, point_graph,\
                                                      fronts_dir, figs_dir,\
                                                      viz_trees)

    opt_mcost, opt_scost = min(mcosts), min(scosts)
    # ---------------------------------------
    plant_mcost, plant_scost = graph_costs(G,
                                           relevant_nodes=point_graph.nodes())

    plant_dist, plant_index = DIST_FUNC(mcosts, scosts, plant_mcost,\
                                        plant_scost)
    plant_closem = mcosts[plant_index]
    plant_closes = scosts[plant_index]
    plant_alpha = alphas[plant_index]

    # ---------------------------------------
    tradeoff = tradeoff_ratio(plant_mcost, opt_mcost, plant_scost, opt_scost)

    # ---------------------------------------
    centroid_tree = centroid_mst(point_graph)

    centroid_mcost, centroid_scost = graph_costs(
        centroid_tree, relevant_nodes=point_graph.nodes())

    centroid_dist, centroid_index = DIST_FUNC(mcosts, scosts,\
                                              centroid_mcost,\
                                              centroid_scost)
    centroid_closem = mcosts[centroid_index]
    centroid_closes = scosts[centroid_index]
    centroid_alpha = alphas[centroid_index]

    # ---------------------------------------
    centroid_success = int(centroid_dist <= plant_dist)
    centroid_ratio = centroid_dist / plant_dist
    if first_time:
        with open(models_fname, 'a') as models_file:
            models_file.write('%s, %s, %f\n' % (plant, 'plant', plant_dist))
            models_file.write('%s, %s, %f, %d, %f\n' % (plant,\
                                                            'centroid',\
                                                            centroid_dist,\
                                                            centroid_success,\
                                                            centroid_ratio))

# ---------------------------------------
    if first_time:
        with open(tree_costs_fname, 'w') as tree_costs_file:
            tree_costs_file.write('tree, mcost, scost\n')
            tree_costs_file.write('%s, %f, %f\n' % ('plant', plant_mcost,\
                                                    plant_scost))
            tree_costs_file.write('%s, %f, %f\n' % ('centroid', centroid_mcost,\
                                                    centroid_scost))
# ---------------------------------------
#point_graph = complete_graph(point_graph)
    random_trials = 20

    for i in xrange(random_trials):
        rand_mst = random_mst(point_graph, euclidean=True)
        rand_mcost, rand_scost = graph_costs(rand_mst)
        rand_dist, rand_index = DIST_FUNC(mcosts, scosts, rand_mcost,\
                                          rand_scost)
        rand_success = int(rand_dist <= plant_dist)
        rand_ratio = rand_dist / plant_dist

        barabasi_mst = barabasi_tree(point_graph)
        barabasi_mcost, barabasi_scost = graph_costs(barabasi_mst)
        barabasi_dist, barabasi_index = DIST_FUNC(mcosts, scosts,\
                                                  barabasi_mcost,\
                                                  barabasi_scost)
        barabasi_success = int(barabasi_dist <= plant_dist)
        barabasi_ratio = barabasi_dist / plant_dist

        with open(tree_costs_fname, 'a') as tree_costs_file:
            tree_costs_file.write('%s, %f, %f\n' % ('random', rand_mcost,\
                                                     rand_scost))
            tree_costs_file.write('%s, %f, %f\n' % ('barabasi',\
                                                     barabasi_mcost,\
                                                     barabasi_scost))

        with open(models_fname, 'a') as models_file:
            models_file.write('%s, %s, %f, %d, %f\n' % (plant, 'random',\
                                                        rand_dist,\
                                                        rand_success,\
                                                        rand_ratio))

            models_file.write('%s, %s, %f, %d, %f\n' % (plant, 'barabasi',\
                                                        barabasi_dist,\
                                                        barabasi_success,\
                                                        barabasi_ratio))


# ---------------------------------------

    def remove_spaces(string):
        return string.replace(' ', '')

    def remove_commas(string):
        return string.replace(',', '')

    if output and first_time:
        write_items = [plant, point_graph.number_of_nodes()]

        write_items.append(plant_alpha)

        write_items = map(str, write_items)
        write_items = map(remove_commas, write_items)
        write_items = ', '.join(write_items)
        with open(output_fname, 'a') as output_file:
            output_file.write('%s\n' % write_items)

        with open(tradeoff_fname, 'a') as tradeoff_file:
            tradeoff_file.write('%s, %f\n' % (plant, tradeoff))
コード例 #2
0
def pareto_plot(G, name, cell_type, species, region, lab, outdir='figs',\
                output=True, viz_trees=VIZ_TREES, axon=False, compare=True):
    if not (nx.is_connected(G)
            and G.number_of_edges() == G.number_of_nodes() - 1):
        print "not a tree"
        return None

    assert G.number_of_nodes() > 0

    print "making graph"
    point_graph = None
    if NO_CONTINUE:
        point_graph = non_continue_subgraph(G)
    else:
        point_graph = complete_graph(G)
    print point_graph.number_of_nodes(), "points"

    sat_tree = satellite_tree(point_graph)
    span_tree = nx.minimum_spanning_tree(point_graph, weight='length')

    opt_scost = float(satellite_cost(sat_tree))
    normalize_scost = lambda cost: normalize_cost(cost, opt_scost)
    opt_mcost = float(mst_cost(span_tree))
    normalize_mcost = lambda cost: normalize_cost(cost, opt_mcost)

    mcosts1 = []
    scosts1 = []

    mcosts2 = []
    scosts2 = []

    mcosts3 = []
    scosts3 = []

    delta = 0.01
    alphas = np.arange(0, 1 + delta, delta)
    print "sorting neighbors"
    sort_neighbors(point_graph)

    comparisons = 0
    dominates = 0
    for i, alpha in enumerate(alphas):
        print "alpha", alpha
        pareto_tree1 = None
        pareto_tree2 = None
        if alpha == 0:
            pareto_tree1 = pareto_tree2 = sat_tree
            pareto_tree3 = sat_tree
        elif alpha == 1:
            pareto_tree1 = pareto_tree2 = span_tree
            pareto_tree3 = span_tree
        else:
            #print "Greedy"
            pareto_tree1 = pareto_prim(point_graph, alpha, axon=axon)
            #pareto_tree1 = pareto_prim_sandbox(point_graph, alpha, axon=axon)
            #print "khuller"
            if compare:
                beta = alpha_to_beta(alpha, opt_mcost, opt_scost)
                pareto_tree2 = khuller(point_graph, span_tree, sat_tree, beta)
            #print "genetic"
            #pareto_tree3 = pareto_genetic(point_graph, alpha)

        assert is_tree(pareto_tree1)
        if compare:
            assert is_tree(pareto_tree2)
        #assert is_tree(pareto_tree3)

        if (alpha != 0 and alpha != 1 and i % 5 == 0) and viz_trees:
            viz_tree(pareto_tree1, name + '-' + str(alpha), outdir=outdir)

        mcost1, scost1 = graph_costs(pareto_tree1)
        mcost1 = normalize_mcost(mcost1)
        scost1 = normalize_scost(scost1)

        if compare:
            mcost2, scost2 = graph_costs(pareto_tree2)
            mcost2 = normalize_mcost(mcost2)
            scost2 = normalize_scost(scost2)

        #mcost3, scost3 = graph_costs(pareto_tree3)
        #mcost3 = normalize_mcost(mcost3)
        #scost3 = normalize_scost(scost3)

        mcosts1.append(mcost1)
        scosts1.append(scost1)

        if compare:
            mcosts2.append(mcost2)
            scosts2.append(scost2)

        #mcosts3.append(mcost3)
        #scosts3.append(scost3)

        if alpha not in [0, 1] and compare:
            comparisons += 1
            if pareto_cost(mcost1, scost1, alpha) <= pareto_cost(
                    mcost2, scost2, alpha):
                dominates += 1

    pylab.figure()
    pylab.plot(mcosts1, scosts1, c='b')
    pylab.scatter(mcosts1, scosts1, c='b', label='greedy mst')

    if compare:
        pylab.plot(mcosts2, scosts2, c='k')
        pylab.scatter(mcosts2, scosts2, c='k', label='khuller mst')

    #pylab.plot(mcosts3, scosts3, c = 'y')
    #pylab.scatter(mcosts3, scosts3, c='y', label='genetic')

    pylab.xlabel('spanning tree cost')
    pylab.ylabel('satellite cost')

    neural_mcost = normalize_mcost(mst_cost(G))
    neural_scost = normalize_scost(satellite_cost(G))

    neural_dist, neural_index = pareto_dist(mcosts1, scosts1, neural_mcost,
                                            neural_scost)
    neural_closem = mcosts1[neural_index]
    neural_closes = scosts1[neural_index]
    neural_alpha = alphas[neural_index]

    pylab.scatter([neural_mcost], [neural_scost],
                  c='r',
                  marker='x',
                  linewidths=15,
                  label='neural mst')
    #pylab.plot([neural_mcost, neural_closem], [neural_scost, neural_closes], c='r', linestyle='--')

    centroid_tree = centroid_mst(point_graph)

    centroid_mcost = normalize_mcost(mst_cost(centroid_tree))
    centroid_scost = normalize_scost(satellite_cost(centroid_tree))

    centroid_dist, centroid_index = pareto_dist(mcosts1, scosts1,
                                                centroid_mcost, centroid_scost)
    centroid_closem = mcosts1[centroid_index]
    centroid_closes = scosts1[centroid_index]
    centroid_alpha = alphas[centroid_index]

    pylab.scatter([centroid_mcost], [centroid_scost],
                  c='g',
                  marker='+',
                  linewidths=15,
                  label='centroid mst')
    #pylab.plot([centroid_mcost, centroid_closem], [centroid_scost, centroid_closes], c='g', linestyle='--')

    #pylab.axhline(opt_scost)
    #pylab.axvline(opt_mcost)

    #pylab.legend()

    ntrials = 20
    successes = 0
    total_rand_dist = 0.0
    rand_mcosts = []
    rand_scosts = []
    for i in xrange(ntrials):
        rand_mst = random_mst(point_graph)

        rand_mcost = normalize_mcost(mst_cost(rand_mst))
        rand_scost = normalize_scost(satellite_cost(rand_mst))
        rand_mcosts.append(rand_mcost)
        rand_scosts.append(rand_scost)

        rand_dist, rand_index = pareto_dist(mcosts1, scosts1, rand_mcost,
                                            rand_scost)
        total_rand_dist += rand_dist
        rand_closem = mcosts1[rand_index]
        rand_closes = scosts1[rand_index]
        rand_alpha = alphas[rand_index]
        if rand_dist < neural_dist:
            successes += 1

    pylab.scatter(rand_mcosts,
                  rand_scosts,
                  c='m',
                  marker='o',
                  label='random mst')

    pylab.savefig('%s/pareto_front_%s.pdf' % (outdir, name), format='pdf')
    pylab.close()

    viz_tree(G, name + str('_neural'), outdir=outdir)
    viz_tree(sat_tree, name + str('_sat'), outdir=outdir)
    viz_tree(span_tree, name + str('_mst'), outdir=outdir)
    viz_tree(centroid_tree, name + '_centroid', outdir=outdir)

    mean_rand_dist = total_rand_dist / ntrials

    f = open('pareto_mst.csv', 'a')
    if output:
        write_items = [
            name, cell_type, species, region, lab,
            point_graph.number_of_nodes()
        ]
        write_items = map(str, write_items)
        write_items.append(neural_alpha)
        write_items += [neural_dist, centroid_dist, mean_rand_dist]
        write_items += [ntrials, successes]
        write_items += [comparisons, dominates]
        write_items = map(str, write_items)
        write_items = ', '.join(write_items)
        f.write('%s\n' % write_items)
コード例 #3
0
ファイル: pareto_steiner.py プロジェクト: arjunc12/neurons
def pareto_analysis_neuron_builder(algorithm, tree_name):
    tree_dir = '/iblsn/data/Arjun/neurons/neuron_builder/%s/trees/%s' % (
        algorithm, tree_name)
    G = read_tree(tree_dir)
    fronts_dir = tree_dir
    output_dir = '/iblsn/data/Arjun/neurons/neuron_builder/%s/temp' % algorithm
    figs_dir = tree_dir
    output = True
    viz_trees = False

    assert G.number_of_nodes() > 0
    assert is_tree(G)

    #print "making graph"
    synapses = G.graph['synapses']
    points = synapses + [G.graph['root']]
    point_graph = G.subgraph(points)
    print point_graph.number_of_nodes(), 'points'

    # ---------------------------------------
    tree_costs_fname = '%s/tree_costs.csv' % fronts_dir

    models_fname = '%s/models_%s.csv' % (output_dir, tree_name)

    output_fname = '%s/pareto_steiner_%s.csv' % (output_dir, tree_name)

    params_fname = '%s/parameters_%s.csv' % (output_dir, tree_name)

    # ---------------------------------------
    alphas, mcosts, scosts, first_time = pareto_front(G, point_graph,\
                                                      neuron_name=None, neuron_type=None,\
                                                      fronts_dir=fronts_dir, figs_dir=fronts_dir,\
                                                      viz_trees=viz_trees)
    # ---------------------------------------

    neural_mcost = mst_cost(G)
    neural_scost = satellite_cost(G, relevant_nodes=point_graph.nodes())

    neural_dist, neural_index = DIST_FUNC(mcosts, scosts, neural_mcost,\
                                          neural_scost)
    neural_closem = mcosts[neural_index]
    neural_closes = scosts[neural_index]
    neural_alpha = alphas[neural_index]

    # ---------------------------------------
    centroid_tree = centroid_mst(point_graph)

    centroid_mcost = mst_cost(centroid_tree)
    centroid_scost = satellite_cost(centroid_tree,
                                    relevant_nodes=point_graph.nodes())

    centroid_dist, centroid_index = DIST_FUNC(mcosts, scosts,\
                                              centroid_mcost,\
                                              centroid_scost)
    centroid_closem = mcosts[centroid_index]
    centroid_closes = scosts[centroid_index]
    centroid_alpha = alphas[centroid_index]

    # ---------------------------------------
    centroid_success = int(centroid_dist <= neural_dist)
    centroid_ratio = centroid_dist / neural_dist
    if first_time:
        with open(models_fname, 'a') as models_file:
            models_file.write('%s, %s, %f\n' % (tree_name,\
                                                    'neural',\
                                                    neural_dist))
            models_file.write('%s, %s, %f, %d, %f\n' % (tree_name,\
                                                            'centroid',\
                                                            centroid_dist,\
                                                            centroid_success,\
                                                            centroid_ratio))

# ---------------------------------------
    if first_time:
        with open(tree_costs_fname, 'w') as tree_costs_file:
            tree_costs_file.write('tree, mcost, scost\n')
            tree_costs_file.write('%s, %f, %f\n' % ('neural',neural_mcost,\
                                                    neural_scost))
            tree_costs_file.write('%s, %f, %f\n' % ('centroid', centroid_mcost,\
                                                    centroid_scost))
# ---------------------------------------
    point_graph = complete_graph(point_graph)
    random_trials = 20

    for i in xrange(random_trials):
        rand_mst = random_mst(point_graph)
        rand_mcost, rand_scost = graph_costs(rand_mst)
        rand_dist, rand_index = DIST_FUNC(mcosts, scosts, rand_mcost,\
                                          rand_scost)
        rand_success = int(rand_dist <= neural_dist)
        rand_ratio = rand_dist / neural_dist

        barabasi_mst = barabasi_tree(point_graph)
        barabasi_mcost, barabasi_scost = graph_costs(barabasi_mst)
        barabasi_dist, barabasi_index = DIST_FUNC(mcosts, scosts,\
                                                  barabasi_mcost,\
                                                  barabasi_scost)
        barabasi_success = int(barabasi_dist <= neural_dist)
        barabasi_ratio = barabasi_dist / neural_dist

        with open(tree_costs_fname, 'a') as tree_costs_file:
            tree_costs_file.write('%s, %f, %f\n' % ('random', rand_mcost,\
                                                     rand_scost))
            tree_costs_file.write('%s, %f, %f\n' % ('barabasi',\
                                                     barabasi_mcost,\
                                                     barabasi_scost))

        with open(models_fname, 'a') as models_file:
            models_file.write('%s, %s, %f, %d, %f\n' % (tree_name,\
                                                            'random',\
                                                            rand_dist,\
                                                            rand_success,\
                                                            rand_ratio))

            models_file.write('%s, %s, %f, %d, %f\n' % (tree_name,\
                                                            'barabasi',\
                                                            barabasi_dist,\
                                                            barabasi_success,\
                                                            barabasi_ratio))


# ---------------------------------------

    def remove_spaces(string):
        return string.replace(' ', '')

    def remove_commas(string):
        return string.replace(',', '')

    if output and first_time:
        write_items = [tree_name, point_graph.number_of_nodes()]

        write_items.append(neural_alpha)

        write_items = map(str, write_items)
        write_items = map(remove_commas, write_items)
        #write_items = map(remove_spaces, write_items)
        write_items = ', '.join(write_items)
        with open(output_fname, 'a') as output_file:
            output_file.write('%s\n' % write_items)

        write_items = [tree_name]

        with open('%s/parameters.txt' % tree_dir) as params_file:
            for line in params_file:
                line = line.split()
                item = line[1]
                item = item.strip('\n')
                write_items.append(item)

        write_items = map(str, write_items)
        write_items = ', '.join(write_items)

        with open(params_fname, 'a') as params_file:
            params_file.write('%s\n' % write_items)
コード例 #4
0
ファイル: pareto_steiner.py プロジェクト: arjunc12/neurons
def pareto_analysis_imaris(G, neuron_name, neuron_type,\
                           fronts_dir=IMARIS_FRONTS_DIR,\
                           figs_dir=IMARIS_FIGS_DIR,\
                           viz_trees=VIZ_TREES_IMARIS):
    import seaborn as sns
    assert G.number_of_nodes() > 0
    assert is_tree(G)

    print neuron_name
    print "making graph"
    synapses = G.graph['synapses']
    points = synapses + [G.graph['root']]
    point_graph = G.subgraph(points)
    if IMARIS_RAND:
        point_graph = complete_graph(point_graph)
    print point_graph.number_of_nodes(), "points"

    alphas, mcosts, scosts, first_time = pareto_front(G, point_graph,\
                                                      neuron_name,\
                                                      neuron_type,\
                                                      fronts_dir, figs_dir,\
                                                      viz_trees)

    # ---------------------------------------

    neural_mcost = mst_cost(G)
    neural_scost = satellite_cost(G, relevant_nodes=point_graph.nodes())

    centroid_tree = centroid_mst(point_graph)
    centroid_mcost = mst_cost(centroid_tree)
    centroid_scost = satellite_cost(centroid_tree,
                                    relevant_nodes=point_graph.nodes())

    tree_costs_fname = '%s/tree_costs.csv' % fronts_dir
    if first_time:
        with open(tree_costs_fname, 'w') as tree_costs_file:
            tree_costs_file.write('tree, mcost, scost\n')
            tree_costs_file.write('%s, %f, %f\n' % ('neural',neural_mcost,\
                                                    neural_scost))
            tree_costs_file.write('%s, %f, %f\n' % ('centroid', centroid_mcost,\
                                                    centroid_scost))

# ---------------------------------------
    if IMARIS_RAND:
        random_trials = 20

        for i in xrange(random_trials):
            rand_mst = random_mst(point_graph, euclidean=True)
            rand_mcost, rand_scost = graph_costs(rand_mst)

            barabasi_mst = barabasi_tree(point_graph)
            barabasi_mcost, barabasi_scost = graph_costs(barabasi_mst)

            with open(tree_costs_fname, 'a') as tree_costs_file:
                tree_costs_file.write('%s, %f, %f\n' % ('random', rand_mcost,\
                                                         rand_scost))
                tree_costs_file.write('%s, %f, %f\n' % ('barabasi',\
                                                         barabasi_mcost,\
                                                         barabasi_scost))


# ---------------------------------------
    pareto_plot(fronts_dir, figs_dir)
    pareto_plot(fronts_dir, figs_dir, log_plot=True)

    pylab.figure()
    sns.set()

    pylab.plot(mcosts, scosts, c='b', label='_nolegend_')
    pylab.scatter(mcosts, scosts, c='b', label='Pareto front')


    tree_costs = zip(['neural', 'centroid'],\
                     [neural_mcost, centroid_mcost],\
                     [neural_scost, centroid_scost])

    for tree, mcost, scost in tree_costs:
        dist, index = DIST_FUNC(mcosts, scosts, mcost, scost)

        x = dist * pylab.array(mcosts)
        y = dist * pylab.array(scosts)

        label = LABELS[tree]
        marker = MARKERS[tree]
        color = COLORS[tree]

        pylab.scatter([mcost], [scost], label=label, marker=marker, s=175,\
                                                     c=color)
        pylab.plot(x, y, c=color, linestyle='-')
        pylab.scatter(x, y, c=color, label='s = %0.2f' % dist)

    pylab.xlabel('Wiring Cost', size=20)
    pylab.ylabel('Conduction Delay', size=20)
    pylab.xticks(fontsize=20)
    pylab.yticks(fontsize=20)

    leg = pylab.legend(frameon=True)
    ax = pylab.gca()
    pylab.setp(ax.get_legend().get_texts(), fontsize=20)  # for legend text
    leg.get_frame().set_linewidth(5)
    leg.get_frame().set_edgecolor('k')
    pylab.tight_layout()

    pylab.savefig('%s/pareto_front_scaled.pdf' % figs_dir, format='pdf')
    pylab.close()
コード例 #5
0
ファイル: pareto_steiner.py プロジェクト: arjunc12/neurons
def pareto_analysis(G, neuron_name, neuron_type,\
                    fronts_dir=NEUROMORPHO_FRONTS_DIR,\
                    output_dir=NEUROMORPHO_OUTPUT_DIR,\
                    figs_dir=NEUROMORPHO_FIGS_DIR, output=True,\
                    viz_trees=VIZ_TREES_NEUROMORPHO):

    assert G.number_of_nodes() > 0
    assert is_tree(G)

    print neuron_name, neuron_type

    #print "making graph"
    synapses = G.graph['synapses']
    points = synapses + [G.graph['root']]
    point_graph = G.subgraph(points)
    print point_graph.number_of_nodes(), 'points'

    # ---------------------------------------
    tree_costs_fname = '%s/tree_costs.csv' % fronts_dir

    models_fname = '%s/models_%s.csv' % (output_dir, neuron_name)
    output_fname = '%s/pareto_steiner_%s.csv' % (output_dir, neuron_name)
    tradeoff_fname = '%s/tradeoff_%s.csv' % (output_dir, neuron_name)

    # ---------------------------------------
    alphas, mcosts, scosts, first_time = pareto_front(G, point_graph,\
                                                      neuron_name, neuron_type,\
                                                      fronts_dir, figs_dir,\
                                                      viz_trees)

    opt_mcost, opt_scost = min(mcosts), min(scosts)
    # ---------------------------------------

    #neural_mcost = mst_cost(G)
    #neural_scost = satellite_cost(G, relevant_nodes=point_graph.nodes())
    neural_mcost, neural_scost = graph_costs(
        G, relevant_nodes=point_graph.nodes())

    neural_dist, neural_index = DIST_FUNC(mcosts, scosts, neural_mcost,\
                                          neural_scost)
    neural_closem = mcosts[neural_index]
    neural_closes = scosts[neural_index]
    neural_alpha = alphas[neural_index]

    # ---------------------------------------
    tradeoff = tradeoff_ratio(neural_mcost, opt_mcost, neural_scost, opt_scost)

    # ---------------------------------------
    centroid_tree = centroid_mst(point_graph)

    #centroid_mcost = mst_cost(centroid_tree)
    #centroid_scost = satellite_cost(centroid_tree, relevant_nodes=point_graph.nodes())
    centroid_mcost, centroid_scost = graph_costs(
        centroid_tree, relevant_nodes=point_graph.nodes())

    centroid_dist, centroid_index = DIST_FUNC(mcosts, scosts,\
                                              centroid_mcost,\
                                              centroid_scost)
    centroid_closem = mcosts[centroid_index]
    centroid_closes = scosts[centroid_index]
    centroid_alpha = alphas[centroid_index]

    # ---------------------------------------
    centroid_success = int(centroid_dist <= neural_dist)
    centroid_ratio = centroid_dist / neural_dist
    if first_time:
        with open(models_fname, 'a') as models_file:
            models_file.write('%s, %s, %s, %f\n' % (neuron_name,\
                                                      neuron_type,\
                                                      'neural',\
                                                      neural_dist))
            models_file.write('%s, %s, %s, %f, %d, %f\n' % (neuron_name,\
                                                            neuron_type,\
                                                            'centroid',\
                                                            centroid_dist,\
                                                            centroid_success,\
                                                            centroid_ratio))

# ---------------------------------------
    if first_time:
        with open(tree_costs_fname, 'w') as tree_costs_file:
            tree_costs_file.write('tree, mcost, scost\n')
            tree_costs_file.write('%s, %f, %f\n' % ('neural',neural_mcost,\
                                                    neural_scost))
            tree_costs_file.write('%s, %f, %f\n' % ('centroid', centroid_mcost,\
                                                    centroid_scost))
# ---------------------------------------
#point_graph = complete_graph(point_graph)
    random_trials = 20

    for i in xrange(random_trials):
        rand_mst = random_mst(point_graph, euclidean=True)
        rand_mcost, rand_scost = graph_costs(rand_mst)
        rand_dist, rand_index = DIST_FUNC(mcosts, scosts, rand_mcost,\
                                          rand_scost)
        rand_success = int(rand_dist <= neural_dist)
        rand_ratio = rand_dist / neural_dist

        barabasi_mst = barabasi_tree(point_graph)
        barabasi_mcost, barabasi_scost = graph_costs(barabasi_mst)
        barabasi_dist, barabasi_index = DIST_FUNC(mcosts, scosts,\
                                                  barabasi_mcost,\
                                                  barabasi_scost)
        barabasi_success = int(barabasi_dist <= neural_dist)
        barabasi_ratio = barabasi_dist / neural_dist

        with open(tree_costs_fname, 'a') as tree_costs_file:
            tree_costs_file.write('%s, %f, %f\n' % ('random', rand_mcost,\
                                                     rand_scost))
            tree_costs_file.write('%s, %f, %f\n' % ('barabasi',\
                                                     barabasi_mcost,\
                                                     barabasi_scost))

        with open(models_fname, 'a') as models_file:
            models_file.write('%s, %s, %s, %f, %d, %f\n' % (neuron_name,\
                                                            neuron_type,\
                                                            'random',\
                                                            rand_dist,\
                                                            rand_success,\
                                                            rand_ratio))

            models_file.write('%s, %s, %s, %f, %d, %f\n' % (neuron_name,\
                                                            neuron_type,\
                                                            'barabasi',\
                                                            barabasi_dist,\
                                                            barabasi_success,\
                                                            barabasi_ratio))


# ---------------------------------------

    def remove_spaces(string):
        return string.replace(' ', '')

    def remove_commas(string):
        return string.replace(',', '')

    if output and first_time:
        write_items = [neuron_name, neuron_type, point_graph.number_of_nodes()]

        write_items.append(neural_alpha)

        write_items = map(str, write_items)
        write_items = map(remove_commas, write_items)
        #write_items = map(remove_spaces, write_items)
        write_items = ', '.join(write_items)
        with open(output_fname, 'a') as output_file:
            output_file.write('%s\n' % write_items)

        with open(tradeoff_fname, 'a') as tradeoff_file:
            tradeoff_file.write('%s, %s, %f\n' %
                                (neuron_name, neuron_type, tradeoff))
コード例 #6
0
ファイル: pareto_functions.py プロジェクト: arjunc12/neurons
def pareto_genetic(G, axon=False, pop_size=POP_SIZE, generations=GENERATIONS,\
                   mutation_prob=MUTATION_PROB):
    root = G.graph['root']

    label_map = {}
    label_map_inv = {}
    for i, u in enumerate(G.nodes()):
        label_map[u] = i
        label_map_inv[i] = u

    G = nx.relabel_nodes(G, label_map)
    G.graph['root'] = label_map[root]

    population = []
    for i in xrange(pop_size):
        mst = random_mst(G)
        mcost, scost = graph_costs(mst)
        #cost = pareto_cost(mcost, scost, alpha)
        population.append((mst, mcost, scost))

    #population = sorted(population)

    for generation in xrange(generations):
        for i, (ind, mcost, scost) in enumerate(population):
            if random() < MUTATION_PROB:
                seq = to_prufer_sequence(ind)
                mutate_tree(seq, mutation_prob=1)
                ind = seq_to_tree(seq, G)
                population[i] = (ind, mcost, scost)

        parent1, parent2 = sample(population, 2)

        p1, m1, s1 = parent1
        p2, m2, s2 = parent2

        p1 = to_prufer_sequence(p1)
        p2 = to_prufer_sequence(p2)
        #mutate_tree(p1, MUTATION_PROB)
        #mutate_tree(p2, MUTATION_PROB)

        o1, o2 = crossover_trees(p1, p2)
        #mutate_tree(o1, MUTATION_PROB)
        #mutate_tree(o2, MUTATION_PROB)

        o1 = seq_to_tree(o1, G)
        o2 = seq_to_tree(o2, G)

        mcost1, scost1 = graph_costs(o1)
        #cost1 = pareto_cost(mcost1, scost1, alpha)
        mcost2, scost2 = graph_costs(o2)
        #cost2 = pareto_cost(mcost2, scost2, alpha)
        offspring = [(o1, mcost1, scost1), (o2, mcost2, scost2)]
        origin = (0, 0)
        for ospring, mcosto, scosto in offspring:
            worst_index = None
            worst_dist = 0
            for i, (ind, mcosti, scosti) in enumerate(population):
                if partially_dominates((mcosto, scosto), (mcosti, scosti)):
                    worst_index = i
                    break
            if worst_index != None:
                population[worst_index] = (ospring, mcosto, scosto)

    best_trees = []
    for ind, mcost, scost in population:
        T = nx.relabel_nodes(ind, label_map_inv)
        T.graph['root'] = root
        best_trees.append((mcost, scost, T))
    return best_trees