Skip to content

Digestion and filtering

hicstuff.digest cuts a genome into fragments (write_frag_info, get_restriction_table) and assigns the mates of each pair to them (attribute_fragments). hicstuff.filter finds the uncuts and loops of a library (get_thresholds) and removes them (filter_events).

See Digesting a genome and Filtering 3C events.

hicstuff.digest

Genome digestion

Functions used to write auxiliary instagraal compatible sparse matrices.

write_frag_info

write_frag_info(fasta, enzyme, min_size=DEFAULT_THRESHOLD_SIZE, circular=False, output_contigs=DEFAULT_INFO_CONTIGS_FILE_NAME, output_frags=DEFAULT_FRAGMENTS_LIST_FILE_NAME, output_dir=None)

Digest and write fragment information

Write the fragments_list.txt and info_contigs.txt that are necessary for instagraal to run.

Parameters:

Name Type Description Default
fasta Path or str

The path to the reference genome

required
enzyme str, int or list of str

If a string, must be the name of an enzyme (e.g. DpnII) and the genome will be cut at the enzyme's restriction sites. If a number, the genome will be cut uniformly into chunks with length equal to that number. A list of enzymes can also be specified if using multiple enzymes.

required
min_size float

Size below which shorter contigs are discarded. Default is 0, i.e. all contigs are retained.

DEFAULT_THRESHOLD_SIZE
circular bool

Whether the genome is circular. Default is False.

False
output_contigs str

The name of the file with contig info. Default is info_contigs.txt

DEFAULT_INFO_CONTIGS_FILE_NAME
output_frags str

The name of the file with fragment info. Default is fragments_list.txt

DEFAULT_FRAGMENTS_LIST_FILE_NAME
output_dir str

The directory, which must exist, in which output_contigs and output_frags are written. By default, they are paths of their own.

None
Source code in src/hicstuff/digest.py
def write_frag_info(
    fasta,
    enzyme,
    min_size=DEFAULT_THRESHOLD_SIZE,
    circular=False,
    output_contigs=DEFAULT_INFO_CONTIGS_FILE_NAME,
    output_frags=DEFAULT_FRAGMENTS_LIST_FILE_NAME,
    output_dir=None,
):
    """Digest and write fragment information

    Write the fragments_list.txt and info_contigs.txt that are necessary for
    instagraal to run.

    Parameters
    ----------
    fasta : pathlib.Path or str
        The path to the reference genome
    enzyme : str, int or list of str
        If a string, must be the name of an enzyme (e.g. DpnII) and the genome
        will be cut at the enzyme's restriction sites. If a number, the genome
        will be cut uniformly into chunks with length equal to that number. A
        list of enzymes can also be specified if using multiple enzymes.
    min_size : float, optional
        Size below which shorter contigs are discarded. Default is 0, i.e. all
        contigs are retained.
    circular : bool, optional
        Whether the genome is circular. Default is False.
    output_contigs : str, optional
        The name of the file with contig info. Default is info_contigs.txt
    output_frags : str, optional
        The name of the file with fragment info. Default is fragments_list.txt
    output_dir : str, optional
        The directory, which must exist, in which output_contigs and
        output_frags are written. By default, they are paths of their own.
    """

    records = SeqIO.parse(hio.read_compressed(fasta), "fasta")

    try:
        info_contigs_path = os.path.join(output_dir, output_contigs)
        frag_list_path = os.path.join(output_dir, output_frags)
    except TypeError:
        info_contigs_path = output_contigs
        frag_list_path = output_frags

    with open(info_contigs_path, "w") as info_contigs:
        info_contigs.write("contig\tlength\tn_frags\tcumul_length\n")

        with open(frag_list_path, "w") as fragments_list:
            fragments_list.write("id\tchrom\tstart_pos\tend_pos\tsize\tgc_content\n")

            total_frags = 0

            for record in records:
                contig_seq = record.seq
                contig_name = record.id
                contig_length = len(contig_seq)
                if contig_length < int(min_size):
                    continue

                sites = get_restriction_table(contig_seq, enzyme, circular=circular)
                fragments = (contig_seq[sites[i] : sites[i + 1]] for i in range(len(sites) - 1))
                n_frags = 0

                current_id = 1
                start_pos = 0
                for frag in fragments:
                    frag_length = len(frag)
                    if frag_length > 0:
                        end_pos = start_pos + frag_length
                        # Fraction (0-1) of G and C over the whole fragment,
                        # ambiguous bases included, as in io.gc_bins.
                        gc_content = SeqUtils.gc_fraction(frag, "ignore")

                        current_fragment_line = f"{current_id}\t{contig_name}\t{start_pos}\t{end_pos}\t{frag_length}\t{gc_content}\n"

                        fragments_list.write(current_fragment_line)

                        if not (
                            (current_id == 1 and start_pos == 0)
                            or (current_id > 1 and start_pos > 0)
                        ):
                            logger.error(
                                "Fragment ID/position inconsistency: id=%d, start=%d",
                                current_id,
                                start_pos,
                            )
                            raise ValueError(
                                f"Fragment ID/position inconsistency: id={current_id}, start_pos={start_pos}"
                            )
                        start_pos = end_pos
                        current_id += 1
                        n_frags += 1

                current_contig_line = f"{contig_name}\t{contig_length}\t{n_frags}\t{total_frags}\n"
                total_frags += n_frags
                info_contigs.write(current_contig_line)

