Skip to content

Mobile genetic elements

metator.mge clusters the contigs of mobile genetic elements (MGEs), from their contacts, and metator.host finds the MAGs that host each MGE cluster. See Clustering mobile genetic elements.

metator.mge

Cluster the contigs of a .metacool map that are mobile genetic elements.

The MGE contigs are clustered from their Hi-C contacts: those the map holds between two contigs, and those its QC block counts within each contig, between reads at least 1001 bp apart.

check_mge_map

check_mge_map(metacool, mc)

Refuse a map that mge cannot cluster the MGE contigs of, before any work.

The contacts within an MGE contig are its reads at least 1001 bp apart, which only the map's QC block, measured from the pairs, gives; its pixels do not (see check_mge_qc).

Parameters:

Name Type Description Default
metacool str

Path to the .metacool file, or URI of an entry of a .mmetacool collection: file.mmetacool::entries/<name>.

required
mc MetaCooler

The map, opened.

required

Raises:

Type Description
MetacoolError

If the map holds no contact statistics of its pairs, has them measured from its pixels or at another distance than 1001 bp, or lacks the columns of metator network: the reason, and how to make a map that mge reads.

Source code in src/metator/mge.py
def check_mge_map(metacool, mc):
    """Refuse a map that mge cannot cluster the MGE contigs of, before any work.

    The contacts within an MGE contig are its reads at least 1001 bp apart,
    which only the map's QC block, measured from the pairs, gives; its pixels
    do not (see check_mge_qc).

    Parameters
    ----------
    metacool : str
        Path to the .metacool file, or URI of an entry of a .mmetacool
        collection: ``file.mmetacool::entries/<name>``.
    mc : metacooler.MetaCooler
        The map, opened.

    Raises
    ------
    metator.metacool.MetacoolError
        If the map holds no contact statistics of its pairs, has them measured
        from its pixels or at another distance than 1001 bp, or lacks the
        columns of metator network: the reason, and how to make a map that mge
        reads."""
    check_mge_qc(metacool, mc)
    with mtmc.read_errors(metacool):
        columns = set(mc.contigs.columns)
    missing = [column for column in MGE_COLUMNS if column not in columns]
    if missing:
        raise mtmc.MetacoolError(
            f"{metacool} lacks the {' and '.join(missing)} column(s) of its contigs table that metator network "
            f"stores: {WHERE_THE_NETWORK_IS}"
        )

check_mge_qc

check_mge_qc(metacool, mc)

Refuse a map without the contact statistics that mge counts the contacts within each MGE contig from: its QC block, measured from the pairs at 1001 bp, with the counts of each contig (see check_mge_map).

Parameters:

Name Type Description Default
metacool str

Path to the .metacool file, or URI of an entry of a .mmetacool collection: file.mmetacool::entries/<name>.

required
mc MetaCooler

The map, opened.

required

Raises:

Type Description
MetacoolError

If the map holds no contact statistics of its pairs, or has them measured from its pixels or at another distance than 1001 bp: the reason, and how to make a map that mge reads.

Source code in src/metator/mge.py
def check_mge_qc(metacool, mc):
    """Refuse a map without the contact statistics that mge counts the contacts
    within each MGE contig from: its QC block, measured from the pairs at 1001
    bp, with the counts of each contig (see check_mge_map).

    Parameters
    ----------
    metacool : str
        Path to the .metacool file, or URI of an entry of a .mmetacool
        collection: ``file.mmetacool::entries/<name>``.
    mc : metacooler.MetaCooler
        The map, opened.

    Raises
    ------
    metator.metacool.MetacoolError
        If the map holds no contact statistics of its pairs, or has them
        measured from its pixels or at another distance than 1001 bp: the
        reason, and how to make a map that mge reads."""
    with mtmc.read_errors(metacool):
        qc = mc.metadata.get("qc")
        columns = set(mc.contigs.columns)
    if not isinstance(qc, dict) or INTRA_LONG not in columns:
        raise mtmc.MetacoolError(
            f"{metacool} holds no contact statistics of the reads of its contigs (metacooler's QC block, with "
            f"{INTRA_LONG} in its contigs table): metator mge counts the contacts within each MGE contig between reads "
            f"more than 1 kb apart, which the pixels of a map do not tell. {HOW_TO_MAKE_A_MAP}"
        )
    if qc.get("source") != QC_SOURCE:
        raise mtmc.MetacoolError(
            f"{metacool} has the contact statistics of its contigs measured from its pixels (QC source "
            f"{qc.get('source')!r}), not from the pairs: metator mge counts the contacts within each MGE contig "
            f"between reads more than 1 kb apart, which the pixels of a map do not tell. {HOW_TO_MAKE_A_MAP}"
        )
    if qc.get("distance_threshold") != DISTANCE_THRESHOLD:
        raise mtmc.MetacoolError(
            f"{metacool} splits the contacts within a contig at {qc.get('distance_threshold')} bp (its QC "
            f"distance_threshold): metator mge counts those between reads more than 1 kb apart, at "
            f"{DISTANCE_THRESHOLD} bp and more. {HOW_TO_MAKE_A_MAP}"
        )

check_contig_map

check_contig_map(metacool, mc, mges_list)

Refuse, before any work, the map of the contigs of a run that clusters its MGE contigs once it has stored its network and its clusters there (metator pipeline --mges, in its step mge): a map that mge would refuse then for want of the contact statistics of its reads (see check_mge_qc), not of the columns of metator network, which the run stores first, and a map that holds none of the MGE contigs (see mge_contigs). The map of the clusters has the contigs of the map of the contigs, under the same names, and its contact statistics, which metacooler carries over as it groups the contigs by cluster.

Parameters:

Name Type Description Default
metacool str

Path to the .metacool file, or URI of an entry of a .mmetacool collection: file.mmetacool::entries/<name>.

required
mc MetaCooler

The map, opened.

required
mges_list list of str

Names of the MGE contigs (see metator.io.import_mges_contigs).

required

Raises:

Type Description
MetacoolError

If the map has no contact statistics that mge reads, or holds none of the MGE contigs.

