Skip to content

Distance law

hicstuff.distance_law computes the distance law from a pairs file (get_distance_law), reads and writes its tables (import_distance_law, export_distance_law), normalises and averages the curves (normalize_distance_law, average_distance_law) and plots them with their slope (plot_ps_slope). See The distance law.

hicstuff.distance_law

export_distance_law

export_distance_law(xs, ps, names, out_file=None)

Export the x(s) and p(s) from two list of numpy.ndarrays to a table in txt file with three columns separated by a tabulation. The first column contains the x(s), the second the p(s) and the third the name of the arm or chromosome. The file is created in the directory given by outdir or the current file if no file is given.

Parameters:

Name Type Description Default
xs list of numpy.ndarray

The list of the start position of logbins of each p(s) in base pairs.

required
ps list of numpy.ndarray

The list of p(s).

required
names list of string

List containing the names of the chromosomes/arms/conditions of the p(s) values given.

required
out_file str or None

Path where output file should be written. ./distance_law.txt by default.

None
Return

txt file: File with three columns separated by a tabulation. The first column contains the x(s), the second the p(s) and the third the name of the arm or chromosome. The file is creates in the output file given or the default one if none given.

Source code in src/hicstuff/distance_law.py
def export_distance_law(xs, ps, names, out_file=None):
    """Export the x(s) and p(s) from two list of numpy.ndarrays to a table
    in txt file with three columns separated by a tabulation. The first column
    contains the x(s), the second the p(s) and the third the name of the arm or
    chromosome. The file is created in the directory given by outdir or the
    current file if no file is given.

    Parameters
    ----------
    xs : list of numpy.ndarray
        The list of the start position of logbins of each p(s) in base pairs.
    ps : list of numpy.ndarray
        The list of p(s).
    names : list of string
        List containing the names of the chromosomes/arms/conditions of the p(s)
        values given.
    out_file : str or None
        Path where output file should be written. ./distance_law.txt by default.

    Return
    ------
    txt file:
        File with three columns separated by a tabulation. The first column
        contains the x(s), the second the p(s) and the third the name of the arm
        or chromosome. The file is creates in the output file given or the
        default one if none given.
    """
    # ./distance_law.txt as out_file if no out_file is given.
    if out_file is None:
        out_file = os.getcwd() + "/distance_law.txt"
    # Sanity check: as many chromosomes/arms as ps
    if len(xs) != len(names):
        logger.error("Number of chromosomes/arms and number of p(s) list differ.")
        sys.exit(1)
    # Create the file and write it
    with open(out_file, "w") as f:
        f.write(f"## hicstuff v{__version__}\n")
        f.write("## distance_law\n")
        f.write("## columns: start_bp\tp(s)\tchrom\n")
        for i in range(len(xs)):
            for j in range(len(xs[i])):
                line = (
                    str(format(xs[i][j], "g"))
                    + "\t"
                    + str(format(ps[i][j], "g"))
                    + "\t"
                    + names[i]
                    + "\n"
                )
                f.write(line)

import_distance_law

import_distance_law(distance_law_file)

Import the table created by export_distance_law and return the list of x(s) and p(s) in the order of the chromosomes.

Parameters:

Name Type Description Default
distance_law_file string

Path to the file containing three columns : the x(s), the p(s), and the chromosome/arm name.

required

Returns:

Type Description
list of numpy.ndarray :

The start coordinate of each bin one array per chromosome or arm.

list of numpy.ndarray :

The distance law probabilities corresponding of the bins of the previous list.

list of numpy.ndarray :

The names of the arms/chromosomes corresponding to the previous list.