attribute_fragments

attribute_fragments(pairs_file, idx_pairs_file, restriction_table, min_size=DEFAULT_THRESHOLD_SIZE)

Writes the indexed pairs file, which has two more columns than the input pairs file corresponding to the restriction fragment index of each read. Note that pairs files have 1bp point positions whereas restriction table has 0bp point poisitions.

Fragments are numbered genome-wide as in the fragments list written by write_frag_info: contig by contig, in the order of restriction_table (that of the genome), whatever #chromsize lines the pairs header has. Contigs shorter than min_size are left out, as write_frag_info leaves them out of the fragments list: their fragments get no index, their #chromsize lines are removed, and pairs with a mate on one of them are discarded.

Parameters:

Name Type Description Default
pairs_file

Path the the input pairs file. Consists of 7 tab-separated columns: readID, chr1, pos1, chr2, pos2, strand1, strand2

required
idx_pairs_file

Path to the output indexed pairs file. Consists of 9 white space separated columns: readID, chr1, pos1, chr2, pos2, strand1, strand2, frag1, frag2. frag1 and frag2 are 0-based restriction fragments based on whole genome.

required
restriction_table

Dictionary with chromosome identifiers (str) as keys and list of positions (int) of restriction sites as values, in the order of the genome. The last position of each list is the length of the chromosome, as returned by get_restriction_table.

required
min_size float

Size below which contigs are left out. Default is 0, i.e. all contigs are retained.

DEFAULT_THRESHOLD_SIZE

Returns:

Type Description
int

The number of pairs discarded because a mate is on a contig shorter than min_size.

Source code in src/hicstuff/digest.py
def attribute_fragments(
    pairs_file, idx_pairs_file, restriction_table, min_size=DEFAULT_THRESHOLD_SIZE
):
    """
    Writes the indexed pairs file, which has two more columns than the input
    pairs file corresponding to the restriction fragment index of each read.
    Note that pairs files have 1bp point positions whereas restriction table
    has 0bp point poisitions.

    Fragments are numbered genome-wide as in the fragments list written by
    write_frag_info: contig by contig, in the order of restriction_table (that
    of the genome), whatever ``#chromsize`` lines the pairs header has.
    Contigs shorter than min_size are left out, as write_frag_info leaves them
    out of the fragments list: their fragments get no index, their
    ``#chromsize`` lines are removed, and pairs with a mate on one of them
    are discarded.

    Parameters
    ----------
    pairs_file: str
        Path the the input pairs file. Consists of 7 tab-separated
        columns: readID, chr1, pos1, chr2, pos2, strand1, strand2
    idx_pairs_file: str
        Path to the output indexed pairs file. Consists of 9 white space
        separated columns: readID, chr1, pos1, chr2, pos2, strand1, strand2,
        frag1, frag2. frag1 and frag2 are 0-based restriction fragments based
        on whole genome.
    restriction_table: dict
        Dictionary with chromosome identifiers (str) as keys and list of
        positions (int) of restriction sites as values, in the order of the
        genome. The last position of each list is the length of the
        chromosome, as returned by get_restriction_table.
    min_size : float, optional
        Size below which contigs are left out. Default is 0, i.e. all contigs
        are retained.

    Returns
    -------
    int
        The number of pairs discarded because a mate is on a contig shorter
        than min_size.
    """

    # NOTE: Bottlenecks here are 1. binary search in find_frag and 2. writerow
    # 1. could be reduced by searching groups of N frags in parallel and 2. by
    # writing N frags simultaneously using a single call of writerows.

    # Contigs that write_frag_info leaves out of the fragments list
    too_short = {chrom for chrom, sites in restriction_table.items() if sites[-1] < int(min_size)}

    # Index of the first fragment of each contig in the fragments list, which
    # follows the genome, as restriction_table does, without the contigs too
    # short. The pairs header plays no part: hicstuff writes its #chromsize
    # lines in that order, but other tools may not, or may not write any.
    shift_frags = {}
    n_frags = 0
    for chrom, sites in restriction_table.items():
        if chrom not in too_short:
            shift_frags[chrom] = n_frags
            # Note the "-1" because there are nfrags + 1 sites in rest table
            n_frags += len(sites) - 1

    # Parse and update header section
    pairs_header = hio.get_pairs_header(pairs_file)
    header_size = len(pairs_header)
    with open(idx_pairs_file, "w") as idx_pairs:
        for line in pairs_header:
            # Add new column names to header
            if line.startswith("#columns"):
                line = line.rstrip() + " frag1 frag2"
            # Contigs left out of the fragments list are left out of the header
            if line.startswith("#chromsize") and line.split()[1] in too_short:
                continue
            idx_pairs.write(line + "\n")

    n_short = 0
    # Attribute pairs to fragments and append them to output file (after header)
    with open(pairs_file) as pairs, open(idx_pairs_file, "a") as idx_pairs:
        # Skip header lines
        for _ in range(header_size):
            next(pairs)

        # Define input and output fields
        pairs_cols = [
            "readID",
            "chr1",
            "pos1",
            "chr2",
            "pos2",
            "strand1",
            "strand2",
        ]
        idx_cols = pairs_cols + ["frag1", "frag2"]

        # Use csv reader / writer to automatically parse columns into a dict
        pairs_reader = csv.DictReader(pairs, fieldnames=pairs_cols, delimiter="\t")
        pairs_writer = csv.DictWriter(idx_pairs, fieldnames=idx_cols, delimiter="\t")

        for pair in pairs_reader:
            chr1, chr2 = pair["chr1"], pair["chr2"]
            # Contigs left out of the fragments list have no fragment index
            if chr1 in too_short or chr2 in too_short:
                n_short += 1
                continue
            # Get the 0-based indices of corresponding restriction fragments
            # Deducing 1 from pair position to get it into 0bp point
            pair["frag1"] = find_frag(int(pair["pos1"]) - 1, restriction_table[chr1])
            pair["frag2"] = find_frag(int(pair["pos2"]) - 1, restriction_table[chr2])
            # Shift fragment indices to make them genome-based instead of
            # chromosome-based
            pair["frag1"] += shift_frags[chr1]
            pair["frag2"] += shift_frags[chr2]

            # Write indexed pairs in the new file
            pairs_writer.writerow(pair)

    if too_short:
        logger.info(
            "%d pairs with a mate on a contig shorter than %d bp were discarded.",
            n_short,
            int(min_size),
        )
    return n_short