Source code in src/metator/mge.py
def check_contig_map(metacool, mc, mges_list):
    """Refuse, before any work, the map of the contigs of a run that clusters
    its MGE contigs once it has stored its network and its clusters there
    (metator pipeline --mges, in its step mge): a map that mge would refuse then
    for want of the contact statistics of its reads (see check_mge_qc), not of
    the columns of metator network, which the run stores first, and a map that
    holds none of the MGE contigs (see mge_contigs). The map of the clusters
    has the contigs of the map of the contigs, under the same names, and its
    contact statistics, which metacooler carries over as it groups the contigs
    by cluster.

    Parameters
    ----------
    metacool : str
        Path to the .metacool file, or URI of an entry of a .mmetacool
        collection: ``file.mmetacool::entries/<name>``.
    mc : metacooler.MetaCooler
        The map, opened.
    mges_list : list of str
        Names of the MGE contigs (see metator.io.import_mges_contigs).

    Raises
    ------
    metator.metacool.MetacoolError
        If the map has no contact statistics that mge reads, or holds none of
        the MGE contigs."""
    check_mge_qc(metacool, mc)
    with mtmc.read_errors(metacool):
        names = set(mc.contigs["name"].astype(str))
    if not names & set(mges_list):
        raise _no_mge_contig(metacool)

mge_contigs

mge_contigs(metacool, mc, mges_list)

The MGE contigs of a map, the longest first (ties by name), with the values of each that mge reads.

Longest first, ties by name: resolve_matrix breaks ties and update_mge_data numbers single-contig clusters in that order, so the result depends on neither the map's order nor its clusters.

Parameters:

Name Type Description Default
metacool str

Path to the .metacool file, or URI of an entry of a .mmetacool collection: file.mmetacool::entries/<name>.

required
mc MetaCooler

The map, opened (see check_mge_map).

required
mges_list list of str

Names of the MGE contigs (see metator.io.import_mges_contigs).

required

Returns:

Type Description
DataFrame

One row per MGE contig of the map, the longest first, ties by name: Name, Size (its length), GC_content and Hit (as metator network stored them).

ndarray

Their positions in the map, from 0, in that order.

ndarray

The contacts within each, between reads more than 1 kb apart (its qc_intra_contig_long).

Raises:

Type Description
MetacoolError

If none of the MGE contigs is in the map: there is nothing to cluster.

Source code in src/metator/mge.py
def mge_contigs(metacool, mc, mges_list):
    """The MGE contigs of a map, the longest first (ties by name), with the values
    of each that mge reads.

    Longest first, ties by name: resolve_matrix breaks ties and update_mge_data
    numbers single-contig clusters in that order, so the result depends on
    neither the map's order nor its clusters.

    Parameters
    ----------
    metacool : str
        Path to the .metacool file, or URI of an entry of a .mmetacool
        collection: ``file.mmetacool::entries/<name>``.
    mc : metacooler.MetaCooler
        The map, opened (see check_mge_map).
    mges_list : list of str
        Names of the MGE contigs (see metator.io.import_mges_contigs).

    Returns
    -------
    pandas.DataFrame
        One row per MGE contig of the map, the longest first, ties by name:
        Name, Size (its length), GC_content and Hit (as metator network stored
        them).
    numpy.ndarray
        Their positions in the map, from 0, in that order.
    numpy.ndarray
        The contacts within each, between reads more than 1 kb apart (its
        qc_intra_contig_long).

    Raises
    ------
    metator.metacool.MetacoolError
        If none of the MGE contigs is in the map: there is nothing to cluster."""
    with mtmc.read_errors(metacool):
        contigs = mc.contigs
    names = contigs["name"].astype(str)
    in_map = set(names)
    missing = [name for name in dict.fromkeys(mges_list) if name not in in_map]
    if missing:
        logger.warning(
            f"{len(missing)} MGE contig(s) are not in {metacool}: they are left out of the MGE clusters: {mtmc._shown(missing)}."
        )
    positions = np.flatnonzero(names.isin(set(mges_list)).to_numpy())
    if not len(positions):
        raise _no_mge_contig(metacool)
    # The longest first, ties by name: whatever the order of the map.
    lengths = contigs["length"].to_numpy(dtype=np.int64)[positions]
    positions = positions[np.lexsort((names.to_numpy()[positions], -lengths))]
    selected = contigs.iloc[positions]
    data = pd.DataFrame(
        {
            "Name": names.iloc[positions].to_numpy(),
            "Size": selected["length"].to_numpy(dtype=np.int64),
            "GC_content": selected["GC_content"].to_numpy(dtype=np.float64),
            "Hit": selected["Hit"].to_numpy(dtype=np.int64),
        }
    )
    return data, positions, selected[INTRA_LONG].to_numpy(dtype=np.int64)

map_matrix

map_matrix(metacool, n_contigs, positions, intra)

The contacts of the MGE contigs of a map, as resolve_matrix reads them: the matrix of their raw contacts, in the order of positions.

Only the upper triangle is filled, which resolve_matrix reads.

Parameters:

Name Type Description Default
metacool str

Path to the .metacool file, or URI of an entry of a .mmetacool collection: file.mmetacool::entries/<name>.

required
n_contigs int

Number of contigs of the map.

required
positions ndarray

Positions in the map of the MGE contigs, from 0, in the order of the matrix (see mge_contigs).

required
intra ndarray

Contacts within each, between reads more than 1 kb apart.

required

Returns:

Type Description
ndarray

Raw matrix of contacts between the MGE contigs.

Source code in src/metator/mge.py
def map_matrix(metacool, n_contigs, positions, intra):
    """The contacts of the MGE contigs of a map, as resolve_matrix reads them: the
    matrix of their raw contacts, in the order of positions.

    Only the upper triangle is filled, which resolve_matrix reads.

    Parameters
    ----------
    metacool : str
        Path to the .metacool file, or URI of an entry of a .mmetacool
        collection: ``file.mmetacool::entries/<name>``.
    n_contigs : int
        Number of contigs of the map.
    positions : numpy.ndarray
        Positions in the map of the MGE contigs, from 0, in the order of the
        matrix (see mge_contigs).
    intra : numpy.ndarray
        Contacts within each, between reads more than 1 kb apart.

    Returns
    -------
    numpy.ndarray
        Raw matrix of contacts between the MGE contigs."""
    import metator.network as mtn

    network = mtn.map_network(metacool, None)
    index = np.full(n_contigs, -1, dtype=np.int64)
    index[positions] = np.arange(len(positions))
    # IDs from 1; each pair of contigs once, in the upper triangle of the
    # matrix whatever their order in the map.
    i = index[network["contig1"].to_numpy() - 1]
    j = index[network["contig2"].to_numpy() - 1]
    between = (i >= 0) & (j >= 0)
    i, j = i[between], j[between]
    mat = np.zeros((len(positions), len(positions)))
    mat[np.minimum(i, j), np.maximum(i, j)] = network["weight"].to_numpy()[between]
    mat[np.arange(len(positions)), np.arange(len(positions))] = intra
    return mat

