Exemplo n.º 1
0
def FN(G, layout):
    VertexDendrograms = G.community_fastgreedy()  # 获取点系统树图
    clustering = VertexDendrograms.as_clustering()  # 转点聚类
    modulrity = clustering.modularity

    covers = clustering.as_cover()  # 转点覆盖
    n = len(covers)
    pal = ig.ClusterColoringPalette(n)
    i = 0
    for li in covers:
        for node in li:
            G.vs[node]['color'] = pal.get(i)
        i += 1
    ig.plot(G,
            '%s_new.png' % gml_name, [0, 0, 1800, 1000],
            keep_aspect_ratio=True,
            vertex_size=20,
            vertex_frame_color='black',
            vertex_frame_width=1,
            layout=layout)

    cover_list = []
    for cover in covers:
        cover_list.append(cover)

    A = getNMI_A('./benchmark%s/community_network%s' % (order, order), '	')
    B = getNMI_B(cover_list, len(G.vs))
    nmi = NMI(A, B)

    with open('%sNMI_modularity.txt' % order, 'w') as op:
        op.write('standard:\n')
        op.write(str(A) + '\n')
        op.write('self:\n')
        op.write(str(B) + '\n')
        op.write('NMI:%s,modularity:%s' % (nmi, modulrity))
Exemplo n.º 2
0
def draw_graph(G,filename,layout):
    clustering=G.components()
    print clustering
    covers = clustering.as_cover()  # 转点覆盖

    n = len(covers)
    pal = ig.ClusterColoringPalette(n)
    i = 0
    for li in covers:
        for node in li:
            G.vs[node]['color'] = pal.get(i)
        i += 1
    ig.plot(G, '%s.png' % filename, [0, 0, 1800, 1000], keep_aspect_ratio=True,vertex_size=20,
            vertex_frame_color='black',vertex_frame_width=1,layout=layout)
def general_analysis(
    exp_ID,
    probe,
    visual=False,
    height=1000,
    length=1000,
    feedbackType=None,
    base_layout=1,
    timeperiods=[("trial_start", "stimOn_times"),
                 ("stimOn_times", "response_times"),
                 ("response_times", "trial_end")],
    region_list=[],
    file_nickname="experiment",
    difficulty=[-1, 1],
    percentage=1,
):
    """

    Makes a general analysis of th three main time perios (prestimulus, during stimulus, and after the stimulus)


    Input:
    exp_ID: experiment ID 
    visual: flag for visuals
    height: height of the resulting graph
    length: length of the resulting graph
    feedBackType: the type of response wanted
    base_layout: index in timeperiods of the base_layout
    timeperiods: names of time series used for reach graph



    Output:


    None

    """

    ###Data collection
    results = []

    data = loading(exp_ID, probe, region_list=region_list)
    for time1, time2 in timeperiods:
        temp_dict = dict()
        graph, partition, regions, locations = community_detection(
            exp_ID,
            probe=probe,
            user_start=time1,
            user_end=time2,
            feedbackType=feedbackType,
            difficulty=difficulty,
            percentage=percentage,
            data=data,
            region_list=region_list)
        temp_dict["graph"] = graph
        temp_dict["partition"] = partition
        temp_dict["regions"] = regions
        temp_dict["locations"] = locations
        results.append(temp_dict)

    ###Analysis functions

    ###Summary of each partition
    """
    Here we provide different measurements.

    Summary: this is just a breakdown of the community alligeance 
    Split Join Distance: Compares the partitions between time periods 
    Compare Communities: computes information variance for each community 
    Ovelap of communities: computes the percentage overlap with respect to the communities of the base layout


    """
    print("Summaries")
    for i in range(len(timeperiods)):
        time1, time2 = timeperiods[i]
        print(time1 + " to " + time2)
        print(results[i]["graph"].summary(verbosity=1))

    ###Split Join Distance

    print("Split join distance")
    #print([[ split_join_distance(graphs_for_partitions[i],graphs_for_partitions[j] ) for i in range(len(graphs_for_partitions))] for j in range(len(graphs_for_partitions))])

    ###Compare Communities

    print("Compare communities")

    print([[ig.compare_communities(i["graph"], j["graph"]) for i in results]
           for j in results])

    print("Ovelap of communities")
    results_no_base = [j for j in results]
    results_no_base = results_no_base[:base_layout] + results_no_base[
        base_layout + 1:]
    partitions_no_base = [i["partition"] for i in results_no_base]
    overlaps = com_overlap(results[base_layout]["partition"],
                           partitions_no_base)
    print(overlaps)

    ###Community assignments based on percentage shared with original community

    print("Matchings ")
    matchings = []
    for i in range(len(results_no_base)):
        matchings.append(
            match_colors(overlaps[i], len(results[base_layout]["partition"]),
                         len(results_no_base[i]["partition"])))
    print(matchings)

    ###Locations by community
    locations_simplified = [parse(i) for i in locations]

    partition = results[base_layout]["partition"]
    num_clusters = max([max(partition[i]) for i in partition]) + 1
    num_to_map = dict()
    for i in range(num_clusters):
        num_to_map[i] = {num_clusters - 1 - i}

    locations_to_order = [i for i in set(locations_simplified)]
    locations_to_order.sort()
    print(locations_to_order)
    order_x = labels_to_dictionary(locations_to_order)
    for i in order_x:
        temp = 0
        for k in order_x[i]:
            temp = k
        order_x[i] = temp

    layout_x = locations_from_dictionary(partition,
                                         length=length,
                                         height=height,
                                         seperated=False)
    layout_y = locations_from_dictionary(
        labels_to_dictionary(locations_simplified),
        order=order_x,
        length=length,
        height=height)
    layout_probe_y = locations_from_dictionary(num_to_map,
                                               length=length,
                                               height=height)
    layout_probe_3 = [[
        int(length * (1 / 2 - 0.1 + 0.2 * i % 3)), layout_probe_y[i][1]
    ] for i in range(len(layout_probe_y))]
    layout_mixed = [[layout_x[i][0], layout_y[i][1]]
                    for i in range(min(len(layout_y), len(layout_x)))]
    layout_depth = [[layout_x[i][0], layout_probe_y[i][1]]
                    for i in range(min(len(layout_probe_y), len(layout_x)))]
    coloring = ig.ClusterColoringPalette(20)
    colorings = []
    for i in range(len(overlaps)):
        o_partition = results_no_base[i]["partition"]
        overlap = overlaps[i]
        #plt.table(cellText=[ [ overlap[(i,j)] for j in o_partition] for i in partition], rowLabels=[i for i in partition] , colLabels=[j for j in o_partition], loc='top' )
        #plt.subplots_adjust(left=0.2, top=0.8)
        #plt.show()

        colorings.append(Pallete_changed(20, coloring, matchings[i]))

    ###Final visualization

    for i in range(len(timeperiods)):
        if i < base_layout:
            pre_graph = results[i]["graph"]
            #visualize(pre_graph, layout= layout_mixed , vertex_size=30, labels=locations_simplified, length=length, height=height, coloring=colorings[i], file_name=file_nickname+"_"+str(i)+"_final" +".svg")
            #visualize(pre_graph, layout= layout_probe_3 , vertex_size=30, labels=locations_simplified, length=length, height=height, coloring=colorings[i], file_name=file_nickname+".pdf")
            visualize(pre_graph,
                      layout=layout_depth,
                      vertex_size=30,
                      labels=locations_simplified,
                      length=length,
                      height=height,
                      coloring=colorings[i],
                      file_name=file_nickname + "_" + str(i) + "_final" +
                      ".svg")
        elif i == base_layout:
            pre_graph = results[i]["graph"]
            #visualize(pre_graph, layout= layout_mixed , vertex_size=30, labels=locations_simplified, length=length, height=height, coloring=coloring, file_name=file_nickname+"_"+str(i)+"_final"+".pdf")
            #visualize(pre_graph, layout= layout_probe_3 , vertex_size=30, labels=locations_simplified, length=length, height=height, coloring=coloring, file_name=file_nickname+".pdf")
            visualize(pre_graph,
                      layout=layout_depth,
                      vertex_size=30,
                      labels=locations_simplified,
                      length=length,
                      height=height,
                      coloring=coloring,
                      file_name=file_nickname + "_" + str(i) + "_final" +
                      ".svg")

        else:
            j = i - 1
            pre_graph = results[i]["graph"]
            #visualize(pre_graph, layout= layout_mixed , vertex_size=30, labels=locations_simplified, length=length, height=height, coloring=colorings[j], file_name=file_nickname+"_"+str(i)+"_final"+".pdf")
            #visualize(pre_graph, layout= layout_probe_3 , vertex_size=30, labels=locations_simplified, length=length, height=height, coloring=colorings[j], file_name=file_nickname+".pdf")
            visualize(pre_graph,
                      layout=layout_depth,
                      vertex_size=30,
                      labels=locations_simplified,
                      length=length,
                      height=height,
                      coloring=colorings[j],
                      file_name=file_nickname + "_" + str(i) + "_final" +
                      ".svg")

    if visual:
        return visualized_3d(results, matchings, base_layout, exp_ID, probe)
    else:
        return []
