Esempio n. 1
0
def get_resource_allocation_matrix(graph):
    '''
	Gets the resource allocation matrix W_ij, which represents the the fraction of
	resoure the jth X node transfers to the ith.
	
	w_ij = (1 /  k(x_j)) * sum_l((a_il * a_jl) / k(y_l)
	
	where the indices, l, represent the nodes for each track. 
	'''
    degree_dict = nx.degree(graph)

    track_nodes, _ = bipartite.sets(graph)

    matrix = {}
    number_of_permutations = int(perm(len(track_nodes), 2))
    for i, (track_i,
            track_j) in enumerate(itertools.permutations(track_nodes, 2)):
        if i % 1e6 == 0:
            print 'working on user perumation {} of {}'.format(
                i + 1, number_of_permutations)

        summation_term = 0.

        user_nodes = set(graph.neighbors(track_i)) | set(
            graph.neighbors(track_j))
        for user_l in user_nodes:
            summation_term += (float(graph.has_edge(track_i, user_l)) *
                               graph.has_edge(track_j, user_l) /
                               degree_dict[user_l])

        matrix[track_i, track_j] = summation_term / degree_dict[track_j]

    return matrix
Esempio n. 2
0
def gen_setcover_inst(G):

    constant_add = len(G)
    print(" const add ", constant_add)
    node_list_A = list(set(G.nodes()))
    node_list_B = [x + constant_add for x in list(set(G.nodes()))]

    g = nx.Graph()
    g.add_nodes_from(node_list_A, bipartite=0)
    g.add_nodes_from(node_list_B, bipartite=1)

    #   for i in range(total_nodes):
    for (v1, v2) in G.edges():
        if (v1 == v2):
            continue
        g.add_edge(v1, v2 + constant_add)
        g.add_edge(v1 + constant_add, v2)

# g.remove_nodes_from(list(nx.isolates(g)))

    set_nodes, element_nodes = bipartite.sets(g)
    set_nodes = list(set_nodes)
    element_nodes = list(element_nodes)
    print(len(set_nodes), len(element_nodes))
    return g
Esempio n. 3
0
def graph_att_head(M, N, weight, ax, title):
    "credit: Jinjing zhou"
    in_nodes = len(M)
    out_nodes = len(N)

    g = nx.bipartite.generators.complete_bipartite_graph(in_nodes, out_nodes)
    X, Y = bipartite.sets(g)
    height_in = 10
    height_out = height_in
    height_in_y = np.linspace(0, height_in, in_nodes)
    height_out_y = np.linspace((height_in - height_out) / 2, height_out, out_nodes)
    pos = dict()
    pos.update((n, (1, i)) for i, n in zip(height_in_y, X))  # put nodes from X at x=1
    pos.update((n, (3, i)) for i, n in zip(height_out_y, Y))  # put nodes from Y at x=2
    ax.axis('off')
    ax.set_xlim(-1, 4)
    ax.set_title(title)
    nx.draw_networkx_nodes(g, pos, nodelist=range(in_nodes), node_color='r', node_size=50, ax=ax)
    nx.draw_networkx_nodes(g, pos, nodelist=range(in_nodes, in_nodes + out_nodes), node_color='b', node_size=50, ax=ax)
    for edge in g.edges():
        nx.draw_networkx_edges(g, pos, edgelist=[edge], width=weight[edge[0], edge[1] - in_nodes] * 1.5, ax=ax)
    nx.draw_networkx_labels(g, pos, {i: label + '  ' for i, label in enumerate(M)}, horizontalalignment='right',
                            font_size=8, ax=ax)
    nx.draw_networkx_labels(g, pos, {i + in_nodes: '  ' + label for i, label in enumerate(N)},
                            horizontalalignment='left', font_size=8, ax=ax)
Esempio n. 4
0
def is_planar(G):
    """
    function checks if graph G has K(5) or K(3,3) as minors,
    returns True /False on planarity and nodes of "bad_minor"
    """
    result = True
    bad_minor = []
    n = len(G.nodes())
    if n > 5:
        for subnodes in it.combinations(G.nodes(), 6):
            subG = G.subgraph(subnodes)
            if bipartite.is_bipartite(
                    G):  # check if the graph G has a subgraph K(3,3)
                X, Y = bipartite.sets(G)
                if len(X) == 3:
                    result = False
                    bad_minor = subnodes
    if n > 4 and result:
        for subnodes in it.combinations(G.nodes(), 5):
            subG = G.subgraph(subnodes)
            if len(subG.edges()
                   ) == 10:  # check if the graph G has a subgraph K(5)
                result = False
                bad_minor = subnodes
    return result, bad_minor
def create_3comms_bipartite(n,m,p,No_isolates=True):
    
    import community as comm

    from networkx.algorithms import bipartite as bip
    u=0
    while  True:
        G=nx.bipartite_random_graph(n,m,p)
        list_of_isolates=nx.isolates(G)
        if No_isolates:
            G.remove_nodes_from(nx.isolates(G))
        partition=comm.best_partition(G)
        sel=max(partition.values())
        if sel==2 and nx.is_connected(G):
            break
        u+=1
        print u,sel
    ndlss=bip.sets(G)
    ndls=[list(i) for i in ndlss]
    slayer1=ndls[0]
    slayer2=ndls[1]
    layer1=[i for i,v in partition.items() if v==0]
    layer2=[i for i,v in partition.items() if v==1]
    layer3=[i for i,v in partition.items() if v==2]
    edgeList=[]
    for e in G.edges():
        if (e[0] in slayer1 and e[1] in slayer2) or (e[0] in slayer2 and e[1] in slayer1):
            edgeList.append(e)
    return G,layer1,layer2,layer3,slayer1,slayer2,edgeList,partition
Esempio n. 6
0
def clusterConstrained(dupes, threshold=0.6):

    dupe_graph = networkx.Graph()
    dupe_graph.add_weighted_edges_from(((x[0], x[1], y) for (x, y) in dupes), bipartite=1)

    dupe_sub_graphs = connected_component_subgraphs(dupe_graph)
    clusters = []
    for sub_graph in dupe_sub_graphs:
        if len(sub_graph) > 2:
            row_order, col_order = bipartite.sets(sub_graph)
            row_order, col_order = list(row_order), list(col_order)
            scored_pairs = numpy.asarray(biadjacency_matrix(sub_graph, row_order, col_order))

            scored_pairs[scored_pairs < threshold] = 0
            scored_pairs = 1 - scored_pairs

            m = _Hungarian()
            clustering = m.compute(scored_pairs)

            cluster = [set([row_order[l[0]], col_order[l[1]]]) for l in clustering if len(l) > 1]
            clusters = clusters + cluster
        else:
            clusters.append(set(sub_graph.edges()[0]))

    return clusters
