Skip to content

Alignment

Three modules align reads: hicstuff.iteralign truncates and extends them (mapping mode iterative), hicstuff.cutsite cuts them at their ligation sites (mapping mode cutsite), and hicstuff.bwamem runs bwa, as a program or in-process through pybwa. See Aligning reads.

hicstuff.iteralign

Iterative alignment

Aligns iteratively reads from a 3C fastq file: reads are trimmed with a range-sweeping number of basepairs and each read set generated this way is mapped onto the reference genome. This may result in a small increase of properly mapped reads.

@author: Remi Montagne & cmdoret

iterative_align

iterative_align(fq_in, tmp_dir, ref, n_cpu, bam_out, aligner='bowtie2', min_len=20, min_qual=30, read_len=None, backend=None)

Iterative alignment

Aligns reads iteratively reads of fq_in with bowtie2, minimap2 or bwa. Reads are truncated to the 20 first nucleotides and unmapped reads are extended by 20 nucleotides and realigned on each iteration.

Parameters:

Name Type Description Default
fq_in str

Path to input fastq file to align iteratively.

required
tmp_dir str

Path where temporary files should be written.

required
ref str

Path to the reference genome if Minimap2 is used for alignment. Path to the index genome if Bowtie2/bwa is used for alignment.

required
n_cpu int

The number of CPUs to use for the iterative alignment.

required
bam_out str

Path where the final alignment should be written in BAM format.

required
aligner str

Choose between minimap2, bwa or bowtie2 for the alignment.

'bowtie2'
min_len int

The initial length of the fragments to align.

20
min_qual int

Minimum mapping quality required to keep Hi-C pairs.

30
read_len int

Read length in the fasta file. If set to None, the length of the first read is used. Set this value to the longest read length in the file if you have 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. In-process, the rounds run in memory, without temporary files.

None

Examples:

iterative_align(fq_in='example_for.fastq', ref='example_bt2_index', bam_out='example_for.bam', aligner="bowtie2") iterative_align(fq_in='example_for.fastq', ref='example_genome.fa', bam_out='example_for.bam', aligner="minimap2")

