Skip to content

Contact maps

metator.metacool writes the contact map of a run, grouped by cluster, as a .metacool file, from the map that the run started from, with its clustering rounds and the normalization of its network. See The contact map of the clusters.

metator.metacool

Contact map of a metaTOR run as a .metacool file.

A .metacool file is metacooler's HDF5 contact map: a cooler whose chromosomes are the contigs, grouped by genome, readable by cooler.Cooler. The map is the interface between the steps of a run: network stores the contig columns and the weights of its normalization (the raw contacts stay as they are; a normalized contact is the count times both weights, as cooler stores balancing weights), partition the rounds core and overlapping (see read_partition), and validation the map of the clusters: one genome per final cluster, __unbinned__ for the others, the summary in the genomes table and every round. pipeline stores what the three steps store, in one map (see write_map), then what markers stores: the marker genes of each contig, in its contigs table (see Markers).

Every map is written in one metacooler edit session, validated in full once, then renamed onto the map of the output directory of the run (or over the input map, with --inplace): the map is whole whatever stops the run and does not grow from run to run. A run holds the map's lock from its checks to its end (see metator.cli.hold_lock).

MetacoolError

Bases: ValueError

The inputs cannot give a .metacool file; the message says why.

Source code in src/metator/metacool.py
class MetacoolError(ValueError):
    """The inputs cannot give a .metacool file; the message says why."""

MapReplacedError

Bases: MetacoolError

A map was replaced or written while it was read (see read_errors): what was read of it would mix two maps.

Source code in src/metator/metacool.py
class MapReplacedError(MetacoolError):
    """A map was replaced or written while it was read (see read_errors): what was
    read of it would mix two maps."""

Network dataclass

The network of the contigs of a run, as a map stores it (see write_map).

Attributes:

Name Type Description
table DataFrame

The contig data of the contigs of the map, in its order (see metator.network.contig_table): its columns that the run measured (GC_content and Hit, and Shotgun_coverage and Restriction_site when it has them) go to the contigs table of the map.

normalization str

The normalization of the network, stored as the weights metator_<normalization> of the bins of the map (see store_normalization): none for "None", the raw counts.

entry dict or None

What the map records of the run that stored the network, under the network key of its metator metadata: the version of metaTOR, the command line and the parameters of the run, and the columns of the map that it read (see metator.cli.network_entry).

tmp_dir (str, optional)

Where the contig data is written for metacooler annotate (contig_data_network.txt): the temporary directory of the run.

Source code in src/metator/metacool.py
@dataclass
class Network:
    """The network of the contigs of a run, as a map stores it (see write_map).

    Attributes
    ----------
    table : pandas.DataFrame
        The contig data of the contigs of the map, in its order (see
        metator.network.contig_table): its columns that the run measured
        (GC_content and Hit, and Shotgun_coverage and Restriction_site when it
        has them) go to the contigs table of the map.
    normalization : str
        The normalization of the network, stored as the weights
        ``metator_<normalization>`` of the bins of the map (see
        store_normalization): none for "None", the raw counts.
    entry : dict or None
        What the map records of the run that stored the network, under the
        network key of its metator metadata: the version of metaTOR, the
        command line and the parameters of the run, and the columns of the map
        that it read (see metator.cli.network_entry).
    tmp_dir : str, optional
        Where the contig data is written for metacooler annotate
        (contig_data_network.txt): the temporary directory of the run."""

    table: pd.DataFrame
    normalization: str
    entry: dict | None = field(default_factory=dict)
    tmp_dir: str | None = None

Markers dataclass

The marker genes of the contigs of a map, as metator markers stores them (see write_map and metator.markers.contig_markers).

Attributes:

Name Type Description
table DataFrame

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

entry dict

What the map records of the run, under the markers key of its metator metadata (see metator.cli.markers_entry).

tmp_dir (str, optional)

Where the table is written for metacooler annotate (contig_markers.txt): the temporary directory of the run.

Source code in src/metator/metacool.py
@dataclass
class Markers:
    """The marker genes of the contigs of a map, as metator markers stores them
    (see write_map and metator.markers.contig_markers).

    Attributes
    ----------
    table : pandas.DataFrame
        One row per contig of the map: its name (Name) and its markers in each
        set (MARKER_COLUMNS, see metator.markers.encode_markers), an empty text
        for none.
    entry : dict
        What the map records of the run, under the markers key of its metator
        metadata (see metator.cli.markers_entry).
    tmp_dir : str, optional
        Where the table is written for metacooler annotate
        (contig_markers.txt): the temporary directory of the run."""

    table: pd.DataFrame
    entry: dict
    tmp_dir: str | None = None

FinalClusters dataclass

The final clusters of a validation, as the map of the clusters stores them (see write_map).

Attributes:

Name Type Description
assignment dict

The final cluster of each binned contig, by name: the other contigs of the map go to metacooler's unbinned genome.

summary str

The summary of the final clusters at full precision (cluster_summary_full.txt, in the temporary directory of the run; see metator.io.SUMMARY_FULL_FILE): one row per final cluster, named by its first column, whose other columns go to the genomes table, with the values of miComplete, where cluster_summary.txt rounds them.

rounds tuple of pandas.DataFrame

The clustering rounds of the run, every cluster and its contigs (see metator.clusters.read_rounds), which replace those of the map.

entry dict

The entry validation of the metator metadata of the map: what the run was, what it read of the map, and the columns of its summary, in order.

Source code in src/metator/metacool.py
@dataclass
class FinalClusters:
    """The final clusters of a validation, as the map of the clusters stores them
    (see write_map).

    Attributes
    ----------
    assignment : dict
        The final cluster of each binned contig, by name: the other contigs of
        the map go to metacooler's __unbinned__ genome.
    summary : str
        The summary of the final clusters at full precision
        (cluster_summary_full.txt, in the temporary directory of the run; see
        metator.io.SUMMARY_FULL_FILE): one row per final cluster, named by its
        first column, whose other columns go to the genomes table, with the
        values of miComplete, where cluster_summary.txt rounds them.
    rounds : tuple of pandas.DataFrame
        The clustering rounds of the run, every cluster and its contigs (see
        metator.clusters.read_rounds), which replace those of the map.
    entry : dict
        The entry validation of the metator metadata of the map: what the run
        was, what it read of the map, and the columns of its summary, in order."""

    assignment: dict
    summary: str | None
    rounds: tuple | None
    entry: dict

MgeGenomes dataclass

The genomes of a map once metator mge stores its round mge in it (see mge_reassignment and write_map).

Attributes:

Name Type Description
assignment dict

The genome of each contig of the map, by name: ND for none.

table DataFrame

The values of each genome, indexed by its name: the genomes table that metacooler reassign stores (see _write_genomes_table).

Source code in src/metator/metacool.py
@dataclass
class MgeGenomes:
    """The genomes of a map once metator mge stores its round mge in it (see
    mge_reassignment and write_map).

    Attributes
    ----------
    assignment : dict
        The genome of each contig of the map, by name: ND for none.
    table : pandas.DataFrame
        The values of each genome, indexed by its name: the genomes table that
        metacooler reassign stores (see _write_genomes_table)."""

    assignment: dict
    table: pd.DataFrame

open_map

open_map(metacool)

The metacooler.MetaCooler of a .metacool map, or of an entry of a .mmetacool collection: a map that cannot be read (a missing file, a file that is not a map, a collection without the entry...) is a MetacoolError naming it.

Source code in src/metator/metacool.py
def open_map(metacool):
    """The metacooler.MetaCooler of a .metacool map, or of an entry of a
    .mmetacool collection: a map that cannot be read (a missing file, a file
    that is not a map, a collection without the entry...) is a MetacoolError
    naming it."""
    import metacooler

    try:
        return metacooler.MetaCooler(metacool)
    except (OSError, KeyError, ValueError) as error:
        reason = error.args[0] if isinstance(error, KeyError) and error.args else error
        raise MetacoolError(f"Cannot read the contact map {metacool}: {reason}") from error

read_errors

read_errors(metacool, remedy=READ_AGAIN)

Raise, as a MapReplacedError (a MetacoolError), metacooler's refusal of a read of the map metacool that spans a replacement of its file (MapChangedError): a run that updates a map in place replaces it with the map of its clusters, whose bins are in another order, and so are the bin ids of its pixels. metacooler reads a map one chunk of pixels at a time, and checks its file before and after each: a read that spanned the replacement would mix the bins of one map with the pixels of the other. The message ends with remedy: what the reader does about it.

Source code in src/metator/metacool.py
@contextmanager
def read_errors(metacool, remedy=READ_AGAIN):
    """Raise, as a MapReplacedError (a MetacoolError), metacooler's refusal of a
    read of the map metacool that spans a replacement of its file
    (MapChangedError): a run that updates a map in place replaces it with the
    map of its clusters, whose bins are in another order, and so are the bin
    ids of its pixels. metacooler reads a map one chunk of pixels at a time,
    and checks its file before and after each: a read that spanned the
    replacement would mix the bins of one map with the pixels of the other. The
    message ends with remedy: what the reader does about it."""
    import metacooler

    try:
        yield
    except metacooler.MapChangedError as error:
        raise MapReplacedError(
            f"{metacool} was replaced or written while it was read, by a run that updated it: what was read of it "
            f"would mix two maps. {remedy}"
        ) from error

check_map_lengths

check_map_lengths(metacool, contigs, lengths, of, where)

Refuse a map that gives contigs another length than lengths (by contig name; the contigs it lacks are not checked): it is not a map of the contigs of of (the assembly, or a contig data file), where (where) they have these lengths.

Source code in src/metator/metacool.py
def check_map_lengths(metacool, contigs, lengths, of, where):
    """Refuse a map that gives contigs another length than lengths (by contig
    name; the contigs it lacks are not checked): it is not a map of the contigs
    of `of` (the assembly, or a contig data file), where (`where`) they have
    these lengths."""
    wrong = [
        f"{str(name)!r} ({int(length)} bp in the map, {lengths[str(name)]} bp in {where})"
        for name, length in zip(contigs["name"], contigs["length"], strict=True)
        if str(name) in lengths and int(length) != lengths[str(name)]
    ]
    if wrong:
        raise MetacoolError(
            f"{metacool} is not a contact map of the contigs of {of}: {len(wrong)} contig(s) have another length in "
            f"it: {_shown(wrong, show=str)}."
        )

map_file

map_file(metacool)

The file of a .metacool map: the map, or the .mmetacool collection of an entry given as file.mmetacool::entries/NAME.

Source code in src/metator/metacool.py
def map_file(metacool):
    """The file of a .metacool map: the map, or the .mmetacool collection of an
    entry given as file.mmetacool::entries/NAME."""
    return str(metacool).split("::", 1)[0]

is_map

is_map(path)

Whether path is a contact map rather than a pairs file: an HDF5 file, which a pairs file never is, or the URI of a map inside one (file::group). A path that is a file is a map only when it is an HDF5 file, whatever its name: a pairs file may have :: in its name.

A URI is one when its file part is an HDF5 file; so are a .mmetacool collection and a .cool file, which open_map then refuses with metacooler's reason.

Source code in src/metator/metacool.py
def is_map(path):
    """Whether path is a contact map rather than a pairs file: an HDF5 file, which
    a pairs file never is, or the URI of a map inside one (file::group). A path
    that is a file is a map only when it is an HDF5 file, whatever its name: a
    pairs file may have :: in its name.

    A URI is one when its file part is an HDF5 file; so are a .mmetacool
    collection and a .cool file, which open_map then refuses with metacooler's
    reason."""
    path = str(path)
    if os.path.isfile(path):
        return _is_hdf5(path)
    return "::" in path and _is_hdf5(map_file(path))

is_entry

is_entry(metacool)

Whether metacool names an entry inside a file (a .mmetacool collection): file::group with a group other than the root of the file (file::/ is the file itself, as metacooler reads it).

Source code in src/metator/metacool.py
def is_entry(metacool):
    """Whether metacool names an entry inside a file (a .mmetacool collection):
    file::group with a group other than the root of the file (file::/ is the
    file itself, as metacooler reads it)."""
    return "::" in str(metacool) and str(metacool).split("::", 1)[1].strip().strip("/") != ""

is_input_map

is_input_map(metacool, outfile)

Whether writing the map at outfile updates the map metacool in place: outfile, its own name not followed (see _named), names the file of the map, its symbolic links followed, as metacooler edits the file that a link points to. A symbolic link at outfile is a file of its own, which a write replaces, whatever it points to; and a map given as a symbolic link is updated in place through its target, not through outfile = the link.

Source code in src/metator/metacool.py
def is_input_map(metacool, outfile):
    """Whether writing the map at outfile updates the map metacool in place:
    outfile, its own name not followed (see _named), names the file of the map,
    its symbolic links followed, as metacooler edits the file that a link
    points to. A symbolic link at outfile is a file of its own, which a write
    replaces, whatever it points to; and a map given as a symbolic link is
    updated in place through its target, not through outfile = the link."""
    source = map_file(metacool)
    return os.path.exists(source) and _named(outfile) == os.path.realpath(source)
is_hard_link_of(metacool, outfile)

