Merge networks into a larger network.

    A naive implementation for merging two networks in edgelist format.

    Parameters
    ---------
    output_file : file, str, or pathlib.Path, optional
        The output file to write the merged network into. Default is
        merged_network.txt
    `*files` : file, str or pathlib.Path
        The network files to merge.

    Note
    ----
    The partitioning step doesn't mind redundant
    edges and handles them pretty well, so if you are not
    using the merged edgelist for anything else you can just
    concatenate the edgelists without using this function.

def merge_networks(output_file="merged_network.txt", *files):
    """Merge networks into a larger network.

    A naive implementation for merging two networks in edgelist format.

    Parameters
    ---------
    output_file : file, str, or pathlib.Path, optional
        The output file to write the merged network into. Default is
        merged_network.txt
    `*files` : file, str or pathlib.Path
        The network files to merge.

    Note
    ----
    The partitioning step doesn't mind redundant
    edges and handles them pretty well, so if you are not
    using the merged edgelist for anything else you can just
    concatenate the edgelists without using this function.
    """

    contacts = dict()
    for network_file in files:
        with open(network_file) as network_file_handle:
            for line in network_file_handle:
                id_a, id_b, n_contacts = line.split("\t")
                pair = sorted((id_a, id_b))
                try:
                    contacts[pair] += n_contacts
                except KeyError:
                    contacts[pair] = n_contacts

    sorted_contacts = sorted(contacts)
    with open(output_file, "w") as output_handle:
        for index_pair in sorted_contacts:
            id_a, id_b = index_pair
            n_contacts = contacts[index_pair]
            output_handle.write("{}\t{}\t{}\n".format(id_a, id_b, n_contacts))