Skip to content

Partition and validation

metator.partition partitions the network many times with the Louvain or Leiden algorithm, and merges the contigs that always fall together into clusters. metator.clusters holds the clustering rounds of a run, the partition among them, as the map stores them. metator.validation measures the clusters with miComplete, and partitions the contaminated ones again, and metator.figures draws the plots of the final clusters. metator.markers finds miComplete's marker genes on each contig of a map, and gives from them miComplete's numbers of a genome of the map, and an estimate of those of any other group of contigs (see Marker genes of the contigs). See Partition and validation.

metator.partition

Partition the metaHiC network with the Louvain or Leiden algorithm.

The partition iterates Louvain or Leiden on the network of the contigs of a map (see metator.network.map_network), finds the core clusters (contigs always together), then merges core clusters whose Hamming distance is below the overlap threshold (so as not to split genomes). metator partition MAP stores the result (metator.clusters.Partition) in the map as clustering rounds; the validation reads it back (partition_table).

algo_partition

algo_partition(
    algorithm="louvain",
    network=None,
    iterations=10,
    resolution_parameter=1.0,
    progress=False,
)

Function to partition the network depednding on the used algorithm.

Parameters:

Name Type Description Default
algorithm str

Algorithm to use to partition network.

'louvain'
network DataFrame

The network: one row per edge, with the ids of its two contigs and its weight, normalized or not (columns contig1, contig2 and weight, see metator.network.map_network).

None
iterations int

Number of iterations of the algorithm of Leiden or Louvain.

10
resolution_parameter float

Resolution parameter for Leiden clustering.

1.0
progress bool

Whether the log follows the iterations (see iterate): that of the partition of the network, not those of the recursive partitions of the validation.

False

Returns:

Type Description
dict

Dictionnary with the id of the contig as key and the list of the results of each iterations separated by a semicolon as values.

Source code in src/metator/partition.py
def algo_partition(
    algorithm="louvain",
    network=None,
    iterations=10,
    resolution_parameter=1.0,
    progress=False,
):
    """Function to partition the network depednding on the used algorithm.

    Parameters
    ----------
    algorithm : str
        Algorithm to use to partition network.
    network : pandas.DataFrame
        The network: one row per edge, with the ids of its two contigs and its
        weight, normalized or not (columns contig1, contig2 and weight, see
        metator.network.map_network).
    iterations : int
        Number of iterations of the algorithm of Leiden or Louvain.
    resolution_parameter : float
        Resolution parameter for Leiden clustering.
    progress : bool
        Whether the log follows the iterations (see iterate): that of the
        partition of the network, not those of the recursive partitions of
        the validation.

    Returns
    -------
    dict
        Dictionnary with the id of the contig as key and the list of the
        results of each iterations separated by a semicolon as values."""
    if algorithm == "leiden":
        output_partition = leiden_iterations(network, iterations, resolution_parameter, progress)
    elif algorithm == "louvain":
        output_partition = louvain_iterations(network, iterations, progress)
    else:
        logger.error('algorithm should be either "louvain" or "leiden"')
        raise ValueError
    return output_partition

defined_overlapping_bins

defined_overlapping_bins(overlap, hamming_distance, core_bins_contigs)

This function extract the overlapped bins

Two core bins overlap when the fraction of iterations that put them together reaches the threshold.

Parameters:

Name Type Description Default
overlap float

hamming distance threshold use to consider that two bins are overlapping.

required
hamming_distance csr_matrix

Matrix with all the previously computed hamming distance between two core bins.

required
core_bins_contigs dict

Dictionnary which has as keys the core bins id and as value the id of the contigs of the core bin.

required

Returns:

Type Description
dict

A dictionnary with the id of the overlapping bins as keys and the list of id of their contigs as values.

Source code in src/metator/partition.py
def defined_overlapping_bins(
    overlap,
    hamming_distance,
    core_bins_contigs,
):
    """This function extract the overlapped bins

    Two core bins overlap when the fraction of iterations that put them
    together reaches the threshold.

    Parameters
    ----------
    overlap : float
        hamming distance threshold use to consider that two bins are
        overlapping.
    hamming_distance : scipy.sparse.csr.csr_matrix
        Matrix with all the previously computed hamming distance between two
        core bins.
    core_bins_contigs : dict
        Dictionnary which has as keys the core bins id and as value the id of
        the contigs of the core bin.

    Returns
    -------
    dict
        A dictionnary with the id of the overlapping bins as keys and the list
        of id of their contigs as values."""
    # Extract bins which are connected, i.e. bins with an hamming distance
    # superior than the threshold given. The small variation is necessary as
    # python give a float not really equal to the true value
    # (i.e. 0.1 -> 0.09999999999999998)
    connections = hamming_distance >= (overlap - 1e-10)
    overlapping_bins_id = sparse.csgraph.connected_components(connections, directed=False)[1]

    # Create a dictionnary of the overlapped bins (ID from the previous file)
    # with the ID of their contigs as value
    overlapping_bins = {}
    cc_id = 0
    # Iterate on each core bins.
    for oc_id in overlapping_bins_id:
        # Extract contig ID from the core bin.
        core_bin_contigs = core_bins_contigs[cc_id].copy()
        # Add the contig ID on the overlapping bin.
        if oc_id + 1 not in overlapping_bins:
            overlapping_bins[oc_id + 1] = core_bin_contigs
        else:
            overlapping_bins[oc_id + 1] += core_bin_contigs
        cc_id += 1

    logger.debug(f"{len(overlapping_bins)} overlapping clusters were found.")

    return overlapping_bins

detect_core_bins

detect_core_bins(output_partition, iterations)

Detect core bins from the output of the partition algorithm.

A core bin holds the contigs that every iteration puts in the same community.

Parameters:

Name Type Description Default
output_partition dict

Dictionnary with the id of the contig as key and the list of the results of each iterations separated by a semicolon as values.

required
iterations int

Number of iterations made previously with the partition algorithm.

required

Returns:

Type Description
dict

Dictionnary which has as keys the core bins id and as value the id of the contigs of the core bin.

DataFrame

Table with the id of the core bin and their values for each iterations.

Source code in src/metator/partition.py
def detect_core_bins(output_partition, iterations):
    """Detect core bins from the output of the partition algorithm.

    A core bin holds the contigs that every iteration puts in the same
    community.

    Parameters
    ----------
    output_partition : dict
        Dictionnary with the id of the contig as key and the list of the
        results of each iterations separated by a semicolon as values.
    iterations : int
        Number of iterations made previously with the partition algorithm.

    Returns
    -------
    dict
        Dictionnary which has as keys the core bins id and as value the id of
        the contigs of the core bin.
    pandas.core.frame.DataFrame
        Table with the id of the core bin and their values for each iterations."""
    # finding duplicate values in the output of louvain or leiden using a
    # flipped dictionary.

    # Create dictionnary for core bins
    core_bins = {}
    core_bins_contigs = {}
    core_bins_rows = []
    core_bin_id = 0
    for key, value in output_partition.items():
        if value not in core_bins:
            # Create an entry in a dictionnary with all the contigs with
            # iterations list as a key.
            core_bins[value] = core_bin_id

            # Create an entry in a dictionnary with all the contigs with core
            # bin id as a key.
            core_bins_contigs[core_bin_id] = [key]
            core_bin_id += 1
            # Add a line to compute the array used to compute the distance
            # between two core bins
            core_bins_rows.append(list(map(int, value.split(";"))))
        # If already an entry created for this bin add a contig in the lists.
        else:
            core_bins_contigs[core_bins[value]].append(key)

    # Transform the array in a dataframe
    core_bins_iterations = pd.DataFrame(np.array(core_bins_rows, dtype=int).reshape(-1, iterations))

    logger.debug(f"{len(core_bins)} core clusters were found.")

    return core_bins_contigs, core_bins_iterations

get_distances_splitmat

get_distances_splitmat(bins, core_bins_iterations)

This function takes a segment of the full iterative clustering matrix and computes, for each index (i.e. contig), the hamming distance to each of the other indices.

The values are one minus the normalized Hamming distance: the fraction of the iterations in which both core bins fell in the same community.

Parameters:

Name Type Description Default
bins DataFrame

Slice of the table with the id of the core bin and their values for each iterations.

required
core_bins_iterations DataFrame

Table with the id of the core bin and their values for each iterations.

required

Returns:

Type Description
csr_matrix

matrix of the distance of the possible pairs from the slice of the table and the table itself.

Source code in src/metator/partition.py
def get_distances_splitmat(bins, core_bins_iterations):
    """This function takes a segment of the full iterative clustering matrix and
    computes, for each index (i.e. contig), the hamming distance to each of the
    other indices.

    The values are one minus the normalized Hamming distance: the fraction of
    the iterations in which both core bins fell in the same community.

    Parameters
    ----------
    bins : pandas.core.frame.DataFrame
        Slice of the table with the id of the core bin and their values for
        each iterations.
    core_bins_iterations : pandas.core.frame.DataFrame
        Table with the id of the core bin and their values for each iterations.

    Returns
    -------
    scipy.sparse.csr.csr_matrix
        matrix of the distance of the possible pairs from the slice of the
        table and the table itself."""
    x = sparse.csr_matrix(1 - cdist(core_bins_iterations, bins.values, metric="hamming"))
    return x

get_hamming_distance

get_hamming_distance(core_bins_iterations, threads)

Generate matrix of Hamming distances between all pairs of core bins.

Parameters:

Name Type Description Default
core_bins_iterations DataFrame

Table with the id of the core bin as index and their values for each iterations.

required
threads int

Number of cores to parallelize computation.

required

Returns:

Type Description
csr_matrix

Matrix with all the previously computed hamming distance between two core bins.

Source code in src/metator/partition.py
def get_hamming_distance(core_bins_iterations, threads):
    """Generate matrix of Hamming distances between all pairs of core bins.

    Parameters
    ----------
    core_bins_iterations : pandas.core.frame.DataFrame
        Table with the id of the core bin as index and their values for each
        iterations.
    threads : int
        Number of cores to parallelize computation.

    Returns
    -------
    scipy.sparse.csr.csr_matrix
        Matrix with all the previously computed hamming distance between two
        core bins."""

    # Compute Hamming distances in the core-bin-level iterative clustering
    # matrix, in parallel
    step = 1000
    steps = np.arange(step, len(core_bins_iterations.index) + step, step)
    split_core_bins = [core_bins_iterations[(k - step) : k] for k in steps]
    distances = partial(get_distances_splitmat, core_bins_iterations=core_bins_iterations)
    # Threads, not processes: SciPy computes the distances without holding the
    # GIL, so the threads run in parallel, and no process is forked from this
    # one, which runs threads and so may deadlock in a fork, nor spawned, which
    # would import the script of a caller of the Python API again.
    with ThreadPoolExecutor(max_workers=max(1, min(threads, len(split_core_bins)))) as executor:
        res = list(executor.map(distances, split_core_bins))
    return sparse.hstack(res).tocsr()

leiden_iterations

leiden_iterations(network, iterations, resolution_parameter, progress=False)

Partition the network with the igraph implementation of Leiden.

Parameters:

Name Type Description Default
network DataFrame

The network (see network_graph).

required
iterations int

Number of iterations of the algorithm of Leiden.

required
resolution_parameter float

Resolution parameter for Leiden clustering.

required
progress bool

Whether the log follows the iterations (see iterate).

False

Returns:

Type Description
dict

Dictionnary with the id of the contig as key and the list of the results of each iterations separated by a semicolon as values.

Source code in src/metator/partition.py
def leiden_iterations(network, iterations, resolution_parameter, progress=False):
    """Partition the network with the igraph implementation of Leiden.

    Parameters
    ----------
    network : pandas.DataFrame
        The network (see network_graph).
    iterations : int
        Number of iterations of the algorithm of Leiden.
    resolution_parameter : float
        Resolution parameter for Leiden clustering.
    progress : bool
        Whether the log follows the iterations (see iterate).

    Returns
    -------
    dict
        Dictionnary with the id of the contig as key and the list of the
        results of each iterations separated by a semicolon as values."""
    graph, contigs = network_graph(network)

    def membership():
        return graph.community_leiden(
            objective_function="modularity",
            weights="weight",
            resolution=resolution_parameter,
            n_iterations=4,
        ).membership

    return merge_iterations(contigs, iterate("leiden", iterations, membership, progress))

louvain_iterations

louvain_iterations(network, iterations, progress=False)

Partition the network with the igraph implementation of Louvain.

Parameters:

Name Type Description Default
network DataFrame

The network (see network_graph).

required
iterations int

Number of iterations of the algorithm of Louvain.

required
progress bool

Whether the log follows the iterations (see iterate).

False

Returns:

Type Description
dict

Dictionnary with the id of the contig as key and the list of the results of each iterations separated by a semicolon as values.

Source code in src/metator/partition.py
def louvain_iterations(network, iterations, progress=False):
    """Partition the network with the igraph implementation of Louvain.

    Parameters
    ----------
    network : pandas.DataFrame
        The network (see network_graph).
    iterations : int
        Number of iterations of the algorithm of Louvain.
    progress : bool
        Whether the log follows the iterations (see iterate).

    Returns
    -------
    dict
        Dictionnary with the id of the contig as key and the list of the
        results of each iterations separated by a semicolon as values."""
    graph, contigs = network_graph(network)

    def membership():
        return graph.community_multilevel(weights="weight").membership

    return merge_iterations(contigs, iterate("louvain", iterations, membership, progress))

iterate

iterate(algorithm, iterations, membership, progress=False)

The memberships of the vertices of a network in iterations iterations of an algorithm (louvain or leiden), each one call of membership.

With progress, the log follows them, as they can take minutes on a large network: a line at each tenth of the iterations, when PROGRESS_INTERVAL seconds have passed since the previous line, and one once they are all done, with the time they took.