Exemplo n.º 4
0
atnet2 = atnet.copy()
atnet2.is_simple()
# if is simple, no need to simplify
atnet2.es.select(weight_lt=7).delete()

# descriptive analysis
atnet2.density()
atnet2.vcount()
atnet2.betweenness()

# component and communities
comp = atnet2.components('WEAK')  # weak components for directed network
pd.value_counts(comp.sizes())  # sizes of components
atnet2 = comp.giant()  # keep the giant component only
print(atnet2.vcount(), "nodes in the giant component.")

communities = atnet2.community_spinglass(weights='weight')
print(len(communities.sizes()), "communities", "with sizes:",
      sorted(communities.sizes()))
atnet2.vs["membership"] = communities.membership

palette = igraph.ClusterColoringPalette(len(communities.membership))
atnet2.vs['color'] = [palette.get(el) for el in atnet2.vs['membership']]
igraph.plot(atnet2, "network communities.png")

for e in atnet2.es:
    e['color'] = atnet2.vs[e.target]['color']

igraph.plot(atnet2, "network communities.png")
Exemplo n.º 5
0
    g_con.es['weight'] = com_weights

    print('communities detected')

    # define visual styling
    visual_style = {}

    # define visual styling
    max_size = 5  # maximum vertex size
    min_width = 0.5  # maximum edge size

    visual_style['vertex_size'] = np.log(
        np.array(list(community_dict.values()))) * max_size
    visual_style['layout'] = g_con.layout_fruchterman_reingold()
    visual_style['vertex_color'] = list(community_dict.keys())
    visual_style['palette'] = ig.ClusterColoringPalette(
        len(list(community_dict.keys())) + 3)
    visual_style['edge_width'] = np.log(np.array(
        g_con.es['weight'])) + min_width
    visual_style['edge_color'] = 'rgba(0,0,0,0.1)'
    visual_style['mark_groups'] = False
    visual_style['margin'] = 50
    visual_style['bbox'] = (700, 700)

    # plot graph grouped by communities
    ig.plot(g_con, './figures/communities_united.png', **visual_style)

    print('communities drawn')

    # circos plot
    visual_style['layout'] = g_con.layout_circle()
    ig.plot(g_con, './figures/circos_united.png', **visual_style)