get_restriction_table

get_restriction_table(seq, enzyme, circular=False)

Get the restriction table for a single genomic sequence.

Parameters:

Name Type Description Default
seq Seq object

A biopython Seq object representing a chromosomes or contig.

required
enzyme int, str or list of str

The name of the restriction enzyme used, or a list of restriction enzyme names. Can also be an integer, to digest by fixed chunk size.

required
circular bool

Wether the genome is circular.

False

Returns:

Name Type Description
numpy.array:

List of restriction fragment boundary positions for the input sequence.

>>> from Bio.Seq import Seq
>>> get_restriction_table(Seq("AAGCCGGATCGG"),"HpaII")
array([0, 4, 12])
>>> get_restriction_table(Seq("AA"),["HpaII", "MluCI"])
array([0, 2])
>>> get_restriction_table(Seq("AA"),"aeiou1")
Traceback (most recent call last):

...

ValueError aeiou1 is not a valid restriction enzyme.
>>> get_restriction_table("AA","HpaII")
Traceback (most recent call last):

...

TypeError expected Seq or MutableSeq, got <class 'str'>
Source code in src/hicstuff/digest.py
def get_restriction_table(seq, enzyme, circular=False):
    """
    Get the restriction table for a single genomic sequence.

    Parameters
    ----------
    seq : Seq object
        A biopython Seq object representing a chromosomes or contig.
    enzyme : int, str or list of str
        The name of the restriction enzyme used, or a list of restriction
        enzyme names. Can also be an integer, to digest by fixed chunk size.
    circular : bool
        Wether the genome is circular.

    Returns
    -------
    numpy.array:
        List of restriction fragment boundary positions for the input sequence.

    >>> from Bio.Seq import Seq
    >>> get_restriction_table(Seq("AAGCCGGATCGG"),"HpaII")
    array([ 0,  4, 12])
    >>> get_restriction_table(Seq("AA"),["HpaII", "MluCI"])
    array([0, 2])
    >>> get_restriction_table(Seq("AA"),"aeiou1")
    Traceback (most recent call last):
        ...
    ValueError: aeiou1 is not a valid restriction enzyme.
    >>> get_restriction_table("AA","HpaII")
    Traceback (most recent call last):
        ...
    TypeError: expected Seq or MutableSeq, got <class 'str'>

    """
    chrom_len = len(seq)
    wrong_enzyme = f"{enzyme} is not a valid restriction enzyme."
    # Restriction batch containing the restriction enzyme
    try:
        enz = [enzyme] if isinstance(enzyme, str) else enzyme
        cutter = RestrictionBatch(enz)
    except (TypeError, ValueError):
        try:
            cutter = max(int(enzyme), DEFAULT_MIN_CHUNK_SIZE)
        except ValueError:
            raise ValueError(wrong_enzyme) from None

    # Conversion from string type to restriction type
    if isinstance(cutter, int):
        sites = [i for i in range(0, chrom_len, cutter)]
        if sites[-1] < chrom_len:
            sites.append(chrom_len)
    else:
        # Find sites of all restriction enzymes given.
        # Always use linear=False (circular) search to capture terminal
        # restriction sites, which biopython >=1.87 omits for linear sequences
        # when the recognition site ends at the last base of the sequence.
        # Wrapping positions beyond chrom_len are filtered out.
        sites = []
        for enz_obj in cutter:
            sites.extend(s - 1 for s in enz_obj.search(seq, linear=False) if s <= chrom_len)
        # Sort by position and add start/end of seq if not already present
        sites.sort()
        if not sites or sites[0] != 0:
            sites.insert(0, 0)
        if sites[-1] != chrom_len:
            sites.append(chrom_len)

    return np.array(sites)

find_frag

find_frag(pos, r_sites)

Use binary search to find the index of a chromosome restriction fragment corresponding to an input genomic position.

Parameters:

Name Type Description Default
pos int

Genomic position, in base pairs.

required
r_sites list

List of genomic positions corresponding to restriction sites.

required

Returns:

Name Type Description
int

The 0-based index of the restriction fragment to which the position belongs.

>>> find_frag(15, [0, 20, 30])
0
>>> find_frag(15, [10, 20, 30])
Traceback (most recent call last):

...

ValueError The first position in the restriction table is not 0.
>>> find_frag(31, [0, 20, 30])
Traceback (most recent call last):

...

ValueError Read position is larger than last entry in restriction table.
Source code in src/hicstuff/digest.py
def find_frag(pos, r_sites):
    """
    Use binary search to find the index of a chromosome restriction fragment
    corresponding to an input genomic position.
    Parameters
    ----------
    pos : int
        Genomic position, in base pairs.
    r_sites : list
        List of genomic positions corresponding to restriction sites.
    Returns
    -------
    int
        The 0-based index of the restriction fragment to which the position belongs.

    >>> find_frag(15, [0, 20, 30])
    0
    >>> find_frag(15, [10, 20, 30])
    Traceback (most recent call last):
        ...
    ValueError: The first position in the restriction table is not 0.
    >>> find_frag(31, [0, 20, 30])
    Traceback (most recent call last):
        ...
    ValueError: Read position is larger than last entry in restriction table.

    """
    if r_sites[0] != 0:
        raise ValueError("The first position in the restriction table is not 0.")
    if pos > r_sites[-1]:
        raise ValueError("Read position is larger than last entry in restriction table.")
    # binary search for the index of the read
    index = max(np.searchsorted(r_sites, pos, side="right") - 1, 0)
    # Last site = end of the chrom, index of last fragment is last site - 1
    index = min(len(r_sites) - 2, index)

    return int(index)

frag_len

frag_len(frags_file_name=DEFAULT_FRAGMENTS_LIST_FILE_NAME, output_dir=None, plot=False, fig_path=None)

logs summary statistics of fragment length distribution based on an input fragment file. Can optionally show a histogram instead of text summary.

Parameters:

Name Type Description Default
frags_file_name str

Path to the output list of fragments.

DEFAULT_FRAGMENTS_LIST_FILE_NAME
output_dir str

Directory where the list should be saved.

None
plot bool

Wether a histogram of fragment length should be shown.

False
fig_path str

If a path is given, the figure will be saved instead of shown.

None
Source code in src/hicstuff/digest.py
def frag_len(
    frags_file_name=DEFAULT_FRAGMENTS_LIST_FILE_NAME,
    output_dir=None,
    plot=False,
    fig_path=None,
):
    """
    logs summary statistics of fragment length distribution based on an
    input fragment file. Can optionally show a histogram instead
    of text summary.
    Parameters
    ----------
    frags_file_name : str
        Path to the output list of fragments.
    output_dir : str
        Directory where the list should be saved.
    plot : bool
        Wether a histogram of fragment length should be shown.
    fig_path : str
        If a path is given, the figure will be saved instead of shown.
    """

    try:
        frag_list_path = os.path.join(output_dir, frags_file_name)
    except TypeError:
        frag_list_path = frags_file_name
    frags = pd.read_csv(frag_list_path, sep="\t")
    nfrags = frags.shape[0]
    med_len = frags["size"].median()
    nbins = 40
    if plot:
        fig, ax = plt.subplots()
        _, _, _ = ax.hist(frags["size"], bins=nbins)

        ax.set_xlabel("Fragment length [bp]")
        ax.set_ylabel("Log10 number of fragments")
        ax.set_title("Distribution of restriction fragment length")
        ax.set_yscale("log", base=10)
        ax.annotate(
            f"Total fragments: {nfrags}",
            xy=(0.95, 0.95),
            xycoords="axes fraction",
            fontsize=12,
            horizontalalignment="right",
            verticalalignment="top",
        )
        ax.annotate(
            f"Median length: {med_len}",
            xy=(0.95, 0.90),
            xycoords="axes fraction",
            fontsize=12,
            horizontalalignment="right",
            verticalalignment="top",
        )
        # Tweak spacing to prevent clipping of ylabel
        fig.tight_layout()
        if fig_path:
            plt.savefig(fig_path)
        else:
            plt.show()
        plt.clf()
    else:
        logger.info(f"Genome digested into {nfrags} fragments with a median length of {med_len}")

gen_enzyme_religation_regex

gen_enzyme_religation_regex(enzyme)

Return a regex which corresponds to all possible religation sites given a set of enzyme.

Parameters:

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

Returns:

re.Pattern : Regex that corresponds to all possible ligation sites given a set of enzyme.

Examples:

gen_enzyme_religation_regex('HpaII') re.compile('CCGCGG') gen_enzyme_religation_regex('HpaII,MluCI') re.compile('AATTAATT|AATTCGG|CCGAATT|CCGCGG')