generate_bin_summary

generate_bin_summary(contigs_data: DataFrame, mge_bins: dict) -> pd.DataFrame

The summary of the MGE clusters: one row per cluster, with its length, GC content, hits, clustering score and contigs.

Parameters:

Name Type Description Default
contigs_data DataFrame

The MGE contigs (see mge_contigs): Name, Size, GC_content and Hit.

required
mge_bins dict

Dictionary with the mge bin id as key and its contigs ("Contigs") and score ("Score") as value.

required

Returns:

Type Description
DataFrame

One row per cluster, in the order of mge_bins: BinName (MetaTOR_MGE_<ID>), BinLength, GC, Hit, BinningScore, ContigsNumber and Contigs (by name, comma-separated).

Source code in src/metator/mge.py
def generate_bin_summary(contigs_data: "pd.DataFrame", mge_bins: dict) -> "pd.DataFrame":
    """The summary of the MGE clusters: one row per cluster, with its length, GC
    content, hits, clustering score and contigs.

    Parameters
    ----------
    contigs_data : pd.DataFrame
        The MGE contigs (see mge_contigs): Name, Size, GC_content and Hit.
    mge_bins : dict
        Dictionary with the mge bin id as key and its contigs ("Contigs") and
        score ("Score") as value.

    Returns
    -------
    pandas.DataFrame
        One row per cluster, in the order of mge_bins: BinName
        (``MetaTOR_MGE_<ID>``), BinLength, GC, Hit, BinningScore, ContigsNumber and
        Contigs (by name, comma-separated).
    """
    # Create output empty DataFrame
    cols = {
        "BinName": pd.Series(dtype="str"),
        "BinLength": pd.Series(dtype="int"),
        "GC": pd.Series(dtype="float"),
        "Hit": pd.Series(dtype="int"),
        "BinningScore": pd.Series(dtype="float"),
        "ContigsNumber": pd.Series(dtype="int"),
        "Contigs": pd.Series(dtype="str"),
    }

    summary = pd.DataFrame(cols, index=list(mge_bins))
    contigs_data = contigs_data.set_index("Name", drop=False)
    # Iterates on the bins to fill the table.
    for bin_id in mge_bins.keys():
        summary.loc[bin_id, "BinName"] = f"MetaTOR_MGE_{bin_id:05d}"
        contigs = mge_bins[bin_id]["Contigs"]
        summary.loc[bin_id, "ContigsNumber"] = int(f"{len(contigs):1d}")
        summary.loc[bin_id, "Contigs"] = ",".join(contigs)
        summary.loc[bin_id, "BinningScore"] = mge_bins[bin_id]["Score"]
        length, hit, gc = 0, 0, 0
        for contig in contigs:
            length += contigs_data.loc[contig, "Size"]
            hit += contigs_data.loc[contig, "Hit"]
            gc += contigs_data.loc[contig, "GC_content"] * contigs_data.loc[contig, "Size"]
        summary.loc[bin_id, "BinLength"] = int(f"{length:1d}")
        summary.loc[bin_id, "Hit"] = int(f"{hit:1d}")
        summary.loc[bin_id, "GC"] = gc / length
    return summary.reset_index(drop=True)

mge_binning

mge_binning(
    metacool: str,
    mges_list: List[str],
    threshold_bin: float = 0.8,
    random: bool = False,
) -> Tuple[pd.DataFrame, dict]

Main function to cluster the MGE contigs of a map.

Parameters:

Name Type Description Default
metacool str

Path to the .metacool file, or URI of an entry of a .mmetacool collection: file.mmetacool::entries/<name>: a map that metator network stored the network of its contigs in (that of a run of network, pipeline or validation).

required
mges_list list of str

Names of the MGE contigs.

required
threshold_bin float

Threshold of score to bin contigs.

0.8
random bool

If enabled, make a random shuffling of the bins.

False

Returns:

Type Description
DataFrame

The summary of the MGE clusters (see generate_bin_summary).

dict

The MGE clusters: their id as key, their contigs ("Contigs", the longest first, ties by name: see mge_contigs) and score ("Score") as value.

Raises:

Type Description
MetacoolError

If the map cannot be read, cannot be clustered (see check_mge_map), or holds none of the MGE contigs.

Source code in src/metator/mge.py
def mge_binning(
    metacool: str,
    mges_list: List[str],
    threshold_bin: float = 0.8,
    random: bool = False,
) -> Tuple[pd.DataFrame, dict]:
    """Main function to cluster the MGE contigs of a map.

    Parameters
    ----------
    metacool : str
        Path to the .metacool file, or URI of an entry of a .mmetacool
        collection: ``file.mmetacool::entries/<name>``: a map that metator
        network stored the network of its contigs in (that of a run of network,
        pipeline or validation).
    mges_list : list of str
        Names of the MGE contigs.
    threshold_bin : float
        Threshold of score to bin contigs.
    random : bool
        If enabled, make a random shuffling of the bins.

    Returns
    -------
    pandas.DataFrame
        The summary of the MGE clusters (see generate_bin_summary).
    dict
        The MGE clusters: their id as key, their contigs ("Contigs", the
        longest first, ties by name: see mge_contigs) and score ("Score") as
        value.

    Raises
    ------
    metator.metacool.MetacoolError
        If the map cannot be read, cannot be clustered (see check_mge_map), or
        holds none of the MGE contigs."""
    with mtmc._metacooler_logging(), mtmc.read_errors(metacool):
        mc = mtmc.open_map(metacool)
        check_mge_map(metacool, mc)
        mges_data, positions, intra = mge_contigs(metacool, mc, mges_list)
        mat = map_matrix(metacool, len(mc.contigs), positions, intra)
    logger.info(
        f"{len(positions)} MGE contig(s) in {metacool}: {int(np.triu(mat, 1).sum())} contacts between them, "
        f"{int(intra.sum())} within them (between reads more than 1 kb apart)."
    )

    # Associates contigs
    bins = resolve_matrix(mat, threshold_bin)

    # Update mges_data and generates bins.
    mges_data, mge_bins = update_mge_data(mges_data, bins)

    if random:
        # Shuffle to simulate random bins.
        mges_data, mge_bins = shuffle_mge_bins(mges_data)

    return generate_bin_summary(mges_data, mge_bins), mge_bins