Source code in src/hicstuff/distance_law.py
def import_distance_law(distance_law_file):
    """Import the table created by export_distance_law and return the list of
    x(s) and p(s) in the order of the chromosomes.

    Parameters
    ----------
    distance_law_file : string
        Path to the file containing three columns : the x(s), the p(s), and the
        chromosome/arm name.

    Returns
    -------
    list of numpy.ndarray :
        The start coordinate of each bin one array per chromosome or arm.
    list of numpy.ndarray :
        The distance law probabilities corresponding of the bins of the
        previous list.
    list of numpy.ndarray :
        The names of the arms/chromosomes corresponding to the previous
        list.
    """
    file = pd.read_csv(
        distance_law_file,
        sep="\t",
        header=None,
        comment="#",
        dtype={"a": np.int32, "b": np.float32, "c": str},
    )
    names_idx = np.unique(file.iloc[:, 2], return_index=True)[1]
    names = [file.iloc[:, 2][index] for index in sorted(names_idx)]
    xs = [None] * len(names)
    ps = [None] * len(names)
    labels = [None] * len(names)
    for i in range(len(names)):
        subfile = file[file.iloc[:, 2] == names[i]]
        xs[i] = np.array(subfile.iloc[:, 0])
        ps[i] = np.array(subfile.iloc[:, 1])
        labels[i] = np.array(subfile.iloc[:, 2])
    return xs, ps, labels

get_distance_law

get_distance_law(pairs_reads_file, fragments_file=None, centro_file=None, base=1.1, out_file=None, circular=False, rm_centro=0)

Compute distance law as a function of the genomic coordinate aka P(s). Bin length increases exponentially with distance. Works on pairs file format from 4D Nucleome Omics Data Standards Working Group. If the genome is composed of several chromosomes and you want to compute the arms separately, provide a file with the positions of centromers. Create a file with three coulumns separated by a tabulation. The first column contains the xs, the second the ps and the third the name of the arm or chromosome. The file is create in the directory given in outdir or in the current directory if no directory given.

When fragments_file is not provided, chromosome sizes are read from the #chromsize: lines of the pairs header and distances are computed directly as abs(pos2 - pos1). This mode is compatible with plain 4DN standard pairs files (with or without frag columns) and with gzip-compressed files. Centromere splitting is not supported in this mode.

Parameters:

Name Type Description Default
pairs_reads_file string

Path of a pairs file format from 4D Nucleome Omics Data Standards Working Group. When fragments_file is provided, the 8th and 9th columns are expected to contain the fragment IDs of reads 1 and 2.

required
fragments_file path or None

Path of a table containing in the first column the ID of the fragment, in the second the names of the chromosome in the third and fourth the start position and the end position of the fragment. The file have no header. (File like the 'fragments_list.txt' from hicstuff). When None, chromosome information is inferred from the pairs header and distances are computed from read positions directly.

None
centro_file None or str

None or path to a file with the genomic positions of the centromers sorted as the chromosomes separated by a space. The file have only one line. Requires fragments_file.

None
base float

Base use to construct the logspace of the bins - 1.1 by default.

1.1
out_file None or str

Path of the output file. If no path given, the output is returned.

None
circular bool

If True, calculate the distance as the chromosome is circular. Default value is False. Cannot be True if centro_file is not None

False
rm_centro int

If a value is given, will remove the contacts close the centromeres. It will remove as many kb as the argument given. Default is None.

0

Returns:

Name Type Description
xs list of numpy.ndarray

Basepair coordinates of log bins used to compute distance law.

ps list of numpy.ndarray

Contacts value, in arbitrary units, at increasingly long genomic ranges given by xs.

names list of strings

Names of chromosomes that are plotted