Esempio n. 7
0
def plot_helper(inst, repos, countries):
    df = pd.read_csv(diffusion_graph_dir+'epoch_0.tsv', sep='\t').dropna()    
    tweets = df.copy().drop('target_url', axis=1).drop_duplicates('source_url')
    #beutify country names
    tweets = tweets.merge(pd.read_csv(countriesFile).rename(columns={'Name':'Country'}), left_on='user_country', right_on='Code').drop(['user_country', 'Code'], axis=1).set_index('source_url')
    tweets.loc[tweets['Country'] == 'United States', 'Country'] = 'USA'
    print('Initial Tweets:', len(tweets))

    #Popularity
    inst.groupby('Institution').mean()['popularity'].sort_values(ascending=False)[:20]
    repos.groupby('Field').size().sort_values(ascending=False)
    inst.groupby('Institution').mean().plot.scatter(x='Score', y='popularity')
    corr = inst.groupby('Institution').mean()[['popularity', 'World Rank', 'National Rank', 'Alumni Employment', 'Publications', 'Influence', 'Citations', 'Broad Impact', 'Patents', 'Score']].corr()
    #sns.heatmap(corr, xticklabels=corr.columns.values, yticklabels=corr.columns.values)
    corr.iloc[0]

    #bipartite graph
    countries['Name'] = countries['Name'].map(lambda n: n+'_user')
    countries['Location'] = countries['Location'].map(lambda n: n+'_inst')
    B = nx.Graph()
    B.add_edges_from([(row['Name'], row['Location']) for _, row in countries.iterrows()])
    plt.figure(figsize=(10,10))
    X, Y = bipartite.sets(B)
    pos = dict()
    pos.update( (n, (1, i)) for i, n in enumerate(X) ) # put nodes from X at x=1
    pos.update( (n, (2, i*4)) for i, n in enumerate(Y) ) # put nodes from Y at x=2
    nx.draw(B, pos=pos, with_labels = True)
Esempio n. 8
0
def main():
    homens = dict()
    arquivoMen = open('men.txt', 'r')
    for linha in arquivoMen:
        h = linha.split(sep=':')[0]
        m = linha.split(sep=':')[1:][0]
        m = m.split(sep=',')
        for i in range(len(m)):
            m[i] = m[i].replace('\n', '').replace(',', '').strip()

        homens[h] = dict((k, 0) for k in m)

    arquivoMen.close()

    mulheres = dict()
    arquivoWomen = open('women.txt', 'r')
    for linha in arquivoWomen:
        m = linha.split(sep=':')[0]
        h = linha.split(sep=':')[1:][0]
        h = h.split(sep=',')
        for i in range(len(h)):
            h[i] = h[i].replace('\n', '').replace(',', '').strip()

        mulheres[m] = h

    arquivoWomen.close()

    edges = GaleShappley(homens, mulheres)

    print(edges)

    G = nx.Graph()
    node_color_map = list()

    for homem in homens:
        for mulher in homens[homem]:
            G.add_node(homem, bipartite=0, color='blue')
            G.add_node(mulher, bipartite=1, color='red')
            G.add_edge(homem, mulher, color='black')

    for edge in edges:
        G.nodes[edge]['color'] = 'red'
        G.nodes[edges[edge]]['color'] = 'blue'
        G.add_edge(edge, edges[edge], color='red')

    edges_color = [G[u][v]['color'] for u, v in G.edges()]

    node_color_map = [u[1]['color'] for u in G.nodes(data=True)]

    X, Y = bipartite.sets(G)
    pos = dict()
    pos.update((n, (1, i)) for i, n in enumerate(X))  # put nodes from X at x=1
    pos.update((n, (2, i)) for i, n in enumerate(Y))  # put nodes from Y at x=2

    nx.draw(G,
            with_labels=True,
            node_color=node_color_map,
            edge_color=edges_color,
            pos=pos)
    plt.savefig('grafo_gale.png')
Esempio n. 9
0
def plot_initial_bgraph(G, subp=121):
    fig = plt.figure(num=1, figsize=(16, 12))
    fig.add_subplot(subp)
    sets = bipartite.sets(G)
    pos = {}
    for i, v in enumerate(sets[0]):
        pos[v] = (0., i)
    for i, v in enumerate(sets[1]):
        pos[v] = (1, i)

    rr = nx.attribute_assortativity_coefficient(G, 'bipartite')
    s_title = 'Bipartite Graph\nAssortativity_coef(bipartition) = %.2f' % rr
    plt.title(s_title)  #,{'size': '20'})
    nx.draw_networkx_nodes(G,
                           pos=pos,
                           nodelist=list(sets[0]),
                           node_color='grey',
                           alpha=0.3)
    nx.draw_networkx_nodes(G,
                           pos=pos,
                           nodelist=list(sets[1]),
                           node_color='gold')
    nx.draw_networkx_labels(G, pos=pos)
    nx.draw_networkx_edges(G, pos=pos, alpha=0.2)
    plt.axis("off")
    # plt.show()
    return pos, fig
Esempio n. 10
0
def draw_bi(B, X=[], Y=[], color_map=None):
    #draw bipartite graph (if the is disconnected then nodes lists have to be provided)
    if nx.is_connected(B):
        X, Y = bipartite.sets(B)
        X = sorted(list(X))
        Y = sorted(list(Y))
        pos = dict()
        pos.update(
            (n, (1, i)) for i, n in enumerate(X))  # put nodes from X at x=1
        pos.update(
            (n, (2, i)) for i, n in enumerate(Y))  # put nodes from Y at x=2
        if color_map == None:
            nx.draw(B, pos=pos, with_labels=True)
        else:
            nx.draw(B, pos=pos, with_labels=True, color=color_map)

        plt.show()
    else:
        if len(X) == 0 or len(Y) == 0:
            return ("Graph is disconnected, please specify nodes sets")
        else:
            X = sorted(list(X))
            Y = sorted(list(Y))
            pos = dict()
            pos.update((n, (1, i))
                       for i, n in enumerate(X))  # put nodes from X at x=1
            pos.update((n, (2, i))
                       for i, n in enumerate(Y))  # put nodes from Y at x=2
            if color_map == None:
                nx.draw(B, pos=pos, with_labels=True)
            else:
                nx.draw(B, pos=pos, with_labels=True, color=color_map)
            plt.show()
Esempio n. 11
0
def clusterConstrained(dupes, threshold=.6):

    dupe_graph = networkx.Graph()
    dupe_graph.add_weighted_edges_from(((x[0], x[1], y) for (x, y) in dupes),
                                       bipartite=1)

    dupe_sub_graphs = connected_component_subgraphs(dupe_graph)
    clusters = []
    for sub_graph in dupe_sub_graphs:
        if len(sub_graph) > 2:
            row_order, col_order = bipartite.sets(sub_graph)
            row_order, col_order = list(row_order), list(col_order)
            scored_pairs = numpy.asarray(
                biadjacency_matrix(sub_graph, row_order, col_order))

            scored_pairs[scored_pairs < threshold] = 0
            scored_pairs = 1 - scored_pairs

            m = _Hungarian()
            clustering = m.compute(scored_pairs)

            cluster = [
                set([row_order[l[0]], col_order[l[1]]]) for l in clustering
                if len(l) > 1
            ]
            clusters = clusters + cluster
        else:
            clusters.append(set(sub_graph.edges()[0]))

    return clusters
Esempio n. 12
0
def buildAffGraph(matrix, k):
	if not os.path.exists('graphs/'):
		os.makedirs('graphs/')

	num = len(matrix)
	B = nx.Graph()
	# Add nodes with the node attribute "bipartite"
	B.add_nodes_from(np.arange(1, num+1), bipartite=0)
	B.add_nodes_from(np.arange(num+1,num*2+1), bipartite=1)
	# Add edges only between nodes of opposite node sets
	for i in range(num):
		for j in range(num):
				B.add_edges_from([(i+1, num+j+1, {'weight': matrix[i,j]})])

	color_map = []
	for node in B:
		if node < num+1:
			color_map.append('blue')
		else: color_map.append('red')

	X, Y = bipartite.sets(B)
	pos = dict()
	pos.update( (n, (1, i)) for i, n in enumerate(X) ) # put nodes from X at x=1
	pos.update( (n, (2, i)) for i, n in enumerate(Y) ) # put nodes from Y at x=2

	nx.draw(B, pos, node_color=color_map, with_labels=True, font_weight='bold')
	labels = nx.get_edge_attributes(B,'weight')
	nx.draw_networkx_edge_labels(B, pos, edge_labels=labels)
	plt.savefig("graphs/aff{}.png".format(k+1))
	plt.close()

	E = nx.algorithms.bipartite.matrix.biadjacency_matrix(B,np.arange(1, num+1)).todense()