write_mges_fasta

write_mges_fasta(metacool, assembly, mge_bins, out_dir, temp_dir=None)

Write the FASTA files of the MGE clusters in out_dir (made if missing), two for each, named after the cluster (MetaTOR_MGE_<ID>), side by side (see metator.outputs.write_fasta_files): <name>.fa, its contigs as records of their own, and <name>.stitched.fa, one record, so that the tools that check the quality of an MGE genome, which expect one sequence per genome, read the cluster as one: its contigs joined by 200 N, in lines of 80 bases. Both list the contigs in the order of the cluster (the longest first, ties by name: see mge_binning). Files of those names are replaced.

Parameters:

Name Type Description Default
metacool str

Path to the .metacool file, or URI of an entry of a .mmetacool collection: the map whose contigs the MGE clusters are.

required
assembly str

Path to the assembly the map was made from: FASTA, plain or compressed with gzip.

required
mge_bins dict

The MGE clusters (see mge_binning).

required
out_dir str

The directory to write them in: fasta/mges of the output directory of the run (see metator.outputs.MGES_DIR).

required
temp_dir str

Where a compressed assembly is copied, plain: the temporary directory of the run.

None

Raises:

Type Description
MetacoolError

If the files cannot be written: the assembly lacks a contig, gives one another length than the map, or is not FASTA (a ValueError, KeyError or OSError of metacooler, message kept).

Source code in src/metator/mge.py
def write_mges_fasta(metacool, assembly, mge_bins, out_dir, temp_dir=None):
    """Write the FASTA files of the MGE clusters in out_dir (made if missing), two
    for each, named after the cluster (``MetaTOR_MGE_<ID>``), side by side (see
    metator.outputs.write_fasta_files): ``<name>.fa``, its contigs as records of
    their own, and ``<name>.stitched.fa``, one record, so that the tools that
    check the quality of an MGE genome, which expect one sequence per genome,
    read the cluster as one: its contigs joined by 200 N, in lines of 80 bases.
    Both list the contigs in the order of the cluster (the longest first, ties
    by name: see mge_binning). Files of those names are replaced.

    Parameters
    ----------
    metacool : str
        Path to the .metacool file, or URI of an entry of a .mmetacool
        collection: the map whose contigs the MGE clusters are.
    assembly : str
        Path to the assembly the map was made from: FASTA, plain or compressed
        with gzip.
    mge_bins : dict
        The MGE clusters (see mge_binning).
    out_dir : str
        The directory to write them in: fasta/mges of the output directory of
        the run (see metator.outputs.MGES_DIR).
    temp_dir : str, optional
        Where a compressed assembly is copied, plain: the temporary directory
        of the run.

    Raises
    ------
    metator.metacool.MetacoolError
        If the files cannot be written: the assembly lacks a contig, gives one
        another length than the map, or is not FASTA (a ValueError, KeyError or
        OSError of metacooler, message kept)."""
    import metator.outputs as mto

    groups = {f"MetaTOR_MGE_{bin_id:05d}": [str(contig) for contig in cluster["Contigs"]] for bin_id, cluster in mge_bins.items()}
    mto.write_fasta_files(metacool, assembly, out_dir, groups=groups, temp_dir=temp_dir)
    logger.info(f"{len(groups)} clusters have been extracted, each as its contigs and stitched: {out_dir}")

resolve_matrix

resolve_matrix(mat: ndarray, threshold: float = 0.8) -> List[Tuple]

Main function to bin mges contigs.

Contacts are divided by the geometric mean of the intra-contig contacts (reads at least 1001 bp apart); two contigs binned together are fused.

Parameters:

Name Type Description Default
mat array

Matrix of the raw contacts between the contigs.

required
threshold float

Threshold of score to bin contigs.

0.8

Returns:

Type Description
list of list

Each binning, in the order made: the two rows of the matrix binned together, then their score.

Source code in src/metator/mge.py
def resolve_matrix(mat: "np.ndarray", threshold: float = 0.8) -> List[Tuple]:
    """Main function to bin mges contigs.

    Contacts are divided by the geometric mean of the intra-contig contacts
    (reads at least 1001 bp apart); two contigs binned together are fused.

    Parameters
    ----------
    mat : np.array
        Matrix of the raw contacts between the contigs.
    threshold : float
        Threshold of score to bin contigs.

    Returns
    -------
    list of list
        Each binning, in the order made: the two rows of the matrix binned
        together, then their score.
    """

    bins: list = []
    n = len(mat)
    # Save a copy of the initial matrix to keep the intra initial values.
    mat0 = np.copy(mat)

    # Normalize values
    for i in range(n):
        for j in range(i + 1, n):
            if (mat[i, i] > 0) and (mat[j, j] > 0):
                mat[i, j] = mat[i, j] / np.sqrt(mat[i, i] * mat[j, j])
            else:
                mat[i, j] = 0

    # Remove the intra contacts.
    for i in range(n):
        mat[i, i] = 0

    # While there is an association bigger than 1 associates the contigs.
    maxi = np.max(mat)
    while maxi > threshold:
        # Handle the case where we have multiple points at the maximum value.
        try:
            i, j = map(int, np.where(mat == maxi))
        except TypeError:
            i, j = map(int, [np.where(mat == maxi)[0][0], np.where(mat == maxi)[1][0]])

        # Compute the sum of the count to create the merge vector.
        a = mat0[i, :] + mat0[:, i] + mat0[j, :] + mat0[:, j]
        # Compute a new intra count.
        intra = mat0[i, i] + mat0[j, j] + mat0[i, j]
        mat0[i, i] = intra
        # Normalize the new vector.
        for k in range(n):
            if k < i:
                mat0[k, i] = a[k]
                if mat0[k, k] > 0:
                    mat[k, i] = a[k] / np.sqrt(intra * mat0[k, k])
                else:
                    mat[k, i] = 0
            elif k > i:
                mat0[i, k] = a[k]
                if mat0[k, k] > 0:
                    mat[i, k] = a[k] / np.sqrt(intra * mat0[k, k])
                else:
                    mat[k, i] = 0
        # Remove the contig j as it has been merged with the contig i.
        mat[j, :] = np.zeros(n)
        mat[:, j] = np.zeros(n)
        mat0[j, :] = np.zeros(n)
        mat0[:, j] = np.zeros(n)

        bins.append([i, j, maxi])
        maxi = np.max(mat)
    return bins