Source code in src/hicstuff/distance_law.py
def get_distance_law(
    pairs_reads_file,
    fragments_file=None,
    centro_file=None,
    base=1.1,
    out_file=None,
    circular=False,
    rm_centro=0,
):
    """Compute distance law as a function of the genomic coordinate aka P(s).
    Bin length increases exponentially with distance. Works on pairs file
    format from 4D Nucleome Omics Data Standards Working Group. If the genome
    is composed of several chromosomes and you want to compute the arms
    separately, provide a file with the positions of centromers. Create a file
    with three coulumns separated by a tabulation. The first column contains
    the xs, the second the ps and the third the name of the arm or chromosome.
    The file is create in the directory given in outdir or in the current
    directory if no directory given.

    When ``fragments_file`` is not provided, chromosome sizes are read from the
    ``#chromsize:`` lines of the pairs header and distances are computed
    directly as ``abs(pos2 - pos1)``.  This mode is compatible with plain 4DN
    standard pairs files (with or without frag columns) and with
    gzip-compressed files.  Centromere splitting is not supported in this mode.

    Parameters
    ----------
    pairs_reads_file : string
        Path of a pairs file format from 4D Nucleome Omics Data Standards
        Working Group. When ``fragments_file`` is provided, the 8th and 9th
        columns are expected to contain the fragment IDs of reads 1 and 2.
    fragments_file : path or None
        Path of a table containing in the first column the ID of the fragment,
        in the second the names of the chromosome in the third and fourth
        the start position and the end position of the fragment. The file have
        no header. (File like the 'fragments_list.txt' from hicstuff).
        When None, chromosome information is inferred from the pairs header and
        distances are computed from read positions directly.
    centro_file : None or str
        None or path to a file with the genomic positions of the centromers
        sorted as the chromosomes separated by a space. The file have only one
        line.  Requires ``fragments_file``.
    base : float
        Base use to construct the logspace of the bins - 1.1 by default.
    out_file : None or str
        Path of the output file. If no path given, the output is returned.
    circular : bool
        If True, calculate the distance as the chromosome is circular. Default
        value is False. Cannot be True if centro_file is not None
    rm_centro : int
        If a value is given, will remove the contacts close the centromeres.
        It will remove as many kb as the argument given. Default is None.

    Returns
    -------
    xs : list of numpy.ndarray
        Basepair coordinates of log bins used to compute distance law.
    ps : list of numpy.ndarray
        Contacts value, in arbitrary units, at increasingly long genomic ranges
        given by xs.
    names : list of strings
        Names of chromosomes that are plotted
    """
    # Sanity check : centro_fileition should be None if chromosomes are
    # circulars (no centromeres is circular chromosomes).
    if circular and centro_file is not None:
        logger.error("Chromosomes cannot have a centromere and be circular")
        sys.exit(1)

    if fragments_file is None:
        # Position-based path: derive chromosome info from the pairs header and
        # compute distances as abs(pos2 - pos1).
        if centro_file is not None:
            logger.error(
                "Centromere splitting requires a fragments file (--frags). "
                "Please provide --frags or omit --centromeres."
            )
            sys.exit(1)
        chrom_sizes, columns = _get_chrom_info_from_pairs(pairs_reads_file)
        if not chrom_sizes:
            logger.error(
                "No #chromsize entries found in pairs header. "
                "Please provide --frags or add chromsize lines to the pairs header."
            )
            sys.exit(1)
        chr_names = list(chrom_sizes.keys())
        chr_segment_length = list(chrom_sizes.values())
        chr_to_idx = {name: i for i, name in enumerate(chr_names)}
        xs = _logbins_xs(None, chr_segment_length, base, circular)
        ps = [[0] * len(xs[i]) for i in range(len(xs))]
        # Determine fieldnames from header columns, falling back to 7-column standard
        if columns is not None:
            fieldnames = columns
        else:
            fieldnames = [
                "readID",
                "chr1",
                "pos1",
                "chr2",
                "pos2",
                "strand1",
                "strand2",
            ]
        with hio.read_compressed(pairs_reads_file) as reads:
            # Skip header lines
            raw_line = reads.readline()
            while raw_line.startswith("#"):
                raw_line = reads.readline()
            # raw_line now holds the first data line; stream it together with the
            # remaining lines so the file is never fully loaded into memory
            reader = csv.DictReader(
                itertools.chain([raw_line], reads),
                fieldnames=fieldnames,
                delimiter="\t",
            )
            for line in reader:
                _get_pairs_distance_pos(line, chr_to_idx, chr_segment_length, xs, ps, circular)
        # Normalise by logbin area (same formula as fragment-based path)
        for i in range(len(xs)):
            n = chr_segment_length[i]
            for j in range(len(xs[i]) - 1):
                ps[i][j] /= ((2 * n - xs[i][j + 1] - xs[i][j]) / 2) * (
                    (1 / np.sqrt(2)) * (xs[i][j + 1] - xs[i][j])
                )
            ps[i][-1] /= ((n - xs[i][-1]) ** 2) / 2
        names = chr_names
        if out_file:
            export_distance_law(xs, ps, names, out_file)
        return xs, ps, names

    # Fragment-based path (original behaviour): requires fragments_file.
    # Import third columns of fragments file
    fragments = pd.read_csv(fragments_file, sep="\t", header=0, usecols=[0, 1, 2, 3])
    # Make sure chrom names column in fragment df are character
    col = fragments.columns[1]
    fragments[col] = fragments[col].astype(str)
    # Calculate the indice of the bins to separate into chromosomes/arms
    chr_segment_bins = _get_chr_segment_bins_index(fragments, centro_file, rm_centro)
    # Calculate the length of each chromosoms/arms
    chr_segment_length = _get_chr_segment_length(fragments, chr_segment_bins)
    xs = _logbins_xs(fragments, chr_segment_length, base, circular)
    # Create the list of p(s) with one array for each chromosome/arm and each
    # array contain as many values as in the logbin
    ps = [None] * len(chr_segment_length)
    for i in range(len(xs)):
        ps[i] = [0] * len(xs[i])
    # Every pair looks up the segment and the coordinates of its fragments:
    # build the arrays once. np.searchsorted on the list converts it to an
    # array on every call, which made each pair cost O(chromosomes).
    segment_bins = np.asarray(chr_segment_bins)
    frag_pos = {col: fragments[col].to_numpy() for col in ("start_pos", "end_pos")}
    # Read the pair reads file (supports plain and gzip-compressed files)
    with hio.read_compressed(pairs_reads_file) as reads:
        # Skip header lines (lines starting with '#')
        raw_line = reads.readline()
        while raw_line.startswith("#"):
            raw_line = reads.readline()
        # raw_line is the first data line; stream it together with the remaining
        # lines so the file is never fully loaded into memory.
        # Reads all the others lines and put the values in a dictionnary with
        # the keys : 'readID', 'chr1', 'pos1', 'chr2', 'pos2', 'strand1',
        # 'strand2', 'frag1', 'frag2'
        reader = csv.DictReader(
            itertools.chain([raw_line], reads),
            fieldnames=[
                "readID",
                "chr1",
                "pos1",
                "chr2",
                "pos2",
                "strand1",
                "strand2",
                "frag1",
                "frag2",
            ],
            delimiter="\t",
        )
        for line in reader:
            _get_pairs_distance(line, frag_pos, segment_bins, chr_segment_length, xs, ps, circular)
    # Divide the number of contacts by the area of the logbin
    for i in range(len(xs)):
        n = chr_segment_length[i]
        for j in range(len(xs[i]) - 1):
            ps[i][j] /= ((2 * n - xs[i][j + 1] - xs[i][j]) / 2) * (
                (1 / np.sqrt(2)) * (xs[i][j + 1] - xs[i][j])
            )
        ps[i][-1] /= ((n - xs[i][-1]) ** 2) / 2
    names = _get_names(fragments, chr_segment_bins)
    if out_file:
        export_distance_law(xs, ps, names, out_file)
    return xs, ps, names