Esempio n. 13
0
def is_planar(G):
    """
    function checks if graph G has K(5) or K(3,3) as minors,
    returns True /False on planarity and nodes of "bad_minor"
    """
    result = True
    bad_minor = []
    n = len(G.nodes())
    iterazione = 0
    if n > 5:
        print "N >5"

        for subnodes in it.combinations(G.nodes(), 6):
            iterazione += 1
            print "iterazione %d" % iterazione
            subG = G.subgraph(subnodes)
            if bipartite.is_bipartite(G):  # check if the graph G has a subgraph K(3,3)
                X, Y = bipartite.sets(G)
                if len(X) == 3:
                    result = False
                    bad_minor = subnodes
                    return result, bad_minor
    iterazione = 0
    if n > 4 and result:
        print "N >4"

        for subnodes in it.combinations(G.nodes(), 5):
            print "iterazione %d" % iterazione
            subG = G.subgraph(subnodes)
            if len(subG.edges()) == 10:  # check if the graph G has a subgraph K(5)
                result = False
                bad_minor = subnodes
                return result, bad_minor

    return result, bad_minor
Esempio n. 14
0
def _show_bipartite_circuit_graph(filename, graph, dir_path):
    no_of_subgraph = 0
    for subgraph in nx.connected_component_subgraphs(graph):
        no_of_subgraph += 1

        color_map = []
        x_pos, y_pos = bipartite.sets(subgraph)
        pos = dict()
        pos.update((n, (1, i))
                   for i, n in enumerate(x_pos))  # put nodes from X at x=1
        pos.update((n, (2, i))
                   for i, n in enumerate(y_pos))  # put nodes from Y at x=2
        #nx.draw(B, pos=pos)
        #plt.show()
        plt.figure(figsize=(6, 8))
        for dummy, attr in subgraph.nodes(data=True):
            if "inst_type" in attr:
                if attr["inst_type"] == 'pmos':
                    color_map.append('red')
                elif attr["inst_type"] == 'nmos':
                    color_map.append('cyan')
                elif attr["inst_type"] == 'cap':
                    color_map.append('orange')
                elif attr["inst_type"] == 'net':
                    color_map.append('pink')
                else:
                    color_map.append('green')
        nx.draw(subgraph, node_color=color_map, with_labels=True, pos=pos)
        plt.title(filename, fontsize=20)
        if not os.path.exists(dir_path):
            os.mkdir(dir_path)
        plt.savefig(dir_path + '/' + filename + "_" + str(no_of_subgraph) +
                    '.png')
        plt.close()
Esempio n. 15
0
def generateDailyGraph(dateLi):
    myUsrDict = deepcopy(ReadData.usrDict);
    myMovDict = deepcopy(ReadData.movDict);
    gx = nx.Graph()

    users = []
    movies = []
    edges = []
    for (uid, mid) in dateLi:
        # add vertex for user if it does not already exist
        if myUsrDict[uid][1] == 0:
            myUsrDict[uid][1] = 1;
            users.append(uid)

        # add vertex for movie if it does not already exist
        if myMovDict[mid][1] == 0:
            myMovDict[mid][1] = 1;
            movies.append(mid)

        edges.append((uid, mid))

    gx.add_nodes_from(users, bipartite=0)
    gx.add_nodes_from(movies, bipartite=1)
    gx.add_edges_from(edges)

    nx.is_connected(gx)

    bottom_nodes, top_nodes = bipartite.sets(gx)

    return gx, bottom_nodes, top_nodes
Esempio n. 16
0
def is_planar(G):
    """
    function checks if graph G has K(5) or K(3,3) as minors,
    returns True /False on planarity and nodes of "bad_minor"
    """
    result = True
    bad_minor = []
    n = len(G.nodes())
    if n > 5:
        for subnodes in it.combinations(G.nodes(), 6):
            subG = G.subgraph(subnodes)
            if subG.number_of_edges() >= 9:
                print "OI"
                if bipartite.is_bipartite(
                        subG):  # check if the graph G has a subgraph K(3,3)
                    X, Y = bipartite.sets(subG)
                    if len(X) == 3:
                        result = False
                        bad_minor = (X.pop(), X.pop(), X.pop(), Y.pop(),
                                     Y.pop(), Y.pop())
                        print[(names[i], names[j]) for i, j in subG.edges()]
                        return result, bad_minor
    if n > 4 and result:
        for subnodes in it.combinations(G.nodes(), 5):
            subG = G.subgraph(subnodes)
            if len(subG.edges()
                   ) == 10:  # check if the graph G has a subgraph K(5)
                result = False
                bad_minor = subnodes
                return result, bad_minor
    return result, bad_minor
Esempio n. 17
0
def complete_bipartite_graph_generation_and_dump_in_json():
    nb_sommets = 15
    seed = 29

    n1 = random.randint(1, nb_sommets - 1)
    n2 = nb_sommets - n1
    p = 0.5

    g = bipartite.complete_bipartite_graph(n1, n2)
    V1, V2 = bipartite.sets(g)
    graph_for_json = dict()
    graph_for_json = {
        "seed": seed,
        "graph_type": "bipartite",
        "total_node_count": len(g.nodes),
        "V1_node_count": len(V1),
        "V2_node_count": len(V2),
        "edge_count": len(list(g.edges)),
        "nodes": sorted(g.nodes),
        "edges": list(g.edges)
    }

    with open('test_dumps/complete_bipartite_1.json', 'w',
              encoding='utf8') as json_file:
        json.dump(graph_for_json, json_file, indent=4)  # Ugly indents

    with open('test_dumps/complete_bipartite_2.json', 'w',
              encoding='utf8') as json_file:
        json_file.write(data_to_json(graph_for_json))  # Nice indents
    def weighted_projected_graph(self):

        # create a projection on one of the nodes
        E = bipartite.sets(self.B)[0]
        print('EEEEEEEEEEEEEEEEEEE')
        print(E)
        P = bipartite.weighted_projected_graph(self.B, E, ratio=True)

        # self.plot_graph(P,'weighted_projected')
        self.plot_graph_2(P, 'weighted_projected')
        print('weighted_projected:number of edges:', P.number_of_edges())
        print(P.edges())
        print(list(P.edges(data=True)))
        weights = []
        for i in list(P.edges(data=True)):
            weights.append(i[2]['weight'])
        print(weights)

        P = bipartite.weighted_projected_graph(self.B, E, ratio=False)
        self.plot_graph_2(P, 'weighted_projected_not_ratio')
        print('RRRRRRRRRRRRRRRRRRRRRRRR')
        print(P.edges())
        weights = []
        for i in list(P.edges(data=True)):
            weights.append(i[2]['weight'])
        print(weights)