shuffle_mge_bins

shuffle_mge_bins(mges_data: DataFrame) -> Tuple[pd.DataFrame, dict]

Function to shuffle id to imitate a random binning with the same bins distribution as the one created by Metator MGE.

Parameters:

Name Type Description Default
mges_data DataFrame

Table with the contigs name as index and with information from metator partition or validation.

required

Returns:

Type Description
DataFrame

Input table with the mge bin id column randomly shuffled.

dict

Dictionary with the mge bin id as key and the list of the contigs name as value from the shuffle contigs bins.

Source code in src/metator/mge.py
def shuffle_mge_bins(
    mges_data: pd.DataFrame,
) -> Tuple[pd.DataFrame, dict]:
    """Function to shuffle id to imitate a random binning with the same bins
    distribution as the one created by Metator MGE.

    Parameters
    ----------
    mges_data : pandas.DataFrame
        Table with the contigs name as index and with information from metator
        partition or validation.

    Returns
    -------
    pandas.DataFrame
        Input table with the mge bin id column randomly shuffled.
    dict
        Dictionary with the mge bin id as key and the list of the contigs name
        as value from the shuffle contigs bins."""

    # Shuffle the ids of the dataframe
    mges_bin_ids = mges_data.MetaTOR_MGE_bin
    shuffle_ids = np.random.permutation(mges_bin_ids)
    mges_data["shuffle"] = shuffle_ids

    mges_bins: dict = {}
    # Rebuild the bins from the shuffled ids, in the same shape as the real
    # binning: {bin id: {"Contigs": [...], "Score": ...}}.
    for index in mges_data.index:
        contig = mges_data.loc[index, "Name"]
        mge_bin_id = mges_data.loc[index, "shuffle"]
        mge_bin = mges_bins.setdefault(mge_bin_id, {"Contigs": [], "Score": np.nan})
        mge_bin["Contigs"].append(contig)
    return mges_data, mges_bins

update_mge_data

update_mge_data(
    mges_data: DataFrame, bins: List[Tuple]
) -> Tuple[pd.DataFrame, dict]

Function to update the mge bins data.

Parameters:

Name Type Description Default
mges_data DataFrame

Table wit the mge contig information.

required
bins list of tuple

List of pairs of contigs with their score of association.

required

Returns:

Type Description
DataFrame

Table wit the mge contig information updated.

dictionnary

Dictionary of the mge bins.

Source code in src/metator/mge.py
def update_mge_data(mges_data: pd.DataFrame, bins: List[Tuple]) -> Tuple[pd.DataFrame, dict]:
    """Function to update the mge bins data.

    Parameters
    ----------
    mges_data : pd.DataFrame
        Table wit the mge contig information.
    bins : list of tuple
        List of pairs of contigs with their score of association.

    Returns
    -------
    pandas.DataFrame
        Table wit the mge contig information updated.
    dictionnary
        Dictionary of the mge bins."""
    # Initiation
    mges_data["MetaTOR_MGE_bin"] = 0
    mges_data["MetaTOR_MGE_Score"] = 0.0
    bin_id = 0
    mge_bins: dict = {}
    mges_data = mges_data.set_index(np.arange(len(mges_data)))
    for contig_tuple in bins:
        i, j, score = contig_tuple
        # If no existing bin, creates one.
        if (mges_data.loc[i, "MetaTOR_MGE_bin"] == 0) and (mges_data.loc[j, "MetaTOR_MGE_bin"] == 0):
            bin_id += 1
            current_bin = bin_id
            current_score = score
        # If one existing bin, append it.
        elif (mges_data.loc[i, "MetaTOR_MGE_bin"] == 0) or (mges_data.loc[j, "MetaTOR_MGE_bin"] == 0):
            current_bin = max(
                mges_data.loc[i, "MetaTOR_MGE_bin"],
                mges_data.loc[j, "MetaTOR_MGE_bin"],
            )
            current_score = min(
                score,
                max(
                    mges_data.loc[i, "MetaTOR_MGE_Score"],
                    mges_data.loc[j, "MetaTOR_MGE_Score"],
                ),
            )
        # Complicated case as we have to fuse two existing bins. The bin j
        # is not reused.
        else:
            current_bin = mges_data.loc[i, "MetaTOR_MGE_bin"]
            bin_j = mges_data.loc[j, "MetaTOR_MGE_bin"]
            if current_bin > bin_j:
                current_bin -= 1
            bin_id -= 1
            for k in range(len(mges_data)):
                if mges_data.loc[k, "MetaTOR_MGE_bin"] == bin_j:
                    mges_data.loc[k, "MetaTOR_MGE_bin"] = current_bin
                elif mges_data.loc[k, "MetaTOR_MGE_bin"] > bin_j:
                    mges_data.loc[k, "MetaTOR_MGE_bin"] -= 1
            current_score = min(
                score,
                mges_data.loc[i, "MetaTOR_MGE_Score"],
                mges_data.loc[j, "MetaTOR_MGE_Score"],
            )
        mges_data.loc[i, "MetaTOR_MGE_bin"] = current_bin
        mges_data.loc[j, "MetaTOR_MGE_bin"] = current_bin
        mges_data.loc[i, "MetaTOR_MGE_Score"] = current_score
        mges_data.loc[j, "MetaTOR_MGE_Score"] = current_score

    # Update unbinned contigs and build mge bins.
    for k in mges_data.index:
        if mges_data.loc[k, "MetaTOR_MGE_bin"] == 0:
            bin_id += 1
            mges_data.loc[k, "MetaTOR_MGE_bin"] = bin_id
            mge_bins[bin_id] = {
                "Contigs": [mges_data.loc[k, "Name"]],
                "Score": np.nan,
            }
        else:
            curr_bin = mges_data.loc[k, "MetaTOR_MGE_bin"]
            try:
                mge_bins[curr_bin]["Contigs"].append(mges_data.loc[k, "Name"])
                mge_bins[curr_bin]["Score"] = min(
                    mge_bins[curr_bin]["Score"],
                    mges_data.loc[k, "MetaTOR_MGE_Score"],
                )
            except KeyError:
                mge_bins[curr_bin] = {
                    "Contigs": [mges_data.loc[k, "Name"]],
                    "Score": mges_data.loc[k, "MetaTOR_MGE_Score"],
                }
    return mges_data, mge_bins

metator.host