normalize_distance_law

normalize_distance_law(xs, ps, inf=3000, sup=None)

Normalize the distance in order to have the sum of the ps values between 'inf' (default value is 3kb) until the end of the array equal to one and limit the effect of coverage between two conditions/chromosomes/arms when you compare them together. If we have a list of ps, it will normalize until the length of the shorter object or the value of sup, whichever is smaller.

Parameters:

Name Type Description Default
xs list of numpy.ndarray

list of logbins corresponding to the ps.

required
ps list of numpy.ndarray

Average ps or list of ps of the chromosomes/arms. xs and ps have to have the same shape.

required
inf integer

Inferior value of the interval on which, the normalization is applied.

3000
sup integer

Superior value of the interval on which, the normalization is applied.

None

Returns:

Type Description
list of numpy.ndarray :

List of ps each normalized separately.

Source code in src/hicstuff/distance_law.py
def normalize_distance_law(xs, ps, inf=3000, sup=None):
    """Normalize the distance in order to have the sum of the ps values between
    'inf' (default value is 3kb) until the end of the array equal to one and
    limit the effect of coverage between two conditions/chromosomes/arms when
    you compare them together. If we have a list of ps, it will normalize until
    the length of the shorter object or the value of sup, whichever is smaller.

    Parameters
    ----------
    xs : list of numpy.ndarray
        list of logbins corresponding to the ps.
    ps : list of numpy.ndarray
        Average ps or list of ps of the chromosomes/arms. xs and ps have to
        have the same shape.
    inf : integer
        Inferior value of the interval on which, the normalization is applied.
    sup : integer
        Superior value of the interval on which, the normalization is applied.

    Returns
    -------
    list of numpy.ndarray :
        List of ps each normalized separately.
    """
    # Sanity check: xs and ps have the same dimension
    if np.shape(np.asarray(xs, dtype="object")) != np.shape(np.asarray(ps, dtype="object")):
        logger.error("xs and ps should have the same dimension.")
        sys.exit(1)
    # Define the length of shortest chromosomes as a lower bound for the sup boundary
    min_xs = len(min(xs, key=len))
    normed_ps = [None] * len(ps)
    if sup is None:
        sup = np.inf
    for chrom_id, chrom_ps in enumerate(ps):
        # Iterate on the different ps to normalize each of theme separately
        chrom_sum = 0
        # Change the last value to have something continuous because the last
        # one is much bigger (computed on matrix corner = triangle instead of trapezoid).
        chrom_ps[-1] = chrom_ps[-2]
        for bin_id, bin_value in enumerate(chrom_ps):
            # Compute normalization factor based on values between inf and sup
            # Sup will be whatever is smaller between user-provided sup and length of
            # the shortest chromosome
            if (xs[chrom_id][bin_id] > inf) and (xs[chrom_id][bin_id] < sup) and (bin_id < min_xs):
                chrom_sum += bin_value
        if chrom_sum == 0:
            chrom_sum += 1
            logger.warning("No values of p(s) in one segment")
        # Make the normalisation
        normed_ps[chrom_id] = np.array(ps[chrom_id]) / chrom_sum
    return normed_ps