Source code in src/hicstuff/digest.py
def gen_enzyme_religation_regex(enzyme):
    """Return a regex which corresponds to all possible religation sites given a
    set of enzyme.
    Parameters:
    -----------
    enzyme : str
        String that contains the names of the enzyme separated by a comma.
    Returns:
    --------
    re.Pattern :
        Regex that corresponds to all possible ligation sites given a set of
        enzyme.
    Examples:
    ---------
    >>> gen_enzyme_religation_regex('HpaII')
    re.compile('CCGCGG')
    >>> gen_enzyme_religation_regex('HpaII,MluCI')
    re.compile('AATTAATT|AATTCGG|CCGAATT|CCGCGG')
    """

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

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

    # Initiation:
    give_list = []
    accept_list = []
    ligation_list = []

    # Iterates on the enzymes.
    for enz in rb:
        # Extract restriction sites and look for cut sites.
        site = enz.elucidate()
        fw_cut = site.find("^")
        rev_cut = site.find("_")

        # Process "give" site. Remove N on the left (useless).
        give_site = site[:rev_cut].replace("^", "")
        while give_site[0] == "N":
            give_site = give_site[1:]
        give_list.append(give_site)

        # Process "accept" site. Remove N on the rigth (useless).
        accept_site = site[fw_cut + 1 :].replace("_", "")
        while accept_site[-1] == "N":
            accept_site = accept_site[:-1]
        accept_list.append(accept_site)

    # Iterates on the two list to build all the possible HiC ligation sites.
    for give_site in give_list:
        for accept_site in accept_list:
            # Replace "N" by "." for regex searching of the sites
            ligation_list.append((give_site + accept_site).replace("N", "."))
            ligation_list.append(
                str(Seq(give_site + accept_site).reverse_complement()).replace("N", ".")
            )

    # Build the regex for any ligation sites.
    pattern = "|".join(sorted(list(set(ligation_list))))
    return re.compile(pattern)

hicstuff.filter

Hi-C event filtering

Analyse the contents of a 3C library and filters spurious events such as loops and uncuts to improve the overall signal. Filtering consists in excluding +- and -+ Hi-C pairs if their reads are closer than a threshold in minimum number of restriction fragments. This threshold represents the distance at which the abundance of these events deviate significantly from the rest of the library. It is estimated automatically by default using the median absolute deviation of pairs at longer distances, but can also be entered manually.

The input is a pairs file whose mates have been assigned to restriction fragments, with 9 columns: readID, chr1, pos1, chr2, pos2, strand1, strand2, frag1, frag2. The fragment indices are 0-based, counted across the genome.