Find the MAGs that host the MGE clusters of a .metacool map: metator host.

The MGE clusters are those of the round mge of the map, which metator mge stores, and the MAGs are the genomes of the map, whatever made them: the final clusters of a metaTOR run, or the bins of another binner that metacooler reassign made the genomes of the map. __unbinned__ is no MAG, and neither is a genome named after an MGE cluster (an MGE cluster made a genome of the map, by metator mge --reassign or metacooler reassign --round mge). A contig of an MGE cluster counts for its MGE cluster only: a MAG that holds it too (a validation clusters the MGE contigs with the other contigs) is taken without it, or the contacts of the MGE cluster within itself would count as contacts with that MAG.

The signal of an MGE cluster with a MAG is the sum of the weights of the edges of the network between their contigs: the network that metator network stored in the map, weighed with its normalization (see metator.network.stored_network). A MAG hosts the MGE cluster when that signal is at least min_share percent (10 by default) of the signal of the MGE cluster with all the MAGs, and when the MGE cluster is in contact with at least min_contigs of its contigs (5 by default). The contacts of the MGE cluster with the contigs in no MAG and with the other MGE clusters do not count in that share: an MGE cluster with few contacts with the MAGs, as a phage that the library caught in its free particles, can be given a host from a small part of its contacts. share_of_all, the share of all the contacts of the MGE cluster with the other contigs, says how small.

metator host stores what it finds in the map (see metator.metacool.write_map): the hosts of each MGE cluster in the round mge (HOST_CLUSTER_COLUMNS), and the MGE clusters of each MAG in the genomes table (HOST_GENOME_COLUMNS); and writes every MGE cluster and MAG in contact in tables/mge_hosts.txt (see write_hosts), and the signal and share of the hosts in plots/mge_hosts.pdf (see plot_hosts), in its output directory.

Hosts dataclass

The hosts of the MGE clusters of a map (see find_hosts).

Attributes:

Name Type Description
pairs DataFrame

One row per MGE cluster and MAG in contact (PAIRS_COLUMNS), the MGE clusters in the order of the round mge, the MAGs of each by decreasing signal (ties in the order of the genomes table): the signal of the MGE cluster with the MAG (signal), the number of contigs of the MAG in contact with it (contigs), the signal as a percentage of that of the MGE cluster with all the MAGs (share) and of all its contacts with the other contigs (share_of_all), and whether the MAG hosts it (host).

clusters DataFrame

One row per MGE cluster, in the order of the round mge: its name, its number of hosts (n_hosts), its hosts by decreasing share (hosts) and their shares, with two decimals (host_shares), each list separated by commas, missing for none.

genomes DataFrame

One row per MAG, in the order of the genomes table: its name, the number of MGE clusters that it hosts (n_mges), and their names, in the order of the round mge, separated by commas (mges, an empty text for none).

Source code in src/metator/host.py
@dataclass
class Hosts:
    """The hosts of the MGE clusters of a map (see find_hosts).

    Attributes
    ----------
    pairs : pandas.DataFrame
        One row per MGE cluster and MAG in contact (PAIRS_COLUMNS), the MGE
        clusters in the order of the round mge, the MAGs of each by
        decreasing signal (ties in the order of the genomes table): the
        signal of the MGE cluster with the MAG (signal), the number of
        contigs of the MAG in contact with it (contigs), the signal as a
        percentage of that of the MGE cluster with all the MAGs (share) and
        of all its contacts with the other contigs (share_of_all), and
        whether the MAG hosts it (host).
    clusters : pandas.DataFrame
        One row per MGE cluster, in the order of the round mge: its name, its
        number of hosts (n_hosts), its hosts by decreasing share (hosts) and
        their shares, with two decimals (host_shares), each list separated by
        commas, missing for none.
    genomes : pandas.DataFrame
        One row per MAG, in the order of the genomes table: its name, the
        number of MGE clusters that it hosts (n_mges), and their names, in the
        order of the round mge, separated by commas (mges, an empty text for
        none).
    """

    pairs: pd.DataFrame
    clusters: pd.DataFrame
    genomes: pd.DataFrame

map_bins

map_bins(metacool, mc)

