def compute_modularity_from_matrix(g, B, communities):
    """
        Computes the modularity (a scalar) from a modularity matrix and a labeling of each node
         and it's community. g is a networkx graph, B is a modularity matrix, and communities is
         a list of lists, which each sub-list containing a list of nodes within that community.
    """
    total_weight = 0.0
    for n1, n2 in g.edges():
        total_weight += g[n1][n2]['weight']
    node2comm = dict()
    for k, comm in enumerate(communities):
        for n in comm:
            node2comm[n] = k
    modularity = 0.0
    for i, n1 in enumerate(g.nodes()):
        for j, n2 in enumerate(g.nodes()):
            if node2comm[n1] == node2comm[n2]:
                modularity += B[i, j]
    if not type(g).__name__ == 'DiGraph':
        modularity /= 2 * total_weight
    return modularity
