Skip to content

Pipeline

hicstuff.pipeline.full_pipeline is hicstuff pipeline: its arguments are the command's options (see Using the Python API). Each step is a function of its own: align_reads, bam2pairs, filter_pcr_dup, pairs2cool, pairs2binnedcool, pairs2metacool, cool2mcool, balance, pairs2matrix.

hicstuff.stats reads the statistics of a run from its log, as hicstuff stats does, and hicstuff.log holds the logger every module writes to.

hicstuff.pipeline

Handle generation of graal-compatible contact maps from fastq files. cmdoret, 20190322

align_reads

align_reads(reads, genome, out_bam, tmp_dir=None, threads=1, aligner='bowtie2', iterative=False, min_qual=30, read_len=None, backend=None)

Select and call correct alignment method and generate logs accordingly. Alignments are filtered so that there at most one alignment per read. Alignments are sorted by read name in the output file.

Parameters:

Name Type Description Default
reads str

Path to the fastq file with Hi-C reads.

required
genome str or BwaIndex

Path to the genome bowtie2/bwa index prefix if using bowtie2 or bwa, or to the fasta if using minimap2. With bwa in-process, an index loaded by hicstuff.bwamem.load_index also works, so that it is loaded once for several files; a path is loaded, or indexed if it has no index.

required
out_bam str

Path to the output BAM file containing mapped Hi-C reads.

required
tmp_dir str

Path where temporary files are stored.

None
threads int

Number of threads to run alignments in parallel.

1
aligner bool

Use minimap2 or bwa instead of bowtie2.

'bowtie2'
iterative bool

Wether to use the iterative mapping procedure (truncating reads and extending iteratively)

False
min_qual int

Minimum mapping quality required to keep an alignment during iterative mapping.

30
read_len int

Maximum read length to expect in the fastq file. Optionally used in iterative alignment mode. Estimated from the first read by default. Useful if input fastq is a composite of different read lengths.

None
backend str

How bwa runs: "binary" (the bwa program), "python" (in-process with pybwa) or "auto", for which see hicstuff.bwamem.resolve_backend. None reads the environment variable HICSTUFF_ALIGNER_BACKEND.

None
Source code in src/hicstuff/pipeline.py
def align_reads(
    reads,
    genome,
    out_bam,
    tmp_dir=None,
    threads=1,
    aligner="bowtie2",
    iterative=False,
    min_qual=30,
    read_len=None,
    backend=None,
):
    """
    Select and call correct alignment method and generate logs accordingly.
    Alignments are filtered so that there at most one alignment per read.
    Alignments are sorted by read name in the output file.

    Parameters
    ----------
    reads : str
        Path to the fastq file with Hi-C reads.
    genome : str or pybwa.BwaIndex
        Path to the genome bowtie2/bwa index prefix if using bowtie2 or bwa, or to the
        fasta if using minimap2. With bwa in-process, an index loaded by
        hicstuff.bwamem.load_index also works, so that it is loaded once for
        several files; a path is loaded, or indexed if it has no index.
    out_bam : str
        Path to the output BAM file containing mapped Hi-C reads.
    tmp_dir : str
        Path where temporary files are stored.
    threads : int
        Number of threads to run alignments in parallel.
    aligner : bool
        Use minimap2 or bwa instead of bowtie2.
    iterative : bool
        Wether to use the iterative mapping procedure (truncating reads and
        extending iteratively)
    min_qual : int
        Minimum mapping quality required to keep an alignment during iterative
        mapping.
    read_len : int
        Maximum read length to expect in the fastq file. Optionally used in iterative
        alignment mode. Estimated from the first read by default. Useful if input fastq
        is a composite of different read lengths.
    backend : str
        How bwa runs: "binary" (the bwa program), "python" (in-process with
        pybwa) or "auto", for which see hicstuff.bwamem.resolve_backend. None
        reads the environment variable HICSTUFF_ALIGNER_BACKEND.
    """
    if tmp_dir is None:
        tmp_dir = os.getcwd()
    if aligner == "bwa" and hbm.resolve_backend(backend) == "python":
        with hbm.loaded_index(genome, tmp_dir) as index:
            if iterative:
                hbm.iterative_align(
                    reads, index, out_bam, threads=threads, min_qual=min_qual, read_len=read_len
                )
            else:
                hbm.align(reads, index, out_bam, threads=threads)
        return
    tmp_bam = out_bam + ".tmp"

    if iterative:
        iter_tmp_dir = hio.generate_temp_dir(tmp_dir)
        hci.iterative_align(
            reads,
            tmp_dir=iter_tmp_dir,
            ref=genome,
            n_cpu=threads,
            bam_out=tmp_bam,
            min_qual=min_qual,
            aligner=aligner,
            read_len=read_len,
        )
        st.rmtree(iter_tmp_dir)
        # Remove supplementary alignments
        ps.view(
            *("-F", "2048", "-h", "-@", str(threads), "-O", "BAM", tmp_bam, "-o", out_bam),
            catch_stdout=False,
        )
    else:
        hio.require_tools(
            [aligner if aligner in ("minimap2", "bwa") else "bowtie2"], "to align reads"
        )
        if aligner == "minimap2":
            map_cmd = "minimap2 -2 -t {threads} -ax sr {fasta} {fastq} > {sam}"
        elif aligner == "bwa":
            map_cmd = "bwa mem -t {threads} -v 1 {index} {fastq} > {sam}"
        else:
            map_cmd = "bowtie2 --very-sensitive-local -p {threads} -x {index} -U {fastq} > {sam}"
        map_args = {
            "threads": threads,
            "sam": tmp_bam,
            "fastq": reads,
            "fasta": genome,
            "index": genome,
        }
        sp.call(map_cmd.format(**map_args), shell=True)
        # Remove supplementary alignments and sort reads by name
        hio.samtools_pipe(
            ["view", "-F", "2048", "-h", "-@", threads, tmp_bam],
            ["sort", "-n", "-@", threads, "-o", out_bam, "-"],
        )
    os.remove(tmp_bam)

bam2pairs

bam2pairs(bam1, bam2, out_pairs, info_contigs, min_qual=30, tmp_dir=None, threads=1, five_prime=False)

Make a .pairs file from two Hi-C bam files sorted by read names. The Hi-C mates are matched by read identifier, without /1 or /2 suffix, walking both files in the order they are sorted in: samtools sort -n (natural) order, or samtools sort -N (lexicographical) order if both headers say so. Reads whose mate is missing from the other file are skipped. Files that turn out not to be in that order are walked in the other one, as other tools (Picard, sambamba sort -n) sort names in lexicographical order without saying so. Files in neither order are sorted again with samtools sort -n in a temporary directory, so that no pair is lost. Pairs where at least one reads maps with MAPQ below min_qual threshold are discarded. Pairs are sorted by readID and stored in upper triangle (first pair higher).

Parameters:

Name Type Description Default
bam1 str

Path to the name-sorted BAM file with aligned Hi-C forward reads.

required
bam2 str

Path to the name-sorted BAM file with aligned Hi-C reverse reads.

required
out_pairs str

Path to the output space-separated .pairs file with columns readID, chr1 pos1 chr2 pos2 strand1 strand2

required
info_contigs str

Path to the info contigs file, to get info on chromosome sizes and order.

required
min_qual int

Minimum mapping quality required to keep a Hi-C pair.

30
tmp_dir str

Directory in which to sort BAM files that are in neither read name order. Defaults to the directory of out_pairs.

None
threads int

Number of threads to sort them with.

1
five_prime bool

Whether each mate's position is its aligned 5' end, the first base of the read that aligns, at the end of the sequenced molecule, as pairtools records it. Otherwise it is the leftmost base of the alignment: the 5' end of a forward-strand mate, but the 3' end of a reverse-strand one.

False
Source code in src/hicstuff/pipeline.py
def bam2pairs(
    bam1, bam2, out_pairs, info_contigs, min_qual=30, tmp_dir=None, threads=1, five_prime=False
):
    """
    Make a .pairs file from two Hi-C bam files sorted by read names.
    The Hi-C mates are matched by read identifier, without /1 or /2 suffix,
    walking both files in the order they are sorted in: ``samtools sort -n``
    (natural) order, or ``samtools sort -N`` (lexicographical) order if both
    headers say so. Reads whose mate is missing from the other file are
    skipped. Files that turn out not to be in that order are walked in the
    other one, as other tools (Picard, sambamba sort -n) sort names in
    lexicographical order without saying so. Files in neither order are
    sorted again with ``samtools sort -n`` in a temporary directory, so that
    no pair is lost.
    Pairs where at least one reads maps with MAPQ below min_qual threshold are
    discarded. Pairs are sorted by readID and stored in upper triangle (first
    pair higher).

    Parameters
    ----------
    bam1 : str
        Path to the name-sorted BAM file with aligned Hi-C forward reads.
    bam2 : str
        Path to the name-sorted BAM file with aligned Hi-C reverse reads.
    out_pairs : str
        Path to the output space-separated .pairs file with columns
        readID, chr1 pos1 chr2 pos2 strand1 strand2
    info_contigs : str
        Path to the info contigs file, to get info on chromosome sizes and order.
    min_qual : int
        Minimum mapping quality required to keep a Hi-C pair.
    tmp_dir : str
        Directory in which to sort BAM files that are in neither read name
        order. Defaults to the directory of out_pairs.
    threads : int
        Number of threads to sort them with.
    five_prime : bool
        Whether each mate's position is its aligned 5' end, the first base of
        the read that aligns, at the end of the sequenced molecule, as
        pairtools records it. Otherwise it is the leftmost base of the
        alignment: the 5' end of a forward-strand mate, but the 3' end of a
        reverse-strand one.
    """
    with ps.AlignmentFile(bam1, "rb") as forward, ps.AlignmentFile(bam2, "rb") as reverse:
        orders = {_name_order_key(forward), _name_order_key(reverse)}
    # Mates are matched by walking both files in the order they are sorted in
    declared = orders.pop() if len(orders) == 1 else _natural_key
    order_names = {_natural_key: "samtools sort -n", str: "samtools sort -N"}
    for name_key in (declared, str if declared is _natural_key else _natural_key):
        try:
            counts = _write_pairs(
                bam1, bam2, out_pairs, info_contigs, name_key, min_qual, five_prime
            )
            break
        except _NameOrderError as err:
            # Pairs may have been missed: start again
            os.remove(out_pairs)
            unsorted = str(err)
            logger.info(
                "%s is not sorted by read name as %s sorts it.", unsorted, order_names[name_key]
            )
    else:
        sort_dir = hio.generate_temp_dir(tmp_dir or os.path.dirname(os.path.abspath(out_pairs)))
        logger.warning(
            "%s is in the read name order of neither samtools sort -n nor samtools sort -N: "
            "sorting both BAM files with samtools sort -n in %s.",
            unsorted,
            sort_dir,
        )
        sorted_bams = [join(sort_dir, "for.bam"), join(sort_dir, "rev.bam")]
        try:
            for bam, sorted_bam in zip((bam1, bam2), sorted_bams):
                ps.sort("-n", "-@", str(threads), "-o", sorted_bam, bam)
            counts = _write_pairs(
                *sorted_bams, out_pairs, info_contigs, _natural_key, min_qual, five_prime
            )
        except _NameOrderError as still_unsorted:
            os.remove(out_pairs)
            bam = bam1 if str(still_unsorted) == sorted_bams[0] else bam2
            raise ValueError(
                f"Cannot match the mates of {bam1} and {bam2}: the read names of "
                f"{bam}, sorted with samtools sort -n (samtools "
                f"{ps.__samtools_version__}), are still not in the order expected."
            ) from None
        finally:
            st.rmtree(sort_dir)
    if counts["unmatched"] > 0:
        logger.warning("%d reads were only present in one BAM file.", counts["unmatched"])
    logger.info(
        f"{100 * round(counts['mapped'] / counts['total'], 2):.2f}% reads (single ends) mapped with Q >= {min_qual} ({counts['mapped']}/{counts['total']})"
    )