Whether outfile is the file of the map metacool under another name (a hard link: the same file, which is not the map's own name, nor a symbolic link). Written as a map of its own, it would replace that name only; metacooler refuses an output that is the same file as its input.

Source code in src/metator/metacool.py
def is_hard_link_of(metacool, outfile):
    """Whether outfile is the file of the map metacool under another name (a hard
    link: the same file, which is not the map's own name, nor a symbolic link).
    Written as a map of its own, it would replace that name only; metacooler
    refuses an output that is the same file as its input."""
    source = map_file(metacool)
    return (
        os.path.lexists(outfile)
        and not os.path.islink(outfile)
        and os.path.exists(source)
        and os.path.samefile(source, outfile)
        and not is_input_map(metacool, outfile)
    )

non_ascii_names

non_ascii_names(names)

The names that are not ASCII, each once, in their order.

Source code in src/metator/metacool.py
def non_ascii_names(names):
    """The names that are not ASCII, each once, in their order."""
    return list(dict.fromkeys(name for name in names if not name.isascii()))

check_ascii_names

check_ascii_names(contigs, bins)

Refuse contig or cluster names that are not ASCII.

Source code in src/metator/metacool.py
def check_ascii_names(contigs, bins):
    """Refuse contig or cluster names that are not ASCII."""
    for kind, names in [("contig", contigs), ("cluster", bins)]:
        bad = non_ascii_names(names)
        if bad:
            raise MetacoolError(
                f"A .metacool file needs ASCII {kind} names (cooler reads them as ASCII text), and "
                f"{len(bad)} {kind} name(s) are not: {_shown(bad)}."
            )

check_bin_names

check_bin_names(bins)

Refuse bin names that metacooler reads as no bin.

metacooler would put the contigs of such a bin in unbinned silently.

Source code in src/metator/metacool.py
def check_bin_names(bins):
    """Refuse bin names that metacooler reads as no bin.

    metacooler would put the contigs of such a bin in __unbinned__ silently."""
    bad = list(dict.fromkeys(name for name in bins if name.strip().lower() in METACOOLER_UNBINNED))
    if bad:
        raise MetacoolError(
            "A .metacool file cannot have clusters named as metacooler marks a contig in no cluster (NA, NaN, N/A, N/D, "
            "-1 or __unbinned__ in any case, and nd in any case other than ND, which marks a contig in no cluster): it "
            f"would put their contigs in __unbinned__. Rename the {len(bad)} cluster(s): {_shown(bad)}."
        )

make_map_directory

make_map_directory(outfile, named=None)

Make the directory of the map at outfile, where metacooler locks and stages the map before it renames it there. A directory that cannot be made is a MetacoolError, which names outfile as named says (outfile itself by default).

Source code in src/metator/metacool.py
def make_map_directory(outfile, named=None):
    """Make the directory of the map at outfile, where metacooler locks and stages
    the map before it renames it there. A directory that cannot be made is a
    MetacoolError, which names outfile as named says (outfile itself by
    default)."""
    try:
        os.makedirs(os.path.dirname(os.path.abspath(outfile)), exist_ok=True)
    except OSError as error:
        raise MetacoolError(
            f"The directory of {named or outfile} cannot be made ({error.strerror}): write the map elsewhere."
        ) from error

normalization_weight_name

normalization_weight_name(normalization)

The weight column of the bins table of a map that stores a normalization of the network (see store_normalization).

Source code in src/metator/metacool.py
def normalization_weight_name(normalization):
    """The weight column of the bins table of a map that stores a normalization of
    the network (see store_normalization)."""
    return f"metator_{normalization}"

store_normalization

store_normalization(metacool, normalization)

Store a normalization of the network in a .metacool map, as a weight column of its bins table: metator_<normalization>.

Every bin of a contig takes its contig's weight, so the normalized contact of two contigs is their count times both weights, as cooler stores balancing weights. depends_on lets metacooler drop the column when an edit changes what it was computed from.

Parameters:

Name Type Description Default
metacool str

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

required
normalization str

Mode of normalization (see metator.network.normalization_weights), but "None".

required

Raises:

Type Description
MetacoolError

If the normalization is unknown, the contigs table of the map lacks a column it reads, the map is replaced or written as it is read, or metacooler cannot store the column (a ValueError, OSError or KeyError, message kept).

Source code in src/metator/metacool.py
def store_normalization(metacool, normalization):
    """Store a normalization of the network in a .metacool map, as a weight column
    of its bins table: ``metator_<normalization>``.

    Every bin of a contig takes its contig's weight, so the normalized contact
    of two contigs is their count times both weights, as cooler stores
    balancing weights. depends_on lets metacooler drop the column when an edit
    changes what it was computed from.

    Parameters
    ----------
    metacool : str
        Path to the .metacool file, or URI of an entry of a .mmetacool
        collection: ``file.mmetacool::entries/<name>``.
    normalization : str
        Mode of normalization (see metator.network.normalization_weights), but
        "None".

    Raises
    ------
    MetacoolError
        If the normalization is unknown, the contigs table of the map lacks a
        column it reads, the map is replaced or written as it is read, or
        metacooler cannot store the column (a ValueError, OSError or KeyError,
        message kept)."""
    with _metacooler_logging(), _as_metacool_errors(), read_errors(metacool):
        _store_normalization(metacool, normalization, _normalization_weights(metacool, normalization))

network_columns

network_columns(table)

The columns of the contig data of a network (table, see Network) that the map stores (CONTIG_COLUMNS, in that order): those that the run measured. The shotgun coverage and the restriction sites are text (-) where it has none.

Source code in src/metator/metacool.py
def network_columns(table):
    """The columns of the contig data of a network (table, see Network) that the
    map stores (CONTIG_COLUMNS, in that order): those that the run measured.
    The shotgun coverage and the restriction sites are text (-) where it has
    none."""
    return [column for column in CONTIG_COLUMNS if column in table.columns and pd.api.types.is_numeric_dtype(table[column])]

holds_partition

holds_partition(mc)

Whether the map mc holds a partition of its network: the clustering round core or overlapping, which metator partition stores (see read_partition).

Source code in src/metator/metacool.py
def holds_partition(mc):
    """Whether the map mc holds a partition of its network: the clustering round
    core or overlapping, which metator partition stores (see read_partition)."""
    return any(entry.get("name") in PARTITION_ROUNDS for entry in mc.cluster_rounds)

partition_network

partition_network(mc)

The digest of the network that the partition of the map mc was made on (see metator.network.network_digest), which metator partition records with it, under the partition key of the metator metadata of the map (as NETWORK_DIGEST): None when the map records none.

Source code in src/metator/metacool.py
def partition_network(mc):
    """The digest of the network that the partition of the map mc was made on (see
    metator.network.network_digest), which metator partition records with it,
    under the partition key of the metator metadata of the map (as
    NETWORK_DIGEST): None when the map records none."""
    entry = _metator_metadata(mc).get("partition")
    digest = entry.get(NETWORK_DIGEST) if isinstance(entry, dict) else None
    return digest if isinstance(digest, str) else None

holds_hosts

holds_hosts(mc)

Whether the map mc holds the hosts of its MGE clusters that metator host found: the host entry of its metator metadata (see HOST_ENTRY).

Source code in src/metator/metacool.py
def holds_hosts(mc):
    """Whether the map mc holds the hosts of its MGE clusters that metator host
    found: the host entry of its metator metadata (see HOST_ENTRY)."""
    return isinstance(_metator_metadata(mc).get(HOST_ENTRY), dict)

host_entry

host_entry(mc)

The host entry of the metator metadata of the map mc (see HOST_ENTRY): what the run that found the hosts of its MGE clusters recorded, its command line and its parameters among them; None when the map holds no hosts.

Source code in src/metator/metacool.py
def host_entry(mc):
    """The host entry of the metator metadata of the map mc (see HOST_ENTRY): what
    the run that found the hosts of its MGE clusters recorded, its command line
    and its parameters among them; None when the map holds no hosts."""
    entry = _metator_metadata(mc).get(HOST_ENTRY)
    return entry if isinstance(entry, dict) else None

hosts_network

hosts_network(mc)

The digest of the network that metator host read to find the hosts that the map mc holds (see holds_hosts), as its host entry records it: None when the map records none.

Source code in src/metator/metacool.py
def hosts_network(mc):
    """The digest of the network that metator host read to find the hosts that
    the map mc holds (see holds_hosts), as its host entry records it: None when
    the map records none."""
    entry = _metator_metadata(mc).get(HOST_ENTRY)
    digest = entry.get(NETWORK_DIGEST) if isinstance(entry, dict) else None
    return digest if isinstance(digest, str) else None

holds_markers

holds_markers(mc)

Whether the map mc holds the marker genes of its contigs that metator markers found: the markers entry of its metator metadata, or a column of MARKER_COLUMNS in its contigs table.

Source code in src/metator/metacool.py
def holds_markers(mc):
    """Whether the map mc holds the marker genes of its contigs that metator
    markers found: the markers entry of its metator metadata, or a column of
    MARKER_COLUMNS in its contigs table."""
    held = isinstance(_metator_metadata(mc).get(MARKERS_ENTRY), dict)
    return held or any(column in mc.contigs.columns for column in MARKER_COLUMNS)

markers_entry

markers_entry(mc)

The markers entry of the metator metadata of the map mc (see MARKERS_ENTRY): what the run that found the marker genes of its contigs recorded, its marker sets among them (see metator.markers.map_sets); None when the map holds no markers.

Source code in src/metator/metacool.py
def markers_entry(mc):
    """The markers entry of the metator metadata of the map mc (see
    MARKERS_ENTRY): what the run that found the marker genes of its contigs
    recorded, its marker sets among them (see metator.markers.map_sets); None
    when the map holds no markers."""
    entry = _metator_metadata(mc).get(MARKERS_ENTRY)
    return entry if isinstance(entry, dict) else None

map_assignment

map_assignment(mc)

The binning of the map mc (opened): the names of its contigs, in the order of its contigs table, and the name of the genome of each (UNBINNED_GENOME for none), as two arrays (see assignment_digest).

Source code in src/metator/metacool.py
def map_assignment(mc):
    """The binning of the map mc (opened): the names of its contigs, in the order
    of its contigs table, and the name of the genome of each (UNBINNED_GENOME
    for none), as two arrays (see assignment_digest)."""
    contigs = mc.contigs
    genomes = mc.genomes["name"].astype(str).to_numpy()
    return contigs["name"].astype(str).to_numpy(), genomes[contigs["genome_id"].to_numpy()]

assignment_digest

assignment_digest(contigs, genomes)

The identity of a binning of the contigs of a map: the SHA-256 of the genome of each contig, by the names of the contigs, as metator.network.network_digest is the identity of a network. It is that of the assignment, not of a map: the same whatever the order of the contigs, another one once a contig is in another genome, or a genome is renamed. metator markers records the binning that it found the marker genes of the contigs in (see ASSIGNMENT_DIGEST), which markers_predate checks the binning of the map against.

Parameters:

Name Type Description Default
contigs sequence of str

The names of the contigs of the map.

required
genomes sequence of str

The name of the genome of each, in the same order: UNBINNED_GENOME for none (see map_assignment).

required

Returns:

Type Description
str

The SHA-256, in hexadecimal, of the name of each contig and of its genome, the contigs by name, each field ended by a NUL, which no name holds.

Source code in src/metator/metacool.py
def assignment_digest(contigs, genomes):
    """The identity of a binning of the contigs of a map: the SHA-256 of the
    genome of each contig, by the names of the contigs, as
    metator.network.network_digest is the identity of a network. It is that
    of the assignment, not of a map: the same whatever the order of the
    contigs, another one once a contig is in another genome, or a genome is
    renamed. metator markers records the binning that it found the marker
    genes of the contigs in (see ASSIGNMENT_DIGEST), which markers_predate
    checks the binning of the map against.

    Parameters
    ----------
    contigs : sequence of str
        The names of the contigs of the map.
    genomes : sequence of str
        The name of the genome of each, in the same order: UNBINNED_GENOME for
        none (see map_assignment).

    Returns
    -------
    str
        The SHA-256, in hexadecimal, of the name of each contig and of its
        genome, the contigs by name, each field ended by a NUL, which no name
        holds."""
    import hashlib

    names = np.asarray(contigs, dtype=str)
    of = np.asarray(genomes, dtype=str)
    order = np.argsort(names, kind="stable")
    fields = zip(names[order].tolist(), of[order].tolist(), strict=True)
    return hashlib.sha256("".join(f"{name}\0{genome}\0" for name, genome in fields).encode()).hexdigest()

markers_binning

markers_binning(mc)

The digest of the binning that metator markers found the marker genes of the contigs of the map mc in (see assignment_digest), as its markers entry records it (ASSIGNMENT_DIGEST): None when the map records none (it holds no markers, or markers that an earlier metaTOR found).

Source code in src/metator/metacool.py
def markers_binning(mc):
    """The digest of the binning that metator markers found the marker genes of
    the contigs of the map mc in (see assignment_digest), as its markers entry
    records it (ASSIGNMENT_DIGEST): None when the map records none (it holds no
    markers, or markers that an earlier metaTOR found)."""
    entry = markers_entry(mc)
    digest = entry.get(ASSIGNMENT_DIGEST) if entry is not None else None
    return digest if isinstance(digest, str) else None

markers_predate

markers_predate(mc)

Whether the marker genes of the contigs of the map mc predate its genomes, as metator report says: found by metator markers in another binning of its contigs than the one the map has (the digest that its markers entry records is not that of its genomes, see assignment_digest). Each contig has its own markers still, but summed over a genome whose contigs changed since, they give an estimate of miComplete's numbers, not those of the genome as metator markers would find its genes. None when the map cannot tell: it records no such digest (see markers_binning).

Source code in src/metator/metacool.py
def markers_predate(mc):
    """Whether the marker genes of the contigs of the map mc predate its genomes,
    as metator report says: found by metator markers in another binning of its
    contigs than the one the map has (the digest that its markers entry records
    is not that of its genomes, see assignment_digest). Each contig has its own
    markers still, but summed over a genome whose contigs changed since, they
    give an estimate of miComplete's numbers, not those of the genome as
    metator markers would find its genes. None when the map cannot tell: it
    records no such digest (see markers_binning)."""
    found_in = markers_binning(mc)
    if found_in is None:
        return None
    return found_in != assignment_digest(*map_assignment(mc))

store_rounds

store_rounds(path, rounds, names=None, name=None)

Store the clustering rounds of a run in the /clusters group of a map, in place of those it held: the overlapping, recursive and final clusters of metator.clusters, with their contigs, their parents and their columns (those of miComplete, and of the bin summary for the final clusters).

A text column holds an empty text where a round has no value (HDF5 stores no missing text), and the contigs of a cluster that the map lacks are left out, with a warning.

Parameters:

Name Type Description Default
path str

Path to the .metacool file, written in place.

required
rounds tuple of pandas.DataFrame, or None

The clusters and their contigs (see metator.clusters.read_rounds).

required
names list of str

The names of the rounds, in the order they were made: by default, those of the clusters, in their order.

None
name str

The map that path is staged for, which the warnings name (path by default).

None
Source code in src/metator/metacool.py
def store_rounds(path, rounds, names=None, name=None):
    """Store the clustering rounds of a run in the /clusters group of a map, in
    place of those it held: the overlapping, recursive and final clusters of
    metator.clusters, with their contigs, their parents and their columns
    (those of miComplete, and of the bin summary for the final clusters).

    A text column holds an empty text where a round has no value (HDF5 stores
    no missing text), and the contigs of a cluster that the map lacks are left
    out, with a warning.

    Parameters
    ----------
    path : str
        Path to the .metacool file, written in place.
    rounds : tuple of pandas.DataFrame, or None
        The clusters and their contigs (see metator.clusters.read_rounds).
    names : list of str, optional
        The names of the rounds, in the order they were made: by default, those
        of the clusters, in their order.
    name : str, optional
        The map that path is staged for, which the warnings name (path by
        default)."""
    import metacooler

    if rounds is None:
        metacooler.drop_clusters(path)
        return
    clusters, members = rounds
    order = list(dict.fromkeys(clusters["round"])) if names is None else list(names)
    steps = {name: "partition" if name in PARTITION_ROUNDS else "validation" for name in order}
    _store_clusters(
        path,
        [{"name": name, "tool": "metaTOR", "version": __version__, "step": steps[name]} for name in order],
        clusters,
        members,
        name=name,
    )

map_rounds

map_rounds(mc)

The clustering rounds of a map (mc, opened), as metator.clusters.Rounds gives them (see Rounds.tables), and as _store_clusters stored them: every cluster of every round, in the order of the rounds and of their clusters, with its parent and the columns its round stored, not those that metacooler computes; and every contig of a cluster, in the order of the map. An empty text of a text column, which _store_clusters stores for a missing value (HDF5 holds no missing text), is a missing value again (None): a genuinely empty text too.

Returns:

Type Description
tuple of pandas.DataFrame

The clusters and their contigs (columns round, cluster, contig).

Source code in src/metator/metacool.py
def map_rounds(mc):
    """The clustering rounds of a map (mc, opened), as metator.clusters.Rounds
    gives them (see Rounds.tables), and as _store_clusters stored them: every
    cluster of every round, in the order of the rounds and of their clusters,
    with its parent and the columns its round stored, not those that metacooler
    computes; and every contig of a cluster, in the order of the map. An empty
    text of a text column, which _store_clusters stores for a missing value
    (HDF5 holds no missing text), is a missing value again (None): a genuinely
    empty text too.

    Returns
    -------
    tuple of pandas.DataFrame
        The clusters and their contigs (columns round, cluster, contig)."""
    clusters = mc.clusters.drop(columns=_computed_cluster_columns(), errors="ignore").reset_index(drop=True)
    for column in clusters.columns:
        if not pd.api.types.is_numeric_dtype(clusters[column]):
            values = clusters[column].astype(object)
            clusters[column] = values.where(values.notna() & (values.astype(str) != ""), None)
    members = mc.cluster_members().reset_index(drop=True)
    return clusters, members[["round", "cluster", "contig"]]

read_partition

read_partition(metacool, mc=None, network=None)

The partition that a map stores, as metator partition MAP stores it (see write_map and metator.clusters.partition_rounds): its clustering rounds core and overlapping, read back as metator.clusters.Partition. With network, the digest of the network stored in the map (see metator.network.stored_network), the partition must have been made on that network, as the map records it (see partition_network): metator network can store another network in the map, and leaves the partition there, which is then not that of the network.

Clusters are numbered as their names say (see metator.clusters.cluster_number) and contigs get their positions in the map, from 1. A core cluster's contigs come in ID order, an overlapping cluster's in the order of its core clusters, then of IDs: the order metator.partition.partition gives, which the map's sorted rounds lose.

Parameters:

Name Type Description Default
metacool str

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

required
mc MetaCooler

The map, opened: by default, metacool is opened.

None
network str

The digest of the network stored in the map, which the partition must have been made on.

None

Returns:

Type Description
Partition

The core and the overlapping clusters of the map.

Raises:

Type Description
MetacoolError

If the map lacks the round core or overlapping (metator partition has not run on it), or, with network, does not record that its partition was made on that network, or a cluster of them is not named as metator partition names it, or holds a contig in no core cluster (an overlapping cluster), or the map cannot be read.

Source code in src/metator/metacool.py
def read_partition(metacool, mc=None, network=None):
    """The partition that a map stores, as metator partition MAP stores it (see
    write_map and metator.clusters.partition_rounds): its clustering rounds
    core and overlapping, read back as metator.clusters.Partition. With
    network, the digest of the network stored in the map (see
    metator.network.stored_network), the partition must have been made on that
    network, as the map records it (see partition_network): metator network can
    store another network in the map, and leaves the partition there, which is
    then not that of the network.

    Clusters are numbered as their names say (see
    metator.clusters.cluster_number) and contigs get their positions in the
    map, from 1. A core cluster's contigs come in ID order, an overlapping
    cluster's in the order of its core clusters, then of IDs: the order
    metator.partition.partition gives, which the map's sorted rounds lose.

    Parameters
    ----------
    metacool : str
        Path to the .metacool file, or URI of an entry of a .mmetacool
        collection, for the messages.
    mc : metacooler.MetaCooler, optional
        The map, opened: by default, metacool is opened.
    network : str, optional
        The digest of the network stored in the map, which the partition must
        have been made on.

    Returns
    -------
    metator.clusters.Partition
        The core and the overlapping clusters of the map.

    Raises
    ------
    MetacoolError
        If the map lacks the round core or overlapping (metator partition has
        not run on it), or, with network, does not record that its partition
        was made on that network, or a cluster of them is not named as metator
        partition names it, or holds a contig in no core cluster (an
        overlapping cluster), or the map cannot be read."""
    with _metacooler_logging(), read_errors(metacool):
        if mc is None:
            mc = open_map(metacool)
        held = [entry["name"] for entry in mc.cluster_rounds]
        missing = [name for name in PARTITION_ROUNDS if name not in held]
        if missing:
            raise MetacoolError(
                f"{metacool} holds no partition of its network (the clustering round(s) {' and '.join(missing)}): run "
                "metator partition on it first, which stores its core and overlapping clusters in the map."
            )
        made_on = partition_network(mc)
        if network is not None and made_on != network:
            reason = (
                "does not record the network that its partition was made on, which metator partition records"
                if made_on is None
                else "holds a partition of another network than the one stored in it now: metator network stored "
                "another network in the map since metator partition ran on it"
            )
            raise MetacoolError(
                f"{metacool} {reason}. Run metator partition {metacool} again, which partitions the network stored in the map."
            )
        ids = pd.Index(mc.contigs["name"].astype(str))
        members = {name: mc.cluster_members(name) for name in PARTITION_ROUNDS}
        # Every cluster of the round, those with no contig too.
        clusters = mc.clusters
    found = {}
    for round_name in PARTITION_ROUNDS:
        named = list(clusters.loc[(clusters["round"] == round_name).to_numpy(), "name"].astype(str))
        numbers = {name: mtcl.cluster_number(round_name, name) for name in named}
        odd = [name for name, number in numbers.items() if number is None]
        # Two names of one number (core_00001 and core_000001).
        seen = {}
        for name, number in numbers.items():
            if number is not None and seen.setdefault(number, name) != name:
                odd.append(name)
        if odd:
            form = "core_<number>" if round_name == mtcl.CORE else "<prefix>_<number>_00000"
            raise MetacoolError(
                f"The clustering round {round_name} of {metacool} holds cluster(s) that metator partition does not "
                f"name so ({form}, one number each): {_shown(odd)}. Run metator partition on the map again."
            )
        held_members = members[round_name]
        # The ID of each contig of a cluster: its position in the map, from 1.
        rows = pd.Series(ids.get_indexer(held_members["contig"].astype(str)) + 1)
        by_cluster = rows.groupby(held_members["cluster"].astype(str).to_numpy()).agg(sorted).to_dict()
        found[round_name] = (
            {numbers[name]: [int(contig) for contig in by_cluster.get(name, [])] for name in named},
            {numbers[name]: name for name in named},
        )
    core, _ = found[mtcl.CORE]
    overlapping, names = found[mtcl.OVERLAPPING]
    # The core cluster of each contig, for the order of the overlapping ones.
    core_of = {contig: number for number, contigs in core.items() for contig in contigs}
    lacking = sorted({contig for contigs in overlapping.values() for contig in contigs} - core_of.keys())
    if lacking:
        raise MetacoolError(
            f"The overlapping clusters of {metacool} hold contig(s) in no core cluster: {_shown([ids[i - 1] for i in lacking])}. "
            "Run metator partition on the map again."
        )
    overlapping = {
        number: sorted(contigs, key=lambda contig: (core_of[contig], contig)) for number, contigs in overlapping.items()
    }
    return mtcl.Partition(core=dict(sorted(core.items())), overlapping=dict(sorted(overlapping.items())), names=names)

write_map

write_map(
    metacool,
    outfile,
    *,
    network=None,
    partition=None,
    rounds=None,
    round_names=None,
    clusters=None,
    mge=None,
    reassign=False,
    hosts=None,
    drop_hosts=False,
    markers=None,
    force=False,
    planned=None,
    mge_follows=False,
    markers_follow=False,
)

Write the map of a run at outfile from its input map, metacool: what the run stores in it, everything else as it was. Each step of a run writes its map so, and pipeline writes what its three steps store, in one map, as the steps one by one write it (then its step markers stores the marker genes of the contigs in it, and, with --mges, its steps mge and host the round mge and the hosts, as markers, mge and host do).

Everything goes into one edit session (see _staged_edit), validated once and renamed once; on any failure outfile is left as it was. In order: the final clusters (a map written anew from the input map, contigs grouped by cluster then longest first), or the genomes that the round mge makes (see mge_reassignment: a map written anew from the input map too), the network (columns and weights, last in both tables), the partition's rounds and entry, then the round mge, or the hosts of the MGE clusters. A run that replaces the rounds warns of those the binning did not make, and drops them.

The hosts that metator host stored in the map (see HOST_ENTRY) describe its round mge, its genomes and its network as they were: a run that replaces the round mge (metator mge, but --random), the rounds (partition) or the genomes (validation, pipeline) drops them, and so does a network run with drop_hosts (another network than the one they were found on), each with a warning.

The marker genes that metator markers stored in the map (see MARKERS_ENTRY) are facts about its contigs, which every write but that of markers keeps: a run that regroups the contigs into other genomes than those that the genes were found in (validation, mge --reassign) says so once the map is written, as they predate its new genomes (see markers_predate), unless markers_follow.

Parameters:

Name Type Description Default
metacool str

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

required
outfile str

Path to the .metacool file to write.

required
network Network
None
partition dict

The entry partition of the metator metadata.

None
rounds tuple of pandas.DataFrame

Clustering rounds, which replace those of the map: the rounds core and overlapping of a partition (see metator.clusters.partition_rounds).

None
round_names list of str

The names of the rounds, in the order they were made (see store_rounds).

None
clusters FinalClusters
None
mge tuple

The tables of the round mge or mge_random (see metator.clusters.mge_round) and its entry (its name, and what made it: see metator.cli.mge_entry). The round mge undoes the MGE genomes of the map (see mge_reassignment).

None
reassign bool

With the round mge (mge), whether its clusters are genomes of the map then (metator mge --reassign).

False
hosts tuple

The hosts of the MGE clusters of the map (a metator.host.Hosts) and the host entry of the run that found them (see metator.cli.host_entry), stored alone (see _store_hosts).

None
drop_hosts bool

Whether to drop the hosts that the map holds, which another network than the one stored now gave (a network run).

False
markers Markers

The marker genes of the contigs of the map (metator markers), stored alone (see _store_markers). Every other write keeps those that the map holds (see MARKERS_ENTRY).

None
force bool

Whether to replace an existing outfile: the input map itself, which a run updates in place, or another file.

False
planned MetaCooler

The input map as the run read it, opened when the run started: the map is refused if it changed since (another run replaced it, or a program wrote it), rather than written from another map than the one that the run worked on.

None
mge_follows bool

Whether the run stores the round mge and the hosts of its MGE clusters in the map once it is written (pipeline --mges, in its steps mge and host): the warnings of what the map no longer holds leave them out, which the run makes again.

False
markers_follow bool

Whether the run says later what becomes of the marker genes of the contigs that the map holds, which this write does not say then: it finds them again once the map is written (pipeline, in its step markers), or regroups the contigs again (pipeline --no-markers --mges, in its step mge, which says it).

False

Raises:

Type Description
ValueError

If clusters come with rounds or round_names: the rounds of a validation are those of its clusters; or with mge: the genomes of a validation are its final clusters; or hosts, or markers, with anything else to store. If reassign comes without the round mge.

MetacoolError

If the outfile is no file's path (a URI), exists (without force), is the .mmetacool collection of the input map or a hard link of the input map, the input map is missing, cannot be read or changed since planned was opened, a contig of the clusters is not a contig of the input map, a cluster name is not ASCII or one that metacooler reads as no cluster (NA, nan, -1...), an MGE cluster is named after a genome that the map keeps (see mge_reassignment), or metacooler cannot write the map (a ValueError, OSError or KeyError, message kept).

Source code in src/metator/metacool.py
def write_map(
    metacool,
    outfile,
    *,
    network=None,
    partition=None,
    rounds=None,
    round_names=None,
    clusters=None,
    mge=None,
    reassign=False,
    hosts=None,
    drop_hosts=False,
    markers=None,
    force=False,
    planned=None,
    mge_follows=False,
    markers_follow=False,
):
    """Write the map of a run at outfile from its input map, metacool: what the
    run stores in it, everything else as it was. Each step of a run writes its
    map so, and pipeline writes what its three steps store, in one map, as the
    steps one by one write it (then its step markers stores the marker genes
    of the contigs in it, and, with --mges, its steps mge and host the round
    mge and the hosts, as markers, mge and host do).

    Everything goes into one edit session (see _staged_edit), validated once
    and renamed once; on any failure outfile is left as it was. In order: the
    final clusters (a map written anew from the input map, contigs grouped by
    cluster then longest first), or the genomes that the round mge makes (see
    mge_reassignment: a map written anew from the input map too), the network
    (columns and weights, last in both tables), the partition's rounds and
    entry, then the round mge, or the hosts of the MGE clusters. A run that
    replaces the rounds warns of those the binning did not make, and drops
    them.

    The hosts that metator host stored in the map (see HOST_ENTRY) describe
    its round mge, its genomes and its network as they were: a run that
    replaces the round mge (metator mge, but --random), the rounds
    (partition) or the genomes (validation, pipeline) drops them, and so does
    a network run with drop_hosts (another network than the one they were
    found on), each with a warning.

    The marker genes that metator markers stored in the map (see
    MARKERS_ENTRY) are facts about its contigs, which every write but that of
    markers keeps: a run that regroups the contigs into other genomes than
    those that the genes were found in (validation, mge --reassign) says so
    once the map is written, as they predate its new genomes (see
    markers_predate), unless markers_follow.

    Parameters
    ----------
    metacool : str
        Path to the input .metacool file, or URI of an entry of a .mmetacool
        collection: ``file.mmetacool::entries/<name>``.
    outfile : str
        Path to the .metacool file to write.
    network : Network, optional
    partition : dict, optional
        The entry partition of the metator metadata.
    rounds : tuple of pandas.DataFrame, optional
        Clustering rounds, which replace those of the map: the rounds core and
        overlapping of a partition (see metator.clusters.partition_rounds).
    round_names : list of str, optional
        The names of the rounds, in the order they were made (see
        store_rounds).
    clusters : FinalClusters, optional
    mge : tuple, optional
        The tables of the round mge or mge_random (see
        metator.clusters.mge_round) and its entry (its name, and what made it:
        see metator.cli.mge_entry). The round mge undoes the MGE genomes of
        the map (see mge_reassignment).
    reassign : bool
        With the round mge (mge), whether its clusters are genomes of the map
        then (metator mge --reassign).
    hosts : tuple, optional
        The hosts of the MGE clusters of the map (a metator.host.Hosts) and
        the host entry of the run that found them (see metator.cli.host_entry),
        stored alone (see _store_hosts).
    drop_hosts : bool
        Whether to drop the hosts that the map holds, which another network
        than the one stored now gave (a network run).
    markers : Markers, optional
        The marker genes of the contigs of the map (metator markers), stored
        alone (see _store_markers). Every other write keeps those that the
        map holds (see MARKERS_ENTRY).
    force : bool
        Whether to replace an existing outfile: the input map itself, which a
        run updates in place, or another file.
    planned : metacooler.MetaCooler, optional
        The input map as the run read it, opened when the run started: the map
        is refused if it changed since (another run replaced it, or a program
        wrote it), rather than written from another map than the one that the
        run worked on.
    mge_follows : bool
        Whether the run stores the round mge and the hosts of its MGE clusters
        in the map once it is written (pipeline --mges, in its steps mge and
        host): the warnings of what the map no longer holds leave them out,
        which the run makes again.
    markers_follow : bool
        Whether the run says later what becomes of the marker genes of the
        contigs that the map holds, which this write does not say then: it
        finds them again once the map is written (pipeline, in its step
        markers), or regroups the contigs again (pipeline --no-markers --mges,
        in its step mge, which says it).

    Raises
    ------
    ValueError
        If clusters come with rounds or round_names: the rounds of a validation
        are those of its clusters; or with mge: the genomes of a validation are
        its final clusters; or hosts, or markers, with anything else to store.
        If reassign comes without the round mge.
    MetacoolError
        If the outfile is no file's path (a URI), exists (without force), is
        the .mmetacool collection of the input map or a hard link of the input
        map, the input map is missing, cannot be read or changed since planned
        was opened, a contig of the clusters is not a contig of the input map,
        a cluster name is not ASCII or one that metacooler reads as no cluster
        (NA, nan, -1...), an MGE cluster is named after a genome that the map
        keeps (see mge_reassignment), or metacooler cannot write the map (a
        ValueError, OSError or KeyError, message kept)."""
    if clusters is not None and (rounds is not None or round_names is not None or mge is not None):
        raise ValueError(
            "write_map takes the clustering rounds and the genomes of a validation from its clusters "
            "(FinalClusters): give clusters without rounds, round_names or mge."
        )
    if hosts is not None and any(store is not None for store in (network, partition, rounds, clusters, mge, markers)):
        raise ValueError("write_map stores the hosts of the MGE clusters of metator host alone: give hosts alone.")
    if markers is not None and any(store is not None for store in (network, partition, rounds, clusters, mge)):
        raise ValueError("write_map stores the marker genes of the contigs of metator markers alone: give markers alone.")
    # What the hosts that the map holds describe, which the run replaces (see
    # HOST_ENTRY): none when it keeps them.
    replaced = (
        "its genomes"
        if clusters is not None
        else "its clustering rounds"
        if rounds is not None
        else f"its round {mtcl.MGE}"
        if mge is not None and mge[1]["name"] == mtcl.MGE
        else "its network"
        if drop_hosts
        else None
    )
    if reassign and (mge is None or mge[1]["name"] != mtcl.MGE):
        raise ValueError(f"reassign makes genomes of the clusters of the round {mtcl.MGE}: give them as mge.")
    metacool, outfile = str(metacool), str(outfile)
    if is_entry(metacool) and is_input_map(metacool, outfile):
        raise MetacoolError(
            f"{outfile} is the .mmetacool collection of the input map {metacool}: the map would replace the whole "
            "collection. Write it to another file."
        )
    _refuse_a_hard_link_of_the_map(metacool, outfile)
    _check_paths(outfile, force, [map_file(metacool)])
    if clusters is not None:
        check_ascii_names((), clusters.assignment.values())
        check_bin_names(clusters.assignment.values())
    in_place = is_input_map(metacool, outfile)
    with _metacooler_logging():
        mc = open_map(metacool)
        with read_errors(metacool):
            contigs = mc.contigs
            # The rounds of the map that the run does not make: said once the
            # map is written.
            later = _later_rounds(mc) if clusters is not None or rounds is not None else []
            # The hosts that the run drops: said once the map is written.
            dropped_hosts = replaced is not None and holds_hosts(mc)
            # The genomes of the map once its round mge is stored: None when
            # they stay as they are.
            genomes = mge_reassignment(mc, mge[0], reassign) if mge is not None and mge[1]["name"] == mtcl.MGE else None
            # The binning that the marker genes that the map holds were found
            # in, which a run that regroups the contigs keeps: said once the
            # map is written, if it regroups them into other genomes.
            regroups = clusters is not None or genomes is not None
            found_in = _markers_found_in(mc) if regroups and not markers_follow else None
        if clusters is not None:
            _check_clustered_contigs(metacool, contigs, clusters)
        writing, written = _what_is_written(contigs, network, rounds, clusters, mge, genomes, hosts, markers)
        source = "in place" if in_place else f"from {metacool}"
        logger.info(f"Writing {outfile} {source}{writing}.")
        with _as_metacool_errors(), ExitStack() as session:
            make_map_directory(outfile)
            # One staged copy, which replaces the map once it is valid (see
            # _staged_edit).
            read = _read(mc, planned)
            staged = _enter_session(session, metacool, outfile, read, force)
            if clusters is not None:
                _store_final_clusters(staged, metacool, read, contigs, clusters, partition)
            elif genomes is not None:
                _store_mge_genomes(staged, metacool, read, genomes)
            if network is not None:
                _store_network(staged, network)
            if clusters is not None:
                store_rounds(staged, clusters.rounds, name=metacool)
            else:
                if rounds is not None:
                    store_rounds(staged, rounds, round_names, name=metacool)
                if partition is not None:
                    _store_metator_entries(staged, {"partition": partition})
            if mge is not None:
                _store_round(staged, metacool, *mge)
                entry = mge[1]
                run = {key: value for key, value in entry.items() if key not in ("name", "tool", "step")}
                _store_metator_entries(staged, {entry["name"]: run})
            # What made the rounds of metator mge that the map no longer
            # holds, which the clusters of a validation carried over.
            _drop_metator_entries(staged, [dropped["name"] for dropped in later if _made_by(dropped) == "metaTOR mge"])
            if markers is not None:
                _store_markers(staged, markers)
            if hosts is not None:
                _store_hosts(staged, metacool, *hosts)
            elif replaced is not None:
                # The hosts that described what the run replaced: those that
                # the map held, and what was carried over of them (the host
                # entry that the clusters of a validation carry, the columns of
                # an earlier round mge that the other rounds kept).
                _drop_hosts(staged, metacool)
        logger.debug(f"{outfile} is written: the contact map{written}.")
    _warn_dropped_rounds(
        [entry for entry in later if not (mge_follows and entry["name"] == mtcl.MGE)], metacool, outfile, in_place
    )
    if dropped_hosts and not mge_follows:
        _warn_dropped_hosts(metacool, outfile, in_place, replaced)
    if found_in is not None and _regrouped(contigs, clusters, genomes) != found_in:
        _log_markers_predate(metacool, outfile, in_place)

mge_genomes

mge_genomes(mc)

The MGE genomes of the map mc (opened), by name, in the order of its genomes table: those that its column mge says are (True), which metator mge --reassign made of the clusters of its round mge (see write_map).

Source code in src/metator/metacool.py
def mge_genomes(mc):
    """The MGE genomes of the map mc (opened), by name, in the order of its genomes
    table: those that its column mge says are (True), which metator mge
    --reassign made of the clusters of its round mge (see write_map)."""
    genomes = mc.genomes
    if MGE_GENOME_COLUMN not in genomes.columns:
        return []
    flagged = genomes[MGE_GENOME_COLUMN].astype(object).map(lambda value: str(value) == "True").to_numpy(bool)
    return list(genomes["name"].astype(str).to_numpy()[flagged])

mge_reassignment

mge_reassignment(mc, rounds, reassign)

The genomes of the map mc (opened) once metator mge stores the round mge of its run in it (rounds: its clusters and their contigs, see metator.clusters.mge_round), or None when the run leaves them as they are.

The MGE genomes that the map holds are undone first: those that its column mge says are (see mge_genomes), and those named after a cluster of its round mge (which metacooler reassign --round mge makes, say). Their contigs go back to their final cluster (the round final), or to none. With reassign (--reassign), each MGE cluster of the run is a genome then, named after it, with its values (GC, Hit, BinningScore): its contigs leave the genomes that held them, MAGs or none. The other genomes are kept, with their values, those of the validation, which describe them with the contigs that they lose, as the log says; a genome whose contigs all leave it is no genome any more, and its values go with it. The column mge of the genomes table says which genomes are MGE genomes (True): it is not there without reassign.

Returns:

Type Description
MgeGenomes, or None

None without reassign, on a map that holds no MGE genome.

Raises:

Type Description
MetacoolError

If a genome that the run keeps is named after an MGE cluster of the run: their contigs would make one genome.

Source code in src/metator/metacool.py
def mge_reassignment(mc, rounds, reassign):
    """The genomes of the map mc (opened) once metator mge stores the round mge of
    its run in it (rounds: its clusters and their contigs, see
    metator.clusters.mge_round), or None when the run leaves them as they are.

    The MGE genomes that the map holds are undone first: those that its column
    mge says are (see mge_genomes), and those named after a cluster of its
    round mge (which metacooler reassign --round mge makes, say). Their
    contigs go back to their final cluster (the round final), or to none.
    With reassign (--reassign), each MGE cluster of the run is a genome then,
    named after it, with its values (GC, Hit, BinningScore): its contigs leave
    the genomes that held them, MAGs or none. The other genomes are kept, with
    their values, those of the validation, which describe them with the
    contigs that they lose, as the log says; a genome whose contigs all leave
    it is no genome any more, and its values go with it. The column mge of
    the genomes table says which genomes are MGE genomes (True): it is not
    there without reassign.

    Returns
    -------
    MgeGenomes, or None
        None without reassign, on a map that holds no MGE genome.

    Raises
    ------
    MetacoolError
        If a genome that the run keeps is named after an MGE cluster of the
        run: their contigs would make one genome."""
    from metacooler.qc import strip_qc_columns

    clusters, members = rounds
    contigs = mc.contigs
    genomes = strip_qc_columns(mc.genomes)
    names = genomes["name"].astype(str).to_numpy()
    held = dict(zip(contigs["name"].astype(str), names[contigs["genome_id"].to_numpy()], strict=True))
    stored = [str(entry.get("name")) for entry in mc.cluster_rounds]
    earlier = set(mge_genomes(mc))
    if mtcl.MGE in stored:
        earlier |= set(mc.cluster_members(mtcl.MGE)["cluster"].astype(str)) & set(names)
    if not earlier and not reassign:
        return None
    final = {}
    if mtcl.FINAL in stored:
        members_final = mc.cluster_members(mtcl.FINAL)
        final = dict(zip(members_final["contig"].astype(str), members_final["cluster"].astype(str), strict=True))
    base = {contig: final.get(contig, UNBINNED_GENOME) if genome in earlier else genome for contig, genome in held.items()}
    moved = {}
    if reassign:
        pairs = zip(members["contig"].astype(str), members["cluster"].astype(str), strict=True)
        moved = {contig: cluster for contig, cluster in pairs if contig in held}
    mges = list(dict.fromkeys(moved.values()))
    clash = sorted({genome for contig, genome in base.items() if contig not in moved} & set(mges))
    if clash:
        raise MetacoolError(
            f"The MGE cluster(s) {_shown(clash)} of the run are named after genome(s) of the map that the run keeps: "
            "their contigs would make one genome. Rename those genomes (metacooler reassign) first."
        )
    assignment = {**base, **moved}
    kept = [genome for genome in dict.fromkeys(assignment.values()) if genome != UNBINNED_GENOME and genome not in mges]
    _log_mge_genomes(held, base, moved, earlier, kept, set(names))
    # The values of the genomes that the run keeps, but those that the MGE
    # genomes of the run get and those that metacooler computes (their
    # length, contigs and bins); none for a genome that gets contigs back
    # after it lost them all.
    columns = [column for column in clusters.columns if column not in CLUSTER_KEY_COLUMNS]
    values = genomes.set_index(pd.Index(names, dtype=object))
    computed = {"name", "length", "n_contigs", "n_bins", MGE_GENOME_COLUMN, *columns}
    table = values.drop(columns=[column for column in values.columns if column in computed]).reindex(
        pd.Index([*kept, *mges], dtype=object)
    )
    if reassign:
        cluster_values = clusters.set_index(pd.Index(clusters["name"].astype(str), dtype=object))
        for column in columns:
            table[column] = cluster_values[column].reindex(table.index)
        table[MGE_GENOME_COLUMN] = ["False"] * len(kept) + ["True"] * len(mges)
    return MgeGenomes({contig: "ND" if genome == UNBINNED_GENOME else genome for contig, genome in assignment.items()}, table)

metator.inputs reads the inputs of metator network and metator pipeline, and makes the map of the contigs that a run starts from out of its pairs files or BAM files (see The inputs of a run).

metator.inputs

The inputs of metator network and metator pipeline.

A run starts from the .metacool contact map of the contigs, or makes it from the pairs files or the BAM files of its Hi-C libraries: one or several of them, each argument a path, a comma-separated list or a glob pattern (see expand), and what each file holds is read from its first bytes (see file_kind). make_map then writes the map of the contigs, one bin per contig of the assembly, all of them in no cluster yet, as metacooler create pairs makes it from the pairs files: the BAM files give their pairs first (see bam_pairs), into the temporary directory of the run.

A BAM file holds both mates of its reads (paired-end alignments, as bwa mem -5SP writes them), or one mate of each (as bowtie2 aligns them, one mate at a time, in two files per library). A pair is the primary alignments of the two mates of a read, both aligned with a mapping quality of at least --min-quality, neither flagged as a PCR or optical duplicate nor as failing QC (see flagged), each at the 5' end of its alignment, as pairtools and hicstuff's mapping mode 5spm record it (see five_prime).

Inputs dataclass

The inputs of a run, as resolve finds them.

Attributes:

Name Type Description
kind str

MAP, PAIRS or BAM.

files list of str

The files, in the order of the arguments: the map alone, for MAP.

libraries list of tuple of str

The files of each Hi-C library: a pairs file, a BAM file of both mates, or the BAM files of its two mates (R1, R2).

layout str or None

For BAM files, BOTH_MATES or ONE_MATE.

Source code in src/metator/inputs.py
@dataclass
class Inputs:
    """The inputs of a run, as resolve finds them.

    Attributes
    ----------
    kind : str
        MAP, PAIRS or BAM.
    files : list of str
        The files, in the order of the arguments: the map alone, for MAP.
    libraries : list of tuple of str
        The files of each Hi-C library: a pairs file, a BAM file of both
        mates, or the BAM files of its two mates (R1, R2).
    layout : str or None
        For BAM files, BOTH_MATES or ONE_MATE.
    """

    kind: str
    files: list = field(default_factory=list)
    libraries: list = field(default_factory=list)
    layout: str | None = None

    @property
    def map(self):
        """The map, for MAP; None otherwise."""
        return self.files[0] if self.kind == MAP else None

    def describe(self):
        """What the inputs are, for the log: "a map", "a pairs file", "3 pairs
        files", "2 BAM files of both mates", "4 BAM files of one mate each"."""
        if self.kind == MAP:
            return "a map"
        what = "pairs file" if self.kind == PAIRS else "BAM file"
        files = f"a {what}" if len(self.files) == 1 else f"{len(self.files)} {what}s"
        if self.kind == BAM:
            files += " of both mates" if self.layout == BOTH_MATES else " of one mate each"
        return files

map property

map

The map, for MAP; None otherwise.

describe

describe()

What the inputs are, for the log: "a map", "a pairs file", "3 pairs files", "2 BAM files of both mates", "4 BAM files of one mate each".

Source code in src/metator/inputs.py
def describe(self):
    """What the inputs are, for the log: "a map", "a pairs file", "3 pairs
    files", "2 BAM files of both mates", "4 BAM files of one mate each"."""
    if self.kind == MAP:
        return "a map"
    what = "pairs file" if self.kind == PAIRS else "BAM file"
    files = f"a {what}" if len(self.files) == 1 else f"{len(self.files)} {what}s"
    if self.kind == BAM:
        files += " of both mates" if self.layout == BOTH_MATES else " of one mate each"
    return files

expand

expand(argument)

The files that an argument of a run names, in order.

A path that exists is that file, whatever its name holds (a comma, a glob character). Otherwise the argument is a comma-separated list, each item a path or a glob pattern (*, ?, [...]), which stands for the files it matches, sorted by name, as hicstuff 4.0 reads its inputs. A pattern that matches no file, and an empty item, are refused.

Parameters:

Name Type Description Default
argument str

A path, comma-separated paths or glob patterns.

required

Returns:

Type Description
list of str

The paths, which may not exist (see resolve).

Raises:

Type Description
MetacoolError

If a pattern matches no file, or the list holds an empty item.

Examples:

>>> expand("L1.pairs.gz,L2.pairs.gz")
['L1.pairs.gz', 'L2.pairs.gz']
Source code in src/metator/inputs.py
def expand(argument):
    """The files that an argument of a run names, in order.

    A path that exists is that file, whatever its name holds (a comma, a glob
    character). Otherwise the argument is a comma-separated list, each item a
    path or a glob pattern (``*``, ``?``, ``[...]``), which stands for the
    files it matches, sorted by name, as hicstuff 4.0 reads its inputs. A
    pattern that matches no file, and an empty item, are refused.

    Parameters
    ----------
    argument : str
        A path, comma-separated paths or glob patterns.

    Returns
    -------
    list of str
        The paths, which may not exist (see resolve).

    Raises
    ------
    metator.metacool.MetacoolError
        If a pattern matches no file, or the list holds an empty item.

    Examples
    --------
    >>> expand("L1.pairs.gz,L2.pairs.gz")
    ['L1.pairs.gz', 'L2.pairs.gz']
    """
    if os.path.exists(argument):
        return [argument]
    files = []
    for item in argument.split(","):
        if not item:
            raise mtmc.MetacoolError(f"The list of inputs {argument!r} holds an empty path.")
        if _GLOB_CHARS.search(item) is None:
            files.append(item)
            continue
        matches = sorted(glob.glob(item))
        if not matches:
            raise mtmc.MetacoolError(f"No file matches the input pattern {item!r}.")
        files.extend(matches)
    return files

file_kind

file_kind(path)

What a file of the inputs of a run holds, from its first bytes, whatever its name: MAP, PAIRS or BAM.

An HDF5 file is a map (open_map refuses one that is not a .metacool map, with metacooler's reason), and so is file::group, a map inside a file, which is no path. A BAM file (compressed with BGZF) and a SAM file (text that starts with its header) are alignments. Any other file is a pairs file, plain or compressed, which metacooler reads. Reads (FASTQ), an assembly (FASTA) and a CRAM file are refused.

Raises:

Type Description
MetacoolError

If the file is not there, is a directory, or holds reads, an assembly or CRAM alignments.

Source code in src/metator/inputs.py
def file_kind(path):
    """What a file of the inputs of a run holds, from its first bytes, whatever its
    name: MAP, PAIRS or BAM.

    An HDF5 file is a map (open_map refuses one that is not a .metacool map,
    with metacooler's reason), and so is file::group, a map inside a file,
    which is no path. A BAM file (compressed with BGZF) and a SAM file (text
    that starts with its header) are alignments. Any other file is a pairs
    file, plain or compressed, which metacooler reads. Reads (FASTQ), an
    assembly (FASTA) and a CRAM file are refused.

    Raises
    ------
    metator.metacool.MetacoolError
        If the file is not there, is a directory, or holds reads, an assembly
        or CRAM alignments.
    """
    path = str(path)
    if mtmc.is_map(path) or ("::" in path and not os.path.exists(path)):
        return MAP
    if not os.path.exists(path):
        raise mtmc.MetacoolError(f"Cannot read the input {path}: no such file.")
    if os.path.isdir(path):
        raise mtmc.MetacoolError(f"Cannot read the input {path}: it is a directory.")
    head = _first_bytes(path)
    if head.startswith(b"BAM\x01") or _SAM_HEADER.match(head):
        return BAM
    if head.startswith(b"CRAM"):
        raise mtmc.MetacoolError(
            f"{path} is a CRAM file, which metaTOR does not read: convert it to BAM (samtools view -b -T ASSEMBLY)."
        )
    if head.startswith(b"@"):
        raise mtmc.MetacoolError(
            f"{path} holds reads (FASTQ): metaTOR aligns no reads. Give the BAM files or the pairs files of the run, or "
            "the map of its contigs, which hicstuff makes from the reads (hicstuff pipeline -M metacool)."
        )
    if head.startswith(b">"):
        raise mtmc.MetacoolError(f"{path} is a FASTA file: give the assembly with -a, and the pairs or BAM files of the run.")
    return PAIRS

resolve

resolve(arguments)

The inputs of a run (see Inputs) from its arguments: one .metacool map, or pairs files, or BAM files (or SAM files), each argument a path, a comma-separated list or a glob pattern (see expand), each file found to be what it is from its first bytes (see file_kind).

Each pairs file, and each BAM file of both mates, is a library. BAM files of one mate each come in two halves, as hicstuff takes them: two arguments are the R1 files and the R2 files; more arguments (as the shell expands unquoted patterns) are as many R1 arguments, then as many R2 arguments. The i-th R1 file and the i-th R2 file are the mates of one library.

Raises:

Type Description
MetacoolError

If an argument names no file, a file is given twice, a map is given with other inputs, kinds or layouts are mixed, or BAM files of one mate each do not come in two halves of as many files.

Source code in src/metator/inputs.py
def resolve(arguments):
    """The inputs of a run (see Inputs) from its arguments: one .metacool map, or
    pairs files, or BAM files (or SAM files), each argument a path, a
    comma-separated list or a glob pattern (see expand), each file found to be
    what it is from its first bytes (see file_kind).

    Each pairs file, and each BAM file of both mates, is a library. BAM files
    of one mate each come in two halves, as hicstuff takes them: two
    arguments are the R1 files and the R2 files; more arguments (as the shell
    expands unquoted patterns) are as many R1 arguments, then as many R2
    arguments. The i-th R1 file and the i-th R2 file are the mates of one
    library.

    Raises
    ------
    metator.metacool.MetacoolError
        If an argument names no file, a file is given twice, a map is given
        with other inputs, kinds or layouts are mixed, or BAM files of one mate
        each do not come in two halves of as many files.
    """
    names = [expand(argument) for argument in arguments]
    files = [path for paths in names for path in paths]
    if not files:
        raise mtmc.MetacoolError("A run needs its inputs: the map of its contigs, or its pairs files or BAM files.")
    kinds = {path: file_kind(path) for path in files}
    seen = {}
    for path in files:
        real = os.path.realpath(mtmc.map_file(path)) if "::" in path else os.path.realpath(path)
        if real in seen:
            raise mtmc.MetacoolError(f"The input {path} is given twice: {seen[real]} is the same file.")
        seen[real] = path
    found = set(kinds.values())
    if MAP in found:
        if len(files) > 1:
            raise mtmc.MetacoolError(
                f"A .metacool map is the one input of a run, given alone, and this run has {len(files)}: {', '.join(files)}."
            )
        return Inputs(MAP, files, [tuple(files)])
    if found == {PAIRS, BAM}:
        bams = [path for path in files if kinds[path] == BAM]
        pairs = [path for path in files if kinds[path] == PAIRS]
        raise mtmc.MetacoolError(
            f"The inputs of a run are pairs files or BAM files, not both: BAM {mtmc._shown(bams)}; pairs {mtmc._shown(pairs)}."
        )
    (kind,) = found
    if kind == PAIRS:
        return Inputs(PAIRS, files, [(path,) for path in files])
    layouts = {path: bam_layout(path) for path in files}
    if len(set(layouts.values())) > 1:
        both = [path for path in files if layouts[path] == BOTH_MATES]
        one = [path for path in files if layouts[path] == ONE_MATE]
        raise mtmc.MetacoolError(
            f"The BAM files of a run hold both mates of each read, or one mate each (an R1 and an R2 file per "
            f"library), not both: both mates in {mtmc._shown(both)}; one mate in {mtmc._shown(one)}."
        )
    if layouts[files[0]] == BOTH_MATES:
        return Inputs(BAM, files, [(path,) for path in files], BOTH_MATES)
    if len(names) < 2 or len(names) % 2:
        raise mtmc.MetacoolError(
            f"One mate of each read in {', '.join(files)}: give the R1 files, then the R2 files, as two arguments (two "
            "comma-separated lists, or two patterns), or as many R1 arguments as R2 arguments."
        )
    half = len(names) // 2
    first = [path for paths in names[:half] for path in paths]
    second = [path for paths in names[half:] for path in paths]
    if len(first) != len(second):
        raise mtmc.MetacoolError(
            f"{len(first)} R1 file(s) and {len(second)} R2 file(s): each BAM file of the first mates needs the BAM file "
            f"of the second mates of its library. R1: {', '.join(first)}; R2: {', '.join(second)}."
        )
    return Inputs(BAM, files, list(zip(first, second, strict=True)), ONE_MATE)

bam_layout

bam_layout(path, threads=1)

BOTH_MATES or ONE_MATE: whether a BAM (or SAM) file holds the two mates of its reads (paired-end alignments), or one mate of each, from its first LAYOUT_PROBE primary alignments: a read flagged first or second of its pair is a mate, an unpaired read one mate aligned on its own.

Raises:

Type Description
MetacoolError

If the file cannot be read, or holds no read.

Source code in src/metator/inputs.py
def bam_layout(path, threads=1):
    """BOTH_MATES or ONE_MATE: whether a BAM (or SAM) file holds the two mates of
    its reads (paired-end alignments), or one mate of each, from its first
    LAYOUT_PROBE primary alignments: a read flagged first or second of its
    pair is a mate, an unpaired read one mate aligned on its own.

    Raises
    ------
    metator.metacool.MetacoolError
        If the file cannot be read, or holds no read.
    """
    mates = set()
    with _alignments(path, threads) as bam:
        try:
            for i, read in enumerate(bam):
                if i == LAYOUT_PROBE:
                    break
                if read.is_secondary or read.is_supplementary:
                    continue
                mates.add(2 if read.is_read2 else 1 if read.is_read1 else 0)
                if {1, 2} <= mates:
                    return BOTH_MATES
        except (OSError, ValueError) as error:
            raise mtmc.MetacoolError(f"Cannot read the BAM file {path}: {error}") from error
    if not mates:
        raise mtmc.MetacoolError(f"{path} holds no read.")
    return ONE_MATE

check_references

check_references(path, references, lengths, what='reference sequences')

Refuse the pairs or the alignments of a file that is not of the assembly: sequences (references: (name, length) pairs) that the assembly gives another length (lengths: by contig name), or none of which is a contig of the assembly. The sequences that are not contigs of the assembly (a spike-in, a host genome) are left out, with a warning: so are the pairs with a read on them.

Parameters:

Name Type Description Default
path str

The BAM or pairs file, for the messages.

required
references list of tuple

Its sequences, as (name, length).

required
lengths dict

The length of each contig of the assembly, by name.

required
what str

What the sequences are, in the messages.

'reference sequences'

Raises:

Type Description
MetacoolError

If a sequence has another length in the assembly, or none is a contig of the assembly.

Source code in src/metator/inputs.py
def check_references(path, references, lengths, what="reference sequences"):
    """Refuse the pairs or the alignments of a file that is not of the assembly:
    sequences (references: (name, length) pairs) that the assembly gives
    another length (lengths: by contig name), or none of which is a contig of
    the assembly. The sequences that are not contigs of the assembly (a
    spike-in, a host genome) are left out, with a warning: so are the pairs
    with a read on them.

    Parameters
    ----------
    path : str
        The BAM or pairs file, for the messages.
    references : list of tuple
        Its sequences, as (name, length).
    lengths : dict
        The length of each contig of the assembly, by name.
    what : str
        What the sequences are, in the messages.

    Raises
    ------
    metator.metacool.MetacoolError
        If a sequence has another length in the assembly, or none is a contig
        of the assembly.
    """
    other = [
        f"{name!r} ({length} bp; {lengths[name]} bp in the assembly)"
        for name, length in references
        if name in lengths and lengths[name] != length
    ]
    if other:
        raise mtmc.MetacoolError(
            f"{path} is not of the contigs of the assembly: {len(other)} of its {what} have another length in the "
            f"assembly: {mtmc._shown(other, show=str)}."
        )
    unknown = [name for name, _ in references if name not in lengths]
    if references and len(unknown) == len(references):
        raise mtmc.MetacoolError(
            f"{path} is not of the contigs of the assembly: none of its {len(references)} {what} is a contig of the "
            f"assembly: {mtmc._shown(unknown)}."
        )
    if unknown:
        logger.warning(
            f"{len(unknown)} of the {what} of {path} are not contigs of the assembly: the pairs with a read on them are "
            f"left out: {mtmc._shown(unknown)}."
        )

five_prime

five_prime(read)

The 1-based position of the 5' end of an alignment (a pysam.AlignedSegment): its first aligned base on the forward strand, its last on the reverse strand, soft-clipped bases left out, as pairtools and hicstuff's mapping mode 5spm record a mate.

It moves the mates on the reverse strand by the length of their alignment from the leftmost base, which metaTOR 1.x recorded: a contact stays between the same two contigs, which the network counts, and only the contacts within a contig at about 1 kb (the short and long contacts that metator mge reads) may change.

Source code in src/metator/inputs.py
def five_prime(read):
    """The 1-based position of the 5' end of an alignment (a
    pysam.AlignedSegment): its first aligned base on the forward strand, its
    last on the reverse strand, soft-clipped bases left out, as pairtools and
    hicstuff's mapping mode 5spm record a mate.

    It moves the mates on the reverse strand by the length of their alignment
    from the leftmost base, which metaTOR 1.x recorded: a contact stays
    between the same two contigs, which the network counts, and only the
    contacts within a contig at about 1 kb (the short and long contacts that
    metator mge reads) may change."""
    return read.reference_end if read.is_reverse else read.reference_start + 1

flagged

flagged(read)

Why a read leaves its pair out for its flags: "duplicate", flagged as a PCR or optical duplicate (0x400, as Picard MarkDuplicates or samtools markdup flag it), or "QC", as failing quality checks (0x200); None for a read that counts.

Source code in src/metator/inputs.py
def flagged(read):
    """Why a read leaves its pair out for its flags: "duplicate", flagged as a
    PCR or optical duplicate (0x400, as Picard MarkDuplicates or samtools
    markdup flag it), or "QC", as failing quality checks (0x200); None for a
    read that counts."""
    if read.is_duplicate:
        return "duplicate"
    if read.is_qcfail:
        return "QC"
    return None

natural_key

natural_key(name)

The sort key of a read name in the order of samtools sort -n: its characters one by one, but its runs of digits found at the same place in two names compared by value (strnum_cmp of samtools: r9 before r10), and their leading zeros ignored (samtools 1.17 and later). Adapted from hicstuff (BSD-3-Clause), which matches the mates of two BAM files so.

Returns:

Type Description
tuple

The text between runs of digits, each ended with "0" when digits follow (samtools compares a digit and another character as characters, and every digit compares alike with a character that is no digit), and the value of each run of digits.

Examples:

>>> sorted(["r10", "r9", "r1"], key=natural_key)
['r1', 'r9', 'r10']
>>> natural_key("r010") == natural_key("r10")
True
Source code in src/metator/inputs.py
def natural_key(name):
    """The sort key of a read name in the order of ``samtools sort -n``: its
    characters one by one, but its runs of digits found at the same place in
    two names compared by value (strnum_cmp of samtools: r9 before r10), and
    their leading zeros ignored (samtools 1.17 and later). Adapted from
    hicstuff (BSD-3-Clause), which matches the mates of two BAM files so.

    Returns
    -------
    tuple
        The text between runs of digits, each ended with "0" when digits follow
        (samtools compares a digit and another character as characters, and
        every digit compares alike with a character that is no digit), and the
        value of each run of digits.

    Examples
    --------
    >>> sorted(["r10", "r9", "r1"], key=natural_key)
    ['r1', 'r9', 'r10']
    >>> natural_key("r010") == natural_key("r10")
    True
    """
    parts = _DIGIT_RUNS.split(name)
    key = []
    for i in range(1, len(parts), 2):
        key.append(parts[i - 1] + "0")
        key.append(int(parts[i]))
    key.append(parts[-1])
    return tuple(key)

bam_pairs

bam_pairs(
    library, out, lengths, layout, min_quality=30, tmp_dir=".", threads=1
)

Write the pairs file of a library of BAM files: the pairs of the reads whose two mates are aligned, each with a mapping quality of at least min_quality, on contigs of the assembly (their primary alignments; the secondary and supplementary ones are left out), each mate at the 5' end of its alignment (see five_prime). A read with a mate flagged as a PCR or optical duplicate, or as failing QC, is left out (see flagged), and the log counts them.

Parameters:

Name Type Description Default
library tuple of str

The BAM file of both mates, or the BAM files of the two mates.

required
out str

The pairs file to write.

required
lengths dict

The length of each contig of the assembly, by name, in its order.

required
layout str

BOTH_MATES or ONE_MATE.

required
min_quality int

The mapping quality that both mates of a pair must reach.

30
tmp_dir str

Where the files are grouped or sorted by read name, when they need it.

'.'
threads int

Threads decompressing the BAM files, and grouping or sorting them.

1

Returns:

Type Description
int

The number of pairs written.

Raises:

Type Description
MetacoolError

If a file cannot be read, holds no read with both mates (BAM files of the mates of other libraries), or the mates cannot be matched.

Source code in src/metator/inputs.py
def bam_pairs(library, out, lengths, layout, min_quality=30, tmp_dir=".", threads=1):
    """Write the pairs file of a library of BAM files: the pairs of the reads
    whose two mates are aligned, each with a mapping quality of at least
    min_quality, on contigs of the assembly (their primary alignments; the
    secondary and supplementary ones are left out), each mate at the 5' end of
    its alignment (see five_prime). A read with a mate flagged as a PCR or
    optical duplicate, or as failing QC, is left out (see flagged), and the
    log counts them.

    Parameters
    ----------
    library : tuple of str
        The BAM file of both mates, or the BAM files of the two mates.
    out : str
        The pairs file to write.
    lengths : dict
        The length of each contig of the assembly, by name, in its order.
    layout : str
        BOTH_MATES or ONE_MATE.
    min_quality : int
        The mapping quality that both mates of a pair must reach.
    tmp_dir : str
        Where the files are grouped or sorted by read name, when they need it.
    threads : int
        Threads decompressing the BAM files, and grouping or sorting them.

    Returns
    -------
    int
        The number of pairs written.

    Raises
    ------
    metator.metacool.MetacoolError
        If a file cannot be read, holds no read with both mates (BAM files of
        the mates of other libraries), or the mates cannot be matched.
    """
    if layout == BOTH_MATES:
        (path,) = library
        counts, other = _both_mates_pairs(path, out, lengths, min_quality, tmp_dir, threads)
        with_both, what = counts["reads"] - counts["lone"], path
        if counts["lone"]:
            logger.info(f"{counts['lone']} of the {counts['reads']} reads of {path} have one mate in it: no pair.")
    else:
        path1, path2 = library
        counts, other = _one_mate_pairs(path1, path2, out, lengths, min_quality, tmp_dir, threads)
        with_both, what = counts["matched"], f"{path1} and {path2}"
        alone = counts["reads1"] + counts["reads2"] - 2 * counts["matched"]
        if alone:
            logger.info(f"{alone} reads have one mate only in {what} (an unaligned mate that the aligner left out): no pair.")
    if not with_both:
        mates = "the two mates of a read" if layout == BOTH_MATES else "the R1 and R2 files of one library"
        raise mtmc.MetacoolError(f"{what} hold no read with both mates: they are not {mates}.")
    if other:
        logger.info(f"{other} pairs of {what} have a read on a sequence that is not a contig of the assembly: left out.")
    if counts["duplicate"] or counts["QC"]:
        logger.info(
            f"{counts['duplicate']} reads of {what} with a mate flagged as a PCR or optical duplicate, and {counts['QC']} "
            "with a mate flagged as failing QC: left out."
        )
    share = 100 * counts["pairs"] / with_both
    logger.info(
        f"{what}: {counts['pairs']} pairs of {with_both} reads with both mates ({share:.2f}%), both aligned with a "
        f"mapping quality of at least {min_quality} on contigs of the assembly."
    )
    return counts["pairs"]

pairs_chromsizes

pairs_chromsizes(path)

The sequences that the header of a pairs file lists (#chromsize lines), as (name, length) pairs: none for a file without them, or compressed with zstd or LZ4, whose header is not read here (metacooler reads the file).

Source code in src/metator/inputs.py
def pairs_chromsizes(path):
    """The sequences that the header of a pairs file lists (#chromsize lines), as
    (name, length) pairs: none for a file without them, or compressed with
    zstd or LZ4, whose header is not read here (metacooler reads the file)."""
    with open(path, "rb") as handle:
        head = handle.read(4)
    if head.startswith(_UNREAD_COMPRESSIONS):
        return []
    sizes = []
    if mio.file_compression(path) == "zip":
        return sizes
    try:
        with mio.read_compressed(path) as handle:
            for line in handle:
                if not line.startswith("#"):
                    break
                if line.startswith("#chromsize:"):
                    fields = line[len("#chromsize:") :].split()
                    if len(fields) == 2 and fields[1].isdigit():
                        sizes.append((fields[0], int(fields[1])))
    except (UnicodeDecodeError, OSError, EOFError):
        # No text: metacooler says what it is not.
        return []
    return sizes

map_name

map_name(prefix, assembly)

The name of the map that a run makes from pairs or BAM files: .metacool, or .metacool without a prefix, the name of the FASTA file of the assembly without its extensions (.gz, .fa, .fasta, .fna...).

Source code in src/metator/inputs.py
def map_name(prefix, assembly):
    """The name of the map that a run makes from pairs or BAM files:
    <prefix>.metacool, or <assembly>.metacool without a prefix, the name of the
    FASTA file of the assembly without its extensions (.gz, .fa, .fasta,
    .fna...)."""
    return f"{prefix or assembly_name(assembly)}.metacool"

assembly_name

assembly_name(assembly)

The name of an assembly: that of its FASTA file, without the extensions of a FASTA file and of its compression (assembly from assembly.fa.gz).

Source code in src/metator/inputs.py
def assembly_name(assembly):
    """The name of an assembly: that of its FASTA file, without the extensions of
    a FASTA file and of its compression (assembly from assembly.fa.gz)."""
    name = os.path.basename(str(assembly))
    for extension in (".gz", ".bz2", ".zip"):
        if name.endswith(extension) and len(name) > len(extension):
            name = name[: -len(extension)]
            break
    for extension in _FASTA_EXTENSIONS:
        if name.lower().endswith(extension) and len(name) > len(extension):
            return name[: -len(extension)]
    return name

make_map

make_map(
    inputs,
    contig_data,
    outfile,
    assembly=None,
    min_quality=30,
    threads=1,
    tmp_dir=".",
    command=None,
)

Write the map of the contigs at outfile, from the pairs files or the BAM files of a run (inputs, see resolve), as metacooler create pairs makes it: one bin per contig of the assembly (contig_data, by name, in its order: see metator.network.create_contig_data), every contig in __unbinned__, the longest first, and the contacts of the pairs of every library, summed, with the contact statistics that metacooler counts on the reads (the QC block, which metator mge reads).

The BAM files give the pairs of each library (see bam_pairs), written in tmp_dir. The headers of the BAM files, and the #chromsize lines of the pairs files, are checked against the assembly first (see check_references).

Parameters:

Name Type Description Default
inputs Inputs

Pairs files or BAM files.

required
contig_data dict

The contigs of the assembly, by name, with their "length".

required
outfile str

The map to write. An earlier one there is replaced once the new map is written.

required
assembly str

The FASTA file of the assembly, whose name the map stores (see assembly_name).

None
min_quality int

The mapping quality that both mates of a pair of a BAM file must reach.

30
threads int

Threads reading the BAM files and binning the pairs.

1
tmp_dir str

Where the pairs of the BAM files are written.

'.'
command str

The command line, stored in the history of the map.

None

Raises:

Type Description
MetacoolError

If an input is not of the assembly, cannot be read, or no pair of the inputs is on the contigs of the assembly. outfile is then left as it was: the map is written next to it, as a hidden file, and renamed onto it once it holds contacts.

Source code in src/metator/inputs.py
def make_map(inputs, contig_data, outfile, assembly=None, min_quality=30, threads=1, tmp_dir=".", command=None):
    """Write the map of the contigs at outfile, from the pairs files or the BAM
    files of a run (inputs, see resolve), as ``metacooler create pairs`` makes
    it: one bin per contig of the assembly (contig_data, by name, in its
    order: see metator.network.create_contig_data), every contig in
    ``__unbinned__``, the longest first, and the contacts of the pairs of
    every library, summed, with the contact statistics that metacooler counts
    on the reads (the QC block, which metator mge reads).

    The BAM files give the pairs of each library (see bam_pairs), written in
    tmp_dir. The headers of the BAM files, and the #chromsize lines of the
    pairs files, are checked against the assembly first (see
    check_references).

    Parameters
    ----------
    inputs : Inputs
        Pairs files or BAM files.
    contig_data : dict
        The contigs of the assembly, by name, with their "length".
    outfile : str
        The map to write. An earlier one there is replaced once the new map is
        written.
    assembly : str, optional
        The FASTA file of the assembly, whose name the map stores (see
        assembly_name).
    min_quality : int
        The mapping quality that both mates of a pair of a BAM file must reach.
    threads : int
        Threads reading the BAM files and binning the pairs.
    tmp_dir : str
        Where the pairs of the BAM files are written.
    command : str, optional
        The command line, stored in the history of the map.

    Raises
    ------
    metator.metacool.MetacoolError
        If an input is not of the assembly, cannot be read, or no pair of the
        inputs is on the contigs of the assembly. outfile is then left as it
        was: the map is written next to it, as a hidden file, and renamed onto
        it once it holds contacts.
    """
    import metacooler

    lengths = {name: data["length"] for name, data in contig_data.items() if data["length"] > 0}
    mtmc.check_ascii_names(list(lengths), [])
    if inputs.kind == PAIRS:
        for path in inputs.files:
            check_references(path, pairs_chromsizes(path), lengths, "sequences (#chromsize)")
        pairs = list(inputs.files)
    else:
        for path in inputs.files:
            references = _references(path)
            if not references:
                raise mtmc.MetacoolError(f"{path} lists no reference sequence in its header: its reads are not aligned.")
            check_references(path, references, lengths)
        pairs = []
        for i, library in enumerate(inputs.libraries):
            pairs.append(os.path.join(tmp_dir, f"library_{i + 1}.pairs"))
            bam_pairs(library, pairs[-1], lengths, inputs.layout, min_quality, tmp_dir, threads)
    logger.info(f"Writing {outfile}: the contact map of the {len(lengths)} contigs of the assembly, in no cluster yet.")
    # Written next to outfile, under a hidden name, and renamed onto it once it
    # holds contacts: an earlier map there is left as it was until then.
    directory, name = os.path.split(os.path.abspath(outfile))
    staged = os.path.join(directory, f".{name}.{os.getpid()}.{os.urandom(4).hex()}.tmp")
    try:
        with mtmc._metacooler_logging(), mtmc._as_metacool_errors():
            metacooler.from_pairs(
                staged,
                bins=pd.DataFrame({"chrom": list(lengths), "start": 0, "end": list(lengths.values())}),
                pairs=pairs,
                # No clustering yet: every contig in __unbinned__, the longest
                # first.
                contig_genome_map=None,
                assembly_name=assembly_name(assembly) if assembly else None,
                metadata={"commands": [command]} if command else None,
                # The QC block, counted on the reads, which only the pairs give.
                qc=True,
                # No P(s) table next to the map: a run writes the map only.
                ps=False,
                nproc=threads,
                keep_partial=False,
            )
            contacts = mtmc.open_map(staged).info.get("nnz", 0)
        if not contacts:
            raise mtmc.MetacoolError(
                f"No pair from {inputs.describe()} is on the contigs of the assembly: give the pairs or the alignments "
                "of the reads of this assembly."
            )
        os.replace(staged, outfile)
    finally:
        if os.path.lexists(staged):
            os.remove(staged)
    logger.info(f"{outfile} is written: the contact map of the contigs, from {inputs.describe()}.")

metator.dump writes the tables of a run from the map of its clusters, as metator dump does (see dump).

metator.dump

The tables of a run, written from the map of its clusters: metator dump.

A run keeps everything it finds in its map and writes its tables in its temporary directory only. metator dump MAP -o DIR writes them from the map, read only: contig_data_final.txt (in the map's order, without the ID column, whose values were positions in the map the run read), cluster_summary.txt (rows, columns and formats as the validation recorded them), binning.txt, clusters.txt (with the number of contigs and the length of each cluster, which the map computes), cluster_members.txt and network.txt.

The map must be the map of the clusters as its run wrote it (see check_dumpable); every table is read through one opened map, and they are renamed into place all at once.

check_dumpable

check_dumpable(metacool, mc)

Refuse a map that holds no run to dump: no validation entry in its metator metadata, or no clustering round final.

The genomes of the map need not be the final clusters of its run: the tables follow the genomes (those that metator mge --reassign makes of its MGE clusters, or a curation by hand with metacooler reassign), each with the values that the genomes table gives it.

Returns:

Type Description
dict

The validation entry of the metator metadata of the map.

Raises:

Type Description
MetacoolError

If the map lacks either.

Source code in src/metator/dump.py
def check_dumpable(metacool, mc):
    """Refuse a map that holds no run to dump: no validation entry in its metator
    metadata, or no clustering round final.

    The genomes of the map need not be the final clusters of its run: the
    tables follow the genomes (those that metator mge --reassign makes of its
    MGE clusters, or a curation by hand with metacooler reassign), each with
    the values that the genomes table gives it.

    Returns
    -------
    dict
        The validation entry of the metator metadata of the map.

    Raises
    ------
    metator.metacool.MetacoolError
        If the map lacks either."""
    missing = []
    metator = mc.metadata.get("metator")
    validation = metator.get("validation") if isinstance(metator, dict) else None
    if not isinstance(validation, dict):
        missing.append("the validation entry of its metator metadata")
    if mtcl.FINAL not in [entry.get("name") for entry in mc.cluster_rounds]:
        missing.append(f"the clustering round {mtcl.FINAL}")
    if missing:
        raise mtmc.MetacoolError(
            f"{metacool} holds no clusters of a validation: it lacks {' and '.join(missing)}. Run metator "
            "validation (or metator pipeline) on it first, which writes the map of the clusters."
        )
    return validation

contig_data_final

contig_data_final(metacool, mc, table)

The contig data of the final clusters of a run (contig_data_final.txt), from its map: one row per contig of the map, in its order.

Parameters:

Name Type Description Default
metacool str

The map, for the messages.

required
mc MetaCooler

The map, opened.

required
table DataFrame

The contig data of the contigs of the map (see metator.network.map_contig_table).

required

Returns:

Type Description
DataFrame

The table, without its ID column.

Source code in src/metator/dump.py
def contig_data_final(metacool, mc, table):
    """The contig data of the final clusters of a run (contig_data_final.txt),
    from its map: one row per contig of the map, in its order.

    Parameters
    ----------
    metacool : str
        The map, for the messages.
    mc : metacooler.MetaCooler
        The map, opened.
    table : pandas.DataFrame
        The contig data of the contigs of the map (see
        metator.network.map_contig_table).

    Returns
    -------
    pandas.DataFrame
        The table, without its ID column."""
    data = mtp.partition_table(table, mtmc.read_partition(metacool, mc))
    # As the validation reads contig_data_partition.txt (see
    # metator.validation.recursive_decontamination): the IDs of the core
    # clusters are numbers there, but next to the - of a contig in none.
    if (data["Core_cluster_ID"] != "-").all():
        data["Core_cluster_ID"] = data["Core_cluster_ID"].astype(np.int64)
    data["Recursive_cluster_ID"] = f"{0:05d}"
    for column in RECURSIVE_COLUMNS[1:]:
        data[column] = pd.Series("-", index=data.index, dtype=object)
    rows = pd.Index(data["Name"])
    sizes = data["Size"].to_numpy()
    # The rounds recursive_<k> in the order they were made: a contig ends in
    # the cluster of the last step that split its cluster.
    for name in [entry["name"] for entry in mc.cluster_rounds]:
        if not _is_recursive_round(name):
            continue
        members = mc.cluster_members(name)
        for cluster, contigs in members.groupby("cluster", sort=False)["contig"]:
            positions = rows.get_indexer(contigs.astype(str))
            positions = positions[positions >= 0]
            data.loc[positions, "Recursive_cluster_ID"] = str(cluster).rsplit("_", 1)[-1]
            data.loc[positions, "Recursive_cluster_contigs"] = len(positions)
            data.loc[positions, "Recursive_cluster_size"] = int(sizes[positions].sum())
    data["Final_cluster"] = final_clusters(mc)
    return data.drop(columns=["ID"])

final_clusters

final_clusters(mc)

The final cluster of each contig of the map, in its order: the name of its genome, ND for metacooler's unbinned (a contig in no final cluster).

Source code in src/metator/dump.py
def final_clusters(mc):
    """The final cluster of each contig of the map, in its order: the name of its
    genome, ND for metacooler's __unbinned__ (a contig in no final cluster)."""
    names = mc.genomes["name"].astype(str).to_numpy()
    final = names[mc.contigs["genome_id"].to_numpy()]
    return np.where(final == UNBINNED_GENOME, "ND", final)

binning

binning(data)

Each contig of a final cluster, and its cluster (binning.txt, the table that anvi'o imports), from the contig data of the final clusters (see contig_data_final), in its order.

Source code in src/metator/dump.py
def binning(data):
    """Each contig of a final cluster, and its cluster (binning.txt, the table
    that anvi'o imports), from the contig data of the final clusters (see
    contig_data_final), in its order."""
    binned = data[data["Final_cluster"] != "ND"]
    return binned[["Name", "Final_cluster"]]

summary_layout

summary_layout(metacool, validation)

How the run wrote the summary of its final clusters (cluster_summary.txt), as the validation entry of its map records it (validation, see metator.cli.validation_entry): its rows, its columns and their formats, with which the values in the genomes table of the map write it again (see cluster_summary).

Returns:

Type Description
SummaryLayout

The rows, the columns and the format of each column.

Raises:

Type Description
MetacoolError

If the entry lacks one of them, as that of a map that a development build of metaTOR 2.0 validated does, or does not record them as metator validation records them: each time, run metator validation on the map again.

Source code in src/metator/dump.py
def summary_layout(metacool, validation):
    """How the run wrote the summary of its final clusters (cluster_summary.txt),
    as the validation entry of its map records it (validation, see
    metator.cli.validation_entry): its rows, its columns and their formats,
    with which the values in the genomes table of the map write it again (see
    cluster_summary).

    Returns
    -------
    metator.io.SummaryLayout
        The rows, the columns and the format of each column.

    Raises
    ------
    metator.metacool.MetacoolError
        If the entry lacks one of them, as that of a map that a development
        build of metaTOR 2.0 validated does, or does not record them as metator
        validation records them: each time, run metator validation on the map
        again."""
    missing = [key for key in SUMMARY_KEYS if key not in validation]
    if missing:
        raise mtmc.MetacoolError(
            f"The validation entry of the metator metadata of {metacool} lacks {', '.join(missing)}, which record how "
            "the summary of its clusters (cluster_summary.txt) is written: a development build of metaTOR 2.0 "
            "validated the map. Run metator validation on the map again."
        )
    rows, columns, formats = (validation[key] for key in SUMMARY_KEYS)
    malformed = []
    if not _texts(rows):
        malformed.append("summary_rows, which must be the names of the clusters")
    if not _texts(columns):
        malformed.append("summary_columns, which must be the names of the columns")
    elif not isinstance(formats, dict) or any(formats.get(column) not in SUMMARY_FORMATS for column in columns):
        malformed.append(f"summary_formats, which must give each column one of the formats {', '.join(SUMMARY_FORMATS)}")
    if malformed:
        raise mtmc.MetacoolError(
            f"The validation entry of the metator metadata of {metacool} does not record the summary of its clusters "
            f"as metator validation records it: {'; '.join(malformed)}. Run metator validation on the map again."
        )
    return mio.SummaryLayout(rows, columns, {column: formats[column] for column in columns})

cluster_summary

cluster_summary(metacool, mc, layout)

The summary of the genomes of the map of a run (cluster_summary.txt), from its genomes table, as the validation wrote the summary of its final clusters (layout, see summary_layout): a line per genome, the final clusters of the summary that are genomes of the map, in its order, then its other genomes, in the order of the genomes table (the MGE genomes that metator mge --reassign makes, or genomes of a curation by hand); its name then the value of each column in the genomes table, written with the format of the column (an empty field for a missing value: NaN, None or an empty text), after a header, an empty field then the columns. The columns are those of the summary, then, when the genomes table says which genomes are MGE genomes, those of MGE_SUMMARY_FORMATS that it holds, then those of HOST_SUMMARY_FORMATS that it holds: the hosts of the MGE clusters that metator host stored there.

Returns:

Type Description
DataFrame

The fields of the summary, as text, indexed by the names of the genomes (an index without a name, which gives the header its empty field).

Raises:

Type Description
MetacoolError

If the genomes table lacks a column of the summary, or holds a value that the format of its column does not write (an edit of the map changed them since the run).

Source code in src/metator/dump.py
def cluster_summary(metacool, mc, layout):
    """The summary of the genomes of the map of a run (cluster_summary.txt), from
    its genomes table, as the validation wrote the summary of its final
    clusters (layout, see summary_layout): a line per genome, the final
    clusters of the summary that are genomes of the map, in its order, then
    its other genomes, in the order of the genomes table (the MGE genomes that
    metator mge --reassign makes, or genomes of a curation by hand); its name
    then the value of each column in the genomes table, written with the
    format of the column (an empty field for a missing value: NaN, None or an
    empty text), after a header, an empty field then the columns. The columns
    are those of the summary, then, when the genomes table says which genomes
    are MGE genomes, those of MGE_SUMMARY_FORMATS that it holds, then those of
    HOST_SUMMARY_FORMATS that it holds: the hosts of the MGE clusters that
    metator host stored there.

    Returns
    -------
    pandas.DataFrame
        The fields of the summary, as text, indexed by the names of the
        genomes (an index without a name, which gives the header its empty
        field).

    Raises
    ------
    metator.metacool.MetacoolError
        If the genomes table lacks a column of the summary, or holds a value
        that the format of its column does not write (an edit of the map
        changed them since the run)."""
    genomes = mc.genomes.set_index(mc.genomes["name"].astype(str))
    missing = [column for column in layout.columns if column not in genomes.columns]
    if missing:
        raise mtmc.MetacoolError(
            f"The genomes table of {metacool} lacks the column(s) {mtmc._shown(missing)} of the summary of its "
            "clusters, which metator validation stored there (an edit of the map dropped them since): run metator "
            "validation on the map again."
        )
    formats = {column: layout.formats[column] for column in layout.columns}
    if mtmc.MGE_GENOME_COLUMN in genomes.columns:
        for column, written in MGE_SUMMARY_FORMATS.items():
            if column in genomes.columns and column not in formats:
                formats[column] = written
    for column, written in HOST_SUMMARY_FORMATS.items():
        if column in genomes.columns and column not in formats:
            formats[column] = written
    listed = set(layout.rows)
    rows = [row for row in layout.rows if row in genomes.index]
    rows += [name for name in genomes.index if name != UNBINNED_GENOME and name not in listed]
    values = genomes.loc[rows, list(formats)]
    fields = {}
    for column, written in formats.items():
        try:
            fields[column] = ["" if _missing(value) else written % value for value in values[column]]
        except (TypeError, ValueError) as error:
            raise mtmc.MetacoolError(
                f"The column {column} of the genomes table of {metacool} holds a value that metator did not write "
                f"there ({written}: {error}): an edit of the map changed it since. Run metator validation on the map "
                "again."
            ) from error
    return pd.DataFrame(fields, index=pd.Index(rows, dtype=object), columns=list(formats), dtype=object)

check_network

check_network(metacool, mc, stored)

Refuse a map whose network is not the one that its clusters were made from: metator partition records the digest of the network that it partitioned (see metator.metacool.partition_network), which that of the network stored in the map (stored, see metator.network.stored_network) must be. metator network, run on the map after the run that wrote its clusters (with another normalization, or on the contacts of another library), stores another network there and keeps the clusters: the network and the clusters of the tables would not go together.

Raises:

Type Description
MetacoolError

With the remedies: metator network with the normalization of the run, which stores its network again on the contacts that it read, or metator partition and validation, which cluster the network stored now.

Source code in src/metator/dump.py
def check_network(metacool, mc, stored):
    """Refuse a map whose network is not the one that its clusters were made from:
    metator partition records the digest of the network that it partitioned
    (see metator.metacool.partition_network), which that of the network stored
    in the map (stored, see metator.network.stored_network) must be. metator
    network, run on the map after the run that wrote its clusters (with another
    normalization, or on the contacts of another library), stores another
    network there and keeps the clusters: the network and the clusters of the
    tables would not go together.

    Raises
    ------
    metator.metacool.MetacoolError
        With the remedies: metator network with the normalization of the run,
        which stores its network again on the contacts that it read, or metator
        partition and validation, which cluster the network stored now."""
    made_on = mtmc.partition_network(mc)
    if made_on == stored.digest:
        return
    if made_on is None:
        raise mtmc.MetacoolError(
            f"{metacool} does not record the network that its clusters were made from (the "
            f"{mtmc.NETWORK_DIGEST} of the partition entry of its metator metadata, which metator partition "
            "records): run metator partition, then metator validation, on the map again (or metator pipeline)."
        )
    partition = mtmc._metator_metadata(mc).get("partition")
    normalization = partition.get("normalization") if isinstance(partition, dict) else None
    run = f" (normalization {normalization})" if isinstance(normalization, str) else ""
    option = f" -n {normalization}" if isinstance(normalization, str) else ""
    raise mtmc.MetacoolError(
        f"The network stored in {metacool} is not the one that its clusters were made from: metator network stored "
        f"another network in the map (normalization {stored.normalization}) after the run that wrote them "
        f"partitioned its own{run}, and kept them. Its tables would give the network of the one and the clusters of "
        f"the other. Run metator network{option} on the map, which stores the network of the run again if its "
        "contacts are those that the run read, or metator partition, then metator validation, on the map again "
        "(or metator pipeline), which cluster the network stored now."
    )

network_table

network_table(table, network)

The network of the contigs of a map (network.txt): one row per edge, the names of its two contigs and its weight, without the contacts within a contig, in the order of the map: from the first contig of the map to the last, each with the contigs after it (see metator.network.map_network). The weight is the count of the contacts of the two contigs times the weight of each, for the normalization that metator network stored, or the count for None.

Parameters:

Name Type Description Default
table DataFrame

The contig data of the contigs of the map, in its order.

required
network DataFrame

The network of the map, by the positions of its contigs (see metator.network.map_network).

required
Source code in src/metator/dump.py
def network_table(table, network):
    """The network of the contigs of a map (network.txt): one row per edge, the
    names of its two contigs and its weight, without the contacts within a
    contig, in the order of the map: from the first contig of the map to the
    last, each with the contigs after it (see metator.network.map_network). The
    weight is the count of the contacts of the two contigs times the weight of
    each, for the normalization that metator network stored, or the count for
    None.

    Parameters
    ----------
    table : pandas.DataFrame
        The contig data of the contigs of the map, in its order.
    network : pandas.DataFrame
        The network of the map, by the positions of its contigs (see
        metator.network.map_network)."""
    names = table["Name"].astype(str).to_numpy()
    return pd.DataFrame(
        {
            "contig1": names[network["contig1"].to_numpy() - 1],
            "contig2": names[network["contig2"].to_numpy() - 1],
            "weight": network["weight"].to_numpy(),
        }
    )

existing_tables

existing_tables(outdir)

The tables of metator dump that outdir holds already (see TABLES), by name.

Source code in src/metator/dump.py
def existing_tables(outdir):
    """The tables of metator dump that outdir holds already (see TABLES), by name."""
    return [name for name in TABLES if os.path.lexists(join(outdir, name))]

read_run

read_run(metacool, remedy=DUMP_AGAIN)

The map of the clusters of a run, opened once, as metator dump and metator export read it, once refused what they refuse: a map without the clusters of a validation, or whose clusters were edited since (see check_dumpable), without the summary that metaTOR 2.0 records (see summary_layout), or whose network is not the one that its clusters were made from (see check_network). A read that spans a replacement of the map raises a MapReplacedError, whose message ends with remedy.

Returns:

Type Description
tuple

The map, opened (a metacooler.MetaCooler); the layout of the summary of its final clusters (see summary_layout); and its network, read through it (see metator.network.stored_network): the contig data of its contigs, and the network weighed with the stored normalization (whose Hit column must be that of its contacts), which must be the one that the clusters were made from.

Source code in src/metator/dump.py
def read_run(metacool, remedy=DUMP_AGAIN):
    """The map of the clusters of a run, opened once, as metator dump and metator
    export read it, once refused what they refuse: a map without the clusters
    of a validation, or whose clusters were edited since (see check_dumpable),
    without the summary that metaTOR 2.0 records (see summary_layout), or
    whose network is not the one that its clusters were made from (see
    check_network). A read that spans a replacement of the map raises a
    MapReplacedError, whose message ends with remedy.

    Returns
    -------
    tuple
        The map, opened (a metacooler.MetaCooler); the layout of the summary
        of its final clusters (see summary_layout); and its network, read
        through it (see metator.network.stored_network): the contig data of
        its contigs, and the network weighed with the stored normalization
        (whose Hit column must be that of its contacts), which must be the one
        that the clusters were made from."""
    with mtmc._metacooler_logging(), mtmc.read_errors(metacool, remedy):
        mc = mtmc.open_map(metacool)
        layout = summary_layout(metacool, check_dumpable(metacool, mc))
    try:
        stored = mtn.stored_network(metacool, mc)
    except mtmc.MapReplacedError as error:
        # A replacement found by a read of stored_network, which names another
        # remedy.
        raise mtmc.MapReplacedError(
            f"{metacool} was replaced or written while it was read, by a run that updated it: what was read of it "
            f"would mix two maps. {remedy}"
        ) from error
    with mtmc._metacooler_logging(), mtmc.read_errors(metacool, remedy):
        check_network(metacool, mc, stored)
    return mc, layout, stored

dump

dump(metacool, outdir, force=False)

Write the tables of the run that wrote the map metacool (see the module's docstring) in outdir, made if it is not there. The map is read only: every table comes from one state of the map, read through one opened map, which is refused if it was replaced or written while it was read.

The tables are written under temporary names, then renamed: an earlier dump's tables are replaced all at once, or not at all.

Parameters:

Name Type Description Default
metacool str

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

required
outdir str

The directory of the tables.

required
force bool

Whether to replace the tables that outdir holds already.

False

Returns:

Type Description
list of str

The paths of the tables, in the order of TABLES.

Raises:

Type Description
MetacoolError

If outdir holds one of the tables already (without force), or a directory in the place of one, the map cannot be read, holds no clusters of a validation or clusters edited since (see check_dumpable), no summary of them that metaTOR 2.0 records (see summary_layout), no network, partition or summary that metaTOR stored, or a network other than the one its clusters were made from (see check_network), or was replaced while it was read, or a table cannot be written.

Source code in src/metator/dump.py
def dump(metacool, outdir, force=False):
    """Write the tables of the run that wrote the map metacool (see the module's
    docstring) in outdir, made if it is not there. The map is read only: every
    table comes from one state of the map, read through one opened map, which
    is refused if it was replaced or written while it was read.

    The tables are written under temporary names, then renamed: an earlier
    dump's tables are replaced all at once, or not at all.

    Parameters
    ----------
    metacool : str
        Path to the .metacool file of the clusters of a run, or URI of an entry
        of a .mmetacool collection: ``file.mmetacool::entries/<name>``.
    outdir : str
        The directory of the tables.
    force : bool
        Whether to replace the tables that outdir holds already.

    Returns
    -------
    list of str
        The paths of the tables, in the order of TABLES.

    Raises
    ------
    metator.metacool.MetacoolError
        If outdir holds one of the tables already (without force), or a
        directory in the place of one, the map cannot be read, holds no
        clusters of a validation or clusters edited since (see check_dumpable),
        no summary of them that metaTOR 2.0 records (see summary_layout), no
        network, partition or summary that metaTOR stored, or a network other
        than the one its clusters were made from (see check_network), or was
        replaced while it was read, or a table cannot be written."""
    blocked = [name for name in TABLES if os.path.isdir(join(outdir, name)) and not os.path.islink(join(outdir, name))]
    if blocked:
        raise mtmc.MetacoolError(
            f"{outdir} holds a directory where metator dump writes {', '.join(blocked)}: remove it, or give another "
            "output directory."
        )
    existing = existing_tables(outdir)
    if existing and not force:
        raise mtmc.MetacoolError(
            f"{outdir} holds the table(s) of an earlier dump: {', '.join(existing)}. Give -F to replace them, or "
            "another output directory."
        )
    try:
        mc, layout, stored = read_run(metacool)
        with mtmc._metacooler_logging(), mtmc.read_errors(metacool, DUMP_AGAIN):
            data = contig_data_final(metacool, mc, stored.table)
            summary = cluster_summary(metacool, mc, layout)
            clusters, members = mtmc.map_rounds(mc)
            # Each cluster with its number of contigs and their length, which
            # the map computes, as the run wrote them in its clusters.txt: the
            # MGE clusters too, which mges_bin_summary.tsv gave as
            # ContigsNumber and BinLength.
            contigs = mc.contigs
            lengths = pd.Series(contigs["length"].to_numpy(), index=contigs["name"].astype(str).to_numpy())
            clusters = mtcl.with_sizes(clusters, members, lengths)
    except mtmc.MapReplacedError as error:
        raise mtmc.MapReplacedError(
            f"{metacool} was replaced or written while metator dump read it, by a run that updated it: what was "
            f"read of it would mix two maps. {DUMP_AGAIN}"
        ) from error
    try:
        os.makedirs(outdir, exist_ok=True)
    except OSError as error:
        raise mtmc.MetacoolError(f"The output directory {outdir} cannot be made: {error}.") from error
    writers = {
        CONTIG_DATA_FILE: lambda path: data.to_csv(path, sep="\t", index=False),
        SUMMARY_FILE: lambda path: summary.to_csv(path, sep="\t"),
        BINNING_FILE: lambda path: binning(data).to_csv(path, sep="\t", header=False, index=False),
        NETWORK_FILE: lambda path: network_table(stored.table, stored.network).to_csv(path, sep="\t", header=False, index=False),
    }
    _write_all(metacool, outdir, writers, (clusters, members))
    logger.info(
        f"The tables of {metacool} are written in {outdir}: {len(data)} contigs, {len(summary)} genomes, "
        f"{clusters['round'].nunique()} clustering rounds and {len(stored.network)} edges of the network."
    )
    return [join(outdir, name) for name in TABLES]