Source code in src/hicstuff/iteralign.py
def iterative_align(
    fq_in,
    tmp_dir,
    ref,
    n_cpu,
    bam_out,
    aligner="bowtie2",
    min_len=20,
    min_qual=30,
    read_len=None,
    backend=None,
):
    """Iterative alignment

    Aligns reads iteratively reads of fq_in with bowtie2, minimap2 or bwa. Reads are
    truncated to the 20 first nucleotides and unmapped reads are extended by 20
    nucleotides and realigned on each iteration.

    Parameters
    ----------

    fq_in : str
        Path to input fastq file to align iteratively.
    tmp_dir : str
        Path where temporary files should be written.
    ref : str
        Path to the reference genome if Minimap2 is used for alignment.
        Path to the index genome if Bowtie2/bwa is used for alignment.
    n_cpu : int
        The number of CPUs to use for the iterative alignment.
    bam_out : str
        Path where the final alignment should be written in BAM format.
    aligner : str
        Choose between minimap2, bwa or bowtie2 for the alignment.
    min_len : int
        The initial length of the fragments to align.
    min_qual : int
        Minimum mapping quality required to keep Hi-C pairs.
    read_len : int
        Read length in the fasta file. If set to None, the length of the first read
        is used. Set this value to the longest read length in the file if you have
        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. In-process,
        the rounds run in memory, without temporary files.

    Examples
    --------

    iterative_align(fq_in='example_for.fastq', ref='example_bt2_index', bam_out='example_for.bam', aligner="bowtie2")
    iterative_align(fq_in='example_for.fastq', ref='example_genome.fa', bam_out='example_for.bam', aligner="minimap2")
    """
    # The aligner program that maps the truncated reads: an unknown aligner
    # is refused when mapping.
    program = _aligner_program(aligner)
    if program == "bwa" and hbm.resolve_backend(backend) == "python":
        index = hio.check_fasta_index(ref, mode="bwa")
        if index is None:
            logger.error(f"Reference index is missing, please build the {aligner} index first.")
            sys.exit(1)
        with hbm.loaded_index(index, tmp_dir) as loaded:
            hbm.iterative_align(
                fq_in,
                loaded,
                bam_out,
                threads=int(n_cpu),
                min_len=min_len,
                min_qual=min_qual,
                read_len=read_len,
            )
        return 0
    if program is not None:
        hio.require_tools([program], "for iterative alignment")

    # set with the name of the unaligned reads :
    remaining_reads = set()
    total_reads = 0
    # Store path of SAM containing aligned reads at each iteration.
    iter_out = []

    # If there is already a file with the same name as the output file,
    # remove it. Otherwise, ignore.
    with contextlib.suppress(FileNotFoundError):
        try:
            os.remove(bam_out)
        except IsADirectoryError:
            logger.error("You need to give the BAM output file, not a folder.")
            raise

    # Bowtie only accepts uncompressed fastq: uncompress it into a temp file
    if program == "bowtie2" and hio.is_compressed(fq_in):
        uncomp_path = join(tmp_dir, os.path.basename(fq_in) + ".tmp")
        with hio.read_compressed(fq_in) as inf:
            with open(uncomp_path, "w") as uncomp:
                st.copyfileobj(inf, uncomp)
    else:
        uncomp_path = fq_in

    # throw error if index does not exist
    index = hio.check_fasta_index(ref, mode=program)
    if index is None:
        logger.error(f"Reference index is missing, please build the {aligner} index first.")
        sys.exit(1)
    # Counting reads
    with hio.read_compressed(uncomp_path) as inf:
        for _ in inf:
            total_reads += 1
    total_reads /= 4

    # Use first read to guess read length if not provided.
    if read_len is None:
        with hio.read_compressed(uncomp_path) as inf:
            # Skip first line (read header)
            inf.readline()
            # Stripping newline from sequence line.
            read_len = len(inf.readline().rstrip())

    # initial length of the fragments to align
    # In case reads are shorter than provided min_len
    if read_len > min_len:
        n = min_len
    else:
        logger.warning("min_len is longer than the reads. Iterative mapping will have no effect.")
        n = read_len
    logger.info(f"{int(total_reads)} reads to parse")

    first_round = True
    # iterative alignment per se
    while n <= read_len:
        logger.info(
            "Truncating unaligned reads to {size}bp and mapping{again}.".format(
                size=int(n), again="" if first_round else " again"
            )
        )
        iter_out += [join(tmp_dir, f"trunc_{str(n)}.bam")]
        # Generate a temporary input fastq file with the n first nucleotids
        # of the reads.
        truncated_reads = _truncate_reads(tmp_dir, uncomp_path, remaining_reads, n, first_round)

        # Align the truncated reads on reference genome
        temp_alignment = join(tmp_dir, "temp_alignment.bam")
        map_args = {
            "fa": ref,
            "cpus": n_cpu,
            "fq": truncated_reads,
            "idx": index,
            "bam": temp_alignment,
        }
        if program == "minimap2":
            cmd = "minimap2 -x sr -a -t {cpus} {fa} {fq}".format(**map_args)
        elif program == "bwa":
            cmd = "bwa mem -t {cpus} -v 1 {idx} {fq}".format(**map_args)
        elif program == "bowtie2":
            cmd = ("bowtie2 -x {idx} -p {cpus} --quiet --very-sensitive-local -U {fq}").format(
                **map_args
            )
        else:
            raise ValueError("Unknown aligner. Select bowtie2, minimap2 or bwa.")

        map_process = sp.Popen(cmd, shell=True, stdout=sp.PIPE)
        hio.samtools_pipe(
            ["sort", "-n", "-@", n_cpu, "-O", "BAM", "-o", temp_alignment],
            stdin=map_process.stdout,
        )
        map_process.wait()

        # filter the reads: the reads whose truncated end was aligned are written
        # to the output file.
        # The reads whose truncated end was not aligned are kept for the next round.
        remaining_reads = _filter_bamfile(temp_alignment, iter_out[-1], min_qual)

        n += 20
        first_round = False

    # one last round without trimming
    logger.info(f"Trying to map unaligned reads at full length ({int(read_len)}bp).")

    truncated_reads = _truncate_reads(
        tmp_dir,
        infile=uncomp_path,
        unaligned_set=remaining_reads,
        trunc_len=n,
        first_round=first_round,
    )
    # The same aligner as the truncated rounds, whatever name it was given by
    if program == "minimap2":
        cmd = f"minimap2 -x sr -a -t {n_cpu} {ref} {truncated_reads}"
    elif program == "bwa":
        cmd = f"bwa mem -v 1 -t {n_cpu} {index} {truncated_reads}"
    else:
        cmd = f"bowtie2 -x {index} -p {n_cpu} --quiet --very-sensitive {truncated_reads}"
    map_process = sp.Popen(cmd, shell=True, stdout=sp.PIPE)
    # Keep reads sorted by name
    hio.samtools_pipe(
        ["sort", "-n", "-@", n_cpu, "-O", "BAM", "-o", temp_alignment],
        stdin=map_process.stdout,
    )
    map_process.wait()
    iter_out += [join(tmp_dir, f"trunc_{str(n)}.bam")]
    remaining_reads = _filter_bamfile(temp_alignment, iter_out[-1], min_qual)

    # Report unaligned reads as well
    iter_out += [join(tmp_dir, "unaligned.bam")]
    temp_bam = ps.AlignmentFile(temp_alignment, "rb", check_sq=False)
    unmapped = ps.AlignmentFile(iter_out[-1], "wb", template=temp_bam)
    for r in temp_bam:
        # Only write primary records (keeping 1 alignment/read)
        if r.query_name in remaining_reads and _is_primary(r):
            unmapped.write(r)
    unmapped.close()
    temp_bam.close()

    # Merge all aligned reads and unmapped reads into a single bam
    ps.merge("-n", "-O", "BAM", "-@", str(n_cpu), bam_out, *iter_out)
    logger.info(
        f"{int(total_reads - len(remaining_reads))} reads aligned / {int(total_reads)} total reads."
    )

    return 0

hicstuff.cutsite

Cut the reads at their ligation sites.

The module will cut at ligation sites of the given enzyme. It will from the original fastq (gzipped or not) files create new gzipped fastq files with combinations of the fragments of reads obtains by cutting at the ligation sites of the reads.

There are three choices to how combine the fragments:

  1. "for_vs_rev": All the combinations are made between one forward fragment and one reverse fragment. It's the most releveant one for usual workflow.
  2. "all": All 2-combinations are made.
  3. "pile": Only combinations between adjacent fragments in the initial reads are made.

This module contains the following functions:

  • cut_ligation_sites
  • cutsite_read
  • write_pair

cut_ligation_sites

cut_ligation_sites(fq_for, fq_rev, digest_for, digest_rev, enzyme, mode, seed_size, n_cpu)

Create new reads to manage pairs with a digestion and create multiple pairs to take into account all the contact present.

The function write two files for both the forward and reverse fastq with the new reads. The new reads have at the end of the ID ":[0-9]" added to differentiate the different pairs created from one read.

The function will look for all the sites present and create new pairs of reads according to the mode given to retreive as much as possible of the HiC signal.

