Input and output¶
hicstuff.io reads and writes contact maps in hicstuff's three formats, and
the files around them: pairs, genomes, aligner indexes.
| To | Use |
|---|---|
| Read a map in any format | flexible_hic_loader |
| Write a map in any format | flexible_hic_saver |
| Tell a map's format | get_hic_format |
| Read or write one format | load_cool, save_cool, load_sparse_matrix, save_sparse_matrix, load_bedgraph2d, save_bedgraph2d |
| Sort a pairs file | sort_pairs |
| Find an aligner's index | check_fasta_index |
File formats describes the files.
hicstuff.io ¶
load_sparse_matrix ¶
Load sparse matrix
Load a text file matrix into a sparse matrix object. The expected format is a 3 column file where columns are row_number, col_number, value. The first line consists of 3 values representing the total number of rows, columns and nonzero values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mat_path
|
(file, str or Path)
|
The input matrix file in instagraal format. |
required |
binning
|
int or auto
|
The binning to perform. If "auto", binning will be automatically inferred so that the matrix size will not go beyond (10000, 10000) in shape. That can be changed by modifying the DEFAULT_MAX_MATRIX_SHAPE value. Default is 1, i.e. no binning is performed |
1
|
dtype
|
type
|
The type of data being loaded. Default is numpy.float64 |
float64
|
Returns:
| Name | Type | Description |
|---|---|---|
sparse_mat |
coo_matrix
|
The output (sparse) matrix in COOrdinate format. |
Examples:
>>> S = load_sparse_matrix('test_data/mat_5kb.tsv', binning=1)
>>> S.data[:10]
array([84., 2., 3., 2., 1., 1., 50., 1., 66., 1.])
>>> S.shape
(16, 16)
Source code in src/hicstuff/io.py
save_sparse_matrix ¶
Save a sparse matrix
Saves a sparse matrix object into tsv format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
s_mat
|
coo_matrix
|
The sparse matrix to save on disk |
required |
path
|
str
|
File path where the matrix will be stored |
required |
Source code in src/hicstuff/io.py
load_pos_col ¶
Loads a single column of a TSV file with header into a numpy array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The path of the TSV file to load. |
required |
colnum
|
int
|
The 0-based index of the column to load. |
required |
header
|
int
|
Number of line to skip. By default the header is a single line. |
1
|
Returns:
| Type | Description |
|---|---|
numpy.array :
|
A 1D numpy array with the |
Examples:
Source code in src/hicstuff/io.py
generate_temp_dir ¶
Temporary directory generation
Generates a temporary file with a random name at the input path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The path at which the temporary directory will be created. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The path of the newly created temporary directory. |
Source code in src/hicstuff/io.py
add_cool_column ¶
Adds a new column to a loaded Cooler store. If the column exists, it is replaced. This will affect the .cool file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
clr
|
Cooler object
|
A Cooler store. |
required |
column
|
pandas Series
|
The column to add to the cooler. |
required |
column_name
|
str
|
The name of the column to add. |
required |
table_name
|
str
|
The name of the table to which the column should be added. Defaults to the "bins" table. |
'bins'
|
metadata
|
dict
|
A dictionary of metadata to associate with the new column. |
None
|
Source code in src/hicstuff/io.py
load_cool ¶
Reads a cool file into memory and parses it into graal style tables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cool
|
str
|
Path to the input .cool file. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
mat |
scipy coo_matrix
|
Hi-C contact map in COO format. |
frags |
pandas DataFrame
|
Table off bins matching the matrix. Corresponds to the content of the fragments_list.txt file. |
chroms |
pandas DataFrame
|
Table of chromosome informations. |
Source code in src/hicstuff/io.py
save_cool ¶
Writes a .cool file from graal style tables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cool_out
|
str
|
Path to the output cool file. |
required |
mat
|
scipy coo_matrix
|
The Hi-C contact matrix in sparse COO format. |
required |
frags
|
pandas DataFrame
|
The graal style 'fragments_list' table. |
required |
metadata
|
dict
|
Potential metadata to associate with the cool file. |
None
|
Source code in src/hicstuff/io.py
read_compressed ¶
Read compressed file
Opens the file in read mode with appropriate decompression algorithm.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
The path to the input file |
required |
mode
|
str
|
"r" to read text, "rb" to read bytes. |
'r'
|
Returns:
| Type | Description |
|---|---|
file-like object
|
The handle to access the input file's content |
Source code in src/hicstuff/io.py
is_compressed ¶
Check compression status
Check if the input file is compressed from the first bytes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
The path to the input file |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the file is compressed, False otherwise. |
Source code in src/hicstuff/io.py
from_dade_matrix ¶
Load a DADE matrix
Load a numpy array from a DADE matrix file, optionally returning bin information from the header. Header data processing is delegated downstream.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
(str, file or Path)
|
The name of the file containing the DADE matrix. |
required |
header
|
bool
|
Whether to return as well information contained in the header. Default is False. |
False
|
Example
>>> import numpy as np
>>> import tempfile
>>> lines = [['RST', 'chr1~0', 'chr1~10', 'chr2~0', 'chr2~30'],
... ['chr1~0', '5'],
... ['chr1~10', '8', '3'],
... ['chr2~0', '3', '5', '5'],
... ['chr2~30', '5', '10', '11', '2']
... ]
>>> formatted = ["\t".join(l) + "\n" for l in lines ]
>>> dade = tempfile.NamedTemporaryFile(mode='w')
>>> for fm in formatted:
... dade.write(fm)
34
9
12
13
18
>>> dade.flush()
>>> M, h = from_dade_matrix(dade.name, header=True)
>>> dade.close()
>>> print(M)
[[ 5. 8. 3. 5.]
[ 8. 3. 5. 10.]
[ 3. 5. 5. 11.]
[ 5. 10. 11. 2.]]
>>> print(h)
['chr1~0', 'chr1~10', 'chr2~0', 'chr2~30']
See https://github.com/scovit/DADE for more details about Dade.
Source code in src/hicstuff/io.py
to_dade_matrix ¶
Returns a Dade matrix from input numpy matrix. Any annotations are added as header. If filename is provided and valid, said matrix is also saved as text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
M
|
ndarray
|
The square matrix to convert. |
required |
annotations
|
array_like of numbers
|
Labels of the header row and column, one more than the number of rows (the first one goes in the corner). The header is left at 0 if omitted. |
None
|
filename
|
str
|
Where to save the matrix, as integers. |
None
|
Returns:
| Type | Description |
|---|---|
numpy.ndarray :
|
The matrix with its header row and column. |
Source code in src/hicstuff/io.py
load_into_redis ¶
Load a file into redis
Load a matrix file and sotre it in memory with redis. Useful to pass around huge datasets from scripts to scripts and load them only once.
Inspired from https://gist.github.com/alexland/ce02d6ae5c8b63413843
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
(str, file or Path)
|
The file of the matrix to load. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
key |
str
|
The key of the dataset needed to retrieve it from redis. |
Source code in src/hicstuff/io.py
load_from_redis ¶
Retrieve a dataset from redis
Retrieve a cached dataset that was stored in redis with the input key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key of the dataset that was stored in redis. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
M |
ndarray
|
The retrieved dataset in array format. |
Source code in src/hicstuff/io.py
dade_to_graal ¶
dade_to_graal(filename, output_matrix=DEFAULT_SPARSE_MATRIX_FILE_NAME, output_contigs=DEFAULT_INFO_CONTIGS_FILE_NAME, output_frags=DEFAULT_FRAGMENTS_LIST_FILE_NAME, output_dir=None)
Convert a matrix from DADE format (https://github.com/scovit/dade) to a graal-compatible format. Since DADE matrices contain both fragment and contact information all files are generated at the same time.
Source code in src/hicstuff/io.py
load_bedgraph2d ¶
Loads matrix and fragment information from a 2D bedgraph file. Note this function assumes chromosomes are ordered in alphabetical. order
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Path to the bedgraph2D file. |
required |
bin_size
|
int
|
The size of bins in the case of fixed bin size. |
None
|
fragments_file
|
str
|
Path to a fragments file to explicitely provide fragments positions. If the matrix does not have fixed bin size, this prevents errors. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
mat |
coo_matrix
|
The Hi-C contact map as the upper triangle of a symetric matrix, in sparse format. |
frags |
DataFrame
|
The list of fragments/bin present in the matrix with their genomic positions. |
Source code in src/hicstuff/io.py
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 | |
flexible_hic_loader ¶
Wrapper function to load COO, bg2 or cool input and return the same output. COO formats requires fragments_file and chroms_file options. bg2 format can infer bin_size if fixed. When providing a bg2 matrix with uneven fragments length, one should provide fragments_file as well or empty bins will be truncated from the output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mat
|
str
|
Path to the matrix in graal, bedgraph2 or cool format. |
required |
fragments_file
|
str or None
|
Path to the file with fragments information (fragments_list.txt). Only required if the matrix is in graal format. |
None
|
chroms_file
|
str or None
|
Path to the file with chromosome information (info_contigs.txt). Only required if the matrix is in graal format. |
None
|
quiet
|
bool
|
If True, will silence warnings for empty outputs. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
mat |
coo_matrix
|
Sparse upper triangle Hi-C matrix. |
frags |
DataFrame or None
|
Table of fragment informations. None if information was not provided. |
chroms |
DataFrame or None
|
Table of chromosomes/contig information. None if information was not provided. |
Source code in src/hicstuff/io.py
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 | |
get_hic_format ¶
Returns the format of the input Hi-C matrix
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mat
|
str
|
Path to the input Hi-C matrix |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
Hi-C format string. One of graal, bg2, cool |
Source code in src/hicstuff/io.py
flexible_hic_saver ¶
Saves objects to the desired Hi-C file format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mat
|
coo_matrix
|
Hi-C contact map. |
required |
out_prefix
|
str
|
Output path without extension (the extension is added based on hic_fmt). |
required |
frags
|
DataFrame or None
|
Table of fragments informations. |
None
|
chroms
|
DataFrame or None
|
Table of chromosomes / contigs informations. |
None
|
hic_fmt
|
str
|
Output format. Can be one of graal for graal-compatible COO format, bg2 for 2D bedgraph format, or cool for cooler compatible format. |
'graal'
|
Source code in src/hicstuff/io.py
save_bedgraph2d ¶
Given a sparse matrix and a corresponding list of fragments, save a file in 2D bedgraph format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mat
|
coo_matrix
|
The sparse contact map. |
required |
frags
|
DataFrame
|
A structure containing the annotations for each matrix bin. Should correspond to the content of the fragments_list.txt file. |
required |
Source code in src/hicstuff/io.py
get_pos_cols ¶
Get column names representing chromosome, start and end column from a dataframe. Allows flexible names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
|
required |
Returns:
| Type | Description |
|---|---|
tuple of str:
|
Tuple containing the names of the chromosome, start and end columns in the input dataframe. |
Examples:
>>> import pandas as pd
>>> d = [1, 2, 3]
>>> df = pd.DataFrame(
... {'Chromosome': d, 'Start': d, 'End': d, 'species': d}
... )
>>> get_pos_cols(df)
('Chromosome', 'Start', 'End')
>>> df = pd.DataFrame(
... {'id': d, 'chr': d, 'start_bp': d, 'end_bp': d}
... )
>>> get_pos_cols(df)
('chr', 'start_bp', 'end_bp')
Source code in src/hicstuff/io.py
gc_bins ¶
Generate GC content annotation for bins using input genome.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
genome_path
|
str
|
Path the the genome file in FASTA format. |
required |
frags
|
DataFrame
|
Table containing bin segmentation of the genome. Required columns: chrom, start, end. |
required |
Returns:
| Type | Description |
|---|---|
numpy.ndarray of floats:
|
GC content per bin, in the range [0.0, 1.0]. |
Source code in src/hicstuff/io.py
sort_pairs ¶
Sort a pairs file in batches using UNIX sort, or in Python.
The pairs are sorted by GNU, uutils or BSD sort when one is on PATH, and in Python otherwise, or when the environment variable HICSTUFF_SORT is "python": both write the same file. The Python sort is single-threaded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
in_file
|
str
|
Path to the unsorted input file. It can be compressed (gzip, bgzip, bzip2 or zip). |
required |
out_file
|
str
|
Path to the sorted output file. It is not compressed. |
required |
keys
|
list of str
|
list of columns to use as sort keys. Each column can be one of readID, chr1, pos1, chr2, pos2, strand1, strand2, frag1, frag2. Key priorities are according to the order in the list. Chromosomes sort byte by byte (chr1, chr10, chr2, as pairtools sort), positions and fragments numerically, read names and strands in dictionary order. Read names that dictionary order finds equal but that differ (r.1 and r1) are ordered byte by byte, so that each one forms one block. |
required |
tmp_dir
|
str
|
Path to the directory where temporary files will be created. Defaults to sort's own: $TMPDIR, else /tmp (/var/tmp for BSD sort), and to Python's for the Python sort. |
None
|
threads
|
int
|
Number of parallel sorting threads, given with --parallel to GNU sort 8.23 or later and to uutils sort. Other sorts choose their own. |
1
|
buffer
|
str
|
Buffer size used for sorting. Consists of a number and a unit. |
'2G'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a key is not one of the columns above, or, for the Python sort, the buffer size is not one sort accepts. Nothing is written then. |
RuntimeError
|
If sort fails. |
Source code in src/hicstuff/io.py
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 | |
get_pairs_header ¶
Retrieves the header of a .pairs file and stores lines into a list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pairs
|
str
|
Path to the pairs file. It can be compressed (gzip, bgzip, bzip2 or zip). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
header |
list of str
|
A list of header lines found, in the same order they appear in pairs. |
Examples:
>>> import os
>>> from tempfile import NamedTemporaryFile
>>> p = NamedTemporaryFile('w', delete=False)
>>> p.writelines(["## pairs format v1.0\n", "#sorted: chr1-chr2\n", "abcd\n"])
>>> p.close()
>>> h = get_pairs_header(p.name)
>>> for line in h:
... print([line])
['## pairs format v1.0']
['#sorted: chr1-chr2']
>>> os.unlink(p.name)
Source code in src/hicstuff/io.py
reorder_fasta ¶
Reorder and trim a fasta file
Sort a fasta file by record lengths, optionally trimming the smallest ones.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
genome
|
(str, file or Path)
|
The genome scaffold file (or file handle) |
required |
output
|
(str, file or Path)
|
The output file to write to |
None
|
threshold
|
int
|
The size below which scaffolds are discarded, by default 100000 |
100000
|
Source code in src/hicstuff/io.py
rename_genome ¶
Rename genome and slugify headers
Rename genomes according to a simple naming scheme; this is mainly done to avoid special character weirdness.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
genome
|
(file, str or Path)
|
The input genome to be renamed and slugify. |
required |
output
|
(file, str or Path)
|
The output genome to be written into. Default is |
None
|
ambiguous
|
bool
|
Whether to retain ambiguous non-N bases, otherwise rename them to Ns. Default is True. |
True
|
Source code in src/hicstuff/io.py
check_fasta_index ¶
Checks for the existence of a bowtie2 or bwa index based on the reference file name.
The index must be named after the reference path as given, which is how bowtie2 and bwa find it: .1.bt2 to .rev.2.bt2 (or .bt2l) for bowtie2, .amb, .ann, .bwt, .pac and .sa for bwa. The reference path is kept as is: relative (./ or ../), absolute, or with dots in its name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ref
|
str or Path
|
Path to the reference genome, or to the index prefix. |
required |
mode
|
str
|
The alignment software used to build the index. bowtie2 or bwa. If any other value is given, the function returns the reference path. |
'bowtie2'
|
Returns:
| Name | Type | Description |
|---|---|---|
index |
str
|
The bowtie2 or bwa index prefix, i.e. ref. None if no index was found |
Source code in src/hicstuff/io.py
alignment_tools ¶
Programs that aligning reads with an aligner runs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
aligner
|
str
|
The aligner: bowtie2, bwa or minimap2. |
required |
index
|
str or None
|
The index prefix found by check_fasta_index, or None if the index of the reference must be built first. |
required |
Returns:
| Type | Description |
|---|---|
list of str
|
The aligner, and the program that builds its index if there is none (bowtie2-build for bowtie2; bwa builds its own). |
Source code in src/hicstuff/io.py
require_tools ¶
Check that programs are on PATH before running them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tools
|
list of str
|
Names of the programs. |
required |
purpose
|
str
|
What they are needed for, completing "needed ...", for the error message. |
required |
alternative
|
str or None
|
What can be done instead of installing them, completing "install them, or ...", for the error message. |
None
|
Raises:
| Type | Description |
|---|---|
ImportError
|
If any of the programs is not on PATH, naming the missing ones. |
Source code in src/hicstuff/io.py
check_is_fasta ¶
Checks whether input file is in fasta format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
in_file
|
str
|
Path to the input file. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
True if the input is in fasta format, False otherwise |
Source code in src/hicstuff/io.py
check_fastq_entries ¶
Check how many reads are in the input fastq.
Reads are counted as a quarter of the lines, counted as wc -l counts
them, without running any program: gzip-compressed files are
decompressed with Python's gzip module.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
in_file
|
str
|
Path to the input file, plain or gzip-compressed. |
required |
threads
|
int
|
Not used, kept so that calls passing it keep working. |
1
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
How many reads listed in the input fastq |
Source code in src/hicstuff/io.py
check_bam_entries ¶
Check how many reads are in the input bam
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
in_file
|
str
|
Path to the input file. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
How many reads listed in the input bam |
Source code in src/hicstuff/io.py
strip_mate_suffix ¶
Read name without its mate suffix, /1 or /2, if it has one.
Aligners do not all keep the suffix in the names they write: bwa mem drops it, while bowtie2 and minimap2 keep it when aligning single reads. Names compared without it match whichever aligner wrote them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Read name, as in a FASTQ or BAM file. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
The name without a trailing |
Examples:
Source code in src/hicstuff/io.py
samtools_pipe ¶
Run samtools commands with the samtools that pysam bundles, each reading
the output of the previous one, as samtools view ... | samtools sort ...
would.
Each command runs in its own child process, so that it can stream from and to a pipe: pysam runs samtools commands within the calling process, which has a single standard input and output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*commands
|
list
|
Each command: the samtools command (view, sort...) followed by its arguments. All but the last write to their standard output, which the next one reads with "-" (or no input file) as input. |
()
|
stdin
|
file object or None
|
Standard input of the first command, such as the standard output of another process. It is closed in this process once handed over, so that the writing process stops if the first command does. |
None
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If any command fails, naming the failed commands. |