import networkx


def calc_cohesion( g, sg0, sg1, max_csize ) :
    """
    Cohesion score is defined as the sum of similarity scores of all boundary edges between two subgraphs.
    But if the sum of number of nodes of the two subgraphs is greater than C{max_csize}, the score is zero.

    @type          g: C{networkx.Graph}
    @param         g: Original graph
    @type        sg0: C{networkx.Graph}
    @param       sg0: First subgraph
    @type        sg1: C{networkx.Graph}
    @param       sg1: Second subgraph
    @type  max_csize: C{float}
    @param max_csize: Maximum size of a cluster
    
    @return: Cohesion score between the two subgraphs.
    """
    score = 0.0
    n0    = len( sg0 )
    n1    = len( sg1 )
    if (n0 + n1 <= max_csize) :
        boundary_edges = networkx.edge_boundary( g, sg0, sg1 )
        for e in boundary_edges :
            score += g[e[0]][e[1]]["similarity"]
    return score / max( n0, n1 )