filter_pcr_dup

filter_pcr_dup(pairs_idx_file, filtered_file)

Filter out PCR duplicates from a pairs file sorted by COORD_SORT_KEYS, using overrrepresented exact coordinates. If multiple fragments have two reads with the exact same coordinates, only one of those fragments is kept.

Parameters:

Name Type Description Default
pairs_idx_file str

Path to an indexed pairs file containing the Hi-C reads.

required
filtered_file str

Path to the output pairs file after removing duplicates.

required
Source code in src/hicstuff/pipeline.py
def filter_pcr_dup(pairs_idx_file, filtered_file):
    """
    Filter out PCR duplicates from a pairs file sorted by COORD_SORT_KEYS,
    using overrrepresented exact coordinates. If multiple fragments have two
    reads with the exact same coordinates, only one of those fragments is kept.
    Parameters
    ----------
    pairs_idx_file : str
        Path to an indexed pairs file containing the Hi-C reads.
    filtered_file : str
        Path to the output pairs file after removing duplicates.
    """
    # Keep count of how many reads are filtered
    filter_count = 0
    reads_count = 0
    # Store header lines
    header = hio.get_pairs_header(pairs_idx_file)
    with open(pairs_idx_file) as pairs, open(filtered_file, "w") as filtered:
        # Copy header lines to filtered file
        for head_line in header:
            filtered.write(head_line + "\n")
            next(pairs)

        # Use csv methods to easily access columns
        paircols = [
            "readID",
            "chr1",
            "pos1",
            "chr2",
            "pos2",
            "strand1",
            "strand2",
            "frag1",
            "frag2",
        ]
        # Columns used for comparison of coordinates
        coord_cols = [col for col in paircols if col != "readID"]
        pair_reader = csv.DictReader(pairs, delimiter="\t", fieldnames=paircols)
        filt_writer = csv.DictWriter(filtered, delimiter="\t", fieldnames=paircols)

        # Initialise a variable to store coordinates of reads in previous pair
        prev = {k: 0 for k in paircols}
        for pair in pair_reader:
            reads_count += 1
            # If coordinates are the same as before, skip pair
            if all(pair[pair_var] == prev[pair_var] for pair_var in coord_cols):
                filter_count += 1
                continue
            # Else write pair and store new coordinates as previous
            else:
                filt_writer.writerow(pair)
                prev = pair
        logger.info(
            f"{100 * round(filter_count / reads_count, 3):.1f}% PCR duplicates have been filtered out ({filter_count}/{reads_count} pairs)"
        )
        logger.info(f"{reads_count - filter_count} pairs remaining after removing PCR duplicates")

sort_and_compress_pairs

sort_and_compress_pairs(pairs_file, out_file, tmp_dir=None, threads=1)

Sort a pairs file by chr1, chr2, pos1, pos2 (the standard order for pairs files) and compress it in the BGZF format, so that pairix can index it: with bgzip, on several threads, if it is installed, otherwise with pysam, on one thread.

Parameters:

Name Type Description Default
pairs_file str

Path to the input, uncompressed pairs file.

required
out_file str

Path to the output sorted and compressed pairs file.

required
tmp_dir str

Directory where temporary files will be created.

None
threads int

Number of threads used for sorting and bgzip compression.

1
Source code in src/hicstuff/pipeline.py
def sort_and_compress_pairs(pairs_file, out_file, tmp_dir=None, threads=1):
    """
    Sort a pairs file by chr1, chr2, pos1, pos2 (the standard order for
    pairs files) and compress it in the BGZF format, so that pairix can index
    it: with bgzip, on several threads, if it is installed, otherwise with
    pysam, on one thread.

    Parameters
    ----------
    pairs_file : str
        Path to the input, uncompressed pairs file.
    out_file : str
        Path to the output sorted and compressed pairs file.
    tmp_dir : str
        Directory where temporary files will be created.
    threads : int
        Number of threads used for sorting and bgzip compression.
    """
    sorted_tmp = out_file + ".tmp"
    hio.sort_pairs(
        pairs_file,
        sorted_tmp,
        keys=["chr1", "chr2", "pos1", "pos2"],
        tmp_dir=tmp_dir,
        threads=threads,
    )
    try:
        if which("bgzip") is not None:
            with open(out_file, "wb") as out:
                sp.run(["bgzip", "-c", "-@", str(threads), sorted_tmp], stdout=out, check=True)
        else:
            ps.tabix_compress(sorted_tmp, out_file, force=True)
    finally:
        os.remove(sorted_tmp)

pairs2cool

pairs2cool(pairs_file, cool_file, bins_file, exclude)

Make a cooler file from the pairs file. See: https://github.com/mirnylab/cooler/ for more informations.

Parameters:

Name Type Description Default
pairs_file str

Path to the pairs file containing input contact data.

required
cool_file str

Path to the output cool file name to generate.

required
bins_file str

Path to the file containing genomic segmentation information. (fragments_list.txt).

required
Source code in src/hicstuff/pipeline.py
def pairs2cool(pairs_file, cool_file, bins_file, exclude):
    """
    Make a cooler file from the pairs file. See: https://github.com/mirnylab/cooler/ for more informations.

    Parameters
    ----------

    pairs_file : str
        Path to the pairs file containing input contact data.
    cool_file : str
        Path to the output cool file name to generate.
    bins_file : str
        Path to the file containing genomic segmentation information. (fragments_list.txt).
    """

    # Exclude some chromosomes from bins
    bins_tmp = bins_file + ".cooler"
    bins = pd.read_csv(bins_file, sep="\t", usecols=[1, 2, 3], skiprows=1, header=None)
    if exclude is not None:
        bins = bins[~bins[1].isin(exclude.split(","))]
    bins.to_csv(bins_tmp, sep="\t", header=False, index=False)

    # Make cool
    try:
        _run_cooler_cload_pairs(bins_tmp, pairs_file, cool_file)
    finally:
        os.remove(bins_tmp)

pairs2binnedcool

pairs2binnedcool(pairs_file, cool_file, binning, info_contigs, exclude)

Make a binned cooler file from the pairs file. See: https://github.com/mirnylab/cooler/ for more informations.

Parameters:

Name Type Description Default
pairs_file str

Path to the pairs file containing input contact data.

required
cool_file str

Path to the output cool file name to generate.

required
binning int

If mat_fmt is set to "cool", the cool file will be further binned to this resolution.

required
info_contigs Path or str

The path to the contigs info file

required
Source code in src/hicstuff/pipeline.py
def pairs2binnedcool(pairs_file, cool_file, binning, info_contigs, exclude):
    """
    Make a *binned* cooler file from the pairs file. See: https://github.com/mirnylab/cooler/ for more informations.

    Parameters
    ----------

    pairs_file : str
        Path to the pairs file containing input contact data.
    cool_file : str
        Path to the output cool file name to generate.
    binning : int
        If mat_fmt is set to "cool", the cool file will be further binned to
        this resolution.
    info_contigs : pathlib.Path or str
        The path to the contigs info file
    """

    # Exclude some chromosomes from bins
    chroms_tmp = info_contigs + ".chroms"
    chroms = pd.read_csv(info_contigs, sep="\t", usecols=[0, 1], skiprows=1, header=None)
    if exclude is not None:
        chroms = chroms[~chroms[0].isin(exclude.split(","))]
    chroms.to_csv(chroms_tmp, index=False, sep="\t", header=False)

    # Run `cooler cload pairs`
    try:
        _run_cooler_cload_pairs(chroms_tmp + ":" + str(binning), pairs_file, cool_file)
    finally:
        os.remove(chroms_tmp)

pairs2metacool

pairs2metacool(pairs_file, metacool_file, bins_file, exclude, threads=1, cmd=None)

Make a metacool file from the pairs file, with one bin per fragment, with metacooler create pairs, through its Python function metacooler.from_pairs. See: https://pypi.org/project/metacooler/.

A metacool file is a cool file, which cooler reads, with metacooler's genomes and contigs on top of it. Its contigs are not yet assigned to genomes: all of them are in metacooler's __unbinned__ genome, longest first, as metacooler create pairs orders them by default, until metacooler reassign assigns them. Unlike cooler, metacooler does not store the contig of each bin as an HDF5 enum, which takes a time that grows with the square of the number of contigs.

Parameters:

Name Type Description Default
pairs_file str

Path to the pairs file containing input contact data.

required
metacool_file str

Path to the output metacool file name to generate.

required
bins_file str

Path to the file containing genomic segmentation information. (fragments_list.txt).

required
exclude None, str or list of str

The contigs to leave out of the matrix, comma-separated, as in pairs2cool.

required
threads int

Number of threads binning the pairs.

1
cmd str or None

The command line that ran the pipeline, stored in the file's metadata as the command that made it. None stores no command.

None
Source code in src/hicstuff/pipeline.py
def pairs2metacool(pairs_file, metacool_file, bins_file, exclude, threads=1, cmd=None):
    """
    Make a metacool file from the pairs file, with one bin per fragment, with
    `metacooler create pairs`, through its Python function
    ``metacooler.from_pairs``. See: https://pypi.org/project/metacooler/.

    A metacool file is a cool file, which cooler reads, with metacooler's
    genomes and contigs on top of it. Its contigs are not yet assigned to
    genomes: all of them are in metacooler's ``__unbinned__`` genome, longest
    first, as `metacooler create pairs` orders them by default, until
    `metacooler reassign` assigns them. Unlike cooler, metacooler does not
    store the contig of each bin as an HDF5 enum, which takes a time that grows
    with the square of the number of contigs.

    Parameters
    ----------
    pairs_file : str
        Path to the pairs file containing input contact data.
    metacool_file : str
        Path to the output metacool file name to generate.
    bins_file : str
        Path to the file containing genomic segmentation information. (fragments_list.txt).
    exclude : None, str or list of str
        The contigs to leave out of the matrix, comma-separated, as in
        pairs2cool.
    threads : int
        Number of threads binning the pairs.
    cmd : str or None
        The command line that ran the pipeline, stored in the file's metadata
        as the command that made it. None stores no command.
    """
    # The names of the contigs are text, even when they are numbers
    bins = pd.read_csv(
        bins_file, sep="\t", usecols=[1, 2, 3], skiprows=1, header=None, dtype={1: str}
    )
    bins.columns = ["chrom", "start", "end"]
    bins = bins[~bins.chrom.isin(_excluded(exclude))].reset_index(drop=True)
    metacooler.from_pairs(
        uri=metacool_file,
        bins=bins,
        pairs=pairs_file,
        # hicstuff has its distance law (--distance-law), and writes one file
        # for the matrix, as it does for a cool matrix.
        ps=False,
        nproc=threads,
        metadata={"commands": [cmd]} if cmd else None,
    )

