Skip to content

Input and output

metator.io reads and writes the files of a run: the contig data and cluster summary tables, FASTA files and indexes. metator.outputs names the folders of the output directory of a run, and writes the FASTA files of its genomes and MGE clusters and the cool files of its MAGs. metator.log holds the logger every module writes to. File formats describes the files.

metator.io

Core I/O tools of metaTOR: FASTA checks, compressed files, restriction sites, the MGE list, miComplete's results and the summary of the clusters.

SummaryLayout

Bases: NamedTuple

How write_bin_summary wrote the summary of the final clusters (cluster_summary.txt), which the map of the clusters records with its values (see metator.cli.validation_entry), to write it again: a header line, an empty field then the columns, then a line per row, its name then a field per column, tab-separated.

Attributes:

Name Type Description
rows list of str

The names of the clusters, in the order of the lines.

columns list of str

The columns, in order, after the name of the cluster.

formats dict

The format of each column, by name, as printf writes it: "%.2f" (a number with two decimals), "%.4f" (four: the abundances), "%d" (a whole number) or "%s" (text as it is: True or False for a boolean).

Source code in src/metator/io.py
class SummaryLayout(NamedTuple):
    """How write_bin_summary wrote the summary of the final clusters
    (cluster_summary.txt), which the map of the clusters records with its
    values (see metator.cli.validation_entry), to write it again: a header
    line, an empty field then the columns, then a line per row, its name then a
    field per column, tab-separated.

    Attributes
    ----------
    rows : list of str
        The names of the clusters, in the order of the lines.
    columns : list of str
        The columns, in order, after the name of the cluster.
    formats : dict
        The format of each column, by name, as printf writes it: "%.2f" (a
        number with two decimals), "%.4f" (four: the abundances), "%d" (a whole
        number) or "%s" (text as it is: True or False for a boolean)."""

    rows: list
    columns: list
    formats: dict

check_is_fasta

check_is_fasta(in_file)

