def qbsolv_response_to_community()

in src/qubo_community.py [0:0]


def qbsolv_response_to_community(nx_G, response_sample, k):
    """
    Extract communities from QBSolv responses and calculate its modularity

    :param nx_G: networkX graph
    :param response_sample: QBSolv responses
    :param k: int, the number of communities to detect for the graph nx_G
    :return: dict, a dictionary of node sets as community groups and the graph modularity
    """

    num_nodes = nx_G.number_of_nodes()

    # Split result out into binary assignments within each community
    result = response_sample.squeeze()
    result = result.reshape(k, num_nodes)

    # Extract node IDs belonging to each community, based on results
    communities = []
    for i in range(k):
        node_c = np.where(result[i] == 1)[0]
        if len(node_c) > 0:
            communities.append(set(node_c))

    # Check if there is multi-community assignment for a node or a node without community assignment
    for i in range(num_nodes):
        if result[:, i].sum() > 1:
            raise ValueError('Multi-community assignment!')
            break
        if result[:, i].sum() == 0:
            raise ValueError('Node without community assignment!')
            break
    
    # Order communities according to lowest-ID nodes in each set, ascending order
    communities.sort(key=min)

    modu = community.modularity(nx_G, communities)
    k = len(communities)  # in case any communities returned no hits

    return {"modularity": modu, "num_comm": k, "comm": communities}