Esempio n. 19
0
def get_valid_fragments(G, stoich_rank):
    #reactions, complexes = bipartite.sets(G)
    complexes, reactions = bipartite.sets(G)

    complexes = list(complexes)
    reactions = list(reactions)

    if 'w1' not in complexes and 'w1' not in reactions:
        raise Exception('my hack to resolve this unexpected behavior shown by bipartite.sets assumes that reaction nodes are named \'w1\', \'w2\', ...')
    
    if 'w1' in complexes:
        complexes, reactions = reactions, complexes

    if not ('w1' in reactions and 's1' in complexes):
        raise Exception('Something went wrong generating the lists of complexes of reactions.')

    complex_perms = list(it.combinations(complexes,stoich_rank))
    reaction_perms = list(it.combinations_with_replacement(reactions,stoich_rank))
    fragments = list(it.product(complex_perms, reaction_perms))

    valid_fragments = []
    
    pool = Pool()
    chunksize = 100

    myval = functools.partial(validate_fragments, G, stoich_rank)
    
    fragment_list = pool.imap(myval, fragments, chunksize)
    valid_fragments = [f for f in fragment_list if f is not None]

    return get_unique_fragments(valid_fragments)
Esempio n. 20
0
 def test_tate_foundation_str_id(self, history_client):
     """Test basic query of Tate_Foundation board members."""
     charity_network = get_charity_network("1085314", client=history_client)
     assert len(charity_network) == 15
     assert is_connected(charity_network)
     tate_foundation, board_members = bipartite.sets(charity_network)
     assert len(board_members) == 14
     assert type(list(tate_foundation)[0]) is int
Esempio n. 21
0
 def test_bipartite_density(self):
     G=nx.path_graph(5)
     X,Y=bipartite.sets(G)
     density=float(len(G.edges()))/(len(X)*len(Y))
     assert_equal(bipartite.density(G,X),density)
     D = nx.DiGraph(G.edges())
     assert_equal(bipartite.density(D,X),density/2.0)
     assert_equal(bipartite.density(nx.Graph(),{}),0.0)
Esempio n. 22
0
 def test_bipartite_density(self):
     G = nx.path_graph(5)
     X, Y = bipartite.sets(G)
     density = float(len(list(G.edges()))) / (len(X) * len(Y))
     assert_equal(bipartite.density(G, X), density)
     D = nx.DiGraph(G.edges())
     assert_equal(bipartite.density(D, X), density / 2.0)
     assert_equal(bipartite.density(nx.Graph(), {}), 0.0)
 def generic_weighted_projected_graph(self):
     E = bipartite.sets(self.B)[0]
     P = bipartite.generic_weighted_projected_graph(self.B, E)
     self.plot_graph_2(P, 'generic_weighted_projected_graph')
     print('generic_weighted_projected_graph:number of edges:',
           P.number_of_edges())
     print(P.edges())
     print(list(P.edges(data=True)))
Esempio n. 24
0
 def test_1hop_tate(self, history_client):
     """Test 1 hop query of Tate_Foundation board members."""
     charity_network = get_charity_network(1085314,
                                           branches=1,
                                           client=history_client)
     assert len(charity_network) == 73
     assert is_connected(charity_network)
     tate_foundation, board_members = bipartite.sets(charity_network)
     assert len(board_members) == 64
Esempio n. 25
0
def save_graph(c2map, filepath):
	graph = c2map['graph']

	X, Y = bipartite.sets(graph)
	pos = dict()
	pos.update( (n, (1, i)) for i, n in enumerate(X) ) # put nodes from X at x=1
	pos.update( (n, (2, i)) for i, n in enumerate(Y) ) # put nodes from Y at x=2
	nx.draw(graph, pos=pos,with_labels=True)
	plt.savefig(filepath)
Esempio n. 26
0
def main():
    fname = os.path.join(dir.graphs_dir, "long-all-bipartite.edges")
    full_g = nx.read_edgelist(fname, delimiter=",", nodetype=str)
    if nx.is_bipartite(full_g):
        nois, followers = bipartite.sets(full_g)
	# bipartite graph projection
        g = projection.overlap_weighted_projected_graph(full_g, nodes=nois, jaccard=False)
        fname = os.path.join(dir.graphs_dir, "projection-full-graph.edgelist")
        nx.write_edgelist(g, fname, delimiter=',', data='weight')
Esempio n. 27
0
def desenhar_bipartido(G, M = []):
	
	X, Y = bipartite.sets(G)
	pos = dict()
	pos.update((n, (1, i)) for i, n in enumerate(X))
	pos.update((n, (2, i)) for i, n in enumerate(Y))
	cores = pintar_arestas(G, M)
	nx.draw(G, with_labels = True, edge_color = cores, pos=pos)
	plt.show()
Esempio n. 28
0
def save_graph(c2map, filepath):
    graph = c2map['graph']

    X, Y = bipartite.sets(graph)
    pos = dict()
    pos.update((n, (1, i)) for i, n in enumerate(X))  # put nodes from X at x=1
    pos.update((n, (2, i)) for i, n in enumerate(Y))  # put nodes from Y at x=2
    nx.draw(graph, pos=pos, with_labels=True)
    plt.savefig(filepath)
Esempio n. 29
0
    def __init__(self, graph):
        self.graph = graph

        parameters = pywrapcp.Solver.DefaultSolverParameters()
        solver = pywrapcp.Solver("SetCover_CP", parameters)
        self.solver = solver

        self.sets, self.items = bipartite.sets(self.graph)
        self.set_variables = self.generate_set_variables()
        self.add_ge_sum_constraints()
Esempio n. 30
0
def generic_recommendation(raw_graph, num_of_articles):
    articles_by_degree = []
    for connected_component in nx.connected_components(raw_graph):
        connected_component = nx.subgraph(raw_graph, connected_component)
        users, articles = bipartite.sets(connected_component)
        articles_degree = filter(lambda node: node[0] in articles, connected_component.degree)
        articles_by_degree.extend(
            sorted(articles_degree, key=itemgetter(1), reverse=True))
    articles, _ = zip(*articles_by_degree)
    return articles[:num_of_articles]
Esempio n. 31
0
    def projected_graph(self):

        if not self.B:
            self.create_bipartite_graph()

        bottom = bipartite.sets(self.B)[0]
        G = bipartite.generic_weighted_projected_graph(
            self.B, bottom, weight_function=self.projection_weight)

        return G
    def __init__(self, sigma: Tuple[Tuple[int]], alpha: Tuple[Tuple[int]]):
        super().__init__()
        self.sigma = sigma  # should include singletons corresponding to fixed points
        self.alpha = alpha  # should include singletons corresponding to fixed points
        f = self.compute_phi()
        self.phi = self.permlist_to_tuple(f)
        self.build_node_info()  # print dictionary for [sigma, alpha, phi]
        self.node_dict = self.sigma_dict, self.alpha_dict, self.phi_dict

        self.node_info = [
            "sigma:", self.sigma_dict, "alpha:", self.alpha_dict, "phi:",
            self.phi_dict
        ]

        self.code_graph = nx.MultiGraph()

        # Create black nodes for each cycle in sigma along with white nodes
        # representing "half edges" around the black nodes
        for cycle in self.sigma:
            self.code_graph.add_node(cycle, bipartite=1)
            for node in cycle:
                self.code_graph.add_node(node, bipartite=0)
                self.code_graph.add_edge(cycle, node)

        # Create black nodes for each cycle in phi along with white nodes
        # representing "half edges" around the black nodes
        for cycle in self.phi:
            self.code_graph.add_node(cycle, bipartite=1)
            for node in cycle:
                self.code_graph.add_edge(cycle, node)

        # Create nodes for each cycle in alpha then
        # glue the nodes corresponding to a the pairs
        for pair in self.alpha:
            self.code_graph.add_node(pair)
            self.code_graph = nx.contracted_nodes(self.code_graph,
                                                  pair[0],
                                                  pair[1],
                                                  self_loops=True)
            # Now contract pair with pair[0] to make sure edges (white nodes) are labeled
            # by the pairs in alpha to keep track of the gluing from the previous step
            self.code_graph = nx.contracted_nodes(self.code_graph,
                                                  pair,
                                                  pair[0],
                                                  self_loops=True)

        # Define the white and black nodes. White correspond to edges labeled by
        # cycles in alpha. Black correspond to nodes labeled by cycles in sigma
        # (vertices) and phi (faces)
        self.black_nodes, self.white_nodes = bipartite.sets(self.code_graph)
        self.vertex_basis()
        self.edge_basis()
        self.face_basis()
        self.d_2()
        self.d_1()