The MAGs and the MGE clusters of a map, as find_hosts reads them (see the module's docstring).

Parameters:

Name Type Description Default
metacool str

Path to the .metacool file, or URI of an entry of a .mmetacool collection, for the messages.

required
mc MetaCooler

The map, opened.

required

Returns:

Type Description
ndarray

The MAG of each contig of the map, in its order: an empty text for a contig in no MAG (in unbinned, in an MGE genome, or in an MGE cluster).

DataFrame

The MGE clusters and their contigs: one row per contig of an MGE cluster, its cluster (mge) and its position in the map, from 0 (position).

list of str

The MGE clusters, in the order of the round mge.

list of str

The MAGs, in the order of the genomes table.

Raises:

Type Description
MetacoolError

If the map holds no round mge, or no MAG.

Source code in src/metator/host.py
def map_bins(metacool, mc):
    """The MAGs and the MGE clusters of a map, as find_hosts reads them (see the
    module's docstring).

    Parameters
    ----------
    metacool : str
        Path to the .metacool file, or URI of an entry of a .mmetacool
        collection, for the messages.
    mc : metacooler.MetaCooler
        The map, opened.

    Returns
    -------
    numpy.ndarray
        The MAG of each contig of the map, in its order: an empty text for a
        contig in no MAG (in __unbinned__, in an MGE genome, or in an MGE
        cluster).
    pandas.DataFrame
        The MGE clusters and their contigs: one row per contig of an MGE
        cluster, its cluster (mge) and its position in the map, from 0
        (position).
    list of str
        The MGE clusters, in the order of the round mge.
    list of str
        The MAGs, in the order of the genomes table.

    Raises
    ------
    metator.metacool.MetacoolError
        If the map holds no round mge, or no MAG."""
    with mtmc.read_errors(metacool):
        rounds = [str(entry.get("name")) for entry in mc.cluster_rounds]
        if mtcl.MGE not in rounds:
            raise mtmc.MetacoolError(
                f"{metacool} holds no MGE clusters (no clustering round {mtcl.MGE}): run metator mge on it first, which "
                "stores them in the map."
            )
        clusters = mc.clusters
        mges = [str(name) for name in clusters.loc[(clusters["round"] == mtcl.MGE).to_numpy(), "name"]]
        members = mc.cluster_members(mtcl.MGE)
        contigs = mc.contigs
        genome_names = mc.genomes["name"].astype(str).to_numpy()
    names = contigs["name"].astype(str).to_numpy()
    position = pd.Series(np.arange(len(names)), index=names)
    members = pd.DataFrame(
        {
            "mge": members["cluster"].astype(str).to_numpy(),
            "position": position.reindex(members["contig"].astype(str)).to_numpy(dtype=np.int64),
        }
    )
    in_mge = np.zeros(len(names), dtype=bool)
    in_mge[members["position"].to_numpy()] = True
    # Genomes named after an MGE cluster are MGE clusters made genomes, no
    # MAGs.
    mge_genomes = set(mges)
    mags = [name for name in genome_names if name != mtmc.UNBINNED_GENOME and name not in mge_genomes]
    if not mags:
        raise mtmc.MetacoolError(
            f"{metacool} holds no MAG to host its MGE clusters: none of its genomes is a MAG (but __unbinned__ and the "
            "MGE clusters made genomes). Run metator validation (or pipeline) on it first, which makes its final "
            "clusters its genomes, or make the bins of another binner its genomes with metacooler reassign."
        )
    genome = genome_names[contigs["genome_id"].to_numpy()]
    mag = np.where(~in_mge & np.isin(genome, mags), genome, "")
    return mag, members, mges, mags

contact_pairs

contact_pairs(network, mag, members, mges, mags)

The signal of each MGE cluster with each MAG it is in contact with (see the module's docstring), from the network of the map.

Parameters:

Name Type Description Default
network DataFrame

The network of the map, by the positions of its contigs, from 1 (see metator.network.map_network): contig1, contig2 and weight.

required
mag

The MAGs and the MGE clusters of the map (see map_bins).

required
members

The MAGs and the MGE clusters of the map (see map_bins).

required
mges

The MAGs and the MGE clusters of the map (see map_bins).

required
mags

The MAGs and the MGE clusters of the map (see map_bins).

required

Returns:

Type Description
DataFrame

One row per MGE cluster and MAG in contact: mge, mag, signal, contigs, share and share_of_all (see Hosts.pairs), the MGE clusters in the order of mges, the MAGs of each by decreasing signal, ties in the order of mags.

Source code in src/metator/host.py
def contact_pairs(network, mag, members, mges, mags):
    """The signal of each MGE cluster with each MAG it is in contact with (see the
    module's docstring), from the network of the map.

    Parameters
    ----------
    network : pandas.DataFrame
        The network of the map, by the positions of its contigs, from 1 (see
        metator.network.map_network): contig1, contig2 and weight.
    mag, members, mges, mags :
        The MAGs and the MGE clusters of the map (see map_bins).

    Returns
    -------
    pandas.DataFrame
        One row per MGE cluster and MAG in contact: mge, mag, signal,
        contigs, share and share_of_all (see Hosts.pairs), the MGE clusters
        in the order of mges, the MAGs of each by decreasing signal, ties in
        the order of mags."""
    in_mge = np.zeros(len(mag), dtype=bool)
    in_mge[members["position"].to_numpy()] = True
    first = network["contig1"].to_numpy() - 1
    second = network["contig2"].to_numpy() - 1
    weight = network["weight"].to_numpy(dtype=np.float64)
    # The edges of the MGE contigs, from each of their two contigs that is
    # one: the contacts of the MGE clusters.
    touched = in_mge[first] | in_mge[second]
    edges = pd.DataFrame(
        {
            "position": np.concatenate([first[touched], second[touched]]),
            "other": np.concatenate([second[touched], first[touched]]),
            "weight": np.concatenate([weight[touched], weight[touched]]),
        }
    )
    edges = edges.merge(members, on="position")
    # The contacts of an MGE cluster with the other contigs: not those within
    # it.
    within = members.rename(columns={"position": "other"}).assign(within=True)
    edges = edges.merge(within, on=["mge", "other"], how="left")
    edges = edges[edges["within"].isna()]
    total = edges.groupby("mge", sort=False)["weight"].sum()
    edges = edges.assign(mag=mag[edges["other"].to_numpy()])
    edges = edges[(edges["mag"] != "").to_numpy()]
    pairs = edges.groupby(["mge", "mag"], sort=False).agg(signal=("weight", "sum"), contigs=("other", "nunique")).reset_index()
    pairs["contigs"] = pairs["contigs"].astype(np.int64)
    # As numbers, whatever the types of an empty table (no MGE cluster in
    # contact with a MAG).
    signal = pairs["signal"].to_numpy(dtype=np.float64)
    pairs["signal"] = signal
    pairs["share"] = 100 * signal / pairs.groupby("mge", sort=False)["signal"].transform("sum").to_numpy(dtype=np.float64)
    pairs["share_of_all"] = 100 * signal / pairs["mge"].map(total).to_numpy(dtype=np.float64)
    order = pd.DataFrame(
        {
            "mge_rank": pairs["mge"].map({name: rank for rank, name in enumerate(mges)}),
            "mag_rank": pairs["mag"].map({name: rank for rank, name in enumerate(mags)}),
            "signal": -pairs["signal"],
        }
    )
    ranked = order.sort_values(["mge_rank", "signal", "mag_rank"], kind="stable").index
    return pairs.loc[ranked].reset_index(drop=True)

find_hosts

find_hosts(metacool, mc, network, min_share=MIN_SHARE, min_contigs=MIN_CONTIGS)

The hosts of the MGE clusters of a map (see the module's docstring).

Parameters:

Name Type Description Default
metacool str

Path to the .metacool file, or URI of an entry of a .mmetacool collection, for the messages.

required
mc MetaCooler

The map, opened: it gives the MAGs and the MGE clusters (see map_bins).

required
network DataFrame

The network of the map, by the positions of its contigs, from 1 (see metator.network.stored_network).

required
min_share float

The share of the signal of an MGE cluster with the MAGs, in percent, from which a MAG is a host.

MIN_SHARE
min_contigs int

The number of contigs of a MAG in contact with an MGE cluster from which the MAG is a host.

MIN_CONTIGS

Returns:

Type Description
Hosts

The MGE clusters and MAGs in contact, the hosts of each MGE cluster, and the MGE clusters of each MAG.

Raises:

Type Description
MetacoolError

If the map holds no round mge, or no MAG (see map_bins).

Source code in src/metator/host.py
def find_hosts(metacool, mc, network, min_share=MIN_SHARE, min_contigs=MIN_CONTIGS):
    """The hosts of the MGE clusters of a map (see the module's docstring).

    Parameters
    ----------
    metacool : str
        Path to the .metacool file, or URI of an entry of a .mmetacool
        collection, for the messages.
    mc : metacooler.MetaCooler
        The map, opened: it gives the MAGs and the MGE clusters (see
        map_bins).
    network : pandas.DataFrame
        The network of the map, by the positions of its contigs, from 1 (see
        metator.network.stored_network).
    min_share : float
        The share of the signal of an MGE cluster with the MAGs, in percent,
        from which a MAG is a host.
    min_contigs : int
        The number of contigs of a MAG in contact with an MGE cluster from
        which the MAG is a host.

    Returns
    -------
    Hosts
        The MGE clusters and MAGs in contact, the hosts of each MGE cluster,
        and the MGE clusters of each MAG.

    Raises
    ------
    metator.metacool.MetacoolError
        If the map holds no round mge, or no MAG (see map_bins)."""
    mag, members, mges, mags = map_bins(metacool, mc)
    pairs = contact_pairs(network, mag, members, mges, mags)
    pairs["host"] = (pairs["share"] >= min_share) & (pairs["contigs"] >= min_contigs)
    hosts = pairs[pairs["host"].to_numpy()]
    by_mge = {name: group for name, group in hosts.groupby("mge", sort=False)}
    clusters = pd.DataFrame(
        [
            (
                name,
                len(by_mge[name]) if name in by_mge else 0,
                SEPARATOR.join(by_mge[name]["mag"]) if name in by_mge else None,
                SEPARATOR.join(f"{share:.2f}" for share in by_mge[name]["share"]) if name in by_mge else None,
            )
            for name in mges
        ],
        columns=["name", *mtmc.HOST_CLUSTER_COLUMNS],
    )
    rank = {name: position for position, name in enumerate(mges)}
    hosted = {name: sorted(group["mge"], key=rank.__getitem__) for name, group in hosts.groupby("mag", sort=False)}
    genomes = pd.DataFrame(
        [(name, len(hosted.get(name, [])), SEPARATOR.join(hosted.get(name, []))) for name in mags],
        columns=["name", *mtmc.HOST_GENOME_COLUMNS],
    )
    n_hosts = clusters["n_hosts"].to_numpy()
    logger.info(
        f"{len(mges)} MGE clusters and {len(mags)} MAGs: {int((n_hosts == 1).sum())} MGE clusters with one host, "
        f"{int((n_hosts > 1).sum())} with several, {int((n_hosts == 0).sum())} with none; "
        f"{int((genomes['n_mges'] > 0).sum())} MAGs host at least one."
    )
    return Hosts(pairs[PAIRS_COLUMNS], clusters, genomes)

recorded_thresholds

recorded_thresholds(mc)

The thresholds with which the hosts of the MGE clusters of a map (mc, opened) were found, as (min_share, min_contigs): the --min-share and --min-contigs of metator host, or the --mge-min-share and --mge-min-contigs of pipeline --mges, as the host entry of the metator metadata of the map records the parameters of the run (see metator.metacool.host_entry); MIN_SHARE and MIN_CONTIGS for one that it does not record.

Source code in src/metator/host.py
def recorded_thresholds(mc):
    """The thresholds with which the hosts of the MGE clusters of a map (mc,
    opened) were found, as (min_share, min_contigs): the --min-share and
    --min-contigs of metator host, or the --mge-min-share and --mge-min-contigs
    of pipeline --mges, as the host entry of the metator metadata of the map
    records the parameters of the run (see metator.metacool.host_entry);
    MIN_SHARE and MIN_CONTIGS for one that it does not record."""
    parameters = (mtmc.host_entry(mc) or {}).get("parameters") or {}
    min_share = parameters.get("min_share", parameters.get("mge_min_share", MIN_SHARE))
    min_contigs = parameters.get("min_contigs", parameters.get("mge_min_contigs", MIN_CONTIGS))
    return float(min_share), int(min_contigs)

write_hosts

write_hosts(pairs, path)

Write the MGE clusters and MAGs in contact (pairs, see Hosts.pairs) at path, tab-separated, with a header: PAIRS_COLUMNS, host True or False. The file is replaced if it exists (a symbolic link there, not its target).

Source code in src/metator/host.py
def write_hosts(pairs, path):
    """Write the MGE clusters and MAGs in contact (pairs, see Hosts.pairs) at path,
    tab-separated, with a header: PAIRS_COLUMNS, host True or False. The file is
    replaced if it exists (a symbolic link there, not its target)."""
    if os.path.islink(path):
        os.remove(path)
    pairs[PAIRS_COLUMNS].to_csv(path, sep="\t", index=False)

plot_hosts

plot_hosts(pairs, path)

Plot the hosts of the MGE clusters (the rows of pairs that are hosts, see Hosts.pairs) at path: the distribution of their signal, on a log scale, and of their share. The axes say so when there is no host.

Source code in src/metator/host.py
def plot_hosts(pairs, path):
    """Plot the hosts of the MGE clusters (the rows of pairs that are hosts, see
    Hosts.pairs) at path: the distribution of their signal, on a log scale,
    and of their share. The axes say so when there is no host."""
    hosts = pairs[pairs["host"].to_numpy()]
    fig = Figure(figsize=(12, 5))
    signal, share = fig.subplots(1, 2)
    if len(hosts):
        values = hosts["signal"].to_numpy(dtype=np.float64)
        low, high = values.min(), values.max()
        # geomspace, whose last edge is the highest signal exactly: a host
        # there is counted.
        signal.hist(values, bins=np.geomspace(low, high if high > low else 10 * low, 21), edgecolor="black")
        signal.set_xscale("log")
        share.hist(hosts["share"].to_numpy(dtype=np.float64), bins=np.linspace(0, 100, 21), edgecolor="black")
    else:
        for ax in (signal, share):
            ax.text(0.5, 0.5, "No host", ha="center", va="center", transform=ax.transAxes)
    signal.set_xlabel("Signal of the MGE cluster with its host (log scale)")
    share.set_xlabel("Share of the signal of the MGE cluster with the MAGs (%)")
    share.set_xlim(0, 100)
    for ax in (signal, share):
        ax.set_ylabel("Hosts")
    fig.suptitle(f"The {len(hosts)} hosts of {hosts['mge'].nunique()} MGE clusters")
    mtf._saved(fig, path)