Parameters:

Name Type Description Default
fq_for str

Path to the forward fastq file to digest.

required
fq_rev str

Path to the reverse fatsq file to digest.

required
digest_for str

Path to the output digested forward fatsq file to write.

required
digest_rev str

Path to the output digested reverse fatsq file to write.

required
enzyme str

The list of restriction enzyme used to digest the genome separated by a comma. Example: HpaII,MluCI.

required
mode str

Mode to use to make the digestion. Three values possible: "all", "for_vs_rev", "pile".

required
seed_size int

Minimum size of a fragment (i.e. seed size used in mapping as reads smaller won't be mapped.)

required
n_cpu int

Number of CPUs.

required
Source code in src/hicstuff/cutsite.py
def cut_ligation_sites(fq_for, fq_rev, digest_for, digest_rev, enzyme, mode, seed_size, n_cpu):
    """Create new reads to manage pairs with a digestion and create multiple
    pairs to take into account all the contact present.

    The function write two files for both the forward and reverse fastq with the
    new reads. The new reads have at the end of the ID ":[0-9]" added to
    differentiate the different pairs created from one read.

    The function will look for all the sites present and create new pairs of
    reads according to the mode given to retreive as much as possible of the HiC
    signal.

    Parameters
    ----------
    fq_for : str
        Path to the forward fastq file to digest.
    fq_rev : str
        Path to the reverse fatsq file to digest.
    digest_for : str
        Path to the output digested forward fatsq file to write.
    digest_rev : str
        Path to the output digested reverse fatsq file to write.
    enzyme : str
        The list of restriction enzyme used to digest the genome separated by a
        comma. Example: HpaII,MluCI.
    mode : str
        Mode to use to make the digestion. Three values possible: "all",
        "for_vs_rev", "pile".
    seed_size : int
        Minimum size of a fragment (i.e. seed size used in mapping as reads
        smaller won't be mapped.)
    n_cpu : int
        Number of CPUs.
    """
    # Process the ligation sites given
    ligation_sites = hcd.gen_enzyme_religation_regex(enzyme)

    # Defined stop_token which is used to mark the end of input file
    stop_token = "STOP"
    # A stack is a string cointaining multiple read pairs
    max_stack_size = 1000

    # Compress and write the new reads in a thread while this one cuts them:
    # zlib releases the GIL while it compresses. Unlike a process, a thread
    # needs no `if __name__ == "__main__":` guard in the scripts calling
    # hicstuff where processes are spawned (macOS, Python >= 3.14).
    queue = queues.Queue(max(1, n_cpu - 1))
    writer_errors = []
    writer = threading.Thread(
        target=_writer, args=(digest_for, digest_rev, queue, stop_token, writer_errors)
    )
    writer.start()
    try:
        original_number_of_pairs, final_number_of_pairs = _cut_pairs(
            fq_for, fq_rev, ligation_sites, mode, seed_size, queue, max_stack_size
        )
    finally:
        # Also on error, so that the writer thread ends
        queue.put(stop_token)
        writer.join()
    if writer_errors:
        raise writer_errors[0]

    # Return information on the different pairs created
    logger.info(f"Library used: {fq_for} - {fq_rev}")
    logger.info(f"Number of pairs before digestion: {original_number_of_pairs}")
    logger.info(f"Number of pairs after digestion: {final_number_of_pairs}")

cutsite_read

cutsite_read(ligation_sites, seq, qual, seed_size=0)

Find ligation sites in a given sequence and return list of the fragmented sequence and quality.

Parameters:

ligation_sites : re.Pattern Regex of all possible ligations according to the given enzymes. seq : str Sequence where to search for ligation_sites. qual : str Quality values of the sequence given. seed_size : int Minimum size of a fragment (i.e. seed size used in mapping as reads smaller won't be mapped.)

Returns:

list of str List of cut sequences. The split is made 4 bases after the start of the ligation site. list of str List of string of the qualities.

Examples:

cutsite_read(re.compile(r'GA.TA.TC'), "AAGAGTATTC", "FFF--FAFAF") (['AAGAGT', 'ATTC'], ['FFF--F', 'AFAF'])

Source code in src/hicstuff/cutsite.py
def cutsite_read(ligation_sites, seq, qual, seed_size=0):
    """Find ligation sites in a given sequence and return list of the fragmented
    sequence and quality.

    Parameters:
    -----------
    ligation_sites : re.Pattern
        Regex of all possible ligations according to the given enzymes.
    seq : str
        Sequence where to search for ligation_sites.
    qual : str
        Quality values of the sequence given.
    seed_size : int
        Minimum size of a fragment (i.e. seed size used in mapping as reads
        smaller won't be mapped.)

    Returns:
    --------
    list of str
        List of cut sequences. The split is made 4 bases after the start of
        the ligation site.
    list of str
        List of string of the qualities.

    Examples:
    ---------
    >>> cutsite_read(re.compile(r'GA.TA.TC'), "AAGAGTATTC", "FFF--FAFAF")
    (['AAGAGT', 'ATTC'], ['FFF--F', 'AFAF'])
    """

    # Find the ligation sites.
    ligation_sites_list = []
    if ligation_sites.search(seq):
        ligation_sites_list = [site.start() for site in ligation_sites.finditer(seq)]
    ligation_sites_list.append(len(seq))

    # Split the sequences on the ligation sites.
    seq_list = []
    qual_list = []
    left_site = 0
    for right_site in ligation_sites_list:
        if right_site + 4 - left_site > seed_size:
            seq_list.append(seq[left_site : right_site + 4])
            qual_list.append(qual[left_site : right_site + 4])
            left_site = right_site + 4

    return seq_list, qual_list

write_pair

write_pair(new_reads_for, new_reads_rev, name, for_seq_list, for_qual_list, rev_seq_list, rev_qual_list, mode, final_number_of_pairs)

Function to write one pair with the combinations of fragment depending on the chosen mode.

Parameters:

new_reads_for : str Stack of the new forward reads ready to be written. new_reads_rev : str Stack of the new reverse reads ready to be written. name : str Name of the fastq read. for_seq_list : list List of forward sequences of the fastq read. for_qual_list : list List of forward qualities of the fastq read. rev_seq_list : list List of reverse sequencs of the fastq read. rev_qual_list : list List of reverse qualities of the fastq read. mode : str Mode to use to make the digestion. Three values possible: "all", "for_vs_rev", "pile". final_numbers_of_pairs : int Count of pairs after cutting.

Returns:

str Stack of forward reads ready to be written with the last pairs added. str Stack of reverse reads ready to be written with the last pairs added. int Count of pairs after cutting.

Source code in src/hicstuff/cutsite.py
def write_pair(
    new_reads_for,
    new_reads_rev,
    name,
    for_seq_list,
    for_qual_list,
    rev_seq_list,
    rev_qual_list,
    mode,
    final_number_of_pairs,
):
    """Function to write one pair with the combinations of fragment depending on
    the chosen mode.

    Parameters:
    -----------
    new_reads_for : str
        Stack of the new forward reads ready to be written.
    new_reads_rev : str
        Stack of the new reverse reads ready to be written.
    name : str
        Name of the fastq read.
    for_seq_list : list
        List of forward sequences of the fastq read.
    for_qual_list : list
        List of forward qualities of the fastq read.
    rev_seq_list : list
        List of reverse sequencs of the fastq read.
    rev_qual_list : list
        List of reverse qualities of the fastq read.
    mode : str
        Mode to use to make the digestion. Three values possible: "all",
        "for_vs_rev", "pile".
    final_numbers_of_pairs : int
        Count of pairs after cutting.

    Returns:
    --------
    str
        Stack of forward reads ready to be written with the last pairs added.
    str
        Stack of reverse reads ready to be written with the last pairs added.
    int
        Count of pairs after cutting.
    """

    # Mode "for_vs_rev": Make contacts only between fragments from different
    # reads (one fragment from forward and one from reverse).
    if mode == "for_vs_rev":
        for i in range(len(for_seq_list)):
            for j in range(len(rev_seq_list)):
                final_number_of_pairs += 1
                new_reads_for += "@{}\n{}\n+\n{}\n".format(
                    name + ":" + str(i) + str(j),
                    for_seq_list[i],
                    for_qual_list[i],
                )
                new_reads_rev += "@{}\n{}\n+\n{}\n".format(
                    name + ":" + str(i) + str(j),
                    rev_seq_list[j],
                    rev_qual_list[j],
                )

    #  Mode "all": Make all the possible contacts between the fragments.
    elif mode == "all":
        seq_list = for_seq_list + rev_seq_list
        qual_list = for_qual_list + rev_qual_list
        for i in range(len(seq_list)):
            for j in range(i + 1, len(seq_list)):
                final_number_of_pairs += 1
                if i < len(for_seq_list):
                    new_reads_for += "@{}\n{}\n+\n{}\n".format(
                        name + ":" + str(i) + str(j),
                        seq_list[i],
                        qual_list[i],
                    )
                # Reverse the forward read if comes from reverse.
                else:
                    new_reads_for += "@{}\n{}\n+\n{}\n".format(
                        name + ":" + str(i) + str(j),
                        seq_list[i][::-1],
                        qual_list[i][::-1],
                    )
                # Reverse the reverse read if comes from forward.
                if j < len(for_seq_list):
                    new_reads_rev += "@{}\n{}\n+\n{}\n".format(
                        name + ":" + str(i) + str(j),
                        seq_list[j][::-1],
                        qual_list[j][::-1],
                    )
                else:
                    new_reads_rev += "@{}\n{}\n+\n{}\n".format(
                        name + ":" + str(i) + str(j),
                        seq_list[j],
                        qual_list[j],
                    )

    # Mode "pile": Only make contacts bewteen two adjacent fragments.
    elif mode == "pile":
        seq_list = for_seq_list + rev_seq_list
        qual_list = for_qual_list + rev_qual_list
        for i in range(len(seq_list) - 1):
            final_number_of_pairs += 1
            if i < len(for_seq_list) - 1:
                new_reads_for += "@{}\n{}\n+\n{}\n".format(
                    name + ":" + str(i) + str(i + 1),
                    seq_list[i],
                    qual_list[i],
                )
                new_reads_rev += "@{}\n{}\n+\n{}\n".format(
                    name + ":" + str(i) + str(i + 1),
                    seq_list[i + 1][::-1],
                    qual_list[i + 1][::-1],
                )
            elif i == len(for_seq_list) - 1:
                new_reads_for += "@{}\n{}\n+\n{}\n".format(
                    name + ":" + str(i) + str(i + 1),
                    seq_list[i],
                    qual_list[i],
                )
                new_reads_rev += "@{}\n{}\n+\n{}\n".format(
                    name + ":" + str(i) + str(i + 1),
                    seq_list[i + 1],
                    qual_list[i + 1],
                )
            else:
                new_reads_for += "@{}\n{}\n+\n{}\n".format(
                    name + ":" + str(i) + str(i + 1),
                    seq_list[i][::-1],
                    qual_list[i][::-1],
                )
                new_reads_rev += "@{}\n{}\n+\n{}\n".format(
                    name + ":" + str(i) + str(i + 1),
                    seq_list[i + 1],
                    qual_list[i + 1],
                )

    return new_reads_for, new_reads_rev, final_number_of_pairs

hicstuff.bwamem

bwa mem through the bwa program, or in-process through pybwa.

hicstuff aligns reads with bwa (--aligner bwa) through one of two backends: the bwa program, or pybwa, a dependency of hicstuff that runs bwa's index and mem within Python (https://github.com/fulcrumgenomics/pybwa). With pybwa, aligning reads needs no program at all.

pybwa writes the primary records of the bwa program, read by read, once read names are trimmed as bwa trims them. It aligns the reads of a file BATCH_SIZE at a time, however, and bwa breaks ties between alignments of equal score with a hash of each read's position among the reads aligned together, which restarts with every batch. Of a read cut into two halves of equal score, the half that is primary can then differ from the bwa program's choice: 0.02 to 0.25% of the pairs of real libraries. With -5 (mapping mode 5spm), the 5'-most half is primary and no such tie arises.

This module contains the following functions:

  • resolve_backend
  • load_index
  • build_index
  • write_fasta
  • align
  • iterative_align
  • align_pairs

pybwa_version

pybwa_version()

The version of pybwa, or None if it cannot be imported.

Source code in src/hicstuff/bwamem.py
def pybwa_version():
    """The version of pybwa, or None if it cannot be imported."""
    try:
        import pybwa  # noqa: F401
    except ImportError:
        return None
    return importlib.metadata.version("pybwa")

describe

describe(backend, five_spm=False)

How bwa mem runs with a backend, as the logs name it.

Source code in src/hicstuff/bwamem.py
def describe(backend, five_spm=False):
    """How bwa mem runs with a backend, as the logs name it."""
    command = f"bwa mem {FIVE_SPM}" if five_spm else "bwa mem"
    if backend == "python":
        return f"{command} in-process, pybwa {pybwa_version()} (bwa {PYBWA_BWA_VERSION})"
    return f"{command}, bwa program"

resolve_backend

resolve_backend(requested=None, prefer_python=False)

The backend that aligns reads with bwa.

Parameters:

Name Type Description Default
requested str or None

"auto", "binary" (the bwa program) or "python" (pybwa). None reads the environment variable HICSTUFF_ALIGNER_BACKEND, and is auto if it is not set.

None
prefer_python bool

Whether auto prefers pybwa to the bwa program, as mapping mode 5spm does. Otherwise auto prefers the bwa program, so that a run aligns its reads as it did before pybwa.

False

Returns:

Type Description
str

"binary" or "python".

Raises:

Type Description
ValueError

If requested is not one of the backends.

ImportError

If the backend requested cannot run, or, for auto, neither can, naming what to install.

Source code in src/hicstuff/bwamem.py
def resolve_backend(requested=None, prefer_python=False):
    """The backend that aligns reads with bwa.

    Parameters
    ----------
    requested : str or None
        "auto", "binary" (the bwa program) or "python" (pybwa). None reads the
        environment variable HICSTUFF_ALIGNER_BACKEND, and is auto if it is
        not set.
    prefer_python : bool
        Whether auto prefers pybwa to the bwa program, as mapping mode 5spm
        does. Otherwise auto prefers the bwa program, so that a run aligns its
        reads as it did before pybwa.

    Returns
    -------
    str
        "binary" or "python".

    Raises
    ------
    ValueError
        If requested is not one of the backends.
    ImportError
        If the backend requested cannot run, or, for auto, neither can,
        naming what to install.
    """
    if requested is None:
        requested = os.environ.get(BACKEND_ENV) or "auto"
    requested = requested.strip().lower()
    if requested not in BACKENDS:
        raise ValueError(
            f"Unknown aligner backend {requested!r}: choose among {', '.join(BACKENDS)}."
        )
    found = {"binary": which("bwa") is not None, "python": pybwa_version() is not None}
    if requested == "auto":
        order = ("python", "binary") if prefer_python else ("binary", "python")
        for backend in order:
            if found[backend]:
                return backend
        msg = (
            "Neither the bwa program nor pybwa is installed, and one of them is needed to "
            "align reads with bwa: install pybwa (pip install pybwa), "
            "or the bwa program."
        )
    elif found[requested]:
        return requested
    elif requested == "binary":
        msg = (
            "bwa is not installed or not on PATH, and needed to align reads with "
            "--aligner-backend binary: install it, or use --aligner-backend python, which "
            "runs bwa in-process with pybwa."
        )
    else:
        msg = (
            "pybwa is not installed, and needed to align reads with --aligner-backend python: "
            "install it (pip install pybwa), or use --aligner-backend "
            "binary, which runs the bwa program."
        )
    logger.error(msg)
    raise ImportError(msg)

build_index

build_index(fasta, prefix)

Build the bwa index of a fasta file at prefix with pybwa.

The BWT is built by the algorithm bwa index chooses: bwtsw for references longer than 50 Mb, is otherwise. The index files are the same whatever the algorithm, which only sets the time and memory taken.

Source code in src/hicstuff/bwamem.py
def build_index(fasta, prefix):
    """Build the bwa index of a fasta file at prefix with pybwa.

    The BWT is built by the algorithm ``bwa index`` chooses: bwtsw for
    references longer than 50 Mb, is otherwise. The index files are the same
    whatever the algorithm, which only sets the time and memory taken.
    """
    from pybwa import BwaIndex, BwaIndexBuildMethod

    with ps.FastxFile(fasta) as records:
        length = sum(len(record.sequence) for record in records)
    # pybwa 2.3 passes its methods to bwa off by one, which hicstuff pins:
    # RB2 runs bwtsw and BWTSW runs is.
    method = BwaIndexBuildMethod.RB2 if length > BWTSW_MIN_LENGTH else BwaIndexBuildMethod.BWTSW
    _quiet()
    BwaIndex.index(fasta, method=method, prefix=prefix)

write_fasta

write_fasta(prefix, handle, line_length=60)

Write the sequences of the bwa index at prefix to handle, in the FASTA format.

bwa keeps the reference in the .pac file, four bases a byte from its most significant bits, with A, C, G and T coded 0 to 3. It codes the other letters (N and the other IUPAC codes) as random bases, and lists each run of them in the .amb file, from which they are restored. Lowercase is not kept: the sequences are written in uppercase, as bwa aligns to them.

Parameters:

Name Type Description Default
prefix str

The prefix of the bwa index.

required
handle file object

A file opened for writing bytes.

required
line_length int

Number of bases on each line of sequence.

60
Source code in src/hicstuff/bwamem.py
def write_fasta(prefix, handle, line_length=60):
    """Write the sequences of the bwa index at prefix to handle, in the FASTA
    format.

    bwa keeps the reference in the .pac file, four bases a byte from its most
    significant bits, with A, C, G and T coded 0 to 3. It codes the other
    letters (N and the other IUPAC codes) as random bases, and lists each run
    of them in the .amb file, from which they are restored. Lowercase is not
    kept: the sequences are written in uppercase, as bwa aligns to them.

    Parameters
    ----------
    prefix : str
        The prefix of the bwa index.
    handle : file object
        A file opened for writing bytes.
    line_length : int
        Number of bases on each line of sequence.
    """
    with open(f"{prefix}.amb") as amb:
        # "length sequences runs", then "offset length letter" for each run,
        # in the order of the reference
        n_runs = int(amb.readline().split()[2])
        runs = [amb.readline().split() for _ in range(n_runs)]
    run_offsets = np.array([int(run[0]) for run in runs], dtype=np.int64)
    with open(f"{prefix}.pac", "rb") as pac:
        for name, offset, length in _sequences(prefix):
            first = offset // 4
            pac.seek(first)
            packed = np.frombuffer(pac.read((offset + length + 3) // 4 - first), dtype=np.uint8)
            codes = np.empty((packed.size, 4), dtype=np.uint8)
            for column, shift in enumerate((6, 4, 2, 0)):
                codes[:, column] = (packed >> shift) & 3
            skip = offset - 4 * first
            sequence = _PAC_BASES[codes.ravel()[skip : skip + length]]
            low, high = np.searchsorted(run_offsets, [offset, offset + length])
            for run_offset, run_length, letter in runs[low:high]:
                start = int(run_offset) - offset
                # bwa keeps the letter as the fasta has it
                sequence[start : start + int(run_length)] = ord(letter.upper())
            handle.write(f">{name}\n".encode())
            full = length - length % line_length
            lines = np.empty((full // line_length, line_length + 1), dtype=np.uint8)
            lines[:, :line_length] = sequence[:full].reshape(-1, line_length)
            lines[:, line_length] = ord("\n")
            handle.write(lines.tobytes())
            if full < length:
                handle.write(sequence[full:].tobytes() + b"\n")

load_index

load_index(genome, tmp_dir)

Load the bwa index of a reference with pybwa, building it first if there is none.

pybwa reads an index with a sequence dictionary named after the index prefix with its last suffix replaced (genome.dict for genome.fa). Rather than write one next to the reference, where another file may have that name, the index files are linked into a new directory of tmp_dir, next to a dictionary written from the index. An index that must be built is built there, from the fasta where it is, plain or compressed.

Parameters:

Name Type Description Default
genome str

Path to the reference fasta, or to the prefix of its bwa index.

required
tmp_dir str

Directory in which the index directory is created.

required

Returns:

Type Description
BwaIndex

The index, loaded in memory.

Source code in src/hicstuff/bwamem.py
def load_index(genome, tmp_dir):
    """Load the bwa index of a reference with pybwa, building it first if
    there is none.

    pybwa reads an index with a sequence dictionary named after the index
    prefix with its last suffix replaced (genome.dict for genome.fa). Rather
    than write one next to the reference, where another file may have that
    name, the index files are linked into a new directory of tmp_dir, next
    to a dictionary written from the index. An index that must be built is
    built there, from the fasta where it is, plain or compressed.

    Parameters
    ----------
    genome : str
        Path to the reference fasta, or to the prefix of its bwa index.
    tmp_dir : str
        Directory in which the index directory is created.

    Returns
    -------
    pybwa.BwaIndex
        The index, loaded in memory.
    """
    from pybwa import BwaIndex

    directory = hio.generate_temp_dir(tmp_dir)
    prefix = os.path.join(directory, "index")
    found = hio.check_fasta_index(genome, mode="bwa")
    if found is None:
        logger.info("bwa index not found at %s, building a temporary one in %s.", genome, directory)
        build_index(genome, prefix)
    else:
        for suffix in INDEX_SUFFIXES:
            os.symlink(os.path.abspath(found + suffix), prefix + suffix)
    _write_sequence_dict(prefix)
    _quiet()
    return BwaIndex(prefix)

loaded_index

loaded_index(genome, tmp_dir)

An index loaded by :func:load_index for the block, whose files are removed when the block ends, or an index already loaded.

Parameters:

Name Type Description Default
genome str or BwaIndex

Path to the reference or the prefix of its index, or an index.

required
tmp_dir str

Directory in which a temporary directory holds the index files.

required
Source code in src/hicstuff/bwamem.py
@contextlib.contextmanager
def loaded_index(genome, tmp_dir):
    """An index loaded by :func:`load_index` for the block, whose files are
    removed when the block ends, or an index already loaded.

    Parameters
    ----------
    genome : str or pybwa.BwaIndex
        Path to the reference or the prefix of its index, or an index.
    tmp_dir : str
        Directory in which a temporary directory holds the index files.
    """
    if not isinstance(genome, (str, os.PathLike)):
        yield genome
        return
    with tempfile.TemporaryDirectory(dir=tmp_dir) as directory:
        yield load_index(genome, directory)

align

align(reads, index, out_bam, threads=1, five_spm=False, batch_size=BATCH_SIZE)

Align the reads of a fastq file with bwa mem in-process, and write their alignments to a BAM file sorted by read name.

The records written are those that hicstuff keeps of the bwa program's: all but the supplementary alignments, and with five_spm (bwa mem -5SPM) only the primary ones, since -M makes split alignments secondary.

Parameters:

Name Type Description Default
reads str

Path to the fastq file, plain or compressed.

required
index BwaIndex

The index, from :func:load_index.

required
out_bam str

Path to the BAM file to write.

required
threads int

Threads of bwa mem and of BAM compression and sorting.

1
five_spm bool

Align with -5SPM.

False
batch_size int

Reads aligned together.

BATCH_SIZE
Source code in src/hicstuff/bwamem.py
def align(reads, index, out_bam, threads=1, five_spm=False, batch_size=BATCH_SIZE):
    """Align the reads of a fastq file with bwa mem in-process, and write
    their alignments to a BAM file sorted by read name.

    The records written are those that hicstuff keeps of the bwa program's:
    all but the supplementary alignments, and with five_spm (``bwa mem
    -5SPM``) only the primary ones, since -M makes split alignments
    secondary.

    Parameters
    ----------
    reads : str
        Path to the fastq file, plain or compressed.
    index : pybwa.BwaIndex
        The index, from :func:`load_index`.
    out_bam : str
        Path to the BAM file to write.
    threads : int
        Threads of bwa mem and of BAM compression and sorting.
    five_spm : bool
        Align with -5SPM.
    batch_size : int
        Reads aligned together.
    """
    from pybwa import BwaMem

    aligner = BwaMem(index=index)
    options = _options(threads, five_spm)
    command = f"bwa mem {FIVE_SPM + ' ' if five_spm else ''}-t {threads} -v 1 <index> {reads}"
    unsorted = out_bam + ".unsorted"
    with ps.AlignmentFile(unsorted, "wb", header=_header(index, command), threads=threads) as out:
        for batch in _batches(reads, batch_size):
            for records in aligner.align(batch, options):
                for record in records:
                    if not (record.is_supplementary or (five_spm and record.is_secondary)):
                        out.write(record)
    _sort_by_name(unsorted, out_bam, threads)

iterative_align

iterative_align(reads, index, out_bam, threads=1, min_len=20, min_qual=30, read_len=None, batch_size=BATCH_SIZE)

Align the reads of a fastq file iteratively with bwa mem in-process, as :func:hicstuff.iteralign.iterative_align does with the bwa program, and write one record per read to a BAM file sorted by read name.

Reads are truncated to min_len bases and aligned; those whose primary alignment is unique enough (flag 0 or 16, mapping quality of min_qual or more) are kept, and the others are extended by 20 bases and aligned again, until the reads are aligned at full length. The rounds run in memory, batch_size reads at a time, without temporary files.

Parameters:

Name Type Description Default
reads str

Path to the fastq file, plain or compressed.

required
index BwaIndex

The index, from :func:load_index.

required
out_bam str

Path to the BAM file to write.

required
threads int

Threads of bwa mem and of BAM compression and sorting.

1
min_len int

Length of the reads in the first round.

20
min_qual int

Mapping quality from which an alignment is kept.

30
read_len int

Length of the reads, that of the first read if None.

None
batch_size int

Reads aligned together.

BATCH_SIZE
Source code in src/hicstuff/bwamem.py
def iterative_align(
    reads, index, out_bam, threads=1, min_len=20, min_qual=30, read_len=None, batch_size=BATCH_SIZE
):
    """Align the reads of a fastq file iteratively with bwa mem in-process,
    as :func:`hicstuff.iteralign.iterative_align` does with the bwa program,
    and write one record per read to a BAM file sorted by read name.

    Reads are truncated to min_len bases and aligned; those whose primary
    alignment is unique enough (flag 0 or 16, mapping quality of min_qual or
    more) are kept, and the others are extended by 20 bases and aligned
    again, until the reads are aligned at full length. The rounds run in
    memory, batch_size reads at a time, without temporary files.

    Parameters
    ----------
    reads : str
        Path to the fastq file, plain or compressed.
    index : pybwa.BwaIndex
        The index, from :func:`load_index`.
    out_bam : str
        Path to the BAM file to write.
    threads : int
        Threads of bwa mem and of BAM compression and sorting.
    min_len : int
        Length of the reads in the first round.
    min_qual : int
        Mapping quality from which an alignment is kept.
    read_len : int
        Length of the reads, that of the first read if None.
    batch_size : int
        Reads aligned together.
    """
    from pybwa import BwaMem

    if read_len is None:
        with ps.FastxFile(reads) as fastq:
            first = next(iter(fastq), None)
        read_len = 0 if first is None else len(first.sequence)
    if read_len > min_len:
        first_len = min_len
    else:
        logger.warning("min_len is longer than the reads. Iterative mapping will have no effect.")
        first_len = read_len
    # The truncated rounds, then the reads at full length, as iteralign
    lengths = list(range(first_len, read_len + 1, 20))
    lengths.append(lengths[-1] + 20)

    aligner = BwaMem(index=index)
    options = _options(threads)
    command = f"bwa mem -t {threads} -v 1 <index> {reads} (iterative)"
    left = [0] * len(lengths)
    total = 0
    unsorted = out_bam + ".unsorted"
    with ps.AlignmentFile(unsorted, "wb", header=_header(index, command), threads=threads) as out:
        for batch in _batches(reads, batch_size):
            total += len(batch)
            pending = batch
            for i, length in enumerate(lengths):
                last = i == len(lengths) - 1
                aligned = aligner.align([_truncated(q, length) for q in pending], options)
                still = []
                for query, records in zip(pending, aligned):
                    primary = _primary(records)
                    # Kept as iteralign keeps it, and written in the last round anyway
                    kept = primary.flag in (0, 16) and primary.mapping_quality >= min_qual
                    if kept or last:
                        out.write(primary)
                    if not kept:
                        still.append(query)
                left[i] += len(still)
                pending = still
    # The messages of iteralign, once all batches are aligned
    logger.info(f"{total} reads to parse")
    for i, length in enumerate(lengths):
        if i < len(lengths) - 1:
            again = "" if i == 0 else " again"
            logger.info(f"Truncating unaligned reads to {length}bp and mapping{again}.")
        else:
            logger.info(f"Trying to map unaligned reads at full length ({read_len}bp).")
        logger.info(f"{left[i]} reads left to map.")
    logger.info(f"{total - left[-1]} reads aligned / {total} total reads.")
    _sort_by_name(unsorted, out_bam, threads)

align_pairs

align_pairs(reads1, reads2, genome, bam1, bam2, threads=1, backend='python', tmp_dir=None)

Align read pairs with bwa mem -5SPM, and write each mate's primary alignments to a BAM file sorted by read name.

With the bwa program, the pairs are aligned in one call, whose output is split by mate. With pybwa, each mate is aligned on its own, which gives the same primary alignments: -S and -P leave mates to their own alignments.

Parameters:

Name Type Description Default
reads1 str

Paths to the fastq files of the first and second mates, in the same order, with the same names.

required
reads2 str

Paths to the fastq files of the first and second mates, in the same order, with the same names.

required
genome str or BwaIndex

The bwa index prefix, or with pybwa an index from :func:load_index.

required
bam1 str

Paths to the BAM files to write, for each mate.

required
bam2 str

Paths to the BAM files to write, for each mate.

required
threads int

Threads of bwa mem and of BAM compression and sorting.

1
backend str

"binary" or "python".

'python'
tmp_dir str

Directory of the index that pybwa loads, when genome is a path.

None

Raises:

Type Description
RuntimeError

If the bwa program fails, for instance on mates named differently. Nothing is left of its output.

Source code in src/hicstuff/bwamem.py
def align_pairs(reads1, reads2, genome, bam1, bam2, threads=1, backend="python", tmp_dir=None):
    """Align read pairs with ``bwa mem -5SPM``, and write each mate's primary
    alignments to a BAM file sorted by read name.

    With the bwa program, the pairs are aligned in one call, whose output is
    split by mate. With pybwa, each mate is aligned on its own, which gives
    the same primary alignments: -S and -P leave mates to their own
    alignments.

    Parameters
    ----------
    reads1, reads2 : str
        Paths to the fastq files of the first and second mates, in the same
        order, with the same names.
    genome : str or pybwa.BwaIndex
        The bwa index prefix, or with pybwa an index from :func:`load_index`.
    bam1, bam2 : str
        Paths to the BAM files to write, for each mate.
    threads : int
        Threads of bwa mem and of BAM compression and sorting.
    backend : str
        "binary" or "python".
    tmp_dir : str
        Directory of the index that pybwa loads, when genome is a path.

    Raises
    ------
    RuntimeError
        If the bwa program fails, for instance on mates named differently.
        Nothing is left of its output.
    """
    if backend == "python":
        with loaded_index(genome, tmp_dir) as index:
            align(reads1, index, bam1, threads=threads, five_spm=True)
            align(reads2, index, bam2, threads=threads, five_spm=True)
        return

    command = ["bwa", "mem", "-v", "1", FIVE_SPM, "-t", str(threads), genome, reads1, reads2]
    unsorted = [bam1 + ".unsorted", bam2 + ".unsorted"]
    try:
        with tempfile.TemporaryFile() as stderr:
            with sp.Popen(command, stdout=sp.PIPE, stderr=stderr) as proc:
                try:
                    with ps.AlignmentFile(proc.stdout, "r") as sam, contextlib.ExitStack() as stack:
                        outs = [
                            stack.enter_context(
                                ps.AlignmentFile(path, "wb", template=sam, threads=threads)
                            )
                            for path in unsorted
                        ]
                        for record in sam:
                            if not (record.is_secondary or record.is_supplementary):
                                outs[record.is_read2].write(record)
                except (OSError, ValueError) as error:
                    # bwa stopped before it wrote a SAM header: its error tells why
                    proc.kill()
                    reading_error = error
                else:
                    reading_error = None
            if proc.returncode != 0 or reading_error is not None:
                stderr.seek(0)
                lines = stderr.read().decode(errors="replace").strip().splitlines()
                reason = lines[-1] if lines else str(reading_error)
                raise RuntimeError(
                    f"bwa mem {FIVE_SPM} failed (exit code {proc.returncode}): {reason}"
                )
        for path, out_bam in zip(unsorted, (bam1, bam2)):
            _sort_by_name(path, out_bam, threads)
    finally:
        for path in unsorted:
            with contextlib.suppress(FileNotFoundError):
                os.remove(path)