def draw_bipartite_graph(G):
    X, Y = bipartite.sets(G)
    pos = dict()
    pos.update( (n, (1, i)) for i, n in enumerate(X) ) # put nodes from X at x=1
    pos.update( (n, (2, i)) for i, n in enumerate(Y) ) # put nodes from Y at x=2
    nx.draw(G, pos=pos, with_labels=True, font_size=8, node_size=1000)

    fig = plt.gcf()
    plt.tight_layout()
    fig.set_size_inches(148, 84)
    plt.savefig('bipartite-graph.png')
def plot_initial_graph(G):
    fig=plt.figure(num=1,figsize=(16,12))
    
    sets=bipartite.sets(G)
    pos=nx.spring_layout(G)
    nx.draw_networkx_nodes(G,pos=pos,nodelist=list(sets[0]),node_color='grey',alpha=0.3)
    nx.draw_networkx_nodes(G,pos=pos,nodelist=list(sets[1]),node_color='gold')
    nx.draw_networkx_labels(G,pos=pos)
    nx.draw_networkx_edges(G,pos=pos,alpha=0.2)
    plt.axis("off")
    plt.show()
Esempio n. 35
0
def answer_two():
    
    B = answer_one()
    employee_nodes, movie_nodes = bipartite.sets(B)
    for node in employee_nodes:
        B.add_node( node, type = "employee")
    for node in movie_nodes:
        B.add_node(node , type = "movie")
    
    
    return B
 def collaboration_weighted_projected_graph(self):
     E = bipartite.sets(self.B)[0]
     P = bipartite.collaboration_weighted_projected_graph(self.B, E)
     self.plot_graph_2(P, 'collaboration_weighted_projected')
     print('collaboration_weighted_projected:number of edges:',
           P.number_of_edges())
     print(P.edges())
     print(list(P.edges(data=True)))
     weights = []
     for i in list(P.edges(data=True)):
         weights.append(i[2]['weight'])
     print(weights)
Esempio n. 37
0
def splitBipartiteGexf(inputGexf, outputGexfPath):
    outputGexfPath = outputGexfPath + os.sep
    jr["input_gexf"] = inputGexf
    jr["outputGexfPath"] = outputGexfPath
    # otuput files
    xgexf = os.path.join(dirname(outputGexfPath),
                         basename(splitext(inputGexf)[0])) + ".x.gexf"
    ygexf = os.path.join(dirname(outputGexfPath),
                         basename(splitext(inputGexf)[0])) + ".y.gexf"

    try:
        graph = nx.readwrite.gexf.read_gexf(inputGexf)
    except:
        throwError("unable to read gexf file")
        return

    # bug in networkx, we need to make the directed graph as undirected
    graph = graph.to_undirected()

    jr["numOfNodes"] = len(graph.nodes())
    jr["numOfEdges"] = len(graph.edges())

    X, Y = bipartite.sets(graph)
    print "biparte.sets..."
    print X
    print Y

    #xgr=project_bipartite_graph(graph,X,"weight")
    xgr = bipartite.generic_weighted_projected_graph(graph, X)
    print "biparte.xgr..."
    print len(xgr.nodes())
    print len(xgr.edges())
    try:
        nx.readwrite.gexf.write_gexf(xgr, xgexf)
    except:
        throwError("unable to write file, path:'" + xgexf + "'")
        return

    #ygr=project_bipartite_graph(graph,Y,"weight")
    ygr = bipartite.generic_weighted_projected_graph(graph, Y)
    print "biparte.ygr..."
    print len(ygr.nodes())
    print len(ygr.edges())
    try:
        nx.readwrite.gexf.write_gexf(ygr, ygexf)
    except:
        throwError("unable to write file, path:'" + ygexf + "'")
        #print sys.exc_info()
    jr['output_gexf'] = [xgexf, ygexf]

    print "nodes in X", xgr.nodes()
    print "edges in X", list(xgr.edges())
    print "nodes in Y", ygr.nodes()
Esempio n. 38
0
def main():
    G = initialize()
    user, business = node_initialize(G)
    user = list(set(user) & set(G.nodes()))
    business = list(set(business) & set(G.nodes()))
    G = make_bipartite(G, user, business)
    print nx.is_bipartite(G)
    G = list(nx.connected_component_subgraphs(G))[0]
    user, business = bipartite.sets(G)
    print "nodes separated"
    Gu = bipartite.projected_graph(G, user)
    print Gu.number_of_nodes()
Esempio n. 39
0
def _getBipartition(G):
   topSet, botSet = bipartite.sets(G)
   topSet, botSet = list(topSet), list(botSet)
   topIndices, botIndices = [], []
   V = G.nodes()
   for i in range(G.order()):
      if V[i] in topSet:
         topIndices.append(i)
      else:
         botIndices.append(i) 
   #print "Computed bipartition."
   return topIndices, botIndices
Esempio n. 40
0
def plot_graph(G):
    X,Y=bipartite.sets(G)
    pos = dict()
    pos.update( (n, (1, i)) for i, n in enumerate(X) ) # put nodes from X at x=1
    pos.update( (n, (2, i)) for i, n in enumerate(Y) ) # put nodes from Y at x=2
    networkx.draw(G, pos=pos, with_labels=False)

    labels = {}
    for node in G.nodes():
        labels[node] = node

    networkx.draw_networkx_labels(G, pos, labels)
    plt.show()
Esempio n. 41
0
def splitBipartiteGexf( inputGexf, outputGexfPath ):
    outputGexfPath = outputGexfPath + os.sep
    jr["input_gexf"] = inputGexf 
    jr["outputGexfPath"] = outputGexfPath
    # otuput files
    xgexf = os.path.join( dirname( outputGexfPath ), basename( splitext( inputGexf )[0] )  )+".x.gexf"
    ygexf = os.path.join( dirname( outputGexfPath ), basename( splitext( inputGexf )[0] )  )+".y.gexf"
        
    try:
        graph = nx.readwrite.gexf.read_gexf( inputGexf );
    except:
        throwError( "unable to read gexf file" )
        return
    
    # bug in networkx, we need to make the directed graph as undirected
    graph=graph.to_undirected()
    
    jr["numOfNodes"] = len( graph.nodes() )
    jr["numOfEdges"] = len( graph.edges() )
    
    X,Y=bipartite.sets(graph)
    print "biparte.sets..."
    print X
    print Y
    
    #xgr=project_bipartite_graph(graph,X,"weight")
    xgr=bipartite.generic_weighted_projected_graph(graph,X)
    print "biparte.xgr..."
    print len(xgr.nodes())
    print len(xgr.edges())
    try:
        nx.readwrite.gexf.write_gexf(xgr, xgexf )
    except:
        throwError( "unable to write file, path:'" + xgexf + "'" )
        return
    
    #ygr=project_bipartite_graph(graph,Y,"weight")
    ygr=bipartite.generic_weighted_projected_graph(graph,Y)
    print "biparte.ygr..."
    print len(ygr.nodes())
    print len(ygr.edges())
    try:
        nx.readwrite.gexf.write_gexf(ygr, ygexf )
    except:
        throwError( "unable to write file, path:'" + ygexf + "'" )
        #print sys.exc_info()
    jr['output_gexf'] = [ xgexf, ygexf ]
    
    print "nodes in X", xgr.nodes()
    print "edges in X", list( xgr.edges() )
    print "nodes in Y", ygr.nodes()