Function from hicstuff.io (https://github.com/koszullab/hicstuff/) Checks whether input file is in fasta format.

Parameters:

Name Type Description Default
in_file str

Path to the input file.

required

Returns:

Type Description
bool

True if the input is in fasta format, False otherwise

Source code in src/metator/io.py
def check_is_fasta(in_file):
    """Function from hicstuff.io (https://github.com/koszullab/hicstuff/) Checks
    whether input file is in fasta format.

    Parameters
    ----------
    in_file : str
        Path to the input file.

    Returns
    -------
    bool
        True if the input is in fasta format, False otherwise"""
    try:
        with read_compressed(in_file) as handle:
            test = any(SeqIO.parse(handle, "fasta"))
    # Biopython >= 1.87 raises ValueError on any text before the first '>'
    # line, blank or '#' lines included. Earlier versions skipped that text
    # (1.85 and 1.86 with a warning), so text with no '>' line gave no record.
    except (FileNotFoundError, ValueError):
        test = False

    return test

file_compression

file_compression(filename)

The compression of a file, found from its first bytes, whatever its name, as read_compressed opens it: "gz", "bz2", "zip", or "uncompressed" for any other file.

Source code in src/metator/io.py
def file_compression(filename):
    """The compression of a file, found from its first bytes, whatever its name,
    as read_compressed opens it: "gz", "bz2", "zip", or "uncompressed" for any
    other file."""
    with open(filename, "rb") as f:
        file_start = f.read(max(len(magic) for magic in COMPRESSION_MAGIC))
    for magic, filetype in COMPRESSION_MAGIC.items():
        if file_start.startswith(magic):
            return filetype
    return "uncompressed"

generate_temp_dir

generate_temp_dir(path)

Temporary directory generation

The name comes from the system's random numbers, not Python's random module, which igraph draws from: a run's partition does not depend on how many of these directories it made.

Parameters:

Name Type Description Default
path str

The path at which the temporary directory will be created.

required

Returns:

Type Description
str

The path of the newly created temporary directory.

Source code in src/metator/io.py
def generate_temp_dir(path):
    """Temporary directory generation

    The name comes from the system's random numbers, not Python's random
    module, which igraph draws from: a run's partition does not depend on how
    many of these directories it made.

    Parameters
    ----------
    path : str
        The path at which the temporary directory will be created.

    Returns
    -------
    str
        The path of the newly created temporary directory."""
    exist = True
    while exist:
        # Keep trying random directory names if they already exist
        directory = str(hex(randbits(32)))[2:]
        full_path = join(path, directory)
        if not exists(full_path):
            exist = False
    try:
        os.makedirs(full_path)
    except PermissionError:
        raise PermissionError(
            "The temporary directory cannot be created in {}. Make sure you have write permission.".format(path)
        ) from None
    return full_path

get_restriction_site

get_restriction_site(enzyme)

Function to return a regex which corresponds to all possible restriction sites given a set of enzyme.

Parameters:

Name Type Description Default
enzyme str

String that contains the names of the enzyme separated by a comma.

required

Returns:

Type Description
str

Regex that corresponds to all possible restriction sites given a set of enzyme.

Examples:

>>> get_restriction_site('DpnII')
'GATC'
>>> get_restriction_site('DpnII,HinfI')
'GA.TC|GATC'
Source code in src/metator/io.py
def get_restriction_site(enzyme):
    """Function to return a regex which corresponds to all possible restriction
    sites given a set of enzyme.

    Parameters
    ----------
    enzyme : str
        String that contains the names of the enzyme separated by a comma.

    Returns
    -------
    str
        Regex that corresponds to all possible restriction sites given a set of
        enzyme.

    Examples
    --------
    >>> get_restriction_site('DpnII')
    'GATC'
    >>> get_restriction_site('DpnII,HinfI')
    'GA.TC|GATC'"""

    # Split the str on the comma to separate the different enzymes.
    enzyme = enzyme.split(",")

    # Check on Biopython dictionnary the enzyme.
    rb = RestrictionBatch(enzyme)

    # Initiation:
    restriction_list = []

    # Iterates on the enzymes.
    for enz in rb:
        # Extract restriction sites and look for cut sites.
        restriction_list.append(enz.site.replace("N", "."))

    # Build the regex for all retsriction sites.
    pattern = "|".join(sorted(list(set(restriction_list))))
    return pattern

import_mges_contigs

import_mges_contigs(mges_file)

Import list of mges contigs.

Parameters:

Name Type Description Default
mges_file str

Path to the mges file which contains the list of mges contigs.

required

Returns:

Type Description
list

List of the mges contigs names: the first word of each line, its blank lines left out.

Source code in src/metator/io.py
def import_mges_contigs(mges_file):
    """Import list of mges contigs.

    Parameters
    ----------
    mges_file : str
        Path to the mges file which contains the list of mges contigs.

    Returns
    -------
    list
        List of the mges contigs names: the first word of each line, its blank
        lines left out."""
    mges_list = []
    with open(mges_file, "r") as mges:
        for contig in mges:
            words = contig.split()
            if words:
                mges_list.append(words[0])
    return mges_list

micomplete_results_to_dict

micomplete_results_to_dict(micomplete_file)

Read micomplte output file and transfrom it as a dictionnary with the bin name as keys and bin information as values.

Parameters:

Name Type Description Default
micomplete_file str

Path to the micomplete output file.

required

Returns:

Type Description
dict

Dictionnary of the output of miComplete as values and the bin id as keys.

Source code in src/metator/io.py
def micomplete_results_to_dict(micomplete_file):
    """Read micomplte output file and transfrom it as a dictionnary with the bin
    name as keys and bin information as values.

    Parameters
    ----------
    micomplete_file : str
        Path to the micomplete output file.

    Returns
    -------
    dict
        Dictionnary of the output of miComplete as values and the bin id as
        keys."""
    # Read table.
    micomplete_summary = pd.read_csv(
        micomplete_file,
        sep="\t",
        comment="#",
        index_col=0,
        **mtcl.EXACT_FLOATS,
    ).iloc[:, :13]

    # Transform to dictionnary.
    micomplete_summary = micomplete_summary.to_dict(orient="index")

    return micomplete_summary

read_compressed

read_compressed(filename)

Read compressed file

Parameters:

Name Type Description Default
filename str

The path to the input file

required

Returns:

Type Description
file-like object

The handle to access the input file's content

Source code in src/metator/io.py
def read_compressed(filename):
    """Read compressed file

    Parameters
    ----------
    filename : str
        The path to the input file

    Returns
    -------
    file-like object
        The handle to access the input file's content"""

    # Open file with appropriate function
    comp = file_compression(filename)
    if comp == "gz":
        return gzip.open(filename, "rt")
    elif comp == "bz2":
        return bz2.open(filename, "rt")
    elif comp == "zip":
        zip_arch = zipfile.ZipFile(filename, "r")
        if len(zip_arch.namelist()) > 1:
            raise IOError("Only a single fastq file must be in the zip archive.")
        else:
            # ZipFile opens as bytes by default, using io to read as text
            zip_content = zip_arch.open(zip_arch.namelist()[0], "r")
            return io.TextIOWrapper(zip_content, encoding="utf-8")
    else:
        return open(filename, "r")

rename_1x_columns

rename_1x_columns(contig_data)

The table of contig data contig_data, its columns named after bins by metaTOR 1.x renamed as metaTOR 2.0 names them (CONTIG_DATA_1X_COLUMNS), to read the contig data files of a 1.x run as those of a 2.0 run: no command reads the tables of 1.x anymore (metator host reads the map).

A column already named as in 2.0 is kept, and the 1.x column of the same meaning left as it is.

Parameters:

Name Type Description Default
contig_data DataFrame

Table of contig data, as read from a contig data file.

required

Returns:

Type Description
DataFrame

The table, its 1.x columns renamed, or the table itself if it has none.

Source code in src/metator/io.py
def rename_1x_columns(contig_data):
    """The table of contig data contig_data, its columns named after bins by
    metaTOR 1.x renamed as metaTOR 2.0 names them (CONTIG_DATA_1X_COLUMNS),
    to read the contig data files of a 1.x run as those of a 2.0 run: no
    command reads the tables of 1.x anymore (metator host reads the map).

    A column already named as in 2.0 is kept, and the 1.x column of the same
    meaning left as it is.

    Parameters
    ----------
    contig_data : pandas.DataFrame
        Table of contig data, as read from a contig data file.

    Returns
    -------
    pandas.DataFrame
        The table, its 1.x columns renamed, or the table itself if it has none."""
    renamed = {
        old: new for old, new in CONTIG_DATA_1X_COLUMNS.items() if old in contig_data.columns and new not in contig_data.columns
    }
    if not renamed:
        return contig_data
    logger.info(
        "Contig data of metaTOR 1.x: its columns %s are read as %s.",
        ", ".join(renamed),
        ", ".join(renamed.values()),
    )
    return contig_data.rename(columns=renamed)

write_bin_summary

write_bin_summary(bin_summary, bin_summary_file, full_file=None)

Function to write the bin summary from dictionnary to table text file.

Parameters:

Name Type Description Default
bin_summary dict

Dictionnary with the output of the miComplete of the bins.

required
bin_summary_file str

Path to the output file to write the summary informations of the bins.

required
full_file str

Path to the same table, its values at full precision (see SUMMARY_FULL_FILE), where bin_summary_file writes its floats with 2 decimals, and the abundances with 4.

None

Returns:

Type Description
SummaryLayout

How the summary is written: its rows, its columns and their format, which the map of the clusters records (see metator.cli.validation_entry).

Source code in src/metator/io.py
def write_bin_summary(bin_summary, bin_summary_file, full_file=None):
    """Function to write the bin summary from dictionnary to table text file.

    Parameters
    ----------
    bin_summary : dict
        Dictionnary with the output of the miComplete of the bins.
    bin_summary_file : str
        Path to the output file to write the summary informations of the bins.
    full_file : str, optional
        Path to the same table, its values at full precision (see
        SUMMARY_FULL_FILE), where bin_summary_file writes its floats with 2
        decimals, and the abundances with 4.

    Returns
    -------
    SummaryLayout
        How the summary is written: its rows, its columns and their format,
        which the map of the clusters records (see
        metator.cli.validation_entry)."""

    # Transform dictionnary to pandas DataFrame.
    bin_summary = pd.DataFrame.from_dict(bin_summary, orient="index")
    formats = {str(column): _summary_format(column, bin_summary[column]) for column in bin_summary.columns}
    if full_file is not None:
        bin_summary.to_csv(full_file, sep="\t")

    # Change float format of the coverage.
    bin_summary["HiC_abundance"] = bin_summary["HiC_abundance"].map(lambda x: "%.4f" % x)
    try:
        bin_summary["SG_abundance"] = bin_summary["SG_abundance"].map(lambda x: "%.4f" % x)
    except KeyError:
        pass

    # Write the file.
    bin_summary.to_csv(bin_summary_file, sep="\t", float_format="%.2f")
    return SummaryLayout([str(row) for row in bin_summary.index], list(formats), formats)

metator.outputs

The files of a run beside its map: where they go in its output directory, the FASTA files of its genomes and MGE clusters, and the cool files of its MAGs.

Every command writes into its output directory (-o), under these names:

  • fasta/mags_with-mges/: the FASTA file of each final cluster, as the validation made it, with the MGE contigs that it holds (validation, pipeline);
  • fasta/mags/: each MAG of the map of the run, unstitched and stitched (see write_fasta_files): its genomes but __unbinned__ and the MGE genomes, which hold no MGE contig once metator mge --reassign made the MGE clusters genomes (pipeline);
  • fasta/mges/: each MGE cluster, unstitched and stitched (mge, pipeline --mges); fasta/mges_random/ for the random clusters of mge --random;
  • cool/: one cool file per MAG, with the MGE clusters that it hosts, balanced (see write_cool_files; pipeline);
  • tables/: the tables of metator dump (pipeline), and mge_hosts.txt (host, pipeline --mges);
  • plots/: the plots, as PDF files (see metator.figures and metator.host).

metator export writes them all again from the map of a run (the FASTA files with the assembly): the clusters of its rounds final and mge (see round_groups and mge_groups), its MAGs (see map_mags and hosted_mges), the summary of its final clusters (see final_summary).

write_fasta_files

write_fasta_files(
    metacool,
    assembly,
    outdir,
    genomes=None,
    groups=None,
    temp_dir=None,
    stitched=True,
)

Write the FASTA files of genomes of a map, or of groups of its contigs, in outdir (made if missing), two for each, side by side (the first only, without stitched: the final clusters of fasta/mags_with-mges, as the validation writes them):

  • <name>.fa: its contigs, the records of the assembly as they are (headers and lines), in the order of the map for a genome, in the order given for a group;
  • <name>.stitched.fa: one record named after it, its contigs (the longest first for a genome, ties in the order of the map; in the order given for a group) joined by SPACER N, in lines of 80 bases.

metacooler writes both (metacooler.write_fasta, once each: each reads the assembly); the stitched files are written in a directory of their own in outdir, then renamed. A file of that name in outdir is replaced.

Parameters:

Name Type Description Default
metacool str

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

required
assembly str

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

required
outdir str

The directory to write them in.

required
genomes list of str

The genomes of the map to write, by name.

None
groups dict

Name -> the names of its contigs, in their order: groups of contigs to write in place of genomes (the clusters of a run that the map does not hold yet).

None
temp_dir str

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

None
stitched bool

Whether to write <name>.stitched.fa too.

True

Returns:

Type Description
list of str

The genomes or groups written, in order: none for none given.

Raises:

Type Description
MetacoolError

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

Source code in src/metator/outputs.py
def write_fasta_files(metacool, assembly, outdir, genomes=None, groups=None, temp_dir=None, stitched=True):
    """Write the FASTA files of genomes of a map, or of groups of its contigs, in
    outdir (made if missing), two for each, side by side (the first only,
    without stitched: the final clusters of fasta/mags_with-mges, as the
    validation writes them):

    - ``<name>.fa``: its contigs, the records of the assembly as they are
      (headers and lines), in the order of the map for a genome, in the order
      given for a group;
    - ``<name>.stitched.fa``: one record named after it, its contigs (the
      longest first for a genome, ties in the order of the map; in the order
      given for a group) joined by SPACER N, in lines of 80 bases.

    metacooler writes both (metacooler.write_fasta, once each: each reads the
    assembly); the stitched files are written in a directory of their own in
    outdir, then renamed. A file of that name in outdir is replaced.

    Parameters
    ----------
    metacool : str
        Path to the .metacool file, or URI of an entry of a .mmetacool
        collection: the map whose contigs they are.
    assembly : str
        Path to the assembly the map was made from: FASTA, plain or compressed
        with gzip.
    outdir : str
        The directory to write them in.
    genomes : list of str, optional
        The genomes of the map to write, by name.
    groups : dict, optional
        Name -> the names of its contigs, in their order: groups of contigs
        to write in place of genomes (the clusters of a run that the map does
        not hold yet).
    temp_dir : str, optional
        Where a compressed assembly is copied, plain, as it is read: the
        temporary directory of the run.
    stitched : bool
        Whether to write ``<name>.stitched.fa`` too.

    Returns
    -------
    list of str
        The genomes or groups written, in order: none for none given.

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

    names = list(genomes) if genomes is not None else None
    groups = dict(groups or {}) if genomes is None else None
    # metacooler writes every genome for none named.
    if not (names if names is not None else groups):
        return []
    os.makedirs(outdir, exist_ok=True)
    with mtmc._metacooler_logging(), mtmc._as_metacool_errors(), mtmc.read_errors(metacool):
        written = metacooler.write_fasta(metacool, assembly, outdir, genomes=names, groups=groups, force=True, temp_dir=temp_dir)
        if not stitched:
            return list(written)
        staged = tempfile.mkdtemp(prefix=".stitched.", dir=outdir)
        try:
            files = metacooler.write_fasta(
                metacool,
                assembly,
                staged,
                genomes=names,
                groups=groups,
                stitch=True,
                spacer=SPACER,
                force=True,
                temp_dir=temp_dir,
            )
            for name, path in files.items():
                os.replace(path, join(outdir, f"{name}{STITCHED}"))
        finally:
            shutil.rmtree(staged, ignore_errors=True)
    return list(written)

round_groups

round_groups(mc, name)

The clusters of the clustering round name of a map (mc, opened), by name, in the order of the round: the names of their contigs, in the order of the map, as the round stores them. None for a map without that round.

Source code in src/metator/outputs.py
def round_groups(mc, name):
    """The clusters of the clustering round name of a map (mc, opened), by name,
    in the order of the round: the names of their contigs, in the order of the
    map, as the round stores them. None for a map without that round."""
    if name not in [entry.get("name") for entry in mc.cluster_rounds]:
        return None
    members = mc.cluster_members(name)
    groups = {}
    for cluster, contig in zip(members["cluster"].astype(str), members["contig"].astype(str), strict=True):
        groups.setdefault(cluster, []).append(contig)
    return groups

mge_groups

mge_groups(mc, name=mtcl.MGE)

The MGE clusters of the round name of a map (mc, opened: mge, or mge_random), by name (see round_groups): their contigs the longest first, ties by name, as metator mge writes them (see metator.mge.mge_binning). None for a map without that round.

Source code in src/metator/outputs.py
def mge_groups(mc, name=mtcl.MGE):
    """The MGE clusters of the round name of a map (mc, opened: mge, or
    mge_random), by name (see round_groups): their contigs the longest first,
    ties by name, as metator mge writes them (see metator.mge.mge_binning).
    None for a map without that round."""
    groups = round_groups(mc, name)
    if groups is None:
        return None
    lengths = dict(zip(mc.contigs["name"].astype(str), mc.contigs["length"].astype(int), strict=True))
    return {cluster: sorted(contigs, key=lambda contig: (-lengths[contig], contig)) for cluster, contigs in groups.items()}

final_summary

final_summary(mc, rows)

The final clusters of a map (mc, opened) as the plots of the validation read them (see metator.figures.plot_figures): by name, those of the summary of the run (rows, see metator.dump.summary_layout) that are genomes of the map, in its order, with their Length, Weighted completeness and Weighted redundancy, as its genomes table holds them: the values of the summary, which cluster_summary.txt rounds to 2 decimals, where the validation drew the values of miComplete.

Source code in src/metator/outputs.py
def final_summary(mc, rows):
    """The final clusters of a map (mc, opened) as the plots of the validation
    read them (see metator.figures.plot_figures): by name, those of the summary
    of the run (rows, see metator.dump.summary_layout) that are genomes of the
    map, in its order, with their Length, Weighted completeness and Weighted
    redundancy, as its genomes table holds them: the values of the summary,
    which cluster_summary.txt rounds to 2 decimals, where the validation drew
    the values of miComplete."""
    genomes = mc.genomes.set_index(mc.genomes["name"].astype(str))
    return {
        name: {column: float(genomes.at[name, column]) for column in mtf.PLOTTED_COLUMNS}
        for name in rows
        if name in genomes.index
    }

map_mags

map_mags(mc)

The MAGs of a map (mc, opened), in the order of its genomes table: its genomes but unbinned and the MGE genomes, those that its column mge says are and those named after a cluster of its round mge (see metator.host.map_bins).

Source code in src/metator/outputs.py
def map_mags(mc):
    """The MAGs of a map (mc, opened), in the order of its genomes table: its
    genomes but __unbinned__ and the MGE genomes, those that its column mge
    says are and those named after a cluster of its round mge (see
    metator.host.map_bins)."""
    names = [str(name) for name in mc.genomes["name"]]
    mges = set(mtmc.mge_genomes(mc))
    if mtcl.MGE in [entry.get("name") for entry in mc.cluster_rounds]:
        mges |= set(mc.cluster_members(mtcl.MGE)["cluster"].astype(str))
    return [name for name in names if name != mtmc.UNBINNED_GENOME and name not in mges]

hosted_mges

hosted_mges(mc)

The MGE clusters that each MAG of a map hosts (mc, opened), by MAG, as metator host stores them in its genomes table (its column mges, names separated by commas): none for a map without hosts.

Source code in src/metator/outputs.py
def hosted_mges(mc):
    """The MGE clusters that each MAG of a map hosts (mc, opened), by MAG, as
    metator host stores them in its genomes table (its column mges, names
    separated by commas): none for a map without hosts."""
    genomes = mc.genomes
    if "mges" not in genomes.columns:
        return {}
    return {
        str(name): [mge for mge in str(mges).split(",") if mge and mge != "nan"]
        for name, mges in zip(genomes["name"], genomes["mges"], strict=True)
        if isinstance(mges, str) and mges
    }

plot_inputs

plot_inputs(mc, rows)

What the plots of the final clusters of a map (mc, opened) are drawn from, as the validation draws them (see metator.figures.plot_figures): the length of its contigs, as a Size column, and the summary of its final clusters (rows: their names, see final_summary).

Source code in src/metator/outputs.py
def plot_inputs(mc, rows):
    """What the plots of the final clusters of a map (mc, opened) are drawn from,
    as the validation draws them (see metator.figures.plot_figures): the length
    of its contigs, as a Size column, and the summary of its final clusters
    (rows: their names, see final_summary)."""
    return pd.DataFrame({"Size": mc.contigs["length"].to_numpy()}), final_summary(mc, rows)

write_cool_files

write_cool_files(metacool, outdir, mags, hosted=None)

Write the cool file of each MAG of a map in outdir (made if missing): <MAG>.cool, the contacts of its contigs and of those of the MGE clusters that it hosts (hosted: their names, by MAG, the MGE genomes of the map), as metacooler extract writes them, at the bins of the map, then balanced as cooler balance balances a cool file, the whole of it at once, with its defaults (the first two diagonals left out, bins with fewer than 10 non-zero pixels masked...): the weight column of its bins. A cool file that cannot be balanced is a warning, and is kept without weights; one whose every bin is masked (too few bins, or contacts, for cooler balance) is a warning too, its weights all NaN.

Returns:

Type Description
list of str

The cool files written, in the order of mags.

Raises:

Type Description
MetacoolError

If metacooler cannot extract a MAG (a ValueError, KeyError or OSError of metacooler, message kept).

Source code in src/metator/outputs.py
def write_cool_files(metacool, outdir, mags, hosted=None):
    """Write the cool file of each MAG of a map in outdir (made if missing):
    ``<MAG>.cool``, the contacts of its contigs and of those of the MGE
    clusters that it hosts (hosted: their names, by MAG, the MGE genomes of
    the map), as metacooler extract writes them, at the bins of the map, then
    balanced as cooler balance balances a cool file, the whole of it at once,
    with its defaults (the first two diagonals left out, bins with fewer than
    10 non-zero pixels masked...): the weight column of its bins. A cool file
    that cannot be balanced is a warning, and is kept without weights; one
    whose every bin is masked (too few bins, or contacts, for cooler balance)
    is a warning too, its weights all NaN.

    Returns
    -------
    list of str
        The cool files written, in the order of mags.

    Raises
    ------
    metator.metacool.MetacoolError
        If metacooler cannot extract a MAG (a ValueError, KeyError or OSError
        of metacooler, message kept)."""
    import cooler
    import metacooler

    os.makedirs(outdir, exist_ok=True)
    written = []
    for mag in mags:
        path = join(outdir, f"{mag}.cool")
        with mtmc._metacooler_logging(), mtmc._as_metacool_errors(), mtmc.read_errors(metacool):
            metacooler.extract(metacool, genomes=[mag, *(hosted or {}).get(mag, [])], output=path)
        try:
            weights, _ = cooler.balance_cooler(cooler.Cooler(path), store=True)
        except Exception as error:
            logger.warning(f"{path} is not balanced, and keeps its raw contacts only: {type(error).__name__}: {error}")
        else:
            if not np.isfinite(weights).any():
                logger.warning(
                    f"Every bin of {path} is masked by its balancing (too few bins, or contacts, for cooler balance): its "
                    "weights are all NaN, and its raw contacts are kept."
                )
        written.append(path)
    return written

metator.log

Basic logging setup for metator

Basic logging setup with two handlers (stdout and log file). By default the log file is disabled, but can be enabled or changed using set_file_handler. Python's warnings (warnings.warn, which cooler and pandas give theirs with) go to the same handlers, as metaTOR's own messages do.

The messages at INFO tell what a run does and finds; those at DEBUG, its bookkeeping (the files it writes on the way, the temporary directory it removes...), are not shown: CURRENT_LOG_LEVEL shows them.

set_file_handler

set_file_handler(log_path, formatter=logfile_formatter)

Change the file handler for custom log file location: that of metaTOR's messages and of Python's warnings.

Source code in src/metator/log.py
def set_file_handler(log_path, formatter=logfile_formatter):
    """Change the file handler for custom log file location: that of metaTOR's
    messages and of Python's warnings."""

    filehandler = logging.FileHandler(log_path, "a")
    filehandler.setLevel(logging.DEBUG)
    filehandler.setFormatter(formatter)
    for _logger in (logger, warnings_logger):
        for hdlr in _logger.handlers[:]:  # remove the existing file handlers
            if isinstance(hdlr, logging.FileHandler):
                _logger.removeHandler(hdlr)
        _logger.addHandler(filehandler)  # set the new handler

duration

duration(seconds)

A duration, in whole seconds, as hicstuff writes it in its log: 0h 17m 31s.

Source code in src/metator/log.py
def duration(seconds):
    """A duration, in whole seconds, as hicstuff writes it in its log: 0h 17m 31s."""
    hours, rest = divmod(round(seconds), 3600)
    minutes, seconds = divmod(rest, 60)
    return f"{hours}h {minutes}m {seconds}s"