cool2mcool

cool2mcool(cool_file, output_file)

Zoomify a binned cooler file. See: https://github.com/mirnylab/cooler/ for more informations.

Parameters:

Name Type Description Default
cool_file str

Path to an existing binned .cool file.

required
output_file str

Path to the new multi-resolution .mcool file.

required
Source code in src/hicstuff/pipeline.py
def cool2mcool(cool_file, output_file):
    """
    Zoomify a *binned* cooler file. See: https://github.com/mirnylab/cooler/ for more informations.

    Parameters
    ----------

    cool_file : str
        Path to an existing binned .cool file.
    output_file : str
        Path to the new multi-resolution .mcool file.
    """

    # Get resolutions
    clr = cooler.Cooler(cool_file)
    res = clr.binsize
    multires = [res, res * 2, res * 5, res * 10, res * 20, res * 50, res * 100]

    # Run cooler zoomify
    cooler.zoomify_cooler(clr.filename, output_file, multires, chunksize=10000000)

balance

balance(cool_file, balancing_args, threads=1)

Balance a binned cooler file, every resolution of a .mcool file, with cooler balance. See: https://github.com/mirnylab/cooler/ for more informations.

Balancing never stops the pipeline. When cooler balance fails at a resolution, a warning carrying cooler's error is logged and that resolution stays as it was; when the weights it stores did not converge, a warning says so. "Matrix balanced" is logged only for the resolutions that got weights.

Parameters:

Name Type Description Default
cool_file str

Path to an existing binned .(m)cool file.

required
balancing_args str

Extra arguments passed to cooler balance (default: None)

required
threads int

Number of processes used to balance, unless set in balancing_args.

1

Returns:

Type Description
list of str

The URIs of the resolutions that hold balancing weights.

Source code in src/hicstuff/pipeline.py
def balance(cool_file, balancing_args, threads=1):
    """
    Balance a *binned* cooler file, every resolution of a .mcool file, with
    `cooler balance`. See: https://github.com/mirnylab/cooler/ for more informations.

    Balancing never stops the pipeline. When `cooler balance` fails at a
    resolution, a warning carrying cooler's error is logged and that
    resolution stays as it was; when the weights it stores did not
    converge, a warning says so. "Matrix balanced" is logged only for the
    resolutions that got weights.

    Parameters
    ----------

    cool_file : str
        Path to an existing binned .(m)cool file.
    balancing_args : str
        Extra arguments passed to `cooler balance` (default: None)
    threads : int
        Number of processes used to balance, unless set in `balancing_args`.

    Returns
    -------
    list of str
        The URIs of the resolutions that hold balancing weights.
    """
    args = _balancing_args(balancing_args, threads)
    command = _cooler_command("balance")
    params = command.make_context("cooler balance", args + ["COOL_PATH"]).params
    # The weight column cooler writes: --name, "weight" by default
    name = params["name"]
    # cooler's process pool starts its workers with Python's default start
    # method. Unless it is fork, every worker imports the script that called
    # hicstuff again (spawn on macOS, forkserver on Linux from Python 3.14),
    # which then fails unless that script guards its code with
    # `if __name__ == "__main__":`. Balance in a new `python -m cooler`
    # process then, whose main module is guarded.
    new_process = params["nproc"] > 1 and multiprocessing.get_start_method() != "fork"
    if cooler.fileops.is_multires_file(cool_file):
        uris = [cool_file + "::" + path for path in cooler.fileops.list_coolers(cool_file)]
    else:
        uris = [cool_file]
    balanced = []
    for uri in uris:
        try:
            what = f"`cooler balance` of {uri}"
            if new_process:
                _run_cooler_program(["balance"], args + [uri], what)
            else:
                _run_cooler(command, args + [uri], what)
        except RuntimeError as err:
            logger.warning("Continuing without balancing: %s", err)
            continue
        with cooler.Cooler(uri).open("r") as grp:
            weights = grp["bins"].get(name)
            # One flag per chromosome with --cis-only or --trans-only
            converged = weights is None or bool(np.all(weights.attrs.get("converged", True)))
        if weights is None:
            # e.g. --stdout, or --convergence-policy discard without convergence
            logger.warning("`cooler balance` stored no %r column in %s.", name, uri)
            continue
        if not converged:
            logger.warning(
                "`cooler balance` did not converge for %s: its %r column is "
                "stored with converged=False.",
                uri,
                name,
            )
        balanced.append(uri)
    if balanced:
        logger.info(
            "Matrix balanced with cooler balance%s.",
            "" if len(balanced) == len(uris) else f" ({len(balanced)} of {len(uris)} resolutions)",
        )
    return balanced

pairs2matrix

pairs2matrix(pairs_file, mat_file, fragments_file, mat_fmt='graal', threads=1, tmp_dir=None)

Generate the matrix by counting the number of occurences of each combination of restriction fragments in a pairs file.

Parameters:

Name Type Description Default
pairs_file str

Path to a Hi-C pairs file, with frag1 and frag2 columns added.

required
mat_file str

Path where the matrix will be written.

required
fragments_file str

Path to the fragments_list.txt file. Used to know total matrix size in case some observations are not observed at the end.

required
mat_fmt str

The format to use when writing the matrix. Can be graal or bg2 format.

'graal'
threads int

Number of threads to use in parallel.

1
tmp_dir str

Temporary directory for sorting files. If None given, will use the system default.

None
Source code in src/hicstuff/pipeline.py
def pairs2matrix(pairs_file, mat_file, fragments_file, mat_fmt="graal", threads=1, tmp_dir=None):
    """Generate the matrix by counting the number of occurences of each
    combination of restriction fragments in a pairs file.

    Parameters
    ----------
    pairs_file : str
        Path to a Hi-C pairs file, with frag1 and frag2 columns added.
    mat_file : str
        Path where the matrix will be written.
    fragments_file : str
        Path to the fragments_list.txt file. Used to know total
        matrix size in case some observations are not observed at the end.
    mat_fmt : str
        The format to use when writing the matrix. Can be graal or bg2 format.
    threads : int
        Number of threads to use in parallel.
    tmp_dir : str
        Temporary directory for sorting files. If None given, will use the system default.
    """
    # Number of fragments is N lines in frag list - 1 for the header
    n_frags = sum(1 for line in open(fragments_file)) - 1
    frags = pd.read_csv(fragments_file, delimiter="\t")

    def write_mat_entry(frag1, frag2, contacts):
        """Write a single sparse matrix entry in either graal or bg2 format"""
        if mat_fmt == "graal":
            mat.write("\t".join(map(str, [frag1, frag2, contacts])) + "\n")
        elif mat_fmt == "bg2":
            frag1, frag2 = int(frag1), int(frag2)
            mat.write(
                "\t".join(
                    map(
                        str,
                        [
                            frags.chrom[frag1],
                            frags.start_pos[frag1],
                            frags.end_pos[frag1],
                            frags.chrom[frag2],
                            frags.start_pos[frag2],
                            frags.end_pos[frag2],
                            contacts,
                        ],
                    )
                )
                + "\n"
            )

    pre_mat_file = mat_file + ".pre.pairs"
    hio.sort_pairs(
        pairs_file,
        pre_mat_file,
        keys=["frag1", "frag2"],
        threads=threads,
        tmp_dir=tmp_dir,
    )
    header_size = len(hio.get_pairs_header(pre_mat_file))
    with open(pre_mat_file) as pairs, open(mat_file, "w") as mat:
        # Skip header lines
        for _ in range(header_size):
            next(pairs)
        prev_pair = None  # Pairs identified by [frag1, frag2]
        n_occ = 0  # Number of occurences of each frag combination
        n_nonzero = 0  # Total number of nonzero matrix entries
        n_pairs = 0  # Total number of pairs entered in the matrix
        pairs_reader = csv.reader(pairs, delimiter="\t")
        # First line contains nrows, ncols and number of nonzero entries.
        # Number of nonzero entries is unknown for now
        if mat_fmt == "graal":
            mat.write("\t".join(map(str, [n_frags, n_frags, "-"])) + "\n")
        for pair in pairs_reader:
            # Fragment ids are field 8 and 9
            curr_pair = [pair[7], pair[8]]
            # Increment number of occurences for fragment pair
            if prev_pair == curr_pair:
                n_occ += 1
            # Write previous pair and start a new one
            else:
                if n_occ > 0:
                    write_mat_entry(prev_pair[0], prev_pair[1], n_occ)
                    n_nonzero += 1
                    n_pairs += n_occ
                prev_pair = curr_pair
                n_occ = 1
        # Write the last value
        if n_occ > 0:
            write_mat_entry(prev_pair[0], prev_pair[1], n_occ)
            n_nonzero += 1
            n_pairs += n_occ

    # Edit header line to fill number of nonzero entries inplace in graal header
    if mat_fmt == "graal":
        with open(mat_file) as mat, open(pre_mat_file, "w") as tmp_mat:
            header = mat.readline()
            header = header.replace("-", str(n_nonzero))
            tmp_mat.write(header)
            st.copyfileobj(mat, tmp_mat)
        # Replace the matrix file with the one with corrected header
        os.rename(pre_mat_file, mat_file)
    else:
        os.remove(pre_mat_file)

    logger.info(
        "%d pairs used to build a contact map of %d bins with %d nonzero entries.",
        n_pairs,
        n_frags,
        n_nonzero,
    )

check_tool

check_tool(name)

Check whether name is on PATH and marked as executable.

Source code in src/hicstuff/pipeline.py
def check_tool(name):
    """Check whether `name` is on PATH and marked as executable."""

    return which(name) is not None

expand_inputs

expand_inputs(arg)

The files that an input argument of hicstuff pipeline names.

An argument that is a path that exists is that file, whatever characters its name holds. Otherwise, it is a comma-separated list of paths, each of which may be a glob pattern (with *, ? or [...]), replaced by the files it matches, sorted by name.

Parameters:

Name Type Description Default
arg str

A path, comma-separated paths, or glob patterns.

required

Returns:

Type Description
list of str

The paths of the files, in the order given.

Raises:

Type Description
ValueError

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

Examples:

>>> expand_inputs("lane1_R1.fq.gz,lane2_R1.fq.gz")
['lane1_R1.fq.gz', 'lane2_R1.fq.gz']
Source code in src/hicstuff/pipeline.py
def expand_inputs(arg):
    """The files that an input argument of ``hicstuff pipeline`` names.

    An argument that is a path that exists is that file, whatever characters
    its name holds. Otherwise, it is a comma-separated list of paths, each of
    which may be a glob pattern (with ``*``, ``?`` or ``[...]``), replaced by
    the files it matches, sorted by name.

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

    Returns
    -------
    list of str
        The paths of the files, in the order given.

    Raises
    ------
    ValueError
        If a pattern matches no file, or a list holds an empty item.

    Examples
    --------
    >>> expand_inputs("lane1_R1.fq.gz,lane2_R1.fq.gz")
    ['lane1_R1.fq.gz', 'lane2_R1.fq.gz']
    """
    if os.path.exists(arg):
        return [arg]
    files = []
    for item in arg.split(","):
        if not item:
            raise ValueError(f"Empty path in the input list {arg!r}.")
        if _GLOB_CHARS.search(item) is None:
            files.append(item)
            continue
        matches = sorted(glob.glob(item))
        if not matches:
            raise ValueError(f"No file matches the input pattern {item!r}.")
        files.extend(matches)
    return files

split_inputs

split_inputs(args, start_stage='fastq')

The R1 and R2 files given by the input arguments of hicstuff pipeline.

Each argument is expanded by :func:expand_inputs. From fastq or BAM files, two arguments are the R1 files and the R2 files. More arguments, as the shell gives them for unquoted glob patterns such as lib1_*_R1.fq.gz lib1_*_R2.fq.gz, must be even in number: the first half are the R1 files, the second half the R2 files. From pairs, every argument is a pairs file.

Parameters:

Name Type Description Default
args list of str

The input arguments, as given on the command line.

required
start_stage str

The start stage of the pipeline: "fastq", "bam", "pairs" or "pairs_idx".

'fastq'

Returns:

Type Description
tuple of (list of str, list of str)

The R1 files and the R2 files, in matching order; the files and an empty list from pairs, or from a single argument.

Raises:

Type Description
ValueError

If the R1 and R2 files cannot be told apart, or an argument names no file (see :func:expand_inputs).

Examples:

>>> split_inputs(["a_R1.fq.gz,b_R1.fq.gz", "a_R2.fq.gz,b_R2.fq.gz"])
(['a_R1.fq.gz', 'b_R1.fq.gz'], ['a_R2.fq.gz', 'b_R2.fq.gz'])
>>> split_inputs(["a_R1.fq.gz", "b_R1.fq.gz", "a_R2.fq.gz", "b_R2.fq.gz"])
(['a_R1.fq.gz', 'b_R1.fq.gz'], ['a_R2.fq.gz', 'b_R2.fq.gz'])
Source code in src/hicstuff/pipeline.py
def split_inputs(args, start_stage="fastq"):
    """The R1 and R2 files given by the input arguments of ``hicstuff pipeline``.

    Each argument is expanded by :func:`expand_inputs`. From fastq or BAM
    files, two arguments are the R1 files and the R2 files. More arguments,
    as the shell gives them for unquoted glob patterns such as
    ``lib1_*_R1.fq.gz lib1_*_R2.fq.gz``, must be even in number: the first
    half are the R1 files, the second half the R2 files. From pairs, every
    argument is a pairs file.

    Parameters
    ----------
    args : list of str
        The input arguments, as given on the command line.
    start_stage : str
        The start stage of the pipeline: "fastq", "bam", "pairs" or
        "pairs_idx".

    Returns
    -------
    tuple of (list of str, list of str)
        The R1 files and the R2 files, in matching order; the files and an
        empty list from pairs, or from a single argument.

    Raises
    ------
    ValueError
        If the R1 and R2 files cannot be told apart, or an argument names no
        file (see :func:`expand_inputs`).

    Examples
    --------
    >>> split_inputs(["a_R1.fq.gz,b_R1.fq.gz", "a_R2.fq.gz,b_R2.fq.gz"])
    (['a_R1.fq.gz', 'b_R1.fq.gz'], ['a_R2.fq.gz', 'b_R2.fq.gz'])
    >>> split_inputs(["a_R1.fq.gz", "b_R1.fq.gz", "a_R2.fq.gz", "b_R2.fq.gz"])
    (['a_R1.fq.gz', 'b_R1.fq.gz'], ['a_R2.fq.gz', 'b_R2.fq.gz'])
    """
    args = list(args)
    if start_stage in ("pairs", "pairs_idx"):
        return [f for arg in args for f in expand_inputs(arg)], []
    if len(args) > 2 and len(args) % 2:
        raise ValueError(
            f"{len(args)} input files: give the R1 files, then the R2 files, as many of each."
        )
    half = max(len(args) // 2, 1)
    forward = [f for arg in args[:half] for f in expand_inputs(arg)]
    reverse = [f for arg in args[half:] for f in expand_inputs(arg)]
    return forward, reverse

check_fastq_pairs

check_fastq_pairs(forward, reverse)

Check that several pairs of fastq files can be read as one library.

Every file must exist and be given once, and the R1 and R2 files of each pair must start with the same read: Illumina names both mates of a read pair alike, with an optional /1 or /2.

Parameters:

Name Type Description Default
forward list of str

The R1 files.

required
reverse list of str

The R2 files, in the order of their R1 files.

required

Raises:

Type Description
ValueError

If a file is missing or given twice, or the files of a pair do not start with the same read.

Source code in src/hicstuff/pipeline.py
def check_fastq_pairs(forward, reverse):
    """Check that several pairs of fastq files can be read as one library.

    Every file must exist and be given once, and the R1 and R2 files of each
    pair must start with the same read: Illumina names both mates of a read
    pair alike, with an optional /1 or /2.

    Parameters
    ----------
    forward : list of str
        The R1 files.
    reverse : list of str
        The R2 files, in the order of their R1 files.

    Raises
    ------
    ValueError
        If a file is missing or given twice, or the files of a pair do not
        start with the same read.
    """
    files = forward + reverse
    missing = [path for path in files if not os.path.exists(path)]
    if missing:
        raise ValueError(f"Input file not found: {', '.join(missing)}")
    seen = {}
    for path in files:
        real = os.path.realpath(path)
        if real in seen:
            raise ValueError(f"Input file given twice: {seen[real]} and {path}.")
        seen[real] = path
    for fq1, fq2 in zip(forward, reverse):
        name1, name2 = _first_read_name(fq1), _first_read_name(fq2)
        if name1 != name2:
            raise ValueError(
                f"{fq1} and {fq2} are not the R1 and R2 files of the same reads: they start "
                f"with reads {name1} and {name2}. Give the R1 files, then the R2 files, in "
                "the same order."
            )

concatenate_fastq

concatenate_fastq(files, out_file)

Concatenate fastq files into one, gzip-compressed if any of them is.

The gzip files are copied as they are, which makes a valid gzip file of several members, read as one by Python, htslib and the aligners. With a gzip file among them, the plain files are compressed; otherwise the output is a plain file. A plain file that does not end with a newline gets one.

Parameters:

Name Type Description Default
files list of str

The fastq files, plain or gzip-compressed, in the order to write them.

required
out_file str

Path of the concatenated file.

required
Source code in src/hicstuff/pipeline.py
def concatenate_fastq(files, out_file):
    """Concatenate fastq files into one, gzip-compressed if any of them is.

    The gzip files are copied as they are, which makes a valid gzip file of
    several members, read as one by Python, htslib and the aligners. With a
    gzip file among them, the plain files are compressed; otherwise the
    output is a plain file. A plain file that does not end with a newline
    gets one.

    Parameters
    ----------
    files : list of str
        The fastq files, plain or gzip-compressed, in the order to write them.
    out_file : str
        Path of the concatenated file.
    """
    gzipped = [_is_gzip(path) for path in files]
    with open(out_file, "wb") as out:
        for path, is_gzip in zip(files, gzipped):
            with open(path, "rb") as src:
                if is_gzip:
                    st.copyfileobj(src, out, 1 << 20)
                elif any(gzipped):
                    # A temporary file, read again soon: compressed fast
                    with gzip.GzipFile(fileobj=out, mode="wb", compresslevel=1) as dst:
                        _copy_lines(src, dst)
                else:
                    _copy_lines(src, out)

full_pipeline

full_pipeline(genome, input1, input2=None, aligner=None, centromeres=None, exclude=None, circular=False, distance_law=False, enzyme=5000, filter_events=False, force=False, mapping='normal', mat_fmt=None, binning=0, zoomify=True, balancing_args=None, min_qual=30, min_size=0, no_cleanup=False, out_dir=None, pcr_duplicates=False, plot=False, prefix=None, read_len=None, remove_centros=None, start_stage='fastq', threads=1, tmp_dir=None, skip_count=False, aligner_backend=None, cmd=None)

Run the whole hicstuff pipeline. Starting from fastq files and a genome to obtain a contact matrix.

Parameters:

Name Type Description Default
genome str

Path to the bowtie2/bwa index prefix if using bowtie2/bwa or to the genome in fasta format if using minimap2.

required
input1 str or list of str

Path to the Hi-C reads in fastq format (forward), the aligned Hi-C reads in BAM format, or the pairs file, depending on the value of start_stage. From fastq, a list of files: the R1 files of several pairs of fastq files (lanes or runs of a library), read as one library.

required
input2 str or list of str

Path to the Hi-C reads in fastq format (reverse), the aligned Hi-C reads in BAM format, or None, depending on the value of start_stage. From fastq, a list of files: the R2 files, in the order of their R1 files. Each pair must start with the same read; the R1 files are concatenated in the temporary directory, as are the R2 files, and aligned as one pair of files.

None
binning int

If mat_fmt is set to "cool", the cool file will be further binned to this resolution.

0
zoomify bool

Whether to zoomify binned cool matrix (only used if mat_fmt == "cool" and binning is set)

True
balancing_args str

Extra arguments passed to cooler balance (default: None) (only used if mat_fmt == "cool" and binning is set)

None
enzyme int or strtest_data / genome / fa
5000
circular bool

Use if the genome is circular.

False
out_dir str or None

Path where output files should be written. Current directory by default.

None
tmp_dir str or None

Path where temporary files will be written. Creates a "tmp" folder in out_dir by default.

None
plot bool

Whether plots should be generated at different steps of the pipeline. Plots are saved in a "plots" directory inside out_dir.

False
min_qual int

Minimum mapping quality required to keep a pair of Hi-C reads.

30
min_size int

Minimum contig size required to keep it. Shorter contigs are left out of the fragments list, and pairs with a mate on one of them are discarded.

0
threads int

Number of threads to use for parallel operations.

1
no_cleanup bool

Whether temporary files should be deleted at the end of the pipeline.

False
mapping str

normal|iterative|cutsite|5spm. Use normal, iterative, cutsite or 5spm mapping. "normal": Normal alignement. "iterative": Truncates and extends reads until unambiguous alignment. "cutsite": Digest reads at religation sites and build new pairs from the fragments created. "5spm": Align the mates with bwa mem -5SPM, which makes the 5'-most alignment of a read its primary one, as the 4DN, Juicer and Arima pipelines do; it aligns with bwa, in-process with pybwa unless aligner_backend says otherwise. The pairs of mode 5spm record each mate at its aligned 5' end, those of the other modes at the leftmost base of its alignment.

'normal'
filter_events bool

Filter spurious or uninformative 3C events. Requires a restriction enzyme.

False
force bool

If True, overwrite existing files with the same name as output.

False
prefix str or None

Choose a common name for output files instead of default graal names.

None
start_stage str

Step at which the pipeline should start. Can be "fastq", "bam", "pairs" or "pairs_idx". With starting from bam allows to skip alignment and start from named-sorted bam files. With "pairs", a single pairs file is given as input, and with "pairs_idx", the pairs in the input must already be attributed to fragments and fragment attribution is skipped.

'fastq'
mat_fmt str or None

Select the output matrix format. Can be either "bg2" for the bedgraph2 format, "cool" for Mirnylab's cool format, "metacool" for metacooler's cool format for metagenomes, with one bin per fragment, graal for a plain text COO format compatible with Koszullab's instagraal software, or "none" for no matrix: the run ends with its pairs file, which tools that build their own contact maps read (metaTOR, metacooler). Options of the cool matrix, binning other than 0 and balancing_args that is not blank, are refused with metacool and none, and exclude that is not blank with none. None, the default, writes a cool matrix, or a metacool matrix, with a warning, when it holds MANY_CONTIGS contigs or more (those that min_size and exclude keep) and binning is 0.

None
aligner str

Read alignment software to use. Can be either "minimap2", "bwa" or "bowtie2". Defaults to bowtie2, and to bwa in mapping mode 5spm, which only aligns with bwa.

None
pcr_duplicates bool

If True, PCR duplicates will be filtered based on genomic positions. Pairs where both reads have exactly the same coordinates are considered duplicates and only one of those will be conserved.

False
distance_law bool

If True, generates a distance law file with the values of the probabilities to have a contact between two distances for each chromosomes or arms if the file with the positions has been given. The values are not normalized, or averaged.

False
centromeres None or str

If not None, path of file with Positions of the centromeres separated by a space and in the same order than the chromosomes.

None
exclude None or str

If not None, the name of the chromosomes to remove (e.g. "2u,chrM")

None
read_len int

Maximum read length to expect in the fastq file. Optionally used in iterative alignment mode. Estimated from the first read by default. Useful if input fastq is a composite of different read lengths.

None
remove_centros None or int

If the distance law is computed, this is the number of kb that will be removed around the centromere position given by in the centromere file.

None
skip_count bool

If True, skip counting reads in the input FASTQ files. Useful for very large files where counting is slow.

False
aligner_backend str

How bwa runs: "binary" (the bwa program), "python" (in-process with pybwa) or "auto". None reads the environment variable HICSTUFF_ALIGNER_BACKEND, and is auto if it is not set. auto runs the bwa program if it is on PATH and pybwa otherwise, and in mapping mode 5spm pybwa first.

None
cmd str

The command line that ran the pipeline, written to the log header after the date. None leaves it out.

None
Source code in src/hicstuff/pipeline.py
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
def full_pipeline(
    genome,
    input1,
    input2=None,
    aligner=None,
    centromeres=None,
    exclude=None,
    circular=False,
    distance_law=False,
    enzyme=5000,
    filter_events=False,
    force=False,
    mapping="normal",
    mat_fmt=None,
    binning=0,
    zoomify=True,
    balancing_args=None,
    min_qual=30,
    min_size=0,
    no_cleanup=False,
    out_dir=None,
    pcr_duplicates=False,
    plot=False,
    prefix=None,
    read_len=None,
    remove_centros=None,
    start_stage="fastq",
    threads=1,
    tmp_dir=None,
    skip_count=False,
    aligner_backend=None,
    cmd=None,
):
    """
    Run the whole hicstuff pipeline. Starting from fastq files and a genome to
    obtain a contact matrix.

    Parameters
    ----------
    genome : str
        Path to the bowtie2/bwa index prefix if using bowtie2/bwa or to the genome
        in fasta format if using minimap2.
    input1 : str or list of str
        Path to the Hi-C reads in fastq format (forward), the aligned Hi-C reads
        in BAM format, or the pairs file, depending on the value of start_stage.
        From fastq, a list of files: the R1 files of several pairs of fastq
        files (lanes or runs of a library), read as one library.
    input2 : str or list of str
        Path to the Hi-C reads in fastq format (reverse), the aligned Hi-C reads
        in BAM format, or None, depending on the value of start_stage. From
        fastq, a list of files: the R2 files, in the order of their R1 files.
        Each pair must start with the same read; the R1 files are concatenated
        in the temporary directory, as are the R2 files, and aligned as one
        pair of files.
    binning : int
        If mat_fmt is set to "cool", the cool file will be further binned to
        this resolution.
    zoomify : bool
        Whether to zoomify binned cool matrix (only used if mat_fmt == "cool" and binning is set)
    balancing_args : str
        Extra arguments passed to `cooler balance` (default: None) (only used if
        mat_fmt == "cool" and binning is set)
    enzyme : int or strtest_data/genome/seq.fa
    circular : bool
        Use if the genome is circular.
    out_dir : str or None
        Path where output files should be written. Current directory by default.
    tmp_dir : str or None
        Path where temporary files will be written. Creates a "tmp" folder in
        out_dir by default.
    plot : bool
        Whether plots should be generated at different steps of the pipeline.
        Plots are saved in a "plots" directory inside out_dir.
    min_qual : int
        Minimum mapping quality required to keep a pair of Hi-C reads.
    min_size : int
        Minimum contig size required to keep it. Shorter contigs are left out
        of the fragments list, and pairs with a mate on one of them are
        discarded.
    threads : int
        Number of threads to use for parallel operations.
    no_cleanup : bool
        Whether temporary files should be deleted at the end of the pipeline.
    mapping : str
        normal|iterative|cutsite|5spm. Use normal, iterative, cutsite or 5spm
        mapping. "normal": Normal alignement. "iterative": Truncates and extends
        reads until unambiguous alignment. "cutsite": Digest reads at religation
        sites and build new pairs from the fragments created. "5spm": Align the
        mates with ``bwa mem -5SPM``, which makes the 5'-most alignment of a read
        its primary one, as the 4DN, Juicer and Arima pipelines do; it aligns
        with bwa, in-process with pybwa unless aligner_backend says otherwise.
        The pairs of mode 5spm record each mate at its aligned 5' end, those of
        the other modes at the leftmost base of its alignment.
    filter_events : bool
        Filter spurious or uninformative 3C events. Requires a restriction enzyme.
    force : bool
        If True, overwrite existing files with the same name as output.
    prefix : str or None
        Choose a common name for output files instead of default graal names.
    start_stage : str
        Step at which the pipeline should start. Can be "fastq", "bam", "pairs"
        or "pairs_idx". With starting from bam allows to skip alignment and start
        from named-sorted bam files. With
        "pairs", a single pairs file is given as input, and with "pairs_idx", the
        pairs in the input must already be attributed to fragments and fragment
        attribution is skipped.
    mat_fmt : str or None
        Select the output matrix format. Can be either "bg2" for the
        bedgraph2 format, "cool" for Mirnylab's cool format, "metacool" for
        metacooler's cool format for metagenomes, with one bin per fragment,
        graal for a plain text COO format compatible with Koszullab's
        instagraal software, or "none" for no matrix: the run ends with its
        pairs file, which tools that build their own contact maps read
        (metaTOR, metacooler). Options of the cool matrix, binning other than
        0 and balancing_args that is not blank, are refused with metacool and
        none, and exclude that is not blank with none. None, the default,
        writes a cool matrix, or a metacool matrix, with a warning, when it
        holds MANY_CONTIGS contigs or more (those that min_size and exclude
        keep) and binning is 0.
    aligner : str
        Read alignment software to use. Can be either "minimap2", "bwa" or
        "bowtie2". Defaults to bowtie2, and to bwa in mapping mode 5spm, which
        only aligns with bwa.
    pcr_duplicates : bool
        If True, PCR duplicates will be filtered based on genomic positions.
        Pairs where both reads have exactly the same coordinates are considered
        duplicates and only one of those will be conserved.
    distance_law : bool
        If True, generates a distance law file with the values of the probabilities
        to have a contact between two distances for each chromosomes or arms if the
        file with the positions has been given. The values are not normalized, or
        averaged.
    centromeres : None or str
        If not None, path of file with Positions of the centromeres separated by a
        space and in the same order than the chromosomes.
    exclude : None or str
        If not None, the name of the chromosomes to remove (e.g. "2u,chrM")
    read_len : int
        Maximum read length to expect in the fastq file. Optionally used in iterative
        alignment mode. Estimated from the first read by default. Useful if input fastq
        is a composite of different read lengths.
    remove_centros : None or int
        If the distance law is computed, this is the number of kb that will be removed
        around the centromere position given by in the centromere file.
    skip_count : bool
        If True, skip counting reads in the input FASTQ files. Useful for very
        large files where counting is slow.
    aligner_backend : str
        How bwa runs: "binary" (the bwa program), "python" (in-process with
        pybwa) or "auto". None reads the environment variable
        HICSTUFF_ALIGNER_BACKEND, and is auto if it is not set. auto runs the
        bwa program if it is on PATH and pybwa otherwise, and in mapping mode
        5spm pybwa first.
    cmd : str
        The command line that ran the pipeline, written to the log header after
        the date. None leaves it out.
    """
    if mapping == "5spm":
        if aligner not in (None, "bwa"):
            msg = (
                f"Mapping mode 5spm aligns with bwa mem -5SPM, not with {aligner}: "
                "leave out the aligner, or set it to bwa."
            )
            logger.error(msg)
            raise ValueError(msg)
        aligner = "bwa"
    elif aligner is None:
        aligner = "bowtie2"
    if aligner_backend is not None and aligner != "bwa" and aligner_backend.lower() == "python":
        msg = f"pybwa runs bwa only: --aligner-backend python cannot align with {aligner}."
        logger.error(msg)
        raise ValueError(msg)
    if aligner not in ("bowtie2", "minimap2", "bwa"):
        logger.error("Incompatible aligner software, choose bowtie2, minimap2 or bwa.")
        raise ValueError("aligner should be either bowtie2, minimap2 or bwa.")
    if mat_fmt is not None and mat_fmt not in MATRIX_FORMATS:
        msg = f"Unknown matrix format {mat_fmt!r}: choose graal, bg2, cool, metacool or none."
        logger.error(msg)
        raise ValueError(msg)
    # None is cool, or metacool with many contigs and no binning
    if mat_fmt in ("cool", None):
        try:
            import cooler
        except ImportError:
            logger.error(
                "The cooler package is require to return matrix in cool format, please install it first."
            )
            raise ImportError("The cooler package is required.") from None
        if binning > 0:
            # Fail now on invalid balancing arguments, not after the alignment
            _balancing_args(balancing_args)
    elif mat_fmt in ("metacool", "none"):
        cool_only = [
            name
            for name, given in [
                ("binning", binning != 0),
                ("balancing_args", bool(balancing_args and balancing_args.strip())),
                (
                    "exclude",
                    mat_fmt == "none" and any(name.strip() for name in _excluded(exclude)),
                ),
            ]
            if given
        ]
        if cool_only:
            options = "is an option" if len(cool_only) == 1 else "are options"
            msg = (
                f"The matrix format {mat_fmt} {_WRITES[mat_fmt]}: {', '.join(cool_only)} "
                f"{options} of the cool matrix."
            )
            logger.error(msg)
            raise ValueError(msg)

    # Pipeline can start from 3 input types
    start_time = datetime.now()
    stages = {"fastq": 0, "bam": 1, "pairs": 2, "pairs_idx": 3}
    stage_name, start_stage = start_stage, stages[start_stage]

    # Check if the genome is an index or fasta file
    idx = hio.check_fasta_index(genome, mode=aligner)
    is_fasta = hio.check_is_fasta(genome)
    # The genome is a fasta file, or the prefix of a bowtie2 or bwa index from
    # which its sequence is read, for the digestion and the fragments.
    # minimap2 reads a fasta file only.
    if not (is_fasta or (idx is not None and aligner != "minimap2")):
        logger.error(
            "The genome must be a fasta file, or the prefix of a %s index: %s",
            "bowtie2 or bwa" if aligner == "minimap2" else aligner,
            genome,
        )
        sys.exit(1)
    # Check that the third parties the run uses can be run: the aligner only
    # aligns reads from fastq files. bwa runs as a program or in-process.
    backend = None
    if start_stage == 0:
        if aligner == "bwa":
            backend = hbm.resolve_backend(aligner_backend, prefer_python=mapping == "5spm")
        if backend != "python":
            hio.require_tools(
                hio.alignment_tools(aligner, idx),
                f"to align the reads of start stage {stage_name}",
                alternative=(
                    "run with -a bwa, which aligns in-process with pybwa"
                    if aligner != "bwa" and hbm.pybwa_version() is not None
                    else None
                ),
            )
    if aligner == "bowtie2" and not is_fasta:
        hio.require_tools(
            ["bowtie2-inspect"], f"to extract the genome sequence from the bowtie2 index {genome}"
        )

    # Check if the number of input files is correct
    for_files, rev_files = _input_files(input1), _input_files(input2)
    if start_stage <= 1:
        if not for_files or not rev_files:
            logger.error("You must provide 2 input files when --start-stage is fastq or bam.")
            sys.exit(1)
        if len(for_files) != len(rev_files):
            logger.error(
                "%d R1 files and %d R2 files: each R1 file needs its R2 file.",
                len(for_files),
                len(rev_files),
            )
            sys.exit(1)
        if start_stage == 1 and len(for_files) > 1:
            logger.error(
                "Several pairs of input files are read from fastq only: give one BAM file per mate."
            )
            sys.exit(1)
    else:
        if rev_files or len(for_files) != 1:
            logger.error(
                "You must provide a single input file when --start-stage is pairs or pairs_idx."
            )
            sys.exit(1)
    # Several pairs of fastq files are concatenated into one pair of files
    several_pairs = len(for_files) > 1
    if several_pairs:
        try:
            check_fastq_pairs(for_files, rev_files)
        except ValueError as error:
            logger.error(str(error))
            sys.exit(1)
    input1 = ",".join(for_files)
    input2 = ",".join(rev_files) if rev_files else None
    # sanitize enzyme
    enzyme = str(enzyme)
    # Remember whether fragments_file has been generated during this run
    fragments_updated = False

    if out_dir is None:
        out_dir = os.getcwd()

    if tmp_dir is None:
        tmp_dir = join(out_dir, "tmp")

    os.makedirs(out_dir, exist_ok=True)
    os.makedirs(tmp_dir, exist_ok=True)

    # Define figures output paths
    if plot:
        fig_dir = join(out_dir, "plots")
        os.makedirs(fig_dir, exist_ok=True)
        if prefix:
            frag_plot = join(fig_dir, prefix + "_frags_hist.pdf")
            dist_plot = join(fig_dir, prefix + "_event_distance.pdf")
            pie_plot = join(fig_dir, prefix + "_event_distribution.pdf")
            distance_law_plot = join(fig_dir, prefix + "_distance_law.pdf")
        else:
            frag_plot = join(fig_dir, "frags_hist.pdf")
            dist_plot = join(fig_dir, "event_distance.pdf")
            pie_plot = join(fig_dir, "event_distribution.pdf")
            distance_law_plot = join(fig_dir, "distance_law.pdf")
        matplotlib.use("Agg")
    else:
        fig_dir = None
        dist_plot = pie_plot = frag_plot = None

    # Use current time for logging and to identify files
    now = time.strftime("%Y%m%d%H%M%S")

    def _tmp_file(fname):
        if prefix:
            fname = prefix + "." + fname
        full_path = join(tmp_dir, fname)
        if not force and os.path.exists(full_path):
            raise OSError(f"Temporary file {full_path} already exists. Use --force to overwrite")
        return full_path

    def _out_file(fname):
        if prefix:
            fname = prefix + "." + fname
        full_path = join(out_dir, fname)
        if not force and os.path.exists(full_path):
            raise OSError(f"Output file {full_path} already exists. Use --force to overwrite")

        return full_path

    # Define temporary file names
    log_file = _out_file("hicstuff_" + now + ".log")
    bam1 = _tmp_file("for.bam")
    bam2 = _tmp_file("rev.bam")
    pairs = _tmp_file("valid.pairs")
    pairs_idx = _tmp_file("valid_idx.pairs")
    pairs_filtered = _tmp_file("valid_idx_filtered.pairs")
    pairs_pcr = _tmp_file("valid_idx_pcrfree.pairs")
    reads_cat = []
    if several_pairs:
        reads_cat = [
            _tmp_file(f"{mate}.fq.gz" if any(map(_is_gzip, files)) else f"{mate}.fq")
            for mate, files in (("for", for_files), ("rev", rev_files))
        ]

    # Enable file logging
    hcl.set_file_handler(log_file)
    # The logs of bwa in-process, or in mapping mode 5spm, name the aligner;
    # other runs log what they did before these existed.
    generate_log_header(
        log_file,
        input1,
        input2,
        genome,
        enzyme,
        aligner=(
            hbm.describe(backend, five_spm=mapping == "5spm")
            if backend == "python" or mapping == "5spm"
            else None
        ),
        cmd=cmd,
    )

    # The genome has two roles: fasta is the file its sequences are read from
    # (digestion, fragments), index the prefix of the aligner's index. What
    # this run writes from the genome goes to a directory of its own, which
    # cleanup removes: the sequence read from an index without fasta, the
    # index built from a fasta file without one, or the files pybwa loads.
    # Nothing is written next to the genome, and a fasta file is not copied.
    genome_dir = None
    if (start_stage == 0 and (backend == "python" or idx is None)) or not is_fasta:
        genome_dir = hio.generate_temp_dir(tmp_dir)
    if is_fasta:
        fasta = genome
    elif aligner == "bwa":
        # A bwa index without fasta: its .pac file holds the sequence
        fasta = join(genome_dir, "genome.fa.gz")
        with gzip.open(fasta, "wb", compresslevel=6) as dst:
            hbm.write_fasta(genome, dst)
    else:
        # A bowtie2 index without fasta: bowtie2-inspect reads the sequence
        fasta = join(genome_dir, "genome.fa.gz")
        bt2fa = sp.Popen(
            ["bowtie2-inspect", genome],
            stdout=sp.PIPE,
            stderr=sp.PIPE,
        )
        # At gzip's default level, as `gzip -c` compressed it
        with gzip.open(fasta, "wb", compresslevel=6) as dst:
            st.copyfileobj(bt2fa.stdout, dst, 1 << 20)
        _, bt2err = bt2fa.communicate()
        # bowtie2-inspect still has return code 0 when crashing, need to
        # actively look for error in stderr
        if re.search(r"[Ee]rror", bt2err.decode()):
            logger.error(bt2err)
            logger.error(
                "bowtie2-inspect has failed, make sure you provided "
                "the path to the bowtie2 index without the extension."
            )
            sys.exit(1)

    # Check for spaces in fasta headers and issue error if found, and count
    # the contigs of the matrix (those --size and --exclude keep), before an
    # index is built: the default format follows from it, and its warnings
    # come first.
    excluded = _excluded(exclude)
    n_contigs = 0
    for record in SeqIO.parse(hio.read_compressed(fasta), "fasta"):
        if len(record.seq) >= int(min_size) and record.id not in excluded:
            n_contigs += 1
        if " " in record.id:
            logger.error("Sequence identifiers contain spaces. Please clean the input genome.")
    # The default matrix: metacool from MANY_CONTIGS contigs, unless binned,
    # which the cool matrix only is; cool otherwise.
    default_fmt = mat_fmt is None
    if default_fmt:
        mat_fmt = "metacool" if n_contigs >= MANY_CONTIGS and binning == 0 else "cool"
    if default_fmt and mat_fmt == "metacool":
        logger.warning(
            f"{n_contigs:,} contigs in the matrix: it will be a metacool matrix, written with "
            "metacooler, rather than a cool matrix, which cooler is slow to write with this many "
            f"contigs ({_SLOW_COOL}). --matrix cool writes the cool matrix all the same."
        )
    elif mat_fmt == "cool" and n_contigs >= MANY_CONTIGS:
        logger.warning(
            f"{n_contigs:,} contigs in the cool matrix: it will be slow to write ({_SLOW_COOL}). "
            "--matrix metacool writes it with metacooler, which does not pay that time, with one "
            "bin per fragment; --matrix none ends the run with its pairs file; --matrix bg2 and "
            "graal write a text matrix."
        )
    if mat_fmt == "cool":
        logger.info(
            "The default output format is now `.cool`. The Hi-C "
            "matrix will be generated with cooler v%s "
            "(Abdennur & Mirny, Bioinformatics 2020).",
            cooler.__version__,
        )
    elif mat_fmt == "metacool":
        logger.info(
            "The Hi-C matrix will be generated with metacooler v%s.", metacooler.__version__
        )

    # A fasta file without bowtie2 or bwa index is indexed in genome_dir when
    # reads are aligned, read where it is, plain or compressed. pybwa indexes
    # it when it loads it, below.
    index = idx
    if idx is None and start_stage == 0:
        if aligner == "bwa" and os.path.isfile(genome + ".bwt.2bit.64"):
            logger.warning(
                "Found a bwa-mem2 index at %s, which bwa and pybwa cannot read: "
                "a bwa index is built instead.",
                genome,
            )
        if backend != "python":
            index = join(genome_dir, "genome")
            logger.info(
                "%s index not found at %s, building a temporary one in %s.",
                aligner,
                genome,
                genome_dir,
            )
            if aligner == "bowtie2":
                sp.run(["bowtie2-build", "-q", fasta, index], stderr=sp.PIPE)
            else:
                sp.run(["bwa", "index", "-p", index, fasta], stderr=sp.PIPE)

    # Define output file names (tsv files)
    if prefix:
        fragments_list = _out_file("frags.tsv")
        info_contigs = _out_file("chr.tsv")
        if mat_fmt != "none":
            mat = _out_file("mat.tsv")
        # If matrix has a different format, give it the right extension
        if mat_fmt not in ("graal", "none"):
            mat = _out_file(mat_fmt)
    else:
        # Default graal file names
        fragments_list = _out_file("fragments_list.txt")
        info_contigs = _out_file("info_contigs.txt")
        if mat_fmt != "none":
            mat = _out_file("abs_fragments_contacts_weighted.txt")
        if mat_fmt not in ("graal", "none"):
            mat = _out_file("abs_fragments_contacts_weighted." + mat_fmt)
    # Define what input files are given
    if start_stage == 0:
        reads1, reads2 = for_files[0], rev_files[0]
    elif start_stage == 1:
        bam1, bam2 = input1, input2
    elif start_stage == 2:
        pairs = input1
    elif start_stage == 3:
        pairs_idx = input1

    # Perform genome alignment
    nreads_input1 = 0
    if start_stage == 0:
        if skip_count:
            logger.info("Skipping read count check (--skip-count).")
        else:
            # Check number of reads in both fastqs, of each pair of files
            logger.info("Checking content of fastq files.")
            nreads_input2 = 0
            counts_differ = False
            for fq1, fq2 in zip(for_files, rev_files):
                nreads1 = hio.check_fastq_entries(fq1, threads)
                nreads2 = hio.check_fastq_entries(fq2, threads)
                nreads_input1 += nreads1
                nreads_input2 += nreads2
                counts_differ = counts_differ or nreads1 != nreads2
                if several_pairs and nreads1 != nreads2:
                    logger.error(
                        "Fastq files %s and %s do not have the same number of reads: %d and %d.",
                        fq1,
                        fq2,
                        nreads1,
                        nreads2,
                    )
                elif several_pairs:
                    logger.info("%d reads in each of %s and %s.", nreads1, fq1, fq2)
            if counts_differ:
                logger.error("Fastq files do not have the same number of reads.")
            else:
                logger.info(f"{int(nreads_input1)} reads found in each fastq file.")

        if several_pairs:
            logger.info(
                "Concatenating %d pairs of fastq files into %s and %s.",
                len(for_files),
                *reads_cat,
            )
            for files, out in zip((for_files, rev_files), reads_cat):
                concatenate_fastq(files, out)
            reads1, reads2 = reads_cat

        # Define mapping choice (default normal):
        if mapping == "normal":
            iterative = False
        elif mapping == "iterative":
            iterative = True
        elif mapping == "cutsite":
            # If no enzyme given use iterative alignment.
            try:
                int(enzyme)
                logger.warning(
                    "No enzyme has been given. Can't map using cutsite, iterative mapping will be used instead."
                )
                iterative = True
            # If cutsite enabled and enzyme given, cut the reads before making a
            # normal alignment.
            except ValueError:
                iterative = False
                digest_for = _tmp_file("digest_for.fq.gz")
                digest_rev = _tmp_file("digest_rev.fq.gz")
                hcc.cut_ligation_sites(
                    fq_for=reads1,
                    fq_rev=reads2,
                    digest_for=digest_for,
                    digest_rev=digest_rev,
                    enzyme=enzyme,
                    mode="for_vs_rev",
                    seed_size=20,
                    n_cpu=threads,
                )
                reads1, reads2 = digest_for, digest_rev
        elif mapping != "5spm":
            logger.error("mapping must be either normal, iterative, cutsite or 5spm.")
            raise ValueError

        # bwa in-process loads the index once, for both mates, and builds it
        # from the fasta if there is none
        if backend == "python":
            logger.info("Aligning with %s.", hbm.describe(backend, five_spm=mapping == "5spm"))
            index = hbm.load_index(fasta if index is None else index, genome_dir)
        if mapping == "5spm":
            logger.info("Now mapping R1 and R2 reads with bwa mem -5SPM...")
            hbm.align_pairs(
                reads1, reads2, index, bam1, bam2, threads=threads, backend=backend, tmp_dir=tmp_dir
            )
        else:
            logger.info("Now separately mapping R1 and R2 reads...")
            for reads, bam in ((reads1, bam1), (reads2, bam2)):
                align_reads(
                    reads,
                    index,
                    bam,
                    tmp_dir=tmp_dir,
                    threads=threads,
                    aligner=aligner,
                    iterative=iterative,
                    min_qual=min_qual,
                    read_len=read_len,
                    backend=backend,
                )

    # Detect if multiple enzymes are given
    if re.search(",", enzyme):
        enzyme = enzyme.split(",")

    # Starting from bam files
    if start_stage <= 1:
        # Check number of reads in both fastqs
        if bam1 == input1:
            logger.info("Checking content of bam files.")
            nreads_input1 = hio.check_bam_entries(bam1)
            nreads_input2 = hio.check_bam_entries(bam2)
            if nreads_input1 != nreads_input2:
                logger.error("Bam files do not have the same number of reads.")
            else:
                logger.info(f"{nreads_input1} reads found in each bam file.")

        fragments_updated = True
        # Generate info_contigs and fragments_list output files
        hcd.write_frag_info(
            fasta,
            enzyme,
            min_size=min_size,
            circular=circular,
            output_contigs=info_contigs,
            output_frags=fragments_list,
        )

        # Log fragment size distribution
        hcd.frag_len(frags_file_name=fragments_list, plot=plot, fig_path=frag_plot)

        # Make pairs file (readID, chr1, chr2, pos1, pos2, strand1, strand2).
        # Mode 5spm records the mates' aligned 5' ends.
        bam2pairs(
            bam1,
            bam2,
            pairs,
            info_contigs,
            min_qual=min_qual,
            tmp_dir=tmp_dir,
            threads=threads,
            five_prime=mapping == "5spm",
        )

    # Pairs with a mate on a contig shorter than min_size, which has no
    # fragment in the fragments list
    small_contig_pairs = 0
    # Starting from pairs file
    if start_stage <= 2:
        restrict_table = {}
        for record in SeqIO.parse(hio.read_compressed(fasta), "fasta"):
            # Get chromosome restriction table
            restrict_table[record.id] = hcd.get_restriction_table(
                record.seq, enzyme, circular=circular
            )

        # Add fragment index to pairs (readID, chr1, pos1, chr2,
        # pos2, strand1, strand2, frag1, frag2), without the pairs on contigs
        # shorter than min_size
        small_contig_pairs = hcd.attribute_fragments(
            pairs, pairs_idx, restrict_table, min_size=min_size
        )

    # Sort pairs file by coordinates (and strands, for PCR duplicate removal)
    # for next steps
    hio.sort_pairs(
        pairs_idx,
        pairs_idx + ".sorted",
        keys=COORD_SORT_KEYS,
        threads=threads,
        tmp_dir=tmp_dir,
    )
    os.rename(pairs_idx + ".sorted", pairs_idx)

    # Count total pairs, including those discarded on small contigs
    tot_pairs = small_contig_pairs
    with open(pairs_idx) as file:
        for line in file:
            if line.startswith("#"):
                continue
            else:
                tot_pairs += 1
    if nreads_input1 != 0:
        logger.info(
            f"{tot_pairs} pairs successfully mapped ({round(100 * tot_pairs / (nreads_input1), 2)}%)"
        )
    else:
        logger.info(f"{tot_pairs} pairs successfully mapped")

    # Filter pairs if requested
    if filter_events:
        uncut_thr, loop_thr = hcf.get_thresholds(
            pairs_idx, plot_events=plot, fig_path=dist_plot, prefix=prefix
        )
        hcf.filter_events(
            pairs_idx,
            pairs_filtered,
            uncut_thr,
            loop_thr,
            plot_events=plot,
            fig_path=pie_plot,
            prefix=prefix,
        )
        use_pairs = pairs_filtered
    else:
        use_pairs = pairs_idx

    # Generate fragments file if it has not been already
    if not fragments_updated:
        hcd.write_frag_info(
            fasta,
            enzyme,
            min_size=min_size,
            circular=circular,
            output_contigs=info_contigs,
            output_frags=fragments_list,
        )

    # Generate distance law table if enabled
    if distance_law:
        out_distance_law = _out_file("distance_law.txt")
        if remove_centros is None:
            remove_centros = 0
        remove_centros = int(remove_centros)
        x_s, p_s, _ = hcdl.get_distance_law(
            pairs_idx,
            fragments_list,
            centro_file=centromeres,
            base=1.1,
            out_file=out_distance_law,
            circular=circular,
            rm_centro=remove_centros,
        )
        # Generate distance law figure is plots are enabled
        if plot:
            # Retrieve chrom labels from distance law file
            _, _, chr_labels = hcdl.import_distance_law(out_distance_law)
            chr_labels = [lab[0] for lab in chr_labels]
            chr_labels_idx = np.unique(chr_labels, return_index=True)[1]
            chr_labels = [chr_labels[index] for index in sorted(chr_labels_idx)]
            p_s = hcdl.normalize_distance_law(x_s, p_s)
            hcdl.plot_ps_slope(x_s, p_s, labels=chr_labels, fig_path=distance_law_plot)

    # Filter out PCR duplicates if requested
    if pcr_duplicates:
        filter_pcr_dup(use_pairs, pairs_pcr)
        use_pairs = pairs_pcr

    # Build matrix from pairs.
    if mat_fmt in ("cool", "metacool"):
        # Log which pairs file is being used and how many pairs are listed
        pairs_count = 0
        with open(use_pairs) as file:
            for line in file:
                if line.startswith("#"):
                    continue
                else:
                    pairs_count += 1
        logger.info(
            "Generating matrix from pairs file %s (%d pairs in the file) ",
            use_pairs,
            pairs_count,
        )

    if mat_fmt == "metacool":
        pairs2metacool(use_pairs, mat, fragments_list, exclude, threads=threads, cmd=cmd)
    elif mat_fmt == "cool":
        # Name matrix file in .cool
        mat = os.path.splitext(mat)[0] + ".cool"

        # If binning is **not** set, parse the pairs into a **un-binned** cool
        if binning == 0:
            ## THIS NEEDS TO BE FIXED AT SOME POINT
            pairs2cool(use_pairs, mat, fragments_list, exclude)

        # If binning is set, proceed to bin the pairs instead
        else:
            cool_file = os.path.splitext(mat)[0] + ".cool"
            pairs2binnedcool(use_pairs, cool_file, binning, info_contigs, exclude)
            mat = cool_file

            # If zoomify == True, zoomify binned cool
            if zoomify:
                mcool_file = os.path.splitext(mat)[0] + ".mcool"
                cool2mcool(mat, mcool_file)
                mat = mcool_file

            # Balance binned matrix
            balance(mat, balancing_args, threads=threads)
    elif mat_fmt == "none":
        logger.info("No matrix (--matrix none): the run ends with its pairs file.")
    else:
        pairs2matrix(
            use_pairs,
            mat,
            fragments_list,
            mat_fmt=mat_fmt,
            threads=threads,
            tmp_dir=tmp_dir,
        )

    # Get stats on the pipeline
    try:
        logger.info("Fetching mapping and pairing stats")
        stats = hcs.get_pipeline_stats(log_file)
        logger.info(stats)
    except IndexError:
        logger.warning("IndexError. Stats not compiled.")
        pass

    # Move final pairs file to main dir.
    p = pathlib.Path(use_pairs).absolute()
    out_dir_abs = pathlib.Path(out_dir).absolute()
    pairsf = out_dir_abs / p.name
    # The final pairs are the input file itself when starting from indexed
    # pairs without filtering: it must be neither moved nor deleted.
    is_input = p == pathlib.Path(input1).absolute()
    # The file may already be in out_dir, even when named through another
    # path (tmp_dir == out_dir, a symbolic link to out_dir).
    in_out_dir = pairsf.exists() and os.path.samefile(p, pairsf)
    # Only rename (move) a temporary file; otherwise copy, unless the file
    # is already in out_dir.
    if not in_out_dir:
        if p.parent == out_dir_abs / "tmp" and not is_input:
            p.rename(pairsf)
        else:
            st.copy2(str(p), str(pairsf))

    # Sort and compress final pairs file
    sort_and_compress_pairs(str(pairsf), str(pairsf) + ".gz", tmp_dir=tmp_dir, threads=threads)
    if not (is_input and in_out_dir):
        os.remove(pairsf)

    # Clean temporary files
    if not no_cleanup:
        tempfiles = [
            pairs,
            pairs_idx,
            pairs_filtered,
            pairs_pcr,
            bam1,
            bam2,
            # The concatenated fastq files of several pairs of files
            *reads_cat,
        ]
        # The genome sequence and the index this run wrote, if any
        if genome_dir is not None:
            st.rmtree(genome_dir)
        # Do not delete files that were given as input
        try:
            tempfiles.remove(input1)
            tempfiles.remove(input2)
        except ValueError:
            pass

        # Delete single-resolution matrix if `--zoomify` is set
        if binning > 0 and zoomify:
            try:
                tempfiles.append(cool_file)
            except ValueError:
                pass

        # Remove the rest of tempfiles
        for file in tempfiles:
            try:
                os.remove(file)
            except FileNotFoundError:
                pass

    end_time = datetime.now()
    duration = relativedelta(end_time, start_time)
    made = "Pairs" if mat_fmt == "none" else "Contact map"
    logger.info(f"{made} generated after {duration.hours}h {duration.minutes}m {duration.seconds}s")

hicstuff.stats

get_pipeline_stats

get_pipeline_stats(log_file)

Get stats after pipeline execution.

Parameters:

Name Type Description Default
log_file str

Path to hicstuff log file.

required

Returns:

Name Type Description
list

A single list containing stats about hicstuff pipeline execution: - Number of sequenced pairs from fastqs - Number (% of total reads) of unmapped reads - Number (% of total reads) of mapped reads - Number (% of total reads) of pairs - Number (% of total pairs) of pairs on contigs shorter than the minimum size - Number (% of total pairs) of filtered pairs - Number (% of total pairs) of loops - Number (% of total pairs) of uncuts - Number (% of total pairs) of abnormal (-- and ++) - Number (% of total pairs) of deduplicated pairs [Number (% of total pairs) of PCR duplicates] - From all pairs used in contact matrix: - Number (% of matrix) of cis pairs - Number (% of matrix) of trans pairs - Trans ratio

Source code in src/hicstuff/stats.py
def get_pipeline_stats(log_file):
    """Get stats after pipeline execution.

    Parameters
    ----------
    log_file : str
        Path to hicstuff log file.

    Returns
    -------
    list:
        A single list containing stats about hicstuff pipeline execution:
        - Number of sequenced pairs from fastqs
        - Number (% of total reads) of unmapped reads
        - Number (% of total reads) of mapped reads
        - Number (% of total reads) of pairs
        - Number (% of total pairs) of pairs on contigs shorter than the
          minimum size
        - Number (% of total pairs) of filtered pairs
            - Number (% of total pairs) of loops
            - Number (% of total pairs) of uncuts
            - Number (% of total pairs) of abnormal (-- and ++)
        - Number (% of total pairs) of deduplicated pairs [Number (% of total pairs) of PCR duplicates]
        - From all pairs used in contact matrix:
            - Number (% of matrix) of cis pairs
            - Number (% of matrix) of trans pairs
            - Trans ratio
    """

    with open(log_file) as file:
        log_lines = [line.rstrip() for line in file]

    # 1. Number (% of total) of (un)mapped reads, as aligned (after digestion
    # at ligation sites in cutsite mode)
    mapping = _search(r"mapped with Q >= \d+ \((\d+)/(\d+)\)", log_lines)
    if mapping is None:
        raise IndexError(f"No read mapping statistics found in {log_file}.")
    tot_mapped, tot_reads = int(mapping[1]), int(mapping[2])
    tot_unmapped = tot_reads - tot_mapped

    # 2. Number of sequenced pairs, logged when counting the input reads,
    # before digesting them at ligation sites (cutsite mode) or by iterative
    # alignment. Without any of them (--skip-count), half the aligned reads.
    for pattern in (
        r"(\d+) reads found in each (?:fastq|bam) file",
        r"Number of pairs before digestion: (\d+)",
        r"(\d+) reads to parse",
    ):
        count = _search(pattern, log_lines)
        if count is not None:
            fastq_pairs = int(count[1])
            break
    else:
        fastq_pairs = tot_reads // 2

    # 3. Number (% of total) of pairs
    tot_pairs = [s for s in log_lines if re.search("pairs successfully mapped", s)][0]
    tot_pairs = re.sub(".*INFO :: ", "", tot_pairs)
    tot_pairs = re.sub(" pairs successfully.*", "", tot_pairs)
    tot_pairs = int(float(tot_pairs))

    # 4. Number (% of total) of pairs on contigs shorter than the minimum size
    small_contigs = _search(r"(\d+) pairs with a mate on a contig shorter than", log_lines)
    small_pairs = 0 if small_contigs is None else int(small_contigs[1])

    # 5. Number (% of total) of filtered pairs
    filtered_pairs = [s for s in log_lines if re.search("pairs discarded:", s)]
    if len(filtered_pairs) > 0:
        filtered_pairs = filtered_pairs[0]
        loops_pairs = re.sub(".*Loops: ", "", filtered_pairs)
        loops_pairs = re.sub(", Uncuts:.*", "", loops_pairs)
        loops_pairs = int(float(loops_pairs))
        uncuts_pairs = re.sub(".*Uncuts: ", "", filtered_pairs)
        uncuts_pairs = re.sub(", Weirds:.*", "", uncuts_pairs)
        uncuts_pairs = int(float(uncuts_pairs))
        abnormal_pairs = re.sub(".*Weirds: ", "", filtered_pairs)
        abnormal_pairs = int(float(abnormal_pairs))
        filtered_pairs = re.sub(".*INFO :: ", "", filtered_pairs)
        filtered_pairs = re.sub(" pairs discarded.*", "", filtered_pairs)
        filtered_pairs = int(float(filtered_pairs))
    else:
        loops_pairs = 0
        uncuts_pairs = 0
        abnormal_pairs = 0
        filtered_pairs = 0

    # 6. Number (% of total) of PCR duplicates pairs
    pcr_pairs = [s for s in log_lines if re.search("PCR duplicates have been filtered", s)]
    if len(pcr_pairs) > 0:
        pcr_pairs = pcr_pairs[0]
        pcr_pairs = re.sub(r".*have been filtered out \(", "", pcr_pairs)
        pcr_pairs = re.sub(r"/.*", "", pcr_pairs)
        pcr_pairs = int(float(pcr_pairs))
    else:
        pcr_pairs = 0

    # 7. Number (%) of final pairs
    removed_pairs = small_pairs + filtered_pairs + pcr_pairs
    final_pairs = tot_pairs - removed_pairs

    # 8. Final stats
    stats = {
        "Sample": re.sub(".hicstuff.*", "", basename(log_file)),
        "Total read pairs": fastq_pairs,
        "Mapped reads": tot_mapped,
        "Unmapped reads": tot_unmapped,
        "Recovered contacts": tot_pairs,
        "Final contacts": final_pairs,
        "Removed contacts": removed_pairs,
        "Small contigs": small_pairs,
        "Filtered out": filtered_pairs,
        "Loops": loops_pairs,
        "Uncuts": uncuts_pairs,
        "Weirds": abnormal_pairs,
        "PCR duplicates": pcr_pairs,
    }

    return stats

hicstuff.log

Basic logging

Basic logging setup with two handlers (standard error and log file). By default the log file is disabled, but can be enabled or changed using set_file_handler.

remove_file_handler

remove_file_handler()

Detach and close the log file handler set by set_file_handler, if any. Other handlers of the logger are left alone.

Source code in src/hicstuff/log.py
def remove_file_handler():
    """Detach and close the log file handler set by set_file_handler, if
    any. Other handlers of the logger are left alone."""
    global _file_handler
    if _file_handler is not None:
        logger.removeHandler(_file_handler)
        _file_handler.close()
        _file_handler = None

set_file_handler

set_file_handler(log_path, formatter=logfile_formatter)

Change the file handler for custom log file location

The handler set by a previous call is replaced. File handlers attached to the logger by other code (an application, pytest) are left alone.

Source code in src/hicstuff/log.py
def set_file_handler(log_path, formatter=logfile_formatter):
    """Change the file handler for custom log file location

    The handler set by a previous call is replaced. File handlers attached
    to the logger by other code (an application, pytest) are left alone.
    """
    global _file_handler
    filehandler = logging.FileHandler(log_path, "a")
    filehandler.setLevel(logging.INFO)
    filehandler.setFormatter(formatter)
    remove_file_handler()
    _file_handler = filehandler
    logger.addHandler(filehandler)  # set the new handler