Esempio n. 42
0
def get_bipartite_sets(G):
    complexes, reactions = bipartite.sets(G)

    # some unexpected behaviour that networkx shows:
    # sometimes 'complexes' and 'reactions' get swapped around by bipartite.sets
    # this seems to happen for larger reaction networks

    if 'w1' not in complexes and 'w1' not in reactions:
        raise Exception('my hack to resolve this unexpected behavior shown by bipartite.sets assumes that reaction nodes are named \'w1\', \'w2\', ...')

    if 'w1' in complexes:
        return reactions, complexes
    else:
        return complexes, reactions
Esempio n. 43
0
    def get_check_nodes(self,encoded_Graph):

            cur_src_node_set, cur_encoded_node_set = bipartite.sets(encoded_Graph)
            cur_encoded_node_list = list(cur_encoded_node_set)
            num_recovered_packets = self.total_src_packets - len(cur_src_node_set)

            #find check nodes in the graph
            check_node_list =[]

            for j in cur_encoded_node_list:
                if encoded_Graph.degree(j) == 1 :
                       check_node_list.append(j)
                       #print j

            return check_node_list, num_recovered_packets
Esempio n. 44
0
def draw_graph(G):
    pos=nx.spring_layout(G) # positions for all nodes
    cnodes,unodes = bipartite.sets(G)

    nx.draw_networkx_nodes(G,pos,nodelist=cnodes,node_color='r')
    nx.draw_networkx_nodes(G,pos,nodelist=unodes,node_color='w')
#    nx.draw_networkx_edges(G,pos)

    pos2 = copy.deepcopy(pos)
    for d in pos:
        pos2[d][1] = pos[d][1] - 0.02
    nx.draw_networkx_labels(G,pos2)

    plt.axis('off')
    plt.show()
Esempio n. 45
0
def getDivFieldEdgeWeight_list():
        df_biparG = nx.Graph()
        df_biparG.add_nodes_from([x['div_id'] for x in _league_div], bipartite=0)
        # even through we are using a bipartite graph structure, node names between
        # the column nodes need to be distinct, or else edge (1,2) and (2,1) are not distinguished.
        # instead use edge (1, f2), (2, f1) - use 'f' prefix for field nodes
        df_biparG.add_edges_from([(x['div_id'],'f'+str(y)) for x in _league_div for y in x['divfield_list']])
        div_nodes, field_nodes = bipartite.sets(df_biparG)
        deg_fnodes = {f:df_biparG.degree(f) for f in field_nodes}
        # effective edge sum lists for each division, the sum of the weights of the connected fields;
        # the weights of the associated fields, which are represented as field nodes,
        # are in turn determined by it's degree.  The inverse of the degree for the connected division is
        # taken, which becomes the weight of the particular field associated with the division.  The weights
        # of each field are summed for each division.  The weights also represent the 'total fairness share'
        # of fields associated with a division.
        # Bipartite graph representations, with divisions as one set of nodes, and fields as the other set
        # are used.  Thus a neighbor of a division is always a field.
        edgesum_list = [{'div_id':d, 'edgesum': sum([1.0/deg_fnodes[f] for f in df_biparG.neighbors(d)])}
                                        for d in div_nodes]
        sorted_edgesum_list = sorted(edgesum_list, key=itemgetter('div_id'))
        logging.debug("div fields bipartite graph %s %s effective edge sum for each node %s",
                                    df_biparG.nodes(), df_biparG.edges(), sorted_edgesum_list)

        # depending on the number of teams in each division, the 'fairness share' for each division is adjusted;
        # i.e. a division with more teams is expected to contribute a larger amount to field sharing obligations,
        # such as the number of expected early/late start times for a particular division.  (If one div has 20 teams
        # and the other connected div has only 10 teams, the 20-team division should have a larger share of filling
        # early and late start time games.
        div_indexer = dict((p['div_id'],i) for i,p in enumerate(_league_div))
        # ratio is represented as factor that is multiplied against the 'expected' fair share, which is the 1-inverse
        # of the number of divisions in the connected group - (dividing by the 1-inverse is equiv to multiple by the
        # number of teams - len(connected_list) as shown below)
        divratio_list = [{'div_id':x, 'ratio': len(connected_list)*float(_league_div[div_indexer.get(x)]['totalteams'])/
                                         sum(_league_div[div_indexer.get(y)]['totalteams'] for y in connected_list)}
                                         for connected_list in getConnectedDivisions() for x in connected_list]
        sorted_divratio_list = sorted(divratio_list, key=itemgetter('div_id'))
        # multiply sorted edgesum list elements w. sorted divratio list elements
        # because of the sort all dictionary elements in the list should be sorted according to div_id and obviating
        # need to create an indexerGet function
        # x['div_id'] could have been y['div_id'] in the list comprehension below
        prod_list = [{'div_id': x['div_id'], 'prodratio': x['edgesum']*y['ratio']}
                                 for (x,y) in zip(sorted_edgesum_list, sorted_divratio_list)]
        logging.debug("getDivFieldEdgeWeight: sorted_edge=%s, sorted_ratio=%s, prod=%s",
                                    sorted_edgesum_list, sorted_divratio_list, prod_list)
        # define indexer function object
        prod_indexerGet = lambda x: dict((p['div_id'],i) for i,p in enumerate(prod_list)).get(x)
        List_Indexer = namedtuple('List_Indexer', 'dict_list indexerGet')
        return List_Indexer(prod_list, prod_indexerGet)
Esempio n. 46
0
	def __init__(self, b, num_clusters = 6):
		self.b = b
		self.num_clusters = num_clusters
		# split the graph into it's two partitions
		self.nodes = list(bipartite.sets(b))
		self.mappings = {}

		# NOTE: self.copora[0] consideres each node in self.nodes[0] and makes a bag of songs representation for it's neighbors.
		# i.e self.corpora[0] is what we pass into lda when we want to model the nodes in self.nodes[0] as documents and the nodes in self.nodes[1] as "words"

		self.corpora, self.dicts = self._get_graph_corpora()
		# lda_models[0] would be the lda model where the "documents" are sets of nodes in self.nodes[1]
		self.lda_models = self._train_lda_models()
		# per_cluster_node_distributions[0] is an array of dicts, each dict mapping id->probability for that cluster index
		self.per_cluster_node_distributions = self._find_per_cluster_node_distributions()

		self.per_dnode_cluster_distributions = self._find_per_dnode_cluster_distributions()