average_distance_law

average_distance_law(xs, ps, sup, big_arm_only=False)

Compute the average distance law between the file the different distance law of the chromosomes/arms.

Parameters:

Name Type Description Default
xs list of numpy.ndarray

The list of logbins.

required
ps list of lists of floats

The list of numpy.ndarray.

required
sup int

Value given to set the minimum size of the chromosomes/arms to make the average.

required
big_arm_only bool

By default False. If True, will only take into account the arms/chromosomes longer than the value of sup. Sup mandatory if set.

False

Returns:

Type Description
numpy.ndarray :

List of the xs with the max length.

numpy.ndarray :

List of the average_ps.

Source code in src/hicstuff/distance_law.py
def average_distance_law(xs, ps, sup, big_arm_only=False):
    """Compute the average distance law between the file the different distance
    law of the chromosomes/arms.

    Parameters
    ----------
    xs : list of numpy.ndarray
        The list of logbins.
    ps : list of lists of floats
        The list of numpy.ndarray.
    sup : int
        Value given to set the minimum size of the chromosomes/arms to make the
        average.
    big_arm_only : bool
        By default False. If True, will only take into account the arms/chromosomes
        longer than the value of sup. Sup mandatory if set.

    Returns
    -------
    numpy.ndarray :
        List of the xs with the max length.
    numpy.ndarray :
        List of the average_ps.
    """
    # Find longest chromosome / arm and make two arrays of this length for the
    # average distance law and remove the last value.
    xs = max(xs, key=len)
    max_length = len(xs)
    ps_values = np.zeros(max_length)
    ps_occur = np.zeros(max_length)
    for chrom_ps in ps:
        # Iterate on ps in order to calculate the number of occurences (all the
        # chromossomes/arms are not as long as the longest one) and the sum of
        # the values of distance law.
        # Change the last value to have something continuous because the last
        # one is much bigger.
        chrom_ps[-1] = chrom_ps[-2]
        # Sanity check : sup strictly inferior to maw length arms.
        if big_arm_only:
            if sup >= xs[-1]:
                logger.error(
                    "sup have to be inferior to the max length of arms/chromsomes if big arm only set"
                )
                sys.exit(1)
            if sup <= xs[len(chrom_ps) - 1]:
                ps_occur[: len(chrom_ps)] += 1
                ps_values[: len(chrom_ps)] += chrom_ps
        else:
            ps_occur[: len(chrom_ps)] += 1
            ps_values[: len(chrom_ps)] += chrom_ps
    # Make the mean
    averaged_ps = ps_values / ps_occur
    return xs, averaged_ps

