Search code examples
python-2.7igraphnetworkxbipartitesna

Weighted Bimodal Bipartite Graph Projection conserving original weights


I have a large ( 36k vertices, 50k edges ) weighted bimodal bipartite graph and I would like to generate a projection that not only count the neighbors like the default weighted implementation but also sum the weights on the edges. You can think of it as a bipartite graph containing black vertices and blue vertices, where I want to conserve the original graph weights when there are only blue vertices.

enter image description here

The implementations I came across keep the orange value, I am interested on the red one (or hopefully get a bi-weighted projection).

I've looked so far in igraph, networkx and python-tool but in so far I only observed the projection counting the amount of edges.

Networkx method generic_weighted_projected_graph(B, nodes, weight_function=None) may make this viable but I can't see how (sna is new to me, although I am an so so python user).


Solution

  • There is an example in the documentation you reference at https://networkx.github.io/documentation/latest/reference/generated/networkx.algorithms.bipartite.projection.generic_weighted_projected_graph.html of how to do exactly this.

    It goes like this:

    import networkx as nx
    from networkx.algorithms import bipartite
    
    edges = [('A1','B1',3),
             ('A1','B2',7),
             ('A2','B1',2),
             ('A2','B2',4),
             ]
    
    B = nx.Graph()
    B.add_weighted_edges_from(edges)
    
    def my_weight(G, u, v, weight='weight'):
        w = 0
        for nbr in set(G[u]) & set(G[v]):
            w += G.edge[u][nbr].get(weight, 1) + G.edge[v][nbr].get(weight,1)
        return w
    
    G = bipartite.generic_weighted_projected_graph(B, ['A1', 'A2'], weight_function=my_weight)
    
    
    print G.edges(data=True)
    

    output

    [('A1', 'A2', {'weight': 16})]