Esempio n. 47
0
    def test_convert_graph_to_factor_garph(self):
        variable_nodes = ['x1', 'x2', 'x3', 'x4']
        factor_nodes = ['fa', 'fb', 'fc']

        g = nx.Graph()
        g.add_nodes_from(variable_nodes, bipartite=0)
        g.add_nodes_from(factor_nodes, bipartite=1)
        g.add_edges_from([('x1', 'fa'), ('fa', 'x2'),
                          ('x2', 'fb'), ('fb', 'x3'),
                          ('x2', 'fc'), ('fc', 'x4')])
        bottom_nodes, top_nodes = bipartite.sets(g, variable_nodes)

        fg = graphs.convert_graph_to_factor_graph(g, nodes.VNode, nodes.FNode,
                                                  rv.Discrete)
        vn = {str(n) for n in fg.get_vnodes()}
        fn = {str(n) for n in fg.get_fnodes()}

        self.assertSetEqual(bottom_nodes, vn)
        self.assertSetEqual(top_nodes, fn)
Esempio n. 48
0
File: bd.py Progetto: yawara/gbc
def params_bd(H):
  V, B = bipartite.sets(H)
  
  k = H.degree(list(B)[0])
  r = H.degree(list(V)[0])
  l = len(set(H.neighbors(list(V)[0])).intersection(set(H.neighbors(list(V)[1]))))
  
  dl =  len(set(H.neighbors(list(B)[0])).intersection(set(H.neighbors(list(B)[1]))))
  
  for b in B:
    if k != H.degree(b):
      raise Exception("Failed: REGULARITY")
  for v in V:
    if r != H.degree(v):
      raise Exception("Failed: 1-BALANCE")
  rtv = set([l])
  cnt = 0
  for i, v1 in enumerate(V):
    for j, v2 in enumerate(V):
      if i < j:
        common_neighbors = set(H.neighbors(v1)).intersection(set(H.neighbors(v2)))
        la = len(common_neighbors)
        print(v1,v2)
        print(common_neighbors)
        print(la)
        if l != la:
          print("Failed: 2-BALANCE")
          cnt += 1
          rtv.add(la)
        print("")
  print(rtv)
  print(cnt)
  
  for i, b1 in enumerate(B):
    for j, b2 in enumerate(B):
      if i < j:
        inter_block = set(H.neighbors(b1)).intersection(set(H.neighbors(b2)))
        dla = len(inter_block)
        if dl != dla:
          raise Exception("Failed: DUAL 2-BALANCE")
  
  return k, r, l, dl
def plot_initial_bgraph(G,subp=121):
    fig=plt.figure(num=1,figsize=(16,12))
    fig.add_subplot(subp)
    sets=bipartite.sets(G)
    pos={}
    for i,v in enumerate(sets[0]):
        pos[v]= (0.,i)
    for i,v in enumerate(sets[1]):
        pos[v]= (1, i)

    rr=nx.attribute_assortativity_coefficient(G,'bipartite')
    s_title='Bipartite Graph\nAssortativity_coef(bipartition) = %.2f' %rr
    plt.title(s_title)#,{'size': '20'})
    nx.draw_networkx_nodes(G,pos=pos,nodelist=list(sets[0]),node_color='grey',alpha=0.3)
    nx.draw_networkx_nodes(G,pos=pos,nodelist=list(sets[1]),node_color='gold')
    nx.draw_networkx_labels(G,pos=pos)
    nx.draw_networkx_edges(G,pos=pos,alpha=0.2)
    plt.axis("off")
    # plt.show()  
    return pos,fig
    def getRandomBPG(l, m, prob=0.03):
        g = nx.bipartite_random_graph(l, m, prob)
        orig = g.copy()
        print "%d %d %f" % (l, m, prob)
        # print "before: edges:%d" % len(g.edges())

        count = 0
        maxcount = CustomData.numAnomEdges(l + m)
        l, r = bipartite.sets(g)
        anom = l.pop()

        # print "adding %d anom edges" % maxcount

        for i in r:
            if not g.has_edge(anom, i) and count < maxcount:
                g.add_edge(anom, i)
                count += 1

        # print "after: edges:%d" % len(g.edges())

        return orig, g
Esempio n. 51
0
def splitBipartiteGexf( inputGexf, outputGexfPath ):
	outputGexfPath = outputGexfPath + os.sep
	jr["input_gexf"] = inputGexf 
	jr["outputGexfPath"] = outputGexfPath
	# otuput files
	xgexf = os.path.join( dirname( outputGexfPath ), basename( splitext( inputGexf )[0] )  )+".x.gexf"
	ygexf = os.path.join( dirname( outputGexfPath ), basename( splitext( inputGexf )[0] )  )+".y.gexf"
		
	try:
		graph = nx.readwrite.gexf.read_gexf( inputGexf );
	except:
		throwError( "unable to read gexf file" )
		return
	
	jr["numOfNodes"] = len( graph.nodes() )
	jr["numOfEdges"] = len( graph.edges() )
	
	X,Y=bipartite.sets(graph)
	# print "biparte.sets...";
	# print X
	# print Y
	
	xgr=project_bipartite_graph(graph,X,"weight")
	# print "biparte.xgr...";
	try:
		nx.readwrite.gexf.write_gexf(xgr, xgexf )
	except:
		throwError( "unable to write file, path:'" + xgexf + "'" )
		return
	
	ygr=project_bipartite_graph(graph,Y,"weight")
	try:
		nx.readwrite.gexf.write_gexf(ygr, ygexf )
	except:
		throwError( "unable to write file, path:'" + ygexf + "'" )
		#print sys.exc_info()
	jr['output_gexf'] = [ xgexf, ygexf ]
Esempio n. 52
0
def plotBipartiteGraph(graph, color1="r", color2="b", figsize=(12, 8), layout="neato"):
 
    labels = {n:n for n in graph.nodes()}
    
    d = nx.degree_centrality(graph)
    
    # layout=nx.spring_layout
    # pos=layout(graph)
    pos = nx.drawing.nx_agraph.graphviz_layout(graph,prog=layout)

    bot_nodes, top_nodes = bipartite.sets(graph)

    plt.figure(figsize=figsize)
    plt.subplots_adjust(left=0,right=1,bottom=0,top=0.95,wspace=0.01,hspace=0.01)
    
    # nodes
    nx.draw_networkx_nodes(graph,pos,
                            nodelist=bot_nodes,
                            node_color=color1,
                            node_size=[v * 350 for v in d.values()],
                            alpha=0.8)
    nx.draw_networkx_nodes(graph,pos,
                            nodelist=top_nodes,
                            node_color=color2,
                            node_size=[v * 350 for v in d.values()],
                            alpha=0.8)
    
    nx.draw_networkx_edges(graph,pos,
                           with_labels=True,
                           edge_color=color1,
                           width=1.0
                        )
    
    if graph.order() < 1000:
        nx.draw_networkx_labels(graph,pos, labels)
        
    return plt
Esempio n. 53
0
 def test_bipartite_density(self):
     G=nx.path_graph(5)
     X,Y=bipartite.sets(G)
     density=float(len(G.edges()))/(len(X)*len(Y))
     assert_equal(bipartite.density(G,X),density)
G=nx.Graph() #Two-Level Graph
for node in J.nodes():
    G.add_node(node,bipartite=0)
for edge in J.edges():
    G.add_edge(edge[0],edge[1])
for edge in F.edges():
    G.add_edge(edge[0]+5,edge[1]+5)
for node in F.nodes():
    G.add_node(node+5,bipartite=1)
for edge in H.edges(data=True):
    G.add_edge(edge[0],edge[1])