slope_distance_law

slope_distance_law(xs, ps)

Compute the slope of the loglog curve of the ps as the [log(ps(n+1)) - log(ps(n))] / [log(n+1) - log(n)]. Compute only list of ps, not list of array.

Parameters:

Name Type Description Default
xs list of numpy.ndarray

The list of logbins.

required
ps list of numpy.ndarray

The list of ps.

required

Returns:

Type Description
list of numpy.ndarray :

The slope of the distance law. It will be shorter of one value than the ps given initially.

Source code in src/hicstuff/distance_law.py
def slope_distance_law(xs, ps):
    """Compute the slope of the loglog curve of the ps as the
    [log(ps(n+1)) - log(ps(n))] / [log(n+1) - log(n)].
    Compute only list of ps, not list of array.

    Parameters
    ----------
    xs : list of numpy.ndarray
        The list of logbins.
    ps : list of numpy.ndarray
        The list of ps.

    Returns
    -------
    list of numpy.ndarray :
        The slope of the distance law. It will be shorter of one value than the
        ps given initially.
    """
    slope = [None] * len(ps)
    for i in range(len(ps)):
        ps[i][ps[i] == 0] = 10 ** (-9)
        # Compute the slope
        slope_temp = np.log(np.array(ps[i][1:]) / np.array(ps[i][:-1])) / np.log(
            np.array(xs[i][1:]) / np.array(xs[i][:-1])
        )
        # The 1.8 is the intensity of the normalisation, it could be adapted.
        slope_temp[np.isnan(slope_temp)] = 10 ** (-15)
        slope[i] = ndimage.filters.gaussian_filter1d(slope_temp, 1.8)
    return slope

get_ylim

get_ylim(xs, curve, inf, sup)

Compute the max and the min of the list of list between the inferior (inf) and superior (sup) bounds.

Parameters:

Name Type Description Default
xs list of numpy.ndarray

The list of the logbins starting position in basepair.

required
curve list of numpy.ndarray

A list of numpy.ndarray from which you want to extract minimum and maximum values in a given interval.

required
inf int

Inferior limit of the interval in basepair.

required
sup int

Superior limit of the interval in basepair.

required

Returns:

Name Type Description
min_tot float

Minimum value of the list of list in this interval.

max_tot float

Maximum value of the list of list in this interval.

Examples:

>>> get_ylim([np.array([1, 4, 15]), np.array([1, 4, 15, 40])],
... [np.array([5.5, 3.2, 17.10]), np.array([24, 32, 1.111, 18.5])],
... 2,
... 15
... )
(1.111, 32.0)
Source code in src/hicstuff/distance_law.py
def get_ylim(xs, curve, inf, sup):
    """Compute the max and the min of the list of list between the inferior
    (inf) and superior (sup) bounds.

    Parameters
    ----------
    xs : list of numpy.ndarray
        The list of the logbins starting position in basepair.
    curve : list of numpy.ndarray
        A list of numpy.ndarray from which you want to extract minimum and
        maximum values in a given interval.
    inf : int
        Inferior limit of the interval in basepair.
    sup : int
        Superior limit of the interval in basepair.

    Returns
    -------
    min_tot : float
        Minimum value of the list of list in this interval.
    max_tot : float
        Maximum value of the list of list in this interval.

    Examples
    --------
    >>> get_ylim([np.array([1, 4, 15]), np.array([1, 4, 15, 40])],
    ... [np.array([5.5, 3.2, 17.10]), np.array([24, 32, 1.111, 18.5])],
    ... 2,
    ... 15
    ... )
    (1.111, 32.0)
    """
    # Create a list in order to add all the interesting values
    flatten_list = []
    for i, logbins in enumerate(xs):
        # Iterate on xs.
        # Search for the minimum index corresponding to the smallest bin
        # superior or equal to inf (in pair base).
        min_value = min(logbins[logbins >= inf], default=0)
        min_index = np.where(logbins == min_value)[0]
        # Skip chromosome if total size smaller than inf
        if len(min_index) == 0:
            continue
        min_index = int(min_index[0])
        # Search for the maximum index corresponding to the biggest bin
        # inferior or equal to sup (in pair base).
        max_value = max(logbins[logbins <= sup])
        max_index = int(np.where(logbins == max_value)[0][0])
        # Add the values in the interval in the flattened list.
        if max_index != len(logbins) - 1:
            max_index += 1
        for j in range(min_index, max_index):
            flatten_list.append(curve[i][j])
    # Calculate the min and the max of this list.
    min_tot = float(min(flatten_list))
    max_tot = float(max(flatten_list))
    return min_tot, max_tot