Source code in src/metator/partition.py
def iterate(algorithm, iterations, membership, progress=False):
    """The memberships of the vertices of a network in iterations iterations of
    an algorithm (louvain or leiden), each one call of membership.

    With progress, the log follows them, as they can take minutes on a large
    network: a line at each tenth of the iterations, when PROGRESS_INTERVAL
    seconds have passed since the previous line, and one once they are all
    done, with the time they took."""
    started = last = time.monotonic()
    step = max(1, iterations // 10)
    memberships = []
    for done in range(1, iterations + 1):
        memberships.append(membership())
        if not progress:
            continue
        now = time.monotonic()
        if done == iterations:
            logger.info(f"{algorithm}: {done}/{iterations} iterations, done in {duration(now - started)}.")
        elif done % step == 0 and now - last >= PROGRESS_INTERVAL:
            logger.info(f"{algorithm}: {done}/{iterations} iterations ({duration(now - started)}).")
            last = now
    return memberships

merge_iterations

merge_iterations(contigs, memberships)

Merge the clusters of each iteration in one dictionnary.

Parameters:

Name Type Description Default
contigs ndarray

Contig ids of the network vertices.

required
memberships list of list

Cluster of each vertex, for each iteration.

required

Returns:

Type Description
dict

Dictionnary with the id of the contig as key and the list of the results of each iterations separated by a semicolon as values.

Source code in src/metator/partition.py
def merge_iterations(contigs, memberships):
    """Merge the clusters of each iteration in one dictionnary.

    Parameters
    ----------
    contigs : numpy.ndarray
        Contig ids of the network vertices.
    memberships : list of list
        Cluster of each vertex, for each iteration.

    Returns
    -------
    dict
        Dictionnary with the id of the contig as key and the list of the
        results of each iterations separated by a semicolon as values."""
    memberships = np.array(memberships).T
    return {int(contig): ";".join(map(str, clusters)) for contig, clusters in zip(contigs, memberships, strict=True)}

partition

partition(
    algorithm,
    network,
    iterations,
    overlapping_parameter,
    resolution_parameter,
    threads,
    prefix,
)

Partition the network of the contigs of a map: its core clusters, then its overlapping clusters.

Parameters:

Name Type Description Default
algorithm str

Algorithm to use to partition the network.

required
network DataFrame

The network of the contigs of the map (see metator.network.map_network).

required
iterations int

Number of iterations to use for the partition.

required
overlapping_parameter int

Hamming distance threshold to use to merge bins (percentage).

required
resolution_parameter float

Resolution parameter to use if Leiden algorithm is chosen.

required
threads int

Number of threads to use.

required
prefix str

Sample prefix to use, which names the overlapping clusters (see metator.clusters.overlapping_name).

required

Returns:

Type Description
Partition

The core and the overlapping clusters, numbered from 1, each with the IDs of its contigs.

Source code in src/metator/partition.py
def partition(
    algorithm,
    network,
    iterations,
    overlapping_parameter,
    resolution_parameter,
    threads,
    prefix,
):
    """Partition the network of the contigs of a map: its core clusters, then its
    overlapping clusters.

    Parameters
    ----------
    algorithm : str
        Algorithm to use to partition the network.
    network : pandas.DataFrame
        The network of the contigs of the map (see
        metator.network.map_network).
    iterations : int
        Number of iterations to use for the partition.
    overlapping_parameter : int
        Hamming distance threshold to use to merge bins (percentage).
    resolution_parameter : float
        Resolution parameter to use if Leiden algorithm is chosen.
    threads : int
        Number of threads to use.
    prefix : str
        Sample prefix to use, which names the overlapping clusters (see
        metator.clusters.overlapping_name).

    Returns
    -------
    metator.clusters.Partition
        The core and the overlapping clusters, numbered from 1, each with the
        IDs of its contigs."""

    # Perform the iterations of Louvain or Leiden to partition the network,
    # which the log follows.
    n_contigs = len(np.unique(network[["contig1", "contig2"]].to_numpy()))
    logger.info(f"{iterations} iterations of {algorithm} on the network of {n_contigs} contigs and {len(network)} edges.")
    output_partition = algo_partition(algorithm, network, iterations, resolution_parameter, progress=True)

    # Detect core bins
    (
        core_bins_contigs,
        core_bins_iterations,
    ) = detect_core_bins(output_partition, iterations)

    # Compute the Hamming distance between core bins.
    hamming_distance = get_hamming_distance(
        core_bins_iterations,
        threads,
    )

    # Defined overlapping bins according to the threshold
    overlapping_bins = defined_overlapping_bins(
        overlapping_parameter,
        hamming_distance,
        core_bins_contigs,
    )
    logger.info(f"{len(core_bins_contigs)} core clusters, merged into {len(overlapping_bins)} overlapping clusters.")

    # The core bins numbered from 1, as the contig data tables number them,
    # and the overlapping bins, numbered from 1 already.
    return mtc.Partition(
        core={core_id + 1: contigs for core_id, contigs in core_bins_contigs.items()},
        overlapping=dict(overlapping_bins),
        names={number: mtc.overlapping_name(prefix, number) for number in overlapping_bins},
    )

network_graph

network_graph(network)

The network as an igraph graph: its vertices are the contigs of its edges, in the order of their ids, and its edges are in the order of its rows.

Parameters:

Name Type Description Default
network DataFrame

One row per edge: the ids of its two contigs (columns contig1 and contig2) and its weight, normalized or not (column weight), as metator.network.map_network gives them.

required

Returns:

Type Description
Graph

Weighted undirected network.

ndarray

Contig ids of the vertices.

Source code in src/metator/partition.py
def network_graph(network):
    """The network as an igraph graph: its vertices are the contigs of its edges,
    in the order of their ids, and its edges are in the order of its rows.

    Parameters
    ----------
    network : pandas.DataFrame
        One row per edge: the ids of its two contigs (columns contig1 and
        contig2) and its weight, normalized or not (column weight), as
        metator.network.map_network gives them.

    Returns
    -------
    igraph.Graph
        Weighted undirected network.
    numpy.ndarray
        Contig ids of the vertices."""
    contigs, vertices = np.unique(network[["contig1", "contig2"]].to_numpy().ravel(), return_inverse=True)
    graph = ig.Graph(
        n=len(contigs),
        edges=vertices.reshape(-1, 2).tolist(),
        edge_attrs={"weight": network["weight"].tolist()},
    )
    return graph, contigs

partition_table

partition_table(contig_data, partition)

The contig data table of a partition: the contig data with the core and the overlapping cluster of each contig, as contig_data_partition.txt held it, and as the validation reads it.

Parameters:

Name Type Description Default
contig_data DataFrame

The contig data, which is left as it is.

required
partition Partition

The core and the overlapping clusters of the partition.

required

Returns:

Type Description
DataFrame

Table with all the information on the contigs included their appartenance to the bins.

Source code in src/metator/partition.py
def partition_table(contig_data, partition):
    """The contig data table of a partition: the contig data with the core and the
    overlapping cluster of each contig, as contig_data_partition.txt held it,
    and as the validation reads it.

    Parameters
    ----------
    contig_data : pandas.DataFrame
        The contig data, which is left as it is.
    partition : metator.clusters.Partition
        The core and the overlapping clusters of the partition.

    Returns
    -------
    pandas.core.frame.DataFrame
        Table with all the information on the contigs included their
        appartenance to the bins."""

    # A copy of the table, from 0 to n - 1: the contig of ID i is row i - 1.
    contigs_data = contig_data.reset_index(drop=True).copy()
    sizes = contigs_data["Size"].to_numpy()
    for kind, clusters in (("Core", partition.core), ("Overlapping", partition.overlapping)):
        ids, counts, lengths = _cluster_columns(clusters, sizes)
        # Object columns, as they mix "-" and numbers.
        contigs_data[f"{kind}_cluster_ID"] = pd.Series(ids, index=contigs_data.index, dtype=object)
        contigs_data[f"{kind}_cluster_contigs"] = pd.Series(counts, index=contigs_data.index, dtype=object)
        contigs_data[f"{kind}_cluster_size"] = pd.Series(lengths, index=contigs_data.index, dtype=object)

    return contigs_data

metator.clusters

The clustering rounds of a run: the map's /clusters group, and their tables.

A run reaches its final clusters in rounds:

  • core: the contigs that every iteration of Louvain or Leiden put together, named core_<number> (:func:core_name), with no parent;
  • overlapping: the core clusters merged, named <prefix>_<number>_00000 (:func:overlapping_name), every one; the validation checks those that reach --size;
  • recursive_<k>: the clusters that step k of the validation makes from a contaminated cluster, their parent;
  • final: the final clusters, each the cluster of its name in the round it comes from;
  • mge, or mge_random with --random: the MGE clusters of metator mge, after the others.

metator partition stores the first two (:func:partition_rounds), the validation reads them back (:func:metator.metacool.read_partition) and records every round (:class:Rounds), which the map of the clusters stores (:func:metator.metacool.write_map) and clusters.txt and cluster_members.txt hold.

Partition dataclass

The clusters of a partition of the network of a map (see :func:metator.partition.partition): its core and its overlapping clusters, by number (from 1), each the IDs of its contigs (their positions in the map, from 1, as in the network: see :func:metator.network.map_network), in the order that the partition lists them, and the name of each overlapping cluster (see :func:overlapping_name).

An overlapping cluster's contigs come in the order of its core clusters, by number, then of their IDs: the record order of the FASTA file miComplete checks.

Source code in src/metator/clusters.py
@dataclass
class Partition:
    """The clusters of a partition of the network of a map (see
    :func:`metator.partition.partition`): its core and its overlapping
    clusters, by number (from 1), each the IDs of its contigs (their positions
    in the map, from 1, as in the network: see
    :func:`metator.network.map_network`), in the order that the partition lists
    them, and the name of each overlapping cluster (see
    :func:`overlapping_name`).

    An overlapping cluster's contigs come in the order of its core clusters, by
    number, then of their IDs: the record order of the FASTA file miComplete
    checks."""

    core: dict
    overlapping: dict
    names: dict

    def sizes(self, lengths):
        """The size in bp of each overlapping cluster, by number: the sum of the
        lengths of its contigs (*lengths*, by contig ID - 1)."""
        return {number: int(sum(lengths[contig - 1] for contig in ids)) for number, ids in self.overlapping.items()}

sizes

sizes(lengths)

The size in bp of each overlapping cluster, by number: the sum of the lengths of its contigs (lengths, by contig ID - 1).

Source code in src/metator/clusters.py
def sizes(self, lengths):
    """The size in bp of each overlapping cluster, by number: the sum of the
    lengths of its contigs (*lengths*, by contig ID - 1)."""
    return {number: int(sum(lengths[contig - 1] for contig in ids)) for number, ids in self.overlapping.items()}

Rounds

The clustering rounds of a run, in the order they are made.

A cluster's parent is looked up in the latest round that holds a cluster of that name, as a recursive cluster replaces the one it was split from.

Source code in src/metator/clusters.py
class Rounds:
    """The clustering rounds of a run, in the order they are made.

    A cluster's parent is looked up in the latest round that holds a cluster of
    that name, as a recursive cluster replaces the one it was split from."""

    def __init__(self):
        self.clusters = []
        self.members = []
        self._latest = {}

    def add(self, round_name, name, contigs, parent=None, columns=None):
        """Record the cluster *name* of *round_name*.

        Parameters
        ----------
        round_name : str
            The round.
        name : str
            The name of the cluster.
        contigs : iterable of str
            The names of its contigs.
        parent : str, optional
            The name of the cluster it was split from, in an earlier round.
        columns : dict, optional
            Its other columns (those of miComplete)."""
        parent_round = self._latest.get(parent) if parent is not None else None
        if parent is not None and parent_round is None:
            raise ValueError(f"The parent of {name}, {parent}, is not a cluster of an earlier round.")
        self.clusters.append(
            {
                "round": round_name,
                "name": name,
                "parent_round": parent_round,
                "parent": parent if parent_round is not None else None,
                **(columns or {}),
            }
        )
        self.members.extend((round_name, name, contig) for contig in contigs)

    def close_round(self, round_name):
        """Make the clusters of *round_name* the latest ones of their names, once
        the round is recorded: its clusters' parents are of earlier rounds."""
        for cluster in self.clusters:
            if cluster["round"] == round_name:
                self._latest[cluster["name"]] = round_name

    def tables(self):
        """The two tables of the rounds: one row per cluster of every round, with
        its parent (missing for none) and its columns, and one row per contig
        of a cluster.

        Returns
        -------
        tuple of pandas.DataFrame
            The clusters and their contigs, with the columns of the tables that
            :meth:`write` writes."""
        clusters = pd.DataFrame(self.clusters, columns=_columns(self.clusters))
        members = pd.DataFrame(self.members, columns=["round", "cluster", "contig"])
        return clusters, members

    def write(self, outdir, lengths=None):
        """Write the two tables of the rounds in *outdir*: one row per cluster of
        every round, and one row per contig of a cluster.

        Parameters
        ----------
        outdir : str
            The directory of the tables.
        lengths : pandas.Series, optional
            The length of each contig, by name: each cluster then gets its
            number of contigs and their length (see with_sizes), as a run
            writes them, and as metator dump writes them from the map.

        Returns
        -------
        tuple of str
            The paths of the two tables."""
        clusters_file = join(outdir, CLUSTERS_FILE)
        members_file = join(outdir, CLUSTER_MEMBERS_FILE)
        clusters, members = self.tables()
        if lengths is not None:
            clusters = with_sizes(clusters, members, lengths)
        write_round_tables(clusters, members, clusters_file, members_file)
        return clusters_file, members_file

add

add(round_name, name, contigs, parent=None, columns=None)

Record the cluster name of round_name.

Parameters:

Name Type Description Default
round_name str

The round.

required
name str

The name of the cluster.

required
contigs iterable of str

The names of its contigs.

required
parent str

The name of the cluster it was split from, in an earlier round.

None
columns dict

Its other columns (those of miComplete).

None
Source code in src/metator/clusters.py
def add(self, round_name, name, contigs, parent=None, columns=None):
    """Record the cluster *name* of *round_name*.

    Parameters
    ----------
    round_name : str
        The round.
    name : str
        The name of the cluster.
    contigs : iterable of str
        The names of its contigs.
    parent : str, optional
        The name of the cluster it was split from, in an earlier round.
    columns : dict, optional
        Its other columns (those of miComplete)."""
    parent_round = self._latest.get(parent) if parent is not None else None
    if parent is not None and parent_round is None:
        raise ValueError(f"The parent of {name}, {parent}, is not a cluster of an earlier round.")
    self.clusters.append(
        {
            "round": round_name,
            "name": name,
            "parent_round": parent_round,
            "parent": parent if parent_round is not None else None,
            **(columns or {}),
        }
    )
    self.members.extend((round_name, name, contig) for contig in contigs)

close_round

close_round(round_name)

Make the clusters of round_name the latest ones of their names, once the round is recorded: its clusters' parents are of earlier rounds.

Source code in src/metator/clusters.py
def close_round(self, round_name):
    """Make the clusters of *round_name* the latest ones of their names, once
    the round is recorded: its clusters' parents are of earlier rounds."""
    for cluster in self.clusters:
        if cluster["round"] == round_name:
            self._latest[cluster["name"]] = round_name

tables

tables()

The two tables of the rounds: one row per cluster of every round, with its parent (missing for none) and its columns, and one row per contig of a cluster.

Returns:

Type Description
tuple of pandas.DataFrame

The clusters and their contigs, with the columns of the tables that :meth:write writes.

Source code in src/metator/clusters.py
def tables(self):
    """The two tables of the rounds: one row per cluster of every round, with
    its parent (missing for none) and its columns, and one row per contig
    of a cluster.

    Returns
    -------
    tuple of pandas.DataFrame
        The clusters and their contigs, with the columns of the tables that
        :meth:`write` writes."""
    clusters = pd.DataFrame(self.clusters, columns=_columns(self.clusters))
    members = pd.DataFrame(self.members, columns=["round", "cluster", "contig"])
    return clusters, members

write

write(outdir, lengths=None)

Write the two tables of the rounds in outdir: one row per cluster of every round, and one row per contig of a cluster.

Parameters:

Name Type Description Default
outdir str

The directory of the tables.

required
lengths Series

The length of each contig, by name: each cluster then gets its number of contigs and their length (see with_sizes), as a run writes them, and as metator dump writes them from the map.

None

Returns:

Type Description
tuple of str

The paths of the two tables.

Source code in src/metator/clusters.py
def write(self, outdir, lengths=None):
    """Write the two tables of the rounds in *outdir*: one row per cluster of
    every round, and one row per contig of a cluster.

    Parameters
    ----------
    outdir : str
        The directory of the tables.
    lengths : pandas.Series, optional
        The length of each contig, by name: each cluster then gets its
        number of contigs and their length (see with_sizes), as a run
        writes them, and as metator dump writes them from the map.

    Returns
    -------
    tuple of str
        The paths of the two tables."""
    clusters_file = join(outdir, CLUSTERS_FILE)
    members_file = join(outdir, CLUSTER_MEMBERS_FILE)
    clusters, members = self.tables()
    if lengths is not None:
        clusters = with_sizes(clusters, members, lengths)
    write_round_tables(clusters, members, clusters_file, members_file)
    return clusters_file, members_file

recursive_round

recursive_round(step)

The name of the round of recursive step step (1, 2...).

Source code in src/metator/clusters.py
def recursive_round(step):
    """The name of the round of recursive step *step* (1, 2...)."""
    return f"recursive_{step}"

core_name

core_name(number)

The name of the core cluster number (1, 2...) of a partition: core_00001..., as the Core_cluster_ID of the contig data tables numbers it (00001...).

Source code in src/metator/clusters.py
def core_name(number):
    """The name of the core cluster *number* (1, 2...) of a partition:
    ``core_00001``..., as the ``Core_cluster_ID`` of the contig data tables
    numbers it (``00001``...)."""
    return f"{CORE}_{number:05d}"

overlapping_name

overlapping_name(prefix, number)

The name of the overlapping cluster number (1, 2...) of a partition: <prefix>_<number>_00000, its FASTA file's name and its name in miComplete's results, as the validation names its recursive clusters <prefix>_<number>_<recursive number> (prefix: metator, or <--prefix>_metator).

Source code in src/metator/clusters.py
def overlapping_name(prefix, number):
    """The name of the overlapping cluster *number* (1, 2...) of a partition:
    ``<prefix>_<number>_00000``, its FASTA file's name and its name in
    miComplete's results, as the validation names its recursive clusters
    ``<prefix>_<number>_<recursive number>`` (*prefix*: ``metator``, or
    ``<--prefix>_metator``)."""
    return f"{prefix}_{number:05d}_{0:05d}"

cluster_number

cluster_number(round_name, name)

The number of a cluster of the round core or overlapping from its name (see :func:core_name and :func:overlapping_name): the number that the Core_cluster_ID or the Overlapping_cluster_ID of the contig data tables gives it, as an int. None for a name of another form: a cluster that metaTOR's partition did not name.

Source code in src/metator/clusters.py
def cluster_number(round_name, name):
    """The number of a cluster of the round ``core`` or ``overlapping`` from its
    name (see :func:`core_name` and :func:`overlapping_name`): the number that
    the ``Core_cluster_ID`` or the ``Overlapping_cluster_ID`` of the contig
    data tables gives it, as an int. None for a name of another form: a cluster
    that metaTOR's partition did not name."""
    if round_name == CORE:
        number = name[len(CORE) + 1 :] if name.startswith(f"{CORE}_") else ""
    else:
        parts = name.rsplit("_", 2)
        number = parts[1] if len(parts) == 3 and parts[0] and parts[2] == f"{0:05d}" else ""
    return int(number) if len(number) >= 5 and number.isascii() and number.isdigit() else None

record_partition

record_partition(rounds, partition, names, quality=None)

Record the rounds core and overlapping of a partition in rounds (a :class:Rounds): every core cluster, named :func:core_name, then every overlapping cluster, named as the partition names it, each with its contigs and no parent, in the order of their numbers. names: the name of each contig, by ID - 1. quality: the columns of miComplete of each overlapping cluster that it checked, by name (none for the others).

Source code in src/metator/clusters.py
def record_partition(rounds, partition, names, quality=None):
    """Record the rounds ``core`` and ``overlapping`` of a partition in *rounds*
    (a :class:`Rounds`): every core cluster, named :func:`core_name`, then
    every overlapping cluster, named as the partition names it, each with its
    contigs and no parent, in the order of their numbers. *names*: the name of
    each contig, by ID - 1. *quality*: the columns of miComplete of each
    overlapping cluster that it checked, by name (none for the others)."""
    quality = quality or {}
    for number, ids in sorted(partition.core.items()):
        rounds.add(CORE, core_name(number), [names[contig - 1] for contig in ids])
    rounds.close_round(CORE)
    for number, ids in sorted(partition.overlapping.items()):
        name = partition.names[number]
        rounds.add(OVERLAPPING, name, [names[contig - 1] for contig in ids], columns=quality.get(name))
    rounds.close_round(OVERLAPPING)
    return rounds

partition_rounds

partition_rounds(partition, names)

The rounds core and overlapping of a partition, as metator partition MAP stores them in the map: every cluster, with its contigs (by name: names, the name of each contig by ID - 1), and no column of miComplete (see :func:record_partition).

Returns:

Type Description
tuple of pandas.DataFrame

The clusters and their contigs (see :meth:Rounds.tables).

Source code in src/metator/clusters.py
def partition_rounds(partition, names):
    """The rounds ``core`` and ``overlapping`` of a partition, as ``metator
    partition MAP`` stores them in the map: every cluster, with its contigs (by
    name: *names*, the name of each contig by ID - 1), and no column of
    miComplete (see :func:`record_partition`).

    Returns
    -------
    tuple of pandas.DataFrame
        The clusters and their contigs (see :meth:`Rounds.tables`)."""
    return record_partition(Rounds(), partition, names).tables()

with_sizes

with_sizes(clusters, members, lengths)

The clusters table of the rounds with the number of contigs and the length of each cluster (SIZE_COLUMNS), after its parent: what metacooler computes from the contigs of a cluster of the map, a cluster without contigs having none (0 and 0).

Parameters:

Name Type Description Default
clusters DataFrame

The tables of the rounds (see Rounds.tables).

required
members DataFrame

The tables of the rounds (see Rounds.tables).

required
lengths Series

The length of each contig, by name.

required

Returns:

Type Description
DataFrame

A copy of clusters with the columns n_contigs and length.

Source code in src/metator/clusters.py
def with_sizes(clusters, members, lengths):
    """The clusters table of the rounds with the number of contigs and the length
    of each cluster (SIZE_COLUMNS), after its parent: what metacooler computes
    from the contigs of a cluster of the map, a cluster without contigs having
    none (0 and 0).

    Parameters
    ----------
    clusters, members : pandas.DataFrame
        The tables of the rounds (see Rounds.tables).
    lengths : pandas.Series
        The length of each contig, by name.

    Returns
    -------
    pandas.DataFrame
        A copy of clusters with the columns n_contigs and length."""
    keys = pd.MultiIndex.from_frame(clusters[["round", "name"]].astype(str))
    contigs = members.assign(length=members["contig"].astype(str).map(lengths))
    if contigs["length"].isna().any():
        unknown = sorted(set(contigs.loc[contigs["length"].isna(), "contig"]))
        raise ValueError(f"No length is given for {len(unknown)} contig(s) of the clusters: {', '.join(unknown[:5])}.")
    grouped = contigs.groupby([contigs["round"].astype(str), contigs["cluster"].astype(str)])
    sized = clusters.copy()
    position = list(sized.columns).index("parent") + 1
    sized.insert(position, "n_contigs", grouped.size().reindex(keys, fill_value=0).to_numpy(dtype="int64"))
    sized.insert(position + 1, "length", grouped["length"].sum().reindex(keys, fill_value=0).to_numpy(dtype="int64"))
    return sized

write_round_tables

write_round_tables(clusters, members, clusters_file, members_file)

Write the two tables of clustering rounds (see :meth:Rounds.tables): the clusters to clusters_file, a missing value written NA, and their contigs to members_file. :meth:Rounds.write writes those of a run so, and metator dump those of a map (see :func:metator.dump.dump).

Source code in src/metator/clusters.py
def write_round_tables(clusters, members, clusters_file, members_file):
    """Write the two tables of clustering rounds (see :meth:`Rounds.tables`): the
    clusters to clusters_file, a missing value written NA, and their contigs to
    members_file. :meth:`Rounds.write` writes those of a run so, and ``metator
    dump`` those of a map (see :func:`metator.dump.dump`)."""
    clusters.to_csv(clusters_file, sep="\t", index=False, na_rep="NA", quoting=csv.QUOTE_NONE)
    members.to_csv(members_file, sep="\t", index=False, quoting=csv.QUOTE_NONE)
    logger.debug(
        f"{len(clusters)} clusters in {clusters['round'].nunique()} rounds are written to {clusters_file} and {members_file}."
    )

read_rounds

read_rounds(outdir)

The two tables of the rounds that a run wrote in outdir, as :meth:Rounds.write writes them, without the number of contigs and the length of each cluster (SIZE_COLUMNS), which the map computes: the tables that :meth:Rounds.tables gives, which the map stores.

Returns:

Type Description
tuple of pandas.DataFrame, or None

The clusters and their contigs, or None when the run wrote neither.

Raises:

Type Description
ValueError

If only one of the two tables is there.

Source code in src/metator/clusters.py
def read_rounds(outdir):
    """The two tables of the rounds that a run wrote in *outdir*, as
    :meth:`Rounds.write` writes them, without the number of contigs and the
    length of each cluster (SIZE_COLUMNS), which the map computes: the tables
    that :meth:`Rounds.tables` gives, which the map stores.

    Returns
    -------
    tuple of pandas.DataFrame, or None
        The clusters and their contigs, or None when the run wrote neither.

    Raises
    ------
    ValueError
        If only one of the two tables is there."""
    paths = [join(outdir, CLUSTERS_FILE), join(outdir, CLUSTER_MEMBERS_FILE)]
    found = [exists(path) for path in paths]
    if not any(found):
        return None
    if not all(found):
        missing = paths[found.index(False)]
        raise ValueError(f"{missing} is missing: the clustering rounds of the run need both of {', '.join(paths)}.")
    # Names as written: a contig called NA, None or nan is a contig. Only
    # the missing values of the clusters table are NA (Rounds.write). Its
    # numbers are read back exactly (EXACT_FLOATS), as the map stores them.
    clusters = pd.read_csv(
        paths[0],
        sep="\t",
        dtype={"name": str, "parent": str, "round": str, "parent_round": str},
        keep_default_na=False,
        na_values=["NA"],
        **EXACT_FLOATS,
    ).drop(columns=list(SIZE_COLUMNS), errors="ignore")
    members = pd.read_csv(paths[1], sep="\t", dtype=str, keep_default_na=False)
    return clusters, members

mge_round

mge_round(summary, name=MGE)

The round mge (or mge_random: name): the MGE clusters of a run of metator mge, from their summary (see metator.mge.generate_bin_summary), in its order: each named as its FASTA files in fasta/mges (MetaTOR_MGE_<ID>), with its contigs (the Contigs column) and no parent. Its other columns are those of the summary (GC, Hit, BinningScore), but those that the map computes from the contigs (see :data:MGE_SUMMARY_KEYS): BinLength is the length of the cluster, and ContigsNumber its number of contigs.

Parameters:

Name Type Description Default
summary DataFrame

The summary of the MGE clusters.

required
name str

The name of the round: mge, or mge_random for a random clustering.

MGE

Returns:

Type Description
tuple of pandas.DataFrame

The clusters and their contigs (see :meth:Rounds.tables).

Source code in src/metator/clusters.py
def mge_round(summary, name=MGE):
    """The round ``mge`` (or ``mge_random``: name): the MGE clusters of a run of
    ``metator mge``, from their summary (see metator.mge.generate_bin_summary),
    in its order: each named as its FASTA files in ``fasta/mges``
    (``MetaTOR_MGE_<ID>``), with its contigs (the ``Contigs`` column) and no
    parent. Its other columns are those of the summary (GC, Hit, BinningScore),
    but those that the map computes from the contigs (see
    :data:`MGE_SUMMARY_KEYS`): ``BinLength`` is the length of the cluster, and
    ``ContigsNumber`` its number of contigs.

    Parameters
    ----------
    summary : pandas.DataFrame
        The summary of the MGE clusters.
    name : str
        The name of the round: ``mge``, or ``mge_random`` for a random
        clustering.

    Returns
    -------
    tuple of pandas.DataFrame
        The clusters and their contigs (see :meth:`Rounds.tables`)."""
    summary = summary.reset_index(drop=True)
    clusters = pd.DataFrame({"round": name, "name": summary["BinName"].astype(str), "parent_round": None, "parent": None})
    for column in summary.columns:
        if column not in MGE_SUMMARY_KEYS:
            clusters[column] = summary[column]
    members = pd.DataFrame(
        [
            (name, cluster, contig)
            for cluster, contigs in zip(summary["BinName"], summary["Contigs"], strict=True)
            for contig in str(contigs).split(",")
        ],
        columns=["round", "cluster", "contig"],
    )
    return clusters, members

metator.validation

Validates bins with miComplete, and partitions contaminated ones again.

Only bins with a weighted completeness of at least 33% and a contamination, (weighted redundancy - 1) / weighted completeness, of at least 5% go through the recursive step. Its bins replace the original when the most complete of them keeps more than 0.4 + (c - 0.4) / 1.6 of a completeness c; otherwise the original is kept. The step repeats on the new bins, 9 times at most (RECURSIVE_STEPS), and the log says when it stops sooner.

miComplete checks the overlapping clusters of the map's partition that reach --size, then those of each recursive step, from FASTA files that metacooler writes in the run's temporary directory. The validation's tables go there too (-N keeps them); the map of the clusters stores what they hold, and metator dump writes them from it. The plots of the final clusters go to the output directory of the run (see metator.figures).

bin_quality

bin_quality(completeness, redundancy)

The quality class of a bin, from miComplete's weighted completeness and weighted redundancy, its contamination being the redundancy minus 1:

  • HQ: completion >= 90% and contamination <= 5%;
  • MQ: completion >= 70% and contamination <= 10%;
  • LQ: completion >= 50% and contamination <= 10%;
  • Contaminated: completion >= 50% and contamination > 10%;
  • Other: completion < 50%.

Parameters:

Name Type Description Default
completeness float

Weighted completeness of the bin, from 0 to 1.

required
redundancy float

Weighted redundancy of the bin, 1 for no duplicated marker.

required

Returns:

Type Description
str

The class of the bin: "HQ", "MQ", "LQ", "Contaminated" or "Other".

Source code in src/metator/validation.py
def bin_quality(completeness, redundancy):
    """The quality class of a bin, from miComplete's weighted completeness and
    weighted redundancy, its contamination being the redundancy minus 1:

    - HQ: completion >= 90% and contamination <= 5%;
    - MQ: completion >= 70% and contamination <= 10%;
    - LQ: completion >= 50% and contamination <= 10%;
    - Contaminated: completion >= 50% and contamination > 10%;
    - Other: completion < 50%.

    Parameters
    ----------
    completeness : float
        Weighted completeness of the bin, from 0 to 1.
    redundancy : float
        Weighted redundancy of the bin, 1 for no duplicated marker.

    Returns
    -------
    str
        The class of the bin: "HQ", "MQ", "LQ", "Contaminated" or "Other".
    """
    completeness, redundancy = float(completeness), float(redundancy)
    if completeness < 0.5:
        return "Other"
    if redundancy > 1.1:
        return "Contaminated"
    if completeness >= 0.9 and redundancy <= 1.05:
        return "HQ"
    if completeness >= 0.7:
        return "MQ"
    return "LQ"

correct_final_bin

correct_final_bin(contigs_data, written, bin_summary)

Function to set the final bin of each contig from the contigs of the FASTA files of the final bins: the contigs written in <bin>.fa (written, the contigs of each FASTA file of the run, by cluster name: see write_overlapping_fasta and write_recursive_fasta) get the bin as Final_cluster.

Parameters:

Name Type Description Default
contigs_data DataFrame

Dataframe with the contigs informations.

required
written dict

The names of the contigs of the FASTA file of each cluster that the run checked, by cluster name.

required
bin_summary dict

Dictionnary with the informations of the final bins kept by MetaTOR.

required

Returns:

Type Description
DataFrame

Dataframe with the contigs informations.

Raises:

Type Description
ValueError

If a contig written in the FASTA file of a final bin is not in contigs_data.

Source code in src/metator/validation.py
def correct_final_bin(contigs_data, written, bin_summary):
    """Function to set the final bin of each contig from the contigs of the FASTA
    files of the final bins: the contigs written in ``<bin>.fa`` (written, the
    contigs of each FASTA file of the run, by cluster name: see
    write_overlapping_fasta and write_recursive_fasta) get the bin as
    Final_cluster.

    Parameters
    ----------
    contigs_data : pandas.core.frame.DataFrame
        Dataframe with the contigs informations.
    written : dict
        The names of the contigs of the FASTA file of each cluster that the run
        checked, by cluster name.
    bin_summary : dict
        Dictionnary with the informations of the final bins kept by MetaTOR.

    Returns
    -------
    pandas.core.frame.DataFrame
        Dataframe with the contigs informations.

    Raises
    ------
    ValueError
        If a contig written in the FASTA file of a final bin is not in
        contigs_data."""
    from metator.metacool import _shown

    contigs_data = contigs_data.set_index("Name", drop=False)
    # A contig written that the table lacks would be added to it, with no
    # other value (a name that the table read otherwise: 00123 as 123).
    absent = [name for bin_name in bin_summary for name in written[bin_name] if name not in contigs_data.index]
    if absent:
        raise ValueError(
            f"{len(absent)} contig(s) of the FASTA files of the final clusters are not in the contig data of the "
            f"validation: {_shown(absent)}."
        )
    for bin_name in bin_summary:
        for name in written[bin_name]:
            contigs_data.loc[name, "Final_cluster"] = bin_name
    contigs_data = contigs_data.reset_index(drop=True)
    return contigs_data

get_bin_coverage

get_bin_coverage(bin_summary, contigs_data)

Function to compute the coverage of each bin.

Parameters:

Name Type Description Default
bin_summary dict

Dictionnary with the informations of the final bins kept by MetaTOR.

required
contigs_data DataFrame

Dataframe with the contigs informations.

required

Returns:

Type Description
dict

Dictionnary with the informations of the final bins kept by MetaTOR with the coverage.

Source code in src/metator/validation.py
def get_bin_coverage(bin_summary, contigs_data):
    """Function to compute the coverage of each bin.

    Parameters
    ----------
    bin_summary : dict
        Dictionnary with the informations of the final bins kept by MetaTOR.
    contigs_data : pandas.core.frame.DataFrame
        Dataframe with the contigs informations.

    Returns
    -------
    dict
        Dictionnary with the informations of the final bins kept by MetaTOR
        with the coverage."""
    # Compute HiC_coverage
    total_hic_hit = 0
    total_sg_hit = 0
    for i in contigs_data.index:
        bin_name = contigs_data.loc[i, "Final_cluster"]
        if contigs_data.loc[contigs_data.index[0], "Shotgun_coverage"] != "-":
            total_sg_hit += contigs_data.loc[i, "Size"] * contigs_data.loc[i, "Shotgun_coverage"]
        total_hic_hit += contigs_data.loc[i, "Hit"]
        if bin_name != "ND":
            try:
                bin_summary[bin_name]["HiC_abundance"] += 100 * contigs_data.loc[i, "Hit"]
            except KeyError:
                bin_summary[bin_name]["HiC_abundance"] = 100 * contigs_data.loc[i, "Hit"]

            # If no depth files were given do not compute the Shotgun coverage.
            if contigs_data.loc[contigs_data.index[0], "Shotgun_coverage"] != "-":
                try:
                    bin_summary[bin_name]["SG_abundance"] += (
                        contigs_data.loc[i, "Size"] * contigs_data.loc[i, "Shotgun_coverage"] * 100
                    )
                except KeyError:
                    bin_summary[bin_name]["SG_abundance"] = (
                        contigs_data.loc[i, "Size"] * contigs_data.loc[i, "Shotgun_coverage"] * 100
                    )
    for bin_name in bin_summary:
        # A pair gives a hit to the contig of each of its reads: the hits of
        # the bin and the total both count read ends, so their ratio is
        # already the share of the Hi-C reads.
        bin_summary[bin_name]["HiC_abundance"] /= total_hic_hit
        if contigs_data.loc[contigs_data.index[0], "Shotgun_coverage"] != "-":
            bin_summary[bin_name]["SG_abundance"] /= total_sg_hit
    return bin_summary

give_results_info

give_results_info(bin_summary)

Function to return the general information about the binning results: the number and total size of the bins of each quality class (see bin_quality), in the log.

Parameters:

Name Type Description Default
bin_summary dict

Dictionnary with the summary results of the kept bins.

required
Source code in src/metator/validation.py
def give_results_info(bin_summary):
    """Function to return the general information about the binning results: the
    number and total size of the bins of each quality class (see bin_quality),
    in the log.

    Parameters
    ----------
    bin_summary : dict
        Dictionnary with the summary results of the kept bins."""
    # Count the bins and their size in each quality class.
    counts = {quality: [0, 0] for quality in ("HQ", "MQ", "LQ", "Contaminated", "Other")}
    for info in bin_summary.values():
        quality = bin_quality(info["Weighted completeness"], info["Weighted redundancy"])
        counts[quality][0] += 1
        counts[quality][1] += int(info["Length"])
    total = sum(count for count, _ in counts.values())
    total_size = sum(size for _, size in counts.values())

    # Return info in the logger:
    logger.info(f"{total} clusters kept after the recursive steps, {total_size} bp in all:")
    for quality, label in (
        ("HQ", "HQ MAGs"),
        ("MQ", "MQ MAGs"),
        ("LQ", "LQ MAGs"),
        ("Contaminated", "Contaminated potential MAGs"),
        ("Other", "Other clusters"),
    ):
        logger.info("{0}: {1}\tTotal Size: {2}".format(label, *counts[quality]))

merge_micomplete

merge_micomplete(out_bact105, out_arch131, outfile)

Merge the bacterial and archaeal outputs of miComplete into one file.

Parameters:

Name Type Description Default
out_bact105 str

Output of miComplete with its 105 bacterial markers.

required
out_arch131 str

Output of miComplete with its 131 archaeal markers.

required
outfile str

Path of the merged output.

required
Source code in src/metator/validation.py
def merge_micomplete(out_bact105, out_arch131, outfile):
    """Merge the bacterial and archaeal outputs of miComplete into one file.

    Parameters
    ----------
    out_bact105 : str
        Output of miComplete with its 105 bacterial markers.
    out_arch131 : str
        Output of miComplete with its 131 archaeal markers.
    outfile : str
        Path of the merged output.
    """
    # Reads both files.
    bact105 = pd.read_csv(out_bact105, sep="\t", comment="#", index_col=0, **mtc.EXACT_FLOATS).loc[:, :"CDs"]
    arch131 = pd.read_csv(out_arch131, sep="\t", comment="#", index_col=0, **mtc.EXACT_FLOATS).loc[:, :"CDs"]

    # Write header
    with open(outfile, "w") as out:
        out.write("## miComplete\n")
        out.write(f"## v{version('micomplete')}\n")
        out.write("## Weights: Bact105 and Arch131\n")
        out.write("Name\t{0}\tMarkers\n".format("\t".join(list(arch131.columns))))
        for bin_id in bact105.index:
            if bact105.loc[bin_id, "Weighted completeness"] >= arch131.loc[bin_id, "Weighted completeness"]:
                out.write("{0}\t{1}\tBacteria\n".format(bin_id, "\t".join(map(str, list(bact105.loc[bin_id])))))
            else:
                out.write("{0}\t{1}\tArchaea\n".format(bin_id, "\t".join(map(str, list(arch131.loc[bin_id])))))

micomplete_compare_bins

micomplete_compare_bins(
    recursive_micomplete_file, bin_summary, parent_dict, step
)

Compare the completness and contamination of the bins from the first step and from the recursive step. If the recursive step decrease the completion of one bin without decreasing its contamination, it will kept the bin before the recursive step.

A recursive split that would drop below 50% completion is not taken: complete bins are kept, even contaminated, for a curation by hand.

Parameters:

Name Type Description Default
recursive_micomplete_file str

Path to the miComplete summary from the recursive step.

required
bin_summary dict

Dictionnary containing iinformation about the bins.

required
parent_dict dict

Dictionnary with recursive bin_id as key and parent bin as values.

required
step int

Recursive step.

required

Returns:

Type Description
dict

Dictionnary with the informations of the final bins kept by MetaTOR.

Source code in src/metator/validation.py
def micomplete_compare_bins(
    recursive_micomplete_file,
    bin_summary,
    parent_dict,
    step,
):
    """Compare the completness and contamination of the bins from the first step
    and from the recursive step. If the recursive step decrease the completion
    of one bin without decreasing its contamination, it will kept the bin
    before the recursive step.

    A recursive split that would drop below 50% completion is not taken:
    complete bins are kept, even contaminated, for a curation by hand.

    Parameters
    ----------
    recursive_micomplete_file : str
        Path to the miComplete summary from the recursive step.
    bin_summary : dict
        Dictionnary containing iinformation about the bins.
    parent_dict : dict
        Dictionnary with recursive bin_id as key and parent bin as values.
    step : int
        Recursive step.

    Returns
    -------
    dict
        Dictionnary with the informations of the final bins kept by MetaTOR."""
    # Setup contamination
    contamination = False

    # Load the miComplete summary
    micomplete_recursive_summary = pd.read_csv(
        recursive_micomplete_file,
        sep="\t",
        comment="#",
        index_col=0,
        **mtc.EXACT_FLOATS,
    ).iloc[:, :13]

    # Group the recursive bins by parent bin, keeping the best completeness of
    # each family. Plain dicts: a list stored in a DataFrame cell is silently
    # turned into a string under pandas >= 3, which kept only the last child.
    children = {}
    max_rec_completeness = {}
    for recursive_bin in micomplete_recursive_summary.index:
        parent_bin = parent_dict[recursive_bin]
        children.setdefault(parent_bin, []).append(recursive_bin)
        completeness = float(micomplete_recursive_summary.loc[recursive_bin, "Weighted completeness"])
        max_rec_completeness[parent_bin] = max(completeness, max_rec_completeness.get(parent_bin, completeness))

    # If there are some recursive bins which have not loose too much completion
    # write their information otherwise keep the original bins.
    for overlapping_bin in list(bin_summary):
        if overlapping_bin not in children:
            bin_summary[overlapping_bin]["recursive"] = False
            continue
        max_rec = max_rec_completeness[overlapping_bin]
        over = float(bin_summary[overlapping_bin]["Weighted completeness"])
        if (max_rec - 0.4) > ((over - 0.4) / 1.6):
            for rec_id in children[overlapping_bin]:
                bin_summary[rec_id] = micomplete_recursive_summary.loc[rec_id, :"CDs"].to_dict()
                bin_summary[rec_id]["recursive"] = True
                bin_summary[rec_id]["step"] = step
                bin_summary[rec_id]["parent"] = overlapping_bin
            # A bin was replaced: run another recursive step.
            contamination = True
            bin_summary.pop(overlapping_bin)
        else:
            bin_summary[overlapping_bin]["recursive"] = False

    return bin_summary, contamination

micomplete_quality

micomplete_quality(fasta_dir, outfile, threads)

Function to evaluate fasta bins using miComplete. Write the bins quality summury in the outfile.

Parameters:

Name Type Description Default
fasta_dir str

Path to the input fasta of the bins to evaluate.

required
outfile str

Path to the file where the results of miComplete will be written.

required
threads int

Numbers of threads to use for miComplete.

required
Source code in src/metator/validation.py
def micomplete_quality(fasta_dir, outfile, threads):
    """Function to evaluate fasta bins using miComplete. Write the bins quality
    summury in the outfile.

    Parameters
    ----------
    fasta_dir : str
        Path to the input fasta of the bins to evaluate.
    outfile : str
        Path to the file where the results of miComplete will be written.
    threads : int
        Numbers of threads to use for miComplete."""
    # miComplete writes its intermediate files to the current directory, named
    # after each fasta: run it in a private directory, removed afterwards, so
    # that runs started from the same directory cannot clobber each other.
    fasta_dir = os.path.abspath(fasta_dir)
    workdir = tempfile.mkdtemp(prefix="micomplete_", dir=os.path.dirname(os.path.abspath(outfile)))
    tmp_seq_tab = join(workdir, "micomplete_seq.tsv")
    with open(tmp_seq_tab, "w") as tab:
        for path in sorted(os.listdir(fasta_dir)):
            if path.endswith(FASTA_EXTENSIONS):
                tab.write(f"{join(fasta_dir, path)}\tfna\n")

    # Run miComplete (through metator._micomplete, which patches it for recent
    # Biopython and Python, and runs pyrodigal and pyhmmer in place of prodigal
    # and hmmsearch) with the bacterial and the archaeal marker sets.
    out_bact105 = join(workdir, "micomplete_bact105.tsv")
    out_arch131 = join(workdir, "micomplete_arch131.tsv")
    for markers, out in (("Bact105", out_bact105), ("Arch131", out_arch131)):
        cmd = [
            sys.executable, "-m", "metator._micomplete", tmp_seq_tab,
            "--hmms", markers,
            "--weights", markers,
            "--threads", str(threads),
            "--outfile", out,
        ]  # fmt: skip
        # In the process group of the run: a Ctrl-C, or the signal that a job
        # scheduler sends to the job, reaches it too.
        sp.run(cmd, cwd=workdir, check=True)

    # Merge bacteria and archaea
    merge_micomplete(out_bact105, out_arch131, outfile)
    shutil.rmtree(workdir)

write_overlapping_fasta

write_overlapping_fasta(
    metacool, assembly, partition, contig_data, size, outdir, temp_dir=None
)

Write the FASTA file of each overlapping cluster of a partition that reaches size bp (--size), for miComplete to check: <outdir>/<name>.fa, the records of its contigs as they are in the assembly, in the order of the partition (that of its core clusters, then of their contigs: see metator.clusters.Partition), through metacooler.write_fasta.

Parameters:

Name Type Description Default
metacool str

The map of the partition (a path, or an entry of a collection).

required
assembly str

Path to the assembly that the map was made from.

required
partition Partition

The core and the overlapping clusters.

required
contig_data DataFrame

The contig data of the contigs of the map, in its order (see metator.network.contig_table): their names and sizes.

required
size int

The size in bp that an overlapping cluster reaches to be checked.

required
outdir str

The directory to write the files in, made if missing.

required
temp_dir str

Where metacooler copies a compressed assembly, plain: the temporary directory of the run.

None

Returns:

Type Description
dict

The names of the contigs of each cluster written, in the order of their records, by cluster name, the clusters by number.

Raises:

Type Description
ValueError

If the assembly lacks a contig of a cluster, or gives it another length than the map (the reason is logged as an error).

Source code in src/metator/validation.py
def write_overlapping_fasta(metacool, assembly, partition, contig_data, size, outdir, temp_dir=None):
    """Write the FASTA file of each overlapping cluster of a partition that
    reaches size bp (--size), for miComplete to check: ``<outdir>/<name>.fa``, the
    records of its contigs as they are in the assembly, in the order of the
    partition (that of its core clusters, then of their contigs: see
    metator.clusters.Partition), through metacooler.write_fasta.

    Parameters
    ----------
    metacool : str
        The map of the partition (a path, or an entry of a collection).
    assembly : str
        Path to the assembly that the map was made from.
    partition : metator.clusters.Partition
        The core and the overlapping clusters.
    contig_data : pandas.DataFrame
        The contig data of the contigs of the map, in its order (see
        metator.network.contig_table): their names and sizes.
    size : int
        The size in bp that an overlapping cluster reaches to be checked.
    outdir : str
        The directory to write the files in, made if missing.
    temp_dir : str, optional
        Where metacooler copies a compressed assembly, plain: the temporary
        directory of the run.

    Returns
    -------
    dict
        The names of the contigs of each cluster written, in the order of their
        records, by cluster name, the clusters by number.

    Raises
    ------
    ValueError
        If the assembly lacks a contig of a cluster, or gives it another length
        than the map (the reason is logged as an error)."""
    names = contig_data["Name"].to_numpy()
    sizes = partition.sizes(contig_data["Size"].to_numpy())
    kept = [number for number in partition.overlapping if sizes[number] >= size]
    groups = {partition.names[number]: [str(names[contig - 1]) for contig in partition.overlapping[number]] for number in kept}
    logger.info(
        f"{len(kept)} of the {len(partition.overlapping)} overlapping clusters reach {size} bp, "
        f"{round(sum(sizes[number] for number in kept) / 10**6, 3)} Mb in all: miComplete checks them."
    )
    _write_fasta(metacool, assembly, outdir, groups, temp_dir, "The clusters to check")
    return groups

plain_assembly

plain_assembly(assembly, directory)

The assembly as the run hands it to metacooler.write_fasta: the file itself, when it is plain, or its copy decompressed in directory (the temporary directory of the run), when it is compressed with gzip, made once for the run: write_fasta would copy it again for every FASTA file write (the overlapping clusters, each recursive step). The copy is named after the assembly, without its .gz: an error of write_fasta names it.

Source code in src/metator/validation.py
def plain_assembly(assembly, directory):
    """The assembly as the run hands it to metacooler.write_fasta: the file
    itself, when it is plain, or its copy decompressed in directory (the
    temporary directory of the run), when it is compressed with gzip, made once
    for the run: write_fasta would copy it again for every FASTA file write
    (the overlapping clusters, each recursive step). The copy is named after
    the assembly, without its .gz: an error of write_fasta names it."""
    if mio.file_compression(assembly) != "gz":
        return assembly
    name = os.path.basename(assembly)
    plain = join(directory, name[: -len(".gz")] if name.endswith(".gz") else f"{name}.fa")
    logger.info(f"Decompressing {assembly} into {plain}, once, for the FASTA files of the clusters.")
    with gzip.open(assembly, "rb") as source, open(plain, "wb") as copy:
        shutil.copyfileobj(source, copy)
    return plain

write_recursive_fasta

write_recursive_fasta(metacool, assembly, groups, outdir, temp_dir=None)

Write the FASTA file of each cluster of a recursive step for miComplete to check: <outdir>/<name>.fa, the records of its contigs (groups: their names, by cluster name) as they are in the assembly, in their order, through metacooler.write_fasta, as write_overlapping_fasta writes those of the overlapping clusters.

Raises:

Type Description
ValueError

If the assembly lacks a contig of a cluster, or gives it another length than the map (the reason is logged as an error).

Source code in src/metator/validation.py
def write_recursive_fasta(metacool, assembly, groups, outdir, temp_dir=None):
    """Write the FASTA file of each cluster of a recursive step for miComplete to
    check: ``<outdir>/<name>.fa``, the records of its contigs (groups: their names,
    by cluster name) as they are in the assembly, in their order, through
    metacooler.write_fasta, as write_overlapping_fasta writes those of the
    overlapping clusters.

    Raises
    ------
    ValueError
        If the assembly lacks a contig of a cluster, or gives it another length
        than the map (the reason is logged as an error)."""
    _write_fasta(metacool, assembly, outdir, groups, temp_dir, "The clusters of the recursive step")

recursive_clustering

recursive_clustering(
    iterations,
    overlapping_parameter,
    resolution_parameter,
    algorithm,
    bin_summary,
    contigs_data,
    network,
    size,
    threads,
    prefix,
)

Function to run recursive iterations on contaminated bins in order to try to improve the quality of the bins using Louvain or Leiden algorithm.

Parameters:

Name Type Description Default
iterations int

Number of iterations to use for recursive iterations of Louvain or Leiden.

required
overlapping_parameter float

Hamming distance threshold to consider two bins as the same bin.

required
resolution_parameter float

Resolution parameter of Leiden algorithm.

required
algorithm str

Algorithm to use, either louvain or leiden.

required
bin_summary dict

Dictionary containing information about the bins.

required
contigs_data DataFrame

Table with all the data from the contigs.

required
network DataFrame

The network of the contigs of the map: one row per edge, with the columns contig1, contig2 and weight (see metator.network.map_network).

required
size int

Size threshold in base pairs of the bins.

required
threads int

Number of threads to use.

required
prefix str

Sample prefix to use.

required

Returns:

Type Description
boolean

True if at least one new recursive bin has been generated.

DataFrame

Updated dictionnary which has as keys the values of the iterations from the recursive partition separated by a semicolon and as values the list of the id of the contigs.

dict

Dictionnary with recursive bin_id as key and parent bin as values.

dict

The names of the contigs of each new recursive bin, in the order of the records of its FASTA file (see write_recursive_fasta), by bin name.

Source code in src/metator/validation.py
def recursive_clustering(
    iterations,
    overlapping_parameter,
    resolution_parameter,
    algorithm,
    bin_summary,
    contigs_data,
    network,
    size,
    threads,
    prefix,
):
    """Function to run recursive iterations on contaminated bins in order to try
    to improve the quality of the bins using Louvain or Leiden algorithm.

    Parameters
    ----------
    iterations : int
        Number of iterations to use for recursive iterations of Louvain or
        Leiden.
    overlapping_parameter : float
        Hamming distance threshold to consider two bins as the same bin.
    resolution_parameter : float
        Resolution parameter of Leiden algorithm.
    algorithm : str
        Algorithm to use, either louvain or leiden.
    bin_summary : dict
        Dictionary containing information about the bins.
    contigs_data : pandas.DataFrame
        Table with all the data from the contigs.
    network : pandas.DataFrame
        The network of the contigs of the map: one row per edge, with the
        columns contig1, contig2 and weight (see metator.network.map_network).
    size : int
        Size threshold in base pairs of the bins.
    threads : int
        Number of threads to use.
    prefix : str
        Sample prefix to use.

    Returns
    -------
    boolean
        True if at least one new recursive bin has been generated.
    pandas.DataFrame
        Updated dictionnary which has as keys the values of the iterations from
        the recursive partition separated by a semicolon and as values the list
        of the id of the contigs.
    dict
        Dictionnary with recursive bin_id as key and parent bin as values.
    dict
        The names of the contigs of each new recursive bin, in the order of the
        records of its FASTA file (see write_recursive_fasta), by bin name."""

    # Default no contamination
    contamination = False

    # Put iterations to on eif spinglass partition used.
    if algorithm == "spinglass":
        iterations = 1
        logger.error("Spinglass is no longer maintained.")
        raise ValueError

    # Check bin_id to decontaminate.
    bin_ids = contaminated_bins(bin_summary)

    # Iterate on cmicomplete summary to find conatminated bins:
    # pool = multiprocessing.Pool(processes=threads)
    output_partitions = list(
        map(
            partial(
                recursive_clustering_worker,
                network=network,
                algorithm=algorithm,
                iterations=iterations,
                resolution_parameter=resolution_parameter,
                contigs_data=contigs_data,
            ),
            bin_ids,
        )
    )

    parent_dict = dict()
    groups = dict()

    for i, bin_id in enumerate(bin_ids):
        output_partition = output_partitions[i]

        # Detect core bins
        (
            recursive_core_bins,
            recursive_bins_iterations,
        ) = mtp.detect_core_bins(output_partition, iterations)

        # Compute the Hamming distance between core bins.
        hamming_distance = mtp.get_hamming_distance(
            recursive_bins_iterations,
            threads,
        )

        # Defined overlapping bins according to the threshold
        recursive_bins = mtp.defined_overlapping_bins(
            overlapping_parameter,
            hamming_distance,
            recursive_core_bins,
        )

        # The new bins: their IDs in the contig data, and their contigs.
        contamination = (
            name_recursive_clusters(
                bin_id,
                contigs_data,
                recursive_bins,
                size,
                parent_dict,
                prefix,
                groups,
            )
            or contamination
        )

        logger.debug("Recursive step for {0} is done.".format(bin_id))

    return contamination, contigs_data, parent_dict, groups

contaminated_bins

contaminated_bins(bin_summary)

The bins that a recursive step partitions again (see recursive_clustering): those that the step before made (their recursive flag: the overlapping clusters at the first step), with a weighted completeness of at least 33% and a contamination, (weighted redundancy - 1) / weighted completeness, of at least 5%.

Parameters:

Name Type Description Default
bin_summary dict

Dictionary containing information about the bins.

required

Returns:

Type Description
list of str

The names of the bins, in the order of bin_summary.

Source code in src/metator/validation.py
def contaminated_bins(bin_summary):
    """The bins that a recursive step partitions again (see
    recursive_clustering): those that the step before made (their recursive
    flag: the overlapping clusters at the first step), with a weighted
    completeness of at least 33% and a contamination, (weighted redundancy -
    1) / weighted completeness, of at least 5%.

    Parameters
    ----------
    bin_summary : dict
        Dictionary containing information about the bins.

    Returns
    -------
    list of str
        The names of the bins, in the order of bin_summary."""
    bin_ids = []
    for bin_id in bin_summary:
        try:
            completness = float(bin_summary[bin_id]["Weighted completeness"])
            conta = float(bin_summary[bin_id]["Weighted redundancy"])
            recursive = bin_summary[bin_id]["recursive"]
            if recursive:
                if completness >= 0.33:
                    if (conta - 1) / completness >= 0.05:
                        bin_ids.append(bin_id)
        except KeyError:
            continue
    return bin_ids

bin_contig_ids

bin_contig_ids(bin_id, contigs_data)

Function to list the IDs of the contigs of a bin from the contigs data: those of its overlapping bin and recursive bin, given by its name (<prefix>_<overlapping bin ID>_<recursive bin ID>).

Parameters:

Name Type Description Default
bin_id str

Name of the bin.

required
contigs_data DataFrame

Table with all the data from the contigs.

required

Returns:

Type Description
list of int

IDs of the contigs of the bin.

Source code in src/metator/validation.py
def bin_contig_ids(bin_id, contigs_data):
    """Function to list the IDs of the contigs of a bin from the contigs data:
    those of its overlapping bin and recursive bin, given by its name
    (``<prefix>_<overlapping bin ID>_<recursive bin ID>``).

    Parameters
    ----------
    bin_id : str
        Name of the bin.
    contigs_data : pandas.DataFrame
        Table with all the data from the contigs.

    Returns
    -------
    list of int
        IDs of the contigs of the bin."""
    over_bin_id = str(bin_id.split("_")[-2])
    rec_bin_id = str(bin_id.split("_")[-1])
    mask = (contigs_data["Overlapping_cluster_ID"] == over_bin_id) & (
        contigs_data["Recursive_cluster_ID"].apply(str) == rec_bin_id
    )
    return list(contigs_data.loc[mask, "ID"])

recursive_clustering_worker

recursive_clustering_worker(
    bin_id, network, algorithm, iterations, resolution_parameter, contigs_data
)

Worker to partition one bin if it's contaminated: its subnetwork, the edges of the network between two of its contigs, in their order.

Parameters:

Name Type Description Default
bin_id str

Name of the bin.

required
network DataFrame

Network of contigs from HiC librairies: one row per edge, with the columns contig1, contig2 and weight.

required
algorithm str

Algorithm to use, either louvain or leiden.

required
iterations int

Number of iterations to use for recursive iterations of Louvain or Leiden.

required
resolution_parameter float

Resolution parameter of Leiden algorithm.

required
contigs_data DataFrame

The contig data of the partition, with the recursive bins so far.

required
Source code in src/metator/validation.py
def recursive_clustering_worker(
    bin_id,
    network,
    algorithm,
    iterations,
    resolution_parameter,
    contigs_data,
):
    """Worker to partition one bin if it's contaminated: its subnetwork, the edges
    of the network between two of its contigs, in their order.

    Parameters
    ----------
    bin_id : str
        Name of the bin.
    network : pandas.DataFrame
        Network of contigs from HiC librairies: one row per edge, with the
        columns contig1, contig2 and weight.
    algorithm : str
        Algorithm to use, either louvain or leiden.
    iterations : int
        Number of iterations to use for recursive iterations of Louvain or
        Leiden.
    resolution_parameter : float
        Resolution parameter of Leiden algorithm.
    contigs_data : pandas.DataFrame
        The contig data of the partition, with the recursive bins so far."""
    logger.debug("Cluster in progress: {0}".format(bin_id))

    # Extract contigs
    list_contigs = bin_contig_ids(bin_id, contigs_data)

    # Extract subnetwork: the edges between two contigs of the bin.
    subnetwork = network[network["contig1"].isin(list_contigs) & network["contig2"].isin(list_contigs)]

    # Partition the subnetwork.
    output_partition = mtp.algo_partition(
        algorithm,
        subnetwork,
        iterations,
        resolution_parameter,
    )
    logger.debug("Output partition done for {0}.".format(bin_id))

    return output_partition

recursive_decontamination

recursive_decontamination(
    algorithm,
    assembly,
    contig_data_file,
    final_fasta_dir,
    input_fasta_dir,
    iterations,
    network,
    outdir,
    overlapping_parameter,
    recursive_fasta_dir,
    resolution_parameter,
    size,
    threads,
    prefix,
    partition,
    *,
    metacool,
    written,
    temp_dir=None,
    plot_outdir=None,
)

Function to validate bins do the recursive decontamination using Louvain or Leiden algorithm

Parameters:

Name Type Description Default
algorithm str

Algorithm to use to recursively partition the network.

required
assembly str

Path to the assembly file used for the partition.

required
contig_data_file str

Path to the contig data table of the partition (see metator.partition.partition_table), to update.

required
final_fasta_dir str

Path to write the final fasta decontaminated bins.

required
input_fasta_dir str

Path to the directory of the FASTA files of the overlapping clusters to check (see write_overlapping_fasta).

required
iterations int

Number of iterations to use for the recursive partition.

required
network DataFrame

The network of the contigs of the map, in the IDs of the contigs in contig_data_file: their positions in the map as the run read it (see metator.network.map_network), which the contig data of the partition numbers them by too (see metator.partition.partition_table).

required
outdir str

Path to the directory where to write the tables of the validation: the temporary directory of the run (see the module's docstring).

required
overlapping_parameter int

Hamming distance threshold in percentage to use to consider to bins as one in the recursive partition.

required
recursive_fasta_dir str

Path to write the fasta decontaminated bins, one directory per recursive step (step_<k>): in the temporary directory of the run.

required
resolution_parameter float

Resolution parameter to use if Leiden algorithm is chosen.

required
size int

Threshold size in base pair of the output bins.

required
threads int

Number of threads to use.

required
prefix str

Sample prefix to use.

required
partition Partition

The core and the overlapping clusters of the partition, recorded as the first rounds of the run (see metator.clusters.record_partition): every cluster, those that miComplete checked with its columns.

required
metacool str

The map of the run, which metacooler writes the FASTA files of the recursive clusters from the assembly with (see write_recursive_fasta).

required
written dict

The names of the contigs of the FASTA file of each overlapping cluster in input_fasta_dir, by cluster name (see write_overlapping_fasta).

required
temp_dir str

Where metacooler copies a compressed assembly, plain: the temporary directory of the run.

None
plot_outdir str

The output directory of the run, where the plots of the final clusters are drawn, in plots/ (see metator.figures.plot_figures). None draws none.

None

Returns:

Type Description
DataFrame

The contig data of the validation, with the final cluster of each contig (Final_cluster, ND for none), as contig_data_final.txt holds it.

SummaryLayout

How the summary of the final clusters (cluster_summary.txt) is written: its rows, its columns and their format.

Source code in src/metator/validation.py
def recursive_decontamination(
    algorithm,
    assembly,
    contig_data_file,
    final_fasta_dir,
    input_fasta_dir,
    iterations,
    network,
    outdir,
    overlapping_parameter,
    recursive_fasta_dir,
    resolution_parameter,
    size,
    threads,
    prefix,
    partition,
    *,
    metacool,
    written,
    temp_dir=None,
    plot_outdir=None,
):
    """Function to validate bins do the recursive decontamination using Louvain or
    Leiden algorithm

    Parameters
    ----------
    algorithm : str
        Algorithm to use to recursively partition the network.
    assembly : str
        Path to the assembly file used for the partition.
    contig_data_file : str
        Path to the contig data table of the partition (see
        metator.partition.partition_table), to update.
    final_fasta_dir : str
        Path to write the final fasta decontaminated bins.
    input_fasta_dir : str
        Path to the directory of the FASTA files of the overlapping clusters to
        check (see write_overlapping_fasta).
    iterations : int
        Number of iterations to use for the recursive partition.
    network : pandas.DataFrame
        The network of the contigs of the map, in the IDs of the contigs in
        contig_data_file: their positions in the map as the run read it (see
        metator.network.map_network), which the contig data of the partition
        numbers them by too (see metator.partition.partition_table).
    outdir : str
        Path to the directory where to write the tables of the validation: the
        temporary directory of the run (see the module's docstring).
    overlapping_parameter : int
        Hamming distance threshold in percentage to use to consider to bins as
        one in the recursive partition.
    recursive_fasta_dir : str
        Path to write the fasta decontaminated bins, one directory per
        recursive step (``step_<k>``): in the temporary directory of the run.
    resolution_parameter : float
        Resolution parameter to use if Leiden algorithm is chosen.
    size : int
        Threshold size in base pair of the output bins.
    threads : int
        Number of threads to use.
    prefix : str
        Sample prefix to use.
    partition : metator.clusters.Partition
        The core and the overlapping clusters of the partition, recorded as the
        first rounds of the run (see metator.clusters.record_partition): every
        cluster, those that miComplete checked with its columns.
    metacool : str
        The map of the run, which metacooler writes the FASTA files of the
        recursive clusters from the assembly with (see write_recursive_fasta).
    written : dict
        The names of the contigs of the FASTA file of each overlapping cluster
        in input_fasta_dir, by cluster name (see write_overlapping_fasta).
    temp_dir : str, optional
        Where metacooler copies a compressed assembly, plain: the temporary
        directory of the run.
    plot_outdir : str, optional
        The output directory of the run, where the plots of the final clusters
        are drawn, in ``plots/`` (see metator.figures.plot_figures). None draws
        none.

    Returns
    -------
    pandas.DataFrame
        The contig data of the validation, with the final cluster of each
        contig (Final_cluster, ND for none), as contig_data_final.txt holds it.
    metator.io.SummaryLayout
        How the summary of the final clusters (cluster_summary.txt) is written:
        its rows, its columns and their format."""

    # No bin to validate: miComplete would write no result to read.
    if not any(path.endswith(FASTA_EXTENSIONS) for path in os.listdir(input_fasta_dir)):
        logger.error(
            "No overlapping cluster of the partition reaches the minimum size of a cluster to check (--size of "
            "validation or pipeline): there is no cluster to validate."
        )
        raise ValueError

    # Defined miComplete output file path
    overlapping_micomplete_file = join(outdir, "overlapping_micomplete_results.txt")

    # Launch miComplete
    started = time.monotonic()
    micomplete_quality(
        input_fasta_dir,
        overlapping_micomplete_file,
        threads,
    )
    checked = time.monotonic() - started

    # Load contigs data:
    contigs_data = pd.read_csv(
        contig_data_file,
        sep="\t",
        header=0,
        # Names as written: a contig named 00123 is not the number 123, nor
        # one named 1e5 a number at all.
        dtype={"Name": str},
        # As written: "00008", not 8.
        converters={"Overlapping_cluster_ID": str},
        # A contig named NA (or null, N/A...) is a name: only an empty field,
        # as pandas writes a missing value, is one.
        keep_default_na=False,
        na_values=[""],
        # The numbers as the map gives them (see metator.clusters.EXACT_FLOATS).
        **mtc.EXACT_FLOATS,
    )
    contigs_data["index"] = contigs_data["ID"] - 1
    contigs_data = contigs_data.set_index("index")

    # Add new coulumns for recursive information.
    contigs_data["Recursive_cluster_ID"] = f"{0:05d}"
    contigs_data["Recursive_cluster_contigs"] = pd.Series("-", index=contigs_data.index, dtype=object)
    contigs_data["Recursive_cluster_size"] = pd.Series("-", index=contigs_data.index, dtype=object)
    contigs_data["Final_cluster"] = "ND"

    # Load miComplete result:
    bin_summary = mio.micomplete_results_to_dict(overlapping_micomplete_file)

    # The clustering rounds of the run, for its map (see metator.clusters):
    # first those of the partition, every core and overlapping cluster, the
    # overlapping clusters that miComplete checked with its columns.
    rounds = mtc.record_partition(mtc.Rounds(), partition, list(contigs_data.sort_index()["Name"]), quality=bin_summary)

    # The contigs of the FASTA file of each cluster checked, by name: those of
    # the final clusters are theirs.
    written = dict(written)

    # Add columns about recursive step.
    for bin_id in bin_summary:
        bin_summary[bin_id]["recursive"] = True
        bin_summary[bin_id]["step"] = 0
        bin_summary[bin_id]["parent"] = None
    logger.info(
        f"miComplete checked the {len(bin_summary)} clusters in {duration(checked)}, and found "
        f"{len(contaminated_bins(bin_summary))} of them contaminated, which the recursive steps partition again."
    )

    # Recursively remove contamination: RECURSIVE_STEPS steps at most, each on
    # the contaminated bins that the step before made, until a step makes no
    # bin that replaces its own.
    for step in range(1, RECURSIVE_STEPS + 1):
        started = time.monotonic()
        counted = f"Recursive step {step}/{RECURSIVE_STEPS}"
        contaminated = len(contaminated_bins(bin_summary))
        if contaminated:
            logger.info(f"{counted}: {contaminated} contaminated cluster(s) to partition again.")
        # Create fasta dir.
        recursive_fasta_dir_step = join(recursive_fasta_dir, f"step_{step}")
        os.makedirs(recursive_fasta_dir_step, exist_ok=True)

        # Iterates Louvain or Leiden on contaminated and complete bins.
        (
            contamination,
            contigs_data,
            parent_dict,
            groups,
        ) = recursive_clustering(
            iterations,
            overlapping_parameter,
            resolution_parameter,
            algorithm,
            bin_summary,
            contigs_data,
            network,
            size,
            threads,
            prefix,
        )

        # The FASTA files of the new bins, for miComplete.
        write_recursive_fasta(metacool, assembly, groups, recursive_fasta_dir_step, temp_dir)
        written.update(groups)

        # Keep the bins as they are: no contaminated bin, or none splits into
        # bins larger than size.
        if not contamination:
            if not contaminated and step == 1:
                found = "no cluster is contaminated, so no recursive step is needed"
            elif not contaminated:
                found = "no contaminated cluster left, so no further recursive step is needed"
            else:
                found = f"none of them splits into clusters of more than {size} bp, so no further recursive step is needed"
            logger.info(f"{counted}: {found}.")
            break

        # Recursive iterations of Louvain or Leiden on the contaminated bins.
        # Save bin information if the new bins have the same quality otherwise
        # keep the original bin information.
        # Run miComplete on the recursive bins.
        recursive_micomplete_file = join(outdir, f"recursive_micomplete_step_{step}.txt")

        micomplete_quality(
            recursive_fasta_dir_step,
            recursive_micomplete_file,
            threads,
        )

        # The clusters of this step, with their contigs now: a later step
        # gives the contigs of a cluster it splits other IDs.
        step_round = mtc.recursive_round(step)
        step_quality = mio.micomplete_results_to_dict(recursive_micomplete_file)
        for bin_id, parent in parent_dict.items():
            rounds.add(
                step_round,
                bin_id,
                _bin_contigs(bin_id, contigs_data),
                parent=parent,
                columns=step_quality.get(bin_id),
            )
        rounds.close_round(step_round)

        # Compare
        before = set(bin_summary)
        bin_summary, contamination = micomplete_compare_bins(
            recursive_micomplete_file,
            bin_summary,
            parent_dict,
            step,
        )
        took = duration(time.monotonic() - started)
        if not contamination:
            logger.info(
                f"{counted}: none of them is replaced, as the {len(groups)} cluster(s) they split into lose too much "
                f"of their completeness ({took}), so no further recursive step is needed."
            )
            break
        logger.info(
            f"{counted}: {len(before - set(bin_summary))} of them replaced by the {len(set(bin_summary) - before)} "
            f"cluster(s) of more than {size} bp that they split into ({took})."
        )
    else:
        logger.info(f"Recursive step {RECURSIVE_STEPS}/{RECURSIVE_STEPS} was the last: its clusters are kept as they are.")

    # Whether each final bin comes from the recursive partition: the flag
    # marked the bins to examine at the next step.
    for info in bin_summary.values():
        info["recursive"] = info["step"] > 0

    # Create fasta directory and copy final bins.
    if not os.path.exists(final_fasta_dir):
        os.makedirs(final_fasta_dir)

    for bin_name in bin_summary:
        dst = join(final_fasta_dir, bin_name + ".fa")
        step = bin_summary[bin_name]["step"]
        if step == 0:
            src = join(input_fasta_dir, bin_name + ".fa")
        else:
            src = join(recursive_fasta_dir, f"step_{step}", f"{bin_name}.fa")
        shutil.copyfile(src, dst)

    # Return some values of efficiency of the binning.
    give_results_info(bin_summary)

    # Correct final bin value in contigs data
    contigs_data = correct_final_bin(contigs_data, written, bin_summary)

    # The contigs of the final bins and their bin, without header: the
    # binning that anvio imports.
    binned = contigs_data[contigs_data["Final_cluster"].isin(list(bin_summary))]
    binned[["Name", "Final_cluster"]].to_csv(join(outdir, "binning.txt"), sep="\t", header=False, index=False)

    # Compute the abundance of the mags.
    bin_summary = get_bin_coverage(bin_summary, contigs_data)

    # The final clusters, each the cluster of the same name of the round it
    # comes from, with the columns of the bin summary (but its parent, which
    # the round says).
    final_contigs = contigs_data.groupby("Final_cluster")["Name"]
    for bin_name, info in bin_summary.items():
        rounds.add(
            mtc.FINAL,
            bin_name,
            final_contigs.get_group(bin_name) if bin_name in final_contigs.groups else [],
            parent=bin_name,
            columns={key: value for key, value in info.items() if key not in ("parent", "recursive")},
        )
    # Each cluster with its number of contigs and their length, as the map
    # computes them, and as metator dump writes them.
    rounds.write(outdir, pd.Series(contigs_data["Size"].to_numpy(), index=contigs_data["Name"].astype(str).to_numpy()))

    # Save bin information in final file
    summary = mio.write_bin_summary(bin_summary, join(outdir, "cluster_summary.txt"), join(outdir, mio.SUMMARY_FULL_FILE))

    # Write the new file
    contigs_data.to_csv(join(outdir, "contig_data_final.txt"), sep="\t", header=True, index=True)

    # The plots of the final clusters, from the numbers of miComplete, which
    # the summary rounds: their quality classes are those of the log.
    if plot_outdir is not None:
        mtf.plot_figures(plot_outdir, contigs_data, bin_summary, size)
    return contigs_data, summary

name_recursive_clusters

name_recursive_clusters(
    bin_id, contigs_data, recursive_bins, size, parent_dict, prefix, groups
)

Record the bins of the recursive partition of a contaminated bin that are larger than size: their IDs in the contig data, their parent, and their contigs, for their FASTA files (see write_recursive_fasta).

Parameters:

Name Type Description Default
bin_id str

Name of the parental bin.

required
contigs_data DataFrame

Table with all the data from the contigs, updated in place: the Recursive_cluster_ID, Recursive_cluster_contigs and Recursive_cluster_size of the contigs of each new bin.

required
recursive_bins dict

Dictionnary which has as keys the values of the recursive iterations from Louvain or Leiden separated by a semicolon and as values the list of the id of the contigs.

required
size int

Size threshold of a bin.

required
parent_dict dict

Dictionnary with recursive bin_id as key and parent bin as values, updated in place.

required
prefix str

Sample prefix to use.

required
groups dict

The names of the contigs of each new bin, in the order of the partition, by bin name (<prefix>_<overlapping ID>_<recursive ID>), updated in place.

required

Returns:

Type Description
boolean

True if one bin is larger than size.

Source code in src/metator/validation.py
def name_recursive_clusters(bin_id, contigs_data, recursive_bins, size, parent_dict, prefix, groups):
    """Record the bins of the recursive partition of a contaminated bin that are
    larger than size: their IDs in the contig data, their parent, and their
    contigs, for their FASTA files (see write_recursive_fasta).

    Parameters
    ----------
    bin_id : str
        Name of the parental bin.
    contigs_data : pandas.DataFrame
        Table with all the data from the contigs, updated in place: the
        Recursive_cluster_ID, Recursive_cluster_contigs and
        Recursive_cluster_size of the contigs of each new bin.
    recursive_bins : dict
        Dictionnary which has as keys the values of the recursive iterations
        from Louvain or Leiden separated by a semicolon and as values the list
        of the id of the contigs.
    size : int
        Size threshold of a bin.
    parent_dict : dict
        Dictionnary with recursive bin_id as key and parent bin as values,
        updated in place.
    prefix : str
        Sample prefix to use.
    groups : dict
        The names of the contigs of each new bin, in the order of the
        partition, by bin name (``<prefix>_<overlapping ID>_<recursive ID>``),
        updated in place.

    Returns
    -------
    boolean
        True if one bin is larger than size."""
    contamination = False
    # Add recursive bin information
    rec_id = 1

    # Extract last recursive ID.
    over_id = contigs_data.loc[recursive_bins[1][0] - 1, "Overlapping_cluster_ID"]
    max_rec_id = max(
        map(
            int,
            contigs_data[contigs_data.Overlapping_cluster_ID == over_id]["Recursive_cluster_ID"],
        )
    )

    for i in recursive_bins:
        # Extract contigs of the bin
        recursive_bin = [id - 1 for id in recursive_bins[i]]
        recursive_bin_data = contigs_data.loc[recursive_bin]
        recursive_bin_contigs_number = len(recursive_bin)
        recursive_bin_length = sum(recursive_bin_data.Size)

        if recursive_bin_length > size:
            # If one new bin is generated change the boolean value to True
            contamination = True
            rec_final_id = max_rec_id + rec_id
            # Write the new information
            contigs_data.loc[recursive_bin, "Recursive_cluster_ID"] = f"{rec_final_id:05d}"
            contigs_data.loc[recursive_bin, "Recursive_cluster_contigs"] = recursive_bin_contigs_number
            contigs_data.loc[recursive_bin, "Recursive_cluster_size"] = recursive_bin_length

            # Defined name of the recursive bin
            oc_id = int(contigs_data.loc[recursive_bin[0], "Overlapping_cluster_ID"])
            name = f"{prefix}_{oc_id:05d}_{rec_final_id:05d}"

            # Update bin_summary:
            parent_dict[name] = bin_id

            # The contigs of its FASTA file.
            groups[name] = [str(contig) for contig in contigs_data.loc[recursive_bin, "Name"]]

            # Add one to the recursive id
            rec_id += 1

    return contamination

metator.markers

The marker genes of the contigs of a .metacool map, as miComplete finds those of a bin: metator markers.

miComplete gives a bin four numbers from the single-copy marker genes found in it: its completeness, redundancy, weighted completeness and weighted redundancy. Each comes from the marker genes of the bin, and each marker gene lies on one contig: stored per contig, the markers of a genome give its four numbers again, with no gene to find (see marker_quality), exactly those that miComplete gives it as the markers were found (trained in single genome mode on its contigs, in the order of the map, see below). Those of any other group of contigs (two genomes merged, a contig moved from one to another, contigs of no genome recruited) give an estimate of the numbers of a bin of them, from the genes found in the genomes of the map, which miComplete's own run on the group can differ from: it trains pyrodigal on the group itself, and counts the E-values of the hits over its proteins. Of 28 curated groups of the mock community MM133 (halves of MAGs, merges of two MAGs, MAGs with contigs of no genome), 23 came out exact; the merge of the MAGs of two organisms (GC 66.5% and 39.0%) has a redundancy of 1.6667 from the stored markers (175 copies of the 105 markers of Bact105), 1.1827 from miComplete, which, trained on the two together, finds 123 copies of 104 of them. This is what metator markers stores in a map (see metator.metacool.write_map), so that a viewer recomputes the numbers of a bin as a curation edits it: those of a genome of the map, and an estimate of those of a bin the curation made.

The genes and their markers are found as metaTOR's miComplete finds them in a bin (see metator._micomplete): pyrodigal in its single genome mode, trained on all the contigs of the bin together, in their order, then run on each contig; then pyhmmer's hmmsearch of the marker HMMs of a set (Bact105: 105 bacterial markers, Arch131: 131 archaeal ones) in the proteins of the genes, with miComplete's E-value threshold (--evalue, 4e-10), its E-values counted over the proteins of the bin (Z, the number of proteins). miComplete reads the hits from the table that hmmsearch writes (--tblout), and drops a hit whose bias is too high for its score (--bias, 0.3) or whose best domain is much less significant than the whole protein (--domain-cutoff, 1e-5): read here from the same table, written by pyhmmer as metaTOR's miComplete writes it, so that the hits are those of miComplete, its rounding of the table's numbers included (see read_hits).

On a map, each genome of the map (not __unbinned__) is a bin: its contigs are trained on in the order of the map, the order in which metaTOR writes the FASTA file of a genome (metacooler fasta, fasta/mags/). Summed over the contigs of such a genome, the markers give the four numbers that miComplete gives that FASTA file. miComplete finds no gene in a bin of less than 20 kb, which prodigal cannot train on: the contigs of a genome that small, and those of no genome, have their genes found in metagenome mode (pyrodigal's pre-trained models, contig by contig), and their markers searched with Z the median number of proteins of the genomes trained in single mode: every genome of the map of 20 kb or more, whatever it is, an MGE genome of metator mge --reassign too, whose fewer proteins lower it. The genomes, and groups of the other contigs, are searched side by side in threads: pyrodigal and pyhmmer release the GIL, and each search runs on one CPU, as miComplete runs hmmsearch in each of its processes.

The markers of a contig, in a set, are written as a text (see encode_markers): its markers sorted by name, comma-separated, each with the number of its proteins that miComplete keeps when above one (Ribosomal_L22,SecY*2); *0 for a marker that miComplete sees on the contig (a hit in the table of hmmsearch) but whose every hit it drops, which still counts in its weighted completeness, as miComplete counts the markers it sees there, and in none of its other numbers. Both columns hold text, an empty one for a contig without a marker. The markers entry of the map records the marker sets that they were found with, their markers and their weights, which turn them into numbers again (see map_sets and stored_quality): those of the miComplete that found them, which the one installed later, whose sets find new markers (see marker_set), may weigh otherwise.

MarkerSet dataclass

A marker set of miComplete (see marker_set).

Attributes:

Name Type Description
name str

Its name: Bact105 or Arch131.

hmms str

The path to its HMMs (share/.hmm of miComplete).

markers tuple of str

The names of its markers, in the order of its HMMs.

weights tuple of float

The weight of each marker, in the same order, as miComplete reads them (share/.weights).

Source code in src/metator/markers.py
@dataclass(frozen=True)
class MarkerSet:
    """A marker set of miComplete (see marker_set).

    Attributes
    ----------
    name : str
        Its name: Bact105 or Arch131.
    hmms : str
        The path to its HMMs (share/<name>.hmm of miComplete).
    markers : tuple of str
        The names of its markers, in the order of its HMMs.
    weights : tuple of float
        The weight of each marker, in the same order, as miComplete reads them
        (share/<name>.weights)."""

    name: str
    hmms: str
    markers: tuple
    weights: tuple

    def entry(self):
        """The set as the markers entry of the metadata of a map records it: its
        markers in the order of its HMMs, and their weights."""
        return {"markers": list(self.markers), "weights": list(self.weights)}

entry

entry()

The set as the markers entry of the metadata of a map records it: its markers in the order of its HMMs, and their weights.

Source code in src/metator/markers.py
def entry(self):
    """The set as the markers entry of the metadata of a map records it: its
    markers in the order of its HMMs, and their weights."""
    return {"markers": list(self.markers), "weights": list(self.weights)}

Proteins dataclass

The proteins of the genes of a group of contigs (see find_proteins).

Attributes:

Name Type Description
fasta str

The proteins, as pyrodigal writes them, and prodigal (-a): one record per gene, <contig>_<number of the gene in the contig>, its translation ending with * for a complete gene.

contigs list of str

The contig of each protein, in the order of the records.

Source code in src/metator/markers.py
@dataclass
class Proteins:
    """The proteins of the genes of a group of contigs (see find_proteins).

    Attributes
    ----------
    fasta : str
        The proteins, as pyrodigal writes them, and prodigal (-a): one record
        per gene, ``<contig>_<number of the gene in the contig>``, its
        translation ending with ``*`` for a complete gene.
    contigs : list of str
        The contig of each protein, in the order of the records."""

    fasta: str
    contigs: list

    def __len__(self):
        return len(self.contigs)

GroupMarkers dataclass

The markers of the contigs of a group (see group_markers).

Attributes:

Name Type Description
proteins int, or None

The number of proteins of the group; None when it is too short to train on (in single genome mode).

markers dict

By marker set, the markers of each contig that has some (see count_markers).

Source code in src/metator/markers.py
@dataclass
class GroupMarkers:
    """The markers of the contigs of a group (see group_markers).

    Attributes
    ----------
    proteins : int, or None
        The number of proteins of the group; None when it is too short to train
        on (in single genome mode).
    markers : dict
        By marker set, the markers of each contig that has some (see
        count_markers)."""

    proteins: int | None
    markers: dict = field(default_factory=dict)

ContigMarkers dataclass

The markers of the contigs of a map (see contig_markers).

Attributes:

Name Type Description
table DataFrame

One row per contig of the map, in its order: its name (Name) and its markers in each set (markers_Bact105, markers_Arch131; see encode_markers), an empty text for none.

trained dict

The genomes whose genes were found in single genome mode, trained on their contigs: the number of proteins of each, by name, in the order of the genomes table.

small list of str

The genomes too short to train on, whose contigs are in metagenome mode, in the order of the genomes table.

meta int

The number of contigs in metagenome mode: those of the small genomes and of no genome (unbinned).

z float, or None

The number of proteins over which the E-values of the contigs in metagenome mode are counted (see metagenome_z); None without such contigs.

assignment str, or None

The binning that the genes were found in: the digest of the genome of each contig of the map as the run read it (see metator.metacool.assignment_digest), which the markers entry of the map records.

Source code in src/metator/markers.py
@dataclass
class ContigMarkers:
    """The markers of the contigs of a map (see contig_markers).

    Attributes
    ----------
    table : pandas.DataFrame
        One row per contig of the map, in its order: its name (Name) and its
        markers in each set (markers_Bact105, markers_Arch131; see
        encode_markers), an empty text for none.
    trained : dict
        The genomes whose genes were found in single genome mode, trained on
        their contigs: the number of proteins of each, by name, in the order of
        the genomes table.
    small : list of str
        The genomes too short to train on, whose contigs are in metagenome
        mode, in the order of the genomes table.
    meta : int
        The number of contigs in metagenome mode: those of the small genomes and
        of no genome (__unbinned__).
    z : float, or None
        The number of proteins over which the E-values of the contigs in
        metagenome mode are counted (see metagenome_z); None without such
        contigs.
    assignment : str, or None
        The binning that the genes were found in: the digest of the genome of
        each contig of the map as the run read it (see
        metator.metacool.assignment_digest), which the markers entry of the
        map records."""

    table: pd.DataFrame
    trained: dict
    small: list
    meta: int
    z: float | None
    assignment: str | None = None

Quality

Bases: NamedTuple

The four numbers that miComplete gives a bin, as it writes them (see marker_quality).

Source code in src/metator/markers.py
class Quality(NamedTuple):
    """The four numbers that miComplete gives a bin, as it writes them (see
    marker_quality)."""

    completeness: float
    redundancy: float
    weighted_completeness: float
    weighted_redundancy: float

marker_column

marker_column(name)

The column of the contigs table of a map that holds the markers of each contig in the marker set name (see encode_markers): markers_.

Source code in src/metator/markers.py
def marker_column(name):
    """The column of the contigs table of a map that holds the markers of each
    contig in the marker set name (see encode_markers): markers_<name>."""
    return f"markers_{name}"

marker_set cached

marker_set(name)

The marker set name of miComplete (Bact105 or Arch131), from the files that miComplete installs: its markers named as miComplete names them (the NAME lines of the HMMs), and their weights (the lines nameweight of the weights file, but its Standard deviation line).

Source code in src/metator/markers.py
@functools.cache
def marker_set(name):
    """The marker set name of miComplete (Bact105 or Arch131), from the files
    that miComplete installs: its markers named as miComplete names them (the
    NAME lines of the HMMs), and their weights (the lines name<TAB>weight of
    the weights file, but its Standard deviation line)."""
    import importlib.util

    # Found, not imported: miComplete imports names that recent Biopython
    # lacks, which only metator._micomplete puts back, in its own process.
    spec = importlib.util.find_spec("micomplete")
    if spec is None or spec.origin is None:
        raise ImportError("miComplete is not installed: metaTOR reads its marker sets.")
    share = os.path.join(os.path.dirname(os.path.abspath(spec.origin)), "share")
    hmms = os.path.join(share, f"{name}.hmm")
    with open(hmms) as handle:
        markers = tuple(line.split(" ")[2].strip() for line in handle if line.startswith("NAME"))
    weights = {}
    with open(os.path.join(share, f"{name}.weights")) as handle:
        for line in handle:
            fields = line.split("\t")
            if fields[0] != "Standard deviation:":
                weights[fields[0]] = float(fields[1])
    return MarkerSet(name, hmms, markers, tuple(weights[marker] for marker in markers))

find_proteins

find_proteins(contigs, meta=False)

The proteins of the genes of a group of contigs, as metaTOR's miComplete finds those of a bin (see metator._micomplete.create_proteome): pyrodigal in its single genome mode, trained on all the contigs together, joined in their order as prodigal joins them, then run on each contig; or, with meta, in its metagenome mode, contig by contig.

Parameters:

Name Type Description Default
contigs list of (str, bytes)

The name and the sequence of each contig, in order.

required
meta bool

Whether to find the genes in metagenome mode.

False

Returns:

Type Description
Proteins, or None

None in single genome mode when the contigs, joined, are too short to train on (MIN_TRAINING): miComplete finds no gene in such a bin.

Source code in src/metator/markers.py
def find_proteins(contigs, meta=False):
    """The proteins of the genes of a group of contigs, as metaTOR's miComplete
    finds those of a bin (see metator._micomplete.create_proteome): pyrodigal
    in its single genome mode, trained on all the contigs together, joined in
    their order as prodigal joins them, then run on each contig; or, with meta,
    in its metagenome mode, contig by contig.

    Parameters
    ----------
    contigs : list of (str, bytes)
        The name and the sequence of each contig, in order.
    meta : bool
        Whether to find the genes in metagenome mode.

    Returns
    -------
    Proteins, or None
        None in single genome mode when the contigs, joined, are too short to
        train on (MIN_TRAINING): miComplete finds no gene in such a bin."""
    import pyrodigal

    finder = pyrodigal.GeneFinder(meta=meta)
    if not meta:
        if not contigs:
            return None
        try:
            # Under 100 kb, pyrodigal warns (see contig_markers, which silences
            # it): prodigal warns too, on a stderr that miComplete discards.
            finder.train(*(sequence for _, sequence in contigs))
        except ValueError:
            return None
    fasta = io.StringIO()
    owners = []
    for name, sequence in contigs:
        genes = finder.find_genes(sequence)
        genes.write_translations(fasta, sequence_id=name)
        owners.extend([name] * len(genes))
    return Proteins(fasta.getvalue(), owners)

search_table

search_table(proteins, markers, evalue=EVALUE, z=None)

The hits of the HMMs of a marker set (a MarkerSet) in proteins (a Proteins), as metaTOR's miComplete runs hmmsearch on a bin (see metator._micomplete.hmm_search): hmmsearch -E <evalue> --tblout, the table written by pyhmmer as hmmsearch writes it (its target E-values per protein of the search, Z: by default, the number of proteins searched).

Returns:

Type Description
str

The table (--tblout), its header once: empty without a protein.

Source code in src/metator/markers.py
def search_table(proteins, markers, evalue=EVALUE, z=None):
    """The hits of the HMMs of a marker set (a MarkerSet) in proteins (a
    Proteins), as metaTOR's miComplete runs hmmsearch on a bin (see
    metator._micomplete.hmm_search): ``hmmsearch -E <evalue> --tblout``, the
    table written by pyhmmer as hmmsearch writes it (its target E-values per
    protein of the search, Z: by default, the number of proteins searched).

    Returns
    -------
    str
        The table (--tblout), its header once: empty without a protein."""
    import pyhmmer

    if not len(proteins):
        return ""
    hmms = _hmms(markers)
    with pyhmmer.easel.SequenceFile(
        io.BytesIO(proteins.fasta.encode()), format="fasta", digital=True, alphabet=hmms[0].alphabet
    ) as sequences:
        block = sequences.read_block()
    # One CPU: the genomes are searched side by side, in threads.
    if z is None:
        searches = pyhmmer.hmmsearch(hmms, block, cpus=1, E=evalue)
    else:
        searches = pyhmmer.hmmsearch(hmms, block, cpus=1, E=evalue, Z=z)
    table = io.BytesIO()
    for i, hits in enumerate(searches):
        hits.write(table, format="targets", header=i == 0)
    return table.getvalue().decode()

read_hits

read_hits(table, bias=BIAS, domain_cutoff=DOMAIN_CUTOFF)

The hits of a table of hmmsearch (--tblout) as miComplete reads them (micomplete.completeness.calcCompleteness.get_completeness): the target protein, the marker (the query) and whether miComplete keeps the hit, from the numbers as the table writes them (two significant digits for an E-value, one decimal for a score): it drops a hit whose score times bias is no more than its bias, or whose best domain has an E-value more than domain_cutoff above that of the whole protein (suspicion_check). Every hit of the table counts in the markers miComplete sees, kept or dropped.

Returns:

Type Description
list of (str, str, bool)

The protein, the marker and whether the hit is kept, in the order of the table.

Source code in src/metator/markers.py
def read_hits(table, bias=BIAS, domain_cutoff=DOMAIN_CUTOFF):
    """The hits of a table of hmmsearch (--tblout) as miComplete reads them
    (micomplete.completeness.calcCompleteness.get_completeness): the target
    protein, the marker (the query) and whether miComplete keeps the hit, from
    the numbers as the table writes them (two significant digits for an
    E-value, one decimal for a score): it drops a hit whose score times bias
    is no more than its bias, or whose best domain has an E-value more than
    domain_cutoff above that of the whole protein (suspicion_check). Every hit
    of the table counts in the markers miComplete sees, kept or dropped.

    Returns
    -------
    list of (str, str, bool)
        The protein, the marker and whether the hit is kept, in the order of
        the table."""
    hits = []
    for line in table.splitlines():
        # miComplete stops at a line "#", hmmsearch's footer (pyhmmer writes
        # none); the header's lines name no marker.
        if line == "#":
            break
        if line.startswith("#"):
            continue
        fields = line.split()
        full_evalue, score, hit_bias, domain_evalue = (float(value) for value in fields[4:8])
        dropped = score * bias <= hit_bias or domain_evalue - full_evalue > domain_cutoff
        hits.append((fields[0], fields[2], not dropped))
    return hits

count_markers

count_markers(proteins, hits)

The markers of each contig of a group (see find_proteins), from the hits of a marker set in their proteins (see read_hits): by contig, the number of its proteins that miComplete keeps for each marker that it sees on the contig, 0 for a marker whose every hit there it drops. A protein counts for each marker that it is kept for.

Returns:

Type Description
dict

By contig (those with a marker only): a dict of the count of each marker.

Source code in src/metator/markers.py
def count_markers(proteins, hits):
    """The markers of each contig of a group (see find_proteins), from the hits
    of a marker set in their proteins (see read_hits): by contig, the number of
    its proteins that miComplete keeps for each marker that it sees on the
    contig, 0 for a marker whose every hit there it drops. A protein counts for
    each marker that it is kept for.

    Returns
    -------
    dict
        By contig (those with a marker only): a dict of the count of each
        marker."""
    owner = {}
    for line in proteins.fasta.splitlines():
        if line.startswith(">"):
            owner[line[1:].split(None, 1)[0]] = len(owner)
    found = {}
    for protein, marker, kept in hits:
        markers = found.setdefault(proteins.contigs[owner[protein]], {})
        markers[marker] = markers.get(marker, 0) + int(kept)
    return found

group_markers

group_markers(
    contigs,
    sets=MARKER_SETS,
    meta=False,
    z=None,
    evalue=EVALUE,
    bias=BIAS,
    domain_cutoff=DOMAIN_CUTOFF,
    proteins=None,
)

The markers of each contig of a group of contigs, found as metaTOR's miComplete finds those of a bin of these contigs, in their order (see find_proteins, search_table and read_hits): in single genome mode, or in metagenome mode with meta; the E-values counted over z proteins (by default, the proteins of the group: those of the bin).

Parameters:

Name Type Description Default
contigs list of (str, bytes)

The name and the sequence of each contig, in order.

required
sets sequence of str

The marker sets (see MARKER_SETS).

MARKER_SETS
meta bool

Whether to find the genes in metagenome mode.

False
z float

The number of proteins that the E-values are counted over.

None
evalue float

miComplete's thresholds (--evalue, --bias, --domain-cutoff).

EVALUE
bias float

miComplete's thresholds (--evalue, --bias, --domain-cutoff).

EVALUE
domain_cutoff float

miComplete's thresholds (--evalue, --bias, --domain-cutoff).

EVALUE
proteins Proteins

The proteins of the group, when found already.

None

Returns:

Type Description
GroupMarkers

Its proteins and the markers of its contigs; without markers, and proteins None, for a group too short to train on (in single genome mode).

Source code in src/metator/markers.py
def group_markers(
    contigs, sets=MARKER_SETS, meta=False, z=None, evalue=EVALUE, bias=BIAS, domain_cutoff=DOMAIN_CUTOFF, proteins=None
):
    """The markers of each contig of a group of contigs, found as metaTOR's
    miComplete finds those of a bin of these contigs, in their order (see
    find_proteins, search_table and read_hits): in single genome mode, or in
    metagenome mode with meta; the E-values counted over z proteins (by
    default, the proteins of the group: those of the bin).

    Parameters
    ----------
    contigs : list of (str, bytes)
        The name and the sequence of each contig, in order.
    sets : sequence of str
        The marker sets (see MARKER_SETS).
    meta : bool
        Whether to find the genes in metagenome mode.
    z : float, optional
        The number of proteins that the E-values are counted over.
    evalue, bias, domain_cutoff : float
        miComplete's thresholds (--evalue, --bias, --domain-cutoff).
    proteins : Proteins, optional
        The proteins of the group, when found already.

    Returns
    -------
    GroupMarkers
        Its proteins and the markers of its contigs; without markers, and
        proteins None, for a group too short to train on (in single genome
        mode)."""
    if proteins is None:
        proteins = find_proteins(contigs, meta=meta)
    if proteins is None:
        return GroupMarkers(None)
    found = GroupMarkers(len(proteins))
    for name in sets:
        table = search_table(proteins, marker_set(name), evalue, z)
        found.markers[name] = count_markers(proteins, read_hits(table, bias, domain_cutoff))
    return found

metagenome_z

metagenome_z(trained, proteins)

The number of proteins that the E-values of the contigs in metagenome mode are counted over: the median number of proteins of the genomes trained in single mode (trained, by genome), every genome of the map that pyrodigal trains on, whatever it is, an MGE genome of metator mge --reassign too, whose fewer proteins lower it; without a trained genome, proteins, the number of proteins of the contigs in metagenome mode, searched as one bin.

Source code in src/metator/markers.py
def metagenome_z(trained, proteins):
    """The number of proteins that the E-values of the contigs in metagenome mode
    are counted over: the median number of proteins of the genomes trained in
    single mode (trained, by genome), every genome of the map that pyrodigal
    trains on, whatever it is, an MGE genome of metator mge --reassign too,
    whose fewer proteins lower it; without a trained genome, proteins, the
    number of proteins of the contigs in metagenome mode, searched as one
    bin."""
    # At least one protein: HMMER counts no E-value over none.
    return max(1.0, float(statistics.median(trained.values())) if trained else float(proteins))

read_contigs

read_contigs(metacool, mc, assembly)

The sequences of the contigs of a map (mc, opened) from its assembly, as metaTOR's miComplete reads those of a bin (Biopython: a record's name is the first word of its header, and its sequence its bases as they are, in upper or lower case).

Parameters:

Name Type Description Default
metacool str

The map, for the messages.

required
mc MetaCooler

The map, opened.

required
assembly str

The assembly that the map was made from: a FASTA file, plain or compressed with gzip.

required

Returns:

Type Description
dict

The sequence of each contig of the map, as bytes, by name.

Raises:

Type Description
MetacoolError

If the assembly names a contig by several records, or the map is not a map of the contigs of the assembly: a contig that the assembly lacks, or of another length there.

Source code in src/metator/markers.py
def read_contigs(metacool, mc, assembly):
    """The sequences of the contigs of a map (mc, opened) from its assembly, as
    metaTOR's miComplete reads those of a bin (Biopython: a record's name is
    the first word of its header, and its sequence its bases as they are, in
    upper or lower case).

    Parameters
    ----------
    metacool : str
        The map, for the messages.
    mc : metacooler.MetaCooler
        The map, opened.
    assembly : str
        The assembly that the map was made from: a FASTA file, plain or
        compressed with gzip.

    Returns
    -------
    dict
        The sequence of each contig of the map, as bytes, by name.

    Raises
    ------
    metator.metacool.MetacoolError
        If the assembly names a contig by several records, or the map is not a
        map of the contigs of the assembly: a contig that the assembly lacks,
        or of another length there."""
    from Bio import SeqIO

    with mtmc.read_errors(metacool):
        contigs = mc.contigs
    wanted = set(contigs["name"].astype(str))
    sequences, lengths, named_again = {}, {}, []
    with mio.read_compressed(assembly) as fasta:
        for record in SeqIO.parse(fasta, "fasta"):
            if record.id in lengths:
                named_again.append(record.id)
                continue
            lengths[record.id] = len(record.seq)
            if record.id in wanted:
                sequences[record.id] = bytes(record.seq)
    if named_again:
        named_again = list(dict.fromkeys(named_again))
        raise mtmc.MetacoolError(
            f"{len(named_again)} contig(s) are named by several records of the assembly {assembly}: "
            f"{mtmc._shown(named_again)}. A contig is read by its name, the first word of its header: give each record "
            "a name of its own."
        )
    missing = [str(name) for name in contigs["name"] if str(name) not in lengths]
    if missing:
        raise mtmc.MetacoolError(
            f"{metacool} is not a contact map of the contigs of the assembly: {len(missing)} of its contig(s) are not "
            f"in the assembly {assembly}: {mtmc._shown(missing)}. Give the assembly that the map was made from."
        )
    mtmc.check_map_lengths(metacool, contigs, lengths, f"the assembly {assembly}", "the assembly")
    return sequences

contig_markers

contig_markers(
    metacool,
    mc,
    sequences,
    threads=1,
    evalue=EVALUE,
    bias=BIAS,
    domain_cutoff=DOMAIN_CUTOFF,
)

The markers of every contig of a map, in each marker set of miComplete (see the module's docstring): each genome of the map (not unbinned) as a bin of its contigs, in the order of the map, trained on in single genome mode, its E-values counted over its proteins; the contigs of the genomes too short to train on, and of no genome, in metagenome mode, their E-values counted over the median number of proteins of the genomes trained in single mode, MGE genomes included (see metagenome_z).

Parameters:

Name Type Description Default
metacool str

The map, for the messages.

required
mc MetaCooler

The map, opened: its genomes and contigs.

required
sequences dict

The sequence of each contig of the map, by name (see read_contigs).

required
threads int

The number of genomes, or groups of contigs, searched side by side.

1
evalue float

miComplete's thresholds (--evalue, --bias, --domain-cutoff).

EVALUE
bias float

miComplete's thresholds (--evalue, --bias, --domain-cutoff).

EVALUE
domain_cutoff float

miComplete's thresholds (--evalue, --bias, --domain-cutoff).

EVALUE

Returns:

Type Description
ContigMarkers

The markers of the contigs, and how their genes were found.

Source code in src/metator/markers.py
def contig_markers(metacool, mc, sequences, threads=1, evalue=EVALUE, bias=BIAS, domain_cutoff=DOMAIN_CUTOFF):
    """The markers of every contig of a map, in each marker set of miComplete
    (see the module's docstring): each genome of the map (not __unbinned__)
    as a bin of its contigs, in the order of the map, trained on in single
    genome mode, its E-values counted over its proteins; the contigs of the
    genomes too short to train on, and of no genome, in metagenome mode, their
    E-values counted over the median number of proteins of the genomes
    trained in single mode, MGE genomes included (see metagenome_z).

    Parameters
    ----------
    metacool : str
        The map, for the messages.
    mc : metacooler.MetaCooler
        The map, opened: its genomes and contigs.
    sequences : dict
        The sequence of each contig of the map, by name (see read_contigs).
    threads : int
        The number of genomes, or groups of contigs, searched side by side.
    evalue, bias, domain_cutoff : float
        miComplete's thresholds (--evalue, --bias, --domain-cutoff).

    Returns
    -------
    ContigMarkers
        The markers of the contigs, and how their genes were found."""
    with mtmc.read_errors(metacool):
        contigs = mc.contigs
        genome_names = mc.genomes["name"].astype(str).to_numpy()
    names = contigs["name"].astype(str).to_numpy()
    of_genome = genome_names[contigs["genome_id"].to_numpy()]
    # The contigs of each genome, in the order of the map, the genomes in the
    # order of the genomes table.
    groups = {name: [] for name in genome_names if name != mtmc.UNBINNED_GENOME}
    for name, genome in zip(names, of_genome, strict=True):
        if genome != mtmc.UNBINNED_GENOME:
            groups[genome].append((name, sequences[name]))
    groups = {genome: group for genome, group in groups.items() if group}
    options = {"evalue": evalue, "bias": bias, "domain_cutoff": domain_cutoff}
    with warnings.catch_warnings():
        # A genome under 100 kb, as many are: pyrodigal warns, and prodigal,
        # on a stderr that miComplete discards. Set here, once, for the
        # threads: catch_warnings is not safe in threads.
        warnings.filterwarnings("ignore", message="sequence should be at least", category=UserWarning)
        order = _by_size(groups)
        found = dict(
            zip(order, _in_threads(lambda genome: group_markers(groups[genome], **options), order, threads), strict=True)
        )
        trained = {genome: found[genome].proteins for genome in groups if found[genome].proteins is not None}
        small = [genome for genome in groups if found[genome].proteins is None]
        # The contigs in metagenome mode, in the order of the map: their genes
        # first, then their markers, once the number of proteins that their
        # E-values are counted over is known.
        small_genomes = set(small)
        meta = [
            (name, sequences[name])
            for name, genome in zip(names, of_genome, strict=True)
            if genome == mtmc.UNBINNED_GENOME or genome in small_genomes
        ]
        parts = _split(meta, max(1, threads) * GROUPS_PER_THREAD) if meta else []
        proteins = _in_threads(lambda part: find_proteins(part, meta=True), parts, threads)
        z = metagenome_z(trained, sum(len(found_proteins) for found_proteins in proteins)) if meta else None
        jobs = list(zip(parts, proteins, strict=True))
        searched = _in_threads(lambda job: group_markers(job[0], meta=True, z=z, proteins=job[1], **options), jobs, threads)
    markers = {name: {} for name in MARKER_SETS}
    for group in [*found.values(), *searched]:
        for name, by_contig in group.markers.items():
            markers[name].update(by_contig)
    table = pd.DataFrame({"Name": names})
    for name in MARKER_SETS:
        table[marker_column(name)] = [encode_markers(markers[name].get(contig, {})) for contig in names]
    result = ContigMarkers(table, trained, small, len(meta), z, mtmc.assignment_digest(names, of_genome))
    _log_markers(result)
    return result

encode_markers

encode_markers(counts)

The markers of a contig (counts: the number of proteins of each, see count_markers) as the contigs table of a map stores them: sorted by name (in the order of their bytes, ASCII), comma-separated, each followed by * and its count when that is not 1 (Ribosomal_L22,SecY*2; *0 for a marker that miComplete sees but drops); an empty text for none.

Source code in src/metator/markers.py
def encode_markers(counts):
    """The markers of a contig (counts: the number of proteins of each, see
    count_markers) as the contigs table of a map stores them: sorted by name
    (in the order of their bytes, ASCII), comma-separated, each followed by
    ``*`` and its count when that is not 1 (``Ribosomal_L22,SecY*2``; ``*0``
    for a marker that miComplete sees but drops); an empty text for none."""
    return SEPARATOR.join(name if count == 1 else f"{name}{COUNT}{count}" for name, count in sorted(counts.items()))

decode_markers

decode_markers(text)

The markers of a contig from their text (see encode_markers): the count of each, by name. An empty text is none, and so is a missing value (None or NaN), which a contigs table edited by another tool may hold: metaTOR stores both columns as text (see metator.metacool._store_markers).

Source code in src/metator/markers.py
def decode_markers(text):
    """The markers of a contig from their text (see encode_markers): the count of
    each, by name. An empty text is none, and so is a missing value (None or
    NaN), which a contigs table edited by another tool may hold: metaTOR
    stores both columns as text (see metator.metacool._store_markers)."""
    if text is None or (isinstance(text, float) and np.isnan(text)) or text == "":
        return {}
    counts = {}
    for item in str(text).split(SEPARATOR):
        name, star, count = item.partition(COUNT)
        counts[name] = int(count) if star else 1
    return counts

sum_markers

sum_markers(counts)

The markers of a group of contigs: those of its contigs (counts, an iterable of dicts, see decode_markers), summed by marker. A marker that miComplete sees on a contig but drops (0) stays, as seen, at 0.

Source code in src/metator/markers.py
def sum_markers(counts):
    """The markers of a group of contigs: those of its contigs (counts, an
    iterable of dicts, see decode_markers), summed by marker. A marker that
    miComplete sees on a contig but drops (0) stays, as seen, at 0."""
    total = {}
    for markers in counts:
        for name, count in markers.items():
            total[name] = total.get(name, 0) + count
    return total

marker_quality

marker_quality(counts, markers, weights)

The completeness, redundancy, weighted completeness and weighted redundancy that miComplete gives a bin whose markers are counts, in a marker set, as miComplete computes and rounds them (micomplete.micomplete._compile_results and micomplete.completeness.calcCompleteness.attribute_weights).

With P the markers present (a count of one or more) and N the markers of the set: completeness = P / N, and redundancy = the sum of the counts of the present markers / P, each rounded to 4 decimals (by Python's round, as miComplete: an exact tie to the even digit, 1.03125 to 1.0312). The weighted completeness WC is the sum of the weights of the markers that miComplete sees (present, or seen and dropped: a count of 0), rounded to 4 decimals, 0.0001 if that is 0; the weighted redundancy is (the sum of the weights of the markers of more than one copy, each once, + WC) / WC, WC not rounded, the quotient rounded to 4 decimals. A bin without a present marker has 0 for all four.

Parameters:

Name Type Description Default
counts dict

The count of each marker of the bin, by name (see sum_markers): the markers that miComplete sees in it only.

required
markers sequence of str

The markers of the set (see MarkerSet.markers).

required
weights sequence of float

The weight of each marker of the set, in the order of markers.

required

Returns:

Type Description
Quality

The four numbers.

Raises:

Type Description
ValueError

If counts names a marker that is not in the set.

Source code in src/metator/markers.py
def marker_quality(counts, markers, weights):
    """The completeness, redundancy, weighted completeness and weighted
    redundancy that miComplete gives a bin whose markers are counts, in a
    marker set, as miComplete computes and rounds them
    (micomplete.micomplete._compile_results and
    micomplete.completeness.calcCompleteness.attribute_weights).

    With P the markers present (a count of one or more) and N the markers of
    the set: completeness = P / N, and redundancy = the sum of the counts of
    the present markers / P, each rounded to 4 decimals (by Python's round,
    as miComplete: an exact tie to the even digit, 1.03125 to 1.0312). The weighted
    completeness WC is the sum of the weights of the markers that miComplete
    sees (present, or seen and dropped: a count of 0), rounded to 4 decimals,
    0.0001 if that is 0; the weighted redundancy is (the sum of the weights of
    the markers of more than one copy, each once, + WC) / WC, WC not rounded,
    the quotient rounded to 4 decimals. A bin without a present marker has 0
    for all four.

    Parameters
    ----------
    counts : dict
        The count of each marker of the bin, by name (see sum_markers): the
        markers that miComplete sees in it only.
    markers : sequence of str
        The markers of the set (see MarkerSet.markers).
    weights : sequence of float
        The weight of each marker of the set, in the order of markers.

    Returns
    -------
    Quality
        The four numbers.

    Raises
    ------
    ValueError
        If counts names a marker that is not in the set."""
    weight = dict(zip(markers, weights, strict=True))
    unknown = [name for name in counts if name not in weight]
    if unknown:
        raise ValueError(f"Markers of no marker set of {len(markers)} markers: {', '.join(sorted(unknown))}.")
    present = [name for name in markers if counts.get(name, 0) > 0]
    if not present:
        return Quality(0.0, 0.0, 0.0, 0.0)
    completeness = round(len(present) / len(markers), 4)
    redundancy = round(sum(counts[name] for name in present) / len(present), 4)
    seen = sum(weight[name] for name in markers if name in counts)
    duplicated = sum(weight[name] for name in present if counts[name] > 1)
    weighted_redundancy = round((duplicated + seen) / seen, 4)
    weighted_completeness = round(seen, 4) or 0.0001
    return Quality(completeness, redundancy, weighted_completeness, weighted_redundancy)

kept_quality

kept_quality(qualities)

The marker set that metaTOR keeps for a bin, and its numbers, from the numbers of each set (qualities, by set name; see marker_quality), as metator.validation.merge_micomplete keeps miComplete's results: Bact105, unless Arch131 has the higher weighted completeness.

Returns:

Type Description
tuple

The set's name for metaTOR (Bacteria or Archaea, see KINGDOMS), and its Quality.

Source code in src/metator/markers.py
def kept_quality(qualities):
    """The marker set that metaTOR keeps for a bin, and its numbers, from the
    numbers of each set (qualities, by set name; see marker_quality), as
    metator.validation.merge_micomplete keeps miComplete's results: Bact105,
    unless Arch131 has the higher weighted completeness.

    Returns
    -------
    tuple
        The set's name for metaTOR (Bacteria or Archaea, see KINGDOMS), and its
        Quality."""
    bacteria, archaea = qualities["Bact105"], qualities["Arch131"]
    if bacteria.weighted_completeness >= archaea.weighted_completeness:
        return KINGDOMS["Bact105"], bacteria
    return KINGDOMS["Arch131"], archaea

quality_of

quality_of(texts, sets)

The numbers that miComplete gives a group of contigs, from their markers as a map stores them (texts: by marker set, the markers of each contig, see encode_markers), with the marker sets that they were found with (sets: by set, its markers and their weights), as metaTOR keeps them (see kept_quality). For the markers that a map stores, the sets are those that its markers entry records (see map_sets and stored_quality): those of the miComplete that found them, which the one installed now may weigh otherwise; for markers found now (see group_markers), those of the installed miComplete (see entry_sets).

Returns:

Type Description
tuple

Bacteria or Archaea, and the Quality of that set.

Source code in src/metator/markers.py
def quality_of(texts, sets):
    """The numbers that miComplete gives a group of contigs, from their markers
    as a map stores them (texts: by marker set, the markers of each contig, see
    encode_markers), with the marker sets that they were found with (sets: by
    set, its markers and their weights), as metaTOR keeps them (see
    kept_quality). For the markers that a map stores, the sets are those that
    its markers entry records (see map_sets and stored_quality): those of the
    miComplete that found them, which the one installed now may weigh
    otherwise; for markers found now (see group_markers), those of the
    installed miComplete (see entry_sets).

    Returns
    -------
    tuple
        Bacteria or Archaea, and the Quality of that set."""
    qualities = {}
    for name in MARKER_SETS:
        counts = sum_markers(decode_markers(text) for text in texts[name])
        qualities[name] = marker_quality(counts, sets[name]["markers"], sets[name]["weights"])
    return kept_quality(qualities)

entry_sets

entry_sets()

The marker sets of the miComplete installed now, which metator markers finds new markers with, as the markers entry of the metadata of a map records them (see metator.cli.markers_entry): by set, its column in the contigs table, its markers in the order of its HMMs and their weights.

Source code in src/metator/markers.py
def entry_sets():
    """The marker sets of the miComplete installed now, which metator markers
    finds new markers with, as the markers entry of the metadata of a map
    records them (see metator.cli.markers_entry): by set, its column in the
    contigs table, its markers in the order of its HMMs and their weights."""
    return {name: {"column": marker_column(name), **marker_set(name).entry()} for name in MARKER_SETS}

map_sets

map_sets(mc)

The marker sets that the marker genes of the contigs of a map were found with, as its markers entry records them (see entry_sets and metator.metacool.markers_entry): by set, in the order of MARKER_SETS, its column in the contigs table (column), its markers (markers) and their weights (weights). The numbers of a group of contigs of the map come from them (see quality_of and stored_quality), not from the files of the miComplete installed now, which finds new markers (see marker_set): its weights, or its markers, may be other than those of the miComplete that found the markers of the map.

Parameters:

Name Type Description Default
mc MetaCooler

The map, opened.

required

Returns:

Type Description
dict

By set name: its column, its markers and their weights.

Raises:

Type Description
MetacoolError

If the map records no such sets: it holds no markers that metator markers found, or its entry lacks a set, its column, or a weight (a number) for each of its markers (by name).

Source code in src/metator/markers.py
def map_sets(mc):
    """The marker sets that the marker genes of the contigs of a map were found
    with, as its markers entry records them (see entry_sets and
    metator.metacool.markers_entry): by set, in the order of MARKER_SETS, its
    column in the contigs table (column), its markers (markers) and their
    weights (weights). The numbers of a group of contigs of the map come from
    them (see quality_of and stored_quality), not from the files of the
    miComplete installed now, which finds new markers (see marker_set): its
    weights, or its markers, may be other than those of the miComplete that
    found the markers of the map.

    Parameters
    ----------
    mc : metacooler.MetaCooler
        The map, opened.

    Returns
    -------
    dict
        By set name: its column, its markers and their weights.

    Raises
    ------
    metator.metacool.MetacoolError
        If the map records no such sets: it holds no markers that metator
        markers found, or its entry lacks a set, its column, or a weight (a
        number) for each of its markers (by name)."""
    entry = mtmc.markers_entry(mc)
    sets = entry.get("sets") if entry is not None else None
    if not isinstance(sets, dict):
        raise mtmc.MetacoolError(
            f"{_named(mc)} records no marker sets of metator markers (the sets of the markers entry of its metator "
            "metadata): run metator markers on it first."
        )
    found = {}
    for name in MARKER_SETS:
        spec = sets.get(name) if isinstance(sets.get(name), dict) else {}
        markers, weights = spec.get("markers"), spec.get("weights")
        readable = (
            isinstance(spec.get("column"), str)
            and isinstance(markers, list)
            and isinstance(weights, list)
            and len(markers) == len(weights)
            and all(isinstance(marker, str) for marker in markers)
            and all(isinstance(weight, (int, float)) and not isinstance(weight, bool) for weight in weights)
        )
        if not readable:
            raise mtmc.MetacoolError(
                f"The markers entry of {_named(mc)} records no marker set {name} that metaTOR reads (its column, its markers "
                "by name, and a weight for each): run metator markers on the map again."
            )
        found[name] = {"column": spec["column"], "markers": list(markers), "weights": [float(weight) for weight in weights]}
    return found

stored_quality

stored_quality(mc, contigs)

The numbers that miComplete gives a group of contigs of a map (mc, opened; contigs: their names, each counted once), from the markers that the map stores, in the columns of its contigs table that its markers entry names, with the marker sets that it records (see map_sets), as metaTOR keeps them (see quality_of): those of a genome of the map as metator markers found its genes, and an estimate of those of any other group (see the module's docstring).

Returns:

Type Description
tuple

Bacteria or Archaea, and the Quality of that set.

Raises:

Type Description
MetacoolError

If the map records no marker sets (see map_sets), lacks the column of one, or a contig of the group.

Source code in src/metator/markers.py
def stored_quality(mc, contigs):
    """The numbers that miComplete gives a group of contigs of a map (mc, opened;
    contigs: their names, each counted once), from the markers that the map
    stores, in the columns of its contigs table that its markers entry names,
    with the marker sets that it records (see map_sets), as metaTOR keeps
    them (see quality_of): those of a genome of the map as metator markers
    found its genes, and an estimate of those of any other group (see the
    module's docstring).

    Returns
    -------
    tuple
        Bacteria or Archaea, and the Quality of that set.

    Raises
    ------
    metator.metacool.MetacoolError
        If the map records no marker sets (see map_sets), lacks the column of
        one, or a contig of the group."""
    sets = map_sets(mc)
    with mtmc.read_errors(_named(mc)):
        table = mc.contigs
    table = table.set_index(table["name"].astype(str))
    names = list(dict.fromkeys(str(name) for name in contigs))
    missing = [name for name in names if name not in table.index]
    if missing:
        raise mtmc.MetacoolError(
            f"{len(missing)} contig(s) of the group are not contigs of {_named(mc)}: {mtmc._shown(missing)}."
        )
    absent = [spec["column"] for spec in sets.values() if spec["column"] not in table.columns]
    if absent:
        raise mtmc.MetacoolError(
            f"{_named(mc)} lacks the column(s) {', '.join(absent)} of its contigs table that its markers entry names: run "
            "metator markers on it again."
        )
    texts = {name: list(table.loc[names, spec["column"]]) for name, spec in sets.items()}
    return quality_of(texts, sets)

metator.figures

The plots of the final clusters of a validation.

validation and pipeline draw them in plots/, in their output directory, as PDF files, once the clusters are final (see plot_figures), where host draws its own (see metator.host.plot_hosts):

  • bins_distribution.pdf: the completeness and the contamination of each cluster, the clusters by decreasing completeness (see figures_bins_distribution);
  • bins_size_distribution.pdf: the share of the contigs of the run in each quality class of the clusters (see metator.validation.bin_quality), and in no cluster (see figures_bins_size_distribution).

They are drawn with matplotlib's Figure, without pyplot: no window, whatever the backend of matplotlib.

figures_bins_distribution

figures_bins_distribution(bin_summary, out_file)

Plot the completeness and the contamination of each final cluster: a dot each, in percent, the clusters by decreasing completeness (their rank on the x axis), with dashed lines at the thresholds of the quality classes and at 100%.

The contamination is the weighted redundancy minus 1 (see metator.validation.bin_quality), drawn from 0 to 105%: a cluster in which miComplete finds no marker gene, of a redundancy of 0, at 0, and a contamination of more than 105% at 105%.

Parameters:

Name Type Description Default
bin_summary DataFrame

The final clusters, one per row, with miComplete's Weighted completeness and Weighted redundancy, as fractions.

required
out_file str

Path of the PNG file to write.

required
Source code in src/metator/figures.py
def figures_bins_distribution(bin_summary, out_file):
    """Plot the completeness and the contamination of each final cluster: a dot
    each, in percent, the clusters by decreasing completeness (their rank on
    the x axis), with dashed lines at the thresholds of the quality classes
    and at 100%.

    The contamination is the weighted redundancy minus 1 (see
    metator.validation.bin_quality), drawn from 0 to 105%: a cluster in which
    miComplete finds no marker gene, of a redundancy of 0, at 0, and a
    contamination of more than 105% at 105%.

    Parameters
    ----------
    bin_summary : pandas.DataFrame
        The final clusters, one per row, with miComplete's Weighted
        completeness and Weighted redundancy, as fractions.
    out_file : str
        Path of the PNG file to write.
    """
    completeness = bin_summary["Weighted completeness"].astype(float).to_numpy() * 100
    contamination = bin_summary["Weighted redundancy"].astype(float).to_numpy() * 100 - 100
    contamination = np.clip(contamination, 0, MAX_CONTAMINATION)
    # By decreasing completeness; clusters of the same completeness in the
    # order of the summary.
    order = np.argsort(-completeness, kind="stable")
    ranks = np.arange(len(order))

    fig = Figure()
    ax = fig.subplots()
    ax.tick_params(axis="both", which="both", length=0)
    ax.set_frame_on(False)
    ax.scatter(ranks, completeness[order], color="r", label="Completion", s=2.5)
    ax.scatter(ranks, contamination[order], color="k", label="Contamination", s=2.5)
    for line in QUALITY_LINES:
        ax.axhline(y=line, color="k", linestyle=(0, (5, 10)))
    ax.set_yticks(QUALITY_LINES)
    ax.set_xticks(np.arange(0, len(order), 50))
    ax.set_xlabel("Rank index")
    ax.set_ylabel("Completeness/Contamination (%)")
    ax.legend(bbox_to_anchor=(0.0, -0.25, 1.0, 1.0), loc="lower center", ncol=2, borderaxespad=0.0)
    _saved(fig, out_file)

figures_bins_size_distribution

figures_bins_size_distribution(bin_summary, total_size, threshold, out_file)

Plot a pie chart of the size of the contigs in each quality class of the final clusters (see metator.validation.bin_quality: HQ, MQ and LQ MAGs, contaminated clusters and other clusters), and in no final cluster.

The legend counts the clusters of each class and their size, in Mb; below the pie, the total size of the contigs, the share of the MAGs (HQ, MQ and LQ) in it, and the size threshold of the clusters.

Parameters:

Name Type Description Default
bin_summary DataFrame

The final clusters, one per row, with their Length and miComplete's Weighted completeness and Weighted redundancy.

required
total_size int

The size of the contigs of the run, in bp: those of its map, the whole assembly for a map of all its contigs.

required
threshold int

The size threshold of the clusters (--size), in bp.

required
out_file str

Path of the PNG file to write.

required

Returns:

Type Description
DataFrame

A copy of bin_summary, with the quality class of each cluster in a MAG_quality column.

Source code in src/metator/figures.py
def figures_bins_size_distribution(bin_summary, total_size, threshold, out_file):
    """Plot a pie chart of the size of the contigs in each quality class of the
    final clusters (see metator.validation.bin_quality: HQ, MQ and LQ MAGs,
    contaminated clusters and other clusters), and in no final cluster.

    The legend counts the clusters of each class and their size, in Mb; below
    the pie, the total size of the contigs, the share of the MAGs (HQ, MQ and
    LQ) in it, and the size threshold of the clusters.

    Parameters
    ----------
    bin_summary : pandas.DataFrame
        The final clusters, one per row, with their Length and miComplete's
        Weighted completeness and Weighted redundancy.
    total_size : int
        The size of the contigs of the run, in bp: those of its map, the
        whole assembly for a map of all its contigs.
    threshold : int
        The size threshold of the clusters (--size), in bp.
    out_file : str
        Path of the PNG file to write.

    Returns
    -------
    pandas.DataFrame
        A copy of bin_summary, with the quality class of each cluster in a
        MAG_quality column.
    """
    from metator.validation import bin_quality

    bin_summary = bin_summary.copy()
    bin_summary["MAG_quality"] = [
        bin_quality(completeness, redundancy)
        for completeness, redundancy in zip(bin_summary["Weighted completeness"], bin_summary["Weighted redundancy"], strict=True)
    ]
    qualities = bin_summary["MAG_quality"]
    lengths = bin_summary["Length"].astype(float).astype(np.int64)
    counts = {quality: int((qualities == quality).sum()) for quality in MAG_QUALITY_COLOURS}
    sizes = {quality: int(lengths[qualities == quality].sum()) for quality in MAG_QUALITY_COLOURS}
    unclustered = total_size - sum(sizes.values())
    mags = sizes["HQ"] + sizes["MQ"] + sizes["LQ"]

    fig = Figure()
    ax = fig.subplots()
    ax.pie([*sizes.values(), unclustered], colors=[*MAG_QUALITY_COLOURS.values(), UNCLUSTERED_COLOUR])
    labels = [
        f"{MAG_QUALITY_NAMES[quality]}: {counts[quality]} - {round(sizes[quality] / 1_000_000, 2)}Mb"
        for quality in MAG_QUALITY_COLOURS
    ]
    labels.append(f"Other contigs - {round(unclustered / 1_000_000, 2)}Mb")
    ax.legend(labels, bbox_to_anchor=(0.9, 0.0, 1.0, 1.0), loc="upper right")
    ax.text(-1.5, -1.2, f"Total size of the contigs: {round(total_size / 1_000_000, 2)}Mb")
    ax.text(-1.5, -1.35, f"Percentage of MAGs: {round(mags / total_size * 100, 2)}%")
    ax.text(-1.5, -1.5, f"Clusters threshold: {round(threshold / 1000, 2)}kb")
    ax.set_title("Size proportion of clusters depending on their quality")
    _saved(fig, out_file)
    return bin_summary

plot_paths

plot_paths(out_dir)

The plots that a run draws in its output directory, out_dir, in the order of PLOTS: plots/bins_distribution.pdf and plots/bins_size_distribution.pdf.

Source code in src/metator/figures.py
def plot_paths(out_dir):
    """The plots that a run draws in its output directory, out_dir, in the order
    of PLOTS: plots/bins_distribution.pdf and plots/bins_size_distribution.pdf."""
    return [join(out_dir, PLOT_DIR, name) for name in PLOTS]

plot_figures

plot_figures(out_dir, contigs_data, bin_summary, threshold)

Draw the plots of the final clusters of a validation in plots/ of its output directory, out_dir, made if missing (see plot_paths): bins_distribution.pdf (see figures_bins_distribution) and bins_size_distribution.pdf (see figures_bins_size_distribution). They replace files of their names; the other files of plots/ are left as they are.

They are figures: one that cannot be drawn is a warning, with the type, message and traceback of the error, and the other one is drawn; a run goes on to write the map of its clusters.

Parameters:

Name Type Description Default
out_dir str

The output directory of the run.

required
contigs_data DataFrame

The contig data of the validation: the Size of each contig of the run, those of its map.

required
bin_summary dict

The final clusters, by name, with their Length and miComplete's Weighted completeness and Weighted redundancy.

required
threshold int

The size threshold of the clusters (--size), in bp.

required
Source code in src/metator/figures.py
def plot_figures(out_dir, contigs_data, bin_summary, threshold):
    """Draw the plots of the final clusters of a validation in plots/ of its output
    directory, out_dir, made if missing (see plot_paths):
    bins_distribution.pdf (see figures_bins_distribution) and
    bins_size_distribution.pdf (see figures_bins_size_distribution). They
    replace files of their names; the other files of plots/ are left as they
    are.

    They are figures: one that cannot be drawn is a warning, with the type,
    message and traceback of the error, and the other one is drawn; a run goes
    on to write the map of its clusters.

    Parameters
    ----------
    out_dir : str
        The output directory of the run.
    contigs_data : pandas.DataFrame
        The contig data of the validation: the Size of each contig of the run,
        those of its map.
    bin_summary : dict
        The final clusters, by name, with their Length and miComplete's
        Weighted completeness and Weighted redundancy.
    threshold : int
        The size threshold of the clusters (--size), in bp.
    """
    plot_dir = join(out_dir, PLOT_DIR)
    try:
        os.makedirs(plot_dir, exist_ok=True)
    except OSError as error:
        logger.warning(f"The plots of the clusters are not drawn: {plot_dir} cannot be made ({error.strerror or error}).")
        return
    dots, pie = plot_paths(out_dir)
    _drawn(dots, lambda: figures_bins_distribution(_plotted(bin_summary), dots))
    _drawn(pie, lambda: figures_bins_size_distribution(_plotted(bin_summary), int(contigs_data["Size"].sum()), threshold, pie))