posJ=nx.spring_layout(J)
posF=nx.spring_layout(F)
posH={0:(0,0),1:(0,2),2:(0,4),3:(0,6),4:(0,8),5:(1,-2),6:(1,0),7:(1,2),8:(1,4),9:(1,6),10:(1,8)}
mode1, mode2 = bipartite.sets(H)
pos=nx.spring_layout(G)
top_set=set()
botom_set=set()
for i in pos:
    npos=pos[i]
    if G.node[i]['bipartite']==0:
        pos[i]=[npos[0],npos[1]+2]
        top_set.add(i)
    elif G.node[i]['bipartite']==1:
        pos[i]=[npos[0],npos[1]-2]
        botom_set.add(i)
'''
plt.figure()
nx.draw(J,pos=posJ,node_color='r',node_size=700,font_size=20,font_color='#FFFFFF',with_labels=False)
nx.draw_networkx_labels(J,posJ,directors,font_size=20,font_color='#FFFFFF')
Esempio n. 55
0
 def test_bipartite_sets(self):
     G=nx.path_graph(4)
     X,Y=bipartite.sets(G)
     assert_equal(X,set([0,2]))
     assert_equal(Y,set([1,3]))
Esempio n. 56
0
remove = [node for node,degree in B.degree().items() if degree == 0]
B.remove_nodes_from(remove)
#print remove
  
for node,degree in (B.degree().items()):
  if (degree == 0):
    #print node
    B.remove_node(node)
  


#print(bipartite.is_bipartite(B))  

Sif(B,"Bipartita_MEF2e")

bottom_nodes, top_nodes = bipartite.sets(B)


pos=nx.spring_layout(B)
#pos=nx.shell_layout(B)
#pos=nx.spectral_layout(B)
#pos=nx.random_layout(B)


nx.draw_networkx_nodes(B,pos,nodelist=bottom_nodes,node_shape='o',node_color='r', node_size=100) #proces
nx.draw_networkx_nodes(B,pos,nodelist=top_nodes,node_shape='p',node_color='y', node_size=450) #coms
nx.draw_networkx_edges(B,pos, edge_color='gray')
nx.draw_networkx_labels(B, pos,font_size=7, font_color='k')

plt.show()
Esempio n. 57
0
    def getPartitionings(self):
        partitionings = [list(bipartite.sets(subG))\
            for subG in nx.connected_component_subgraphs(self.g)]

        return partitionings
    color[n]=get_rgb_from_hue_spectrum(a[n]/a[max(a)], 0.3, 0.0)
    pc.append(a[n]/a[max(a)])
nx.set_node_attributes(G, 'color', color)

plt.clf()
fig = plt.Figure()
fig.set_canvas(plt.gcf().canvas)
pos = nx.spring_layout(g)
nx.draw_networkx_nodes(G, pos, node_size=600,node_color=pc ,cmap=plt.get_cmap('jet'),labels=G.nodes())#,,
nx.draw_networkx_labels(G,pos,font_size=14)
nx.draw_networkx_edges(G, pos, edge_color='b', arrows=True)
nx.draw_networkx_edges(G,pos,font_size=14)

plt.savefig('directed_Network_2.pdf',bbox_inches="tight")

banks , sov = bipartite.sets(B)
pos = dict()
pos.update( (n, (1, i)) for i, n in enumerate(banks) ) # put nodes from X at x=1
pos.update( (n, (2, i)) for i, n in enumerate(sov) ) # put nodes from Y at x=2
col= []
for n, d in B.nodes_iter(data=True):
   col.append(d['bipartite'])
   col[col==1]=='b'
   col[col==0]=='g'
   


fig = plt.Figure()
fig.set_canvas(plt.gcf().canvas)
nx.draw_networkx_nodes(B, pos, node_size=200,node_color=col ,cmap=plt.get_cmap('jet'),labels=B.nodes())#,,
nx.draw_networkx_labels(B,pos,font_size=10)
Esempio n. 59
0
    def _get_cosine_network_graph(self, ions_of_interest, clustering, peak_names):

        ions_of_interest_clustering = []
        for item in ions_of_interest:
            pos = peak_names.index(item)
            cl = clustering[pos]
            ions_of_interest_clustering.append(cl)
        ions_of_interest_clustering = np.array(ions_of_interest_clustering)

        # Create the networkx graph object.
        # Clusters with fewer than min_size_to_plot members are not plotted
        min_size_to_plot = 4
        node_no = 0
        G = nx.Graph()
        uc = np.unique(clustering)
        cluster_nodes = {}
        singleton_clusters = []
        cluster_interests = {}
        for cluster in uc:
            # check cluster size
            members = np.where(clustering == cluster)[0]
            if len(members) < min_size_to_plot:
                # print "Not plotting cluster %d with %d members." % (cluster, len(members))
                singleton_clusters.append(cluster)
                continue
            # append to graph
            cluster_nodes[cluster] = node_no
            G.add_node(node_no, bipartite=0, name=cluster)
            node_no += 1
            # also print out the ions of interest in this cluster
            interest_members = np.where(ions_of_interest_clustering == cluster)[0]
            if len(interest_members) > 0:
                cluster_interests[cluster] = []
                for idx in interest_members:
                    tokens = ions_of_interest[idx].split('_')
                    pid = int(tokens[2])
                    cluster_interests[cluster].append(pid)

        peak_nodes = {}
        for i,name in enumerate(peak_names):
            this_cluster = clustering[i]
            if this_cluster in cluster_nodes:
                peak_nodes[name] = node_no
                G.add_node(node_no,bipartite=1, name=name)
                G.add_edge(node_no,cluster_nodes[clustering[i]])
                node_no += 1

        # Position the clusters in a grid, and their members in circle coming out from the cluster.
        # cstep determines the distance between grid points.
        # If you want cluster members closer to the cluster centers, change the 0.75 in
        # the x_pos and y_pos lines
        C,P = bipartite.sets(G)
        n_clusters = len(C)
        n_rows = np.ceil(np.sqrt(n_clusters))
        pos = {}
        current_row = 0
        current_col = 0
        cstep = 2.0
        for c in C:
            n_list = G.neighbors(c)
            pos[c] = [cstep*current_row,cstep*current_col]
            # find neighbours
            step = 2*np.pi/len(n_list)
            angle = 0.0
            for n in n_list:
                x_pos = 0.75*np.sin(angle)
                y_pos = 0.75*np.cos(angle)
                pos[n] = [pos[c][0]+x_pos,pos[c][1]+y_pos]
                angle += step
            current_col += 1
            if current_col >= n_rows:
                current_col = 0
                current_row += 1

        return C, P, G, pos, peak_nodes, cluster_interests
Esempio n. 60
0
numEdges = int(nodesAndEdges[1])

# adds nodes
for i in range(1, numNodes + 1):
	G.add_node(str(i))

# adds edges
for i in range(0, numEdges):
	temp = inputFile.readline().strip().split(" ")
	node1 = temp[0]
	node2 = temp[1]
	G.add_edge(node1, node2)

# if the graph is bipartite, we can easily find the optimal soltuion
if nx.is_bipartite(G):
	top_nodes, bottom_nodes = bipartite.sets(G)
	partition1 = list(top_nodes)
	partition2 = list(bottom_nodes)
	maxEdgeCount = 0
	for i in range(0, len(partition1)):
		maxEdgeCount += len(G.neighbors(partition1[i]))

# If it's not bipartite, we must start attempting to find the optimal solution
else:
	graph_dict = dict()
	sorted_graph_dict = dict()
	for i in G.nodes():
		graph_dict[i] = G.neighbors(str(i))
		sorted_graph_dict[i] = G.neighbors(str(i))

	maxEdgeCount = 0