plot_ps_slope

plot_ps_slope(xs, ps, labels, fig_path=None, inf=3000, sup=None)

Compute two plots, one with the different distance law of each arm/chromosome in loglog scale and one with the slope (derivative) of these curves. Generate a svg file with savefig.

Parameters:

Name Type Description Default
xs list of numpy.ndarray

The list of the logbins of each ps.

required
ps list of numpy.ndarray

The list of ps.

required
labels list of strings

Names of the different curves in the order in which they are given.

required
fig_path str

Path where the figure will be created. If None (default), the plot is shown in an interactive window.

None
inf int

Value of the mimimum x of the window of the plot. Have to be strictly positive. By default 3000.

3000
sup int

Value of the maximum x of the window of the plot. By default None.

None
Source code in src/hicstuff/distance_law.py
def plot_ps_slope(xs, ps, labels, fig_path=None, inf=3000, sup=None):
    """Compute two plots, one with the different distance law of each
    arm/chromosome in loglog scale and one with the slope (derivative) of these
    curves. Generate a svg file with savefig.

    Parameters
    ----------
    xs : list of numpy.ndarray
        The list of the logbins of each ps.
    ps : list of numpy.ndarray
        The list of ps.
    labels : list of strings
        Names of the different curves in the order in which they are given.
    fig_path : str
        Path where the figure will be created. If None (default), the plot is
        shown in an interactive window.
    inf : int
        Value of the mimimum x of the window of the plot. Have to be strictly
        positive. By default 3000.
    sup : int
        Value of the maximum x of the window of the plot. By default None.

    """
    # Give the max value for sup if no value have been attributed
    if sup is None:
        sup = max(max(xs, key=len))

    # Compute slopes from the curves
    slope = slope_distance_law(xs, ps)
    # Make the plot of distance law
    # Give a range of color
    cols = iter(cm.rainbow(np.linspace(0, 1, len(ps))))
    fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, figsize=(18, 10))
    plt.subplots_adjust(left=0.05, right=0.85, top=0.93, bottom=0.07)
    ax1.set_xlabel("Distance (pb)", fontsize="x-large")
    ax1.set_ylabel("P(s)", fontsize="x-large")
    ax1.set_title("Distance law", fontsize="xx-large")
    ylim = get_ylim(xs, ps, inf, sup)
    ax1.set_ylim(0.9 * ylim[0], 1.1 * ylim[1])
    for i in range(len(ps)):
        # Iterate on the different distance law array and take them by order of
        # size in order to have the color scale equivalent to the size scale
        next(cols)
        ax1.loglog(xs[i], ps[i], label=labels[i])
    # Make the same plot with the slope
    cols = iter(cm.rainbow(np.linspace(0, 1, len(slope))))
    ax2.set_xlabel("Distance (pb)", fontsize="x-large")
    ax2.set_ylabel("Slope", fontsize="x-large")
    ax2.set_title("Slope of the distance law", fontsize="xx-large")
    ax2.set_xlim([inf, sup])
    ylim = get_ylim(xs, slope, inf, sup)
    ax2.set_ylim(1.1 * ylim[0], 0.9 * ylim[1])
    xs2 = [None] * len(xs)
    for i in range(len(slope)):
        xs2[i] = xs[i][:-1]
        next(cols)
        ax2.semilogx(xs2[i], slope[i], label=labels[i], subs=[2, 3, 4, 5, 6, 7, 8, 9])
    ax2.legend(loc="upper left", bbox_to_anchor=(1.02, 1.00), ncol=1, fontsize="large")
    # Save the figure in svg
    if fig_path is not None:
        plt.savefig(fig_path)
    else:
        plt.show()