@author: cmdoret (reimplementation of Axel KournaK's code)

process_read_pair

process_read_pair(line)

Process and order read pairs in a .pairs record.

Takes a read pair (line) from a .pairs file as input, reorders the pair so that read 1 in intrachromosomal pairs always has the smallest genomic coordinate.

Parameters:

Name Type Description Default
line str

Record from a pairs file with columns: readID, chr1, pos1, chr2, pos2, strand1, strand2, frag1, frag2

required

Returns:

Type Description
dict

Dictionary with reordered pair where each column from the line as an entry. The number of restriction sites separating reads in the pair and the type of event are also stored in the dictionary, under keys "nsites" and "type".

Examples:

>>> d = process_read_pair("readX\ta\t1\tb\t20\t-\t-\t1\t3")
>>> for u in sorted(d.items()):
...     print(u)
('chr1', 'a')
('chr2', 'b')
('frag1', 1)
('frag2', 3)
('nsites', 2)
('pos1', 1)
('pos2', 20)
('readID', 'readX')
('strand1', '-')
('strand2', '-')
('type', 'inter')
>>> d = process_read_pair('readY\ta\t20\ta\t10\t-\t+\t2\t1')
>>> [d[x] for x in sorted(d.keys())]
['a', 'a', 1, 2, 1, 10, 20, 'readY', '+', '-', '+-']
Source code in src/hicstuff/filter.py
def process_read_pair(line):
    r"""Process and order read pairs in a .pairs record.

    Takes a read pair (line) from a .pairs file as input, reorders the pair
    so that read 1 in intrachromosomal pairs always has the smallest genomic
    coordinate.

    Parameters
    ----------
    line : str
        Record from a pairs file with columns: readID, chr1, pos1, chr2,
        pos2, strand1, strand2, frag1, frag2

    Returns
    -------
    dict
        Dictionary with reordered pair where each column from the line as an
        entry. The number of restriction sites separating reads in the pair and
        the type of event are also stored in the dictionary, under keys
        "nsites" and "type".

    Examples
    --------
        >>> d = process_read_pair("readX\ta\t1\tb\t20\t-\t-\t1\t3")
        >>> for u in sorted(d.items()):
        ...     print(u)
        ('chr1', 'a')
        ('chr2', 'b')
        ('frag1', 1)
        ('frag2', 3)
        ('nsites', 2)
        ('pos1', 1)
        ('pos2', 20)
        ('readID', 'readX')
        ('strand1', '-')
        ('strand2', '-')
        ('type', 'inter')
        >>> d = process_read_pair('readY\ta\t20\ta\t10\t-\t+\t2\t1')
        >>> [d[x] for x in sorted(d.keys())]
        ['a', 'a', 1, 2, 1, 10, 20, 'readY', '+', '-', '+-']
    """
    # Split line by whitespace
    p = line.split("\t")
    if len(p) != 9:
        raise ValueError(
            "Your input file does not have 9 columns. Make sure "
            "the file has the readID and twice the following 4 fields "
            "(once for each read in the pair): chr pos strand frag."
        )
    # Saving each column as a dictionary entry with meaningful key
    cols = [
        "readID",
        "chr1",
        "pos1",
        "chr2",
        "pos2",
        "strand1",
        "strand2",
        "frag1",
        "frag2",
    ]
    p = {cols[i]: p[i] for i in range(len(cols))}
    # Transforming numeric columns to int
    for col in ["pos1", "pos2", "frag1", "frag2"]:
        p[col] = int(p[col])

    # invert records for intrachromosomal pairs where rec2 comes before
    # rec1 in genomic coordinates
    if p["chr1"] == p["chr2"] and p["pos2"] < p["pos1"]:
        p["strand1"], p["strand2"] = p["strand2"], p["strand1"]
        p["pos1"], p["pos2"] = p["pos2"], p["pos1"]
        p["frag1"], p["frag2"] = p["frag2"], p["frag1"]

    # Number of restriction sites separating reads in the pair
    p["nsites"] = abs(p["frag2"] - p["frag1"])
    # Get event type
    if p["chr1"] == p["chr2"]:
        p["type"] = "".join([p["strand1"], p["strand2"]])
    else:
        p["type"] = "inter"

    return p

get_thresholds

get_thresholds(in_dat, interactive=False, plot_events=False, fig_path=None, prefix=None, sample_size=1000000)

Guess distance threshold for event filtering

Analyse the events in about a million Hi-C pairs drawn from the whole library, the same pairs whatever the order of the file, plot the occurrences of each event type according to number of restriction fragments, and ask user interactively for the minimum threshold for uncuts and loops.

Parameters:

Name Type Description Default
in_dat

Path to the .pairs file containing Hi-C pairs.

required
interactive

If True, plots are diplayed and thresholds are required interactively.

False
plot_events bool

Whether to show the plot

False
fig_path str

Path where the figure will be saved. If None, the figure will be diplayed interactively.

None
prefix str

If the library has a name, it will be shown on plots.

None
sample_size int

Number of pairs from which the thresholds are estimated. Larger libraries are sampled by a hash of each line, the same pairs whatever the order of the file. Smaller ones are used whole.

1000000

Returns:

Type Description
dictionary

dictionary with keys "uncuts" and "loops" where the values are the corresponding thresholds entered by the user.

Source code in src/hicstuff/filter.py
def get_thresholds(
    in_dat, interactive=False, plot_events=False, fig_path=None, prefix=None, sample_size=1_000_000
):
    """Guess distance threshold for event filtering

    Analyse the events in about a million Hi-C pairs drawn from the whole
    library, the same pairs whatever the order of the file, plot the
    occurrences of each event type according to number of restriction
    fragments, and ask user interactively for the minimum threshold for uncuts
    and loops.

    Parameters
    ----------
    in_dat: str
        Path to the .pairs file containing Hi-C pairs.
    interactive: bool
        If True, plots are diplayed and thresholds are required interactively.
    plot_events : bool
        Whether to show the plot
    fig_path : str
        Path where the figure will be saved. If None, the figure will be
        diplayed interactively.
    prefix : str
        If the library has a name, it will be shown on plots.
    sample_size : int
        Number of pairs from which the thresholds are estimated. Larger
        libraries are sampled by a hash of each line, the same pairs
        whatever the order of the file. Smaller ones are used whole.

    Returns
    -------
    dictionary
        dictionary with keys "uncuts" and "loops" where the values are the
        corresponding thresholds entered by the user.
    """
    thr_uncut = None
    thr_loop = None
    max_sites = 50
    # Map of event -> legend name of event for intrachromosomal pairs.
    legend = {
        "++": "++ (weird)",
        "--": "-- (weird)",
        "+-": "+- (uncuts)",
        "-+": "-+ (loops)",
    }
    colors = {"++": "#222222", "+-": "r", "--": "#666666", "-+": "tab:orange"}
    n_events = {event: np.zeros(max_sites) for event in legend}
    for line in _sample_pairs(in_dat, sample_size):
        # Process Hi-C pair into a dictionary
        p = process_read_pair(line)
        # Type of event and number of restriction site between reads
        etype = p["type"]
        nsites = p["nsites"]
        # Count number of events for intrachrom pairs
        if etype != "inter" and nsites < max_sites:
            n_events[etype][nsites] += 1

    def plot_event(n_events, legend, name):
        """Plot the frequency of a given event types over distance."""
        plt.xlim([-0.5, 15])
        plt.plot(
            range(n_events[name].shape[0]),
            n_events[name],
            "o-",
            label=legend[name],
            linewidth=2.0,
            c=colors[name],
        )

    if interactive:
        # PLot:
        try:
            plt.figure(0)
            for event in legend:
                plot_event(n_events, legend, event)
            plt.grid()
            plt.xlabel("Number of restriction fragment(s)")
            plt.ylabel("Number of events")
            plt.yscale("log")
            plt.legend()
            plt.show(block=False)

        except (OSError, RuntimeError):
            logger.warning(
                "Unable to show plots, skipping figure generation. Perhaps "
                "there is no Xserver running ? (might be due to windows "
                "environment). Try running without the interactive option."
            )

        # Asks the user for appropriate thresholds
        print(
            "Please enter the number of restriction fragments separating "
            "reads in a Hi-C pair below or at which loops and "
            "uncuts events will be excluded\n",
            file=sys.stderr,
        )
        thr_uncut = int(input("Enter threshold for the uncuts events (+-):"))
        thr_loop = int(input("Enter threshold for the loops events (-+):"))
        try:
            plt.clf()
        except (OSError, RuntimeError):
            pass
    else:
        # Estimate thresholds from data
        for event in n_events:
            fixed = n_events[event]
            fixed[fixed == 0] = 1
            n_events[event] = fixed

        all_events = np.log(np.array(list(n_events.values())))
        # Compute median occurences at each restriction sites
        event_med = np.median(all_events, axis=0)
        # Compute MAD, to have a robust estimator of the expected deviation
        # from median at long distances
        mad = np.median(abs(all_events - event_med))
        exp_stdev = mad / 0.67449
        # Iterate over sites, from furthest to frag+2
        for site in range(max_sites)[:1:-1]:
            # For uncuts and loops, keep the last (closest) site where the
            # deviation from other events <= expected_stdev
            if abs(np.log(n_events["+-"][site]) - event_med[site]) <= exp_stdev:
                thr_uncut = site
            if abs(np.log(n_events["-+"][site]) - event_med[site]) <= exp_stdev:
                thr_loop = site
        if thr_uncut is None or thr_loop is None:
            raise ValueError(
                "The threshold for loops or uncut could not be estimated. "
                "Please try running with -i to investigate the problem."
            )
        logger.info(f"Filtering with thresholds: uncuts={thr_uncut} loops={thr_loop}")
        if plot_events:
            try:
                plt.figure(1)
                plt.xlim([-0.5, 15])
                # Draw colored lines for events to discard
                plt.plot(
                    range(0, thr_uncut + 1),
                    n_events["+-"][: thr_uncut + 1],
                    "o-",
                    c=colors["+-"],
                    label=legend["+-"],
                )
                plt.plot(
                    range(0, thr_loop + 1),
                    n_events["-+"][: thr_loop + 1],
                    "o-",
                    c=colors["-+"],
                    label=legend["-+"],
                )
                plt.plot(
                    range(0, 2),
                    n_events["--"][:2],
                    "o-",
                    c=colors["--"],
                    label=legend["--"],
                )
                plt.plot(
                    range(0, 2),
                    n_events["++"][:2],
                    "o-",
                    c=colors["++"],
                    label=legend["++"],
                )
                # Draw black lines for events to keep
                plt.plot(
                    range(thr_uncut, n_events["+-"].shape[0]),
                    n_events["+-"][thr_uncut:],
                    "o-",
                    range(thr_loop, n_events["-+"].shape[0]),
                    n_events["-+"][thr_loop:],
                    "o-",
                    range(1, n_events["--"].shape[0]),
                    n_events["--"][1:],
                    "o-",
                    range(1, n_events["++"].shape[0]),
                    n_events["++"][1:],
                    "o-",
                    label="kept",
                    linewidth=2.0,
                    c="g",
                )
                plt.grid()
                plt.xlabel("Number of restriction site(s)")
                plt.ylabel("Number of events")
                plt.yscale("log")
                # Remove duplicate "kept" entries in legend
                handles, labels = plt.gca().get_legend_handles_labels()
                by_label = dict(zip(labels, handles))
                plt.legend(by_label.values(), by_label.keys())
                # Show uncut and loop threshold as vertical lines
                plt.axvline(x=thr_loop, color=colors["-+"])
                plt.axvline(x=thr_uncut, color=colors["+-"])

                if prefix:
                    plt.title(f"Library events by distance in {prefix}")
                plt.tight_layout()
                if fig_path:
                    plt.savefig(fig_path)
                else:
                    plt.show(block=False)

            except (OSError, RuntimeError):
                logger.warning(
                    "Unable to show plots, skipping figure generation. Is "
                    "an X server running? (might be due to windows "
                    "environment). Try running without the plot option."
                )
    return thr_uncut, thr_loop

filter_events

filter_events(in_dat, out_filtered, thr_uncut, thr_loop, plot_events=False, fig_path=None, prefix=None)

Filter events (loops, uncuts and weirds)

Filter out spurious intrachromosomal Hi-C pairs from input file. +- pairs with reads closer or at the uncut threshold and -+ pairs with reads closer or at the loop thresholds are excluded from the ouput file. -- and ++ pairs with both mates on the same fragments are also discarded. All others are written.

Parameters:

Name Type Description Default
in_dat file object

File handle in read mode to the 2D BED file containing Hi-C pairs.

required
out_filtered file object

File handle in write mode the output filtered 2D BED file.

required
thr_uncut int

Minimum number of restriction sites between reads to keep an intrachromosomal +- pair.

required
thr_loop int

Minimum number of restriction sites between reads to keep an intrachromosomal -+ pair.

required
plot_events bool

If True, a plot showing the proportion of each type of event will be shown after filtering.

False
fig_path str

Path where the figure will be saved. If None, figure is displayed interactively.

None
prefix str

If the library has a name, it will be shown on plots.

None
Source code in src/hicstuff/filter.py
def filter_events(
    in_dat,
    out_filtered,
    thr_uncut,
    thr_loop,
    plot_events=False,
    fig_path=None,
    prefix=None,
):
    """Filter events (loops, uncuts and weirds)

    Filter out spurious intrachromosomal Hi-C pairs from input file. +- pairs
    with reads closer or at the uncut threshold and -+ pairs with reads closer
    or at the loop thresholds are excluded from the ouput file. -- and ++ pairs
    with both mates on the same fragments are also discarded. All others are
    written.

    Parameters
    ----------
    in_dat : file object
        File handle in read mode to the 2D BED file containing Hi-C pairs.
    out_filtered : file object
        File handle in write mode the output filtered 2D BED file.
    thr_uncut : int
        Minimum number of restriction sites between reads to keep an
        intrachromosomal +- pair.
    thr_loop : int
        Minimum number of restriction sites between reads to keep an
        intrachromosomal -+ pair.
    plot_events : bool
        If True, a plot showing the proportion of each type of event will be
        shown after filtering.
    fig_path : str
        Path where the figure will be saved. If None, figure is displayed
        interactively.
    prefix : str
        If the library has a name, it will be shown on plots.
    """
    n_uncuts = 0
    n_loops = 0
    n_weirds = 0
    lrange_intra = 0
    lrange_inter = 0

    # open the files for reading and writing
    with open(in_dat) as pairs, open(out_filtered, "w") as filtered:
        for line in pairs:  # iterate over each line
            # Copy header lines to output
            if line.startswith("#"):
                filtered.write(line)
                continue

            p = process_read_pair(line)
            line_to_write = (
                "\t".join(
                    map(
                        str,
                        (
                            p["readID"],
                            p["chr1"],
                            p["pos1"],
                            p["chr2"],
                            p["pos2"],
                            p["strand1"],
                            p["strand2"],
                            p["frag1"],
                            p["frag2"],
                        ),
                    )
                )
                + "\n"
            )
            if p["chr1"] == p["chr2"]:
                # Do not report ++ and -- pairs on the same fragment (impossible)
                if p["frag1"] == p["frag2"] and p["strand1"] == p["strand2"]:
                    n_weirds += 1
                elif p["nsites"] <= thr_loop and p["type"] == "-+":
                    n_loops += 1
                elif p["nsites"] <= thr_uncut and p["type"] == "+-":
                    n_uncuts += 1
                else:
                    lrange_intra += 1
                    filtered.write(line_to_write)

            if p["chr1"] != p["chr2"]:
                lrange_inter += 1
                filtered.write(line_to_write)

    if lrange_inter > 0:
        ratio_inter = round(100 * lrange_inter / float(lrange_intra + lrange_inter), 2)
    else:
        ratio_inter = 0

    # Log quick summary of operation results
    kept = lrange_intra + lrange_inter
    discarded = n_loops + n_uncuts + n_weirds
    total = kept + discarded
    logger.info(
        f"Proportion of inter contacts: {ratio_inter}% (intra: {lrange_intra}, "
        f"inter: {lrange_inter})"
    )
    logger.info(
        f"{discarded} pairs discarded: Loops: {n_loops}, Uncuts: {n_uncuts}, Weirds: {n_weirds}"
    )
    logger.info(f"{kept} pairs kept ({round(100 * kept / (kept + discarded), 2)}%)")

    # Visualize summary if requested by user
    if plot_events:
        try:
            # Plot: make a square figure and axes to plot a pieChart:
            plt.figure(2, figsize=(6, 6))
            # The slices will be ordered and plotted counter-clockwise.
            fracs = [n_uncuts, n_loops, n_weirds, lrange_intra, lrange_inter]
            # Format labels to include event names and proportion
            labels = list(
                map(
                    lambda x: (x[0] + ": %.2f%%") % (100 * x[1] / total),
                    [
                        ("Uncuts", n_uncuts),
                        ("Loops", n_loops),
                        ("Weirds", n_weirds),
                        ("3D intra", lrange_intra),
                        ("3D inter", lrange_inter),
                    ],
                )
            )
            colors = ["salmon", "lightskyblue", "yellow", "palegreen", "plum"]
            patches, _ = plt.pie(fracs, colors=colors, startangle=90)
            plt.legend(
                patches,
                labels,
                loc="upper left",
                bbox_to_anchor=(-0.1, 1.0),
            )
            if prefix:
                plt.title(
                    f"Distribution of library events in {prefix}",
                    bbox={"facecolor": "1.0", "pad": 5},
                )
            plt.text(
                0.3,
                1.15,
                "Threshold Uncuts = " + str(thr_uncut),
                fontdict=None,
            )
            plt.text(
                0.3,
                1.05,
                "Threshold Loops = " + str(thr_loop),
                fontdict=None,
            )

            plt.text(
                -1.5,
                -1.2,
                "Total number of reads = " + str(total),
                fontdict=None,
            )
            plt.text(
                -1.5,
                -1.3,
                "Ratio inter/(intra+inter) = " + str(ratio_inter) + "%",
                fontdict=None,
            )
            percentage = round(
                100
                * float(lrange_inter + lrange_intra)
                / (n_loops + n_uncuts + n_weirds + lrange_inter + lrange_intra)
            )
            plt.text(
                -1.5,
                -1.4,
                f"Selected reads = {percentage}%",
                fontdict=None,
            )
            if fig_path:
                plt.savefig(fig_path)
            else:
                plt.show()
            plt.clf()
        except (OSError, RuntimeError):
            logger.warning(
                "Unable to show plots. Perhaps there is no Xserver running ?"
                "(might be due to windows environment) skipping figure "
                "generation."
            )